import { t as __exportAll } from "./rolldown-runtime-twds-ZHy.mjs";
import { t as KV } from "./schema-Dsr_V2Wp.mjs";
import { n as deleteImage, o as touchImage } from "./image-store-Gpo2mgM9.mjs";
import { TriggerAction } from "iii-sdk";
//#region src/state/keyed-mutex.ts
const locks = /* @__PURE__ */ new Map();
function withKeyedLock(key, fn) {
	const next = (locks.get(key) ?? Promise.resolve()).then(fn, fn);
	const cleanup = next.then(() => {}, () => {});
	locks.set(key, cleanup);
	cleanup.then(() => {
		if (locks.get(key) === cleanup) locks.delete(key);
	});
	return next;
}
//#endregion
//#region src/functions/image-refs.ts
var image_refs_exports = /* @__PURE__ */ __exportAll({
	decrementImageRef: () => decrementImageRef,
	getImageRefCount: () => getImageRefCount,
	incrementImageRef: () => incrementImageRef
});
async function getImageRefCount(kv, filePath) {
	const count = await kv.get(KV.imageRefs, filePath);
	return count ? Number(count) : 0;
}
async function incrementImageRef(kv, filePath) {
	return withKeyedLock(`imgRef:${filePath}`, async () => {
		const current = await getImageRefCount(kv, filePath);
		await kv.set(KV.imageRefs, filePath, current + 1);
		await touchImage(filePath);
	});
}
async function decrementImageRef(kv, sdk, filePath) {
	return withKeyedLock(`imgRef:${filePath}`, async () => {
		const current = await getImageRefCount(kv, filePath);
		if (current <= 1) {
			await kv.delete(KV.imageEmbeddings, filePath);
			await kv.delete(KV.imageRefs, filePath);
			const { deletedBytes } = await deleteImage(filePath);
			if (deletedBytes > 0) sdk.trigger({
				function_id: "mem::disk-size-delta",
				payload: { deltaBytes: -deletedBytes },
				action: TriggerAction.Void()
			});
		} else await kv.set(KV.imageRefs, filePath, current - 1);
	});
}
//#endregion
export { image_refs_exports as n, withKeyedLock as r, getImageRefCount as t };

//# sourceMappingURL=image-refs-C7h9L5wx.mjs.map