import { isRootNamespace, namespaceKey } from "../namespace.js";
import { openProjectionSubscription } from "./runtime.js";
//#region src/stream/projections/channel.ts
/** Max events retained per raw subscription. Older events are dropped. */
const DEFAULT_BUFFER = 4096;
function channelProjection(channels, namespace, options = {}) {
	const chs = [...channels].sort();
	const ns = [...namespace];
	const bufferSize = options.bufferSize ?? DEFAULT_BUFFER;
	const replay = options.replay ?? true;
	return {
		key: `channel|${bufferSize}|${replay ? "replay" : "live"}|${chs.join(",")}|${namespaceKey(ns)}`,
		namespace: ns,
		initial: [],
		open({ thread, store, rootBus }) {
			if (!replay && isRootNamespace(ns) && chs.every((c) => rootBus.channels.includes(c))) {
				const requestedSet = new Set(chs);
				const namedCustom = /* @__PURE__ */ new Set();
				for (const channel of chs) if (channel.startsWith("custom:")) namedCustom.add(channel.slice(7));
				const matches = (event) => {
					if (requestedSet.has(event.method)) return true;
					if (event.method !== "custom" || namedCustom.size === 0) return false;
					const data = event.params.data;
					return typeof data?.name === "string" && namedCustom.has(data.name);
				};
				const push = (event) => {
					if (!matches(event)) return;
					const current = store.getSnapshot();
					const next = current.length >= bufferSize ? [...current.slice(current.length - bufferSize + 1), event] : [...current, event];
					store.setValue(next);
				};
				const unsubscribe = rootBus.subscribe(push);
				return { dispose() {
					unsubscribe();
				} };
			}
			return openProjectionSubscription({
				thread,
				channels: chs,
				namespace: ns,
				resumeOnPause: true,
				onEvent(event) {
					const current = store.getSnapshot();
					const next = current.length >= bufferSize ? [...current.slice(current.length - bufferSize + 1), event] : [...current, event];
					store.setValue(next);
				}
			});
		}
	};
}
//#endregion
export { channelProjection };

//# sourceMappingURL=channel.js.map