'use strict';

require('../chunk-OWW5GUSB.js');
var internal = require('@opennextjs/cloudflare/overrides/internal');
var cloudflareContext = require('@opennextjs/cloudflare/cloudflare-context');

var R2_BUCKET_BINDING = "NEXT_INC_CACHE_R2_BUCKET";
var R2_PREFIX_ENV = "NEXT_INC_CACHE_R2_PREFIX";
var PATH_INDEX_BINDING = "CIMPLIFY_PATH_INDEX";
var CIMPLIFY_TAG_PREFIX = "cimplify:";
function r2Key(env, key, cacheType) {
  return internal.computeCacheKey(key, {
    prefix: env[R2_PREFIX_ENV],
    buildId: globalThis.process?.env?.OPEN_NEXT_BUILD_ID,
    cacheType
  });
}
function cimplifyTags(value) {
  return (value?.tags ?? []).filter((t) => t.startsWith(CIMPLIFY_TAG_PREFIX));
}
function pathIndexFor(env) {
  const ns = env[PATH_INDEX_BINDING];
  const prefix = env[R2_PREFIX_ENV];
  if (!ns || !prefix) return null;
  return ns.get(ns.idFromName(prefix));
}
var evictIncrementalCache = {
  name: "cimplify-evict-r2-cache",
  async get(key, cacheType) {
    const env = cloudflareContext.getCloudflareContext().env;
    const r2 = env[R2_BUCKET_BINDING];
    if (!r2) return null;
    try {
      const obj = await r2.get(r2Key(env, key, cacheType));
      if (!obj) return null;
      return {
        value: await obj.json(),
        lastModified: obj.uploaded.getTime()
      };
    } catch {
      return null;
    }
  },
  async set(key, value, cacheType) {
    const env = cloudflareContext.getCloudflareContext().env;
    const r2 = env[R2_BUCKET_BINDING];
    if (!r2) return;
    const k = r2Key(env, key, cacheType);
    try {
      await r2.put(k, JSON.stringify(value));
    } catch {
      return;
    }
    const tags = cimplifyTags(value);
    if (tags.length === 0) return;
    const index = pathIndexFor(env);
    if (!index) return;
    try {
      await index.indexAdd(key, k, tags, cacheType === "fetch");
    } catch {
    }
  },
  async delete(key) {
    const env = cloudflareContext.getCloudflareContext().env;
    const r2 = env[R2_BUCKET_BINDING];
    if (!r2) return;
    try {
      await r2.delete(r2Key(env, key));
    } catch {
    }
  }
};
var evict_incremental_cache_default = evictIncrementalCache;

exports.evictIncrementalCache = evict_incremental_cache_default;
