async cleanStates()

in src/auth/storage.ts [157:212]


  async cleanStates(removeStateId?: string) {
    const now = Date.now();

    const removalResult = await this._stateStorage.each<StateRemovalResult | void>((key, value) => {
      if (value === null || value === undefined) {
        return undefined;
      }

      // Remove requested state
      if (key === this.stateKeyPrefix + removeStateId) {
        return this._stateStorage.remove(key);
      }

      if (key.indexOf(this.stateKeyPrefix) === 0) {
        // Clean old states
        const state = value as AuthState;
        const created = state.created ?? Date.now();
        if (created + this.stateTTL < now) {
          return this._stateStorage.remove(key);
        }

        // Data to clean up due quota
        return {
          key,
          created,
          size: JSON.stringify(state).length,
        };
      }

      return undefined;
    });
    const currentStates = removalResult.filter(
      (state): state is StateRemovalResult => state !== null && state !== undefined,
    );

    let stateStorageSize = currentStates.reduce((overallSize, state) => state.size + overallSize, 0);

    if (stateStorageSize > this.stateQuota) {
      currentStates.sort((a, b) => a.created - b.created);

      const removalPromises = currentStates
        .filter(state => {
          if (stateStorageSize > this.stateQuota) {
            stateStorageSize -= state.size;
            return true;
          }

          return false;
        })
        .map(state => this._stateStorage.remove(state.key));

      return removalPromises.length && Promise.all(removalPromises);
    }

    return undefined;
  }