import {
  CACHE_DEFAULT_TTL
} from "./chunk-L6FTY45T.js";
import {
  __decorateClass,
  __decorateParam
} from "./chunk-2E224ZSN.js";

// runtime/subsystems/cache/cache.memory-backend.ts
import { Injectable, Inject, Optional } from "@nestjs/common";
var MemoryCacheService = class {
  constructor(defaultTtl = null) {
    this.defaultTtl = defaultTtl;
  }
  defaultTtl;
  store = /* @__PURE__ */ new Map();
  timers = /* @__PURE__ */ new Map();
  /** In-flight getOrSet promises — keyed by cache key to deduplicate stampedes. */
  inflight = /* @__PURE__ */ new Map();
  async get(key) {
    const record = this.store.get(key);
    if (!record) return null;
    if (record.expiresAt !== null && record.expiresAt <= Date.now()) {
      this.evict(key);
      return null;
    }
    return record.value;
  }
  async set(key, value, ttlSeconds) {
    const effectiveTtl = ttlSeconds ?? this.defaultTtl ?? null;
    this.clearTimer(key);
    const expiresAt = effectiveTtl !== null ? Date.now() + effectiveTtl * 1e3 : null;
    this.store.set(key, { value, expiresAt });
    if (effectiveTtl !== null) {
      const timer = setTimeout(() => this.evict(key), effectiveTtl * 1e3);
      this.timers.set(key, timer);
    }
  }
  async delete(key) {
    this.evict(key);
  }
  async invalidateByPrefix(prefix) {
    let count = 0;
    for (const key of this.store.keys()) {
      if (key.startsWith(prefix)) {
        this.evict(key);
        count++;
      }
    }
    return count;
  }
  async has(key) {
    const value = await this.get(key);
    return value !== null;
  }
  async getOrSet(key, factory, ttlSeconds) {
    const cached = await this.get(key);
    if (cached !== null) return cached;
    const existing = this.inflight.get(key);
    if (existing !== void 0) return existing;
    const promise = factory().then(async (value) => {
      await this.set(key, value, ttlSeconds);
      return value;
    }).finally(() => {
      this.inflight.delete(key);
    });
    this.inflight.set(key, promise);
    return promise;
  }
  /** Remove a key from store and cancel its expiry timer. */
  evict(key) {
    this.store.delete(key);
    this.clearTimer(key);
  }
  clearTimer(key) {
    const timer = this.timers.get(key);
    if (timer !== void 0) {
      clearTimeout(timer);
      this.timers.delete(key);
    }
  }
};
MemoryCacheService = __decorateClass([
  Injectable(),
  __decorateParam(0, Optional()),
  __decorateParam(0, Inject(CACHE_DEFAULT_TTL))
], MemoryCacheService);

export {
  MemoryCacheService
};
//# sourceMappingURL=chunk-IF5I3DAA.js.map