@powersync/capacitor 0.0.0-dev-20250922105508

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 (43) hide show
  1. package/LICENSE +201 -0
  2. package/README.md +95 -0
  3. package/android/build.gradle +71 -0
  4. package/android/src/main/AndroidManifest.xml +2 -0
  5. package/android/src/main/cpp/powersync_capacitor_jni.c +58 -0
  6. package/android/src/main/java/com/powersync/capacitor/PowerSync.java +13 -0
  7. package/android/src/main/java/com/powersync/capacitor/PowerSyncPlugin.java +20 -0
  8. package/android/src/main/res/.gitkeep +0 -0
  9. package/dist/docs.json +39 -0
  10. package/dist/esm/PowerSyncDatabase.d.ts +15 -0
  11. package/dist/esm/PowerSyncDatabase.js +70 -0
  12. package/dist/esm/PowerSyncDatabase.js.map +1 -0
  13. package/dist/esm/adapter/CapacitorSQLiteAdapter.d.ts +35 -0
  14. package/dist/esm/adapter/CapacitorSQLiteAdapter.js +234 -0
  15. package/dist/esm/adapter/CapacitorSQLiteAdapter.js.map +1 -0
  16. package/dist/esm/adapter/CapacitorSQLiteOpenFactory.d.ts +6 -0
  17. package/dist/esm/adapter/CapacitorSQLiteOpenFactory.js +10 -0
  18. package/dist/esm/adapter/CapacitorSQLiteOpenFactory.js.map +1 -0
  19. package/dist/esm/index.d.ts +3 -0
  20. package/dist/esm/index.js +4 -0
  21. package/dist/esm/index.js.map +1 -0
  22. package/dist/esm/plugin/PowerSyncCore.d.ts +2 -0
  23. package/dist/esm/plugin/PowerSyncCore.js +5 -0
  24. package/dist/esm/plugin/PowerSyncCore.js.map +1 -0
  25. package/dist/esm/plugin/PowerSyncPlugin.d.ts +15 -0
  26. package/dist/esm/plugin/PowerSyncPlugin.js +2 -0
  27. package/dist/esm/plugin/PowerSyncPlugin.js.map +1 -0
  28. package/dist/esm/plugin/web.d.ts +5 -0
  29. package/dist/esm/plugin/web.js +7 -0
  30. package/dist/esm/plugin/web.js.map +1 -0
  31. package/dist/esm/sync/CapacitorSyncImplementation.d.ts +7 -0
  32. package/dist/esm/sync/CapacitorSyncImplementation.js +20 -0
  33. package/dist/esm/sync/CapacitorSyncImplementation.js.map +1 -0
  34. package/dist/plugin.cjs.js +349 -0
  35. package/dist/plugin.cjs.js.map +1 -0
  36. package/dist/plugin.js +349 -0
  37. package/dist/plugin.js.map +1 -0
  38. package/ios/Sources/CPowerSyncCore/PowerSyncCore.c +13 -0
  39. package/ios/Sources/CPowerSyncCore/include/PowerSyncCore.h +6 -0
  40. package/ios/Sources/PowerSyncPlugin/PowerSync.swift +7 -0
  41. package/ios/Sources/PowerSyncPlugin/PowerSyncPlugin.swift +22 -0
  42. package/ios/Tests/PowerSyncPluginTests/PowerSyncPluginTests.swift +15 -0
  43. package/package.json +84 -0
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,95 @@
1
+ <p align="center">
2
+ <a href="https://www.powersync.com" target="_blank"><img src="https://github.com/powersync-ja/.github/assets/7372448/d2538c43-c1a0-4c47-9a76-41462dba484f"/></a>
3
+ </p>
4
+
5
+ # PowerSync SDK for Capacitor
6
+
7
+ _[PowerSync](https://www.powersync.com) is a sync engine for building local-first apps with instantly-responsive UI/UX and simplified state transfer. Syncs between SQLite on the client-side and Postgres, MongoDB or MySQL on the server-side._
8
+
9
+ This package (`@powersync/capacitor`) is the PowerSync SDK for Capacitor apps. It wraps the [PowerSync Web SDK](https://www.npmjs.com/package/@powersync/web) and uses [Capacitor Community SQLite](https://github.com/capacitor-community/sqlite) as the database driver for Android and iOS.
10
+
11
+ ## Note: Alpha Release
12
+
13
+ This package is currently in an alpha release.
14
+
15
+ ## Installation
16
+
17
+ ### Install Package
18
+
19
+ ```bash
20
+ npm install @powersync/capacitor
21
+ ```
22
+
23
+ This package uses `@powersync/web` as a peer dependency. For additional `@powersync/web` configuration and instructions see the Web SDK [README](https://www.npmjs.com/package/@powersync/web).
24
+
25
+ ### Install Peer Dependencies
26
+
27
+ You must also install the following peer dependencies:
28
+
29
+ ```bash
30
+ npm install @capacitor-community/sqlite @powersync/web @journeyapps/wa-sqlite
31
+ ```
32
+
33
+ See the [Capacitor Community SQLite](https://github.com/capacitor-community/sqlite?tab=readme-ov-file#installation) repository for additional instructions.
34
+
35
+ ### Sync Capacitor Plugins
36
+
37
+ After installing, sync your Capacitor project:
38
+
39
+ ```bash
40
+ npx cap sync
41
+ ```
42
+
43
+ ## Usage
44
+
45
+ ```javascript
46
+ import { PowerSyncDatabase } from '@powersync/capacitor';
47
+ // Import general components from the Web SDK package
48
+ import { Schema } from '@powersync/web';
49
+ /**
50
+ * The Capacitor PowerSyncDatabase will automatically detect the platform
51
+ * and use the appropriate database drivers.
52
+ */
53
+ const db = new PowerSyncDatabase({
54
+ schema: new Schema({...}),
55
+ database: {
56
+ dbFilename: "mydatabase.sqlite"
57
+ }
58
+ });
59
+ ```
60
+
61
+ - On Android and iOS, this SDK uses [Capacitor Community SQLite](https://github.com/capacitor-community/sqlite) for native database access.
62
+ - On web, it falls back to the [PowerSync Web SDK](https://www.npmjs.com/package/@powersync/web).
63
+
64
+ When using custom database factories, be sure to specify the `CapacitorSQLiteOpenFactory` for Capacitor platforms.
65
+
66
+ ```javascript
67
+ const db = new PowerSyncDatabase({
68
+ schema: new Schema({...}),
69
+ database: isWeb ? new WASQLiteOpenFactory({dbFilename: "mydb.sqlite"}) :
70
+ new CapacitorSQLiteOpenFactory({dbFilename: "mydb.sqlite"})
71
+ });
72
+ ```
73
+
74
+ ## Platform Support
75
+
76
+ - **Android**: Uses native SQLite via Capacitor Community SQLite.
77
+ - **iOS**: Uses native SQLite via Capacitor Community SQLite.
78
+ - **Web**: Uses WASQLite via the PowerSync Web SDK.
79
+ - **Electron**: Uses WASQLite via the PowerSync Web SDK.
80
+
81
+ ## Limitations
82
+
83
+ - Encryption for native mobile platforms is not yet supported.
84
+ - Multiple tab support is not available for native Android and iOS targets.
85
+ - The Capacitor Community SQLite APIs differ for execution and query operations. The `.execute()` method cannot be used for `SELECT` queries or `RETURNING` queries.
86
+
87
+ ## Examples
88
+
89
+ See the [`demos/example-capacitor/`](https://github.com/journeyapps/powersync-react-native-sdk/blob/capacitor-sdk/demos/example-capacitor/README.md#L1) directory for a working example.
90
+
91
+ ## Found a bug or need help?
92
+
93
+ - Join our [Discord server](https://discord.gg/powersync) to ask questions or share feedback.
94
+ - Open a [GitHub issue](https://github.com/powersync-ja/powersync-js/issues) for bugs.
95
+ - Submit ideas via our [public roadmap](https://roadmap.powersync.com/tabs/5-roadmap/submit-idea) or [schedule a chat](https://calendly.com/powersync-product/powersync-chat).
@@ -0,0 +1,71 @@
1
+ ext {
2
+ junitVersion = project.hasProperty('junitVersion') ? rootProject.ext.junitVersion : '4.13.2'
3
+ androidxAppCompatVersion = project.hasProperty('androidxAppCompatVersion') ? rootProject.ext.androidxAppCompatVersion : '1.7.0'
4
+ androidxJunitVersion = project.hasProperty('androidxJunitVersion') ? rootProject.ext.androidxJunitVersion : '1.2.1'
5
+ androidxEspressoCoreVersion = project.hasProperty('androidxEspressoCoreVersion') ? rootProject.ext.androidxEspressoCoreVersion : '3.6.1'
6
+ powerSyncCoreVersion = project.hasProperty('powerSyncCoreVersion') ? rootProject.ext.powerSyncCoreVersion : '0.4.5'
7
+ }
8
+
9
+ buildscript {
10
+ repositories {
11
+ google()
12
+ mavenCentral()
13
+ }
14
+ dependencies {
15
+ classpath 'com.android.tools.build:gradle:8.7.2'
16
+ }
17
+ }
18
+
19
+ apply plugin: 'com.android.library'
20
+
21
+ android {
22
+ namespace "com.powersync.capacitor"
23
+ compileSdk project.hasProperty('compileSdkVersion') ? rootProject.ext.compileSdkVersion : 35
24
+ defaultConfig {
25
+ minSdkVersion project.hasProperty('minSdkVersion') ? rootProject.ext.minSdkVersion : 23
26
+ targetSdkVersion project.hasProperty('targetSdkVersion') ? rootProject.ext.targetSdkVersion : 35
27
+ versionCode 1
28
+ versionName "1.0"
29
+ testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
30
+ }
31
+
32
+ externalNativeBuild {
33
+ cmake {
34
+ path "CMakeLists.txt"
35
+ }
36
+ }
37
+
38
+ buildFeatures {
39
+ prefab true
40
+ }
41
+
42
+ buildTypes {
43
+ release {
44
+ minifyEnabled false
45
+ proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
46
+ }
47
+ }
48
+ lintOptions {
49
+ abortOnError false
50
+ }
51
+ compileOptions {
52
+ sourceCompatibility JavaVersion.VERSION_21
53
+ targetCompatibility JavaVersion.VERSION_21
54
+ }
55
+ }
56
+
57
+ repositories {
58
+ google()
59
+ mavenCentral()
60
+ }
61
+
62
+
63
+ dependencies {
64
+ implementation fileTree(dir: 'libs', include: ['*.jar'])
65
+ implementation project(':capacitor-android')
66
+ implementation "androidx.appcompat:appcompat:$androidxAppCompatVersion"
67
+ implementation "com.powersync:powersync-sqlite-core:$powerSyncCoreVersion"
68
+ testImplementation "junit:junit:$junitVersion"
69
+ androidTestImplementation "androidx.test.ext:junit:$androidxJunitVersion"
70
+ androidTestImplementation "androidx.test.espresso:espresso-core:$androidxEspressoCoreVersion"
71
+ }
@@ -0,0 +1,2 @@
1
+ <manifest xmlns:android="http://schemas.android.com/apk/res/android">
2
+ </manifest>
@@ -0,0 +1,58 @@
1
+ #include <jni.h>
2
+ #include <dlfcn.h>
3
+ #include <android/log.h>
4
+
5
+ #define LOG_TAG "PowerSyncNative"
6
+
7
+ // Forward declarations (no need for full struct definitions)
8
+ typedef struct sqlite3 sqlite3;
9
+ typedef struct sqlite3_api_routines sqlite3_api_routines;
10
+
11
+ typedef int (*sqlite3_auto_extension_fn)(void (*xEntryPoint)(void));
12
+
13
+ extern int sqlite3_powersync_init(
14
+ sqlite3 *db, // Database handle
15
+ const char **pzErrMsg, // Error message out parameter
16
+ const struct sqlite3_api_routines *pThunk // SQLite API routines
17
+ );
18
+
19
+ int register_powersync(void) {
20
+ void *handle = dlopen("libsqlcipher.so", RTLD_LAZY);
21
+ if (!handle) {
22
+ __android_log_print(ANDROID_LOG_WARN, LOG_TAG, "Failed to dlopen libsqlcipher.so, trying process handle");
23
+ // Try loading from the process itself
24
+ handle = dlopen(NULL, RTLD_LAZY);
25
+ if (!handle) {
26
+ __android_log_print(ANDROID_LOG_ERROR, LOG_TAG, "Failed to dlopen process handle. SQLCipher symbols not found.");
27
+ return -1;
28
+ }
29
+ } else {
30
+ __android_log_print(ANDROID_LOG_DEBUG, LOG_TAG, "Successfully loaded libsqlcipher.so");
31
+ }
32
+
33
+ __android_log_print(ANDROID_LOG_DEBUG, LOG_TAG, "Resolving sqlite3_auto_extension symbol");
34
+ sqlite3_auto_extension_fn auto_ext = (sqlite3_auto_extension_fn)dlsym(handle, "sqlite3_auto_extension");
35
+ if (!auto_ext) {
36
+ __android_log_print(ANDROID_LOG_ERROR, LOG_TAG, "Failed to resolve sqlite3_auto_extension symbol");
37
+ }
38
+
39
+
40
+ if (!auto_ext) {
41
+ __android_log_print(ANDROID_LOG_ERROR, LOG_TAG, "Required symbols not found. Aborting registration.");
42
+ dlclose(handle);
43
+ return -2;
44
+ }
45
+
46
+ __android_log_print(ANDROID_LOG_DEBUG, LOG_TAG, "Registering powersync extension");
47
+ int result = auto_ext((void(*)(void))sqlite3_powersync_init);
48
+ __android_log_print(ANDROID_LOG_DEBUG, LOG_TAG, "register_powersync result: %d", result);
49
+ dlclose(handle);
50
+ __android_log_print(ANDROID_LOG_DEBUG, LOG_TAG, "Completed register_powersync");
51
+ return result;
52
+ }
53
+
54
+ // JNI wrapper
55
+ JNIEXPORT jint JNICALL
56
+ Java_com_powersync_capacitor_PowerSync_registerPowersync(JNIEnv *env, jobject thiz) {
57
+ return register_powersync();
58
+ }
@@ -0,0 +1,13 @@
1
+ package com.powersync.capacitor;
2
+
3
+ import com.getcapacitor.Logger;
4
+
5
+ public class PowerSync {
6
+ static {
7
+ System.loadLibrary("powersync_capacitor");
8
+ // Ensures we load this early before registering.
9
+ System.loadLibrary("sqlcipher");
10
+ }
11
+
12
+ public static native int registerPowersync();
13
+ }
@@ -0,0 +1,20 @@
1
+ package com.powersync.capacitor;
2
+
3
+ import com.getcapacitor.JSObject;
4
+ import com.getcapacitor.Plugin;
5
+ import com.getcapacitor.PluginCall;
6
+ import com.getcapacitor.PluginMethod;
7
+ import com.getcapacitor.annotation.CapacitorPlugin;
8
+
9
+ @CapacitorPlugin(name = "PowerSync")
10
+ public class PowerSyncPlugin extends Plugin {
11
+
12
+ private PowerSync implementation = new PowerSync();
13
+
14
+ @PluginMethod
15
+ public void registerCore(PluginCall call) {
16
+ JSObject ret = new JSObject();
17
+ ret.put("responseCode", implementation.registerPowersync());
18
+ call.resolve(ret);
19
+ }
20
+ }
File without changes
package/dist/docs.json ADDED
@@ -0,0 +1,39 @@
1
+ {
2
+ "api": {
3
+ "name": "PowerSyncPlugin",
4
+ "slug": "powersyncplugin",
5
+ "docs": "",
6
+ "tags": [],
7
+ "methods": [
8
+ {
9
+ "name": "registerCore",
10
+ "signature": "() => Promise<RegistrationResponse>",
11
+ "parameters": [],
12
+ "returns": "Promise<RegistrationResponse>",
13
+ "tags": [],
14
+ "docs": "Registers the PowerSync core extension with the SQLite library.",
15
+ "complexTypes": [
16
+ "RegistrationResponse"
17
+ ],
18
+ "slug": "registercore"
19
+ }
20
+ ],
21
+ "properties": []
22
+ },
23
+ "interfaces": [],
24
+ "enums": [],
25
+ "typeAliases": [
26
+ {
27
+ "name": "RegistrationResponse",
28
+ "slug": "registrationresponse",
29
+ "docs": "",
30
+ "types": [
31
+ {
32
+ "text": "{\n /**\n * Zero for successful registration, non-zero for failure.\n * - [Android] -1: SQLCipher library not found.\n * - [Android] -2: Required symbols not found.\n * - The result of sqlite3_auto_extension\n */\n responseCode: number;\n}",
33
+ "complexTypes": []
34
+ }
35
+ ]
36
+ }
37
+ ],
38
+ "pluginConfigs": []
39
+ }
@@ -0,0 +1,15 @@
1
+ import { DBAdapter, PowerSyncBackendConnector, RequiredAdditionalConnectionOptions, StreamingSyncImplementation, PowerSyncDatabase as WebPowerSyncDatabase, WebPowerSyncDatabaseOptionsWithSettings } from '@powersync/web';
2
+ /**
3
+ * PowerSyncDatabase class for managing database connections and sync implementations.
4
+ * This extends the WebPowerSyncDatabase to provide platform-specific implementations
5
+ * for Capacitor environments (iOS and Android).
6
+ *
7
+ * @experimental
8
+ * @alpha
9
+ */
10
+ export declare class PowerSyncDatabase extends WebPowerSyncDatabase {
11
+ protected get isNativeCapacitorPlatform(): boolean;
12
+ protected openDBAdapter(options: WebPowerSyncDatabaseOptionsWithSettings): DBAdapter;
13
+ protected runExclusive<T>(cb: () => Promise<T>): Promise<T>;
14
+ protected generateSyncStreamImplementation(connector: PowerSyncBackendConnector, options: RequiredAdditionalConnectionOptions): StreamingSyncImplementation;
15
+ }
@@ -0,0 +1,70 @@
1
+ import { Capacitor } from '@capacitor/core';
2
+ import { PowerSyncDatabase as WebPowerSyncDatabase, WebRemote } from '@powersync/web';
3
+ import { CapacitorSQLiteAdapter } from './adapter/CapacitorSQLiteAdapter';
4
+ import { CapacitorStreamingSyncImplementation } from './sync/CapacitorSyncImplementation';
5
+ /**
6
+ * PowerSyncDatabase class for managing database connections and sync implementations.
7
+ * This extends the WebPowerSyncDatabase to provide platform-specific implementations
8
+ * for Capacitor environments (iOS and Android).
9
+ *
10
+ * @experimental
11
+ * @alpha
12
+ */
13
+ export class PowerSyncDatabase extends WebPowerSyncDatabase {
14
+ get isNativeCapacitorPlatform() {
15
+ const platform = Capacitor.getPlatform();
16
+ return platform == 'ios' || platform == 'android';
17
+ }
18
+ openDBAdapter(options) {
19
+ var _a, _b, _c;
20
+ const platform = Capacitor.getPlatform();
21
+ if (platform == 'ios' || platform == 'android') {
22
+ if (options.database.dbLocation) {
23
+ (_a = options.logger) === null || _a === void 0 ? void 0 : _a.warn(`
24
+ dbLocation is ignored on iOS and Android platforms.
25
+ The database directory can be configured in the Capacitor project.
26
+ See https://github.com/capacitor-community/sqlite?tab=readme-ov-file#installation`);
27
+ }
28
+ (_b = options.logger) === null || _b === void 0 ? void 0 : _b.debug(`Using CapacitorSQLiteAdapter for platform: ${platform}`);
29
+ return new CapacitorSQLiteAdapter({
30
+ dbFilename: options.database.dbFilename
31
+ });
32
+ }
33
+ else {
34
+ (_c = options.logger) === null || _c === void 0 ? void 0 : _c.debug(`Using default web adapter for web platform`);
35
+ return super.openDBAdapter(options);
36
+ }
37
+ }
38
+ runExclusive(cb) {
39
+ if (this.isNativeCapacitorPlatform) {
40
+ // Use mutex for mobile platforms.
41
+ // This is mainly for testing purposes since navigator.locks require secure contexts.
42
+ return this.runExclusiveMutex.runExclusive(cb);
43
+ }
44
+ else {
45
+ // Use navigator.locks for web platform
46
+ return super.runExclusive(cb);
47
+ }
48
+ }
49
+ generateSyncStreamImplementation(connector, options) {
50
+ var _a;
51
+ if (this.isNativeCapacitorPlatform) {
52
+ // We don't want to support multi-tab on mobile platforms.
53
+ // We technically can, but it's not a common use case and requires additional work/testing.
54
+ this.logger.debug(`Using Capacitor sync implementation`);
55
+ if ((_a = this.options.flags) === null || _a === void 0 ? void 0 : _a.enableMultiTabs) {
56
+ this.logger.warn(`enableMultiTabs is not supported on Capacitor mobile platforms. Ignoring the flag.`);
57
+ }
58
+ const remote = new WebRemote(connector, this.logger);
59
+ return new CapacitorStreamingSyncImplementation(Object.assign(Object.assign({}, this.options), { retryDelayMs: options.retryDelayMs, crudUploadThrottleMs: options.crudUploadThrottleMs, adapter: this.bucketStorageAdapter, remote, uploadCrud: async () => {
60
+ await this.waitForReady();
61
+ await connector.uploadData(this);
62
+ }, identifier: this.database.name, logger: this.logger, subscriptions: options.subscriptions }));
63
+ }
64
+ else {
65
+ this.logger.debug(`Using default web sync implementation for web platform`);
66
+ return super.generateSyncStreamImplementation(connector, options);
67
+ }
68
+ }
69
+ }
70
+ //# sourceMappingURL=PowerSyncDatabase.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"PowerSyncDatabase.js","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;IACH,CAAC;CACF","sourcesContent":["import { Capacitor } from '@capacitor/core';\nimport {\n DBAdapter,\n PowerSyncBackendConnector,\n RequiredAdditionalConnectionOptions,\n StreamingSyncImplementation,\n PowerSyncDatabase as WebPowerSyncDatabase,\n WebPowerSyncDatabaseOptionsWithSettings,\n WebRemote\n} from '@powersync/web';\nimport { CapacitorSQLiteAdapter } from './adapter/CapacitorSQLiteAdapter';\nimport { CapacitorStreamingSyncImplementation } from './sync/CapacitorSyncImplementation';\n\n/**\n * PowerSyncDatabase class for managing database connections and sync implementations.\n * This extends the WebPowerSyncDatabase to provide platform-specific implementations\n * for Capacitor environments (iOS and Android).\n *\n * @experimental\n * @alpha\n */\nexport class PowerSyncDatabase extends WebPowerSyncDatabase {\n protected get isNativeCapacitorPlatform(): boolean {\n const platform = Capacitor.getPlatform();\n return platform == 'ios' || platform == 'android';\n }\n\n protected openDBAdapter(options: WebPowerSyncDatabaseOptionsWithSettings): DBAdapter {\n const platform = Capacitor.getPlatform();\n if (platform == 'ios' || platform == 'android') {\n if (options.database.dbLocation) {\n options.logger?.warn(`\n dbLocation is ignored on iOS and Android platforms. \n The database directory can be configured in the Capacitor project.\n See https://github.com/capacitor-community/sqlite?tab=readme-ov-file#installation`);\n }\n options.logger?.debug(`Using CapacitorSQLiteAdapter for platform: ${platform}`);\n return new CapacitorSQLiteAdapter({\n dbFilename: options.database.dbFilename\n });\n } else {\n options.logger?.debug(`Using default web adapter for web platform`);\n return super.openDBAdapter(options);\n }\n }\n\n protected runExclusive<T>(cb: () => Promise<T>): Promise<T> {\n if (this.isNativeCapacitorPlatform) {\n // Use mutex for mobile platforms.\n // This is mainly for testing purposes since navigator.locks require secure contexts.\n return this.runExclusiveMutex.runExclusive(cb);\n } else {\n // Use navigator.locks for web platform\n return super.runExclusive(cb);\n }\n }\n\n protected generateSyncStreamImplementation(\n connector: PowerSyncBackendConnector,\n options: RequiredAdditionalConnectionOptions\n ): StreamingSyncImplementation {\n if (this.isNativeCapacitorPlatform) {\n // We don't want to support multi-tab on mobile platforms.\n // We technically can, but it's not a common use case and requires additional work/testing.\n this.logger.debug(`Using Capacitor sync implementation`);\n if (this.options.flags?.enableMultiTabs) {\n this.logger.warn(`enableMultiTabs is not supported on Capacitor mobile platforms. Ignoring the flag.`);\n }\n const remote = new WebRemote(connector, this.logger);\n\n return new CapacitorStreamingSyncImplementation({\n ...(this.options as {}),\n retryDelayMs: options.retryDelayMs,\n crudUploadThrottleMs: options.crudUploadThrottleMs,\n adapter: this.bucketStorageAdapter,\n remote,\n uploadCrud: async () => {\n await this.waitForReady();\n await connector.uploadData(this);\n },\n identifier: this.database.name,\n logger: this.logger,\n subscriptions: options.subscriptions\n });\n } else {\n this.logger.debug(`Using default web sync implementation for web platform`);\n return super.generateSyncStreamImplementation(connector, options);\n }\n }\n}\n"]}
@@ -0,0 +1,35 @@
1
+ import { SQLiteDBConnection } from '@capacitor-community/sqlite';
2
+ import { BaseObserver, DBAdapter, DBAdapterListener, DBLockOptions, LockContext, QueryResult, SQLOpenOptions, Transaction } from '@powersync/web';
3
+ import Lock from 'async-lock';
4
+ /**
5
+ * An implementation of {@link DBAdapter} using the Capacitor Community SQLite [plugin](https://github.com/capacitor-community/sqlite).
6
+ *
7
+ * @experimental
8
+ * @alpha This is currently experimental and may change without a major version bump.
9
+ */
10
+ export declare class CapacitorSQLiteAdapter extends BaseObserver<DBAdapterListener> implements DBAdapter {
11
+ protected options: SQLOpenOptions;
12
+ protected _writeConnection: SQLiteDBConnection | null;
13
+ protected _readConnection: SQLiteDBConnection | null;
14
+ protected initializedPromise: Promise<void>;
15
+ protected lock: Lock;
16
+ constructor(options: SQLOpenOptions);
17
+ protected get writeConnection(): SQLiteDBConnection;
18
+ protected get readConnection(): SQLiteDBConnection;
19
+ private init;
20
+ close(): Promise<void>;
21
+ get name(): string;
22
+ protected generateLockContext(db: SQLiteDBConnection): LockContext;
23
+ execute(query: string, params?: any[]): Promise<QueryResult>;
24
+ executeRaw(query: string, params?: any[]): Promise<any[][]>;
25
+ executeBatch(query: string, params?: any[][]): Promise<QueryResult>;
26
+ readLock<T>(fn: (tx: LockContext) => Promise<T>, options?: DBLockOptions): Promise<T>;
27
+ readTransaction<T>(fn: (tx: Transaction) => Promise<T>, options?: DBLockOptions): Promise<T>;
28
+ writeLock<T>(fn: (tx: LockContext) => Promise<T>, options?: DBLockOptions): Promise<T>;
29
+ writeTransaction<T>(fn: (tx: Transaction) => Promise<T>, options?: DBLockOptions): Promise<T>;
30
+ refreshSchema(): Promise<void>;
31
+ getAll<T>(sql: string, parameters?: any[]): Promise<T[]>;
32
+ getOptional<T>(sql: string, parameters?: any[]): Promise<T | null>;
33
+ get<T>(sql: string, parameters?: any[]): Promise<T>;
34
+ protected internalTransaction<T>(ctx: LockContext, fn: (tx: Transaction) => Promise<T>): Promise<T>;
35
+ }