import { f as tryReadJson, m as writeJson, p as tryReadJsonSync } from "./json-files-BiJ8jTLe.js";
import { o as resolveCompatibilityHostVersion } from "./version-DzRkiGSk.js";
import { t as isBlockedObjectKey } from "./prototype-keys-gIgii6VQ.js";
import { c as resolveInstalledPluginIndexStorePath, t as clearLoadInstalledPluginIndexInstallRecordsCache } from "./installed-plugin-index-record-reader-Crf7lxJ6.js";
import { c as resolveEffectiveEnableState, s as normalizePluginsConfig } from "./config-state-CQ3C5tII.js";
import { t as isPluginEnabledByDefaultForPlatform } from "./default-enablement-CT7_t1ee.js";
import { t as clearPluginMetadataLifecycleCaches } from "./plugin-metadata-lifecycle-BqWfg4Sp.js";
import { a as refreshInstalledPluginIndex, d as resolveCompatRegistryVersion, f as resolveInstalledPluginIndexPolicyHash, m as hashJson, o as diffInstalledPluginIndexInvalidationReasons, r as loadInstalledPluginIndex, s as INSTALLED_PLUGIN_INDEX_WARNING, u as extractPluginInstallRecordsFromInstalledPluginIndex } from "./installed-plugin-index-BVZVYQO0.js";
import { At as boolean, Et as array, Nn as record, Rn as string, Tn as object, Xn as union, Zn as unknown, dn as literal, wn as number } from "./schemas-CjJwTzTb.js";
import { r as saveJsonFile } from "./json-file-DXqJk-4P.js";
import { n as safeParseWithSchema } from "./zod-parse-B4dzFRWI.js";
//#region src/plugins/installed-plugin-index-store.ts
const StringArraySchema = array(string());
const InstalledPluginIndexStartupSchema = object({
	sidecar: boolean(),
	memory: boolean(),
	deferConfiguredChannelFullLoadUntilAfterListen: boolean(),
	agentHarnesses: StringArraySchema
});
const InstalledPluginFileSignatureSchema = object({
	size: number(),
	mtimeMs: number(),
	ctimeMs: number().optional()
});
const InstalledPluginIndexRecordSchema = object({
	pluginId: string(),
	packageName: string().optional(),
	packageVersion: string().optional(),
	installRecord: record(string(), unknown()).optional(),
	installRecordHash: string().optional(),
	packageInstall: unknown().optional(),
	packageChannel: unknown().optional(),
	manifestPath: string(),
	manifestHash: string(),
	manifestFile: InstalledPluginFileSignatureSchema.optional(),
	format: string().optional(),
	bundleFormat: string().optional(),
	source: string().optional(),
	setupSource: string().optional(),
	packageJson: object({
		path: string(),
		hash: string(),
		fileSignature: InstalledPluginFileSignatureSchema.optional()
	}).optional(),
	rootDir: string(),
	origin: string(),
	enabled: boolean(),
	enabledByDefault: boolean().optional(),
	enabledByDefaultOnPlatforms: StringArraySchema.optional(),
	syntheticAuthRefs: StringArraySchema.optional(),
	startup: InstalledPluginIndexStartupSchema,
	compat: array(string())
});
const InstalledPluginInstallRecordSchema = record(string(), unknown());
const PluginDiagnosticSchema = object({
	level: union([literal("warn"), literal("error")]),
	message: string(),
	pluginId: string().optional(),
	source: string().optional()
});
const InstalledPluginIndexSchema = object({
	version: literal(1),
	warning: string().optional(),
	hostContractVersion: string(),
	compatRegistryVersion: string(),
	migrationVersion: literal(1),
	policyHash: string(),
	generatedAtMs: number(),
	refreshReason: string().optional(),
	installRecords: record(string(), InstalledPluginInstallRecordSchema).optional(),
	plugins: array(InstalledPluginIndexRecordSchema),
	diagnostics: array(PluginDiagnosticSchema)
});
function copySafeInstallRecords(records) {
	if (!records) return;
	const safeRecords = {};
	for (const [pluginId, record] of Object.entries(records)) {
		if (isBlockedObjectKey(pluginId)) continue;
		safeRecords[pluginId] = record;
	}
	return safeRecords;
}
function parseInstalledPluginIndex(value) {
	const parsed = safeParseWithSchema(InstalledPluginIndexSchema, value);
	if (!parsed) return null;
	const installRecords = copySafeInstallRecords(parsed.installRecords) ?? copySafeInstallRecords(extractPluginInstallRecordsFromInstalledPluginIndex(parsed)) ?? {};
	return {
		version: parsed.version,
		...parsed.warning ? { warning: parsed.warning } : {},
		hostContractVersion: parsed.hostContractVersion,
		compatRegistryVersion: parsed.compatRegistryVersion,
		migrationVersion: parsed.migrationVersion,
		policyHash: parsed.policyHash,
		generatedAtMs: parsed.generatedAtMs,
		...parsed.refreshReason ? { refreshReason: parsed.refreshReason } : {},
		installRecords,
		plugins: parsed.plugins,
		diagnostics: parsed.diagnostics
	};
}
async function readPersistedInstalledPluginIndex(options = {}) {
	return parseInstalledPluginIndex(await tryReadJson(resolveInstalledPluginIndexStorePath(options)));
}
function readPersistedInstalledPluginIndexSync(options = {}) {
	return parseInstalledPluginIndex(tryReadJsonSync(resolveInstalledPluginIndexStorePath(options)));
}
async function writePersistedInstalledPluginIndex(index, options = {}) {
	const filePath = resolveInstalledPluginIndexStorePath(options);
	await writeJson(filePath, {
		...index,
		warning: INSTALLED_PLUGIN_INDEX_WARNING
	}, {
		trailingNewline: true,
		dirMode: 448,
		mode: 384
	});
	clearPluginMetadataLifecycleCaches();
	clearLoadInstalledPluginIndexInstallRecordsCache();
	return filePath;
}
function writePersistedInstalledPluginIndexSync(index, options = {}) {
	const filePath = resolveInstalledPluginIndexStorePath(options);
	saveJsonFile(filePath, {
		...index,
		warning: INSTALLED_PLUGIN_INDEX_WARNING
	});
	clearPluginMetadataLifecycleCaches();
	clearLoadInstalledPluginIndexInstallRecordsCache();
	return filePath;
}
function hasPolicyRefreshTargets(persisted, policyPluginIds) {
	if (!policyPluginIds || policyPluginIds.length === 0) return true;
	const pluginIds = new Set(persisted.plugins.map((plugin) => plugin.pluginId));
	return policyPluginIds.every((pluginId) => pluginIds.has(pluginId));
}
function canRefreshPersistedPolicyState(persisted, params) {
	if (!persisted || params.reason !== "policy-changed") return false;
	const env = params.env ?? process.env;
	if (persisted.version !== 1 || persisted.hostContractVersion !== resolveCompatibilityHostVersion(env) || persisted.compatRegistryVersion !== resolveCompatRegistryVersion() || persisted.migrationVersion !== 1) return false;
	if (params.installRecords && hashJson(params.installRecords) !== hashJson(persisted.installRecords ?? {})) return false;
	return hasPolicyRefreshTargets(persisted, params.policyPluginIds);
}
function refreshPersistedPolicyState(persisted, params) {
	const normalizedConfig = normalizePluginsConfig(params.config?.plugins);
	return {
		...persisted,
		policyHash: resolveInstalledPluginIndexPolicyHash(params.config),
		generatedAtMs: (params.now?.() ?? /* @__PURE__ */ new Date()).getTime(),
		refreshReason: params.reason,
		plugins: persisted.plugins.map((plugin) => ({
			...plugin,
			enabled: resolveEffectiveEnableState({
				id: plugin.pluginId,
				origin: plugin.origin,
				config: normalizedConfig,
				rootConfig: params.config,
				enabledByDefault: isPluginEnabledByDefaultForPlatform(plugin)
			}).enabled
		}))
	};
}
async function inspectPersistedInstalledPluginIndex(params = {}) {
	const persisted = await readPersistedInstalledPluginIndex(params);
	const current = loadInstalledPluginIndex({
		...params,
		installRecords: params.installRecords ?? extractPluginInstallRecordsFromInstalledPluginIndex(persisted)
	});
	if (!persisted) return {
		state: "missing",
		refreshReasons: ["missing"],
		persisted: null,
		current
	};
	const refreshReasons = diffInstalledPluginIndexInvalidationReasons(persisted, current);
	return {
		state: refreshReasons.length > 0 ? "stale" : "fresh",
		refreshReasons,
		persisted,
		current
	};
}
async function refreshPersistedInstalledPluginIndex(params) {
	const persisted = params.reason === "policy-changed" || !params.installRecords ? await readPersistedInstalledPluginIndex(params) : null;
	if (canRefreshPersistedPolicyState(persisted, params)) {
		const index = refreshPersistedPolicyState(persisted, params);
		await writePersistedInstalledPluginIndex(index, params);
		return index;
	}
	const index = refreshInstalledPluginIndex({
		...params,
		installRecords: params.installRecords ?? extractPluginInstallRecordsFromInstalledPluginIndex(persisted)
	});
	await writePersistedInstalledPluginIndex(index, params);
	return index;
}
function refreshPersistedInstalledPluginIndexSync(params) {
	const persisted = params.reason === "policy-changed" || !params.installRecords ? readPersistedInstalledPluginIndexSync(params) : null;
	if (canRefreshPersistedPolicyState(persisted, params)) {
		const index = refreshPersistedPolicyState(persisted, params);
		writePersistedInstalledPluginIndexSync(index, params);
		return index;
	}
	const index = refreshInstalledPluginIndex({
		...params,
		installRecords: params.installRecords ?? extractPluginInstallRecordsFromInstalledPluginIndex(persisted)
	});
	writePersistedInstalledPluginIndexSync(index, params);
	return index;
}
//#endregion
export { refreshPersistedInstalledPluginIndexSync as a, refreshPersistedInstalledPluginIndex as i, readPersistedInstalledPluginIndex as n, writePersistedInstalledPluginIndex as o, readPersistedInstalledPluginIndexSync as r, inspectPersistedInstalledPluginIndex as t };
