Repositorio del curso CCOM4030 el semestre B91 del proyecto Artesanías con el Instituto de Cultura

localforage.nopromises.js 82KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465
  1. /*!
  2. localForage -- Offline Storage, Improved
  3. Version 1.9.0
  4. https://localforage.github.io/localForage
  5. (c) 2013-2017 Mozilla, Apache License 2.0
  6. */
  7. (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){
  8. 'use strict';
  9. var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; };
  10. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  11. function getIDB() {
  12. /* global indexedDB,webkitIndexedDB,mozIndexedDB,OIndexedDB,msIndexedDB */
  13. try {
  14. if (typeof indexedDB !== 'undefined') {
  15. return indexedDB;
  16. }
  17. if (typeof webkitIndexedDB !== 'undefined') {
  18. return webkitIndexedDB;
  19. }
  20. if (typeof mozIndexedDB !== 'undefined') {
  21. return mozIndexedDB;
  22. }
  23. if (typeof OIndexedDB !== 'undefined') {
  24. return OIndexedDB;
  25. }
  26. if (typeof msIndexedDB !== 'undefined') {
  27. return msIndexedDB;
  28. }
  29. } catch (e) {
  30. return;
  31. }
  32. }
  33. var idb = getIDB();
  34. function isIndexedDBValid() {
  35. try {
  36. // Initialize IndexedDB; fall back to vendor-prefixed versions
  37. // if needed.
  38. if (!idb || !idb.open) {
  39. return false;
  40. }
  41. // We mimic PouchDB here;
  42. //
  43. // We test for openDatabase because IE Mobile identifies itself
  44. // as Safari. Oh the lulz...
  45. var isSafari = typeof openDatabase !== 'undefined' && /(Safari|iPhone|iPad|iPod)/.test(navigator.userAgent) && !/Chrome/.test(navigator.userAgent) && !/BlackBerry/.test(navigator.platform);
  46. var hasFetch = typeof fetch === 'function' && fetch.toString().indexOf('[native code') !== -1;
  47. // Safari <10.1 does not meet our requirements for IDB support
  48. // (see: https://github.com/pouchdb/pouchdb/issues/5572).
  49. // Safari 10.1 shipped with fetch, we can use that to detect it.
  50. // Note: this creates issues with `window.fetch` polyfills and
  51. // overrides; see:
  52. // https://github.com/localForage/localForage/issues/856
  53. return (!isSafari || hasFetch) && typeof indexedDB !== 'undefined' &&
  54. // some outdated implementations of IDB that appear on Samsung
  55. // and HTC Android devices <4.4 are missing IDBKeyRange
  56. // See: https://github.com/mozilla/localForage/issues/128
  57. // See: https://github.com/mozilla/localForage/issues/272
  58. typeof IDBKeyRange !== 'undefined';
  59. } catch (e) {
  60. return false;
  61. }
  62. }
  63. // Abstracts constructing a Blob object, so it also works in older
  64. // browsers that don't support the native Blob constructor. (i.e.
  65. // old QtWebKit versions, at least).
  66. // Abstracts constructing a Blob object, so it also works in older
  67. // browsers that don't support the native Blob constructor. (i.e.
  68. // old QtWebKit versions, at least).
  69. function createBlob(parts, properties) {
  70. /* global BlobBuilder,MSBlobBuilder,MozBlobBuilder,WebKitBlobBuilder */
  71. parts = parts || [];
  72. properties = properties || {};
  73. try {
  74. return new Blob(parts, properties);
  75. } catch (e) {
  76. if (e.name !== 'TypeError') {
  77. throw e;
  78. }
  79. var Builder = typeof BlobBuilder !== 'undefined' ? BlobBuilder : typeof MSBlobBuilder !== 'undefined' ? MSBlobBuilder : typeof MozBlobBuilder !== 'undefined' ? MozBlobBuilder : WebKitBlobBuilder;
  80. var builder = new Builder();
  81. for (var i = 0; i < parts.length; i += 1) {
  82. builder.append(parts[i]);
  83. }
  84. return builder.getBlob(properties.type);
  85. }
  86. }
  87. // This is CommonJS because lie is an external dependency, so Rollup
  88. // can just ignore it.
  89. if (typeof Promise === 'undefined') {
  90. // In the "nopromises" build this will just throw if you don't have
  91. // a global promise object, but it would throw anyway later.
  92. _dereq_('lie/polyfill');
  93. }
  94. var Promise$1 = Promise;
  95. function executeCallback(promise, callback) {
  96. if (callback) {
  97. promise.then(function (result) {
  98. callback(null, result);
  99. }, function (error) {
  100. callback(error);
  101. });
  102. }
  103. }
  104. function executeTwoCallbacks(promise, callback, errorCallback) {
  105. if (typeof callback === 'function') {
  106. promise.then(callback);
  107. }
  108. if (typeof errorCallback === 'function') {
  109. promise["catch"](errorCallback);
  110. }
  111. }
  112. function normalizeKey(key) {
  113. // Cast the key to a string, as that's all we can set as a key.
  114. if (typeof key !== 'string') {
  115. console.warn(key + ' used as a key, but it is not a string.');
  116. key = String(key);
  117. }
  118. return key;
  119. }
  120. function getCallback() {
  121. if (arguments.length && typeof arguments[arguments.length - 1] === 'function') {
  122. return arguments[arguments.length - 1];
  123. }
  124. }
  125. // Some code originally from async_storage.js in
  126. // [Gaia](https://github.com/mozilla-b2g/gaia).
  127. var DETECT_BLOB_SUPPORT_STORE = 'local-forage-detect-blob-support';
  128. var supportsBlobs = void 0;
  129. var dbContexts = {};
  130. var toString = Object.prototype.toString;
  131. // Transaction Modes
  132. var READ_ONLY = 'readonly';
  133. var READ_WRITE = 'readwrite';
  134. // Transform a binary string to an array buffer, because otherwise
  135. // weird stuff happens when you try to work with the binary string directly.
  136. // It is known.
  137. // From http://stackoverflow.com/questions/14967647/ (continues on next line)
  138. // encode-decode-image-with-base64-breaks-image (2013-04-21)
  139. function _binStringToArrayBuffer(bin) {
  140. var length = bin.length;
  141. var buf = new ArrayBuffer(length);
  142. var arr = new Uint8Array(buf);
  143. for (var i = 0; i < length; i++) {
  144. arr[i] = bin.charCodeAt(i);
  145. }
  146. return buf;
  147. }
  148. //
  149. // Blobs are not supported in all versions of IndexedDB, notably
  150. // Chrome <37 and Android <5. In those versions, storing a blob will throw.
  151. //
  152. // Various other blob bugs exist in Chrome v37-42 (inclusive).
  153. // Detecting them is expensive and confusing to users, and Chrome 37-42
  154. // is at very low usage worldwide, so we do a hacky userAgent check instead.
  155. //
  156. // content-type bug: https://code.google.com/p/chromium/issues/detail?id=408120
  157. // 404 bug: https://code.google.com/p/chromium/issues/detail?id=447916
  158. // FileReader bug: https://code.google.com/p/chromium/issues/detail?id=447836
  159. //
  160. // Code borrowed from PouchDB. See:
  161. // https://github.com/pouchdb/pouchdb/blob/master/packages/node_modules/pouchdb-adapter-idb/src/blobSupport.js
  162. //
  163. function _checkBlobSupportWithoutCaching(idb) {
  164. return new Promise$1(function (resolve) {
  165. var txn = idb.transaction(DETECT_BLOB_SUPPORT_STORE, READ_WRITE);
  166. var blob = createBlob(['']);
  167. txn.objectStore(DETECT_BLOB_SUPPORT_STORE).put(blob, 'key');
  168. txn.onabort = function (e) {
  169. // If the transaction aborts now its due to not being able to
  170. // write to the database, likely due to the disk being full
  171. e.preventDefault();
  172. e.stopPropagation();
  173. resolve(false);
  174. };
  175. txn.oncomplete = function () {
  176. var matchedChrome = navigator.userAgent.match(/Chrome\/(\d+)/);
  177. var matchedEdge = navigator.userAgent.match(/Edge\//);
  178. // MS Edge pretends to be Chrome 42:
  179. // https://msdn.microsoft.com/en-us/library/hh869301%28v=vs.85%29.aspx
  180. resolve(matchedEdge || !matchedChrome || parseInt(matchedChrome[1], 10) >= 43);
  181. };
  182. })["catch"](function () {
  183. return false; // error, so assume unsupported
  184. });
  185. }
  186. function _checkBlobSupport(idb) {
  187. if (typeof supportsBlobs === 'boolean') {
  188. return Promise$1.resolve(supportsBlobs);
  189. }
  190. return _checkBlobSupportWithoutCaching(idb).then(function (value) {
  191. supportsBlobs = value;
  192. return supportsBlobs;
  193. });
  194. }
  195. function _deferReadiness(dbInfo) {
  196. var dbContext = dbContexts[dbInfo.name];
  197. // Create a deferred object representing the current database operation.
  198. var deferredOperation = {};
  199. deferredOperation.promise = new Promise$1(function (resolve, reject) {
  200. deferredOperation.resolve = resolve;
  201. deferredOperation.reject = reject;
  202. });
  203. // Enqueue the deferred operation.
  204. dbContext.deferredOperations.push(deferredOperation);
  205. // Chain its promise to the database readiness.
  206. if (!dbContext.dbReady) {
  207. dbContext.dbReady = deferredOperation.promise;
  208. } else {
  209. dbContext.dbReady = dbContext.dbReady.then(function () {
  210. return deferredOperation.promise;
  211. });
  212. }
  213. }
  214. function _advanceReadiness(dbInfo) {
  215. var dbContext = dbContexts[dbInfo.name];
  216. // Dequeue a deferred operation.
  217. var deferredOperation = dbContext.deferredOperations.pop();
  218. // Resolve its promise (which is part of the database readiness
  219. // chain of promises).
  220. if (deferredOperation) {
  221. deferredOperation.resolve();
  222. return deferredOperation.promise;
  223. }
  224. }
  225. function _rejectReadiness(dbInfo, err) {
  226. var dbContext = dbContexts[dbInfo.name];
  227. // Dequeue a deferred operation.
  228. var deferredOperation = dbContext.deferredOperations.pop();
  229. // Reject its promise (which is part of the database readiness
  230. // chain of promises).
  231. if (deferredOperation) {
  232. deferredOperation.reject(err);
  233. return deferredOperation.promise;
  234. }
  235. }
  236. function _getConnection(dbInfo, upgradeNeeded) {
  237. return new Promise$1(function (resolve, reject) {
  238. dbContexts[dbInfo.name] = dbContexts[dbInfo.name] || createDbContext();
  239. if (dbInfo.db) {
  240. if (upgradeNeeded) {
  241. _deferReadiness(dbInfo);
  242. dbInfo.db.close();
  243. } else {
  244. return resolve(dbInfo.db);
  245. }
  246. }
  247. var dbArgs = [dbInfo.name];
  248. if (upgradeNeeded) {
  249. dbArgs.push(dbInfo.version);
  250. }
  251. var openreq = idb.open.apply(idb, dbArgs);
  252. if (upgradeNeeded) {
  253. openreq.onupgradeneeded = function (e) {
  254. var db = openreq.result;
  255. try {
  256. db.createObjectStore(dbInfo.storeName);
  257. if (e.oldVersion <= 1) {
  258. // Added when support for blob shims was added
  259. db.createObjectStore(DETECT_BLOB_SUPPORT_STORE);
  260. }
  261. } catch (ex) {
  262. if (ex.name === 'ConstraintError') {
  263. console.warn('The database "' + dbInfo.name + '"' + ' has been upgraded from version ' + e.oldVersion + ' to version ' + e.newVersion + ', but the storage "' + dbInfo.storeName + '" already exists.');
  264. } else {
  265. throw ex;
  266. }
  267. }
  268. };
  269. }
  270. openreq.onerror = function (e) {
  271. e.preventDefault();
  272. reject(openreq.error);
  273. };
  274. openreq.onsuccess = function () {
  275. resolve(openreq.result);
  276. _advanceReadiness(dbInfo);
  277. };
  278. });
  279. }
  280. function _getOriginalConnection(dbInfo) {
  281. return _getConnection(dbInfo, false);
  282. }
  283. function _getUpgradedConnection(dbInfo) {
  284. return _getConnection(dbInfo, true);
  285. }
  286. function _isUpgradeNeeded(dbInfo, defaultVersion) {
  287. if (!dbInfo.db) {
  288. return true;
  289. }
  290. var isNewStore = !dbInfo.db.objectStoreNames.contains(dbInfo.storeName);
  291. var isDowngrade = dbInfo.version < dbInfo.db.version;
  292. var isUpgrade = dbInfo.version > dbInfo.db.version;
  293. if (isDowngrade) {
  294. // If the version is not the default one
  295. // then warn for impossible downgrade.
  296. if (dbInfo.version !== defaultVersion) {
  297. console.warn('The database "' + dbInfo.name + '"' + " can't be downgraded from version " + dbInfo.db.version + ' to version ' + dbInfo.version + '.');
  298. }
  299. // Align the versions to prevent errors.
  300. dbInfo.version = dbInfo.db.version;
  301. }
  302. if (isUpgrade || isNewStore) {
  303. // If the store is new then increment the version (if needed).
  304. // This will trigger an "upgradeneeded" event which is required
  305. // for creating a store.
  306. if (isNewStore) {
  307. var incVersion = dbInfo.db.version + 1;
  308. if (incVersion > dbInfo.version) {
  309. dbInfo.version = incVersion;
  310. }
  311. }
  312. return true;
  313. }
  314. return false;
  315. }
  316. // encode a blob for indexeddb engines that don't support blobs
  317. function _encodeBlob(blob) {
  318. return new Promise$1(function (resolve, reject) {
  319. var reader = new FileReader();
  320. reader.onerror = reject;
  321. reader.onloadend = function (e) {
  322. var base64 = btoa(e.target.result || '');
  323. resolve({
  324. __local_forage_encoded_blob: true,
  325. data: base64,
  326. type: blob.type
  327. });
  328. };
  329. reader.readAsBinaryString(blob);
  330. });
  331. }
  332. // decode an encoded blob
  333. function _decodeBlob(encodedBlob) {
  334. var arrayBuff = _binStringToArrayBuffer(atob(encodedBlob.data));
  335. return createBlob([arrayBuff], { type: encodedBlob.type });
  336. }
  337. // is this one of our fancy encoded blobs?
  338. function _isEncodedBlob(value) {
  339. return value && value.__local_forage_encoded_blob;
  340. }
  341. // Specialize the default `ready()` function by making it dependent
  342. // on the current database operations. Thus, the driver will be actually
  343. // ready when it's been initialized (default) *and* there are no pending
  344. // operations on the database (initiated by some other instances).
  345. function _fullyReady(callback) {
  346. var self = this;
  347. var promise = self._initReady().then(function () {
  348. var dbContext = dbContexts[self._dbInfo.name];
  349. if (dbContext && dbContext.dbReady) {
  350. return dbContext.dbReady;
  351. }
  352. });
  353. executeTwoCallbacks(promise, callback, callback);
  354. return promise;
  355. }
  356. // Try to establish a new db connection to replace the
  357. // current one which is broken (i.e. experiencing
  358. // InvalidStateError while creating a transaction).
  359. function _tryReconnect(dbInfo) {
  360. _deferReadiness(dbInfo);
  361. var dbContext = dbContexts[dbInfo.name];
  362. var forages = dbContext.forages;
  363. for (var i = 0; i < forages.length; i++) {
  364. var forage = forages[i];
  365. if (forage._dbInfo.db) {
  366. forage._dbInfo.db.close();
  367. forage._dbInfo.db = null;
  368. }
  369. }
  370. dbInfo.db = null;
  371. return _getOriginalConnection(dbInfo).then(function (db) {
  372. dbInfo.db = db;
  373. if (_isUpgradeNeeded(dbInfo)) {
  374. // Reopen the database for upgrading.
  375. return _getUpgradedConnection(dbInfo);
  376. }
  377. return db;
  378. }).then(function (db) {
  379. // store the latest db reference
  380. // in case the db was upgraded
  381. dbInfo.db = dbContext.db = db;
  382. for (var i = 0; i < forages.length; i++) {
  383. forages[i]._dbInfo.db = db;
  384. }
  385. })["catch"](function (err) {
  386. _rejectReadiness(dbInfo, err);
  387. throw err;
  388. });
  389. }
  390. // FF doesn't like Promises (micro-tasks) and IDDB store operations,
  391. // so we have to do it with callbacks
  392. function createTransaction(dbInfo, mode, callback, retries) {
  393. if (retries === undefined) {
  394. retries = 1;
  395. }
  396. try {
  397. var tx = dbInfo.db.transaction(dbInfo.storeName, mode);
  398. callback(null, tx);
  399. } catch (err) {
  400. if (retries > 0 && (!dbInfo.db || err.name === 'InvalidStateError' || err.name === 'NotFoundError')) {
  401. return Promise$1.resolve().then(function () {
  402. if (!dbInfo.db || err.name === 'NotFoundError' && !dbInfo.db.objectStoreNames.contains(dbInfo.storeName) && dbInfo.version <= dbInfo.db.version) {
  403. // increase the db version, to create the new ObjectStore
  404. if (dbInfo.db) {
  405. dbInfo.version = dbInfo.db.version + 1;
  406. }
  407. // Reopen the database for upgrading.
  408. return _getUpgradedConnection(dbInfo);
  409. }
  410. }).then(function () {
  411. return _tryReconnect(dbInfo).then(function () {
  412. createTransaction(dbInfo, mode, callback, retries - 1);
  413. });
  414. })["catch"](callback);
  415. }
  416. callback(err);
  417. }
  418. }
  419. function createDbContext() {
  420. return {
  421. // Running localForages sharing a database.
  422. forages: [],
  423. // Shared database.
  424. db: null,
  425. // Database readiness (promise).
  426. dbReady: null,
  427. // Deferred operations on the database.
  428. deferredOperations: []
  429. };
  430. }
  431. // Open the IndexedDB database (automatically creates one if one didn't
  432. // previously exist), using any options set in the config.
  433. function _initStorage(options) {
  434. var self = this;
  435. var dbInfo = {
  436. db: null
  437. };
  438. if (options) {
  439. for (var i in options) {
  440. dbInfo[i] = options[i];
  441. }
  442. }
  443. // Get the current context of the database;
  444. var dbContext = dbContexts[dbInfo.name];
  445. // ...or create a new context.
  446. if (!dbContext) {
  447. dbContext = createDbContext();
  448. // Register the new context in the global container.
  449. dbContexts[dbInfo.name] = dbContext;
  450. }
  451. // Register itself as a running localForage in the current context.
  452. dbContext.forages.push(self);
  453. // Replace the default `ready()` function with the specialized one.
  454. if (!self._initReady) {
  455. self._initReady = self.ready;
  456. self.ready = _fullyReady;
  457. }
  458. // Create an array of initialization states of the related localForages.
  459. var initPromises = [];
  460. function ignoreErrors() {
  461. // Don't handle errors here,
  462. // just makes sure related localForages aren't pending.
  463. return Promise$1.resolve();
  464. }
  465. for (var j = 0; j < dbContext.forages.length; j++) {
  466. var forage = dbContext.forages[j];
  467. if (forage !== self) {
  468. // Don't wait for itself...
  469. initPromises.push(forage._initReady()["catch"](ignoreErrors));
  470. }
  471. }
  472. // Take a snapshot of the related localForages.
  473. var forages = dbContext.forages.slice(0);
  474. // Initialize the connection process only when
  475. // all the related localForages aren't pending.
  476. return Promise$1.all(initPromises).then(function () {
  477. dbInfo.db = dbContext.db;
  478. // Get the connection or open a new one without upgrade.
  479. return _getOriginalConnection(dbInfo);
  480. }).then(function (db) {
  481. dbInfo.db = db;
  482. if (_isUpgradeNeeded(dbInfo, self._defaultConfig.version)) {
  483. // Reopen the database for upgrading.
  484. return _getUpgradedConnection(dbInfo);
  485. }
  486. return db;
  487. }).then(function (db) {
  488. dbInfo.db = dbContext.db = db;
  489. self._dbInfo = dbInfo;
  490. // Share the final connection amongst related localForages.
  491. for (var k = 0; k < forages.length; k++) {
  492. var forage = forages[k];
  493. if (forage !== self) {
  494. // Self is already up-to-date.
  495. forage._dbInfo.db = dbInfo.db;
  496. forage._dbInfo.version = dbInfo.version;
  497. }
  498. }
  499. });
  500. }
  501. function getItem(key, callback) {
  502. var self = this;
  503. key = normalizeKey(key);
  504. var promise = new Promise$1(function (resolve, reject) {
  505. self.ready().then(function () {
  506. createTransaction(self._dbInfo, READ_ONLY, function (err, transaction) {
  507. if (err) {
  508. return reject(err);
  509. }
  510. try {
  511. var store = transaction.objectStore(self._dbInfo.storeName);
  512. var req = store.get(key);
  513. req.onsuccess = function () {
  514. var value = req.result;
  515. if (value === undefined) {
  516. value = null;
  517. }
  518. if (_isEncodedBlob(value)) {
  519. value = _decodeBlob(value);
  520. }
  521. resolve(value);
  522. };
  523. req.onerror = function () {
  524. reject(req.error);
  525. };
  526. } catch (e) {
  527. reject(e);
  528. }
  529. });
  530. })["catch"](reject);
  531. });
  532. executeCallback(promise, callback);
  533. return promise;
  534. }
  535. // Iterate over all items stored in database.
  536. function iterate(iterator, callback) {
  537. var self = this;
  538. var promise = new Promise$1(function (resolve, reject) {
  539. self.ready().then(function () {
  540. createTransaction(self._dbInfo, READ_ONLY, function (err, transaction) {
  541. if (err) {
  542. return reject(err);
  543. }
  544. try {
  545. var store = transaction.objectStore(self._dbInfo.storeName);
  546. var req = store.openCursor();
  547. var iterationNumber = 1;
  548. req.onsuccess = function () {
  549. var cursor = req.result;
  550. if (cursor) {
  551. var value = cursor.value;
  552. if (_isEncodedBlob(value)) {
  553. value = _decodeBlob(value);
  554. }
  555. var result = iterator(value, cursor.key, iterationNumber++);
  556. // when the iterator callback returns any
  557. // (non-`undefined`) value, then we stop
  558. // the iteration immediately
  559. if (result !== void 0) {
  560. resolve(result);
  561. } else {
  562. cursor["continue"]();
  563. }
  564. } else {
  565. resolve();
  566. }
  567. };
  568. req.onerror = function () {
  569. reject(req.error);
  570. };
  571. } catch (e) {
  572. reject(e);
  573. }
  574. });
  575. })["catch"](reject);
  576. });
  577. executeCallback(promise, callback);
  578. return promise;
  579. }
  580. function setItem(key, value, callback) {
  581. var self = this;
  582. key = normalizeKey(key);
  583. var promise = new Promise$1(function (resolve, reject) {
  584. var dbInfo;
  585. self.ready().then(function () {
  586. dbInfo = self._dbInfo;
  587. if (toString.call(value) === '[object Blob]') {
  588. return _checkBlobSupport(dbInfo.db).then(function (blobSupport) {
  589. if (blobSupport) {
  590. return value;
  591. }
  592. return _encodeBlob(value);
  593. });
  594. }
  595. return value;
  596. }).then(function (value) {
  597. createTransaction(self._dbInfo, READ_WRITE, function (err, transaction) {
  598. if (err) {
  599. return reject(err);
  600. }
  601. try {
  602. var store = transaction.objectStore(self._dbInfo.storeName);
  603. // The reason we don't _save_ null is because IE 10 does
  604. // not support saving the `null` type in IndexedDB. How
  605. // ironic, given the bug below!
  606. // See: https://github.com/mozilla/localForage/issues/161
  607. if (value === null) {
  608. value = undefined;
  609. }
  610. var req = store.put(value, key);
  611. transaction.oncomplete = function () {
  612. // Cast to undefined so the value passed to
  613. // callback/promise is the same as what one would get out
  614. // of `getItem()` later. This leads to some weirdness
  615. // (setItem('foo', undefined) will return `null`), but
  616. // it's not my fault localStorage is our baseline and that
  617. // it's weird.
  618. if (value === undefined) {
  619. value = null;
  620. }
  621. resolve(value);
  622. };
  623. transaction.onabort = transaction.onerror = function () {
  624. var err = req.error ? req.error : req.transaction.error;
  625. reject(err);
  626. };
  627. } catch (e) {
  628. reject(e);
  629. }
  630. });
  631. })["catch"](reject);
  632. });
  633. executeCallback(promise, callback);
  634. return promise;
  635. }
  636. function removeItem(key, callback) {
  637. var self = this;
  638. key = normalizeKey(key);
  639. var promise = new Promise$1(function (resolve, reject) {
  640. self.ready().then(function () {
  641. createTransaction(self._dbInfo, READ_WRITE, function (err, transaction) {
  642. if (err) {
  643. return reject(err);
  644. }
  645. try {
  646. var store = transaction.objectStore(self._dbInfo.storeName);
  647. // We use a Grunt task to make this safe for IE and some
  648. // versions of Android (including those used by Cordova).
  649. // Normally IE won't like `.delete()` and will insist on
  650. // using `['delete']()`, but we have a build step that
  651. // fixes this for us now.
  652. var req = store["delete"](key);
  653. transaction.oncomplete = function () {
  654. resolve();
  655. };
  656. transaction.onerror = function () {
  657. reject(req.error);
  658. };
  659. // The request will be also be aborted if we've exceeded our storage
  660. // space.
  661. transaction.onabort = function () {
  662. var err = req.error ? req.error : req.transaction.error;
  663. reject(err);
  664. };
  665. } catch (e) {
  666. reject(e);
  667. }
  668. });
  669. })["catch"](reject);
  670. });
  671. executeCallback(promise, callback);
  672. return promise;
  673. }
  674. function clear(callback) {
  675. var self = this;
  676. var promise = new Promise$1(function (resolve, reject) {
  677. self.ready().then(function () {
  678. createTransaction(self._dbInfo, READ_WRITE, function (err, transaction) {
  679. if (err) {
  680. return reject(err);
  681. }
  682. try {
  683. var store = transaction.objectStore(self._dbInfo.storeName);
  684. var req = store.clear();
  685. transaction.oncomplete = function () {
  686. resolve();
  687. };
  688. transaction.onabort = transaction.onerror = function () {
  689. var err = req.error ? req.error : req.transaction.error;
  690. reject(err);
  691. };
  692. } catch (e) {
  693. reject(e);
  694. }
  695. });
  696. })["catch"](reject);
  697. });
  698. executeCallback(promise, callback);
  699. return promise;
  700. }
  701. function length(callback) {
  702. var self = this;
  703. var promise = new Promise$1(function (resolve, reject) {
  704. self.ready().then(function () {
  705. createTransaction(self._dbInfo, READ_ONLY, function (err, transaction) {
  706. if (err) {
  707. return reject(err);
  708. }
  709. try {
  710. var store = transaction.objectStore(self._dbInfo.storeName);
  711. var req = store.count();
  712. req.onsuccess = function () {
  713. resolve(req.result);
  714. };
  715. req.onerror = function () {
  716. reject(req.error);
  717. };
  718. } catch (e) {
  719. reject(e);
  720. }
  721. });
  722. })["catch"](reject);
  723. });
  724. executeCallback(promise, callback);
  725. return promise;
  726. }
  727. function key(n, callback) {
  728. var self = this;
  729. var promise = new Promise$1(function (resolve, reject) {
  730. if (n < 0) {
  731. resolve(null);
  732. return;
  733. }
  734. self.ready().then(function () {
  735. createTransaction(self._dbInfo, READ_ONLY, function (err, transaction) {
  736. if (err) {
  737. return reject(err);
  738. }
  739. try {
  740. var store = transaction.objectStore(self._dbInfo.storeName);
  741. var advanced = false;
  742. var req = store.openKeyCursor();
  743. req.onsuccess = function () {
  744. var cursor = req.result;
  745. if (!cursor) {
  746. // this means there weren't enough keys
  747. resolve(null);
  748. return;
  749. }
  750. if (n === 0) {
  751. // We have the first key, return it if that's what they
  752. // wanted.
  753. resolve(cursor.key);
  754. } else {
  755. if (!advanced) {
  756. // Otherwise, ask the cursor to skip ahead n
  757. // records.
  758. advanced = true;
  759. cursor.advance(n);
  760. } else {
  761. // When we get here, we've got the nth key.
  762. resolve(cursor.key);
  763. }
  764. }
  765. };
  766. req.onerror = function () {
  767. reject(req.error);
  768. };
  769. } catch (e) {
  770. reject(e);
  771. }
  772. });
  773. })["catch"](reject);
  774. });
  775. executeCallback(promise, callback);
  776. return promise;
  777. }
  778. function keys(callback) {
  779. var self = this;
  780. var promise = new Promise$1(function (resolve, reject) {
  781. self.ready().then(function () {
  782. createTransaction(self._dbInfo, READ_ONLY, function (err, transaction) {
  783. if (err) {
  784. return reject(err);
  785. }
  786. try {
  787. var store = transaction.objectStore(self._dbInfo.storeName);
  788. var req = store.openKeyCursor();
  789. var keys = [];
  790. req.onsuccess = function () {
  791. var cursor = req.result;
  792. if (!cursor) {
  793. resolve(keys);
  794. return;
  795. }
  796. keys.push(cursor.key);
  797. cursor["continue"]();
  798. };
  799. req.onerror = function () {
  800. reject(req.error);
  801. };
  802. } catch (e) {
  803. reject(e);
  804. }
  805. });
  806. })["catch"](reject);
  807. });
  808. executeCallback(promise, callback);
  809. return promise;
  810. }
  811. function dropInstance(options, callback) {
  812. callback = getCallback.apply(this, arguments);
  813. var currentConfig = this.config();
  814. options = typeof options !== 'function' && options || {};
  815. if (!options.name) {
  816. options.name = options.name || currentConfig.name;
  817. options.storeName = options.storeName || currentConfig.storeName;
  818. }
  819. var self = this;
  820. var promise;
  821. if (!options.name) {
  822. promise = Promise$1.reject('Invalid arguments');
  823. } else {
  824. var isCurrentDb = options.name === currentConfig.name && self._dbInfo.db;
  825. var dbPromise = isCurrentDb ? Promise$1.resolve(self._dbInfo.db) : _getOriginalConnection(options).then(function (db) {
  826. var dbContext = dbContexts[options.name];
  827. var forages = dbContext.forages;
  828. dbContext.db = db;
  829. for (var i = 0; i < forages.length; i++) {
  830. forages[i]._dbInfo.db = db;
  831. }
  832. return db;
  833. });
  834. if (!options.storeName) {
  835. promise = dbPromise.then(function (db) {
  836. _deferReadiness(options);
  837. var dbContext = dbContexts[options.name];
  838. var forages = dbContext.forages;
  839. db.close();
  840. for (var i = 0; i < forages.length; i++) {
  841. var forage = forages[i];
  842. forage._dbInfo.db = null;
  843. }
  844. var dropDBPromise = new Promise$1(function (resolve, reject) {
  845. var req = idb.deleteDatabase(options.name);
  846. req.onerror = req.onblocked = function (err) {
  847. var db = req.result;
  848. if (db) {
  849. db.close();
  850. }
  851. reject(err);
  852. };
  853. req.onsuccess = function () {
  854. var db = req.result;
  855. if (db) {
  856. db.close();
  857. }
  858. resolve(db);
  859. };
  860. });
  861. return dropDBPromise.then(function (db) {
  862. dbContext.db = db;
  863. for (var i = 0; i < forages.length; i++) {
  864. var _forage = forages[i];
  865. _advanceReadiness(_forage._dbInfo);
  866. }
  867. })["catch"](function (err) {
  868. (_rejectReadiness(options, err) || Promise$1.resolve())["catch"](function () {});
  869. throw err;
  870. });
  871. });
  872. } else {
  873. promise = dbPromise.then(function (db) {
  874. if (!db.objectStoreNames.contains(options.storeName)) {
  875. return;
  876. }
  877. var newVersion = db.version + 1;
  878. _deferReadiness(options);
  879. var dbContext = dbContexts[options.name];
  880. var forages = dbContext.forages;
  881. db.close();
  882. for (var i = 0; i < forages.length; i++) {
  883. var forage = forages[i];
  884. forage._dbInfo.db = null;
  885. forage._dbInfo.version = newVersion;
  886. }
  887. var dropObjectPromise = new Promise$1(function (resolve, reject) {
  888. var req = idb.open(options.name, newVersion);
  889. req.onerror = function (err) {
  890. var db = req.result;
  891. db.close();
  892. reject(err);
  893. };
  894. req.onupgradeneeded = function () {
  895. var db = req.result;
  896. db.deleteObjectStore(options.storeName);
  897. };
  898. req.onsuccess = function () {
  899. var db = req.result;
  900. db.close();
  901. resolve(db);
  902. };
  903. });
  904. return dropObjectPromise.then(function (db) {
  905. dbContext.db = db;
  906. for (var j = 0; j < forages.length; j++) {
  907. var _forage2 = forages[j];
  908. _forage2._dbInfo.db = db;
  909. _advanceReadiness(_forage2._dbInfo);
  910. }
  911. })["catch"](function (err) {
  912. (_rejectReadiness(options, err) || Promise$1.resolve())["catch"](function () {});
  913. throw err;
  914. });
  915. });
  916. }
  917. }
  918. executeCallback(promise, callback);
  919. return promise;
  920. }
  921. var asyncStorage = {
  922. _driver: 'asyncStorage',
  923. _initStorage: _initStorage,
  924. _support: isIndexedDBValid(),
  925. iterate: iterate,
  926. getItem: getItem,
  927. setItem: setItem,
  928. removeItem: removeItem,
  929. clear: clear,
  930. length: length,
  931. key: key,
  932. keys: keys,
  933. dropInstance: dropInstance
  934. };
  935. function isWebSQLValid() {
  936. return typeof openDatabase === 'function';
  937. }
  938. // Sadly, the best way to save binary data in WebSQL/localStorage is serializing
  939. // it to Base64, so this is how we store it to prevent very strange errors with less
  940. // verbose ways of binary <-> string data storage.
  941. var BASE_CHARS = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';
  942. var BLOB_TYPE_PREFIX = '~~local_forage_type~';
  943. var BLOB_TYPE_PREFIX_REGEX = /^~~local_forage_type~([^~]+)~/;
  944. var SERIALIZED_MARKER = '__lfsc__:';
  945. var SERIALIZED_MARKER_LENGTH = SERIALIZED_MARKER.length;
  946. // OMG the serializations!
  947. var TYPE_ARRAYBUFFER = 'arbf';
  948. var TYPE_BLOB = 'blob';
  949. var TYPE_INT8ARRAY = 'si08';
  950. var TYPE_UINT8ARRAY = 'ui08';
  951. var TYPE_UINT8CLAMPEDARRAY = 'uic8';
  952. var TYPE_INT16ARRAY = 'si16';
  953. var TYPE_INT32ARRAY = 'si32';
  954. var TYPE_UINT16ARRAY = 'ur16';
  955. var TYPE_UINT32ARRAY = 'ui32';
  956. var TYPE_FLOAT32ARRAY = 'fl32';
  957. var TYPE_FLOAT64ARRAY = 'fl64';
  958. var TYPE_SERIALIZED_MARKER_LENGTH = SERIALIZED_MARKER_LENGTH + TYPE_ARRAYBUFFER.length;
  959. var toString$1 = Object.prototype.toString;
  960. function stringToBuffer(serializedString) {
  961. // Fill the string into a ArrayBuffer.
  962. var bufferLength = serializedString.length * 0.75;
  963. var len = serializedString.length;
  964. var i;
  965. var p = 0;
  966. var encoded1, encoded2, encoded3, encoded4;
  967. if (serializedString[serializedString.length - 1] === '=') {
  968. bufferLength--;
  969. if (serializedString[serializedString.length - 2] === '=') {
  970. bufferLength--;
  971. }
  972. }
  973. var buffer = new ArrayBuffer(bufferLength);
  974. var bytes = new Uint8Array(buffer);
  975. for (i = 0; i < len; i += 4) {
  976. encoded1 = BASE_CHARS.indexOf(serializedString[i]);
  977. encoded2 = BASE_CHARS.indexOf(serializedString[i + 1]);
  978. encoded3 = BASE_CHARS.indexOf(serializedString[i + 2]);
  979. encoded4 = BASE_CHARS.indexOf(serializedString[i + 3]);
  980. /*jslint bitwise: true */
  981. bytes[p++] = encoded1 << 2 | encoded2 >> 4;
  982. bytes[p++] = (encoded2 & 15) << 4 | encoded3 >> 2;
  983. bytes[p++] = (encoded3 & 3) << 6 | encoded4 & 63;
  984. }
  985. return buffer;
  986. }
  987. // Converts a buffer to a string to store, serialized, in the backend
  988. // storage library.
  989. function bufferToString(buffer) {
  990. // base64-arraybuffer
  991. var bytes = new Uint8Array(buffer);
  992. var base64String = '';
  993. var i;
  994. for (i = 0; i < bytes.length; i += 3) {
  995. /*jslint bitwise: true */
  996. base64String += BASE_CHARS[bytes[i] >> 2];
  997. base64String += BASE_CHARS[(bytes[i] & 3) << 4 | bytes[i + 1] >> 4];
  998. base64String += BASE_CHARS[(bytes[i + 1] & 15) << 2 | bytes[i + 2] >> 6];
  999. base64String += BASE_CHARS[bytes[i + 2] & 63];
  1000. }
  1001. if (bytes.length % 3 === 2) {
  1002. base64String = base64String.substring(0, base64String.length - 1) + '=';
  1003. } else if (bytes.length % 3 === 1) {
  1004. base64String = base64String.substring(0, base64String.length - 2) + '==';
  1005. }
  1006. return base64String;
  1007. }
  1008. // Serialize a value, afterwards executing a callback (which usually
  1009. // instructs the `setItem()` callback/promise to be executed). This is how
  1010. // we store binary data with localStorage.
  1011. function serialize(value, callback) {
  1012. var valueType = '';
  1013. if (value) {
  1014. valueType = toString$1.call(value);
  1015. }
  1016. // Cannot use `value instanceof ArrayBuffer` or such here, as these
  1017. // checks fail when running the tests using casper.js...
  1018. //
  1019. // TODO: See why those tests fail and use a better solution.
  1020. if (value && (valueType === '[object ArrayBuffer]' || value.buffer && toString$1.call(value.buffer) === '[object ArrayBuffer]')) {
  1021. // Convert binary arrays to a string and prefix the string with
  1022. // a special marker.
  1023. var buffer;
  1024. var marker = SERIALIZED_MARKER;
  1025. if (value instanceof ArrayBuffer) {
  1026. buffer = value;
  1027. marker += TYPE_ARRAYBUFFER;
  1028. } else {
  1029. buffer = value.buffer;
  1030. if (valueType === '[object Int8Array]') {
  1031. marker += TYPE_INT8ARRAY;
  1032. } else if (valueType === '[object Uint8Array]') {
  1033. marker += TYPE_UINT8ARRAY;
  1034. } else if (valueType === '[object Uint8ClampedArray]') {
  1035. marker += TYPE_UINT8CLAMPEDARRAY;
  1036. } else if (valueType === '[object Int16Array]') {
  1037. marker += TYPE_INT16ARRAY;
  1038. } else if (valueType === '[object Uint16Array]') {
  1039. marker += TYPE_UINT16ARRAY;
  1040. } else if (valueType === '[object Int32Array]') {
  1041. marker += TYPE_INT32ARRAY;
  1042. } else if (valueType === '[object Uint32Array]') {
  1043. marker += TYPE_UINT32ARRAY;
  1044. } else if (valueType === '[object Float32Array]') {
  1045. marker += TYPE_FLOAT32ARRAY;
  1046. } else if (valueType === '[object Float64Array]') {
  1047. marker += TYPE_FLOAT64ARRAY;
  1048. } else {
  1049. callback(new Error('Failed to get type for BinaryArray'));
  1050. }
  1051. }
  1052. callback(marker + bufferToString(buffer));
  1053. } else if (valueType === '[object Blob]') {
  1054. // Conver the blob to a binaryArray and then to a string.
  1055. var fileReader = new FileReader();
  1056. fileReader.onload = function () {
  1057. // Backwards-compatible prefix for the blob type.
  1058. var str = BLOB_TYPE_PREFIX + value.type + '~' + bufferToString(this.result);
  1059. callback(SERIALIZED_MARKER + TYPE_BLOB + str);
  1060. };
  1061. fileReader.readAsArrayBuffer(value);
  1062. } else {
  1063. try {
  1064. callback(JSON.stringify(value));
  1065. } catch (e) {
  1066. console.error("Couldn't convert value into a JSON string: ", value);
  1067. callback(null, e);
  1068. }
  1069. }
  1070. }
  1071. // Deserialize data we've inserted into a value column/field. We place
  1072. // special markers into our strings to mark them as encoded; this isn't
  1073. // as nice as a meta field, but it's the only sane thing we can do whilst
  1074. // keeping localStorage support intact.
  1075. //
  1076. // Oftentimes this will just deserialize JSON content, but if we have a
  1077. // special marker (SERIALIZED_MARKER, defined above), we will extract
  1078. // some kind of arraybuffer/binary data/typed array out of the string.
  1079. function deserialize(value) {
  1080. // If we haven't marked this string as being specially serialized (i.e.
  1081. // something other than serialized JSON), we can just return it and be
  1082. // done with it.
  1083. if (value.substring(0, SERIALIZED_MARKER_LENGTH) !== SERIALIZED_MARKER) {
  1084. return JSON.parse(value);
  1085. }
  1086. // The following code deals with deserializing some kind of Blob or
  1087. // TypedArray. First we separate out the type of data we're dealing
  1088. // with from the data itself.
  1089. var serializedString = value.substring(TYPE_SERIALIZED_MARKER_LENGTH);
  1090. var type = value.substring(SERIALIZED_MARKER_LENGTH, TYPE_SERIALIZED_MARKER_LENGTH);
  1091. var blobType;
  1092. // Backwards-compatible blob type serialization strategy.
  1093. // DBs created with older versions of localForage will simply not have the blob type.
  1094. if (type === TYPE_BLOB && BLOB_TYPE_PREFIX_REGEX.test(serializedString)) {
  1095. var matcher = serializedString.match(BLOB_TYPE_PREFIX_REGEX);
  1096. blobType = matcher[1];
  1097. serializedString = serializedString.substring(matcher[0].length);
  1098. }
  1099. var buffer = stringToBuffer(serializedString);
  1100. // Return the right type based on the code/type set during
  1101. // serialization.
  1102. switch (type) {
  1103. case TYPE_ARRAYBUFFER:
  1104. return buffer;
  1105. case TYPE_BLOB:
  1106. return createBlob([buffer], { type: blobType });
  1107. case TYPE_INT8ARRAY:
  1108. return new Int8Array(buffer);
  1109. case TYPE_UINT8ARRAY:
  1110. return new Uint8Array(buffer);
  1111. case TYPE_UINT8CLAMPEDARRAY:
  1112. return new Uint8ClampedArray(buffer);
  1113. case TYPE_INT16ARRAY:
  1114. return new Int16Array(buffer);
  1115. case TYPE_UINT16ARRAY:
  1116. return new Uint16Array(buffer);
  1117. case TYPE_INT32ARRAY:
  1118. return new Int32Array(buffer);
  1119. case TYPE_UINT32ARRAY:
  1120. return new Uint32Array(buffer);
  1121. case TYPE_FLOAT32ARRAY:
  1122. return new Float32Array(buffer);
  1123. case TYPE_FLOAT64ARRAY:
  1124. return new Float64Array(buffer);
  1125. default:
  1126. throw new Error('Unkown type: ' + type);
  1127. }
  1128. }
  1129. var localforageSerializer = {
  1130. serialize: serialize,
  1131. deserialize: deserialize,
  1132. stringToBuffer: stringToBuffer,
  1133. bufferToString: bufferToString
  1134. };
  1135. /*
  1136. * Includes code from:
  1137. *
  1138. * base64-arraybuffer
  1139. * https://github.com/niklasvh/base64-arraybuffer
  1140. *
  1141. * Copyright (c) 2012 Niklas von Hertzen
  1142. * Licensed under the MIT license.
  1143. */
  1144. function createDbTable(t, dbInfo, callback, errorCallback) {
  1145. t.executeSql('CREATE TABLE IF NOT EXISTS ' + dbInfo.storeName + ' ' + '(id INTEGER PRIMARY KEY, key unique, value)', [], callback, errorCallback);
  1146. }
  1147. // Open the WebSQL database (automatically creates one if one didn't
  1148. // previously exist), using any options set in the config.
  1149. function _initStorage$1(options) {
  1150. var self = this;
  1151. var dbInfo = {
  1152. db: null
  1153. };
  1154. if (options) {
  1155. for (var i in options) {
  1156. dbInfo[i] = typeof options[i] !== 'string' ? options[i].toString() : options[i];
  1157. }
  1158. }
  1159. var dbInfoPromise = new Promise$1(function (resolve, reject) {
  1160. // Open the database; the openDatabase API will automatically
  1161. // create it for us if it doesn't exist.
  1162. try {
  1163. dbInfo.db = openDatabase(dbInfo.name, String(dbInfo.version), dbInfo.description, dbInfo.size);
  1164. } catch (e) {
  1165. return reject(e);
  1166. }
  1167. // Create our key/value table if it doesn't exist.
  1168. dbInfo.db.transaction(function (t) {
  1169. createDbTable(t, dbInfo, function () {
  1170. self._dbInfo = dbInfo;
  1171. resolve();
  1172. }, function (t, error) {
  1173. reject(error);
  1174. });
  1175. }, reject);
  1176. });
  1177. dbInfo.serializer = localforageSerializer;
  1178. return dbInfoPromise;
  1179. }
  1180. function tryExecuteSql(t, dbInfo, sqlStatement, args, callback, errorCallback) {
  1181. t.executeSql(sqlStatement, args, callback, function (t, error) {
  1182. if (error.code === error.SYNTAX_ERR) {
  1183. t.executeSql('SELECT name FROM sqlite_master ' + "WHERE type='table' AND name = ?", [dbInfo.storeName], function (t, results) {
  1184. if (!results.rows.length) {
  1185. // if the table is missing (was deleted)
  1186. // re-create it table and retry
  1187. createDbTable(t, dbInfo, function () {
  1188. t.executeSql(sqlStatement, args, callback, errorCallback);
  1189. }, errorCallback);
  1190. } else {
  1191. errorCallback(t, error);
  1192. }
  1193. }, errorCallback);
  1194. } else {
  1195. errorCallback(t, error);
  1196. }
  1197. }, errorCallback);
  1198. }
  1199. function getItem$1(key, callback) {
  1200. var self = this;
  1201. key = normalizeKey(key);
  1202. var promise = new Promise$1(function (resolve, reject) {
  1203. self.ready().then(function () {
  1204. var dbInfo = self._dbInfo;
  1205. dbInfo.db.transaction(function (t) {
  1206. tryExecuteSql(t, dbInfo, 'SELECT * FROM ' + dbInfo.storeName + ' WHERE key = ? LIMIT 1', [key], function (t, results) {
  1207. var result = results.rows.length ? results.rows.item(0).value : null;
  1208. // Check to see if this is serialized content we need to
  1209. // unpack.
  1210. if (result) {
  1211. result = dbInfo.serializer.deserialize(result);
  1212. }
  1213. resolve(result);
  1214. }, function (t, error) {
  1215. reject(error);
  1216. });
  1217. });
  1218. })["catch"](reject);
  1219. });
  1220. executeCallback(promise, callback);
  1221. return promise;
  1222. }
  1223. function iterate$1(iterator, callback) {
  1224. var self = this;
  1225. var promise = new Promise$1(function (resolve, reject) {
  1226. self.ready().then(function () {
  1227. var dbInfo = self._dbInfo;
  1228. dbInfo.db.transaction(function (t) {
  1229. tryExecuteSql(t, dbInfo, 'SELECT * FROM ' + dbInfo.storeName, [], function (t, results) {
  1230. var rows = results.rows;
  1231. var length = rows.length;
  1232. for (var i = 0; i < length; i++) {
  1233. var item = rows.item(i);
  1234. var result = item.value;
  1235. // Check to see if this is serialized content
  1236. // we need to unpack.
  1237. if (result) {
  1238. result = dbInfo.serializer.deserialize(result);
  1239. }
  1240. result = iterator(result, item.key, i + 1);
  1241. // void(0) prevents problems with redefinition
  1242. // of `undefined`.
  1243. if (result !== void 0) {
  1244. resolve(result);
  1245. return;
  1246. }
  1247. }
  1248. resolve();
  1249. }, function (t, error) {
  1250. reject(error);
  1251. });
  1252. });
  1253. })["catch"](reject);
  1254. });
  1255. executeCallback(promise, callback);
  1256. return promise;
  1257. }
  1258. function _setItem(key, value, callback, retriesLeft) {
  1259. var self = this;
  1260. key = normalizeKey(key);
  1261. var promise = new Promise$1(function (resolve, reject) {
  1262. self.ready().then(function () {
  1263. // The localStorage API doesn't return undefined values in an
  1264. // "expected" way, so undefined is always cast to null in all
  1265. // drivers. See: https://github.com/mozilla/localForage/pull/42
  1266. if (value === undefined) {
  1267. value = null;
  1268. }
  1269. // Save the original value to pass to the callback.
  1270. var originalValue = value;
  1271. var dbInfo = self._dbInfo;
  1272. dbInfo.serializer.serialize(value, function (value, error) {
  1273. if (error) {
  1274. reject(error);
  1275. } else {
  1276. dbInfo.db.transaction(function (t) {
  1277. tryExecuteSql(t, dbInfo, 'INSERT OR REPLACE INTO ' + dbInfo.storeName + ' ' + '(key, value) VALUES (?, ?)', [key, value], function () {
  1278. resolve(originalValue);
  1279. }, function (t, error) {
  1280. reject(error);
  1281. });
  1282. }, function (sqlError) {
  1283. // The transaction failed; check
  1284. // to see if it's a quota error.
  1285. if (sqlError.code === sqlError.QUOTA_ERR) {
  1286. // We reject the callback outright for now, but
  1287. // it's worth trying to re-run the transaction.
  1288. // Even if the user accepts the prompt to use
  1289. // more storage on Safari, this error will
  1290. // be called.
  1291. //
  1292. // Try to re-run the transaction.
  1293. if (retriesLeft > 0) {
  1294. resolve(_setItem.apply(self, [key, originalValue, callback, retriesLeft - 1]));
  1295. return;
  1296. }
  1297. reject(sqlError);
  1298. }
  1299. });
  1300. }
  1301. });
  1302. })["catch"](reject);
  1303. });
  1304. executeCallback(promise, callback);
  1305. return promise;
  1306. }
  1307. function setItem$1(key, value, callback) {
  1308. return _setItem.apply(this, [key, value, callback, 1]);
  1309. }
  1310. function removeItem$1(key, callback) {
  1311. var self = this;
  1312. key = normalizeKey(key);
  1313. var promise = new Promise$1(function (resolve, reject) {
  1314. self.ready().then(function () {
  1315. var dbInfo = self._dbInfo;
  1316. dbInfo.db.transaction(function (t) {
  1317. tryExecuteSql(t, dbInfo, 'DELETE FROM ' + dbInfo.storeName + ' WHERE key = ?', [key], function () {
  1318. resolve();
  1319. }, function (t, error) {
  1320. reject(error);
  1321. });
  1322. });
  1323. })["catch"](reject);
  1324. });
  1325. executeCallback(promise, callback);
  1326. return promise;
  1327. }
  1328. // Deletes every item in the table.
  1329. // TODO: Find out if this resets the AUTO_INCREMENT number.
  1330. function clear$1(callback) {
  1331. var self = this;
  1332. var promise = new Promise$1(function (resolve, reject) {
  1333. self.ready().then(function () {
  1334. var dbInfo = self._dbInfo;
  1335. dbInfo.db.transaction(function (t) {
  1336. tryExecuteSql(t, dbInfo, 'DELETE FROM ' + dbInfo.storeName, [], function () {
  1337. resolve();
  1338. }, function (t, error) {
  1339. reject(error);
  1340. });
  1341. });
  1342. })["catch"](reject);
  1343. });
  1344. executeCallback(promise, callback);
  1345. return promise;
  1346. }
  1347. // Does a simple `COUNT(key)` to get the number of items stored in
  1348. // localForage.
  1349. function length$1(callback) {
  1350. var self = this;
  1351. var promise = new Promise$1(function (resolve, reject) {
  1352. self.ready().then(function () {
  1353. var dbInfo = self._dbInfo;
  1354. dbInfo.db.transaction(function (t) {
  1355. // Ahhh, SQL makes this one soooooo easy.
  1356. tryExecuteSql(t, dbInfo, 'SELECT COUNT(key) as c FROM ' + dbInfo.storeName, [], function (t, results) {
  1357. var result = results.rows.item(0).c;
  1358. resolve(result);
  1359. }, function (t, error) {
  1360. reject(error);
  1361. });
  1362. });
  1363. })["catch"](reject);
  1364. });
  1365. executeCallback(promise, callback);
  1366. return promise;
  1367. }
  1368. // Return the key located at key index X; essentially gets the key from a
  1369. // `WHERE id = ?`. This is the most efficient way I can think to implement
  1370. // this rarely-used (in my experience) part of the API, but it can seem
  1371. // inconsistent, because we do `INSERT OR REPLACE INTO` on `setItem()`, so
  1372. // the ID of each key will change every time it's updated. Perhaps a stored
  1373. // procedure for the `setItem()` SQL would solve this problem?
  1374. // TODO: Don't change ID on `setItem()`.
  1375. function key$1(n, callback) {
  1376. var self = this;
  1377. var promise = new Promise$1(function (resolve, reject) {
  1378. self.ready().then(function () {
  1379. var dbInfo = self._dbInfo;
  1380. dbInfo.db.transaction(function (t) {
  1381. tryExecuteSql(t, dbInfo, 'SELECT key FROM ' + dbInfo.storeName + ' WHERE id = ? LIMIT 1', [n + 1], function (t, results) {
  1382. var result = results.rows.length ? results.rows.item(0).key : null;
  1383. resolve(result);
  1384. }, function (t, error) {
  1385. reject(error);
  1386. });
  1387. });
  1388. })["catch"](reject);
  1389. });
  1390. executeCallback(promise, callback);
  1391. return promise;
  1392. }
  1393. function keys$1(callback) {
  1394. var self = this;
  1395. var promise = new Promise$1(function (resolve, reject) {
  1396. self.ready().then(function () {
  1397. var dbInfo = self._dbInfo;
  1398. dbInfo.db.transaction(function (t) {
  1399. tryExecuteSql(t, dbInfo, 'SELECT key FROM ' + dbInfo.storeName, [], function (t, results) {
  1400. var keys = [];
  1401. for (var i = 0; i < results.rows.length; i++) {
  1402. keys.push(results.rows.item(i).key);
  1403. }
  1404. resolve(keys);
  1405. }, function (t, error) {
  1406. reject(error);
  1407. });
  1408. });
  1409. })["catch"](reject);
  1410. });
  1411. executeCallback(promise, callback);
  1412. return promise;
  1413. }
  1414. // https://www.w3.org/TR/webdatabase/#databases
  1415. // > There is no way to enumerate or delete the databases available for an origin from this API.
  1416. function getAllStoreNames(db) {
  1417. return new Promise$1(function (resolve, reject) {
  1418. db.transaction(function (t) {
  1419. t.executeSql('SELECT name FROM sqlite_master ' + "WHERE type='table' AND name <> '__WebKitDatabaseInfoTable__'", [], function (t, results) {
  1420. var storeNames = [];
  1421. for (var i = 0; i < results.rows.length; i++) {
  1422. storeNames.push(results.rows.item(i).name);
  1423. }
  1424. resolve({
  1425. db: db,
  1426. storeNames: storeNames
  1427. });
  1428. }, function (t, error) {
  1429. reject(error);
  1430. });
  1431. }, function (sqlError) {
  1432. reject(sqlError);
  1433. });
  1434. });
  1435. }
  1436. function dropInstance$1(options, callback) {
  1437. callback = getCallback.apply(this, arguments);
  1438. var currentConfig = this.config();
  1439. options = typeof options !== 'function' && options || {};
  1440. if (!options.name) {
  1441. options.name = options.name || currentConfig.name;
  1442. options.storeName = options.storeName || currentConfig.storeName;
  1443. }
  1444. var self = this;
  1445. var promise;
  1446. if (!options.name) {
  1447. promise = Promise$1.reject('Invalid arguments');
  1448. } else {
  1449. promise = new Promise$1(function (resolve) {
  1450. var db;
  1451. if (options.name === currentConfig.name) {
  1452. // use the db reference of the current instance
  1453. db = self._dbInfo.db;
  1454. } else {
  1455. db = openDatabase(options.name, '', '', 0);
  1456. }
  1457. if (!options.storeName) {
  1458. // drop all database tables
  1459. resolve(getAllStoreNames(db));
  1460. } else {
  1461. resolve({
  1462. db: db,
  1463. storeNames: [options.storeName]
  1464. });
  1465. }
  1466. }).then(function (operationInfo) {
  1467. return new Promise$1(function (resolve, reject) {
  1468. operationInfo.db.transaction(function (t) {
  1469. function dropTable(storeName) {
  1470. return new Promise$1(function (resolve, reject) {
  1471. t.executeSql('DROP TABLE IF EXISTS ' + storeName, [], function () {
  1472. resolve();
  1473. }, function (t, error) {
  1474. reject(error);
  1475. });
  1476. });
  1477. }
  1478. var operations = [];
  1479. for (var i = 0, len = operationInfo.storeNames.length; i < len; i++) {
  1480. operations.push(dropTable(operationInfo.storeNames[i]));
  1481. }
  1482. Promise$1.all(operations).then(function () {
  1483. resolve();
  1484. })["catch"](function (e) {
  1485. reject(e);
  1486. });
  1487. }, function (sqlError) {
  1488. reject(sqlError);
  1489. });
  1490. });
  1491. });
  1492. }
  1493. executeCallback(promise, callback);
  1494. return promise;
  1495. }
  1496. var webSQLStorage = {
  1497. _driver: 'webSQLStorage',
  1498. _initStorage: _initStorage$1,
  1499. _support: isWebSQLValid(),
  1500. iterate: iterate$1,
  1501. getItem: getItem$1,
  1502. setItem: setItem$1,
  1503. removeItem: removeItem$1,
  1504. clear: clear$1,
  1505. length: length$1,
  1506. key: key$1,
  1507. keys: keys$1,
  1508. dropInstance: dropInstance$1
  1509. };
  1510. function isLocalStorageValid() {
  1511. try {
  1512. return typeof localStorage !== 'undefined' && 'setItem' in localStorage &&
  1513. // in IE8 typeof localStorage.setItem === 'object'
  1514. !!localStorage.setItem;
  1515. } catch (e) {
  1516. return false;
  1517. }
  1518. }
  1519. function _getKeyPrefix(options, defaultConfig) {
  1520. var keyPrefix = options.name + '/';
  1521. if (options.storeName !== defaultConfig.storeName) {
  1522. keyPrefix += options.storeName + '/';
  1523. }
  1524. return keyPrefix;
  1525. }
  1526. // Check if localStorage throws when saving an item
  1527. function checkIfLocalStorageThrows() {
  1528. var localStorageTestKey = '_localforage_support_test';
  1529. try {
  1530. localStorage.setItem(localStorageTestKey, true);
  1531. localStorage.removeItem(localStorageTestKey);
  1532. return false;
  1533. } catch (e) {
  1534. return true;
  1535. }
  1536. }
  1537. // Check if localStorage is usable and allows to save an item
  1538. // This method checks if localStorage is usable in Safari Private Browsing
  1539. // mode, or in any other case where the available quota for localStorage
  1540. // is 0 and there wasn't any saved items yet.
  1541. function _isLocalStorageUsable() {
  1542. return !checkIfLocalStorageThrows() || localStorage.length > 0;
  1543. }
  1544. // Config the localStorage backend, using options set in the config.
  1545. function _initStorage$2(options) {
  1546. var self = this;
  1547. var dbInfo = {};
  1548. if (options) {
  1549. for (var i in options) {
  1550. dbInfo[i] = options[i];
  1551. }
  1552. }
  1553. dbInfo.keyPrefix = _getKeyPrefix(options, self._defaultConfig);
  1554. if (!_isLocalStorageUsable()) {
  1555. return Promise$1.reject();
  1556. }
  1557. self._dbInfo = dbInfo;
  1558. dbInfo.serializer = localforageSerializer;
  1559. return Promise$1.resolve();
  1560. }
  1561. // Remove all keys from the datastore, effectively destroying all data in
  1562. // the app's key/value store!
  1563. function clear$2(callback) {
  1564. var self = this;
  1565. var promise = self.ready().then(function () {
  1566. var keyPrefix = self._dbInfo.keyPrefix;
  1567. for (var i = localStorage.length - 1; i >= 0; i--) {
  1568. var key = localStorage.key(i);
  1569. if (key.indexOf(keyPrefix) === 0) {
  1570. localStorage.removeItem(key);
  1571. }
  1572. }
  1573. });
  1574. executeCallback(promise, callback);
  1575. return promise;
  1576. }
  1577. // Retrieve an item from the store. Unlike the original async_storage
  1578. // library in Gaia, we don't modify return values at all. If a key's value
  1579. // is `undefined`, we pass that value to the callback function.
  1580. function getItem$2(key, callback) {
  1581. var self = this;
  1582. key = normalizeKey(key);
  1583. var promise = self.ready().then(function () {
  1584. var dbInfo = self._dbInfo;
  1585. var result = localStorage.getItem(dbInfo.keyPrefix + key);
  1586. // If a result was found, parse it from the serialized
  1587. // string into a JS object. If result isn't truthy, the key
  1588. // is likely undefined and we'll pass it straight to the
  1589. // callback.
  1590. if (result) {
  1591. result = dbInfo.serializer.deserialize(result);
  1592. }
  1593. return result;
  1594. });
  1595. executeCallback(promise, callback);
  1596. return promise;
  1597. }
  1598. // Iterate over all items in the store.
  1599. function iterate$2(iterator, callback) {
  1600. var self = this;
  1601. var promise = self.ready().then(function () {
  1602. var dbInfo = self._dbInfo;
  1603. var keyPrefix = dbInfo.keyPrefix;
  1604. var keyPrefixLength = keyPrefix.length;
  1605. var length = localStorage.length;
  1606. // We use a dedicated iterator instead of the `i` variable below
  1607. // so other keys we fetch in localStorage aren't counted in
  1608. // the `iterationNumber` argument passed to the `iterate()`
  1609. // callback.
  1610. //
  1611. // See: github.com/mozilla/localForage/pull/435#discussion_r38061530
  1612. var iterationNumber = 1;
  1613. for (var i = 0; i < length; i++) {
  1614. var key = localStorage.key(i);
  1615. if (key.indexOf(keyPrefix) !== 0) {
  1616. continue;
  1617. }
  1618. var value = localStorage.getItem(key);
  1619. // If a result was found, parse it from the serialized
  1620. // string into a JS object. If result isn't truthy, the
  1621. // key is likely undefined and we'll pass it straight
  1622. // to the iterator.
  1623. if (value) {
  1624. value = dbInfo.serializer.deserialize(value);
  1625. }
  1626. value = iterator(value, key.substring(keyPrefixLength), iterationNumber++);
  1627. if (value !== void 0) {
  1628. return value;
  1629. }
  1630. }
  1631. });
  1632. executeCallback(promise, callback);
  1633. return promise;
  1634. }
  1635. // Same as localStorage's key() method, except takes a callback.
  1636. function key$2(n, callback) {
  1637. var self = this;
  1638. var promise = self.ready().then(function () {
  1639. var dbInfo = self._dbInfo;
  1640. var result;
  1641. try {
  1642. result = localStorage.key(n);
  1643. } catch (error) {
  1644. result = null;
  1645. }
  1646. // Remove the prefix from the key, if a key is found.
  1647. if (result) {
  1648. result = result.substring(dbInfo.keyPrefix.length);
  1649. }
  1650. return result;
  1651. });
  1652. executeCallback(promise, callback);
  1653. return promise;
  1654. }
  1655. function keys$2(callback) {
  1656. var self = this;
  1657. var promise = self.ready().then(function () {
  1658. var dbInfo = self._dbInfo;
  1659. var length = localStorage.length;
  1660. var keys = [];
  1661. for (var i = 0; i < length; i++) {
  1662. var itemKey = localStorage.key(i);
  1663. if (itemKey.indexOf(dbInfo.keyPrefix) === 0) {
  1664. keys.push(itemKey.substring(dbInfo.keyPrefix.length));
  1665. }
  1666. }
  1667. return keys;
  1668. });
  1669. executeCallback(promise, callback);
  1670. return promise;
  1671. }
  1672. // Supply the number of keys in the datastore to the callback function.
  1673. function length$2(callback) {
  1674. var self = this;
  1675. var promise = self.keys().then(function (keys) {
  1676. return keys.length;
  1677. });
  1678. executeCallback(promise, callback);
  1679. return promise;
  1680. }
  1681. // Remove an item from the store, nice and simple.
  1682. function removeItem$2(key, callback) {
  1683. var self = this;
  1684. key = normalizeKey(key);
  1685. var promise = self.ready().then(function () {
  1686. var dbInfo = self._dbInfo;
  1687. localStorage.removeItem(dbInfo.keyPrefix + key);
  1688. });
  1689. executeCallback(promise, callback);
  1690. return promise;
  1691. }
  1692. // Set a key's value and run an optional callback once the value is set.
  1693. // Unlike Gaia's implementation, the callback function is passed the value,
  1694. // in case you want to operate on that value only after you're sure it
  1695. // saved, or something like that.
  1696. function setItem$2(key, value, callback) {
  1697. var self = this;
  1698. key = normalizeKey(key);
  1699. var promise = self.ready().then(function () {
  1700. // Convert undefined values to null.
  1701. // https://github.com/mozilla/localForage/pull/42
  1702. if (value === undefined) {
  1703. value = null;
  1704. }
  1705. // Save the original value to pass to the callback.
  1706. var originalValue = value;
  1707. return new Promise$1(function (resolve, reject) {
  1708. var dbInfo = self._dbInfo;
  1709. dbInfo.serializer.serialize(value, function (value, error) {
  1710. if (error) {
  1711. reject(error);
  1712. } else {
  1713. try {
  1714. localStorage.setItem(dbInfo.keyPrefix + key, value);
  1715. resolve(originalValue);
  1716. } catch (e) {
  1717. // localStorage capacity exceeded.
  1718. // TODO: Make this a specific error/event.
  1719. if (e.name === 'QuotaExceededError' || e.name === 'NS_ERROR_DOM_QUOTA_REACHED') {
  1720. reject(e);
  1721. }
  1722. reject(e);
  1723. }
  1724. }
  1725. });
  1726. });
  1727. });
  1728. executeCallback(promise, callback);
  1729. return promise;
  1730. }
  1731. function dropInstance$2(options, callback) {
  1732. callback = getCallback.apply(this, arguments);
  1733. options = typeof options !== 'function' && options || {};
  1734. if (!options.name) {
  1735. var currentConfig = this.config();
  1736. options.name = options.name || currentConfig.name;
  1737. options.storeName = options.storeName || currentConfig.storeName;
  1738. }
  1739. var self = this;
  1740. var promise;
  1741. if (!options.name) {
  1742. promise = Promise$1.reject('Invalid arguments');
  1743. } else {
  1744. promise = new Promise$1(function (resolve) {
  1745. if (!options.storeName) {
  1746. resolve(options.name + '/');
  1747. } else {
  1748. resolve(_getKeyPrefix(options, self._defaultConfig));
  1749. }
  1750. }).then(function (keyPrefix) {
  1751. for (var i = localStorage.length - 1; i >= 0; i--) {
  1752. var key = localStorage.key(i);
  1753. if (key.indexOf(keyPrefix) === 0) {
  1754. localStorage.removeItem(key);
  1755. }
  1756. }
  1757. });
  1758. }
  1759. executeCallback(promise, callback);
  1760. return promise;
  1761. }
  1762. var localStorageWrapper = {
  1763. _driver: 'localStorageWrapper',
  1764. _initStorage: _initStorage$2,
  1765. _support: isLocalStorageValid(),
  1766. iterate: iterate$2,
  1767. getItem: getItem$2,
  1768. setItem: setItem$2,
  1769. removeItem: removeItem$2,
  1770. clear: clear$2,
  1771. length: length$2,
  1772. key: key$2,
  1773. keys: keys$2,
  1774. dropInstance: dropInstance$2
  1775. };
  1776. var sameValue = function sameValue(x, y) {
  1777. return x === y || typeof x === 'number' && typeof y === 'number' && isNaN(x) && isNaN(y);
  1778. };
  1779. var includes = function includes(array, searchElement) {
  1780. var len = array.length;
  1781. var i = 0;
  1782. while (i < len) {
  1783. if (sameValue(array[i], searchElement)) {
  1784. return true;
  1785. }
  1786. i++;
  1787. }
  1788. return false;
  1789. };
  1790. var isArray = Array.isArray || function (arg) {
  1791. return Object.prototype.toString.call(arg) === '[object Array]';
  1792. };
  1793. // Drivers are stored here when `defineDriver()` is called.
  1794. // They are shared across all instances of localForage.
  1795. var DefinedDrivers = {};
  1796. var DriverSupport = {};
  1797. var DefaultDrivers = {
  1798. INDEXEDDB: asyncStorage,
  1799. WEBSQL: webSQLStorage,
  1800. LOCALSTORAGE: localStorageWrapper
  1801. };
  1802. var DefaultDriverOrder = [DefaultDrivers.INDEXEDDB._driver, DefaultDrivers.WEBSQL._driver, DefaultDrivers.LOCALSTORAGE._driver];
  1803. var OptionalDriverMethods = ['dropInstance'];
  1804. var LibraryMethods = ['clear', 'getItem', 'iterate', 'key', 'keys', 'length', 'removeItem', 'setItem'].concat(OptionalDriverMethods);
  1805. var DefaultConfig = {
  1806. description: '',
  1807. driver: DefaultDriverOrder.slice(),
  1808. name: 'localforage',
  1809. // Default DB size is _JUST UNDER_ 5MB, as it's the highest size
  1810. // we can use without a prompt.
  1811. size: 4980736,
  1812. storeName: 'keyvaluepairs',
  1813. version: 1.0
  1814. };
  1815. function callWhenReady(localForageInstance, libraryMethod) {
  1816. localForageInstance[libraryMethod] = function () {
  1817. var _args = arguments;
  1818. return localForageInstance.ready().then(function () {
  1819. return localForageInstance[libraryMethod].apply(localForageInstance, _args);
  1820. });
  1821. };
  1822. }
  1823. function extend() {
  1824. for (var i = 1; i < arguments.length; i++) {
  1825. var arg = arguments[i];
  1826. if (arg) {
  1827. for (var _key in arg) {
  1828. if (arg.hasOwnProperty(_key)) {
  1829. if (isArray(arg[_key])) {
  1830. arguments[0][_key] = arg[_key].slice();
  1831. } else {
  1832. arguments[0][_key] = arg[_key];
  1833. }
  1834. }
  1835. }
  1836. }
  1837. }
  1838. return arguments[0];
  1839. }
  1840. var LocalForage = function () {
  1841. function LocalForage(options) {
  1842. _classCallCheck(this, LocalForage);
  1843. for (var driverTypeKey in DefaultDrivers) {
  1844. if (DefaultDrivers.hasOwnProperty(driverTypeKey)) {
  1845. var driver = DefaultDrivers[driverTypeKey];
  1846. var driverName = driver._driver;
  1847. this[driverTypeKey] = driverName;
  1848. if (!DefinedDrivers[driverName]) {
  1849. // we don't need to wait for the promise,
  1850. // since the default drivers can be defined
  1851. // in a blocking manner
  1852. this.defineDriver(driver);
  1853. }
  1854. }
  1855. }
  1856. this._defaultConfig = extend({}, DefaultConfig);
  1857. this._config = extend({}, this._defaultConfig, options);
  1858. this._driverSet = null;
  1859. this._initDriver = null;
  1860. this._ready = false;
  1861. this._dbInfo = null;
  1862. this._wrapLibraryMethodsWithReady();
  1863. this.setDriver(this._config.driver)["catch"](function () {});
  1864. }
  1865. // Set any config values for localForage; can be called anytime before
  1866. // the first API call (e.g. `getItem`, `setItem`).
  1867. // We loop through options so we don't overwrite existing config
  1868. // values.
  1869. LocalForage.prototype.config = function config(options) {
  1870. // If the options argument is an object, we use it to set values.
  1871. // Otherwise, we return either a specified config value or all
  1872. // config values.
  1873. if ((typeof options === 'undefined' ? 'undefined' : _typeof(options)) === 'object') {
  1874. // If localforage is ready and fully initialized, we can't set
  1875. // any new configuration values. Instead, we return an error.
  1876. if (this._ready) {
  1877. return new Error("Can't call config() after localforage " + 'has been used.');
  1878. }
  1879. for (var i in options) {
  1880. if (i === 'storeName') {
  1881. options[i] = options[i].replace(/\W/g, '_');
  1882. }
  1883. if (i === 'version' && typeof options[i] !== 'number') {
  1884. return new Error('Database version must be a number.');
  1885. }
  1886. this._config[i] = options[i];
  1887. }
  1888. // after all config options are set and
  1889. // the driver option is used, try setting it
  1890. if ('driver' in options && options.driver) {
  1891. return this.setDriver(this._config.driver);
  1892. }
  1893. return true;
  1894. } else if (typeof options === 'string') {
  1895. return this._config[options];
  1896. } else {
  1897. return this._config;
  1898. }
  1899. };
  1900. // Used to define a custom driver, shared across all instances of
  1901. // localForage.
  1902. LocalForage.prototype.defineDriver = function defineDriver(driverObject, callback, errorCallback) {
  1903. var promise = new Promise$1(function (resolve, reject) {
  1904. try {
  1905. var driverName = driverObject._driver;
  1906. var complianceError = new Error('Custom driver not compliant; see ' + 'https://mozilla.github.io/localForage/#definedriver');
  1907. // A driver name should be defined and not overlap with the
  1908. // library-defined, default drivers.
  1909. if (!driverObject._driver) {
  1910. reject(complianceError);
  1911. return;
  1912. }
  1913. var driverMethods = LibraryMethods.concat('_initStorage');
  1914. for (var i = 0, len = driverMethods.length; i < len; i++) {
  1915. var driverMethodName = driverMethods[i];
  1916. // when the property is there,
  1917. // it should be a method even when optional
  1918. var isRequired = !includes(OptionalDriverMethods, driverMethodName);
  1919. if ((isRequired || driverObject[driverMethodName]) && typeof driverObject[driverMethodName] !== 'function') {
  1920. reject(complianceError);
  1921. return;
  1922. }
  1923. }
  1924. var configureMissingMethods = function configureMissingMethods() {
  1925. var methodNotImplementedFactory = function methodNotImplementedFactory(methodName) {
  1926. return function () {
  1927. var error = new Error('Method ' + methodName + ' is not implemented by the current driver');
  1928. var promise = Promise$1.reject(error);
  1929. executeCallback(promise, arguments[arguments.length - 1]);
  1930. return promise;
  1931. };
  1932. };
  1933. for (var _i = 0, _len = OptionalDriverMethods.length; _i < _len; _i++) {
  1934. var optionalDriverMethod = OptionalDriverMethods[_i];
  1935. if (!driverObject[optionalDriverMethod]) {
  1936. driverObject[optionalDriverMethod] = methodNotImplementedFactory(optionalDriverMethod);
  1937. }
  1938. }
  1939. };
  1940. configureMissingMethods();
  1941. var setDriverSupport = function setDriverSupport(support) {
  1942. if (DefinedDrivers[driverName]) {
  1943. console.info('Redefining LocalForage driver: ' + driverName);
  1944. }
  1945. DefinedDrivers[driverName] = driverObject;
  1946. DriverSupport[driverName] = support;
  1947. // don't use a then, so that we can define
  1948. // drivers that have simple _support methods
  1949. // in a blocking manner
  1950. resolve();
  1951. };
  1952. if ('_support' in driverObject) {
  1953. if (driverObject._support && typeof driverObject._support === 'function') {
  1954. driverObject._support().then(setDriverSupport, reject);
  1955. } else {
  1956. setDriverSupport(!!driverObject._support);
  1957. }
  1958. } else {
  1959. setDriverSupport(true);
  1960. }
  1961. } catch (e) {
  1962. reject(e);
  1963. }
  1964. });
  1965. executeTwoCallbacks(promise, callback, errorCallback);
  1966. return promise;
  1967. };
  1968. LocalForage.prototype.driver = function driver() {
  1969. return this._driver || null;
  1970. };
  1971. LocalForage.prototype.getDriver = function getDriver(driverName, callback, errorCallback) {
  1972. var getDriverPromise = DefinedDrivers[driverName] ? Promise$1.resolve(DefinedDrivers[driverName]) : Promise$1.reject(new Error('Driver not found.'));
  1973. executeTwoCallbacks(getDriverPromise, callback, errorCallback);
  1974. return getDriverPromise;
  1975. };
  1976. LocalForage.prototype.getSerializer = function getSerializer(callback) {
  1977. var serializerPromise = Promise$1.resolve(localforageSerializer);
  1978. executeTwoCallbacks(serializerPromise, callback);
  1979. return serializerPromise;
  1980. };
  1981. LocalForage.prototype.ready = function ready(callback) {
  1982. var self = this;
  1983. var promise = self._driverSet.then(function () {
  1984. if (self._ready === null) {
  1985. self._ready = self._initDriver();
  1986. }
  1987. return self._ready;
  1988. });
  1989. executeTwoCallbacks(promise, callback, callback);
  1990. return promise;
  1991. };
  1992. LocalForage.prototype.setDriver = function setDriver(drivers, callback, errorCallback) {
  1993. var self = this;
  1994. if (!isArray(drivers)) {
  1995. drivers = [drivers];
  1996. }
  1997. var supportedDrivers = this._getSupportedDrivers(drivers);
  1998. function setDriverToConfig() {
  1999. self._config.driver = self.driver();
  2000. }
  2001. function extendSelfWithDriver(driver) {
  2002. self._extend(driver);
  2003. setDriverToConfig();
  2004. self._ready = self._initStorage(self._config);
  2005. return self._ready;
  2006. }
  2007. function initDriver(supportedDrivers) {
  2008. return function () {
  2009. var currentDriverIndex = 0;
  2010. function driverPromiseLoop() {
  2011. while (currentDriverIndex < supportedDrivers.length) {
  2012. var driverName = supportedDrivers[currentDriverIndex];
  2013. currentDriverIndex++;
  2014. self._dbInfo = null;
  2015. self._ready = null;
  2016. return self.getDriver(driverName).then(extendSelfWithDriver)["catch"](driverPromiseLoop);
  2017. }
  2018. setDriverToConfig();
  2019. var error = new Error('No available storage method found.');
  2020. self._driverSet = Promise$1.reject(error);
  2021. return self._driverSet;
  2022. }
  2023. return driverPromiseLoop();
  2024. };
  2025. }
  2026. // There might be a driver initialization in progress
  2027. // so wait for it to finish in order to avoid a possible
  2028. // race condition to set _dbInfo
  2029. var oldDriverSetDone = this._driverSet !== null ? this._driverSet["catch"](function () {
  2030. return Promise$1.resolve();
  2031. }) : Promise$1.resolve();
  2032. this._driverSet = oldDriverSetDone.then(function () {
  2033. var driverName = supportedDrivers[0];
  2034. self._dbInfo = null;
  2035. self._ready = null;
  2036. return self.getDriver(driverName).then(function (driver) {
  2037. self._driver = driver._driver;
  2038. setDriverToConfig();
  2039. self._wrapLibraryMethodsWithReady();
  2040. self._initDriver = initDriver(supportedDrivers);
  2041. });
  2042. })["catch"](function () {
  2043. setDriverToConfig();
  2044. var error = new Error('No available storage method found.');
  2045. self._driverSet = Promise$1.reject(error);
  2046. return self._driverSet;
  2047. });
  2048. executeTwoCallbacks(this._driverSet, callback, errorCallback);
  2049. return this._driverSet;
  2050. };
  2051. LocalForage.prototype.supports = function supports(driverName) {
  2052. return !!DriverSupport[driverName];
  2053. };
  2054. LocalForage.prototype._extend = function _extend(libraryMethodsAndProperties) {
  2055. extend(this, libraryMethodsAndProperties);
  2056. };
  2057. LocalForage.prototype._getSupportedDrivers = function _getSupportedDrivers(drivers) {
  2058. var supportedDrivers = [];
  2059. for (var i = 0, len = drivers.length; i < len; i++) {
  2060. var driverName = drivers[i];
  2061. if (this.supports(driverName)) {
  2062. supportedDrivers.push(driverName);
  2063. }
  2064. }
  2065. return supportedDrivers;
  2066. };
  2067. LocalForage.prototype._wrapLibraryMethodsWithReady = function _wrapLibraryMethodsWithReady() {
  2068. // Add a stub for each driver API method that delays the call to the
  2069. // corresponding driver method until localForage is ready. These stubs
  2070. // will be replaced by the driver methods as soon as the driver is
  2071. // loaded, so there is no performance impact.
  2072. for (var i = 0, len = LibraryMethods.length; i < len; i++) {
  2073. callWhenReady(this, LibraryMethods[i]);
  2074. }
  2075. };
  2076. LocalForage.prototype.createInstance = function createInstance(options) {
  2077. return new LocalForage(options);
  2078. };
  2079. return LocalForage;
  2080. }();
  2081. // The actual localForage object that we expose as a module or via a
  2082. // global. It's extended by pulling in one of our other libraries.
  2083. var localforage_js = new LocalForage();
  2084. module.exports = localforage_js;
  2085. },{"undefined":undefined}]},{},[1])(1)
  2086. });