@pol-studios/db 1.0.23 → 1.0.24

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (32) hide show
  1. package/dist/{DataLayerContext-ZmLPYR_s.d.ts → DataLayerContext-BnDyYvkg.d.ts} +2 -2
  2. package/dist/auth/context.js +2 -2
  3. package/dist/auth/hooks.js +3 -3
  4. package/dist/auth/index.js +3 -3
  5. package/dist/{chunk-Q7WJEOQ5.js → chunk-2DOYFTN4.js} +27 -31
  6. package/dist/chunk-2DOYFTN4.js.map +1 -0
  7. package/dist/{chunk-3L4HOEXV.js → chunk-7OLNKLII.js} +3 -3
  8. package/dist/{chunk-TSXQTYUG.js → chunk-LABTYQOJ.js} +4 -4
  9. package/dist/{chunk-MBU4KE3V.js → chunk-VWPLASGY.js} +2 -2
  10. package/dist/{chunk-3UYBZHEV.js → chunk-VZMZXL37.js} +2 -2
  11. package/dist/{chunk-KDORWXGS.js → chunk-WHJJDWFT.js} +16 -7
  12. package/dist/chunk-WHJJDWFT.js.map +1 -0
  13. package/dist/hooks/index.d.ts +5 -4
  14. package/dist/hooks/index.js +1 -1
  15. package/dist/{index-2YySlz7X.d.ts → index-B6xGmPRV.d.ts} +1 -1
  16. package/dist/index.d.ts +4 -4
  17. package/dist/index.js +6 -6
  18. package/dist/index.native.d.ts +5 -5
  19. package/dist/index.native.js +6 -6
  20. package/dist/index.web.d.ts +6 -6
  21. package/dist/index.web.js +5 -5
  22. package/dist/types/index.d.ts +2 -2
  23. package/dist/{useDbCount-s-aR9YeV.d.ts → useDbCount-Dn_1uI69.d.ts} +1 -1
  24. package/dist/{useResolveFeedback-DTGcHpCs.d.ts → useResolveFeedback-CBHY2Z1Q.d.ts} +3 -3
  25. package/dist/with-auth/index.js +4 -4
  26. package/package.json +1 -1
  27. package/dist/chunk-KDORWXGS.js.map +0 -1
  28. package/dist/chunk-Q7WJEOQ5.js.map +0 -1
  29. /package/dist/{chunk-3L4HOEXV.js.map → chunk-7OLNKLII.js.map} +0 -0
  30. /package/dist/{chunk-TSXQTYUG.js.map → chunk-LABTYQOJ.js.map} +0 -0
  31. /package/dist/{chunk-MBU4KE3V.js.map → chunk-VWPLASGY.js.map} +0 -0
  32. /package/dist/{chunk-3UYBZHEV.js.map → chunk-VZMZXL37.js.map} +0 -0
@@ -758,6 +758,8 @@ interface DataLayerCoreContextValue {
758
758
  queryClient: QueryClient;
759
759
  /** Database schema */
760
760
  schema: DatabaseSchema;
761
+ /** Sync controls (for PowerSync, no-op for Supabase-only) - stable reference */
762
+ syncControl: SyncControl;
761
763
  }
762
764
  /**
763
765
  * DYNAMIC status context - values that change during runtime
@@ -770,8 +772,6 @@ interface DataLayerStatusContextValue {
770
772
  status: DataLayerStatus;
771
773
  /** Sync status (for PowerSync, no-op for Supabase-only) */
772
774
  syncStatus: SyncStatus;
773
- /** Sync controls (for PowerSync, no-op for Supabase-only) */
774
- syncControl: SyncControl;
775
775
  }
