"use strict";
var __create = Object.create;
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __getProtoOf = Object.getPrototypeOf;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
var __export = (target, all) => {
  for (var name in all)
    __defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
  if (from && typeof from === "object" || typeof from === "function") {
    for (let key of __getOwnPropNames(from))
      if (!__hasOwnProp.call(to, key) && key !== except)
        __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
  }
  return to;
};
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
  // If the importer is in node compatibility mode or this is not an ESM
  // file that has been converted to a CommonJS file using a Babel-
  // compatible transform (i.e. "__esModule" has not been set), then set
  // "default" to the CommonJS "module.exports" for node compatibility.
  isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
  mod
));
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);

// src/db/index.ts
var index_exports = {};
__export(index_exports, {
  CanvasDbProvider: () => CanvasDbProvider,
  InMemoryStorageAdapter: () => InMemoryStorageAdapter,
  SupabaseStorageAdapter: () => SupabaseStorageAdapter,
  canvasKeys: () => canvasKeys,
  createGraphEdge: () => createGraphEdge,
  createGraphNode: () => createGraphNode,
  deleteGraphEdge: () => deleteGraphEdge,
  deleteGraphNode: () => deleteGraphNode,
  fetchGraphEdges: () => fetchGraphEdges,
  fetchGraphNode: () => fetchGraphNode,
  fetchGraphNodes: () => fetchGraphNodes,
  storageAdapterAtom: () => storageAdapterAtom,
  updateGraphEdge: () => updateGraphEdge,
  updateGraphNode: () => updateGraphNode,
  useCreateEdge: () => useCreateEdge,
  useCreateNode: () => useCreateNode,
  useDeleteEdge: () => useDeleteEdge,
  useDeleteNode: () => useDeleteNode,
  useGraphEdges: () => useGraphEdges,
  useGraphNodes: () => useGraphNodes,
  useStorageAdapter: () => useStorageAdapter,
  useUpdateEdge: () => useUpdateEdge,
  useUpdateNode: () => useUpdateNode
});
module.exports = __toCommonJS(index_exports);

// src/db/adapter.ts
var import_jotai = require("jotai");
var InMemoryStorageAdapter = class {
  constructor() {
    __publicField(this, "nodes", /* @__PURE__ */ new Map());
    __publicField(this, "edges", /* @__PURE__ */ new Map());
  }
  async fetchNodes(graphId) {
    return Array.from(this.nodes.values()).filter((n) => n.graph_id === graphId);
  }
  async createNode(graphId, node) {
    const now = (/* @__PURE__ */ new Date()).toISOString();
    const fullNode = {
      id: node.id ?? crypto.randomUUID(),
      graph_id: graphId,
      label: node.label ?? null,
      node_type: node.node_type ?? null,
      configuration: node.configuration ?? null,
      ui_properties: node.ui_properties ?? null,
      data: node.data ?? null,
      created_at: now,
      updated_at: now
    };
    this.nodes.set(fullNode.id, fullNode);
    return fullNode;
  }
  async updateNode(nodeId, updates) {
    const existing = this.nodes.get(nodeId);
    if (!existing) throw new Error(`Node ${nodeId} not found`);
    const updated = {
      ...existing,
      ...updates,
      updated_at: (/* @__PURE__ */ new Date()).toISOString()
    };
    this.nodes.set(nodeId, updated);
    return updated;
  }
  async deleteNode(nodeId) {
    this.nodes.delete(nodeId);
    for (const [edgeId, edge] of this.edges) {
      if (edge.source_node_id === nodeId || edge.target_node_id === nodeId) {
        this.edges.delete(edgeId);
      }
    }
  }
  async fetchEdges(graphId) {
    return Array.from(this.edges.values()).filter((e) => e.graph_id === graphId);
  }
  async createEdge(graphId, edge) {
    const now = (/* @__PURE__ */ new Date()).toISOString();
    const fullEdge = {
      id: edge.id ?? crypto.randomUUID(),
      graph_id: graphId,
      source_node_id: edge.source_node_id ?? "",
      target_node_id: edge.target_node_id ?? "",
      edge_type: edge.edge_type ?? null,
      filter_condition: edge.filter_condition ?? null,
      ui_properties: edge.ui_properties ?? null,
      data: edge.data ?? null,
      created_at: now,
      updated_at: now
    };
    this.edges.set(fullEdge.id, fullEdge);
    return fullEdge;
  }
  async updateEdge(edgeId, updates) {
    const existing = this.edges.get(edgeId);
    if (!existing) throw new Error(`Edge ${edgeId} not found`);
    const updated = {
      ...existing,
      ...updates,
      updated_at: (/* @__PURE__ */ new Date()).toISOString()
    };
    this.edges.set(edgeId, updated);
    return updated;
  }
  async deleteEdge(edgeId) {
    this.edges.delete(edgeId);
  }
  // --- Batch Operations ---
  async createNodes(graphId, nodes) {
    return Promise.all(nodes.map((n) => this.createNode(graphId, n)));
  }
  async deleteNodes(nodeIds) {
    for (const id of nodeIds) {
      await this.deleteNode(id);
    }
  }
  async createEdges(graphId, edges) {
    return Promise.all(edges.map((e) => this.createEdge(graphId, e)));
  }
  async deleteEdges(edgeIds) {
    for (const id of edgeIds) {
      await this.deleteEdge(id);
    }
  }
};
var storageAdapterAtom = (0, import_jotai.atom)(null);

