@pol-studios/db 1.0.19 → 1.0.21

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 (36) hide show
  1. package/dist/DataLayerContext-ZmLPYR_s.d.ts +825 -0
  2. package/dist/EntityPermissions-DwFt4tUd.d.ts +35 -0
  3. package/dist/FilterConfig-Bt2Ek74z.d.ts +99 -0
  4. package/dist/UserMetadataContext-B8gVWGMl.d.ts +35 -0
  5. package/dist/UserMetadataContext-DntmpK41.d.ts +33 -0
  6. package/dist/auth/context.d.ts +48 -0
  7. package/dist/auth/guards.d.ts +180 -0
  8. package/dist/auth/hooks.d.ts +312 -0
  9. package/dist/auth/index.d.ts +11 -0
  10. package/dist/client/index.d.ts +16 -0
  11. package/dist/core/index.d.ts +539 -0
  12. package/dist/database.types-ChFCG-4M.d.ts +8604 -0
  13. package/dist/executor-CB4KHyYG.d.ts +507 -0
  14. package/dist/gen/index.d.ts +1099 -0
  15. package/dist/hooks/index.d.ts +100 -0
  16. package/dist/index-BNKhgDdC.d.ts +433 -0
  17. package/dist/index.d.ts +33 -0
  18. package/dist/index.native.d.ts +793 -0
  19. package/dist/index.web.d.ts +321 -0
  20. package/dist/mutation/index.d.ts +58 -0
  21. package/dist/parser/index.d.ts +366 -0
  22. package/dist/powersync-bridge/index.d.ts +284 -0
  23. package/dist/query/index.d.ts +723 -0
  24. package/dist/realtime/index.d.ts +44 -0
  25. package/dist/select-query-parser-BwyHum1L.d.ts +352 -0
  26. package/dist/setupAuthContext-Kv-THH-h.d.ts +61 -0
  27. package/dist/types/index.d.ts +10 -0
  28. package/dist/types-CYr9JiUE.d.ts +62 -0
  29. package/dist/useBatchUpsert-9OYjibLh.d.ts +24 -0
  30. package/dist/useDbCount-Id14x_1P.d.ts +1082 -0
  31. package/dist/useDbQuery-C-TL8jY1.d.ts +19 -0
  32. package/dist/useReceiptAI-6HkRpRml.d.ts +58 -0
  33. package/dist/useResolveFeedback-Ca2rh_Bs.d.ts +997 -0
  34. package/dist/useSupabase-DvWVuHHE.d.ts +28 -0
  35. package/dist/with-auth/index.d.ts +704 -0
  36. package/package.json +61 -13
