supastash 0.1.0

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 (232) hide show
  1. package/README.md +250 -0
  2. package/dist/core/config/index.d.ts +90 -0
  3. package/dist/core/config/index.d.ts.map +1 -0
  4. package/dist/core/config/index.js +111 -0
  5. package/dist/core/schemaManager/index.d.ts +19 -0
  6. package/dist/core/schemaManager/index.d.ts.map +1 -0
  7. package/dist/core/schemaManager/index.js +53 -0
  8. package/dist/db/adapters/expo_sqlite.d.ts +3 -0
  9. package/dist/db/adapters/expo_sqlite.d.ts.map +1 -0
  10. package/dist/db/adapters/expo_sqlite.js +21 -0
  11. package/dist/db/adapters/rn_nitro.d.ts +3 -0
  12. package/dist/db/adapters/rn_nitro.d.ts.map +1 -0
  13. package/dist/db/adapters/rn_nitro.js +22 -0
  14. package/dist/db/adapters/rn_sqlite_storage.d.ts +3 -0
  15. package/dist/db/adapters/rn_sqlite_storage.d.ts.map +1 -0
  16. package/dist/db/adapters/rn_sqlite_storage.js +22 -0
  17. package/dist/db/dbErrorMsg.d.ts +2 -0
  18. package/dist/db/dbErrorMsg.d.ts.map +1 -0
  19. package/dist/db/dbErrorMsg.js +28 -0
  20. package/dist/db/dbInitializer.d.ts +7 -0
  21. package/dist/db/dbInitializer.d.ts.map +1 -0
  22. package/dist/db/dbInitializer.js +33 -0
  23. package/dist/hooks/supastashData/addPayloadToUI.d.ts +2 -0
  24. package/dist/hooks/supastashData/addPayloadToUI.d.ts.map +1 -0
  25. package/dist/hooks/supastashData/addPayloadToUI.js +36 -0
  26. package/dist/hooks/supastashData/dataState.d.ts +8 -0
  27. package/dist/hooks/supastashData/dataState.d.ts.map +1 -0
  28. package/dist/hooks/supastashData/dataState.js +7 -0
  29. package/dist/hooks/supastashData/eventQueues.d.ts +5 -0
  30. package/dist/hooks/supastashData/eventQueues.d.ts.map +1 -0
  31. package/dist/hooks/supastashData/eventQueues.js +54 -0
  32. package/dist/hooks/supastashData/fetchCalls.d.ts +9 -0
  33. package/dist/hooks/supastashData/fetchCalls.d.ts.map +1 -0
  34. package/dist/hooks/supastashData/fetchCalls.js +63 -0
  35. package/dist/hooks/supastashData/index.d.ts +53 -0
  36. package/dist/hooks/supastashData/index.d.ts.map +1 -0
  37. package/dist/hooks/supastashData/index.js +95 -0
  38. package/dist/hooks/supastashData/realtimeSubscription.d.ts +5 -0
  39. package/dist/hooks/supastashData/realtimeSubscription.d.ts.map +1 -0
  40. package/dist/hooks/supastashData/realtimeSubscription.js +95 -0
  41. package/dist/hooks/supastashData/registerSub.d.ts +4 -0
  42. package/dist/hooks/supastashData/registerSub.d.ts.map +1 -0
  43. package/dist/hooks/supastashData/registerSub.js +20 -0
  44. package/dist/hooks/supastashLogic.d.ts +19 -0
  45. package/dist/hooks/supastashLogic.d.ts.map +1 -0
  46. package/dist/hooks/supastashLogic.js +67 -0
  47. package/dist/hooks/syncEngine/index.d.ts +9 -0
  48. package/dist/hooks/syncEngine/index.d.ts.map +1 -0
  49. package/dist/hooks/syncEngine/index.js +66 -0
  50. package/dist/hooks/syncEngine/pullFromRemote/index.d.ts +5 -0
  51. package/dist/hooks/syncEngine/pullFromRemote/index.d.ts.map +1 -0
  52. package/dist/hooks/syncEngine/pullFromRemote/index.js +28 -0
  53. package/dist/hooks/syncEngine/pushLocal/index.d.ts +5 -0
  54. package/dist/hooks/syncEngine/pushLocal/index.d.ts.map +1 -0
  55. package/dist/hooks/syncEngine/pushLocal/index.js +36 -0
  56. package/dist/index.d.ts +14 -0
  57. package/dist/index.d.ts.map +1 -0
  58. package/dist/index.js +10 -0
  59. package/dist/store/tableFilters.d.ts +3 -0
  60. package/dist/store/tableFilters.d.ts.map +1 -0
  61. package/dist/store/tableFilters.js +2 -0
  62. package/dist/types/expoSqlite.types.d.ts +57 -0
  63. package/dist/types/index.d.ts +5 -0
  64. package/dist/types/index.d.ts.map +1 -0
  65. package/dist/types/index.js +1 -0
  66. package/dist/types/query.types.d.ts +153 -0
  67. package/dist/types/realtimeData.types.d.ts +186 -0
  68. package/dist/types/rnNitroSqlite.types.d.ts +101 -0
  69. package/dist/types/rnSqliteStorage.types.d.ts +67 -0
  70. package/dist/types/schemaManager.types.d.ts +44 -0
  71. package/dist/types/supastashConfig.types.d.ts +72 -0
  72. package/dist/types/syncEngine.types.d.ts +12 -0
  73. package/dist/utils/connection.d.ts +2 -0
  74. package/dist/utils/connection.d.ts.map +1 -0
  75. package/dist/utils/connection.js +7 -0
  76. package/dist/utils/events/eventBus.d.ts +3 -0
  77. package/dist/utils/events/eventBus.d.ts.map +1 -0
  78. package/dist/utils/events/eventBus.js +4 -0
  79. package/dist/utils/fetchData/buildFilter.d.ts +7 -0
  80. package/dist/utils/fetchData/buildFilter.d.ts.map +1 -0
  81. package/dist/utils/fetchData/buildFilter.js +13 -0
  82. package/dist/utils/fetchData/createTable.d.ts +8 -0
  83. package/dist/utils/fetchData/createTable.d.ts.map +1 -0
  84. package/dist/utils/fetchData/createTable.js +48 -0
  85. package/dist/utils/fetchData/deleteData.d.ts +3 -0
  86. package/dist/utils/fetchData/deleteData.d.ts.map +1 -0
  87. package/dist/utils/fetchData/deleteData.js +25 -0
  88. package/dist/utils/fetchData/fetchLocalData.d.ts +9 -0
  89. package/dist/utils/fetchData/fetchLocalData.d.ts.map +1 -0
  90. package/dist/utils/fetchData/fetchLocalData.js +51 -0
  91. package/dist/utils/fetchData/getKeyType.d.ts +7 -0
  92. package/dist/utils/fetchData/getKeyType.d.ts.map +1 -0
  93. package/dist/utils/fetchData/getKeyType.js +25 -0
  94. package/dist/utils/fetchData/initialFetch.d.ts +3 -0
  95. package/dist/utils/fetchData/initialFetch.d.ts.map +1 -0
  96. package/dist/utils/fetchData/initialFetch.js +20 -0
  97. package/dist/utils/fetchData/realTimeCall.d.ts +5 -0
  98. package/dist/utils/fetchData/realTimeCall.d.ts.map +1 -0
  99. package/dist/utils/fetchData/realTimeCall.js +43 -0
  100. package/dist/utils/fetchData/realTimeManager.d.ts +40 -0
  101. package/dist/utils/fetchData/realTimeManager.d.ts.map +1 -0
  102. package/dist/utils/fetchData/realTimeManager.js +262 -0
  103. package/dist/utils/fetchData/receiveData.d.ts +3 -0
  104. package/dist/utils/fetchData/receiveData.d.ts.map +1 -0
  105. package/dist/utils/fetchData/receiveData.js +38 -0
  106. package/dist/utils/fetchData/setDataInBatches.d.ts +3 -0
  107. package/dist/utils/fetchData/setDataInBatches.d.ts.map +1 -0
  108. package/dist/utils/fetchData/setDataInBatches.js +20 -0
  109. package/dist/utils/fetchData/validatePayload.d.ts +7 -0
  110. package/dist/utils/fetchData/validatePayload.d.ts.map +1 -0
  111. package/dist/utils/fetchData/validatePayload.js +18 -0
  112. package/dist/utils/genUUID.d.ts +2 -0
  113. package/dist/utils/genUUID.d.ts.map +1 -0
  114. package/dist/utils/genUUID.js +7 -0
  115. package/dist/utils/getTableSchema.d.ts +8 -0
  116. package/dist/utils/getTableSchema.d.ts.map +1 -0
  117. package/dist/utils/getTableSchema.js +28 -0
  118. package/dist/utils/logs.d.ts +7 -0
  119. package/dist/utils/logs.d.ts.map +1 -0
  120. package/dist/utils/logs.js +15 -0
  121. package/dist/utils/query/builder/crud.d.ts +50 -0
  122. package/dist/utils/query/builder/crud.d.ts.map +1 -0
  123. package/dist/utils/query/builder/crud.js +83 -0
  124. package/dist/utils/query/builder/filters.d.ts +145 -0
  125. package/dist/utils/query/builder/filters.d.ts.map +1 -0
  126. package/dist/utils/query/builder/filters.js +223 -0
  127. package/dist/utils/query/builder/index.d.ts +45 -0
  128. package/dist/utils/query/builder/index.d.ts.map +1 -0
  129. package/dist/utils/query/builder/index.js +60 -0
  130. package/dist/utils/query/builder/mainQuery.d.ts +10 -0
  131. package/dist/utils/query/builder/mainQuery.d.ts.map +1 -0
  132. package/dist/utils/query/builder/mainQuery.js +63 -0
  133. package/dist/utils/query/helpers/localDb/getLocalMethod.d.ts +15 -0
  134. package/dist/utils/query/helpers/localDb/getLocalMethod.d.ts.map +1 -0
  135. package/dist/utils/query/helpers/localDb/getLocalMethod.js +24 -0
  136. package/dist/utils/query/helpers/localDb/localQueryBuilder.d.ts +34 -0
  137. package/dist/utils/query/helpers/localDb/localQueryBuilder.d.ts.map +1 -0
  138. package/dist/utils/query/helpers/localDb/localQueryBuilder.js +52 -0
  139. package/dist/utils/query/helpers/mainQueryHelpers.d.ts +12 -0
  140. package/dist/utils/query/helpers/mainQueryHelpers.d.ts.map +1 -0
  141. package/dist/utils/query/helpers/mainQueryHelpers.js +164 -0
  142. package/dist/utils/query/helpers/queryValidator.d.ts +7 -0
  143. package/dist/utils/query/helpers/queryValidator.d.ts.map +1 -0
  144. package/dist/utils/query/helpers/queryValidator.js +27 -0
  145. package/dist/utils/query/helpers/remoteDb/queryFilterBuilder.d.ts +12 -0
  146. package/dist/utils/query/helpers/remoteDb/queryFilterBuilder.d.ts.map +1 -0
  147. package/dist/utils/query/helpers/remoteDb/queryFilterBuilder.js +41 -0
  148. package/dist/utils/query/helpers/remoteDb/queryUtils.d.ts +8 -0
  149. package/dist/utils/query/helpers/remoteDb/queryUtils.d.ts.map +1 -0
  150. package/dist/utils/query/helpers/remoteDb/queryUtils.js +30 -0
  151. package/dist/utils/query/localDbQuery/delete.d.ts +16 -0
  152. package/dist/utils/query/localDbQuery/delete.d.ts.map +1 -0
  153. package/dist/utils/query/localDbQuery/delete.js +54 -0
  154. package/dist/utils/query/localDbQuery/index.d.ts +8 -0
  155. package/dist/utils/query/localDbQuery/index.d.ts.map +1 -0
  156. package/dist/utils/query/localDbQuery/index.js +15 -0
  157. package/dist/utils/query/localDbQuery/insert.d.ts +10 -0
  158. package/dist/utils/query/localDbQuery/insert.d.ts.map +1 -0
  159. package/dist/utils/query/localDbQuery/insert.js +64 -0
  160. package/dist/utils/query/localDbQuery/select.d.ts +13 -0
  161. package/dist/utils/query/localDbQuery/select.d.ts.map +1 -0
  162. package/dist/utils/query/localDbQuery/select.js +41 -0
  163. package/dist/utils/query/localDbQuery/update.d.ts +11 -0
  164. package/dist/utils/query/localDbQuery/update.d.ts.map +1 -0
  165. package/dist/utils/query/localDbQuery/update.js +56 -0
  166. package/dist/utils/query/localDbQuery/upsert.d.ts +9 -0
  167. package/dist/utils/query/localDbQuery/upsert.d.ts.map +1 -0
  168. package/dist/utils/query/localDbQuery/upsert.js +67 -0
  169. package/dist/utils/query/remoteQuery/supabaseQuery.d.ts +8 -0
  170. package/dist/utils/query/remoteQuery/supabaseQuery.d.ts.map +1 -0
  171. package/dist/utils/query/remoteQuery/supabaseQuery.js +124 -0
  172. package/dist/utils/schema/createSyncStatus.d.ts +9 -0
  173. package/dist/utils/schema/createSyncStatus.d.ts.map +1 -0
  174. package/dist/utils/schema/createSyncStatus.js +23 -0
  175. package/dist/utils/schema/wipeTables.d.ts +66 -0
  176. package/dist/utils/schema/wipeTables.d.ts.map +1 -0
  177. package/dist/utils/schema/wipeTables.js +124 -0
  178. package/dist/utils/serializer.d.ts +8 -0
  179. package/dist/utils/serializer.d.ts.map +1 -0
  180. package/dist/utils/serializer.js +32 -0
  181. package/dist/utils/supabaseClientErr.d.ts +2 -0
  182. package/dist/utils/supabaseClientErr.d.ts.map +1 -0
  183. package/dist/utils/supabaseClientErr.js +15 -0
  184. package/dist/utils/sync/getAllTables.d.ts +2 -0
  185. package/dist/utils/sync/getAllTables.d.ts.map +1 -0
  186. package/dist/utils/sync/getAllTables.js +7 -0
  187. package/dist/utils/sync/pullFromRemote/getLastDeletedInfo.d.ts +13 -0
  188. package/dist/utils/sync/pullFromRemote/getLastDeletedInfo.d.ts.map +1 -0
  189. package/dist/utils/sync/pullFromRemote/getLastDeletedInfo.js +29 -0
  190. package/dist/utils/sync/pullFromRemote/getLastPulledInfo.d.ts +13 -0
  191. package/dist/utils/sync/pullFromRemote/getLastPulledInfo.d.ts.map +1 -0
  192. package/dist/utils/sync/pullFromRemote/getLastPulledInfo.js +29 -0
  193. package/dist/utils/sync/pullFromRemote/pullData.d.ts +9 -0
  194. package/dist/utils/sync/pullFromRemote/pullData.d.ts.map +1 -0
  195. package/dist/utils/sync/pullFromRemote/pullData.js +71 -0
  196. package/dist/utils/sync/pullFromRemote/pullDeletedData.d.ts +12 -0
  197. package/dist/utils/sync/pullFromRemote/pullDeletedData.d.ts.map +1 -0
  198. package/dist/utils/sync/pullFromRemote/pullDeletedData.js +69 -0
  199. package/dist/utils/sync/pullFromRemote/stringifyFields.d.ts +2 -0
  200. package/dist/utils/sync/pullFromRemote/stringifyFields.d.ts.map +1 -0
  201. package/dist/utils/sync/pullFromRemote/stringifyFields.js +11 -0
  202. package/dist/utils/sync/pullFromRemote/updateLocalDb.d.ts +14 -0
  203. package/dist/utils/sync/pullFromRemote/updateLocalDb.d.ts.map +1 -0
  204. package/dist/utils/sync/pullFromRemote/updateLocalDb.js +128 -0
  205. package/dist/utils/sync/pushLocal/deleteChunks.d.ts +8 -0
  206. package/dist/utils/sync/pushLocal/deleteChunks.d.ts.map +1 -0
  207. package/dist/utils/sync/pushLocal/deleteChunks.js +51 -0
  208. package/dist/utils/sync/pushLocal/getAllUnsyncedData.d.ts +14 -0
  209. package/dist/utils/sync/pushLocal/getAllUnsyncedData.d.ts.map +1 -0
  210. package/dist/utils/sync/pushLocal/getAllUnsyncedData.js +70 -0
  211. package/dist/utils/sync/pushLocal/parseFields.d.ts +7 -0
  212. package/dist/utils/sync/pushLocal/parseFields.d.ts.map +1 -0
  213. package/dist/utils/sync/pushLocal/parseFields.js +24 -0
  214. package/dist/utils/sync/pushLocal/sendUnsyncedToSupabase.d.ts +6 -0
  215. package/dist/utils/sync/pushLocal/sendUnsyncedToSupabase.d.ts.map +1 -0
  216. package/dist/utils/sync/pushLocal/sendUnsyncedToSupabase.js +43 -0
  217. package/dist/utils/sync/pushLocal/uploadChunk.d.ts +8 -0
  218. package/dist/utils/sync/pushLocal/uploadChunk.d.ts.map +1 -0
  219. package/dist/utils/sync/pushLocal/uploadChunk.js +117 -0
  220. package/dist/utils/sync/refreshTables.d.ts +12 -0
  221. package/dist/utils/sync/refreshTables.d.ts.map +1 -0
  222. package/dist/utils/sync/refreshTables.js +40 -0
  223. package/dist/utils/syncStatus.d.ts +67 -0
  224. package/dist/utils/syncStatus.d.ts.map +1 -0
  225. package/dist/utils/syncStatus.js +97 -0
  226. package/dist/utils/syncUpdate.d.ts +7 -0
  227. package/dist/utils/syncUpdate.d.ts.map +1 -0
  228. package/dist/utils/syncUpdate.js +19 -0
  229. package/dist/utils/tableValidator.d.ts +12 -0
  230. package/dist/utils/tableValidator.d.ts.map +1 -0
  231. package/dist/utils/tableValidator.js +23 -0
  232. package/package.json +60 -0