// src/db/supabase-adapter.ts
var SupabaseStorageAdapter = class {
  constructor(client) {
    this.client = client;
  }
  /** Get the underlying Supabase client (for advanced use or backward compat) */
  getClient() {
    return this.client;
  }
  // --- Node Operations ---
  async fetchNodes(graphId) {
    const {
      data,
      error
    } = await this.client.from("nodes").select("*").eq("graph_id", graphId).order("created_at", {
      ascending: true
    });
    if (error) throw error;
    return data || [];
  }
  async createNode(graphId, node) {
    const {
      data,
      error
    } = await this.client.from("nodes").insert({
      graph_id: graphId,
      label: node.label ?? null,
      node_type: node.node_type ?? null,
      configuration: node.configuration ?? null,
      ui_properties: node.ui_properties ?? null,
      data: node.data ?? null
    }).select().single();
    if (error) throw error;
    return data;
  }
  async updateNode(nodeId, updates) {
    const {
      data,
      error
    } = await this.client.from("nodes").update({
      ...updates,
      updated_at: (/* @__PURE__ */ new Date()).toISOString()
    }).eq("id", nodeId).select().single();
    if (error) throw error;
    return data;
  }
  async deleteNode(nodeId) {
    const {
      error
    } = await this.client.from("nodes").delete().eq("id", nodeId);
    if (error) throw error;
  }
  // --- Edge Operations ---
  async fetchEdges(graphId) {
    const {
      data,
      error
    } = await this.client.from("edges").select("*").eq("graph_id", graphId).order("created_at", {
      ascending: true
    });
    if (error) throw error;
    return data || [];
  }
  async createEdge(graphId, edge) {
    const {
      data,
      error
    } = await this.client.from("edges").insert({
      graph_id: graphId,
      source_node_id: edge.source_node_id ?? "",
      target_node_id: edge.target_node_id ?? "",
      edge_type: edge.edge_type ?? null,
      filter_condition: edge.filter_condition ?? null,
      ui_properties: edge.ui_properties ?? null,
      data: edge.data ?? null
    }).select().single();
    if (error) throw error;
    return data;
  }
  async updateEdge(edgeId, updates) {
    const {
      data,
      error
    } = await this.client.from("edges").update({
      ...updates,
      updated_at: (/* @__PURE__ */ new Date()).toISOString()
    }).eq("id", edgeId).select().single();
    if (error) throw error;
    return data;
  }
  async deleteEdge(edgeId) {
    const {
      error
    } = await this.client.from("edges").delete().eq("id", edgeId);
    if (error) throw error;
  }
  // --- Realtime (optional) ---
  subscribe(graphId, onChange) {
    const channel = this.client.channel(`canvas-${graphId}`).on("postgres_changes", {
      event: "*",
      schema: "public",
      table: "nodes",
      filter: `graph_id=eq.${graphId}`
    }, (payload) => {
      onChange({
        type: payload.eventType,
        table: "nodes",
        new: payload.new,
        old: payload.old
      });
    }).on("postgres_changes", {
      event: "*",
      schema: "public",
      table: "edges",
      filter: `graph_id=eq.${graphId}`
    }, (payload) => {
      onChange({
        type: payload.eventType,
        table: "edges",
        new: payload.new,
        old: payload.old
      });
    }).subscribe();
    return () => {
      channel.unsubscribe();
    };
  }
};

// src/db/provider.tsx
var import_react = __toESM(require("react"));
var import_jotai2 = require("jotai");
var import_jotai3 = require("jotai");
var import_jsx_runtime = require("react/jsx-runtime");
var AdapterContext = /* @__PURE__ */ (0, import_react.createContext)(null);
function CanvasDbProvider({
  adapter,
  children
}) {
  const setAdapter = (0, import_jotai2.useSetAtom)(storageAdapterAtom);
  const prevAdapterRef = (0, import_react.useRef)(null);
  const resolved = adapter === prevAdapterRef.current ? prevAdapterRef.current : adapter;
  prevAdapterRef.current = resolved;
  (0, import_react.useEffect)(() => {
    setAdapter(resolved);
    return () => setAdapter(null);
  }, [resolved, setAdapter]);
  return /* @__PURE__ */ (0, import_jsx_runtime.jsx)(AdapterContext, {
    value: resolved,
    children
  });
}
function useStorageAdapter() {
  const contextAdapter = (0, import_react.useContext)(AdapterContext);
  const atomAdapter = (0, import_jotai2.useAtomValue)(storageAdapterAtom);
  const adapter = contextAdapter || atomAdapter;
  if (!adapter) {
    throw new Error("useStorageAdapter must be used within CanvasDbProvider");
  }
  return adapter;
}
var supabaseClientAtom = (0, import_jotai3.atom)(null);
function useSupabaseClient() {
  const client = (0, import_jotai3.useAtomValue)(supabaseClientAtom);
  if (!client) {
    throw new Error("useSupabaseClient: no Supabase client available. Use CanvasDbProvider with a SupabaseStorageAdapter.");
  }
  return client;
}

