koaSession中间件的store规范格式化处理函数
@param   {Object}      options         [session配置]
@return  {Object}      koaSession中间件的store规范格式化对象
432852
function (options) {
    // 获取sessionstore处理类，根据type区分
    const SessionStore = require('./session.' + options.type);
    // 定义实例化对象
    const _sessionStore = new SessionStore(options);

    // 定时清理过期会话
    store.setCleanup(_sessionStore);

    // 比如符合{get, set, destory}
    return {
        get: async function (sid) {
            return _sessionStore.get(sid);
        },
        set: async function (sid, session, ttl) {
            // session.sid为当没有cookie的时候自动生成的，当自动生成时以自动生成的为准
            if (session.sid && session.sid !== sid) sid = session.sid;
            _sessionStore.set(sid, session, ttl);
        },
        destroy: function (sid) {
            // 当有会话销毁的时候通知回调
            handlerCallback([sid]);
            _sessionStore.destroy(sid);
        }
    };
}
1354891
function (options) {
  if (!(this instanceof Store)) {
    return new Store(options)
  }

  this._opts = options || {}
  this.db = new Datastore({ filename: this._opts.filename, autoload: true })
}
792397
function Renderer(options) {
  if (!(this instanceof Renderer)) {
    return new Renderer(options);
  }

  // create complete options object (using defaults)
  if (options) {
    debug("creating koa-handlebars instance with options", options);
  } else {
    debug("creating koa-handlebars instance");
  }

  var o = this.options = extend({}, Renderer.defaults, options);
  debug("using %s as the root", chalk.grey(o.root));

  // custom handlebars instance
  if (o.handlebars) {
    debug("using a custom handlebars instance");
    this.handlebars = o.handlebars;
  } else {
    this.handlebars = handlebars.create();
  }

  // register global helpers/partials
  if (o.helpers) this.helper(o.helpers);
  if (o.partials) this.partial(o.partials);

  // enabling caching (via lru-cache)
  if (o.cache) {
    debug("caching enabled");
    this.cache = new Cache({ max: 100 });
  }
}
1221598
function MemcacheStore (options) {
  options = options || {};
  this._host = options.host || '127.0.0.1';
  this._port = options.port || 11211;
  this._prefix = options.prefix || '';
  this._user = options.user || '';
  this._password = options.password || '';
  this._pool = options.pool = (options.pool > 1 ? options.pool : 1);
  this._connectionString = this._user + ':' + this._password + '@' + this._host + ':' + this._port;

  debug('create: host=%s, port=%s, prefix=%s, user=%s, password=%s', this._host, this._port, this._prefix, this._user, this._password);

  this._clients = [];
  this._clientIndex = -1;
  for (var i = 0; i < options.pool; i++) {
    this._clients.push(memjs.Client.create(this._connectionString));
  }

  return this;
}
1360509
function(options) {
      options = opts(this, options);
      options.applevel = true;

      var token = this.options.session_token;
      this.options.email = null;
      this.options.username = null;
      this.options.session_token = null;

      if (options.savelogin) {
        store('email', null, this.options.appid);
        store('username', null, this.options.appid);
        store('session_token', this.options.appid);
      }

      return new APICall({
        action: 'account/logout',
        type: 'POST',
        processResponse: APICall.basicResponse,
        headers: {
          'X-CloudMine-SessionToken': token
        },
        options: options
      });
    }
374225
function JugglingStore(schema, options) {
		options = options || {};
		Store.call(this, options);
		this.maxAge = options.maxAge || defaults.maxAge;
		var coll = this.collection = schema.define('Session', {
			sid: {
				type: String,
				index: true
			},
			expires: {
				type: Date,
				index: true
			},
			session: schema.constructor.JSON
		}, {
			table: options.table || defaults.table
		});

		coll.validatesUniquenessOf('sid');

		// destroy all expired sessions after each create/update
		coll.afterSave = function(next) {
			coll.iterate({where: {
				expires: {lte: new Date()}
			}}, function(obj, nexti, i) {
				obj.destroy(nexti);
			}, next);
		};
	}