@@ -0,0 +1,101 @@
1
+ export interface RNNitroSQLiteDatabase {
2
+ transaction(fn: (tx: Transaction) => Promise<void> | void): Promise<void>;
3
+ execute: ExecuteQuery;
4
+ executeAsync: ExecuteAsyncQuery;
5
+ }
6
+
7
+ enum ColumnType {
8
+ BOOLEAN,
9
+ NUMBER,
10
+ INT64,
11
+ TEXT,
12
+ ARRAY_BUFFER,
13
+ NULL_VALUE,
14
+ }
15
+
16
+ // Passing null/undefined in array types is not possible, so we us a special struct as a workaround.
17
+ type SQLiteNullValue = {
18
+ isNitroSQLiteNull: true;
19
+ };
20
+ type SQLiteValue = boolean | number | string | ArrayBuffer | SQLiteNullValue;
21
+
22
+ /** Used internally to transform the query params into a native format without nullish values */
23
+ type NativeSQLiteQueryParams = SQLiteValue[];
24
+
25
+ /**
26
+ * Represents a value that can be stored in a SQLite database
27
+ */
28
+ type SQLiteQueryParamItem = SQLiteValue | null | undefined;
29
+ type SQLiteQueryParams = SQLiteQueryParamItem[];
30
+
31
+ type QueryResultRowItem = SQLiteValue | undefined;
32
+ type QueryResultRow = Record<string, QueryResultRowItem>;
33
+ interface QueryResult<Row extends QueryResultRow = QueryResultRow> {
34
+ readonly insertId?: number;
35
+ readonly rowsAffected: number;
36
+
37
+ readonly rows?: {
38
+ /** Raw array with all dataset */
39
+ _array: Row[];
40
+ /** The lengh of the dataset */
41
+ length: number;
42
+ /** A convenience function to acess the index based the row object
43
+ * @param idx the row index
44
+ * @returns the row structure identified by column names
45
+ */
46
+ item: (idx: number) => Row | undefined;
47
+ };
48
+ }
49
+
50
+ type ExecuteQuery = <Row extends QueryResultRow = QueryResultRow>(
51
+ query: string,
52
+ params?: SQLiteQueryParams
53
+ ) => QueryResult<Row>;
54
+
55
+ type ExecuteAsyncQuery = <Row extends QueryResultRow = QueryResultRow>(
56
+ query: string,
57
+ params?: SQLiteQueryParams
58
+ ) => Promise<QueryResult<Row>>;
59
+
60
+ interface Transaction {
61
+ commit(): QueryResult;
62
+ rollback(): QueryResult;
63
+ execute: ExecuteQuery;
64
+ executeAsync: ExecuteAsyncQuery;
65
+ }
66
+
67
+ /**
68
+ * Allows the execution of bulk of sql commands
69
+ * inside a transaction
70
+ * If a single query must be executed many times with different arguments, its preferred
71
+ * to declare it a single time, and use an array of array parameters.
72
+ */
73
+ interface BatchQueryCommand {
74
+ query: string;
75
+ params?: SQLiteQueryParams | SQLiteQueryParams[];
76
+ }
77
+
78
+ /**
79
+ * Used internally to transform the batch query commands into a native format without nullish values
80
+ */
81
+ interface NativeBatchQueryCommand {
82
+ query: string;
83
+ params?: NativeSQLiteQueryParams | NativeSQLiteQueryParams[];
84
+ }
85
+
86
+ /**
87
+ * status: 0 or undefined for correct execution, 1 for error
88
+ * message: if status === 1, here you will find error description
89
+ * rowsAffected: Number of affected rows if status == 0
90
+ */
91
+ interface BatchQueryResult {
92
+ rowsAffected?: number;
93
+ }
94
+
95
+ /**
96
+ * Result of loading a file and executing every line as a SQL command
97
+ * Similar to BatchQueryResult
98
+ */
99
+ interface FileLoadResult extends BatchQueryResult {
100
+ commands?: number;
101
+ }
@@ -0,0 +1,67 @@
1
+ interface ResultSet {
2
+ insertId: number;
3
+ rowsAffected: number;
4
+ rows: ResultSetRowList;
5
+ }
6
+
7
+ interface ResultSetRowList {
8
+ length: number;
9
+ raw(): any[];
10
+ item(index: number): any;
11
+ }
12
+
13
+ enum SQLErrors {
14
+ UNKNOWN_ERR = 0,
15
+ DATABASE_ERR = 1,
16
+ VERSION_ERR = 2,
17
+ TOO_LARGE_ERR = 3,
18
+ QUOTA_ERR = 4,
19
+ SYNTAX_ERR = 5,
20
+ CONSTRAINT_ERR = 6,
21
+ TIMEOUT_ERR = 7,
22
+ }
23
+
24
+ interface SQLError {
25
+ code: number;
26
+ message: string;
27
+ }
28
+
29
+ type StatementCallback = (
30
+ transaction: Transaction,
31
+ resultSet: ResultSet
32
+ ) => void;
33
+ type StatementErrorCallback = (
34
+ transaction: Transaction,
35
+ error: SQLError
36
+ ) => void;
37
+ interface Transaction {
38
+ executeSql(
39
+ sqlStatement: string,
40
+ arguments?: any[]
41
+ ): Promise<[Transaction, ResultSet]>;
42
+ executeSql(
43
+ sqlStatement: string,
44
+ arguments?: any[],
45
+ callback?: StatementCallback,
46
+ errorCallback?: StatementErrorCallback
47
+ ): void;
48
+ }
49
+
50
+ type TransactionCallback = (transaction: Transaction) => void;
51
+ type TransactionErrorCallback = (error: SQLError) => void;
52
+
53
+ export interface RNStorageSQLiteDatabase {
54
+ transaction(scope: (tx: Transaction) => void): Promise<Transaction>;
55
+ transaction(
56
+ scope: (tx: Transaction) => void,
57
+ error?: TransactionErrorCallback,
58
+ success?: TransactionCallback
59
+ ): void;
60
+ executeSql(statement: string, params?: any[]): Promise<[ResultSet]>;
61
+ executeSql(
62
+ statement: string,
63
+ params?: any[],
64
+ success?: StatementCallback,
65
+ error?: StatementErrorCallback
66
+ ): void;
67
+ }
@@ -0,0 +1,44 @@
1
+ type SqlPrimitive =
2
+ | "TEXT"
3
+ | "INTEGER"
4
+ | "REAL"
5
+ | "BLOB"
6
+ | "NUMERIC"
7
+ | `NUMERIC(${number},${number})`
8
+ | string;
9
+
10
+ type SqlModifier =
11
+ | "PRIMARY KEY"
12
+ | "NOT NULL"
13
+ | "UNIQUE"
14
+ | "DEFAULT"
15
+ | "CHECK"
16
+ | "COLLATE"
17
+ | "REFERENCES"
18
+ | "AUTOINCREMENT"
19
+ | "ON CONFLICT"
20
+ | "GENERATED ALWAYS"
21
+ | "AS"
22
+ | "STORED"
23
+ | "VIRTUAL"
24
+ | "NULL"
25
+ | "CURRENT_TIMESTAMP"
26
+ | "CURRENT_DATE"
27
+ | "CURRENT_TIME"
28
+ | "IF NOT EXISTS"
29
+ | "WITHOUT ROWID"
30
+ | string;
31
+
32
+ type ColumnDefinition = `${SqlPrimitive}${
33
+ | ""
34
+ | ` ${SqlModifier}`
35
+ | ` ${SqlModifier} ${SqlModifier}`
36
+ | ` ${SqlModifier} ${SqlModifier} ${SqlModifier}`}`;
37
+
38
+ type LocalSchemaDefinition = Record<string, ColumnDefinition>;
39
+
40
+ export type DefineLocalSchema = (
41
+ tableName: string,
42
+ schema: LocalSchemaDefinition,
43
+ deletePreviousSchema?: boolean
44
+ ) => void;
@@ -0,0 +1,72 @@
1
+ import { SupabaseClient } from "@supabase/supabase-js";
2
+ import { SQLiteOpenOptions } from "expo-sqlite";
3
+ import { ExpoSQLiteDatabase } from "./expoSqlite.types";
4
+ import { RNNitroSQLiteDatabase } from "./rnNitroSqlite.types";
5
+ import { RNStorageSQLiteDatabase } from "./rnSqliteStorage.types";
6
+
7
+ export type SupastashSQLiteClientTypes =
8
+ | "expo"
9
+ | "rn-storage"
10
+ | "rn-nitro"
11
+ | null;
12
+
13
+ export type SupastashConfig<T extends SupastashSQLiteClientTypes> = {
14
+ dbName: string;
15
+ supabaseClient: SupabaseClient<any, "public", any> | null;
16
+ sqliteClient: T extends "expo"
17
+ ? ExpoSQLiteClient
18
+ : T extends "rn-storage"
19
+ ? RNStorageSQLiteClient
20
+ : T extends "rn-nitro"
21
+ ? RNSqliteNitroClient
22
+ : null;
23
+ sqliteClientType: T;
24
+ excludeTables?: { pull?: string[]; push?: string[] };
25
+ pollingInterval?: {
26
+ pull?: number;
27
+ push?: number;
28
+ };
29
+ listeners?: number;
30
+ onSchemaInit?: () => void;
31
+ debugMode?: boolean;
32
+ };
33
+
34
+ interface SupastashSQLiteDatabase {
35
+ runAsync(sql: string, params?: any[]): Promise<void>;
36
+ getAllAsync<T = any>(sql: string, params?: any[]): Promise<T[]>;
37
+ getFirstAsync<T = any>(sql: string, params?: any[]): Promise<T | null>;
38
+ execAsync(statements: string): Promise<void>;
39
+ }
40
+
41
+ export interface SupastashSQLiteAdapter {
42
+ openDatabaseAsync(
43
+ name: string,
44
+ sqliteClient: ExpoSQLiteClient | RNStorageSQLiteClient | RNSqliteNitroClient
45
+ ): Promise<SupastashSQLiteDatabase>;
46
+ }
47
+
48
+ export interface ExpoSQLiteClient {
49
+ openDatabaseAsync: (
50
+ databaseName: string,
51
+ options?: SQLiteOpenOptions | undefined,
52
+ directory?: string | undefined
53
+ ) => Promise<ExpoSQLiteDatabase>;
54
+ }
55
+
56
+ export interface RNStorageSQLiteClient {
57
+ openDatabase: ({
58
+ name,
59
+ }: {
60
+ name: string;
61
+ }) => Promise<RNStorageSQLiteDatabase>;
62
+ }
63
+
64
+ export interface RNSqliteNitroClient {
65
+ open: (options: { name: string; location?: string }) => RNNitroSQLiteDatabase;
66
+ }
67
+
68
+ export interface SupastashHookReturn {
69
+ dbReady: boolean;
70
+ startSync: () => void;
71
+ stopSync: () => void;
72
+ }
@@ -0,0 +1,12 @@
1
+ export type SyncResult = {
2
+ success: string[]; // IDs that were successfully upserted
3
+ skipped: { id: string; reason: string }[]; // IDs that were skipped with reason
4
+ };
5
+
6
+ export type TableSchema = {
7
+ name: string;
8
+ type: string;
9
+ notnull: boolean;
10
+ dflt_value: string;
11
+ pk: number;
12
+ };
@@ -0,0 +1,2 @@
1
+ export declare function isOnline(): Promise<boolean>;
2
+ //# sourceMappingURL=connection.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"connection.d.ts","sourceRoot":"","sources":["../../src/utils/connection.ts"],"names":[],"mappings":"AAEA,wBAAsB,QAAQ,IAAI,OAAO,CAAC,OAAO,CAAC,CAIjD"}
@@ -0,0 +1,7 @@
1
+ import NetInfo from "@react-native-community/netinfo";
2
+ export async function isOnline() {
3
+ if (!NetInfo)
4
+ return true;
5
+ const networkState = await NetInfo.fetch();
6
+ return !!(networkState.isConnected && networkState.isInternetReachable);
7
+ }
@@ -0,0 +1,3 @@
1
+ import { EventEmitter } from "events";
2
+ export declare const supastashEventBus: EventEmitter<[never]>;
3
+ //# sourceMappingURL=eventBus.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"eventBus.d.ts","sourceRoot":"","sources":["../../../src/utils/events/eventBus.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,YAAY,EAAE,MAAM,QAAQ,CAAC;AAGtC,eAAO,MAAM,iBAAiB,uBAAqB,CAAC"}
@@ -0,0 +1,4 @@
1
+ import { EventEmitter } from "events";
2
+ import { getSupastashConfig } from "../../core/config";
3
+ export const supastashEventBus = new EventEmitter();
4
+ supastashEventBus.setMaxListeners(getSupastashConfig()?.listeners || 250);
@@ -0,0 +1,7 @@
1
+ import { FilterOperator } from "../../types/realtimeData.types";
2
+ export declare function buildFilterString(filters: {
3
+ column: string;
4
+ operator: FilterOperator;
5
+ value: string | number | null | (string | number)[];
6
+ } | undefined): string | undefined;
7
+ //# sourceMappingURL=buildFilter.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"buildFilter.d.ts","sourceRoot":"","sources":["../../../src/utils/fetchData/buildFilter.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,cAAc,EAAE,MAAM,gCAAgC,CAAC;AAEhE,wBAAgB,iBAAiB,CAC/B,OAAO,EACH;IACE,MAAM,EAAE,MAAM,CAAC;IACf,QAAQ,EAAE,cAAc,CAAC;IACzB,KAAK,EAAE,MAAM,GAAG,MAAM,GAAG,IAAI,GAAG,CAAC,MAAM,GAAG,MAAM,CAAC,EAAE,CAAC;CACrD,GACD,SAAS,GACZ,MAAM,GAAG,SAAS,CAepB"}
@@ -0,0 +1,13 @@
1
+ export function buildFilterString(filters) {
2
+ if (!filters) {
3
+ return undefined;
4
+ }
5
+ const { column, operator, value } = filters;
6
+ if (value === null) {
7
+ return `${column}=${operator}.null`;
8
+ }
9
+ if (operator === "in" && Array.isArray(value)) {
10
+ return `${column}=in.(${value.join(",")})`;
11
+ }
12
+ return `${column}=${operator}.${value}`;
13
+ }
@@ -0,0 +1,8 @@
1
+ import { PayloadData } from "../../types/query.types";
2
+ /**
3
+ * Creates a table in the database
4
+ * @param table - The name of the table to create
5
+ * @param payload - The payload of the table
6
+ */
7
+ export declare function createTable(table: string, payload?: PayloadData): Promise<void>;
8
+ //# sourceMappingURL=createTable.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"createTable.d.ts","sourceRoot":"","sources":["../../../src/utils/fetchData/createTable.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,WAAW,EAAE,MAAM,yBAAyB,CAAC;AAMtD;;;;GAIG;AACH,wBAAsB,WAAW,CAAC,KAAK,EAAE,MAAM,EAAE,OAAO,CAAC,EAAE,WAAW,iBA8CrE"}
@@ -0,0 +1,48 @@
1
+ import { getSupastashConfig } from "../../core/config";
2
+ import { getSupastashDb } from "../../db/dbInitializer";
3
+ import log from "../logs";
4
+ import { checkIfTableExist } from "../tableValidator";
5
+ import { getKeyType } from "./getKeyType";
6
+ import { validatePayload } from "./validatePayload";
7
+ /**
8
+ * Creates a table in the database
9
+ * @param table - The name of the table to create
10
+ * @param payload - The payload of the table
11
+ */
12
+ export async function createTable(table, payload) {
13
+ const db = await getSupastashDb();
14
+ const config = getSupastashConfig();
15
+ let newPayload = payload;
16
+ const isTableExist = await checkIfTableExist(table);
17
+ if (isTableExist)
18
+ return;
19
+ if (!newPayload && config.supabaseClient) {
20
+ const { data, error } = await config.supabaseClient
21
+ .from(table)
22
+ .select("*")
23
+ .limit(1);
24
+ if (error) {
25
+ log("[Supastash] Error fetching data from supabase", error);
26
+ return;
27
+ }
28
+ newPayload = data?.[0];
29
+ }
30
+ if (!newPayload) {
31
+ log(`[Supastash] Can't create table ${table} because no data was found
32
+ Try creating the table manually using the 'defineLocalSchema()' function.
33
+ `);
34
+ return;
35
+ }
36
+ try {
37
+ validatePayload(newPayload);
38
+ const columns = Object.keys({ ...newPayload, synced_at: null }).map((key) => `${key} ${getKeyType(newPayload[key])}`);
39
+ log("Table to be created", columns);
40
+ // Create the table
41
+ await db.runAsync(`CREATE TABLE IF NOT EXISTS ${table} (${columns.join(", ")})`);
42
+ }
43
+ catch (error) {
44
+ throw new Error(`Failed to create table ${table}.
45
+ Use the 'defineLocalSchema()' function to create the table manually.
46
+ Error: ${error}`);
47
+ }
48
+ }
@@ -0,0 +1,3 @@
1
+ import { PayloadData } from "../../types/query.types";
2
+ export declare function deleteData(payload: PayloadData, table: string, setDataMap: React.Dispatch<React.SetStateAction<Map<string, PayloadData>>>, setVersion: React.Dispatch<React.SetStateAction<string>>, dataMap: Map<string, PayloadData>, shouldFetch?: boolean): Promise<void>;
3
+ //# sourceMappingURL=deleteData.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"deleteData.d.ts","sourceRoot":"","sources":["../../../src/utils/fetchData/deleteData.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,WAAW,EAAE,MAAM,yBAAyB,CAAC;AAKtD,wBAAsB,UAAU,CAC9B,OAAO,EAAE,WAAW,EACpB,KAAK,EAAE,MAAM,EACb,UAAU,EAAE,KAAK,CAAC,QAAQ,CAAC,KAAK,CAAC,cAAc,CAAC,GAAG,CAAC,MAAM,EAAE,WAAW,CAAC,CAAC,CAAC,EAC1E,UAAU,EAAE,KAAK,CAAC,QAAQ,CAAC,KAAK,CAAC,cAAc,CAAC,MAAM,CAAC,CAAC,EACxD,OAAO,EAAE,GAAG,CAAC,MAAM,EAAE,WAAW,CAAC,EACjC,WAAW,GAAE,OAAc,iBAyB5B"}
@@ -0,0 +1,25 @@
1
+ import { permanentlyDeleteData } from "../../utils/query/localDbQuery/delete";
2
+ import { checkIfTableExist } from "../../utils/tableValidator";
3
+ import { createTable } from "./createTable";
4
+ export async function deleteData(payload, table, setDataMap, setVersion, dataMap, shouldFetch = true) {
5
+ if (!shouldFetch)
6
+ return;
7
+ try {
8
+ const exist = await checkIfTableExist(table);
9
+ if (!exist) {
10
+ await createTable(table, payload);
11
+ }
12
+ if (!payload?.id)
13
+ return;
14
+ // Delete the data
15
+ dataMap.delete(payload.id);
16
+ setDataMap(new Map(dataMap));
17
+ setVersion(`${table}-${Date.now()}`);
18
+ await permanentlyDeleteData(table, [
19
+ { column: "id", operator: "=", value: payload.id },
20
+ ]);
21
+ }
22
+ catch (error) {
23
+ console.error("[Supastash] Error receiving data:", error);
24
+ }
25
+ }
@@ -0,0 +1,9 @@
1
+ import { PayloadData } from "../../types/query.types";
2
+ /**
3
+ * Fetches the local data from the database
4
+ * @param table - The name of the table to fetch from
5
+ * @param setData - The function to set the data
6
+ * @param shouldFetch - Whether to fetch the data
7
+ */
8
+ export declare function fetchLocalData(table: string, setDataMap: React.Dispatch<React.SetStateAction<Map<string, PayloadData>>>, setVersion: React.Dispatch<React.SetStateAction<string>>, shouldFetch?: boolean, limit?: number): Promise<void>;
9
+ //# sourceMappingURL=fetchLocalData.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"fetchLocalData.d.ts","sourceRoot":"","sources":["../../../src/utils/fetchData/fetchLocalData.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,WAAW,EAAE,MAAM,yBAAyB,CAAC;AAuBtD;;;;;GAKG;AACH,wBAAsB,cAAc,CAClC,KAAK,EAAE,MAAM,EACb,UAAU,EAAE,KAAK,CAAC,QAAQ,CAAC,KAAK,CAAC,cAAc,CAAC,GAAG,CAAC,MAAM,EAAE,WAAW,CAAC,CAAC,CAAC,EAC1E,UAAU,EAAE,KAAK,CAAC,QAAQ,CAAC,KAAK,CAAC,cAAc,CAAC,MAAM,CAAC,CAAC,EACxD,WAAW,GAAE,OAAc,EAC3B,KAAK,GAAE,MAAY,iBAkCpB"}
@@ -0,0 +1,51 @@
1
+ import { getSupastashDb } from "../../db/dbInitializer";
2
+ let isFetching = new Map();
3
+ function parseJSONColumns(row) {
4
+ const parsedRow = { ...row };
5
+ for (const key in parsedRow) {
6
+ const value = parsedRow[key];
7
+ if (typeof value === "string" &&
8
+ (value.startsWith("{") || value.startsWith("["))) {
9
+ try {
10
+ parsedRow[key] = JSON.parse(value);
11
+ }
12
+ catch { }
13
+ }
14
+ }
15
+ return parsedRow;
16
+ }
17
+ /**
18
+ * Fetches the local data from the database
19
+ * @param table - The name of the table to fetch from
20
+ * @param setData - The function to set the data
21
+ * @param shouldFetch - Whether to fetch the data
22
+ */
23
+ export async function fetchLocalData(table, setDataMap, setVersion, shouldFetch = true, limit = 200) {
24
+ if (!shouldFetch || isFetching.get(table))
25
+ return;
26
+ isFetching.set(table, true);
27
+ if (!/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(table)) {
28
+ throw new Error(`Invalid table name: ${table}`);
29
+ }
30
+ const limitClause = `LIMIT ${limit ?? 200}`;
31
+ try {
32
+ const db = await getSupastashDb();
33
+ const localData = await db.getAllAsync(`SELECT * FROM ${table} WHERE deleted_at IS NULL ${limitClause}`);
34
+ const dataMap = new Map(localData
35
+ ?.map((item) => {
36
+ if (!item.id)
37
+ return undefined;
38
+ return [item.id, parseJSONColumns(item)];
39
+ })
40
+ .filter((item) => item !== undefined) ??
41
+ []);
42
+ setDataMap(dataMap);
43
+ setVersion(`${table}-${Date.now()}`);
44
+ }
45
+ catch (error) {
46
+ console.error(`[Supastash] Error fetching local data for ${table}:`, error);
47
+ }
48
+ finally {
49
+ isFetching.delete(table);
50
+ }
51
+ }
@@ -0,0 +1,7 @@
1
+ /**
2
+ * Gets the type of the key
3
+ * @param value - The value of the key
4
+ * @returns The type of the key
5
+ */
6
+ export declare function getKeyType(value: any): "NULL" | "INTEGER" | "REAL" | "TEXT" | "BLOB";
7
+ //# sourceMappingURL=getKeyType.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"getKeyType.d.ts","sourceRoot":"","sources":["../../../src/utils/fetchData/getKeyType.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AACH,wBAAgB,UAAU,CACxB,KAAK,EAAE,GAAG,GACT,MAAM,GAAG,SAAS,GAAG,MAAM,GAAG,MAAM,GAAG,MAAM,CAuB/C"}
@@ -0,0 +1,25 @@
1
+ /**
2
+ * Gets the type of the key
3
+ * @param value - The value of the key
4
+ * @returns The type of the key
5
+ */
6
+ export function getKeyType(value) {
7
+ if (value === null || value === undefined)
8
+ return "NULL";
9
+ const valueType = typeof value;
10
+ if (valueType === "number") {
11
+ return Number.isInteger(value) ? "INTEGER" : "REAL";
12
+ }
13
+ if (value instanceof Date)
14
+ return "TEXT";
15
+ if (value instanceof ArrayBuffer ||
16
+ value instanceof Uint8Array ||
17
+ (typeof Buffer !== "undefined" && Buffer.isBuffer(value))) {
18
+ return "BLOB";
19
+ }
20
+ if (valueType === "boolean")
21
+ return "INTEGER";
22
+ if (valueType === "string")
23
+ return "TEXT";
24
+ return "TEXT";
25
+ }
@@ -0,0 +1,3 @@
1
+ import { RealtimeFilter } from "../../types/realtimeData.types";
2
+ export declare function initialFetch(table: string, filter?: RealtimeFilter, onReceiveData?: (payload: any) => Promise<void>, onPushToRemote?: (payload: any[]) => Promise<boolean>): Promise<void>;
3
+ //# sourceMappingURL=initialFetch.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"initialFetch.d.ts","sourceRoot":"","sources":["../../../src/utils/fetchData/initialFetch.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,cAAc,EAAE,MAAM,gCAAgC,CAAC;AAOhE,wBAAsB,YAAY,CAChC,KAAK,EAAE,MAAM,EACb,MAAM,CAAC,EAAE,cAAc,EACvB,aAAa,CAAC,EAAE,CAAC,OAAO,EAAE,GAAG,KAAK,OAAO,CAAC,IAAI,CAAC,EAC/C,cAAc,CAAC,EAAE,CAAC,OAAO,EAAE,GAAG,EAAE,KAAK,OAAO,CAAC,OAAO,CAAC,iBAatD"}
@@ -0,0 +1,20 @@
1
+ import { updateLocalDb } from "../sync/pullFromRemote/updateLocalDb";
2
+ import { pushLocalDataToRemote } from "../sync/pushLocal/sendUnsyncedToSupabase";
3
+ import { createTable } from "./createTable";
4
+ let isInSync = new Map();
5
+ export async function initialFetch(table, filter, onReceiveData, onPushToRemote) {
6
+ if (isInSync.get(table))
7
+ return;
8
+ isInSync.set(table, true);
9
+ try {
10
+ await createTable(table);
11
+ await updateLocalDb(table, filter, onReceiveData);
12
+ await pushLocalDataToRemote(table, onPushToRemote);
13
+ }
14
+ catch (error) {
15
+ console.error(`[Supastash] Error on initial fetch for ${table}`, error);
16
+ }
17
+ finally {
18
+ isInSync.delete(table);
19
+ }
20
+ }
@@ -0,0 +1,5 @@
1
+ import { PayloadData } from "../../types/query.types";
2
+ import { RealtimeOptions } from "../../types/realtimeData.types";
3
+ declare const useRealtimeData: (table: string, queueHandler: (eventType: string, data: PayloadData) => void, options: RealtimeOptions, initialized: boolean, realtime: boolean) => void;
4
+ export default useRealtimeData;
5
+ //# sourceMappingURL=realTimeCall.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"realTimeCall.d.ts","sourceRoot":"","sources":["../../../src/utils/fetchData/realTimeCall.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,WAAW,EAAE,MAAM,yBAAyB,CAAC;AACtD,OAAO,EAAE,eAAe,EAAE,MAAM,gCAAgC,CAAC;AAMjE,QAAA,MAAM,eAAe,GACnB,OAAO,MAAM,EACb,cAAc,CAAC,SAAS,EAAE,MAAM,EAAE,IAAI,EAAE,WAAW,KAAK,IAAI,EAC5D,SAAS,eAAe,EACxB,aAAa,OAAO,EACpB,UAAU,OAAO,SAmDlB,CAAC;AAEF,eAAe,eAAe,CAAC"}
@@ -0,0 +1,43 @@
1
+ import { useEffect } from "react";
2
+ import { getSupastashConfig } from "../../core/config";
3
+ import { supabaseClientErr } from "../supabaseClientErr";
4
+ import { buildFilterString } from "./buildFilter";
5
+ const hasRegistered = new Map();
6
+ const useRealtimeData = (table, queueHandler, options, initialized, realtime) => {
7
+ const { lazy, shouldFetch } = options;
8
+ useEffect(() => {
9
+ if (!realtime || (options.lazy && !initialized) || !shouldFetch) {
10
+ return;
11
+ }
12
+ const filterString = options.filter
13
+ ? buildFilterString(options.filter)
14
+ : undefined;
15
+ if (hasRegistered.get(`${table}:${filterString ?? ""}`))
16
+ return;
17
+ hasRegistered.set(`${table}:${filterString ?? ""}`, true);
18
+ const supabase = getSupastashConfig().supabaseClient;
19
+ if (!supabase) {
20
+ console.error("[Supastash] No supabase client found", supabaseClientErr);
21
+ return;
22
+ }
23
+ const subDetails = filterString
24
+ ? { event: "*", schema: "public", table, filter: filterString }
25
+ : { event: "*", schema: "public", table };
26
+ const subscription = supabase
27
+ .channel(`supastash:realtime:${table}:${filterString ? filterString : ""}`)
28
+ .on("postgres_changes", subDetails, (payload) => {
29
+ console.log("[Supastash] 🔥 GOT PAYLOAD:", payload?.new?.id
30
+ ? payload?.new?.id
31
+ : "No id found for this item", `on table ${table}`, `with event type ${payload.eventType}`);
32
+ queueHandler(payload.eventType, payload.new);
33
+ })
34
+ .subscribe((status, err) => {
35
+ if (err)
36
+ console.error(`[Supastash] 📡 STATUS: ${status} on table ${table}`, err);
37
+ });
38
+ return () => {
39
+ supabase.removeChannel(subscription);
40
+ };
41
+ }, [table, lazy, initialized, realtime, shouldFetch]);
42
+ };
43
+ export default useRealtimeData;