// src/utils/debug.ts
var import_debug = __toESM(require("debug"));
var NAMESPACE = "canvas";
function createDebug(module2) {
  const base = (0, import_debug.default)(`${NAMESPACE}:${module2}`);
  const warn = (0, import_debug.default)(`${NAMESPACE}:${module2}:warn`);
  const error = (0, import_debug.default)(`${NAMESPACE}:${module2}:error`);
  warn.enabled = true;
  error.enabled = true;
  warn.log = console.warn.bind(console);
  error.log = console.error.bind(console);
  const debugFn = Object.assign(base, {
    warn,
    error
  });
  return debugFn;
}
var debug = {
  graph: {
    node: createDebug("graph:node"),
    edge: createDebug("graph:edge"),
    sync: createDebug("graph:sync")
  },
  ui: {
    selection: createDebug("ui:selection"),
    drag: createDebug("ui:drag"),
    resize: createDebug("ui:resize")
  },
  sync: {
    status: createDebug("sync:status"),
    mutations: createDebug("sync:mutations"),
    queue: createDebug("sync:queue")
  },
  viewport: createDebug("viewport")
};

// src/db/queries/nodes.ts
var debug2 = createDebug("db:nodes");
async function fetchGraphNodes(supabase, graphId) {
  if (!graphId) {
    throw new Error("graphId is required to fetch nodes");
  }
  const {
    data,
    error
  } = await supabase.from("nodes").select("*").eq("graph_id", graphId).order("created_at", {
    ascending: true
  });
  if (error) {
    debug2.error("Error fetching nodes for graph %s: %O", graphId, error);
    throw error;
  }
  return data || [];
}
async function fetchGraphNode(supabase, nodeId) {
  if (!nodeId) {
    throw new Error("nodeId is required to fetch node");
  }
  const {
    data,
    error
  } = await supabase.from("nodes").select("*").eq("id", nodeId).single();
  if (error) {
    if (error.code === "PGRST116") {
      return null;
    }
    debug2.error("Error fetching node %s: %O", nodeId, error);
    throw error;
  }
  return data;
}
async function createGraphNode(supabase, node) {
  const {
    data,
    error
  } = await supabase.from("nodes").insert(node).select().single();
  if (error) {
    debug2.error("Error creating node: %O", error);
    throw error;
  }
  return data;
}
async function updateGraphNode(supabase, nodeId, updates) {
  const {
    data,
    error
  } = await supabase.from("nodes").update({
    ...updates,
    updated_at: (/* @__PURE__ */ new Date()).toISOString()
  }).eq("id", nodeId).select().single();
  if (error) {
    debug2.error("Error updating node %s: %O", nodeId, error);
    throw error;
  }
  return data;
}
async function deleteGraphNode(supabase, nodeId) {
  const {
    error
  } = await supabase.from("nodes").delete().eq("id", nodeId);
  if (error) {
    debug2.error("Error deleting node %s: %O", nodeId, error);
    throw error;
  }
}

// src/db/queries/edges.ts
var debug3 = createDebug("db:edges");
async function fetchGraphEdges(supabase, graphId) {
  if (!graphId) {
    throw new Error("graphId is required to fetch edges");
  }
  const {
    data,
    error
  } = await supabase.from("edges").select("*").eq("graph_id", graphId).order("created_at", {
    ascending: true
  });
  if (error) {
    debug3.error("Error fetching edges for graph %s: %O", graphId, error);
    throw error;
  }
  return data || [];
}
async function createGraphEdge(supabase, edge) {
  const {
    data,
    error
  } = await supabase.from("edges").insert(edge).select().single();
  if (error) {
    debug3.error("Error creating edge: %O", error);
    throw error;
  }
  return data;
}
async function updateGraphEdge(supabase, edgeId, updates) {
  const {
    data,
    error
  } = await supabase.from("edges").update({
    ...updates,
    updated_at: (/* @__PURE__ */ new Date()).toISOString()
  }).eq("id", edgeId).select().single();
  if (error) {
    debug3.error("Error updating edge %s: %O", edgeId, error);
    throw error;
  }
  return data;
}
async function deleteGraphEdge(supabase, edgeId) {
  const {
    error
  } = await supabase.from("edges").delete().eq("id", edgeId);
  if (error) {
    debug3.error("Error deleting edge %s: %O", edgeId, error);
    throw error;
  }
}

// src/db/hooks/keys.ts
var canvasKeys = {
  all: ["canvas"],
  graphs: () => [...canvasKeys.all, "graphs"],
  graph: (graphId) => [...canvasKeys.graphs(), graphId],
  nodes: (graphId) => [...canvasKeys.graph(graphId), "nodes"],
  node: (graphId, nodeId) => [...canvasKeys.nodes(graphId), nodeId],
  edges: (graphId) => [...canvasKeys.graph(graphId), "edges"],
  edge: (graphId, edgeId) => [...canvasKeys.edges(graphId), edgeId]
};

// src/db/hooks/useGraphNodes.ts
var import_compiler_runtime = require("react/compiler-runtime");
var import_react_query = require("@tanstack/react-query");
function useGraphNodes(graphId, t0) {
  const $ = (0, import_compiler_runtime.c)(11);
  let t1;
  if ($[0] !== t0) {
    t1 = t0 === void 0 ? {} : t0;
    $[0] = t0;
    $[1] = t1;
  } else {
    t1 = $[1];
  }
  const options = t1;
  const {
    enabled: t2
  } = options;
  const enabled = t2 === void 0 ? true : t2;
  const supabase = useSupabaseClient();
  let t3;
  if ($[2] !== graphId) {
    t3 = canvasKeys.nodes(graphId || "");
    $[2] = graphId;
    $[3] = t3;
  } else {
    t3 = $[3];
  }
  let t4;
  if ($[4] !== graphId || $[5] !== supabase) {
    t4 = () => fetchGraphNodes(supabase, graphId);
    $[4] = graphId;
    $[5] = supabase;
    $[6] = t4;
  } else {
    t4 = $[6];
  }
  const t5 = enabled && !!graphId;
  let t6;
  if ($[7] !== t3 || $[8] !== t4 || $[9] !== t5) {
    t6 = {
      queryKey: t3,
      queryFn: t4,
      enabled: t5
    };
    $[7] = t3;
    $[8] = t4;
    $[9] = t5;
    $[10] = t6;
  } else {
    t6 = $[10];
  }
  return (0, import_react_query.useQuery)(t6);
}