648735
function create(options) {
  return knex(extend({
    client: "pg",
    debug: debug(),
    connection: connection(),
    pool: pool()
  }, options));
}
753511
function CacheManager (options) {
  options = options || {};

  options.ttl = Number(options.ttl);
  if (isNaN(options.ttl)) options.ttl = DEFAULT_TTL;

  if (!options.store) {
    options.store = new MemoryStore();
  }
  if (typeof options.store === 'string') {
    options.store = getDefaultStore(options.store, options.storeConfig);
  }
  if (typeof options.store.get !== 'function') {
    throw new Error('store engine must implement `get` method');
  }
  if (typeof options.store.set !== 'function') {
    throw new Error('store engine must implement `set` method');
  }
  if (typeof options.store.delete !== 'function') {
    throw new Error('store engine must implement `delete` method');
  }

  debug('create: ttl=%s', options.ttl);
  this._ttl = options.ttl;
  this._store = options.store;

  this._keys = {};
  this._fuzzyKeys = [];

  this._getMethodQueue = new CallQueue();
}
76922
function isomorphic(options = {}) {
    if (!(typeof options === 'object' && options.template))
        return isomorphic({
            routes: arguments[0],
            configStore: arguments[1],
            template: arguments[2],
            distPathName: arguments[3],
            injection: {
                js: arguments[4]
            }
        })

    // TODO: 尝试解决闭包内存泄漏
    let { routes, configStore } = options

    return async (ctx, next) => {

        try {
            const memoryHistory = createMemoryHistory(ctx.url)
            const store = configStore(/*memoryHistory*/) // fix redux warring
            const history = syncHistoryWithStore(memoryHistory, store)
            const { redirectLocation, renderProps } = await asyncMatch({ history, routes, location: ctx.url })

            if (redirectLocation) {
                ctx.redirect(redirectLocation.pathname + redirectLocation.search)
            } else if (renderProps) {
                const cookies = cookie.parse(ctx.request.header.cookie || '')

                // 准备语言到store中

                // 先查看URL参数是否有语音设置
                // hl 这个参数名是参考了Instargram
                let lang = ctx.query.hl

                // 如果没有，检查cookie
                if (!lang && cookies.spLocaleId)
                    lang = cookies.spLocaleId
                // 如果没有，再看header里是否有语言设置
                if (!lang)
                    lang = ctx.header['accept-language']
                // 如没有，再用默认
                if (!lang)
                    lang = 'en'

                // TODO: 修改成统一派发 CHANGE_SERVER_DATA
                store.dispatch({ type: CHANGE_LANGUAGE, data: lang })
                store.dispatch({ type: TELL_ME_URL, data: ctx.origin })
                store.dispatch(i18nActionInit(store.getState()))
                store.dispatch(i18nActionLocales())

                // 告诉浏览器用的lang
                // ctx.set('Content-Language', lang)
                // ctx.set('Vary', 'Accept-Language, Accept-Encoding')

                // 准备预处理数据到store中
                await asyncStore(store, renderProps)

                // 从react里处理并扩展到html
                extendHtml(store, renderProps)

                ctx.body = renderHtml(
                    renderToString(
                        <Provider store={store}>
                            <RouterContext {...renderProps } />
                        </Provider>
                    ),
                    store.getState(),
                    options
                )
            } else {
                await next()
            }

        } catch (e) {
            console.error('Server-Render Error Occures: %s', e.stack)
            ctx.status = 500
            ctx.body = e.message
        }
    }
}
1031060
function storeOptions() {
    var showTomster = this.checked;

    chrome.storage.sync.set({
      options: { showTomster: showTomster }
    }, function optionsSaved() {
      console.log("saved!");
    });
  }
801003
function RedisStore (options) {
  options = options || {};
  this._host = options.host || '127.0.0.1';
  this._port = options.port || 6379;
  this._db = options.db || 0;
  this._prefix = options.prefix || '';
  this._pool = options.pool = (options.pool > 1 ? options.pool : 1);

  debug('create: host=%s, port=%s, db=%s, prefix=%s', this._host, this._port, this._db, this._prefix);

  // 兼容旧的redis模块配置
  options.password = options.password || options.auth_pass;

  this._clients = [];
  this._clientIndex = -1;
  for (var i = 0; i < options.pool; i++) {
    this._clients.push(new Redis(options));
  }

  return this;
}
456365
function filterStore(operation, store, args) {
  const filter = obj => {
    switch (operation) {
      case 'omit':
        return _.isFunction(args[0])
          ? _.omitBy(obj, args[0])
          : _.omit(obj, args);
      case 'pick':
        return _.isFunction(args[0])
          ? _.pickBy(obj, args[0])
          : _.pick(obj, args);
      default:
        break;
    }
  };
  switch (store) {
    case 'context':
    case 'functions':
    case 'directives':
    case 'plugins':
    case 'types':
      _.set(this, `_${store}`, filter(_.get(this, `_${store}`)));
      break;
    default:
      assert(false, `invalid store for ${operation} operation`);
      break;
  }
  return this;
}
959363
function MemoryStore (options) {
  options = options || {};

  options.max = Number(options.max);
  if (isNaN(options.max)) options.max = DEFAULT_MAX;
  this._max = options.max;

  options.gcProbability = Number(options.gcProbability);
  if (isNaN(options.gcProbability)) options.gcProbability = DEFAULT_PROBABILITY;
  this._gcProbability = options.gcProbability;

  debug('init: max=%s, gcProbability=%s', this._max, this._gcProbability);

  this._keys = {};
  this._keyTotal = 0;

  return this;
}
737974
function LokiStore (options) {
    if (!(this instanceof LokiStore)) {
      throw new TypeError('Cannot call LokiStore constructor as a function')
    }

    let self = this

    // Parse options

    options = options || {}
    Store.call(this, options)

    this.autosave = options.autosave !== false
    this.storePath = options.path || './session-store.db'
    this.ttl = options.ttl || 1209600
    if (this.ttl === 0) { this.ttl = null }

    // Initialize Loki.js

    this.client = new Loki(this.storePath, {
      env: 'NODEJS',
      autosave: self.autosave,
      autosaveInterval: 5000
    })

    // Setup error logging

    if (options.logErrors) {
      if (typeof options.logErrors !== 'function') {
        options.logErrors = function (err) {
          console.error('Warning: connect-loki reported a client error: ' + err)
        }
      }
      this.logger = options.logErrors
    } else {
      this.logger = _.noop
    }

    // Get / Create collection

    this.client.loadDatabase({}, () => {
      self.collection = self.client.getCollection('Sessions')
      if (_.isNil(self.collection)) {
        self.collection = self.client.addCollection('Sessions', {
          indices: ['sid'],
          ttlInterval: self.ttl
        })
      }
      self.collection.on('error', (err) => {
        return self.logger(err)
      })
      self.emit('connect')
    })
  }
