You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

2497 lines
81 KiB

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