// src/db/hooks/useGraphEdges.ts
var import_compiler_runtime2 = require("react/compiler-runtime");
var import_react_query2 = require("@tanstack/react-query");
function useGraphEdges(graphId, t0) {
  const $ = (0, import_compiler_runtime2.c)(11);
  let t1;
  if ($[0] !== t0) {
    t1 = t0 === void 0 ? {} : t0;
    $[0] = t0;
    $[1] = t1;
  } else {
    t1 = $[1];
  }
  const options = t1;
  const {
    enabled: t2
  } = options;
  const enabled = t2 === void 0 ? true : t2;
  const supabase = useSupabaseClient();
  let t3;
  if ($[2] !== graphId) {
    t3 = canvasKeys.edges(graphId || "");
    $[2] = graphId;
    $[3] = t3;
  } else {
    t3 = $[3];
  }
  let t4;
  if ($[4] !== graphId || $[5] !== supabase) {
    t4 = () => fetchGraphEdges(supabase, graphId);
    $[4] = graphId;
    $[5] = supabase;
    $[6] = t4;
  } else {
    t4 = $[6];
  }
  const t5 = enabled && !!graphId;
  let t6;
  if ($[7] !== t3 || $[8] !== t4 || $[9] !== t5) {
    t6 = {
      queryKey: t3,
      queryFn: t4,
      enabled: t5
    };
    $[7] = t3;
    $[8] = t4;
    $[9] = t5;
    $[10] = t6;
  } else {
    t6 = $[10];
  }
  return (0, import_react_query2.useQuery)(t6);
}

// src/db/hooks/useUpdateNode.ts
var import_compiler_runtime3 = require("react/compiler-runtime");
var import_react_query3 = require("@tanstack/react-query");
var import_jotai5 = require("jotai");

// src/core/sync-store.ts
var import_jotai4 = require("jotai");
var debug4 = createDebug("sync");
var syncStatusAtom = (0, import_jotai4.atom)("synced");
var pendingMutationsCountAtom = (0, import_jotai4.atom)(0);
var isOnlineAtom = (0, import_jotai4.atom)(typeof navigator !== "undefined" ? navigator.onLine : true);
var lastSyncErrorAtom = (0, import_jotai4.atom)(null);
var lastSyncTimeAtom = (0, import_jotai4.atom)(Date.now());
var mutationQueueAtom = (0, import_jotai4.atom)([]);
var syncStateAtom = (0, import_jotai4.atom)((get) => ({
  status: get(syncStatusAtom),
  pendingMutations: get(pendingMutationsCountAtom),
  lastError: get(lastSyncErrorAtom),
  lastSyncTime: get(lastSyncTimeAtom),
  isOnline: get(isOnlineAtom),
  queuedMutations: get(mutationQueueAtom).length
}));
var startMutationAtom = (0, import_jotai4.atom)(null, (get, set) => {
  const currentCount = get(pendingMutationsCountAtom);
  const newCount = currentCount + 1;
  set(pendingMutationsCountAtom, newCount);
  debug4("Mutation started. Pending count: %d -> %d", currentCount, newCount);
  if (newCount > 0 && get(syncStatusAtom) !== "syncing") {
    set(syncStatusAtom, "syncing");
    debug4("Status -> syncing");
  }
});
var completeMutationAtom = (0, import_jotai4.atom)(null, (get, set, success = true) => {
  const currentCount = get(pendingMutationsCountAtom);
  const newCount = Math.max(0, currentCount - 1);
  set(pendingMutationsCountAtom, newCount);
  debug4("Mutation completed (success: %s). Pending count: %d -> %d", success, currentCount, newCount);
  if (success) {
    set(lastSyncTimeAtom, Date.now());
    if (newCount === 0) {
      set(lastSyncErrorAtom, null);
    }
  }
  if (newCount === 0) {
    const isOnline = get(isOnlineAtom);
    const hasError = get(lastSyncErrorAtom) !== null;
    if (hasError) {
      set(syncStatusAtom, "error");
      debug4("Status -> error");
    } else if (!isOnline) {
      set(syncStatusAtom, "offline");
      debug4("Status -> offline");
    } else {
      set(syncStatusAtom, "synced");
      debug4("Status -> synced");
    }
  }
});
var trackMutationErrorAtom = (0, import_jotai4.atom)(null, (_get, set, error) => {
  set(lastSyncErrorAtom, error);
  debug4("Mutation failed: %s", error);
});
var setOnlineStatusAtom = (0, import_jotai4.atom)(null, (get, set, isOnline) => {
  set(isOnlineAtom, isOnline);
  const pendingCount = get(pendingMutationsCountAtom);
  const hasError = get(lastSyncErrorAtom) !== null;
  const queueLength = get(mutationQueueAtom).length;
  if (pendingCount === 0) {
    if (hasError || queueLength > 0) {
      set(syncStatusAtom, "error");
    } else {
      set(syncStatusAtom, isOnline ? "synced" : "offline");
    }
  }
});
var queueMutationAtom = (0, import_jotai4.atom)(null, (get, set, mutation) => {
  const queue = get(mutationQueueAtom);
  const newMutation = {
    ...mutation,
    id: crypto.randomUUID(),
    timestamp: Date.now(),
    retryCount: 0,
    maxRetries: mutation.maxRetries ?? 3
  };
  const newQueue = [...queue, newMutation];
  set(mutationQueueAtom, newQueue);
  debug4("Queued mutation: %s. Queue size: %d", mutation.type, newQueue.length);
  if (get(pendingMutationsCountAtom) === 0) {
    set(syncStatusAtom, "error");
  }
  return newMutation.id;
});
var dequeueMutationAtom = (0, import_jotai4.atom)(null, (get, set, mutationId) => {
  const queue = get(mutationQueueAtom);
  const newQueue = queue.filter((m) => m.id !== mutationId);
  set(mutationQueueAtom, newQueue);
  debug4("Dequeued mutation: %s. Queue size: %d", mutationId, newQueue.length);
  if (newQueue.length === 0 && get(pendingMutationsCountAtom) === 0 && get(lastSyncErrorAtom) === null) {
    set(syncStatusAtom, get(isOnlineAtom) ? "synced" : "offline");
  }
});
var incrementRetryCountAtom = (0, import_jotai4.atom)(null, (get, set, mutationId) => {
  const queue = get(mutationQueueAtom);
  const newQueue = queue.map((m) => m.id === mutationId ? {
    ...m,
    retryCount: m.retryCount + 1
  } : m);
  set(mutationQueueAtom, newQueue);
});
var getNextQueuedMutationAtom = (0, import_jotai4.atom)((get) => {
  const queue = get(mutationQueueAtom);
  return queue.find((m) => m.retryCount < m.maxRetries) ?? null;
});
var clearMutationQueueAtom = (0, import_jotai4.atom)(null, (get, set) => {
  set(mutationQueueAtom, []);
  debug4("Cleared mutation queue");
  if (get(pendingMutationsCountAtom) === 0 && get(lastSyncErrorAtom) === null) {
    set(syncStatusAtom, get(isOnlineAtom) ? "synced" : "offline");
  }
});