385445
function Store(data) {
  if (!(this instanceof Store)) return new Store(data);

  //当前应用的数据
  this.data = Immutable.fromJS(data || {});

  //缓存初始状态的值
  this.init = this.data;

  //注册store change的callback
  this.callbacks = [];

  /**
   * 暴露给外面的方法
   */
  return {
    data: this.getData.bind(this),
    onStoreChange: this.onStoreChange.bind(this),
    removeStoreChange: this.removeStoreChange.bind(this),
    cursor: this.cursor.bind(this),
    reset: this.reset.bind(this)
  };
}
679646
function( options ){

			options 			= options || {};
			options.$db 		= cOptions.db;
			options.$dbName 	= cOptions.database;
			options.$model 		= cOptions.model;

			return new cOptions.cls( options );
		}
954916
function MongooseStore(session, mongooseModel) {
  var
  self = this;

  if(!session || !session.Store) {
    throw 'express-session was not passed in constructor.';
  }

  if(!mongooseModel || !mongooseModel.findById) {
    throw 'Mongoose Model was not passed in constructor.';
  }

  var Store = session.Store;

  /**
   * MongooseStore session store constructor
   */
  function MStore(config) {
    var
    me = this,

    // define our options for this store instance
    opts = _.extend({}, defaults, config),

    // default (un)serializer using JSON
    serializer = JSON.stringify,
    unserializer = JSON.parse;

    // call superclass method
    Store.call(me, opts);

    var
    defExpireTime  = opts.defaultExpirationTime,
    propSid        = opts.propertySessionId,
    propData       = opts.propertyData,
    propLastActive = opts.propertyLastActivity;

    // creates/updates a query to search for a certain property
    function _applyProp(property, value, obj) {
      obj = obj || {};
      obj[property] = value;
      return obj;
    }

    // checks a session document's expiration date to see if it's still valid
    function _checkExpiration(session) {
      return !session[propLastActive] || new Date < (session[propLastActive].getTime() + defExpireTime);
    }

    _.extend(me, {

      // get session data by session id:
      get: function (sid, callback) {
        var cb = callback || _.noop;

        // ensureIndex is already called on start-up
        mongooseModel.findOne(_applyProp(propSid, sid), function(err, doc) {

          if(err || !doc) { // exit immediately
            cb(err, null);
            return;
          }

          if(_checkExpiration(doc) && doc[propData] !== undefined) { // we're still valid:
            cb(null, unserializer(doc[propData]));
          }
          else { // needs clean-up
            me.destroy(sid, cb);
          }
        });
      },

      // set session data by session id:
      set: function (sid, session, callback) {
        var rec = {};

        // apply our properties:
        _applyProp(propSid, sid, rec);
        _applyProp(propData, serializer(session), rec);

        // opportunity to do:
        _applyProp(propLastActive, new Date(), rec);

        mongooseModel.findOneAndUpdate(_applyProp(propSid, sid), rec, {upsert: true}, function(err){
          (callback||_.noop)(err);
        });
      },

      // destroy session by session id:
      destroy: function (sid, callback) {
        mongooseModel.findOneAndRemove(_applyProp(propSid, sid), function(err) {
          (callback||_.noop)(err);
        });
      },

      // get the number of total sessions:
      length: function (callback) {
        mongooseModel.count({}, callback||_.noop);
      },

      // clear all stored sessions:
      clear: function (callback) {
        mongooseModel.remove({}, callback||_.noop);
      }
    });

    return me;
  }

  // inherit by default from connect memory store:
  util.inherits(MStore, Store);

  // return preconfigured mongoose store:
  return MStore;
}