@@ -0,0 +1,793 @@
1
+ export { C as CompositeTypes, c as Constants, D as Database, E as Enums, J as Json, T as Tables, a as TablesInsert, b as TablesUpdate } from './database.types-ChFCG-4M.js';
2
+ export { a as FilterConfig, F as FilterConfigOption, G as Group, P as PropertyType, S as SortConfig, T as TableInfo, V as ValueForPropertyType, W as WhereFilter } from './FilterConfig-Bt2Ek74z.js';
3
+ export { r as BackendSelectionResult, B as BooleanOperator, l as ClarificationQuestion, k as ClarificationSuggestion, C as CombinedProviderStatus, j as ComputedSortConfig, n as DataLayerWithPowerSyncProps, D as DbChangeLog, a as EnhancedSyncControl, E as EnhancedSyncStatus, e as Filter, d as FilterConditionType, m as FilterContextType, f as FilterGroup, g as FilterInput, F as FilterOperator, h as FilterState, H as HasPowerSyncConfig, O as OrderColumn, i as Pagination, P as PowerSyncEnabledConfig, b as PowerSyncEnabledContextValue, q as PowerSyncTables, Q as QueryState, S as Sort, U as UseDataLayerWithPowerSync, p as UseSyncControlWithPowerSync, o as UseSyncStatusWithPowerSync, V as ValueOrArrayForPropertyType, c as createCombinedStatus, s as normalizeFilter, u as useDbAdvanceFilterQuery, u as useDbAdvanceQuery } from './index-BNKhgDdC.js';
4
+ export { A as AIOptions, B as AIResponse, P as AlertProps, K as BUCKETS, L as BucketName, I as CustomPageQueryResult, N as DEFAULT_QUERY_TIMEOUT, a9 as FeedbackListItem, aa as FeedbackListParams, Q as LiveChangeContext, R as LiveChangeContextProvider, D as ServerAvailabilityState, J as StorageObjectMetadata, ac as SubmitFeedbackParams, S as SupabaseAdapter, T as TIMEOUT_ERROR_MESSAGE, G as UpdateOptions, U as UseDbPartialAdvanceQueryResult, p as UseDbPartialQueryResult, r as UseDbRealtimeQueryResult, v as UseMutationSuccessOptions, t as convertFilterToRealtimeQuery, M as createInCondition, y as createSupabaseAdapter, H as executeAdvanceQuery, z as getErrorBody, k as getSupabaseUrl, O as isTimeoutError, n as newTimeActivity, s as setSupabaseUrl, C as useAI, ad as useApplyFeedback, g as useAutosaveState, a4 as useChangelogById, a5 as useChangelogBySlug, a6 as useChangelogEntries, a7 as useChangelogMedia, a2 as useChangelogs, c as useDbDelete, a as useDbInsert, l as useDbMultiDelete, m as useDbMultiUpsert, o as useDbPartialAdvanceQuery, q as useDbPartialQuery, u as useDbRealtime, d as useDbRealtimeQuery, b as useDbUpdate, c as useDelete, W as useDeleteChangelog, Z as useDeleteChangelogEntry, a0 as useDeleteChangelogMedia, a8 as useFeedbackList, a as useInsert, f as useLatestOperationLog, e as useLiveChangeTracking, _ as useMultiDeleteChangelogEntries, Y as useMultiUpsertChangelogEntries, w as useMutationSuccess, x as useMutationSuccessRN, a3 as usePublishedChangelogs, u as useRealtime, d as useRealtimeQuery, ae as useResolveFeedback, F as useSearchQuery, E as useServerAvailability, j as useStoragePath, i as useStorageUrl, ab as useSubmitFeedback, h as useToastError, b as useUpdate, a1 as useUploadChangelogMedia, V as useUpsertChangelog, X as useUpsertChangelogEntry, $ as useUpsertChangelogMedia } from './useResolveFeedback-Ca2rh_Bs.js';
5
+ export { F as Fetch, i as GenericFunction, g as GenericNonUpdatableView, j as GenericSchema, G as GenericTable, f as GenericUpdatableView, h as GenericView, P as PostgrestError, d as PostgrestMaybeSingleResponse, e as PostgrestResponse, b as PostgrestResponseFailure, a as PostgrestResponseSuccess, c as PostgrestSingleResponse, k as Prettify } from './types-CYr9JiUE.js';
6
+ export { U as UseDbQuerySingleReturn, u as useDbQuery } from './useDbQuery-C-TL8jY1.js';
7
+ import * as _tanstack_react_query from '@tanstack/react-query';
8
+ import { QueryClient } from '@tanstack/react-query';
9
+ import { FileOptions } from '@supabase/storage-js';
10
+ export { D as DatabaseTypes, P as PublicTableNames, R as ResolveRowType, S as SchemaNames, l as SchemaTableNames, T as TableIdentifier, r as UseAdvanceQueryOptions, s as UseAdvanceQueryResult, n as UseDbCountOptions, o as UseDbCountResult, U as UseDbInfiniteQueryOptions, m as UseDbInfiniteQueryResult, q as UseDbQueryOptions, p as UseDbQueryResult, k as useAdvanceQuery, a as useDataLayer, j as useDbCount, j as useDbCountV3, d as useDbDeleteV3, i as useDbInfiniteQuery, i as useDbInfiniteQueryV3, e as useDbInsertV3, g as useDbQueryById, f as useDbQueryV3, h as useDbUpdateV3, u as useDbUpsert, u as useDbUpsertV3, u as useUpsert } from './useDbCount-Id14x_1P.js';
11
+ export { useOnlineStatus, useSyncControl, useSyncStatus } from './hooks/index.js';
12
+ export { u as useBatchDelete, a as useBatchUpsert } from './useBatchUpsert-9OYjibLh.js';
13
+ import { DatabaseSchema, QueryOptions, DataLayerConfig } from './core/index.js';
14
+ export { AdapterRegistry as AdapterRegistryInterface, AutoStrategy, BuiltQuery, CachedStrategy, ColumnInfo, ColumnType, ConnectionConfig, DataAdapter, DataLayerHooks, DeleteMutationResult, ExtractInsert, ExtractRow, ExtractUpdate, HybridStrategy, MutationHookResult, MutationResult, OrderBy, ParsedSelect, PowerSyncStrategy, QueryResult, QuerySingleResult, RelationshipInfo, RelationshipType, ResolvedRelationship, ScopeDefinition, SelectColumn, SelectRelation, SupabaseStrategy, SyncControl, SyncMode, SyncScope, SyncStatus, TableNames, TableSchema, TableStrategy, UseDbMutationHook, UseDbQueryByIdHook, UseDbQueryHook, WhereClause, WhereOperators } from './core/index.js';
15
+ export { UsePartialAdvancedQueryResult, UsePartialQueryResult, UseQuerySingleReturn, extractColumnNames, extractRelationNames, getRelationSelect, hasRelation, parseSelect, stringifySelect, tokenizeTopLevel, useAdvancedFilterQuery, useAdvancedQuery, useInfiniteQuery, usePartialAdvancedQuery, usePartialQuery, useQuery } from './query/index.js';
16
+ import { Q as QueryExecutor, P as PowerSyncDatabase$1 } from './executor-CB4KHyYG.js';
17
+ export { e as RelationJoinData, R as RelationshipResolver, b as ResultJoiner, S as SQLBuilder, f as createQueryExecutor, c as createRelationshipResolver, d as createResultJoiner, a as createSQLBuilder } from './executor-CB4KHyYG.js';
18
+ import { T as TableDataAdapter, C as CapableDataAdapter, c as AdapterCapabilities, A as AdapterQueryResult, p as DataLayerContextValue, S as SyncStatusInfo } from './DataLayerContext-ZmLPYR_s.js';
19
+ export { f as ADAPTER_STRATEGIES, i as AdapterAutoDetector, a as AdapterConfig, d as AdapterDependencies, b as AdapterFactory, g as AdapterRegistry, e as AdapterStrategyType, k as AutoDetectionResult, l as AutoDetectorOptions, m as BackendChangeListener, B as BackendStatus, D as DataLayerContext, n as DataLayerCoreContext, q as DataLayerCoreContextValue, s as DataLayerStatus, o as DataLayerStatusContext, r as DataLayerStatusContextValue, j as createAdapterAutoDetector, h as createAdapterRegistry } from './DataLayerContext-ZmLPYR_s.js';
20
+ import * as react from 'react';
21
+ import react__default, { ReactNode, JSX } from 'react';
22
+ import { SupabaseClient } from '@supabase/supabase-js';
23
+ export { C as ClientInstanceId, S as SupabaseDatabaseTypes, a as SupabaseProvider, T as TypedSupabaseClient, U as UserSessionId, c as createNewSupabaseClient, u as default, o as onSupabaseInitialized, s as setDefaultOptions, t as typedSupabase, u as useSupabase } from './useSupabase-DvWVuHHE.js';
24
+ export { e as UserMetadataContextProvider, c as UserMetadataContextType, a as UserMetadataInsert, U as UserMetadataRow, b as UserMetadataUpdate, u as useLiveChangesIndicator, h as useSetUserMetadata, f as useUserMetadata, i as useUserMetadataState, g as useUserMetadataValue, d as userMetadataContext } from './UserMetadataContext-B8gVWGMl.js';
25
+ import * as react_dropzone from 'react-dropzone';
26
+ import { FileRejection, FileError } from 'react-dropzone';
27
+ export { AnyPostgrestResponse, FilterDefinition, FilterDefinitions, FilterFn, NestedPath, OPERATOR_MAP, OperatorFn, OrderDefinition, Path, PostgrestFilter, PostgrestFilterOperator, PostgrestHasMorePaginationCacheData, PostgrestHasMorePaginationResponse, PostgrestPaginationCacheData, PostgrestPaginationResponse, PostgrestParser, PostgrestQueryParser, PostgrestQueryParserOptions, SUPPORTED_OPERATORS, ValueType, binarySearch, buildSortedComparator, denormalize, encodeObject, extractPathsFromFilters, filterFilterDefinitionsByPaths, findFilters, findIndexOrdered, findLastIndex, get, getTable, groupPathsRecursive, ifDateGetTime, isAndFilter, isAnyPostgrestResponse, isFilterDefinition, isISODateString, isNestedPath, isNotNull, isObject, isOrFilter, isPostgrestBuilder, isPostgrestHasMorePaginationCacheData, isPostgrestHasMorePaginationResponse, isPostgrestPaginationCacheData, isPostgrestPaginationResponse, parseOrderByKey, parseSelectParam, parseValue, removeAliasFromDeclaration, removeFirstPathElement, setFilterValue, sortSearchParams } from './parser/index.js';
28
+ export { G as GetResult, S as SelectQueryError } from './select-query-parser-BwyHum1L.js';
29
+ export { Accessory, Address, AdvanceQuery, AdvanceQueryNotificationSetting, AdvancedQueryView, BillableService, BillingDetails, CachedEmbedding, Changelog, ChangelogEntry, ChangelogMedia, ChargeTable, Circuit, Client, Comment, CommentReaction, CommentRead, CommentSection, CommentTag, CommonNote, CommonNoteCategory, CommonNoteSubCategory, ControlComponent, ControlComponentDatasheet, Controller, CoreSavedQuery, CoreSavedQueryAccess, Currency, CurrencyUsdConversion, DataExchangeImport, Datasheet, Dimension, DimmerModule, DimmerRack, Embedding, EquipmentConfigurationGroup, EquipmentFixture, EquipmentFixtureConfiguration, EquipmentFixtureConfigurationAccessoryEntry, EquipmentFixtureConfigurationControlComponentEntry, EquipmentFixtureCost, EquipmentFixtureDatasheet, EquipmentFixtureDimension, EquipmentFixtureDocument, EquipmentFixtureLampConfiguration, EquipmentFixtureListing, EquipmentFixtureMode, EquipmentFixtureModeChannel, EquipmentFixturePreset, EquipmentFixtureUnit, EquipmentFixtureUnitControl, EquipmentFixtureUnitLocation, EquipmentFixtureUnitLocationTag, EquipmentFixtureUnitLocationTagValue, EquipmentFixtureUnitPatternEntry, EquipmentFixtureWeight, EquipmentType, EquipmentUnitMediaContent, Expense, ExpenseLineItem, ExpenseReport, Fixture, FixtureCatalog, FixtureCatalogItem, FixtureCategory, FixtureTag, GlobalExpenseReport, HighlightServer, HighlightServerInstance, HighlightServerInstanceLog, HighlightServerInstanceOptions, HighlightServerInstanceStatus, HighlightServerRequest, Invoice, InvoiceSummaryTable, InvoiceTerm, InvoiceTermCondition, Lamp, LampCategory, LampCurrentListing, LampType, LicenseAssignment, Logo, Manufacturer, ManufacturerTag, ManufacturerToTag, OperationLog, OrderHinted, Organization, OrganizationUser, OrganizationUserAccess, ParameterMappingProfile, ParameterMappingProfileAssignment, Pattern, PaymentCustomer, PaymentInvoice, PaymentPaymentIntents, PaymentPlan, PaymentProduct, PaymentProductFeature, PaymentSubscription, PaymentSubscriptionPlan, PhaseActivityBucket, ProfileConfig as Profile, ProfileConfig, ProfileTimeBank, Project, ProjectDatabase, ProjectDatabaseEquipmentConfigurationGroup, ProjectDatabaseExcelParameterAssignment, ProjectDatabaseGroup, ProjectDatabaseParameterMappingProfile, ProjectDefaultRateByTitle, ProjectDocument, ProjectDocumentLineItem, PunchList, PunchListAccess, PunchListItem, PunchListItemAssignment, PunchListItemAttachedEntity, PunchListItemAttachment, PunchListItemCheckListItem, PunchListPage, PunchListPageAccess, PunchListUserOrderHint, QrCode, RetainageItem, RevitEquipmentUnitChange, RevitImport, RevitValueChangedEvent, Role, Service, ServiceCosts, ServiceStorageHourly, SmartCode, SmartCodeTag, Subtask, SystemBroadcastChannel, SystemBroadcastChannelThrottle, SystemConfiguration, SystemEmailNotification, SystemEvent, SystemEventListener, SystemEventWorker, SystemGlobalVariables, SystemHealthCheck, SystemInAppNotification, SystemLog, SystemMutedTopic, SystemNotification, SystemPushNotification, SystemSubscriber, SystemSupportAccess, SystemSupportTeam, SystemTask, SystemTaskAttempt, SystemTaskAttemptAccess, SystemTemp, SystemTicket, SystemTicketAttachment, SystemTicketComment, SystemTicketCommentAttachment, SystemUserPushTokens, Tag, Task, TaxCategory, Ticket, TicketAttachment, TicketComment, TicketCommentAttachment, TimeActivity, TimeBankTransaction, UserMetadata, UserTimesheet, WeeklyTimesheet, WorkEstimation, WorkEstimationLineItem, WorkingPhase, WorkingPhaseBillingItemDailySummary, WorkingPhaseBillingItemLatestSummary, WorkingPhaseCategory, WorkingPhaseDailySummary, WorkingPhaseRoleRate, WorkingPhaseSummary } from './gen/index.js';
30
+ import * as react_jsx_runtime from 'react/jsx-runtime';
31
+ import 'moment';
32
+ import '@supabase-cache-helpers/postgrest-react-query';
33
+ import '@pol-studios/utils';
34
+ import '@supabase/functions-js';
35
+ import '@supabase/postgrest-js';
36
+ import '@supabase/supabase-js/dist/module/lib/types.js';
37
+
38
+ type RequestOptions = {
39
+ onUploadProgress?: (bytesUploaded: number, bytesTotal: number) => any;
40
+ };
41
+ declare function sanitizeStorageKey(path: string): string;
42
+ declare function useDbAttachmentUpload(bucketId: string, options?: RequestOptions): _tanstack_react_query.UseMutationResult<{
43
+ bucketId: string;
44
+ path: string;
45
+ contentType: string;
46
+ }, Error, {
47
+ directory?: string;
48
+ fileName?: string;
49
+ file: File | Blob | Pick<ReadableStreamDefaultReader, "read">;
50
+ onUploadProgress?: (bytesUploaded: number, bytesTotal: number) => any;
51
+ } & FileOptions, unknown>;
52
+
53
+ /**
54
+ * PowerSync Adapter
55
+ *
56
+ * Wraps the QueryExecutor to execute queries against PowerSync's local SQLite database.
57
+ * Implements the TableDataAdapter interface for use with the V3 data layer.
58
+ *
59
+ * This adapter provides offline-first data access by querying the local SQLite
60
+ * database that PowerSync keeps synchronized with Supabase.
61
+ */
62
+
63
+ /**
64
+ * Handler interface for PowerSync watch callbacks.
65
+ */
66
+ interface WatchHandler {
67
+ onResult: (results: {
68
+ rows?: {
69
+ _array: Record<string, unknown>[];
70
+ };
71
+ }) => void;
72
+ onError?: (error: Error) => void;
73
+ }
74
+ /**
75
+ * Options for PowerSync watch operations.
76
+ */
77
+ interface SQLWatchOptions {
78
+ signal?: AbortSignal;
79
+ tables?: string[];
80
+ throttleMs?: number;
81
+ }
82
+ /**
83
+ * Extended PowerSync database interface that includes watch functionality.
84
+ * This extends the base interface from the executor to add reactive query support.
85
+ *
86
+ * The watch method is optional to maintain backward compatibility with databases
87
+ * that don't support reactive queries. When not available, subscribe will fall
88
+ * back to polling.
89
+ */
90
+ interface PowerSyncDatabase {
91
+ getAll<T>(sql: string, params?: unknown[]): Promise<T[]>;
92
+ get<T>(sql: string, params?: unknown[]): Promise<T | null>;
93
+ execute(sql: string, params?: unknown[]): Promise<{
94
+ rowsAffected: number;
95
+ }>;
96
+ /**
97
+ * Watch a SQL query for changes.
98
+ * Executes the query and invokes the handler whenever the underlying data changes.
99
+ * Optional - if not available, subscribe will fall back to polling.
100
+ */
101
+ watch?(sql: string, parameters?: unknown[], handler?: WatchHandler, options?: SQLWatchOptions): void;
102
+ }
103
+ /**
104
+ * PowerSyncAdapter implements the TableDataAdapter interface by delegating
105
+ * all operations to the QueryExecutor.
106
+ *
107
+ * @example
108
+ * const adapter = createPowerSyncAdapter(powerSyncDb, schema);
109
+ *
110
+ * // Query with filtering and pagination
111
+ * const { data, count } = await adapter.query<EquipmentUnit>("EquipmentUnit", {
112
+ * where: { status: "active" },
113
+ * orderBy: [{ field: "name", direction: "asc" }],
114
+ * limit: 10
115
+ * });
116
+ *
117
+ * // Query with relations
118
+ * const { data } = await adapter.query<EquipmentUnitWithRelations>("EquipmentUnit", {
119
+ * select: "*, EquipmentFixture(*), ProjectDatabase(name)"
120
+ * });
121
+ */
122
+ /**
123
+ * Function type for resolving table names to PowerSync aliases.
124
+ * Used to map schema-qualified names like "core.Profile" to aliases like "CoreProfile".
125
+ */
126
+ type TableNameResolver = (table: string) => string;
127
+ declare class PowerSyncAdapter implements TableDataAdapter, CapableDataAdapter {
128
+ private db;
129
+ private schema;
130
+ /**
131
+ * Unique identifier for this adapter type
132
+ */
133
+ readonly name = "powersync";
134
+ /**
135
+ * Capabilities supported by this adapter
136
+ */
137
+ readonly capabilities: AdapterCapabilities;
138
+ /**
139
+ * The underlying query executor
140
+ */
141
+ private executor;
142
+ /**
143
+ * Optional custom table name resolver.
144
+ * If not provided, uses default auto-alias generation.
145
+ */
146
+ private tableNameResolver?;
147
+ /**
148
+ * Create a new PowerSyncAdapter
149
+ *
150
+ * @param db - PowerSync database instance
151
+ * @param schema - Database schema for relationship resolution
152
+ * @param tableNameResolver - Optional custom resolver for table names to PowerSync aliases
153
+ */
154
+ constructor(db: PowerSyncDatabase, schema: DatabaseSchema, tableNameResolver?: TableNameResolver);
155
+ /**
156
+ * Resolve a table name to its PowerSync alias.
157
+ * Schema-qualified names like "chat.Conversation" become "Conversation" (schema stripped).
158
+ * Unqualified names pass through unchanged.
159
+ *
160
+ * @param table - Original table name (may be schema-qualified)
161
+ * @returns The PowerSync alias to use in SQLite queries
162
+ */
163
+ private resolveTableName;
164
+ /**
165
+ * Execute a query and return results with optional count for pagination.
166
+ *
167
+ * @param table - The table name to query
168
+ * @param options - Query options (select, where, orderBy, limit, offset)
169
+ * @returns Promise resolving to query results with optional count
170
+ */
171
+ query<T>(table: string, options?: QueryOptions): Promise<AdapterQueryResult<T>>;
172
+ /**
173
+ * Query a single record by ID.
174
+ *
175
+ * @param table - The table name to query
176
+ * @param id - The record ID
177
+ * @param options - Optional query options (mainly for select)
178
+ * @returns Promise resolving to the record or null if not found
179
+ */
180
+ queryById<T>(table: string, id: string, options?: Pick<QueryOptions, "select">): Promise<T | null>;
181
+ /**
182
+ * Subscribe to changes on a query using PowerSync's native watch() API.
183
+ *
184
+ * This uses PowerSync's reactive query watching which efficiently detects
185
+ * changes to the underlying data and re-executes the query only when needed.
186
+ *
187
+ * If the database doesn't support watch(), falls back to polling every 5 seconds.
188
+ *
189
+ * @param table - The table name to watch
190
+ * @param options - Query options to filter what to watch
191
+ * @param callback - Function called with updated data
192
+ * @returns Unsubscribe function
193
+ */
194
+ subscribe<T>(table: string, options: QueryOptions, callback: (data: T[]) => void): () => void;
195
+ /**
196
+ * Fallback polling-based subscription for databases that don't support watch().
197
+ *
198
+ * @internal
199
+ */
200
+ private subscribeWithPolling;
201
+ /**
202
+ * Insert a new record.
203
+ *
204
+ * @param table - The table name
205
+ * @param data - The data to insert
206
+ * @returns Promise resolving to the inserted record
207
+ */
208
+ insert<T>(table: string, data: Partial<T>): Promise<T>;
209
+ /**
210
+ * Update an existing record by ID.
211
+ *
212
+ * @param table - The table name
213
+ * @param id - The record ID to update
214
+ * @param data - The data to update
215
+ * @returns Promise resolving to the updated record
216
+ */
217
+ update<T>(table: string, id: string, data: Partial<T>): Promise<T>;
218
+ /**
219
+ * Upsert (insert or update) a record.
220
+ * If the record has an ID and exists, it will be updated.
221
+ * Otherwise, a new record will be inserted.
222
+ *
223
+ * @param table - The table name
224
+ * @param data - The data to upsert
225
+ * @returns Promise resolving to the upserted record
226
+ */
227
+ upsert<T>(table: string, data: Partial<T>): Promise<T>;
228
+ /**
229
+ * Delete a record by ID.
230
+ *
231
+ * @param table - The table name
232
+ * @param id - The record ID to delete
233
+ * @returns Promise that resolves when deletion is complete
234
+ */
235
+ delete(table: string, id: string): Promise<void>;
236
+ /**
237
+ * Get the underlying QueryExecutor for advanced use cases.
238
+ *
239
+ * This allows direct access to the executor for operations that
240
+ * may not be covered by the TableDataAdapter interface.
241
+ *
242
+ * @returns The QueryExecutor instance
243
+ */
244
+ getExecutor(): QueryExecutor;
245
+ /**
246
+ * Get the raw PowerSync database for advanced use cases.
247
+ *
248
+ * This allows direct SQL execution when the adapter methods
249
+ * are not sufficient.
250
+ *
251
+ * @returns The PowerSyncDatabase instance
252
+ */
253
+ getDatabase(): PowerSyncDatabase;
254
+ /**
255
+ * Get the database schema.
256
+ *
257
+ * @returns The DatabaseSchema used for relationship resolution
258
+ */
259
+ getSchema(): DatabaseSchema;
260
+ }
261
+ /**
262
+ * Create a new PowerSyncAdapter instance.
263
+ *
264
+ * This is the recommended way to create a PowerSyncAdapter as it provides
265
+ * a cleaner API and allows for future enhancements without breaking changes.
266
+ *
267
+ * @param db - PowerSync database instance
268
+ * @param schema - Database schema for relationship resolution
269
+ * @returns A new PowerSyncAdapter instance
270
+ *
271
+ * @example
272
+ * import { createPowerSyncAdapter } from "./adapters/powersync-adapter";
273
+ *
274
+ * const adapter = createPowerSyncAdapter(powerSyncDb, databaseSchema);
275
+ *
276
+ * // Use the adapter
277
+ * const { data } = await adapter.query("EquipmentUnit", {
278
+ * where: { status: "active" }
279
+ * });
280
+ */
281
+ declare function createPowerSyncAdapter(db: PowerSyncDatabase, schema: DatabaseSchema): PowerSyncAdapter;
282
+
283
+ /**
284
+ * V3 Data Layer Provider
285
+ *
286
+ * React context provider that initializes adapters, manages the PowerSync lifecycle,
287
+ * and provides context for all V3 hooks. This is the main entry point for the V3
288
+ * data layer in a React application.
289
+ */
290
+
291
+ /**
292
+ * Props for DataLayerProvider
293
+ */
294
+ interface DataLayerProviderProps {
295
+ /** Data layer configuration */
296
+ config: DataLayerConfig;
297
+ /** Children to render */
298
+ children: ReactNode;
299
+ /**
300
+ * Optional PowerSync database instance.
301
+ *
302
+ * This accepts any object that implements the PowerSyncDatabase interface,
303
+ * including the AbstractPowerSyncDatabase from @pol-studios/powersync.
304
+ *
305
+ * When using with @pol-studios/powersync, pass the `db` value from usePowerSync():
306
+ * @example
307
+ * ```tsx
308
+ * // With @pol-studios/powersync
309
+ * const { db, isReady } = usePowerSync();
310
+ *
311
+ * if (!isReady) return <Loading />;
312
+ *
313
+ * return (
314
+ * <DataLayerProvider
315
+ * config={config}
316
+ * powerSyncInstance={db}
317
+ * supabaseClient={supabase}
318
+ * queryClient={queryClient}
319
+ * >
320
+ * {children}
321
+ * </DataLayerProvider>
322
+ * );
323
+ * ```
324
+ */
325
+ powerSyncInstance?: PowerSyncDatabase$1 | null;
326
+ /** Supabase client (required) */
327
+ supabaseClient: SupabaseClient;
328
+ /** React Query client (required) */
329
+ queryClient: QueryClient;
330
+ /** Callback when initialization completes */
331
+ onInitialized?: (context: DataLayerContextValue) => void;
332
+ /** Callback when error occurs */
333
+ onError?: (error: Error) => void;
334
+ /**
335
+ * Current sync status from @pol-studios/powersync.
336
+ * Pass the status object from useSyncStatus() hook.
337
+ * When hasSynced is false and useOnlineUntilSynced is true (default),
338
+ * queries will use Supabase until initial sync completes.
339
+ */
340
+ powerSyncSyncStatus?: SyncStatusInfo;
341
+ }
342
+ /**
343
+ * Provider component for the V3 data layer.
344
+ *
345
+ * This provider:
346
+ * - Creates and manages the AdapterRegistry
347
+ * - Initializes the AdapterAutoDetector for backend selection
348
+ * - Sets up Supabase and PowerSync adapters
349
+ * - Tracks online/offline status
350
+ * - Provides context for all V3 hooks
351
+ *
352
+ * @example
353
+ * ```tsx
354
+ * import { DataLayerProvider } from "@pol-studios/db";
355
+ *
356
+ * function App() {
357
+ * return (
358
+ * <DataLayerProvider
359
+ * config={dataLayerConfig}
360
+ * supabaseClient={supabase}
361
+ * queryClient={queryClient}
362
+ * powerSyncInstance={powerSyncDb}
363
+ * >
364
+ * <YourApp />
365
+ * </DataLayerProvider>
366
+ * );
367
+ * }
368
+ * ```
369
+ */
370
+ declare function DataLayerProvider({ config, children, powerSyncInstance, supabaseClient, queryClient, onInitialized, onError, powerSyncSyncStatus, }: DataLayerProviderProps): JSX.Element;
371
+
372
+ interface FileWithPreview extends File {
373
+ preview?: string;
374
+ errors: readonly FileError[];
375
+ }
376
+ type UseSupabaseUploadOptions = {
377
+ /**
378
+ * Name of bucket to upload files to in your Supabase project
379
+ */
380
+ bucketName: string;
381
+ /**
382
+ * Folder to upload files to in the specified bucket within your Supabase project.
383
+ *
384
+ * Defaults to uploading files to the root of the bucket
385
+ *
386
+ * e.g If specified path is `test`, your file will be uploaded as `test/file_name`
387
+ */
388
+ path?: string;
389
+ /**
390
+ * Allowed MIME types for each file upload (e.g `image/png`, `text/html`, etc). Wildcards are also supported (e.g `image/*`).
391
+ *
392
+ * Defaults to allowing uploading of all MIME types.
393
+ */
394
+ allowedMimeTypes?: string[];
395
+ /**
396
+ * Maximum upload size of each file allowed in bytes. (e.g 1000 bytes = 1 KB)
397
+ */
398
+ maxFileSize?: number;
399
+ /**
400
+ * Maximum number of files allowed per upload.
401
+ */
402
+ maxFiles?: number;
403
+ /**
404
+ * The number of seconds the asset is cached in the browser and in the Supabase CDN.
405
+ *
406
+ * This is set in the Cache-Control: max-age=<seconds> header. Defaults to 3600 seconds.
407
+ */
408
+ cacheControl?: number;
409
+ /**
410
+ * When set to true, the file is overwritten if it exists.
411
+ *
412
+ * When set to false, an error is thrown if the object already exists. Defaults to `false`
413
+ */
414
+ upsert?: boolean;
415
+ };
416
+ type UseSupabaseUploadReturn = ReturnType<typeof useSupabaseUpload>;
417
+ declare const useSupabaseUpload: (options: UseSupabaseUploadOptions) => {
418
+ open: () => void;
419
+ isFocused: boolean;
420
+ isDragActive: boolean;
421
+ isDragAccept: boolean;
422
+ isDragReject: boolean;
423
+ isFileDialogActive: boolean;
424
+ acceptedFiles: readonly react_dropzone.FileWithPath[];
425
+ fileRejections: readonly FileRejection[];
426
+ rootRef: React.RefObject<HTMLElement>;
427
+ inputRef: React.RefObject<HTMLInputElement>;
428
+ getRootProps: <T extends react_dropzone.DropzoneRootProps>(props?: T) => T;
429
+ getInputProps: <T extends react_dropzone.DropzoneInputProps>(props?: T) => T;
430
+ files: FileWithPreview[];
431
+ setFiles: react.Dispatch<react.SetStateAction<FileWithPreview[]>>;
432
+ successes: string[];
433
+ isSuccess: boolean;
434
+ loading: boolean;
435
+ errors: {
436
+ name: string;
437
+ message: string;
438
+ }[];
439
+ setErrors: react.Dispatch<react.SetStateAction<{
440
+ name: string;
441
+ message: string;
442
+ }[]>>;
443
+ onUpload: () => Promise<void>;
444
+ maxFileSize: number;
445
+ maxFiles: number;
446
+ allowedMimeTypes: string[];
447
+ };
448
+
449
+ /**
450
+ * Conflict Types for @pol-studios/db
451
+ *
452
+ * Canonical type definitions for conflict detection and resolution.
453
+ * These types are shared between @pol-studios/db and @pol-studios/powersync.
454
+ */
455
+ /**
456
+ * Represents a field-level conflict where both local and server changed the same field.
457
+ */
458
+ interface FieldConflict {
459
+ /** The field name that has conflicting changes */
460
+ field: string;
461
+ /** The local (pending) value */
462
+ localValue: unknown;
463
+ /** The current server value */
464
+ serverValue: unknown;
465
+ /** User who made the server change (from AuditLog.changeBy) */
466
+ changedBy: string | null;
467
+ /** When the server change occurred (from AuditLog.changeAt) */
468
+ changedAt: Date;
469
+ }
470
+ /**
471
+ * Result of checking for conflicts between local changes and server state.
472
+ */
473
+ interface ConflictCheckResult {
474
+ /** Whether any field conflicts were detected */
475
+ hasConflict: boolean;
476
+ /** List of field-level conflicts */
477
+ conflicts: FieldConflict[];
478
+ /** Fields that can safely sync (no server changes) */
479
+ nonConflictingChanges: string[];
480
+ /** The table name */
481
+ table: string;
482
+ /** The record ID */
483
+ recordId: string;
484
+ }
485
+ /**
486
+ * User's resolution choice for a conflict.
487
+ */
488
+ type ConflictResolution = {
489
+ action: 'overwrite';
490
+ } | {
491
+ action: 'keep-server';
492
+ } | {
493
+ action: 'partial';
494
+ fields: string[];
495
+ };
496
+
497
+ /**
498
+ * Interface for ConflictBus from @pol-studios/powersync.
499
+ * Defined here to avoid circular dependency between packages.
500
+ */
501
+ interface ConflictBusInterface {
502
+ onConflict: (listener: (conflict: ConflictCheckResult) => void) => () => void;
503
+ onResolution: (listener: (table: string, recordId: string, resolution: ConflictResolution) => void) => () => void;
504
+ emitConflict: (conflict: ConflictCheckResult) => void;
505
+ emitResolution: (table: string, recordId: string, resolution: ConflictResolution) => void;
506
+ }
507
+ /**
508
+ * Context value provided to consumers.
509
+ */
510
+ interface ConflictContextValue {
511
+ /** Current conflict state */
512
+ pendingConflicts: ConflictCheckResult[];
513
+ /** Add a conflict (called by connector) */
514
+ addConflict: (conflict: ConflictCheckResult) => void;
515
+ /** Resolve a single conflict by table and record ID */
516
+ resolveConflict: (table: string, recordId: string, resolution: ConflictResolution) => void;
517
+ /** Resolve all pending conflicts with the same resolution */
518
+ resolveAll: (resolution: ConflictResolution) => void;
519
+ /** Remove a conflict by table and record ID (after sync completes) */
520
+ removeConflict: (table: string, recordId: string) => void;
521
+ /** Get resolution for a specific table and record */
522
+ getResolution: (table: string, recordId: string) => ConflictResolution | undefined;
523
+ /** Clear all resolved conflicts from the resolutions map */
524
+ clearResolved: () => void;
525
+ /** Clear all conflicts (resolved and pending) */
526
+ clearAll: () => void;
527
+ /** Whether there are any pending conflicts */
528
+ hasConflicts: boolean;
529
+ }
530
+ declare const ConflictContext: react__default.Context<ConflictContextValue>;
531
+ interface ConflictProviderProps {
532
+ children: react__default.ReactNode;
533
+ /**
534
+ * Optional: Event bus for receiving conflicts from the connector.
535
+ * When provided, the provider will:
536
+ * - Subscribe to conflict events and add them to state
537
+ * - Emit resolution events when conflicts are resolved
538
+ */
539
+ conflictBus?: ConflictBusInterface;
540
+ }
541
+ /**
542
+ * Provider component for conflict state management.
543
+ *
544
+ * Wrap your app with this provider to enable conflict detection and resolution.
545
+ *
546
+ * @example
547
+ * ```tsx
548
+ * <PowerSyncProvider connector={connector}>
549
+ * <ConflictProvider>
550
+ * <App />
551
+ * </ConflictProvider>
552
+ * </PowerSyncProvider>
553
+ * ```
554
+ */
555
+ declare function ConflictProvider({ children, conflictBus }: ConflictProviderProps): react_jsx_runtime.JSX.Element;
556
+
557
+ /**
558
+ * Conflict State Hooks for @pol-studios/db
559
+ *
560
+ * Provides hooks for accessing and filtering conflict state.
561
+ */
562
+
563
+ /**
564
+ * Hook to access the full conflict state and actions.
565
+ *
566
+ * @throws Error if used outside of ConflictProvider
567
+ * @returns Full conflict context value
568
+ *
569
+ * @example
570
+ * ```tsx
571
+ * function ConflictManager() {
572
+ * const { pendingConflicts, resolveAll, clearResolved } = useConflictState();
573
+ *
574
+ * return (
575
+ * <View>
576
+ * <Text>{pendingConflicts.length} conflicts pending</Text>
577
+ * <Button onPress={() => resolveAll({ action: 'keep-server' })}>
578
+ * Accept All Server Changes
579
+ * </Button>
580
+ * </View>
581
+ * );
582
+ * }
583
+ * ```
584
+ */
585
+ declare function useConflictState(): ConflictContextValue;
586
+ /**
587
+ * Hook to get only pending conflicts (read-only).
588
+ *
589
+ * Use this when you only need to display conflicts without resolution actions.
590
+ *
591
+ * @returns Array of pending conflicts
592
+ *
593
+ * @example
594
+ * ```tsx
595
+ * function ConflictBadge() {
596
+ * const conflicts = usePendingConflicts();
597
+ * if (conflicts.length === 0) return null;
598
+ * return <Badge count={conflicts.length} />;
599
+ * }
600
+ * ```
601
+ */
602
+ declare function usePendingConflicts(): ConflictCheckResult[];
603
+ /**
604
+ * Hook to check if there are any pending conflicts.
605
+ *
606
+ * Optimized for conditional rendering - only triggers re-render on boolean change.
607
+ *
608
+ * @returns True if there are pending conflicts
609
+ *
610
+ * @example
611
+ * ```tsx
612
+ * function App() {
613
+ * const hasConflicts = useHasConflicts();
614
+ * return (
615
+ * <>
616
+ * {hasConflicts && <ConflictBanner />}
617
+ * <MainContent />
618
+ * </>
619
+ * );
620
+ * }
621
+ * ```
622
+ */
623
+ declare function useHasConflicts(): boolean;
624
+ /**
625
+ * Hook to get a specific conflict by table and record ID.
626
+ *
627
+ * Returns null if no conflict exists for the record.
628
+ *
629
+ * @param table - The table name
630
+ * @param recordId - The record ID to look up
631
+ * @returns The conflict for this record, or null
632
+ *
633
+ * @example
634
+ * ```tsx
635
+ * function RecordEditor({ table, recordId }: { table: string; recordId: string }) {
636
+ * const conflict = useConflictForRecord(table, recordId);
637
+ *
638
+ * if (conflict) {
639
+ * return <ConflictWarning conflict={conflict} />;
640
+ * }
641
+ *
642
+ * return <EditForm recordId={recordId} />;
643
+ * }
644
+ * ```
645
+ */
646
+ declare function useConflictForRecord(table: string, recordId: string): ConflictCheckResult | null;
647
+ /**
648
+ * Hook to get conflicts filtered by table name.
649
+ *
650
+ * Useful for showing conflicts scoped to a specific entity type.
651
+ *
652
+ * @param table - The table name to filter by
653
+ * @returns Conflicts for the specified table
654
+ *
655
+ * @example
656
+ * ```tsx
657
+ * function EquipmentConflicts() {
658
+ * const conflicts = useConflictsForTable('EquipmentFixtureUnit');
659
+ * return (
660
+ * <FlatList
661
+ * data={conflicts}
662
+ * renderItem={({ item }) => <ConflictCard conflict={item} />}
663
+ * />
664
+ * );
665
+ * }
666
+ * ```
667
+ */
668
+ declare function useConflictsForTable(table: string): ConflictCheckResult[];
669
+ /**
670
+ * Hook to get conflict count by table.
671
+ *
672
+ * Returns a map of table names to conflict counts for summary display.
673
+ *
674
+ * @returns Map of table name to conflict count
675
+ *
676
+ * @example
677
+ * ```tsx
678
+ * function ConflictSummary() {
679
+ * const countByTable = useConflictCountByTable();
680
+ * return (
681
+ * <View>
682
+ * {Array.from(countByTable.entries()).map(([table, count]) => (
683
+ * <Text key={table}>{table}: {count} conflicts</Text>
684
+ * ))}
685
+ * </View>
686
+ * );
687
+ * }
688
+ * ```
689
+ */
690
+ declare function useConflictCountByTable(): Map<string, number>;
691
+
692
+ /**
693
+ * Conflict Resolution Hook for @pol-studios/db
694
+ *
695
+ * Provides methods for resolving individual conflicts.
696
+ */
697
+
698
+ /**
699
+ * Return type for useConflictResolution hook.
700
+ */
701
+ interface UseConflictResolutionReturn {
702
+ /** The conflict being resolved */
703
+ conflict: ConflictCheckResult;
704
+ /** Resolve with a specific resolution */
705
+ resolve: (resolution: ConflictResolution) => void;
706
+ /** Accept server changes, discard local */
707
+ keepServer: () => void;
708
+ /** Overwrite server with local changes */
709
+ overwrite: () => void;
710
+ /** Only sync fields that don't conflict */
711
+ syncNonConflicting: () => void;
712
+ /** Sync specific fields only */
713
+ syncFields: (fields: string[]) => void;
714
+ /** Check if a specific field has a conflict */
715
+ hasFieldConflict: (field: string) => boolean;
716
+ /** Get conflict info for a specific field */
717
+ getFieldConflict: (field: string) => {
718
+ localValue: unknown;
719
+ serverValue: unknown;
720
+ changedBy: string | null;
721
+ changedAt: Date;
722
+ } | null;
723
+ }
724
+ /**
725
+ * Hook for resolving a specific conflict.
726
+ *
727
+ * Provides convenience methods for common resolution patterns.
728
+ *
729
+ * @param conflict - The conflict to resolve
730
+ * @returns Resolution methods and utilities
731
+ *
732
+ * @example
733
+ * ```tsx
734
+ * function ConflictCard({ conflict }: { conflict: ConflictCheckResult }) {
735
+ * const {
736
+ * keepServer,
737
+ * overwrite,
738
+ * syncNonConflicting,
739
+ * hasFieldConflict,
740
+ * getFieldConflict,
741
+ * } = useConflictResolution(conflict);
742
+ *
743
+ * return (
744
+ * <Card>
745
+ * <Text>Conflict on {conflict.table}</Text>
746
+ * {conflict.conflicts.map(fc => (
747
+ * <View key={fc.field}>
748
+ * <Text>{fc.field}</Text>
749
+ * <Text>Yours: {String(fc.localValue)}</Text>
750
+ * <Text>Theirs: {String(fc.serverValue)} by {fc.changedBy}</Text>
751
+ * </View>
752
+ * ))}
753
+ * <Button onPress={keepServer}>Keep Theirs</Button>
754
+ * <Button onPress={overwrite}>Use Mine</Button>
755
+ * <Button onPress={syncNonConflicting}>Sync Safe Fields Only</Button>
756
+ * </Card>
757
+ * );
758
+ * }
759
+ * ```
760
+ */
761
+ declare function useConflictResolution(conflict: ConflictCheckResult): UseConflictResolutionReturn;
762
+ /**
763
+ * Hook for bulk conflict resolution.
764
+ *
765
+ * Provides methods for resolving multiple conflicts at once.
766
+ *
767
+ * @returns Bulk resolution methods
768
+ *
769
+ * @example
770
+ * ```tsx
771
+ * function ConflictSummary() {
772
+ * const conflicts = usePendingConflicts();
773
+ * const { resolveAllKeepServer, resolveAllOverwrite } = useBulkConflictResolution();
774
+ *
775
+ * return (
776
+ * <View>
777
+ * <Text>{conflicts.length} conflicts</Text>
778
+ * <Button onPress={resolveAllKeepServer}>Accept All Server Changes</Button>
779
+ * <Button onPress={resolveAllOverwrite}>Overwrite All with Mine</Button>
780
+ * </View>
781
+ * );
782
+ * }
783
+ * ```
784
+ */
785
+ declare function useBulkConflictResolution(): {
786
+ resolveAllKeepServer: () => void;
787
+ resolveAllOverwrite: () => void;
788
+ resolveAllSyncNonConflicting: () => void;
789
+ clearResolved: () => void;
790
+ conflictCount: number;
791
+ };
792
+
793
+ export { AdapterCapabilities, AdapterQueryResult, CapableDataAdapter, type ConflictCheckResult, ConflictContext, type ConflictContextValue, ConflictProvider, type ConflictProviderProps, type ConflictResolution, DataLayerConfig, DataLayerContextValue, DataLayerProvider, type DataLayerProviderProps, DatabaseSchema, type FieldConflict, PowerSyncAdapter, PowerSyncDatabase$1 as PowerSyncDatabase, QueryExecutor, QueryOptions, SyncStatusInfo, TableDataAdapter, type UseConflictResolutionReturn, type UseSupabaseUploadOptions, type UseSupabaseUploadReturn, createPowerSyncAdapter, sanitizeStorageKey, useBulkConflictResolution, useConflictCountByTable, useConflictForRecord, useConflictResolution, useConflictState, useConflictsForTable, useDbAttachmentUpload as useDbUpload, useHasConflicts, usePendingConflicts, useSupabaseUpload };