// src/db/hooks/useUpdateNode.ts
function useUpdateNode() {
  const $ = (0, import_compiler_runtime3.c)(18);
  const queryClient = (0, import_react_query3.useQueryClient)();
  const supabase = useSupabaseClient();
  const startMutation = (0, import_jotai5.useSetAtom)(startMutationAtom);
  const completeMutation = (0, import_jotai5.useSetAtom)(completeMutationAtom);
  let t0;
  if ($[0] !== supabase) {
    t0 = async (t12) => {
      const {
        nodeId,
        updates
      } = t12;
      return updateGraphNode(supabase, nodeId, updates);
    };
    $[0] = supabase;
    $[1] = t0;
  } else {
    t0 = $[1];
  }
  let t1;
  if ($[2] !== queryClient || $[3] !== startMutation) {
    t1 = async (t22) => {
      const {
        nodeId: nodeId_0,
        graphId,
        updates: updates_0
      } = t22;
      startMutation();
      await queryClient.cancelQueries({
        queryKey: canvasKeys.nodes(graphId)
      });
      const previousNodes = queryClient.getQueryData(canvasKeys.nodes(graphId));
      if (previousNodes) {
        queryClient.setQueryData(canvasKeys.nodes(graphId), (old) => old?.map((node) => node.id === nodeId_0 ? {
          ...node,
          ...updates_0,
          updated_at: (/* @__PURE__ */ new Date()).toISOString()
        } : node));
      }
      return {
        previousNodes,
        graphId
      };
    };
    $[2] = queryClient;
    $[3] = startMutation;
    $[4] = t1;
  } else {
    t1 = $[4];
  }
  let t2;
  if ($[5] !== completeMutation || $[6] !== queryClient) {
    t2 = (_err, _variables, context) => {
      if (context?.previousNodes) {
        queryClient.setQueryData(canvasKeys.nodes(context.graphId), context.previousNodes);
      }
      completeMutation(false);
    };
    $[5] = completeMutation;
    $[6] = queryClient;
    $[7] = t2;
  } else {
    t2 = $[7];
  }
  let t3;
  if ($[8] !== completeMutation) {
    t3 = () => {
      completeMutation(true);
    };
    $[8] = completeMutation;
    $[9] = t3;
  } else {
    t3 = $[9];
  }
  let t4;
  if ($[10] !== queryClient) {
    t4 = (_data, _error, variables) => {
      queryClient.invalidateQueries({
        queryKey: canvasKeys.nodes(variables.graphId)
      });
    };
    $[10] = queryClient;
    $[11] = t4;
  } else {
    t4 = $[11];
  }
  let t5;
  if ($[12] !== t0 || $[13] !== t1 || $[14] !== t2 || $[15] !== t3 || $[16] !== t4) {
    t5 = {
      mutationFn: t0,
      onMutate: t1,
      onError: t2,
      onSuccess: t3,
      onSettled: t4
    };
    $[12] = t0;
    $[13] = t1;
    $[14] = t2;
    $[15] = t3;
    $[16] = t4;
    $[17] = t5;
  } else {
    t5 = $[17];
  }
  return (0, import_react_query3.useMutation)(t5);
}

