import { getInternalStorageBucket, listInternalStorageBucketNames } from "./internal.js";
import { DurableCacheStorage } from "../fetch/index.js";
import { getOrigin } from "../listen/index.js";
import { getConfig } from "../config/index.js";
function getDurableStorageBucketOrigin() {
    const config = getConfig();
    return (config.getDurableStorageBucketOrigin?.() ??
        config.getDurableCacheStorageOrigin?.() ??
        getOrigin());
}
export class DurableStorageBucket {
    caches;
    name;
    options;
    constructor(options) {
        this.name = options.name;
        this.options = options;
        const internalBucket = getInternalStorageBucket(options.name);
        this.caches = new DurableCacheStorage({
            url: getDurableStorageBucketOrigin,
            internalBucket
        });
    }
    async estimate() {
        return undefined;
    }
    async expires() {
        return undefined;
    }
    async getDirectory() {
        return undefined;
    }
    async persist() {
        return false;
    }
    async persisted() {
        return this.options.persisted;
    }
    async setExpires(expires) {
        if (expires < Date.now()) {
            await deleteStorageBucket(this);
        }
    }
}
async function deleteStorageBucket(bucket) {
    for (const cacheName of await bucket.caches.keys()) {
        await bucket.caches.delete(cacheName);
    }
    await getInternalStorageBucket(bucket.name).delete();
}
export class DurableStorageBucketManager {
    buckets = new Map();
    async delete(name) {
        await deleteStorageBucket(await this.open(name));
        this.buckets.delete(name);
    }
    async keys() {
        return [...new Set([
                ...this.buckets.keys(),
                ...await listInternalStorageBucketNames()
            ])];
    }
    async open(name, options) {
        const open = this.buckets.get(name);
        if (open) {
            return open;
        }
        const bucket = new DurableStorageBucket({
            ...options,
            name
        });
        this.buckets.set(name, bucket);
        return bucket;
    }
}
export const storageBuckets = new DurableStorageBucketManager();
//# sourceMappingURL=manager.js.map