776
776
  /**
777
777
  * Context value for the data layer (combines core and status)
@@ -12,8 +12,8 @@ import {
12
12
  useUserMetadataState,
13
13
  useUserMetadataValue,
14
14
  userMetadataContext
15
- } from "../chunk-3UYBZHEV.js";
16
- import "../chunk-Q7WJEOQ5.js";
15
+ } from "../chunk-VZMZXL37.js";
16
+ import "../chunk-2DOYFTN4.js";
17
17
  import "../chunk-GC3TBUWE.js";
18
18
  import "../chunk-J4ZVCXZ4.js";
19
19
  import "../chunk-OQ7U6EQ3.js";
@@ -11,14 +11,14 @@ import {
11
11
  usePermissionLoading,
12
12
  usePermissionsBatch,
13
13
  useSetupAuth
14
- } from "../chunk-MBU4KE3V.js";
14
+ } from "../chunk-VWPLASGY.js";
15
15
  import {
16
16
  useSetUserMetadata,
17
17
  useUserMetadata,
18
18
  useUserMetadataState,
19
19
  useUserMetadataValue
20
- } from "../chunk-3UYBZHEV.js";
21
- import "../chunk-Q7WJEOQ5.js";
20
+ } from "../chunk-VZMZXL37.js";
21
+ import "../chunk-2DOYFTN4.js";
22
22
  import "../chunk-GC3TBUWE.js";
23
23
  import "../chunk-J4ZVCXZ4.js";
24
24
  import "../chunk-OQ7U6EQ3.js";
@@ -12,7 +12,7 @@ import {
12
12
  usePermissionLoading,
13
13
  usePermissionsBatch,
14
14
  useSetupAuth
15
- } from "../chunk-MBU4KE3V.js";
15
+ } from "../chunk-VWPLASGY.js";
16
16
  import {
17
17
  AuthProvider,
18
18
  PermissionProvider,
@@ -27,8 +27,8 @@ import {
27
27
  useUserMetadataState,
28
28
  useUserMetadataValue,
29
29
  userMetadataContext
30
- } from "../chunk-3UYBZHEV.js";
31
- import "../chunk-Q7WJEOQ5.js";
30
+ } from "../chunk-VZMZXL37.js";
31
+ import "../chunk-2DOYFTN4.js";
32
32
  import {
33
33
  hasAccess,
34
34
  hasAllAccess,
@@ -1483,25 +1483,22 @@ function notifyFailedUploadListeners() {
1483
1483
  failedUploadListeners.forEach((listener) => listener());
1484
1484
  }
1485
1485
  function useSyncControl() {
1486
- const $ = _c7(12);
1487
- const statusContext = useContext3(DataLayerStatusContext);
1486
+ const $ = _c7(11);
1488
1487
  const coreContext = useContext3(DataLayerCoreContext);
1489
- if (!statusContext || !coreContext) {
1488
+ if (!coreContext) {
1490
1489
  throw new Error("useSyncControl must be used within a DataLayerProvider. Make sure you have wrapped your app with <DataLayerProvider>.");
1491
1490
  }
1492
1491
  const {
1493
1492
  syncControl,
1494
- status
1495
- } = statusContext;
1496
- const {
1497
1493
  powerSync
1498
1494
  } = coreContext;
1495
+ const isPowerSyncActive = powerSync !== null;
1499
1496
  const [isAutoRetryPaused, setIsAutoRetryPaused] = useState3(false);
1500
1497
  const failedUploads = useSyncExternalStore(subscribeToFailedUploads, getFailedUploadsSnapshot, _temp);
1501
1498
  let t0;
1502
- if ($[0] !== powerSync || $[1] !== status.currentBackend || $[2] !== syncControl) {
1499
+ if ($[0] !== isPowerSyncActive || $[1] !== syncControl) {
1503
1500
  t0 = async () => {
1504
- if (!powerSync || status.currentBackend !== "powersync") {
1501
+ if (!isPowerSyncActive) {
1505
1502
  console.warn("[useSyncControl] retryFailedUploads called but PowerSync is not available");
1506
1503
  return;
1507
1504
  }
@@ -1513,39 +1510,38 @@ function useSyncControl() {
1513
1510
  notifyFailedUploadListeners();
1514
1511
  await syncControl.triggerSync();
1515
1512
  };
1516
- $[0] = powerSync;
1517
- $[1] = status.currentBackend;
1518
- $[2] = syncControl;
1519
- $[3] = t0;
1513
+ $[0] = isPowerSyncActive;
1514
+ $[1] = syncControl;
1515
+ $[2] = t0;
1520
1516
  } else {
1521
- t0 = $[3];
1517
+ t0 = $[2];
1522
1518
  }
1523
1519
  const retryFailedUploads = t0;
1524
1520
  const clearFailedUploads = _temp2;
1525
1521
  let t1;
1526
- if ($[4] === /* @__PURE__ */ Symbol.for("react.memo_cache_sentinel")) {
1522
+ if ($[3] === /* @__PURE__ */ Symbol.for("react.memo_cache_sentinel")) {
1527
1523
  t1 = () => {
1528
1524
  setIsAutoRetryPaused(true);
1529
1525
  console.log("[useSyncControl] Auto-retry paused");
1530
1526
  };
1531
- $[4] = t1;
1527
+ $[3] = t1;
1532
1528
  } else {
1533
- t1 = $[4];
1529
+ t1 = $[3];
1534
1530
  }
1535
1531
  const pauseAutoRetry = t1;
1536
1532
  let t2;
1537
- if ($[5] === /* @__PURE__ */ Symbol.for("react.memo_cache_sentinel")) {
1533
+ if ($[4] === /* @__PURE__ */ Symbol.for("react.memo_cache_sentinel")) {
1538
1534
  t2 = () => {
1539
1535
  setIsAutoRetryPaused(false);
1540
1536
  console.log("[useSyncControl] Auto-retry resumed");
1541
1537
  };
1542
- $[5] = t2;
1538
+ $[4] = t2;
1543
1539
  } else {
1544
- t2 = $[5];
1540
+ t2 = $[4];
1545
1541
  }
1546
1542
  const resumeAutoRetry = t2;
1547
1543
  let t3;
1548
- if ($[6] === /* @__PURE__ */ Symbol.for("react.memo_cache_sentinel")) {
1544
+ if ($[5] === /* @__PURE__ */ Symbol.for("react.memo_cache_sentinel")) {
1549
1545
  t3 = {
1550
1546
  triggerSync: _temp3,
1551
1547
  startLiveSync: _temp4,
@@ -1558,16 +1554,16 @@ function useSyncControl() {
1558
1554
  resumeAutoRetry: _temp0,
1559
1555
  isAutoRetryPaused: false
1560
1556
  };
1561
- $[6] = t3;
1557
+ $[5] = t3;
1562
1558
  } else {
1563
- t3 = $[6];
1559
+ t3 = $[5];
1564
1560
  }
1565
1561
  const noOpControls = t3;
1566
1562
  let t4;
1567
1563
  bb0: {
1568
- if (powerSync && status.currentBackend === "powersync") {
1564
+ if (isPowerSyncActive) {
1569
1565
  let t5;
1570
- if ($[7] !== failedUploads || $[8] !== isAutoRetryPaused || $[9] !== retryFailedUploads || $[10] !== syncControl) {
1566
+ if ($[6] !== failedUploads || $[7] !== isAutoRetryPaused || $[8] !== retryFailedUploads || $[9] !== syncControl) {
1571
1567
  t5 = {
1572
1568
  ...syncControl,
1573
1569
  retryFailedUploads,
@@ -1577,13 +1573,13 @@ function useSyncControl() {
1577
1573
  resumeAutoRetry,
1578
1574
  isAutoRetryPaused
1579
1575
  };
1580
- $[7] = failedUploads;
1581
- $[8] = isAutoRetryPaused;
1582
- $[9] = retryFailedUploads;
1583
- $[10] = syncControl;
1584
- $[11] = t5;
1576
+ $[6] = failedUploads;
1577
+ $[7] = isAutoRetryPaused;
1578
+ $[8] = retryFailedUploads;
1579
+ $[9] = syncControl;
1580
+ $[10] = t5;
1585
1581
  } else {
1586
- t5 = $[11];
1582
+ t5 = $[10];
1587
1583
  }
1588
1584
  t4 = t5;
1589
1585
  break bb0;
@@ -1678,4 +1674,4 @@ export {
1678
1674
  useSyncControl,
1679
1675
  useOnlineStatus
1680
1676
  };
1681
- //# sourceMappingURL=chunk-Q7WJEOQ5.js.map
1677
+ //# sourceMappingURL=chunk-2DOYFTN4.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/hooks/useDataLayer.ts","../src/providers/DataLayerContext.ts","../src/hooks/useDbQuery.ts","../src/hooks/useDbQueryById.ts","../src/hooks/useAdvanceQuery.ts","../src/hooks/useDbInsert.ts","../src/hooks/useDbUpdate.ts","../src/hooks/useDbUpsert.ts","../src/hooks/useDbDelete.ts","../src/hooks/useDbInfiniteQuery.ts","../src/hooks/useDbCount.ts","../src/hooks/useSyncStatus.ts","../src/hooks/useSyncControl.ts","../src/hooks/useOnlineStatus.ts"],"sourcesContent":["/**\n * V3 Data Layer Hooks\n *\n * Provides access to the V3 data layer context for components.\n * This module provides three hooks for different use cases:\n *\n * - useDataLayerCore(): Stable values only (registry, adapters, clients)\n * Use in query/mutation hooks to avoid re-renders on status changes.\n *\n * - useDataLayerStatus(): Dynamic values only (status, syncStatus, syncControl)\n * Use for UI components that display sync status, online indicator, etc.\n *\n * - useDataLayer(): Combined access (backward compatible)\n * Use when you need both core and status values.\n */\n\nimport { useContext } from \"react\";\nimport { DataLayerContext, DataLayerCoreContext, DataLayerStatusContext, type DataLayerContextValue, type DataLayerCoreContextValue, type DataLayerStatusContextValue } from \"../providers/DataLayerContext\";\n\n// =============================================================================\n// PERFORMANCE-OPTIMIZED HOOKS (Recommended)\n// =============================================================================\n\n/**\n * Hook to access ONLY the stable core values (registry, adapters, clients)\n *\n * PERFORMANCE BENEFIT: Components using this hook will NOT re-render when\n * network status or sync status changes. Use this in query/mutation hooks.\n *\n * Provides access to:\n * - registry: Adapter registry for getting table adapters\n * - getAdapter: Function to get adapter for a specific table\n * - powerSync: PowerSync database instance (null when not available)\n * - supabase: Supabase client (always available)\n * - queryClient: React Query client\n * - schema: Database schema\n *\n * @throws Error if used outside of DataLayerProvider\n *\n * @example\n * const { getAdapter, supabase } = useDataLayerCore();\n * const adapter = getAdapter(\"Task\");\n * // This component won't re-render on sync status changes\n */\nexport function useDataLayerCore() {\n const context = useContext(DataLayerCoreContext);\n if (!context) {\n throw new Error(\"useDataLayerCore must be used within a DataLayerProvider. Make sure you have wrapped your app with <DataLayerProvider>.\");\n }\n return context;\n}\n\n/**\n * Hook to access ONLY the dynamic status values\n *\n * PERFORMANCE BENEFIT: Only components that actually need status information\n * will re-render when status changes. Use for UI components that display\n * sync status, online indicator, pending uploads count, etc.\n *\n * Provides access to:\n * - status: Current initialization and connection status\n * - syncStatus: Sync status for PowerSync\n * - syncControl: Sync controls for PowerSync\n *\n * @throws Error if used outside of DataLayerProvider\n *\n * @example\n * const { status, syncStatus } = useDataLayerStatus();\n *\n * return (\n * <StatusBar\n * isOnline={status.isOnline}\n * pendingUploads={syncStatus.pendingUploads}\n * />\n * );\n */\nexport function useDataLayerStatus() {\n const context = useContext(DataLayerStatusContext);\n if (!context) {\n throw new Error(\"useDataLayerStatus must be used within a DataLayerProvider. Make sure you have wrapped your app with <DataLayerProvider>.\");\n }\n return context;\n}\n\n// =============================================================================\n// BACKWARD COMPATIBLE HOOKS\n// =============================================================================\n\n/**\n * Hook to access the V3 data layer context (combined core + status)\n *\n * NOTE: Consider using useDataLayerCore() or useDataLayerStatus() instead\n * for better render performance. This hook re-renders on ALL status changes.\n *\n * Provides access to:\n * - registry: Adapter registry for getting table adapters\n * - getAdapter: Function to get adapter for a specific table\n * - powerSync: PowerSync database instance (null when not available)\n * - supabase: Supabase client (always available)\n * - queryClient: React Query client\n * - schema: Database schema\n * - status: Current initialization and connection status\n * - syncStatus: Sync status for PowerSync\n * - syncControl: Sync controls for PowerSync\n *\n * @throws Error if used outside of DataLayerProvider\n *\n * @example\n * const { getAdapter, status } = useDataLayer();\n *\n * if (status.isInitialized) {\n * const adapter = getAdapter(\"Task\");\n * // Use adapter...\n * }\n */\nexport function useDataLayer() {\n const context = useContext(DataLayerContext);\n if (!context) {\n throw new Error(\"useDataLayer must be used within a DataLayerProvider. Make sure you have wrapped your app with <DataLayerProvider>.\");\n }\n return context;\n}\n\n/**\n * Hook to safely access data layer context (returns null if not in provider)\n *\n * Use this when you need to check if the data layer is available\n * without throwing an error. Useful for conditional rendering or\n * components that may be rendered outside the provider context.\n *\n * @example\n * const dataLayer = useDataLayerOptional();\n *\n * if (dataLayer) {\n * // Safe to use data layer\n * } else {\n * // Render fallback UI\n * }\n */\nexport function useDataLayerOptional() {\n return useContext(DataLayerContext);\n}\nexport default useDataLayer;","/**\n * V3 Data Layer Context\n *\n * Defines the React context and types for the V3 data layer provider.\n * This context provides access to adapters, sync status, and core instances.\n *\n * PERFORMANCE OPTIMIZATION:\n * The context is split into two separate contexts to prevent unnecessary re-renders:\n * - DataLayerCoreContext: Stable values that don't change after initialization\n * - DataLayerStatusContext: Dynamic values that change during runtime\n *\n * The original DataLayerContext is kept for backward compatibility.\n */\n\nimport { createContext } from \"react\";\nimport type { SupabaseClient } from \"@supabase/supabase-js\";\nimport type { QueryClient } from \"@tanstack/react-query\";\nimport type { AdapterRegistry } from \"../adapters/registry\";\nimport type { PowerSyncDatabase } from \"../query/executor\";\nimport type { DatabaseSchema, SyncStatus, SyncControl } from \"../core/types\";\nimport type { BackendStatus, AutoDetectionResult } from \"../adapters/auto-detector\";\nimport type { TableDataAdapter } from \"../adapters/types\";\n\n// =============================================================================\n// Status Types\n// =============================================================================\n\n/**\n * Status of the data layer initialization\n */\nexport interface DataLayerStatus {\n /** Whether the data layer is fully initialized */\n isInitialized: boolean;\n /** Current active backend */\n currentBackend: \"powersync\" | \"supabase\" | null;\n /** PowerSync connection status */\n powerSyncStatus: BackendStatus;\n /** Whether device is online */\n isOnline: boolean;\n /** Last auto-detection result */\n lastDetection: AutoDetectionResult | null;\n /** Initialization error if any */\n error: Error | null;\n /** Whether initial sync has completed (from PowerSync) */\n hasSynced: boolean;\n}\n\n// =============================================================================\n// Split Context Types (Performance Optimization)\n// =============================================================================\n\n/**\n * STABLE core context - values that don't change after initialization\n *\n * Use useDataLayerCore() to access these values in query/mutation hooks\n * to avoid re-renders when sync status changes.\n */\nexport interface DataLayerCoreContextValue {\n /** Adapter registry for getting table adapters */\n registry: AdapterRegistry;\n /** Get adapter for a specific table */\n getAdapter: (table: string) => TableDataAdapter;\n /** PowerSync database instance (null when not available) */\n powerSync: PowerSyncDatabase | null;\n /** Supabase client (always available) */\n supabase: SupabaseClient;\n /** React Query client */\n queryClient: QueryClient;\n /** Database schema */\n schema: DatabaseSchema;\n /** Sync controls (for PowerSync, no-op for Supabase-only) - stable reference */\n syncControl: SyncControl;\n}\n\n/**\n * DYNAMIC status context - values that change during runtime\n *\n * Use useDataLayerStatus() for UI components that display sync status,\n * online indicator, etc. Components using this WILL re-render when status changes.\n */\nexport interface DataLayerStatusContextValue {\n /** Current status */\n status: DataLayerStatus;\n /** Sync status (for PowerSync, no-op for Supabase-only) */\n syncStatus: SyncStatus;\n}\n\n// =============================================================================\n// Combined Context Value Type (Backward Compatibility)\n// =============================================================================\n\n/**\n * Context value for the data layer (combines core and status)\n *\n * @deprecated Prefer using useDataLayerCore() or useDataLayerStatus() for better performance.\n * This combined interface is kept for backward compatibility.\n */\nexport interface DataLayerContextValue {\n /** Adapter registry for getting table adapters */\n registry: AdapterRegistry;\n\n /** Get adapter for a specific table */\n getAdapter: (table: string) => TableDataAdapter;\n\n /** PowerSync database instance (null when not available) */\n powerSync: PowerSyncDatabase | null;\n\n /** Supabase client (always available) */\n supabase: SupabaseClient;\n\n /** React Query client */\n queryClient: QueryClient;\n\n /** Database schema */\n schema: DatabaseSchema;\n\n /** Current status */\n status: DataLayerStatus;\n\n /** Sync status (for PowerSync, no-op for Supabase-only) */\n syncStatus: SyncStatus;\n\n /** Sync controls (for PowerSync, no-op for Supabase-only) */\n syncControl: SyncControl;\n}\n\n// =============================================================================\n// Context Creation\n// =============================================================================\n\n/**\n * STABLE Core context - values that don't change after initialization\n *\n * Use useDataLayerCore() hook to access. Components consuming this context\n * will NOT re-render when sync status or network status changes.\n */\nexport const DataLayerCoreContext = createContext<DataLayerCoreContextValue | null>(null);\nDataLayerCoreContext.displayName = \"DataLayerCoreContext\";\n\n/**\n * DYNAMIC Status context - values that change during runtime\n *\n * Use useDataLayerStatus() hook to access. Components consuming this context\n * WILL re-render when sync status or network status changes.\n */\nexport const DataLayerStatusContext = createContext<DataLayerStatusContextValue | null>(null);\nDataLayerStatusContext.displayName = \"DataLayerStatusContext\";\n\n/**\n * Combined data layer context (backward compatibility)\n *\n * @deprecated Prefer using DataLayerCoreContext or DataLayerStatusContext for better performance.\n * Provides access to the V3 data layer throughout the React component tree.\n * Must be accessed via the useDataLayer hook or similar consumer.\n */\nexport const DataLayerContext = createContext<DataLayerContextValue | null>(null);\nDataLayerContext.displayName = \"DataLayerContext\";","/**\n * V3 useDbQuery Hook\n *\n * React hook for querying multiple records from a table.\n * Works identically whether PowerSync or Supabase is the backend.\n * Uses React Query for state management and caching.\n *\n * Types are automatically inferred from table names when you augment\n * the DatabaseTypes interface with your app's Database type.\n *\n * @example\n * // In your app's types/db.d.ts:\n * declare module \"@pol-studios/db\" {\n * interface DatabaseTypes {\n * database: import(\"@/database.types\").Database;\n * }\n * }\n *\n * // Then usage auto-infers types:\n * const { data } = useDbQuery(\"EquipmentFixtureUnit\", { ... });\n * // data is typed as Tables<\"EquipmentFixtureUnit\">[]\n */\n\nimport { useMemo, useEffect, useCallback } from \"react\";\nimport { useQuery } from \"@tanstack/react-query\";\nimport { useDataLayerCore, useDataLayerStatus } from \"./useDataLayer\";\nimport type { QueryOptions } from \"../core/types\";\n\n// =============================================================================\n// Module Augmentation Interface\n// =============================================================================\n\n/**\n * Augment this interface in your app to enable automatic type inference.\n *\n * @example\n * // In types/db.d.ts\n * declare module \"@pol-studios/db\" {\n * interface DatabaseTypes {\n * database: import(\"@/database.types\").Database;\n * }\n * }\n */\n// eslint-disable-next-line @typescript-eslint/no-empty-interface\nexport interface DatabaseTypes {}\n\n// =============================================================================\n// Database Type Helpers\n// =============================================================================\n\n/**\n * The configured Database type, or a generic fallback\n */\ntype ConfiguredDatabase = DatabaseTypes extends {\n database: infer DB;\n} ? DB : GenericSchema;\n\n/**\n * Generic schema structure for fallback\n */\ntype GenericSchema = {\n public: {\n Tables: Record<string, {\n Row: Record<string, unknown>;\n }>;\n Views: Record<string, {\n Row: Record<string, unknown>;\n }>;\n };\n [schema: string]: {\n Tables: Record<string, {\n Row: Record<string, unknown>;\n }>;\n Views?: Record<string, {\n Row: Record<string, unknown>;\n }>;\n };\n};\n\n/**\n * Default schema from Database (usually \"public\")\n */\ntype DefaultSchema = ConfiguredDatabase extends {\n public: infer S;\n} ? S : never;\n\n/**\n * Extract all valid table names from the default schema\n */\nexport type PublicTableNames = DefaultSchema extends {\n Tables: infer T;\n} ? keyof T & string : string;\n\n/**\n * Extract all valid schema names\n */\nexport type SchemaNames = keyof ConfiguredDatabase & string;\n\n/**\n * Extract table names for a specific schema\n */\nexport type SchemaTableNames<S extends string> = ConfiguredDatabase extends { [K in S]: {\n Tables: infer T;\n} } ? keyof T & string : string;\n\n/**\n * Build dot notation strings for all schema.table combinations\n */\ntype SchemaDotTable = { [S in SchemaNames]: S extends \"public\" ? never // Skip public schema for dot notation\n: `${S}.${SchemaTableNames<S>}` }[SchemaNames];\n\n/**\n * Table identifier - provides autocomplete for valid table names\n *\n * Supports:\n * - \"TableName\" - public schema tables\n * - \"schema.TableName\" - dot notation for other schemas\n * - { schema, table } - object format for other schemas\n */\nexport type TableIdentifier = PublicTableNames | SchemaDotTable | { [S in Exclude<SchemaNames, \"public\">]: {\n schema: S;\n table: SchemaTableNames<S>;\n} }[Exclude<SchemaNames, \"public\">];\n\n/**\n * Resolve row type from a table identifier\n *\n * Supports:\n * - \"TableName\" → public schema\n * - \"schema.TableName\" → specified schema (dot notation)\n * - { schema: \"schema\", table: \"TableName\" } → specified schema (object)\n */\nexport type ResolveRowType<T extends TableIdentifier> = T extends string ?\n// Check for dot notation first (e.g., \"core.Profile\")\nT extends `${infer Schema}.${infer Table}` ? ConfiguredDatabase extends { [K in Schema]: {\n Tables: { [K2 in Table]: {\n Row: infer R;\n } };\n} } ? R : Record<string, unknown> :\n// Plain string - look in public schema\nDefaultSchema extends {\n Tables: { [K in T]: {\n Row: infer R;\n } };\n} ? R : DefaultSchema extends {\n Views: { [K in T]: {\n Row: infer R;\n } };\n} ? R : Record<string, unknown> : T extends {\n schema: infer S;\n table: infer TN;\n} ?\n// Object with schema - look in specified schema\nS extends string ? TN extends string ? ConfiguredDatabase extends { [K in S]: {\n Tables: { [K2 in TN]: {\n Row: infer R;\n } };\n} } ? R : Record<string, unknown> : Record<string, unknown> : Record<string, unknown> : Record<string, unknown>;\n\n// =============================================================================\n// Types\n// =============================================================================\n\n/**\n * Options for useDbQuery hook\n */\nexport interface UseDbQueryOptions extends Omit<QueryOptions, \"enabled\"> {\n /** Whether the query is enabled (default: true) */\n enabled?: boolean;\n /**\n * React Query stale time in ms\n * Default depends on backend:\n * - PowerSync (offline): 0 - always refetch from SQLite (disk is fast)\n * - Supabase (online): 30000 - use normal caching\n */\n staleTime?: number;\n /** React Query gcTime (cache time) in ms (default: 300000 - 5 minutes) */\n gcTime?: number;\n /** Whether to refetch on window focus (default: true) */\n refetchOnWindowFocus?: boolean;\n /**\n * Whether to refetch on mount\n * Default depends on backend:\n * - PowerSync (offline): \"always\" - always query SQLite\n * - Supabase (online): true - refetch if stale\n */\n refetchOnMount?: boolean | \"always\";\n /** Whether to enable real-time subscriptions (if adapter supports) */\n realtime?: boolean;\n /** If true, returns single item instead of array (for compatibility with V2) */\n single?: boolean;\n}\n\n/**\n * Result from useDbQuery hook\n */\nexport interface UseDbQueryResult<T> {\n /** Query data */\n data: T[] | undefined;\n /** Whether query is loading (initial load) */\n isLoading: boolean;\n /** Whether query is in pending state */\n isPending: boolean;\n /** Whether query is currently fetching (including refetch) */\n isFetching: boolean;\n /** Whether query is currently refetching (alias for isFetching for V2 compatibility) */\n isRefetching: boolean;\n /** Whether query completed successfully */\n isSuccess: boolean;\n /** Whether query errored */\n isError: boolean;\n /** Query error if any */\n error: Error | null;\n /** Refetch the query */\n refetch: () => Promise<void>;\n /** Total count (if pagination is used) */\n count?: number;\n /** Whether data is stale */\n isStale: boolean;\n /** Timestamp of last data update */\n dataUpdatedAt: number | null;\n}\n\n// =============================================================================\n// Helper Functions\n// =============================================================================\n\n/**\n * Build a query key for React Query\n *\n * Creates a stable, unique key for caching based on table and query options.\n * Keys are namespaced with \"v3\" to avoid collisions with V2 queries.\n *\n * NOTE: Backend is intentionally NOT included in the key. The data is the same\n * regardless of whether it comes from Supabase or PowerSync - switching backends\n * should NOT invalidate the cache. This is critical for offline-first UX.\n */\nfunction buildQueryKey(table: string, options: UseDbQueryOptions): unknown[] {\n return [\"v3\", \"query\", table, options.select ?? \"*\", JSON.stringify(options.where ?? {}), JSON.stringify(options.orderBy ?? []), options.limit, options.offset];\n}\n\n/**\n * Serialize query options for dependency tracking\n */\nfunction serializeQueryOptions(options: UseDbQueryOptions): string {\n return JSON.stringify({\n select: options.select,\n where: options.where,\n orderBy: options.orderBy,\n limit: options.limit,\n offset: options.offset\n });\n}\n\n// =============================================================================\n// Hook Implementation\n// =============================================================================\n\n/**\n * Helper to resolve table name from TableIdentifier\n */\nfunction resolveTableName(table: TableIdentifier): string {\n if (typeof table === \"string\") {\n return table;\n }\n return `${table.schema}.${table.table}`;\n}\n\n/**\n * Hook for querying multiple records from a table\n *\n * This hook provides a unified interface for querying data that works\n * identically whether the backend is PowerSync (offline-first) or\n * Supabase (online-only). It uses React Query for caching and state management.\n *\n * Features:\n * - Automatic type inference from table names (when DatabaseTypes is augmented)\n * - Automatic backend selection based on DataLayerProvider configuration\n * - React Query integration for caching, deduplication, and background updates\n * - Optional real-time subscriptions (when adapter supports it)\n * - Pagination support with count\n *\n * @param table - Table name (string) or { schema, table } object\n * @param options - Query options (select, where, orderBy, limit, offset, etc.)\n * @returns Query result with data, loading states, error, and refetch function\n *\n * @example\n * // Basic query - types auto-inferred from table name\n * const { data } = useDbQuery(\"EquipmentFixtureUnit\");\n * // data is typed as Tables<\"EquipmentFixtureUnit\">[]\n *\n * @example\n * // Query from non-public schema\n * const { data } = useDbQuery({ schema: \"core\", table: \"Profile\" });\n * // data is typed as Tables<{ schema: \"core\" }, \"Profile\">[]\n *\n * @example\n * // Query with filters and sorting\n * const { data } = useDbQuery(\"Task\", {\n * select: \"*, Project(*)\",\n * where: { status: \"active\" },\n * orderBy: [{ field: \"createdAt\", direction: \"desc\" }],\n * limit: 10,\n * });\n */\n/**\n * Main hook signature with auto-inferred types from table identifiers\n */\nexport function useDbQuery<T extends TableIdentifier>(table: T, options?: UseDbQueryOptions): UseDbQueryResult<ResolveRowType<T>>;\n\n/**\n * Overload for explicit type parameter when table name is a string literal\n */\nexport function useDbQuery<T>(table: string, options?: UseDbQueryOptions): UseDbQueryResult<T>;\n\n// Implementation signature - uses any to satisfy both overloads\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport function useDbQuery<T = any>(table: TableIdentifier | string, options: UseDbQueryOptions = {}): UseDbQueryResult<T> {\n const tableName = typeof table === \"string\" ? table : resolveTableName(table as TableIdentifier);\n const {\n registry,\n queryClient\n } = useDataLayerCore();\n const {\n status\n } = useDataLayerStatus();\n\n // Determine if using PowerSync (offline/SQLite) or Supabase (online)\n const isPowerSync = status.currentBackend === \"powersync\";\n\n // Backend-aware defaults:\n // - PowerSync: staleTime=0, refetchOnMount=\"always\" (SQLite is fast, always query disk)\n // - Supabase: staleTime=30000, refetchOnMount=true (use normal React Query caching)\n // - realtime: PowerSync=true (use watch() for live updates), Supabase=false (no streaming)\n const {\n enabled = true,\n staleTime = isPowerSync ? 0 : 30000,\n gcTime = 300000,\n // 5 minutes - keep in memory for instant display while refetching\n refetchOnWindowFocus = true,\n refetchOnMount = isPowerSync ? \"always\" : true,\n realtime = isPowerSync,\n // Enable real-time subscriptions by default for PowerSync\n ...queryOptions\n } = options;\n\n // Get adapter for this table\n const adapter = useMemo(() => {\n if (!status.isInitialized) return null;\n try {\n return registry.getAdapter(tableName);\n } catch {\n return null;\n }\n }, [registry, tableName, status.isInitialized, status.currentBackend]);\n\n // Build query key - memoized to prevent unnecessary re-renders\n // Backend is NOT included - cache persists across backend switches for offline-first UX\n const queryKey = useMemo(() => buildQueryKey(tableName, options), [tableName, serializeQueryOptions(options)]);\n\n // Memoize query options to prevent re-creating on every render\n const memoizedQueryOptions = useMemo(() => ({\n select: queryOptions.select,\n where: queryOptions.where,\n orderBy: queryOptions.orderBy,\n limit: queryOptions.limit,\n offset: queryOptions.offset\n }), [serializeQueryOptions(queryOptions)]);\n\n // Query function\n const queryFn = useCallback(async () => {\n if (!adapter) {\n throw new Error(`Adapter not available for table: ${tableName}`);\n }\n const result = await adapter.query(tableName, memoizedQueryOptions);\n return result;\n }, [adapter, tableName, memoizedQueryOptions]);\n\n // Execute query with React Query\n // Backend-aware caching strategy:\n // - PowerSync: SQLite is source of truth, always refetch from disk (it's fast)\n // - Supabase: Use normal React Query caching to avoid unnecessary network requests\n const query = useQuery({\n queryKey,\n queryFn,\n enabled: enabled && status.isInitialized && adapter !== null,\n staleTime,\n gcTime,\n refetchOnWindowFocus,\n refetchOnMount\n });\n\n // Set up real-time subscription if enabled\n useEffect(() => {\n if (!realtime || !adapter?.subscribe || !status.isInitialized) {\n return;\n }\n\n // Skip first callback - initial query is already running\n let isFirstCallback = true;\n const unsubscribe = adapter.subscribe(tableName, memoizedQueryOptions, data => {\n // Skip the first callback since initial query handles it\n if (isFirstCallback) {\n isFirstCallback = false;\n return;\n }\n\n // Check if query has relations (contains parentheses like \"Table(*)\")\n const hasRelations = memoizedQueryOptions.select?.includes(\"(\");\n if (hasRelations) {\n // Has relations - subscription returns flat data without nested relations\n // Invalidate to trigger a full refetch with relations\n queryClient.invalidateQueries({\n queryKey\n });\n } else {\n // No relations - safe to directly update cache with flat data\n queryClient.setQueryData(queryKey, {\n data,\n count: data.length\n });\n }\n });\n return () => {\n unsubscribe();\n };\n }, [realtime, adapter, tableName, memoizedQueryOptions, queryClient, queryKey, status.isInitialized]);\n\n // Build refetch function\n const refetch = useCallback(async () => {\n await query.refetch();\n }, [query]);\n return {\n data: query.data?.data as T[] | undefined,\n isLoading: query.isLoading,\n isPending: query.isPending,\n isFetching: query.isFetching,\n isRefetching: query.isFetching,\n // Alias for V2 compatibility\n isSuccess: query.isSuccess,\n isError: query.isError,\n error: query.error as Error | null,\n refetch,\n count: query.data?.count,\n isStale: query.isStale,\n dataUpdatedAt: query.dataUpdatedAt ?? null\n };\n}\nexport default useDbQuery;","/**\n * V3 useDbQueryById Hook\n *\n * React hook for querying a single record by ID from a table.\n * Works identically whether PowerSync or Supabase is the backend.\n * Uses React Query for state management and caching.\n */\n\nimport { useCallback, useMemo } from \"react\";\nimport { useQuery } from \"@tanstack/react-query\";\nimport { useDataLayerCore, useDataLayerStatus } from \"./useDataLayer\";\nimport type { WhereClause } from \"../core/types\";\n\n// =============================================================================\n// Types\n// =============================================================================\n\n/**\n * Options for useDbQueryById hook\n */\nexport interface UseDbQueryByIdOptions {\n /** Columns to select (Supabase-style select string) */\n select?: string;\n /** Whether the query is enabled (default: true if id is provided) */\n enabled?: boolean;\n /** React Query stale time in ms (default: 30000) */\n staleTime?: number;\n}\n\n/**\n * Result from useDbQueryById hook\n */\nexport interface UseDbQueryByIdResult<T> {\n /** Query data (undefined while loading, null if not found) */\n data: T | null | undefined;\n /** Whether query is loading (initial load) */\n isLoading: boolean;\n /** Whether query is in pending state */\n isPending: boolean;\n /** Whether query is currently fetching (including refetch) */\n isFetching: boolean;\n /** Query error if any */\n error: Error | null;\n /** Refetch the query */\n refetch: () => Promise<void>;\n}\n\n// =============================================================================\n// Helper Functions\n// =============================================================================\n\n/**\n * Build a query key for React Query\n *\n * Creates a stable, unique key for caching based on table, ID, and select.\n * Keys are namespaced with \"v3\" to avoid collisions with V2 queries.\n */\nfunction buildQueryKey(table: string, id: string | number | null | undefined, select?: string): unknown[] {\n return [\"v3\", \"queryById\", table, id, select ?? \"*\"];\n}\n\n// =============================================================================\n// Hook Implementation\n// =============================================================================\n\n/**\n * Hook for querying a single record by ID\n *\n * This hook provides a unified interface for fetching a single record that works\n * identically whether the backend is PowerSync (offline-first) or\n * Supabase (online-only). It uses React Query for caching and state management.\n *\n * Features:\n * - Automatic backend selection based on DataLayerProvider configuration\n * - React Query integration for caching, deduplication, and background updates\n * - Automatic disabling when ID is null/undefined\n * - Fallback to query with where clause if adapter doesn't support queryById\n * - Type-safe with generic type parameter\n *\n * @param table - The table name to query\n * @param id - The record ID (query is disabled if null/undefined)\n * @param options - Query options (select, enabled, staleTime)\n * @returns Query result with data, loading states, error, and refetch function\n *\n * @example\n * // Basic query by ID\n * const { data, isLoading, error } = useDbQueryById<Task>(\"Task\", taskId);\n *\n * @example\n * // Query with relations\n * const { data, isLoading, error } = useDbQueryById<Task>(\"Task\", taskId, {\n * select: \"*, Project(*), AssignedUser:User(*)\",\n * });\n *\n * @example\n * // Conditional query based on other state\n * const { data } = useDbQueryById<Project>(\"Project\", selectedProjectId, {\n * enabled: hasPermission && !!selectedProjectId,\n * });\n *\n * @example\n * // With custom stale time\n * const { data } = useDbQueryById<User>(\"User\", userId, {\n * staleTime: 60000, // 1 minute\n * });\n */\nexport function useDbQueryById<T = Record<string, unknown>>(table: string, id: string | number | null | undefined, options: UseDbQueryByIdOptions = {}): UseDbQueryByIdResult<T> {\n const {\n registry\n } = useDataLayerCore();\n const {\n status\n } = useDataLayerStatus();\n const {\n select,\n enabled = id != null,\n staleTime = 30000\n } = options;\n\n // Get adapter for this table\n const adapter = useMemo(() => {\n if (!status.isInitialized) return null;\n try {\n return registry.getAdapter(table);\n } catch {\n return null;\n }\n }, [registry, table, status.isInitialized, status.currentBackend]);\n\n // Build query key - memoized to prevent unnecessary re-renders\n const queryKey = useMemo(() => buildQueryKey(table, id, select), [table, id, select]);\n\n // Query function\n const queryFn = useCallback(async (): Promise<T | null> => {\n if (!adapter) {\n throw new Error(`Adapter not available for table: ${table}`);\n }\n if (id == null) {\n return null;\n }\n\n // Use queryById if available, otherwise fall back to query with where\n if (adapter.queryById) {\n return adapter.queryById<T>(table, String(id), {\n select\n });\n }\n\n // Fallback: use query with where clause\n const result = await adapter.query<T>(table, {\n select,\n where: {\n id\n } as WhereClause,\n limit: 1\n });\n return result.data[0] ?? null;\n }, [adapter, table, id, select]);\n\n // Execute query with React Query\n const query = useQuery({\n queryKey,\n queryFn,\n enabled: enabled && status.isInitialized && adapter !== null && id != null,\n staleTime\n });\n\n // Build refetch function\n const refetch = useCallback(async () => {\n await query.refetch();\n }, [query]);\n return {\n data: query.data,\n isLoading: query.isLoading,\n isPending: query.isPending,\n isFetching: query.isFetching,\n error: query.error as Error | null,\n refetch\n };\n}\nexport default useDbQueryById;","/**\n * V3 useAdvanceQuery Hook\n *\n * Hybrid query hook that combines PowerSync (local SQLite) with edge function filtering.\n * - When NO filters active: Uses PowerSync for fast local queries that stay in sync\n * - When filters active: Uses edge function for complex filtering\n *\n * This provides the best of both worlds:\n * - Fast, reactive local queries via PowerSync\n * - Complex filtering, natural language queries, and aggregations via edge function\n *\n * @example\n * const [result, filters, setFilters] = useAdvanceQuery<Equipment[]>(\n * \"EquipmentFixtureUnit\",\n * {\n * select: \"*, EquipmentFixtureUnitControl(*)\",\n * where: { projectDatabaseId: 123 },\n * orderBy: [{ field: \"unitNumber\", direction: \"asc\" }],\n * filterKey: \"equipment-filters\",\n * }\n * );\n */\n\nimport { Dispatch, SetStateAction, useCallback, useMemo, useRef, useState, useEffect } from \"react\";\nimport { useQuery } from \"@tanstack/react-query\";\nimport { useDataLayerCore, useDataLayerStatus } from \"./useDataLayer\";\nimport { useDbQuery } from \"./useDbQuery\";\nimport type { TableIdentifier, ResolveRowType, UseDbQueryOptions } from \"./useDbQuery\";\nimport type { QueryOptions } from \"../core/types\";\nimport { useSessionStorageState } from \"@pol-studios/hooks/storage\";\nimport { isUsable, omit } from \"@pol-studios/utils\";\nimport { getSupabaseUrl } from \"../config\";\nimport useSupabase from \"../useSupabase\";\n\n// =============================================================================\n// Types (re-exported from useDbAdvanceQuery for compatibility)\n// =============================================================================\n\nexport type FilterOperator = \"=\" | \">\" | \">=\" | \"<\" | \"<=\" | \"contains\" | \"ilike\" | \"is\" | \"in\" | \"ai_search\";\nexport interface Filter {\n id: string;\n field: string;\n op: FilterOperator;\n value: string | number | string[] | number[] | boolean | null;\n not?: boolean;\n similarity?: number;\n where?: string;\n display?: string;\n}\nexport interface FilterGroup {\n id: string;\n op: \"AND\" | \"OR\";\n filters: Array<Filter | FilterGroup>;\n not?: boolean;\n}\nexport interface Pagination {\n offset?: number;\n limit?: number;\n}\nexport interface Sort {\n field: string;\n direction: \"asc\" | \"desc\";\n}\nexport interface QueryState extends FilterGroup {\n pagination?: Pagination;\n sort?: Sort[];\n distinctOn?: string[];\n naturalLanguageQuery?: string;\n isReady: boolean;\n}\nexport interface ClarificationQuestion {\n question: string;\n suggestions: Array<{\n interpretation: string;\n field_path: string;\n example: string;\n confidence: number;\n }>;\n}\n\n// =============================================================================\n// Options and Result Types\n// =============================================================================\n\nexport interface UseAdvanceQueryOptions extends Omit<UseDbQueryOptions, \"realtime\"> {\n /** Key for persisting filter state (required for filter state persistence) */\n filterKey: string;\n /** Initial filter state */\n initialFilters?: QueryState;\n /** Timeout for edge function requests in ms (default: 15000) */\n timeout?: number;\n /** Count mode: \"exact\" | \"estimated\" | \"\" (default: \"exact\") */\n count?: \"exact\" | \"estimated\" | \"\";\n /**\n * Whether to enable real-time subscriptions\n * - PowerSync path: Uses watch() for reactive updates (default: true when PowerSync)\n * - Edge function path: Uses Supabase realtime to invalidate query on changes\n */\n realtime?: boolean;\n}\nexport interface UseAdvanceQueryResult<T> {\n data: T[] | undefined;\n isLoading: boolean;\n isPending: boolean;\n isFetching: boolean;\n isRefetching: boolean;\n isSuccess: boolean;\n isError: boolean;\n error: Error | null;\n refetch: () => Promise<void>;\n count?: number;\n clarification?: ClarificationQuestion;\n}\n\n// =============================================================================\n// Default Filter State\n// =============================================================================\n\nconst createDefaultFilterState = (): QueryState => ({\n id: \"root\",\n op: \"AND\",\n filters: [],\n pagination: undefined,\n sort: [],\n isReady: true\n});\n\n// =============================================================================\n// Hook Implementation\n// =============================================================================\n\n/**\n * Hybrid advance query hook\n *\n * Uses PowerSync (local SQLite) when no filters are active for fast, reactive queries.\n * Falls back to edge function when filters are active for complex filtering.\n */\nexport function useAdvanceQuery<T extends TableIdentifier>(table: T, options: UseAdvanceQueryOptions): [UseAdvanceQueryResult<ResolveRowType<T>>, QueryState, Dispatch<SetStateAction<QueryState>>];\nexport function useAdvanceQuery<T>(table: string, options: UseAdvanceQueryOptions): [UseAdvanceQueryResult<T>, QueryState, Dispatch<SetStateAction<QueryState>>];\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport function useAdvanceQuery<T = any>(table: TableIdentifier | string, options: UseAdvanceQueryOptions): [UseAdvanceQueryResult<T>, QueryState, Dispatch<SetStateAction<QueryState>>] {\n const tableName = typeof table === \"string\" ? table : `${(table as {\n schema: string;\n table: string;\n }).schema}.${(table as {\n schema: string;\n table: string;\n }).table}`;\n const {\n registry,\n queryClient\n } = useDataLayerCore();\n const {\n status\n } = useDataLayerStatus();\n const supabase = useSupabase();\n const {\n filterKey,\n initialFilters,\n enabled = true,\n timeout = 15000,\n count = \"exact\",\n realtime,\n select,\n where,\n orderBy,\n limit,\n offset,\n ...restOptions\n } = options;\n\n // Determine if realtime should be enabled\n // Default: true for PowerSync path, false for edge function path\n const isPowerSync = status.currentBackend === \"powersync\";\n const realtimeEnabled = realtime ?? isPowerSync;\n\n // ==========================================================================\n // Filter State Management\n // ==========================================================================\n\n const defaultFilterState = useMemo(() => initialFilters ?? createDefaultFilterState(),\n // eslint-disable-next-line react-hooks/exhaustive-deps\n [] // Only compute once\n );\n const [filtersRaw, setFiltersRaw] = useSessionStorageState<QueryState>(filterKey, defaultFilterState);\n const filters = filtersRaw ?? defaultFilterState;\n\n // Type-safe setFilters wrapper\n const setFilters: Dispatch<SetStateAction<QueryState>> = useCallback(action => {\n if (typeof action === \"function\") {\n setFiltersRaw(prev => action(prev ?? defaultFilterState));\n } else {\n setFiltersRaw(action);\n }\n }, [setFiltersRaw, defaultFilterState]);\n\n // ==========================================================================\n // Determine Query Strategy\n // ==========================================================================\n\n const hasAdvancedFilters = useMemo(() => (filters?.filters?.length ?? 0) > 0 || !!filters?.naturalLanguageQuery, [filters?.filters?.length, filters?.naturalLanguageQuery]);\n\n // Use direct DB query (via useDbQuery) when: no advanced filters\n // useDbQuery handles adapter selection (PowerSync vs Supabase) based on sync status\n // This ensures queries use Supabase during initial sync when PowerSync hasn't synced yet\n const usePowerSyncPath = !hasAdvancedFilters;\n\n // ==========================================================================\n // PowerSync Query (no filters path)\n // ==========================================================================\n\n // Convert orderBy from Sort[] to QueryOptions orderBy format\n const powerSyncOrderBy = useMemo(() => {\n if (filters?.sort && filters.sort.length > 0) {\n return filters.sort.map(s => ({\n field: s.field,\n direction: s.direction\n }));\n }\n return orderBy;\n }, [filters?.sort, orderBy]);\n const powerSyncResult = useDbQuery<T>(table as string, {\n select,\n where,\n orderBy: powerSyncOrderBy,\n limit: filters?.pagination?.limit ?? limit,\n offset: filters?.pagination?.offset ?? offset,\n enabled: enabled && usePowerSyncPath && filters?.isReady !== false,\n realtime: realtimeEnabled // Enable watch() subscriptions for reactive updates\n });\n\n // ==========================================================================\n // Edge Function Query (with filters path)\n // ==========================================================================\n\n const [extraData, setExtraData] = useState<{\n count?: number;\n key?: string;\n }>({});\n const edgeFunctionQueryKey = useMemo(() => [\"v3\", \"advance-query\", tableName, select, JSON.stringify(where), JSON.stringify(filters), status.currentBackend], [tableName, select, where, filters, status.currentBackend]);\n const edgeFunctionResult = useQuery<{\n data: T[];\n count?: number;\n clarification?: ClarificationQuestion;\n }>({\n queryKey: edgeFunctionQueryKey,\n queryFn: async ({\n signal\n }) => {\n const {\n data: {\n session\n }\n } = await supabase.auth.getSession();\n if (!session?.access_token) {\n throw new Error(\"No active session\");\n }\n const controller = new AbortController();\n signal.addEventListener(\"abort\", () => controller.abort());\n const timeoutId = setTimeout(() => controller.abort(), timeout);\n try {\n // Build filter body\n const filterBody = {\n id: filters.id || \"root\",\n op: filters.op || \"AND\",\n not: filters.not,\n filters: filters.filters || []\n };\n\n // Parse base where conditions into filters\n const baseFilters: Filter[] = [];\n if (where) {\n Object.entries(where).forEach(([field, value]) => {\n if (value !== undefined && value !== null) {\n if (typeof value === \"object\" && \"in\" in value) {\n // Handle { in: [...] } syntax\n baseFilters.push({\n id: `base-${field}`,\n field,\n op: \"in\",\n value: (value as {\n in: unknown[];\n }).in as string[] | number[]\n });\n } else {\n baseFilters.push({\n id: `base-${field}`,\n field,\n op: \"=\",\n value: value as string | number | boolean | null\n });\n }\n }\n });\n }\n\n // Combine base filters with user filters\n const combinedFilters = [...baseFilters, ...filterBody.filters];\n const currentKey = `${tableName}${select}${JSON.stringify(omit(filters, [\"pagination\", \"isReady\"]))}`;\n const res = await fetch(`${getSupabaseUrl()}/functions/v1/query?forceDenoVersion=2`, {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n Authorization: `Bearer ${session.access_token}`\n },\n body: JSON.stringify({\n table: tableName,\n schema: \"public\",\n select: select ?? \"*\",\n filters: {\n id: filterBody.id,\n op: filterBody.op,\n not: filterBody.not,\n filters: combinedFilters\n },\n pagination: filters.pagination,\n sort: filters.sort || orderBy?.map(o => ({\n field: o.field,\n direction: o.direction\n })),\n distinctOn: filters.distinctOn,\n naturalLanguageQuery: filters.naturalLanguageQuery,\n count: currentKey === extraData.key ? \"\" : count\n }),\n signal: controller.signal\n });\n if (!res.ok) {\n const errorData = await res.json();\n const errorMessage = typeof errorData?.error === \"string\" ? errorData.error : errorData?.error?.message || errorData?.message || \"Query failed\";\n throw new Error(errorMessage);\n }\n const result = await res.json();\n\n // Handle clarification response\n if (result.clarification) {\n return {\n data: [] as T[],\n count: 0,\n clarification: result.clarification\n };\n }\n setExtraData(prev => ({\n count: prev.key === currentKey ? prev.count : result.count,\n key: currentKey\n }));\n return {\n data: result.data as T[],\n count: result.count\n };\n } finally {\n clearTimeout(timeoutId);\n }\n },\n enabled: enabled && !usePowerSyncPath && filters?.isReady !== false,\n staleTime: 30000,\n gcTime: 300000,\n refetchOnMount: true,\n refetchOnWindowFocus: false\n });\n\n // ==========================================================================\n // Supabase Realtime Subscription (edge function path only)\n // ==========================================================================\n\n // When realtime is enabled and using edge function path,\n // subscribe to Supabase realtime to invalidate query on changes\n useEffect(() => {\n // Only set up realtime for edge function path when realtime is enabled\n if (!realtimeEnabled || usePowerSyncPath || !enabled) {\n return;\n }\n\n // Build filter for the subscription based on where clause\n const channel = supabase.channel(`advance-query-${tableName}-${filterKey}`).on(\"postgres_changes\", {\n event: \"*\",\n // Listen to INSERT, UPDATE, DELETE\n schema: \"public\",\n table: tableName\n // Note: We can't easily filter by complex where clauses,\n // so we invalidate on any change to the table\n }, () => {\n // Invalidate the query to trigger a refetch\n queryClient.invalidateQueries({\n queryKey: edgeFunctionQueryKey\n });\n }).subscribe();\n return () => {\n supabase.removeChannel(channel);\n };\n }, [realtimeEnabled, usePowerSyncPath, enabled, supabase, tableName, filterKey, queryClient, edgeFunctionQueryKey]);\n\n // ==========================================================================\n // Combine Results\n // ==========================================================================\n\n const result = useMemo((): UseAdvanceQueryResult<T> => {\n if (usePowerSyncPath) {\n // PowerSync path\n return {\n data: powerSyncResult.data as T[] | undefined,\n isLoading: powerSyncResult.isLoading,\n isPending: powerSyncResult.isPending,\n isFetching: powerSyncResult.isFetching,\n isRefetching: powerSyncResult.isRefetching,\n isSuccess: powerSyncResult.isSuccess,\n isError: powerSyncResult.isError,\n error: powerSyncResult.error,\n refetch: powerSyncResult.refetch,\n count: powerSyncResult.count ?? powerSyncResult.data?.length\n };\n }\n\n // Edge function path\n return {\n data: edgeFunctionResult.data?.data,\n isLoading: edgeFunctionResult.isLoading,\n isPending: edgeFunctionResult.isPending,\n isFetching: edgeFunctionResult.isFetching,\n isRefetching: edgeFunctionResult.isFetching,\n isSuccess: edgeFunctionResult.isSuccess,\n isError: edgeFunctionResult.isError,\n error: edgeFunctionResult.error as Error | null,\n refetch: async () => {\n await edgeFunctionResult.refetch();\n },\n count: edgeFunctionResult.data?.count ?? extraData.count,\n clarification: edgeFunctionResult.data?.clarification\n };\n }, [usePowerSyncPath, powerSyncResult, edgeFunctionResult, extraData.count]);\n return [result, filters, setFilters];\n}\nexport default useAdvanceQuery;","import { c as _c } from \"react/compiler-runtime\";\n/**\n * V3 useDbInsert Hook\n *\n * React hook for inserting records into a table using the V3 adapter pattern.\n * Integrates with React Query for mutation management and cache invalidation.\n */\n\nimport { useCallback, useMemo } from \"react\";\nimport { useMutation, useQueryClient } from \"@tanstack/react-query\";\nimport { useDataLayerCore, useDataLayerStatus } from \"./useDataLayer\";\n\n/**\n * Options for useDbInsert hook\n */\nexport interface UseDbInsertOptions<T> {\n /** Callback when insert succeeds */\n onSuccess?: (data: T) => void;\n /** Callback when insert fails */\n onError?: (error: Error) => void;\n /** Tables to invalidate after successful insert */\n invalidateTables?: string[];\n}\n\n/**\n * Result from useDbInsert hook\n */\nexport interface UseDbInsertResult<T> {\n /** Trigger insert (fire and forget) */\n mutate: (data: Partial<T>) => void;\n /** Trigger insert and await result */\n mutateAsync: (data: Partial<T>) => Promise<T>;\n /** Whether mutation is in progress */\n isPending: boolean;\n /** Mutation error if any */\n error: Error | null;\n /** Reset mutation state */\n reset: () => void;\n /** Last successful data */\n data: T | undefined;\n}\n\n/**\n * Hook for inserting records into a table\n *\n * Uses the V3 adapter pattern to route inserts to the appropriate backend\n * (PowerSync, Supabase, or Cached) based on table configuration.\n *\n * @param table - The table name to insert into\n * @param options - Optional configuration for callbacks and cache invalidation\n * @returns Mutation result with mutate/mutateAsync functions\n *\n * @example\n * ```typescript\n * const { mutateAsync, isPending } = useDbInsert<Task>(\"Task\");\n * const newTask = await mutateAsync({ title: \"New Task\", status: \"pending\" });\n * ```\n *\n * @example\n * ```typescript\n * // With options\n * const { mutate } = useDbInsert<Project>(\"Project\", {\n * onSuccess: (data) => console.log(\"Created:\", data),\n * onError: (error) => console.error(\"Failed:\", error),\n * invalidateTables: [\"Project\", \"ProjectSummary\"],\n * });\n * ```\n */\nexport function useDbInsert(table, t0) {\n const $ = _c(28);\n let t1;\n if ($[0] !== t0) {\n t1 = t0 === undefined ? {} : t0;\n $[0] = t0;\n $[1] = t1;\n } else {\n t1 = $[1];\n }\n const options = t1;\n const {\n registry\n } = useDataLayerCore();\n const {\n status\n } = useDataLayerStatus();\n const queryClient = useQueryClient();\n const {\n onSuccess,\n onError,\n invalidateTables: t2\n } = options;\n let t3;\n if ($[2] !== t2 || $[3] !== table) {\n t3 = t2 === undefined ? [table] : t2;\n $[2] = t2;\n $[3] = table;\n $[4] = t3;\n } else {\n t3 = $[4];\n }\n const invalidateTables = t3;\n let t4;\n bb0: {\n if (!status.isInitialized) {\n t4 = null;\n break bb0;\n }\n try {\n let t5;\n if ($[5] !== registry || $[6] !== table) {\n t5 = registry.getAdapter(table);\n $[5] = registry;\n $[6] = table;\n $[7] = t5;\n } else {\n t5 = $[7];\n }\n t4 = t5;\n } catch {\n t4 = null;\n }\n }\n const adapter = t4;\n let t5;\n if ($[8] !== adapter || $[9] !== table) {\n t5 = async data => {\n if (!adapter) {\n throw new Error(`Adapter not available for table: ${table}`);\n }\n return adapter.insert(table, data);\n };\n $[8] = adapter;\n $[9] = table;\n $[10] = t5;\n } else {\n t5 = $[10];\n }\n const mutationFn = t5;\n let t6;\n if ($[11] !== invalidateTables || $[12] !== onSuccess || $[13] !== queryClient) {\n t6 = data_0 => {\n invalidateTables.forEach(t => {\n queryClient.invalidateQueries({\n predicate: query => query.queryKey[0] === \"v3\" && query.queryKey[2] === t\n });\n });\n onSuccess?.(data_0);\n };\n $[11] = invalidateTables;\n $[12] = onSuccess;\n $[13] = queryClient;\n $[14] = t6;\n } else {\n t6 = $[14];\n }\n let t7;\n if ($[15] !== onError) {\n t7 = error => {\n onError?.(error instanceof Error ? error : new Error(String(error)));\n };\n $[15] = onError;\n $[16] = t7;\n } else {\n t7 = $[16];\n }\n let t8;\n if ($[17] !== mutationFn || $[18] !== t6 || $[19] !== t7) {\n t8 = {\n mutationFn,\n onSuccess: t6,\n onError: t7\n };\n $[17] = mutationFn;\n $[18] = t6;\n $[19] = t7;\n $[20] = t8;\n } else {\n t8 = $[20];\n }\n const mutation = useMutation(t8);\n const t9 = mutation.error as Error | null;\n let t10;\n if ($[21] !== mutation.data || $[22] !== mutation.isPending || $[23] !== mutation.mutate || $[24] !== mutation.mutateAsync || $[25] !== mutation.reset || $[26] !== t9) {\n t10 = {\n mutate: mutation.mutate,\n mutateAsync: mutation.mutateAsync,\n isPending: mutation.isPending,\n error: t9,\n reset: mutation.reset,\n data: mutation.data\n };\n $[21] = mutation.data;\n $[22] = mutation.isPending;\n $[23] = mutation.mutate;\n $[24] = mutation.mutateAsync;\n $[25] = mutation.reset;\n $[26] = t9;\n $[27] = t10;\n } else {\n t10 = $[27];\n }\n return t10;\n}\nexport default useDbInsert;","import { c as _c } from \"react/compiler-runtime\";\n/**\n * V3 useDbUpdate Hook\n *\n * React hook for updating records in a table using the V3 adapter pattern.\n * Integrates with React Query for mutation management, cache invalidation,\n * and optional optimistic updates.\n */\n\nimport { useCallback, useMemo } from \"react\";\nimport { useMutation, useQueryClient } from \"@tanstack/react-query\";\nimport { useDataLayerCore, useDataLayerStatus } from \"./useDataLayer\";\n\n/**\n * Options for useDbUpdate hook\n */\nexport interface UseDbUpdateOptions<T> {\n /** Callback when update succeeds */\n onSuccess?: (data: T) => void;\n /** Callback when update fails */\n onError?: (error: Error) => void;\n /** Tables to invalidate after successful update */\n invalidateTables?: string[];\n /** Enable optimistic updates */\n optimistic?: boolean;\n}\n\n/**\n * Result from useDbUpdate hook\n */\nexport interface UseDbUpdateResult<T> {\n /** Trigger update (fire and forget) */\n mutate: (params: {\n id: string;\n data: Partial<T>;\n }) => void;\n /** Trigger update and await result */\n mutateAsync: (params: {\n id: string;\n data: Partial<T>;\n }) => Promise<T>;\n /** Whether mutation is in progress */\n isPending: boolean;\n /** Mutation error if any */\n error: Error | null;\n /** Reset mutation state */\n reset: () => void;\n /** Last successful data */\n data: T | undefined;\n}\n\n/**\n * Hook for updating records in a table\n *\n * Uses the V3 adapter pattern to route updates to the appropriate backend\n * (PowerSync, Supabase, or Cached) based on table configuration.\n *\n * @param table - The table name to update records in\n * @param options - Optional configuration for callbacks, cache invalidation, and optimistic updates\n * @returns Mutation result with mutate/mutateAsync functions\n *\n * @example\n * ```typescript\n * const { mutateAsync, isPending } = useDbUpdate<Task>(\"Task\");\n * const updated = await mutateAsync({ id: taskId, data: { status: \"completed\" } });\n * ```\n *\n * @example\n * ```typescript\n * // With optimistic updates\n * const { mutate } = useDbUpdate<Project>(\"Project\", {\n * optimistic: true,\n * onSuccess: (data) => console.log(\"Updated:\", data),\n * onError: (error) => console.error(\"Failed:\", error),\n * });\n * ```\n */\nexport function useDbUpdate(table, t0) {\n const $ = _c(35);\n let t1;\n if ($[0] !== t0) {\n t1 = t0 === undefined ? {} : t0;\n $[0] = t0;\n $[1] = t1;\n } else {\n t1 = $[1];\n }\n const options = t1;\n const {\n registry\n } = useDataLayerCore();\n const {\n status\n } = useDataLayerStatus();\n const queryClient = useQueryClient();\n const {\n onSuccess,\n onError,\n invalidateTables: t2,\n optimistic: t3\n } = options;\n let t4;\n if ($[2] !== t2 || $[3] !== table) {\n t4 = t2 === undefined ? [table] : t2;\n $[2] = t2;\n $[3] = table;\n $[4] = t4;\n } else {\n t4 = $[4];\n }\n const invalidateTables = t4;\n const optimistic = t3 === undefined ? false : t3;\n let t5;\n bb0: {\n if (!status.isInitialized) {\n t5 = null;\n break bb0;\n }\n try {\n let t6;\n if ($[5] !== registry || $[6] !== table) {\n t6 = registry.getAdapter(table);\n $[5] = registry;\n $[6] = table;\n $[7] = t6;\n } else {\n t6 = $[7];\n }\n t5 = t6;\n } catch {\n t5 = null;\n }\n }\n const adapter = t5;\n let t6;\n if ($[8] !== adapter || $[9] !== table) {\n t6 = async params => {\n if (!adapter) {\n throw new Error(`Adapter not available for table: ${table}`);\n }\n return adapter.update(table, params.id, params.data);\n };\n $[8] = adapter;\n $[9] = table;\n $[10] = t6;\n } else {\n t6 = $[10];\n }\n const mutationFn = t6;\n let t7;\n if ($[11] !== optimistic || $[12] !== queryClient || $[13] !== table) {\n t7 = optimistic ? async () => {\n await queryClient.cancelQueries({\n predicate: query => query.queryKey[0] === \"v3\" && query.queryKey[2] === table\n });\n const previousData = queryClient.getQueriesData({\n predicate: query_0 => query_0.queryKey[0] === \"v3\" && query_0.queryKey[2] === table\n });\n return {\n previousData\n };\n } : undefined;\n $[11] = optimistic;\n $[12] = queryClient;\n $[13] = table;\n $[14] = t7;\n } else {\n t7 = $[14];\n }\n let t8;\n if ($[15] !== invalidateTables || $[16] !== onSuccess || $[17] !== queryClient) {\n t8 = data => {\n invalidateTables.forEach(t => {\n queryClient.invalidateQueries({\n predicate: query_1 => query_1.queryKey[0] === \"v3\" && query_1.queryKey[2] === t\n });\n });\n onSuccess?.(data);\n };\n $[15] = invalidateTables;\n $[16] = onSuccess;\n $[17] = queryClient;\n $[18] = t8;\n } else {\n t8 = $[18];\n }\n let t9;\n if ($[19] !== onError || $[20] !== optimistic || $[21] !== queryClient) {\n t9 = (error, _variables, context) => {\n if (optimistic && context?.previousData) {\n context.previousData.forEach(t10 => {\n const [queryKey, data_0] = t10;\n queryClient.setQueryData(queryKey, data_0);\n });\n }\n onError?.(error instanceof Error ? error : new Error(String(error)));\n };\n $[19] = onError;\n $[20] = optimistic;\n $[21] = queryClient;\n $[22] = t9;\n } else {\n t9 = $[22];\n }\n let t10;\n if ($[23] !== mutationFn || $[24] !== t7 || $[25] !== t8 || $[26] !== t9) {\n t10 = {\n mutationFn,\n onMutate: t7,\n onSuccess: t8,\n onError: t9\n };\n $[23] = mutationFn;\n $[24] = t7;\n $[25] = t8;\n $[26] = t9;\n $[27] = t10;\n } else {\n t10 = $[27];\n }\n const mutation = useMutation(t10);\n const t11 = mutation.error as Error | null;\n let t12;\n if ($[28] !== mutation.data || $[29] !== mutation.isPending || $[30] !== mutation.mutate || $[31] !== mutation.mutateAsync || $[32] !== mutation.reset || $[33] !== t11) {\n t12 = {\n mutate: mutation.mutate,\n mutateAsync: mutation.mutateAsync,\n isPending: mutation.isPending,\n error: t11,\n reset: mutation.reset,\n data: mutation.data\n };\n $[28] = mutation.data;\n $[29] = mutation.isPending;\n $[30] = mutation.mutate;\n $[31] = mutation.mutateAsync;\n $[32] = mutation.reset;\n $[33] = t11;\n $[34] = t12;\n } else {\n t12 = $[34];\n }\n return t12;\n}\nexport default useDbUpdate;","import { c as _c } from \"react/compiler-runtime\";\n/**\n * V3 useDbUpsert Hook\n *\n * React hook for upserting (insert or update) records in a table using the V3 adapter pattern.\n * Integrates with React Query for mutation management and cache invalidation.\n */\n\nimport { useCallback, useMemo } from \"react\";\nimport { useMutation, useQueryClient } from \"@tanstack/react-query\";\nimport { useDataLayerCore, useDataLayerStatus } from \"./useDataLayer\";\n\n/**\n * Options for useDbUpsert hook\n */\nexport interface UseDbUpsertOptions<T> {\n /** Callback when upsert succeeds */\n onSuccess?: (data: T) => void;\n /** Callback when upsert fails */\n onError?: (error: Error) => void;\n /** Tables to invalidate after successful upsert */\n invalidateTables?: string[];\n}\n\n/**\n * Result from useDbUpsert hook\n */\nexport interface UseDbUpsertResult<T> {\n /** Trigger upsert (fire and forget) */\n mutate: (data: Partial<T>) => void;\n /** Trigger upsert and await result */\n mutateAsync: (data: Partial<T>) => Promise<T>;\n /** Whether mutation is in progress */\n isPending: boolean;\n /** Mutation error if any */\n error: Error | null;\n /** Reset mutation state */\n reset: () => void;\n /** Last successful data */\n data: T | undefined;\n}\n\n/**\n * Hook for upserting (insert or update) records in a table\n *\n * Uses the V3 adapter pattern to route upserts to the appropriate backend\n * (PowerSync, Supabase, or Cached) based on table configuration.\n *\n * If the record has an ID and exists, it will be updated.\n * Otherwise, a new record will be inserted.\n *\n * @param table - The table name to upsert into\n * @param options - Optional configuration for callbacks and cache invalidation\n * @returns Mutation result with mutate/mutateAsync functions\n *\n * @example\n * ```typescript\n * const { mutateAsync, isPending } = useDbUpsert<Task>(\"Task\");\n * const task = await mutateAsync({ id: existingId, title: \"Updated Title\" });\n * ```\n *\n * @example\n * ```typescript\n * // Insert if no ID, update if ID exists\n * const { mutate } = useDbUpsert<Setting>(\"Setting\", {\n * onSuccess: (data) => console.log(\"Upserted:\", data),\n * invalidateTables: [\"Setting\", \"UserPreferences\"],\n * });\n *\n * // This will insert (no id)\n * mutate({ key: \"theme\", value: \"dark\" });\n *\n * // This will update (has id)\n * mutate({ id: \"setting-123\", key: \"theme\", value: \"light\" });\n * ```\n */\nexport function useDbUpsert(table, t0) {\n const $ = _c(28);\n let t1;\n if ($[0] !== t0) {\n t1 = t0 === undefined ? {} : t0;\n $[0] = t0;\n $[1] = t1;\n } else {\n t1 = $[1];\n }\n const options = t1;\n const {\n registry\n } = useDataLayerCore();\n const {\n status\n } = useDataLayerStatus();\n const queryClient = useQueryClient();\n const {\n onSuccess,\n onError,\n invalidateTables: t2\n } = options;\n let t3;\n if ($[2] !== t2 || $[3] !== table) {\n t3 = t2 === undefined ? [table] : t2;\n $[2] = t2;\n $[3] = table;\n $[4] = t3;\n } else {\n t3 = $[4];\n }\n const invalidateTables = t3;\n let t4;\n bb0: {\n if (!status.isInitialized) {\n t4 = null;\n break bb0;\n }\n ;\n try {\n let t6;\n if ($[5] !== registry || $[6] !== table) {\n t6 = registry.getAdapter(table);\n $[5] = registry;\n $[6] = table;\n $[7] = t6;\n } else {\n t6 = $[7];\n }\n const resolvedAdapter = t6;\n t4 = resolvedAdapter;\n } catch (t5) {\n const error = t5;\n if (__DEV__) {\n console.warn(`[useDbUpsert] Failed to get adapter for table \"${table}\":`, error);\n }\n t4 = null;\n }\n }\n const adapter = t4;\n let t5;\n if ($[8] !== adapter || $[9] !== table) {\n t5 = async data => {\n if (__DEV__) {\n console.log(`[useDbUpsert] mutationFn called for table \"${table}\":`, {\n adapterName: adapter?.name ?? \"null\",\n dataKeys: Object.keys(data),\n hasId: \"id\" in data\n });\n }\n if (!adapter) {\n throw new Error(`Adapter not available for table: ${table}`);\n }\n const result = await adapter.upsert(table, data);\n if (__DEV__) {\n console.log(`[useDbUpsert] upsert completed for table \"${table}\":`, {\n adapterName: adapter.name,\n resultId: (result as Record<string, unknown>)?.id ?? \"unknown\"\n });\n }\n return result;\n };\n $[8] = adapter;\n $[9] = table;\n $[10] = t5;\n } else {\n t5 = $[10];\n }\n const mutationFn = t5;\n let t6;\n if ($[11] !== invalidateTables || $[12] !== onSuccess || $[13] !== queryClient) {\n t6 = data_0 => {\n invalidateTables.forEach(t => {\n queryClient.invalidateQueries({\n predicate: query => query.queryKey[0] === \"v3\" && query.queryKey[2] === t\n });\n });\n onSuccess?.(data_0);\n };\n $[11] = invalidateTables;\n $[12] = onSuccess;\n $[13] = queryClient;\n $[14] = t6;\n } else {\n t6 = $[14];\n }\n let t7;\n if ($[15] !== onError) {\n t7 = error_0 => {\n onError?.(error_0 instanceof Error ? error_0 : new Error(String(error_0)));\n };\n $[15] = onError;\n $[16] = t7;\n } else {\n t7 = $[16];\n }\n let t8;\n if ($[17] !== mutationFn || $[18] !== t6 || $[19] !== t7) {\n t8 = {\n mutationFn,\n onSuccess: t6,\n onError: t7\n };\n $[17] = mutationFn;\n $[18] = t6;\n $[19] = t7;\n $[20] = t8;\n } else {\n t8 = $[20];\n }\n const mutation = useMutation(t8);\n const t9 = mutation.error as Error | null;\n let t10;\n if ($[21] !== mutation.data || $[22] !== mutation.isPending || $[23] !== mutation.mutate || $[24] !== mutation.mutateAsync || $[25] !== mutation.reset || $[26] !== t9) {\n t10 = {\n mutate: mutation.mutate,\n mutateAsync: mutation.mutateAsync,\n isPending: mutation.isPending,\n error: t9,\n reset: mutation.reset,\n data: mutation.data\n };\n $[21] = mutation.data;\n $[22] = mutation.isPending;\n $[23] = mutation.mutate;\n $[24] = mutation.mutateAsync;\n $[25] = mutation.reset;\n $[26] = t9;\n $[27] = t10;\n } else {\n t10 = $[27];\n }\n return t10;\n}\nexport default useDbUpsert;","import { c as _c } from \"react/compiler-runtime\";\n/**\n * V3 useDbDelete Hook\n *\n * React hook for deleting records from a table using the V3 adapter pattern.\n * Integrates with React Query for mutation management, cache invalidation,\n * and optional optimistic deletes.\n */\n\nimport { useCallback, useMemo } from \"react\";\nimport { useMutation, useQueryClient } from \"@tanstack/react-query\";\nimport { useDataLayerCore, useDataLayerStatus } from \"./useDataLayer\";\n\n/**\n * Options for useDbDelete hook\n */\nexport interface UseDbDeleteOptions {\n /** Callback when delete succeeds */\n onSuccess?: () => void;\n /** Callback when delete fails */\n onError?: (error: Error) => void;\n /** Tables to invalidate after successful delete */\n invalidateTables?: string[];\n /** Enable optimistic delete */\n optimistic?: boolean;\n}\n\n/**\n * Result from useDbDelete hook\n */\nexport interface UseDbDeleteResult {\n /** Trigger delete (fire and forget) */\n mutate: (id: string) => void;\n /** Trigger delete and await completion */\n mutateAsync: (id: string) => Promise<void>;\n /** Whether mutation is in progress */\n isPending: boolean;\n /** Mutation error if any */\n error: Error | null;\n /** Reset mutation state */\n reset: () => void;\n}\n\n/**\n * Hook for deleting records from a table\n *\n * Uses the V3 adapter pattern to route deletes to the appropriate backend\n * (PowerSync, Supabase, or Cached) based on table configuration.\n *\n * @param table - The table name to delete from\n * @param options - Optional configuration for callbacks, cache invalidation, and optimistic deletes\n * @returns Mutation result with mutate/mutateAsync functions\n *\n * @example\n * ```typescript\n * const { mutateAsync, isPending } = useDbDelete(\"Task\");\n * await mutateAsync(taskId);\n * ```\n *\n * @example\n * ```typescript\n * // With optimistic delete for instant UI feedback\n * const { mutate } = useDbDelete(\"Comment\", {\n * optimistic: true,\n * onSuccess: () => console.log(\"Deleted successfully\"),\n * onError: (error) => console.error(\"Delete failed:\", error),\n * invalidateTables: [\"Comment\", \"Post\"],\n * });\n *\n * // Immediately removes from UI, rolls back on failure\n * mutate(commentId);\n * ```\n */\nexport function useDbDelete(table, t0) {\n const $ = _c(34);\n let t1;\n if ($[0] !== t0) {\n t1 = t0 === undefined ? {} : t0;\n $[0] = t0;\n $[1] = t1;\n } else {\n t1 = $[1];\n }\n const options = t1;\n const {\n registry\n } = useDataLayerCore();\n const {\n status\n } = useDataLayerStatus();\n const queryClient = useQueryClient();\n const {\n onSuccess,\n onError,\n invalidateTables: t2,\n optimistic: t3\n } = options;\n let t4;\n if ($[2] !== t2 || $[3] !== table) {\n t4 = t2 === undefined ? [table] : t2;\n $[2] = t2;\n $[3] = table;\n $[4] = t4;\n } else {\n t4 = $[4];\n }\n const invalidateTables = t4;\n const optimistic = t3 === undefined ? false : t3;\n let t5;\n bb0: {\n if (!status.isInitialized) {\n t5 = null;\n break bb0;\n }\n try {\n let t6;\n if ($[5] !== registry || $[6] !== table) {\n t6 = registry.getAdapter(table);\n $[5] = registry;\n $[6] = table;\n $[7] = t6;\n } else {\n t6 = $[7];\n }\n t5 = t6;\n } catch {\n t5 = null;\n }\n }\n const adapter = t5;\n let t6;\n if ($[8] !== adapter || $[9] !== table) {\n t6 = async id => {\n if (!adapter) {\n throw new Error(`Adapter not available for table: ${table}`);\n }\n await adapter.delete(table, id);\n };\n $[8] = adapter;\n $[9] = table;\n $[10] = t6;\n } else {\n t6 = $[10];\n }\n const mutationFn = t6;\n let t7;\n if ($[11] !== optimistic || $[12] !== queryClient || $[13] !== table) {\n t7 = optimistic ? async id_0 => {\n await queryClient.cancelQueries({\n predicate: query => query.queryKey[0] === \"v3\" && query.queryKey[2] === table\n });\n const previousData = queryClient.getQueriesData({\n predicate: query_0 => query_0.queryKey[0] === \"v3\" && query_0.queryKey[2] === table\n });\n queryClient.setQueriesData({\n predicate: query_1 => query_1.queryKey[0] === \"v3\" && query_1.queryKey[2] === table\n }, old => {\n if (!old?.data) {\n return old;\n }\n return {\n ...old,\n data: old.data.filter(item => item.id !== id_0)\n };\n });\n return {\n previousData\n };\n } : undefined;\n $[11] = optimistic;\n $[12] = queryClient;\n $[13] = table;\n $[14] = t7;\n } else {\n t7 = $[14];\n }\n let t8;\n if ($[15] !== invalidateTables || $[16] !== onSuccess || $[17] !== queryClient) {\n t8 = () => {\n invalidateTables.forEach(t => {\n queryClient.invalidateQueries({\n predicate: query_2 => query_2.queryKey[0] === \"v3\" && query_2.queryKey[2] === t\n });\n });\n onSuccess?.();\n };\n $[15] = invalidateTables;\n $[16] = onSuccess;\n $[17] = queryClient;\n $[18] = t8;\n } else {\n t8 = $[18];\n }\n let t9;\n if ($[19] !== onError || $[20] !== optimistic || $[21] !== queryClient) {\n t9 = (error, _id, context) => {\n if (optimistic && context?.previousData) {\n context.previousData.forEach(t10 => {\n const [queryKey, data] = t10;\n queryClient.setQueryData(queryKey, data);\n });\n }\n onError?.(error instanceof Error ? error : new Error(String(error)));\n };\n $[19] = onError;\n $[20] = optimistic;\n $[21] = queryClient;\n $[22] = t9;\n } else {\n t9 = $[22];\n }\n let t10;\n if ($[23] !== mutationFn || $[24] !== t7 || $[25] !== t8 || $[26] !== t9) {\n t10 = {\n mutationFn,\n onMutate: t7,\n onSuccess: t8,\n onError: t9\n };\n $[23] = mutationFn;\n $[24] = t7;\n $[25] = t8;\n $[26] = t9;\n $[27] = t10;\n } else {\n t10 = $[27];\n }\n const mutation = useMutation(t10);\n const t11 = mutation.error as Error | null;\n let t12;\n if ($[28] !== mutation.isPending || $[29] !== mutation.mutate || $[30] !== mutation.mutateAsync || $[31] !== mutation.reset || $[32] !== t11) {\n t12 = {\n mutate: mutation.mutate,\n mutateAsync: mutation.mutateAsync,\n isPending: mutation.isPending,\n error: t11,\n reset: mutation.reset\n };\n $[28] = mutation.isPending;\n $[29] = mutation.mutate;\n $[30] = mutation.mutateAsync;\n $[31] = mutation.reset;\n $[32] = t11;\n $[33] = t12;\n } else {\n t12 = $[33];\n }\n return t12;\n}\nexport default useDbDelete;","/**\n * V3 useDbInfiniteQuery Hook\n *\n * React hook for querying records with infinite scroll pagination.\n * Works identically whether PowerSync or Supabase is the backend.\n * Uses React Query's useInfiniteQuery for state management and caching.\n *\n * Types are automatically inferred from table names when you augment\n * the DatabaseTypes interface with your app's Database type.\n *\n * @example\n * // In your app's types/db.d.ts:\n * declare module \"@pol-studios/db\" {\n * interface DatabaseTypes {\n * database: import(\"@/database.types\").Database;\n * }\n * }\n *\n * // Then usage auto-infers types:\n * const { data, fetchNextPage, hasNextPage } = useDbInfiniteQuery(\"EquipmentFixtureUnit\", {\n * pageSize: 20,\n * orderBy: [{ field: \"createdAt\", direction: \"desc\" }],\n * });\n */\n\nimport { useMemo, useCallback } from \"react\";\nimport { useInfiniteQuery, InfiniteData } from \"@tanstack/react-query\";\nimport { useDataLayerCore, useDataLayerStatus } from \"./useDataLayer\";\nimport type { QueryOptions, WhereClause } from \"../core/types\";\n\n// =============================================================================\n// Module Augmentation Interface\n// =============================================================================\n\n/**\n * Augment this interface in your app to enable automatic type inference.\n */\n// eslint-disable-next-line @typescript-eslint/no-empty-interface\nexport interface DatabaseTypes {}\n\n// =============================================================================\n// Database Type Helpers\n// =============================================================================\n\n/**\n * The configured Database type, or a generic fallback\n */\ntype ConfiguredDatabase = DatabaseTypes extends {\n database: infer DB;\n} ? DB : GenericSchema;\n\n/**\n * Generic schema structure for fallback\n */\ntype GenericSchema = {\n public: {\n Tables: Record<string, {\n Row: Record<string, unknown>;\n }>;\n Views: Record<string, {\n Row: Record<string, unknown>;\n }>;\n };\n [schema: string]: {\n Tables: Record<string, {\n Row: Record<string, unknown>;\n }>;\n Views?: Record<string, {\n Row: Record<string, unknown>;\n }>;\n };\n};\n\n/**\n * Default schema from Database (usually \"public\")\n */\ntype DefaultSchema = ConfiguredDatabase extends {\n public: infer S;\n} ? S : never;\n\n/**\n * Extract all valid table names from the default schema\n */\nexport type PublicTableNames = DefaultSchema extends {\n Tables: infer T;\n} ? keyof T & string : string;\n\n/**\n * Extract all valid schema names\n */\nexport type SchemaNames = keyof ConfiguredDatabase & string;\n\n/**\n * Extract table names for a specific schema\n */\nexport type SchemaTableNames<S extends string> = ConfiguredDatabase extends { [K in S]: {\n Tables: infer T;\n} } ? keyof T & string : string;\n\n/**\n * Build dot notation strings for all schema.table combinations\n */\ntype SchemaDotTable = { [S in SchemaNames]: S extends \"public\" ? never : `${S}.${SchemaTableNames<S>}` }[SchemaNames];\n\n/**\n * Table identifier - provides autocomplete for valid table names\n */\nexport type TableIdentifier = PublicTableNames | SchemaDotTable | { [S in Exclude<SchemaNames, \"public\">]: {\n schema: S;\n table: SchemaTableNames<S>;\n} }[Exclude<SchemaNames, \"public\">];\n\n/**\n * Resolve row type from a table identifier\n */\nexport type ResolveRowType<T extends TableIdentifier> = T extends string ? T extends `${infer Schema}.${infer Table}` ? ConfiguredDatabase extends { [K in Schema]: {\n Tables: { [K2 in Table]: {\n Row: infer R;\n } };\n} } ? R : Record<string, unknown> : DefaultSchema extends {\n Tables: { [K in T]: {\n Row: infer R;\n } };\n} ? R : DefaultSchema extends {\n Views: { [K in T]: {\n Row: infer R;\n } };\n} ? R : Record<string, unknown> : T extends {\n schema: infer S;\n table: infer TN;\n} ? S extends string ? TN extends string ? ConfiguredDatabase extends { [K in S]: {\n Tables: { [K2 in TN]: {\n Row: infer R;\n } };\n} } ? R : Record<string, unknown> : Record<string, unknown> : Record<string, unknown> : Record<string, unknown>;\n\n// =============================================================================\n// Types\n// =============================================================================\n\n/**\n * Options for useDbInfiniteQuery hook\n */\nexport interface UseDbInfiniteQueryOptions extends Omit<QueryOptions, \"limit\" | \"offset\" | \"enabled\"> {\n /** Whether the query is enabled (default: true) */\n enabled?: boolean;\n /** React Query stale time in ms (default: 30000) */\n staleTime?: number;\n /** Whether to refetch on window focus (default: true) */\n refetchOnWindowFocus?: boolean;\n /** Number of items per page (default: 50) */\n pageSize?: number;\n /** Text to search for */\n searchText?: string;\n /** Fields to search in when searchText is provided */\n searchFields?: string[];\n}\n\n/**\n * Result from useDbInfiniteQuery hook\n */\nexport interface UseDbInfiniteQueryResult<T> {\n /** Flattened array of all loaded data */\n data: T[] | undefined;\n /** Whether query is loading (initial load) */\n isLoading: boolean;\n /** Whether query is in pending state */\n isPending: boolean;\n /** Whether query is currently fetching (including refetch) */\n isFetching: boolean;\n /** Query error if any */\n error: Error | null;\n /** Function to fetch the next page */\n fetchNextPage: () => Promise<void>;\n /** Whether there are more pages to load */\n hasNextPage: boolean;\n /** Whether currently fetching the next page */\n isFetchingNextPage: boolean;\n /** Total count of items (if available) */\n count?: number;\n /** Refetch all pages */\n refetch: () => Promise<void>;\n}\n\n/**\n * Internal page result type\n */\ninterface PageResult<T> {\n data: T[];\n count?: number;\n}\n\n// =============================================================================\n// Helper Functions\n// =============================================================================\n\n/**\n * Build a query key for React Query infinite queries\n */\nfunction buildInfiniteQueryKey(table: string, options: UseDbInfiniteQueryOptions): unknown[] {\n return [\"v3\", \"infinite-query\", table, options.select ?? \"*\", JSON.stringify(options.where ?? {}), JSON.stringify(options.orderBy ?? []), options.pageSize ?? 50, options.searchText ?? \"\", JSON.stringify(options.searchFields ?? [])];\n}\n\n/**\n * Serialize query options for dependency tracking\n */\nfunction serializeInfiniteQueryOptions(options: UseDbInfiniteQueryOptions): string {\n return JSON.stringify({\n select: options.select,\n where: options.where,\n orderBy: options.orderBy,\n pageSize: options.pageSize,\n searchText: options.searchText,\n searchFields: options.searchFields\n });\n}\n\n/**\n * Helper to resolve table name from TableIdentifier\n */\nfunction resolveTableName(table: TableIdentifier): string {\n if (typeof table === \"string\") {\n return table;\n }\n return `${table.schema}.${table.table}`;\n}\n\n/**\n * Build search where clause from searchText and searchFields\n */\nfunction buildSearchWhereClause(searchText: string, searchFields: string[], existingWhere?: WhereClause): WhereClause {\n const searchWhere: WhereClause = {};\n if (searchFields.length === 1) {\n searchWhere[searchFields[0]] = {\n like: `%${searchText}%`\n };\n } else if (searchFields.length > 1) {\n searchWhere[searchFields[0]] = {\n like: `%${searchText}%`\n };\n }\n return {\n ...existingWhere,\n ...searchWhere\n };\n}\n\n// =============================================================================\n// Hook Implementation\n// =============================================================================\n\n/**\n * Hook for querying records with infinite scroll pagination\n *\n * @param table - Table name (string) or { schema, table } object\n * @param options - Query options (select, where, orderBy, pageSize, searchText, etc.)\n * @returns Query result with data, loading states, pagination controls, and refetch function\n *\n * @example\n * // Basic infinite query - types auto-inferred from table name\n * const { data, fetchNextPage, hasNextPage } = useDbInfiniteQuery(\"EquipmentFixtureUnit\");\n *\n * @example\n * // With search and pagination\n * const { data, fetchNextPage, hasNextPage, isFetchingNextPage } = useDbInfiniteQuery(\"Task\", {\n * pageSize: 20,\n * searchText: searchQuery,\n * searchFields: [\"name\", \"description\"],\n * orderBy: [{ field: \"createdAt\", direction: \"desc\" }],\n * });\n *\n * @example\n * // In a FlatList or similar\n * <FlatList\n * data={data}\n * onEndReached={() => hasNextPage && fetchNextPage()}\n * ListFooterComponent={isFetchingNextPage ? <Spinner /> : null}\n * />\n */\nexport function useDbInfiniteQuery<T extends TableIdentifier>(table: T, options?: UseDbInfiniteQueryOptions): UseDbInfiniteQueryResult<ResolveRowType<T>>;\n\n/**\n * Overload for explicit type parameter (backwards compatibility)\n */\nexport function useDbInfiniteQuery<T>(table: string, options?: UseDbInfiniteQueryOptions): UseDbInfiniteQueryResult<T>;\nexport function useDbInfiniteQuery<T>(table: TableIdentifier, options: UseDbInfiniteQueryOptions = {}): UseDbInfiniteQueryResult<T> {\n const tableName = resolveTableName(table);\n const {\n registry\n } = useDataLayerCore();\n const {\n status\n } = useDataLayerStatus();\n const {\n enabled = true,\n staleTime = 30000,\n refetchOnWindowFocus = true,\n pageSize = 50,\n searchText,\n searchFields,\n ...queryOptions\n } = options;\n\n // Get adapter for this table\n const adapter = useMemo(() => {\n if (!status.isInitialized) return null;\n try {\n return registry.getAdapter(tableName);\n } catch {\n return null;\n }\n }, [registry, tableName, status.isInitialized, status.currentBackend]);\n\n // Build query key\n const queryKey = useMemo(() => buildInfiniteQueryKey(tableName, options), [tableName, serializeInfiniteQueryOptions(options)]);\n\n // Build the where clause including search conditions\n const effectiveWhere = useMemo(() => {\n if (searchText && searchFields && searchFields.length > 0) {\n return buildSearchWhereClause(searchText, searchFields, queryOptions.where);\n }\n return queryOptions.where;\n }, [searchText, searchFields, queryOptions.where]);\n\n // Memoize base query options\n const memoizedQueryOptions = useMemo(() => ({\n select: queryOptions.select,\n where: effectiveWhere,\n orderBy: queryOptions.orderBy\n }), [queryOptions.select, effectiveWhere, queryOptions.orderBy]);\n\n // Execute infinite query with React Query\n const infiniteQuery = useInfiniteQuery<PageResult<T>, Error, InfiniteData<PageResult<T>, number>, unknown[], number>({\n queryKey,\n queryFn: async ({\n pageParam\n }) => {\n if (!adapter) {\n throw new Error(`Adapter not available for table: ${tableName}`);\n }\n const offset = (pageParam - 1) * pageSize;\n const result = await adapter.query<T>(tableName, {\n ...memoizedQueryOptions,\n limit: pageSize,\n offset\n });\n return {\n data: result.data ?? [],\n count: result.count\n };\n },\n initialPageParam: 1,\n getNextPageParam: (lastPage, allPages) => {\n const totalLoaded = allPages.reduce((sum, page) => sum + page.data.length, 0);\n const totalCount = lastPage.count;\n if (totalCount !== undefined && totalLoaded >= totalCount) {\n return undefined;\n }\n if (lastPage.data.length < pageSize) {\n return undefined;\n }\n return allPages.length + 1;\n },\n enabled: enabled && status.isInitialized && adapter !== null,\n staleTime,\n refetchOnWindowFocus\n });\n\n // Flatten all pages into a single data array\n const flattenedData = useMemo(() => {\n if (!infiniteQuery.data?.pages) return undefined;\n return infiniteQuery.data.pages.flatMap(page_0 => page_0.data);\n }, [infiniteQuery.data?.pages]);\n\n // Get total count from the last page\n const count = useMemo(() => {\n if (!infiniteQuery.data?.pages || infiniteQuery.data.pages.length === 0) {\n return undefined;\n }\n return infiniteQuery.data.pages[infiniteQuery.data.pages.length - 1].count;\n }, [infiniteQuery.data?.pages]);\n\n // Build fetchNextPage function\n const fetchNextPage = useCallback(async () => {\n await infiniteQuery.fetchNextPage();\n }, [infiniteQuery]);\n\n // Build refetch function\n const refetch = useCallback(async () => {\n await infiniteQuery.refetch();\n }, [infiniteQuery]);\n return {\n data: flattenedData,\n isLoading: infiniteQuery.isLoading,\n isPending: infiniteQuery.isPending,\n isFetching: infiniteQuery.isFetching,\n error: infiniteQuery.error as Error | null,\n fetchNextPage,\n hasNextPage: infiniteQuery.hasNextPage ?? false,\n isFetchingNextPage: infiniteQuery.isFetchingNextPage,\n count,\n refetch\n };\n}\nexport default useDbInfiniteQuery;","import { c as _c } from \"react/compiler-runtime\";\n/**\n * V3 useDbCount Hook\n *\n * React hook for counting records in a table.\n * Works with the data layer using either PowerSync or Supabase backend.\n */\n\nimport { useMemo, useCallback } from \"react\";\nimport { useQuery } from \"@tanstack/react-query\";\nimport { useDataLayerCore, useDataLayerStatus } from \"./useDataLayer\";\nimport type { WhereClause } from \"../core/types\";\n\n// =============================================================================\n// Types\n// =============================================================================\n\n/**\n * Options for useDbCount hook\n */\nexport interface UseDbCountOptions {\n /** Filter conditions */\n where?: WhereClause;\n /** Whether the query is enabled (default: true) */\n enabled?: boolean;\n /** React Query stale time in ms (default: 30000) */\n staleTime?: number;\n}\n\n/**\n * Result from useDbCount hook\n */\nexport interface UseDbCountResult {\n /** The count value */\n count: number | undefined;\n /** Whether query is loading */\n isLoading: boolean;\n /** Whether query is fetching */\n isFetching: boolean;\n /** Query error if any */\n error: Error | null;\n /** Refetch the count */\n refetch: () => Promise<void>;\n}\n\n// =============================================================================\n// Hook Implementation\n// =============================================================================\n\n/**\n * Hook for counting records in a table\n *\n * @param table - The table name to count\n * @param options - Count options (where filter, enabled)\n * @returns Count result with loading states\n *\n * @example\n * // Simple count\n * const { count, isLoading } = useDbCount(\"EquipmentFixtureUnit\");\n *\n * @example\n * // Count with filter\n * const { count } = useDbCount(\"EquipmentFixtureUnit\", {\n * where: { projectDatabaseId: 123 },\n * });\n */\nexport function useDbCount(table, t0) {\n const $ = _c(27);\n let t1;\n if ($[0] !== t0) {\n t1 = t0 === undefined ? {} : t0;\n $[0] = t0;\n $[1] = t1;\n } else {\n t1 = $[1];\n }\n const options = t1;\n const {\n registry\n } = useDataLayerCore();\n const {\n status\n } = useDataLayerStatus();\n const {\n enabled: t2,\n staleTime: t3,\n where\n } = options;\n const enabled = t2 === undefined ? true : t2;\n const staleTime = t3 === undefined ? 30000 : t3;\n let t4;\n bb0: {\n if (!status.isInitialized) {\n t4 = null;\n break bb0;\n }\n try {\n let t5;\n if ($[2] !== registry || $[3] !== table) {\n t5 = registry.getAdapter(table);\n $[2] = registry;\n $[3] = table;\n $[4] = t5;\n } else {\n t5 = $[4];\n }\n t4 = t5;\n } catch {\n t4 = null;\n }\n }\n const adapter = t4;\n let t5;\n if ($[5] !== where) {\n t5 = JSON.stringify(where ?? {});\n $[5] = where;\n $[6] = t5;\n } else {\n t5 = $[6];\n }\n let t6;\n if ($[7] !== t5 || $[8] !== table) {\n t6 = [\"v3\", \"count\", table, t5];\n $[7] = t5;\n $[8] = table;\n $[9] = t6;\n } else {\n t6 = $[9];\n }\n const queryKey = t6;\n let t7;\n if ($[10] !== adapter || $[11] !== table || $[12] !== where) {\n t7 = async () => {\n if (!adapter) {\n throw new Error(`Adapter not available for table: ${table}`);\n }\n const result = await adapter.query(table, {\n where,\n select: \"id\"\n });\n return result.count ?? result.data.length;\n };\n $[10] = adapter;\n $[11] = table;\n $[12] = where;\n $[13] = t7;\n } else {\n t7 = $[13];\n }\n const queryFn = t7;\n const t8 = enabled && status.isInitialized && adapter !== null;\n let t9;\n if ($[14] !== queryFn || $[15] !== queryKey || $[16] !== staleTime || $[17] !== t8) {\n t9 = {\n queryKey,\n queryFn,\n enabled: t8,\n staleTime\n };\n $[14] = queryFn;\n $[15] = queryKey;\n $[16] = staleTime;\n $[17] = t8;\n $[18] = t9;\n } else {\n t9 = $[18];\n }\n const query = useQuery(t9);\n let t10;\n if ($[19] !== query) {\n t10 = async () => {\n await query.refetch();\n };\n $[19] = query;\n $[20] = t10;\n } else {\n t10 = $[20];\n }\n const refetch = t10;\n const t11 = query.error as Error | null;\n let t12;\n if ($[21] !== query.data || $[22] !== query.isFetching || $[23] !== query.isLoading || $[24] !== refetch || $[25] !== t11) {\n t12 = {\n count: query.data,\n isLoading: query.isLoading,\n isFetching: query.isFetching,\n error: t11,\n refetch\n };\n $[21] = query.data;\n $[22] = query.isFetching;\n $[23] = query.isLoading;\n $[24] = refetch;\n $[25] = t11;\n $[26] = t12;\n } else {\n t12 = $[26];\n }\n return t12;\n}\nexport default useDbCount;","import { c as _c } from \"react/compiler-runtime\";\n/**\n * V3 useSyncStatus Hook\n *\n * Provides sync status information from the data layer.\n * Returns default \"always synced\" status when PowerSync is not available.\n *\n * Uses the split context architecture for optimal performance.\n */\n\nimport { useState, useEffect, useContext } from \"react\";\nimport { DataLayerStatusContext, DataLayerCoreContext } from \"../providers/DataLayerContext\";\nimport type { SyncStatus } from \"../core/types\";\n\n/**\n * Default sync status when PowerSync is not available\n */\nconst defaultSyncStatus: SyncStatus = {\n isConnected: true,\n // Supabase-only mode is always \"connected\" when online\n isSyncing: false,\n lastSyncedAt: null,\n pendingUploads: 0,\n error: null\n};\n\n/**\n * Hook to get the current sync status\n *\n * When PowerSync is not available, returns a default \"always synced\" status.\n *\n * This hook uses the split context architecture - it only subscribes to\n * status changes, not core value changes.\n *\n * @example\n * const { isSyncing, pendingUploads, isConnected } = useSyncStatus();\n *\n * if (pendingUploads > 0) {\n * console.log(`${pendingUploads} changes waiting to sync`);\n * }\n */\nexport function useSyncStatus() {\n const $ = _c(6);\n const statusContext = useContext(DataLayerStatusContext);\n const coreContext = useContext(DataLayerCoreContext);\n if (!statusContext || !coreContext) {\n throw new Error(\"useSyncStatus must be used within a DataLayerProvider. Make sure you have wrapped your app with <DataLayerProvider>.\");\n }\n const {\n syncStatus,\n status\n } = statusContext;\n const {\n powerSync\n } = coreContext;\n const [currentStatus, setCurrentStatus] = useState(syncStatus);\n let t0;\n let t1;\n if ($[0] !== powerSync || $[1] !== status.currentBackend || $[2] !== status.isOnline || $[3] !== syncStatus) {\n t0 = () => {\n if (powerSync && status.currentBackend === \"powersync\") {\n setCurrentStatus(syncStatus);\n } else {\n setCurrentStatus({\n ...defaultSyncStatus,\n isConnected: status.isOnline\n });\n }\n };\n t1 = [syncStatus, status.currentBackend, status.isOnline, powerSync];\n $[0] = powerSync;\n $[1] = status.currentBackend;\n $[2] = status.isOnline;\n $[3] = syncStatus;\n $[4] = t0;\n $[5] = t1;\n } else {\n t0 = $[4];\n t1 = $[5];\n }\n useEffect(t0, t1);\n return currentStatus;\n}\nexport default useSyncStatus;","import { c as _c } from \"react/compiler-runtime\";\n/**\n * V3 useSyncControl Hook\n *\n * Provides sync control functions from the data layer.\n * Returns no-op functions when PowerSync is not available.\n *\n * Uses the split context architecture for optimal performance.\n */\n\nimport { useMemo, useContext, useState, useCallback, useSyncExternalStore } from \"react\";\nimport { DataLayerCoreContext } from \"../providers/DataLayerContext\";\nimport type { SyncControl, FailedUpload } from \"../core/types\";\n\n// Try to import from @pol-studios/powersync - this may not be available in all environments\nlet failedUploadStore: {\n getAll: () => FailedUpload[];\n clear: () => void;\n load: () => Promise<void>;\n} | null = null;\n\n// Dynamic import attempt - gracefully handles if powersync package is not available\ntry {\n // eslint-disable-next-line @typescript-eslint/no-require-imports\n const powersyncSync = require(\"@pol-studios/powersync/sync\");\n failedUploadStore = powersyncSync.failedUploadStore;\n} catch {\n // PowerSync sync module not available - will use no-op fallbacks\n}\n\n// Subscription tracking for useSyncExternalStore\nlet failedUploadListeners: Set<() => void> = new Set();\nlet cachedFailedUploads: FailedUpload[] = [];\n\n/**\n * Subscribe to failed upload store changes\n */\nfunction subscribeToFailedUploads(callback: () => void): () => void {\n failedUploadListeners.add(callback);\n return () => {\n failedUploadListeners.delete(callback);\n };\n}\n\n/**\n * Get current snapshot of failed uploads\n */\nfunction getFailedUploadsSnapshot(): FailedUpload[] {\n if (!failedUploadStore) {\n return [];\n }\n const uploads = failedUploadStore.getAll();\n // Only update cache if actually changed (referential equality check)\n if (uploads.length !== cachedFailedUploads.length || uploads.some((u, i) => u.id !== cachedFailedUploads[i]?.id)) {\n cachedFailedUploads = uploads;\n }\n return cachedFailedUploads;\n}\n\n/**\n * Notify all listeners of failed upload changes\n */\nfunction notifyFailedUploadListeners(): void {\n failedUploadListeners.forEach(listener => listener());\n}\n\n/**\n * Hook to get sync controls for PowerSync\n *\n * When PowerSync is not available, all methods are no-ops that log a warning.\n *\n * PERFORMANCE: This hook only subscribes to DataLayerCoreContext (stable values),\n * NOT DataLayerStatusContext. This means components using useSyncControl() will\n * NOT re-render when network status or sync status changes.\n *\n * @example\n * const { triggerSync, startLiveSync, stopLiveSync } = useSyncControl();\n *\n * // Manually trigger a sync\n * await triggerSync();\n *\n * // Start/stop live sync\n * await startLiveSync();\n * stopLiveSync();\n *\n * @example Failed upload controls\n * const {\n * failedUploads,\n * retryFailedUploads,\n * clearFailedUploads,\n * pauseAutoRetry,\n * resumeAutoRetry,\n * isAutoRetryPaused\n * } = useSyncControl();\n *\n * // Show failed uploads count\n * console.log(`${failedUploads.length} uploads failed`);\n *\n * // Manually retry all failed uploads\n * await retryFailedUploads();\n *\n * // Discard all failed uploads\n * clearFailedUploads();\n */\nexport function useSyncControl() {\n const $ = _c(11);\n const coreContext = useContext(DataLayerCoreContext);\n if (!coreContext) {\n throw new Error(\"useSyncControl must be used within a DataLayerProvider. Make sure you have wrapped your app with <DataLayerProvider>.\");\n }\n const {\n syncControl,\n powerSync\n } = coreContext;\n const isPowerSyncActive = powerSync !== null;\n const [isAutoRetryPaused, setIsAutoRetryPaused] = useState(false);\n const failedUploads = useSyncExternalStore(subscribeToFailedUploads, getFailedUploadsSnapshot, _temp);\n let t0;\n if ($[0] !== isPowerSyncActive || $[1] !== syncControl) {\n t0 = async () => {\n if (!isPowerSyncActive) {\n console.warn(\"[useSyncControl] retryFailedUploads called but PowerSync is not available\");\n return;\n }\n if (!failedUploadStore) {\n console.warn(\"[useSyncControl] retryFailedUploads called but failedUploadStore is not available\");\n return;\n }\n failedUploadStore.clear();\n notifyFailedUploadListeners();\n await syncControl.triggerSync();\n };\n $[0] = isPowerSyncActive;\n $[1] = syncControl;\n $[2] = t0;\n } else {\n t0 = $[2];\n }\n const retryFailedUploads = t0;\n const clearFailedUploads = _temp2;\n let t1;\n if ($[3] === Symbol.for(\"react.memo_cache_sentinel\")) {\n t1 = () => {\n setIsAutoRetryPaused(true);\n console.log(\"[useSyncControl] Auto-retry paused\");\n };\n $[3] = t1;\n } else {\n t1 = $[3];\n }\n const pauseAutoRetry = t1;\n let t2;\n if ($[4] === Symbol.for(\"react.memo_cache_sentinel\")) {\n t2 = () => {\n setIsAutoRetryPaused(false);\n console.log(\"[useSyncControl] Auto-retry resumed\");\n };\n $[4] = t2;\n } else {\n t2 = $[4];\n }\n const resumeAutoRetry = t2;\n let t3;\n if ($[5] === Symbol.for(\"react.memo_cache_sentinel\")) {\n t3 = {\n triggerSync: _temp3,\n startLiveSync: _temp4,\n stopLiveSync: _temp5,\n setScope: _temp6,\n retryFailedUploads: _temp7,\n clearFailedUploads: _temp8,\n failedUploads: [],\n pauseAutoRetry: _temp9,\n resumeAutoRetry: _temp0,\n isAutoRetryPaused: false\n };\n $[5] = t3;\n } else {\n t3 = $[5];\n }\n const noOpControls = t3;\n let t4;\n bb0: {\n if (isPowerSyncActive) {\n let t5;\n if ($[6] !== failedUploads || $[7] !== isAutoRetryPaused || $[8] !== retryFailedUploads || $[9] !== syncControl) {\n t5 = {\n ...syncControl,\n retryFailedUploads,\n clearFailedUploads,\n failedUploads,\n pauseAutoRetry,\n resumeAutoRetry,\n isAutoRetryPaused\n };\n $[6] = failedUploads;\n $[7] = isAutoRetryPaused;\n $[8] = retryFailedUploads;\n $[9] = syncControl;\n $[10] = t5;\n } else {\n t5 = $[10];\n }\n t4 = t5;\n break bb0;\n }\n t4 = noOpControls;\n }\n const controls = t4;\n return controls;\n}\nfunction _temp0() {\n console.warn(\"[useSyncControl] resumeAutoRetry called but PowerSync is not available\");\n}\nfunction _temp9() {\n console.warn(\"[useSyncControl] pauseAutoRetry called but PowerSync is not available\");\n}\nfunction _temp8() {\n console.warn(\"[useSyncControl] clearFailedUploads called but PowerSync is not available\");\n}\nasync function _temp7() {\n console.warn(\"[useSyncControl] retryFailedUploads called but PowerSync is not available\");\n}\nasync function _temp6(_scopeName, _values) {\n console.warn(\"[useSyncControl] setScope called but PowerSync is not available\");\n}\nfunction _temp5() {\n console.warn(\"[useSyncControl] stopLiveSync called but PowerSync is not available\");\n}\nasync function _temp4() {\n console.warn(\"[useSyncControl] startLiveSync called but PowerSync is not available\");\n}\nasync function _temp3() {\n console.warn(\"[useSyncControl] triggerSync called but PowerSync is not available\");\n}\nfunction _temp2() {\n if (!failedUploadStore) {\n console.warn(\"[useSyncControl] clearFailedUploads called but failedUploadStore is not available\");\n return;\n }\n failedUploadStore.clear();\n notifyFailedUploadListeners();\n}\nfunction _temp() {\n return [];\n}\nexport default useSyncControl;","import { c as _c } from \"react/compiler-runtime\";\n/**\n * V3 useOnlineStatus Hook\n *\n * Provides online/connection status information.\n * Uses DataLayerProvider's status as the SINGLE source of truth.\n *\n * On React Native: status.isOnline comes from PowerSync platform adapter (NetInfo)\n * On Web: status.isOnline comes from browser navigator.onLine\n */\n\nimport { useMemo } from \"react\";\nimport { useDataLayerCore, useDataLayerStatus } from \"./useDataLayer\";\n\n/**\n * Online status information\n */\nexport interface OnlineStatus {\n /** Whether the device has network connectivity */\n isOnline: boolean;\n /** Whether PowerSync is connected (false if using Supabase-only) */\n isConnected: boolean;\n /** Current backend being used */\n backend: \"powersync\" | \"supabase\" | null;\n}\n\n/**\n * Hook to get online/connection status\n *\n * Uses DataLayerProvider's status as the single source of truth:\n * - On React Native: isOnline comes from PowerSync platform adapter (NetInfo)\n * - On Web: isOnline comes from browser navigator.onLine\n *\n * @example\n * const { isOnline, isConnected, backend } = useOnlineStatus();\n *\n * if (!isOnline) {\n * return <OfflineBanner />;\n * }\n */\nexport function useOnlineStatus() {\n const $ = _c(4);\n const {\n powerSync\n } = useDataLayerCore();\n const {\n status\n } = useDataLayerStatus();\n const t0 = powerSync !== null && status.powerSyncStatus === \"available\";\n let t1;\n if ($[0] !== status.currentBackend || $[1] !== status.isOnline || $[2] !== t0) {\n t1 = {\n isOnline: status.isOnline,\n isConnected: t0,\n backend: status.currentBackend\n };\n $[0] = status.currentBackend;\n $[1] = status.isOnline;\n $[2] = t0;\n $[3] = t1;\n } else {\n t1 = $[3];\n }\n return t1;\n}\nexport default useO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pF;AACA,eAAe,SAAS;AACtB,UAAQ,KAAK,sEAAsE;AACrF;AACA,eAAe,SAAS;AACtB,UAAQ,KAAK,oEAAoE;AACnF;AACA,SAAS,SAAS;AAChB,MAAI,CAAC,mBAAmB;AACtB,YAAQ,KAAK,mFAAmF;AAChG;AAAA,EACF;AACA,oBAAkB,MAAM;AACxB,8BAA4B;AAC9B;AACA,SAAS,QAAQ;AACf,SAAO,CAAC;AACV;;;ACrPA,SAAS,KAAKC,WAAU;AAwCjB,SAAS,kBAAkB;AAChC,QAAM,IAAIC,IAAG,CAAC;AACd,QAAM;AAAA,IACJ;AAAA,EACF,IAAI,iBAAiB;AACrB,QAAM;AAAA,IACJ;AAAA,EACF,IAAI,mBAAmB;AACvB,QAAM,KAAK,cAAc,QAAQ,OAAO,oBAAoB;AAC5D,MAAI;AACJ,MAAI,EAAE,CAAC,MAAM,OAAO,kBAAkB,EAAE,CAAC,MAAM,OAAO,YAAY,EAAE,CAAC,MAAM,IAAI;AAC7E,SAAK;AAAA,MACH,UAAU,OAAO;AAAA,MACjB,aAAa;AAAA,MACb,SAAS,OAAO;AAAA,IAClB;AACA,MAAE,CAAC,IAAI,OAAO;AACd,MAAE,CAAC,IAAI,OAAO;AACd,MAAE,CAAC,IAAI;AACP,MAAE,CAAC,IAAI;AAAA,EACT,OAAO;AACL,SAAK,EAAE,CAAC;AAAA,EACV;AACA,SAAO;AACT;","names":["useCallback","useMemo","useQuery","buildQueryKey","useMemo","useCallback","useQuery","useCallback","useMemo","useEffect","useQuery","useMemo","useCallback","useQuery","result","useEffect","t5","_c","useMutation","useQueryClient","_c","useQueryClient","t6","t10","useMutation","_c","useMutation","useQueryClient","_c","useQueryClient","t6","t5","useMutation","_c","useMutation","useQueryClient","_c","useQueryClient","t6","t10","useMutation","useMemo","useCallback","resolveTableName","useMemo","useCallback","_c","useQuery","_c","t5","useQuery","_c","useState","useEffect","useContext","_c","useContext","useState","useEffect","_c","useContext","useState","_c","useContext","useState","_c","_c"]}
@@ -6,10 +6,10 @@ import {
6
6
  } from "./chunk-7SCJNYTE.js";
7
7
  import {
8
8
  useDbQuery
9
- } from "./chunk-3UYBZHEV.js";
9
+ } from "./chunk-VZMZXL37.js";
10
10
  import {
11
11
  useDbUpsert
12
- } from "./chunk-Q7WJEOQ5.js";
12
+ } from "./chunk-2DOYFTN4.js";
13
13
  import {
14
14
  getSupabaseUrl
15
15
  } from "./chunk-GC3TBUWE.js";
@@ -3388,4 +3388,4 @@ export {
3388
3388
  useApplyFeedback,
3389
3389
  useResolveFeedback
3390
3390
  };
3391
- //# sourceMappingURL=chunk-3L4HOEXV.js.map
3391
+ //# sourceMappingURL=chunk-7OLNKLII.js.map
@@ -3,13 +3,13 @@ import {
3
3
  } from "./chunk-SM73S2DY.js";
4
4
  import {
5
5
  useSetupAuth
6
- } from "./chunk-MBU4KE3V.js";
6
+ } from "./chunk-VWPLASGY.js";
7
7
  import {
8
8
  useDbQuery
9
- } from "./chunk-3UYBZHEV.js";
9
+ } from "./chunk-VZMZXL37.js";
10
10
  import {
11
11
  useDbUpsert
12
- } from "./chunk-Q7WJEOQ5.js";
12
+ } from "./chunk-2DOYFTN4.js";
13
13
  import {
14
14
  delay,
15
15
  isNullOrWhitespace,
@@ -467,4 +467,4 @@ export {
467
467
  useSetUserMetadata,
468
468
  useUserMetadataState
469
469
  };
470
- //# sourceMappingURL=chunk-TSXQTYUG.js.map
470
+ //# sourceMappingURL=chunk-LABTYQOJ.js.map
@@ -1,7 +1,7 @@
1
1
  import {
2
2
  permissionContext,
3
3
  setupAuthContext
4
- } from "./chunk-3UYBZHEV.js";
4
+ } from "./chunk-VZMZXL37.js";
5
5
  import {
6
6
  isUsable
7
7
  } from "./chunk-OQ7U6EQ3.js";
@@ -244,4 +244,4 @@ export {
244
244
  useInvalidatePermission,
245
245
  usePermissionLoading
246
246
  };
247
- //# sourceMappingURL=chunk-MBU4KE3V.js.map
247
+ //# sourceMappingURL=chunk-VWPLASGY.js.map
@@ -1,6 +1,6 @@
1
1
  import {
2
2
  useDbUpsert
3
- } from "./chunk-Q7WJEOQ5.js";
3
+ } from "./chunk-2DOYFTN4.js";
4
4
  import {
5
5
  isUsable,
6
6
  newUuid,
@@ -918,4 +918,4 @@ export {
918
918
  useSetUserMetadata,
919
919
  useUserMetadataState
920
920
  };
921
- //# sourceMappingURL=chunk-3UYBZHEV.js.map
921
+ //# sourceMappingURL=chunk-VZMZXL37.js.map