// src/db/hooks/useCreateNode.ts
var import_compiler_runtime4 = require("react/compiler-runtime");
var import_react_query4 = require("@tanstack/react-query");
var import_jotai6 = require("jotai");
function useCreateNode() {
  const $ = (0, import_compiler_runtime4.c)(17);
  const queryClient = (0, import_react_query4.useQueryClient)();
  const supabase = useSupabaseClient();
  const startMutation = (0, import_jotai6.useSetAtom)(startMutationAtom);
  const completeMutation = (0, import_jotai6.useSetAtom)(completeMutationAtom);
  let t0;
  if ($[0] !== supabase) {
    t0 = async (node) => createGraphNode(supabase, node);
    $[0] = supabase;
    $[1] = t0;
  } else {
    t0 = $[1];
  }
  let t1;
  if ($[2] !== queryClient || $[3] !== startMutation) {
    t1 = async (node_0) => {
      startMutation();
      await queryClient.cancelQueries({
        queryKey: canvasKeys.nodes(node_0.graph_id)
      });
      const previousNodes = queryClient.getQueryData(canvasKeys.nodes(node_0.graph_id));
      const optimisticNode = {
        ...node_0,
        id: `temp-${Date.now()}`,
        created_at: (/* @__PURE__ */ new Date()).toISOString(),
        updated_at: (/* @__PURE__ */ new Date()).toISOString()
      };
      queryClient.setQueryData(canvasKeys.nodes(node_0.graph_id), (old) => [...old || [], optimisticNode]);
      return {
        previousNodes,
        graphId: node_0.graph_id,
        optimisticId: optimisticNode.id
      };
    };
    $[2] = queryClient;
    $[3] = startMutation;
    $[4] = t1;
  } else {
    t1 = $[4];
  }
  let t2;
  let t3;
  if ($[5] !== completeMutation || $[6] !== queryClient) {
    t2 = (_err, _variables, context) => {
      if (context?.previousNodes) {
        queryClient.setQueryData(canvasKeys.nodes(context.graphId), context.previousNodes);
      }
      completeMutation(false);
    };
    t3 = (newNode, _variables_0, context_0) => {
      if (context_0) {
        queryClient.setQueryData(canvasKeys.nodes(context_0.graphId), (old_0) => old_0?.map((node_1) => node_1.id === context_0.optimisticId ? newNode : node_1));
      }
      completeMutation(true);
    };
    $[5] = completeMutation;
    $[6] = queryClient;
    $[7] = t2;
    $[8] = t3;
  } else {
    t2 = $[7];
    t3 = $[8];
  }
  let t4;
  if ($[9] !== queryClient) {
    t4 = (_data, _error, variables) => {
      queryClient.invalidateQueries({
        queryKey: canvasKeys.nodes(variables.graph_id)
      });
    };
    $[9] = queryClient;
    $[10] = t4;
  } else {
    t4 = $[10];
  }
  let t5;
  if ($[11] !== t0 || $[12] !== t1 || $[13] !== t2 || $[14] !== t3 || $[15] !== t4) {
    t5 = {
      mutationFn: t0,
      onMutate: t1,
      onError: t2,
      onSuccess: t3,
      onSettled: t4
    };
    $[11] = t0;
    $[12] = t1;
    $[13] = t2;
    $[14] = t3;
    $[15] = t4;
    $[16] = t5;
  } else {
    t5 = $[16];
  }
  return (0, import_react_query4.useMutation)(t5);
}

// src/db/hooks/useDeleteNode.ts
var import_compiler_runtime5 = require("react/compiler-runtime");
var import_react_query5 = require("@tanstack/react-query");
var import_jotai7 = require("jotai");
function useDeleteNode() {
  const $ = (0, import_compiler_runtime5.c)(18);
  const queryClient = (0, import_react_query5.useQueryClient)();
  const supabase = useSupabaseClient();
  const startMutation = (0, import_jotai7.useSetAtom)(startMutationAtom);
  const completeMutation = (0, import_jotai7.useSetAtom)(completeMutationAtom);
  let t0;
  if ($[0] !== supabase) {
    t0 = async (t12) => {
      const {
        nodeId
      } = t12;
      return deleteGraphNode(supabase, nodeId);
    };
    $[0] = supabase;
    $[1] = t0;
  } else {
    t0 = $[1];
  }
  let t1;
  if ($[2] !== queryClient || $[3] !== startMutation) {
    t1 = async (t22) => {
      const {
        nodeId: nodeId_0,
        graphId
      } = t22;
      startMutation();
      await queryClient.cancelQueries({
        queryKey: canvasKeys.nodes(graphId)
      });
      const previousNodes = queryClient.getQueryData(canvasKeys.nodes(graphId));
      if (previousNodes) {
        queryClient.setQueryData(canvasKeys.nodes(graphId), (old) => old?.filter((node) => node.id !== nodeId_0));
      }
      return {
        previousNodes,
        graphId
      };
    };
    $[2] = queryClient;
    $[3] = startMutation;
    $[4] = t1;
  } else {
    t1 = $[4];
  }
  let t2;
  if ($[5] !== completeMutation || $[6] !== queryClient) {
    t2 = (_err, _variables, context) => {
      if (context?.previousNodes) {
        queryClient.setQueryData(canvasKeys.nodes(context.graphId), context.previousNodes);
      }
      completeMutation(false);
    };
    $[5] = completeMutation;
    $[6] = queryClient;
    $[7] = t2;
  } else {
    t2 = $[7];
  }
  let t3;
  if ($[8] !== completeMutation) {
    t3 = () => {
      completeMutation(true);
    };
    $[8] = completeMutation;
    $[9] = t3;
  } else {
    t3 = $[9];
  }
  let t4;
  if ($[10] !== queryClient) {
    t4 = (_data, _error, variables) => {
      queryClient.invalidateQueries({
        queryKey: canvasKeys.nodes(variables.graphId)
      });
    };
    $[10] = queryClient;
    $[11] = t4;
  } else {
    t4 = $[11];
  }
  let t5;
  if ($[12] !== t0 || $[13] !== t1 || $[14] !== t2 || $[15] !== t3 || $[16] !== t4) {
    t5 = {
      mutationFn: t0,
      onMutate: t1,
      onError: t2,
      onSuccess: t3,
      onSettled: t4
    };
    $[12] = t0;
    $[13] = t1;
    $[14] = t2;
    $[15] = t3;
    $[16] = t4;
    $[17] = t5;
  } else {
    t5 = $[17];
  }
  return (0, import_react_query5.useMutation)(t5);
}

