import { DEFAULT_MESSAGES_KEY } from "../constants.js";
import { ensureMessageInstances } from "../message-coercion.js";
import { isRootNamespace, namespaceKey } from "../namespace.js";
import { openProjectionSubscription } from "./runtime.js";
//#region src/stream/projections/values.ts
function valuesProjection(namespace, messagesKey = DEFAULT_MESSAGES_KEY) {
	const ns = [...namespace];
	return {
		key: `values|${messagesKey}|${namespaceKey(ns)}`,
		namespace: ns,
		initial: void 0,
		open({ thread, store, rootBus }) {
			const applyValuesEvent = (event) => {
				const coerced = coerceMessagesInState(event.params.data, messagesKey);
				store.setValue(coerced);
			};
			if (isRootNamespace(ns) && rootBus.channels.includes("values")) {
				const unsubscribe = rootBus.subscribe((event) => {
					if (event.method !== "values") return;
					if (!isRootNamespace(event.params.namespace)) return;
					applyValuesEvent(event);
				});
				return { dispose() {
					unsubscribe();
				} };
			}
			return openProjectionSubscription({
				thread,
				channels: ["values"],
				namespace: ns,
				onEvent(event) {
					if (event.method !== "values") return;
					applyValuesEvent(event);
				}
			});
		}
	};
}
function coerceMessagesInState(value, messagesKey) {
	if (value == null || typeof value !== "object" || Array.isArray(value)) return value;
	const state = value;
	const maybeMessages = state[messagesKey];
	if (!Array.isArray(maybeMessages) || maybeMessages.length === 0) return value;
	if (!maybeMessages.some((m) => m != null && typeof m.getType !== "function")) return value;
	return {
		...state,
		[messagesKey]: ensureMessageInstances(maybeMessages)
	};
}
//#endregion
export { valuesProjection };

//# sourceMappingURL=values.js.map