react-native-cloud-sync 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (268) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +360 -0
  3. package/app.plugin.js +3 -0
  4. package/ios/CloudSyncError.swift +144 -0
  5. package/ios/CloudSyncImpl.swift +1263 -0
  6. package/ios/RNCloudSync.h +25 -0
  7. package/ios/RNCloudSync.mm +477 -0
  8. package/jest-mock.js +136 -0
  9. package/lib/commonjs/config.js +85 -0
  10. package/lib/commonjs/config.js.map +1 -0
  11. package/lib/commonjs/errors.js +244 -0
  12. package/lib/commonjs/errors.js.map +1 -0
  13. package/lib/commonjs/hooks.js +257 -0
  14. package/lib/commonjs/hooks.js.map +1 -0
  15. package/lib/commonjs/index.js +244 -0
  16. package/lib/commonjs/index.js.map +1 -0
  17. package/lib/commonjs/internal/autoFlush.js +65 -0
  18. package/lib/commonjs/internal/autoFlush.js.map +1 -0
  19. package/lib/commonjs/internal/base64.js +58 -0
  20. package/lib/commonjs/internal/base64.js.map +1 -0
  21. package/lib/commonjs/internal/bytes.js +32 -0
  22. package/lib/commonjs/internal/bytes.js.map +1 -0
  23. package/lib/commonjs/internal/cloudKitRest.js +527 -0
  24. package/lib/commonjs/internal/cloudKitRest.js.map +1 -0
  25. package/lib/commonjs/internal/enums.js +23 -0
  26. package/lib/commonjs/internal/enums.js.map +1 -0
  27. package/lib/commonjs/internal/googleDriveRest.js +624 -0
  28. package/lib/commonjs/internal/googleDriveRest.js.map +1 -0
  29. package/lib/commonjs/internal/keys.js +139 -0
  30. package/lib/commonjs/internal/keys.js.map +1 -0
  31. package/lib/commonjs/internal/logger.js +29 -0
  32. package/lib/commonjs/internal/logger.js.map +1 -0
  33. package/lib/commonjs/internal/nativeModule.js +125 -0
  34. package/lib/commonjs/internal/nativeModule.js.map +1 -0
  35. package/lib/commonjs/internal/timeout.js +72 -0
  36. package/lib/commonjs/internal/timeout.js.map +1 -0
  37. package/lib/commonjs/package.json +1 -0
  38. package/lib/commonjs/providers/cloudKit.js +398 -0
  39. package/lib/commonjs/providers/cloudKit.js.map +1 -0
  40. package/lib/commonjs/providers/cloudKitBackup.js +86 -0
  41. package/lib/commonjs/providers/cloudKitBackup.js.map +1 -0
  42. package/lib/commonjs/providers/cloudKitEncrypted.js +150 -0
  43. package/lib/commonjs/providers/cloudKitEncrypted.js.map +1 -0
  44. package/lib/commonjs/providers/googleDrive.js +219 -0
  45. package/lib/commonjs/providers/googleDrive.js.map +1 -0
  46. package/lib/commonjs/providers/googleDriveFiles.js +68 -0
  47. package/lib/commonjs/providers/googleDriveFiles.js.map +1 -0
  48. package/lib/commonjs/providers/icloudDocuments.js +121 -0
  49. package/lib/commonjs/providers/icloudDocuments.js.map +1 -0
  50. package/lib/commonjs/providers/icloudKV.js +171 -0
  51. package/lib/commonjs/providers/icloudKV.js.map +1 -0
  52. package/lib/commonjs/providers/icloudKV.web.js +42 -0
  53. package/lib/commonjs/providers/icloudKV.web.js.map +1 -0
  54. package/lib/commonjs/providers/memory.js +201 -0
  55. package/lib/commonjs/providers/memory.js.map +1 -0
  56. package/lib/commonjs/resolvers.js +128 -0
  57. package/lib/commonjs/resolvers.js.map +1 -0
  58. package/lib/commonjs/specs/NativeRNCloudSync.js +14 -0
  59. package/lib/commonjs/specs/NativeRNCloudSync.js.map +1 -0
  60. package/lib/commonjs/store.js +1064 -0
  61. package/lib/commonjs/store.js.map +1 -0
  62. package/lib/commonjs/testing.js +32 -0
  63. package/lib/commonjs/testing.js.map +1 -0
  64. package/lib/commonjs/types.js +86 -0
  65. package/lib/commonjs/types.js.map +1 -0
  66. package/lib/module/config.js +72 -0
  67. package/lib/module/config.js.map +1 -0
  68. package/lib/module/errors.js +231 -0
  69. package/lib/module/errors.js.map +1 -0
  70. package/lib/module/hooks.js +250 -0
  71. package/lib/module/hooks.js.map +1 -0
  72. package/lib/module/index.js +46 -0
  73. package/lib/module/index.js.map +1 -0
  74. package/lib/module/internal/autoFlush.js +62 -0
  75. package/lib/module/internal/autoFlush.js.map +1 -0
  76. package/lib/module/internal/base64.js +53 -0
  77. package/lib/module/internal/base64.js.map +1 -0
  78. package/lib/module/internal/bytes.js +28 -0
  79. package/lib/module/internal/bytes.js.map +1 -0
  80. package/lib/module/internal/cloudKitRest.js +518 -0
  81. package/lib/module/internal/cloudKitRest.js.map +1 -0
  82. package/lib/module/internal/enums.js +18 -0
  83. package/lib/module/internal/enums.js.map +1 -0
  84. package/lib/module/internal/googleDriveRest.js +620 -0
  85. package/lib/module/internal/googleDriveRest.js.map +1 -0
  86. package/lib/module/internal/keys.js +134 -0
  87. package/lib/module/internal/keys.js.map +1 -0
  88. package/lib/module/internal/logger.js +23 -0
  89. package/lib/module/internal/logger.js.map +1 -0
  90. package/lib/module/internal/nativeModule.js +117 -0
  91. package/lib/module/internal/nativeModule.js.map +1 -0
  92. package/lib/module/internal/timeout.js +67 -0
  93. package/lib/module/internal/timeout.js.map +1 -0
  94. package/lib/module/package.json +1 -0
  95. package/lib/module/providers/cloudKit.js +392 -0
  96. package/lib/module/providers/cloudKit.js.map +1 -0
  97. package/lib/module/providers/cloudKitBackup.js +82 -0
  98. package/lib/module/providers/cloudKitBackup.js.map +1 -0
  99. package/lib/module/providers/cloudKitEncrypted.js +146 -0
  100. package/lib/module/providers/cloudKitEncrypted.js.map +1 -0
  101. package/lib/module/providers/googleDrive.js +214 -0
  102. package/lib/module/providers/googleDrive.js.map +1 -0
  103. package/lib/module/providers/googleDriveFiles.js +64 -0
  104. package/lib/module/providers/googleDriveFiles.js.map +1 -0
  105. package/lib/module/providers/icloudDocuments.js +117 -0
  106. package/lib/module/providers/icloudDocuments.js.map +1 -0
  107. package/lib/module/providers/icloudKV.js +165 -0
  108. package/lib/module/providers/icloudKV.js.map +1 -0
  109. package/lib/module/providers/icloudKV.web.js +36 -0
  110. package/lib/module/providers/icloudKV.web.js.map +1 -0
  111. package/lib/module/providers/memory.js +197 -0
  112. package/lib/module/providers/memory.js.map +1 -0
  113. package/lib/module/resolvers.js +120 -0
  114. package/lib/module/resolvers.js.map +1 -0
  115. package/lib/module/specs/NativeRNCloudSync.js +12 -0
  116. package/lib/module/specs/NativeRNCloudSync.js.map +1 -0
  117. package/lib/module/store.js +1061 -0
  118. package/lib/module/store.js.map +1 -0
  119. package/lib/module/testing.js +17 -0
  120. package/lib/module/testing.js.map +1 -0
  121. package/lib/module/types.js +82 -0
  122. package/lib/module/types.js.map +1 -0
  123. package/lib/typescript/commonjs/config.d.ts +33 -0
  124. package/lib/typescript/commonjs/config.d.ts.map +1 -0
  125. package/lib/typescript/commonjs/errors.d.ts +140 -0
  126. package/lib/typescript/commonjs/errors.d.ts.map +1 -0
  127. package/lib/typescript/commonjs/hooks.d.ts +109 -0
  128. package/lib/typescript/commonjs/hooks.d.ts.map +1 -0
  129. package/lib/typescript/commonjs/index.d.ts +37 -0
  130. package/lib/typescript/commonjs/index.d.ts.map +1 -0
  131. package/lib/typescript/commonjs/internal/autoFlush.d.ts +45 -0
  132. package/lib/typescript/commonjs/internal/autoFlush.d.ts.map +1 -0
  133. package/lib/typescript/commonjs/internal/base64.d.ts +12 -0
  134. package/lib/typescript/commonjs/internal/base64.d.ts.map +1 -0
  135. package/lib/typescript/commonjs/internal/bytes.d.ts +12 -0
  136. package/lib/typescript/commonjs/internal/bytes.d.ts.map +1 -0
  137. package/lib/typescript/commonjs/internal/cloudKitRest.d.ts +149 -0
  138. package/lib/typescript/commonjs/internal/cloudKitRest.d.ts.map +1 -0
  139. package/lib/typescript/commonjs/internal/enums.d.ts +10 -0
  140. package/lib/typescript/commonjs/internal/enums.d.ts.map +1 -0
  141. package/lib/typescript/commonjs/internal/googleDriveRest.d.ts +232 -0
  142. package/lib/typescript/commonjs/internal/googleDriveRest.d.ts.map +1 -0
  143. package/lib/typescript/commonjs/internal/keys.d.ts +28 -0
  144. package/lib/typescript/commonjs/internal/keys.d.ts.map +1 -0
  145. package/lib/typescript/commonjs/internal/logger.d.ts +10 -0
  146. package/lib/typescript/commonjs/internal/logger.d.ts.map +1 -0
  147. package/lib/typescript/commonjs/internal/nativeModule.d.ts +29 -0
  148. package/lib/typescript/commonjs/internal/nativeModule.d.ts.map +1 -0
  149. package/lib/typescript/commonjs/internal/timeout.d.ts +36 -0
  150. package/lib/typescript/commonjs/internal/timeout.d.ts.map +1 -0
  151. package/lib/typescript/commonjs/package.json +1 -0
  152. package/lib/typescript/commonjs/providers/cloudKit.d.ts +86 -0
  153. package/lib/typescript/commonjs/providers/cloudKit.d.ts.map +1 -0
  154. package/lib/typescript/commonjs/providers/cloudKitBackup.d.ts +65 -0
  155. package/lib/typescript/commonjs/providers/cloudKitBackup.d.ts.map +1 -0
  156. package/lib/typescript/commonjs/providers/cloudKitEncrypted.d.ts +37 -0
  157. package/lib/typescript/commonjs/providers/cloudKitEncrypted.d.ts.map +1 -0
  158. package/lib/typescript/commonjs/providers/googleDrive.d.ts +35 -0
  159. package/lib/typescript/commonjs/providers/googleDrive.d.ts.map +1 -0
  160. package/lib/typescript/commonjs/providers/googleDriveFiles.d.ts +59 -0
  161. package/lib/typescript/commonjs/providers/googleDriveFiles.d.ts.map +1 -0
  162. package/lib/typescript/commonjs/providers/icloudDocuments.d.ts +101 -0
  163. package/lib/typescript/commonjs/providers/icloudDocuments.d.ts.map +1 -0
  164. package/lib/typescript/commonjs/providers/icloudKV.d.ts +26 -0
  165. package/lib/typescript/commonjs/providers/icloudKV.d.ts.map +1 -0
  166. package/lib/typescript/commonjs/providers/icloudKV.web.d.ts +12 -0
  167. package/lib/typescript/commonjs/providers/icloudKV.web.d.ts.map +1 -0
  168. package/lib/typescript/commonjs/providers/memory.d.ts +90 -0
  169. package/lib/typescript/commonjs/providers/memory.d.ts.map +1 -0
  170. package/lib/typescript/commonjs/resolvers.d.ts +60 -0
  171. package/lib/typescript/commonjs/resolvers.d.ts.map +1 -0
  172. package/lib/typescript/commonjs/specs/NativeRNCloudSync.d.ts +133 -0
  173. package/lib/typescript/commonjs/specs/NativeRNCloudSync.d.ts.map +1 -0
  174. package/lib/typescript/commonjs/store.d.ts +118 -0
  175. package/lib/typescript/commonjs/store.d.ts.map +1 -0
  176. package/lib/typescript/commonjs/testing.d.ts +16 -0
  177. package/lib/typescript/commonjs/testing.d.ts.map +1 -0
  178. package/lib/typescript/commonjs/types.d.ts +367 -0
  179. package/lib/typescript/commonjs/types.d.ts.map +1 -0
  180. package/lib/typescript/module/config.d.ts +33 -0
  181. package/lib/typescript/module/config.d.ts.map +1 -0
  182. package/lib/typescript/module/errors.d.ts +140 -0
  183. package/lib/typescript/module/errors.d.ts.map +1 -0
  184. package/lib/typescript/module/hooks.d.ts +109 -0
  185. package/lib/typescript/module/hooks.d.ts.map +1 -0
  186. package/lib/typescript/module/index.d.ts +37 -0
  187. package/lib/typescript/module/index.d.ts.map +1 -0
  188. package/lib/typescript/module/internal/autoFlush.d.ts +45 -0
  189. package/lib/typescript/module/internal/autoFlush.d.ts.map +1 -0
  190. package/lib/typescript/module/internal/base64.d.ts +12 -0
  191. package/lib/typescript/module/internal/base64.d.ts.map +1 -0
  192. package/lib/typescript/module/internal/bytes.d.ts +12 -0
  193. package/lib/typescript/module/internal/bytes.d.ts.map +1 -0
  194. package/lib/typescript/module/internal/cloudKitRest.d.ts +149 -0
  195. package/lib/typescript/module/internal/cloudKitRest.d.ts.map +1 -0
  196. package/lib/typescript/module/internal/enums.d.ts +10 -0
  197. package/lib/typescript/module/internal/enums.d.ts.map +1 -0
  198. package/lib/typescript/module/internal/googleDriveRest.d.ts +232 -0
  199. package/lib/typescript/module/internal/googleDriveRest.d.ts.map +1 -0
  200. package/lib/typescript/module/internal/keys.d.ts +28 -0
  201. package/lib/typescript/module/internal/keys.d.ts.map +1 -0
  202. package/lib/typescript/module/internal/logger.d.ts +10 -0
  203. package/lib/typescript/module/internal/logger.d.ts.map +1 -0
  204. package/lib/typescript/module/internal/nativeModule.d.ts +29 -0
  205. package/lib/typescript/module/internal/nativeModule.d.ts.map +1 -0
  206. package/lib/typescript/module/internal/timeout.d.ts +36 -0
  207. package/lib/typescript/module/internal/timeout.d.ts.map +1 -0
  208. package/lib/typescript/module/package.json +1 -0
  209. package/lib/typescript/module/providers/cloudKit.d.ts +86 -0
  210. package/lib/typescript/module/providers/cloudKit.d.ts.map +1 -0
  211. package/lib/typescript/module/providers/cloudKitBackup.d.ts +65 -0
  212. package/lib/typescript/module/providers/cloudKitBackup.d.ts.map +1 -0
  213. package/lib/typescript/module/providers/cloudKitEncrypted.d.ts +37 -0
  214. package/lib/typescript/module/providers/cloudKitEncrypted.d.ts.map +1 -0
  215. package/lib/typescript/module/providers/googleDrive.d.ts +35 -0
  216. package/lib/typescript/module/providers/googleDrive.d.ts.map +1 -0
  217. package/lib/typescript/module/providers/googleDriveFiles.d.ts +59 -0
  218. package/lib/typescript/module/providers/googleDriveFiles.d.ts.map +1 -0
  219. package/lib/typescript/module/providers/icloudDocuments.d.ts +101 -0
  220. package/lib/typescript/module/providers/icloudDocuments.d.ts.map +1 -0
  221. package/lib/typescript/module/providers/icloudKV.d.ts +26 -0
  222. package/lib/typescript/module/providers/icloudKV.d.ts.map +1 -0
  223. package/lib/typescript/module/providers/icloudKV.web.d.ts +12 -0
  224. package/lib/typescript/module/providers/icloudKV.web.d.ts.map +1 -0
  225. package/lib/typescript/module/providers/memory.d.ts +90 -0
  226. package/lib/typescript/module/providers/memory.d.ts.map +1 -0
  227. package/lib/typescript/module/resolvers.d.ts +60 -0
  228. package/lib/typescript/module/resolvers.d.ts.map +1 -0
  229. package/lib/typescript/module/specs/NativeRNCloudSync.d.ts +133 -0
  230. package/lib/typescript/module/specs/NativeRNCloudSync.d.ts.map +1 -0
  231. package/lib/typescript/module/store.d.ts +118 -0
  232. package/lib/typescript/module/store.d.ts.map +1 -0
  233. package/lib/typescript/module/testing.d.ts +16 -0
  234. package/lib/typescript/module/testing.d.ts.map +1 -0
  235. package/lib/typescript/module/types.d.ts +367 -0
  236. package/lib/typescript/module/types.d.ts.map +1 -0
  237. package/package.json +186 -0
  238. package/plugin/build/index.d.ts +45 -0
  239. package/plugin/build/index.js +93 -0
  240. package/react-native-cloud-sync.podspec +48 -0
  241. package/src/config.ts +94 -0
  242. package/src/errors.ts +263 -0
  243. package/src/hooks.ts +337 -0
  244. package/src/index.ts +113 -0
  245. package/src/internal/autoFlush.ts +87 -0
  246. package/src/internal/base64.ts +63 -0
  247. package/src/internal/bytes.ts +28 -0
  248. package/src/internal/cloudKitRest.ts +654 -0
  249. package/src/internal/enums.ts +35 -0
  250. package/src/internal/googleDriveRest.ts +765 -0
  251. package/src/internal/keys.ts +160 -0
  252. package/src/internal/logger.ts +23 -0
  253. package/src/internal/nativeModule.ts +149 -0
  254. package/src/internal/timeout.ts +83 -0
  255. package/src/providers/cloudKit.ts +510 -0
  256. package/src/providers/cloudKitBackup.ts +124 -0
  257. package/src/providers/cloudKitEncrypted.ts +175 -0
  258. package/src/providers/googleDrive.ts +251 -0
  259. package/src/providers/googleDriveFiles.ts +117 -0
  260. package/src/providers/icloudDocuments.ts +175 -0
  261. package/src/providers/icloudKV.ts +206 -0
  262. package/src/providers/icloudKV.web.ts +41 -0
  263. package/src/providers/memory.ts +302 -0
  264. package/src/resolvers.ts +133 -0
  265. package/src/specs/NativeRNCloudSync.ts +184 -0
  266. package/src/store.ts +1288 -0
  267. package/src/testing.ts +22 -0
  268. package/src/types.ts +426 -0
