"use client"
import { t as PUBLIC_API_URL } from "./const-CaIm1Z8g.mjs";
import React, { createContext, useContext, useMemo } from "react";
import { jsx } from "react/jsx-runtime";
import { QueryClient } from "@tanstack/react-query";
import axios, { AxiosError, isAxiosError } from "axios";
import { track } from "@amplitude/unified";

//#region recce-source/js/src/lib/api/axiosClient.ts
const axiosClient = axios.create({ baseURL: PUBLIC_API_URL });
const reactQueryClient = new QueryClient();

//#endregion
//#region recce-source/js/src/lib/api/track.ts
function track$1(eventInput, eventProperties, eventOptions) {
	if (!amplitudeInitialized) console.log("[Tracking]", eventInput, eventProperties, eventOptions);
	return track(eventInput, eventProperties, eventOptions);
}
let amplitudeInitialized = false;
function trackMultiNodesAction(props) {
	track$1("[Web] multi_nodes_action", props);
}
function trackHistoryAction(props) {
	track$1("[Web] history_action", props);
}
function trackPreviewChange(props) {
	track$1("[Experiment] preview_change", props);
}
function trackPreviewChangeFeedback(props) {
	track$1("[Experiment] preview_change", props);
}
function trackSingleEnvironment(props) {
	track$1("[Experiment] single_environment", props);
}
function getExperimentTrackingBreakingChangeEnabled() {
	return false;
}
function trackColumnLevelLineage(props) {
	track$1("[Web] column_level_lineage", props);
}
function trackShareState(props) {
	track$1("[Web] share_state", props);
}
function trackStateAction(props) {
	track$1("[Web] state_action", props);
}
function trackCopyToClipboard(props) {
	track$1("[Click] copy_to_clipboard", props);
}
function trackNavigation(props) {
	track$1("[Web] navigation_change", props);
}
function trackLineageViewRender(props) {
	track$1("[Web] lineage_view_render", props);
}
function trackEnvironmentConfig(props) {
	track$1("[Web] environment_config", props);
}
const EXPLORE_ACTION = {
	ROW_COUNT: "row_count",
	ROW_COUNT_DIFF: "row_count_diff",
	PROFILE: "profile",
	PROFILE_DIFF: "profile_diff",
	VALUE_DIFF: "value_diff",
	SCHEMA_DIFF: "schema_diff",
	LINEAGE_DIFF: "lineage_diff",
	QUERY: "query",
	HISTOGRAM_DIFF: "histogram_diff",
	TOP_K_DIFF: "top_k_diff"
};
const EXPLORE_SOURCE = {
	LINEAGE_VIEW_TOP_BAR: "lineage_view_top_bar",
	LINEAGE_VIEW_CONTEXT_MENU: "lineage_view_context_menu",
	NODE_KEBAB_MENU: "node_kebab_menu",
	NODE_SIDEBAR_SINGLE_ENV: "node_sidebar_single_env",
	NODE_SIDEBAR_MULTI_ENV: "node_sidebar_multi_env",
	SCHEMA_ROW_COUNT_BUTTON: "schema_row_count_button",
	SCHEMA_COLUMN_MENU: "schema_column_menu"
};
function trackExploreAction(props) {
	track$1("[Web] explore_action", props);
}
const EXPLORE_FORM_EVENT = {
	EXECUTE: "execute",
	CANCEL: "cancel"
};
function trackExploreActionForm(props) {
	track$1("[Web] explore_action_form", props);
}
function isExploreAction(type) {
	return Object.values(EXPLORE_ACTION).includes(type);
}
const LINEAGE_SELECTION_ACTION = {
	SELECT_PARENT_NODES: "select_parent_nodes",
	SELECT_CHILD_NODES: "select_child_nodes",
	SELECT_ALL_UPSTREAM: "select_all_upstream",
	SELECT_ALL_DOWNSTREAM: "select_all_downstream"
};
function trackLineageSelection(props) {
	track$1("[Web] lineage_selection", props);
}

//#endregion
//#region recce-source/js/src/lib/api/types.ts
function isQueryRun(run) {
	return run.type === "query";
}
function isQueryBaseRun(run) {
	return run.type === "query_base";
}
function isQueryDiffRun(run) {
	return run.type === "query_diff";
}
function isValueDiffRun(run) {
	return run.type === "value_diff";
}
function isValueDiffDetailRun(run) {
	return run.type === "value_diff_detail";
}
function isProfileRun(run) {
	return run.type === "profile";
}
function isProfileDiffRun(run) {
	return run.type === "profile_diff";
}
function isRowCountRun(run) {
	return run.type === "row_count";
}
function isRowCountDiffRun(run) {
	return run.type === "row_count_diff";
}
function isTopKDiffRun(run) {
	return run.type === "top_k_diff";
}
function isHistogramDiffRun(run) {
	return run.type === "histogram_diff";
}

