cbl-ionic 0.2.6 → 1.0.1

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 (62) hide show
  1. package/CblIonic.podspec +1 -1
  2. package/README.md +12 -0
  3. package/android/build.gradle +1 -1
  4. package/android/src/main/java/cbl/js/kotiln/DatabaseManager.kt +19 -6
  5. package/android/src/main/java/cbl/js/kotiln/URLEndpointListenerManager.kt +143 -0
  6. package/android/src/main/java/com/couchbase/ionic/CblIonicPluginPlugin.kt +186 -30
  7. package/android/src/main/java/com/couchbase/ionic/PluginHelper.kt +27 -38
  8. package/android/src/main/java/com/couchbase/ionic/QueryHelper.kt +14 -4
  9. package/android/src/main/java/com/couchbase/ionic/ReplicatorHelper.kt +33 -11
  10. package/dist/esm/cblite-js/cblite/core-types.d.ts +148 -5
  11. package/dist/esm/cblite-js/cblite/src/collection-config.d.ts +34 -0
  12. package/dist/esm/cblite-js/cblite/src/collection-config.js +40 -0
  13. package/dist/esm/cblite-js/cblite/src/collection-config.js.map +1 -1
  14. package/dist/esm/cblite-js/cblite/src/collection.d.ts +1 -2
  15. package/dist/esm/cblite-js/cblite/src/collection.js +17 -17
  16. package/dist/esm/cblite-js/cblite/src/collection.js.map +1 -1
  17. package/dist/esm/cblite-js/cblite/src/database-logging.js +1 -1
  18. package/dist/esm/cblite-js/cblite/src/database-logging.js.map +1 -1
  19. package/dist/esm/cblite-js/cblite/src/database.d.ts +13 -2
  20. package/dist/esm/cblite-js/cblite/src/database.js +50 -34
  21. package/dist/esm/cblite-js/cblite/src/database.js.map +1 -1
  22. package/dist/esm/cblite-js/cblite/src/document.d.ts +3 -4
  23. package/dist/esm/cblite-js/cblite/src/document.js +6 -6
  24. package/dist/esm/cblite-js/cblite/src/document.js.map +1 -1
  25. package/dist/esm/cblite-js/cblite/src/index.d.ts +1 -0
  26. package/dist/esm/cblite-js/cblite/src/index.js +1 -0
  27. package/dist/esm/cblite-js/cblite/src/index.js.map +1 -1
  28. package/dist/esm/cblite-js/cblite/src/query.js +6 -11
  29. package/dist/esm/cblite-js/cblite/src/query.js.map +1 -1
  30. package/dist/esm/cblite-js/cblite/src/replicated-document.js +2 -2
  31. package/dist/esm/cblite-js/cblite/src/replicated-document.js.map +1 -1
  32. package/dist/esm/cblite-js/cblite/src/replicator-configuration.d.ts +2 -1
  33. package/dist/esm/cblite-js/cblite/src/replicator-configuration.js +29 -3
  34. package/dist/esm/cblite-js/cblite/src/replicator-configuration.js.map +1 -1
  35. package/dist/esm/cblite-js/cblite/src/replicator.js +8 -5
  36. package/dist/esm/cblite-js/cblite/src/replicator.js.map +1 -1
  37. package/dist/esm/cblite-js/cblite/src/scope.js +2 -2
  38. package/dist/esm/cblite-js/cblite/src/scope.js.map +1 -1
  39. package/dist/esm/cblite-js/cblite/src/url-endpoint-listener.d.ts +84 -0
  40. package/dist/esm/cblite-js/cblite/src/url-endpoint-listener.js +109 -0
  41. package/dist/esm/cblite-js/cblite/src/url-endpoint-listener.js.map +1 -0
  42. package/dist/esm/couchbase-lite/capacitor-engine.d.ts +17 -2
  43. package/dist/esm/couchbase-lite/capacitor-engine.js +19 -1
  44. package/dist/esm/couchbase-lite/capacitor-engine.js.map +1 -1
  45. package/dist/plugin.cjs.js +288 -82
  46. package/dist/plugin.cjs.js.map +1 -1
  47. package/dist/plugin.js +288 -82
  48. package/dist/plugin.js.map +1 -1
  49. package/ios/Plugin/CblIonicPlugin.swift +120 -7
  50. package/ios/Plugin/CblIonicPluginPlugin.m +7 -0
  51. package/ios/Plugin/cbl-js-swift/CollectionManager.swift +24 -3
  52. package/ios/Plugin/cbl-js-swift/DatabaseManager.swift +29 -13
  53. package/ios/Plugin/cbl-js-swift/FileSystemHelper.swift +0 -2
  54. package/ios/Plugin/cbl-js-swift/IndexHelper.swift +0 -2
  55. package/ios/Plugin/cbl-js-swift/LoggingManager.swift +0 -2
  56. package/ios/Plugin/cbl-js-swift/MapHelper.swift +0 -25
  57. package/ios/Plugin/cbl-js-swift/QueryHelper.swift +0 -2
  58. package/ios/Plugin/cbl-js-swift/README.md +12 -0
  59. package/ios/Plugin/cbl-js-swift/ReplicatorHelper.swift +116 -5
  60. package/ios/Plugin/cbl-js-swift/ReplicatorManager.swift +0 -2
  61. package/ios/Plugin/cbl-js-swift/URLEndpointListenerManager.swift +154 -0
  62. package/package.json +8 -3
