text: /**
   * @copyright Microsoft Corporation. All rights reserved.
   */
  import { _LogSource, _TraceLogger } from '@microsoft/sp-diagnostics';
  import { ServiceKey, UrlUtilities, TimeProvider } from '@microsoft/sp-core-library';
  import { fetchProviderServiceKey } from '../httpClient/FetchProvider';
  /**
   * {@inheritDoc IDigestCache}
   *
   * @public
   */
  var DigestCache = /** @class */ (function () {
      function DigestCache(serviceScope) {
          var _this = this;
          this._digestsByUrl = new Map();
          serviceScope.whenFinished(function () {
              _this._fetchProvider = serviceScope.consume(fetchProviderServiceKey);
              _this._timeProvider = serviceScope.consume(TimeProvider.serviceKey);
          });
      }
      /**
       * {@inheritDoc IDigestCache.fetchDigest}
       */
      DigestCache.prototype.fetchDigest = function (webUrl) {
          var _this = this;
          var normalizedWebUrl = UrlUtilities.removeEndSlash(webUrl);
          var cachedDigest = this._digestsByUrl.get(normalizedWebUrl);
          if (cachedDigest) {
              var timestamp = this._timeProvider.getDate().getTime();
              if (timestamp < cachedDigest.expirationTimestamp) {
                  _TraceLogger.logVerbose(DigestCache._logSource, 'DigestCache: Reusing cached digest.  Expiration: ' + cachedDigest.expirationTimestamp);
                  return Promise.resolve(cachedDigest.value);
              }
          }
          // If it wasn't in the cache, then we need to fetch a new one.
          // Create the REST API URL
          var digestUrl = normalizedWebUrl + '/_api/contextinfo';
          // NOTE: We don't want people to be injecting random headers throughout
          // their code.  As SPHttpClient evolves, maybe there is some way we can
          // combine this with the headers being added there.
          var rawRequest = new Request(digestUrl, {
              method: 'POST',
              headers: {
                  Accept: 'application/json',
                  'Content-type': 'application/json;odata=verbose;charset=utf-8'
              },
              credentials: 'same-origin',
              cache: 'no-cache'
          });
          var preFetchDigestTime = this._timeProvider.getDate().getTime();
          return this._fetchProvider
              .fetch(rawRequest)
              .then(function (response) {
              return response.json();
          })
              .then(function (responseObject) {
              var digestValue = responseObject.FormDigestValue;
              var seconds = responseObject.FormDigestTimeoutSeconds;
              var expirationTimeMs = preFetchDigestTime + 1000 * seconds - DigestCache.REST_EXPIRATION_SLOP_MS;
              _this.addDigestToCache(normalizedWebUrl, digestValue, expirationTimeMs);
              _TraceLogger.logVerbose(DigestCache._logSource, 'DigestCache: Fetched new digest');
              return digestValue;
          });
      };
      /**
       * {@inheritDoc IDigestCache.addDigestToCache}
       */
      DigestCache.prototype.addDigestToCache = function (webUrl, digestValue, expirationTimestamp) {
          // Don't use bad digest to the cache
          var currentTimestamp = this._timeProvider.getDate().getTime();
          if (currentTimestamp < expirationTimestamp) {
              var normalizedWebUrl = UrlUtilities.removeEndSlash(webUrl);
              var newCachedDigest = {
                  value: digestValue,
                  expirationTimestamp: expirationTimestamp
              };
              this._digestsByUrl.set(normalizedWebUrl, newCachedDigest);
          }
      };
      /**
       * {@inheritDoc IDigestCache.clearDigest}
       */
      DigestCache.prototype.clearDigest = function (webUrl) {
          var normalizedWebUrl = UrlUtilities.removeEndSlash(webUrl);
          var found = this._digestsByUrl.delete(normalizedWebUrl);
          _TraceLogger.logVerbose(DigestCache._logSource, "DigestCache: Requested to clear cache entry: " + (found ? 'found' : 'not found'));
          return found;
      };
      /**
       * {@inheritDoc IDigestCache.clearAllDigests}
       */
      DigestCache.prototype.clearAllDigests = function () {
          this._digestsByUrl.clear();
      };
      /**
       * The service key for IDigestCache.
       */
      DigestCache.serviceKey = ServiceKey.create('sp-client-base:DigestCache', DigestCache);
      // The digest cache expiration times are measured from whenever the C# code on the server
      // generated the digest, whereas in the current implementation, we start measuring from
      // whenever the user navigated to the current page. We don’t know how much time elapsed
      // between those two times (e.g. due to a page taking unusually long to load on the server
      // or a sluggish browser), so we conservatively subtract 30 seconds from
      // SPWebApplication.FormDigestSettings.Timeout (whose default is 30 minutes). If for some reason an
      // admin had configured the timeout to be very short, then the preloaded value can’t be used at all,
      // but this isn’t a big deal since the REST call is measured accurately and has a much smaller slop.
      // Estimates any noise e.g. due to server clocks being slightly out of sync, or the browser
      // clock being imprecise
      DigestCache.REST_EXPIRATION_SLOP_MS = 15000; // 15 secs
      DigestCache._logSource = _LogSource.create('DigestCache');
      return DigestCache;
  }());
  export default DigestCache;
  //# sourceMappingURL=DigestCache.js.map