import { Zero } from "../../zero-client/src/client/zero.js";
import "./zero.js";
import { batch, createContext, createEffect, createMemo, onCleanup, splitProps, untrack, useContext } from "solid-js";
//#region ../zero-solid/src/use-zero.ts
var ZeroContext = createContext(void 0);
/**
* @deprecated Use {@linkcode ZeroProvider} instead of managing your own Zero instance.
*/
function createZero(options) {
	return new Zero({
		...options,
		batchViewUpdates: batch
	});
}
function useZero() {
	const zero = useContext(ZeroContext);
	if (zero === void 0) throw new Error("useZero must be used within a ZeroProvider");
	return zero;
}
/**
* @deprecated Use {@linkcode useZero} instead, alongside default types defined with:
*
* ```ts
* declare module '@rocicorp/zero' {
*   interface DefaultTypes {
*     schema: typeof schema;
*     context: Context;
*   }
* }
*/
function createUseZero() {
	return () => useZero();
}
function ZeroProvider(props) {
	let prevAuth = "auth" in props ? props.auth : void 0;
	const auth = createMemo(() => "auth" in props ? props.auth : void 0);
	const hasAuth = createMemo(() => typeof auth() === "string");
	const zero = createMemo(() => {
		if ("zero" in props) return props.zero;
		hasAuth();
		const [, options] = splitProps(props, ["children", "auth"]);
		const authValue = untrack(auth);
		prevAuth = authValue;
		const createdZero = new Zero({
			...options,
			...authValue !== void 0 ? { auth: authValue } : {},
			batchViewUpdates: batch
		});
		options.init?.(createdZero);
		onCleanup(() => createdZero.close());
		return createdZero;
	});
	createEffect(() => {
		const currentZero = zero();
		if (!currentZero || "zero" in props) return;
		const currentAuth = auth();
		if (currentAuth !== prevAuth) {
			const previousAuth = prevAuth;
			prevAuth = currentAuth;
			if (typeof previousAuth === "string" && typeof currentAuth === "string") currentZero.connection.connect({ auth: currentAuth });
		}
	});
	return ZeroContext.Provider({
		value: zero,
		get children() {
			return props.children;
		}
	});
}
//#endregion
export { ZeroProvider, createUseZero, createZero, useZero };

//# sourceMappingURL=use-zero.js.map