@powersync/react-native 0.0.0-dev-20240506092851

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.
package/LICENSE ADDED
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
package/README.md ADDED
@@ -0,0 +1,121 @@
1
+ <p align="center">
2
+ <a href="https://www.powersync.com" target="_blank"><img src="https://github.com/powersync-ja/.github/assets/19345049/602bafa0-41ce-4cee-a432-56848c278722"/></a>
3
+ </p>
4
+
5
+ # PowerSync SDK for React Native
6
+
7
+ [PowerSync](https://powersync.com) is a service and set of SDKs that keeps Postgres databases in sync with on-device SQLite databases.
8
+
9
+ This package (`packages/react-native`) is the PowerSync SDK for React Native clients. It is an extension of `packages/common`.
10
+
11
+ See a summary of features [here](https://docs.powersync.co/client-sdk-references/react-native-and-expo).
12
+
13
+ # Installation
14
+
15
+ ## Install Package
16
+
17
+ ```bash
18
+ npx expo install @powersync/react-native
19
+ ```
20
+
21
+ ## Install Peer Dependency: SQLite
22
+
23
+ This SDK currently requires `@journeyapps/react-native-quick-sqlite` as a peer dependency.
24
+
25
+ Install it in your app with:
26
+
27
+ ```bash
28
+ npx expo install @journeyapps/react-native-quick-sqlite
29
+ ```
30
+
31
+ ## Install Polyfills
32
+
33
+ ### Fetch
34
+
35
+ This SDK requires HTTP streaming in order to function. The following `fetch` polyfills are required for the React Native implementation of `fetch`:
36
+
37
+ - react-native-fetch-api
38
+ - react-native-polyfill-globals
39
+ - react-native-url-polyfill
40
+ - text-encoding
41
+ - web-streams-polyfill@3.2.1
42
+
43
+ These are listed as peer dependencies and need to be added to the React Native project
44
+
45
+ ```bash
46
+ npx expo install react-native-fetch-api react-native-polyfill-globals react-native-url-polyfill text-encoding web-streams-polyfill@3.2.1 base-64 react-native-get-random-values@1.9.0
47
+ ```
48
+
49
+ Enable the polyfills in React Native app with
50
+
51
+ ```JavaScript
52
+ // App.js
53
+ import 'react-native-polyfill-globals/auto';
54
+ ```
55
+
56
+ ### Babel Plugins: Watched Queries
57
+
58
+ Watched queries require support for Async Iterators. Expo apps currently require polyfill and Babel plugins in order to use this functionality.
59
+
60
+ ```bash
61
+ npx expo install @azure/core-asynciterator-polyfill
62
+ ```
63
+
64
+ Make sure to import the polyfill early in your application
65
+
66
+ ```JavaScript
67
+ // App.js
68
+ import '@azure/core-asynciterator-polyfill';
69
+ ```
70
+
71
+ Install the async generator Babel plugin
72
+
73
+ ```bash
74
+ pnpm add -D @babel/plugin-transform-async-generator-functions
75
+ ```
76
+
77
+ Add the Babel plugin to your `babel.config.js` file
78
+
79
+ ```JavaScript
80
+ module.exports = function (api) {
81
+ return {
82
+ presets: [...],
83
+ plugins: [
84
+ // ... Other plugins
85
+ '@babel/plugin-transform-async-generator-functions'
86
+ ]
87
+ };
88
+ };
89
+ ```
90
+
91
+ # Native Projects
92
+
93
+ This package uses native libraries. Create native Android and iOS projects (if not created already) by running:
94
+
95
+ ```bash
96
+ npx expo run:android
97
+ # OR
98
+ npx expo run:ios
99
+ ```
100
+
101
+ # Getting Started
102
+
103
+ Our [SDK reference](https://docs.powersync.com/client-sdk-references/react-native-and-expo) contains everything you need to know to get started implementing PowerSync in your project.
104
+
105
+ # Changelog
106
+
107
+ A changelog for this SDK is available [here](https://releases.powersync.com/announcements/react-native-client-sdk).
108
+
109
+ # API Reference
110
+
111
+ The full API reference for this SDK can be found [here](https://powersync-ja.github.io/powersync-js/react-native-sdk).
112
+
113
+ # Examples
114
+
115
+ For example projects built with PowerSync and React Native, see our [Demo Apps / Example Projects](https://docs.powersync.com/resources/demo-apps-example-projects#react-native-and-expo) gallery. Most of these projects can also be found in the [`demos/`](../demos/) directory.
116
+
117
+ # Found a bug or need help?
118
+
119
+ - Join our [Discord server](https://discord.gg/powersync) where you can browse topics from our community, ask questions, share feedback, or just say hello :)
120
+ - Please open a [GitHub issue](https://github.com/powersync-ja/powersync-js/issues) when you come across a bug.
121
+ - Have feedback or an idea? [Submit an idea](https://roadmap.powersync.com/tabs/5-roadmap/submit-idea) via our public roadmap or [schedule a chat](https://calendly.com/powersync-product/powersync-chat) with someone from our product team.
@@ -0,0 +1,6 @@
1
+ import { AbstractPowerSyncDatabase, AbstractStreamingSyncImplementation, PowerSyncBackendConnector, BucketStorageAdapter } from '@powersync/common';
2
+ export declare class PowerSyncDatabase extends AbstractPowerSyncDatabase {
3
+ _initialize(): Promise<void>;
4
+ protected generateBucketStorageAdapter(): BucketStorageAdapter;
5
+ protected generateSyncStreamImplementation(connector: PowerSyncBackendConnector): AbstractStreamingSyncImplementation;
6
+ }
@@ -0,0 +1,24 @@
1
+ import { AbstractPowerSyncDatabase, SqliteBucketStorage } from '@powersync/common';
2
+ import { ReactNativeRemote } from '../sync/stream/ReactNativeRemote';
3
+ import { ReactNativeStreamingSyncImplementation } from '../sync/stream/ReactNativeStreamingSyncImplementation';
4
+ export class PowerSyncDatabase extends AbstractPowerSyncDatabase {
5
+ async _initialize() { }
6
+ generateBucketStorageAdapter() {
7
+ return new SqliteBucketStorage(this.database, AbstractPowerSyncDatabase.transactionMutex);
8
+ }
9
+ generateSyncStreamImplementation(connector) {
10
+ const remote = new ReactNativeRemote(connector);
11
+ return new ReactNativeStreamingSyncImplementation({
12
+ adapter: this.bucketStorageAdapter,
13
+ remote,
14
+ uploadCrud: async () => {
15
+ await this.waitForReady();
16
+ await connector.uploadData(this);
17
+ },
18
+ retryDelayMs: this.options.retryDelay,
19
+ crudUploadThrottleMs: this.options.crudUploadThrottleMs,
20
+ identifier: this.options.database.name
21
+ });
22
+ }
23
+ }
24
+ //# sourceMappingURL=PowerSyncDatabase.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"PowerSyncDatabase.js","sourceRoot":"","sources":["../../src/db/PowerSyncDatabase.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,yBAAyB,EAGzB,mBAAmB,EAEpB,MAAM,mBAAmB,CAAC;AAC3B,OAAO,EAAE,iBAAiB,EAAE,MAAM,kCAAkC,CAAC;AACrE,OAAO,EAAE,sCAAsC,EAAE,MAAM,uDAAuD,CAAC;AAE/G,MAAM,OAAO,iBAAkB,SAAQ,yBAAyB;IAC9D,KAAK,CAAC,WAAW,KAAmB,CAAC;IAE3B,4BAA4B;QACpC,OAAO,IAAI,mBAAmB,CAAC,IAAI,CAAC,QAAQ,EAAE,yBAAyB,CAAC,gBAAgB,CAAC,CAAC;IAC5F,CAAC;IAES,gCAAgC,CACxC,SAAoC;QAEpC,MAAM,MAAM,GAAG,IAAI,iBAAiB,CAAC,SAAS,CAAC,CAAC;QAEhD,OAAO,IAAI,sCAAsC,CAAC;YAChD,OAAO,EAAE,IAAI,CAAC,oBAAoB;YAClC,MAAM;YACN,UAAU,EAAE,KAAK,IAAI,EAAE;gBACrB,MAAM,IAAI,CAAC,YAAY,EAAE,CAAC;gBAC1B,MAAM,SAAS,CAAC,UAAU,CAAC,IAAI,CAAC,CAAC;YACnC,CAAC;YACD,YAAY,EAAE,IAAI,CAAC,OAAO,CAAC,UAAU;YACrC,oBAAoB,EAAE,IAAI,CAAC,OAAO,CAAC,oBAAoB;YACvD,UAAU,EAAE,IAAI,CAAC,OAAO,CAAC,QAAQ,CAAC,IAAI;SACvC,CAAC,CAAC;IACL,CAAC;CACF"}
@@ -0,0 +1,33 @@
1
+ import { BaseObserver, DBAdapter, DBAdapterListener, LockContext as PowerSyncLockContext, Transaction as PowerSyncTransaction, DBLockOptions, QueryResult } from '@powersync/common';
2
+ import { QuickSQLiteConnection } from '@journeyapps/react-native-quick-sqlite';
3
+ /**
4
+ * Adapter for React Native Quick SQLite
5
+ */
6
+ export declare class RNQSDBAdapter extends BaseObserver<DBAdapterListener> implements DBAdapter {
7
+ protected baseDB: QuickSQLiteConnection;
8
+ name: string;
9
+ getAll: <T>(sql: string, parameters?: any[]) => Promise<T[]>;
10
+ getOptional: <T>(sql: string, parameters?: any[]) => Promise<T | null>;
11
+ get: <T>(sql: string, parameters?: any[]) => Promise<T>;
12
+ constructor(baseDB: QuickSQLiteConnection, name: string);
13
+ close(): void;
14
+ readLock<T>(fn: (tx: PowerSyncLockContext) => Promise<T>, options?: DBLockOptions): Promise<T>;
15
+ readTransaction<T>(fn: (tx: PowerSyncTransaction) => Promise<T>, options?: DBLockOptions): Promise<T>;
16
+ writeLock<T>(fn: (tx: PowerSyncLockContext) => Promise<T>, options?: DBLockOptions): Promise<T>;
17
+ writeTransaction<T>(fn: (tx: PowerSyncTransaction) => Promise<T>, options?: DBLockOptions): Promise<T>;
18
+ execute(query: string, params?: any[]): Promise<import("@journeyapps/react-native-quick-sqlite").QueryResult>;
19
+ executeBatch(query: string, params?: any[][]): Promise<QueryResult>;
20
+ /**
21
+ * This provides a top-level read only execute method which is executed inside a read-lock.
22
+ * This is necessary since the high level `execute` method uses a write-lock under
23
+ * the hood. Helper methods such as `get`, `getAll` and `getOptional` are read only,
24
+ * and should use this method.
25
+ */
26
+ private readOnlyExecute;
27
+ /**
28
+ * Adds DB get utils to lock contexts and transaction contexts
29
+ * @param tx
30
+ * @returns
31
+ */
32
+ private generateDBHelpers;
33
+ }
@@ -0,0 +1,101 @@
1
+ import { BaseObserver } from '@powersync/common';
2
+ /**
3
+ * Adapter for React Native Quick SQLite
4
+ */
5
+ export class RNQSDBAdapter extends BaseObserver {
6
+ baseDB;
7
+ name;
8
+ getAll;
9
+ getOptional;
10
+ get;
11
+ constructor(baseDB, name) {
12
+ super();
13
+ this.baseDB = baseDB;
14
+ this.name = name;
15
+ // link table update commands
16
+ baseDB.registerTablesChangedHook((update) => {
17
+ this.iterateListeners((cb) => cb.tablesUpdated?.(update));
18
+ });
19
+ const topLevelUtils = this.generateDBHelpers({
20
+ // Arrow function binds `this` for use in readOnlyExecute
21
+ execute: (sql, params) => this.readOnlyExecute(sql, params)
22
+ });
23
+ // Only assigning get helpers
24
+ this.getAll = topLevelUtils.getAll;
25
+ this.getOptional = topLevelUtils.getOptional;
26
+ this.get = topLevelUtils.get;
27
+ }
28
+ close() {
29
+ return this.baseDB.close();
30
+ }
31
+ readLock(fn, options) {
32
+ return this.baseDB.readLock((dbTx) => fn(this.generateDBHelpers(dbTx)), options);
33
+ }
34
+ readTransaction(fn, options) {
35
+ return this.baseDB.readTransaction((dbTx) => fn(this.generateDBHelpers(dbTx)), options);
36
+ }
37
+ writeLock(fn, options) {
38
+ return this.baseDB.writeLock((dbTx) => fn(this.generateDBHelpers(dbTx)), options);
39
+ }
40
+ writeTransaction(fn, options) {
41
+ return this.baseDB.writeTransaction((dbTx) => fn(this.generateDBHelpers(dbTx)), options);
42
+ }
43
+ execute(query, params) {
44
+ return this.baseDB.execute(query, params);
45
+ }
46
+ async executeBatch(query, params = []) {
47
+ const commands = [];
48
+ for (let i = 0; i < params.length; i++) {
49
+ commands.push([query, params[i]]);
50
+ }
51
+ const result = await this.baseDB.executeBatch(commands);
52
+ return {
53
+ rowsAffected: result.rowsAffected ? result.rowsAffected : 0
54
+ };
55
+ }
56
+ /**
57
+ * This provides a top-level read only execute method which is executed inside a read-lock.
58
+ * This is necessary since the high level `execute` method uses a write-lock under
59
+ * the hood. Helper methods such as `get`, `getAll` and `getOptional` are read only,
60
+ * and should use this method.
61
+ */
62
+ readOnlyExecute(sql, params) {
63
+ return this.baseDB.readLock((ctx) => ctx.execute(sql, params));
64
+ }
65
+ /**
66
+ * Adds DB get utils to lock contexts and transaction contexts
67
+ * @param tx
68
+ * @returns
69
+ */
70
+ generateDBHelpers(tx) {
71
+ return {
72
+ ...tx,
73
+ /**
74
+ * Execute a read-only query and return results
75
+ */
76
+ getAll: async (sql, parameters) => {
77
+ const res = await tx.execute(sql, parameters);
78
+ return res.rows?._array ?? [];
79
+ },
80
+ /**
81
+ * Execute a read-only query and return the first result, or null if the ResultSet is empty.
82
+ */
83
+ getOptional: async (sql, parameters) => {
84
+ const res = await tx.execute(sql, parameters);
85
+ return res.rows?.item(0) ?? null;
86
+ },
87
+ /**
88
+ * Execute a read-only query and return the first result, error if the ResultSet is empty.
89
+ */
90
+ get: async (sql, parameters) => {
91
+ const res = await tx.execute(sql, parameters);
92
+ const first = res.rows?.item(0);
93
+ if (!first) {
94
+ throw new Error('Result set is empty');
95
+ }
96
+ return first;
97
+ }
98
+ };
99
+ }
100
+ }
101
+ //# sourceMappingURL=RNQSDBAdapter.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"RNQSDBAdapter.js","sourceRoot":"","sources":["../../../../src/db/adapters/react-native-quick-sqlite/RNQSDBAdapter.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,YAAY,EAQb,MAAM,mBAAmB,CAAC;AAG3B;;GAEG;AACH,MAAM,OAAO,aAAc,SAAQ,YAA+B;IAMpD;IACH;IANT,MAAM,CAAuD;IAC7D,WAAW,CAA4D;IACvE,GAAG,CAAqD;IAExD,YACY,MAA6B,EAChC,IAAY;QAEnB,KAAK,EAAE,CAAC;QAHE,WAAM,GAAN,MAAM,CAAuB;QAChC,SAAI,GAAJ,IAAI,CAAQ;QAGnB,6BAA6B;QAC7B,MAAM,CAAC,yBAAyB,CAAC,CAAC,MAAM,EAAE,EAAE;YAC1C,IAAI,CAAC,gBAAgB,CAAC,CAAC,EAAE,EAAE,EAAE,CAAC,EAAE,CAAC,aAAa,EAAE,CAAC,MAAM,CAAC,CAAC,CAAC;QAC5D,CAAC,CAAC,CAAC;QAEH,MAAM,aAAa,GAAG,IAAI,CAAC,iBAAiB,CAAC;YAC3C,yDAAyD;YACzD,OAAO,EAAE,CAAC,GAAW,EAAE,MAAc,EAAE,EAAE,CAAC,IAAI,CAAC,eAAe,CAAC,GAAG,EAAE,MAAM,CAAC;SAC5E,CAAC,CAAC;QACH,6BAA6B;QAC7B,IAAI,CAAC,MAAM,GAAG,aAAa,CAAC,MAAM,CAAC;QACnC,IAAI,CAAC,WAAW,GAAG,aAAa,CAAC,WAAW,CAAC;QAC7C,IAAI,CAAC,GAAG,GAAG,aAAa,CAAC,GAAG,CAAC;IAC/B,CAAC;IAED,KAAK;QACH,OAAO,IAA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M,KAAK,GAAG,GAAG,CAAC,IAAI,EAAE,IAAI,CAAC,CAAC,CAAC,CAAC;gBAChC,IAAI,CAAC,KAAK,EAAE,CAAC;oBACX,MAAM,IAAI,KAAK,CAAC,qBAAqB,CAAC,CAAC;gBACzC,CAAC;gBACD,OAAO,KAAK,CAAC;YACf,CAAC;SACF,CAAC;IACJ,CAAC;CACF"}
@@ -0,0 +1,7 @@
1
+ import { AbstractPowerSyncDatabase, AbstractPowerSyncDatabaseOpenFactory, DBAdapter, PowerSyncDatabaseOptions, PowerSyncOpenFactoryOptions } from '@powersync/common';
2
+ export declare class RNQSPowerSyncDatabaseOpenFactory extends AbstractPowerSyncDatabaseOpenFactory {
3
+ protected instanceGenerated: boolean;
4
+ constructor(options: PowerSyncOpenFactoryOptions);
5
+ protected openDB(): DBAdapter;
6
+ generateInstance(options: PowerSyncDatabaseOptions): AbstractPowerSyncDatabase;
7
+ }
@@ -0,0 +1,46 @@
1
+ import { open, QuickSQLite } from '@journeyapps/react-native-quick-sqlite';
2
+ import { AbstractPowerSyncDatabaseOpenFactory } from '@powersync/common';
3
+ import { PowerSyncDatabase } from '../../../db/PowerSyncDatabase';
4
+ import { RNQSDBAdapter } from './RNQSDBAdapter';
5
+ export class RNQSPowerSyncDatabaseOpenFactory extends AbstractPowerSyncDatabaseOpenFactory {
6
+ instanceGenerated;
7
+ constructor(options) {
8
+ super(options);
9
+ this.instanceGenerated = false;
10
+ }
11
+ openDB() {
12
+ /**
13
+ * React Native Quick SQLite opens files relative to the `Documents`dir on iOS and the `Files`
14
+ * dir on Android. Locations need to be relative to those dirs using with dot ("../") notation
15
+ * to navigate up the directory tree.
16
+ * This simple adapter assumes any platform specific relative directory is already catered for
17
+ * in the options (if provided)
18
+ * https://github.com/margelo/react-native-quick-sqlite/blob/main/README.md#loading-existing-dbs
19
+ */
20
+ const { dbFilename } = this.options;
21
+ const openOptions = { location: this.options.dbLocation };
22
+ let DB;
23
+ try {
24
+ // Hot reloads can sometimes clear global JS state, but not close DB on native side
25
+ DB = open(dbFilename, openOptions);
26
+ }
27
+ catch (ex) {
28
+ if (ex.message.includes('already open')) {
29
+ QuickSQLite.close(dbFilename);
30
+ DB = open(dbFilename, openOptions);
31
+ }
32
+ else {
33
+ throw ex;
34
+ }
35
+ }
36
+ return new RNQSDBAdapter(DB, this.options.dbFilename);
37
+ }
38
+ generateInstance(options) {
39
+ if (this.instanceGenerated) {
40
+ this.options.logger?.warn('Generating multiple PowerSync instances can sometimes cause unexpected results.');
41
+ }
42
+ this.instanceGenerated = true;
43
+ return new PowerSyncDatabase(options);
44
+ }
45
+ }
46
+ //# sourceMappingURL=RNQSDBOpenFactory.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"RNQSDBOpenFactory.js","sourceRoot":"","sources":["../../../../src/db/adapters/react-native-quick-sqlite/RNQSDBOpenFactory.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,IAAI,EAAE,WAAW,EAAyB,MAAM,wCAAwC,CAAC;AAElG,OAAO,EAEL,oCAAoC,EAIrC,MAAM,mBAAmB,CAAC;AAC3B,OAAO,EAAE,iBAAiB,EAAE,MAAM,+BAA+B,CAAC;AAClE,OAAO,EAAE,aAAa,EAAE,MAAM,iBAAiB,CAAC;AAEhD,MAAM,OAAO,gCAAiC,SAAQ,oCAAoC;IAC9E,iBAAiB,CAAU;IAErC,YAAY,OAAoC;QAC9C,KAAK,CAAC,OAAO,CAAC,CAAC;QACf,IAAI,CAAC,iBAAiB,GAAG,KAAK,CAAC;IACjC,CAAC;IACS,MAAM;QACd;;;;;;;WAOG;QACH,MAAM,EAAE,UAAU,EAAE,GAAG,IAAI,CAAC,OAAO,CAAC;QACpC,MAAM,WAAW,GAAG,EAAE,QAAQ,EAAE,IAAI,CAAC,OAAO,CAAC,UAAU,EAAE,CAAC;QAC1D,IAAI,EAAyB,CAAC;QAC9B,IAAI,CAAC;YACH,mFAAmF;YACnF,EAAE,GAAG,IAAI,CAAC,UAAU,EAAE,WAAW,CAAC,CAAC;QACrC,CAAC;QAAC,OAAO,EAAE,EAAE,CAAC;YACZ,IAAI,EAAE,CAAC,OAAO,CAAC,QAAQ,CAAC,cAAc,CAAC,EAAE,CAAC;gBACxC,WAAW,CAAC,KAAK,CAAC,UAAU,CAAC,CAAC;gBAC9B,EAAE,GAAG,IAAI,CAAC,UAAU,EAAE,WAAW,CAAC,CAAC;YACrC,CAAC;iBAAM,CAAC;gBACN,MAAM,EAAE,CAAC;YACX,CAAC;QACH,CAAC;QAED,OAAO,IAAI,aAAa,CAAC,EAAE,EAAE,IAAI,CAAC,OAAO,CAAC,UAAU,CAAC,CAAC;IACxD,CAAC;IAED,gBAAgB,CAAC,OAAiC;QAChD,IAAI,IAAI,CAAC,iBAAiB,EAAE,CAAC;YAC3B,IAAI,CAAC,OAAO,CAAC,MAAM,EAAE,IAAI,CAAC,iFAAiF,CAAC,CAAC;QAC/G,CAAC;QACD,IAAI,CAAC,iBAAiB,GAAG,IAAI,CAAC;QAC9B,OAAO,IAAI,iBAAiB,CAAC,OAAO,CAAC,CAAC;IACxC,CAAC;CACF"}
package/lib/index.d.ts ADDED
@@ -0,0 +1,7 @@
1
+ export * from '@powersync/common';
2
+ export * from '@powersync/react';
3
+ export * from './db/PowerSyncDatabase';
4
+ export * from './db/adapters/react-native-quick-sqlite/RNQSDBAdapter';
5
+ export * from './db/adapters/react-native-quick-sqlite//RNQSDBOpenFactory';
6
+ export * from './sync/stream/ReactNativeRemote';
7
+ export * from './sync/stream/ReactNativeStreamingSyncImplementation';
package/lib/index.js ADDED
@@ -0,0 +1,9 @@
1
+ // Re export to only require one import in client side code
2
+ export * from '@powersync/common';
3
+ export * from '@powersync/react';
4
+ export * from './db/PowerSyncDatabase';
5
+ export * from './db/adapters/react-native-quick-sqlite/RNQSDBAdapter';
6
+ export * from './db/adapters/react-native-quick-sqlite//RNQSDBOpenFactory';
7
+ export * from './sync/stream/ReactNativeRemote';
8
+ export * from './sync/stream/ReactNativeStreamingSyncImplementation';
9
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,2DAA2D;AAC3D,cAAc,mBAAmB,CAAC;AAClC,cAAc,kBAAkB,CAAC;AAEjC,cAAc,wBAAwB,CAAC;AACvC,cAAc,uDAAuD,CAAC;AACtE,cAAc,4DAA4D,CAAC;AAC3E,cAAc,iCAAiC,CAAC;AAChD,cAAc,sDAAsD,CAAC"}
@@ -0,0 +1,7 @@
1
+ import { AbstractRemote } from '@powersync/common';
2
+ export declare const STREAMING_POST_TIMEOUT_MS = 30000;
3
+ export declare class ReactNativeRemote extends AbstractRemote {
4
+ post(path: string, data: any, headers?: Record<string, string>): Promise<any>;
5
+ get(path: string, headers?: Record<string, string>): Promise<any>;
6
+ postStreaming(path: string, data: any, headers?: Record<string, string>, signal?: AbortSignal): Promise<any>;
7
+ }
@@ -0,0 +1,152 @@
1
+ import { AbortOperation, AbstractRemote } from '@powersync/common';
2
+ import { Platform } from 'react-native';
3
+ export const STREAMING_POST_TIMEOUT_MS = 30_000;
4
+ export class ReactNativeRemote extends AbstractRemote {
5
+ async post(path, data, headers = {}) {
6
+ const request = await this.buildRequest(path);
7
+ const res = await fetch(request.url, {
8
+ method: 'POST',
9
+ headers: {
10
+ ...headers,
11
+ ...request.headers
12
+ },
13
+ body: JSON.stringify(data)
14
+ });
15
+ if (!res.ok) {
16
+ throw new Error(`Received ${res.status} - ${res.statusText} when posting to ${path}: ${await res.text()}}`);
17
+ }
18
+ return res.json();
19
+ }
20
+ async get(path, headers) {
21
+ const request = await this.buildRequest(path);
22
+ const res = await fetch(request.url, {
23
+ method: 'GET',
24
+ headers: {
25
+ ...headers,
26
+ ...request.headers
27
+ }
28
+ });
29
+ if (!res.ok) {
30
+ throw new Error(`Received ${res.status} - ${res.statusText} when getting from ${path}: ${await res.text()}}`);
31
+ }
32
+ return res.json();
33
+ }
34
+ async postStreaming(path, data, headers = {}, signal) {
35
+ // Ensure polyfills are present
36
+ if (typeof ReadableStream == 'undefined' ||
37
+ typeof TextEncoder == 'undefined' ||
38
+ typeof TextDecoder == 'undefined') {
39
+ const errorMessage = `Polyfills are undefined. Please ensure React Native polyfills are installed and imported in the app entrypoint.
40
+ "import 'react-native-polyfill-globals/auto';"
41
+ `;
42
+ this.logger.error(errorMessage);
43
+ throw new Error(errorMessage);
44
+ }
45
+ const request = await this.buildRequest(path);
46
+ const timeout = Platform.OS == 'android'
47
+ ? setTimeout(() => {
48
+ this.logger.warn(`HTTP Streaming POST is taking longer than ${Math.ceil(STREAMING_POST_TIMEOUT_MS / 1000)} seconds to resolve. If using a debug build, please ensure Flipper Network plugin is disabled.`);
49
+ }, STREAMING_POST_TIMEOUT_MS)
50
+ : null;
51
+ /**
52
+ * This abort controller will abort the fetch request if it has not resolved yet.
53
+ * If the request has resolved, it will be used to close the stream.
54
+ * Aborting the request after the stream is resolved and is in use seems to throw
55
+ * unhandled exceptions on the window level.
56
+ */
57
+ const controller = new AbortController();
58
+ let requestResolved = false;
59
+ signal?.addEventListener('abort', () => {
60
+ if (!requestResolved) {
61
+ // Only abort via the abort controller if the request has not resolved yet
62
+ controller.abort(signal.reason ??
63
+ new AbortOperation('Cancelling network request before it resolves. Abort signal has been received.'));
64
+ }
65
+ });
66
+ const res = await fetch(request.url, {
67
+ method: 'POST',
68
+ headers: { ...headers, ...request.headers },
69
+ body: JSON.stringify(data),
70
+ signal: controller.signal,
71
+ cache: 'no-store',
72
+ /**
73
+ * The `react-native-fetch-api` polyfill provides streaming support via
74
+ * this non-standard flag
75
+ * https://github.com/react-native-community/fetch#enable-text-streaming
76
+ */
77
+ // @ts-expect-error https://github.com/react-native-community/fetch#enable-text-streaming
78
+ reactNative: { textStreaming: true }
79
+ }).catch((ex) => {
80
+ if (ex.name == 'AbortError') {
81
+ throw new AbortOperation(`Pending fetch request to ${request.url} has been aborted.`);
82
+ }
83
+ throw ex;
84
+ });
85
+ if (timeout != null) {
86
+ clearTimeout(timeout);
87
+ }
88
+ if (!res) {
89
+ throw new Error('Fetch request was aborted');
90
+ }
91
+ requestResolved = true;
92
+ if (!res.ok) {
93
+ const text = await res.text();
94
+ this.logger.error(`Could not POST streaming to ${path} - ${res.status} - ${res.statusText}: ${text}`);
95
+ const error = new Error(`HTTP ${res.statusText}: ${text}`);
96
+ error.status = res.status;
97
+ throw error;
98
+ }
99
+ /**
100
+ * The can-ndjson-stream does not handle aborted streams well.
101
+ * This will intercept the readable stream and close the stream if
102
+ * aborted.
103
+ * TODO this function is duplicated in the Web SDK.
104
+ * The common SDK is a bit oblivious to `ReadableStream` classes.
105
+ * This should be improved when moving to Websockets
106
+ */
107
+ const reader = res.body.getReader();
108
+ // This will close the network request and read stream
109
+ const closeReader = async () => {
110
+ try {
111
+ await reader.cancel();
112
+ }
113
+ catch (ex) {
114
+ // an error will throw if the reader hasn't been used yet
115
+ }
116
+ reader.releaseLock();
117
+ };
118
+ signal?.addEventListener('abort', () => {
119
+ closeReader();
120
+ });
121
+ const outputStream = new ReadableStream({
122
+ start: (controller) => {
123
+ const processStream = async () => {
124
+ while (!signal?.aborted) {
125
+ try {
126
+ const { done, value } = await reader.read();
127
+ // When no more data needs to be consumed, close the stream
128
+ if (done) {
129
+ break;
130
+ }
131
+ // Enqueue the next data chunk into our target stream
132
+ controller.enqueue(value);
133
+ }
134
+ catch (ex) {
135
+ this.logger.error('Caught exception when reading sync stream', ex);
136
+ break;
137
+ }
138
+ }
139
+ if (!signal?.aborted) {
140
+ // Close the downstream readable stream
141
+ await closeReader();
142
+ }
143
+ controller.close();
144
+ };
145
+ processStream();
146
+ }
147
+ });
148
+ // Create a new response out of the intercepted stream
149
+ return new Response(outputStream).body;
150
+ }
151
+ }
152
+ //# sourceMappingURL=ReactNativeRemote.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"ReactNativeRemote.js","sourceRoot":"","sources":["../../../src/sync/stream/ReactNativeRemote.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,c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OAAO,IAAI,QAAQ,CAAC,YAAY,CAAC,CAAC,IAAI,CAAC;IACzC,CAAC;CACF"}
@@ -0,0 +1,11 @@
1
+ import { AbstractStreamingSyncImplementation, AbstractStreamingSyncImplementationOptions, LockOptions, LockType } from '@powersync/common';
2
+ import Lock from 'async-lock';
3
+ export declare class ReactNativeStreamingSyncImplementation extends AbstractStreamingSyncImplementation {
4
+ locks: Map<LockType, Lock>;
5
+ constructor(options: AbstractStreamingSyncImplementationOptions);
6
+ /**
7
+ * Configures global locks on sync process
8
+ */
9
+ initLocks(): void;
10
+ obtainLock<T>(lockOptions: LockOptions<T>): Promise<T>;
11
+ }
@@ -0,0 +1,43 @@
1
+ import { AbstractStreamingSyncImplementation, LockType } from '@powersync/common';
2
+ import Lock from 'async-lock';
3
+ /**
4
+ * Global locks which prevent multiple instances from syncing
5
+ * concurrently.
6
+ */
7
+ const LOCKS = new Map();
8
+ export class ReactNativeStreamingSyncImplementation extends AbstractStreamingSyncImplementation {
9
+ locks;
10
+ constructor(options) {
11
+ super(options);
12
+ this.initLocks();
13
+ }
14
+ /**
15
+ * Configures global locks on sync process
16
+ */
17
+ initLocks() {
18
+ const { identifier } = this.options;
19
+ if (identifier && LOCKS.has(identifier)) {
20
+ this.locks = LOCKS.get(identifier);
21
+ return;
22
+ }
23
+ this.locks = new Map();
24
+ this.locks.set(LockType.CRUD, new Lock());
25
+ this.locks.set(LockType.SYNC, new Lock());
26
+ if (identifier) {
27
+ LOCKS.set(identifier, this.locks);
28
+ }
29
+ }
30
+ obtainLock(lockOptions) {
31
+ const lock = this.locks.get(lockOptions.type);
32
+ if (!lock) {
33
+ throw new Error(`Lock type ${lockOptions.type} not found`);
34
+ }
35
+ return lock.acquire(lockOptions.type, async () => {
36
+ if (lockOptions.signal?.aborted) {
37
+ throw new Error('Aborted');
38
+ }
39
+ return lockOptions.callback();
40
+ });
41
+ }
42
+ }
43
+ //# sourceMappingURL=ReactNativeStreamingSyncImplementation.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"ReactNativeStreamingSyncImplementation.js","sourceRoot":"","sources":["../../../src/sync/stream/ReactNativeStreamingSyncImplementation.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,mCAAmC,EAGnC,QAAQ,EACT,MAAM,mBAAmB,CAAC;AAC3B,OAAO,IAAI,MAAM,YAAY,CAAC;AAE9B;;;GAGG;AACH,MAAM,KAAK,GAAG,IAAI,GAAG,EAA+B,CAAC;AAErD,MAAM,OAAO,sCAAuC,SAAQ,mCAAmC;IAC7F,KAAK,CAAsB;IAE3B,YAAY,OAAmD;QAC7D,KAAK,CAAC,OAAO,CAAC,CAAC;QACf,IAAI,CAAC,SAAS,EAAE,CAAC;IACnB,CAAC;IAED;;OAEG;IACH,SAAS;QACP,MAAM,EAAE,UAAU,EAAE,GAAG,IAAI,CAAC,OAAO,CAAC;QACpC,IAAI,UAAU,IAAI,KAAK,CAAC,GAAG,CAAC,UAAU,CAAC,EAAE,CAAC;YACxC,IAAI,CAAC,KAAK,GAAG,KAAK,CAAC,GAAG,CAAC,UAAU,CAAE,CAAC;YACpC,OAAO;QACT,CAAC;QAED,IAAI,CAAC,KAAK,GAAG,IAAI,GAAG,EAAkB,CAAC;QACvC,IAAI,CAAC,KAAK,CAAC,GAAG,CAAC,QAAQ,CAAC,IAAI,EAAE,IAAI,IAAI,EAAE,CAAC,CAAC;QAC1C,IAAI,CAAC,KAAK,CAAC,GAAG,CAAC,QAAQ,CAAC,IAAI,EAAE,IAAI,IAAI,EAAE,CAAC,CAAC;QAE1C,IAAI,UAAU,EAAE,CAAC;YACf,KAAK,CAAC,GAAG,CAAC,UAAU,EAAE,IAAI,CAAC,KAAK,CAAC,CAAC;QACpC,CAAC;IACH,CAAC;IAED,UAAU,CAAI,WAA2B;QACvC,MAAM,IAAI,GAAG,IAAI,CAAC,KAAK,CAAC,GAAG,CAAC,WAAW,CAAC,IAAI,CAAC,CAAC;QAC9C,IAAI,CAAC,IAAI,EAAE,CAAC;YACV,MAAM,IAAI,KAAK,CAAC,aAAa,WAAW,CAAC,IAAI,YAAY,CAAC,CAAC;QAC7D,CAAC;QACD,OAAO,IAAI,CAAC,OAAO,CAAC,WAAW,CAAC,IAAI,EAAE,KAAK,IAAI,EAAE;YAC/C,IAAI,WAAW,CAAC,MAAM,EAAE,OAAO,EAAE,CAAC;gBAChC,MAAM,IAAI,KAAK,CAAC,SAAS,CAAC,CAAC;YAC7B,CAAC;YAED,OAAO,WAAW,CAAC,QAAQ,EAAE,CAAC;QAChC,CAAC,CAAC,CAAC;IACL,CAAC;CACF"}
package/package.json ADDED
@@ -0,0 +1,60 @@
1
+ {
2
+ "name": "@powersync/react-native",
3
+ "version": "0.0.0-dev-20240506092851",
4
+ "publishConfig": {
5
+ "registry": "https://registry.npmjs.org/",
6
+ "access": "public"
7
+ },
8
+ "description": "PowerSync - sync Postgres with SQLite in your React Native app for offline-first and real-time data",
9
+ "main": "./lib/index.js",
10
+ "types": "./lib/index.d.ts",
11
+ "files": [
12
+ "lib"
13
+ ],
14
+ "repository": {
15
+ "type": "git",
16
+ "url": "git+https://github.com/powersync-ja/powersync-js.git"
17
+ },
18
+ "author": "JOURNEYAPPS",
19
+ "license": "Apache-2.0",
20
+ "bugs": {
21
+ "url": "https://github.com/powersync-ja/powersync-js/issues"
22
+ },
23
+ "homepage": "https://docs.powersync.com/",
24
+ "peerDependencies": {
25
+ "@journeyapps/react-native-quick-sqlite": "^1.1.5",
26
+ "base-64": "^1.0.0",
27
+ "react": "*",
28
+ "react-native": "*",
29
+ "react-native-fetch-api": "^3.0.0",
30
+ "react-native-get-random-values": "^1.9.0",
31
+ "react-native-polyfill-globals": "^3.1.0",
32
+ "react-native-url-polyfill": "^2.0.0",
33
+ "text-encoding": "^0.7.0",
34
+ "web-streams-polyfill": "^3.2.1"
35
+ },
36
+ "dependencies": {
37
+ "async-lock": "^1.4.0",
38
+ "@powersync/react": "0.0.0-dev-20240506092851",
39
+ "@powersync/common": "0.0.0-dev-20240506092851"
40
+ },
41
+ "devDependencies": {
42
+ "@journeyapps/react-native-quick-sqlite": "^1.1.5",
43
+ "@types/async-lock": "^1.4.0",
44
+ "react-native": "0.72.4",
45
+ "react": "18.2.0",
46
+ "typescript": "^5.1.3"
47
+ },
48
+ "keywords": [
49
+ "data sync",
50
+ "offline-first",
51
+ "sqlite",
52
+ "real-time data stream",
53
+ "live data"
54
+ ],
55
+ "scripts": {
56
+ "build": "tsc -b",
57
+ "clean": "rm -rf lib tsconfig.tsbuildinfo",
58
+ "watch": "tsc -b -w"
59
+ }
60
+ }