diff options
| author | Pliable Pixels <pliablepixels@gmail.com> | 2016-08-01 16:43:27 -0400 |
|---|---|---|
| committer | Pliable Pixels <pliablepixels@gmail.com> | 2016-08-01 16:43:27 -0400 |
| commit | 69e7033fca28646d1f3f2c78db6e0e6c2796c3e8 (patch) | |
| tree | dc9cb04aeaaf961e776645b656a9f4dc4e457025 /www | |
| parent | 81d24bbed0af0ba7b39948ca968528b225a46c76 (diff) | |
#292 - various items cleaned up, default to sqlite for devices, cleaned up entry paths to PortalLogin and ensured its AFTER DataModel.init() - wonder if this fixes #193
Former-commit-id: fbe5c0b0649b44912f5a52babeea5aa91a58e70f
Diffstat (limited to 'www')
54 files changed, 8567 insertions, 327 deletions
diff --git a/www/index.html b/www/index.html index 946fc664..d71f6154 100644 --- a/www/index.html +++ b/www/index.html @@ -52,6 +52,10 @@ <!-- cordova script (this will be a 404 during development) --> <script src="cordova.js"></script> + <script src="lib/localforage/dist/localforage.js"></script> +<script src="lib/localforage-cordovasqlitedriver/dist/localforage-cordovasqlitedriver.js"></script> + + <script src="js/ionicUtils.js"></script> <script src="lib/ionic-native-transitions/dist/ionic-native-transitions.min.js"></script> <script src="lib/angular-wizard/dist/angular-wizard.min.js"></script> diff --git a/www/js/DataModel.js b/www/js/DataModel.js index df92729e..681e8fbd 100644 --- a/www/js/DataModel.js +++ b/www/js/DataModel.js @@ -2,7 +2,7 @@ /* jslint browser: true*/ -/* global cordova,StatusBar,angular,console, URI, moment*/ +/* global cordova,StatusBar,angular,console, URI, moment, localforage*/ // This is my central data respository and common functions // that many other controllers use @@ -10,7 +10,7 @@ angular.module('zmApp.controllers') -.service('ZMDataModel', ['$http', '$q', '$ionicLoading', '$ionicBackdrop', '$fileLogger', 'zm', '$rootScope', '$ionicContentBanner', '$timeout', '$cordovaPinDialog', '$ionicPopup', '$localstorage', '$state', '$ionicNativeTransitions', '$translate', +.service('ZMDataModel', ['$http', '$q', '$ionicLoading', '$ionicBackdrop', '$fileLogger', 'zm', '$rootScope', '$ionicContentBanner', '$timeout', '$cordovaPinDialog', '$ionicPopup', '$localstorage', '$state', '$ionicNativeTransitions', '$translate', '$cordovaSQLite', function ($http, $q, $ionicLoading, $ionicBackdrop, $fileLogger, zm, $rootScope, $ionicContentBanner, $timeout, $cordovaPinDialog, @@ -24,6 +24,8 @@ angular.module('zmApp.controllers') var monitors = []; var multiservers = []; var oldevents = []; + var migrationComplete = false; + var languages = [ { @@ -41,7 +43,10 @@ angular.module('zmApp.controllers') ]; var serverGroupList = {}; - + var defaultLang = 'en'; + var isFirstUse = true; + var lastUpdateCheck = null; + var latestBlogPostChecked = null; var loginData = { 'serverName': '', 'username': '', @@ -65,7 +70,7 @@ angular.module('zmApp.controllers') 'eventServerInterval': '', // list of intervals for all monitors 'refreshSec': '2', // timer value for frame change in sec 'enableLogs': true, - 'enableDebug': false, // if enabled with log messages with "debug" + 'enableDebug': true, // if enabled with log messages with "debug" 'usePin': false, 'pinCode': '', 'canSwipeMonitors': true, @@ -140,11 +145,29 @@ angular.module('zmApp.controllers') } + + function setLogin(newLogin) { loginData = angular.copy(newLogin); serverGroupList[loginData.serverName] = angular.copy(loginData); - $localstorage.setObject("serverGroupList", serverGroupList); - $localstorage.set("defaultServerName", loginData.serverName); + //$localstorage.setObject("serverGroupList", serverGroupList); + localforage.setItem("serverGroupList", serverGroupList, function (err) { + if (err) zmLog("localforage store error " + JSON.stringify(err)); + }); + //$localstorage.set("defaultServerName", loginData.serverName); + localforage.setItem("defaultServerName", loginData.serverName, function (err) { + if (err) zmLog("localforage store error " + JSON.stringify(err)); + }); + + + + //setDB("serverGroupList", serverGroupList); + //setDB ("defaultServerName", loginData.serverName); + + + + + // console.log ("SAVING " + loginData.serverName); // console.log ("DATA IS " + JSON.stringify(loginData)); @@ -205,8 +228,13 @@ angular.module('zmApp.controllers') // used by various controllers to log messages to file //------------------------------------------------------------- - isEmpty: function (obj) - { + migrationComplete: function () { + migrationComplete = true; + }, + + + + isEmpty: function (obj) { return isEmpty(obj); }, @@ -223,6 +251,25 @@ angular.module('zmApp.controllers') zmDebug(val); }, + setLastUpdateCheck: function (val) { + lastUpdateCheck = val; + localforage.setItem("lastUpdateCheck", lastUpdateCheck); + }, + + getLastUpdateCheck: function () { + return lastUpdateCheck; + }, + + setLatestBlogPostChecked: function (val) { + latestBlogPostChecked = val; + localforage.seItem("latestBlogPostChecked", latestBlogPostChecked); + }, + + getLatestBlogPostChecked: function () { + return latestBlogPostChecked; + }, + + // This function is called when the app is ready to run // sets up various variables // including persistent login data for the ZM apis and portal @@ -369,185 +416,206 @@ angular.module('zmApp.controllers') init: function () { // console.log("****** DATAMODEL INIT SERVICE CALLED ********"); - zmLog("ZMData init: checking for stored variables & setting up log file"); - serverGroupList = $localstorage.getObject("serverGroupList"); - var demoServer = "{\"serverName\":\"zmNinjaDemo\",\"username\":\"zmninja\",\"password\":\"zmNinja$xc129\",\"url\":\"https://demo.zoneminder.com/zm\",\"apiurl\":\"https://demo.zoneminder.com/zm/api\",\"eventServer\":\"\",\"maxMontage\":\"40\",\"streamingurl\":\"https://demo.zoneminder.com/cgi-bin-zm\",\"maxFPS\":\"3\",\"montageQuality\":\"50\",\"singleImageQuality\":\"100\",\"montageHistoryQuality\":\"50\",\"useSSL\":true,\"keepAwake\":true,\"isUseAuth\":\"1\",\"isUseEventServer\":false,\"disablePush\":false,\"eventServerMonitors\":\"\",\"eventServerInterval\":\"\",\"refreshSec\":\"2\",\"enableDebug\":false,\"usePin\":false,\"pinCode\":\"\",\"canSwipeMonitors\":true,\"persistMontageOrder\":false,\"onTapScreen\":\"Events\",\"enableh264\":true,\"gapless\":false,\"montageOrder\":\"\",\"montageHiddenOrder\":\"\",\"montageArraySize\":\"0\",\"graphSize\":2000,\"enableAlarmCount\":true,\"montageSize\":\"3\",\"useNphZms\":true,\"useNphZmsForEvents\":true,\"packMontage\":false,\"exitOnSleep\":false,\"forceNetworkStop\":false,\"defaultPushSound\":false,\"enableBlog\":true,\"use24hr\":false, \"packeryPositions\":\"\"}"; - var demoS = JSON.parse(demoServer); - console.log("JSON parsed demo" + JSON.stringify(demoS)); - var isFoundDemo = false; - var as = Object.keys(serverGroupList); - for (var x = 0; x < as.length; x++) { - if (as[x] == 'zmNinjaDemo') - isFoundDemo = true; - //console.log ("************ FOUND SERVER NAME " + as[x]); - // if serverGroupList[x] - } - // Don't add the demo if there is another server - // because this means the user deleted it - if (!isFoundDemo && as.length == 0) { - zmDebug("Pushing demo server config to server groups"); - //serverGroupList.push(demoS); - serverGroupList[demoS.serverName] = angular.copy(demoS); - } - var sname = - $localstorage.get("defaultServerName"); - //console.log ("!!!!!!!!!!!!!!!!!!default server name is " + sname); + zmLog("ZMData init: checking for stored variables & setting up log file"); - var loadedData = serverGroupList[sname]; - if (!isEmpty(loadedData)) { - loginData = loadedData; + $ionicLoading.show({ + template: "retrieving profile data..." + }); + localforage.getItem("serverGroupList").then(function (val) { + $ionicLoading.hide(); + serverGroupList = val; + console.log(">>>> serverGroupList " + JSON.stringify(serverGroupList)); + var demoServer = "{\"serverName\":\"zmNinjaDemo\",\"username\":\"zmninja\",\"password\":\"zmNinja$xc129\",\"url\":\"https://demo.zoneminder.com/zm\",\"apiurl\":\"https://demo.zoneminder.com/zm/api\",\"eventServer\":\"\",\"maxMontage\":\"40\",\"streamingurl\":\"https://demo.zoneminder.com/cgi-bin-zm\",\"maxFPS\":\"3\",\"montageQuality\":\"50\",\"singleImageQuality\":\"100\",\"montageHistoryQuality\":\"50\",\"useSSL\":true,\"keepAwake\":true,\"isUseAuth\":\"1\",\"isUseEventServer\":false,\"disablePush\":false,\"eventServerMonitors\":\"\",\"eventServerInterval\":\"\",\"refreshSec\":\"2\",\"enableDebug\":false,\"usePin\":false,\"pinCode\":\"\",\"canSwipeMonitors\":true,\"persistMontageOrder\":false,\"onTapScreen\":\"Events\",\"enableh264\":true,\"gapless\":false,\"montageOrder\":\"\",\"montageHiddenOrder\":\"\",\"montageArraySize\":\"0\",\"graphSize\":2000,\"enableAlarmCount\":true,\"montageSize\":\"3\",\"useNphZms\":true,\"useNphZmsForEvents\":true,\"packMontage\":false,\"exitOnSleep\":false,\"forceNetworkStop\":false,\"defaultPushSound\":false,\"enableBlog\":true,\"use24hr\":false, \"packeryPositions\":\"\"}"; + var demoS = JSON.parse(demoServer); + console.log("JSON parsed demo" + JSON.stringify(demoS)); + + var isFoundDemo = false; + var as = Object.keys(serverGroupList); + for (var x = 0; x < as.length; x++) { + if (as[x] == 'zmNinjaDemo') + isFoundDemo = true; + //console.log ("************ FOUND SERVER NAME " + as[x]); + // if serverGroupList[x] + } - // old version hacks for new variables + // Don't add the demo if there is another server + // because this means the user deleted it - if (typeof loginData.enableAlarmCount === 'undefined') { - zmDebug("enableAlarmCount does not exist, setting to true"); - loginData.enableAlarmCount = true; + if (!isFoundDemo && as.length == 0) { + zmDebug("Pushing demo server config to server groups"); + //serverGroupList.push(demoS); + serverGroupList[demoS.serverName] = angular.copy(demoS); } - - if (typeof loginData.onTapScreen == 'undefined') - { - loginData.onTapScreen = $translate.instant('kTapMontage'); - } - - if (loginData.onTapScreen != $translate.instant('kTapMontage') && - loginData.onTapScreen != $translate.instant('kTapEvents') && - loginData.onTapScreen != $translate.instant('kTapLiveMonitor')) - { - zmLog ("Invalid onTap setting found, resetting"); - loginData.onTapScreen = $translate.instant('kMontage'); - } - - if (typeof loginData.minAlarmCount === 'undefined') { - zmDebug("minAlarmCount does not exist, setting to true"); - loginData.minAlarmCount = 1; - } + var sname; + $ionicLoading.show({ + template: "retrieving profile data..." + }); + localforage.getItem("defaultServerName") + .then(function (val) { + $ionicLoading.hide(); + //console.log ("!!!!!!!!!!!!!!!!!!default server name is " + sname); + sname = val; + console.log("!!!!!!!!!!!!!!!!!!!Got VAL " + sname); + var loadedData = serverGroupList[sname]; + console.log(">>>>>>>>>>> loadedData is: " + JSON.stringify(loadedData)); + if (!isEmpty(loadedData)) { + loginData = loadedData; + + // old version hacks for new variables + + if (typeof loginData.enableAlarmCount === 'undefined') { + zmDebug("enableAlarmCount does not exist, setting to true"); + loginData.enableAlarmCount = true; + } + if (typeof loginData.onTapScreen == 'undefined') { + loginData.onTapScreen = $translate.instant('kTapMontage'); + } - if (typeof loginData.montageSize == 'undefined') { - zmDebug("montageSize does not exist, setting to 2 (2 per col)"); - loginData.montageSize = 2; - } + if (loginData.onTapScreen != $translate.instant('kTapMontage') && + loginData.onTapScreen != $translate.instant('kTapEvents') && + loginData.onTapScreen != $translate.instant('kTapLiveMonitor')) { + zmLog("Invalid onTap setting found, resetting"); + loginData.onTapScreen = $translate.instant('kMontage'); + } - if (typeof loginData.useNphZms == 'undefined') { - zmDebug("useNphZms does not exist. Setting to true"); - loginData.useNphZms = true; - } + if (typeof loginData.minAlarmCount === 'undefined') { + zmDebug("minAlarmCount does not exist, setting to true"); + loginData.minAlarmCount = 1; + } + if (typeof loginData.montageSize == 'undefined') { + zmDebug("montageSize does not exist, setting to 2 (2 per col)"); + loginData.montageSize = 2; + } - if (typeof loginData.useNphZmsForEvents == 'undefined') { - zmDebug("useNphZmsForEvents does not exist. Setting to true"); - loginData.useNphZmsForEvents = true; - } - if (typeof loginData.forceImageModePath == 'undefined') { - zmDebug("forceImageModePath does not exist. Setting to false"); - loginData.forceImageModePath = false; - } + if (typeof loginData.useNphZms == 'undefined') { + zmDebug("useNphZms does not exist. Setting to true"); + loginData.useNphZms = true; + } - if (typeof loginData.reachability == 'undefined') { - zmDebug("reachability does not exist. Setting to true"); - loginData.reachability = true; - } - // force it - this may not be the problem - loginData.reachability = true; - // and now, force enable it - loginData.useNphZms = true; - loginData.useNphZmsForEvents = true; - if (typeof loginData.packMontage == 'undefined') { - zmDebug("packMontage does not exist. Setting to false"); - loginData.packMontage = false; - } + if (typeof loginData.useNphZmsForEvents == 'undefined') { + zmDebug("useNphZmsForEvents does not exist. Setting to true"); + loginData.useNphZmsForEvents = true; + } - if (typeof loginData.forceNetworkStop == 'undefined') { - zmDebug("forceNetwork does not exist. Setting to false"); - loginData.forceNetworkStop = false; - } + if (typeof loginData.forceImageModePath == 'undefined') { + zmDebug("forceImageModePath does not exist. Setting to false"); + loginData.forceImageModePath = false; + } - if (typeof loginData.enableLogs == 'undefined') { - zmDebug("enableLogs does not exist. Setting to true"); - loginData.enableLogs = true; - } + if (typeof loginData.reachability == 'undefined') { + zmDebug("reachability does not exist. Setting to true"); + loginData.reachability = true; + } + // force it - this may not be the problem + loginData.reachability = true; + // and now, force enable it + loginData.useNphZms = true; + loginData.useNphZmsForEvents = true; + if (typeof loginData.packMontage == 'undefined') { + zmDebug("packMontage does not exist. Setting to false"); + loginData.packMontage = false; + } - if (typeof loginData.defaultPushSound == 'undefined') { - zmDebug("defaultPushSound does not exist. Setting to false"); - loginData.defaultPushSound = false; - } + if (typeof loginData.forceNetworkStop == 'undefined') { + zmDebug("forceNetwork does not exist. Setting to false"); + loginData.forceNetworkStop = false; + } + if (typeof loginData.enableLogs == 'undefined') { + zmDebug("enableLogs does not exist. Setting to true"); + loginData.enableLogs = true; + } - if (typeof loginData.exitOnSleep == 'undefined') { - zmDebug("exitOnSleep does not exist. Setting to false"); - loginData.exitOnSleep = false; - } - if (typeof loginData.enableBlog == 'undefined') { - zmDebug("enableBlog does not exist. Setting to true"); - loginData.enableBlog = true; + if (typeof loginData.defaultPushSound == 'undefined') { + zmDebug("defaultPushSound does not exist. Setting to false"); + loginData.defaultPushSound = false; + } - } - if (typeof loginData.packeryPositions == 'undefined') { - zmDebug("packeryPositions does not exist. Setting to empty"); - loginData.packeryPositions = ""; - } + if (typeof loginData.exitOnSleep == 'undefined') { + zmDebug("exitOnSleep does not exist. Setting to false"); + loginData.exitOnSleep = false; + } + if (typeof loginData.enableBlog == 'undefined') { + zmDebug("enableBlog does not exist. Setting to true"); + loginData.enableBlog = true; - if (typeof loginData.packerySizes == 'undefined') { - zmDebug("packerySizes does not exist. Setting to empty"); - loginData.packerySizes = ""; + } - } + if (typeof loginData.packeryPositions == 'undefined') { + zmDebug("packeryPositions does not exist. Setting to empty"); + loginData.packeryPositions = ""; - if (typeof loginData.use24hr == 'undefined') { - zmDebug("use24hr does not exist. Setting to false"); - loginData.use24hr = false; + } - } - if (typeof timelineModalGraphType == 'undefined') { - zmDebug("timeline graph type not set. Setting to all"); - loginData.timelineModalGraphType = $translate.instant('kGraphAll'); - console.log(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>" + loginData.timelineModalGraphType); - } + if (typeof loginData.packerySizes == 'undefined') { + zmDebug("packerySizes does not exist. Setting to empty"); + loginData.packerySizes = ""; - if (typeof loginData.resumeDelay == 'undefined') { - zmDebug("resumeDelay does not exist. Setting to 0"); - loginData.resumeDelay = "0"; + } - } + if (typeof loginData.use24hr == 'undefined') { + zmDebug("use24hr does not exist. Setting to false"); + loginData.use24hr = false; + } + if (typeof timelineModalGraphType == 'undefined') { + zmDebug("timeline graph type not set. Setting to all"); + loginData.timelineModalGraphType = $translate.instant('kGraphAll'); + console.log(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>" + loginData.timelineModalGraphType); + } - if (typeof loginData.montageHistoryQuality == 'undefined') { - zmDebug("montageHistoryQuality does not exist. Setting to 50"); - loginData.montageHistoryQuality = "50"; + if (typeof loginData.resumeDelay == 'undefined') { + zmDebug("resumeDelay does not exist. Setting to 0"); + loginData.resumeDelay = "0"; + + } - } - zmLog("DataModel init recovered this loginData as " + JSON.stringify(loginData)); - } else { - zmLog("defaultServer configuration NOT found. Keeping login at defaults"); - } + if (typeof loginData.montageHistoryQuality == 'undefined') { + zmDebug("montageHistoryQuality does not exist. Setting to 50"); + loginData.montageHistoryQuality = "50"; - monitorsLoaded = 0; - //console.log("Getting out of ZMDataModel init"); - $rootScope.showBlog = loginData.enableBlog; - zmDebug("loginData structure values: " + JSON.stringify(loginData)); + } + + zmLog("DataModel init recovered this loginData as " + JSON.stringify(loginData)); + } else { + zmLog("defaultServer configuration NOT found. Keeping login at defaults"); + } + // FIXME: HACK: This is the latest entry point into dataModel init, so start portal login after this + // not the neatest way + $rootScope.$emit('init-complete'); + }); + + monitorsLoaded = 0; + //console.log("Getting out of ZMDataModel init"); + $rootScope.showBlog = loginData.enableBlog; + zmDebug("loginData structure values: " + JSON.stringify(loginData)); + //$rootScope.$emit('init-complete'); + }); }, @@ -592,10 +660,16 @@ angular.module('zmApp.controllers') setDefaultLanguage: function (l, permanent) { if (!l) l = 'en'; + defaultLang = l; var d = $q.defer(); - if (permanent) - window.localStorage.setItem("defaultLang", l); + if (permanent) { + //window.localStorage.setItem("defaultLang", l); + + console.log("setting default lang"); + localforage.setItem("defaultlang", l); + } + console.log("invoking translate use with " + l); $translate.use(l).then(function (data) { zmLog("Device Language is:" + data); moment.locale(data); @@ -613,7 +687,8 @@ angular.module('zmApp.controllers') }, getDefaultLanguage: function () { - return window.localStorage.getItem("defaultLang"); + return defaultLang; + //return window.localStorage.getItem("defaultLang"); }, @@ -653,7 +728,9 @@ angular.module('zmApp.controllers') }, isFirstUse: function () { - return ((window.localStorage.getItem("isFirstUse") == undefined) ? true : false); + console.log("isFirstUse is " + isFirstUse); + return isFirstUse; + // return ((window.localStorage.getItem("isFirstUse") == undefined) ? true : false); }, @@ -665,7 +742,10 @@ angular.module('zmApp.controllers') // Allow the option to reset first use if I need it in future //----------------------------------------------------------------- setFirstUse: function (val) { - window.localStorage.setItem("isFirstUse", val ? "1" : "0"); + //window.localStorage.setItem("isFirstUse", val ? "1" : "0"); + //localforage.setItem("isFirstUse", val, + // function(err) {if (err) zmLog ("localforage error, //storing isFirstUse: " + JSON.stringify(err));}); + isFirstUse = val; }, diff --git a/www/js/LoginCtrl.js b/www/js/LoginCtrl.js index 06164891..643d0ff9 100644 --- a/www/js/LoginCtrl.js +++ b/www/js/LoginCtrl.js @@ -1,8 +1,8 @@ /* jshint -W041 */ /* jslint browser: true*/ -/* global cordova,StatusBar,angular,console,alert,URI */ +/* global cordova,StatusBar,angular,console,alert,URI, localforage */ -angular.module('zmApp.controllers').controller('zmApp.LoginCtrl', ['$scope', '$rootScope', 'zm', '$ionicModal', 'ZMDataModel', '$ionicSideMenuDelegate', '$ionicPopup', '$http', '$q', '$ionicLoading', 'zmAutoLogin', '$cordovaPinDialog', 'EventServer', '$ionicHistory', '$state', '$ionicActionSheet', 'SecuredPopups', '$localstorage', '$stateParams', '$translate', function ($scope, $rootScope, zm, $ionicModal, ZMDataModel, $ionicSideMenuDelegate, $ionicPopup, $http, $q, $ionicLoading, zmAutoLogin, $cordovaPinDialog, EventServer, $ionicHistory, $state, $ionicActionSheet, SecuredPopups, $localstorage, $stateParams, $translate) { +angular.module('zmApp.controllers').controller('zmApp.LoginCtrl', ['$scope', '$rootScope', 'zm', '$ionicModal', 'ZMDataModel', '$ionicSideMenuDelegate', '$ionicPopup', '$http', '$q', '$ionicLoading', 'zmAutoLogin', '$cordovaPinDialog', 'EventServer', '$ionicHistory', '$state', '$ionicActionSheet', 'SecuredPopups', '$stateParams', '$translate', function ($scope, $rootScope, zm, $ionicModal, ZMDataModel, $ionicSideMenuDelegate, $ionicPopup, $http, $q, $ionicLoading, zmAutoLogin, $cordovaPinDialog, EventServer, $ionicHistory, $state, $ionicActionSheet, SecuredPopups, $stateParams, $translate) { $scope.openMenu = function () { $ionicSideMenuDelegate.toggleLeft(); }; @@ -34,7 +34,7 @@ angular.module('zmApp.controllers').controller('zmApp.LoginCtrl', ['$scope', '$r function onPause() { ZMDataModel.zmLog ("Login screen going to background, saving data"); - $localstorage.setObject ("settings-temp-data",$scope.loginData); + localforage.setItem ("settings-temp-data",$scope.loginData); } @@ -251,17 +251,22 @@ angular.module('zmApp.controllers').controller('zmApp.LoginCtrl', ['$scope', '$r else { - var savedData = $localstorage.getObject ("settings-temp-data"); - if (! ZMDataModel.isEmpty(savedData)) - { - $scope.loginData = savedData; - ZMDataModel.zmLog ("retrieved pre-stored loginData on past pause: " + JSON.stringify($scope.loginData)); - $localstorage.setObject("settings-temp-data", {}); - } - else - { - ZMDataModel.zmLog ("Not recovering login data as its empty"); - } + var savedData; + localforage.getItem("settings-temp-data").then (function(value) { + savedData = value; + //= zmStorageService.getObject ("settings-temp-data"); + if (! ZMDataModel.isEmpty(savedData)) + { + $scope.loginData = savedData; + ZMDataModel.zmLog ("retrieved pre-stored loginData on past pause: " + JSON.stringify($scope.loginData)); + localforage.removeItem("settings-temp-data"); + //zmStorageService.setObject("settings-temp-data", {}); + } + else + { + ZMDataModel.zmLog ("Not recovering login data as its empty"); + } + }); } diff --git a/www/js/NewsCtrl.js b/www/js/NewsCtrl.js index a0ab8565..b914b32a 100644 --- a/www/js/NewsCtrl.js +++ b/www/js/NewsCtrl.js @@ -2,7 +2,7 @@ /* jslint browser: true*/ /* global cordova,StatusBar,angular,console,moment*/ -angular.module('zmApp.controllers').controller('zmApp.NewsCtrl', ['$scope', '$rootScope', '$ionicModal', 'ZMDataModel','$ionicSideMenuDelegate', '$ionicHistory', '$state', '$http', 'zm', '$localstorage', function ($scope, $rootScope, $ionicModal, ZMDataModel,$ionicSideMenuDelegate, $ionicHistory, $state, $http, zm, $localstorage) { +angular.module('zmApp.controllers').controller('zmApp.NewsCtrl', ['$scope', '$rootScope', '$ionicModal', 'ZMDataModel','$ionicSideMenuDelegate', '$ionicHistory', '$state', '$http', 'zm', function ($scope, $rootScope, $ionicModal, ZMDataModel,$ionicSideMenuDelegate, $ionicHistory, $state, $http, zm) { $scope.openMenu = function () { $ionicSideMenuDelegate.toggleLeft(); }; @@ -39,7 +39,8 @@ $scope.openMenu = function () { $scope.isUnread = function(itemdate) { - var lastDate = $localstorage.get("latestBlogPostChecked"); + var lastDate = ZMDataModel.getLatestBlogPostChecked(); + //get("latestBlogPostChecked"); if (!lastDate) return true; var mLastDate = moment(lastDate); var mItemDate = moment(itemdate); @@ -52,13 +53,15 @@ $scope.openMenu = function () { $scope.loadPost = function (item, itemdate) { - var lastDate = $localstorage.get("latestBlogPostChecked"); + var lastDate = + ZMDataModel.getLatestBlogPostChecked(); //zmStorageService.get("latestBlogPostChecked"); if (!lastDate) { ZMDataModel.zmDebug ("First time checking blog posts, I see"); - $localstorage.set("latestBlogPostChecked", itemdate); + ZMDataModel.setLatestBlogPostChecked(itemdate); + //zmStorageService.set("latestBlogPostChecked", itemdate); } else @@ -71,7 +74,8 @@ $scope.openMenu = function () { if (mItemDate.diff(mLastDate) >0) { ZMDataModel.zmDebug ("Updating lastDate to this post"); - $localstorage.set("latestBlogPostChecked", itemdate); + + ZMDataModel.setLatestBlogPostChecked(itemdate); //zmStorageService.set("latestBlogPostChecked", itemdate); if (itemdate == $scope.newsItems[0].date) { diff --git a/www/js/app.js b/www/js/app.js index b6afba53..40fb76cb 100644 --- a/www/js/app.js +++ b/www/js/app.js @@ -1,11 +1,12 @@ /* jshint -W041 */ /* jslint browser: true*/ -/* global cordova,StatusBar,angular,console,alert,PushNotification, moment ,ionic, URI,Packery, ConnectSDK,$*/ +/* global cordova,StatusBar,angular,console,alert,PushNotification, moment ,ionic, URI,Packery, ConnectSDK, localforage,$*/ var appVersion = "0.0.0"; + // core app start stuff angular.module('zmApp', [ 'ionic', @@ -76,7 +77,9 @@ angular.module('zmApp', [ nphSwitchTimer: 3000, eventHistoryTimer: 10000, eventPlaybackQuery: 3000, - packeryTimer:500 + packeryTimer: 500, + dbName: 'zmninja.db', + dbTableName: 'userProfile' @@ -84,23 +87,23 @@ angular.module('zmApp', [ // filter for montage iteration -.filter('onlyEnabled', function() { +.filter('onlyEnabled', function () { - // Create the return function and set the required parameter name to **input** - return function(input) { + // Create the return function and set the required parameter name to **input** + return function (input) { - var out = []; + var out = []; - angular.forEach(input, function(item) { + angular.forEach(input, function (item) { - if ((item.Monitor.Function != 'None') && (item.Monitor.Enabled!='0')) { - out.push(item); - } - - }); + if ((item.Monitor.Function != 'None') && (item.Monitor.Enabled != '0')) { + out.push(item); + } - return out; - }; + }); + + return out; + }; }) @@ -115,19 +118,20 @@ angular.module('zmApp', [ }) -.directive('dannyPackery', ['$rootScope', function($rootScope) { +.directive('dannyPackery', ['$rootScope', function ($rootScope) { return { restrict: 'A', - link: function(scope, element, attrs) { + link: function (scope, element, attrs) { console.log('Running dannyPackery linking function!'); - if($rootScope.packery === undefined || $rootScope.packery === null){ + if ($rootScope.packery === undefined || $rootScope.packery === null) { console.log('making packery!'); - $rootScope.packery = new Packery(element[0].parentElement, {columnWidth: '.item'}); + $rootScope.packery = new Packery(element[0].parentElement, { + columnWidth: '.item' + }); $rootScope.packery.bindResize(); $rootScope.packery.appended(element[0]); - $rootScope.packery.items.splice(1,1); // hack to fix a bug where the first element was added twice in two different positions - } - else{ + $rootScope.packery.items.splice(1, 1); // hack to fix a bug where the first element was added twice in two different positions + } else { $rootScope.packery.appended(element[0]); } $rootScope.packery.layout(); @@ -137,23 +141,23 @@ angular.module('zmApp', [ // credit https://gist.github.com/Zren/beaafd64f395e23f4604 -.directive('mouseWheelScroll', function($timeout) { +.directive('mouseWheelScroll', function ($timeout) { return { - restrict: 'A', - link: function($scope, $element, $attrs) { - var onMouseWheel, scrollCtrl; - scrollCtrl = $element.controller('$ionicScroll'); - //console.log(scrollCtrl); - if (!scrollCtrl) { - return console.error('mouseWheelScroll must be attached to a $ionicScroll controller.'); + restrict: 'A', + link: function ($scope, $element, $attrs) { + var onMouseWheel, scrollCtrl; + scrollCtrl = $element.controller('$ionicScroll'); + //console.log(scrollCtrl); + if (!scrollCtrl) { + return console.error('mouseWheelScroll must be attached to a $ionicScroll controller.'); + } + onMouseWheel = function (e) { + return scrollCtrl.scrollBy(0, -e.wheelDeltaY, false); + }; + return scrollCtrl.element.addEventListener('wheel', onMouseWheel); } - onMouseWheel = function(e) { - return scrollCtrl.scrollBy(0, -e.wheelDeltaY, false); - }; - return scrollCtrl.element.addEventListener('wheel', onMouseWheel); - } }; - }) +}) // this can be used to route img-src through interceptors. Works well, but when // nph-zms streams images it doesn't work as success is never received @@ -452,7 +456,7 @@ angular.module('zmApp', [ 'request': function (config) { - // console.log (">>>>"+config.url); + // console.log (">>>>"+config.url); // handle basic auth properly if (config.url.indexOf("@") > -1) { //console.log ("HTTP basic auth INTERCEPTOR URL IS " + config.url); @@ -483,14 +487,10 @@ angular.module('zmApp', [ // these can take time, so lets bump up timeout config.timeout = zm.largeHttpTimeout; - } - else if ((config.url.indexOf("view=view_video")> -1) || - config.url.indexOf(".mp4")>-1) - { - console.log (">>> skipping timers for MP4"); - } - else - { + } else if ((config.url.indexOf("view=view_video") > -1) || + config.url.indexOf(".mp4") > -1) { + console.log(">>> skipping timers for MP4"); + } else { config.timeout = zm.httpTimeout; } return config; @@ -537,7 +537,7 @@ angular.module('zmApp', [ function checkUpdate() { - var lastdateString = $localstorage.get("lastUpdateCheck"); + var lastdateString = ZMDataModel.getLastUpdateCheck(); var lastdate; if (!lastdateString) { @@ -558,8 +558,8 @@ angular.module('zmApp', [ $http.get(zm.latestRelease) .then(function (success) { - - $localstorage.set("lastUpdateCheck", moment().toISOString()); + ZMDataModel.setLastUpdateCheck(moment().toISOString()); + // $localstorage.set("lastUpdateCheck", moment().toISOString()); //console.log ("FULL STRING " + success.data.tag_name); var res = success.data.tag_name.match("v(.*)"); zmUpdateVersion = res[1]; @@ -584,7 +584,7 @@ angular.module('zmApp', [ return; } - var lastDate = $localstorage.get("latestBlogPostChecked"); + var lastDate = ZMDataModel.getLatestBlogPostChecked(); if (!lastDate) { $rootScope.newBlogPost = "(new post)"; @@ -649,6 +649,11 @@ angular.module('zmApp', [ // doLogin() emits this when our auth credentials work //------------------------------------------------------------------ + $rootScope.$on("init-complete", function () { + ZMDataModel.zmLog (">>>>>>>>>>>>>>> All init over, going to portal login"); + $state.go("zm-portal-login"); + }); + $rootScope.$on("auth-success", function () { var contentBannerInstance = $ionicContentBanner.show({ @@ -723,7 +728,7 @@ angular.module('zmApp', [ }); - + return d.promise; @@ -818,7 +823,7 @@ angular.module('zmApp', [ //eventServer.start(); $rootScope.loggedIntoZm = 1; - ZMDataModel.zmLog("zmAutologin successfully logged into Zoneminder"); + ZMDataModel.zmLog("zmAutolog.runin successfully logged into Zoneminder"); d.resolve("Login Success"); @@ -916,10 +921,10 @@ angular.module('zmApp', [ //==================================================================== -.run(function ($ionicPlatform, $ionicPopup, $rootScope, zm, $state, $stateParams, ZMDataModel, $cordovaSplashscreen, $http, $interval, zmAutoLogin, zmCheckUpdates, $fileLogger, $timeout, $ionicHistory, $window, $ionicSideMenuDelegate, EventServer, $ionicContentBanner, $ionicLoading, $ionicNativeTransitions, $translate) { +.run(function ($ionicPlatform, $ionicPopup, $rootScope, zm, $state, $stateParams, ZMDataModel, $cordovaSplashscreen, $http, $interval, zmAutoLogin, zmCheckUpdates, $fileLogger, $timeout, $ionicHistory, $window, $ionicSideMenuDelegate, EventServer, $ionicContentBanner, $ionicLoading, $ionicNativeTransitions, $translate, $localstorage) { + - $rootScope.appName = "zmNinja"; $rootScope.zmGlobalCookie = ""; @@ -951,7 +956,7 @@ angular.module('zmApp', [ // only for android $rootScope.exitApp = function () { ZMDataModel.zmLog("user exited app"); - + ionic.Platform.exitApp(); }; @@ -979,7 +984,7 @@ angular.module('zmApp', [ }); }, false); - + // This code takes care of trapping the Android back button // and takes it to the menu. @@ -1024,6 +1029,7 @@ angular.module('zmApp', [ $rootScope.userCancelledAuth = true; window.stop(); + console.log ("inside cancelAuth , calling wizard"); $state.go("login", { "wizard": false }); @@ -1037,14 +1043,16 @@ angular.module('zmApp', [ $rootScope.$on('$stateChangeStart', function (event, toState, toParams) { var requireLogin = toState.data.requireLogin; - if (ZMDataModel.isLoggedIn()) { + if (ZMDataModel.isLoggedIn() || toState.name =="login" ) { //console.log("State transition is authorized"); return; } else { - ZMDataModel.zmLog("Not logged in, requested to go to " + JSON.stringify(toState)); + ZMDataModel.zmLog("In Auth State trans: Not logged in, requested to go to " + JSON.stringify(toState)); // event.preventDefault(); - // $state.transitionTo('login'); + // + + $state.transitionTo('login'); } @@ -1071,111 +1079,208 @@ angular.module('zmApp', [ //--------------------------------------------------------------------- $ionicPlatform.ready(function () { - - var pixelRatio = window.devicePixelRatio || 1; - $rootScope.devWidth = ((window.innerWidth > 0) ? window.innerWidth : screen.width); - $rootScope.devHeight = ((window.innerHeight > 0) ? window.innerHeight : screen.height); - // for making sure we canuse $state.go with ng-click - // needed for views that use popovers - $rootScope.$state = $state; - $rootScope.$stateParams = $stateParams; - - - if (window.cordova && window.cordova.plugins.Keyboard) { - cordova.plugins.Keyboard.disableScroll(true); - } - if (window.StatusBar) { - // org.apache.cordova.statusbar required - StatusBar.styleDefault(); - } - - - if (window.cordova) { - $cordovaSplashscreen.hide(); - - ZMDataModel.zmLog ("Enabling insecure SSL"); - cordova.plugins.certificates.trustUnsecureCerts(true); - - cordova.getAppVersion(function (version) { - appVersion = version; - ZMDataModel.zmLog("App Version: " + appVersion); - ZMDataModel.setAppVersion(appVersion); - }); - } - - $fileLogger.checkFile().then(function (resp) { - if (parseInt(resp.size) > zm.logFileMaxSize) { - - $fileLogger.deleteLogfile().then(function () { - ZMDataModel.zmLog("Deleting old log file as it exceeds " + zm.logFileMaxSize + " bytes"); - }); - } - }); - - $fileLogger.setStorageFilename(zm.logFile); - $fileLogger.setTimestampFormat('MMM d, y ' + ZMDataModel.getTimeFormat()); - - + $rootScope.db = null; $rootScope.platformOS = "desktop"; ZMDataModel.zmLog("Device is ready"); - var ld = ZMDataModel.getLogin(); + // var ld = ZMDataModel.getLogin(); if ($ionicPlatform.is('ios')) $rootScope.platformOS = "ios"; if ($ionicPlatform.is('android')) $rootScope.platformOS = "android"; ZMDataModel.zmLog("You are running on " + $rootScope.platformOS); - - $ionicNativeTransitions.enable(true, false); - - - var lang = ZMDataModel.getDefaultLanguage(); - - - if (lang == undefined) - { - ZMDataModel.zmLog ("No language set, switching to en"); - lang = "en"; + + + + localforage.defineDriver(window.cordovaSQLiteDriver).then(function () { + return localforage.setDriver([ + // Try setting cordovaSQLiteDriver if available, + window.cordovaSQLiteDriver._driver, + // otherwise use one of the default localforage drivers as a fallback. + // This should allow you to transparently do your tests in a browser + localforage.LOCALSTORAGE, + localforage.INDEXEDDB, + localforage.WEBSQL - - } - else - { - ZMDataModel.zmLog ("Language stored as:"+lang); - - } - - // This always returns success - I'm not rejecting - ZMDataModel.setDefaultLanguage(lang, false) - .then (function(success) { - ZMDataModel.zmLog(">>>>Language to be used:" + $translate.proposedLanguage()); - moment.locale($translate.proposedLanguage()); - continueRestOfInit(); - - }); + ]); + }).then(function () { + // this should alert "cordovaSQLiteDriver" when in an emulator or a device + ZMDataModel.zmLog("localforage driver for storage:" + localforage.driver()); + + // Now lets import old data if it exists: + var defaultServerName = $localstorage.get("defaultServerName"); + + localforage.getItem("defaultServerName") + .then (function (val) + { + if (!val && defaultServerName) + { + ZMDataModel.zmLog (">>>>Importing data from localstorage...."); + + + + var dsn = defaultServerName; + var dl = $localstorage.get('defaultLang'); + var ifu = ($localstorage.get('isFirstUse')=='0' ? false:true); + var luc = $localstorage.get('lastUpdateCheck'); + var lbpc = $localstorage.get('latestBlogPostChecked'); + var sgl = $localstorage.getObject('serverGroupList'); + + ZMDataModel.zmLog (">>>Localstorage data found as below:"); + ZMDataModel.zmLog ("server name:"+dsn); + ZMDataModel.zmLog ("default lang :"+dl); + ZMDataModel.zmLog ("is first use:"+ifu); + ZMDataModel.zmLog ("last update check:"+luc); + ZMDataModel.zmLog ("latest blog post check:"+lbpc); + ZMDataModel.zmLog ("server group list:"+sgl); + + localforage.setItem('defaultLang', dl) + .then (function() { + + ZMDataModel.zmLog (">>>>migrated defaultLang..."); + ZMDataModel.setFirstUse(ifu); + return localforage.setItem('isFirstUse', ifu); + }) + .then (function() { + ZMDataModel.zmLog (">>>>migrated isFirstUse..."); + return localforage.setItem('lastUpdateCheck', ifu); + }) + .then (function() { + ZMDataModel.zmLog (">>>>migrated lastUpdateCheck..."); + return localforage.setItem('latestBlogPostChecked', lbpc); + }) + .then (function() { + ZMDataModel.zmLog (">>>>migrated latestBlogPostChecked..."); + return localforage.setItem('serverGroupList', sgl); + }) + .then (function() { + ZMDataModel.zmLog (">>>>migrated serverGroupList..."); + return localforage.setItem('defaultServerName',dsn); + }) + .then (function() { + ZMDataModel.zmLog (">>>>migrated defaultServerName..."); + ZMDataModel.zmLog (">>>>Migrated all values, continuing..."); + //ZMDataModel.migrationComplete(); + continueInitialInit(); + }); + + } + else + { + ZMDataModel.zmLog (">>>>No data to import...."); + //ZMDataModel.migrationComplete(); + continueInitialInit(); + } + + + + }); + + }); + - - - function continueRestOfInit() + function continueInitialInit() { + var pixelRatio = window.devicePixelRatio || 1; + $rootScope.devWidth = ((window.innerWidth > 0) ? window.innerWidth : screen.width); + $rootScope.devHeight = ((window.innerHeight > 0) ? window.innerHeight : screen.height); + // for making sure we canuse $state.go with ng-click + // needed for views that use popovers + $rootScope.$state = $state; + $rootScope.$stateParams = $stateParams; + + + if (window.cordova && window.cordova.plugins.Keyboard) { + cordova.plugins.Keyboard.disableScroll(true); + } + if (window.StatusBar) { + // org.apache.cordova.statusbar required + StatusBar.styleDefault(); + } + + + if (window.cordova) { + $cordovaSplashscreen.hide(); + + ZMDataModel.zmLog("Enabling insecure SSL"); + cordova.plugins.certificates.trustUnsecureCerts(true); + + cordova.getAppVersion(function (version) { + appVersion = version; + ZMDataModel.zmLog("App Version: " + appVersion); + ZMDataModel.setAppVersion(appVersion); + }); + } + + $fileLogger.checkFile().then(function (resp) { + if (parseInt(resp.size) > zm.logFileMaxSize) { + + $fileLogger.deleteLogfile().then(function () { + ZMDataModel.zmLog("Deleting old log file as it exceeds " + zm.logFileMaxSize + " bytes"); + + }); + } + }); + + $fileLogger.setStorageFilename(zm.logFile); + $fileLogger.setTimestampFormat('MMM d, y ' + ZMDataModel.getTimeFormat()); + + + + + $ionicNativeTransitions.enable(true, false); + + + var lang = ZMDataModel.getDefaultLanguage(); + + + if (lang == undefined) { + ZMDataModel.zmLog("No language set, switching to en"); + lang = "en"; + + + } else { + ZMDataModel.zmLog("Language stored as:" + lang); + + } + //continueRestOfInit(); + // This always returns success - I'm not rejecting + ZMDataModel.setDefaultLanguage(lang, false) + .then(function (success) { + ZMDataModel.zmLog(">>>>Language to be used:" + $translate.proposedLanguage()); + moment.locale($translate.proposedLanguage()); + continueRestOfInit(); + + }); + } + + + + + + + function continueRestOfInit() { ZMDataModel.zmLog("Language file loaded, continuing with rest"); ZMDataModel.init(); EventServer.init(); zmCheckUpdates.start(); ZMDataModel.zmLog("Setting up POST LOGIN timer"); zmAutoLogin.start(); + + + } - - //--------------------------------------------------------------------------- - // resume handler - //---------------------------------------------------------------------------- + + //--------------------------------------------------------------------------- + // resume handler + //---------------------------------------------------------------------------- document.addEventListener("resume", function () { ZMDataModel.zmLog("App is resuming from background"); var forceDelay = ZMDataModel.getLogin().resumeDelay; @@ -1218,9 +1323,9 @@ angular.module('zmApp', [ }, false); - //--------------------------------------------------------------------------- - // background handler - //---------------------------------------------------------------------------- + //--------------------------------------------------------------------------- + // background handler + //---------------------------------------------------------------------------- document.addEventListener("pause", function () { ZMDataModel.setBackground(true); ZMDataModel.setJustResumed(true); // used for window stop @@ -1251,9 +1356,9 @@ angular.module('zmApp', [ }, false); - - + + }); //platformReady @@ -1302,28 +1407,28 @@ angular.module('zmApp', [ $ionicNativeTransitionsProvider.setDefaultOptions({ duration: 250, }); - + $translateProvider.useStaticFilesLoader({ - prefix: 'lang/locale-', - suffix: '.json' - }); - + prefix: 'lang/locale-', + suffix: '.json' + }); + //$translateProvider.useLocalStorage(); - - - $translateProvider.registerAvailableLanguageKeys(['en', 'de','es', 'fr', 'it', 'ja', 'ko', 'zh', 'zh_CN', 'zh_TW', 'pt'], { - 'en_*': 'en', - 'de_*': 'de', - 'es_*': 'es', - 'fr_*': 'fr', - 'it_*': 'it', - 'ja_*': 'ja', - 'ko_*': 'ko', - 'pt_*': 'pt', - '*': 'en' // must be last - }); - - + + + $translateProvider.registerAvailableLanguageKeys(['en', 'de', 'es', 'fr', 'it', 'ja', 'ko', 'zh', 'zh_CN', 'zh_TW', 'pt'], { + 'en_*': 'en', + 'de_*': 'de', + 'es_*': 'es', + 'fr_*': 'fr', + 'it_*': 'it', + 'ja_*': 'ja', + 'ko_*': 'ko', + 'pt_*': 'pt', + '*': 'en' // must be last + }); + + //$translateProvider.determinePreferredLanguage(); //$translateProvider.preferredLanguage("en"); @@ -1605,8 +1710,8 @@ angular.module('zmApp', [ $urlRouterProvider.otherwise(function ($injector, $location) { var $state = $injector.get("$state"); - - $state.go("zm-portal-login"); + // we will do this after data is loaded + // $state.go("zm-portal-login"); }); diff --git a/www/js/ionicUtils.js b/www/js/ionicUtils.js index dab37f6f..9b8a21ff 100644 --- a/www/js/ionicUtils.js +++ b/www/js/ionicUtils.js @@ -6,8 +6,13 @@ angular.module('ionic.utils', []) -.factory('$localstorage', ['$window', function($window) { +.factory('$localstorage', ['$window', function($window) { return { + + init: function() + { + }, + set: function(key, value) { $window.localStorage[key] = value; }, diff --git a/www/lib/localforage-cordovasqlitedriver/.babelrc b/www/lib/localforage-cordovasqlitedriver/.babelrc new file mode 100644 index 00000000..653b5be2 --- /dev/null +++ b/www/lib/localforage-cordovasqlitedriver/.babelrc @@ -0,0 +1,3 @@ +{ + "presets": [ "es2015-rollup" ] +}
\ No newline at end of file diff --git a/www/lib/localforage-cordovasqlitedriver/.bower.json b/www/lib/localforage-cordovasqlitedriver/.bower.json new file mode 100644 index 00000000..7cc247e6 --- /dev/null +++ b/www/lib/localforage-cordovasqlitedriver/.bower.json @@ -0,0 +1,34 @@ +{ + "name": "localforage-cordovasqlitedriver", + "version": "1.4.1", + "main": [ + "src/localforage-cordovasqlitedriver.js" + ], + "ignore": [ + ".travis.yml", + "CONTRIBUTING.md", + "config.rb", + "Gemfile", + "Gemfile.lock", + "Rakefile", + "LICENSE", + "docs*", + "examples*", + "test*", + "site*" + ], + "dependencies": { + "localforage": "^1.4.0" + }, + "homepage": "https://github.com/thgreasi/localForage-cordovaSQLiteDriver", + "_release": "1.4.1", + "_resolution": { + "type": "version", + "tag": "v1.4.1", + "commit": "8e372775636d7e462bb3231cd9745864f420a0f4" + }, + "_source": "https://github.com/thgreasi/localForage-cordovaSQLiteDriver.git", + "_target": "~1.4.1", + "_originalSource": "localForage-cordovaSQLiteDriver", + "_direct": true +}
\ No newline at end of file diff --git a/www/lib/localforage-cordovasqlitedriver/.eslintrc b/www/lib/localforage-cordovasqlitedriver/.eslintrc new file mode 100644 index 00000000..9e56abf4 --- /dev/null +++ b/www/lib/localforage-cordovasqlitedriver/.eslintrc @@ -0,0 +1,25 @@ +{ + "parser": "babel-eslint", + "parserOptions": { + "ecmaVersion": 6, + "sourceType": "module", + "ecmaFeatures": { + "modules": true + } + }, + "extends": "eslint:recommended", + "env": { + "node": true, + "mocha": true + }, + "rules":{ + "no-console": 0 + }, + "globals": { + "localforage": true, + "Promise": true, + "console": true, + "self": true, + "System": true + } +}
\ No newline at end of file diff --git a/www/lib/localforage-cordovasqlitedriver/.gitignore b/www/lib/localforage-cordovasqlitedriver/.gitignore new file mode 100644 index 00000000..0f1e467f --- /dev/null +++ b/www/lib/localforage-cordovasqlitedriver/.gitignore @@ -0,0 +1,35 @@ +.DS_Store +.swp +build +bower_components +node_modules +components + +# Logs + Sauce Labs Tests +*.log + +#WebStorm files +.idea + +### Ruby Stuff for slate docs +*.gem +*.rbc +.bundle +.config +coverage +InstalledFiles +lib/bundler/man +pkg +rdoc +spec/reports +test/tmp +test/version_tmp +tmp +*.DS_STORE +build/ +.cache + +# YARD artifacts +.yardoc +_yardoc +doc/ diff --git a/www/lib/localforage-cordovasqlitedriver/.jscsrc b/www/lib/localforage-cordovasqlitedriver/.jscsrc new file mode 100644 index 00000000..3415b8de --- /dev/null +++ b/www/lib/localforage-cordovasqlitedriver/.jscsrc @@ -0,0 +1,31 @@ +{ + "esnext": true, + "disallowSpacesInAnonymousFunctionExpression": { + "beforeOpeningRoundBrace": true + }, + "disallowTrailingComma": true, + "requireBlocksOnNewline": true, + "requireLineFeedAtFileEnd": true, + "requireSpaceAfterKeywords": [ + "if", + "else", + "for", + "while", + "do", + "switch", + "return", + "try", + "catch" + ], + "requireSpaceBeforeBlockStatements": true, + "requireSpacesInConditionalExpression": true, + "requireSpacesInFunctionExpression": { + "beforeOpeningCurlyBrace": true + }, + "safeContextKeyword": ["globalObject", "self"], + "validateQuoteMarks": { + "escape": true, + "mark": "'" + }, + "validateIndentation": 4 +} diff --git a/www/lib/localforage-cordovasqlitedriver/.jshintrc b/www/lib/localforage-cordovasqlitedriver/.jshintrc new file mode 100644 index 00000000..f29a720b --- /dev/null +++ b/www/lib/localforage-cordovasqlitedriver/.jshintrc @@ -0,0 +1,32 @@ +{ + "asi": false, + "bitwise": true, + "browser": true, + "curly": true, + "eqeqeq": true, + "eqnull": true, + "esnext": true, + "immed": true, + "latedef": true, + "newcap": true, + "noarg": true, + "nonew": true, + "quotmark": false, + "strict": false, + "trailing": false, + "undef": true, + "unused": true, + + "validthis": true, + + "globals": { + "console": true, + "define": true, + "localforage": true, + "module": true, + "Promise": true, + "require": true, + "self": true, + "System": true + } +} diff --git a/www/lib/localforage-cordovasqlitedriver/README.md b/www/lib/localforage-cordovasqlitedriver/README.md new file mode 100644 index 00000000..88669300 --- /dev/null +++ b/www/lib/localforage-cordovasqlitedriver/README.md @@ -0,0 +1,65 @@ +# localForage-cordovaSQLiteDriver +[](https://www.npmjs.com/package/localforage-cordovasqlitedriver) +SQLite driver for [Cordova](https://cordova.apache.org/) apps using [localForage](https://github.com/mozilla/localForage). + +## Requirements + +* [Cordova](https://cordova.apache.org/)/[ionic](http://ionicframework.com/) +* [Cordova SQLite storage plugin](https://github.com/litehelpers/Cordova-sqlite-storage/) or [Cordova SQLite Plugin 2](https://github.com/nolanlawson/cordova-plugin-sqlite-2) +* [localForage](https://github.com/mozilla/localForage) v1.4.0+ + * for earlier versions of localforage, please use the v1.2.x releases + +## Install Dependencies + +* install Cordova-sqlite-storage plugin `cordova plugin add https://github.com/litehelpers/Cordova-sqlite-storage.git` +* install localForage-cordovaSQLiteDriver `bower install --save localForage-cordovaSQLiteDriver` + +## CHANGELOG + +### v1.3 +Reduce driver size (almost by 50%) by "inheriting" the method implementations of the `localforage.WEBSQL` driver. + +### v1.2 *BREAKING CHANGE* +Add support for newer versions of [Cordova SQLite storage plugin](https://github.com/litehelpers/Cordova-sqlite-storage/) (v0.8.x & v1.2.x). + +*UPGRADE WARNING*: The default storage location for SQLite has changed in newer versions of [Cordova SQLite storage plugin](https://github.com/litehelpers/Cordova-sqlite-storage/). The new "`default`" location value is NOT the same as the old "`default`" location and will break an upgrade for an app that was using the old default value (0) on iOS. If you are upgrading to a newer version of `localForage-cordovaSQLiteDriver` you need to verify where your previous storage location was and update the `location` property of the localForage database. Otherwise the default is `'default'`. This is to avoid breaking the iCloud Design Guide. See [here](https://github.com/litehelpers/Cordova-sqlite-storage#important-icloud-backup-of-sqlite-database-is-not-allowed) for further details. + +### v1.1 +Try using the `getSerializer()` (available in localforage v1.3) as the prefered way to retrieve the serializer. + +## Setup Your Project + +* Include localforage and localForage-cordovaSQLiteDriver in your main html page, after the cordova include. +* Call `defineDriver` and `setDriver` to make localForage use the cordovaSQLiteDriver. + +```html +<script src="cordova.js"></script> + +<script src="lib/localforage/dist/localforage.js"></script> +<script src="lib/localForage-cordovaSQLiteDriver/src/localforage-cordovasqlitedriver.js"></script> +<script> +localforage.defineDriver(window.cordovaSQLiteDriver).then(function() { + return localforage.setDriver([ + // Try setting cordovaSQLiteDriver if available, + window.cordovaSQLiteDriver._driver, + // otherwise use one of the default localforage drivers as a fallback. + // This should allow you to transparently do your tests in a browser + localforage.INDEXEDDB, + localforage.WEBSQL, + localforage.LOCALSTORAGE + ]); +}).then(function() { + // this should alert "cordovaSQLiteDriver" when in an emulator or a device + alert(localforage.driver()); + // set a value; + return localforage.setItem('testPromiseKey', 'testPromiseValue'); +}).then(function() { + return localforage.getItem('testPromiseKey'); +}).then(function(value) { + alert(value); +}).catch(function(err) { + alert(err); +}); +</script> +``` +[Exaple Ionic project](https://github.com/thgreasi/localForage-cordovaSQLiteDriver-TestIonicApp) diff --git a/www/lib/localforage-cordovasqlitedriver/bower.json b/www/lib/localforage-cordovasqlitedriver/bower.json new file mode 100644 index 00000000..2c3510de --- /dev/null +++ b/www/lib/localforage-cordovasqlitedriver/bower.json @@ -0,0 +1,23 @@ +{ + "name": "localforage-cordovasqlitedriver", + "version": "1.4.1", + "main": [ + "src/localforage-cordovasqlitedriver.js" + ], + "ignore": [ + ".travis.yml", + "CONTRIBUTING.md", + "config.rb", + "Gemfile", + "Gemfile.lock", + "Rakefile", + "LICENSE", + "docs*", + "examples*", + "test*", + "site*" + ], + "dependencies": { + "localforage": "^1.4.0" + } +} diff --git a/www/lib/localforage-cordovasqlitedriver/dist/localforage-cordovasqlitedriver.es6.js b/www/lib/localforage-cordovasqlitedriver/dist/localforage-cordovasqlitedriver.es6.js new file mode 100644 index 00000000..8dbc92b0 --- /dev/null +++ b/www/lib/localforage-cordovasqlitedriver/dist/localforage-cordovasqlitedriver.es6.js @@ -0,0 +1,142 @@ +function getSerializerPromise(localForageInstance) { + if (getSerializerPromise.result) { + return getSerializerPromise.result; + } + if (!localForageInstance || typeof localForageInstance.getSerializer !== 'function') { + Promise.reject(new Error('localforage.getSerializer() was not available! ' + 'localforage v1.4+ is required!')); + } + getSerializerPromise.result = localForageInstance.getSerializer(); + return getSerializerPromise.result; +} + +function getDriverPromise(localForageInstance, driverName) { + getDriverPromise.result = getDriverPromise.result || {}; + if (getDriverPromise.result[driverName]) { + return getDriverPromise.result[driverName]; + } + if (!localForageInstance || typeof localForageInstance.getDriver !== 'function') { + Promise.reject(new Error('localforage.getDriver() was not available! ' + 'localforage v1.4+ is required!')); + } + getDriverPromise.result[driverName] = localForageInstance.getDriver(driverName); + return getDriverPromise.result[driverName]; +} + +function getWebSqlDriverPromise(localForageInstance) { + return getDriverPromise(localForageInstance, localForageInstance.WEBSQL); +} + +/* global document, sqlitePlugin */ +// we can't import this, since it gets defined later +// import sqlitePlugin from 'sqlitePlugin'; + +var deviceReady = new Promise(function (resolve, reject) { + if (typeof sqlitePlugin !== 'undefined') { + resolve(); + } else if (typeof cordova === 'undefined') { + reject(); + } else { + // Wait for Cordova to load + document.addEventListener("deviceready", resolve, false); + } +}); + +var openDatabasePromise = deviceReady.catch(Promise.resolve).then(function () { + return new Promise(function (resolve, reject) { + if (typeof sqlitePlugin !== 'undefined' && typeof sqlitePlugin.openDatabase === 'function') { + resolve(sqlitePlugin.openDatabase); + } else { + reject('SQLite plugin is not present.'); + } + }); +}); + +// // If cordova is not present, we can stop now. +// if (!globalObject.cordova) { +// return; +// } + +// Open the cordova sqlite plugin database (automatically creates one if one didn't +// previously exist), using any options set in the config. +function _initStorage(options) { + var self = this; + var dbInfo = { + db: null + }; + + if (options) { + for (var i in options) { + dbInfo[i] = typeof options[i] !== 'string' ? options[i].toString() : options[i]; + } + } + + var dbInfoPromise = openDatabasePromise.then(function (openDatabase) { + return new Promise(function (resolve, reject) { + // Open the database; the openDatabase API will automatically + // create it for us if it doesn't exist. + try { + dbInfo.location = dbInfo.location || 'default'; + dbInfo.db = openDatabase({ + name: dbInfo.name, + version: String(dbInfo.version), + description: dbInfo.description, + size: dbInfo.size, + location: dbInfo.location + }); + } catch (e) { + reject(e); + } + + // Create our key/value table if it doesn't exist. + dbInfo.db.transaction(function (t) { + t.executeSql('CREATE TABLE IF NOT EXISTS ' + dbInfo.storeName + ' (id INTEGER PRIMARY KEY, key unique, value)', [], function () { + self._dbInfo = dbInfo; + resolve(); + }, function (t, error) { + reject(error); + }); + }); + }); + }); + + var serializerPromise = getSerializerPromise(self); + var webSqlDriverPromise = getWebSqlDriverPromise(self); + + return Promise.all([serializerPromise, webSqlDriverPromise, dbInfoPromise]).then(function (results) { + dbInfo.serializer = results[0]; + return dbInfoPromise; + }); +} + +var cordovaSQLiteDriver = { + _driver: 'cordovaSQLiteDriver', + _initStorage: _initStorage, + _support: function _support() { + return openDatabasePromise.then(function (openDatabase) { + return !!openDatabase; + }).catch(function () { + return false; + }); + } +}; + +function wireUpDriverMethods(driver) { + var LibraryMethods = ['clear', 'getItem', 'iterate', 'key', 'keys', 'length', 'removeItem', 'setItem']; + + function wireUpDriverMethod(driver, methodName) { + driver[methodName] = function () { + var localForageInstance = this; + var args = arguments; + return getWebSqlDriverPromise(localForageInstance).then(function (webSqlDriver) { + return webSqlDriver[methodName].apply(localForageInstance, args); + }); + }; + } + + for (var i = 0, len = LibraryMethods.length; i < len; i++) { + wireUpDriverMethod(driver, LibraryMethods[i]); + } +} + +wireUpDriverMethods(cordovaSQLiteDriver); + +export default cordovaSQLiteDriver;
\ No newline at end of file diff --git a/www/lib/localforage-cordovasqlitedriver/dist/localforage-cordovasqlitedriver.js b/www/lib/localforage-cordovasqlitedriver/dist/localforage-cordovasqlitedriver.js new file mode 100644 index 00000000..f6b925e6 --- /dev/null +++ b/www/lib/localforage-cordovasqlitedriver/dist/localforage-cordovasqlitedriver.js @@ -0,0 +1,150 @@ +(function (global, factory) { + typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() : + typeof define === 'function' && define.amd ? define(factory) : + (global.cordovaSQLiteDriver = factory()); +}(this, function () { 'use strict'; + + function getSerializerPromise(localForageInstance) { + if (getSerializerPromise.result) { + return getSerializerPromise.result; + } + if (!localForageInstance || typeof localForageInstance.getSerializer !== 'function') { + Promise.reject(new Error('localforage.getSerializer() was not available! ' + 'localforage v1.4+ is required!')); + } + getSerializerPromise.result = localForageInstance.getSerializer(); + return getSerializerPromise.result; + } + + function getDriverPromise(localForageInstance, driverName) { + getDriverPromise.result = getDriverPromise.result || {}; + if (getDriverPromise.result[driverName]) { + return getDriverPromise.result[driverName]; + } + if (!localForageInstance || typeof localForageInstance.getDriver !== 'function') { + Promise.reject(new Error('localforage.getDriver() was not available! ' + 'localforage v1.4+ is required!')); + } + getDriverPromise.result[driverName] = localForageInstance.getDriver(driverName); + return getDriverPromise.result[driverName]; + } + + function getWebSqlDriverPromise(localForageInstance) { + return getDriverPromise(localForageInstance, localForageInstance.WEBSQL); + } + + /* global document, sqlitePlugin */ + // we can't import this, since it gets defined later + // import sqlitePlugin from 'sqlitePlugin'; + + var deviceReady = new Promise(function (resolve, reject) { + if (typeof sqlitePlugin !== 'undefined') { + resolve(); + } else if (typeof cordova === 'undefined') { + reject(); + } else { + // Wait for Cordova to load + document.addEventListener("deviceready", resolve, false); + } + }); + + var openDatabasePromise = deviceReady.catch(Promise.resolve).then(function () { + return new Promise(function (resolve, reject) { + if (typeof sqlitePlugin !== 'undefined' && typeof sqlitePlugin.openDatabase === 'function') { + resolve(sqlitePlugin.openDatabase); + } else { + reject('SQLite plugin is not present.'); + } + }); + }); + + // // If cordova is not present, we can stop now. + // if (!globalObject.cordova) { + // return; + // } + + // Open the cordova sqlite plugin database (automatically creates one if one didn't + // previously exist), using any options set in the config. + function _initStorage(options) { + var self = this; + var dbInfo = { + db: null + }; + + if (options) { + for (var i in options) { + dbInfo[i] = typeof options[i] !== 'string' ? options[i].toString() : options[i]; + } + } + + var dbInfoPromise = openDatabasePromise.then(function (openDatabase) { + return new Promise(function (resolve, reject) { + // Open the database; the openDatabase API will automatically + // create it for us if it doesn't exist. + try { + dbInfo.location = dbInfo.location || 'default'; + dbInfo.db = openDatabase({ + name: dbInfo.name, + version: String(dbInfo.version), + description: dbInfo.description, + size: dbInfo.size, + location: dbInfo.location + }); + } catch (e) { + reject(e); + } + + // Create our key/value table if it doesn't exist. + dbInfo.db.transaction(function (t) { + t.executeSql('CREATE TABLE IF NOT EXISTS ' + dbInfo.storeName + ' (id INTEGER PRIMARY KEY, key unique, value)', [], function () { + self._dbInfo = dbInfo; + resolve(); + }, function (t, error) { + reject(error); + }); + }); + }); + }); + + var serializerPromise = getSerializerPromise(self); + var webSqlDriverPromise = getWebSqlDriverPromise(self); + + return Promise.all([serializerPromise, webSqlDriverPromise, dbInfoPromise]).then(function (results) { + dbInfo.serializer = results[0]; + return dbInfoPromise; + }); + } + + var cordovaSQLiteDriver = { + _driver: 'cordovaSQLiteDriver', + _initStorage: _initStorage, + _support: function _support() { + return openDatabasePromise.then(function (openDatabase) { + return !!openDatabase; + }).catch(function () { + return false; + }); + } + }; + + function wireUpDriverMethods(driver) { + var LibraryMethods = ['clear', 'getItem', 'iterate', 'key', 'keys', 'length', 'removeItem', 'setItem']; + + function wireUpDriverMethod(driver, methodName) { + driver[methodName] = function () { + var localForageInstance = this; + var args = arguments; + return getWebSqlDriverPromise(localForageInstance).then(function (webSqlDriver) { + return webSqlDriver[methodName].apply(localForageInstance, args); + }); + }; + } + + for (var i = 0, len = LibraryMethods.length; i < len; i++) { + wireUpDriverMethod(driver, LibraryMethods[i]); + } + } + + wireUpDriverMethods(cordovaSQLiteDriver); + + return cordovaSQLiteDriver; + +}));
\ No newline at end of file diff --git a/www/lib/localforage-cordovasqlitedriver/lib/cordova-sqlite.js b/www/lib/localforage-cordovasqlitedriver/lib/cordova-sqlite.js new file mode 100644 index 00000000..9a755349 --- /dev/null +++ b/www/lib/localforage-cordovasqlitedriver/lib/cordova-sqlite.js @@ -0,0 +1,25 @@ +/* global document, sqlitePlugin */ +// we can't import this, since it gets defined later +// import sqlitePlugin from 'sqlitePlugin'; + +var deviceReady = new Promise(function(resolve, reject) { + if (typeof sqlitePlugin !== 'undefined') { + resolve(); + } else if (typeof cordova === 'undefined') { + reject(); + } else { + // Wait for Cordova to load + document.addEventListener("deviceready", resolve, false); + } +}); + +export var openDatabasePromise = deviceReady.catch(Promise.resolve).then(function() { + return new Promise(function(resolve, reject) { + if (typeof sqlitePlugin !== 'undefined' && + typeof sqlitePlugin.openDatabase === 'function') { + resolve(sqlitePlugin.openDatabase); + } else { + reject('SQLite plugin is not present.'); + } + }); +}); diff --git a/www/lib/localforage-cordovasqlitedriver/lib/localforage-cordovasqlitedriver.js b/www/lib/localforage-cordovasqlitedriver/lib/localforage-cordovasqlitedriver.js new file mode 100644 index 00000000..ffbf7a79 --- /dev/null +++ b/www/lib/localforage-cordovasqlitedriver/lib/localforage-cordovasqlitedriver.js @@ -0,0 +1,120 @@ +/* + * Includes code from: + * + * localForage - websql driver + * https://github.com/mozilla/localforage + * + * Copyright (c) 2015 Mozilla + * Licensed under Apache 2.0 license. + * + */ +// import localforage from 'localforage'; +import { getSerializerPromise, getWebSqlDriverPromise } from './utils'; +import { openDatabasePromise } from './cordova-sqlite'; + +// // If cordova is not present, we can stop now. +// if (!globalObject.cordova) { +// return; +// } + +// Open the cordova sqlite plugin database (automatically creates one if one didn't +// previously exist), using any options set in the config. +function _initStorage(options) { + var self = this; + var dbInfo = { + db: null + }; + + if (options) { + for (var i in options) { + dbInfo[i] = typeof(options[i]) !== 'string' ? + options[i].toString() : options[i]; + } + } + + var dbInfoPromise = openDatabasePromise.then(function(openDatabase){ + return new Promise(function(resolve, reject) { + // Open the database; the openDatabase API will automatically + // create it for us if it doesn't exist. + try { + dbInfo.location = dbInfo.location || 'default'; + dbInfo.db = openDatabase({ + name: dbInfo.name, + version: String(dbInfo.version), + description: dbInfo.description, + size: dbInfo.size, + location: dbInfo.location + }); + } catch (e) { + reject(e); + } + + // Create our key/value table if it doesn't exist. + dbInfo.db.transaction(function(t) { + t.executeSql('CREATE TABLE IF NOT EXISTS ' + dbInfo.storeName + + ' (id INTEGER PRIMARY KEY, key unique, value)', [], + function() { + self._dbInfo = dbInfo; + resolve(); + }, function(t, error) { + reject(error); + }); + }); + }); + }); + + var serializerPromise = getSerializerPromise(self); + var webSqlDriverPromise = getWebSqlDriverPromise(self); + + return Promise.all([ + serializerPromise, + webSqlDriverPromise, + dbInfoPromise + ]).then(function(results) { + dbInfo.serializer = results[0]; + return dbInfoPromise; + }); +} + +var cordovaSQLiteDriver = { + _driver: 'cordovaSQLiteDriver', + _initStorage: _initStorage, + _support: function() { + return openDatabasePromise.then(function(openDatabase) { + return !!openDatabase; + }).catch(function(){ + return false; + }); + } +}; + +function wireUpDriverMethods(driver) { + var LibraryMethods = [ + 'clear', + 'getItem', + 'iterate', + 'key', + 'keys', + 'length', + 'removeItem', + 'setItem' + ]; + + function wireUpDriverMethod(driver, methodName) { + driver[methodName] = function () { + var localForageInstance = this; + var args = arguments; + return getWebSqlDriverPromise(localForageInstance).then(function (webSqlDriver) { + return webSqlDriver[methodName].apply(localForageInstance, args); + }); + }; + } + + for (var i = 0, len = LibraryMethods.length; i < len; i++) { + wireUpDriverMethod(driver, LibraryMethods[i]); + } +} + +wireUpDriverMethods(cordovaSQLiteDriver); + +export default cordovaSQLiteDriver; diff --git a/www/lib/localforage-cordovasqlitedriver/lib/utils.js b/www/lib/localforage-cordovasqlitedriver/lib/utils.js new file mode 100644 index 00000000..e83b61d9 --- /dev/null +++ b/www/lib/localforage-cordovasqlitedriver/lib/utils.js @@ -0,0 +1,40 @@ +export function getSerializerPromise(localForageInstance) { + if (getSerializerPromise.result) { + return getSerializerPromise.result; + } + if (!localForageInstance || typeof localForageInstance.getSerializer !== 'function') { + Promise.reject(new Error( + 'localforage.getSerializer() was not available! ' + + 'localforage v1.4+ is required!')); + } + getSerializerPromise.result = localForageInstance.getSerializer(); + return getSerializerPromise.result; +} + +export function getDriverPromise(localForageInstance, driverName) { + getDriverPromise.result = getDriverPromise.result || {}; + if (getDriverPromise.result[driverName]) { + return getDriverPromise.result[driverName]; + } + if (!localForageInstance || typeof localForageInstance.getDriver !== 'function') { + Promise.reject(new Error( + 'localforage.getDriver() was not available! ' + + 'localforage v1.4+ is required!')); + } + getDriverPromise.result[driverName] = localForageInstance.getDriver(driverName); + return getDriverPromise.result[driverName]; +} + +export function getWebSqlDriverPromise(localForageInstance) { + return getDriverPromise(localForageInstance, localForageInstance.WEBSQL); +} + +export function executeCallback(promise, callback) { + if (callback) { + promise.then(function(result) { + callback(null, result); + }, function(error) { + callback(error); + }); + } +} diff --git a/www/lib/localforage-cordovasqlitedriver/package.json b/www/lib/localforage-cordovasqlitedriver/package.json new file mode 100644 index 00000000..cb09c3c7 --- /dev/null +++ b/www/lib/localforage-cordovasqlitedriver/package.json @@ -0,0 +1,44 @@ +{ + "name": "localforage-cordovasqlitedriver", + "version": "1.4.1", + "description": "SQLite driver for Cordova apps using localForage.", + "homepage": "https://github.com/thgreasi/localForage-cordovaSQLiteDriver", + "main": "dist/localforage-cordovasqlitedriver.js", + "jsnext:main": "dist/localforage-cordovasqlitedriver.es6.js", + "scripts": { + "prebuild": "eslint lib test", + "build": "rollup -c rollup.config.umd.js && rollup -c rollup.config.es6.js", + "pretest": "rollup -c rollup.config.test.js", + "test": "mocha build/test-bundle.js", + "prepublish": "npm run build && npm test" + }, + "repository": { + "type": "git", + "url": "git://github.com/thgreasi/localForage-cordovaSQLiteDriver.git" + }, + "keywords": [ + "localforage", + "SQLite", + "driver", + "cordova" + ], + "author": "Thodoris Greasidis", + "licence": "Apache-2.0", + "bugs": { + "url": "http://github.com/thgreasi/localForage-cordovaSQLiteDriver/issues" + }, + "devDependencies": { + "babel-eslint": "^6.0.4", + "babel-preset-es2015-rollup": "^1.1.1", + "eslint": "^2.8.0", + "mocha": "^2.4.5", + "requirejs": "^2.2.0", + "rollup": "^0.26.1", + "rollup-plugin-babel": "^2.4.0", + "rollup-plugin-multi-entry": "^1.2.0", + "source-map-support": "^0.4.0" + }, + "dependencies": { + "localforage": ">=1.4.0" + } +} diff --git a/www/lib/localforage-cordovasqlitedriver/rollup.config.es6.js b/www/lib/localforage-cordovasqlitedriver/rollup.config.es6.js new file mode 100644 index 00000000..ef894ed6 --- /dev/null +++ b/www/lib/localforage-cordovasqlitedriver/rollup.config.es6.js @@ -0,0 +1,6 @@ +import config from './rollup.config'; + +config.format = 'es6'; +config.dest = 'dist/localforage-cordovasqlitedriver.es6.js'; + +export default config; diff --git a/www/lib/localforage-cordovasqlitedriver/rollup.config.js b/www/lib/localforage-cordovasqlitedriver/rollup.config.js new file mode 100644 index 00000000..b189698c --- /dev/null +++ b/www/lib/localforage-cordovasqlitedriver/rollup.config.js @@ -0,0 +1,7 @@ +import babel from 'rollup-plugin-babel'; + +export default { + entry: 'lib/localforage-cordovasqlitedriver.js', + // sourceMap: true, + plugins: [babel()] +}; diff --git a/www/lib/localforage-cordovasqlitedriver/rollup.config.test.js b/www/lib/localforage-cordovasqlitedriver/rollup.config.test.js new file mode 100644 index 00000000..ec95bc65 --- /dev/null +++ b/www/lib/localforage-cordovasqlitedriver/rollup.config.test.js @@ -0,0 +1,11 @@ +import babel from 'rollup-plugin-babel'; +import multiEntry from 'rollup-plugin-multi-entry'; + +export default { + entry: 'test/**/*_test.js', + plugins: [babel(), multiEntry()], + format: 'cjs', + intro: 'require("source-map-support").install();', + dest: 'build/test-bundle.js', + sourceMap: true +}; diff --git a/www/lib/localforage-cordovasqlitedriver/rollup.config.umd.js b/www/lib/localforage-cordovasqlitedriver/rollup.config.umd.js new file mode 100644 index 00000000..75f776a8 --- /dev/null +++ b/www/lib/localforage-cordovasqlitedriver/rollup.config.umd.js @@ -0,0 +1,7 @@ +import config from './rollup.config'; + +config.format = 'umd'; +config.dest = 'dist/localforage-cordovasqlitedriver.js'; +config.moduleName = 'cordovaSQLiteDriver'; + +export default config; diff --git a/www/lib/localforage/.babelrc b/www/lib/localforage/.babelrc new file mode 100644 index 00000000..22227717 --- /dev/null +++ b/www/lib/localforage/.babelrc @@ -0,0 +1,6 @@ +{ + "presets": ["es2015-loose"], + "plugins": [ + "add-module-exports" + ] +} diff --git a/www/lib/localforage/.babelrc-umd b/www/lib/localforage/.babelrc-umd new file mode 100644 index 00000000..3d671241 --- /dev/null +++ b/www/lib/localforage/.babelrc-umd @@ -0,0 +1,7 @@ +{ + "presets": ["es2015-loose"], + "plugins": [ + "add-module-exports", + "transform-es2015-modules-umd" + ] +} diff --git a/www/lib/localforage/.bower.json b/www/lib/localforage/.bower.json new file mode 100644 index 00000000..2e7c08b3 --- /dev/null +++ b/www/lib/localforage/.bower.json @@ -0,0 +1,39 @@ +{ + "name": "localforage", + "main": [ + "dist/localforage.js" + ], + "ignore": [ + ".travis.yml", + "CONTRIBUTING.md", + "config.rb", + "Gemfile", + "Gemfile.lock", + "Rakefile", + "LICENSE", + "docs*", + "examples*", + "test*", + "site*" + ], + "dependencies": {}, + "devDependencies": { + "es6-promise": "~1.0.0", + "requirejs": "~2.1.10", + "mocha": "~1.18.2", + "expect": "~0.3.1", + "assert": "~0.1.0", + "modernizr": "~2.8.1" + }, + "version": "1.4.2", + "homepage": "https://github.com/mozilla/localForage", + "_release": "1.4.2", + "_resolution": { + "type": "version", + "tag": "1.4.2", + "commit": "48a690d11da378850949de8dff4b69c5c290969b" + }, + "_source": "https://github.com/mozilla/localForage.git", + "_target": "^1.4.0", + "_originalSource": "localforage" +}
\ No newline at end of file diff --git a/www/lib/localforage/.gitignore b/www/lib/localforage/.gitignore new file mode 100644 index 00000000..94d6ad69 --- /dev/null +++ b/www/lib/localforage/.gitignore @@ -0,0 +1,37 @@ +.DS_Store +.swp +bower_components +node_modules +components +test/localforage.browserify.js +test/localforage.component.js +test/localforage.webpack.js + +# Logs + Sauce Labs Tests +*.log + +#WebStorm files +.idea + +### Ruby Stuff for slate docs +*.gem +*.rbc +.bundle +.config +coverage +InstalledFiles +lib/bundler/man +pkg +rdoc +spec/reports +test/tmp +test/version_tmp +tmp +*.DS_STORE +build/ +.cache + +# YARD artifacts +.yardoc +_yardoc +doc/ diff --git a/www/lib/localforage/.jscsrc b/www/lib/localforage/.jscsrc new file mode 100644 index 00000000..3415b8de --- /dev/null +++ b/www/lib/localforage/.jscsrc @@ -0,0 +1,31 @@ +{ + "esnext": true, + "disallowSpacesInAnonymousFunctionExpression": { + "beforeOpeningRoundBrace": true + }, + "disallowTrailingComma": true, + "requireBlocksOnNewline": true, + "requireLineFeedAtFileEnd": true, + "requireSpaceAfterKeywords": [ + "if", + "else", + "for", + "while", + "do", + "switch", + "return", + "try", + "catch" + ], + "requireSpaceBeforeBlockStatements": true, + "requireSpacesInConditionalExpression": true, + "requireSpacesInFunctionExpression": { + "beforeOpeningCurlyBrace": true + }, + "safeContextKeyword": ["globalObject", "self"], + "validateQuoteMarks": { + "escape": true, + "mark": "'" + }, + "validateIndentation": 4 +} diff --git a/www/lib/localforage/.jshintrc b/www/lib/localforage/.jshintrc new file mode 100644 index 00000000..f29a720b --- /dev/null +++ b/www/lib/localforage/.jshintrc @@ -0,0 +1,32 @@ +{ + "asi": false, + "bitwise": true, + "browser": true, + "curly": true, + "eqeqeq": true, + "eqnull": true, + "esnext": true, + "immed": true, + "latedef": true, + "newcap": true, + "noarg": true, + "nonew": true, + "quotmark": false, + "strict": false, + "trailing": false, + "undef": true, + "unused": true, + + "validthis": true, + + "globals": { + "console": true, + "define": true, + "localforage": true, + "module": true, + "Promise": true, + "require": true, + "self": true, + "System": true + } +} diff --git a/www/lib/localforage/CHANGELOG.md b/www/lib/localforage/CHANGELOG.md new file mode 100644 index 00000000..6dcc68c7 --- /dev/null +++ b/www/lib/localforage/CHANGELOG.md @@ -0,0 +1,87 @@ +# About this CHANGELOG + +This file will include all API breakage, new features, and upgrade info in +localForage's lifetime. + +### [1.3](https://github.com/mozilla/localForage/releases/tag/1.3.0) +* We now use ES6 for our source code and `webpack` to bundle the `dist/` files. + +### [1.2](https://github.com/mozilla/localForage/releases/tag/1.2.0) +* Iterate through the entire database using `iterate()`. ([#283](https://github.com/mozilla/localForage/pull/283); fixes [#186](https://github.com/mozilla/localForage/pull/186)) + +### [1.1](https://github.com/mozilla/localForage/releases/tag/1.1.0) +* Custom drivers can be created using `defineDriver()`. ([#282](https://github.com/mozilla/localForage/pull/282); fixes [#267](https://github.com/mozilla/localForage/pull/267)) + +### [1.0.3](https://github.com/mozilla/localForage/releases/tag/1.0.3) +* `config()` accepts a new option: `driver`, so users can set the driver during config rather than using `setDriver()`. ([#273](https://github.com/mozilla/localForage/pull/273); fixes [#168](https://github.com/mozilla/localForage/pull/168)) + +### [1.0](https://github.com/mozilla/localForage/releases/tag/1.0.0) + +* It is no longer necessary to queue commands using `ready()` when using RequireJS. ([723cc94e06](https://github.com/mozilla/localForage/commit/723cc94e06af4f5ba4c53fa65524ccd5f6c4432e)) +* `setDriver` now accepts an array of drivers to be used, in order of preference, instead of simply a string. The string option is still supported. (eg. now one can use `setDriver(['WebSQL', 'localStorage'])` instead of `setDriver('WebSQL')`) +* node-style, error-first argument method signatures are used for callbacks. Promises don't use error-first method signatures; instead they supply an error to the promise's `reject()` function. + +### [0.9](https://github.com/mozilla/localForage/releases/tag/0.9.1) + +This release drops support for some legacy browsers, though not actually the +ones you might think. localForage's new policy is to support the current +version of all major browsers plus up to three versions back. + +* Add built versions without the Promises polyfill to `dist/` directory. ([#172](https://github.com/mozilla/localForage/pull/172)) +* **Drop support for Firefox 3.5. Minimum version is now Firefox 25.** (Technically, Firefox 4+ seems to work.) +* **Drop support for Chrome 31 and below. Minimum version is now Chrome 32.** +* Fix a **lot** of bugs. Especially in Internet Exploder. +* Switch to Mocha tests and test on [Sauce Labs](https://saucelabs.com/). +* Add a `keys()` method. ([#180](https://github.com/mozilla/localForage/pull/180)) +* Check for localStorage instead of assuming it's available. ([#183](https://github.com/mozilla/localForage/pull/183)) + +### [Version 0.8](https://github.com/mozilla/localForage/releases/tag/0.8.1) + +* Add support for web workers. ([#144](https://github.com/mozilla/localForage/pull/144), [#147](https://github.com/mozilla/localForage/pull/147)). + +### [Version 0.6.1](https://github.com/mozilla/localForage/releases/tag/0.6.1) + +* Put built versions back in `dist/` directory. + +### [Version 0.6.0](https://github.com/mozilla/localForage/releases/tag/0.6.0) + +* Add `localforage.config`. ([#40](https://github.com/mozilla/localForage/pull/140)) +* Fix iFrame bug in WebKit. ([#78](https://github.com/mozilla/localForage/issues/78)) +* Improve error handling. ([#60](https://github.com/mozilla/localForage/issues/60)) +* Remove support for `window.localForageConfig`. ([#135](https://github.com/mozilla/localForage/issues/135)) + +### [Version 0.4](https://github.com/mozilla/localForage/releases/tag/0.4.0) + +* Built versions of localForage are now in the top-level directory. ([2d11c90](https://github.com/mozilla/localForage/commit/2d11c90)) + +### [Version 0.3](https://github.com/mozilla/localForage/releases/tag/0.3.0) + +* Check code quality in test suite ([#124](https://github.com/mozilla/localForage/pull/124)) +* `_initDriver()` is called after first public API call ([#119](https://github.com/mozilla/localForage/pull/119)) + +### [Version 0.2.1](https://github.com/mozilla/localForage/releases/tag/0.2.1) + +* Allow configuration of WebSQL DB size ([commit](https://github.com/mozilla/localForage/commit/6e78fff51a23e729206a03e5b750e959d8610f8c)) +* Use bower for JS dependencies instead of `vendor/` folder ([#109](https://github.com/mozilla/localForage/pull/109)) + +### [Version 0.2.0](https://github.com/mozilla/localForage/releases/tag/0.2.0) + +* Add support for ArrayBuffer, Blob, and TypedArrays ([#54](https://github.com/mozilla/localForage/pull/54), [#73](https://github.com/mozilla/localForage/pull/73)) + +### [Version 0.1.1](https://github.com/mozilla/localForage/releases/tag/0.1.1) + +* Added config options to allow users to set their own database names, etc. ([#100](https://github.com/mozilla/localForage/pull/100)) + +--- + +### March 16th, 2014 + +* Moved Backbone adapter to its own repository ([b7987b3091855379d4908376b668b4b51a6fedfe](https://github.com/mozilla/localForage/commit/b7987b3091855379d4908376b668b4b51a6fedfe)) + +### March 13th, 2014 + +* Changed `localforage.driver` to a function instead of the string directly ([49415145021b0029d2521182de6e338e048fe5b1](https://github.com/mozilla/localForage/commit/49415145021b0029d2521182de6e338e048fe5b1)) + +### March 4th, 2014 + +* Changed the IndexedDB database name from `asyncStorage` to `localforage` ([f4e0156a29969a79005ac27b303d7e321a720fc6](https://github.com/mozilla/localForage/commit/f4e0156a29969a79005ac27b303d7e321a720fc6)) diff --git a/www/lib/localforage/Gruntfile.js b/www/lib/localforage/Gruntfile.js new file mode 100644 index 00000000..7df7b00a --- /dev/null +++ b/www/lib/localforage/Gruntfile.js @@ -0,0 +1,268 @@ +/* jshint node:true */ +var path = require('path'); +var saucelabsBrowsers = require(path.resolve('test', 'saucelabs-browsers.js')); + +var sourceFiles = [ + 'Gruntfile.js', + 'src/*.js', + 'src/**/*.js', + 'test/**/test.*.js' +]; + +module.exports = exports = function(grunt) { + 'use strict'; + + var BANNER = '/*!\n' + + ' localForage -- Offline Storage, Improved\n' + + ' Version ' + grunt.file.readJSON('package.json').version + '\n' + + ' https://mozilla.github.io/localForage\n' + + ' (c) 2013-2015 Mozilla, Apache License 2.0\n' + + '*/\n'; + + var babelModuleIdProvider = function getModuleId(moduleName) { + var files = { + 'src/localforage': 'localforage', + 'src/utils/serializer': 'localforageSerializer', + 'src/drivers/indexeddb': 'asyncStorage', + 'src/drivers/localstorage': 'localStorageWrapper', + 'src/drivers/websql': 'webSQLStorage' + }; + + return files[moduleName] || moduleName.replace('src/', ''); + }; + + grunt.initConfig({ + babel: { + options: { + babelrc: false, + extends: path.resolve('.babelrc-umd'), + moduleIds: true, + getModuleId: babelModuleIdProvider + }, + dist: { + files: { + 'build/es5src/localforage.js': 'src/localforage.js', + 'build/es5src/utils/serializer.js': 'src/utils/serializer.js', + 'build/es5src/drivers/indexeddb.js': 'src/drivers/indexeddb.js', + 'build/es5src/drivers/localstorage.js': 'src/drivers/localstorage.js', + 'build/es5src/drivers/websql.js': 'src/drivers/websql.js' + } + } + }, + browserify: { + package_bundling_test: { + src: 'test/runner.browserify.js', + dest: 'test/localforage.browserify.js' + }, + main: { + files: { + 'dist/localforage.js': 'src/localforage.js' + }, + options: { + browserifyOptions: { + standalone: 'localforage' + }, + transform: ['rollupify', 'babelify'], + plugin: ['bundle-collapser/plugin'] + } + }, + no_promises: { + files: { + 'dist/localforage.nopromises.js': 'src/localforage.js' + }, + options: { + browserifyOptions: { + standalone: 'localforage' + }, + transform: ['rollupify', 'babelify'], + plugin: ['bundle-collapser/plugin'], + exclude: ['lie/polyfill'] + } + } + }, + run: { + derequire: { + exec: 'derequire ' + + '< dist/localforage.js > dist/localforage.tmp ' + + '&& ncp dist/localforage.tmp dist/localforage.js' + + '&& rimraf dist/localforage.tmp' + }, + derequire_no_promises: { + exec: 'derequire ' + + '< dist/localforage.nopromises.js > dist/localforage.nopromises.tmp ' + + '&& ncp dist/localforage.nopromises.tmp dist/localforage.nopromises.js' + + '&& rimraf dist/localforage.nopromises.tmp' + } + }, + concat: { + options: { + separator: '' + }, + localforage: { + // just to add the BANNER + // without adding an extra grunt module + files: { + 'dist/localforage.js': [ + 'dist/localforage.js' + ], + 'dist/localforage.nopromises.js': [ + 'dist/localforage.nopromises.js' + ] + }, + options: { + banner: BANNER + } + } + }, + connect: { + test: { + options: { + base: '.', + hostname: '*', + port: 9999, + middleware: function(connect) { + return [ + function(req, res, next) { + res.setHeader('Access-Control-Allow-Origin', + '*'); + res.setHeader('Access-Control-Allow-Methods', + '*'); + + return next(); + }, + connect.static(require('path').resolve('.')) + ]; + } + } + } + }, + es3_safe_recast: { + dist: { + files: [{ + src: ['dist/localforage.js'], + dest: 'dist/localforage.js' + }] + }, + nopromises: { + files: [{ + src: ['dist/localforage.nopromises.js'], + dest: 'dist/localforage.nopromises.js' + }] + } + }, + jscs: { + source: sourceFiles + }, + jshint: { + options: { + jshintrc: '.jshintrc' + }, + source: sourceFiles + }, + mocha: { + unit: { + options: { + urls: [ + 'http://localhost:9999/test/test.main.html', + 'http://localhost:9999/test/test.min.html', + 'http://localhost:9999/test/test.callwhenready.html', + 'http://localhost:9999/test/test.customdriver.html', + 'http://localhost:9999/test/test.faultydriver.html', + 'http://localhost:9999/test/test.nodriver.html', + 'http://localhost:9999/test/test.browserify.html', + 'http://localhost:9999/test/test.require.html', + 'http://localhost:9999/test/test.webpack.html' + ] + } + } + }, + 'saucelabs-mocha': { + all: { + options: { + username: process.env.SAUCE_USERNAME, + key: process.env.SAUCE_ACCESS_KEY, + urls: ['http://localhost:9999/test/test.main.html'], + tunnelTimeout: 5, + build: process.env.TRAVIS_JOB_ID, + concurrency: 3, + browsers: saucelabsBrowsers, + testname: 'localForage Tests' + } + } + }, + uglify: { + localforage: { + files: { + 'dist/localforage.min.js': ['dist/localforage.js'], + 'dist/localforage.nopromises.min.js': [ + 'dist/localforage.nopromises.js' + ] + }, + options: { + banner: BANNER + } + } + }, + watch: { + build: { + files: ['src/*.js', 'src/**/*.js'], + tasks: ['build'] + }, + /*jshint scripturl:true */ + 'mocha:unit': { + files: [ + 'dist/localforage.js', + 'test/runner.js', + 'test/test.*.*' + ], + tasks: [ + 'jshint', + 'jscs', + 'browserify:package_bundling_test', + 'webpack:package_bundling_test', + 'mocha:unit' + ] + } + }, + webpack: { + package_bundling_test: { + entry: './test/runner.webpack.js', + output: { + path: 'test/', + filename: 'localforage.webpack.js' + } + } + } + }); + + require('load-grunt-tasks')(grunt); + + grunt.registerTask('default', ['build', 'connect', 'watch']); + grunt.registerTask('build', ['browserify:main', 'browserify:no_promises', + 'run:derequire', 'run:derequire_no_promises', + 'concat', 'es3_safe_recast', 'uglify']); + grunt.registerTask('serve', ['build', 'connect:test', 'watch']); + + // These are the test tasks we run regardless of Sauce Labs credentials. + var testTasks = [ + 'build', + 'babel', + 'jshint', + 'jscs', + 'browserify:package_bundling_test', + 'webpack:package_bundling_test', + 'connect:test', + 'mocha' + ]; + grunt.registerTask('test:local', testTasks.slice()); + + // Run tests using Sauce Labs if we are on Travis or have locally + // available Sauce Labs credentials. Use `grunt test:local` to skip + // Sauce Labs tests. + // if (process.env.TRAVIS_JOB_ID || + // (process.env.SAUCE_USERNAME && process.env.SAUCE_ACCESS_KEY)) { + // testTasks.push('saucelabs-mocha'); + // } + + grunt.registerTask('test', testTasks); +}; diff --git a/www/lib/localforage/README.md b/www/lib/localforage/README.md new file mode 100644 index 00000000..e51d3bb6 --- /dev/null +++ b/www/lib/localforage/README.md @@ -0,0 +1,268 @@ +# localForage [](http://travis-ci.org/mozilla/localForage) + +localForage is a fast and simple storage library for JavaScript. localForage +improves the offline experience of your web app by using asynchronous storage +(IndexedDB or WebSQL) with a simple, `localStorage`-like API. + +localForage uses localStorage in browsers with no IndexedDB or +WebSQL support. See [the wiki for detailed compatibility info][supported browsers]. + +To use localForage, just drop a single JavaScript file into your page: + +```html +<script src="localforage.js"></script> +<script>localforage.getItem('something', myCallback);</script> +``` + +Download the [latest localForage from GitHub](https://github.com/mozilla/localForage/releases/latest), or install with +[npm](https://www.npmjs.com/): + +```bash +npm install localforage +``` + +or [bower](http://bower.io): + +```bash +bower install localforage +``` + +localForage is compatible with [browserify](http://browserify.org/). + +[supported browsers]: https://github.com/mozilla/localForage/wiki/Supported-Browsers-Platforms + +## Support + +Lost? Need help? Try the +[localForage API documentation](https://mozilla.github.io/localForage). + +If you're stuck using the library, running the tests, or want to contribute +to localForage, you can visit +[irc.freenode.net](https://freenode.net/) and head to the `#localforage` +channel to ask questions about localForage. + +The best person to ask about localForage is [**tofumatt**][tofumatt], who +is usually online from 8am-8pm GMT (London Time). + +[tofumatt]: http://tofumatt.com/ + +# How to use localForage + +## Callbacks vs Promises + +Because localForage uses async storage, it has an async API. +It's otherwise exactly the same as the +[localStorage API](https://hacks.mozilla.org/2009/06/localstorage/). + +localForage has a dual API that allows you to either use Node-style callbacks +or [Promises](https://www.promisejs.org/). If you are unsure which one is right for you, it's recommend to use Promises. + +Here's an example of the Node-style callback form: + +```js +localforage.setItem('key', 'value', function (err) { + // if err is non-null, we got an error + localforage.getItem('key', function (err, value) { + // if err is non-null, we got an error. otherwise, value is the value + }); +}); +``` + +And the Promise form: + +```js +localforage.setItem('key', 'value').then(function () { + return localforage.getItem('key'); +}).then(function (value) { + // we got our value +}).catch(function (err) { + // we got an error +}); +``` + +For more examples, please visit [the API docs](http://mozilla.github.io/localForage). + +## Storing Blobs, TypedArrays, and other JS objects + +You can store any type in localForage; you aren't limited to strings like in +localStorage. Even if localStorage is your storage backend, localForage +automatically does `JSON.parse()` and `JSON.stringify()` when getting/setting +values. + +localForage supports storing all native JS objects that can be serialized to +JSON, as well as ArrayBuffers, Blobs, and TypedArrays. Check the +[API docs][api] for a full list of types supported by localForage. + +All types are supported in every storage backend, though storage limits in +localStorage make storing many large Blobs impossible. + +[api]: https://mozilla.github.io/localForage/#setitem + +## Configuration + +You can set database information with the `config()` method. +Available options are `driver`, `name`, `storeName`, `version`, `size`, and +`description`. + +Example: +```javascript +localforage.config({ + driver : localforage.WEBSQL, // Force WebSQL; same as using setDriver() + name : 'myApp', + version : 1.0, + size : 4980736, // Size of database, in bytes. WebSQL-only for now. + storeName : 'keyvaluepairs', // Should be alphanumeric, with underscores. + description : 'some description' +}); +``` + +**Note:** you must call `config()` _before_ you interact with your data. This +means calling `config()` before using `getItem()`, `setItem()`, `removeItem()`, +`clear()`, `key()`, `keys()` or `length()`. + +## Multiple instances + +You can create multiple instances of localForage that point to different stores +using `createInstance`. All the configuration options used by +[`config`](#configuration) are supported. + +``` javascript +var store = localforage.createInstance({ + name: "nameHere" +}); + +var otherStore = localforage.createInstance({ + name: "otherName" +}); + +// Setting the key on one of these doesn't affect the other. +store.setItem("key", "value"); +otherStore.setItem("key", "value2"); +``` + +## RequireJS + +You can use localForage with [RequireJS](http://requirejs.org/): + +```javascript +define(['localforage'], function(localforage) { + // As a callback: + localforage.setItem('mykey', 'myvalue', console.log); + + // With a Promise: + localforage.setItem('mykey', 'myvalue').then(console.log); +}); +``` + +## Browserify and Webpack + +localForage 1.3+ works with both Browserify and Webpack. If you're using an +earlier version of localForage and are having issues with Browserify or +Webpack, please upgrade to 1.3.0 or above. + +If you're using localForage in your own build system (eg. browserify or +webpack) make sure you have the +[required plugins and transformers](https://github.com/mozilla/localForage/blob/master/package.json#L24) +installed (eg. `npm install --save-dev babel-plugin-system-import-transformer`). + +## TypeScript + +To import localForage in TypeScript: + +```javascript +const localForage:LocalForage = require("localforage"); +``` + +Note that the ES6 style import is not supported for our module type. Check out the following to know why: +* http://stackoverflow.com/questions/29596714/new-es6-syntax-for-importing-commonjs-amd-modules-i-e-import-foo-require +* http://www.jbrantly.com/es6-modules-with-typescript-and-webpack/ + +## Framework Support + +If you use a framework listed, there's a localForage storage driver for the +models in your framework so you can store data offline with localForage. We +have drivers for the following frameworks: + +* [AngularJS](https://github.com/ocombe/angular-localForage) +* [Backbone](https://github.com/mozilla/localForage-backbone) +* [Ember](https://github.com/genkgo/ember-localforage-adapter) + +If you have a driver you'd like listed, please +[open an issue](https://github.com/mozilla/localForage/issues/new) to have it +added to this list. + +## Custom Drivers + +You can create your own driver if you want; see the +[`defineDriver`](https://mozilla.github.io/localForage/#definedriver) API docs. + +There is a [list of custom drivers on the wiki][custom drivers]. + +[custom drivers]: https://github.com/mozilla/localForage/wiki/Custom-Drivers + +# Working on localForage + +You'll need [node/npm](http://nodejs.org/) and +[bower](http://bower.io/#installing-bower). + +To work on localForage, you should start by +[forking it](https://github.com/mozilla/localForage/fork) and installing its +dependencies. Replace `USERNAME` with your GitHub username and run the +following: + +```bash +# Install bower globally if you don't have it: +npm install -g bower + +# Replace USERNAME with your GitHub username: +git clone git@github.com:USERNAME/localForage.git +cd localForage +npm install +bower install +``` + +Omitting the bower dependencies will cause the tests to fail! + +## Running Tests + +You need PhantomJS installed to run local tests. Run `npm test` (or, +directly: `grunt test`). Your code must also pass the +[linter](http://jshint.com/). + +localForage is designed to run in the browser, so the tests explicitly require +a browser environment. Local tests are run on a headless WebKit (using +[PhantomJS](http://phantomjs.org)). + +When you submit a pull request, tests will be run against all browsers that +localForage supports on Travis CI using [Sauce Labs](https://saucelabs.com/). + +## Building the API Documentation + +We currently use a Ruby tool to build our +[API documentation](https://mozilla.github.io/localForage). You can install the Ruby dependencies with [Bundler](http://bundler.io): + +```bash +# From inside the localForage directory +bundle install +``` + +Then use `grunt` to serve the site: + +```bash +grunt site +``` + +Navigate to [localhost:4567](http://localhost:4567/) in your browser to see the +docs. + +There is an [open issue to move to a node tool for the docs](https://github.com/mozilla/localForage/issues/192). + +# License + +This program is free software; it is distributed under an +[Apache License](https://github.com/mozilla/localForage/blob/master/LICENSE). + +--- + +Copyright (c) 2013-2015 [Mozilla](https://mozilla.org) +([Contributors](https://github.com/mozilla/localForage/graphs/contributors)). diff --git a/www/lib/localforage/bower.json b/www/lib/localforage/bower.json new file mode 100644 index 00000000..777496a5 --- /dev/null +++ b/www/lib/localforage/bower.json @@ -0,0 +1,29 @@ +{ + "name": "localforage", + "main": [ + "dist/localforage.js" + ], + "ignore": [ + ".travis.yml", + "CONTRIBUTING.md", + "config.rb", + "Gemfile", + "Gemfile.lock", + "Rakefile", + "LICENSE", + "docs*", + "examples*", + "test*", + "site*" + ], + "dependencies": {}, + "devDependencies": { + "es6-promise": "~1.0.0", + "requirejs": "~2.1.10", + "mocha": "~1.18.2", + "expect": "~0.3.1", + "assert": "~0.1.0", + "modernizr": "~2.8.1" + }, + "version": "1.4.2" +} diff --git a/www/lib/localforage/component.json b/www/lib/localforage/component.json new file mode 100644 index 00000000..0dc32a2f --- /dev/null +++ b/www/lib/localforage/component.json @@ -0,0 +1,15 @@ +{ + "name": "localforage", + "version": "1.4.2", + "dependencies": { + "then/promise": "5.0.0" + }, + "scripts": [ + "build/es5src/localforage.js", + "build/es5src/utils/serializer.js", + "build/es5src/drivers/indexeddb.js", + "build/es5src/drivers/localstorage.js", + "build/es5src/drivers/websql.js" + ], + "main": "build/es5src/localforage.js" +} diff --git a/www/lib/localforage/contribute.json b/www/lib/localforage/contribute.json new file mode 100644 index 00000000..129af323 --- /dev/null +++ b/www/lib/localforage/contribute.json @@ -0,0 +1,31 @@ +{ + "name": "localforage", + "description": "Offline storage, improved. Wraps IndexedDB, WebSQL, or localStorage using a simple but powerful API.", + "repository": { + "url": "https://github.com/mozilla/localForage", + "license": "Apache 2.0", + "tests": "https://travis-ci.org/mozilla/localForage" + }, + "participate": { + "home": "https://github.com/mozilla/localForage", + "docs": "http://mozilla.github.io/localForage", + "irc": "irc://irc.mozilla.org/#apps", + "irc-contacts": [ + "tofumatt" + ] + }, + "bugs": { + "list": "https://github.com/mozilla/localForage/issues", + "report": "https://github.com/mozilla/localForage/issues/new", + "goodfirstbug": "https://github.com/mozilla/localForage/labels/help%20wanted" + + }, + "keywords": [ + "javascript", + "indexeddb", + "localstorage", + "offline", + "storage", + "websql" + ] +} diff --git a/www/lib/localforage/dist/localforage.js b/www/lib/localforage/dist/localforage.js new file mode 100644 index 00000000..48f395ae --- /dev/null +++ b/www/lib/localforage/dist/localforage.js @@ -0,0 +1,2296 @@ +/*! + localForage -- Offline Storage, Improved + Version 1.4.2 + https://mozilla.github.io/localForage + (c) 2013-2015 Mozilla, Apache License 2.0 +*/ +(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.localforage = f()}})(function(){var define,module,exports;return (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw (f.code="MODULE_NOT_FOUND", f)}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(_dereq_,module,exports){ +(function (global){ +'use strict'; +var Mutation = global.MutationObserver || global.WebKitMutationObserver; + +var scheduleDrain; + +{ + if (Mutation) { + var called = 0; + var observer = new Mutation(nextTick); + var element = global.document.createTextNode(''); + observer.observe(element, { + characterData: true + }); + scheduleDrain = function () { + element.data = (called = ++called % 2); + }; + } else if (!global.setImmediate && typeof global.MessageChannel !== 'undefined') { + var channel = new global.MessageChannel(); + channel.port1.onmessage = nextTick; + scheduleDrain = function () { + channel.port2.postMessage(0); + }; + } else if ('document' in global && 'onreadystatechange' in global.document.createElement('script')) { + scheduleDrain = function () { + + // Create a <script> element; its readystatechange event will be fired asynchronously once it is inserted + // into the document. Do so, thus queuing up the task. Remember to clean up once it's been called. + var scriptEl = global.document.createElement('script'); + scriptEl.onreadystatechange = function () { + nextTick(); + + scriptEl.onreadystatechange = null; + scriptEl.parentNode.removeChild(scriptEl); + scriptEl = null; + }; + global.document.documentElement.appendChild(scriptEl); + }; + } else { + scheduleDrain = function () { + setTimeout(nextTick, 0); + }; + } +} + +var draining; +var queue = []; +//named nextTick for less confusing stack traces +function nextTick() { + draining = true; + var i, oldQueue; + var len = queue.length; + while (len) { + oldQueue = queue; + queue = []; + i = -1; + while (++i < len) { + oldQueue[i](); + } + len = queue.length; + } + draining = false; +} + +module.exports = immediate; +function immediate(task) { + if (queue.push(task) === 1 && !draining) { + scheduleDrain(); + } +} + +}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) +},{}],2:[function(_dereq_,module,exports){ +'use strict'; +var immediate = _dereq_(1); + +/* istanbul ignore next */ +function INTERNAL() {} + +var handlers = {}; + +var REJECTED = ['REJECTED']; +var FULFILLED = ['FULFILLED']; +var PENDING = ['PENDING']; + +module.exports = exports = Promise; + +function Promise(resolver) { + if (typeof resolver !== 'function') { + throw new TypeError('resolver must be a function'); + } + this.state = PENDING; + this.queue = []; + this.outcome = void 0; + if (resolver !== INTERNAL) { + safelyResolveThenable(this, resolver); + } +} + +Promise.prototype["catch"] = function (onRejected) { + return this.then(null, onRejected); +}; +Promise.prototype.then = function (onFulfilled, onRejected) { + if (typeof onFulfilled !== 'function' && this.state === FULFILLED || + typeof onRejected !== 'function' && this.state === REJECTED) { + return this; + } + var promise = new this.constructor(INTERNAL); + if (this.state !== PENDING) { + var resolver = this.state === FULFILLED ? onFulfilled : onRejected; + unwrap(promise, resolver, this.outcome); + } else { + this.queue.push(new QueueItem(promise, onFulfilled, onRejected)); + } + + return promise; +}; +function QueueItem(promise, onFulfilled, onRejected) { + this.promise = promise; + if (typeof onFulfilled === 'function') { + this.onFulfilled = onFulfilled; + this.callFulfilled = this.otherCallFulfilled; + } + if (typeof onRejected === 'function') { + this.onRejected = onRejected; + this.callRejected = this.otherCallRejected; + } +} +QueueItem.prototype.callFulfilled = function (value) { + handlers.resolve(this.promise, value); +}; +QueueItem.prototype.otherCallFulfilled = function (value) { + unwrap(this.promise, this.onFulfilled, value); +}; +QueueItem.prototype.callRejected = function (value) { + handlers.reject(this.promise, value); +}; +QueueItem.prototype.otherCallRejected = function (value) { + unwrap(this.promise, this.onRejected, value); +}; + +function unwrap(promise, func, value) { + immediate(function () { + var returnValue; + try { + returnValue = func(value); + } catch (e) { + return handlers.reject(promise, e); + } + if (returnValue === promise) { + handlers.reject(promise, new TypeError('Cannot resolve promise with itself')); + } else { + handlers.resolve(promise, returnValue); + } + }); +} + +handlers.resolve = function (self, value) { + var result = tryCatch(getThen, value); + if (result.status === 'error') { + return handlers.reject(self, result.value); + } + var thenable = result.value; + + if (thenable) { + safelyResolveThenable(self, thenable); + } else { + self.state = FULFILLED; + self.outcome = value; + var i = -1; + var len = self.queue.length; + while (++i < len) { + self.queue[i].callFulfilled(value); + } + } + return self; +}; +handlers.reject = function (self, error) { + self.state = REJECTED; + self.outcome = error; + var i = -1; + var len = self.queue.length; + while (++i < len) { + self.queue[i].callRejected(error); + } + return self; +}; + +function getThen(obj) { + // Make sure we only access the accessor once as required by the spec + var then = obj && obj.then; + if (obj && typeof obj === 'object' && typeof then === 'function') { + return function appyThen() { + then.apply(obj, arguments); + }; + } +} + +function safelyResolveThenable(self, thenable) { + // Either fulfill, reject or reject with error + var called = false; + function onError(value) { + if (called) { + return; + } + called = true; + handlers.reject(self, value); + } + + function onSuccess(value) { + if (called) { + return; + } + called = true; + handlers.resolve(self, value); + } + + function tryToUnwrap() { + thenable(onSuccess, onError); + } + + var result = tryCatch(tryToUnwrap); + if (result.status === 'error') { + onError(result.value); + } +} + +function tryCatch(func, value) { + var out = {}; + try { + out.value = func(value); + out.status = 'success'; + } catch (e) { + out.status = 'error'; + out.value = e; + } + return out; +} + +exports.resolve = resolve; +function resolve(value) { + if (value instanceof this) { + return value; + } + return handlers.resolve(new this(INTERNAL), value); +} + +exports.reject = reject; +function reject(reason) { + var promise = new this(INTERNAL); + return handlers.reject(promise, reason); +} + +exports.all = all; +function all(iterable) { + var self = this; + if (Object.prototype.toString.call(iterable) !== '[object Array]') { + return this.reject(new TypeError('must be an array')); + } + + var len = iterable.length; + var called = false; + if (!len) { + return this.resolve([]); + } + + var values = new Array(len); + var resolved = 0; + var i = -1; + var promise = new this(INTERNAL); + + while (++i < len) { + allResolver(iterable[i], i); + } + return promise; + function allResolver(value, i) { + self.resolve(value).then(resolveFromAll, function (error) { + if (!called) { + called = true; + handlers.reject(promise, error); + } + }); + function resolveFromAll(outValue) { + values[i] = outValue; + if (++resolved === len && !called) { + called = true; + handlers.resolve(promise, values); + } + } + } +} + +exports.race = race; +function race(iterable) { + var self = this; + if (Object.prototype.toString.call(iterable) !== '[object Array]') { + return this.reject(new TypeError('must be an array')); + } + + var len = iterable.length; + var called = false; + if (!len) { + return this.resolve([]); + } + + var i = -1; + var promise = new this(INTERNAL); + + while (++i < len) { + resolver(iterable[i]); + } + return promise; + function resolver(value) { + self.resolve(value).then(function (response) { + if (!called) { + called = true; + handlers.resolve(promise, response); + } + }, function (error) { + if (!called) { + called = true; + handlers.reject(promise, error); + } + }); + } +} + +},{"1":1}],3:[function(_dereq_,module,exports){ +(function (global){ +'use strict'; +if (typeof global.Promise !== 'function') { + global.Promise = _dereq_(2); +} + +}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) +},{"2":2}],4:[function(_dereq_,module,exports){ +'use strict'; + +var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol ? "symbol" : typeof obj; }; + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function getIDB() { + /* global indexedDB,webkitIndexedDB,mozIndexedDB,OIndexedDB,msIndexedDB */ + if (typeof indexedDB !== 'undefined') { + return indexedDB; + } + if (typeof webkitIndexedDB !== 'undefined') { + return webkitIndexedDB; + } + if (typeof mozIndexedDB !== 'undefined') { + return mozIndexedDB; + } + if (typeof OIndexedDB !== 'undefined') { + return OIndexedDB; + } + if (typeof msIndexedDB !== 'undefined') { + return msIndexedDB; + } +} + +var idb = getIDB(); + +function isIndexedDBValid() { + try { + // Initialize IndexedDB; fall back to vendor-prefixed versions + // if needed. + if (!idb) { + return false; + } + // We mimic PouchDB here; just UA test for Safari (which, as of + // iOS 8/Yosemite, doesn't properly support IndexedDB). + // IndexedDB support is broken and different from Blink's. + // This is faster than the test case (and it's sync), so we just + // do this. *SIGH* + // http://bl.ocks.org/nolanlawson/raw/c83e9039edf2278047e9/ + // + // We test for openDatabase because IE Mobile identifies itself + // as Safari. Oh the lulz... + if (typeof openDatabase !== 'undefined' && typeof navigator !== 'undefined' && navigator.userAgent && /Safari/.test(navigator.userAgent) && !/Chrome/.test(navigator.userAgent)) { + return false; + } + + return idb && typeof idb.open === 'function' && + // Some Samsung/HTC Android 4.0-4.3 devices + // have older IndexedDB specs; if this isn't available + // their IndexedDB is too old for us to use. + // (Replaces the onupgradeneeded test.) + typeof IDBKeyRange !== 'undefined'; + } catch (e) { + return false; + } +} + +function isWebSQLValid() { + return typeof openDatabase === 'function'; +} + +function isLocalStorageValid() { + try { + return typeof localStorage !== 'undefined' && 'setItem' in localStorage && localStorage.setItem; + } catch (e) { + return false; + } +} + +// Abstracts constructing a Blob object, so it also works in older +// browsers that don't support the native Blob constructor. (i.e. +// old QtWebKit versions, at least). +// Abstracts constructing a Blob object, so it also works in older +// browsers that don't support the native Blob constructor. (i.e. +// old QtWebKit versions, at least). +function createBlob(parts, properties) { + /* global BlobBuilder,MSBlobBuilder,MozBlobBuilder,WebKitBlobBuilder */ + parts = parts || []; + properties = properties || {}; + try { + return new Blob(parts, properties); + } catch (e) { + if (e.name !== 'TypeError') { + throw e; + } + var Builder = typeof BlobBuilder !== 'undefined' ? BlobBuilder : typeof MSBlobBuilder !== 'undefined' ? MSBlobBuilder : typeof MozBlobBuilder !== 'undefined' ? MozBlobBuilder : WebKitBlobBuilder; + var builder = new Builder(); + for (var i = 0; i < parts.length; i += 1) { + builder.append(parts[i]); + } + return builder.getBlob(properties.type); + } +} + +// This is CommonJS because lie is an external dependency, so Rollup +// can just ignore it. +if (typeof Promise === 'undefined' && typeof _dereq_ !== 'undefined') { + _dereq_(3); +} +var Promise$1 = Promise; + +function executeCallback(promise, callback) { + if (callback) { + promise.then(function (result) { + callback(null, result); + }, function (error) { + callback(error); + }); + } +} + +// Some code originally from async_storage.js in +// [Gaia](https://github.com/mozilla-b2g/gaia). + +var DETECT_BLOB_SUPPORT_STORE = 'local-forage-detect-blob-support'; +var supportsBlobs; +var dbContexts; + +// Transform a binary string to an array buffer, because otherwise +// weird stuff happens when you try to work with the binary string directly. +// It is known. +// From http://stackoverflow.com/questions/14967647/ (continues on next line) +// encode-decode-image-with-base64-breaks-image (2013-04-21) +function _binStringToArrayBuffer(bin) { + var length = bin.length; + var buf = new ArrayBuffer(length); + var arr = new Uint8Array(buf); + for (var i = 0; i < length; i++) { + arr[i] = bin.charCodeAt(i); + } + return buf; +} + +// +// Blobs are not supported in all versions of IndexedDB, notably +// Chrome <37 and Android <5. In those versions, storing a blob will throw. +// +// Various other blob bugs exist in Chrome v37-42 (inclusive). +// Detecting them is expensive and confusing to users, and Chrome 37-42 +// is at very low usage worldwide, so we do a hacky userAgent check instead. +// +// content-type bug: https://code.google.com/p/chromium/issues/detail?id=408120 +// 404 bug: https://code.google.com/p/chromium/issues/detail?id=447916 +// FileReader bug: https://code.google.com/p/chromium/issues/detail?id=447836 +// +// Code borrowed from PouchDB. See: +// https://github.com/pouchdb/pouchdb/blob/9c25a23/src/adapters/idb/blobSupport.js +// +function _checkBlobSupportWithoutCaching(txn) { + return new Promise$1(function (resolve) { + var blob = createBlob(['']); + txn.objectStore(DETECT_BLOB_SUPPORT_STORE).put(blob, 'key'); + + txn.onabort = function (e) { + // If the transaction aborts now its due to not being able to + // write to the database, likely due to the disk being full + e.preventDefault(); + e.stopPropagation(); + resolve(false); + }; + + txn.oncomplete = function () { + var matchedChrome = navigator.userAgent.match(/Chrome\/(\d+)/); + var matchedEdge = navigator.userAgent.match(/Edge\//); + // MS Edge pretends to be Chrome 42: + // https://msdn.microsoft.com/en-us/library/hh869301%28v=vs.85%29.aspx + resolve(matchedEdge || !matchedChrome || parseInt(matchedChrome[1], 10) >= 43); + }; + })["catch"](function () { + return false; // error, so assume unsupported + }); +} + +function _checkBlobSupport(idb) { + if (typeof supportsBlobs === 'boolean') { + return Promise$1.resolve(supportsBlobs); + } + return _checkBlobSupportWithoutCaching(idb).then(function (value) { + supportsBlobs = value; + return supportsBlobs; + }); +} + +function _deferReadiness(dbInfo) { + var dbContext = dbContexts[dbInfo.name]; + + // Create a deferred object representing the current database operation. + var deferredOperation = {}; + + deferredOperation.promise = new Promise$1(function (resolve) { + deferredOperation.resolve = resolve; + }); + + // Enqueue the deferred operation. + dbContext.deferredOperations.push(deferredOperation); + + // Chain its promise to the database readiness. + if (!dbContext.dbReady) { + dbContext.dbReady = deferredOperation.promise; + } else { + dbContext.dbReady = dbContext.dbReady.then(function () { + return deferredOperation.promise; + }); + } +} + +function _advanceReadiness(dbInfo) { + var dbContext = dbContexts[dbInfo.name]; + + // Dequeue a deferred operation. + var deferredOperation = dbContext.deferredOperations.pop(); + + // Resolve its promise (which is part of the database readiness + // chain of promises). + if (deferredOperation) { + deferredOperation.resolve(); + } +} + +function _getConnection(dbInfo, upgradeNeeded) { + return new Promise$1(function (resolve, reject) { + + if (dbInfo.db) { + if (upgradeNeeded) { + _deferReadiness(dbInfo); + dbInfo.db.close(); + } else { + return resolve(dbInfo.db); + } + } + + var dbArgs = [dbInfo.name]; + + if (upgradeNeeded) { + dbArgs.push(dbInfo.version); + } + + var openreq = idb.open.apply(idb, dbArgs); + + if (upgradeNeeded) { + openreq.onupgradeneeded = function (e) { + var db = openreq.result; + try { + db.createObjectStore(dbInfo.storeName); + if (e.oldVersion <= 1) { + // Added when support for blob shims was added + db.createObjectStore(DETECT_BLOB_SUPPORT_STORE); + } + } catch (ex) { + if (ex.name === 'ConstraintError') { + console.warn('The database "' + dbInfo.name + '"' + ' has been upgraded from version ' + e.oldVersion + ' to version ' + e.newVersion + ', but the storage "' + dbInfo.storeName + '" already exists.'); + } else { + throw ex; + } + } + }; + } + + openreq.onerror = function () { + reject(openreq.error); + }; + + openreq.onsuccess = function () { + resolve(openreq.result); + _advanceReadiness(dbInfo); + }; + }); +} + +function _getOriginalConnection(dbInfo) { + return _getConnection(dbInfo, false); +} + +function _getUpgradedConnection(dbInfo) { + return _getConnection(dbInfo, true); +} + +function _isUpgradeNeeded(dbInfo, defaultVersion) { + if (!dbInfo.db) { + return true; + } + + var isNewStore = !dbInfo.db.objectStoreNames.contains(dbInfo.storeName); + var isDowngrade = dbInfo.version < dbInfo.db.version; + var isUpgrade = dbInfo.version > dbInfo.db.version; + + if (isDowngrade) { + // If the version is not the default one + // then warn for impossible downgrade. + if (dbInfo.version !== defaultVersion) { + console.warn('The database "' + dbInfo.name + '"' + ' can\'t be downgraded from version ' + dbInfo.db.version + ' to version ' + dbInfo.version + '.'); + } + // Align the versions to prevent errors. + dbInfo.version = dbInfo.db.version; + } + + if (isUpgrade || isNewStore) { + // If the store is new then increment the version (if needed). + // This will trigger an "upgradeneeded" event which is required + // for creating a store. + if (isNewStore) { + var incVersion = dbInfo.db.version + 1; + if (incVersion > dbInfo.version) { + dbInfo.version = incVersion; + } + } + + return true; + } + + return false; +} + +// encode a blob for indexeddb engines that don't support blobs +function _encodeBlob(blob) { + return new Promise$1(function (resolve, reject) { + var reader = new FileReader(); + reader.onerror = reject; + reader.onloadend = function (e) { + var base64 = btoa(e.target.result || ''); + resolve({ + __local_forage_encoded_blob: true, + data: base64, + type: blob.type + }); + }; + reader.readAsBinaryString(blob); + }); +} + +// decode an encoded blob +function _decodeBlob(encodedBlob) { + var arrayBuff = _binStringToArrayBuffer(atob(encodedBlob.data)); + return createBlob([arrayBuff], { type: encodedBlob.type }); +} + +// is this one of our fancy encoded blobs? +function _isEncodedBlob(value) { + return value && value.__local_forage_encoded_blob; +} + +// Specialize the default `ready()` function by making it dependent +// on the current database operations. Thus, the driver will be actually +// ready when it's been initialized (default) *and* there are no pending +// operations on the database (initiated by some other instances). +function _fullyReady(callback) { + var self = this; + + var promise = self._initReady().then(function () { + var dbContext = dbContexts[self._dbInfo.name]; + + if (dbContext && dbContext.dbReady) { + return dbContext.dbReady; + } + }); + + promise.then(callback, callback); + return promise; +} + +// Open the IndexedDB database (automatically creates one if one didn't +// previously exist), using any options set in the config. +function _initStorage(options) { + var self = this; + var dbInfo = { + db: null + }; + + if (options) { + for (var i in options) { + dbInfo[i] = options[i]; + } + } + + // Initialize a singleton container for all running localForages. + if (!dbContexts) { + dbContexts = {}; + } + + // Get the current context of the database; + var dbContext = dbContexts[dbInfo.name]; + + // ...or create a new context. + if (!dbContext) { + dbContext = { + // Running localForages sharing a database. + forages: [], + // Shared database. + db: null, + // Database readiness (promise). + dbReady: null, + // Deferred operations on the database. + deferredOperations: [] + }; + // Register the new context in the global container. + dbContexts[dbInfo.name] = dbContext; + } + + // Register itself as a running localForage in the current context. + dbContext.forages.push(self); + + // Replace the default `ready()` function with the specialized one. + if (!self._initReady) { + self._initReady = self.ready; + self.ready = _fullyReady; + } + + // Create an array of initialization states of the related localForages. + var initPromises = []; + + function ignoreErrors() { + // Don't handle errors here, + // just makes sure related localForages aren't pending. + return Promise$1.resolve(); + } + + for (var j = 0; j < dbContext.forages.length; j++) { + var forage = dbContext.forages[j]; + if (forage !== self) { + // Don't wait for itself... + initPromises.push(forage._initReady()["catch"](ignoreErrors)); + } + } + + // Take a snapshot of the related localForages. + var forages = dbContext.forages.slice(0); + + // Initialize the connection process only when + // all the related localForages aren't pending. + return Promise$1.all(initPromises).then(function () { + dbInfo.db = dbContext.db; + // Get the connection or open a new one without upgrade. + return _getOriginalConnection(dbInfo); + }).then(function (db) { + dbInfo.db = db; + if (_isUpgradeNeeded(dbInfo, self._defaultConfig.version)) { + // Reopen the database for upgrading. + return _getUpgradedConnection(dbInfo); + } + return db; + }).then(function (db) { + dbInfo.db = dbContext.db = db; + self._dbInfo = dbInfo; + // Share the final connection amongst related localForages. + for (var k = 0; k < forages.length; k++) { + var forage = forages[k]; + if (forage !== self) { + // Self is already up-to-date. + forage._dbInfo.db = dbInfo.db; + forage._dbInfo.version = dbInfo.version; + } + } + }); +} + +function getItem(key, callback) { + var self = this; + + // Cast the key to a string, as that's all we can set as a key. + if (typeof key !== 'string') { + console.warn(key + ' used as a key, but it is not a string.'); + key = String(key); + } + + var promise = new Promise$1(function (resolve, reject) { + self.ready().then(function () { + var dbInfo = self._dbInfo; + var store = dbInfo.db.transaction(dbInfo.storeName, 'readonly').objectStore(dbInfo.storeName); + var req = store.get(key); + + req.onsuccess = function () { + var value = req.result; + if (value === undefined) { + value = null; + } + if (_isEncodedBlob(value)) { + value = _decodeBlob(value); + } + resolve(value); + }; + + req.onerror = function () { + reject(req.error); + }; + })["catch"](reject); + }); + + executeCallback(promise, callback); + return promise; +} + +// Iterate over all items stored in database. +function iterate(iterator, callback) { + var self = this; + + var promise = new Promise$1(function (resolve, reject) { + self.ready().then(function () { + var dbInfo = self._dbInfo; + var store = dbInfo.db.transaction(dbInfo.storeName, 'readonly').objectStore(dbInfo.storeName); + + var req = store.openCursor(); + var iterationNumber = 1; + + req.onsuccess = function () { + var cursor = req.result; + + if (cursor) { + var value = cursor.value; + if (_isEncodedBlob(value)) { + value = _decodeBlob(value); + } + var result = iterator(value, cursor.key, iterationNumber++); + + if (result !== void 0) { + resolve(result); + } else { + cursor["continue"](); + } + } else { + resolve(); + } + }; + + req.onerror = function () { + reject(req.error); + }; + })["catch"](reject); + }); + + executeCallback(promise, callback); + + return promise; +} + +function setItem(key, value, callback) { + var self = this; + + // Cast the key to a string, as that's all we can set as a key. + if (typeof key !== 'string') { + console.warn(key + ' used as a key, but it is not a string.'); + key = String(key); + } + + var promise = new Promise$1(function (resolve, reject) { + var dbInfo; + self.ready().then(function () { + dbInfo = self._dbInfo; + if (value instanceof Blob) { + return _checkBlobSupport(dbInfo.db).then(function (blobSupport) { + if (blobSupport) { + return value; + } + return _encodeBlob(value); + }); + } + return value; + }).then(function (value) { + var transaction = dbInfo.db.transaction(dbInfo.storeName, 'readwrite'); + var store = transaction.objectStore(dbInfo.storeName); + + // The reason we don't _save_ null is because IE 10 does + // not support saving the `null` type in IndexedDB. How + // ironic, given the bug below! + // See: https://github.com/mozilla/localForage/issues/161 + if (value === null) { + value = undefined; + } + + transaction.oncomplete = function () { + // Cast to undefined so the value passed to + // callback/promise is the same as what one would get out + // of `getItem()` later. This leads to some weirdness + // (setItem('foo', undefined) will return `null`), but + // it's not my fault localStorage is our baseline and that + // it's weird. + if (value === undefined) { + value = null; + } + + resolve(value); + }; + transaction.onabort = transaction.onerror = function () { + var err = req.error ? req.error : req.transaction.error; + reject(err); + }; + + var req = store.put(value, key); + })["catch"](reject); + }); + + executeCallback(promise, callback); + return promise; +} + +function removeItem(key, callback) { + var self = this; + + // Cast the key to a string, as that's all we can set as a key. + if (typeof key !== 'string') { + console.warn(key + ' used as a key, but it is not a string.'); + key = String(key); + } + + var promise = new Promise$1(function (resolve, reject) { + self.ready().then(function () { + var dbInfo = self._dbInfo; + var transaction = dbInfo.db.transaction(dbInfo.storeName, 'readwrite'); + var store = transaction.objectStore(dbInfo.storeName); + + // We use a Grunt task to make this safe for IE and some + // versions of Android (including those used by Cordova). + // Normally IE won't like `.delete()` and will insist on + // using `['delete']()`, but we have a build step that + // fixes this for us now. + var req = store["delete"](key); + transaction.oncomplete = function () { + resolve(); + }; + + transaction.onerror = function () { + reject(req.error); + }; + + // The request will be also be aborted if we've exceeded our storage + // space. + transaction.onabort = function () { + var err = req.error ? req.error : req.transaction.error; + reject(err); + }; + })["catch"](reject); + }); + + executeCallback(promise, callback); + return promise; +} + +function clear(callback) { + var self = this; + + var promise = new Promise$1(function (resolve, reject) { + self.ready().then(function () { + var dbInfo = self._dbInfo; + var transaction = dbInfo.db.transaction(dbInfo.storeName, 'readwrite'); + var store = transaction.objectStore(dbInfo.storeName); + var req = store.clear(); + + transaction.oncomplete = function () { + resolve(); + }; + + transaction.onabort = transaction.onerror = function () { + var err = req.error ? req.error : req.transaction.error; + reject(err); + }; + })["catch"](reject); + }); + + executeCallback(promise, callback); + return promise; +} + +function length(callback) { + var self = this; + + var promise = new Promise$1(function (resolve, reject) { + self.ready().then(function () { + var dbInfo = self._dbInfo; + var store = dbInfo.db.transaction(dbInfo.storeName, 'readonly').objectStore(dbInfo.storeName); + var req = store.count(); + + req.onsuccess = function () { + resolve(req.result); + }; + + req.onerror = function () { + reject(req.error); + }; + })["catch"](reject); + }); + + executeCallback(promise, callback); + return promise; +} + +function key(n, callback) { + var self = this; + + var promise = new Promise$1(function (resolve, reject) { + if (n < 0) { + resolve(null); + + return; + } + + self.ready().then(function () { + var dbInfo = self._dbInfo; + var store = dbInfo.db.transaction(dbInfo.storeName, 'readonly').objectStore(dbInfo.storeName); + + var advanced = false; + var req = store.openCursor(); + req.onsuccess = function () { + var cursor = req.result; + if (!cursor) { + // this means there weren't enough keys + resolve(null); + + return; + } + + if (n === 0) { + // We have the first key, return it if that's what they + // wanted. + resolve(cursor.key); + } else { + if (!advanced) { + // Otherwise, ask the cursor to skip ahead n + // records. + advanced = true; + cursor.advance(n); + } else { + // When we get here, we've got the nth key. + resolve(cursor.key); + } + } + }; + + req.onerror = function () { + reject(req.error); + }; + })["catch"](reject); + }); + + executeCallback(promise, callback); + return promise; +} + +function keys(callback) { + var self = this; + + var promise = new Promise$1(function (resolve, reject) { + self.ready().then(function () { + var dbInfo = self._dbInfo; + var store = dbInfo.db.transaction(dbInfo.storeName, 'readonly').objectStore(dbInfo.storeName); + + var req = store.openCursor(); + var keys = []; + + req.onsuccess = function () { + var cursor = req.result; + + if (!cursor) { + resolve(keys); + return; + } + + keys.push(cursor.key); + cursor["continue"](); + }; + + req.onerror = function () { + reject(req.error); + }; + })["catch"](reject); + }); + + executeCallback(promise, callback); + return promise; +} + +var asyncStorage = { + _driver: 'asyncStorage', + _initStorage: _initStorage, + iterate: iterate, + getItem: getItem, + setItem: setItem, + removeItem: removeItem, + clear: clear, + length: length, + key: key, + keys: keys +}; + +// Sadly, the best way to save binary data in WebSQL/localStorage is serializing +// it to Base64, so this is how we store it to prevent very strange errors with less +// verbose ways of binary <-> string data storage. +var BASE_CHARS = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'; + +var BLOB_TYPE_PREFIX = '~~local_forage_type~'; +var BLOB_TYPE_PREFIX_REGEX = /^~~local_forage_type~([^~]+)~/; + +var SERIALIZED_MARKER = '__lfsc__:'; +var SERIALIZED_MARKER_LENGTH = SERIALIZED_MARKER.length; + +// OMG the serializations! +var TYPE_ARRAYBUFFER = 'arbf'; +var TYPE_BLOB = 'blob'; +var TYPE_INT8ARRAY = 'si08'; +var TYPE_UINT8ARRAY = 'ui08'; +var TYPE_UINT8CLAMPEDARRAY = 'uic8'; +var TYPE_INT16ARRAY = 'si16'; +var TYPE_INT32ARRAY = 'si32'; +var TYPE_UINT16ARRAY = 'ur16'; +var TYPE_UINT32ARRAY = 'ui32'; +var TYPE_FLOAT32ARRAY = 'fl32'; +var TYPE_FLOAT64ARRAY = 'fl64'; +var TYPE_SERIALIZED_MARKER_LENGTH = SERIALIZED_MARKER_LENGTH + TYPE_ARRAYBUFFER.length; + +function stringToBuffer(serializedString) { + // Fill the string into a ArrayBuffer. + var bufferLength = serializedString.length * 0.75; + var len = serializedString.length; + var i; + var p = 0; + var encoded1, encoded2, encoded3, encoded4; + + if (serializedString[serializedString.length - 1] === '=') { + bufferLength--; + if (serializedString[serializedString.length - 2] === '=') { + bufferLength--; + } + } + + var buffer = new ArrayBuffer(bufferLength); + var bytes = new Uint8Array(buffer); + + for (i = 0; i < len; i += 4) { + encoded1 = BASE_CHARS.indexOf(serializedString[i]); + encoded2 = BASE_CHARS.indexOf(serializedString[i + 1]); + encoded3 = BASE_CHARS.indexOf(serializedString[i + 2]); + encoded4 = BASE_CHARS.indexOf(serializedString[i + 3]); + + /*jslint bitwise: true */ + bytes[p++] = encoded1 << 2 | encoded2 >> 4; + bytes[p++] = (encoded2 & 15) << 4 | encoded3 >> 2; + bytes[p++] = (encoded3 & 3) << 6 | encoded4 & 63; + } + return buffer; +} + +// Converts a buffer to a string to store, serialized, in the backend +// storage library. +function bufferToString(buffer) { + // base64-arraybuffer + var bytes = new Uint8Array(buffer); + var base64String = ''; + var i; + + for (i = 0; i < bytes.length; i += 3) { + /*jslint bitwise: true */ + base64String += BASE_CHARS[bytes[i] >> 2]; + base64String += BASE_CHARS[(bytes[i] & 3) << 4 | bytes[i + 1] >> 4]; + base64String += BASE_CHARS[(bytes[i + 1] & 15) << 2 | bytes[i + 2] >> 6]; + base64String += BASE_CHARS[bytes[i + 2] & 63]; + } + + if (bytes.length % 3 === 2) { + base64String = base64String.substring(0, base64String.length - 1) + '='; + } else if (bytes.length % 3 === 1) { + base64String = base64String.substring(0, base64String.length - 2) + '=='; + } + + return base64String; +} + +// Serialize a value, afterwards executing a callback (which usually +// instructs the `setItem()` callback/promise to be executed). This is how +// we store binary data with localStorage. +function serialize(value, callback) { + var valueString = ''; + if (value) { + valueString = value.toString(); + } + + // Cannot use `value instanceof ArrayBuffer` or such here, as these + // checks fail when running the tests using casper.js... + // + // TODO: See why those tests fail and use a better solution. + if (value && (value.toString() === '[object ArrayBuffer]' || value.buffer && value.buffer.toString() === '[object ArrayBuffer]')) { + // Convert binary arrays to a string and prefix the string with + // a special marker. + var buffer; + var marker = SERIALIZED_MARKER; + + if (value instanceof ArrayBuffer) { + buffer = value; + marker += TYPE_ARRAYBUFFER; + } else { + buffer = value.buffer; + + if (valueString === '[object Int8Array]') { + marker += TYPE_INT8ARRAY; + } else if (valueString === '[object Uint8Array]') { + marker += TYPE_UINT8ARRAY; + } else if (valueString === '[object Uint8ClampedArray]') { + marker += TYPE_UINT8CLAMPEDARRAY; + } else if (valueString === '[object Int16Array]') { + marker += TYPE_INT16ARRAY; + } else if (valueString === '[object Uint16Array]') { + marker += TYPE_UINT16ARRAY; + } else if (valueString === '[object Int32Array]') { + marker += TYPE_INT32ARRAY; + } else if (valueString === '[object Uint32Array]') { + marker += TYPE_UINT32ARRAY; + } else if (valueString === '[object Float32Array]') { + marker += TYPE_FLOAT32ARRAY; + } else if (valueString === '[object Float64Array]') { + marker += TYPE_FLOAT64ARRAY; + } else { + callback(new Error('Failed to get type for BinaryArray')); + } + } + + callback(marker + bufferToString(buffer)); + } else if (valueString === '[object Blob]') { + // Conver the blob to a binaryArray and then to a string. + var fileReader = new FileReader(); + + fileReader.onload = function () { + // Backwards-compatible prefix for the blob type. + var str = BLOB_TYPE_PREFIX + value.type + '~' + bufferToString(this.result); + + callback(SERIALIZED_MARKER + TYPE_BLOB + str); + }; + + fileReader.readAsArrayBuffer(value); + } else { + try { + callback(JSON.stringify(value)); + } catch (e) { + console.error("Couldn't convert value into a JSON string: ", value); + + callback(null, e); + } + } +} + +// Deserialize data we've inserted into a value column/field. We place +// special markers into our strings to mark them as encoded; this isn't +// as nice as a meta field, but it's the only sane thing we can do whilst +// keeping localStorage support intact. +// +// Oftentimes this will just deserialize JSON content, but if we have a +// special marker (SERIALIZED_MARKER, defined above), we will extract +// some kind of arraybuffer/binary data/typed array out of the string. +function deserialize(value) { + // If we haven't marked this string as being specially serialized (i.e. + // something other than serialized JSON), we can just return it and be + // done with it. + if (value.substring(0, SERIALIZED_MARKER_LENGTH) !== SERIALIZED_MARKER) { + return JSON.parse(value); + } + + // The following code deals with deserializing some kind of Blob or + // TypedArray. First we separate out the type of data we're dealing + // with from the data itself. + var serializedString = value.substring(TYPE_SERIALIZED_MARKER_LENGTH); + var type = value.substring(SERIALIZED_MARKER_LENGTH, TYPE_SERIALIZED_MARKER_LENGTH); + + var blobType; + // Backwards-compatible blob type serialization strategy. + // DBs created with older versions of localForage will simply not have the blob type. + if (type === TYPE_BLOB && BLOB_TYPE_PREFIX_REGEX.test(serializedString)) { + var matcher = serializedString.match(BLOB_TYPE_PREFIX_REGEX); + blobType = matcher[1]; + serializedString = serializedString.substring(matcher[0].length); + } + var buffer = stringToBuffer(serializedString); + + // Return the right type based on the code/type set during + // serialization. + switch (type) { + case TYPE_ARRAYBUFFER: + return buffer; + case TYPE_BLOB: + return createBlob([buffer], { type: blobType }); + case TYPE_INT8ARRAY: + return new Int8Array(buffer); + case TYPE_UINT8ARRAY: + return new Uint8Array(buffer); + case TYPE_UINT8CLAMPEDARRAY: + return new Uint8ClampedArray(buffer); + case TYPE_INT16ARRAY: + return new Int16Array(buffer); + case TYPE_UINT16ARRAY: + return new Uint16Array(buffer); + case TYPE_INT32ARRAY: + return new Int32Array(buffer); + case TYPE_UINT32ARRAY: + return new Uint32Array(buffer); + case TYPE_FLOAT32ARRAY: + return new Float32Array(buffer); + case TYPE_FLOAT64ARRAY: + return new Float64Array(buffer); + default: + throw new Error('Unkown type: ' + type); + } +} + +var localforageSerializer = { + serialize: serialize, + deserialize: deserialize, + stringToBuffer: stringToBuffer, + bufferToString: bufferToString +}; + +/* + * Includes code from: + * + * base64-arraybuffer + * https://github.com/niklasvh/base64-arraybuffer + * + * Copyright (c) 2012 Niklas von Hertzen + * Licensed under the MIT license. + */ +// Open the WebSQL database (automatically creates one if one didn't +// previously exist), using any options set in the config. +function _initStorage$1(options) { + var self = this; + var dbInfo = { + db: null + }; + + if (options) { + for (var i in options) { + dbInfo[i] = typeof options[i] !== 'string' ? options[i].toString() : options[i]; + } + } + + var dbInfoPromise = new Promise$1(function (resolve, reject) { + // Open the database; the openDatabase API will automatically + // create it for us if it doesn't exist. + try { + dbInfo.db = openDatabase(dbInfo.name, String(dbInfo.version), dbInfo.description, dbInfo.size); + } catch (e) { + return reject(e); + } + + // Create our key/value table if it doesn't exist. + dbInfo.db.transaction(function (t) { + t.executeSql('CREATE TABLE IF NOT EXISTS ' + dbInfo.storeName + ' (id INTEGER PRIMARY KEY, key unique, value)', [], function () { + self._dbInfo = dbInfo; + resolve(); + }, function (t, error) { + reject(error); + }); + }); + }); + + dbInfo.serializer = localforageSerializer; + return dbInfoPromise; +} + +function getItem$1(key, callback) { + var self = this; + + // Cast the key to a string, as that's all we can set as a key. + if (typeof key !== 'string') { + console.warn(key + ' used as a key, but it is not a string.'); + key = String(key); + } + + var promise = new Promise$1(function (resolve, reject) { + self.ready().then(function () { + var dbInfo = self._dbInfo; + dbInfo.db.transaction(function (t) { + t.executeSql('SELECT * FROM ' + dbInfo.storeName + ' WHERE key = ? LIMIT 1', [key], function (t, results) { + var result = results.rows.length ? results.rows.item(0).value : null; + + // Check to see if this is serialized content we need to + // unpack. + if (result) { + result = dbInfo.serializer.deserialize(result); + } + + resolve(result); + }, function (t, error) { + + reject(error); + }); + }); + })["catch"](reject); + }); + + executeCallback(promise, callback); + return promise; +} + +function iterate$1(iterator, callback) { + var self = this; + + var promise = new Promise$1(function (resolve, reject) { + self.ready().then(function () { + var dbInfo = self._dbInfo; + + dbInfo.db.transaction(function (t) { + t.executeSql('SELECT * FROM ' + dbInfo.storeName, [], function (t, results) { + var rows = results.rows; + var length = rows.length; + + for (var i = 0; i < length; i++) { + var item = rows.item(i); + var result = item.value; + + // Check to see if this is serialized content + // we need to unpack. + if (result) { + result = dbInfo.serializer.deserialize(result); + } + + result = iterator(result, item.key, i + 1); + + // void(0) prevents problems with redefinition + // of `undefined`. + if (result !== void 0) { + resolve(result); + return; + } + } + + resolve(); + }, function (t, error) { + reject(error); + }); + }); + })["catch"](reject); + }); + + executeCallback(promise, callback); + return promise; +} + +function setItem$1(key, value, callback) { + var self = this; + + // Cast the key to a string, as that's all we can set as a key. + if (typeof key !== 'string') { + console.warn(key + ' used as a key, but it is not a string.'); + key = String(key); + } + + var promise = new Promise$1(function (resolve, reject) { + self.ready().then(function () { + // The localStorage API doesn't return undefined values in an + // "expected" way, so undefined is always cast to null in all + // drivers. See: https://github.com/mozilla/localForage/pull/42 + if (value === undefined) { + value = null; + } + + // Save the original value to pass to the callback. + var originalValue = value; + + var dbInfo = self._dbInfo; + dbInfo.serializer.serialize(value, function (value, error) { + if (error) { + reject(error); + } else { + dbInfo.db.transaction(function (t) { + t.executeSql('INSERT OR REPLACE INTO ' + dbInfo.storeName + ' (key, value) VALUES (?, ?)', [key, value], function () { + resolve(originalValue); + }, function (t, error) { + reject(error); + }); + }, function (sqlError) { + // The transaction failed; check + // to see if it's a quota error. + if (sqlError.code === sqlError.QUOTA_ERR) { + // We reject the callback outright for now, but + // it's worth trying to re-run the transaction. + // Even if the user accepts the prompt to use + // more storage on Safari, this error will + // be called. + // + // TODO: Try to re-run the transaction. + reject(sqlError); + } + }); + } + }); + })["catch"](reject); + }); + + executeCallback(promise, callback); + return promise; +} + +function removeItem$1(key, callback) { + var self = this; + + // Cast the key to a string, as that's all we can set as a key. + if (typeof key !== 'string') { + console.warn(key + ' used as a key, but it is not a string.'); + key = String(key); + } + + var promise = new Promise$1(function (resolve, reject) { + self.ready().then(function () { + var dbInfo = self._dbInfo; + dbInfo.db.transaction(function (t) { + t.executeSql('DELETE FROM ' + dbInfo.storeName + ' WHERE key = ?', [key], function () { + resolve(); + }, function (t, error) { + + reject(error); + }); + }); + })["catch"](reject); + }); + + executeCallback(promise, callback); + return promise; +} + +// Deletes every item in the table. +// TODO: Find out if this resets the AUTO_INCREMENT number. +function clear$1(callback) { + var self = this; + + var promise = new Promise$1(function (resolve, reject) { + self.ready().then(function () { + var dbInfo = self._dbInfo; + dbInfo.db.transaction(function (t) { + t.executeSql('DELETE FROM ' + dbInfo.storeName, [], function () { + resolve(); + }, function (t, error) { + reject(error); + }); + }); + })["catch"](reject); + }); + + executeCallback(promise, callback); + return promise; +} + +// Does a simple `COUNT(key)` to get the number of items stored in +// localForage. +function length$1(callback) { + var self = this; + + var promise = new Promise$1(function (resolve, reject) { + self.ready().then(function () { + var dbInfo = self._dbInfo; + dbInfo.db.transaction(function (t) { + // Ahhh, SQL makes this one soooooo easy. + t.executeSql('SELECT COUNT(key) as c FROM ' + dbInfo.storeName, [], function (t, results) { + var result = results.rows.item(0).c; + + resolve(result); + }, function (t, error) { + + reject(error); + }); + }); + })["catch"](reject); + }); + + executeCallback(promise, callback); + return promise; +} + +// Return the key located at key index X; essentially gets the key from a +// `WHERE id = ?`. This is the most efficient way I can think to implement +// this rarely-used (in my experience) part of the API, but it can seem +// inconsistent, because we do `INSERT OR REPLACE INTO` on `setItem()`, so +// the ID of each key will change every time it's updated. Perhaps a stored +// procedure for the `setItem()` SQL would solve this problem? +// TODO: Don't change ID on `setItem()`. +function key$1(n, callback) { + var self = this; + + var promise = new Promise$1(function (resolve, reject) { + self.ready().then(function () { + var dbInfo = self._dbInfo; + dbInfo.db.transaction(function (t) { + t.executeSql('SELECT key FROM ' + dbInfo.storeName + ' WHERE id = ? LIMIT 1', [n + 1], function (t, results) { + var result = results.rows.length ? results.rows.item(0).key : null; + resolve(result); + }, function (t, error) { + reject(error); + }); + }); + })["catch"](reject); + }); + + executeCallback(promise, callback); + return promise; +} + +function keys$1(callback) { + var self = this; + + var promise = new Promise$1(function (resolve, reject) { + self.ready().then(function () { + var dbInfo = self._dbInfo; + dbInfo.db.transaction(function (t) { + t.executeSql('SELECT key FROM ' + dbInfo.storeName, [], function (t, results) { + var keys = []; + + for (var i = 0; i < results.rows.length; i++) { + keys.push(results.rows.item(i).key); + } + + resolve(keys); + }, function (t, error) { + + reject(error); + }); + }); + })["catch"](reject); + }); + + executeCallback(promise, callback); + return promise; +} + +var webSQLStorage = { + _driver: 'webSQLStorage', + _initStorage: _initStorage$1, + iterate: iterate$1, + getItem: getItem$1, + setItem: setItem$1, + removeItem: removeItem$1, + clear: clear$1, + length: length$1, + key: key$1, + keys: keys$1 +}; + +// Config the localStorage backend, using options set in the config. +function _initStorage$2(options) { + var self = this; + var dbInfo = {}; + if (options) { + for (var i in options) { + dbInfo[i] = options[i]; + } + } + + dbInfo.keyPrefix = dbInfo.name + '/'; + + if (dbInfo.storeName !== self._defaultConfig.storeName) { + dbInfo.keyPrefix += dbInfo.storeName + '/'; + } + + self._dbInfo = dbInfo; + dbInfo.serializer = localforageSerializer; + + return Promise$1.resolve(); +} + +// Remove all keys from the datastore, effectively destroying all data in +// the app's key/value store! +function clear$2(callback) { + var self = this; + var promise = self.ready().then(function () { + var keyPrefix = self._dbInfo.keyPrefix; + + for (var i = localStorage.length - 1; i >= 0; i--) { + var key = localStorage.key(i); + + if (key.indexOf(keyPrefix) === 0) { + localStorage.removeItem(key); + } + } + }); + + executeCallback(promise, callback); + return promise; +} + +// Retrieve an item from the store. Unlike the original async_storage +// library in Gaia, we don't modify return values at all. If a key's value +// is `undefined`, we pass that value to the callback function. +function getItem$2(key, callback) { + var self = this; + + // Cast the key to a string, as that's all we can set as a key. + if (typeof key !== 'string') { + console.warn(key + ' used as a key, but it is not a string.'); + key = String(key); + } + + var promise = self.ready().then(function () { + var dbInfo = self._dbInfo; + var result = localStorage.getItem(dbInfo.keyPrefix + key); + + // If a result was found, parse it from the serialized + // string into a JS object. If result isn't truthy, the key + // is likely undefined and we'll pass it straight to the + // callback. + if (result) { + result = dbInfo.serializer.deserialize(result); + } + + return result; + }); + + executeCallback(promise, callback); + return promise; +} + +// Iterate over all items in the store. +function iterate$2(iterator, callback) { + var self = this; + + var promise = self.ready().then(function () { + var dbInfo = self._dbInfo; + var keyPrefix = dbInfo.keyPrefix; + var keyPrefixLength = keyPrefix.length; + var length = localStorage.length; + + // We use a dedicated iterator instead of the `i` variable below + // so other keys we fetch in localStorage aren't counted in + // the `iterationNumber` argument passed to the `iterate()` + // callback. + // + // See: github.com/mozilla/localForage/pull/435#discussion_r38061530 + var iterationNumber = 1; + + for (var i = 0; i < length; i++) { + var key = localStorage.key(i); + if (key.indexOf(keyPrefix) !== 0) { + continue; + } + var value = localStorage.getItem(key); + + // If a result was found, parse it from the serialized + // string into a JS object. If result isn't truthy, the + // key is likely undefined and we'll pass it straight + // to the iterator. + if (value) { + value = dbInfo.serializer.deserialize(value); + } + + value = iterator(value, key.substring(keyPrefixLength), iterationNumber++); + + if (value !== void 0) { + return value; + } + } + }); + + executeCallback(promise, callback); + return promise; +} + +// Same as localStorage's key() method, except takes a callback. +function key$2(n, callback) { + var self = this; + var promise = self.ready().then(function () { + var dbInfo = self._dbInfo; + var result; + try { + result = localStorage.key(n); + } catch (error) { + result = null; + } + + // Remove the prefix from the key, if a key is found. + if (result) { + result = result.substring(dbInfo.keyPrefix.length); + } + + return result; + }); + + executeCallback(promise, callback); + return promise; +} + +function keys$2(callback) { + var self = this; + var promise = self.ready().then(function () { + var dbInfo = self._dbInfo; + var length = localStorage.length; + var keys = []; + + for (var i = 0; i < length; i++) { + if (localStorage.key(i).indexOf(dbInfo.keyPrefix) === 0) { + keys.push(localStorage.key(i).substring(dbInfo.keyPrefix.length)); + } + } + + return keys; + }); + + executeCallback(promise, callback); + return promise; +} + +// Supply the number of keys in the datastore to the callback function. +function length$2(callback) { + var self = this; + var promise = self.keys().then(function (keys) { + return keys.length; + }); + + executeCallback(promise, callback); + return promise; +} + +// Remove an item from the store, nice and simple. +function removeItem$2(key, callback) { + var self = this; + + // Cast the key to a string, as that's all we can set as a key. + if (typeof key !== 'string') { + console.warn(key + ' used as a key, but it is not a string.'); + key = String(key); + } + + var promise = self.ready().then(function () { + var dbInfo = self._dbInfo; + localStorage.removeItem(dbInfo.keyPrefix + key); + }); + + executeCallback(promise, callback); + return promise; +} + +// Set a key's value and run an optional callback once the value is set. +// Unlike Gaia's implementation, the callback function is passed the value, +// in case you want to operate on that value only after you're sure it +// saved, or something like that. +function setItem$2(key, value, callback) { + var self = this; + + // Cast the key to a string, as that's all we can set as a key. + if (typeof key !== 'string') { + console.warn(key + ' used as a key, but it is not a string.'); + key = String(key); + } + + var promise = self.ready().then(function () { + // Convert undefined values to null. + // https://github.com/mozilla/localForage/pull/42 + if (value === undefined) { + value = null; + } + + // Save the original value to pass to the callback. + var originalValue = value; + + return new Promise$1(function (resolve, reject) { + var dbInfo = self._dbInfo; + dbInfo.serializer.serialize(value, function (value, error) { + if (error) { + reject(error); + } else { + try { + localStorage.setItem(dbInfo.keyPrefix + key, value); + resolve(originalValue); + } catch (e) { + // localStorage capacity exceeded. + // TODO: Make this a specific error/event. + if (e.name === 'QuotaExceededError' || e.name === 'NS_ERROR_DOM_QUOTA_REACHED') { + reject(e); + } + reject(e); + } + } + }); + }); + }); + + executeCallback(promise, callback); + return promise; +} + +var localStorageWrapper = { + _driver: 'localStorageWrapper', + _initStorage: _initStorage$2, + // Default API, from Gaia/localStorage. + iterate: iterate$2, + getItem: getItem$2, + setItem: setItem$2, + removeItem: removeItem$2, + clear: clear$2, + length: length$2, + key: key$2, + keys: keys$2 +}; + +function executeTwoCallbacks(promise, callback, errorCallback) { + if (typeof callback === 'function') { + promise.then(callback); + } + + if (typeof errorCallback === 'function') { + promise["catch"](errorCallback); + } +} + +// Custom drivers are stored here when `defineDriver()` is called. +// They are shared across all instances of localForage. +var CustomDrivers = {}; + +var DriverType = { + INDEXEDDB: 'asyncStorage', + LOCALSTORAGE: 'localStorageWrapper', + WEBSQL: 'webSQLStorage' +}; + +var DefaultDriverOrder = [DriverType.INDEXEDDB, DriverType.WEBSQL, DriverType.LOCALSTORAGE]; + +var LibraryMethods = ['clear', 'getItem', 'iterate', 'key', 'keys', 'length', 'removeItem', 'setItem']; + +var DefaultConfig = { + description: '', + driver: DefaultDriverOrder.slice(), + name: 'localforage', + // Default DB size is _JUST UNDER_ 5MB, as it's the highest size + // we can use without a prompt. + size: 4980736, + storeName: 'keyvaluepairs', + version: 1.0 +}; + +var driverSupport = {}; +// Check to see if IndexedDB is available and if it is the latest +// implementation; it's our preferred backend library. We use "_spec_test" +// as the name of the database because it's not the one we'll operate on, +// but it's useful to make sure its using the right spec. +// See: https://github.com/mozilla/localForage/issues/128 +driverSupport[DriverType.INDEXEDDB] = isIndexedDBValid(); + +driverSupport[DriverType.WEBSQL] = isWebSQLValid(); + +driverSupport[DriverType.LOCALSTORAGE] = isLocalStorageValid(); + +var isArray = Array.isArray || function (arg) { + return Object.prototype.toString.call(arg) === '[object Array]'; +}; + +function callWhenReady(localForageInstance, libraryMethod) { + localForageInstance[libraryMethod] = function () { + var _args = arguments; + return localForageInstance.ready().then(function () { + return localForageInstance[libraryMethod].apply(localForageInstance, _args); + }); + }; +} + +function extend() { + for (var i = 1; i < arguments.length; i++) { + var arg = arguments[i]; + + if (arg) { + for (var key in arg) { + if (arg.hasOwnProperty(key)) { + if (isArray(arg[key])) { + arguments[0][key] = arg[key].slice(); + } else { + arguments[0][key] = arg[key]; + } + } + } + } + } + + return arguments[0]; +} + +function isLibraryDriver(driverName) { + for (var driver in DriverType) { + if (DriverType.hasOwnProperty(driver) && DriverType[driver] === driverName) { + return true; + } + } + + return false; +} + +var LocalForage = function () { + function LocalForage(options) { + _classCallCheck(this, LocalForage); + + this.INDEXEDDB = DriverType.INDEXEDDB; + this.LOCALSTORAGE = DriverType.LOCALSTORAGE; + this.WEBSQL = DriverType.WEBSQL; + + this._defaultConfig = extend({}, DefaultConfig); + this._config = extend({}, this._defaultConfig, options); + this._driverSet = null; + this._initDriver = null; + this._ready = false; + this._dbInfo = null; + + this._wrapLibraryMethodsWithReady(); + this.setDriver(this._config.driver); + } + + // Set any config values for localForage; can be called anytime before + // the first API call (e.g. `getItem`, `setItem`). + // We loop through options so we don't overwrite existing config + // values. + + + LocalForage.prototype.config = function config(options) { + // If the options argument is an object, we use it to set values. + // Otherwise, we return either a specified config value or all + // config values. + if ((typeof options === 'undefined' ? 'undefined' : _typeof(options)) === 'object') { + // If localforage is ready and fully initialized, we can't set + // any new configuration values. Instead, we return an error. + if (this._ready) { + return new Error("Can't call config() after localforage " + 'has been used.'); + } + + for (var i in options) { + if (i === 'storeName') { + options[i] = options[i].replace(/\W/g, '_'); + } + + this._config[i] = options[i]; + } + + // after all config options are set and + // the driver option is used, try setting it + if ('driver' in options && options.driver) { + this.setDriver(this._config.driver); + } + + return true; + } else if (typeof options === 'string') { + return this._config[options]; + } else { + return this._config; + } + }; + + // Used to define a custom driver, shared across all instances of + // localForage. + + + LocalForage.prototype.defineDriver = function defineDriver(driverObject, callback, errorCallback) { + var promise = new Promise$1(function (resolve, reject) { + try { + var driverName = driverObject._driver; + var complianceError = new Error('Custom driver not compliant; see ' + 'https://mozilla.github.io/localForage/#definedriver'); + var namingError = new Error('Custom driver name already in use: ' + driverObject._driver); + + // A driver name should be defined and not overlap with the + // library-defined, default drivers. + if (!driverObject._driver) { + reject(complianceError); + return; + } + if (isLibraryDriver(driverObject._driver)) { + reject(namingError); + return; + } + + var customDriverMethods = LibraryMethods.concat('_initStorage'); + for (var i = 0; i < customDriverMethods.length; i++) { + var customDriverMethod = customDriverMethods[i]; + if (!customDriverMethod || !driverObject[customDriverMethod] || typeof driverObject[customDriverMethod] !== 'function') { + reject(complianceError); + return; + } + } + + var supportPromise = Promise$1.resolve(true); + if ('_support' in driverObject) { + if (driverObject._support && typeof driverObject._support === 'function') { + supportPromise = driverObject._support(); + } else { + supportPromise = Promise$1.resolve(!!driverObject._support); + } + } + + supportPromise.then(function (supportResult) { + driverSupport[driverName] = supportResult; + CustomDrivers[driverName] = driverObject; + resolve(); + }, reject); + } catch (e) { + reject(e); + } + }); + + executeTwoCallbacks(promise, callback, errorCallback); + return promise; + }; + + LocalForage.prototype.driver = function driver() { + return this._driver || null; + }; + + LocalForage.prototype.getDriver = function getDriver(driverName, callback, errorCallback) { + var self = this; + var getDriverPromise = Promise$1.resolve().then(function () { + if (isLibraryDriver(driverName)) { + switch (driverName) { + case self.INDEXEDDB: + return asyncStorage; + case self.LOCALSTORAGE: + return localStorageWrapper; + case self.WEBSQL: + return webSQLStorage; + } + } else if (CustomDrivers[driverName]) { + return CustomDrivers[driverName]; + } else { + throw new Error('Driver not found.'); + } + }); + executeTwoCallbacks(getDriverPromise, callback, errorCallback); + return getDriverPromise; + }; + + LocalForage.prototype.getSerializer = function getSerializer(callback) { + var serializerPromise = Promise$1.resolve(localforageSerializer); + executeTwoCallbacks(serializerPromise, callback); + return serializerPromise; + }; + + LocalForage.prototype.ready = function ready(callback) { + var self = this; + + var promise = self._driverSet.then(function () { + if (self._ready === null) { + self._ready = self._initDriver(); + } + + return self._ready; + }); + + executeTwoCallbacks(promise, callback, callback); + return promise; + }; + + LocalForage.prototype.setDriver = function setDriver(drivers, callback, errorCallback) { + var self = this; + + if (!isArray(drivers)) { + drivers = [drivers]; + } + + var supportedDrivers = this._getSupportedDrivers(drivers); + + function setDriverToConfig() { + self._config.driver = self.driver(); + } + + function initDriver(supportedDrivers) { + return function () { + var currentDriverIndex = 0; + + function driverPromiseLoop() { + while (currentDriverIndex < supportedDrivers.length) { + var driverName = supportedDrivers[currentDriverIndex]; + currentDriverIndex++; + + self._dbInfo = null; + self._ready = null; + + return self.getDriver(driverName).then(function (driver) { + self._extend(driver); + setDriverToConfig(); + + self._ready = self._initStorage(self._config); + return self._ready; + })["catch"](driverPromiseLoop); + } + + setDriverToConfig(); + var error = new Error('No available storage method found.'); + self._driverSet = Promise$1.reject(error); + return self._driverSet; + } + + return driverPromiseLoop(); + }; + } + + // There might be a driver initialization in progress + // so wait for it to finish in order to avoid a possible + // race condition to set _dbInfo + var oldDriverSetDone = this._driverSet !== null ? this._driverSet["catch"](function () { + return Promise$1.resolve(); + }) : Promise$1.resolve(); + + this._driverSet = oldDriverSetDone.then(function () { + var driverName = supportedDrivers[0]; + self._dbInfo = null; + self._ready = null; + + return self.getDriver(driverName).then(function (driver) { + self._driver = driver._driver; + setDriverToConfig(); + self._wrapLibraryMethodsWithReady(); + self._initDriver = initDriver(supportedDrivers); + }); + })["catch"](function () { + setDriverToConfig(); + var error = new Error('No available storage method found.'); + self._driverSet = Promise$1.reject(error); + return self._driverSet; + }); + + executeTwoCallbacks(this._driverSet, callback, errorCallback); + return this._driverSet; + }; + + LocalForage.prototype.supports = function supports(driverName) { + return !!driverSupport[driverName]; + }; + + LocalForage.prototype._extend = function _extend(libraryMethodsAndProperties) { + extend(this, libraryMethodsAndProperties); + }; + + LocalForage.prototype._getSupportedDrivers = function _getSupportedDrivers(drivers) { + var supportedDrivers = []; + for (var i = 0, len = drivers.length; i < len; i++) { + var driverName = drivers[i]; + if (this.supports(driverName)) { + supportedDrivers.push(driverName); + } + } + return supportedDrivers; + }; + + LocalForage.prototype._wrapLibraryMethodsWithReady = function _wrapLibraryMethodsWithReady() { + // Add a stub for each driver API method that delays the call to the + // corresponding driver method until localForage is ready. These stubs + // will be replaced by the driver methods as soon as the driver is + // loaded, so there is no performance impact. + for (var i = 0; i < LibraryMethods.length; i++) { + callWhenReady(this, LibraryMethods[i]); + } + }; + + LocalForage.prototype.createInstance = function createInstance(options) { + return new LocalForage(options); + }; + + return LocalForage; +}(); + +// The actual localForage object that we expose as a module or via a +// global. It's extended by pulling in one of our other libraries. + + +var localforage_js = new LocalForage(); + +module.exports = localforage_js; + +},{"3":3}]},{},[4])(4) +});
\ No newline at end of file diff --git a/www/lib/localforage/dist/localforage.min.js b/www/lib/localforage/dist/localforage.min.js new file mode 100644 index 00000000..a0c0ed38 --- /dev/null +++ b/www/lib/localforage/dist/localforage.min.js @@ -0,0 +1,7 @@ +/*! + localForage -- Offline Storage, Improved + Version 1.4.2 + https://mozilla.github.io/localForage + (c) 2013-2015 Mozilla, Apache License 2.0 +*/ +!function(a){if("object"==typeof exports&&"undefined"!=typeof module)module.exports=a();else if("function"==typeof define&&define.amd)define([],a);else{var b;b="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:this,b.localforage=a()}}(function(){return function a(b,c,d){function e(g,h){if(!c[g]){if(!b[g]){var i="function"==typeof require&&require;if(!h&&i)return i(g,!0);if(f)return f(g,!0);var j=new Error("Cannot find module '"+g+"'");throw j.code="MODULE_NOT_FOUND",j}var k=c[g]={exports:{}};b[g][0].call(k.exports,function(a){var c=b[g][1][a];return e(c?c:a)},k,k.exports,a,b,c,d)}return c[g].exports}for(var f="function"==typeof require&&require,g=0;g<d.length;g++)e(d[g]);return e}({1:[function(a,b,c){(function(a){"use strict";function c(){k=!0;for(var a,b,c=l.length;c;){for(b=l,l=[],a=-1;++a<c;)b[a]();c=l.length}k=!1}function d(a){1!==l.push(a)||k||e()}var e,f=a.MutationObserver||a.WebKitMutationObserver;if(f){var g=0,h=new f(c),i=a.document.createTextNode("");h.observe(i,{characterData:!0}),e=function(){i.data=g=++g%2}}else if(a.setImmediate||"undefined"==typeof a.MessageChannel)e="document"in a&&"onreadystatechange"in a.document.createElement("script")?function(){var b=a.document.createElement("script");b.onreadystatechange=function(){c(),b.onreadystatechange=null,b.parentNode.removeChild(b),b=null},a.document.documentElement.appendChild(b)}:function(){setTimeout(c,0)};else{var j=new a.MessageChannel;j.port1.onmessage=c,e=function(){j.port2.postMessage(0)}}var k,l=[];b.exports=d}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{}],2:[function(a,b,c){"use strict";function d(){}function e(a){if("function"!=typeof a)throw new TypeError("resolver must be a function");this.state=s,this.queue=[],this.outcome=void 0,a!==d&&i(this,a)}function f(a,b,c){this.promise=a,"function"==typeof b&&(this.onFulfilled=b,this.callFulfilled=this.otherCallFulfilled),"function"==typeof c&&(this.onRejected=c,this.callRejected=this.otherCallRejected)}function g(a,b,c){o(function(){var d;try{d=b(c)}catch(e){return p.reject(a,e)}d===a?p.reject(a,new TypeError("Cannot resolve promise with itself")):p.resolve(a,d)})}function h(a){var b=a&&a.then;return a&&"object"==typeof a&&"function"==typeof b?function(){b.apply(a,arguments)}:void 0}function i(a,b){function c(b){f||(f=!0,p.reject(a,b))}function d(b){f||(f=!0,p.resolve(a,b))}function e(){b(d,c)}var f=!1,g=j(e);"error"===g.status&&c(g.value)}function j(a,b){var c={};try{c.value=a(b),c.status="success"}catch(d){c.status="error",c.value=d}return c}function k(a){return a instanceof this?a:p.resolve(new this(d),a)}function l(a){var b=new this(d);return p.reject(b,a)}function m(a){function b(a,b){function d(a){g[b]=a,++h!==e||f||(f=!0,p.resolve(j,g))}c.resolve(a).then(d,function(a){f||(f=!0,p.reject(j,a))})}var c=this;if("[object Array]"!==Object.prototype.toString.call(a))return this.reject(new TypeError("must be an array"));var e=a.length,f=!1;if(!e)return this.resolve([]);for(var g=new Array(e),h=0,i=-1,j=new this(d);++i<e;)b(a[i],i);return j}function n(a){function b(a){c.resolve(a).then(function(a){f||(f=!0,p.resolve(h,a))},function(a){f||(f=!0,p.reject(h,a))})}var c=this;if("[object Array]"!==Object.prototype.toString.call(a))return this.reject(new TypeError("must be an array"));var e=a.length,f=!1;if(!e)return this.resolve([]);for(var g=-1,h=new this(d);++g<e;)b(a[g]);return h}var o=a(1),p={},q=["REJECTED"],r=["FULFILLED"],s=["PENDING"];b.exports=c=e,e.prototype["catch"]=function(a){return this.then(null,a)},e.prototype.then=function(a,b){if("function"!=typeof a&&this.state===r||"function"!=typeof b&&this.state===q)return this;var c=new this.constructor(d);if(this.state!==s){var e=this.state===r?a:b;g(c,e,this.outcome)}else this.queue.push(new f(c,a,b));return c},f.prototype.callFulfilled=function(a){p.resolve(this.promise,a)},f.prototype.otherCallFulfilled=function(a){g(this.promise,this.onFulfilled,a)},f.prototype.callRejected=function(a){p.reject(this.promise,a)},f.prototype.otherCallRejected=function(a){g(this.promise,this.onRejected,a)},p.resolve=function(a,b){var c=j(h,b);if("error"===c.status)return p.reject(a,c.value);var d=c.value;if(d)i(a,d);else{a.state=r,a.outcome=b;for(var e=-1,f=a.queue.length;++e<f;)a.queue[e].callFulfilled(b)}return a},p.reject=function(a,b){a.state=q,a.outcome=b;for(var c=-1,d=a.queue.length;++c<d;)a.queue[c].callRejected(b);return a},c.resolve=k,c.reject=l,c.all=m,c.race=n},{1:1}],3:[function(a,b,c){(function(b){"use strict";"function"!=typeof b.Promise&&(b.Promise=a(2))}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{2:2}],4:[function(a,b,c){"use strict";function d(a,b){if(!(a instanceof b))throw new TypeError("Cannot call a class as a function")}function e(){return"undefined"!=typeof indexedDB?indexedDB:"undefined"!=typeof webkitIndexedDB?webkitIndexedDB:"undefined"!=typeof mozIndexedDB?mozIndexedDB:"undefined"!=typeof OIndexedDB?OIndexedDB:"undefined"!=typeof msIndexedDB?msIndexedDB:void 0}function f(){try{return fa?"undefined"!=typeof openDatabase&&"undefined"!=typeof navigator&&navigator.userAgent&&/Safari/.test(navigator.userAgent)&&!/Chrome/.test(navigator.userAgent)?!1:fa&&"function"==typeof fa.open&&"undefined"!=typeof IDBKeyRange:!1}catch(a){return!1}}function g(){return"function"==typeof openDatabase}function h(){try{return"undefined"!=typeof localStorage&&"setItem"in localStorage&&localStorage.setItem}catch(a){return!1}}function i(a,b){a=a||[],b=b||{};try{return new Blob(a,b)}catch(c){if("TypeError"!==c.name)throw c;for(var d="undefined"!=typeof BlobBuilder?BlobBuilder:"undefined"!=typeof MSBlobBuilder?MSBlobBuilder:"undefined"!=typeof MozBlobBuilder?MozBlobBuilder:WebKitBlobBuilder,e=new d,f=0;f<a.length;f+=1)e.append(a[f]);return e.getBlob(b.type)}}function j(a,b){b&&a.then(function(a){b(null,a)},function(a){b(a)})}function k(a){for(var b=a.length,c=new ArrayBuffer(b),d=new Uint8Array(c),e=0;b>e;e++)d[e]=a.charCodeAt(e);return c}function l(a){return new ia(function(b){var c=i([""]);a.objectStore(ja).put(c,"key"),a.onabort=function(a){a.preventDefault(),a.stopPropagation(),b(!1)},a.oncomplete=function(){var a=navigator.userAgent.match(/Chrome\/(\d+)/),c=navigator.userAgent.match(/Edge\//);b(c||!a||parseInt(a[1],10)>=43)}})["catch"](function(){return!1})}function m(a){return"boolean"==typeof ga?ia.resolve(ga):l(a).then(function(a){return ga=a})}function n(a){var b=ha[a.name],c={};c.promise=new ia(function(a){c.resolve=a}),b.deferredOperations.push(c),b.dbReady?b.dbReady=b.dbReady.then(function(){return c.promise}):b.dbReady=c.promise}function o(a){var b=ha[a.name],c=b.deferredOperations.pop();c&&c.resolve()}function p(a,b){return new ia(function(c,d){if(a.db){if(!b)return c(a.db);n(a),a.db.close()}var e=[a.name];b&&e.push(a.version);var f=fa.open.apply(fa,e);b&&(f.onupgradeneeded=function(b){var c=f.result;try{c.createObjectStore(a.storeName),b.oldVersion<=1&&c.createObjectStore(ja)}catch(d){if("ConstraintError"!==d.name)throw d;console.warn('The database "'+a.name+'" has been upgraded from version '+b.oldVersion+" to version "+b.newVersion+', but the storage "'+a.storeName+'" already exists.')}}),f.onerror=function(){d(f.error)},f.onsuccess=function(){c(f.result),o(a)}})}function q(a){return p(a,!1)}function r(a){return p(a,!0)}function s(a,b){if(!a.db)return!0;var c=!a.db.objectStoreNames.contains(a.storeName),d=a.version<a.db.version,e=a.version>a.db.version;if(d&&(a.version!==b&&console.warn('The database "'+a.name+"\" can't be downgraded from version "+a.db.version+" to version "+a.version+"."),a.version=a.db.version),e||c){if(c){var f=a.db.version+1;f>a.version&&(a.version=f)}return!0}return!1}function t(a){return new ia(function(b,c){var d=new FileReader;d.onerror=c,d.onloadend=function(c){var d=btoa(c.target.result||"");b({__local_forage_encoded_blob:!0,data:d,type:a.type})},d.readAsBinaryString(a)})}function u(a){var b=k(atob(a.data));return i([b],{type:a.type})}function v(a){return a&&a.__local_forage_encoded_blob}function w(a){var b=this,c=b._initReady().then(function(){var a=ha[b._dbInfo.name];return a&&a.dbReady?a.dbReady:void 0});return c.then(a,a),c}function x(a){function b(){return ia.resolve()}var c=this,d={db:null};if(a)for(var e in a)d[e]=a[e];ha||(ha={});var f=ha[d.name];f||(f={forages:[],db:null,dbReady:null,deferredOperations:[]},ha[d.name]=f),f.forages.push(c),c._initReady||(c._initReady=c.ready,c.ready=w);for(var g=[],h=0;h<f.forages.length;h++){var i=f.forages[h];i!==c&&g.push(i._initReady()["catch"](b))}var j=f.forages.slice(0);return ia.all(g).then(function(){return d.db=f.db,q(d)}).then(function(a){return d.db=a,s(d,c._defaultConfig.version)?r(d):a}).then(function(a){d.db=f.db=a,c._dbInfo=d;for(var b=0;b<j.length;b++){var e=j[b];e!==c&&(e._dbInfo.db=d.db,e._dbInfo.version=d.version)}})}function y(a,b){var c=this;"string"!=typeof a&&(console.warn(a+" used as a key, but it is not a string."),a=String(a));var d=new ia(function(b,d){c.ready().then(function(){var e=c._dbInfo,f=e.db.transaction(e.storeName,"readonly").objectStore(e.storeName),g=f.get(a);g.onsuccess=function(){var a=g.result;void 0===a&&(a=null),v(a)&&(a=u(a)),b(a)},g.onerror=function(){d(g.error)}})["catch"](d)});return j(d,b),d}function z(a,b){var c=this,d=new ia(function(b,d){c.ready().then(function(){var e=c._dbInfo,f=e.db.transaction(e.storeName,"readonly").objectStore(e.storeName),g=f.openCursor(),h=1;g.onsuccess=function(){var c=g.result;if(c){var d=c.value;v(d)&&(d=u(d));var e=a(d,c.key,h++);void 0!==e?b(e):c["continue"]()}else b()},g.onerror=function(){d(g.error)}})["catch"](d)});return j(d,b),d}function A(a,b,c){var d=this;"string"!=typeof a&&(console.warn(a+" used as a key, but it is not a string."),a=String(a));var e=new ia(function(c,e){var f;d.ready().then(function(){return f=d._dbInfo,b instanceof Blob?m(f.db).then(function(a){return a?b:t(b)}):b}).then(function(b){var d=f.db.transaction(f.storeName,"readwrite"),g=d.objectStore(f.storeName);null===b&&(b=void 0),d.oncomplete=function(){void 0===b&&(b=null),c(b)},d.onabort=d.onerror=function(){var a=h.error?h.error:h.transaction.error;e(a)};var h=g.put(b,a)})["catch"](e)});return j(e,c),e}function B(a,b){var c=this;"string"!=typeof a&&(console.warn(a+" used as a key, but it is not a string."),a=String(a));var d=new ia(function(b,d){c.ready().then(function(){var e=c._dbInfo,f=e.db.transaction(e.storeName,"readwrite"),g=f.objectStore(e.storeName),h=g["delete"](a);f.oncomplete=function(){b()},f.onerror=function(){d(h.error)},f.onabort=function(){var a=h.error?h.error:h.transaction.error;d(a)}})["catch"](d)});return j(d,b),d}function C(a){var b=this,c=new ia(function(a,c){b.ready().then(function(){var d=b._dbInfo,e=d.db.transaction(d.storeName,"readwrite"),f=e.objectStore(d.storeName),g=f.clear();e.oncomplete=function(){a()},e.onabort=e.onerror=function(){var a=g.error?g.error:g.transaction.error;c(a)}})["catch"](c)});return j(c,a),c}function D(a){var b=this,c=new ia(function(a,c){b.ready().then(function(){var d=b._dbInfo,e=d.db.transaction(d.storeName,"readonly").objectStore(d.storeName),f=e.count();f.onsuccess=function(){a(f.result)},f.onerror=function(){c(f.error)}})["catch"](c)});return j(c,a),c}function E(a,b){var c=this,d=new ia(function(b,d){return 0>a?void b(null):void c.ready().then(function(){var e=c._dbInfo,f=e.db.transaction(e.storeName,"readonly").objectStore(e.storeName),g=!1,h=f.openCursor();h.onsuccess=function(){var c=h.result;return c?void(0===a?b(c.key):g?b(c.key):(g=!0,c.advance(a))):void b(null)},h.onerror=function(){d(h.error)}})["catch"](d)});return j(d,b),d}function F(a){var b=this,c=new ia(function(a,c){b.ready().then(function(){var d=b._dbInfo,e=d.db.transaction(d.storeName,"readonly").objectStore(d.storeName),f=e.openCursor(),g=[];f.onsuccess=function(){var b=f.result;return b?(g.push(b.key),void b["continue"]()):void a(g)},f.onerror=function(){c(f.error)}})["catch"](c)});return j(c,a),c}function G(a){var b,c,d,e,f,g=.75*a.length,h=a.length,i=0;"="===a[a.length-1]&&(g--,"="===a[a.length-2]&&g--);var j=new ArrayBuffer(g),k=new Uint8Array(j);for(b=0;h>b;b+=4)c=la.indexOf(a[b]),d=la.indexOf(a[b+1]),e=la.indexOf(a[b+2]),f=la.indexOf(a[b+3]),k[i++]=c<<2|d>>4,k[i++]=(15&d)<<4|e>>2,k[i++]=(3&e)<<6|63&f;return j}function H(a){var b,c=new Uint8Array(a),d="";for(b=0;b<c.length;b+=3)d+=la[c[b]>>2],d+=la[(3&c[b])<<4|c[b+1]>>4],d+=la[(15&c[b+1])<<2|c[b+2]>>6],d+=la[63&c[b+2]];return c.length%3===2?d=d.substring(0,d.length-1)+"=":c.length%3===1&&(d=d.substring(0,d.length-2)+"=="),d}function I(a,b){var c="";if(a&&(c=a.toString()),a&&("[object ArrayBuffer]"===a.toString()||a.buffer&&"[object ArrayBuffer]"===a.buffer.toString())){var d,e=oa;a instanceof ArrayBuffer?(d=a,e+=qa):(d=a.buffer,"[object Int8Array]"===c?e+=sa:"[object Uint8Array]"===c?e+=ta:"[object Uint8ClampedArray]"===c?e+=ua:"[object Int16Array]"===c?e+=va:"[object Uint16Array]"===c?e+=xa:"[object Int32Array]"===c?e+=wa:"[object Uint32Array]"===c?e+=ya:"[object Float32Array]"===c?e+=za:"[object Float64Array]"===c?e+=Aa:b(new Error("Failed to get type for BinaryArray"))),b(e+H(d))}else if("[object Blob]"===c){var f=new FileReader;f.onload=function(){var c=ma+a.type+"~"+H(this.result);b(oa+ra+c)},f.readAsArrayBuffer(a)}else try{b(JSON.stringify(a))}catch(g){console.error("Couldn't convert value into a JSON string: ",a),b(null,g)}}function J(a){if(a.substring(0,pa)!==oa)return JSON.parse(a);var b,c=a.substring(Ba),d=a.substring(pa,Ba);if(d===ra&&na.test(c)){var e=c.match(na);b=e[1],c=c.substring(e[0].length)}var f=G(c);switch(d){case qa:return f;case ra:return i([f],{type:b});case sa:return new Int8Array(f);case ta:return new Uint8Array(f);case ua:return new Uint8ClampedArray(f);case va:return new Int16Array(f);case xa:return new Uint16Array(f);case wa:return new Int32Array(f);case ya:return new Uint32Array(f);case za:return new Float32Array(f);case Aa:return new Float64Array(f);default:throw new Error("Unkown type: "+d)}}function K(a){var b=this,c={db:null};if(a)for(var d in a)c[d]="string"!=typeof a[d]?a[d].toString():a[d];var e=new ia(function(a,d){try{c.db=openDatabase(c.name,String(c.version),c.description,c.size)}catch(e){return d(e)}c.db.transaction(function(e){e.executeSql("CREATE TABLE IF NOT EXISTS "+c.storeName+" (id INTEGER PRIMARY KEY, key unique, value)",[],function(){b._dbInfo=c,a()},function(a,b){d(b)})})});return c.serializer=Ca,e}function L(a,b){var c=this;"string"!=typeof a&&(console.warn(a+" used as a key, but it is not a string."),a=String(a));var d=new ia(function(b,d){c.ready().then(function(){var e=c._dbInfo;e.db.transaction(function(c){c.executeSql("SELECT * FROM "+e.storeName+" WHERE key = ? LIMIT 1",[a],function(a,c){var d=c.rows.length?c.rows.item(0).value:null;d&&(d=e.serializer.deserialize(d)),b(d)},function(a,b){d(b)})})})["catch"](d)});return j(d,b),d}function M(a,b){var c=this,d=new ia(function(b,d){c.ready().then(function(){var e=c._dbInfo;e.db.transaction(function(c){c.executeSql("SELECT * FROM "+e.storeName,[],function(c,d){for(var f=d.rows,g=f.length,h=0;g>h;h++){var i=f.item(h),j=i.value;if(j&&(j=e.serializer.deserialize(j)),j=a(j,i.key,h+1),void 0!==j)return void b(j)}b()},function(a,b){d(b)})})})["catch"](d)});return j(d,b),d}function N(a,b,c){var d=this;"string"!=typeof a&&(console.warn(a+" used as a key, but it is not a string."),a=String(a));var e=new ia(function(c,e){d.ready().then(function(){void 0===b&&(b=null);var f=b,g=d._dbInfo;g.serializer.serialize(b,function(b,d){d?e(d):g.db.transaction(function(d){d.executeSql("INSERT OR REPLACE INTO "+g.storeName+" (key, value) VALUES (?, ?)",[a,b],function(){c(f)},function(a,b){e(b)})},function(a){a.code===a.QUOTA_ERR&&e(a)})})})["catch"](e)});return j(e,c),e}function O(a,b){var c=this;"string"!=typeof a&&(console.warn(a+" used as a key, but it is not a string."),a=String(a));var d=new ia(function(b,d){c.ready().then(function(){var e=c._dbInfo;e.db.transaction(function(c){c.executeSql("DELETE FROM "+e.storeName+" WHERE key = ?",[a],function(){b()},function(a,b){d(b)})})})["catch"](d)});return j(d,b),d}function P(a){var b=this,c=new ia(function(a,c){b.ready().then(function(){var d=b._dbInfo;d.db.transaction(function(b){b.executeSql("DELETE FROM "+d.storeName,[],function(){a()},function(a,b){c(b)})})})["catch"](c)});return j(c,a),c}function Q(a){var b=this,c=new ia(function(a,c){b.ready().then(function(){var d=b._dbInfo;d.db.transaction(function(b){b.executeSql("SELECT COUNT(key) as c FROM "+d.storeName,[],function(b,c){var d=c.rows.item(0).c;a(d)},function(a,b){c(b)})})})["catch"](c)});return j(c,a),c}function R(a,b){var c=this,d=new ia(function(b,d){c.ready().then(function(){var e=c._dbInfo;e.db.transaction(function(c){c.executeSql("SELECT key FROM "+e.storeName+" WHERE id = ? LIMIT 1",[a+1],function(a,c){var d=c.rows.length?c.rows.item(0).key:null;b(d)},function(a,b){d(b)})})})["catch"](d)});return j(d,b),d}function S(a){var b=this,c=new ia(function(a,c){b.ready().then(function(){var d=b._dbInfo;d.db.transaction(function(b){b.executeSql("SELECT key FROM "+d.storeName,[],function(b,c){for(var d=[],e=0;e<c.rows.length;e++)d.push(c.rows.item(e).key);a(d)},function(a,b){c(b)})})})["catch"](c)});return j(c,a),c}function T(a){var b=this,c={};if(a)for(var d in a)c[d]=a[d];return c.keyPrefix=c.name+"/",c.storeName!==b._defaultConfig.storeName&&(c.keyPrefix+=c.storeName+"/"),b._dbInfo=c,c.serializer=Ca,ia.resolve()}function U(a){var b=this,c=b.ready().then(function(){for(var a=b._dbInfo.keyPrefix,c=localStorage.length-1;c>=0;c--){var d=localStorage.key(c);0===d.indexOf(a)&&localStorage.removeItem(d)}});return j(c,a),c}function V(a,b){var c=this;"string"!=typeof a&&(console.warn(a+" used as a key, but it is not a string."),a=String(a));var d=c.ready().then(function(){var b=c._dbInfo,d=localStorage.getItem(b.keyPrefix+a);return d&&(d=b.serializer.deserialize(d)),d});return j(d,b),d}function W(a,b){var c=this,d=c.ready().then(function(){for(var b=c._dbInfo,d=b.keyPrefix,e=d.length,f=localStorage.length,g=1,h=0;f>h;h++){var i=localStorage.key(h);if(0===i.indexOf(d)){var j=localStorage.getItem(i);if(j&&(j=b.serializer.deserialize(j)),j=a(j,i.substring(e),g++),void 0!==j)return j}}});return j(d,b),d}function X(a,b){var c=this,d=c.ready().then(function(){var b,d=c._dbInfo;try{b=localStorage.key(a)}catch(e){b=null}return b&&(b=b.substring(d.keyPrefix.length)),b});return j(d,b),d}function Y(a){var b=this,c=b.ready().then(function(){for(var a=b._dbInfo,c=localStorage.length,d=[],e=0;c>e;e++)0===localStorage.key(e).indexOf(a.keyPrefix)&&d.push(localStorage.key(e).substring(a.keyPrefix.length));return d});return j(c,a),c}function Z(a){var b=this,c=b.keys().then(function(a){return a.length});return j(c,a),c}function $(a,b){var c=this;"string"!=typeof a&&(console.warn(a+" used as a key, but it is not a string."),a=String(a));var d=c.ready().then(function(){var b=c._dbInfo;localStorage.removeItem(b.keyPrefix+a)});return j(d,b),d}function _(a,b,c){var d=this;"string"!=typeof a&&(console.warn(a+" used as a key, but it is not a string."),a=String(a));var e=d.ready().then(function(){void 0===b&&(b=null);var c=b;return new ia(function(e,f){var g=d._dbInfo;g.serializer.serialize(b,function(b,d){if(d)f(d);else try{localStorage.setItem(g.keyPrefix+a,b),e(c)}catch(h){"QuotaExceededError"!==h.name&&"NS_ERROR_DOM_QUOTA_REACHED"!==h.name||f(h),f(h)}})})});return j(e,c),e}function aa(a,b,c){"function"==typeof b&&a.then(b),"function"==typeof c&&a["catch"](c)}function ba(a,b){a[b]=function(){var c=arguments;return a.ready().then(function(){return a[b].apply(a,c)})}}function ca(){for(var a=1;a<arguments.length;a++){var b=arguments[a];if(b)for(var c in b)b.hasOwnProperty(c)&&(La(b[c])?arguments[0][c]=b[c].slice():arguments[0][c]=b[c])}return arguments[0]}function da(a){for(var b in Ga)if(Ga.hasOwnProperty(b)&&Ga[b]===a)return!0;return!1}var ea="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(a){return typeof a}:function(a){return a&&"function"==typeof Symbol&&a.constructor===Symbol?"symbol":typeof a},fa=e();"undefined"==typeof Promise&&"undefined"!=typeof a&&a(3);var ga,ha,ia=Promise,ja="local-forage-detect-blob-support",ka={_driver:"asyncStorage",_initStorage:x,iterate:z,getItem:y,setItem:A,removeItem:B,clear:C,length:D,key:E,keys:F},la="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",ma="~~local_forage_type~",na=/^~~local_forage_type~([^~]+)~/,oa="__lfsc__:",pa=oa.length,qa="arbf",ra="blob",sa="si08",ta="ui08",ua="uic8",va="si16",wa="si32",xa="ur16",ya="ui32",za="fl32",Aa="fl64",Ba=pa+qa.length,Ca={serialize:I,deserialize:J,stringToBuffer:G,bufferToString:H},Da={_driver:"webSQLStorage",_initStorage:K,iterate:M,getItem:L,setItem:N,removeItem:O,clear:P,length:Q,key:R,keys:S},Ea={_driver:"localStorageWrapper",_initStorage:T,iterate:W,getItem:V,setItem:_,removeItem:$,clear:U,length:Z,key:X,keys:Y},Fa={},Ga={INDEXEDDB:"asyncStorage",LOCALSTORAGE:"localStorageWrapper",WEBSQL:"webSQLStorage"},Ha=[Ga.INDEXEDDB,Ga.WEBSQL,Ga.LOCALSTORAGE],Ia=["clear","getItem","iterate","key","keys","length","removeItem","setItem"],Ja={description:"",driver:Ha.slice(),name:"localforage",size:4980736,storeName:"keyvaluepairs",version:1},Ka={};Ka[Ga.INDEXEDDB]=f(),Ka[Ga.WEBSQL]=g(),Ka[Ga.LOCALSTORAGE]=h();var La=Array.isArray||function(a){return"[object Array]"===Object.prototype.toString.call(a)},Ma=function(){function a(b){d(this,a),this.INDEXEDDB=Ga.INDEXEDDB,this.LOCALSTORAGE=Ga.LOCALSTORAGE,this.WEBSQL=Ga.WEBSQL,this._defaultConfig=ca({},Ja),this._config=ca({},this._defaultConfig,b),this._driverSet=null,this._initDriver=null,this._ready=!1,this._dbInfo=null,this._wrapLibraryMethodsWithReady(),this.setDriver(this._config.driver)}return a.prototype.config=function(a){if("object"===("undefined"==typeof a?"undefined":ea(a))){if(this._ready)return new Error("Can't call config() after localforage has been used.");for(var b in a)"storeName"===b&&(a[b]=a[b].replace(/\W/g,"_")),this._config[b]=a[b];return"driver"in a&&a.driver&&this.setDriver(this._config.driver),!0}return"string"==typeof a?this._config[a]:this._config},a.prototype.defineDriver=function(a,b,c){var d=new ia(function(b,c){try{var d=a._driver,e=new Error("Custom driver not compliant; see https://mozilla.github.io/localForage/#definedriver"),f=new Error("Custom driver name already in use: "+a._driver);if(!a._driver)return void c(e);if(da(a._driver))return void c(f);for(var g=Ia.concat("_initStorage"),h=0;h<g.length;h++){var i=g[h];if(!i||!a[i]||"function"!=typeof a[i])return void c(e)}var j=ia.resolve(!0);"_support"in a&&(j=a._support&&"function"==typeof a._support?a._support():ia.resolve(!!a._support)),j.then(function(c){Ka[d]=c,Fa[d]=a,b()},c)}catch(k){c(k)}});return aa(d,b,c),d},a.prototype.driver=function(){return this._driver||null},a.prototype.getDriver=function(a,b,c){var d=this,e=ia.resolve().then(function(){if(!da(a)){if(Fa[a])return Fa[a];throw new Error("Driver not found.")}switch(a){case d.INDEXEDDB:return ka;case d.LOCALSTORAGE:return Ea;case d.WEBSQL:return Da}});return aa(e,b,c),e},a.prototype.getSerializer=function(a){var b=ia.resolve(Ca);return aa(b,a),b},a.prototype.ready=function(a){var b=this,c=b._driverSet.then(function(){return null===b._ready&&(b._ready=b._initDriver()),b._ready});return aa(c,a,a),c},a.prototype.setDriver=function(a,b,c){function d(){f._config.driver=f.driver()}function e(a){return function(){function b(){for(;c<a.length;){var e=a[c];return c++,f._dbInfo=null,f._ready=null,f.getDriver(e).then(function(a){return f._extend(a),d(),f._ready=f._initStorage(f._config),f._ready})["catch"](b)}d();var g=new Error("No available storage method found.");return f._driverSet=ia.reject(g),f._driverSet}var c=0;return b()}}var f=this;La(a)||(a=[a]);var g=this._getSupportedDrivers(a),h=null!==this._driverSet?this._driverSet["catch"](function(){return ia.resolve()}):ia.resolve();return this._driverSet=h.then(function(){var a=g[0];return f._dbInfo=null,f._ready=null,f.getDriver(a).then(function(a){f._driver=a._driver,d(),f._wrapLibraryMethodsWithReady(),f._initDriver=e(g)})})["catch"](function(){d();var a=new Error("No available storage method found.");return f._driverSet=ia.reject(a),f._driverSet}),aa(this._driverSet,b,c),this._driverSet},a.prototype.supports=function(a){return!!Ka[a]},a.prototype._extend=function(a){ca(this,a)},a.prototype._getSupportedDrivers=function(a){for(var b=[],c=0,d=a.length;d>c;c++){var e=a[c];this.supports(e)&&b.push(e)}return b},a.prototype._wrapLibraryMethodsWithReady=function(){for(var a=0;a<Ia.length;a++)ba(this,Ia[a])},a.prototype.createInstance=function(b){return new a(b)},a}(),Na=new Ma;b.exports=Na},{3:3}]},{},[4])(4)});
\ No newline at end of file diff --git a/www/lib/localforage/dist/localforage.nopromises.js b/www/lib/localforage/dist/localforage.nopromises.js new file mode 100644 index 00000000..76993df5 --- /dev/null +++ b/www/lib/localforage/dist/localforage.nopromises.js @@ -0,0 +1,1960 @@ +/*! + localForage -- Offline Storage, Improved + Version 1.4.2 + https://mozilla.github.io/localForage + (c) 2013-2015 Mozilla, Apache License 2.0 +*/ +(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.localforage = f()}})(function(){var define,module,exports;return (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw (f.code="MODULE_NOT_FOUND", f)}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(_dereq_,module,exports){ +'use strict'; + +var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol ? "symbol" : typeof obj; }; + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function getIDB() { + /* global indexedDB,webkitIndexedDB,mozIndexedDB,OIndexedDB,msIndexedDB */ + if (typeof indexedDB !== 'undefined') { + return indexedDB; + } + if (typeof webkitIndexedDB !== 'undefined') { + return webkitIndexedDB; + } + if (typeof mozIndexedDB !== 'undefined') { + return mozIndexedDB; + } + if (typeof OIndexedDB !== 'undefined') { + return OIndexedDB; + } + if (typeof msIndexedDB !== 'undefined') { + return msIndexedDB; + } +} + +var idb = getIDB(); + +function isIndexedDBValid() { + try { + // Initialize IndexedDB; fall back to vendor-prefixed versions + // if needed. + if (!idb) { + return false; + } + // We mimic PouchDB here; just UA test for Safari (which, as of + // iOS 8/Yosemite, doesn't properly support IndexedDB). + // IndexedDB support is broken and different from Blink's. + // This is faster than the test case (and it's sync), so we just + // do this. *SIGH* + // http://bl.ocks.org/nolanlawson/raw/c83e9039edf2278047e9/ + // + // We test for openDatabase because IE Mobile identifies itself + // as Safari. Oh the lulz... + if (typeof openDatabase !== 'undefined' && typeof navigator !== 'undefined' && navigator.userAgent && /Safari/.test(navigator.userAgent) && !/Chrome/.test(navigator.userAgent)) { + return false; + } + + return idb && typeof idb.open === 'function' && + // Some Samsung/HTC Android 4.0-4.3 devices + // have older IndexedDB specs; if this isn't available + // their IndexedDB is too old for us to use. + // (Replaces the onupgradeneeded test.) + typeof IDBKeyRange !== 'undefined'; + } catch (e) { + return false; + } +} + +function isWebSQLValid() { + return typeof openDatabase === 'function'; +} + +function isLocalStorageValid() { + try { + return typeof localStorage !== 'undefined' && 'setItem' in localStorage && localStorage.setItem; + } catch (e) { + return false; + } +} + +// Abstracts constructing a Blob object, so it also works in older +// browsers that don't support the native Blob constructor. (i.e. +// old QtWebKit versions, at least). +// Abstracts constructing a Blob object, so it also works in older +// browsers that don't support the native Blob constructor. (i.e. +// old QtWebKit versions, at least). +function createBlob(parts, properties) { + /* global BlobBuilder,MSBlobBuilder,MozBlobBuilder,WebKitBlobBuilder */ + parts = parts || []; + properties = properties || {}; + try { + return new Blob(parts, properties); + } catch (e) { + if (e.name !== 'TypeError') { + throw e; + } + var Builder = typeof BlobBuilder !== 'undefined' ? BlobBuilder : typeof MSBlobBuilder !== 'undefined' ? MSBlobBuilder : typeof MozBlobBuilder !== 'undefined' ? MozBlobBuilder : WebKitBlobBuilder; + var builder = new Builder(); + for (var i = 0; i < parts.length; i += 1) { + builder.append(parts[i]); + } + return builder.getBlob(properties.type); + } +} + +// This is CommonJS because lie is an external dependency, so Rollup +// can just ignore it. +if (typeof Promise === 'undefined' && typeof _dereq_ !== 'undefined') { + _dereq_('lie/polyfill'); +} +var Promise$1 = Promise; + +function executeCallback(promise, callback) { + if (callback) { + promise.then(function (result) { + callback(null, result); + }, function (error) { + callback(error); + }); + } +} + +// Some code originally from async_storage.js in +// [Gaia](https://github.com/mozilla-b2g/gaia). + +var DETECT_BLOB_SUPPORT_STORE = 'local-forage-detect-blob-support'; +var supportsBlobs; +var dbContexts; + +// Transform a binary string to an array buffer, because otherwise +// weird stuff happens when you try to work with the binary string directly. +// It is known. +// From http://stackoverflow.com/questions/14967647/ (continues on next line) +// encode-decode-image-with-base64-breaks-image (2013-04-21) +function _binStringToArrayBuffer(bin) { + var length = bin.length; + var buf = new ArrayBuffer(length); + var arr = new Uint8Array(buf); + for (var i = 0; i < length; i++) { + arr[i] = bin.charCodeAt(i); + } + return buf; +} + +// +// Blobs are not supported in all versions of IndexedDB, notably +// Chrome <37 and Android <5. In those versions, storing a blob will throw. +// +// Various other blob bugs exist in Chrome v37-42 (inclusive). +// Detecting them is expensive and confusing to users, and Chrome 37-42 +// is at very low usage worldwide, so we do a hacky userAgent check instead. +// +// content-type bug: https://code.google.com/p/chromium/issues/detail?id=408120 +// 404 bug: https://code.google.com/p/chromium/issues/detail?id=447916 +// FileReader bug: https://code.google.com/p/chromium/issues/detail?id=447836 +// +// Code borrowed from PouchDB. See: +// https://github.com/pouchdb/pouchdb/blob/9c25a23/src/adapters/idb/blobSupport.js +// +function _checkBlobSupportWithoutCaching(txn) { + return new Promise$1(function (resolve) { + var blob = createBlob(['']); + txn.objectStore(DETECT_BLOB_SUPPORT_STORE).put(blob, 'key'); + + txn.onabort = function (e) { + // If the transaction aborts now its due to not being able to + // write to the database, likely due to the disk being full + e.preventDefault(); + e.stopPropagation(); + resolve(false); + }; + + txn.oncomplete = function () { + var matchedChrome = navigator.userAgent.match(/Chrome\/(\d+)/); + var matchedEdge = navigator.userAgent.match(/Edge\//); + // MS Edge pretends to be Chrome 42: + // https://msdn.microsoft.com/en-us/library/hh869301%28v=vs.85%29.aspx + resolve(matchedEdge || !matchedChrome || parseInt(matchedChrome[1], 10) >= 43); + }; + })["catch"](function () { + return false; // error, so assume unsupported + }); +} + +function _checkBlobSupport(idb) { + if (typeof supportsBlobs === 'boolean') { + return Promise$1.resolve(supportsBlobs); + } + return _checkBlobSupportWithoutCaching(idb).then(function (value) { + supportsBlobs = value; + return supportsBlobs; + }); +} + +function _deferReadiness(dbInfo) { + var dbContext = dbContexts[dbInfo.name]; + + // Create a deferred object representing the current database operation. + var deferredOperation = {}; + + deferredOperation.promise = new Promise$1(function (resolve) { + deferredOperation.resolve = resolve; + }); + + // Enqueue the deferred operation. + dbContext.deferredOperations.push(deferredOperation); + + // Chain its promise to the database readiness. + if (!dbContext.dbReady) { + dbContext.dbReady = deferredOperation.promise; + } else { + dbContext.dbReady = dbContext.dbReady.then(function () { + return deferredOperation.promise; + }); + } +} + +function _advanceReadiness(dbInfo) { + var dbContext = dbContexts[dbInfo.name]; + + // Dequeue a deferred operation. + var deferredOperation = dbContext.deferredOperations.pop(); + + // Resolve its promise (which is part of the database readiness + // chain of promises). + if (deferredOperation) { + deferredOperation.resolve(); + } +} + +function _getConnection(dbInfo, upgradeNeeded) { + return new Promise$1(function (resolve, reject) { + + if (dbInfo.db) { + if (upgradeNeeded) { + _deferReadiness(dbInfo); + dbInfo.db.close(); + } else { + return resolve(dbInfo.db); + } + } + + var dbArgs = [dbInfo.name]; + + if (upgradeNeeded) { + dbArgs.push(dbInfo.version); + } + + var openreq = idb.open.apply(idb, dbArgs); + + if (upgradeNeeded) { + openreq.onupgradeneeded = function (e) { + var db = openreq.result; + try { + db.createObjectStore(dbInfo.storeName); + if (e.oldVersion <= 1) { + // Added when support for blob shims was added + db.createObjectStore(DETECT_BLOB_SUPPORT_STORE); + } + } catch (ex) { + if (ex.name === 'ConstraintError') { + console.warn('The database "' + dbInfo.name + '"' + ' has been upgraded from version ' + e.oldVersion + ' to version ' + e.newVersion + ', but the storage "' + dbInfo.storeName + '" already exists.'); + } else { + throw ex; + } + } + }; + } + + openreq.onerror = function () { + reject(openreq.error); + }; + + openreq.onsuccess = function () { + resolve(openreq.result); + _advanceReadiness(dbInfo); + }; + }); +} + +function _getOriginalConnection(dbInfo) { + return _getConnection(dbInfo, false); +} + +function _getUpgradedConnection(dbInfo) { + return _getConnection(dbInfo, true); +} + +function _isUpgradeNeeded(dbInfo, defaultVersion) { + if (!dbInfo.db) { + return true; + } + + var isNewStore = !dbInfo.db.objectStoreNames.contains(dbInfo.storeName); + var isDowngrade = dbInfo.version < dbInfo.db.version; + var isUpgrade = dbInfo.version > dbInfo.db.version; + + if (isDowngrade) { + // If the version is not the default one + // then warn for impossible downgrade. + if (dbInfo.version !== defaultVersion) { + console.warn('The database "' + dbInfo.name + '"' + ' can\'t be downgraded from version ' + dbInfo.db.version + ' to version ' + dbInfo.version + '.'); + } + // Align the versions to prevent errors. + dbInfo.version = dbInfo.db.version; + } + + if (isUpgrade || isNewStore) { + // If the store is new then increment the version (if needed). + // This will trigger an "upgradeneeded" event which is required + // for creating a store. + if (isNewStore) { + var incVersion = dbInfo.db.version + 1; + if (incVersion > dbInfo.version) { + dbInfo.version = incVersion; + } + } + + return true; + } + + return false; +} + +// encode a blob for indexeddb engines that don't support blobs +function _encodeBlob(blob) { + return new Promise$1(function (resolve, reject) { + var reader = new FileReader(); + reader.onerror = reject; + reader.onloadend = function (e) { + var base64 = btoa(e.target.result || ''); + resolve({ + __local_forage_encoded_blob: true, + data: base64, + type: blob.type + }); + }; + reader.readAsBinaryString(blob); + }); +} + +// decode an encoded blob +function _decodeBlob(encodedBlob) { + var arrayBuff = _binStringToArrayBuffer(atob(encodedBlob.data)); + return createBlob([arrayBuff], { type: encodedBlob.type }); +} + +// is this one of our fancy encoded blobs? +function _isEncodedBlob(value) { + return value && value.__local_forage_encoded_blob; +} + +// Specialize the default `ready()` function by making it dependent +// on the current database operations. Thus, the driver will be actually +// ready when it's been initialized (default) *and* there are no pending +// operations on the database (initiated by some other instances). +function _fullyReady(callback) { + var self = this; + + var promise = self._initReady().then(function () { + var dbContext = dbContexts[self._dbInfo.name]; + + if (dbContext && dbContext.dbReady) { + return dbContext.dbReady; + } + }); + + promise.then(callback, callback); + return promise; +} + +// Open the IndexedDB database (automatically creates one if one didn't +// previously exist), using any options set in the config. +function _initStorage(options) { + var self = this; + var dbInfo = { + db: null + }; + + if (options) { + for (var i in options) { + dbInfo[i] = options[i]; + } + } + + // Initialize a singleton container for all running localForages. + if (!dbContexts) { + dbContexts = {}; + } + + // Get the current context of the database; + var dbContext = dbContexts[dbInfo.name]; + + // ...or create a new context. + if (!dbContext) { + dbContext = { + // Running localForages sharing a database. + forages: [], + // Shared database. + db: null, + // Database readiness (promise). + dbReady: null, + // Deferred operations on the database. + deferredOperations: [] + }; + // Register the new context in the global container. + dbContexts[dbInfo.name] = dbContext; + } + + // Register itself as a running localForage in the current context. + dbContext.forages.push(self); + + // Replace the default `ready()` function with the specialized one. + if (!self._initReady) { + self._initReady = self.ready; + self.ready = _fullyReady; + } + + // Create an array of initialization states of the related localForages. + var initPromises = []; + + function ignoreErrors() { + // Don't handle errors here, + // just makes sure related localForages aren't pending. + return Promise$1.resolve(); + } + + for (var j = 0; j < dbContext.forages.length; j++) { + var forage = dbContext.forages[j]; + if (forage !== self) { + // Don't wait for itself... + initPromises.push(forage._initReady()["catch"](ignoreErrors)); + } + } + + // Take a snapshot of the related localForages. + var forages = dbContext.forages.slice(0); + + // Initialize the connection process only when + // all the related localForages aren't pending. + return Promise$1.all(initPromises).then(function () { + dbInfo.db = dbContext.db; + // Get the connection or open a new one without upgrade. + return _getOriginalConnection(dbInfo); + }).then(function (db) { + dbInfo.db = db; + if (_isUpgradeNeeded(dbInfo, self._defaultConfig.version)) { + // Reopen the database for upgrading. + return _getUpgradedConnection(dbInfo); + } + return db; + }).then(function (db) { + dbInfo.db = dbContext.db = db; + self._dbInfo = dbInfo; + // Share the final connection amongst related localForages. + for (var k = 0; k < forages.length; k++) { + var forage = forages[k]; + if (forage !== self) { + // Self is already up-to-date. + forage._dbInfo.db = dbInfo.db; + forage._dbInfo.version = dbInfo.version; + } + } + }); +} + +function getItem(key, callback) { + var self = this; + + // Cast the key to a string, as that's all we can set as a key. + if (typeof key !== 'string') { + console.warn(key + ' used as a key, but it is not a string.'); + key = String(key); + } + + var promise = new Promise$1(function (resolve, reject) { + self.ready().then(function () { + var dbInfo = self._dbInfo; + var store = dbInfo.db.transaction(dbInfo.storeName, 'readonly').objectStore(dbInfo.storeName); + var req = store.get(key); + + req.onsuccess = function () { + var value = req.result; + if (value === undefined) { + value = null; + } + if (_isEncodedBlob(value)) { + value = _decodeBlob(value); + } + resolve(value); + }; + + req.onerror = function () { + reject(req.error); + }; + })["catch"](reject); + }); + + executeCallback(promise, callback); + return promise; +} + +// Iterate over all items stored in database. +function iterate(iterator, callback) { + var self = this; + + var promise = new Promise$1(function (resolve, reject) { + self.ready().then(function () { + var dbInfo = self._dbInfo; + var store = dbInfo.db.transaction(dbInfo.storeName, 'readonly').objectStore(dbInfo.storeName); + + var req = store.openCursor(); + var iterationNumber = 1; + + req.onsuccess = function () { + var cursor = req.result; + + if (cursor) { + var value = cursor.value; + if (_isEncodedBlob(value)) { + value = _decodeBlob(value); + } + var result = iterator(value, cursor.key, iterationNumber++); + + if (result !== void 0) { + resolve(result); + } else { + cursor["continue"](); + } + } else { + resolve(); + } + }; + + req.onerror = function () { + reject(req.error); + }; + })["catch"](reject); + }); + + executeCallback(promise, callback); + + return promise; +} + +function setItem(key, value, callback) { + var self = this; + + // Cast the key to a string, as that's all we can set as a key. + if (typeof key !== 'string') { + console.warn(key + ' used as a key, but it is not a string.'); + key = String(key); + } + + var promise = new Promise$1(function (resolve, reject) { + var dbInfo; + self.ready().then(function () { + dbInfo = self._dbInfo; + if (value instanceof Blob) { + return _checkBlobSupport(dbInfo.db).then(function (blobSupport) { + if (blobSupport) { + return value; + } + return _encodeBlob(value); + }); + } + return value; + }).then(function (value) { + var transaction = dbInfo.db.transaction(dbInfo.storeName, 'readwrite'); + var store = transaction.objectStore(dbInfo.storeName); + + // The reason we don't _save_ null is because IE 10 does + // not support saving the `null` type in IndexedDB. How + // ironic, given the bug below! + // See: https://github.com/mozilla/localForage/issues/161 + if (value === null) { + value = undefined; + } + + transaction.oncomplete = function () { + // Cast to undefined so the value passed to + // callback/promise is the same as what one would get out + // of `getItem()` later. This leads to some weirdness + // (setItem('foo', undefined) will return `null`), but + // it's not my fault localStorage is our baseline and that + // it's weird. + if (value === undefined) { + value = null; + } + + resolve(value); + }; + transaction.onabort = transaction.onerror = function () { + var err = req.error ? req.error : req.transaction.error; + reject(err); + }; + + var req = store.put(value, key); + })["catch"](reject); + }); + + executeCallback(promise, callback); + return promise; +} + +function removeItem(key, callback) { + var self = this; + + // Cast the key to a string, as that's all we can set as a key. + if (typeof key !== 'string') { + console.warn(key + ' used as a key, but it is not a string.'); + key = String(key); + } + + var promise = new Promise$1(function (resolve, reject) { + self.ready().then(function () { + var dbInfo = self._dbInfo; + var transaction = dbInfo.db.transaction(dbInfo.storeName, 'readwrite'); + var store = transaction.objectStore(dbInfo.storeName); + + // We use a Grunt task to make this safe for IE and some + // versions of Android (including those used by Cordova). + // Normally IE won't like `.delete()` and will insist on + // using `['delete']()`, but we have a build step that + // fixes this for us now. + var req = store["delete"](key); + transaction.oncomplete = function () { + resolve(); + }; + + transaction.onerror = function () { + reject(req.error); + }; + + // The request will be also be aborted if we've exceeded our storage + // space. + transaction.onabort = function () { + var err = req.error ? req.error : req.transaction.error; + reject(err); + }; + })["catch"](reject); + }); + + executeCallback(promise, callback); + return promise; +} + +function clear(callback) { + var self = this; + + var promise = new Promise$1(function (resolve, reject) { + self.ready().then(function () { + var dbInfo = self._dbInfo; + var transaction = dbInfo.db.transaction(dbInfo.storeName, 'readwrite'); + var store = transaction.objectStore(dbInfo.storeName); + var req = store.clear(); + + transaction.oncomplete = function () { + resolve(); + }; + + transaction.onabort = transaction.onerror = function () { + var err = req.error ? req.error : req.transaction.error; + reject(err); + }; + })["catch"](reject); + }); + + executeCallback(promise, callback); + return promise; +} + +function length(callback) { + var self = this; + + var promise = new Promise$1(function (resolve, reject) { + self.ready().then(function () { + var dbInfo = self._dbInfo; + var store = dbInfo.db.transaction(dbInfo.storeName, 'readonly').objectStore(dbInfo.storeName); + var req = store.count(); + + req.onsuccess = function () { + resolve(req.result); + }; + + req.onerror = function () { + reject(req.error); + }; + })["catch"](reject); + }); + + executeCallback(promise, callback); + return promise; +} + +function key(n, callback) { + var self = this; + + var promise = new Promise$1(function (resolve, reject) { + if (n < 0) { + resolve(null); + + return; + } + + self.ready().then(function () { + var dbInfo = self._dbInfo; + var store = dbInfo.db.transaction(dbInfo.storeName, 'readonly').objectStore(dbInfo.storeName); + + var advanced = false; + var req = store.openCursor(); + req.onsuccess = function () { + var cursor = req.result; + if (!cursor) { + // this means there weren't enough keys + resolve(null); + + return; + } + + if (n === 0) { + // We have the first key, return it if that's what they + // wanted. + resolve(cursor.key); + } else { + if (!advanced) { + // Otherwise, ask the cursor to skip ahead n + // records. + advanced = true; + cursor.advance(n); + } else { + // When we get here, we've got the nth key. + resolve(cursor.key); + } + } + }; + + req.onerror = function () { + reject(req.error); + }; + })["catch"](reject); + }); + + executeCallback(promise, callback); + return promise; +} + +function keys(callback) { + var self = this; + + var promise = new Promise$1(function (resolve, reject) { + self.ready().then(function () { + var dbInfo = self._dbInfo; + var store = dbInfo.db.transaction(dbInfo.storeName, 'readonly').objectStore(dbInfo.storeName); + + var req = store.openCursor(); + var keys = []; + + req.onsuccess = function () { + var cursor = req.result; + + if (!cursor) { + resolve(keys); + return; + } + + keys.push(cursor.key); + cursor["continue"](); + }; + + req.onerror = function () { + reject(req.error); + }; + })["catch"](reject); + }); + + executeCallback(promise, callback); + return promise; +} + +var asyncStorage = { + _driver: 'asyncStorage', + _initStorage: _initStorage, + iterate: iterate, + getItem: getItem, + setItem: setItem, + removeItem: removeItem, + clear: clear, + length: length, + key: key, + keys: keys +}; + +// Sadly, the best way to save binary data in WebSQL/localStorage is serializing +// it to Base64, so this is how we store it to prevent very strange errors with less +// verbose ways of binary <-> string data storage. +var BASE_CHARS = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'; + +var BLOB_TYPE_PREFIX = '~~local_forage_type~'; +var BLOB_TYPE_PREFIX_REGEX = /^~~local_forage_type~([^~]+)~/; + +var SERIALIZED_MARKER = '__lfsc__:'; +var SERIALIZED_MARKER_LENGTH = SERIALIZED_MARKER.length; + +// OMG the serializations! +var TYPE_ARRAYBUFFER = 'arbf'; +var TYPE_BLOB = 'blob'; +var TYPE_INT8ARRAY = 'si08'; +var TYPE_UINT8ARRAY = 'ui08'; +var TYPE_UINT8CLAMPEDARRAY = 'uic8'; +var TYPE_INT16ARRAY = 'si16'; +var TYPE_INT32ARRAY = 'si32'; +var TYPE_UINT16ARRAY = 'ur16'; +var TYPE_UINT32ARRAY = 'ui32'; +var TYPE_FLOAT32ARRAY = 'fl32'; +var TYPE_FLOAT64ARRAY = 'fl64'; +var TYPE_SERIALIZED_MARKER_LENGTH = SERIALIZED_MARKER_LENGTH + TYPE_ARRAYBUFFER.length; + +function stringToBuffer(serializedString) { + // Fill the string into a ArrayBuffer. + var bufferLength = serializedString.length * 0.75; + var len = serializedString.length; + var i; + var p = 0; + var encoded1, encoded2, encoded3, encoded4; + + if (serializedString[serializedString.length - 1] === '=') { + bufferLength--; + if (serializedString[serializedString.length - 2] === '=') { + bufferLength--; + } + } + + var buffer = new ArrayBuffer(bufferLength); + var bytes = new Uint8Array(buffer); + + for (i = 0; i < len; i += 4) { + encoded1 = BASE_CHARS.indexOf(serializedString[i]); + encoded2 = BASE_CHARS.indexOf(serializedString[i + 1]); + encoded3 = BASE_CHARS.indexOf(serializedString[i + 2]); + encoded4 = BASE_CHARS.indexOf(serializedString[i + 3]); + + /*jslint bitwise: true */ + bytes[p++] = encoded1 << 2 | encoded2 >> 4; + bytes[p++] = (encoded2 & 15) << 4 | encoded3 >> 2; + bytes[p++] = (encoded3 & 3) << 6 | encoded4 & 63; + } + return buffer; +} + +// Converts a buffer to a string to store, serialized, in the backend +// storage library. +function bufferToString(buffer) { + // base64-arraybuffer + var bytes = new Uint8Array(buffer); + var base64String = ''; + var i; + + for (i = 0; i < bytes.length; i += 3) { + /*jslint bitwise: true */ + base64String += BASE_CHARS[bytes[i] >> 2]; + base64String += BASE_CHARS[(bytes[i] & 3) << 4 | bytes[i + 1] >> 4]; + base64String += BASE_CHARS[(bytes[i + 1] & 15) << 2 | bytes[i + 2] >> 6]; + base64String += BASE_CHARS[bytes[i + 2] & 63]; + } + + if (bytes.length % 3 === 2) { + base64String = base64String.substring(0, base64String.length - 1) + '='; + } else if (bytes.length % 3 === 1) { + base64String = base64String.substring(0, base64String.length - 2) + '=='; + } + + return base64String; +} + +// Serialize a value, afterwards executing a callback (which usually +// instructs the `setItem()` callback/promise to be executed). This is how +// we store binary data with localStorage. +function serialize(value, callback) { + var valueString = ''; + if (value) { + valueString = value.toString(); + } + + // Cannot use `value instanceof ArrayBuffer` or such here, as these + // checks fail when running the tests using casper.js... + // + // TODO: See why those tests fail and use a better solution. + if (value && (value.toString() === '[object ArrayBuffer]' || value.buffer && value.buffer.toString() === '[object ArrayBuffer]')) { + // Convert binary arrays to a string and prefix the string with + // a special marker. + var buffer; + var marker = SERIALIZED_MARKER; + + if (value instanceof ArrayBuffer) { + buffer = value; + marker += TYPE_ARRAYBUFFER; + } else { + buffer = value.buffer; + + if (valueString === '[object Int8Array]') { + marker += TYPE_INT8ARRAY; + } else if (valueString === '[object Uint8Array]') { + marker += TYPE_UINT8ARRAY; + } else if (valueString === '[object Uint8ClampedArray]') { + marker += TYPE_UINT8CLAMPEDARRAY; + } else if (valueString === '[object Int16Array]') { + marker += TYPE_INT16ARRAY; + } else if (valueString === '[object Uint16Array]') { + marker += TYPE_UINT16ARRAY; + } else if (valueString === '[object Int32Array]') { + marker += TYPE_INT32ARRAY; + } else if (valueString === '[object Uint32Array]') { + marker += TYPE_UINT32ARRAY; + } else if (valueString === '[object Float32Array]') { + marker += TYPE_FLOAT32ARRAY; + } else if (valueString === '[object Float64Array]') { + marker += TYPE_FLOAT64ARRAY; + } else { + callback(new Error('Failed to get type for BinaryArray')); + } + } + + callback(marker + bufferToString(buffer)); + } else if (valueString === '[object Blob]') { + // Conver the blob to a binaryArray and then to a string. + var fileReader = new FileReader(); + + fileReader.onload = function () { + // Backwards-compatible prefix for the blob type. + var str = BLOB_TYPE_PREFIX + value.type + '~' + bufferToString(this.result); + + callback(SERIALIZED_MARKER + TYPE_BLOB + str); + }; + + fileReader.readAsArrayBuffer(value); + } else { + try { + callback(JSON.stringify(value)); + } catch (e) { + console.error("Couldn't convert value into a JSON string: ", value); + + callback(null, e); + } + } +} + +// Deserialize data we've inserted into a value column/field. We place +// special markers into our strings to mark them as encoded; this isn't +// as nice as a meta field, but it's the only sane thing we can do whilst +// keeping localStorage support intact. +// +// Oftentimes this will just deserialize JSON content, but if we have a +// special marker (SERIALIZED_MARKER, defined above), we will extract +// some kind of arraybuffer/binary data/typed array out of the string. +function deserialize(value) { + // If we haven't marked this string as being specially serialized (i.e. + // something other than serialized JSON), we can just return it and be + // done with it. + if (value.substring(0, SERIALIZED_MARKER_LENGTH) !== SERIALIZED_MARKER) { + return JSON.parse(value); + } + + // The following code deals with deserializing some kind of Blob or + // TypedArray. First we separate out the type of data we're dealing + // with from the data itself. + var serializedString = value.substring(TYPE_SERIALIZED_MARKER_LENGTH); + var type = value.substring(SERIALIZED_MARKER_LENGTH, TYPE_SERIALIZED_MARKER_LENGTH); + + var blobType; + // Backwards-compatible blob type serialization strategy. + // DBs created with older versions of localForage will simply not have the blob type. + if (type === TYPE_BLOB && BLOB_TYPE_PREFIX_REGEX.test(serializedString)) { + var matcher = serializedString.match(BLOB_TYPE_PREFIX_REGEX); + blobType = matcher[1]; + serializedString = serializedString.substring(matcher[0].length); + } + var buffer = stringToBuffer(serializedString); + + // Return the right type based on the code/type set during + // serialization. + switch (type) { + case TYPE_ARRAYBUFFER: + return buffer; + case TYPE_BLOB: + return createBlob([buffer], { type: blobType }); + case TYPE_INT8ARRAY: + return new Int8Array(buffer); + case TYPE_UINT8ARRAY: + return new Uint8Array(buffer); + case TYPE_UINT8CLAMPEDARRAY: + return new Uint8ClampedArray(buffer); + case TYPE_INT16ARRAY: + return new Int16Array(buffer); + case TYPE_UINT16ARRAY: + return new Uint16Array(buffer); + case TYPE_INT32ARRAY: + return new Int32Array(buffer); + case TYPE_UINT32ARRAY: + return new Uint32Array(buffer); + case TYPE_FLOAT32ARRAY: + return new Float32Array(buffer); + case TYPE_FLOAT64ARRAY: + return new Float64Array(buffer); + default: + throw new Error('Unkown type: ' + type); + } +} + +var localforageSerializer = { + serialize: serialize, + deserialize: deserialize, + stringToBuffer: stringToBuffer, + bufferToString: bufferToString +}; + +/* + * Includes code from: + * + * base64-arraybuffer + * https://github.com/niklasvh/base64-arraybuffer + * + * Copyright (c) 2012 Niklas von Hertzen + * Licensed under the MIT license. + */ +// Open the WebSQL database (automatically creates one if one didn't +// previously exist), using any options set in the config. +function _initStorage$1(options) { + var self = this; + var dbInfo = { + db: null + }; + + if (options) { + for (var i in options) { + dbInfo[i] = typeof options[i] !== 'string' ? options[i].toString() : options[i]; + } + } + + var dbInfoPromise = new Promise$1(function (resolve, reject) { + // Open the database; the openDatabase API will automatically + // create it for us if it doesn't exist. + try { + dbInfo.db = openDatabase(dbInfo.name, String(dbInfo.version), dbInfo.description, dbInfo.size); + } catch (e) { + return reject(e); + } + + // Create our key/value table if it doesn't exist. + dbInfo.db.transaction(function (t) { + t.executeSql('CREATE TABLE IF NOT EXISTS ' + dbInfo.storeName + ' (id INTEGER PRIMARY KEY, key unique, value)', [], function () { + self._dbInfo = dbInfo; + resolve(); + }, function (t, error) { + reject(error); + }); + }); + }); + + dbInfo.serializer = localforageSerializer; + return dbInfoPromise; +} + +function getItem$1(key, callback) { + var self = this; + + // Cast the key to a string, as that's all we can set as a key. + if (typeof key !== 'string') { + console.warn(key + ' used as a key, but it is not a string.'); + key = String(key); + } + + var promise = new Promise$1(function (resolve, reject) { + self.ready().then(function () { + var dbInfo = self._dbInfo; + dbInfo.db.transaction(function (t) { + t.executeSql('SELECT * FROM ' + dbInfo.storeName + ' WHERE key = ? LIMIT 1', [key], function (t, results) { + var result = results.rows.length ? results.rows.item(0).value : null; + + // Check to see if this is serialized content we need to + // unpack. + if (result) { + result = dbInfo.serializer.deserialize(result); + } + + resolve(result); + }, function (t, error) { + + reject(error); + }); + }); + })["catch"](reject); + }); + + executeCallback(promise, callback); + return promise; +} + +function iterate$1(iterator, callback) { + var self = this; + + var promise = new Promise$1(function (resolve, reject) { + self.ready().then(function () { + var dbInfo = self._dbInfo; + + dbInfo.db.transaction(function (t) { + t.executeSql('SELECT * FROM ' + dbInfo.storeName, [], function (t, results) { + var rows = results.rows; + var length = rows.length; + + for (var i = 0; i < length; i++) { + var item = rows.item(i); + var result = item.value; + + // Check to see if this is serialized content + // we need to unpack. + if (result) { + result = dbInfo.serializer.deserialize(result); + } + + result = iterator(result, item.key, i + 1); + + // void(0) prevents problems with redefinition + // of `undefined`. + if (result !== void 0) { + resolve(result); + return; + } + } + + resolve(); + }, function (t, error) { + reject(error); + }); + }); + })["catch"](reject); + }); + + executeCallback(promise, callback); + return promise; +} + +function setItem$1(key, value, callback) { + var self = this; + + // Cast the key to a string, as that's all we can set as a key. + if (typeof key !== 'string') { + console.warn(key + ' used as a key, but it is not a string.'); + key = String(key); + } + + var promise = new Promise$1(function (resolve, reject) { + self.ready().then(function () { + // The localStorage API doesn't return undefined values in an + // "expected" way, so undefined is always cast to null in all + // drivers. See: https://github.com/mozilla/localForage/pull/42 + if (value === undefined) { + value = null; + } + + // Save the original value to pass to the callback. + var originalValue = value; + + var dbInfo = self._dbInfo; + dbInfo.serializer.serialize(value, function (value, error) { + if (error) { + reject(error); + } else { + dbInfo.db.transaction(function (t) { + t.executeSql('INSERT OR REPLACE INTO ' + dbInfo.storeName + ' (key, value) VALUES (?, ?)', [key, value], function () { + resolve(originalValue); + }, function (t, error) { + reject(error); + }); + }, function (sqlError) { + // The transaction failed; check + // to see if it's a quota error. + if (sqlError.code === sqlError.QUOTA_ERR) { + // We reject the callback outright for now, but + // it's worth trying to re-run the transaction. + // Even if the user accepts the prompt to use + // more storage on Safari, this error will + // be called. + // + // TODO: Try to re-run the transaction. + reject(sqlError); + } + }); + } + }); + })["catch"](reject); + }); + + executeCallback(promise, callback); + return promise; +} + +function removeItem$1(key, callback) { + var self = this; + + // Cast the key to a string, as that's all we can set as a key. + if (typeof key !== 'string') { + console.warn(key + ' used as a key, but it is not a string.'); + key = String(key); + } + + var promise = new Promise$1(function (resolve, reject) { + self.ready().then(function () { + var dbInfo = self._dbInfo; + dbInfo.db.transaction(function (t) { + t.executeSql('DELETE FROM ' + dbInfo.storeName + ' WHERE key = ?', [key], function () { + resolve(); + }, function (t, error) { + + reject(error); + }); + }); + })["catch"](reject); + }); + + executeCallback(promise, callback); + return promise; +} + +// Deletes every item in the table. +// TODO: Find out if this resets the AUTO_INCREMENT number. +function clear$1(callback) { + var self = this; + + var promise = new Promise$1(function (resolve, reject) { + self.ready().then(function () { + var dbInfo = self._dbInfo; + dbInfo.db.transaction(function (t) { + t.executeSql('DELETE FROM ' + dbInfo.storeName, [], function () { + resolve(); + }, function (t, error) { + reject(error); + }); + }); + })["catch"](reject); + }); + + executeCallback(promise, callback); + return promise; +} + +// Does a simple `COUNT(key)` to get the number of items stored in +// localForage. +function length$1(callback) { + var self = this; + + var promise = new Promise$1(function (resolve, reject) { + self.ready().then(function () { + var dbInfo = self._dbInfo; + dbInfo.db.transaction(function (t) { + // Ahhh, SQL makes this one soooooo easy. + t.executeSql('SELECT COUNT(key) as c FROM ' + dbInfo.storeName, [], function (t, results) { + var result = results.rows.item(0).c; + + resolve(result); + }, function (t, error) { + + reject(error); + }); + }); + })["catch"](reject); + }); + + executeCallback(promise, callback); + return promise; +} + +// Return the key located at key index X; essentially gets the key from a +// `WHERE id = ?`. This is the most efficient way I can think to implement +// this rarely-used (in my experience) part of the API, but it can seem +// inconsistent, because we do `INSERT OR REPLACE INTO` on `setItem()`, so +// the ID of each key will change every time it's updated. Perhaps a stored +// procedure for the `setItem()` SQL would solve this problem? +// TODO: Don't change ID on `setItem()`. +function key$1(n, callback) { + var self = this; + + var promise = new Promise$1(function (resolve, reject) { + self.ready().then(function () { + var dbInfo = self._dbInfo; + dbInfo.db.transaction(function (t) { + t.executeSql('SELECT key FROM ' + dbInfo.storeName + ' WHERE id = ? LIMIT 1', [n + 1], function (t, results) { + var result = results.rows.length ? results.rows.item(0).key : null; + resolve(result); + }, function (t, error) { + reject(error); + }); + }); + })["catch"](reject); + }); + + executeCallback(promise, callback); + return promise; +} + +function keys$1(callback) { + var self = this; + + var promise = new Promise$1(function (resolve, reject) { + self.ready().then(function () { + var dbInfo = self._dbInfo; + dbInfo.db.transaction(function (t) { + t.executeSql('SELECT key FROM ' + dbInfo.storeName, [], function (t, results) { + var keys = []; + + for (var i = 0; i < results.rows.length; i++) { + keys.push(results.rows.item(i).key); + } + + resolve(keys); + }, function (t, error) { + + reject(error); + }); + }); + })["catch"](reject); + }); + + executeCallback(promise, callback); + return promise; +} + +var webSQLStorage = { + _driver: 'webSQLStorage', + _initStorage: _initStorage$1, + iterate: iterate$1, + getItem: getItem$1, + setItem: setItem$1, + removeItem: removeItem$1, + clear: clear$1, + length: length$1, + key: key$1, + keys: keys$1 +}; + +// Config the localStorage backend, using options set in the config. +function _initStorage$2(options) { + var self = this; + var dbInfo = {}; + if (options) { + for (var i in options) { + dbInfo[i] = options[i]; + } + } + + dbInfo.keyPrefix = dbInfo.name + '/'; + + if (dbInfo.storeName !== self._defaultConfig.storeName) { + dbInfo.keyPrefix += dbInfo.storeName + '/'; + } + + self._dbInfo = dbInfo; + dbInfo.serializer = localforageSerializer; + + return Promise$1.resolve(); +} + +// Remove all keys from the datastore, effectively destroying all data in +// the app's key/value store! +function clear$2(callback) { + var self = this; + var promise = self.ready().then(function () { + var keyPrefix = self._dbInfo.keyPrefix; + + for (var i = localStorage.length - 1; i >= 0; i--) { + var key = localStorage.key(i); + + if (key.indexOf(keyPrefix) === 0) { + localStorage.removeItem(key); + } + } + }); + + executeCallback(promise, callback); + return promise; +} + +// Retrieve an item from the store. Unlike the original async_storage +// library in Gaia, we don't modify return values at all. If a key's value +// is `undefined`, we pass that value to the callback function. +function getItem$2(key, callback) { + var self = this; + + // Cast the key to a string, as that's all we can set as a key. + if (typeof key !== 'string') { + console.warn(key + ' used as a key, but it is not a string.'); + key = String(key); + } + + var promise = self.ready().then(function () { + var dbInfo = self._dbInfo; + var result = localStorage.getItem(dbInfo.keyPrefix + key); + + // If a result was found, parse it from the serialized + // string into a JS object. If result isn't truthy, the key + // is likely undefined and we'll pass it straight to the + // callback. + if (result) { + result = dbInfo.serializer.deserialize(result); + } + + return result; + }); + + executeCallback(promise, callback); + return promise; +} + +// Iterate over all items in the store. +function iterate$2(iterator, callback) { + var self = this; + + var promise = self.ready().then(function () { + var dbInfo = self._dbInfo; + var keyPrefix = dbInfo.keyPrefix; + var keyPrefixLength = keyPrefix.length; + var length = localStorage.length; + + // We use a dedicated iterator instead of the `i` variable below + // so other keys we fetch in localStorage aren't counted in + // the `iterationNumber` argument passed to the `iterate()` + // callback. + // + // See: github.com/mozilla/localForage/pull/435#discussion_r38061530 + var iterationNumber = 1; + + for (var i = 0; i < length; i++) { + var key = localStorage.key(i); + if (key.indexOf(keyPrefix) !== 0) { + continue; + } + var value = localStorage.getItem(key); + + // If a result was found, parse it from the serialized + // string into a JS object. If result isn't truthy, the + // key is likely undefined and we'll pass it straight + // to the iterator. + if (value) { + value = dbInfo.serializer.deserialize(value); + } + + value = iterator(value, key.substring(keyPrefixLength), iterationNumber++); + + if (value !== void 0) { + return value; + } + } + }); + + executeCallback(promise, callback); + return promise; +} + +// Same as localStorage's key() method, except takes a callback. +function key$2(n, callback) { + var self = this; + var promise = self.ready().then(function () { + var dbInfo = self._dbInfo; + var result; + try { + result = localStorage.key(n); + } catch (error) { + result = null; + } + + // Remove the prefix from the key, if a key is found. + if (result) { + result = result.substring(dbInfo.keyPrefix.length); + } + + return result; + }); + + executeCallback(promise, callback); + return promise; +} + +function keys$2(callback) { + var self = this; + var promise = self.ready().then(function () { + var dbInfo = self._dbInfo; + var length = localStorage.length; + var keys = []; + + for (var i = 0; i < length; i++) { + if (localStorage.key(i).indexOf(dbInfo.keyPrefix) === 0) { + keys.push(localStorage.key(i).substring(dbInfo.keyPrefix.length)); + } + } + + return keys; + }); + + executeCallback(promise, callback); + return promise; +} + +// Supply the number of keys in the datastore to the callback function. +function length$2(callback) { + var self = this; + var promise = self.keys().then(function (keys) { + return keys.length; + }); + + executeCallback(promise, callback); + return promise; +} + +// Remove an item from the store, nice and simple. +function removeItem$2(key, callback) { + var self = this; + + // Cast the key to a string, as that's all we can set as a key. + if (typeof key !== 'string') { + console.warn(key + ' used as a key, but it is not a string.'); + key = String(key); + } + + var promise = self.ready().then(function () { + var dbInfo = self._dbInfo; + localStorage.removeItem(dbInfo.keyPrefix + key); + }); + + executeCallback(promise, callback); + return promise; +} + +// Set a key's value and run an optional callback once the value is set. +// Unlike Gaia's implementation, the callback function is passed the value, +// in case you want to operate on that value only after you're sure it +// saved, or something like that. +function setItem$2(key, value, callback) { + var self = this; + + // Cast the key to a string, as that's all we can set as a key. + if (typeof key !== 'string') { + console.warn(key + ' used as a key, but it is not a string.'); + key = String(key); + } + + var promise = self.ready().then(function () { + // Convert undefined values to null. + // https://github.com/mozilla/localForage/pull/42 + if (value === undefined) { + value = null; + } + + // Save the original value to pass to the callback. + var originalValue = value; + + return new Promise$1(function (resolve, reject) { + var dbInfo = self._dbInfo; + dbInfo.serializer.serialize(value, function (value, error) { + if (error) { + reject(error); + } else { + try { + localStorage.setItem(dbInfo.keyPrefix + key, value); + resolve(originalValue); + } catch (e) { + // localStorage capacity exceeded. + // TODO: Make this a specific error/event. + if (e.name === 'QuotaExceededError' || e.name === 'NS_ERROR_DOM_QUOTA_REACHED') { + reject(e); + } + reject(e); + } + } + }); + }); + }); + + executeCallback(promise, callback); + return promise; +} + +var localStorageWrapper = { + _driver: 'localStorageWrapper', + _initStorage: _initStorage$2, + // Default API, from Gaia/localStorage. + iterate: iterate$2, + getItem: getItem$2, + setItem: setItem$2, + removeItem: removeItem$2, + clear: clear$2, + length: length$2, + key: key$2, + keys: keys$2 +}; + +function executeTwoCallbacks(promise, callback, errorCallback) { + if (typeof callback === 'function') { + promise.then(callback); + } + + if (typeof errorCallback === 'function') { + promise["catch"](errorCallback); + } +} + +// Custom drivers are stored here when `defineDriver()` is called. +// They are shared across all instances of localForage. +var CustomDrivers = {}; + +var DriverType = { + INDEXEDDB: 'asyncStorage', + LOCALSTORAGE: 'localStorageWrapper', + WEBSQL: 'webSQLStorage' +}; + +var DefaultDriverOrder = [DriverType.INDEXEDDB, DriverType.WEBSQL, DriverType.LOCALSTORAGE]; + +var LibraryMethods = ['clear', 'getItem', 'iterate', 'key', 'keys', 'length', 'removeItem', 'setItem']; + +var DefaultConfig = { + description: '', + driver: DefaultDriverOrder.slice(), + name: 'localforage', + // Default DB size is _JUST UNDER_ 5MB, as it's the highest size + // we can use without a prompt. + size: 4980736, + storeName: 'keyvaluepairs', + version: 1.0 +}; + +var driverSupport = {}; +// Check to see if IndexedDB is available and if it is the latest +// implementation; it's our preferred backend library. We use "_spec_test" +// as the name of the database because it's not the one we'll operate on, +// but it's useful to make sure its using the right spec. +// See: https://github.com/mozilla/localForage/issues/128 +driverSupport[DriverType.INDEXEDDB] = isIndexedDBValid(); + +driverSupport[DriverType.WEBSQL] = isWebSQLValid(); + +driverSupport[DriverType.LOCALSTORAGE] = isLocalStorageValid(); + +var isArray = Array.isArray || function (arg) { + return Object.prototype.toString.call(arg) === '[object Array]'; +}; + +function callWhenReady(localForageInstance, libraryMethod) { + localForageInstance[libraryMethod] = function () { + var _args = arguments; + return localForageInstance.ready().then(function () { + return localForageInstance[libraryMethod].apply(localForageInstance, _args); + }); + }; +} + +function extend() { + for (var i = 1; i < arguments.length; i++) { + var arg = arguments[i]; + + if (arg) { + for (var key in arg) { + if (arg.hasOwnProperty(key)) { + if (isArray(arg[key])) { + arguments[0][key] = arg[key].slice(); + } else { + arguments[0][key] = arg[key]; + } + } + } + } + } + + return arguments[0]; +} + +function isLibraryDriver(driverName) { + for (var driver in DriverType) { + if (DriverType.hasOwnProperty(driver) && DriverType[driver] === driverName) { + return true; + } + } + + return false; +} + +var LocalForage = function () { + function LocalForage(options) { + _classCallCheck(this, LocalForage); + + this.INDEXEDDB = DriverType.INDEXEDDB; + this.LOCALSTORAGE = DriverType.LOCALSTORAGE; + this.WEBSQL = DriverType.WEBSQL; + + this._defaultConfig = extend({}, DefaultConfig); + this._config = extend({}, this._defaultConfig, options); + this._driverSet = null; + this._initDriver = null; + this._ready = false; + this._dbInfo = null; + + this._wrapLibraryMethodsWithReady(); + this.setDriver(this._config.driver); + } + + // Set any config values for localForage; can be called anytime before + // the first API call (e.g. `getItem`, `setItem`). + // We loop through options so we don't overwrite existing config + // values. + + + LocalForage.prototype.config = function config(options) { + // If the options argument is an object, we use it to set values. + // Otherwise, we return either a specified config value or all + // config values. + if ((typeof options === 'undefined' ? 'undefined' : _typeof(options)) === 'object') { + // If localforage is ready and fully initialized, we can't set + // any new configuration values. Instead, we return an error. + if (this._ready) { + return new Error("Can't call config() after localforage " + 'has been used.'); + } + + for (var i in options) { + if (i === 'storeName') { + options[i] = options[i].replace(/\W/g, '_'); + } + + this._config[i] = options[i]; + } + + // after all config options are set and + // the driver option is used, try setting it + if ('driver' in options && options.driver) { + this.setDriver(this._config.driver); + } + + return true; + } else if (typeof options === 'string') { + return this._config[options]; + } else { + return this._config; + } + }; + + // Used to define a custom driver, shared across all instances of + // localForage. + + + LocalForage.prototype.defineDriver = function defineDriver(driverObject, callback, errorCallback) { + var promise = new Promise$1(function (resolve, reject) { + try { + var driverName = driverObject._driver; + var complianceError = new Error('Custom driver not compliant; see ' + 'https://mozilla.github.io/localForage/#definedriver'); + var namingError = new Error('Custom driver name already in use: ' + driverObject._driver); + + // A driver name should be defined and not overlap with the + // library-defined, default drivers. + if (!driverObject._driver) { + reject(complianceError); + return; + } + if (isLibraryDriver(driverObject._driver)) { + reject(namingError); + return; + } + + var customDriverMethods = LibraryMethods.concat('_initStorage'); + for (var i = 0; i < customDriverMethods.length; i++) { + var customDriverMethod = customDriverMethods[i]; + if (!customDriverMethod || !driverObject[customDriverMethod] || typeof driverObject[customDriverMethod] !== 'function') { + reject(complianceError); + return; + } + } + + var supportPromise = Promise$1.resolve(true); + if ('_support' in driverObject) { + if (driverObject._support && typeof driverObject._support === 'function') { + supportPromise = driverObject._support(); + } else { + supportPromise = Promise$1.resolve(!!driverObject._support); + } + } + + supportPromise.then(function (supportResult) { + driverSupport[driverName] = supportResult; + CustomDrivers[driverName] = driverObject; + resolve(); + }, reject); + } catch (e) { + reject(e); + } + }); + + executeTwoCallbacks(promise, callback, errorCallback); + return promise; + }; + + LocalForage.prototype.driver = function driver() { + return this._driver || null; + }; + + LocalForage.prototype.getDriver = function getDriver(driverName, callback, errorCallback) { + var self = this; + var getDriverPromise = Promise$1.resolve().then(function () { + if (isLibraryDriver(driverName)) { + switch (driverName) { + case self.INDEXEDDB: + return asyncStorage; + case self.LOCALSTORAGE: + return localStorageWrapper; + case self.WEBSQL: + return webSQLStorage; + } + } else if (CustomDrivers[driverName]) { + return CustomDrivers[driverName]; + } else { + throw new Error('Driver not found.'); + } + }); + executeTwoCallbacks(getDriverPromise, callback, errorCallback); + return getDriverPromise; + }; + + LocalForage.prototype.getSerializer = function getSerializer(callback) { + var serializerPromise = Promise$1.resolve(localforageSerializer); + executeTwoCallbacks(serializerPromise, callback); + return serializerPromise; + }; + + LocalForage.prototype.ready = function ready(callback) { + var self = this; + + var promise = self._driverSet.then(function () { + if (self._ready === null) { + self._ready = self._initDriver(); + } + + return self._ready; + }); + + executeTwoCallbacks(promise, callback, callback); + return promise; + }; + + LocalForage.prototype.setDriver = function setDriver(drivers, callback, errorCallback) { + var self = this; + + if (!isArray(drivers)) { + drivers = [drivers]; + } + + var supportedDrivers = this._getSupportedDrivers(drivers); + + function setDriverToConfig() { + self._config.driver = self.driver(); + } + + function initDriver(supportedDrivers) { + return function () { + var currentDriverIndex = 0; + + function driverPromiseLoop() { + while (currentDriverIndex < supportedDrivers.length) { + var driverName = supportedDrivers[currentDriverIndex]; + currentDriverIndex++; + + self._dbInfo = null; + self._ready = null; + + return self.getDriver(driverName).then(function (driver) { + self._extend(driver); + setDriverToConfig(); + + self._ready = self._initStorage(self._config); + return self._ready; + })["catch"](driverPromiseLoop); + } + + setDriverToConfig(); + var error = new Error('No available storage method found.'); + self._driverSet = Promise$1.reject(error); + return self._driverSet; + } + + return driverPromiseLoop(); + }; + } + + // There might be a driver initialization in progress + // so wait for it to finish in order to avoid a possible + // race condition to set _dbInfo + var oldDriverSetDone = this._driverSet !== null ? this._driverSet["catch"](function () { + return Promise$1.resolve(); + }) : Promise$1.resolve(); + + this._driverSet = oldDriverSetDone.then(function () { + var driverName = supportedDrivers[0]; + self._dbInfo = null; + self._ready = null; + + return self.getDriver(driverName).then(function (driver) { + self._driver = driver._driver; + setDriverToConfig(); + self._wrapLibraryMethodsWithReady(); + self._initDriver = initDriver(supportedDrivers); + }); + })["catch"](function () { + setDriverToConfig(); + var error = new Error('No available storage method found.'); + self._driverSet = Promise$1.reject(error); + return self._driverSet; + }); + + executeTwoCallbacks(this._driverSet, callback, errorCallback); + return this._driverSet; + }; + + LocalForage.prototype.supports = function supports(driverName) { + return !!driverSupport[driverName]; + }; + + LocalForage.prototype._extend = function _extend(libraryMethodsAndProperties) { + extend(this, libraryMethodsAndProperties); + }; + + LocalForage.prototype._getSupportedDrivers = function _getSupportedDrivers(drivers) { + var supportedDrivers = []; + for (var i = 0, len = drivers.length; i < len; i++) { + var driverName = drivers[i]; + if (this.supports(driverName)) { + supportedDrivers.push(driverName); + } + } + return supportedDrivers; + }; + + LocalForage.prototype._wrapLibraryMethodsWithReady = function _wrapLibraryMethodsWithReady() { + // Add a stub for each driver API method that delays the call to the + // corresponding driver method until localForage is ready. These stubs + // will be replaced by the driver methods as soon as the driver is + // loaded, so there is no performance impact. + for (var i = 0; i < LibraryMethods.length; i++) { + callWhenReady(this, LibraryMethods[i]); + } + }; + + LocalForage.prototype.createInstance = function createInstance(options) { + return new LocalForage(options); + }; + + return LocalForage; +}(); + +// The actual localForage object that we expose as a module or via a +// global. It's extended by pulling in one of our other libraries. + + +var localforage_js = new LocalForage(); + +module.exports = localforage_js; + +},{"undefined":undefined}]},{},[1])(1) +});
\ No newline at end of file diff --git a/www/lib/localforage/dist/localforage.nopromises.min.js b/www/lib/localforage/dist/localforage.nopromises.min.js new file mode 100644 index 00000000..39ed4377 --- /dev/null +++ b/www/lib/localforage/dist/localforage.nopromises.min.js @@ -0,0 +1,7 @@ +/*! + localForage -- Offline Storage, Improved + Version 1.4.2 + https://mozilla.github.io/localForage + (c) 2013-2015 Mozilla, Apache License 2.0 +*/ +!function(a){if("object"==typeof exports&&"undefined"!=typeof module)module.exports=a();else if("function"==typeof define&&define.amd)define([],a);else{var b;b="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:this,b.localforage=a()}}(function(){return function a(b,c,d){function e(g,h){if(!c[g]){if(!b[g]){var i="function"==typeof require&&require;if(!h&&i)return i(g,!0);if(f)return f(g,!0);var j=new Error("Cannot find module '"+g+"'");throw j.code="MODULE_NOT_FOUND",j}var k=c[g]={exports:{}};b[g][0].call(k.exports,function(a){var c=b[g][1][a];return e(c?c:a)},k,k.exports,a,b,c,d)}return c[g].exports}for(var f="function"==typeof require&&require,g=0;g<d.length;g++)e(d[g]);return e}({1:[function(a,b,c){"use strict";function d(a,b){if(!(a instanceof b))throw new TypeError("Cannot call a class as a function")}function e(){return"undefined"!=typeof indexedDB?indexedDB:"undefined"!=typeof webkitIndexedDB?webkitIndexedDB:"undefined"!=typeof mozIndexedDB?mozIndexedDB:"undefined"!=typeof OIndexedDB?OIndexedDB:"undefined"!=typeof msIndexedDB?msIndexedDB:void 0}function f(){try{return fa?"undefined"!=typeof openDatabase&&"undefined"!=typeof navigator&&navigator.userAgent&&/Safari/.test(navigator.userAgent)&&!/Chrome/.test(navigator.userAgent)?!1:fa&&"function"==typeof fa.open&&"undefined"!=typeof IDBKeyRange:!1}catch(a){return!1}}function g(){return"function"==typeof openDatabase}function h(){try{return"undefined"!=typeof localStorage&&"setItem"in localStorage&&localStorage.setItem}catch(a){return!1}}function i(a,b){a=a||[],b=b||{};try{return new Blob(a,b)}catch(c){if("TypeError"!==c.name)throw c;for(var d="undefined"!=typeof BlobBuilder?BlobBuilder:"undefined"!=typeof MSBlobBuilder?MSBlobBuilder:"undefined"!=typeof MozBlobBuilder?MozBlobBuilder:WebKitBlobBuilder,e=new d,f=0;f<a.length;f+=1)e.append(a[f]);return e.getBlob(b.type)}}function j(a,b){b&&a.then(function(a){b(null,a)},function(a){b(a)})}function k(a){for(var b=a.length,c=new ArrayBuffer(b),d=new Uint8Array(c),e=0;b>e;e++)d[e]=a.charCodeAt(e);return c}function l(a){return new ia(function(b){var c=i([""]);a.objectStore(ja).put(c,"key"),a.onabort=function(a){a.preventDefault(),a.stopPropagation(),b(!1)},a.oncomplete=function(){var a=navigator.userAgent.match(/Chrome\/(\d+)/),c=navigator.userAgent.match(/Edge\//);b(c||!a||parseInt(a[1],10)>=43)}})["catch"](function(){return!1})}function m(a){return"boolean"==typeof ga?ia.resolve(ga):l(a).then(function(a){return ga=a})}function n(a){var b=ha[a.name],c={};c.promise=new ia(function(a){c.resolve=a}),b.deferredOperations.push(c),b.dbReady?b.dbReady=b.dbReady.then(function(){return c.promise}):b.dbReady=c.promise}function o(a){var b=ha[a.name],c=b.deferredOperations.pop();c&&c.resolve()}function p(a,b){return new ia(function(c,d){if(a.db){if(!b)return c(a.db);n(a),a.db.close()}var e=[a.name];b&&e.push(a.version);var f=fa.open.apply(fa,e);b&&(f.onupgradeneeded=function(b){var c=f.result;try{c.createObjectStore(a.storeName),b.oldVersion<=1&&c.createObjectStore(ja)}catch(d){if("ConstraintError"!==d.name)throw d;console.warn('The database "'+a.name+'" has been upgraded from version '+b.oldVersion+" to version "+b.newVersion+', but the storage "'+a.storeName+'" already exists.')}}),f.onerror=function(){d(f.error)},f.onsuccess=function(){c(f.result),o(a)}})}function q(a){return p(a,!1)}function r(a){return p(a,!0)}function s(a,b){if(!a.db)return!0;var c=!a.db.objectStoreNames.contains(a.storeName),d=a.version<a.db.version,e=a.version>a.db.version;if(d&&(a.version!==b&&console.warn('The database "'+a.name+"\" can't be downgraded from version "+a.db.version+" to version "+a.version+"."),a.version=a.db.version),e||c){if(c){var f=a.db.version+1;f>a.version&&(a.version=f)}return!0}return!1}function t(a){return new ia(function(b,c){var d=new FileReader;d.onerror=c,d.onloadend=function(c){var d=btoa(c.target.result||"");b({__local_forage_encoded_blob:!0,data:d,type:a.type})},d.readAsBinaryString(a)})}function u(a){var b=k(atob(a.data));return i([b],{type:a.type})}function v(a){return a&&a.__local_forage_encoded_blob}function w(a){var b=this,c=b._initReady().then(function(){var a=ha[b._dbInfo.name];return a&&a.dbReady?a.dbReady:void 0});return c.then(a,a),c}function x(a){function b(){return ia.resolve()}var c=this,d={db:null};if(a)for(var e in a)d[e]=a[e];ha||(ha={});var f=ha[d.name];f||(f={forages:[],db:null,dbReady:null,deferredOperations:[]},ha[d.name]=f),f.forages.push(c),c._initReady||(c._initReady=c.ready,c.ready=w);for(var g=[],h=0;h<f.forages.length;h++){var i=f.forages[h];i!==c&&g.push(i._initReady()["catch"](b))}var j=f.forages.slice(0);return ia.all(g).then(function(){return d.db=f.db,q(d)}).then(function(a){return d.db=a,s(d,c._defaultConfig.version)?r(d):a}).then(function(a){d.db=f.db=a,c._dbInfo=d;for(var b=0;b<j.length;b++){var e=j[b];e!==c&&(e._dbInfo.db=d.db,e._dbInfo.version=d.version)}})}function y(a,b){var c=this;"string"!=typeof a&&(console.warn(a+" used as a key, but it is not a string."),a=String(a));var d=new ia(function(b,d){c.ready().then(function(){var e=c._dbInfo,f=e.db.transaction(e.storeName,"readonly").objectStore(e.storeName),g=f.get(a);g.onsuccess=function(){var a=g.result;void 0===a&&(a=null),v(a)&&(a=u(a)),b(a)},g.onerror=function(){d(g.error)}})["catch"](d)});return j(d,b),d}function z(a,b){var c=this,d=new ia(function(b,d){c.ready().then(function(){var e=c._dbInfo,f=e.db.transaction(e.storeName,"readonly").objectStore(e.storeName),g=f.openCursor(),h=1;g.onsuccess=function(){var c=g.result;if(c){var d=c.value;v(d)&&(d=u(d));var e=a(d,c.key,h++);void 0!==e?b(e):c["continue"]()}else b()},g.onerror=function(){d(g.error)}})["catch"](d)});return j(d,b),d}function A(a,b,c){var d=this;"string"!=typeof a&&(console.warn(a+" used as a key, but it is not a string."),a=String(a));var e=new ia(function(c,e){var f;d.ready().then(function(){return f=d._dbInfo,b instanceof Blob?m(f.db).then(function(a){return a?b:t(b)}):b}).then(function(b){var d=f.db.transaction(f.storeName,"readwrite"),g=d.objectStore(f.storeName);null===b&&(b=void 0),d.oncomplete=function(){void 0===b&&(b=null),c(b)},d.onabort=d.onerror=function(){var a=h.error?h.error:h.transaction.error;e(a)};var h=g.put(b,a)})["catch"](e)});return j(e,c),e}function B(a,b){var c=this;"string"!=typeof a&&(console.warn(a+" used as a key, but it is not a string."),a=String(a));var d=new ia(function(b,d){c.ready().then(function(){var e=c._dbInfo,f=e.db.transaction(e.storeName,"readwrite"),g=f.objectStore(e.storeName),h=g["delete"](a);f.oncomplete=function(){b()},f.onerror=function(){d(h.error)},f.onabort=function(){var a=h.error?h.error:h.transaction.error;d(a)}})["catch"](d)});return j(d,b),d}function C(a){var b=this,c=new ia(function(a,c){b.ready().then(function(){var d=b._dbInfo,e=d.db.transaction(d.storeName,"readwrite"),f=e.objectStore(d.storeName),g=f.clear();e.oncomplete=function(){a()},e.onabort=e.onerror=function(){var a=g.error?g.error:g.transaction.error;c(a)}})["catch"](c)});return j(c,a),c}function D(a){var b=this,c=new ia(function(a,c){b.ready().then(function(){var d=b._dbInfo,e=d.db.transaction(d.storeName,"readonly").objectStore(d.storeName),f=e.count();f.onsuccess=function(){a(f.result)},f.onerror=function(){c(f.error)}})["catch"](c)});return j(c,a),c}function E(a,b){var c=this,d=new ia(function(b,d){return 0>a?void b(null):void c.ready().then(function(){var e=c._dbInfo,f=e.db.transaction(e.storeName,"readonly").objectStore(e.storeName),g=!1,h=f.openCursor();h.onsuccess=function(){var c=h.result;return c?void(0===a?b(c.key):g?b(c.key):(g=!0,c.advance(a))):void b(null)},h.onerror=function(){d(h.error)}})["catch"](d)});return j(d,b),d}function F(a){var b=this,c=new ia(function(a,c){b.ready().then(function(){var d=b._dbInfo,e=d.db.transaction(d.storeName,"readonly").objectStore(d.storeName),f=e.openCursor(),g=[];f.onsuccess=function(){var b=f.result;return b?(g.push(b.key),void b["continue"]()):void a(g)},f.onerror=function(){c(f.error)}})["catch"](c)});return j(c,a),c}function G(a){var b,c,d,e,f,g=.75*a.length,h=a.length,i=0;"="===a[a.length-1]&&(g--,"="===a[a.length-2]&&g--);var j=new ArrayBuffer(g),k=new Uint8Array(j);for(b=0;h>b;b+=4)c=la.indexOf(a[b]),d=la.indexOf(a[b+1]),e=la.indexOf(a[b+2]),f=la.indexOf(a[b+3]),k[i++]=c<<2|d>>4,k[i++]=(15&d)<<4|e>>2,k[i++]=(3&e)<<6|63&f;return j}function H(a){var b,c=new Uint8Array(a),d="";for(b=0;b<c.length;b+=3)d+=la[c[b]>>2],d+=la[(3&c[b])<<4|c[b+1]>>4],d+=la[(15&c[b+1])<<2|c[b+2]>>6],d+=la[63&c[b+2]];return c.length%3===2?d=d.substring(0,d.length-1)+"=":c.length%3===1&&(d=d.substring(0,d.length-2)+"=="),d}function I(a,b){var c="";if(a&&(c=a.toString()),a&&("[object ArrayBuffer]"===a.toString()||a.buffer&&"[object ArrayBuffer]"===a.buffer.toString())){var d,e=oa;a instanceof ArrayBuffer?(d=a,e+=qa):(d=a.buffer,"[object Int8Array]"===c?e+=sa:"[object Uint8Array]"===c?e+=ta:"[object Uint8ClampedArray]"===c?e+=ua:"[object Int16Array]"===c?e+=va:"[object Uint16Array]"===c?e+=xa:"[object Int32Array]"===c?e+=wa:"[object Uint32Array]"===c?e+=ya:"[object Float32Array]"===c?e+=za:"[object Float64Array]"===c?e+=Aa:b(new Error("Failed to get type for BinaryArray"))),b(e+H(d))}else if("[object Blob]"===c){var f=new FileReader;f.onload=function(){var c=ma+a.type+"~"+H(this.result);b(oa+ra+c)},f.readAsArrayBuffer(a)}else try{b(JSON.stringify(a))}catch(g){console.error("Couldn't convert value into a JSON string: ",a),b(null,g)}}function J(a){if(a.substring(0,pa)!==oa)return JSON.parse(a);var b,c=a.substring(Ba),d=a.substring(pa,Ba);if(d===ra&&na.test(c)){var e=c.match(na);b=e[1],c=c.substring(e[0].length)}var f=G(c);switch(d){case qa:return f;case ra:return i([f],{type:b});case sa:return new Int8Array(f);case ta:return new Uint8Array(f);case ua:return new Uint8ClampedArray(f);case va:return new Int16Array(f);case xa:return new Uint16Array(f);case wa:return new Int32Array(f);case ya:return new Uint32Array(f);case za:return new Float32Array(f);case Aa:return new Float64Array(f);default:throw new Error("Unkown type: "+d)}}function K(a){var b=this,c={db:null};if(a)for(var d in a)c[d]="string"!=typeof a[d]?a[d].toString():a[d];var e=new ia(function(a,d){try{c.db=openDatabase(c.name,String(c.version),c.description,c.size)}catch(e){return d(e)}c.db.transaction(function(e){e.executeSql("CREATE TABLE IF NOT EXISTS "+c.storeName+" (id INTEGER PRIMARY KEY, key unique, value)",[],function(){b._dbInfo=c,a()},function(a,b){d(b)})})});return c.serializer=Ca,e}function L(a,b){var c=this;"string"!=typeof a&&(console.warn(a+" used as a key, but it is not a string."),a=String(a));var d=new ia(function(b,d){c.ready().then(function(){var e=c._dbInfo;e.db.transaction(function(c){c.executeSql("SELECT * FROM "+e.storeName+" WHERE key = ? LIMIT 1",[a],function(a,c){var d=c.rows.length?c.rows.item(0).value:null;d&&(d=e.serializer.deserialize(d)),b(d)},function(a,b){d(b)})})})["catch"](d)});return j(d,b),d}function M(a,b){var c=this,d=new ia(function(b,d){c.ready().then(function(){var e=c._dbInfo;e.db.transaction(function(c){c.executeSql("SELECT * FROM "+e.storeName,[],function(c,d){for(var f=d.rows,g=f.length,h=0;g>h;h++){var i=f.item(h),j=i.value;if(j&&(j=e.serializer.deserialize(j)),j=a(j,i.key,h+1),void 0!==j)return void b(j)}b()},function(a,b){d(b)})})})["catch"](d)});return j(d,b),d}function N(a,b,c){var d=this;"string"!=typeof a&&(console.warn(a+" used as a key, but it is not a string."),a=String(a));var e=new ia(function(c,e){d.ready().then(function(){void 0===b&&(b=null);var f=b,g=d._dbInfo;g.serializer.serialize(b,function(b,d){d?e(d):g.db.transaction(function(d){d.executeSql("INSERT OR REPLACE INTO "+g.storeName+" (key, value) VALUES (?, ?)",[a,b],function(){c(f)},function(a,b){e(b)})},function(a){a.code===a.QUOTA_ERR&&e(a)})})})["catch"](e)});return j(e,c),e}function O(a,b){var c=this;"string"!=typeof a&&(console.warn(a+" used as a key, but it is not a string."),a=String(a));var d=new ia(function(b,d){c.ready().then(function(){var e=c._dbInfo;e.db.transaction(function(c){c.executeSql("DELETE FROM "+e.storeName+" WHERE key = ?",[a],function(){b()},function(a,b){d(b)})})})["catch"](d)});return j(d,b),d}function P(a){var b=this,c=new ia(function(a,c){b.ready().then(function(){var d=b._dbInfo;d.db.transaction(function(b){b.executeSql("DELETE FROM "+d.storeName,[],function(){a()},function(a,b){c(b)})})})["catch"](c)});return j(c,a),c}function Q(a){var b=this,c=new ia(function(a,c){b.ready().then(function(){var d=b._dbInfo;d.db.transaction(function(b){b.executeSql("SELECT COUNT(key) as c FROM "+d.storeName,[],function(b,c){var d=c.rows.item(0).c;a(d)},function(a,b){c(b)})})})["catch"](c)});return j(c,a),c}function R(a,b){var c=this,d=new ia(function(b,d){c.ready().then(function(){var e=c._dbInfo;e.db.transaction(function(c){c.executeSql("SELECT key FROM "+e.storeName+" WHERE id = ? LIMIT 1",[a+1],function(a,c){var d=c.rows.length?c.rows.item(0).key:null;b(d)},function(a,b){d(b)})})})["catch"](d)});return j(d,b),d}function S(a){var b=this,c=new ia(function(a,c){b.ready().then(function(){var d=b._dbInfo;d.db.transaction(function(b){b.executeSql("SELECT key FROM "+d.storeName,[],function(b,c){for(var d=[],e=0;e<c.rows.length;e++)d.push(c.rows.item(e).key);a(d)},function(a,b){c(b)})})})["catch"](c)});return j(c,a),c}function T(a){var b=this,c={};if(a)for(var d in a)c[d]=a[d];return c.keyPrefix=c.name+"/",c.storeName!==b._defaultConfig.storeName&&(c.keyPrefix+=c.storeName+"/"),b._dbInfo=c,c.serializer=Ca,ia.resolve()}function U(a){var b=this,c=b.ready().then(function(){for(var a=b._dbInfo.keyPrefix,c=localStorage.length-1;c>=0;c--){var d=localStorage.key(c);0===d.indexOf(a)&&localStorage.removeItem(d)}});return j(c,a),c}function V(a,b){var c=this;"string"!=typeof a&&(console.warn(a+" used as a key, but it is not a string."),a=String(a));var d=c.ready().then(function(){var b=c._dbInfo,d=localStorage.getItem(b.keyPrefix+a);return d&&(d=b.serializer.deserialize(d)),d});return j(d,b),d}function W(a,b){var c=this,d=c.ready().then(function(){for(var b=c._dbInfo,d=b.keyPrefix,e=d.length,f=localStorage.length,g=1,h=0;f>h;h++){var i=localStorage.key(h);if(0===i.indexOf(d)){var j=localStorage.getItem(i);if(j&&(j=b.serializer.deserialize(j)),j=a(j,i.substring(e),g++),void 0!==j)return j}}});return j(d,b),d}function X(a,b){var c=this,d=c.ready().then(function(){var b,d=c._dbInfo;try{b=localStorage.key(a)}catch(e){b=null}return b&&(b=b.substring(d.keyPrefix.length)),b});return j(d,b),d}function Y(a){var b=this,c=b.ready().then(function(){for(var a=b._dbInfo,c=localStorage.length,d=[],e=0;c>e;e++)0===localStorage.key(e).indexOf(a.keyPrefix)&&d.push(localStorage.key(e).substring(a.keyPrefix.length));return d});return j(c,a),c}function Z(a){var b=this,c=b.keys().then(function(a){return a.length});return j(c,a),c}function $(a,b){var c=this;"string"!=typeof a&&(console.warn(a+" used as a key, but it is not a string."),a=String(a));var d=c.ready().then(function(){var b=c._dbInfo;localStorage.removeItem(b.keyPrefix+a)});return j(d,b),d}function _(a,b,c){var d=this;"string"!=typeof a&&(console.warn(a+" used as a key, but it is not a string."),a=String(a));var e=d.ready().then(function(){void 0===b&&(b=null);var c=b;return new ia(function(e,f){var g=d._dbInfo;g.serializer.serialize(b,function(b,d){if(d)f(d);else try{localStorage.setItem(g.keyPrefix+a,b),e(c)}catch(h){"QuotaExceededError"!==h.name&&"NS_ERROR_DOM_QUOTA_REACHED"!==h.name||f(h),f(h)}})})});return j(e,c),e}function aa(a,b,c){"function"==typeof b&&a.then(b),"function"==typeof c&&a["catch"](c)}function ba(a,b){a[b]=function(){var c=arguments;return a.ready().then(function(){return a[b].apply(a,c)})}}function ca(){for(var a=1;a<arguments.length;a++){var b=arguments[a];if(b)for(var c in b)b.hasOwnProperty(c)&&(La(b[c])?arguments[0][c]=b[c].slice():arguments[0][c]=b[c])}return arguments[0]}function da(a){for(var b in Ga)if(Ga.hasOwnProperty(b)&&Ga[b]===a)return!0;return!1}var ea="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(a){return typeof a}:function(a){return a&&"function"==typeof Symbol&&a.constructor===Symbol?"symbol":typeof a},fa=e();"undefined"==typeof Promise&&"undefined"!=typeof a&&a("lie/polyfill");var ga,ha,ia=Promise,ja="local-forage-detect-blob-support",ka={_driver:"asyncStorage",_initStorage:x,iterate:z,getItem:y,setItem:A,removeItem:B,clear:C,length:D,key:E,keys:F},la="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",ma="~~local_forage_type~",na=/^~~local_forage_type~([^~]+)~/,oa="__lfsc__:",pa=oa.length,qa="arbf",ra="blob",sa="si08",ta="ui08",ua="uic8",va="si16",wa="si32",xa="ur16",ya="ui32",za="fl32",Aa="fl64",Ba=pa+qa.length,Ca={serialize:I,deserialize:J,stringToBuffer:G,bufferToString:H},Da={_driver:"webSQLStorage",_initStorage:K,iterate:M,getItem:L,setItem:N,removeItem:O,clear:P,length:Q,key:R,keys:S},Ea={_driver:"localStorageWrapper",_initStorage:T,iterate:W,getItem:V,setItem:_,removeItem:$,clear:U,length:Z,key:X,keys:Y},Fa={},Ga={INDEXEDDB:"asyncStorage",LOCALSTORAGE:"localStorageWrapper",WEBSQL:"webSQLStorage"},Ha=[Ga.INDEXEDDB,Ga.WEBSQL,Ga.LOCALSTORAGE],Ia=["clear","getItem","iterate","key","keys","length","removeItem","setItem"],Ja={description:"",driver:Ha.slice(),name:"localforage",size:4980736,storeName:"keyvaluepairs",version:1},Ka={};Ka[Ga.INDEXEDDB]=f(),Ka[Ga.WEBSQL]=g(),Ka[Ga.LOCALSTORAGE]=h();var La=Array.isArray||function(a){return"[object Array]"===Object.prototype.toString.call(a)},Ma=function(){function a(b){d(this,a),this.INDEXEDDB=Ga.INDEXEDDB,this.LOCALSTORAGE=Ga.LOCALSTORAGE,this.WEBSQL=Ga.WEBSQL,this._defaultConfig=ca({},Ja),this._config=ca({},this._defaultConfig,b),this._driverSet=null,this._initDriver=null,this._ready=!1,this._dbInfo=null,this._wrapLibraryMethodsWithReady(),this.setDriver(this._config.driver)}return a.prototype.config=function(a){if("object"===("undefined"==typeof a?"undefined":ea(a))){if(this._ready)return new Error("Can't call config() after localforage has been used.");for(var b in a)"storeName"===b&&(a[b]=a[b].replace(/\W/g,"_")),this._config[b]=a[b];return"driver"in a&&a.driver&&this.setDriver(this._config.driver),!0}return"string"==typeof a?this._config[a]:this._config},a.prototype.defineDriver=function(a,b,c){var d=new ia(function(b,c){try{var d=a._driver,e=new Error("Custom driver not compliant; see https://mozilla.github.io/localForage/#definedriver"),f=new Error("Custom driver name already in use: "+a._driver);if(!a._driver)return void c(e);if(da(a._driver))return void c(f);for(var g=Ia.concat("_initStorage"),h=0;h<g.length;h++){var i=g[h];if(!i||!a[i]||"function"!=typeof a[i])return void c(e)}var j=ia.resolve(!0);"_support"in a&&(j=a._support&&"function"==typeof a._support?a._support():ia.resolve(!!a._support)),j.then(function(c){Ka[d]=c,Fa[d]=a,b()},c)}catch(k){c(k)}});return aa(d,b,c),d},a.prototype.driver=function(){return this._driver||null},a.prototype.getDriver=function(a,b,c){var d=this,e=ia.resolve().then(function(){if(!da(a)){if(Fa[a])return Fa[a];throw new Error("Driver not found.")}switch(a){case d.INDEXEDDB:return ka;case d.LOCALSTORAGE:return Ea;case d.WEBSQL:return Da}});return aa(e,b,c),e},a.prototype.getSerializer=function(a){var b=ia.resolve(Ca);return aa(b,a),b},a.prototype.ready=function(a){var b=this,c=b._driverSet.then(function(){return null===b._ready&&(b._ready=b._initDriver()),b._ready});return aa(c,a,a),c},a.prototype.setDriver=function(a,b,c){function d(){f._config.driver=f.driver()}function e(a){return function(){function b(){for(;c<a.length;){var e=a[c];return c++,f._dbInfo=null,f._ready=null,f.getDriver(e).then(function(a){return f._extend(a),d(),f._ready=f._initStorage(f._config),f._ready})["catch"](b)}d();var g=new Error("No available storage method found.");return f._driverSet=ia.reject(g),f._driverSet}var c=0;return b()}}var f=this;La(a)||(a=[a]);var g=this._getSupportedDrivers(a),h=null!==this._driverSet?this._driverSet["catch"](function(){return ia.resolve()}):ia.resolve();return this._driverSet=h.then(function(){var a=g[0];return f._dbInfo=null,f._ready=null,f.getDriver(a).then(function(a){f._driver=a._driver,d(),f._wrapLibraryMethodsWithReady(),f._initDriver=e(g)})})["catch"](function(){d();var a=new Error("No available storage method found.");return f._driverSet=ia.reject(a),f._driverSet}),aa(this._driverSet,b,c),this._driverSet},a.prototype.supports=function(a){return!!Ka[a]},a.prototype._extend=function(a){ca(this,a)},a.prototype._getSupportedDrivers=function(a){for(var b=[],c=0,d=a.length;d>c;c++){var e=a[c];this.supports(e)&&b.push(e)}return b},a.prototype._wrapLibraryMethodsWithReady=function(){for(var a=0;a<Ia.length;a++)ba(this,Ia[a])},a.prototype.createInstance=function(b){return new a(b)},a}(),Na=new Ma;b.exports=Na},{undefined:void 0}]},{},[1])(1)});
\ No newline at end of file diff --git a/www/lib/localforage/package.json b/www/lib/localforage/package.json new file mode 100644 index 00000000..3d9894fa --- /dev/null +++ b/www/lib/localforage/package.json @@ -0,0 +1,66 @@ +{ + "name": "localforage", + "author": "Mozilla", + "license": "Apache-2.0", + "description": "Offline storage, improved.", + "keywords": [ + "indexeddb", + "localstorage", + "storage", + "websql" + ], + "version": "1.4.2", + "homepage": "https://github.com/mozilla/localForage", + "repository": { + "type": "git", + "url": "git://github.com/mozilla/localForage.git" + }, + "scripts": { + "publish-docs": "node -e \"require('grunt').cli()\" null copy build-rules-html publish-rules", + "test": "node -e \"require('grunt').cli()\" null test" + }, + "devDependencies": { + "babel-core": "^6.5.1", + "babel-loader": "^6.2.2", + "babel-plugin-add-module-exports": "^0.1.2", + "babel-plugin-transform-es2015-modules-umd": "^6.5.0", + "babel-preset-es2015": "^6.6.0", + "babel-preset-es2015-loose": "^7.0.0", + "babelify": "^7.2.0", + "bundle-collapser": "^1.2.1", + "cors": "^2.3.1", + "derequire": "^2.0.3", + "grunt": "^0.4.2", + "grunt-babel": "^6.0.0", + "grunt-browserify": "^3.8.0", + "grunt-contrib-concat": "^0.3.0", + "grunt-contrib-connect": "^0.8.0", + "grunt-contrib-jshint": "^0.9.2", + "grunt-contrib-uglify": "^0.4.0", + "grunt-contrib-watch": "^0.5.0", + "grunt-es3-safe-recast": "^0.1.0", + "grunt-jscs": "^1.5.0", + "grunt-mocha": "^0.4.10", + "grunt-rollup": "^0.6.2", + "grunt-run": "^0.5.2", + "grunt-saucelabs": "^5.1.2", + "grunt-webpack": "^1.0.11", + "load-grunt-tasks": "^0.4.0", + "mocha": "^1.18.2", + "ncp": "^2.0.0", + "phantomjs": "^1.9.7-12", + "rimraf": "^2.5.2", + "rollupify": "^0.1.0", + "script-loader": "^0.6.1", + "uglify-js": "^2.3.x", + "webpack": "^1.12.13", + "webpack-dev-server": "^1.10.1" + }, + "main": "dist/localforage.js", + "bugs": { + "url": "http://github.com/mozilla/localForage/issues" + }, + "dependencies": { + "lie": "3.0.2" + } +} diff --git a/www/lib/localforage/src/drivers/indexeddb.js b/www/lib/localforage/src/drivers/indexeddb.js new file mode 100644 index 00000000..2dd52554 --- /dev/null +++ b/www/lib/localforage/src/drivers/indexeddb.js @@ -0,0 +1,689 @@ +import createBlob from '../utils/createBlob'; +import idb from '../utils/idb'; +import Promise from '../utils/promise'; +import executeCallback from '../utils/executeCallback'; + +// Some code originally from async_storage.js in +// [Gaia](https://github.com/mozilla-b2g/gaia). + +var DETECT_BLOB_SUPPORT_STORE = 'local-forage-detect-blob-support'; +var supportsBlobs; +var dbContexts; + +// Transform a binary string to an array buffer, because otherwise +// weird stuff happens when you try to work with the binary string directly. +// It is known. +// From http://stackoverflow.com/questions/14967647/ (continues on next line) +// encode-decode-image-with-base64-breaks-image (2013-04-21) +function _binStringToArrayBuffer(bin) { + var length = bin.length; + var buf = new ArrayBuffer(length); + var arr = new Uint8Array(buf); + for (var i = 0; i < length; i++) { + arr[i] = bin.charCodeAt(i); + } + return buf; +} + +// +// Blobs are not supported in all versions of IndexedDB, notably +// Chrome <37 and Android <5. In those versions, storing a blob will throw. +// +// Various other blob bugs exist in Chrome v37-42 (inclusive). +// Detecting them is expensive and confusing to users, and Chrome 37-42 +// is at very low usage worldwide, so we do a hacky userAgent check instead. +// +// content-type bug: https://code.google.com/p/chromium/issues/detail?id=408120 +// 404 bug: https://code.google.com/p/chromium/issues/detail?id=447916 +// FileReader bug: https://code.google.com/p/chromium/issues/detail?id=447836 +// +// Code borrowed from PouchDB. See: +// https://github.com/pouchdb/pouchdb/blob/9c25a23/src/adapters/idb/blobSupport.js +// +function _checkBlobSupportWithoutCaching(txn) { + return new Promise(function(resolve) { + var blob = createBlob(['']); + txn.objectStore(DETECT_BLOB_SUPPORT_STORE).put(blob, 'key'); + + txn.onabort = function(e) { + // If the transaction aborts now its due to not being able to + // write to the database, likely due to the disk being full + e.preventDefault(); + e.stopPropagation(); + resolve(false); + }; + + txn.oncomplete = function() { + var matchedChrome = navigator.userAgent.match(/Chrome\/(\d+)/); + var matchedEdge = navigator.userAgent.match(/Edge\//); + // MS Edge pretends to be Chrome 42: + // https://msdn.microsoft.com/en-us/library/hh869301%28v=vs.85%29.aspx + resolve(matchedEdge || !matchedChrome || + parseInt(matchedChrome[1], 10) >= 43); + }; + }).catch(function() { + return false; // error, so assume unsupported + }); +} + +function _checkBlobSupport(idb) { + if (typeof supportsBlobs === 'boolean') { + return Promise.resolve(supportsBlobs); + } + return _checkBlobSupportWithoutCaching(idb).then(function(value) { + supportsBlobs = value; + return supportsBlobs; + }); +} + +function _deferReadiness(dbInfo) { + var dbContext = dbContexts[dbInfo.name]; + + // Create a deferred object representing the current database operation. + var deferredOperation = {}; + + deferredOperation.promise = new Promise(function(resolve) { + deferredOperation.resolve = resolve; + }); + + // Enqueue the deferred operation. + dbContext.deferredOperations.push(deferredOperation); + + // Chain its promise to the database readiness. + if (!dbContext.dbReady) { + dbContext.dbReady = deferredOperation.promise; + } else { + dbContext.dbReady = dbContext.dbReady.then(function() { + return deferredOperation.promise; + }); + } +} + +function _advanceReadiness(dbInfo) { + var dbContext = dbContexts[dbInfo.name]; + + // Dequeue a deferred operation. + var deferredOperation = dbContext.deferredOperations.pop(); + + // Resolve its promise (which is part of the database readiness + // chain of promises). + if (deferredOperation) { + deferredOperation.resolve(); + } +} + +function _getConnection(dbInfo, upgradeNeeded) { + return new Promise(function(resolve, reject) { + + if (dbInfo.db) { + if (upgradeNeeded) { + _deferReadiness(dbInfo); + dbInfo.db.close(); + } else { + return resolve(dbInfo.db); + } + } + + var dbArgs = [dbInfo.name]; + + if (upgradeNeeded) { + dbArgs.push(dbInfo.version); + } + + var openreq = idb.open.apply(idb, dbArgs); + + if (upgradeNeeded) { + openreq.onupgradeneeded = function(e) { + var db = openreq.result; + try { + db.createObjectStore(dbInfo.storeName); + if (e.oldVersion <= 1) { + // Added when support for blob shims was added + db.createObjectStore(DETECT_BLOB_SUPPORT_STORE); + } + } catch (ex) { + if (ex.name === 'ConstraintError') { + console.warn('The database "' + dbInfo.name + '"' + + ' has been upgraded from version ' + e.oldVersion + + ' to version ' + e.newVersion + + ', but the storage "' + dbInfo.storeName + '" already exists.'); + } else { + throw ex; + } + } + }; + } + + openreq.onerror = function() { + reject(openreq.error); + }; + + openreq.onsuccess = function() { + resolve(openreq.result); + _advanceReadiness(dbInfo); + }; + }); +} + +function _getOriginalConnection(dbInfo) { + return _getConnection(dbInfo, false); +} + +function _getUpgradedConnection(dbInfo) { + return _getConnection(dbInfo, true); +} + +function _isUpgradeNeeded(dbInfo, defaultVersion) { + if (!dbInfo.db) { + return true; + } + + var isNewStore = !dbInfo.db.objectStoreNames.contains(dbInfo.storeName); + var isDowngrade = dbInfo.version < dbInfo.db.version; + var isUpgrade = dbInfo.version > dbInfo.db.version; + + if (isDowngrade) { + // If the version is not the default one + // then warn for impossible downgrade. + if (dbInfo.version !== defaultVersion) { + console.warn('The database "' + dbInfo.name + '"' + + ' can\'t be downgraded from version ' + dbInfo.db.version + + ' to version ' + dbInfo.version + '.'); + } + // Align the versions to prevent errors. + dbInfo.version = dbInfo.db.version; + } + + if (isUpgrade || isNewStore) { + // If the store is new then increment the version (if needed). + // This will trigger an "upgradeneeded" event which is required + // for creating a store. + if (isNewStore) { + var incVersion = dbInfo.db.version + 1; + if (incVersion > dbInfo.version) { + dbInfo.version = incVersion; + } + } + + return true; + } + + return false; +} + +// encode a blob for indexeddb engines that don't support blobs +function _encodeBlob(blob) { + return new Promise(function(resolve, reject) { + var reader = new FileReader(); + reader.onerror = reject; + reader.onloadend = function(e) { + var base64 = btoa(e.target.result || ''); + resolve({ + __local_forage_encoded_blob: true, + data: base64, + type: blob.type + }); + }; + reader.readAsBinaryString(blob); + }); +} + +// decode an encoded blob +function _decodeBlob(encodedBlob) { + var arrayBuff = _binStringToArrayBuffer(atob(encodedBlob.data)); + return createBlob([arrayBuff], {type: encodedBlob.type}); +} + +// is this one of our fancy encoded blobs? +function _isEncodedBlob(value) { + return value && value.__local_forage_encoded_blob; +} + +// Specialize the default `ready()` function by making it dependent +// on the current database operations. Thus, the driver will be actually +// ready when it's been initialized (default) *and* there are no pending +// operations on the database (initiated by some other instances). +function _fullyReady(callback) { + var self = this; + + var promise = self._initReady().then(function() { + var dbContext = dbContexts[self._dbInfo.name]; + + if (dbContext && dbContext.dbReady) { + return dbContext.dbReady; + } + }); + + promise.then(callback, callback); + return promise; +} + +// Open the IndexedDB database (automatically creates one if one didn't +// previously exist), using any options set in the config. +function _initStorage(options) { + var self = this; + var dbInfo = { + db: null + }; + + if (options) { + for (var i in options) { + dbInfo[i] = options[i]; + } + } + + // Initialize a singleton container for all running localForages. + if (!dbContexts) { + dbContexts = {}; + } + + // Get the current context of the database; + var dbContext = dbContexts[dbInfo.name]; + + // ...or create a new context. + if (!dbContext) { + dbContext = { + // Running localForages sharing a database. + forages: [], + // Shared database. + db: null, + // Database readiness (promise). + dbReady: null, + // Deferred operations on the database. + deferredOperations: [] + }; + // Register the new context in the global container. + dbContexts[dbInfo.name] = dbContext; + } + + // Register itself as a running localForage in the current context. + dbContext.forages.push(self); + + // Replace the default `ready()` function with the specialized one. + if (!self._initReady) { + self._initReady = self.ready; + self.ready = _fullyReady; + } + + // Create an array of initialization states of the related localForages. + var initPromises = []; + + function ignoreErrors() { + // Don't handle errors here, + // just makes sure related localForages aren't pending. + return Promise.resolve(); + } + + for (var j = 0; j < dbContext.forages.length; j++) { + var forage = dbContext.forages[j]; + if (forage !== self) { // Don't wait for itself... + initPromises.push(forage._initReady().catch(ignoreErrors)); + } + } + + // Take a snapshot of the related localForages. + var forages = dbContext.forages.slice(0); + + // Initialize the connection process only when + // all the related localForages aren't pending. + return Promise.all(initPromises).then(function() { + dbInfo.db = dbContext.db; + // Get the connection or open a new one without upgrade. + return _getOriginalConnection(dbInfo); + }).then(function(db) { + dbInfo.db = db; + if (_isUpgradeNeeded(dbInfo, self._defaultConfig.version)) { + // Reopen the database for upgrading. + return _getUpgradedConnection(dbInfo); + } + return db; + }).then(function(db) { + dbInfo.db = dbContext.db = db; + self._dbInfo = dbInfo; + // Share the final connection amongst related localForages. + for (var k = 0; k < forages.length; k++) { + var forage = forages[k]; + if (forage !== self) { // Self is already up-to-date. + forage._dbInfo.db = dbInfo.db; + forage._dbInfo.version = dbInfo.version; + } + } + }); +} + +function getItem(key, callback) { + var self = this; + + // Cast the key to a string, as that's all we can set as a key. + if (typeof key !== 'string') { + console.warn(key + + ' used as a key, but it is not a string.'); + key = String(key); + } + + var promise = new Promise(function(resolve, reject) { + self.ready().then(function() { + var dbInfo = self._dbInfo; + var store = dbInfo.db.transaction(dbInfo.storeName, 'readonly') + .objectStore(dbInfo.storeName); + var req = store.get(key); + + req.onsuccess = function() { + var value = req.result; + if (value === undefined) { + value = null; + } + if (_isEncodedBlob(value)) { + value = _decodeBlob(value); + } + resolve(value); + }; + + req.onerror = function() { + reject(req.error); + }; + }).catch(reject); + }); + + executeCallback(promise, callback); + return promise; +} + +// Iterate over all items stored in database. +function iterate(iterator, callback) { + var self = this; + + var promise = new Promise(function(resolve, reject) { + self.ready().then(function() { + var dbInfo = self._dbInfo; + var store = dbInfo.db.transaction(dbInfo.storeName, 'readonly') + .objectStore(dbInfo.storeName); + + var req = store.openCursor(); + var iterationNumber = 1; + + req.onsuccess = function() { + var cursor = req.result; + + if (cursor) { + var value = cursor.value; + if (_isEncodedBlob(value)) { + value = _decodeBlob(value); + } + var result = iterator(value, cursor.key, + iterationNumber++); + + if (result !== void(0)) { + resolve(result); + } else { + cursor.continue(); + } + } else { + resolve(); + } + }; + + req.onerror = function() { + reject(req.error); + }; + }).catch(reject); + }); + + executeCallback(promise, callback); + + return promise; +} + +function setItem(key, value, callback) { + var self = this; + + // Cast the key to a string, as that's all we can set as a key. + if (typeof key !== 'string') { + console.warn(key + + ' used as a key, but it is not a string.'); + key = String(key); + } + + var promise = new Promise(function(resolve, reject) { + var dbInfo; + self.ready().then(function() { + dbInfo = self._dbInfo; + if (value instanceof Blob) { + return _checkBlobSupport(dbInfo.db).then(function(blobSupport) { + if (blobSupport) { + return value; + } + return _encodeBlob(value); + }); + } + return value; + }).then(function(value) { + var transaction = dbInfo.db.transaction(dbInfo.storeName, 'readwrite'); + var store = transaction.objectStore(dbInfo.storeName); + + // The reason we don't _save_ null is because IE 10 does + // not support saving the `null` type in IndexedDB. How + // ironic, given the bug below! + // See: https://github.com/mozilla/localForage/issues/161 + if (value === null) { + value = undefined; + } + + transaction.oncomplete = function() { + // Cast to undefined so the value passed to + // callback/promise is the same as what one would get out + // of `getItem()` later. This leads to some weirdness + // (setItem('foo', undefined) will return `null`), but + // it's not my fault localStorage is our baseline and that + // it's weird. + if (value === undefined) { + value = null; + } + + resolve(value); + }; + transaction.onabort = transaction.onerror = function() { + var err = req.error ? req.error : req.transaction.error; + reject(err); + }; + + var req = store.put(value, key); + }).catch(reject); + }); + + executeCallback(promise, callback); + return promise; +} + +function removeItem(key, callback) { + var self = this; + + // Cast the key to a string, as that's all we can set as a key. + if (typeof key !== 'string') { + console.warn(key + + ' used as a key, but it is not a string.'); + key = String(key); + } + + var promise = new Promise(function(resolve, reject) { + self.ready().then(function() { + var dbInfo = self._dbInfo; + var transaction = dbInfo.db.transaction(dbInfo.storeName, 'readwrite'); + var store = transaction.objectStore(dbInfo.storeName); + + // We use a Grunt task to make this safe for IE and some + // versions of Android (including those used by Cordova). + // Normally IE won't like `.delete()` and will insist on + // using `['delete']()`, but we have a build step that + // fixes this for us now. + var req = store.delete(key); + transaction.oncomplete = function() { + resolve(); + }; + + transaction.onerror = function() { + reject(req.error); + }; + + // The request will be also be aborted if we've exceeded our storage + // space. + transaction.onabort = function() { + var err = req.error ? req.error : req.transaction.error; + reject(err); + }; + }).catch(reject); + }); + + executeCallback(promise, callback); + return promise; +} + +function clear(callback) { + var self = this; + + var promise = new Promise(function(resolve, reject) { + self.ready().then(function() { + var dbInfo = self._dbInfo; + var transaction = dbInfo.db.transaction(dbInfo.storeName, 'readwrite'); + var store = transaction.objectStore(dbInfo.storeName); + var req = store.clear(); + + transaction.oncomplete = function() { + resolve(); + }; + + transaction.onabort = transaction.onerror = function() { + var err = req.error ? req.error : req.transaction.error; + reject(err); + }; + }).catch(reject); + }); + + executeCallback(promise, callback); + return promise; +} + +function length(callback) { + var self = this; + + var promise = new Promise(function(resolve, reject) { + self.ready().then(function() { + var dbInfo = self._dbInfo; + var store = dbInfo.db.transaction(dbInfo.storeName, 'readonly') + .objectStore(dbInfo.storeName); + var req = store.count(); + + req.onsuccess = function() { + resolve(req.result); + }; + + req.onerror = function() { + reject(req.error); + }; + }).catch(reject); + }); + + executeCallback(promise, callback); + return promise; +} + +function key(n, callback) { + var self = this; + + var promise = new Promise(function(resolve, reject) { + if (n < 0) { + resolve(null); + + return; + } + + self.ready().then(function() { + var dbInfo = self._dbInfo; + var store = dbInfo.db.transaction(dbInfo.storeName, 'readonly') + .objectStore(dbInfo.storeName); + + var advanced = false; + var req = store.openCursor(); + req.onsuccess = function() { + var cursor = req.result; + if (!cursor) { + // this means there weren't enough keys + resolve(null); + + return; + } + + if (n === 0) { + // We have the first key, return it if that's what they + // wanted. + resolve(cursor.key); + } else { + if (!advanced) { + // Otherwise, ask the cursor to skip ahead n + // records. + advanced = true; + cursor.advance(n); + } else { + // When we get here, we've got the nth key. + resolve(cursor.key); + } + } + }; + + req.onerror = function() { + reject(req.error); + }; + }).catch(reject); + }); + + executeCallback(promise, callback); + return promise; +} + +function keys(callback) { + var self = this; + + var promise = new Promise(function(resolve, reject) { + self.ready().then(function() { + var dbInfo = self._dbInfo; + var store = dbInfo.db.transaction(dbInfo.storeName, 'readonly') + .objectStore(dbInfo.storeName); + + var req = store.openCursor(); + var keys = []; + + req.onsuccess = function() { + var cursor = req.result; + + if (!cursor) { + resolve(keys); + return; + } + + keys.push(cursor.key); + cursor.continue(); + }; + + req.onerror = function() { + reject(req.error); + }; + }).catch(reject); + }); + + executeCallback(promise, callback); + return promise; +} + +var asyncStorage = { + _driver: 'asyncStorage', + _initStorage: _initStorage, + iterate: iterate, + getItem: getItem, + setItem: setItem, + removeItem: removeItem, + clear: clear, + length: length, + key: key, + keys: keys +}; +export default asyncStorage; diff --git a/www/lib/localforage/src/drivers/localstorage.js b/www/lib/localforage/src/drivers/localstorage.js new file mode 100644 index 00000000..85ef32bf --- /dev/null +++ b/www/lib/localforage/src/drivers/localstorage.js @@ -0,0 +1,270 @@ +// If IndexedDB isn't available, we'll fall back to localStorage. +// Note that this will have considerable performance and storage +// side-effects (all data will be serialized on save and only data that +// can be converted to a string via `JSON.stringify()` will be saved). + +import serializer from '../utils/serializer'; +import Promise from '../utils/promise'; +import executeCallback from '../utils/executeCallback'; + +// Config the localStorage backend, using options set in the config. +function _initStorage(options) { + var self = this; + var dbInfo = {}; + if (options) { + for (var i in options) { + dbInfo[i] = options[i]; + } + } + + dbInfo.keyPrefix = dbInfo.name + '/'; + + if (dbInfo.storeName !== self._defaultConfig.storeName) { + dbInfo.keyPrefix += dbInfo.storeName + '/'; + } + + self._dbInfo = dbInfo; + dbInfo.serializer = serializer; + + return Promise.resolve(); +} + +// Remove all keys from the datastore, effectively destroying all data in +// the app's key/value store! +function clear(callback) { + var self = this; + var promise = self.ready().then(function() { + var keyPrefix = self._dbInfo.keyPrefix; + + for (var i = localStorage.length - 1; i >= 0; i--) { + var key = localStorage.key(i); + + if (key.indexOf(keyPrefix) === 0) { + localStorage.removeItem(key); + } + } + }); + + executeCallback(promise, callback); + return promise; +} + +// Retrieve an item from the store. Unlike the original async_storage +// library in Gaia, we don't modify return values at all. If a key's value +// is `undefined`, we pass that value to the callback function. +function getItem(key, callback) { + var self = this; + + // Cast the key to a string, as that's all we can set as a key. + if (typeof key !== 'string') { + console.warn(key + + ' used as a key, but it is not a string.'); + key = String(key); + } + + var promise = self.ready().then(function() { + var dbInfo = self._dbInfo; + var result = localStorage.getItem(dbInfo.keyPrefix + key); + + // If a result was found, parse it from the serialized + // string into a JS object. If result isn't truthy, the key + // is likely undefined and we'll pass it straight to the + // callback. + if (result) { + result = dbInfo.serializer.deserialize(result); + } + + return result; + }); + + executeCallback(promise, callback); + return promise; +} + +// Iterate over all items in the store. +function iterate(iterator, callback) { + var self = this; + + var promise = self.ready().then(function() { + var dbInfo = self._dbInfo; + var keyPrefix = dbInfo.keyPrefix; + var keyPrefixLength = keyPrefix.length; + var length = localStorage.length; + + // We use a dedicated iterator instead of the `i` variable below + // so other keys we fetch in localStorage aren't counted in + // the `iterationNumber` argument passed to the `iterate()` + // callback. + // + // See: github.com/mozilla/localForage/pull/435#discussion_r38061530 + var iterationNumber = 1; + + for (var i = 0; i < length; i++) { + var key = localStorage.key(i); + if (key.indexOf(keyPrefix) !== 0) { + continue; + } + var value = localStorage.getItem(key); + + // If a result was found, parse it from the serialized + // string into a JS object. If result isn't truthy, the + // key is likely undefined and we'll pass it straight + // to the iterator. + if (value) { + value = dbInfo.serializer.deserialize(value); + } + + value = iterator(value, key.substring(keyPrefixLength), + iterationNumber++); + + if (value !== void(0)) { + return value; + } + } + }); + + executeCallback(promise, callback); + return promise; +} + +// Same as localStorage's key() method, except takes a callback. +function key(n, callback) { + var self = this; + var promise = self.ready().then(function() { + var dbInfo = self._dbInfo; + var result; + try { + result = localStorage.key(n); + } catch (error) { + result = null; + } + + // Remove the prefix from the key, if a key is found. + if (result) { + result = result.substring(dbInfo.keyPrefix.length); + } + + return result; + }); + + executeCallback(promise, callback); + return promise; +} + +function keys(callback) { + var self = this; + var promise = self.ready().then(function() { + var dbInfo = self._dbInfo; + var length = localStorage.length; + var keys = []; + + for (var i = 0; i < length; i++) { + if (localStorage.key(i).indexOf(dbInfo.keyPrefix) === 0) { + keys.push(localStorage.key(i).substring(dbInfo.keyPrefix.length)); + } + } + + return keys; + }); + + executeCallback(promise, callback); + return promise; +} + +// Supply the number of keys in the datastore to the callback function. +function length(callback) { + var self = this; + var promise = self.keys().then(function(keys) { + return keys.length; + }); + + executeCallback(promise, callback); + return promise; +} + +// Remove an item from the store, nice and simple. +function removeItem(key, callback) { + var self = this; + + // Cast the key to a string, as that's all we can set as a key. + if (typeof key !== 'string') { + console.warn(key + + ' used as a key, but it is not a string.'); + key = String(key); + } + + var promise = self.ready().then(function() { + var dbInfo = self._dbInfo; + localStorage.removeItem(dbInfo.keyPrefix + key); + }); + + executeCallback(promise, callback); + return promise; +} + +// Set a key's value and run an optional callback once the value is set. +// Unlike Gaia's implementation, the callback function is passed the value, +// in case you want to operate on that value only after you're sure it +// saved, or something like that. +function setItem(key, value, callback) { + var self = this; + + // Cast the key to a string, as that's all we can set as a key. + if (typeof key !== 'string') { + console.warn(key + + ' used as a key, but it is not a string.'); + key = String(key); + } + + var promise = self.ready().then(function() { + // Convert undefined values to null. + // https://github.com/mozilla/localForage/pull/42 + if (value === undefined) { + value = null; + } + + // Save the original value to pass to the callback. + var originalValue = value; + + return new Promise(function(resolve, reject) { + var dbInfo = self._dbInfo; + dbInfo.serializer.serialize(value, function(value, error) { + if (error) { + reject(error); + } else { + try { + localStorage.setItem(dbInfo.keyPrefix + key, value); + resolve(originalValue); + } catch (e) { + // localStorage capacity exceeded. + // TODO: Make this a specific error/event. + if (e.name === 'QuotaExceededError' || + e.name === 'NS_ERROR_DOM_QUOTA_REACHED') { + reject(e); + } + reject(e); + } + } + }); + }); + }); + + executeCallback(promise, callback); + return promise; +} + +var localStorageWrapper = { + _driver: 'localStorageWrapper', + _initStorage: _initStorage, + // Default API, from Gaia/localStorage. + iterate: iterate, + getItem: getItem, + setItem: setItem, + removeItem: removeItem, + clear: clear, + length: length, + key: key, + keys: keys +}; + +export default localStorageWrapper; diff --git a/www/lib/localforage/src/drivers/websql.js b/www/lib/localforage/src/drivers/websql.js new file mode 100644 index 00000000..04e6df2d --- /dev/null +++ b/www/lib/localforage/src/drivers/websql.js @@ -0,0 +1,351 @@ +import serializer from '../utils/serializer'; +import Promise from '../utils/promise'; +import executeCallback from '../utils/executeCallback'; + +/* + * Includes code from: + * + * base64-arraybuffer + * https://github.com/niklasvh/base64-arraybuffer + * + * Copyright (c) 2012 Niklas von Hertzen + * Licensed under the MIT license. + */ +// Open the WebSQL database (automatically creates one if one didn't +// previously exist), using any options set in the config. +function _initStorage(options) { + var self = this; + var dbInfo = { + db: null + }; + + if (options) { + for (var i in options) { + dbInfo[i] = typeof(options[i]) !== 'string' ? + options[i].toString() : options[i]; + } + } + + var dbInfoPromise = new Promise(function(resolve, reject) { + // Open the database; the openDatabase API will automatically + // create it for us if it doesn't exist. + try { + dbInfo.db = openDatabase(dbInfo.name, String(dbInfo.version), + dbInfo.description, dbInfo.size); + } catch (e) { + return reject(e); + } + + // Create our key/value table if it doesn't exist. + dbInfo.db.transaction(function(t) { + t.executeSql('CREATE TABLE IF NOT EXISTS ' + dbInfo.storeName + + ' (id INTEGER PRIMARY KEY, key unique, value)', [], + function() { + self._dbInfo = dbInfo; + resolve(); + }, function(t, error) { + reject(error); + }); + }); + }); + + dbInfo.serializer = serializer; + return dbInfoPromise; +} + +function getItem(key, callback) { + var self = this; + + // Cast the key to a string, as that's all we can set as a key. + if (typeof key !== 'string') { + console.warn(key + + ' used as a key, but it is not a string.'); + key = String(key); + } + + var promise = new Promise(function(resolve, reject) { + self.ready().then(function() { + var dbInfo = self._dbInfo; + dbInfo.db.transaction(function(t) { + t.executeSql('SELECT * FROM ' + dbInfo.storeName + + ' WHERE key = ? LIMIT 1', [key], + function(t, results) { + var result = results.rows.length ? + results.rows.item(0).value : null; + + // Check to see if this is serialized content we need to + // unpack. + if (result) { + result = dbInfo.serializer.deserialize(result); + } + + resolve(result); + }, function(t, error) { + + reject(error); + }); + }); + }).catch(reject); + }); + + executeCallback(promise, callback); + return promise; +} + +function iterate(iterator, callback) { + var self = this; + + var promise = new Promise(function(resolve, reject) { + self.ready().then(function() { + var dbInfo = self._dbInfo; + + dbInfo.db.transaction(function(t) { + t.executeSql('SELECT * FROM ' + dbInfo.storeName, [], + function(t, results) { + var rows = results.rows; + var length = rows.length; + + for (var i = 0; i < length; i++) { + var item = rows.item(i); + var result = item.value; + + // Check to see if this is serialized content + // we need to unpack. + if (result) { + result = dbInfo.serializer.deserialize(result); + } + + result = iterator(result, item.key, i + 1); + + // void(0) prevents problems with redefinition + // of `undefined`. + if (result !== void(0)) { + resolve(result); + return; + } + } + + resolve(); + }, function(t, error) { + reject(error); + }); + }); + }).catch(reject); + }); + + executeCallback(promise, callback); + return promise; +} + +function setItem(key, value, callback) { + var self = this; + + // Cast the key to a string, as that's all we can set as a key. + if (typeof key !== 'string') { + console.warn(key + + ' used as a key, but it is not a string.'); + key = String(key); + } + + var promise = new Promise(function(resolve, reject) { + self.ready().then(function() { + // The localStorage API doesn't return undefined values in an + // "expected" way, so undefined is always cast to null in all + // drivers. See: https://github.com/mozilla/localForage/pull/42 + if (value === undefined) { + value = null; + } + + // Save the original value to pass to the callback. + var originalValue = value; + + var dbInfo = self._dbInfo; + dbInfo.serializer.serialize(value, function(value, error) { + if (error) { + reject(error); + } else { + dbInfo.db.transaction(function(t) { + t.executeSql('INSERT OR REPLACE INTO ' + + dbInfo.storeName + + ' (key, value) VALUES (?, ?)', + [key, value], function() { + resolve(originalValue); + }, function(t, error) { + reject(error); + }); + }, function(sqlError) { + // The transaction failed; check + // to see if it's a quota error. + if (sqlError.code === sqlError.QUOTA_ERR) { + // We reject the callback outright for now, but + // it's worth trying to re-run the transaction. + // Even if the user accepts the prompt to use + // more storage on Safari, this error will + // be called. + // + // TODO: Try to re-run the transaction. + reject(sqlError); + } + }); + } + }); + }).catch(reject); + }); + + executeCallback(promise, callback); + return promise; +} + +function removeItem(key, callback) { + var self = this; + + // Cast the key to a string, as that's all we can set as a key. + if (typeof key !== 'string') { + console.warn(key + + ' used as a key, but it is not a string.'); + key = String(key); + } + + var promise = new Promise(function(resolve, reject) { + self.ready().then(function() { + var dbInfo = self._dbInfo; + dbInfo.db.transaction(function(t) { + t.executeSql('DELETE FROM ' + dbInfo.storeName + + ' WHERE key = ?', [key], + function() { + resolve(); + }, function(t, error) { + + reject(error); + }); + }); + }).catch(reject); + }); + + executeCallback(promise, callback); + return promise; +} + +// Deletes every item in the table. +// TODO: Find out if this resets the AUTO_INCREMENT number. +function clear(callback) { + var self = this; + + var promise = new Promise(function(resolve, reject) { + self.ready().then(function() { + var dbInfo = self._dbInfo; + dbInfo.db.transaction(function(t) { + t.executeSql('DELETE FROM ' + dbInfo.storeName, [], + function() { + resolve(); + }, function(t, error) { + reject(error); + }); + }); + }).catch(reject); + }); + + executeCallback(promise, callback); + return promise; +} + +// Does a simple `COUNT(key)` to get the number of items stored in +// localForage. +function length(callback) { + var self = this; + + var promise = new Promise(function(resolve, reject) { + self.ready().then(function() { + var dbInfo = self._dbInfo; + dbInfo.db.transaction(function(t) { + // Ahhh, SQL makes this one soooooo easy. + t.executeSql('SELECT COUNT(key) as c FROM ' + + dbInfo.storeName, [], function(t, results) { + var result = results.rows.item(0).c; + + resolve(result); + }, function(t, error) { + + reject(error); + }); + }); + }).catch(reject); + }); + + executeCallback(promise, callback); + return promise; +} + +// Return the key located at key index X; essentially gets the key from a +// `WHERE id = ?`. This is the most efficient way I can think to implement +// this rarely-used (in my experience) part of the API, but it can seem +// inconsistent, because we do `INSERT OR REPLACE INTO` on `setItem()`, so +// the ID of each key will change every time it's updated. Perhaps a stored +// procedure for the `setItem()` SQL would solve this problem? +// TODO: Don't change ID on `setItem()`. +function key(n, callback) { + var self = this; + + var promise = new Promise(function(resolve, reject) { + self.ready().then(function() { + var dbInfo = self._dbInfo; + dbInfo.db.transaction(function(t) { + t.executeSql('SELECT key FROM ' + dbInfo.storeName + + ' WHERE id = ? LIMIT 1', [n + 1], + function(t, results) { + var result = results.rows.length ? + results.rows.item(0).key : null; + resolve(result); + }, function(t, error) { + reject(error); + }); + }); + }).catch(reject); + }); + + executeCallback(promise, callback); + return promise; +} + +function keys(callback) { + var self = this; + + var promise = new Promise(function(resolve, reject) { + self.ready().then(function() { + var dbInfo = self._dbInfo; + dbInfo.db.transaction(function(t) { + t.executeSql('SELECT key FROM ' + dbInfo.storeName, [], + function(t, results) { + var keys = []; + + for (var i = 0; i < results.rows.length; i++) { + keys.push(results.rows.item(i).key); + } + + resolve(keys); + }, function(t, error) { + + reject(error); + }); + }); + }).catch(reject); + }); + + executeCallback(promise, callback); + return promise; +} + +var webSQLStorage = { + _driver: 'webSQLStorage', + _initStorage: _initStorage, + iterate: iterate, + getItem: getItem, + setItem: setItem, + removeItem: removeItem, + clear: clear, + length: length, + key: key, + keys: keys +}; + +export default webSQLStorage; diff --git a/www/lib/localforage/src/localforage.js b/www/lib/localforage/src/localforage.js new file mode 100644 index 00000000..837f3c7a --- /dev/null +++ b/www/lib/localforage/src/localforage.js @@ -0,0 +1,377 @@ +import isIndexedDBValid from './utils/isIndexedDBValid'; +import isWebSQLValid from './utils/isWebSQLValid'; +import isLocalStorageValid from './utils/isLocalStorageValid'; +import idbDriver from './drivers/indexeddb'; +import websqlDriver from './drivers/websql'; +import localstorageDriver from './drivers/localstorage'; +import serializer from './utils/serializer'; +import Promise from './utils/promise'; +import executeTwoCallbacks from './utils/executeTwoCallbacks'; + +// Custom drivers are stored here when `defineDriver()` is called. +// They are shared across all instances of localForage. +var CustomDrivers = {}; + +var DriverType = { + INDEXEDDB: 'asyncStorage', + LOCALSTORAGE: 'localStorageWrapper', + WEBSQL: 'webSQLStorage' +}; + +var DefaultDriverOrder = [ + DriverType.INDEXEDDB, + DriverType.WEBSQL, + DriverType.LOCALSTORAGE +]; + +var LibraryMethods = [ + 'clear', + 'getItem', + 'iterate', + 'key', + 'keys', + 'length', + 'removeItem', + 'setItem' +]; + +var DefaultConfig = { + description: '', + driver: DefaultDriverOrder.slice(), + name: 'localforage', + // Default DB size is _JUST UNDER_ 5MB, as it's the highest size + // we can use without a prompt. + size: 4980736, + storeName: 'keyvaluepairs', + version: 1.0 +}; + +var driverSupport = {}; +// Check to see if IndexedDB is available and if it is the latest +// implementation; it's our preferred backend library. We use "_spec_test" +// as the name of the database because it's not the one we'll operate on, +// but it's useful to make sure its using the right spec. +// See: https://github.com/mozilla/localForage/issues/128 +driverSupport[DriverType.INDEXEDDB] = isIndexedDBValid(); + +driverSupport[DriverType.WEBSQL] = isWebSQLValid(); + +driverSupport[DriverType.LOCALSTORAGE] = isLocalStorageValid(); + +var isArray = Array.isArray || function(arg) { + return Object.prototype.toString.call(arg) === '[object Array]'; + }; + +function callWhenReady(localForageInstance, libraryMethod) { + localForageInstance[libraryMethod] = function() { + var _args = arguments; + return localForageInstance.ready().then(function() { + return localForageInstance[libraryMethod].apply(localForageInstance, _args); + }); + }; +} + +function extend() { + for (var i = 1; i < arguments.length; i++) { + var arg = arguments[i]; + + if (arg) { + for (var key in arg) { + if (arg.hasOwnProperty(key)) { + if (isArray(arg[key])) { + arguments[0][key] = arg[key].slice(); + } else { + arguments[0][key] = arg[key]; + } + } + } + } + } + + return arguments[0]; +} + +function isLibraryDriver(driverName) { + for (var driver in DriverType) { + if (DriverType.hasOwnProperty(driver) && + DriverType[driver] === driverName) { + return true; + } + } + + return false; +} + +class LocalForage { + constructor(options) { + this.INDEXEDDB = DriverType.INDEXEDDB; + this.LOCALSTORAGE = DriverType.LOCALSTORAGE; + this.WEBSQL = DriverType.WEBSQL; + + this._defaultConfig = extend({}, DefaultConfig); + this._config = extend({}, this._defaultConfig, options); + this._driverSet = null; + this._initDriver = null; + this._ready = false; + this._dbInfo = null; + + this._wrapLibraryMethodsWithReady(); + this.setDriver(this._config.driver); + } + + // Set any config values for localForage; can be called anytime before + // the first API call (e.g. `getItem`, `setItem`). + // We loop through options so we don't overwrite existing config + // values. + config(options) { + // If the options argument is an object, we use it to set values. + // Otherwise, we return either a specified config value or all + // config values. + if (typeof(options) === 'object') { + // If localforage is ready and fully initialized, we can't set + // any new configuration values. Instead, we return an error. + if (this._ready) { + return new Error("Can't call config() after localforage " + + 'has been used.'); + } + + for (var i in options) { + if (i === 'storeName') { + options[i] = options[i].replace(/\W/g, '_'); + } + + this._config[i] = options[i]; + } + + // after all config options are set and + // the driver option is used, try setting it + if ('driver' in options && options.driver) { + this.setDriver(this._config.driver); + } + + return true; + } else if (typeof(options) === 'string') { + return this._config[options]; + } else { + return this._config; + } + } + + // Used to define a custom driver, shared across all instances of + // localForage. + defineDriver(driverObject, callback, errorCallback) { + var promise = new Promise(function(resolve, reject) { + try { + var driverName = driverObject._driver; + var complianceError = new Error( + 'Custom driver not compliant; see ' + + 'https://mozilla.github.io/localForage/#definedriver' + ); + var namingError = new Error( + 'Custom driver name already in use: ' + driverObject._driver + ); + + // A driver name should be defined and not overlap with the + // library-defined, default drivers. + if (!driverObject._driver) { + reject(complianceError); + return; + } + if (isLibraryDriver(driverObject._driver)) { + reject(namingError); + return; + } + + var customDriverMethods = LibraryMethods.concat('_initStorage'); + for (var i = 0; i < customDriverMethods.length; i++) { + var customDriverMethod = customDriverMethods[i]; + if (!customDriverMethod || !driverObject[customDriverMethod] || + typeof driverObject[customDriverMethod] !== 'function') { + reject(complianceError); + return; + } + } + + var supportPromise = Promise.resolve(true); + if ('_support' in driverObject) { + if (driverObject._support && typeof driverObject._support === 'function') { + supportPromise = driverObject._support(); + } else { + supportPromise = Promise.resolve(!!driverObject._support); + } + } + + supportPromise.then(function(supportResult) { + driverSupport[driverName] = supportResult; + CustomDrivers[driverName] = driverObject; + resolve(); + }, reject); + } catch (e) { + reject(e); + } + }); + + executeTwoCallbacks(promise, callback, errorCallback); + return promise; + } + + driver() { + return this._driver || null; + } + + getDriver(driverName, callback, errorCallback) { + var self = this; + var getDriverPromise = Promise.resolve().then(() => { + if (isLibraryDriver(driverName)) { + switch (driverName) { + case self.INDEXEDDB: + return idbDriver; + case self.LOCALSTORAGE: + return localstorageDriver; + case self.WEBSQL: + return websqlDriver; + } + } else if (CustomDrivers[driverName]) { + return CustomDrivers[driverName]; + } else { + throw new Error('Driver not found.'); + } + }); + executeTwoCallbacks(getDriverPromise, callback, errorCallback); + return getDriverPromise; + } + + getSerializer(callback) { + var serializerPromise = Promise.resolve(serializer); + executeTwoCallbacks(serializerPromise, callback); + return serializerPromise; + } + + ready(callback) { + var self = this; + + var promise = self._driverSet.then(() => { + if (self._ready === null) { + self._ready = self._initDriver(); + } + + return self._ready; + }); + + executeTwoCallbacks(promise, callback, callback); + return promise; + } + + setDriver(drivers, callback, errorCallback) { + var self = this; + + if (!isArray(drivers)) { + drivers = [drivers]; + } + + var supportedDrivers = this._getSupportedDrivers(drivers); + + function setDriverToConfig() { + self._config.driver = self.driver(); + } + + function initDriver(supportedDrivers) { + return function() { + var currentDriverIndex = 0; + + function driverPromiseLoop() { + while (currentDriverIndex < supportedDrivers.length) { + var driverName = supportedDrivers[currentDriverIndex]; + currentDriverIndex++; + + self._dbInfo = null; + self._ready = null; + + return self.getDriver(driverName) + .then(driver => { + self._extend(driver); + setDriverToConfig(); + + self._ready = self._initStorage(self._config); + return self._ready; + }) + .catch(driverPromiseLoop); + } + + setDriverToConfig(); + var error = new Error('No available storage method found.'); + self._driverSet = Promise.reject(error); + return self._driverSet; + } + + return driverPromiseLoop(); + }; + } + + // There might be a driver initialization in progress + // so wait for it to finish in order to avoid a possible + // race condition to set _dbInfo + var oldDriverSetDone = this._driverSet !== null ? + this._driverSet.catch(() => Promise.resolve()) : + Promise.resolve(); + + this._driverSet = oldDriverSetDone.then(() => { + var driverName = supportedDrivers[0]; + self._dbInfo = null; + self._ready = null; + + return self.getDriver(driverName) + .then(driver => { + self._driver = driver._driver; + setDriverToConfig(); + self._wrapLibraryMethodsWithReady(); + self._initDriver = initDriver(supportedDrivers); + }); + }).catch(() => { + setDriverToConfig(); + var error = new Error('No available storage method found.'); + self._driverSet = Promise.reject(error); + return self._driverSet; + }); + + executeTwoCallbacks(this._driverSet, callback, errorCallback); + return this._driverSet; + } + + supports(driverName) { + return !!driverSupport[driverName]; + } + + _extend(libraryMethodsAndProperties) { + extend(this, libraryMethodsAndProperties); + } + + _getSupportedDrivers(drivers) { + var supportedDrivers = []; + for (var i = 0, len = drivers.length; i < len; i++) { + var driverName = drivers[i]; + if (this.supports(driverName)) { + supportedDrivers.push(driverName); + } + } + return supportedDrivers; + } + + _wrapLibraryMethodsWithReady() { + // Add a stub for each driver API method that delays the call to the + // corresponding driver method until localForage is ready. These stubs + // will be replaced by the driver methods as soon as the driver is + // loaded, so there is no performance impact. + for (var i = 0; i < LibraryMethods.length; i++) { + callWhenReady(this, LibraryMethods[i]); + } + } + + createInstance(options) { + return new LocalForage(options); + } +} + +// The actual localForage object that we expose as a module or via a +// global. It's extended by pulling in one of our other libraries. +export default new LocalForage(); diff --git a/www/lib/localforage/src/utils/createBlob.js b/www/lib/localforage/src/utils/createBlob.js new file mode 100644 index 00000000..4d698551 --- /dev/null +++ b/www/lib/localforage/src/utils/createBlob.js @@ -0,0 +1,29 @@ +// Abstracts constructing a Blob object, so it also works in older +// browsers that don't support the native Blob constructor. (i.e. +// old QtWebKit versions, at least). +// Abstracts constructing a Blob object, so it also works in older +// browsers that don't support the native Blob constructor. (i.e. +// old QtWebKit versions, at least). +function createBlob(parts, properties) { + /* global BlobBuilder,MSBlobBuilder,MozBlobBuilder,WebKitBlobBuilder */ + parts = parts || []; + properties = properties || {}; + try { + return new Blob(parts, properties); + } catch (e) { + if (e.name !== 'TypeError') { + throw e; + } + var Builder = typeof BlobBuilder !== 'undefined' ? BlobBuilder : + typeof MSBlobBuilder !== 'undefined' ? MSBlobBuilder : + typeof MozBlobBuilder !== 'undefined' ? MozBlobBuilder : + WebKitBlobBuilder; + var builder = new Builder(); + for (var i = 0; i < parts.length; i += 1) { + builder.append(parts[i]); + } + return builder.getBlob(properties.type); + } +} + +export default createBlob; diff --git a/www/lib/localforage/src/utils/executeCallback.js b/www/lib/localforage/src/utils/executeCallback.js new file mode 100644 index 00000000..c6982d4a --- /dev/null +++ b/www/lib/localforage/src/utils/executeCallback.js @@ -0,0 +1,11 @@ +function executeCallback(promise, callback) { + if (callback) { + promise.then(function(result) { + callback(null, result); + }, function(error) { + callback(error); + }); + } +} + +export default executeCallback; diff --git a/www/lib/localforage/src/utils/executeTwoCallbacks.js b/www/lib/localforage/src/utils/executeTwoCallbacks.js new file mode 100644 index 00000000..f98c7585 --- /dev/null +++ b/www/lib/localforage/src/utils/executeTwoCallbacks.js @@ -0,0 +1,11 @@ +function executeTwoCallbacks(promise, callback, errorCallback) { + if (typeof callback === 'function') { + promise.then(callback); + } + + if (typeof errorCallback === 'function') { + promise.catch(errorCallback); + } +} + +export default executeTwoCallbacks; diff --git a/www/lib/localforage/src/utils/idb.js b/www/lib/localforage/src/utils/idb.js new file mode 100644 index 00000000..47541f6a --- /dev/null +++ b/www/lib/localforage/src/utils/idb.js @@ -0,0 +1,21 @@ +function getIDB() { + /* global indexedDB,webkitIndexedDB,mozIndexedDB,OIndexedDB,msIndexedDB */ + if (typeof indexedDB !== 'undefined') { + return indexedDB; + } + if (typeof webkitIndexedDB !== 'undefined') { + return webkitIndexedDB; + } + if (typeof mozIndexedDB !== 'undefined') { + return mozIndexedDB; + } + if (typeof OIndexedDB !== 'undefined') { + return OIndexedDB; + } + if (typeof msIndexedDB !== 'undefined') { + return msIndexedDB; + } +} + +var idb = getIDB(); +export default idb; diff --git a/www/lib/localforage/src/utils/isIndexedDBValid.js b/www/lib/localforage/src/utils/isIndexedDBValid.js new file mode 100644 index 00000000..aa14b6d8 --- /dev/null +++ b/www/lib/localforage/src/utils/isIndexedDBValid.js @@ -0,0 +1,37 @@ +import idb from './idb'; + +function isIndexedDBValid() { + try { + // Initialize IndexedDB; fall back to vendor-prefixed versions + // if needed. + if (!idb) { + return false; + } + // We mimic PouchDB here; just UA test for Safari (which, as of + // iOS 8/Yosemite, doesn't properly support IndexedDB). + // IndexedDB support is broken and different from Blink's. + // This is faster than the test case (and it's sync), so we just + // do this. *SIGH* + // http://bl.ocks.org/nolanlawson/raw/c83e9039edf2278047e9/ + // + // We test for openDatabase because IE Mobile identifies itself + // as Safari. Oh the lulz... + if (typeof openDatabase !== 'undefined' && typeof navigator !== 'undefined' && + navigator.userAgent && + /Safari/.test(navigator.userAgent) && !/Chrome/.test(navigator.userAgent)) { + return false; + } + + return idb && + typeof idb.open === 'function' && + // Some Samsung/HTC Android 4.0-4.3 devices + // have older IndexedDB specs; if this isn't available + // their IndexedDB is too old for us to use. + // (Replaces the onupgradeneeded test.) + typeof IDBKeyRange !== 'undefined'; + } catch (e) { + return false; + } +} + +export default isIndexedDBValid; diff --git a/www/lib/localforage/src/utils/isLocalStorageValid.js b/www/lib/localforage/src/utils/isLocalStorageValid.js new file mode 100644 index 00000000..0c7c1245 --- /dev/null +++ b/www/lib/localforage/src/utils/isLocalStorageValid.js @@ -0,0 +1,11 @@ +function isLocalStorageValid() { + try { + return typeof localStorage !== 'undefined' && + ('setItem' in localStorage) && + localStorage.setItem; + } catch (e) { + return false; + } +} + +export default isLocalStorageValid; diff --git a/www/lib/localforage/src/utils/isWebSQLValid.js b/www/lib/localforage/src/utils/isWebSQLValid.js new file mode 100644 index 00000000..1a4386ac --- /dev/null +++ b/www/lib/localforage/src/utils/isWebSQLValid.js @@ -0,0 +1,5 @@ +function isWebSQLValid() { + return typeof openDatabase === 'function'; +} + +export default isWebSQLValid; diff --git a/www/lib/localforage/src/utils/promise.js b/www/lib/localforage/src/utils/promise.js new file mode 100644 index 00000000..177a10d0 --- /dev/null +++ b/www/lib/localforage/src/utils/promise.js @@ -0,0 +1,6 @@ +// This is CommonJS because lie is an external dependency, so Rollup +// can just ignore it. +if (typeof Promise === 'undefined' && typeof require !== 'undefined') { + require('lie/polyfill'); +} +export default Promise; diff --git a/www/lib/localforage/src/utils/serializer.js b/www/lib/localforage/src/utils/serializer.js new file mode 100644 index 00000000..08e5fc8f --- /dev/null +++ b/www/lib/localforage/src/utils/serializer.js @@ -0,0 +1,233 @@ +import createBlob from './createBlob'; + +// Sadly, the best way to save binary data in WebSQL/localStorage is serializing +// it to Base64, so this is how we store it to prevent very strange errors with less +// verbose ways of binary <-> string data storage. +var BASE_CHARS = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'; + +var BLOB_TYPE_PREFIX = '~~local_forage_type~'; +var BLOB_TYPE_PREFIX_REGEX = /^~~local_forage_type~([^~]+)~/; + +var SERIALIZED_MARKER = '__lfsc__:'; +var SERIALIZED_MARKER_LENGTH = SERIALIZED_MARKER.length; + +// OMG the serializations! +var TYPE_ARRAYBUFFER = 'arbf'; +var TYPE_BLOB = 'blob'; +var TYPE_INT8ARRAY = 'si08'; +var TYPE_UINT8ARRAY = 'ui08'; +var TYPE_UINT8CLAMPEDARRAY = 'uic8'; +var TYPE_INT16ARRAY = 'si16'; +var TYPE_INT32ARRAY = 'si32'; +var TYPE_UINT16ARRAY = 'ur16'; +var TYPE_UINT32ARRAY = 'ui32'; +var TYPE_FLOAT32ARRAY = 'fl32'; +var TYPE_FLOAT64ARRAY = 'fl64'; +var TYPE_SERIALIZED_MARKER_LENGTH = SERIALIZED_MARKER_LENGTH + + TYPE_ARRAYBUFFER.length; + +function stringToBuffer(serializedString) { + // Fill the string into a ArrayBuffer. + var bufferLength = serializedString.length * 0.75; + var len = serializedString.length; + var i; + var p = 0; + var encoded1, encoded2, encoded3, encoded4; + + if (serializedString[serializedString.length - 1] === '=') { + bufferLength--; + if (serializedString[serializedString.length - 2] === '=') { + bufferLength--; + } + } + + var buffer = new ArrayBuffer(bufferLength); + var bytes = new Uint8Array(buffer); + + for (i = 0; i < len; i += 4) { + encoded1 = BASE_CHARS.indexOf(serializedString[i]); + encoded2 = BASE_CHARS.indexOf(serializedString[i + 1]); + encoded3 = BASE_CHARS.indexOf(serializedString[i + 2]); + encoded4 = BASE_CHARS.indexOf(serializedString[i + 3]); + + /*jslint bitwise: true */ + bytes[p++] = (encoded1 << 2) | (encoded2 >> 4); + bytes[p++] = ((encoded2 & 15) << 4) | (encoded3 >> 2); + bytes[p++] = ((encoded3 & 3) << 6) | (encoded4 & 63); + } + return buffer; +} + +// Converts a buffer to a string to store, serialized, in the backend +// storage library. +function bufferToString(buffer) { + // base64-arraybuffer + var bytes = new Uint8Array(buffer); + var base64String = ''; + var i; + + for (i = 0; i < bytes.length; i += 3) { + /*jslint bitwise: true */ + base64String += BASE_CHARS[bytes[i] >> 2]; + base64String += BASE_CHARS[((bytes[i] & 3) << 4) | (bytes[i + 1] >> 4)]; + base64String += BASE_CHARS[((bytes[i + 1] & 15) << 2) | (bytes[i + 2] >> 6)]; + base64String += BASE_CHARS[bytes[i + 2] & 63]; + } + + if ((bytes.length % 3) === 2) { + base64String = base64String.substring(0, base64String.length - 1) + '='; + } else if (bytes.length % 3 === 1) { + base64String = base64String.substring(0, base64String.length - 2) + '=='; + } + + return base64String; +} + +// Serialize a value, afterwards executing a callback (which usually +// instructs the `setItem()` callback/promise to be executed). This is how +// we store binary data with localStorage. +function serialize(value, callback) { + var valueString = ''; + if (value) { + valueString = value.toString(); + } + + // Cannot use `value instanceof ArrayBuffer` or such here, as these + // checks fail when running the tests using casper.js... + // + // TODO: See why those tests fail and use a better solution. + if (value && (value.toString() === '[object ArrayBuffer]' || + value.buffer && + value.buffer.toString() === '[object ArrayBuffer]')) { + // Convert binary arrays to a string and prefix the string with + // a special marker. + var buffer; + var marker = SERIALIZED_MARKER; + + if (value instanceof ArrayBuffer) { + buffer = value; + marker += TYPE_ARRAYBUFFER; + } else { + buffer = value.buffer; + + if (valueString === '[object Int8Array]') { + marker += TYPE_INT8ARRAY; + } else if (valueString === '[object Uint8Array]') { + marker += TYPE_UINT8ARRAY; + } else if (valueString === '[object Uint8ClampedArray]') { + marker += TYPE_UINT8CLAMPEDARRAY; + } else if (valueString === '[object Int16Array]') { + marker += TYPE_INT16ARRAY; + } else if (valueString === '[object Uint16Array]') { + marker += TYPE_UINT16ARRAY; + } else if (valueString === '[object Int32Array]') { + marker += TYPE_INT32ARRAY; + } else if (valueString === '[object Uint32Array]') { + marker += TYPE_UINT32ARRAY; + } else if (valueString === '[object Float32Array]') { + marker += TYPE_FLOAT32ARRAY; + } else if (valueString === '[object Float64Array]') { + marker += TYPE_FLOAT64ARRAY; + } else { + callback(new Error('Failed to get type for BinaryArray')); + } + } + + callback(marker + bufferToString(buffer)); + } else if (valueString === '[object Blob]') { + // Conver the blob to a binaryArray and then to a string. + var fileReader = new FileReader(); + + fileReader.onload = function() { + // Backwards-compatible prefix for the blob type. + var str = BLOB_TYPE_PREFIX + value.type + '~' + + bufferToString(this.result); + + callback(SERIALIZED_MARKER + TYPE_BLOB + str); + }; + + fileReader.readAsArrayBuffer(value); + } else { + try { + callback(JSON.stringify(value)); + } catch (e) { + console.error("Couldn't convert value into a JSON string: ", + value); + + callback(null, e); + } + } +} + +// Deserialize data we've inserted into a value column/field. We place +// special markers into our strings to mark them as encoded; this isn't +// as nice as a meta field, but it's the only sane thing we can do whilst +// keeping localStorage support intact. +// +// Oftentimes this will just deserialize JSON content, but if we have a +// special marker (SERIALIZED_MARKER, defined above), we will extract +// some kind of arraybuffer/binary data/typed array out of the string. +function deserialize(value) { + // If we haven't marked this string as being specially serialized (i.e. + // something other than serialized JSON), we can just return it and be + // done with it. + if (value.substring(0, + SERIALIZED_MARKER_LENGTH) !== SERIALIZED_MARKER) { + return JSON.parse(value); + } + + // The following code deals with deserializing some kind of Blob or + // TypedArray. First we separate out the type of data we're dealing + // with from the data itself. + var serializedString = value.substring(TYPE_SERIALIZED_MARKER_LENGTH); + var type = value.substring(SERIALIZED_MARKER_LENGTH, + TYPE_SERIALIZED_MARKER_LENGTH); + + var blobType; + // Backwards-compatible blob type serialization strategy. + // DBs created with older versions of localForage will simply not have the blob type. + if (type === TYPE_BLOB && BLOB_TYPE_PREFIX_REGEX.test(serializedString)) { + var matcher = serializedString.match(BLOB_TYPE_PREFIX_REGEX); + blobType = matcher[1]; + serializedString = serializedString.substring(matcher[0].length); + } + var buffer = stringToBuffer(serializedString); + + // Return the right type based on the code/type set during + // serialization. + switch (type) { + case TYPE_ARRAYBUFFER: + return buffer; + case TYPE_BLOB: + return createBlob([buffer], {type: blobType}); + case TYPE_INT8ARRAY: + return new Int8Array(buffer); + case TYPE_UINT8ARRAY: + return new Uint8Array(buffer); + case TYPE_UINT8CLAMPEDARRAY: + return new Uint8ClampedArray(buffer); + case TYPE_INT16ARRAY: + return new Int16Array(buffer); + case TYPE_UINT16ARRAY: + return new Uint16Array(buffer); + case TYPE_INT32ARRAY: + return new Int32Array(buffer); + case TYPE_UINT32ARRAY: + return new Uint32Array(buffer); + case TYPE_FLOAT32ARRAY: + return new Float32Array(buffer); + case TYPE_FLOAT64ARRAY: + return new Float64Array(buffer); + default: + throw new Error('Unkown type: ' + type); + } +} + +var localforageSerializer = { + serialize: serialize, + deserialize: deserialize, + stringToBuffer: stringToBuffer, + bufferToString: bufferToString +}; + +export default localforageSerializer; |