@@ -78,9 +78,11 @@ public class CblIonicPluginPlugin: CAPPlugin {
78
78
  return
79
79
  }
80
80
  do {
81
- try DatabaseManager.shared.open (name, databaseConfig: configValue)
81
+ let databaseUniqueName = try DatabaseManager.shared.open (name, databaseConfig: configValue)
82
82
  DispatchQueue.main.async {
83
- call.resolve()
83
+ call.resolve(
84
+ ["databaseUniqueName": databaseUniqueName]
85
+ )
84
86
  return
85
87
  }
86
88
  } catch {
@@ -783,10 +785,19 @@ public class CblIonicPluginPlugin: CAPPlugin {
783
785
  }
784
786
 
785
787
  var data: [String: Any] = [:]
786
- let documentMap = MapHelper.documentToMap(doc)
787
- data["_data"] = documentMap
788
- data["_id"] = docId
789
- data["_sequence"] = doc.sequence
788
+ let documentJson = doc.toJSON()
789
+ if !documentJson.isEmpty {
790
+ guard let jsonData = documentJson.data(using: .utf8),
791
+ let jsonDict = try JSONSerialization.jsonObject(with: jsonData, options: []) as? [String: Any] else {
792
+ call.reject("DOCUMENT_ERROR", "Failed to parse document JSON", nil)
793
+ return
794
+ }
795
+ data["_data"] = jsonDict
796
+ } else {
797
+ data["_data"] = [:]
798
+ }
799
+ data["_id"] = docId
800
+ data["_sequence"] = doc.sequence
790
801
  data["_revId"] = doc.revisionID
791
802
  DispatchQueue.main.async {
792
803
  call.resolve(data)
@@ -1320,7 +1331,7 @@ public class CblIonicPluginPlugin: CAPPlugin {
1320
1331
  }
1321
1332
  } else {
1322
1333
  DispatchQueue.main.async {
1323
- call.reject("No such replicator listener")
1334
+ call.reject("No such listener found")
1324
1335
  }
1325
1336
  return
1326
1337
  }
@@ -1580,4 +1591,106 @@ public class CblIonicPluginPlugin: CAPPlugin {
1580
1591
  }
1581
1592
  }
1582
1593
  }