// src/db/hooks/useUpdateEdge.ts
var import_compiler_runtime6 = require("react/compiler-runtime");
var import_react_query6 = require("@tanstack/react-query");
var import_jotai8 = require("jotai");
function useUpdateEdge() {
  const $ = (0, import_compiler_runtime6.c)(18);
  const queryClient = (0, import_react_query6.useQueryClient)();
  const supabase = useSupabaseClient();
  const startMutation = (0, import_jotai8.useSetAtom)(startMutationAtom);
  const completeMutation = (0, import_jotai8.useSetAtom)(completeMutationAtom);
  let t0;
  if ($[0] !== supabase) {
    t0 = async (t12) => {
      const {
        edgeId,
        updates
      } = t12;
      return updateGraphEdge(supabase, edgeId, updates);
    };
    $[0] = supabase;
    $[1] = t0;
  } else {
    t0 = $[1];
  }
  let t1;
  if ($[2] !== queryClient || $[3] !== startMutation) {
    t1 = async (t22) => {
      const {
        edgeId: edgeId_0,
        graphId,
        updates: updates_0
      } = t22;
      startMutation();
      await queryClient.cancelQueries({
        queryKey: canvasKeys.edges(graphId)
      });
      const previousEdges = queryClient.getQueryData(canvasKeys.edges(graphId));
      if (previousEdges) {
        queryClient.setQueryData(canvasKeys.edges(graphId), (old) => old?.map((edge) => edge.id === edgeId_0 ? {
          ...edge,
          ...updates_0,
          updated_at: (/* @__PURE__ */ new Date()).toISOString()
        } : edge));
      }
      return {
        previousEdges,
        graphId
      };
    };
    $[2] = queryClient;
    $[3] = startMutation;
    $[4] = t1;
  } else {
    t1 = $[4];
  }
  let t2;
  if ($[5] !== completeMutation || $[6] !== queryClient) {
    t2 = (_err, _variables, context) => {
      if (context?.previousEdges) {
        queryClient.setQueryData(canvasKeys.edges(context.graphId), context.previousEdges);
      }
      completeMutation(false);
    };
    $[5] = completeMutation;
    $[6] = queryClient;
    $[7] = t2;
  } else {
    t2 = $[7];
  }
  let t3;
  if ($[8] !== completeMutation) {
    t3 = () => {
      completeMutation(true);
    };
    $[8] = completeMutation;
    $[9] = t3;
  } else {
    t3 = $[9];
  }
  let t4;
  if ($[10] !== queryClient) {
    t4 = (_data, _error, variables) => {
      queryClient.invalidateQueries({
        queryKey: canvasKeys.edges(variables.graphId)
      });
    };
    $[10] = queryClient;
    $[11] = t4;
  } else {
    t4 = $[11];
  }
  let t5;
  if ($[12] !== t0 || $[13] !== t1 || $[14] !== t2 || $[15] !== t3 || $[16] !== t4) {
    t5 = {
      mutationFn: t0,
      onMutate: t1,
      onError: t2,
      onSuccess: t3,
      onSettled: t4
    };
    $[12] = t0;
    $[13] = t1;
    $[14] = t2;
    $[15] = t3;
    $[16] = t4;
    $[17] = t5;
  } else {
    t5 = $[17];
  }
  return (0, import_react_query6.useMutation)(t5);
}