@@ -0,0 +1,302 @@
1
+ import { CloudSyncError, ErrorCode } from '../errors'
2
+ import type {
3
+ AccountChangeEvent,
4
+ AccountStatus,
5
+ CloudProvider,
6
+ RemoteChangeEvent,
7
+ Unsubscribe,
8
+ } from '../types'
9
+
10
+ const NAME = 'memory' as const
11
+
12
+ export type FaultOp = 'getItem' | 'setItem' | 'removeItem' | 'getAllKeys' | 'getAccountStatus'
13
+
14
+ /** Epoch millis stamped on every write, so `getItemWithMeta` has something real to report. */
15
+ interface Entry {
16
+ value: string
17
+ modifiedAt: number
18
+ }
19
+
20
+ export interface Fault {
21
+ code: ErrorCode
22
+ message?: string
23
+ retryAfterMs?: number
24
+ limitBytes?: number
25
+ actualBytes?: number
26
+ serverValue?: string | null
27
+ /**
28
+ * Fail only this many times, then succeed. Useful for asserting that retry and
29
+ * outbox logic converges instead of looping.
30
+ */
31
+ times?: number
32
+ /**
33
+ * Fail only for keys this returns true for. Defaults to every key.
34
+ *
35
+ * Real backends fail per record, not per operation - one oversized or
36
+ * conflicting key while the rest of a batch goes through. Scoping a fault to
37
+ * a key is also what makes interleaving tests deterministic, since two
38
+ * operations in flight no longer compete for the same `times` budget.
39
+ */
40
+ only?: (key: string) => boolean
41
+ }
42
+
43
+ export interface MemoryProviderOptions {
44
+ /** Seed data the provider starts with. */
45
+ initial?: Record<string, string>
46
+ /** Per-operation failures to inject. */
47
+ faults?: Partial<Record<FaultOp, Fault>>
48
+ /** Account status reported by `getAccountStatus`. Defaults to `available`. */
49
+ accountStatus?: AccountStatus
50
+ /** Artificial delay in ms applied to every operation. */
51
+ latencyMs?: number
52
+ /**
53
+ * What `isAvailable()` reports. Defaults to true.
54
+ *
55
+ * Set false to reproduce the signed-out fleet - the case where the store must
56
+ * refuse to answer a read rather than resolving `null`, because `null` there
57
+ * reads as "no backup exists" and the documented first-launch recipe seeds
58
+ * empty state over the user's real data.
59
+ */
60
+ available?: boolean
61
+ /** A name other than `'memory'`, for tests that need two distinct doubles. */
62
+ name?: string
63
+ /** Quota reported by `getQuota()`. Omitted means the provider reports none. */
64
+ quota?: { usedBytes?: number; totalBytes?: number }
65
+ }
66
+
67
+ /** A provider name other than the four built in. Used to type custom doubles. */
68
+ export type MemoryProviderName = string
69
+
70
+ export interface MemoryProvider extends CloudProvider {
71
+ /** Direct read of the backing map, bypassing fault injection. */
72
+ dump: () => Record<string, string>
73
+ /** Replace the backing data without going through `setItem`. */
74
+ seed: (data: Record<string, string>) => void
75
+ /** Clear data, faults and listeners. */
76
+ reset: () => void
77
+ /** Install or replace a fault at runtime. */
78
+ setFault: (op: FaultOp, fault: Fault | null) => void
79
+ /** Fire a remote-change event, as if another device had written. */
80
+ emitRemoteChange: (e: Partial<RemoteChangeEvent>) => void
81
+ /** Fire an account-change event, including the identity-switch case. */
82
+ emitAccountChange: (e: Partial<AccountChangeEvent>) => void
83
+ /** Flip what `isAvailable()` reports, to simulate signing out mid-session. */
84
+ setAvailable: (value: boolean) => void
85
+ /** How many times each operation has been called. */
86
+ readonly calls: Readonly<Record<FaultOp, number>>
87
+ /** How many times the store asked this provider to drop cached state. */
88
+ readonly cacheClears: number
89
+ }
90
+
91
+ /**
92
+ * An in-memory provider with fault injection.
93
+ *
94
+ * This exists because cloud storage is the hardest thing in a mobile app to test
95
+ * honestly. iCloud on the simulator is unreliable enough that the most-used
96
+ * library in this space gave up on it publicly - "We've therefore stopped
97
+ * testing the library on the simulator and test on a real device only and would
98
+ * encourage users to do the same." Real-device-only testing means the failure
99
+ * paths that matter most (signed out, offline, quota exceeded, rate limited,
100
+ * account switched mid-session) are effectively never exercised.
101
+ *
102
+ * So they are exercised here instead, deterministically, in Jest. This is
103
+ * exported from the package entry (`react-native-cloud-sync/testing`)
104
+ * rather than buried in source, so it is usable without reaching into internals.
105
+ */
106
+ export function createMemoryProvider(options: MemoryProviderOptions = {}): MemoryProvider {
107
+ const NAME_FOR_THIS = options.name ?? NAME
108
+
109
+ function seedEntries(record: Record<string, string>): Map<string, Entry> {
110
+ const now = Date.now()
111
+ return new Map(Object.entries(record).map(([k, v]) => [k, { value: v, modifiedAt: now }]))
112
+ }
113
+
114
+ let data = seedEntries(options.initial ?? {})
115
+ let faults: Partial<Record<FaultOp, Fault>> = { ...options.faults }
116
+ let accountStatus: AccountStatus = options.accountStatus ?? 'available'
117
+ let available = options.available ?? true
118
+ let cacheClears = 0
119
+ const latencyMs = options.latencyMs ?? 0
120
+
121
+ const remoteListeners = new Set<(e: RemoteChangeEvent) => void>()
122
+ const accountListeners = new Set<(e: AccountChangeEvent) => void>()
123
+
124
+ const calls: Record<FaultOp, number> = {
125
+ getItem: 0,
126
+ setItem: 0,
127
+ removeItem: 0,
128
+ getAllKeys: 0,
129
+ getAccountStatus: 0,
130
+ }
131
+
132
+ const remaining = new Map<FaultOp, number>()
133
+
134
+ /**
135
+ * `keys` is what the operation touches, so a fault can be scoped to one of
136
+ * them. A batch fails if the fault matches any key in it, matching how a real
137
+ * backend rejects a whole atomic batch for one bad record.
138
+ */
139
+ async function gate(op: FaultOp, keys: string[] = []): Promise<void> {
140
+ calls[op] += 1
141
+
142
+ if (latencyMs > 0) await new Promise(r => setTimeout(r, latencyMs))
143
+
144
+ const fault = faults[op]
145
+ if (fault == null) return
146
+ if (fault.only != null && !keys.some(k => fault.only!(k))) return
147
+
148
+ if (fault.times != null) {
149
+ const left = remaining.get(op) ?? fault.times
150
+ if (left <= 0) return
151
+ remaining.set(op, left - 1)
152
+ }
153
+
154
+ throw new CloudSyncError(
155
+ fault.code,
156
+ fault.message ?? `[RNCloudSync] Injected ${fault.code} on ${op}`,
157
+ {
158
+ provider: NAME_FOR_THIS,
159
+ retryAfterMs: fault.retryAfterMs,
160
+ limitBytes: fault.limitBytes,
161
+ actualBytes: fault.actualBytes,
162
+ serverValue: fault.serverValue,
163
+ }
164
+ )
165
+ }
166
+
167
+ return {
168
+ name: NAME_FOR_THIS,
169
+
170
+ isAvailable: () => Promise.resolve(available),
171
+
172
+ getAccountStatus: async () => {
173
+ await gate('getAccountStatus')
174
+ return accountStatus
175
+ },
176
+
177
+ getItem: async (key: string) => {
178
+ await gate('getItem', [key])
179
+ return data.get(key)?.value ?? null
180
+ },
181
+
182
+ // Implemented so the store's metadata-aware read path, and the resolver
183
+ // that orders on server time rather than on a timestamp the app embedded,
184
+ // are exercised by something other than a network provider.
185
+ getItemWithMeta: async (key: string) => {
186
+ await gate('getItem', [key])
187
+ const entry = data.get(key)
188
+ return entry == null ? null : { value: entry.value, modifiedAt: entry.modifiedAt }
189
+ },
190
+
191
+ setItem: async (key: string, value: string) => {
192
+ await gate('setItem', [key])
193
+ data.set(key, { value, modifiedAt: Date.now() })
194
+ },
195
+
196
+ removeItem: async (key: string) => {
197
+ await gate('removeItem', [key])
198
+ data.delete(key)
199
+ },
200
+
201
+ getAllKeys: async () => {
202
+ await gate('getAllKeys')
203
+ return [...data.keys()]
204
+ },
205
+
206
+ // One `gate` call per batch, not per key - so a test can assert that the
207
+ // store really batched instead of looping.
208
+ multiGet: async (keys: string[]) => {
209
+ await gate('getItem', keys)
210
+ return keys.map(k => data.get(k)?.value ?? null)
211
+ },
212
+
213
+ multiSet: async (entries: [string, string][]) => {
214
+ await gate('setItem', entries.map(([k]) => k))
215
+ const now = Date.now()
216
+ for (const [key, value] of entries) data.set(key, { value, modifiedAt: now })
217
+ },
218
+
219
+ multiRemove: async (keys: string[]) => {
220
+ await gate('removeItem', keys)
221
+ for (const key of keys) data.delete(key)
222
+ },
223
+
224
+ getQuota: () =>
225
+ Promise.resolve(
226
+ options.quota == null
227
+ ? null
228
+ : { ...options.quota, provider: NAME_FOR_THIS }
229
+ ),
230
+
231
+ clearCaches: () => {
232
+ cacheClears += 1
233
+ },
234
+
235
+ onRemoteChange: (listener): Unsubscribe => {
236
+ remoteListeners.add(listener)
237
+ return () => remoteListeners.delete(listener)
238
+ },
239
+
240
+ onAccountChange: (listener): Unsubscribe => {
241
+ accountListeners.add(listener)
242
+ return () => accountListeners.delete(listener)
243
+ },
244
+
245
+ dump: () => Object.fromEntries([...data].map(([k, e]) => [k, e.value])),
246
+
247
+ seed: (next: Record<string, string>) => {
248
+ data = seedEntries(next)
249
+ },
250
+
251
+ reset: () => {
252
+ data = new Map()
253
+ faults = {}
254
+ remaining.clear()
255
+ remoteListeners.clear()
256
+ accountListeners.clear()
257
+ accountStatus = 'available'
258
+ available = options.available ?? true
259
+ cacheClears = 0
260
+ for (const k of Object.keys(calls) as FaultOp[]) calls[k] = 0
261
+ },
262
+
263
+ setAvailable: (value: boolean) => {
264
+ available = value
265
+ },
266
+
267
+ setFault: (op: FaultOp, fault: Fault | null) => {
268
+ if (fault == null) {
269
+ delete faults[op]
270
+ remaining.delete(op)
271
+ return
272
+ }
273
+ faults[op] = fault
274
+ remaining.delete(op)
275
+ },
276
+
277
+ emitRemoteChange: (e) => {
278
+ const event: RemoteChangeEvent = {
279
+ keys: e.keys ?? [],
280
+ reason: e.reason ?? 'serverChange',
281
+ provider: NAME_FOR_THIS,
282
+ }
283
+ for (const l of remoteListeners) l(event)
284
+ },
285
+
286
+ emitAccountChange: (e) => {
287
+ if (e.status != null) accountStatus = e.status
288
+ const event: AccountChangeEvent = {
289
+ status: e.status ?? accountStatus,
290
+ identityChanged: e.identityChanged ?? false,
291
+ provider: NAME_FOR_THIS,
292
+ }
293
+ for (const l of accountListeners) l(event)
294
+ },
295
+
296
+ calls,
297
+
298
+ get cacheClears() {
299
+ return cacheClears
300
+ },
301
+ }
302
+ }
@@ -0,0 +1,133 @@
1
+ import type { ResolveCandidate, ResolveFn } from './types'
2
+
3
+ /**
4
+ * Resolves by a numeric timestamp inside a JSON value.
5
+ *
6
+ * The common shape by far: values are JSON objects carrying `updatedAt` (or
7
+ * similar), and the newest wins. Candidates that are not JSON, or that lack the
8
+ * field, lose to any that have it - a value you cannot date is not evidence
9
+ * against one you can.
10
+ *
11
+ * ```ts
12
+ * createCloudStore({
13
+ * providers: ['icloudKV', 'googleDrive'],
14
+ * writeMode: 'mirror',
15
+ * resolve: resolveByTimestamp('updatedAt'),
16
+ * })
17
+ * ```
18
+ */
19
+ export function resolveByTimestamp(field = 'updatedAt'): ResolveFn {
20
+ return (candidates: ResolveCandidate[]): string | null => {
21
+ if (candidates.length === 0) return null
22
+
23
+ let best: ResolveCandidate | null = null
24
+ let bestAt = Number.NEGATIVE_INFINITY
25
+
26
+ for (const candidate of candidates) {
27
+ const at = timestampOf(candidate.value, field)
28
+ // Strictly greater, so an earlier provider wins a tie - which keeps the
29
+ // result stable rather than flapping between equal copies.
30
+ if (at > bestAt) {
31
+ best = candidate
32
+ bestAt = at
33
+ }
34
+ }
35
+
36
+ // Nothing was datable: fall back to preference order rather than guessing.
37
+ if (best == null) return candidates[0].value
38
+ return best.value
39
+ }
40
+ }
41
+
42
+ function timestampOf(value: string, field: string): number {
43
+ try {
44
+ const parsed: unknown = JSON.parse(value)
45
+ if (parsed == null || typeof parsed !== 'object') return Number.NEGATIVE_INFINITY
46
+ const raw = (parsed as Record<string, unknown>)[field]
47
+ if (typeof raw === 'number' && Number.isFinite(raw)) return raw
48
+ // ISO strings are just as common as epoch millis.
49
+ if (typeof raw === 'string') {
50
+ const parsedDate = Date.parse(raw)
51
+ if (!Number.isNaN(parsedDate)) return parsedDate
52
+ }
53
+ return Number.NEGATIVE_INFINITY
54
+ }
55
+ catch {
56
+ return Number.NEGATIVE_INFINITY
57
+ }
58
+ }
59
+
60
+ /** Always takes the first provider that has a value. The default behaviour. */
61
+ export const resolveByPreferenceOrder: ResolveFn = candidates =>
62
+ candidates.length > 0 ? candidates[0].value : null
63
+
64
+ /**
65
+ * Resolves by the *server's* last-modified time rather than a timestamp inside
66
+ * the value.
67
+ *
68
+ * {@link resolveByTimestamp} requires every value to be JSON carrying a field
69
+ * the app remembered to update - a real constraint, and one that silently fails
70
+ * open the day someone writes a plain string or forgets to bump `updatedAt`.
71
+ * Both CloudKit (`modified.timestamp`) and Drive (`modifiedTime`) already
72
+ * report a modification time, one query parameter away, so this orders on that
73
+ * instead and works on payloads the app never had to instrument.
74
+ *
75
+ * The catch, and the reason this is not the default: `NSUbiquitousKeyValueStore`
76
+ * exposes no per-key timestamp at all, so an `icloudKV` candidate never carries
77
+ * one. Pass `fallback` to say what should happen then - by default an undated
78
+ * candidate loses to any dated one, and preference order breaks a tie among
79
+ * undated ones.
80
+ *
81
+ * ```ts
82
+ * createCloudStore({
83
+ * providers: ['cloudKit', 'googleDrive'], // both report server time
84
+ * writeMode: 'mirror',
85
+ * resolve: resolveByModifiedAt(),
86
+ * })
87
+ * ```
88
+ */
89
+ export function resolveByModifiedAt(
90
+ options: { fallback?: ResolveFn } = {}
91
+ ): ResolveFn {
92
+ const fallback = options.fallback ?? resolveByPreferenceOrder
93
+
94
+ return (candidates: ResolveCandidate[]): string | null => {
95
+ if (candidates.length === 0) return null
96
+
97
+ const dated = candidates.filter(
98
+ (c): c is ResolveCandidate & { modifiedAt: number } =>
99
+ typeof c.modifiedAt === 'number' && Number.isFinite(c.modifiedAt)
100
+ )
101
+
102
+ // Nothing reported a server time - every candidate came from a provider
103
+ // that does not track one. Guessing here would be worse than deferring.
104
+ if (dated.length === 0) return fallback(candidates)
105
+
106
+ let best = dated[0]
107
+ // Strictly greater, so an earlier provider wins a tie and the result stays
108
+ // stable rather than flapping between equal copies.
109
+ for (const candidate of dated) if (candidate.modifiedAt > best.modifiedAt) best = candidate
110
+
111
+ return best.value
112
+ }
113
+ }
114
+
115
+ /**
116
+ * Tries each resolver in turn and takes the first non-null answer.
117
+ *
118
+ * The practical combination for a mixed fleet: server time where the provider
119
+ * reports it, an embedded timestamp where it does not.
120
+ *
121
+ * ```ts
122
+ * resolveFirstOf(resolveByModifiedAt(), resolveByTimestamp('updatedAt'))
123
+ * ```
124
+ */
125
+ export function resolveFirstOf(...resolvers: ResolveFn[]): ResolveFn {
126
+ return (candidates: ResolveCandidate[]): string | null => {
127
+ for (const resolve of resolvers) {
128
+ const answer = resolve(candidates)
129
+ if (answer != null) return answer
130
+ }
131
+ return null
132
+ }
133
+ }
@@ -0,0 +1,184 @@
1
+ import type { TurboModule } from 'react-native'
2
+ import { TurboModuleRegistry } from 'react-native'
3
+ import type { EventEmitter } from 'react-native/Libraries/Types/CodegenTypes'
4
+
5
+ /**
6
+ * Codegen cannot express an index signature, so dynamic dictionaries cross the
7
+ * bridge as `UnsafeObject`. Same workaround react-native-background-downloader
8
+ * uses for its header maps.
9
+ */
10
+ export type UnsafeObject = { [key: string]: string }
11
+
12
+ export type RemoteChangeNativeEvent = {
13
+ keys: string[]
14
+ /** One of ChangeReason. Kept as a plain string - codegen has no string unions. */
15
+ reason: string
16
+ provider: string
17
+ }
18
+
19
+ export type AccountChangeNativeEvent = {
20
+ /** One of AccountStatus. */
21
+ status: string
22
+ identityChanged: boolean
23
+ provider: string
24
+ }
25
+
26
+ export type DocumentEntryNativeEvent = {
27
+ name: string
28
+ sizeBytes: number
29
+ /** False when the file exists in the account but has no local copy yet. */
30
+ isDownloaded: boolean
31
+ isDownloading: boolean
32
+ }
33
+
34
+ export type AssetProgressNativeEvent = {
35
+ recordName: string
36
+ fieldName: string
37
+ bytesTransferred: number
38
+ bytesTotal: number
39
+ }
40
+
41
+ export interface Spec extends TurboModule {
42
+ getConstants: () => {
43
+ /** The iCloud container id resolved from entitlements, or '' if unset. */
44
+ containerIdentifier: string
45
+ /** True when the build carries an iCloud entitlement at all. */
46
+ hasICloudEntitlement: boolean
47
+ }
48
+
49
+ // ---------------------------------------------------------------- account
50
+
51
+ getAccountStatus: () => Promise<string>
52
+ isAvailable: () => Promise<boolean>
53
+
54
+ // ------------------------------------------- iCloud key-value store (KVS)
55
+
56
+ kvGetItem: (key: string) => Promise<string | null>
57
+ kvSetItem: (key: string, value: string) => Promise<void>
58
+ kvRemoveItem: (key: string) => Promise<void>
59
+ kvGetAllKeys: () => Promise<string[]>
60
+ /**
61
+ * Every key and value at once - one bridge hop where `kvGetAllKeys` plus N
62
+ * `kvGetItem` calls would be N+1. Non-string values are omitted rather than
63
+ * coerced, since a stringified number would not round-trip through
64
+ * `kvSetItem`.
65
+ */
66
+ kvGetAllItems: () => Promise<UnsafeObject>
67
+ /**
68
+ * Flushes pending KV changes to disk.
69
+ *
70
+ * Note this is `NSUbiquitousKeyValueStore.synchronize()`, which despite the
71
+ * name does NOT confirm a server round trip - it only schedules the upload.
72
+ * Callers must not treat a resolved `kvSync()` as "the cloud has my data".
73
+ */
74
+ kvSync: () => Promise<boolean>
75
+
76
+ /**
77
+ * How full the key-value store is, against Apple's documented ceilings.
78
+ *
79
+ * Measured from `dictionaryRepresentation` (a local plist, not a network
80
+ * call) because Apple exposes no usage API. Without it an app can only learn
81
+ * it is near the 1 MB *total* by exceeding it, and exceeding it is silent.
82
+ */
83
+ kvGetUsage: () => Promise<{
84
+ usedBytes: number
85
+ totalBytes: number
86
+ keyCount: number
87
+ maxKeys: number
88
+ }>
89
+
90
+ // ------------------------------------------------------------- CloudKit
91
+
92
+ /**
93
+ * `encrypted` reads the value out of `CKRecord.encryptedValues` rather than
94
+ * the plain field. A field is one or the other, never both - CloudKit records
95
+ * encryption in the schema - so reading the wrong side returns null, which is
96
+ * indistinguishable from a missing record.
97
+ */
98
+ ckGetRecord: (
99
+ recordType: string,
100
+ recordName: string,
101
+ zoneName: string | null,
102
+ encrypted: boolean
103
+ ) => Promise<string | null>
104
+ /**
105
+ * `encrypted` writes through `CKRecord.encryptedValues`, so CloudKit
106
+ * end-to-end encrypts the value with a key from the user's iCloud Keychain.
107
+ * Nothing server-side can read it back - including CloudKit Web Services, and
108
+ * therefore this package's Android and web paths.
109
+ */
110
+ ckSaveRecord: (
111
+ recordType: string,
112
+ recordName: string,
113
+ value: string,
114
+ zoneName: string | null,
115
+ encrypted: boolean
116
+ ) => Promise<void>
117
+ ckDeleteRecord: (recordName: string, zoneName: string | null) => Promise<boolean>
118
+ ckQueryRecordNames: (recordType: string, zoneName: string | null) => Promise<string[]>
119
+
120
+ ckCreateZone: (zoneName: string) => Promise<void>
121
+ ckDeleteZone: (zoneName: string) => Promise<void>
122
+ ckListZones: () => Promise<string[]>
123
+
124
+ /** Uploads a local file as a CKAsset field. Emits `onAssetProgress` while running. */
125
+ ckSaveAsset: (
126
+ recordType: string,
127
+ recordName: string,
128
+ fieldName: string,
129
+ fileUri: string,
130
+ zoneName: string | null
131
+ ) => Promise<void>
132
+ /**
133
+ * Downloads a CKAsset field. Emits `onAssetProgress` while running.
134
+ *
135
+ * `destinationUri` is where the bytes land; null picks a temporary path.
136
+ * Worth passing for anything the user keeps or hands to a share sheet - the
137
+ * default is in `NSTemporaryDirectory`, which iOS may reclaim.
138
+ */
139
+ ckFetchAsset: (
140
+ recordName: string,
141
+ fieldName: string,
142
+ zoneName: string | null,
143
+ destinationUri: string | null
144
+ ) => Promise<string | null>
145
+ /**
146
+ * Cancels an in-flight asset transfer. Resolves true when there was one.
147
+ *
148
+ * The cancelled call's own promise rejects with `ERR_CANCELLED` - CloudKit
149
+ * reports the cancellation as `CKError.operationCancelled`, which the error
150
+ * mapper already recognises.
151
+ */
152
+ ckCancelAsset: (recordName: string, fieldName: string) => Promise<boolean>
153
+
154
+ // ------------------------------------------------- iCloud Drive documents
155
+
156
+ /** Whether a usable iCloud Drive container exists on this device right now. */
157
+ docIsAvailable: () => Promise<boolean>
158
+ /** Copies a local file into iCloud Drive under `name`. Resolves its iCloud path. */
159
+ docSave: (fileUri: string, name: string) => Promise<string>
160
+ /**
161
+ * Ensures `name` has been downloaded and resolves a local path, or null when
162
+ * no such file exists. Copies out to `destinationUri` when one is given.
163
+ */
164
+ docFetch: (
165
+ name: string,
166
+ destinationUri: string | null,
167
+ timeoutMs: number
168
+ ) => Promise<string | null>
169
+ docList: () => Promise<DocumentEntryNativeEvent[]>
170
+ /** Resolves true when something was deleted, false when it was already gone. */
171
+ docRemove: (name: string) => Promise<boolean>
172
+
173
+ // --------------------------------------------------------------- events
174
+
175
+ readonly onRemoteChange: EventEmitter<RemoteChangeNativeEvent>
176
+ readonly onAccountChange: EventEmitter<AccountChangeNativeEvent>
177
+ readonly onAssetProgress: EventEmitter<AssetProgressNativeEvent>
178
+
179
+ // -------------------------------------------------------------- tooling
180
+
181
+ setLogsEnabled: (enabled: boolean) => void
182
+ }
183
+
184
+ export default TurboModuleRegistry.get<Spec>('RNCloudSync')