1594
+
1595
+ // MARK: - URL Endpoint Listener
1596
+
1597
+ @objc func URLEndpointListener_createListener(_ call: CAPPluginCall) {
1598
+ guard let collectionsArray = call.getArray("collections") as? [[String: String]],
1599
+ let port = call.getInt("port"),
1600
+ let networkInterface = call.getString("networkInterface")
1601
+ else {
1602
+ call.reject("Missing required parameters")
1603
+ return
1604
+ }
1605
+ let authenticatorConfig = call.getObject("authenticatorConfig") as? [String: Any]
1606
+ let tlsIdentityConfig = call.getObject("tlsIdentityConfig") as? [String: Any]
1607
+ let disableTLS = call.getBool("disableTLS")
1608
+ let enableDeltaSync = call.getBool("enableDeltaSync")
1609
+ var collections: [Collection] = []
1610
+ do {
1611
+ for dict in collectionsArray {
1612
+ guard let dbName = dict["databaseName"],
1613
+ let scopeName = dict["scopeName"],
1614
+ let collectionName = dict["name"],
1615
+ let db = DatabaseManager.shared.getDatabase(dbName),
1616
+ let scope = try? db.scope(name: scopeName),
1617
+ let collection = try? scope.collection(name: collectionName) else {
1618
+ call.reject("Invalid collection parameters")
1619
+ return
1620
+ }
1621
+ collections.append(collection)
1622
+ }
1623
+ let listenerId = try URLEndpointListenerManager.shared.createListener(
1624
+ collections: collections,
1625
+ port: UInt16(port),
1626
+ networkInterface: networkInterface,
1627
+ disableTLS: disableTLS,
1628
+ enableDeltaSync: enableDeltaSync,
1629
+ authenticatorConfig: authenticatorConfig,
1630
+ tlsIdentityConfig: tlsIdentityConfig
1631
+ )
1632
+ call.resolve(["listenerId": listenerId])
1633
+ } catch {
1634
+ call.reject("Failed to create listener: \(error.localizedDescription)")
1635
+ }
1636
+ }
1637
+
1638
+ @objc func URLEndpointListener_startListener(_ call: CAPPluginCall) {
1639
+ guard let listenerId = call.getString("listenerId") else {
1640
+ call.reject("Missing required parameter: 'listenerId'")
1641
+ return
1642
+ }
1643
+
1644
+ do {
1645
+ try URLEndpointListenerManager.shared.startListener(listenerId: listenerId)
1646
+ call.resolve()
1647
+ } catch {
1648
+ call.reject("Failed to start listener: \(error.localizedDescription)")
1649
+ }
1650
+ }
1651
+ @objc func URLEndpointListener_stopListener(_ call: CAPPluginCall) {
1652
+
1653
+ guard let listenerId = call.getString("listenerId") else {
1654
+ call.reject("Missing required parameter: 'listenerId'")
1655
+ return
1656
+ }
1657
+
1658
+ do {
1659
+ try URLEndpointListenerManager.shared.stopListener(listenerId: listenerId)
1660
+ call.resolve()
1661
+ } catch {
1662
+ call.reject("Failed to stop listener: \(error.localizedDescription)")
1663
+ }
1664
+ }
1665
+ @objc func URLEndpointListener_getStatus(_ call: CAPPluginCall) {
1666
+ guard let listenerId = call.getString("listenerId") else {
1667
+ call.reject("Missing required parameter: 'listenerId'")
1668
+ return
1669
+ }
1670
+
1671
+ do {
1672
+ let status = try URLEndpointListenerManager.shared.getListenerStatus(listenerId: listenerId)
1673
+
1674
+ let result: [String: Any] = [
1675
+ "connectionsCount": status.connectionCount,
1676
+ "activeConnectionCount": status.activeConnectionCount
1677
+ ]
1678
+ call.resolve(result)
1679
+ } catch {
1680
+ call.reject("Failed to get listener status: \(error.localizedDescription)")
1681
+ }
1682
+ }
1683
+ @objc func URLEndpointListener_deleteIdentity(_ call: CAPPluginCall) {
1684
+ guard let label = call.getString("label") else {
1685
+ call.reject("Missing required parameter: 'label'")
1686
+ return
1687
+ }
1688
+
1689
+ do {
1690
+ try URLEndpointListenerManager.shared.deleteIdentity(label: label)
1691
+ call.resolve()
1692
+ } catch {
1693
+ call.reject("Failed to delete identity: \(error.localizedDescription)")
1694
+ }
1695
+ }
1583
1696
  }
@@ -83,4 +83,11 @@ CAP_PLUGIN(CblIonicPlugin, "CblIonicPlugin",
83
83
  CAP_PLUGIN_METHOD(replicator_RemoveChangeListener, CAPPluginReturnPromise);
84
84
  CAP_PLUGIN_METHOD(replicator_AddDocumentChangeListener, CAPPluginReturnCallback);
85
85
  CAP_PLUGIN_METHOD(replicator_Cleanup, CAPPluginReturnPromise);
86
+
87
+ // URL Endpoints functions
88
+ CAP_PLUGIN_METHOD(URLEndpointListener_createListener, CAPPluginReturnPromise);
89
+ CAP_PLUGIN_METHOD(URLEndpointListener_startListener, CAPPluginReturnPromise);
90
+ CAP_PLUGIN_METHOD(URLEndpointListener_stopListener, CAPPluginReturnPromise);
91
+ CAP_PLUGIN_METHOD(URLEndpointListener_getStatus, CAPPluginReturnPromise);
92
+ CAP_PLUGIN_METHOD(URLEndpointListener_deleteIdentity, CAPPluginReturnPromise);
86
93
  )