//#endregion
//#region recce-source/js/src/lib/hooks/ApiConfigContext.tsx
const defaultConfig = {
	apiPrefix: "",
	authToken: void 0,
	baseUrl: void 0
};
const ApiConfigContext = createContext(null);
/**
* Creates an axios instance configured with the given API config.
*
* The instance has interceptors that:
* 1. Replace /api prefix with the configured apiPrefix (if provided)
* 2. Add Authorization header with Bearer token (if authToken provided)
*/
function createApiClient(config) {
	const { apiPrefix, authToken, baseUrl } = config;
	const client = axios.create({ baseURL: baseUrl ?? PUBLIC_API_URL });
	client.interceptors.request.use((requestConfig) => {
		try {
			if (apiPrefix && requestConfig.url) {
				if (requestConfig.url === "/api") requestConfig.url = apiPrefix;
				else if (requestConfig.url.startsWith("/api/")) requestConfig.url = apiPrefix + requestConfig.url.slice(4);
			}
			if (authToken) requestConfig.headers.Authorization = `Bearer ${authToken}`;
			return requestConfig;
		} catch (error) {
			console.warn("API request interceptor error, proceeding with unmodified request:", error);
			return requestConfig;
		}
	}, (error) => {
		return Promise.reject(error);
	});
	return client;
}
function ApiConfigProvider({ children, apiPrefix = defaultConfig.apiPrefix, authToken = defaultConfig.authToken, baseUrl = defaultConfig.baseUrl }) {
	const config = useMemo(() => ({
		apiPrefix,
		authToken,
		baseUrl
	}), [
		apiPrefix,
		authToken,
		baseUrl
	]);
	const apiClient = useMemo(() => createApiClient(config), [config]);
	const contextValue = useMemo(() => ({
		...config,
		apiClient
	}), [config, apiClient]);
	return /* @__PURE__ */ jsx(ApiConfigContext.Provider, {
		value: contextValue,
		children
	});
}
const defaultApiConfigContext = {
	apiPrefix: "",
	authToken: void 0,
	baseUrl: void 0,
	apiClient: axios.create({ baseURL: PUBLIC_API_URL })
};
/**
* Hook to access the API configuration and configured axios client.
*
* When used outside ApiConfigProvider, returns default config with
* standard axiosClient (for OSS backward compatibility).
*
* @returns ApiConfigContextType with apiPrefix, authToken, and apiClient
*/
function useApiConfig() {
	return useContext(ApiConfigContext) ?? defaultApiConfigContext;
}
/**
* Hook to get the configured axios client.
* Convenience wrapper around useApiConfig().apiClient
*
* @returns AxiosInstance configured with API prefix and auth token
*/
function useApiClient() {
	return useApiConfig().apiClient;
}
/**
* Safe version of useApiConfig that returns null if outside provider.
* Useful for components that need to detect if ApiConfigProvider is present.
*/
function useApiConfigSafe() {
	return useContext(ApiConfigContext);
}

//#endregion
//#region recce-source/js/src/lib/api/cacheKeys.ts
const cacheKeys = {
	rowCount: (model) => ["row_count", model],
	lineage: () => ["lineage"],
	checks: () => ["checks", "list"],
	check: (checkId) => ["checks", checkId],
	checkEvents: (checkId) => [
		"checks",
		checkId,
		"events"
	],
	runs: () => ["runs"],
	run: (runId) => ["runs", runId],
	runsAggregated: () => ["runs_aggregated"],
	flag: () => ["flag"],
	instanceInfo: () => ["instance_info"],
	user: () => ["user"]
};

//#endregion
//#region recce-source/js/src/lib/api/flag.ts
async function getServerFlag(client = axiosClient) {
	return (await client.get("/api/flag")).data;
}
async function markOnboardingCompleted(client = axiosClient) {
	try {
		await client.post("/api/onboarding/completed");
	} catch (_error) {}
}
async function markRelaunchHintCompleted(client = axiosClient) {
	try {
		await client.post("/api/relaunch-hint/completed");
	} catch (_error) {}
}

//#endregion
//#region recce-source/js/src/lib/api/info.ts
async function getLineage(base = false) {
	return (await axiosClient.get(`/api/lineage?base=${base}`)).data;
}
async function getLineageWithError(base = false) {
	try {
		return { data: await getLineage(base) };
	} catch (err) {
		if (err instanceof AxiosError) {
			const detail = (err.response?.data)?.detail;
			if (detail) return { error: detail };
			else return { error: err.message };
		} else if (err instanceof Error) return { error: err.message };
		else return { error: "An unknown error occurred" };
	}
}
async function getLineageDiff() {
	const [base, current] = await Promise.all([getLineageWithError(true), getLineageWithError(false)]);
	return {
		base: base.data,
		current: current.data,
		base_error: base.error,
		current_error: current.error
	};
}
async function getServerInfo(client = axiosClient) {
	return (await client.get(`/api/info`)).data;
}
async function getModelInfo(model) {
	return (await axiosClient.get(`/api/model/${model}`)).data;
}

