{"version":3,"sources":["../src/RedisStringsHandler.ts","../src/utils/debug.ts","../src/utils/redisConnection.ts","../src/SyncedMap.ts","../src/DeduplicatedRequestHandler.ts","../src/utils/json.ts","../src/serializer.ts","../src/utils/cacheTtl.ts","../src/utils/abortableGet.ts","../src/utils/deadline.ts","../src/utils/clusterSafeUnlink.ts","../src/utils/prefix.ts","../src/CachedHandler.ts","../src/CacheComponentsHandler.ts","../src/utils/compareAndUnlink.ts","../src/utils/tagRevalidation.ts","../src/index.ts"],"sourcesContent":["import { createClient, RedisClientOptions } from 'redis';\nimport { SyncedMap } from './SyncedMap';\nimport { DeduplicatedRequestHandler } from './DeduplicatedRequestHandler';\nimport { debug } from './utils/debug';\nimport { CacheValueSerializer, jsonCacheValueSerializer } from './serializer';\nimport { resolveCacheEntryTtlSeconds } from './utils/cacheTtl';\nimport { shouldDeferRedisConnection } from './utils/redisConnection';\nimport { AbortableGet, createAbortableGet } from './utils/abortableGet';\nimport { RedisTimeoutError, untilDeadline } from './utils/deadline';\nimport { clusterSafeUnlink } from './utils/clusterSafeUnlink';\n\nexport type Client = ReturnType<typeof createClient>;\n\nexport type CacheEntry = {\n  value: unknown;\n  lastModified: number;\n  tags: string[];\n};\n\n/** Discriminated union of the `ctx` argument Next.js passes to\n * {@link RedisStringsHandler.get}. The Pages Router (`PAGES`) has no PPR\n * concept, so `isRoutePPREnabled` is optional for it.\n *\n * Note: `REDIRECT` is intentionally absent. Next.js always calls `get()` with\n * `kind: 'PAGES'` for Pages Router routes, even when the stored value has\n * `kind: 'REDIRECT'`. The handler returns whatever value is cached and Next.js\n * interprets it accordingly. */\nexport type GetContext =\n  | {\n      kind: 'APP_ROUTE' | 'APP_PAGE';\n      isRoutePPREnabled: boolean;\n      isFallback: boolean;\n    }\n  | {\n      kind: 'PAGES';\n      isRoutePPREnabled?: boolean;\n      isFallback: boolean;\n    }\n  | {\n      kind: 'FETCH';\n      revalidate: number;\n      fetchUrl: string;\n      fetchIdx: number;\n      tags: string[];\n      softTags: string[];\n      isFallback: boolean;\n    };\n\n/** Discriminated union of cache payloads accepted by\n * {@link RedisStringsHandler.set}. `null` is a valid payload: the Pages Router\n * stores `notFound: true` results as a cache entry with a null value. */\nexport type SetCacheValue =\n  | {\n      kind: 'APP_PAGE';\n      status?: number;\n      headers: {\n        'x-nextjs-stale-time': string; // timestamp in ms\n        'x-next-cache-tags': string; // comma separated paths (tags)\n      };\n      html: string;\n      rscData: Buffer;\n      segmentData: unknown;\n      postponed: unknown;\n    }\n  | {\n      kind: 'APP_ROUTE';\n      status: number;\n      headers: {\n        'cache-control'?: string;\n        'x-nextjs-stale-time': string; // timestamp in ms\n        'x-next-cache-tags': string; // comma separated paths (tags)\n      };\n      body: Buffer;\n    }\n  | {\n      kind: 'PAGES';\n      html: string;\n      pageData: Record<string, unknown>;\n      headers?: Record<string, number | string | string[] | undefined>;\n      status?: number;\n    }\n  | {\n      kind: 'REDIRECT';\n      props: Record<string, unknown>;\n    }\n  | {\n      kind: 'FETCH';\n      data: {\n        headers: Record<string, string>;\n        body: string; // base64 encoded\n        status: number;\n        url: string;\n      };\n      revalidate: number | false;\n    }\n  | null;\n\nexport function redisErrorHandler<T extends Promise<unknown>>(\n  debugInfo: string,\n  redisCommandResult: T,\n): T {\n  const beforeTimestamp = performance.now();\n  return redisCommandResult.catch((error) => {\n    console.error(\n      'Redis command error',\n      (performance.now() - beforeTimestamp).toFixed(2),\n      'ms',\n      debugInfo,\n      error,\n    );\n    throw error;\n  }) as T;\n}\n\nif (process.env.DEBUG_CACHE_HANDLER) {\n  // This is a test to check if the event loop is lagging. If it lags, increase CPU of container\n  setInterval(() => {\n    const start = performance.now();\n    setImmediate(() => {\n      const duration = performance.now() - start;\n      if (duration > 100) {\n        debug(\n          'yellow',\n          `RedisStringsHandler detected an event loop lag of: ${duration.toFixed(2)}ms. If your container is hosted in a cloud provider with container suspension this is normal. If not you should increase the CPU of your container.`,\n        );\n      }\n    });\n  }, 500);\n}\n\nexport type CreateRedisStringsHandlerOptions = {\n  /** Redis redisUrl to use.\n   * @default process.env.REDIS_URL? process.env.REDIS_URL : process.env.REDISHOST\n          ? `redis://${process.env.REDISHOST}:${process.env.REDISPORT}`\n          : 'redis://localhost:6379'\n   */\n  redisUrl?: string;\n  /** Redis database number to use. Uses DB 0 for production, DB 1 otherwise\n   * @default process.env.VERCEL_ENV === 'production' ? 0 : 1\n   */\n  database?: number;\n  /** Prefix added to all Redis keys\n   * @default process.env.KEY_PREFIX || process.env.VERCEL_URL || 'UNDEFINED_URL_'\n   */\n  keyPrefix?: string;\n  /** Timeout in milliseconds for time critical Redis operations (during cache get, which blocks site rendering).\n   *  If redis get is not fulfilled within this time, the cache handler will return null so site rendering will\n   *  not be blocked further and site can fallback to re-render/re-fetch the content.\n   * @default 500\n   */\n  getTimeoutMs?: number;\n  /** Timeout in milliseconds for the Redis writes that a request waits for (set, revalidateTag).\n   *  If Redis does not confirm them within this time, `set` logs a warning and returns, so the\n   *  request is not blocked further. The write can still be applied later, or be lost.\n   *  `revalidateTag` logs an error and throws a `RedisTimeoutError` instead, because a lost\n   *  invalidation leaves stale entries on every instance.\n   * @default process.env.REDIS_WRITE_TIMEOUT_MS, else getTimeoutMs\n   */\n  writeTimeoutMs?: number;\n  /** Number of entries to query in one batch during full sync of shared tags hash map\n   * @default 250\n   */\n  revalidateTagQuerySize?: number;\n  /** Key used to store shared tags hash map in Redis\n   * @default '__sharedTags__'\n   */\n  sharedTagsKey?: string;\n  /** Average interval in milliseconds between tag map full re-syncs\n   * @default 3600000 (1 hour)\n   */\n  avgResyncIntervalMs?: number;\n  /** Enable deduplication of Redis get requests via internal in-memory cache\n   * @default true\n   */\n  redisGetDeduplication?: boolean;\n  /** Time in milliseconds to cache Redis get results in memory. Set this to 0 to disable in-memory caching completely\n   * @default 10000\n   */\n  inMemoryCachingTime?: number;\n  /** Default stale age in seconds for cached items\n   * @default 1209600 (14 days)\n   */\n  defaultStaleAge?: number;\n  /** Function to calculate expire age (redis TTL value) from stale age\n   * @default Production: staleAge * 2, Other: staleAge * 1.2\n   */\n  estimateExpireAge?: (staleAge: number) => number;\n  /** Kill container on Redis client error if error threshold is reached\n   * @default 0 (0 means no error threshold)\n   */\n  killContainerOnErrorThreshold?: number;\n  /** Maximum number of Redis hash slot groups deleted concurrently during tag invalidation.\n   *  Keeps Valkey/Redis cluster invalidation cluster-safe without creating unbounded\n   *  command bursts for high-cardinality tags.\n   * @default 16\n   */\n  revalidateTagDeleteConcurrency?: number;\n  /** Additional Redis client socket options\n   * @example { tls: true, rejectUnauthorized: false }\n   */\n  socketOptions?: RedisClientOptions['socket'];\n  /** Additional Redis client options to be passed directly to createClient\n   * @example { username: 'user', password: 'pass' }\n   */\n  clientOptions?: Omit<RedisClientOptions, 'url' | 'database' | 'socket'>;\n  /** Pluggable wire-format codec for Redis string values. Lets you plug in\n   * compression (gzip/brotli), encryption, or any other custom encoding without\n   * forking this package or losing the existing dedup / batch / keyspace features.\n   *\n   * Both `serialize` and `deserialize` may return a `Promise`, enabling\n   * non-blocking async codecs (e.g. `zlib.brotliCompress`) that don't block the\n   * Node.js event loop. Synchronous implementations continue to work unchanged.\n   *\n   * Only the main cache-entry storage path is routed through the serializer.\n   * The shared-tags map and the revalidated-tags map are not. The in-memory\n   * deduplication cache stores the wire-format string verbatim - its contents\n   * change with the serializer, but the cache itself is not re-encoded.\n   *\n   * Operational note: changing the serializer (or any of its parameters such as\n   * a compression level or encryption key) makes existing Redis keys unreadable.\n   * Either flush the affected keys or bump `keyPrefix` before deploying.\n   *\n   * @default jsonCacheValueSerializer (JSON.stringify with bufferAndMapReplacer\n   * so native Buffer and Map values inside a CacheEntry round-trip transparently)\n   */\n  valueSerializer?: CacheValueSerializer;\n};\n\n// One SyncedMap.delete() publishes a single sync message for every key it\n// receives. Clearing the local read-through cache one key at a time therefore\n// turns a high-cardinality tag into one Redis publish per key, ahead of the\n// bounded UNLINK workers. Batch the keys, and cap each message so a very\n// large tag cannot produce an unbounded pub/sub payload either.\nconst LOCAL_CACHE_DELETE_BATCH_SIZE = 500;\n\n// Identifier prefix used by Next.js to mark automatically generated cache tags\n// These tags are created internally by Next.js for route-based invalidation\nconst NEXT_CACHE_IMPLICIT_TAG_ID = '_N_T_';\n\n// Redis key used to store a map of tags and their last revalidation timestamps\n// This helps track when specific tags were last invalidated\nconst REVALIDATED_TAGS_KEY = '__revalidated_tags__';\n\n// Cache kinds this handler is designed and tested for. Kept as the single\n// source of truth for both payload validation and the warning message, so\n// adding a kind is a one-line change here instead of edits scattered across\n// the type union, the guard chain, and the log string.\nconst SUPPORTED_GET_KINDS = [\n  'APP_ROUTE',\n  'APP_PAGE',\n  'PAGES',\n  'FETCH',\n] as const;\nconst SUPPORTED_SET_KINDS = [\n  'APP_ROUTE',\n  'APP_PAGE',\n  'PAGES',\n  'REDIRECT',\n  'FETCH',\n] as const;\n\nlet killContainerOnErrorCount: number = 0;\nexport default class RedisStringsHandler {\n  private client: Client;\n  private sharedTagsMap: SyncedMap<string[]>;\n  private revalidatedTagsMap: SyncedMap<number>;\n  private inMemoryDeduplicationCache: SyncedMap<Promise<string | null>>;\n  private getTimeoutMs: number;\n  private writeTimeoutMs: number;\n  private redisGet: AbortableGet;\n  private redisDeduplicationHandler: DeduplicatedRequestHandler<\n    AbortableGet,\n    string | null\n  >;\n  private deduplicatedRedisGet: (key: string) => AbortableGet;\n  private keyPrefix: string;\n  private redisGetDeduplication: boolean;\n  private inMemoryCachingTime: number;\n  private defaultStaleAge: number;\n  private estimateExpireAge: (staleAge: number) => number;\n  private killContainerOnErrorThreshold: number;\n  private valueSerializer: CacheValueSerializer;\n  private redisConnectionDeferred: boolean;\n  private revalidateTagDeleteConcurrency: number;\n\n  constructor({\n    redisUrl = process.env.REDIS_URL\n      ? process.env.REDIS_URL\n      : process.env.REDISHOST\n        ? `redis://${process.env.REDISHOST}:${process.env.REDISPORT}`\n        : 'redis://localhost:6379',\n    database = process.env.VERCEL_ENV === 'production' ? 0 : 1,\n    keyPrefix = process.env.KEY_PREFIX ||\n      process.env.VERCEL_URL ||\n      'UNDEFINED_URL_',\n    sharedTagsKey = '__sharedTags__',\n    getTimeoutMs = process.env.REDIS_COMMAND_TIMEOUT_MS\n      ? (Number.parseInt(process.env.REDIS_COMMAND_TIMEOUT_MS) ?? 500)\n      : 500,\n    writeTimeoutMs = process.env.REDIS_WRITE_TIMEOUT_MS\n      ? Number.parseInt(process.env.REDIS_WRITE_TIMEOUT_MS) || getTimeoutMs\n      : getTimeoutMs,\n    revalidateTagQuerySize = 250,\n    avgResyncIntervalMs = 60 * 60 * 1_000,\n    redisGetDeduplication = true,\n    inMemoryCachingTime = 10_000,\n    defaultStaleAge = 60 * 60 * 24 * 14,\n    estimateExpireAge = (staleAge) =>\n      process.env.VERCEL_ENV === 'production' ? staleAge * 2 : staleAge * 1.2,\n    killContainerOnErrorThreshold = process.env\n      .KILL_CONTAINER_ON_ERROR_THRESHOLD\n      ? (Number.parseInt(process.env.KILL_CONTAINER_ON_ERROR_THRESHOLD) ?? 0)\n      : 0,\n    revalidateTagDeleteConcurrency = 16,\n    socketOptions,\n    clientOptions,\n    valueSerializer = jsonCacheValueSerializer,\n  }: CreateRedisStringsHandlerOptions) {\n    try {\n      this.keyPrefix = keyPrefix;\n      this.redisGetDeduplication = redisGetDeduplication;\n      this.inMemoryCachingTime = inMemoryCachingTime;\n      this.defaultStaleAge = defaultStaleAge;\n      this.estimateExpireAge = estimateExpireAge;\n      this.killContainerOnErrorThreshold = killContainerOnErrorThreshold;\n      this.revalidateTagDeleteConcurrency = Math.max(\n        1,\n        Math.floor(revalidateTagDeleteConcurrency),\n      );\n      this.getTimeoutMs = getTimeoutMs;\n      this.writeTimeoutMs = writeTimeoutMs;\n      this.valueSerializer = valueSerializer;\n      this.redisConnectionDeferred = shouldDeferRedisConnection();\n\n      try {\n        // Create Redis client with properly typed configuration\n        this.client = createClient({\n          url: redisUrl,\n          pingInterval: 10_000, // Useful with Redis deployments that do not use TCP Keep-Alive. Restarts the connection if it is idle for too long.\n          ...(database !== 0 ? { database } : {}),\n          ...(socketOptions ? { socket: { ...socketOptions } } : {}),\n          ...(clientOptions || {}),\n        });\n\n        this.client.on('error', (error) => {\n          console.error(\n            'Redis client error',\n            error,\n            killContainerOnErrorCount++,\n          );\n          setTimeout(() => {\n            // Avoid overlapping connect() calls which can lead to\n            // \"Socket already opened\" errors when a reconnect is already\n            // in progress or the socket is still open.\n            if (!this.client.isOpen && !this.client.isReady) {\n              this.client.connect().catch((error) => {\n                console.error(\n                  'Failed to reconnect Redis client after connection loss:',\n                  error,\n                );\n              });\n            }\n          }, 1000);\n          if (\n            this.killContainerOnErrorThreshold > 0 &&\n            killContainerOnErrorCount >= this.killContainerOnErrorThreshold\n          ) {\n            console.error(\n              'Redis client error threshold reached, disconnecting and exiting (please implement a restart process/container watchdog to handle this error)',\n              error,\n              killContainerOnErrorCount++,\n            );\n            this.client.disconnect();\n            this.client.quit();\n            setTimeout(() => {\n              process.exit(1);\n            }, 500);\n          }\n        });\n\n        if (!this.redisConnectionDeferred) {\n          this.client\n            .connect()\n            .then(() => {\n              debug('green', 'Redis client connected.');\n            })\n            .catch((error) => {\n              console.error('Failed to connect Redis client:', error);\n              throw error;\n            });\n        }\n      } catch (error: unknown) {\n        console.error('Failed to initialize Redis client');\n        throw error;\n      }\n\n      const filterKeys = (key: string): boolean =>\n        key !== REVALIDATED_TAGS_KEY && key !== sharedTagsKey;\n\n      this.sharedTagsMap = new SyncedMap<string[]>({\n        client: this.client,\n        keyPrefix,\n        redisKey: sharedTagsKey,\n        database,\n        querySize: revalidateTagQuerySize,\n        filterKeys,\n        resyncIntervalMs:\n          avgResyncIntervalMs -\n          avgResyncIntervalMs / 10 +\n          Math.random() * (avgResyncIntervalMs / 10),\n      });\n\n      this.revalidatedTagsMap = new SyncedMap<number>({\n        client: this.client,\n        keyPrefix,\n        redisKey: REVALIDATED_TAGS_KEY,\n        database,\n        querySize: revalidateTagQuerySize,\n        filterKeys,\n        customizedSync: { withoutOrphanCleanup: true },\n        resyncIntervalMs:\n          avgResyncIntervalMs +\n          avgResyncIntervalMs / 10 +\n          Math.random() * (avgResyncIntervalMs / 10),\n      });\n\n      this.inMemoryDeduplicationCache = new SyncedMap({\n        client: this.client,\n        keyPrefix,\n        redisKey: 'inMemoryDeduplicationCache',\n        database,\n        querySize: revalidateTagQuerySize,\n        filterKeys,\n        customizedSync: {\n          withoutRedisHashmap: true,\n          withoutSetSync: true,\n        },\n      });\n\n      const redisGet = createAbortableGet(this.client);\n      this.redisDeduplicationHandler = new DeduplicatedRequestHandler(\n        redisGet,\n        inMemoryCachingTime,\n        this.inMemoryDeduplicationCache,\n      );\n      this.redisGet = redisGet;\n      this.deduplicatedRedisGet =\n        this.redisDeduplicationHandler.deduplicatedFunction;\n    } catch (error) {\n      console.error(\n        'RedisStringsHandler constructor error',\n        error,\n        killContainerOnErrorCount++,\n      );\n      if (\n        killContainerOnErrorThreshold > 0 &&\n        killContainerOnErrorCount >= killContainerOnErrorThreshold\n      ) {\n        console.error(\n          'RedisStringsHandler constructor error threshold reached, disconnecting and exiting (please implement a restart process/container watchdog to handle this error)',\n          error,\n          killContainerOnErrorCount++,\n        );\n        process.exit(1);\n      }\n      throw error;\n    }\n  }\n\n  resetRequestCache(): void {}\n\n  private clientReadyCalls = 0;\n\n  private async assertClientIsReady(): Promise<void> {\n    if (this.clientReadyCalls > 10) {\n      throw new Error(\n        'assertClientIsReady called more than 10 times without being ready.',\n      );\n    }\n    let readyTimeout: ReturnType<typeof setTimeout> | undefined;\n    try {\n      await Promise.race([\n        Promise.all([\n          this.sharedTagsMap.waitUntilReady(),\n          this.revalidatedTagsMap.waitUntilReady(),\n        ]),\n        new Promise((_, reject) => {\n          readyTimeout = setTimeout(() => {\n            reject(\n              new Error(\n                'assertClientIsReady: Timeout waiting for Redis maps to be ready',\n              ),\n            );\n          }, 30_000);\n        }),\n      ]);\n    } finally {\n      // Always clear the timeout: once the race is won (the common case after\n      // the initial sync), the timer would otherwise stay pending for the full\n      // 30s. Timers capture the ambient async context (AsyncLocalStorage),\n      // so in a Next.js server every leaked timer pins the request's store —\n      // and with it the whole response object graph — for at least 30s on\n      // every single cache operation.\n      clearTimeout(readyTimeout);\n    }\n    this.clientReadyCalls = 0;\n    if (!this.client.isReady) {\n      if (this.redisConnectionDeferred) {\n        return;\n      }\n      throw new Error(\n        'assertClientIsReady: Redis client is not ready yet or connection is lost.',\n      );\n    }\n  }\n\n  private isClientUnavailable(): boolean {\n    return this.redisConnectionDeferred || !this.client.isReady;\n  }\n\n  public async get(key: string, ctx: GetContext): Promise<CacheEntry | null> {\n    try {\n      if (!(SUPPORTED_GET_KINDS as readonly string[]).includes(ctx.kind)) {\n        console.warn(\n          'RedisStringsHandler.get() called with',\n          key,\n          ctx,\n          `this cache handler is only designed and tested for kinds ${SUPPORTED_GET_KINDS.join(', ')} and not for kind`,\n          (ctx as { kind: string })?.kind,\n        );\n      }\n\n      debug('green', 'RedisStringsHandler.get() called with', key, ctx);\n      await this.assertClientIsReady();\n      if (this.isClientUnavailable()) {\n        return null;\n      }\n\n      const clientGet = this.redisGetDeduplication\n        ? this.deduplicatedRedisGet(key)\n        : this.redisGet;\n\n      const redisGetOperation = clientGet(\n        this.keyPrefix + key,\n        AbortSignal.timeout(this.getTimeoutMs),\n      ).catch((error) => {\n        if (error instanceof RedisTimeoutError) {\n          return null;\n        }\n        throw error;\n      });\n      const serializedCacheEntry = await redisErrorHandler(\n        'RedisStringsHandler.get(), operation: get' +\n          (this.redisGetDeduplication ? 'deduplicated' : '') +\n          ' ' +\n          this.getTimeoutMs +\n          'ms ' +\n          this.keyPrefix +\n          ' ' +\n          key,\n        redisGetOperation,\n      );\n\n      debug(\n        'green',\n        'RedisStringsHandler.get() finished with result (serializedCacheEntry)',\n        serializedCacheEntry?.substring(0, 200),\n      );\n\n      if (!serializedCacheEntry) {\n        return null;\n      }\n\n      let cacheEntry: CacheEntry | null;\n      try {\n        cacheEntry =\n          await this.valueSerializer.deserialize(serializedCacheEntry);\n      } catch (err) {\n        // A decode failure (e.g. legacy/corrupted entry after swapping codecs,\n        // bumping a compression level or rotating an encryption key) is treated\n        // as a cache miss rather than a hard error - this matches the\n        // null-from-deserialize semantics in the CacheValueSerializer contract\n        // and prevents a single unreadable entry from incrementing\n        // killContainerOnErrorCount on every read.\n        console.warn(\n          'RedisStringsHandler.get() valueSerializer.deserialize failed, treating as cache miss',\n          this.keyPrefix + key,\n          err,\n        );\n        return null;\n      }\n\n      debug(\n        'green',\n        'RedisStringsHandler.get() finished with result (cacheEntry)',\n        JSON.stringify(cacheEntry).substring(0, 200),\n      );\n\n      if (!cacheEntry) {\n        return null;\n      }\n\n      if (!cacheEntry?.tags) {\n        console.warn(\n          'RedisStringsHandler.get() called with',\n          key,\n          ctx,\n          'cacheEntry is mall formed (missing tags)',\n        );\n      }\n      // value === null is a legitimate entry: the Pages Router stores\n      // `notFound: true` results as a cache entry with a null value.\n      // Only an absent value indicates a malformed entry.\n      if (cacheEntry?.value === undefined) {\n        console.warn(\n          'RedisStringsHandler.get() called with',\n          key,\n          ctx,\n          'cacheEntry is mall formed (missing value)',\n        );\n      }\n      if (!cacheEntry?.lastModified) {\n        console.warn(\n          'RedisStringsHandler.get() called with',\n          key,\n          ctx,\n          'cacheEntry is mall formed (missing lastModified)',\n        );\n      }\n\n      const tagsToCheckForRevalidation =\n        ctx.kind === 'FETCH'\n          ? new Set([\n              ...(cacheEntry.tags || []),\n              ...(ctx?.softTags || []),\n              ...(ctx?.tags || []),\n            ])\n          : new Set(cacheEntry.tags || []);\n\n      if (tagsToCheckForRevalidation.size > 0) {\n        // INFO: implicit tags (revalidate of nested fetch in api route/page on revalidatePath call of the page/api route). See revalidateTag() for more information\n        //\n        // This code checks if any of the cache tags associated with this entry\n        // have been revalidated since the entry was last modified. If any tag was revalidated more recently than the entry's\n        // lastModified timestamp, then the cached content is considered stale (therefore return null) and should be removed.\n        for (const tag of tagsToCheckForRevalidation) {\n          // Get the last revalidation time for this tag from our revalidatedTagsMap\n          const revalidationTime = this.revalidatedTagsMap.get(tag);\n\n          // If we have a revalidation time for this tag and it's more recent than when\n          // this cache entry was last modified, the entry is stale\n          if (revalidationTime && revalidationTime > cacheEntry.lastModified) {\n            const redisKey = this.keyPrefix + key;\n\n            // We don't await this cleanup since it can happen asynchronously in the background.\n            // The cache entry is already considered invalid at this point.\n            this.client\n              .unlink(redisKey)\n              .catch((err) => {\n                // Log error but don't retry deletion since the cache entry will likely be\n                // updated immediately after via set(). A retry could dangerously execute\n                // after the new value is set.\n                console.error(\n                  'Error occurred while unlinking stale data. Error was:',\n                  err,\n                );\n              })\n              .finally(async () => {\n                // Only FETCH reads clear the shared revalidation marker. A page/route\n                // entry and one or more nested FETCH entries can all be tagged with\n                // the same implicit tag; if a page/route read deleted the marker\n                // here, a not-yet-read FETCH entry sharing that tag would lose the\n                // only signal it has that it is stale (its own Redis key can still\n                // exist when the direct sharedTagsMap-based delete in\n                // revalidateTag() raced with this entry's set()). Only FETCH reads\n                // are the intended (and only) consumer of this marker, so only they\n                // retire it once observed.\n                if (ctx.kind === 'FETCH') {\n                  await this.revalidatedTagsMap.delete(tag);\n                }\n              });\n\n            debug(\n              'green',\n              'RedisStringsHandler.get() found revalidation time for tag. Cache entry is stale and will be deleted and \"null\" will be returned.',\n              tag,\n              redisKey,\n              revalidationTime,\n              cacheEntry,\n            );\n\n            // Return null to indicate no valid cache entry was found\n            return null;\n          }\n        }\n      }\n\n      // Match Next's FileSystemCache: fallback and postponed PPR entries do not\n      // expose a complete Flight payload via rscData on read.\n      const value = cacheEntry.value as SetCacheValue;\n      if (\n        ctx.kind === 'APP_PAGE' &&\n        value != null &&\n        value.kind === 'APP_PAGE'\n      ) {\n        const postponedState =\n          value.postponed ?? (value as { postboned?: unknown }).postboned;\n        if (\n          ctx.isFallback ||\n          (ctx.isRoutePPREnabled && postponedState != null)\n        ) {\n          return {\n            ...cacheEntry,\n            value: { ...value, rscData: undefined },\n          };\n        }\n      }\n\n      return cacheEntry;\n    } catch (error) {\n      // This catch block is necessary to handle any errors that may occur during:\n      // 1. Redis operations (get, unlink)\n      // 2. Tag validation and cleanup\n      // (Deserialization errors are handled locally above and treated as cache misses,\n      // so they do not reach this branch and do not count toward the kill threshold.)\n      // If any error occurs, we return null to indicate no valid cache entry was found,\n      // allowing the application to regenerate the content rather than crash\n      console.error(\n        'RedisStringsHandler.get() Error occurred while getting cache entry. Returning null so site can continue to serve content while cache is disabled. The original error was:',\n        error,\n        killContainerOnErrorCount++,\n      );\n\n      if (\n        this.killContainerOnErrorThreshold > 0 &&\n        killContainerOnErrorCount >= this.killContainerOnErrorThreshold\n      ) {\n        console.error(\n          'RedisStringsHandler get() error threshold reached, disconnecting and exiting (please implement a restart process/container watchdog to handle this error)',\n          error,\n          killContainerOnErrorCount,\n        );\n        this.client.disconnect();\n        this.client.quit();\n        setTimeout(() => {\n          process.exit(1);\n        }, 500);\n      }\n      return null;\n    }\n  }\n  public async set(\n    key: string,\n    data: SetCacheValue,\n    ctx: {\n      isRoutePPREnabled: boolean;\n      isFallback: boolean;\n      tags?: string[];\n      // Different versions of Next.js use different arguments for the same functionality\n      revalidate?: number | false; // Version 15.0.3\n      cacheControl?: { revalidate: number | false; expire: number | undefined }; // Version 15.0.3+\n    },\n  ) {\n    try {\n      if (\n        data !== null &&\n        !(SUPPORTED_SET_KINDS as readonly string[]).includes(data.kind)\n      ) {\n        console.warn(\n          'RedisStringsHandler.set() called with',\n          key,\n          ctx,\n          data,\n          `this cache handler is only designed and tested for kinds ${SUPPORTED_SET_KINDS.join(', ')} and not for kind`,\n          (data as { kind: string })?.kind,\n        );\n      }\n\n      await this.assertClientIsReady();\n      if (this.isClientUnavailable()) {\n        return;\n      }\n\n      if (data?.kind === 'APP_PAGE' || data?.kind === 'APP_ROUTE') {\n        const tags = data.headers['x-next-cache-tags']?.split(',');\n        ctx.tags = [...(ctx.tags || []), ...(tags || [])];\n      }\n\n      // Pages Router entries (PAGES, REDIRECT and null/notFound results) do not\n      // carry an x-next-cache-tags header. Attach the implicit path tag\n      // (_N_T_/<path>) so that revalidatePath()/revalidateTag('_N_T_/<path>')\n      // invalidates them the same way as App Router entries.\n      if (data === null || data.kind === 'PAGES' || data.kind === 'REDIRECT') {\n        const implicitTag = NEXT_CACHE_IMPLICIT_TAG_ID + key;\n        if (!ctx.tags?.includes(implicitTag)) {\n          ctx.tags = [...(ctx.tags || []), implicitTag];\n        }\n      }\n\n      // Constructing and serializing the value for storing it in redis\n      const cacheEntry: CacheEntry = {\n        lastModified: Date.now(),\n        tags: ctx?.tags || [],\n        value: data,\n      };\n      const serializedCacheEntry =\n        await this.valueSerializer.serialize(cacheEntry);\n\n      // pre seed data into deduplicated get client. This will reduce redis load by not requesting\n      // the same value from redis which was just set.\n      if (this.redisGetDeduplication) {\n        this.redisDeduplicationHandler.seedRequestReturn(\n          key,\n          serializedCacheEntry,\n        );\n      }\n\n      const expireAt = resolveCacheEntryTtlSeconds(ctx, data, {\n        estimateExpireAge: this.estimateExpireAge,\n        defaultStaleAge: this.defaultStaleAge,\n      });\n\n      // Setting the cache entry in redis\n      const setOperation: Promise<string | null> = redisErrorHandler(\n        'RedisStringsHandler.set(), operation: set ' +\n          this.keyPrefix +\n          ' ' +\n          key,\n        this.client.set(this.keyPrefix + key, serializedCacheEntry, {\n          ...(expireAt ? { EX: expireAt } : {}),\n        }),\n      );\n\n      debug(\n        'blue',\n        'RedisStringsHandler.set() will set the following serializedCacheEntry',\n        this.keyPrefix,\n        key,\n        data,\n        ctx,\n        serializedCacheEntry?.substring(0, 200),\n        expireAt,\n      );\n\n      // Setting the tags for the cache entry in the sharedTagsMap (locally stored hashmap synced via redis)\n      // An untagged write intentionally leaves an existing association in\n      // place. The local map can lag behind another instance's tagged write,\n      // so deleting here could remove that instance's fresh association and\n      // make its value impossible to invalidate. A stale association only\n      // costs one extra cache miss on a later revalidateTag().\n      //\n      // A tagged write always stores its association, even when the local map\n      // already shows the same tags. That map can lag behind another instance\n      // that stored different tags for this key. Skipping the write would leave\n      // the shared hash pointing at those other tags, and revalidateTag() would\n      // never find this value. A later full sync reads the same hash, so it\n      // cannot repair the miss.\n      let setTagsOperation: Promise<void> | undefined;\n      if (ctx.tags && ctx.tags.length > 0) {\n        setTagsOperation = this.sharedTagsMap.set(\n          key,\n          structuredClone(ctx.tags) as string[],\n        );\n      }\n\n      debug(\n        'blue',\n        'RedisStringsHandler.set() will set the following sharedTagsMap',\n        key,\n        ctx.tags as string[],\n      );\n\n      await untilDeadline(\n        Promise.all([setOperation, setTagsOperation]),\n        AbortSignal.timeout(this.writeTimeoutMs),\n      );\n    } catch (error) {\n      if (error instanceof RedisTimeoutError) {\n        console.warn(\n          'RedisStringsHandler.set() Redis did not confirm the write within',\n          this.writeTimeoutMs,\n          'ms. Returning without it, the entry may not be stored:',\n          this.keyPrefix + key,\n        );\n        return;\n      }\n      console.error(\n        'RedisStringsHandler.set() Error occurred while setting cache entry. The original error was:',\n        error,\n        killContainerOnErrorCount++,\n      );\n      if (\n        this.killContainerOnErrorThreshold > 0 &&\n        killContainerOnErrorCount >= this.killContainerOnErrorThreshold\n      ) {\n        console.error(\n          'RedisStringsHandler set() error threshold reached, disconnecting and exiting (please implement a restart process/container watchdog to handle this error)',\n          error,\n          killContainerOnErrorCount,\n        );\n        this.client.disconnect();\n        this.client.quit();\n        setTimeout(() => {\n          process.exit(1);\n        }, 500);\n      }\n      throw error;\n    }\n  }\n\n  private async deleteLocalReadCacheKeys(keys: string[]): Promise<void> {\n    const errors: unknown[] = [];\n    for (let i = 0; i < keys.length; i += LOCAL_CACHE_DELETE_BATCH_SIZE) {\n      try {\n        await this.inMemoryDeduplicationCache.delete(\n          keys.slice(i, i + LOCAL_CACHE_DELETE_BATCH_SIZE),\n        );\n      } catch (error) {\n        errors.push(error);\n      }\n    }\n    if (errors.length === 1) {\n      throw errors[0];\n    }\n    if (errors.length > 1) {\n      throw new Error(\n        `Failed to clear ${errors.length} local read-cache batches`,\n      );\n    }\n  }\n\n  // eslint-disable-next-line @typescript-eslint/no-explicit-any\n  public async revalidateTag(tagOrTags: string | string[], ...rest: any[]) {\n    try {\n      debug(\n        'red',\n        'RedisStringsHandler.revalidateTag() called with',\n        tagOrTags,\n        rest,\n      );\n      const tags = new Set([tagOrTags || []].flat());\n      await this.assertClientIsReady();\n      if (this.isClientUnavailable()) {\n        return;\n      }\n\n      // Start every write before waiting, so that one deadline bounds them\n      // all and a timeout does not skip the writes after it.\n      const writes: Promise<unknown>[] = [];\n\n      // find all keys that are related to this tag\n      const keysToDelete: Set<string> = new Set();\n\n      for (const tag of tags) {\n        // INFO: implicit tags (revalidate of nested fetch in api route/page on revalidatePath call of the page/api route)\n        //\n        // Invalidation logic for fetch requests that are related to a invalidated page.\n        // revalidateTag is called for the page tag (_N_T_...) and the fetch request needs to be invalidated as well\n        // unfortunately this is not possible since the revalidateTag is not called with any data that would allow us to find the cache entry of the fetch request\n        // in case of a fetch request get method call, the get method of the cache handler is called with some information about the pages/routes the fetch request is inside\n        // therefore we only mark the page/route as stale here (with help of the revalidatedTagsMap)\n        // and delete the cache entry of the fetch request on the next request to the get function\n        if (tag.startsWith(NEXT_CACHE_IMPLICIT_TAG_ID)) {\n          const now = Date.now();\n          debug(\n            'red',\n            'RedisStringsHandler.revalidateTag() set revalidation time for tag',\n            tag,\n            'to',\n            now,\n          );\n          writes.push(this.revalidatedTagsMap.set(tag, now));\n        }\n      }\n\n      // Scan the whole sharedTagsMap for keys that are dependent on any of the revalidated tags\n      for (const [key, sharedTags] of this.sharedTagsMap.entries()) {\n        if (sharedTags.some((tag) => tags.has(tag))) {\n          keysToDelete.add(key);\n        }\n      }\n\n      debug(\n        'red',\n        'RedisStringsHandler.revalidateTag() found',\n        keysToDelete,\n        'keys to delete',\n      );\n\n      if (keysToDelete.size > 0) {\n        // prepare deletion of all keys in redis that are related to this tag.\n        // Always slot-grouped, including standalone Redis. Cluster mode rejects\n        // one UNLINK whose keys span hash slots (CROSSSLOT). See\n        // clusterSafeUnlink for the protocol formula and the single-node cost:\n        // one command per occupied slot, bounded by\n        // revalidateTagDeleteConcurrency.\n        const redisKeys = Array.from(keysToDelete);\n        const fullRedisKeys = redisKeys.map((key) => this.keyPrefix + key);\n        const redisKeyByFullRedisKey = new Map(\n          fullRedisKeys.map((fullRedisKey, index) => [\n            fullRedisKey,\n            redisKeys[index]!,\n          ]),\n        );\n        const clearLocalReadCache =\n          this.redisGetDeduplication && this.inMemoryCachingTime > 0;\n\n        // Clear local read-through cache before deleting Redis values. With\n        // slot-grouped deletes, some Redis keys can be gone while other slots are\n        // still pending; clearing first prevents stale local reads in that window.\n        // This is a best-effort race-avoidance step: a failure here (e.g. the\n        // local cache's pub/sub notification could not be published) must not\n        // prevent the Redis UNLINKs below from running, since skipping the\n        // actual invalidation would be far worse than a brief stale-read window\n        // that resolves itself once the in-memory cache entry expires.\n        // The clearing publishes through Redis too, so it is part of the same\n        // write and the write deadline below bounds it.\n        const clearBeforeDelete = clearLocalReadCache\n          ? this.deleteLocalReadCacheKeys(redisKeys).catch((err) => {\n              console.error(\n                'RedisStringsHandler.revalidateTag() failed to clear local read-through cache before deletion. Continuing with Redis deletion regardless. Error was:',\n                err,\n              );\n            })\n          : Promise.resolve();\n\n        writes.push(\n          clearBeforeDelete.then(() =>\n            redisErrorHandler(\n              'RedisStringsHandler.revalidateTag(), operation: cluster-safe unlink ' +\n                this.keyPrefix +\n                ' ' +\n                fullRedisKeys.length +\n                ' key(s)',\n              clusterSafeUnlink(this.client, fullRedisKeys, {\n                concurrency: this.revalidateTagDeleteConcurrency,\n                onGroupSuccess: async (deletedFullRedisKeys) => {\n                  if (clearLocalReadCache) {\n                    await this.deleteLocalReadCacheKeys(\n                      deletedFullRedisKeys.flatMap((fullRedisKey) => {\n                        const redisKey =\n                          redisKeyByFullRedisKey.get(fullRedisKey);\n                        return redisKey ? [redisKey] : [];\n                      }),\n                    );\n                  }\n                },\n              }),\n            ),\n          ),\n        );\n\n        // Do not delete sharedTagsMap entries here. A fresh set() can write a\n        // replacement value and tag association immediately after UNLINK; an\n        // unconditional HDEL would remove that fresh association. Stale tag\n        // metadata is harmless for correctness and is removed by SyncedMap's\n        // periodic orphan cleanup, which compares the tag hash against live\n        // Redis keys.\n      }\n\n      await untilDeadline(\n        Promise.all(writes),\n        AbortSignal.timeout(this.writeTimeoutMs),\n      );\n      debug(\n        'red',\n        'RedisStringsHandler.revalidateTag() finished delete operations',\n      );\n    } catch (error) {\n      // Unlike set(), a lost invalidation leaves stale entries on every\n      // instance, so the caller must see it fail.\n      if (error instanceof RedisTimeoutError) {\n        console.error(\n          'RedisStringsHandler.revalidateTag() Redis did not confirm the writes within',\n          this.writeTimeoutMs,\n          'ms. Other instances may serve stale entries for tags:',\n          tagOrTags,\n        );\n        throw error;\n      }\n      console.error(\n        'RedisStringsHandler.revalidateTag() Error occurred while revalidating tags. The original error was:',\n        error,\n        killContainerOnErrorCount++,\n      );\n      if (\n        this.killContainerOnErrorThreshold > 0 &&\n        killContainerOnErrorCount >= this.killContainerOnErrorThreshold\n      ) {\n        console.error(\n          'RedisStringsHandler revalidateTag() error threshold reached, disconnecting and exiting (please implement a restart process/container watchdog to handle this error)',\n          error,\n          killContainerOnErrorCount,\n        );\n        this.client.disconnect();\n        this.client.quit();\n        setTimeout(() => {\n          process.exit(1);\n        }, 500);\n      }\n      throw error;\n    }\n  }\n}\n","export function debug(\n  color:\n    | 'red'\n    | 'blue'\n    | 'green'\n    | 'yellow'\n    | 'cyan'\n    | 'white'\n    | 'none' = 'none',\n  ...args: unknown[]\n): void {\n  const colorCode = {\n    red: '\\x1b[31m',\n    blue: '\\x1b[34m',\n    green: '\\x1b[32m',\n    yellow: '\\x1b[33m',\n    cyan: '\\x1b[36m',\n    white: '\\x1b[37m',\n    none: '',\n  };\n  if (process.env.DEBUG_CACHE_HANDLER) {\n    console.log(colorCode[color], 'DEBUG CACHE HANDLER: ', ...args);\n  }\n}\n\nexport function debugVerbose(color: string, ...args: unknown[]) {\n  if (process.env.DEBUG_CACHE_HANDLER_VERBOSE_VERBOSE) {\n    console.log('\\x1b[35m', 'DEBUG SYNCED MAP: ', ...args);\n  }\n}\n","/**\n * Matches `PHASE_PRODUCTION_BUILD` from `next/constants`.\n *\n * Hardcoded so ESM builds (tsup `shims: false`) never call `require()`.\n * A dynamic `require('next/constants')` throws in ESM, and catching that used\n * to cache `undefined` for the process lifetime — disabling the build-phase\n * Redis skip entirely.\n */\nexport const PHASE_PRODUCTION_BUILD = 'phase-production-build';\n\n/**\n * Returns true during `next build` so handlers can skip opening Redis\n * connections. Matches the official Next.js cache-handler-redis example.\n */\nexport function shouldDeferRedisConnection(): boolean {\n  return process.env.NEXT_PHASE === PHASE_PRODUCTION_BUILD;\n}\n","// SyncedMap.ts\nimport { Client, redisErrorHandler } from './RedisStringsHandler';\nimport { debugVerbose, debug } from './utils/debug';\nimport { shouldDeferRedisConnection } from './utils/redisConnection';\n\ntype CustomizedSync = {\n  withoutRedisHashmap?: boolean;\n  withoutSetSync?: boolean;\n  /**\n   * Skip SCAN-based orphan cleanup. Required for maps whose keys are not Redis\n   * string keys (tag manifests). Otherwise startup/resync HDELs every tag.\n   */\n  withoutOrphanCleanup?: boolean;\n};\n\ntype SyncedMapOptions = {\n  client: Client;\n  keyPrefix: string;\n  redisKey: string; // Redis Hash key\n  database: number;\n  querySize: number;\n  filterKeys: (key: string) => boolean;\n  resyncIntervalMs?: number;\n  customizedSync?: CustomizedSync;\n};\n\nexport type SyncMessage<V> = {\n  type: 'insert' | 'delete';\n  key?: string;\n  value?: V;\n  keys?: string[];\n};\n\nconst SYNC_CHANNEL_SUFFIX = ':sync-channel:';\nexport class SyncedMap<V> {\n  private client: Client;\n  private subscriberClient: Client;\n  private map: Map<string, V>;\n  private keyPrefix: string;\n  private syncChannel: string;\n  private redisKey: string;\n  private database: number;\n  private querySize: number;\n  private filterKeys: (key: string) => boolean;\n  private resyncIntervalMs?: number;\n  private customizedSync?: CustomizedSync;\n\n  private setupLock: Promise<void>;\n  private setupLockResolve!: () => void;\n  private isReconnecting = false;\n\n  constructor(options: SyncedMapOptions) {\n    this.client = options.client;\n    this.keyPrefix = options.keyPrefix;\n    this.redisKey = options.redisKey;\n    this.syncChannel = `${options.keyPrefix}${SYNC_CHANNEL_SUFFIX}${options.redisKey}`;\n    this.database = options.database;\n    this.querySize = options.querySize;\n    this.filterKeys = options.filterKeys;\n    this.resyncIntervalMs = options.resyncIntervalMs;\n    this.customizedSync = options.customizedSync;\n\n    this.map = new Map<string, V>();\n    this.subscriberClient = this.client.duplicate();\n    this.setupLock = new Promise<void>((resolve) => {\n      this.setupLockResolve = resolve;\n    });\n\n    this.setup().catch((error) => {\n      console.error('Failed to setup SyncedMap:', error);\n      throw error;\n    });\n  }\n\n  private async setup() {\n    if (shouldDeferRedisConnection()) {\n      this.setupLockResolve();\n      return;\n    }\n\n    let setupPromises: Promise<void>[] = [];\n    if (!this.customizedSync?.withoutRedisHashmap) {\n      setupPromises.push(this.initialSync());\n      this.setupPeriodicResync();\n    }\n    setupPromises.push(this.setupPubSub());\n    await Promise.all(setupPromises);\n    this.setupLockResolve();\n  }\n\n  private async initialSync() {\n    // Redis cursors are opaque uint64 strings. redis@4's hScan() coerces them\n    // through Number(), which loses precision above 2^53-1 and can loop forever\n    // on large keyspaces (see issue #97). Bypass with sendCommand until redis ^5,\n    // where SCAN/HSCAN keep cursor as a string.\n    let cursor = '0';\n\n    try {\n      do {\n        const [nextCursor, tuples] = (await redisErrorHandler(\n          'SyncedMap.initialSync(), operation: HSCAN ' +\n            this.keyPrefix +\n            this.redisKey,\n          this.client.sendCommand([\n            'HSCAN',\n            this.keyPrefix + this.redisKey,\n            cursor,\n            'COUNT',\n            String(this.querySize),\n          ]),\n        )) as [string, string[]];\n        for (let i = 0; i < tuples.length; i += 2) {\n          const field = tuples[i];\n          if (this.filterKeys(field)) {\n            this.map.set(field, JSON.parse(tuples[i + 1]));\n          }\n        }\n        cursor = nextCursor;\n      } while (cursor !== '0');\n\n      // sharedTagsMap keys are cache keys (Redis strings). Tag-manifest maps\n      // use tag names as hash fields — those never appear in SCAN.\n      if (!this.customizedSync?.withoutOrphanCleanup) {\n        await this.cleanupKeysNotInRedis();\n      }\n    } catch (error) {\n      console.error('Error during initial sync:', error);\n      throw error;\n    }\n  }\n\n  private async cleanupKeysNotInRedis() {\n    // Same uint64 cursor issue as initialSync(); sendCommand until redis ^5.\n    let cursor = '0';\n    let remoteKeys: string[] = [];\n    try {\n      do {\n        const [nextCursor, keys] = (await redisErrorHandler(\n          'SyncedMap.cleanupKeysNotInRedis(), operation: SCAN ' +\n            this.keyPrefix,\n          this.client.sendCommand([\n            'SCAN',\n            cursor,\n            'MATCH',\n            `${this.keyPrefix}*`,\n            'COUNT',\n            String(this.querySize),\n          ]),\n        )) as [string, string[]];\n        remoteKeys = remoteKeys.concat(keys);\n        cursor = nextCursor;\n      } while (cursor !== '0');\n\n      const remoteKeysSet = new Set(\n        remoteKeys.map((key) => key.substring(this.keyPrefix.length)),\n      );\n\n      const keysToDelete: string[] = [];\n      for (const key of this.map.keys()) {\n        const keyStr = key as unknown as string;\n        if (!remoteKeysSet.has(keyStr) && this.filterKeys(keyStr)) {\n          keysToDelete.push(keyStr);\n        }\n      }\n\n      if (keysToDelete.length > 0) {\n        await this.delete(keysToDelete);\n      }\n    } catch (error) {\n      console.error('Error during cleanup of keys not in Redis:', error);\n      throw error;\n    }\n  }\n\n  private setupPeriodicResync() {\n    if (this.resyncIntervalMs && this.resyncIntervalMs > 0) {\n      setInterval(() => {\n        this.initialSync().catch((error) => {\n          console.error('Error during periodic resync:', error);\n        });\n      }, this.resyncIntervalMs);\n    }\n  }\n\n  private async setupPubSub() {\n    const syncHandler = async (message: string) => {\n      const syncMessage: SyncMessage<V> = JSON.parse(message);\n      if (syncMessage.type === 'insert') {\n        if (syncMessage.key !== undefined && syncMessage.value !== undefined) {\n          this.map.set(syncMessage.key, syncMessage.value);\n        }\n      } else if (syncMessage.type === 'delete') {\n        if (syncMessage.keys) {\n          for (const key of syncMessage.keys) {\n            this.map.delete(key);\n          }\n        }\n      }\n    };\n\n    const keyEventHandler = async (key: string, message: string) => {\n      debug(\n        'yellow',\n        'SyncedMap.keyEventHandler() called with message',\n        this.redisKey,\n        message,\n        key,\n      );\n      // const key = message;\n      if (key.startsWith(this.keyPrefix)) {\n        const keyInMap = key.substring(this.keyPrefix.length);\n        if (this.filterKeys(keyInMap)) {\n          debugVerbose(\n            'SyncedMap.keyEventHandler() key matches filter and will be deleted',\n            this.redisKey,\n            message,\n            key,\n          );\n          await this.delete(keyInMap, true);\n        }\n      } else {\n        debugVerbose(\n          'SyncedMap.keyEventHandler() key does not have prefix',\n          this.redisKey,\n          message,\n          key,\n        );\n      }\n    };\n\n    try {\n      // Attach error handler BEFORE subscribing so that errors during\n      // subscribe or after connection loss are always caught and trigger\n      // a reconnection. Previously this was attached after the subscribe()\n      // calls, which meant if subscribe threw during an outage the handler\n      // was never attached and the subscriber was permanently dead.\n      this.subscriberClient.on('error', async (err) => {\n        console.error('Subscriber client error:', err);\n        await this.reconnectSubscriber();\n      });\n\n      const connectIfNeeded = async () => {\n        // Avoid overlapping connect() calls which can lead to\n        // \"Socket already opened\" errors when a connect is already in progress\n        // or the socket is still open.\n        if (!this.subscriberClient.isOpen && !this.subscriberClient.isReady) {\n          await this.subscriberClient.connect();\n        }\n      };\n\n      await connectIfNeeded().catch(async (error) => {\n        console.error('Failed to connect subscriber client. Retrying...');\n        try {\n          await connectIfNeeded();\n        } catch (err) {\n          console.error('Failed to connect subscriber client.', err);\n          throw err;\n        }\n        // keep original error in logs for context\n        void error;\n      });\n\n      // Check if keyspace event configuration is set correctly\n      if (\n        (process.env.SKIP_KEYSPACE_CONFIG_CHECK || '').toUpperCase() !== 'TRUE'\n      ) {\n        const keyspaceEventConfig = (\n          await this.subscriberClient.configGet('notify-keyspace-events')\n        )?.['notify-keyspace-events'];\n        if (!keyspaceEventConfig.includes('E')) {\n          throw new Error(\n            'Keyspace event configuration is set to \"' +\n              keyspaceEventConfig +\n              \" but has to include 'E' for Keyevent events, \" +\n              'published with __keyevent@<db>__ prefix. We recommend to set it to ' +\n              \"'Exe' like so `redis-cli -h localhost config set notify-keyspace-events Exe`\",\n          );\n        }\n        if (\n          !keyspaceEventConfig.includes('A') &&\n          !(\n            keyspaceEventConfig.includes('x') &&\n            keyspaceEventConfig.includes('e')\n          )\n        ) {\n          throw new Error(\n            'Keyspace event configuration is set to \"' +\n              keyspaceEventConfig +\n              \" but has to include 'A' or 'x' and 'e' for expired and \" +\n              'evicted events. We recommend to set it to ' +\n              \"'Exe' like so `redis-cli -h localhost config set notify-keyspace-events Exe`\",\n          );\n        }\n      }\n\n      await Promise.all([\n        // We use a custom channel for insert/delete For the following reason:\n        // With custom channel we can delete multiple entries in one message. If we would listen to unlink / del we\n        // could get thousands of messages for one revalidateTag (For example revalidateTag(\"algolia\") would send an enormous amount of network packages)\n        // Also we can send the value in the message for insert\n        this.subscriberClient.subscribe(this.syncChannel, syncHandler),\n        // Subscribe to Redis keyevent notifications for evicted and expired keys\n        this.subscriberClient.subscribe(\n          `__keyevent@${this.database}__:evicted`,\n          keyEventHandler,\n        ),\n        this.subscriberClient.subscribe(\n          `__keyevent@${this.database}__:expired`,\n          keyEventHandler,\n        ),\n      ]);\n    } catch (error) {\n      console.error('Error setting up pub/sub client:', error);\n      throw error;\n    }\n  }\n\n  /**\n   * Reconnect the subscriber client with exponential backoff.\n   * Guarded by `isReconnecting` to prevent concurrent reconnection\n   * attempts when multiple error events fire during an outage.\n   * Retries indefinitely (with capped delay) so the subscriber\n   * eventually recovers once Redis is available again.\n   */\n  private async reconnectSubscriber(): Promise<void> {\n    if (this.isReconnecting) return;\n    this.isReconnecting = true;\n\n    try {\n      let attempt = 0;\n      while (true) {\n        try {\n          // Forcibly tear down the old subscriber so its internal reconnect\n          // loop cannot come back to life once Redis recovers. `quit()` waits\n          // for the server and can silently fail during an outage, leaving a\n          // zombie client that still fires our error handler. Remove that\n          // handler first so a delayed error from the old socket cannot tear\n          // down the replacement subscriber we are about to create.\n          try {\n            this.subscriberClient.removeAllListeners('error');\n            await this.subscriberClient.disconnect();\n          } catch {\n            // expected during outage\n          }\n          // Create a fresh subscriber client\n          this.subscriberClient = this.client.duplicate();\n          await this.setupPubSub();\n          return; // success\n        } catch (error) {\n          const delay = Math.min(\n            500 * Math.pow(2, Math.min(attempt, 5)),\n            10_000,\n          );\n          attempt++;\n          console.error(\n            `Subscriber reconnect attempt ${attempt} failed, retrying in ${delay}ms`,\n            error,\n          );\n          await new Promise((r) => setTimeout(r, delay));\n        }\n      }\n    } finally {\n      this.isReconnecting = false;\n    }\n  }\n\n  public async waitUntilReady() {\n    await this.setupLock;\n  }\n\n  public get(key: string): V | undefined {\n    debugVerbose(\n      'SyncedMap.get() called with key',\n      key,\n      JSON.stringify(this.map.get(key))?.substring(0, 100),\n    );\n    return this.map.get(key);\n  }\n\n  public async set(key: string, value: V): Promise<void> {\n    debugVerbose(\n      'SyncedMap.set() called with key',\n      key,\n      JSON.stringify(value)?.substring(0, 100),\n    );\n    this.map.set(key, value);\n    const operations = [];\n\n    // This is needed if we only want to sync delete commands. This is especially useful for non serializable data like a promise map\n    if (this.customizedSync?.withoutSetSync) {\n      return;\n    }\n    if (!this.customizedSync?.withoutRedisHashmap) {\n      operations.push(\n        redisErrorHandler(\n          'SyncedMap.set(), operation: hSet ' +\n            this.syncChannel +\n            ' ' +\n            this.keyPrefix +\n            ' ' +\n            key,\n          this.client.hSet(\n            this.keyPrefix + this.redisKey,\n            key as unknown as string,\n            JSON.stringify(value),\n          ),\n        ),\n      );\n    }\n\n    const insertMessage: SyncMessage<V> = {\n      type: 'insert',\n      key: key as unknown as string,\n      value,\n    };\n    operations.push(\n      redisErrorHandler(\n        'SyncedMap.set(), operation: publish ' +\n          this.syncChannel +\n          ' ' +\n          this.keyPrefix +\n          ' ' +\n          key,\n        this.client.publish(this.syncChannel, JSON.stringify(insertMessage)),\n      ),\n    );\n    await Promise.all(operations);\n  }\n\n  public async delete(\n    keys: string[] | string,\n    withoutSyncMessage = false,\n  ): Promise<void> {\n    debugVerbose(\n      'SyncedMap.delete() called with keys',\n      this.redisKey,\n      keys,\n      withoutSyncMessage,\n    );\n\n    const keysArray = Array.isArray(keys) ? keys : [keys];\n    const operations = [];\n\n    for (const key of keysArray) {\n      this.map.delete(key);\n    }\n\n    if (!this.customizedSync?.withoutRedisHashmap) {\n      operations.push(\n        redisErrorHandler(\n          'SyncedMap.delete(), operation: hDel ' +\n            this.syncChannel +\n            ' ' +\n            this.keyPrefix +\n            ' ' +\n            this.redisKey +\n            ' ' +\n            keysArray,\n          this.client.hDel(this.keyPrefix + this.redisKey, keysArray),\n        ),\n      );\n    }\n\n    if (!withoutSyncMessage) {\n      const deletionMessage: SyncMessage<V> = {\n        type: 'delete',\n        keys: keysArray,\n      };\n      operations.push(\n        redisErrorHandler(\n          'SyncedMap.delete(), operation: publish ' +\n            this.syncChannel +\n            ' ' +\n            this.keyPrefix +\n            ' ' +\n            keysArray,\n          this.client.publish(\n            this.syncChannel,\n            JSON.stringify(deletionMessage),\n          ),\n        ),\n      );\n    }\n\n    await Promise.all(operations);\n    debugVerbose(\n      'SyncedMap.delete() finished operations',\n      this.redisKey,\n      keys,\n      operations.length,\n    );\n  }\n\n  public has(key: string): boolean {\n    return this.map.has(key);\n  }\n\n  public entries(): IterableIterator<[string, V]> {\n    return this.map.entries();\n  }\n}\n","import { debugVerbose } from './utils/debug';\nimport { SyncedMap } from './SyncedMap';\nexport class DeduplicatedRequestHandler<\n  T extends (...args: [never, never]) => Promise<K>,\n  K,\n> {\n  private inMemoryDeduplicationCache: SyncedMap<Promise<K>>;\n  private cachingTimeMs: number;\n  private fn: T;\n\n  constructor(\n    fn: T,\n    cachingTimeMs: number,\n    inMemoryDeduplicationCache: SyncedMap<Promise<K>>,\n  ) {\n    this.fn = fn;\n    this.cachingTimeMs = cachingTimeMs;\n    this.inMemoryDeduplicationCache = inMemoryDeduplicationCache;\n  }\n\n  // Method to manually seed a result into the cache\n  seedRequestReturn(key: string, value: K): void {\n    const resultPromise = new Promise<K>((res) => res(value));\n    this.inMemoryDeduplicationCache.set(key, resultPromise);\n\n    debugVerbose(\n      'DeduplicatedRequestHandler.seedRequestReturn() seeded result ',\n      key,\n      (value as string).substring(0, 200),\n    );\n\n    setTimeout(() => {\n      this.inMemoryDeduplicationCache.delete(key);\n    }, this.cachingTimeMs);\n  }\n\n  // Method to handle deduplicated requests\n  deduplicatedFunction = (key: string): T => {\n    debugVerbose(\n      'DeduplicatedRequestHandler.deduplicatedFunction() called with',\n      key,\n    );\n    //eslint-disable-next-line @typescript-eslint/no-this-alias\n    const self = this;\n    const dedupedFn = async (...args: [never, never]): Promise<K> => {\n      // If there's already a pending request with the same key, return it\n      debugVerbose(\n        'DeduplicatedRequestHandler.deduplicatedFunction().dedupedFn called with',\n        key,\n      );\n      if (\n        self.inMemoryDeduplicationCache &&\n        self.inMemoryDeduplicationCache.has(key)\n      ) {\n        debugVerbose(\n          'DeduplicatedRequestHandler.deduplicatedFunction().dedupedFn ',\n          key,\n          'found key in inMemoryDeduplicationCache',\n        );\n        const res = await self.inMemoryDeduplicationCache\n          .get(key)!\n          .then((v) => structuredClone(v));\n        debugVerbose(\n          'DeduplicatedRequestHandler.deduplicatedFunction().dedupedFn ',\n          key,\n          'found key in inMemoryDeduplicationCache and served result from there',\n          JSON.stringify(res).substring(0, 200),\n        );\n        return res;\n      }\n\n      // If no pending request, call the original function and store the promise\n      const promise = self.fn(...args);\n      self.inMemoryDeduplicationCache.set(key, promise);\n\n      debugVerbose(\n        'DeduplicatedRequestHandler.deduplicatedFunction().dedupedFn ',\n        key,\n        'did not found key in inMemoryDeduplicationCache. Setting it now and waiting for promise to resolve',\n      );\n\n      try {\n        const ts = performance.now();\n        const result = await promise;\n        debugVerbose(\n          'DeduplicatedRequestHandler.deduplicatedFunction().dedupedFn ',\n          key,\n          'promise resolved (in ',\n          performance.now() - ts,\n          'ms). Returning result',\n          JSON.stringify(result).substring(0, 200),\n        );\n        return structuredClone(result);\n      } finally {\n        // Once the promise is resolved/rejected and caching timeout is over, remove it from the map\n        setTimeout(() => {\n          debugVerbose(\n            'DeduplicatedRequestHandler.deduplicatedFunction().dedupedFn ',\n            key,\n            'deleting key from inMemoryDeduplicationCache after ',\n            self.cachingTimeMs,\n            'ms',\n          );\n          self.inMemoryDeduplicationCache.delete(key);\n        }, self.cachingTimeMs);\n      }\n    };\n    return dedupedFn as T;\n  };\n}\n","// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport function bufferAndMapReviver(_: string, value: any): any {\n  if (value && typeof value === 'object' && typeof value.$binary === 'string') {\n    return Buffer.from(value.$binary, 'base64');\n  }\n  if (\n    value &&\n    typeof value === 'object' &&\n    typeof value.$map === 'object' &&\n    !!value.$map\n  ) {\n    return new Map(\n      Object.entries(value.$map).map(([key, value]) => {\n        const revivedValue = bufferAndMapReviver('', value);\n        return [key, revivedValue];\n      }),\n    );\n  }\n  return value;\n}\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport function bufferAndMapReplacer(_: string, value: any): any {\n  if (Buffer.isBuffer(value)) {\n    return {\n      $binary: value.toString('base64'),\n    };\n  }\n  if (\n    value &&\n    typeof value === 'object' &&\n    value?.type === 'Buffer' &&\n    Array.isArray(value.data)\n  ) {\n    return {\n      $binary: Buffer.from(value.data).toString('base64'),\n    };\n  }\n  if (value && typeof value === 'object' && value instanceof Map) {\n    return {\n      $map: Object.fromEntries(\n        Array.from(value.entries()).map(([key, value]) => {\n          const replacedValue = bufferAndMapReplacer('', value);\n          return [key, replacedValue];\n        }),\n      ),\n    };\n  }\n  return value;\n}\n","/**\n * Pluggable wire-format codec for Redis string values used by `RedisStringsHandler`.\n *\n * The serializer is the single point at which an in-memory `CacheEntry` becomes the\n * string written to Redis (and back). Plugging in a custom serializer lets you add\n * compression (gzip/brotli), encryption, or any other custom encoding without forking\n * this package or losing the existing dedup / batch / keyspace features.\n *\n * Both `serialize` and `deserialize` may return either a value directly or a `Promise`,\n * which enables non-blocking async codecs such as stream-based compression\n * (`zlib.brotliCompress`) or encryption (`crypto.subtle`). Synchronous implementations\n * continue to work unchanged - awaiting a plain value is a no-op.\n *\n * The default export {@link jsonCacheValueSerializer} is `JSON.stringify` /\n * `JSON.parse` paired with {@link bufferAndMapReplacer} / {@link bufferAndMapReviver},\n * so native `Buffer` and `Map` values inside a `CacheEntry` round-trip transparently\n * (this is required for Next.js RSC payloads).\n *\n * Operational note: changing the serializer (or any of its parameters such as a\n * compression level or encryption key) makes existing Redis keys unreadable, because\n * the deserializer will fail or return `null` for entries written by the previous\n * format. Either flush the affected keys, bump `keyPrefix`, or migrate values\n * out-of-band before deploying a new serializer.\n */\nimport type { CacheEntry } from './RedisStringsHandler';\nimport { bufferAndMapReplacer, bufferAndMapReviver } from './utils/json';\n\nexport type CacheValueSerializer = {\n  /**\n   * Encode an in-memory `CacheEntry` into the string written to Redis.\n   * May return a `Promise` for async codecs (e.g. compression, encryption).\n   */\n  serialize(value: CacheEntry): string | Promise<string>;\n  /**\n   * Decode a string read from Redis back into a `CacheEntry`.\n   * Returning `null` (or a `Promise<null>`) signals \"treat as cache miss\" -\n   * the handler will return `null` from `get()` without surfacing an error.\n   * May return a `Promise` for async codecs.\n   */\n  deserialize(stored: string): CacheEntry | null | Promise<CacheEntry | null>;\n};\n\n/**\n * Default serializer used by `RedisStringsHandler` when no `valueSerializer` is\n * configured. Wraps `JSON.stringify` / `JSON.parse` with this package's\n * {@link bufferAndMapReplacer} / {@link bufferAndMapReviver} so native `Buffer`\n * and `Map` values inside a `CacheEntry` survive the round-trip.\n *\n * Exported as a singleton so consumers can compare against the default by\n * reference (e.g. to detect that no custom serializer was configured).\n */\nexport const jsonCacheValueSerializer: CacheValueSerializer = {\n  serialize(value) {\n    return JSON.stringify(value, bufferAndMapReplacer);\n  },\n  deserialize(stored) {\n    return JSON.parse(stored, bufferAndMapReviver) as CacheEntry | null;\n  },\n};\n","export type ResolveCacheEntryTtlContext = {\n  revalidate?: number | false;\n  cacheControl?: { revalidate?: number | false; expire?: number | undefined };\n};\n\nexport type ResolveCacheEntryTtlData = {\n  kind?: string;\n  revalidate?: number | false;\n} | null;\n\nexport type ResolveCacheEntryTtlOptions = {\n  estimateExpireAge: (staleAge: number) => number;\n  defaultStaleAge: number;\n};\n\n/**\n * Resolves the Redis TTL (seconds) for an ISR / incremental-cache entry.\n *\n * Official Next.js semantics (cache-handler-redis example + self-hosting docs):\n * - Key TTL on `cacheControl.expire`, never on `revalidate` alone.\n * - Past `revalidate` an entry is only stale (SWR); evicting at that boundary\n *   would defeat background refresh.\n * - When no finite `expire` is provided, fall back to `estimateExpireAge(revalidate)`\n *   for legacy Pages Router / pre-cacheLife callers that only pass `revalidate`.\n * - When neither `expire` nor `revalidate` is available, return `undefined` (no TTL;\n *   rely on tag-based invalidation). This is intentional — not a missing\n *   `defaultStaleAge` fallback. `revalidate: false` is a separate branch above\n *   and is covered by unit + Pages Router integration tests (`/static-forever`).\n */\nexport function resolveCacheEntryTtlSeconds(\n  ctx: ResolveCacheEntryTtlContext,\n  data: ResolveCacheEntryTtlData,\n  options: ResolveCacheEntryTtlOptions,\n): number | undefined {\n  const expire = ctx.cacheControl?.expire;\n\n  if (Number.isFinite(expire) && expire! > 0) {\n    return Math.max(1, Math.ceil(expire!));\n  }\n\n  const revalidate = resolveRevalidateValue(ctx, data);\n\n  if (revalidate === false) {\n    return options.estimateExpireAge(options.defaultStaleAge);\n  }\n\n  if (revalidate && Number.isSafeInteger(revalidate) && revalidate > 0) {\n    return options.estimateExpireAge(revalidate);\n  }\n\n  return undefined;\n}\n\nfunction resolveRevalidateValue(\n  ctx: ResolveCacheEntryTtlContext,\n  data: ResolveCacheEntryTtlData,\n): number | false | undefined {\n  if (data?.kind === 'FETCH' && data.revalidate !== undefined) {\n    return data.revalidate;\n  }\n  if (ctx.revalidate !== undefined) {\n    return ctx.revalidate;\n  }\n  if (ctx.cacheControl?.revalidate !== undefined) {\n    return ctx.cacheControl.revalidate;\n  }\n  if (data?.revalidate !== undefined) {\n    return data.revalidate;\n  }\n  return undefined;\n}\n","// A namespace import, not `import { commandOptions }`: node-redis v5 and v6\n// do not export commandOptions, and a named import of it fails at load time.\nimport * as redis from 'redis';\nimport { RedisTimeoutError, untilDeadline } from './deadline';\n\n/**\n * Reads one string key. Rejects with RedisTimeoutError no later than the\n * moment `signal` aborts, whatever the client does with the signal.\n */\nexport type AbortableGet = (\n  key: string,\n  signal: AbortSignal,\n) => Promise<string | null>;\n\ntype WithAbortSignalClient = {\n  withAbortSignal(signal: AbortSignal): {\n    get(key: string): Promise<string | null>;\n  };\n};\n\ntype CommandOptionsClient = {\n  get(options: unknown, key: string): Promise<string | null>;\n};\n\ntype CommandOptionsFn = (options: { signal: AbortSignal }) => unknown;\n\nfunction hasWithAbortSignal(client: object): client is WithAbortSignalClient {\n  return (\n    typeof (client as Partial<WithAbortSignalClient>).withAbortSignal ===\n    'function'\n  );\n}\n\nfunction createClientGet(client: object): AbortableGet {\n  if (hasWithAbortSignal(client)) {\n    return (key, signal) => client.withAbortSignal(signal).get(key);\n  }\n\n  const { commandOptions } = redis as { commandOptions?: CommandOptionsFn };\n  if (typeof commandOptions !== 'function') {\n    throw new Error(\n      'Unsupported redis client: the client has no withAbortSignal() and the redis package exports no commandOptions(). Install redis 4.7.0, ^5 or ^6.',\n    );\n  }\n  const commandOptionsClient = client as CommandOptionsClient;\n  return (key, signal) =>\n    commandOptionsClient.get(commandOptions({ signal }), key);\n}\n\nexport function createAbortableGet(client: object): AbortableGet {\n  const clientGet = createClientGet(client);\n\n  // The signal also goes to the client, so that node-redis can drop a\n  // command it has not written yet.\n  return async (key, signal) => {\n    if (signal.aborted) {\n      throw new RedisTimeoutError();\n    }\n    return untilDeadline(clientGet(key, signal), signal);\n  };\n}\n","/** A Redis command did not get a reply before its signal aborted. */\nexport class RedisTimeoutError extends Error {\n  constructor() {\n    super('Redis command got no reply before its deadline');\n    this.name = 'RedisTimeoutError';\n  }\n}\n\n/**\n * Settles like `operation`, but rejects with RedisTimeoutError no later than\n * the moment `signal` aborts.\n *\n * No node-redis version times out a command that is already written to the\n * socket, and node-redis 5 and 6 also stop listening to the signal at that\n * point. So a server that keeps the connection open but does not reply holds\n * the command until the connection drops. node-redis 4 rejects an aborted\n * command with an error that has no stable name or code, so that case also\n * becomes RedisTimeoutError here.\n */\nexport async function untilDeadline<T>(\n  operation: Promise<T>,\n  signal: AbortSignal,\n): Promise<T> {\n  let onAbort!: () => void;\n  const aborted = new Promise<never>((_, reject) => {\n    onAbort = () => reject(new RedisTimeoutError());\n  });\n  if (signal.aborted) {\n    onAbort();\n  } else {\n    signal.addEventListener('abort', onAbort, { once: true });\n  }\n  try {\n    return await Promise.race([operation, aborted]);\n  } catch (error) {\n    if (signal.aborted) {\n      throw new RedisTimeoutError();\n    }\n    throw error;\n  } finally {\n    signal.removeEventListener('abort', onAbort);\n  }\n}\n","/**\n * Delete keys with one UNLINK per Redis Cluster hash slot.\n *\n * Cluster mode rejects a multi-key command whose keys are not in the same\n * slot, with `CROSSSLOT`. That check happens even when every slot currently\n * lives on the node that received the command. A cache tag does not imply a\n * hash slot, so the old single UNLINK of every key for a tag failed and left\n * the values in place (issue #101).\n *\n * The slot comes from the cluster protocol, unchanged since Redis 3.0 and\n * copied by Valkey:\n *\n *   HASH_SLOT = CRC16(key) mod 16384\n *\n * CRC16 is the XMODEM variant: polynomial 0x1021, initial value 0. The table\n * below is that algorithm, built once at load, matching Appendix A of the\n * Redis cluster specification. `CLUSTER KEYSLOT` on a cluster node returns\n * the same number. Hash tags are part of the same rule: if the key contains\n * `{...}` with at least one character between the braces, only that text is\n * hashed. `{user}.a` and `{user}.b` therefore share a slot.\n *\n * https://redis.io/docs/latest/operate/oss_and_stack/reference/cluster-spec/\n * https://valkey.io/topics/cluster-spec/#key-distribution-model\n *\n * `redis` 4.7 does not export this function. `@redis/client` calculates it\n * with the `cluster-key-slot` package and keeps that package private, so the\n * formula is inlined instead of imported from a path pnpm does not allow.\n * The CRC itself will not change quietly: a different formula would move\n * every existing key to another slot and break every running cluster. Hash-tag\n * edge cases are the part that a future client release might correct, and\n * those corrections have to be applied here by hand.\n *\n * `revalidateTag()` always uses this function. There is no cluster-mode\n * switch. Standalone Redis accepts one UNLINK across slots, so grouping is\n * not required there and cannot drop a key: every input key is sent in\n * exactly one group. What does change on a single node is the command shape.\n * One tag becomes one UNLINK per occupied slot, at most `concurrency` of\n * those commands at a time. A failure deletes the groups that succeeded and\n * leaves the rest, instead of one command covering every key.\n *\n * This does not speak the cluster bus. The handler uses the standalone\n * client. Same-slot UNLINK avoids CROSSSLOT on the node it is connected to,\n * including a cluster node that owns all 16,384 slots (the #101 setup). A\n * slot owned by another node comes back as MOVED, and that group is reported\n * as a failure. Redirects are not followed.\n */\n\nconst REDIS_CLUSTER_SLOT_COUNT = 16_384;\n\n// XMODEM CRC16 table from Appendix A of the Redis cluster specification.\nconst CRC16_TABLE = (() => {\n  const table: number[] = [];\n  for (let i = 0; i < 256; i++) {\n    let crc = i << 8;\n    for (let bit = 0; bit < 8; bit++) {\n      crc = crc & 0x8000 ? (crc << 1) ^ 0x1021 : crc << 1;\n    }\n    table[i] = crc & 0xffff;\n  }\n  return table;\n})();\n\ntype UnlinkClient = {\n  unlink(keys: string | string[]): Promise<number>;\n};\n\nexport type ClusterSafeUnlinkFailure = {\n  slot: number;\n  keys: string[];\n  error: unknown;\n};\n\nexport type ClusterSafeUnlinkResult = {\n  deleted: number;\n  commandCount: number;\n  successfulKeys: string[];\n  failures: ClusterSafeUnlinkFailure[];\n};\n\nexport type ClusterSafeUnlinkOptions = {\n  concurrency?: number;\n  onGroupSuccess?: (keys: string[]) => void | Promise<void>;\n};\n\nexport class ClusterSafeUnlinkError extends Error {\n  constructor(public readonly result: ClusterSafeUnlinkResult) {\n    super(\n      `Cluster-safe unlink failed for ${result.failures.reduce(\n        (sum, failure) => sum + failure.keys.length,\n        0,\n      )} key(s) across ${result.failures.length} hash slot group(s)`,\n    );\n    this.name = 'ClusterSafeUnlinkError';\n  }\n}\n\n// Hash-tag exception from the same specification: hash only the first\n// non-empty `{...}` segment. Anything else hashes as the whole key.\nfunction hashSlotKey(key: string): string {\n  const open = key.indexOf('{');\n  if (open === -1) {\n    return key;\n  }\n\n  const close = key.indexOf('}', open + 1);\n  if (close === -1 || close === open + 1) {\n    return key;\n  }\n\n  return key.slice(open + 1, close);\n}\n\nfunction crc16(value: string): number {\n  const bytes = Buffer.from(value);\n  let crc = 0;\n\n  for (const byte of bytes) {\n    crc = ((crc << 8) ^ CRC16_TABLE[((crc >> 8) ^ byte) & 0xff]!) & 0xffff;\n  }\n\n  return crc;\n}\n\nexport function redisClusterKeySlot(key: string): number {\n  return crc16(hashSlotKey(key)) % REDIS_CLUSTER_SLOT_COUNT;\n}\n\nfunction normalizeConcurrency(concurrency: number | undefined): number {\n  if (concurrency === undefined || !Number.isFinite(concurrency)) {\n    return 16;\n  }\n  return Math.max(1, Math.floor(concurrency));\n}\n\nexport async function clusterSafeUnlink(\n  client: UnlinkClient,\n  keys: string[],\n  options: ClusterSafeUnlinkOptions = {},\n): Promise<ClusterSafeUnlinkResult> {\n  const groups = new Map<number, string[]>();\n  for (const key of keys) {\n    const slot = redisClusterKeySlot(key);\n    const group = groups.get(slot);\n    if (group) {\n      group.push(key);\n    } else {\n      groups.set(slot, [key]);\n    }\n  }\n\n  const work = Array.from(groups.entries());\n  const concurrency = normalizeConcurrency(options.concurrency);\n  const result: ClusterSafeUnlinkResult = {\n    deleted: 0,\n    commandCount: 0,\n    successfulKeys: [],\n    failures: [],\n  };\n  let nextIndex = 0;\n\n  async function worker(): Promise<void> {\n    while (nextIndex < work.length) {\n      const [slot, groupKeys] = work[nextIndex++]!;\n      // Count the UNLINK once, before either the command or the success\n      // callback can reject. A callback failure happens after the command\n      // already ran, so counting again in the catch would report two\n      // commands for one UNLINK.\n      result.commandCount++;\n      try {\n        const deleted = await client.unlink(\n          groupKeys.length === 1 ? groupKeys[0]! : groupKeys,\n        );\n        result.deleted += deleted;\n        // No spread: one slot group can hold more keys than the engine\n        // accepts as function arguments.\n        for (const key of groupKeys) {\n          result.successfulKeys.push(key);\n        }\n        await options.onGroupSuccess?.(groupKeys);\n      } catch (error) {\n        result.failures.push({ slot, keys: groupKeys, error });\n      }\n    }\n  }\n\n  await Promise.all(\n    Array.from({ length: Math.min(concurrency, work.length) }, () => worker()),\n  );\n\n  if (result.failures.length > 0) {\n    throw new ClusterSafeUnlinkError(result);\n  }\n\n  return result;\n}\n","import fs from 'node:fs';\nimport path from 'node:path';\n\nexport function readBuildId(serverDistDir?: string): string | undefined {\n  try {\n    if (serverDistDir) {\n      const buildIdPath = path.join(serverDistDir, '..', 'BUILD_ID');\n      const buildId = fs.readFileSync(buildIdPath, 'utf8').trim();\n      return buildId || undefined;\n    }\n  } catch {\n    // fall through to cwd-based read\n  }\n  try {\n    const fromCwd = path.join(process.cwd(), '.next', 'BUILD_ID');\n    const buildId = fs.readFileSync(fromCwd, 'utf8').trim();\n    return buildId || undefined;\n  } catch {\n    return undefined;\n  }\n}\n\nexport function resolveKeyPrefix({\n  optionKeyPrefix,\n  serverDistDir,\n  env,\n}: {\n  optionKeyPrefix?: string;\n  serverDistDir?: string;\n  env: NodeJS.ProcessEnv;\n}): string {\n  // If the option is explicitly provided, honor it even if it's an empty string\n  if (optionKeyPrefix !== undefined) {\n    return optionKeyPrefix;\n  }\n\n  const keyPrefixEnv =\n    env.KEY_PREFIX && env.KEY_PREFIX.length > 0 ? env.KEY_PREFIX : undefined;\n  const vercelUrl =\n    env.VERCEL_URL && env.VERCEL_URL.length > 0 ? env.VERCEL_URL : undefined;\n  const buildId = readBuildId(serverDistDir);\n\n  return keyPrefixEnv ?? vercelUrl ?? buildId ?? 'UNDEFINED_URL_';\n}\n","import RedisStringsHandler, {\n  CreateRedisStringsHandlerOptions,\n} from './RedisStringsHandler';\nimport { debugVerbose } from './utils/debug';\nimport { resolveKeyPrefix } from './utils/prefix';\n\nlet cachedHandler: RedisStringsHandler;\n\ntype NextCacheHandlerOptions = CreateRedisStringsHandlerOptions & {\n  serverDistDir?: string;\n};\n\nexport default class CachedHandler {\n  constructor(options: NextCacheHandlerOptions) {\n    if (!cachedHandler) {\n      console.log('created cached handler');\n      const keyPrefix = resolveKeyPrefix({\n        optionKeyPrefix: options.keyPrefix,\n        serverDistDir: options.serverDistDir,\n        env: process.env,\n      });\n\n      cachedHandler = new RedisStringsHandler({\n        ...options,\n        keyPrefix,\n      });\n    }\n  }\n  get(\n    ...args: Parameters<RedisStringsHandler['get']>\n  ): ReturnType<RedisStringsHandler['get']> {\n    debugVerbose('CachedHandler.get called with', args);\n    return cachedHandler.get(...args);\n  }\n  set(\n    ...args: Parameters<RedisStringsHandler['set']>\n  ): ReturnType<RedisStringsHandler['set']> {\n    debugVerbose('CachedHandler.set called with', args);\n    return cachedHandler.set(...args);\n  }\n  revalidateTag(\n    ...args: Parameters<RedisStringsHandler['revalidateTag']>\n  ): ReturnType<RedisStringsHandler['revalidateTag']> {\n    debugVerbose('CachedHandler.revalidateTag called with', args);\n    return cachedHandler.revalidateTag(...args);\n  }\n  resetRequestCache(\n    ...args: Parameters<RedisStringsHandler['resetRequestCache']>\n  ): ReturnType<RedisStringsHandler['resetRequestCache']> {\n    // debug(\"CachedHandler.resetRequestCache called with\", args);\n    return cachedHandler.resetRequestCache(...args);\n  }\n}\n","import { createClient } from 'redis';\nimport type { RedisClientOptions } from 'redis';\nimport {\n  Client,\n  CreateRedisStringsHandlerOptions,\n  redisErrorHandler,\n} from './RedisStringsHandler';\nimport { SyncedMap } from './SyncedMap';\nimport { DeduplicatedRequestHandler } from './DeduplicatedRequestHandler';\nimport { debug } from './utils/debug';\nimport { resolveKeyPrefix } from './utils/prefix';\nimport { shouldDeferRedisConnection } from './utils/redisConnection';\nimport { AbortableGet, createAbortableGet } from './utils/abortableGet';\nimport { compareAndUnlink } from './utils/compareAndUnlink';\nimport { RedisTimeoutError, untilDeadline } from './utils/deadline';\nimport {\n  applyTagUpdate,\n  areTagsExpired,\n  areTagsStale,\n  maxExpiredTimestamp,\n  normalizeTagManifest,\n  persistableTagManifest,\n  type TagManifestEntry,\n} from './utils/tagRevalidation';\n\nexport interface CacheComponentsEntry {\n  value: ReadableStream<Uint8Array>;\n  tags: string[];\n  stale: number;\n  timestamp: number;\n  expire: number;\n  revalidate: number;\n}\n\nexport interface CacheComponentsHandler {\n  get(\n    cacheKey: string,\n    softTags: string[],\n  ): Promise<CacheComponentsEntry | undefined>;\n  set(\n    cacheKey: string,\n    pendingEntry: Promise<CacheComponentsEntry>,\n  ): Promise<void>;\n  refreshTags(): Promise<void>;\n  getExpiration(tags: string[]): Promise<number>;\n  updateTags(tags: string[], durations?: { expire?: number }): Promise<void>;\n}\n\ntype StoredCacheEntry = Omit<CacheComponentsEntry, 'value'> & {\n  value: Uint8Array | string;\n};\n\nconst REVALIDATED_TAGS_KEY = '__cacheComponents_revalidated_tags__';\nconst SHARED_TAGS_KEY = '__cacheComponents_sharedTags__';\n\nlet killContainerOnErrorCount = 0;\n\nexport type CreateCacheComponentsHandlerOptions =\n  CreateRedisStringsHandlerOptions & { serverDistDir?: string };\n\nasync function streamToBuffer(\n  stream: ReadableStream<Uint8Array>,\n): Promise<Uint8Array> {\n  const reader = stream.getReader();\n  const chunks: Uint8Array[] = [];\n\n  while (true) {\n    const { value, done } = await reader.read();\n    if (done) break;\n    if (value) {\n      chunks.push(value);\n    }\n  }\n\n  if (chunks.length === 1) {\n    return chunks[0];\n  }\n\n  const totalLength = chunks.reduce((sum, chunk) => sum + chunk.byteLength, 0);\n  const result = new Uint8Array(totalLength);\n  let offset = 0;\n  for (const chunk of chunks) {\n    result.set(chunk, offset);\n    offset += chunk.byteLength;\n  }\n  return result;\n}\n\nfunction bufferToReadableStream(\n  buffer: Uint8Array,\n): ReadableStream<Uint8Array> {\n  return new ReadableStream<Uint8Array>({\n    start(controller) {\n      controller.enqueue(buffer);\n      controller.close();\n    },\n  });\n}\n\nclass RedisCacheComponentsHandler implements CacheComponentsHandler {\n  private client: Client;\n  private revalidatedTagsMap: SyncedMap<TagManifestEntry | number>;\n  private sharedTagsMap: SyncedMap<string[]>;\n  private inMemoryDeduplicationCache: SyncedMap<Promise<string | null>>;\n  private keyPrefix: string;\n  private getTimeoutMs: number;\n  private writeTimeoutMs: number;\n  private redisGet: AbortableGet;\n  private redisDeduplicationHandler: DeduplicatedRequestHandler<\n    AbortableGet,\n    string | null\n  >;\n  private deduplicatedRedisGet: (key: string) => AbortableGet;\n  private redisGetDeduplication: boolean;\n  private inMemoryCachingTime: number;\n  private redisConnectionDeferred: boolean;\n  private pendingStaleRemovals = new Map<\n    string,\n    Set<{ superseded: boolean }>\n  >();\n\n  constructor({\n    redisUrl = process.env.REDIS_URL\n      ? process.env.REDIS_URL\n      : process.env.REDISHOST\n        ? `redis://${process.env.REDISHOST}:${process.env.REDISPORT}`\n        : 'redis://localhost:6379',\n    database = process.env.VERCEL_ENV === 'production' ? 0 : 1,\n    keyPrefix,\n    getTimeoutMs = process.env.REDIS_COMMAND_TIMEOUT_MS\n      ? (Number.parseInt(process.env.REDIS_COMMAND_TIMEOUT_MS) ?? 500)\n      : 500,\n    writeTimeoutMs = process.env.REDIS_WRITE_TIMEOUT_MS\n      ? Number.parseInt(process.env.REDIS_WRITE_TIMEOUT_MS) || getTimeoutMs\n      : getTimeoutMs,\n    revalidateTagQuerySize = 250,\n    avgResyncIntervalMs = 60 * 60 * 1_000,\n    redisGetDeduplication = true,\n    inMemoryCachingTime = 10_000,\n    socketOptions,\n    clientOptions,\n    killContainerOnErrorThreshold = process.env\n      .KILL_CONTAINER_ON_ERROR_THRESHOLD\n      ? (Number.parseInt(process.env.KILL_CONTAINER_ON_ERROR_THRESHOLD) ?? 0)\n      : 0,\n    serverDistDir,\n  }: CreateCacheComponentsHandlerOptions) {\n    try {\n      this.keyPrefix = resolveKeyPrefix({\n        optionKeyPrefix: keyPrefix,\n        serverDistDir,\n        env: process.env,\n      });\n      this.getTimeoutMs = getTimeoutMs;\n      this.writeTimeoutMs = writeTimeoutMs;\n      this.redisGetDeduplication = redisGetDeduplication;\n      this.inMemoryCachingTime = inMemoryCachingTime;\n      this.redisConnectionDeferred = shouldDeferRedisConnection();\n\n      this.client = createClient({\n        url: redisUrl,\n        pingInterval: 10_000,\n        ...(database !== 0 ? { database } : {}),\n        ...(socketOptions\n          ? { socket: { ...socketOptions } as RedisClientOptions['socket'] }\n          : {}),\n        ...(clientOptions || {}),\n      });\n\n      this.client.on('error', (error) => {\n        console.error(\n          'RedisCacheComponentsHandler client error',\n          error,\n          killContainerOnErrorCount++,\n        );\n        setTimeout(() => {\n          // node-redis throws \"Socket already opened\" if connect() is called while a socket is already open.\n          // When we get an error while isOpen=true (but isReady=false), we should *not* force an extra connect.\n          if (this.client.isOpen) return;\n\n          this.client.connect().catch((err) => {\n            console.error(\n              'Failed to reconnect RedisCacheComponentsHandler client after connection loss:',\n              err,\n            );\n          });\n        }, 1000);\n        if (\n          killContainerOnErrorThreshold > 0 &&\n          killContainerOnErrorCount >= killContainerOnErrorThreshold\n        ) {\n          console.error(\n            'RedisCacheComponentsHandler client error threshold reached, disconnecting and exiting (please implement a restart process/container watchdog to handle this error)',\n            error,\n            killContainerOnErrorCount++,\n          );\n          this.client.disconnect();\n          this.client.quit();\n          setTimeout(() => {\n            process.exit(1);\n          }, 500);\n        }\n      });\n\n      if (!this.redisConnectionDeferred) {\n        this.client\n          .connect()\n          .then(() => {\n            debug('green', 'RedisCacheComponentsHandler client connected.');\n          })\n          .catch(() => {\n            this.client.connect().catch((error) => {\n              console.error(\n                'Failed to connect RedisCacheComponentsHandler client:',\n                error,\n              );\n              this.client.disconnect();\n              throw error;\n            });\n          });\n      }\n\n      const filterKeys = (key: string): boolean =>\n        key !== REVALIDATED_TAGS_KEY && key !== SHARED_TAGS_KEY;\n\n      this.revalidatedTagsMap = new SyncedMap<TagManifestEntry | number>({\n        client: this.client,\n        keyPrefix: this.keyPrefix,\n        redisKey: REVALIDATED_TAGS_KEY,\n        database,\n        querySize: revalidateTagQuerySize,\n        filterKeys,\n        customizedSync: { withoutOrphanCleanup: true },\n        resyncIntervalMs:\n          avgResyncIntervalMs +\n          avgResyncIntervalMs / 10 +\n          Math.random() * (avgResyncIntervalMs / 10),\n      });\n\n      this.sharedTagsMap = new SyncedMap<string[]>({\n        client: this.client,\n        keyPrefix: this.keyPrefix,\n        redisKey: SHARED_TAGS_KEY,\n        database,\n        querySize: revalidateTagQuerySize,\n        filterKeys,\n        resyncIntervalMs:\n          avgResyncIntervalMs -\n          avgResyncIntervalMs / 10 +\n          Math.random() * (avgResyncIntervalMs / 10),\n      });\n\n      this.inMemoryDeduplicationCache = new SyncedMap({\n        client: this.client,\n        keyPrefix: this.keyPrefix,\n        redisKey: '__cacheComponents_inMemoryDeduplicationCache__',\n        database,\n        querySize: revalidateTagQuerySize,\n        filterKeys,\n        customizedSync: {\n          withoutRedisHashmap: true,\n          withoutSetSync: true,\n        },\n      });\n\n      const redisGet = createAbortableGet(this.client);\n      this.redisDeduplicationHandler = new DeduplicatedRequestHandler(\n        redisGet,\n        inMemoryCachingTime,\n        this.inMemoryDeduplicationCache,\n      );\n      this.redisGet = redisGet;\n      this.deduplicatedRedisGet =\n        this.redisDeduplicationHandler.deduplicatedFunction;\n    } catch (error) {\n      console.error('RedisCacheComponentsHandler constructor error', error);\n      throw error;\n    }\n  }\n\n  private async assertClientIsReady(): Promise<void> {\n    if (this.redisConnectionDeferred) {\n      await Promise.all([\n        this.revalidatedTagsMap.waitUntilReady(),\n        this.sharedTagsMap.waitUntilReady(),\n      ]);\n      return;\n    }\n\n    if (!this.client.isReady && !this.client.isOpen) {\n      await this.client.connect().catch((error) => {\n        console.error(\n          'RedisCacheComponentsHandler assertClientIsReady reconnect error:',\n          error,\n        );\n        throw error;\n      });\n    }\n    await Promise.all([\n      this.revalidatedTagsMap.waitUntilReady(),\n      this.sharedTagsMap.waitUntilReady(),\n    ]);\n  }\n\n  private isClientUnavailable(): boolean {\n    return this.redisConnectionDeferred || !this.client.isReady;\n  }\n\n  private tagManifestFor(tag: string, now = Date.now()): TagManifestEntry {\n    return normalizeTagManifest(this.revalidatedTagsMap.get(tag), now);\n  }\n\n  async get(\n    cacheKey: string,\n    _softTags: string[],\n  ): Promise<CacheComponentsEntry | undefined> {\n    // Soft-tag staleness is handled by Next.js via getExpiration() (implicit\n    // `_N_T_` tags). Explicit cacheTag()s are checked below via the tag\n    // manifest, matching DefaultCacheHandler.get() in Next.js 16.0–16.3.\n    void _softTags;\n\n    // Construct the full Redis key\n    // For cache components, Next.js provides the full key including environment prefix\n    // We prepend our keyPrefix for multi-tenant isolation\n    const redisKey = `${this.keyPrefix}${cacheKey}`;\n\n    try {\n      await this.assertClientIsReady();\n      if (this.isClientUnavailable()) {\n        return undefined;\n      }\n\n      const readSerialized = (useDedup: boolean) =>\n        redisErrorHandler(\n          'RedisCacheComponentsHandler.get(), operation: get' +\n            (useDedup ? ' deduplicated' : '') +\n            ' ' +\n            this.getTimeoutMs +\n            'ms ' +\n            redisKey,\n          (useDedup ? this.deduplicatedRedisGet(cacheKey) : this.redisGet)(\n            redisKey,\n            AbortSignal.timeout(this.getTimeoutMs),\n          ),\n        );\n\n      let usedDedup = this.redisGetDeduplication;\n      let serialized = await readSerialized(usedDedup);\n\n      for (let attempt = 0; attempt < 2; attempt++) {\n        if (!serialized) {\n          return undefined;\n        }\n\n        const stored: StoredCacheEntry = JSON.parse(serialized);\n        const now = Date.now();\n        const tags = stored.tags || [];\n        const expiryTime = stored.timestamp + stored.expire * 1000;\n        const ttlExpired =\n          Number.isFinite(stored.expire) &&\n          stored.expire > 0 &&\n          now > expiryTime;\n        const tagsExpired = areTagsExpired(tags, stored.timestamp, now, (tag) =>\n          this.tagManifestFor(tag, now),\n        );\n\n        if (ttlExpired || tagsExpired) {\n          if (usedDedup) {\n            usedDedup = false;\n            serialized = await readSerialized(false);\n            continue;\n          }\n\n          // The tag cleanup is part of the raced operation, so it still runs\n          // when the unlink answers after the deadline. A set() that sends its\n          // SET after this EVAL supersedes the removal, so a late cleanup\n          // cannot delete the tag record of the replacement entry.\n          const pending = { superseded: false };\n          const removals = this.pendingStaleRemovals.get(cacheKey) ?? new Set();\n          removals.add(pending);\n          this.pendingStaleRemovals.set(cacheKey, removals);\n          const removal = compareAndUnlink(this.client, redisKey, serialized)\n            .then(async (dropped) => {\n              if (dropped && !pending.superseded) {\n                await this.sharedTagsMap.delete(cacheKey).catch(() => {});\n              }\n            })\n            .finally(() => {\n              removals.delete(pending);\n              if (\n                removals.size === 0 &&\n                this.pendingStaleRemovals.get(cacheKey) === removals\n              ) {\n                this.pendingStaleRemovals.delete(cacheKey);\n              }\n            });\n          try {\n            await untilDeadline(\n              removal,\n              AbortSignal.timeout(this.getTimeoutMs),\n            );\n          } catch (error) {\n            if (!(error instanceof RedisTimeoutError)) {\n              throw error;\n            }\n            console.warn(\n              'RedisCacheComponentsHandler.get() Redis did not confirm the removal of a stale entry within',\n              this.getTimeoutMs,\n              'ms. Returning a cache miss without it:',\n              redisKey,\n            );\n          }\n          return undefined;\n        }\n\n        const valueBuffer =\n          typeof stored.value === 'string'\n            ? new Uint8Array(Buffer.from(stored.value, 'base64'))\n            : stored.value;\n\n        const entry: CacheComponentsEntry = {\n          ...stored,\n          value: bufferToReadableStream(valueBuffer),\n        };\n\n        if (\n          areTagsStale(tags, stored.timestamp, (tag) =>\n            this.tagManifestFor(tag, now),\n          )\n        ) {\n          entry.revalidate = -1;\n        }\n\n        return entry;\n      }\n\n      return undefined;\n    } catch (error) {\n      console.error(\n        'RedisCacheComponentsHandler.get() Error occurred while getting cache entry. Returning undefined so site can continue to serve content while cache is disabled. The original error was:',\n        error,\n        killContainerOnErrorCount++,\n      );\n      return undefined;\n    }\n  }\n\n  async set(\n    cacheKey: string,\n    pendingEntry: Promise<CacheComponentsEntry>,\n  ): Promise<void> {\n    try {\n      await this.assertClientIsReady();\n      if (this.isClientUnavailable()) {\n        return;\n      }\n\n      const entry = await pendingEntry;\n\n      const [storeStream] = entry.value.tee();\n\n      // Don't mutate entry.value as Next.js may still be using it internally\n      // entry.value = forwardStream;\n\n      const buffer = await streamToBuffer(storeStream);\n\n      const stored: StoredCacheEntry = {\n        value: Buffer.from(buffer).toString('base64'),\n        tags: entry.tags || [],\n        stale: entry.stale,\n        timestamp: entry.timestamp,\n        expire: entry.expire,\n        revalidate: entry.revalidate,\n      };\n\n      let serialized: string;\n      try {\n        const cleanStored = {\n          value: stored.value,\n          tags: Array.isArray(stored.tags) ? [...stored.tags] : [],\n          stale: Number(stored.stale),\n          timestamp: Number(stored.timestamp),\n          expire: Number(stored.expire),\n          revalidate: Number(stored.revalidate),\n        };\n        serialized = JSON.stringify(cleanStored);\n      } catch (jsonError) {\n        console.error('JSON.stringify error:', jsonError);\n        console.error('Stored object:', stored);\n        throw jsonError;\n      }\n\n      if (this.redisGetDeduplication) {\n        this.redisDeduplicationHandler.seedRequestReturn(cacheKey, serialized);\n      }\n\n      // expire is already a duration in seconds, use it directly\n      const ttlSeconds =\n        Number.isFinite(stored.expire) && stored.expire > 0\n          ? Math.floor(stored.expire)\n          : undefined;\n\n      const redisKey = `${this.keyPrefix}${cacheKey}`;\n\n      for (const pending of this.pendingStaleRemovals.get(cacheKey) ?? []) {\n        pending.superseded = true;\n      }\n\n      const setOperation = redisErrorHandler(\n        'RedisCacheComponentsHandler.set(), operation: set ' + redisKey,\n        this.client.set(redisKey, serialized, {\n          ...(ttlSeconds ? { EX: ttlSeconds } : {}),\n        }),\n      );\n\n      let tagsOperation: Promise<void> | undefined;\n      const tags = stored.tags || [];\n      if (tags.length > 0) {\n        const currentTags = this.sharedTagsMap.get(cacheKey);\n        const currentIsSameAsNew =\n          currentTags?.length === tags.length &&\n          currentTags.every((v) => tags.includes(v)) &&\n          tags.every((v) => currentTags!.includes(v));\n\n        if (!currentIsSameAsNew) {\n          tagsOperation = this.sharedTagsMap.set(cacheKey, [...tags]);\n        }\n      }\n\n      await untilDeadline(\n        Promise.all([setOperation, tagsOperation]),\n        AbortSignal.timeout(this.writeTimeoutMs),\n      );\n    } catch (error) {\n      if (error instanceof RedisTimeoutError) {\n        console.warn(\n          'RedisCacheComponentsHandler.set() Redis did not confirm the write within',\n          this.writeTimeoutMs,\n          'ms. Returning without it, the entry may not be stored:',\n          cacheKey,\n        );\n        return;\n      }\n      console.error(\n        'RedisCacheComponentsHandler.set() Error occurred while setting cache entry. The original error was:',\n        error,\n        killContainerOnErrorCount++,\n      );\n      throw error;\n    }\n  }\n\n  async refreshTags(): Promise<void> {\n    await this.assertClientIsReady();\n  }\n\n  async getExpiration(tags: string[]): Promise<number> {\n    try {\n      await this.assertClientIsReady();\n      return maxExpiredTimestamp(tags || [], (tag) => this.tagManifestFor(tag));\n    } catch (error) {\n      console.error(\n        'RedisCacheComponentsHandler.getExpiration() Error occurred while getting expiration for tags. The original error was:',\n        error,\n      );\n      return 0;\n    }\n  }\n\n  async updateTags(\n    tags: string[],\n    durations?: { expire?: number },\n  ): Promise<void> {\n    try {\n      await this.assertClientIsReady();\n      if (this.isClientUnavailable()) {\n        return;\n      }\n\n      const now = Date.now();\n      const updated = new Set(tags || []);\n      const writes: Promise<void>[] = [];\n      for (const tag of updated) {\n        const next = applyTagUpdate(this.tagManifestFor(tag), durations, now);\n        writes.push(\n          this.revalidatedTagsMap.set(tag, persistableTagManifest(next, now)),\n        );\n      }\n\n      if (this.redisGetDeduplication && this.inMemoryCachingTime > 0) {\n        for (const [key, sharedTags] of this.sharedTagsMap.entries()) {\n          if (sharedTags.some((tag) => updated.has(tag))) {\n            writes.push(this.inMemoryDeduplicationCache.delete(key, true));\n          }\n        }\n      }\n\n      await untilDeadline(\n        Promise.all(writes),\n        AbortSignal.timeout(this.writeTimeoutMs),\n      );\n    } catch (error) {\n      if (error instanceof RedisTimeoutError) {\n        console.warn(\n          'RedisCacheComponentsHandler.updateTags() Redis did not confirm the writes within',\n          this.writeTimeoutMs,\n          'ms. Returning without them, other instances may serve stale entries for tags:',\n          tags,\n        );\n        return;\n      }\n      console.error(\n        'RedisCacheComponentsHandler.updateTags() Error occurred while updating tags. The original error was:',\n        error,\n        killContainerOnErrorCount++,\n      );\n      throw error;\n    }\n  }\n}\n\nlet singletonHandler: CacheComponentsHandler | undefined;\n\nexport function getRedisCacheComponentsHandler(\n  options: CreateCacheComponentsHandlerOptions = {},\n): CacheComponentsHandler {\n  if (!singletonHandler) {\n    singletonHandler = new RedisCacheComponentsHandler(options);\n  }\n  return singletonHandler;\n}\n\n// Lazily resolve the default Cache Components handler.\n//\n// Constructing a RedisCacheComponentsHandler opens a Redis connection in its\n// constructor. Building the singleton at module-eval time therefore means that simply\n// *importing this package* — e.g. only for `RedisStringsHandler` (the legacy\n// `cacheHandler`), with Cache Components never enabled — eagerly connects to Redis,\n// defaulting to `redis://localhost:6379` when neither `REDIS_URL` nor `REDISHOST` is\n// set. In a deployment whose Redis is not on localhost that yields a non-stop\n// `RedisCacheComponentsHandler client error ECONNREFUSED 127.0.0.1:6379` reconnect\n// loop, and it also makes a consumer's later `getRedisCacheComponentsHandler(options)`\n// a no-op, because the singleton was already built with defaults (see #84).\n//\n// Defer construction to first use via a Proxy: importing the package never connects, a\n// consumer that configures the handler via `getRedisCacheComponentsHandler(options)`\n// before it is first used has that configuration honored, and a consumer that never\n// touches Cache Components never opens a Redis connection at all.\nlet resolvedHandler: CacheComponentsHandler | undefined;\n\nexport const redisCacheHandler: CacheComponentsHandler = new Proxy(\n  {} as CacheComponentsHandler,\n  {\n    get(_target, prop) {\n      if (!resolvedHandler) {\n        resolvedHandler = getRedisCacheComponentsHandler();\n      }\n      const value = resolvedHandler[prop as keyof CacheComponentsHandler];\n      return typeof value === 'function'\n        ? (value as (...args: unknown[]) => unknown).bind(resolvedHandler)\n        : value;\n    },\n    has(_target, prop) {\n      return prop in RedisCacheComponentsHandler.prototype;\n    },\n  },\n);\n","/**\n * Atomically delete `key` only if its current value still equals `expected`.\n * GET then UNLINK would race: another instance can SET a replacement in between.\n */\nconst COMPARE_AND_UNLINK = `\nif redis.call('GET', KEYS[1]) == ARGV[1] then\n  return redis.call('UNLINK', KEYS[1])\nend\nreturn 0\n`;\n\ntype EvalClient = {\n  eval(\n    script: string,\n    options: { keys: string[]; arguments: string[] },\n  ): Promise<unknown>;\n};\n\nexport async function compareAndUnlink(\n  client: EvalClient,\n  key: string,\n  expected: string,\n): Promise<boolean> {\n  const deleted = await client.eval(COMPARE_AND_UNLINK, {\n    keys: [key],\n    arguments: [expected],\n  });\n  return deleted === 1 || deleted === 1n;\n}\n","/**\n * Tag manifest matching Next.js 16.0–16.3\n * `next/dist/server/lib/cache-handlers/default.js` `updateTags`\n * and `next/dist/server/lib/incremental-cache/tags-manifest.external.js`.\n *\n * `revalidateTag(tag, profile)` resolves `cacheLife[profile].expire` (seconds)\n * and calls `updateTags(tags, { expire })`. `updateTag` / no profile calls\n * `updateTags(tags)` with no durations (immediate hard expire).\n */\nexport type TagManifestEntry = {\n  stale?: number;\n  expired?: number;\n};\n\n/**\n * Read a tag-manifest field from Redis.\n *\n * Next.js 16.0–16.3 never persists plain numbers here — `updateTags` always\n * writes `{ stale, expired }` via `applyTagUpdate()`. A plain number can only\n * appear from older releases of this package that stored `Date.now()` directly\n * (before the `{ stale, expired }` manifest). ISR uses a separate Redis hash\n * (`__revalidated_tags__`) and is unaffected.\n *\n * A future-looking plain number is not produced by Next.js and is not the same\n * as intentional SWR (`{ stale: now, expired: now + N }`). It can only happen\n * when another instance wrote the timestamp with a faster clock (NTP skew).\n * Clamp to `now` on read so the revalidation is not delayed on slower instances.\n */\nexport function normalizeTagManifest(\n  stored: unknown,\n  now: number = Date.now(),\n): TagManifestEntry {\n  if (typeof stored === 'number' && Number.isFinite(stored)) {\n    return { expired: Math.min(stored, now) };\n  }\n\n  if (stored && typeof stored === 'object') {\n    const rec = stored as {\n      stale?: unknown;\n      expired?: unknown;\n      last?: unknown;\n      pending?: unknown;\n    };\n    const stale =\n      typeof rec.stale === 'number' && Number.isFinite(rec.stale)\n        ? rec.stale\n        : typeof rec.last === 'number' && Number.isFinite(rec.last)\n          ? rec.last\n          : undefined;\n    const expired =\n      typeof rec.expired === 'number' && Number.isFinite(rec.expired)\n        ? rec.expired\n        : typeof rec.pending === 'number' && Number.isFinite(rec.pending)\n          ? rec.pending\n          : undefined;\n    return {\n      ...(stale !== undefined ? { stale } : {}),\n      ...(expired !== undefined ? { expired } : {}),\n    };\n  }\n\n  return {};\n}\n\n/**\n * Mirrors Next.js DefaultCacheHandler.updateTags().\n */\nexport function applyTagUpdate(\n  existing: TagManifestEntry,\n  durations: { expire?: number } | undefined,\n  now: number,\n): TagManifestEntry {\n  if (durations) {\n    const updates = { ...existing };\n    updates.stale = now;\n    if (durations.expire !== undefined) {\n      updates.expired = now + durations.expire * 1000;\n    }\n    return updates;\n  }\n\n  return {\n    ...existing,\n    expired: now,\n  };\n}\n\n/**\n * Immediate hard-expires (`expired <= now`) are stored as a plain number so\n * older package versions that JSON.parse + numeric-compare the hash field still\n * see the invalidation during a rolling deploy. SWR windows stay objects.\n */\nexport function persistableTagManifest(\n  entry: TagManifestEntry,\n  now: number,\n): TagManifestEntry | number {\n  if (\n    typeof entry.expired === 'number' &&\n    entry.expired <= now &&\n    (entry.stale === undefined || entry.stale <= entry.expired)\n  ) {\n    return entry.expired;\n  }\n  return entry;\n}\n\n/**\n * Mirrors Next.js `areTagsExpired`: hard miss once `expired` has elapsed\n * and is newer than the entry timestamp.\n */\nexport function areTagsExpired(\n  tags: string[],\n  entryTimestamp: number,\n  now: number,\n  getEntry: (tag: string) => TagManifestEntry | undefined,\n): boolean {\n  for (const tag of tags) {\n    const expiredAt = getEntry(tag)?.expired;\n    if (\n      typeof expiredAt === 'number' &&\n      expiredAt <= now &&\n      expiredAt > entryTimestamp\n    ) {\n      return true;\n    }\n  }\n  return false;\n}\n\n/**\n * Mirrors Next.js `areTagsStale`: SWR when `stale` is newer than the entry.\n */\nexport function areTagsStale(\n  tags: string[],\n  entryTimestamp: number,\n  getEntry: (tag: string) => TagManifestEntry | undefined,\n): boolean {\n  for (const tag of tags) {\n    const staleAt = getEntry(tag)?.stale ?? 0;\n    if (typeof staleAt === 'number' && staleAt > entryTimestamp) {\n      return true;\n    }\n  }\n  return false;\n}\n\n/**\n * Mirrors Next.js DefaultCacheHandler.getExpiration(): max `expired` or 0.\n */\nexport function maxExpiredTimestamp(\n  tags: string[],\n  getEntry: (tag: string) => TagManifestEntry | undefined,\n): number {\n  let max = 0;\n  for (const tag of tags) {\n    const expired = getEntry(tag)?.expired || 0;\n    if (expired > max) {\n      max = expired;\n    }\n  }\n  return max;\n}\n","import CachedHandler from './CachedHandler';\nexport default CachedHandler;\n\nimport RedisStringsHandler from './RedisStringsHandler';\nexport { RedisStringsHandler };\nexport type { CreateRedisStringsHandlerOptions } from './RedisStringsHandler';\n\nexport { jsonCacheValueSerializer } from './serializer';\nexport type { CacheValueSerializer } from './serializer';\nexport { bufferAndMapReplacer, bufferAndMapReviver } from './utils/json';\nexport { resolveCacheEntryTtlSeconds } from './utils/cacheTtl';\nexport type {\n  ResolveCacheEntryTtlContext,\n  ResolveCacheEntryTtlData,\n  ResolveCacheEntryTtlOptions,\n} from './utils/cacheTtl';\nexport { shouldDeferRedisConnection } from './utils/redisConnection';\n\nimport {\n  redisCacheHandler,\n  getRedisCacheComponentsHandler,\n} from './CacheComponentsHandler';\nexport { redisCacheHandler, getRedisCacheComponentsHandler };\n"],"mappings":";AAAA,SAAS,oBAAwC;;;ACA1C,SAAS,MACd,QAOa,WACV,MACG;AACN,QAAM,YAAY;AAAA,IAChB,KAAK;AAAA,IACL,MAAM;AAAA,IACN,OAAO;AAAA,IACP,QAAQ;AAAA,IACR,MAAM;AAAA,IACN,OAAO;AAAA,IACP,MAAM;AAAA,EACR;AACA,MAAI,QAAQ,IAAI,qBAAqB;AACnC,YAAQ,IAAI,UAAU,KAAK,GAAG,yBAAyB,GAAG,IAAI;AAAA,EAChE;AACF;AAEO,SAAS,aAAa,UAAkB,MAAiB;AAC9D,MAAI,QAAQ,IAAI,qCAAqC;AACnD,YAAQ,IAAI,YAAY,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