// src/db/hooks/useCreateEdge.ts
var import_compiler_runtime7 = require("react/compiler-runtime");
var import_react_query7 = require("@tanstack/react-query");
var import_jotai9 = require("jotai");
function useCreateEdge() {
  const $ = (0, import_compiler_runtime7.c)(17);
  const queryClient = (0, import_react_query7.useQueryClient)();
  const supabase = useSupabaseClient();
  const startMutation = (0, import_jotai9.useSetAtom)(startMutationAtom);
  const completeMutation = (0, import_jotai9.useSetAtom)(completeMutationAtom);
  let t0;
  if ($[0] !== supabase) {
    t0 = async (edge) => createGraphEdge(supabase, edge);
    $[0] = supabase;
    $[1] = t0;
  } else {
    t0 = $[1];
  }
  let t1;
  if ($[2] !== queryClient || $[3] !== startMutation) {
    t1 = async (edge_0) => {
      startMutation();
      await queryClient.cancelQueries({
        queryKey: canvasKeys.edges(edge_0.graph_id)
      });
      const previousEdges = queryClient.getQueryData(canvasKeys.edges(edge_0.graph_id));
      const optimisticEdge = {
        ...edge_0,
        id: `temp-${Date.now()}`,
        created_at: (/* @__PURE__ */ new Date()).toISOString(),
        updated_at: (/* @__PURE__ */ new Date()).toISOString()
      };
      queryClient.setQueryData(canvasKeys.edges(edge_0.graph_id), (old) => [...old || [], optimisticEdge]);
      return {
        previousEdges,
        graphId: edge_0.graph_id,
        optimisticId: optimisticEdge.id
      };
    };
    $[2] = queryClient;
    $[3] = startMutation;
    $[4] = t1;
  } else {
    t1 = $[4];
  }
  let t2;
  let t3;
  if ($[5] !== completeMutation || $[6] !== queryClient) {
    t2 = (_err, _variables, context) => {
      if (context?.previousEdges) {
        queryClient.setQueryData(canvasKeys.edges(context.graphId), context.previousEdges);
      }
      completeMutation(false);
    };
    t3 = (newEdge, _variables_0, context_0) => {
      if (context_0) {
        queryClient.setQueryData(canvasKeys.edges(context_0.graphId), (old_0) => old_0?.map((edge_1) => edge_1.id === context_0.optimisticId ? newEdge : edge_1));
      }
      completeMutation(true);
    };
    $[5] = completeMutation;
    $[6] = queryClient;
    $[7] = t2;
    $[8] = t3;
  } else {
    t2 = $[7];
    t3 = $[8];
  }
  let t4;
  if ($[9] !== queryClient) {
    t4 = (_data, _error, variables) => {
      queryClient.invalidateQueries({
        queryKey: canvasKeys.edges(variables.graph_id)
      });
    };
    $[9] = queryClient;
    $[10] = t4;
  } else {
    t4 = $[10];
  }
  let t5;
  if ($[11] !== t0 || $[12] !== t1 || $[13] !== t2 || $[14] !== t3 || $[15] !== t4) {
    t5 = {
      mutationFn: t0,
      onMutate: t1,
      onError: t2,
      onSuccess: t3,
      onSettled: t4
    };
    $[11] = t0;
    $[12] = t1;
    $[13] = t2;
    $[14] = t3;
    $[15] = t4;
    $[16] = t5;
  } else {
    t5 = $[16];
  }
  return (0, import_react_query7.useMutation)(t5);
}

// src/db/hooks/useDeleteEdge.ts
var import_compiler_runtime8 = require("react/compiler-runtime");
var import_react_query8 = require("@tanstack/react-query");
var import_jotai10 = require("jotai");
function useDeleteEdge() {
  const $ = (0, import_compiler_runtime8.c)(18);
  const queryClient = (0, import_react_query8.useQueryClient)();
  const supabase = useSupabaseClient();
  const startMutation = (0, import_jotai10.useSetAtom)(startMutationAtom);
  const completeMutation = (0, import_jotai10.useSetAtom)(completeMutationAtom);
  let t0;
  if ($[0] !== supabase) {
    t0 = async (t12) => {
      const {
        edgeId
      } = t12;
      return deleteGraphEdge(supabase, edgeId);
    };
    $[0] = supabase;
    $[1] = t0;
  } else {
    t0 = $[1];
  }
  let t1;
  if ($[2] !== queryClient || $[3] !== startMutation) {
    t1 = async (t22) => {
      const {
        edgeId: edgeId_0,
        graphId
      } = t22;
      startMutation();
      await queryClient.cancelQueries({
        queryKey: canvasKeys.edges(graphId)
      });
      const previousEdges = queryClient.getQueryData(canvasKeys.edges(graphId));
      if (previousEdges) {
        queryClient.setQueryData(canvasKeys.edges(graphId), (old) => old?.filter((edge) => edge.id !== edgeId_0));
      }
      return {
        previousEdges,
        graphId
      };
    };
    $[2] = queryClient;
    $[3] = startMutation;
    $[4] = t1;
  } else {
    t1 = $[4];
  }
  let t2;
  if ($[5] !== completeMutation || $[6] !== queryClient) {
    t2 = (_err, _variables, context) => {
      if (context?.previousEdges) {
        queryClient.setQueryData(canvasKeys.edges(context.graphId), context.previousEdges);
      }
      completeMutation(false);
    };
    $[5] = completeMutation;
    $[6] = queryClient;
    $[7] = t2;
  } else {
    t2 = $[7];
  }
  let t3;
  if ($[8] !== completeMutation) {
    t3 = () => {
      completeMutation(true);
    };
    $[8] = completeMutation;
    $[9] = t3;
  } else {
    t3 = $[9];
  }
  let t4;
  if ($[10] !== queryClient) {
    t4 = (_data, _error, variables) => {
      queryClient.invalidateQueries({
        queryKey: canvasKeys.edges(variables.graphId)
      });
    };
    $[10] = queryClient;
    $[11] = t4;
  } else {
    t4 = $[11];
  }
  let t5;
  if ($[12] !== t0 || $[13] !== t1 || $[14] !== t2 || $[15] !== t3 || $[16] !== t4) {
    t5 = {
      mutationFn: t0,
      onMutate: t1,
      onError: t2,
      onSuccess: t3,
      onSettled: t4
    };
    $[12] = t0;
    $[13] = t1;
    $[14] = t2;
    $[15] = t3;
    $[16] = t4;
    $[17] = t5;
  } else {
    t5 = $[17];
  }
  return (0, import_react_query8.useMutation)(t5);
}
//# sourceMappingURL=index.js.map