//#endregion
//#region recce-source/js/src/lib/api/runs.ts
function mutateAddKey(run) {
	if (run.result == null) return run;
	if (isQueryRun(run)) run.result.columns = run.result.columns.map((c) => {
		if (c.key) return c;
		c.key = c.name;
		return c;
	});
	return run;
}
async function submitRun(type, params, options, client = axiosClient) {
	const track_props = options?.trackProps ? { ...options.trackProps } : {};
	if (getExperimentTrackingBreakingChangeEnabled()) track_props.breaking_change_analysis = true;
	return (await client.post("/api/runs", {
		type,
		params,
		nowait: options?.nowait,
		track_props
	})).data;
}
async function getRun(runId, client = axiosClient) {
	return (await client.get(`/api/runs/${runId}`)).data;
}
async function waitRun(runId, timeout, client = axiosClient) {
	return mutateAddKey((await client.get(`/api/runs/${runId}/wait`, { params: { timeout } })).data);
}
async function cancelRun(runId, client = axiosClient) {
	return await client.post(`/api/runs/${runId}/cancel`);
}
async function submitRunFromCheck(checkId, options, client = axiosClient) {
	return (await client.post(`/api/checks/${checkId}/run`, { nowait: options?.nowait })).data;
}
async function searchRuns(type, params, limit, client = axiosClient) {
	return (await client.post(`/api/runs/search`, {
		type,
		params,
		limit
	})).data;
}
async function listRuns(client = axiosClient) {
	return (await client.get("/api/runs")).data;
}
async function aggregateRuns(client = axiosClient) {
	return (await client.post(`/api/runs/aggregate`, {})).data;
}

//#endregion
//#region recce-source/js/src/lib/api/state.ts
async function saveAs(input, client = axiosClient) {
	return (await client.post("/api/save-as", input)).data;
}
async function rename(input, client = axiosClient) {
	return (await client.post("/api/rename", input)).data;
}
async function exportState(client = axiosClient) {
	return (await client.post("/api/export")).data;
}
async function importState(file, checksOnly, client = axiosClient) {
	const formData = new FormData();
	formData.append("file", file);
	formData.append("checks_only", (!!checksOnly).toString());
	return (await client.post("/api/import", formData)).data;
}
async function isStateSyncing(client = axiosClient) {
	return (await client.get("/api/sync")).status === 208;
}
async function syncState(input, client = axiosClient) {
	try {
		const response = await client.post("/api/sync", input);
		if (response.status === 202) return { status: "accepted" };
		if (response.status === 208) return { status: "syncing" };
	} catch (error) {
		if (isAxiosError(error)) {
			if (error.response?.status === 409) return { status: "conflict" };
		}
	}
	throw new Error("Failed to sync state");
}
async function shareState(client = axiosClient) {
	return (await client.post("/api/share")).data;
}

//#endregion
export { trackLineageViewRender as $, isProfileDiffRun as A, EXPLORE_ACTION as B, markRelaunchHintCompleted as C, useApiConfig as D, useApiClient as E, isRowCountDiffRun as F, isExploreAction as G, EXPLORE_SOURCE as H, isRowCountRun as I, trackEnvironmentConfig as J, trackColumnLevelLineage as K, isTopKDiffRun as L, isQueryBaseRun as M, isQueryDiffRun as N, useApiConfigSafe as O, isQueryRun as P, trackLineageSelection as Q, isValueDiffDetailRun as R, markOnboardingCompleted as S, ApiConfigProvider as T, LINEAGE_SELECTION_ACTION as U, EXPLORE_FORM_EVENT as V, getExperimentTrackingBreakingChangeEnabled as W, trackExploreActionForm as X, trackExploreAction as Y, trackHistoryAction as Z, getLineageDiff as _, saveAs as a, trackSingleEnvironment as at, getServerInfo as b, aggregateRuns as c, reactQueryClient as ct, listRuns as d, trackMultiNodesAction as et, searchRuns as f, getLineage as g, waitRun as h, rename as i, trackShareState as it, isProfileRun as j, isHistogramDiffRun as k, cancelRun as l, submitRunFromCheck as m, importState as n, trackPreviewChange as nt, shareState as o, trackStateAction as ot, submitRun as p, trackCopyToClipboard as q, isStateSyncing as r, trackPreviewChangeFeedback as rt, syncState as s, axiosClient as st, exportState as t, trackNavigation as tt, getRun as u, getLineageWithError as v, cacheKeys as w, getServerFlag as x, getModelInfo as y, isValueDiffRun as z };
//# sourceMappingURL=state-Sc2b4jri.mjs.map