"use strict";
/* Socket Lib - Built with rolldown */
Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
const require_runtime = require('../_virtual/_rolldown/runtime.js');
const require_primordials_string = require('../primordials/string.js');
const require_primordials_array = require('../primordials/array.js');
const require_node_fs = require('../node/fs.js');
const require_node_path = require('../node/path.js');
const require_primordials_date = require('../primordials/date.js');
const require_primordials_json = require('../primordials/json.js');
const require_fs_read_json = require('../fs/read-json.js');
const require_objects_predicates = require('../objects/predicates.js');
const require_paths_socket = require('../paths/socket.js');
const require_fs_safe = require('../fs/safe.js');
const require_constants_time = require('../constants/time.js');
let node_fs = require("node:fs");
let node_process = require("node:process");
node_process = require_runtime.__toESM(node_process);

//#region src/dlx/binary-cache.ts
/**
* @file On-disk cache metadata helpers for dlx binaries.
*
*   - `getDlxCachePath` — root of the binary cache (alias of getSocketDlxDir)
*   - `getBinaryCacheMetadataPath` — path to a cache entry's .dlx-metadata.json
*   - `isBinaryCacheValid` — TTL-based liveness check
*   - `writeBinaryCacheMetadata` — atomic write of cache metadata
*   - `cleanDlxCache` — TTL-based eviction sweep
*   - `listDlxCache` — enumerate cached binaries with their metadata Split out of
*     `dlx/binary.ts` for size hygiene.
*/
/**
* Clean expired entries from the DLX cache.
*
* @example
*   ;```typescript
*   // Remove cache entries older than the default TTL
*   const removed = await cleanDlxCache()
*
*   // Remove entries older than 1 hour
*   const removed2 = await cleanDlxCache(60 * 60 * 1000)
*   ```
*/
async function cleanDlxCache(maxAge = require_constants_time.DLX_BINARY_CACHE_TTL) {
	const cacheDir = getDlxCachePath();
	const fs = /* @__PURE__ */ require_node_fs.getNodeFs();
	if (!fs.existsSync(cacheDir)) return 0;
	let cleaned = 0;
	const now = require_primordials_date.DateNow();
	const path = /* @__PURE__ */ require_node_path.getNodePath();
	const entries = await fs.promises.readdir(cacheDir);
	for (const entry of entries) {
		const entryPath = path.join(cacheDir, entry);
		const metaPath = getBinaryCacheMetadataPath(entryPath);
		try {
			if (!await (0, node_fs.existsSync)(entryPath)) continue;
			const metadata = await /* @__PURE__ */ require_fs_read_json.readJson(metaPath, { throws: false });
			if (!metadata || typeof metadata !== "object" || require_primordials_array.ArrayIsArray(metadata)) continue;
			const timestamp = metadata["timestamp"];
			const age = typeof timestamp === "number" && timestamp > 0 ? now - timestamp : Number.POSITIVE_INFINITY;
			if (age < 0 || age > maxAge) {
				await require_fs_safe.safeDelete(entryPath, {
					force: true,
					recursive: true
				});
				cleaned += 1;
			}
		} catch {
			try {
				if (!(await fs.promises.readdir(entryPath)).length) {
					await require_fs_safe.safeDelete(entryPath);
					cleaned += 1;
				}
			} catch {}
		}
	}
	return cleaned;
}
/**
* Get metadata file path for a cached binary.
*
* @example
*   ;```typescript
*   const metaPath = getBinaryCacheMetadataPath('/tmp/dlx-cache/a1b2c3d4')
*   // '/tmp/dlx-cache/a1b2c3d4/.dlx-metadata.json'
*   ```
*/
function getBinaryCacheMetadataPath(cacheEntryPath) {
	return (/* @__PURE__ */ require_node_path.getNodePath()).join(cacheEntryPath, ".dlx-metadata.json");
}
/**
* Get the DLX binary cache directory path. Alias of `getSocketDlxDir` — DLX
* binary cache uses the same directory as dlx-package for unified DLX storage.
*
* @example
*   ;```typescript
*   const cachePath = getDlxCachePath()
*   ```
*/
const getDlxCachePath = require_paths_socket.getSocketDlxDir;
/**
* Check if a cached binary is still valid.
*
* @example
*   ;```typescript
*   const ttl = 7 * 24 * 60 * 60 * 1000
*   const valid = await isBinaryCacheValid('/tmp/dlx-cache/a1b2c3d4', ttl)
*   if (!valid) {
*     // Re-download the binary
*   }
*   ```
*/
async function isBinaryCacheValid(cacheEntryPath, cacheTtl) {
	const fs = /* @__PURE__ */ require_node_fs.getNodeFs();
	try {
		const metaPath = getBinaryCacheMetadataPath(cacheEntryPath);
		if (!fs.existsSync(metaPath)) return false;
		const metadata = await /* @__PURE__ */ require_fs_read_json.readJson(metaPath, { throws: false });
		if (!/* @__PURE__ */ require_objects_predicates.isPlainObject(metadata)) return false;
		const now = require_primordials_date.DateNow();
		const timestamp = metadata["timestamp"];
		if (typeof timestamp !== "number" || timestamp <= 0) return false;
		const age = now - timestamp;
		if (age < 0) return false;
		return age < cacheTtl;
	} catch {
		return false;
	}
}
/**
* Get information about cached binaries.
*
* @example
*   ```typescript
*   const entries = await listDlxCache()
*   for (const entry of entries) {
*   console.log(`${entry.name}: ${entry.size} bytes`)
*   }
*   ```
*/
async function listDlxCache() {
	const cacheDir = getDlxCachePath();
	const fs = /* @__PURE__ */ require_node_fs.getNodeFs();
	if (!fs.existsSync(cacheDir)) return [];
	const results = [];
	const now = require_primordials_date.DateNow();
	const path = /* @__PURE__ */ require_node_path.getNodePath();
	const entries = await fs.promises.readdir(cacheDir);
	for (const entry of entries) {
		const entryPath = path.join(cacheDir, entry);
		try {
			if (!await (0, node_fs.existsSync)(entryPath)) continue;
			const metadata = await /* @__PURE__ */ require_fs_read_json.readJson(getBinaryCacheMetadataPath(entryPath), { throws: false });
			if (!metadata || typeof metadata !== "object" || require_primordials_array.ArrayIsArray(metadata)) continue;
			const metaObj = metadata;
			const url = metaObj["source"]?.["url"] || metaObj["url"] || "";
			const binaryFile = require_primordials_array.ArrayPrototypeFind(await fs.promises.readdir(entryPath), (f) => !require_primordials_string.StringPrototypeStartsWith(f, "."));
			if (binaryFile) {
				const binaryPath = path.join(entryPath, binaryFile);
				const binaryStats = await fs.promises.stat(binaryPath);
				results.push({
					age: now - (metaObj["timestamp"] || 0),
					integrity: metaObj["integrity"] || "",
					name: binaryFile,
					size: binaryStats.size,
					url
				});
			}
		} catch {}
	}
	return results;
}
/**
* Read the DlxMetadata for a cached binary. Returns `undefined` when the
* metadata file is missing, unreadable, or doesn't match the expected shape.
* Useful for callers that want to recover the integrity / size / source URL of
* an already-cached download without re-fetching.
*
* @example
*   ```typescript
*   const meta = await readBinaryCacheMetadata(cacheEntryDir)
*   if (meta) {
*   console.log(`Pinned integrity: ${meta.integrity}`)
*   }
*   ```
*/
async function readBinaryCacheMetadata(cacheEntryPath) {
	const fs = /* @__PURE__ */ require_node_fs.getNodeFs();
	try {
		const metaPath = getBinaryCacheMetadataPath(cacheEntryPath);
		if (!fs.existsSync(metaPath)) return;
		const metadata = await /* @__PURE__ */ require_fs_read_json.readJson(metaPath, { throws: false });
		if (!/* @__PURE__ */ require_objects_predicates.isPlainObject(metadata)) return;
		return metadata;
	} catch {
		return;
	}
}
/**
* Write metadata for a cached binary. Uses unified schema shared with C++
* decompressor and CLI dlxBinary.
*
* @example
*   ;```typescript
*   await writeBinaryCacheMetadata(
*     '/tmp/dlx-cache/a1b2c3d4',
*     'a1b2c3d4',
*     'https://example.com/tool',
*     'sha512-abc123...',
*     15000000,
*   )
*   ```
*/
async function writeBinaryCacheMetadata(cacheEntryPath, cacheKey, url, integrity, size) {
	const metaPath = getBinaryCacheMetadataPath(cacheEntryPath);
	const metadata = {
		version: "1.0.0",
		cache_key: cacheKey,
		timestamp: require_primordials_date.DateNow(),
		integrity,
		size,
		source: {
			type: "download",
			url
		}
	};
	const fs = /* @__PURE__ */ require_node_fs.getNodeFs();
	const tmpPath = `${metaPath}.tmp.${node_process.default.pid}`;
	await fs.promises.writeFile(tmpPath, require_primordials_json.JSONStringify(metadata, null, 2));
	await fs.promises.rename(tmpPath, metaPath);
}

//#endregion
exports.cleanDlxCache = cleanDlxCache;
exports.getBinaryCacheMetadataPath = getBinaryCacheMetadataPath;
exports.getDlxCachePath = getDlxCachePath;
exports.isBinaryCacheValid = isBinaryCacheValid;
exports.listDlxCache = listDlxCache;
exports.readBinaryCacheMetadata = readBinaryCacheMetadata;
exports.writeBinaryCacheMetadata = writeBinaryCacheMetadata;