{"version":3,"sources":["../../src/db/redis.ts"],"sourcesContent":["// ============================================================================\n// Rollease SDK - Redis Cache Adapter\n// ============================================================================\n\nimport type {\n  CacheAdapter,\n  InvalidationBus,\n  InvalidationListener,\n  InvalidationMessage,\n} from \"./adapter\";\n\ntype RedisClientLike = {\n  isOpen?: boolean;\n  connect?: () => Promise<unknown>;\n  get: (key: string) => Promise<string | null>;\n  set: (\n    key: string,\n    value: string,\n    options?: { PX?: number; EX?: number }\n  ) => Promise<unknown>;\n  del: (key: string | string[]) => Promise<unknown>;\n  scanIterator?: (options?: {\n    MATCH?: string;\n    COUNT?: number;\n  }) => AsyncIterable<string>;\n  quit?: () => Promise<unknown>;\n  disconnect?: () => Promise<unknown> | unknown;\n};\n\ntype RedisPubSubClientLike = RedisClientLike & {\n  publish?: (channel: string, message: string) => Promise<unknown>;\n  subscribe?: (\n    channel: string,\n    listener: (message: string) => void\n  ) => Promise<unknown>;\n  unsubscribe?: (channel: string) => Promise<unknown>;\n  duplicate?: () => RedisPubSubClientLike;\n};\n\nexport interface RedisCacheAdapterOptions {\n  /** Existing redis v4 client. If omitted, the adapter lazy-creates one. */\n  client?: RedisClientLike;\n  /** Redis connection URL used when client is omitted. */\n  url?: string;\n  /** Optional prefix for every cache key. */\n  keyPrefix?: string;\n  /** Automatically connect before commands. Defaults to true. */\n  autoConnect?: boolean;\n  /** SCAN batch size for delPattern. Defaults to 100. */\n  scanCount?: number;\n}\n\nexport class RedisCacheAdapter implements CacheAdapter {\n  private client?: RedisClientLike;\n  private ownsClient: boolean;\n  private keyPrefix: string;\n  private autoConnect: boolean;\n  private scanCount: number;\n  private connectPromise?: Promise<void>;\n  private connected = false;\n  private url?: string;\n\n  constructor(options: RedisCacheAdapterOptions = {}) {\n    this.client = options.client;\n    this.ownsClient = !options.client;\n    this.url = options.url;\n    this.keyPrefix = options.keyPrefix ?? \"\";\n    this.autoConnect = options.autoConnect ?? true;\n    this.scanCount = options.scanCount ?? 100;\n  }\n\n  async get(key: string): Promise<string | null> {\n    const client = await this.getClient();\n    return client.get(this.key(key));\n  }\n\n  async set(key: string, value: string, ttlMs: number): Promise<void> {\n    const client = await this.getClient();\n    const normalizedTtl = Math.max(1, Math.ceil(ttlMs));\n    await client.set(this.key(key), value, { PX: normalizedTtl });\n  }\n\n  async del(key: string): Promise<void> {\n    const client = await this.getClient();\n    await client.del(this.key(key));\n  }\n\n  async delPattern(pattern: string): Promise<void> {\n    const client = await this.getClient();\n    if (!client.scanIterator) {\n      throw new Error(\"Redis client must support scanIterator() for delPattern()\");\n    }\n\n    // Escape Redis glob special characters in the prefix portion to avoid\n    // unintended pattern matching (e.g. prefix containing `[` or `*`).\n    const escapedPrefix = this.keyPrefix.replace(/([*?[\\]\\\\])/g, \"\\\\$1\");\n    const fullPattern = `${escapedPrefix}${pattern}`;\n    const batch: string[] = [];\n    for await (const key of client.scanIterator({\n      MATCH: fullPattern,\n      COUNT: this.scanCount,\n    })) {\n      batch.push(key);\n      if (batch.length >= this.scanCount) {\n        await client.del(batch.splice(0, batch.length));\n      }\n    }\n\n    if (batch.length > 0) {\n      await client.del(batch);\n    }\n  }\n\n  async close(): Promise<void> {\n    if (!this.client || !this.ownsClient) return;\n\n    if (this.client.quit) {\n      await this.client.quit();\n      return;\n    }\n\n    if (this.client.disconnect) {\n      await this.client.disconnect();\n    }\n  }\n\n  private async getClient(): Promise<RedisClientLike> {\n    if (!this.client) {\n      const moduleName = \"redis\";\n      const redisModule = (await import(moduleName)) as {\n        createClient: (options?: { url?: string }) => RedisClientLike;\n      };\n      this.client = redisModule.createClient(\n        this.url ? { url: this.url } : undefined\n      );\n    }\n\n    if (\n      this.autoConnect &&\n      this.client.connect &&\n      !this.connected &&\n      this.client.isOpen !== true\n    ) {\n      this.connectPromise ??= this.client.connect().then(() => {\n        this.connected = true;\n      });\n      await this.connectPromise;\n    }\n\n    return this.client;\n  }\n\n  private key(key: string): string {\n    return `${this.keyPrefix}${key}`;\n  }\n}\n\nexport function createRedisCache(\n  options: RedisCacheAdapterOptions = {}\n): RedisCacheAdapter {\n  return new RedisCacheAdapter(options);\n}\n\nexport interface RedisInvalidationBusOptions {\n  /** Existing redis v4 client. If omitted, the bus lazy-creates one. */\n  client?: RedisPubSubClientLike;\n  /** Optional dedicated subscriber client. Defaults to client.duplicate() when available. */\n  subscriber?: RedisPubSubClientLike;\n  /** Redis connection URL used when client is omitted. */\n  url?: string;\n  /** Pub/sub channel name. @default 'rollease:invalidation' */\n  channel?: string;\n  /** Automatically connect before commands. Defaults to true. */\n  autoConnect?: boolean;\n}\n\nexport class RedisInvalidationBus implements InvalidationBus {\n  private publisher?: RedisPubSubClientLike;\n  private subscriber?: RedisPubSubClientLike;\n  private ownsClients: boolean;\n  private url?: string;\n  private channel: string;\n  private autoConnect: boolean;\n  private connected = false;\n  private subscribed = false;\n  private connectPromise?: Promise<void>;\n  private listeners = new Set<InvalidationListener>();\n\n  constructor(options: RedisInvalidationBusOptions = {}) {\n    this.publisher = options.client;\n    this.subscriber = options.subscriber;\n    this.ownsClients = !options.client;\n    this.url = options.url;\n    this.channel = options.channel ?? \"rollease:invalidation\";\n    this.autoConnect = options.autoConnect ?? true;\n  }\n\n  async publish(message: InvalidationMessage): Promise<void> {\n    const client = await this.getPublisher();\n    if (!client.publish) {\n      throw new Error(\"Redis client must support publish() for invalidation\");\n    }\n    await client.publish(\n      this.channel,\n      JSON.stringify({ ...message, ts: message.ts ?? Date.now() })\n    );\n  }\n\n  async subscribe(listener: InvalidationListener): Promise<() => void> {\n    this.listeners.add(listener);\n    await this.ensureSubscribed();\n    return () => {\n      this.listeners.delete(listener);\n    };\n  }\n\n  async close(): Promise<void> {\n    this.listeners.clear();\n    if (this.subscriber?.unsubscribe && this.subscribed) {\n      await this.subscriber.unsubscribe(this.channel);\n    }\n    if (!this.ownsClients) return;\n    await closeRedisClient(this.subscriber);\n    if (this.publisher !== this.subscriber) {\n      await closeRedisClient(this.publisher);\n    }\n  }\n\n  private async ensureSubscribed(): Promise<void> {\n    if (this.subscribed) return;\n    const subscriber = await this.getSubscriber();\n    if (!subscriber.subscribe) {\n      throw new Error(\"Redis client must support subscribe() for invalidation\");\n    }\n    await subscriber.subscribe(this.channel, (raw) => {\n      let parsed: InvalidationMessage;\n      try {\n        parsed = JSON.parse(raw) as InvalidationMessage;\n      } catch {\n        return;\n      }\n      for (const listener of this.listeners) {\n        void listener(parsed);\n      }\n    });\n    this.subscribed = true;\n  }\n\n  private async getPublisher(): Promise<RedisPubSubClientLike> {\n    if (!this.publisher) {\n      const redisModule = await importRedisModule();\n      this.publisher = redisModule.createClient(\n        this.url ? { url: this.url } : undefined\n      ) as RedisPubSubClientLike;\n    }\n    await this.connectClients();\n    return this.publisher;\n  }\n\n  private async getSubscriber(): Promise<RedisPubSubClientLike> {\n    if (!this.subscriber) {\n      const publisher = await this.getPublisher();\n      this.subscriber = publisher.duplicate\n        ? publisher.duplicate()\n        : publisher;\n      if (\n        this.autoConnect &&\n        this.subscriber !== publisher &&\n        this.subscriber.connect &&\n        this.subscriber.isOpen !== true\n      ) {\n        await this.subscriber.connect();\n      }\n    }\n    await this.connectClients();\n    return this.subscriber;\n  }\n\n  private async connectClients(): Promise<void> {\n    if (!this.autoConnect || this.connected) return;\n    this.connectPromise ??= (async () => {\n      if (this.publisher?.connect && this.publisher.isOpen !== true) {\n        await this.publisher.connect();\n      }\n      if (\n        this.subscriber &&\n        this.subscriber !== this.publisher &&\n        this.subscriber.connect &&\n        this.subscriber.isOpen !== true\n      ) {\n        await this.subscriber.connect();\n      }\n      this.connected = true;\n    })();\n    await this.connectPromise;\n  }\n}\n\nexport function createRedisInvalidationBus(\n  options: RedisInvalidationBusOptions = {}\n): RedisInvalidationBus {\n  return new RedisInvalidationBus(options);\n}\n\nasync function closeRedisClient(client: RedisPubSubClientLike | undefined): Promise<void> {\n  if (!client) return;\n  if (client.quit) {\n    await client.quit();\n    return;\n  }\n  if (client.disconnect) {\n    await client.disconnect();\n  }\n}\n\nasync function importRedisModule(): Promise<{\n  createClient: (options?: { url?: string }) => RedisPubSubClientLike;\n}> {\n  const moduleName = \"redis\";\n  return (await import(moduleName)) as {\n    createClient: (options?: { url?: string }) => RedisPubSubClientLike;\n  };\n}\n"],"mappings":";AAoDO,IAAM,oBAAN,MAAgD;AAAA,EAC7C;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA,YAAY;AAAA,EACZ;AAAA,EAER,YAAY,UAAoC,CAAC,GAAG;AAClD,SAAK,SAAS,QAAQ;AACtB,SAAK,aAAa,CAAC,QAAQ;AAC3B,SAAK,MAAM,QAAQ;AACnB,SAAK,YAAY,QAAQ,aAAa;AACtC,SAAK,cAAc,QAAQ,eAAe;AAC1C,SAAK,YAAY,QAAQ,aAAa;AAAA,EACxC;AAAA,EAEA,MAAM,IAAI,KAAqC;AAC7C,UAAM,SAAS,MAAM,KAAK,UAAU;AACpC,WAAO,OAAO,IAAI,KAAK,IAAI,GAAG,CAAC;AAAA,EACjC;AAAA,EAEA,MAAM,IAAI,KAAa,OAAe,OAA8B;AAClE,UAAM,SAAS,MAAM,KAAK,UAAU;AACpC,UAAM,gBAAgB,KAAK,IAAI,GAAG,KAAK,KAAK,KAAK,CAAC;AAClD,UAAM,OAAO,IAAI,KAAK,IAAI,GAAG,GAAG,OAAO,EAAE,IAAI,cAAc,CAAC;AAAA,EAC9D;AAAA,EAEA,MAAM,IAAI,KAA4B;AACpC,UAAM,SAAS,MAAM,KAAK,UAAU;AACpC,UAAM,OAAO,IAAI,KAAK,IAAI,GAAG,CAAC;AAAA,EAChC;AAAA,EAEA,MAAM,WAAW,SAAgC;AAC/C,UAAM,SAAS,MAAM,KAAK,UAAU;AACpC,QAAI,CAAC,OAAO,cAAc;AACxB,YAAM,IAAI,MAAM,2DAA2D;AAAA,IAC7E;AAIA,UAAM,gBAAgB,KAAK,UAAU,QAAQ,gBAAgB,MAAM;AACnE,UAAM,cAAc,GAAG,aAAa,GAAG,OAAO;AAC9C,UAAM,QAAkB,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