@@ -24,6 +24,28 @@ public struct CollectionDto: Codable {
24
24
  public struct ConfigDto: Codable {
25
25
  let channels: [String]
26
26
  let documentIds: [String]
27
+ let pushFilter: String?
28
+ let pullFilter: String?
29
+
30
+ enum CodingKeys: String, CodingKey {
31
+ case channels, documentIds, pushFilter, pullFilter
32
+ }
33
+
34
+ public init(from decoder: Decoder) throws {
35
+ let container = try decoder.container(keyedBy: CodingKeys.self)
36
+ channels = try container.decodeIfPresent([String].self, forKey: .channels) ?? []
37
+ documentIds = try container.decodeIfPresent([String].self, forKey: .documentIds) ?? []
38
+ pushFilter = try container.decodeIfPresent(String.self, forKey: .pushFilter)
39
+ pullFilter = try container.decodeIfPresent(String.self, forKey: .pullFilter)
40
+ }
41
+
42
+ public func encode(to encoder: Encoder) throws {
43
+ var container = encoder.container(keyedBy: CodingKeys.self)
44
+ try container.encode(channels, forKey: .channels)
45
+ try container.encode(documentIds, forKey: .documentIds)
46
+ try container.encodeIfPresent(pushFilter, forKey: .pushFilter)
47
+ try container.encodeIfPresent(pullFilter, forKey: .pullFilter)
48
+ }
27
49
  }
28
50
 
29
51
  public struct DocumentDto: Codable {
@@ -402,7 +424,6 @@ public class CollectionManager {
402
424
  collectionName: String,
403
425
  scopeName: String,
404
426
  databaseName: String) throws -> CollectionDocumentResult {
405
-
406
427
  guard let collection = try self.getCollection(
407
428
  collectionName,
408
429
  scopeName: scopeName,
@@ -412,7 +433,7 @@ public class CollectionManager {
412
433
  scopeName: scopeName,
413
434
  databaseName: databaseName)
414
435
  }
415
-
436
+
416
437
  do {
417
438
  //create the document
418
439
  let mutableDocument: MutableDocument
@@ -426,7 +447,7 @@ public class CollectionManager {
426
447
  for (key, blob) in blobs {
427
448
  mutableDocument.setBlob(blob, forKey: key)
428
449
  }
429
-
450
+
430
451
  if let concurrencyControlValue = concurrencyControl {
431
452
  let results = try collection.save(document: mutableDocument, concurrencyControl: concurrencyControlValue)
432
453
  if results {
@@ -1,6 +1,5 @@
1
1
  //
2
2
  // DatabaseManager.swift
3
- // Created by Aaron LaBeau on 07/04/24.
4
3
  //
5
4
 
6
5
  import Foundation
@@ -35,6 +34,9 @@ public class DatabaseManager {
35
34
  private var defaultCollectionName: String = "_default"
36
35
  private var defaultScopeName: String = "_default"
37
36
 
37
+ private let databaseQueue = DispatchQueue(label: "com.couchbase.lite.database.access")
38
+
39
+
38
40
  // MARK: - Singleton
39
41
  public static let shared = DatabaseManager()
40
42
 
@@ -46,12 +48,9 @@ public class DatabaseManager {
46
48
  // MARK: - Helper Functions
47
49
 
48
50
  public func getDatabase(_ name: String) -> Database? {
49
- objc_sync_enter(openDatabases)
50
- defer {
51
- objc_sync_exit(openDatabases)
51
+ return databaseQueue.sync {
52
+ return openDatabases[name]
52
53
  }
53
-
54
- return openDatabases[name]
55
54
  }
56
55
 
57
56
  public func buildDatabaseConfig(_ config: [AnyHashable: Any]?) -> DatabaseConfiguration {
@@ -70,15 +69,17 @@ public class DatabaseManager {
70
69
 
71
70
  // MARK: Database Functions
72
71
 
73
- public func open(_ databaseName: String, databaseConfig: [AnyHashable: Any]?) throws {
72
+ public func open(_ databaseName: String, databaseConfig: [AnyHashable: Any]?) throws -> String {
74
73
  do {
75
- if self.openDatabases[databaseName] != nil {
76
- self.openDatabases.removeValue(forKey: databaseName)
77
- }
74
+ let nanoId = generateNanoId()
75
+ let uniqueName = "\(databaseName)_\(nanoId)"
78
76
 
79
77
  let config = self.buildDatabaseConfig(databaseConfig)
80
78
  let database = try Database(name: databaseName, config: config)
81
- self.openDatabases[databaseName] = database
79
+
80
+ openDatabases[uniqueName] = database
81
+
82
+ return uniqueName
82
83
  } catch {
83
84
  throw DatabaseError.unableToOpenDatabase(databaseName: databaseName)
84
85
  }
@@ -100,8 +101,10 @@ public class DatabaseManager {
100
101
  throw DatabaseError.invalidDatabaseName(databaseName: databaseName)
101
102
  }
102
103
  do {
103
- try database.delete()
104
- openDatabases.removeValue(forKey: databaseName)
104
+ return try databaseQueue.sync {
105
+ try database.delete()
106
+ openDatabases.removeValue(forKey: databaseName)
107
+ }
105
108
  } catch {
106
109
  if let nsError = error as NSError?, nsError.code == 19 {
107
110
  // SQLite error code 19 (SQLITE_CONSTRAINT) indicates that the database is locked.
@@ -317,3 +320,16 @@ public class DatabaseManager {
317
320
  }
318
321
  }
319
322
  }
323
+
324
+ func generateNanoId(size: Int = 21) -> String {
325
+ let alphabet = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
326
+ let characters = Array(alphabet)
327
+ var nanoId = ""
328
+
329
+ for _ in 0..<size {
330
+ let randomIndex = Int.random(in: 0..<characters.count)
331
+ nanoId.append(characters[randomIndex])
332
+ }
333
+
334
+ return nanoId
335
+ }
@@ -2,8 +2,6 @@
2
2
  // FileSystemHelper.swift
3
3
  // CbliteSwiftJsLib
4
4
  //
5
- // Created by Aaron LaBeau on 07/04/24.
6
- //
7
5
 
8
6
  import Foundation
9
7
 
@@ -2,8 +2,6 @@
2
2
  // IndexHelper.swift
3
3
  // CbliteSwiftJsLib
4
4
  //
5
- // Created by Aaron LaBeau on 07/04/24.
6
- //
7
5
 
8
6
  import Foundation
9
7
  import CouchbaseLiteSwift
@@ -2,8 +2,6 @@
2
2
  // LoggingManager.swift
3
3
  // CbliteSwiftJsLib
4
4
  //
5
- // Created by Aaron LaBeau on 09/04/24.
6
- //
7
5
 
8
6
  import Foundation
9
7
  import CouchbaseLiteSwift
@@ -1,37 +1,12 @@
1
1
  //
2
2
  // QueryHelper.swift
3
3
  // CbliteSwiftJsLib
4
- //
5
- // Created by Aaron LaBeau on 07/04/24.
6
4
 
7
5
  import Foundation
8
6
  import CouchbaseLiteSwift
9
7
 
10
8
  public struct MapHelper {
11
9
 
12
- public static func documentToMap(_ document: Document) ->
13
- [String: Any] {
14
- var docMap = [String: Any]()
15
- let documentAsMap = document.toDictionary()
16
- for (key, value) in documentAsMap {
17
- if let blobEntry = value as? Blob {
18
- var properties = blobEntry.properties
19
- if let data = blobEntry.content {
20
- var content: [Int] = []
21
- data.regions.forEach { region in
22
- for byte in region {
23
- content.append(Int(byte))
24
- }
25
- }
26
- docMap[key] = properties.merging(["raw": content]) { (_, new) in new }
27
- }
28
- } else {
29
- docMap[key] = value
30
- }
31
- }
32
- return docMap
33
- }
34
-
35
10
  public static func resultToMap(_ result: Result,
36
11
  databaseName: String) ->
37
12
  [String: Any] {
@@ -2,8 +2,6 @@
2
2
  // QueryHelper.swift
3
3
  // CbliteSwiftJsLib
4
4
  //
5
- // Created by Aaron LaBeau on 08/04/24.
6
- //
7
5
 
8
6
  import Foundation
9
7
  import CouchbaseLiteSwift
@@ -7,3 +7,15 @@ CbliteSwiftJsLib is a set of shared code to use with various integration librari
7
7
  ## License
8
8
 
9
9
  CbliteSwiftJsLib is available under the Apache 2.0 license. See the LICENSE file for more info.
10
+
11
+ ---
12
+
13
+ ## 📢 Support Policy
14
+
15
+ We truly appreciate your interest in this project!
16
+ This project is **community-maintained**, which means it's **not officially supported** by our support team.
17
+
18
+ If you need help, have found a bug, or want to contribute improvements, the best place to do that is right here — by [opening a GitHub issue](https://github.com/Couchbase-Ecosystem/cbl-js-swift/issues).
19
+ Our support portal is unable to assist with requests related to this project, so we kindly ask that all inquiries stay within GitHub.
20
+
21
+ Your collaboration helps us all move forward together — thank you!
@@ -2,14 +2,103 @@
2
2
  // ReplicatorHelper.swift
3
3
  // CbliteSwiftJsLib
4
4
  //
5
- // Created by Aaron LaBeau on 07/04/24.
6
- //
7
5
 
8
6
  import Foundation
9
7
  import JavaScriptCore
10
8
  import CouchbaseLiteSwift
11
9
 
12
10
  public struct ReplicatorHelper {
11
+ private static let jsContextQueue = DispatchQueue(label: "com.couchbase.jscontext")
12
+
13
+ private static let jsContext: JSContext = {
14
+ let context = JSContext()!
15
+
16
+ // Setup console.log for debugging
17
+ let logFunction: @convention(block) (String) -> Void = { message in
18
+ print("JSFilter: \(message)")
19
+ }
20
+
21
+ context.setObject(logFunction, forKeyedSubscript: "log" as NSString)
22
+ context.evaluateScript("var console = { log: log };")
23
+
24
+ // Handle JavaScript exceptions
25
+ context.exceptionHandler = { context, exception in
26
+ if let exc = exception {
27
+ print("JSFilter Exception: \(exc.toString() ?? "unknown error")")
28
+ }
29
+ }
30
+
31
+ return context
32
+ }()
33
+
34
+ private static func evaluateFilter(_ filterFunction: String, document: Document, flags: DocumentFlags) -> Bool {
35
+ return jsContextQueue.sync {
36
+ autoreleasepool {
37
+ // Convert document to dictionary
38
+ var docDict = document.toDictionary()
39
+ docDict["id"] = document.id
40
+
41
+ // Create flags array
42
+ let flagsArray: [String] = [
43
+ flags.contains(.deleted) ? "DELETED" : nil,
44
+ flags.contains(.accessRemoved) ? "ACCESS_REMOVED" : nil
45
+ ].compactMap { $0 }
46
+
47
+ // Set objects directly in JSContext
48
+ jsContext.setObject(docDict, forKeyedSubscript: "currentDocument" as NSString)
49
+ jsContext.setObject(flagsArray, forKeyedSubscript: "currentFlags" as NSString)
50
+ jsContext.setObject(filterFunction, forKeyedSubscript: "filterFunctionString" as NSString)
51
+
52
+ // Create and execute the filter script
53
+ let script = """
54
+ (function() {
55
+ try {
56
+ // Enum for flags
57
+ const ReplicatedDocumentFlag = {
58
+ DELETED: 'DELETED',
59
+ ACCESS_REMOVED: 'ACCESS_REMOVED'
60
+ };
61
+ // Create the filter function from string
62
+ const filterFunc = eval('(' + filterFunctionString + ')');
63
+
64
+ const result = filterFunc(currentDocument, currentFlags);
65
+ // Ensure we return a boolean
66
+ return !!result;
67
+ } catch (e) {
68
+ console.log('Filter error: ' + e.toString());
69
+ console.log('Stack: ' + (e.stack || 'No stack trace'));
70
+ return false;
71
+ }
72
+ })()
73
+ """
74
+
75
+ // Execute the script
76
+ guard let result = jsContext.evaluateScript(script) else {
77
+ print("JSFilter: Script evaluation returned nil")
78
+ return false
79
+ }
80
+
81
+ // Clear references
82
+ jsContext.setObject(nil, forKeyedSubscript: "currentDocument" as NSString)
83
+ jsContext.setObject(nil, forKeyedSubscript: "currentFlags" as NSString)
84
+ jsContext.setObject(nil, forKeyedSubscript: "filterFunctionString" as NSString)
85
+
86
+ // Convert result to boolean
87
+ return result.toBool()
88
+ }
89
+ }
90
+ }
91
+
92
+ // Create a ReplicationFilter from a JavaScript function string
93
+ private static func createFilter(from functionString: String?) -> ReplicationFilter? {
94
+ guard let functionString = functionString, !functionString.isEmpty else {
95
+ return nil
96
+ }
97
+
98
+ return { (document, flags) -> Bool in
99
+ return evaluateFilter(functionString, document: document, flags: flags)
100
+ }
101
+ }
13
102
 
14
103
  public static func replicatorConfigFromJson(_ data: [String: Any], collectionConfiguration: [CollectionConfigItem]) throws -> ReplicatorConfiguration {
15
104
  guard let target = data["target"] as? [String: Any],
@@ -22,7 +111,8 @@ public struct ReplicatorHelper {
22
111
  let autoPurgeEnabled = data["autoPurgeEnabled"] as? Bool,
23
112
  let heartbeat = data["heartbeat"] as? NSNumber,
24
113
  let maxAttempts = data["maxAttempts"] as? NSNumber,
25
- let maxAttemptWaitTime = data["maxAttemptWaitTime"] as? NSNumber
114
+ let maxAttemptWaitTime = data["maxAttemptWaitTime"] as? NSNumber,
115
+ let pinnedServerCertificate = data["pinnedServerCertificate"] as? String
26
116
  else {
27
117
  throw ReplicatorError.fatalError(message: "Invalid JSON data")
28
118
  }
@@ -31,12 +121,23 @@ public struct ReplicatorHelper {
31
121
 
32
122
  //set values from data
33
123
  var replConfig = ReplicatorConfiguration(target: endpoint)
34
- replConfig.acceptParentDomainCookie = acceptSelfSignedCerts
35
124
  replConfig.acceptParentDomainCookie = acceptParentDomainCookies
36
125
  replConfig.allowReplicatingInBackground = allowReplicationInBackground
126
+ replConfig.acceptOnlySelfSignedServerCertificate = acceptSelfSignedCerts
37
127
  replConfig.continuous = continuous
38
128
  replConfig.enableAutoPurge = autoPurgeEnabled
39
-
129
+
130
+ if !pinnedServerCertificate.isEmpty {
131
+ guard let certData = Data(base64Encoded: pinnedServerCertificate) else {
132
+ throw ReplicatorError.fatalError(message: "Invalid pinned server certificate")
133
+ }
134
+ guard let pinnedCert = SecCertificateCreateWithData(nil, certData as CFData) else {
135
+ throw ReplicatorError.fatalError(message: "Invalid pinned server certificate")
136
+ }
137
+
138
+ replConfig.pinnedServerCertificate = pinnedCert
139
+ }
140
+
40
141
  replConfig.heartbeat = TimeInterval(exactly: heartbeat.int64Value) ?? 300
41
142
  replConfig.maxAttemptWaitTime = TimeInterval(exactly: maxAttemptWaitTime.int64Value) ?? 0
42
143
  replConfig.maxAttempts = maxAttempts.uintValue
@@ -96,6 +197,16 @@ public struct ReplicatorHelper {
96
197
  if item.config.documentIds.count > 0 {
97
198
  collectionConfig.documentIDs = item.config.documentIds
98
199
  }
200
+
201
+ // Process push and pull filters
202
+ if let pushFilterStr = item.config.pushFilter, !pushFilterStr.isEmpty {
203
+ collectionConfig.pushFilter = createFilter(from: pushFilterStr)
204
+ }
205
+
206
+ if let pullFilterStr = item.config.pullFilter, !pullFilterStr.isEmpty {
207
+ collectionConfig.pullFilter = createFilter(from: pullFilterStr)
208
+ }
209
+
99
210
  replicationConfig.addCollections(collections, config: collectionConfig)
100
211
  }
101
212
  }
@@ -2,8 +2,6 @@
2
2
  // ReplicatorManager.swift
3
3
  // CbliteSwiftJsLib
4
4
  //
5
- // Created by Aaron LaBeau on 09/04/24.
6
- //
7
5
 
8
6
  import Foundation
9
7
  import CouchbaseLiteSwift