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,654 @@
1
+ import { CloudSyncError, ErrorCode } from '../errors'
2
+ import { byteLength } from './bytes'
3
+ import { withTimeout } from './timeout'
4
+
5
+ /** Default request timeout. Generous, because a large record on a slow link is normal. */
6
+ const DEFAULT_TIMEOUT_MS = 30_000
7
+
8
+ /**
9
+ * CloudKit Web Services REST client.
10
+ *
11
+ * This is how the `cloudKit` provider reaches a user's PRIVATE database from
12
+ * Android and from the browser, where `CloudKit.framework` does not exist.
13
+ *
14
+ * Why an interactive user token and not a server key: Apple is explicit that a
15
+ * server-to-server key reaches only the *public* database - "Use a
16
+ * server-to-server key to access the public database of a container as the
17
+ * developer who created the key." Sign in with Apple cannot substitute either;
18
+ * per Apple DTS, "The unique user identifiers for Sign in with Apple and
19
+ * CloudKit are not linked." So an interactive `ckWebAuthToken` is not a shortcut
20
+ * this package chose - it is the only mechanism that exists.
21
+ *
22
+ * Deliberately no dependency on CloudKit JS. That library pulls Node's `crypto`
23
+ * for server-to-server signing, which is what killed the last React Native
24
+ * attempt at this (KjellConnelly/react-native-cloudkit pinned v1 because "2.0
25
+ * requires crypto which ... doesn't work with React Native"). The REST API in
26
+ * user-token mode needs no crypto at all: two query parameters on a `fetch`.
27
+ */
28
+
29
+ export interface CloudKitRestConfig {
30
+ /** e.g. `iCloud.com.example.app`. Must match the app's entitlement exactly. */
31
+ containerIdentifier: string
32
+ /**
33
+ * A CloudKit Console **Client** API token, not a server-to-server key.
34
+ *
35
+ * A client token grants only what the authenticated user could already do, so
36
+ * it is safe to ship in an app binary. A server-to-server private key is not.
37
+ */
38
+ apiToken: string
39
+ environment: 'development' | 'production'
40
+ /** Returns the stored `ckWebAuthToken`, or null when the user has not signed in. */
41
+ getAuthToken: () => Promise<string | null> | string | null
42
+ /**
43
+ * Called when CloudKit reports the token is no longer usable, so the host can
44
+ * clear it and prompt for re-auth.
45
+ *
46
+ * This fires more often than you might expect: a `ckWebAuthToken` expires
47
+ * after 30 minutes, or 2 weeks if the user ticked "Keep me signed in" during
48
+ * sign-in. Apple documents no refresh mechanism.
49
+ */
50
+ onAuthExpired?: () => Promise<void> | void
51
+ /** Overridable for tests. Defaults to global `fetch`. */
52
+ fetchImpl?: typeof fetch
53
+ /**
54
+ * Abandon a request that has not answered in this long. Default 30000.
55
+ *
56
+ * React Native's `fetch` has no timeout of its own, so without this a socket
57
+ * that never answers hangs the operation forever - and `isReachable()` is on
58
+ * the path of every read, so one hung probe stalls the whole store.
59
+ */
60
+ timeoutMs?: number
61
+ }
62
+
63
+ /**
64
+ * How many operations one `/records/modify` or `/records/lookup` call carries.
65
+ *
66
+ * Apple does not publish a hard maximum, but very large batches are rejected
67
+ * outright and a batch is atomic, so an oversized one fails as a unit. 200
68
+ * matches the page size CloudKit itself uses for query results.
69
+ */
70
+ const MAX_BATCH = 200
71
+
72
+ export const RECORD_TYPE_DEFAULT = 'KVBlob'
73
+ export const VALUE_FIELD = 'value'
74
+
75
+ /** CloudKit's documented per-record ceiling, excluding assets. */
76
+ export const MAX_RECORD_BYTES = 1024 * 1024
77
+
78
+ interface CloudKitRecordResult {
79
+ recordName?: string
80
+ fields?: Record<string, { value?: unknown }>
81
+ serverErrorCode?: string
82
+ reason?: string
83
+ retryAfter?: number
84
+ serverRecord?: { fields?: Record<string, { value?: unknown }>; recordChangeTag?: string }
85
+ /** Epoch millis. CloudKit returns this on every lookup without being asked. */
86
+ modified?: { timestamp?: number }
87
+ /**
88
+ * The record's version. Passing it back on a save turns a blind overwrite
89
+ * into a conditional one - see {@link CloudKitRestClient.saveRecord}.
90
+ */
91
+ recordChangeTag?: string
92
+ }
93
+
94
+ interface CloudKitResponse {
95
+ records?: CloudKitRecordResult[]
96
+ zones?: { zoneID?: { zoneName?: string } }[]
97
+ /**
98
+ * Top-level error fields. Critically, an `AUTHENTICATION_REQUIRED` response is
99
+ * HTTP 421 carrying these at the ROOT with **no `records` array** - so any
100
+ * check that looks for the error inside `records` can never fire. cryptoc's
101
+ * implementation had exactly that bug: its auth handling was unreachable, so
102
+ * an expired token was never cleared and every read and write silently
103
+ * no-opped forever.
104
+ */
105
+ serverErrorCode?: string
106
+ reason?: string
107
+ retryAfter?: number
108
+ redirectURL?: string
109
+ /** Set when a query has more results than one response can carry. */
110
+ continuationMarker?: string
111
+ }
112
+
113
+ /**
114
+ * CloudKit codes that all mean "the record is already there".
115
+ *
116
+ * `ATOMIC_ERROR` is included because an atomic batch reports a failed operation
117
+ * at the top level rather than per record.
118
+ */
119
+ const EXISTS_CODES = new Set(['EXISTS', 'CONFLICT', 'ATOMIC_ERROR'])
120
+
121
+ function isAlreadyExists(e: unknown): boolean {
122
+ if (!(e instanceof CloudSyncError)) return false
123
+ if (e.serverErrorCode != null) return EXISTS_CODES.has(e.serverErrorCode)
124
+ return e.code === ErrorCode.CONFLICT
125
+ }
126
+
127
+ /** How long a reachability answer is reused. See {@link CloudKitRestClient.isReachable}. */
128
+ const REACHABILITY_TTL_MS = 30_000
129
+
130
+ /** Record name used only to prove the container is reachable and authenticated. */
131
+ const AVAILABILITY_PROBE_RECORD = '__rncs_availability_probe__'
132
+
133
+ export class CloudKitRestClient {
134
+ private readonly config: CloudKitRestConfig
135
+ private reachability: { at: number; ok: boolean } | null = null
136
+
137
+ constructor(config: CloudKitRestConfig) {
138
+ this.config = config
139
+ }
140
+
141
+ private baseUrl(): string {
142
+ const { containerIdentifier, environment } = this.config
143
+ return `https://api.apple-cloudkit.com/database/1/${containerIdentifier}/${environment}/private`
144
+ }
145
+
146
+ private get fetch(): typeof fetch {
147
+ return this.config.fetchImpl ?? globalThis.fetch
148
+ }
149
+
150
+ private async requireAuthToken(): Promise<string> {
151
+ if (!this.config.apiToken)
152
+ throw new CloudSyncError(
153
+ ErrorCode.CONTAINER_MISCONFIGURED,
154
+ '[RNCloudSync] No CloudKit API token configured. Create a Client token in the '
155
+ + 'CloudKit Console under API Access and pass it to configureCloudKit().',
156
+ { provider: 'cloudKit' }
157
+ )
158
+
159
+ const token = await this.config.getAuthToken()
160
+ if (!token)
161
+ throw new CloudSyncError(
162
+ ErrorCode.NOT_SIGNED_IN,
163
+ '[RNCloudSync] No CloudKit web auth token. The user must sign in with their '
164
+ + 'Apple ID before the private database can be reached.',
165
+ { provider: 'cloudKit' }
166
+ )
167
+
168
+ return token
169
+ }
170
+
171
+ private async handleAuthExpired(): Promise<void> {
172
+ await this.config.onAuthExpired?.()
173
+ }
174
+
175
+ /**
176
+ * Maps a CloudKit `serverErrorCode` onto the package's shared vocabulary.
177
+ * Codes are from Apple's CloudKit Web Services error reference.
178
+ */
179
+ private async toError(
180
+ code: string | undefined,
181
+ reason: string | undefined,
182
+ retryAfter: number | undefined,
183
+ serverValue?: string | null
184
+ ): Promise<CloudSyncError> {
185
+ const message = `[RNCloudSync] CloudKit: ${code ?? 'unknown'}${reason ? ` - ${reason}` : ''}`
186
+ const provider = 'cloudKit'
187
+ const base = { provider, serverErrorCode: code }
188
+
189
+ switch (code) {
190
+ case 'AUTHENTICATION_REQUIRED':
191
+ case 'AUTHENTICATION_FAILED':
192
+ await this.handleAuthExpired()
193
+ return new CloudSyncError(ErrorCode.AUTH_EXPIRED, message, base)
194
+ case 'ACCESS_DENIED':
195
+ await this.handleAuthExpired()
196
+ return new CloudSyncError(ErrorCode.AUTH_EXPIRED, message, base)
197
+ case 'QUOTA_EXCEEDED':
198
+ return new CloudSyncError(ErrorCode.QUOTA_EXCEEDED, message, base)
199
+ case 'THROTTLED':
200
+ case 'TRY_AGAIN_LATER':
201
+ return new CloudSyncError(ErrorCode.RATE_LIMITED, message, {
202
+ ...base,
203
+ retryAfterMs: retryAfter != null ? retryAfter * 1000 : undefined,
204
+ })
205
+ case 'CONFLICT':
206
+ return new CloudSyncError(ErrorCode.CONFLICT, message, { ...base, serverValue })
207
+ case 'BAD_REQUEST':
208
+ case 'ZONE_NOT_FOUND':
209
+ return new CloudSyncError(ErrorCode.CONTAINER_MISCONFIGURED, message, base)
210
+ default:
211
+ return new CloudSyncError(ErrorCode.UNKNOWN, message, base)
212
+ }
213
+ }
214
+
215
+ private async post(path: string, body: unknown): Promise<CloudKitResponse> {
216
+ const token = await this.requireAuthToken()
217
+ const url
218
+ = `${this.baseUrl()}${path}`
219
+ + `?ckAPIToken=${encodeURIComponent(this.config.apiToken)}`
220
+ + `&ckWebAuthToken=${encodeURIComponent(token)}`
221
+
222
+ let res: Response
223
+ try {
224
+ res = await withTimeout(
225
+ this.fetch(url, {
226
+ method: 'POST',
227
+ headers: { 'Content-Type': 'application/json' },
228
+ body: JSON.stringify(body),
229
+ }),
230
+ this.config.timeoutMs ?? DEFAULT_TIMEOUT_MS,
231
+ 'cloudKit'
232
+ )
233
+ }
234
+ catch (e) {
235
+ // A timeout is already a classified, retryable CloudSyncError; re-wrapping
236
+ // it as a network failure would throw away the distinction.
237
+ if (e instanceof CloudSyncError) throw e
238
+ throw new CloudSyncError(
239
+ ErrorCode.NETWORK_UNAVAILABLE,
240
+ '[RNCloudSync] CloudKit request failed to reach the server.',
241
+ { provider: 'cloudKit', cause: e }
242
+ )
243
+ }
244
+
245
+ const json = (await res.json().catch(() => null)) as CloudKitResponse | null
246
+
247
+ // Top-level error dict. This is the branch cryptoc's port could never
248
+ // reach - 421 responses carry no `records`, so an error nested-lookup misses
249
+ // it entirely. Check the root BEFORE looking at per-record results.
250
+ if (json?.serverErrorCode != null)
251
+ throw await this.toError(json.serverErrorCode, json.reason, json.retryAfter)
252
+
253
+ if (!res.ok) {
254
+ // HTTP-level failure with no parseable CloudKit error body.
255
+ if (res.status === 401 || res.status === 421) {
256
+ await this.handleAuthExpired()
257
+ throw new CloudSyncError(
258
+ ErrorCode.AUTH_EXPIRED,
259
+ `[RNCloudSync] CloudKit returned HTTP ${res.status}; the web auth token is no longer valid.`,
260
+ { provider: 'cloudKit' }
261
+ )
262
+ }
263
+ if (res.status === 429 || res.status === 503)
264
+ throw new CloudSyncError(
265
+ ErrorCode.RATE_LIMITED,
266
+ `[RNCloudSync] CloudKit returned HTTP ${res.status}.`,
267
+ { provider: 'cloudKit' }
268
+ )
269
+
270
+ throw new CloudSyncError(
271
+ ErrorCode.UNKNOWN,
272
+ `[RNCloudSync] CloudKit returned HTTP ${res.status}.`,
273
+ { provider: 'cloudKit' }
274
+ )
275
+ }
276
+
277
+ return json ?? {}
278
+ }
279
+
280
+ async getRecord(recordName: string, recordType = RECORD_TYPE_DEFAULT): Promise<string | null> {
281
+ return (await this.getRecordWithMeta(recordName, recordType))?.value ?? null
282
+ }
283
+
284
+ /**
285
+ * A read that also returns the server's own modification time and the
286
+ * record's change tag.
287
+ *
288
+ * Both come back on a plain lookup whether or not anyone asks, so surfacing
289
+ * them costs nothing - and they are what make {@link resolveByModifiedAt} and
290
+ * conditional writes possible without the app instrumenting its payloads.
291
+ */
292
+ async getRecordWithMeta(
293
+ recordName: string,
294
+ recordType = RECORD_TYPE_DEFAULT
295
+ ): Promise<{ value: string; modifiedAt?: number; recordChangeTag?: string } | null> {
296
+ void recordType
297
+ const json = await this.post('/records/lookup', {
298
+ records: [{ recordName }],
299
+ })
300
+
301
+ const record = json.records?.find(r => r.recordName === recordName) ?? json.records?.[0]
302
+ if (record == null) return null
303
+
304
+ if (record.serverErrorCode != null) {
305
+ // A record that simply is not there is a normal outcome, not a failure.
306
+ // Note the real code is NOT_FOUND - `UNKNOWN_ITEM` is a CloudKit
307
+ // *framework* code and never appears in Web Services responses, so
308
+ // matching on it (as cryptoc did) silently misclassifies every miss.
309
+ if (record.serverErrorCode === 'NOT_FOUND') return null
310
+ throw await this.toError(record.serverErrorCode, record.reason, record.retryAfter)
311
+ }
312
+
313
+ const value = record.fields?.[VALUE_FIELD]?.value
314
+ if (typeof value !== 'string') return null
315
+
316
+ return {
317
+ value,
318
+ modifiedAt: typeof record.modified?.timestamp === 'number'
319
+ ? record.modified.timestamp
320
+ : undefined,
321
+ recordChangeTag: record.recordChangeTag,
322
+ }
323
+ }
324
+
325
+ /**
326
+ * Reads many records in one request.
327
+ *
328
+ * `/records/lookup` has taken an array of record ids since the API shipped,
329
+ * so reading 200 keys one at a time was 200 round trips for no reason - and
330
+ * 200 chances to be throttled. Results are matched back by `recordName`
331
+ * rather than by position, because CloudKit does not promise the response
332
+ * preserves request order.
333
+ */
334
+ async getRecords(
335
+ recordNames: string[],
336
+ recordType = RECORD_TYPE_DEFAULT
337
+ ): Promise<(string | null)[]> {
338
+ void recordType
339
+ if (recordNames.length === 0) return []
340
+
341
+ const found = new Map<string, string>()
342
+
343
+ for (const batch of chunk(recordNames, MAX_BATCH)) {
344
+ const json = await this.post('/records/lookup', {
345
+ records: batch.map(recordName => ({ recordName })),
346
+ })
347
+
348
+ for (const record of json.records ?? []) {
349
+ if (record.recordName == null) continue
350
+ if (record.serverErrorCode != null) {
351
+ // Absent is absent, per record - one missing key must not fail the
352
+ // whole batch the way an atomic *write* legitimately does.
353
+ if (record.serverErrorCode === 'NOT_FOUND') continue
354
+ throw await this.toError(record.serverErrorCode, record.reason, record.retryAfter)
355
+ }
356
+ const value = record.fields?.[VALUE_FIELD]?.value
357
+ if (typeof value === 'string') found.set(record.recordName, value)
358
+ }
359
+ }
360
+
361
+ return recordNames.map(name => found.get(name) ?? null)
362
+ }
363
+
364
+ /**
365
+ * Writes many records in one request.
366
+ *
367
+ * Uses `forceUpdate`, which creates or replaces in a single operation, so
368
+ * unlike the single-record path there is no create-then-fall-back-to-update
369
+ * dance to repeat per key.
370
+ *
371
+ * `atomic: false`, deliberately: a batch is a convenience for the caller, not
372
+ * a transaction they asked for, and one oversized record should not silently
373
+ * discard the other 199. Per-record failures are collected and raised
374
+ * together.
375
+ */
376
+ async saveRecords(
377
+ entries: [string, string][],
378
+ recordType = RECORD_TYPE_DEFAULT
379
+ ): Promise<void> {
380
+ if (entries.length === 0) return
381
+
382
+ for (const [recordName, value] of entries) {
383
+ const bytes = byteLength(value)
384
+ if (bytes > MAX_RECORD_BYTES)
385
+ throw new CloudSyncError(
386
+ ErrorCode.PAYLOAD_TOO_LARGE,
387
+ `[RNCloudSync] '${recordName}' is ${bytes} bytes; CloudKit records are limited to `
388
+ + `${MAX_RECORD_BYTES}.`,
389
+ { provider: 'cloudKit', limitBytes: MAX_RECORD_BYTES, actualBytes: bytes }
390
+ )
391
+ }
392
+
393
+ for (const batch of chunk(entries, MAX_BATCH)) {
394
+ const json = await this.post('/records/modify', {
395
+ atomic: false,
396
+ operations: batch.map(([recordName, value]) => ({
397
+ operationType: 'forceUpdate',
398
+ record: { recordType, recordName, fields: { [VALUE_FIELD]: { value } } },
399
+ })),
400
+ })
401
+
402
+ for (const record of json.records ?? [])
403
+ if (record.serverErrorCode != null)
404
+ throw await this.toError(record.serverErrorCode, record.reason, record.retryAfter)
405
+ }
406
+ }
407
+
408
+ /** Deletes many records in one request, with the same per-record rules. */
409
+ async deleteRecords(recordNames: string[], recordType = RECORD_TYPE_DEFAULT): Promise<void> {
410
+ if (recordNames.length === 0) return
411
+
412
+ for (const batch of chunk(recordNames, MAX_BATCH)) {
413
+ const json = await this.post('/records/modify', {
414
+ atomic: false,
415
+ operations: batch.map(recordName => ({
416
+ operationType: 'forceDelete',
417
+ record: { recordType, recordName },
418
+ })),
419
+ })
420
+
421
+ for (const record of json.records ?? []) {
422
+ if (record.serverErrorCode == null) continue
423
+ // Deleting something that was never there is the end state the caller
424
+ // asked for.
425
+ if (record.serverErrorCode === 'NOT_FOUND') continue
426
+ throw await this.toError(record.serverErrorCode, record.reason, record.retryAfter)
427
+ }
428
+ }
429
+ }
430
+
431
+ async saveRecord(
432
+ recordName: string,
433
+ value: string,
434
+ recordType = RECORD_TYPE_DEFAULT
435
+ ): Promise<void> {
436
+ const bytes = byteLength(value)
437
+ if (bytes > MAX_RECORD_BYTES)
438
+ throw new CloudSyncError(
439
+ ErrorCode.PAYLOAD_TOO_LARGE,
440
+ `[RNCloudSync] Value is ${bytes} bytes; CloudKit records are limited to ${MAX_RECORD_BYTES}. `
441
+ + `Use the store facade with tiering enabled to route large values to a CKAsset.`,
442
+ { provider: 'cloudKit', limitBytes: MAX_RECORD_BYTES, actualBytes: bytes }
443
+ )
444
+
445
+ const record = {
446
+ recordType,
447
+ recordName,
448
+ fields: { [VALUE_FIELD]: { value } },
449
+ }
450
+
451
+ // `atomic` defaults to true server-side. Setting it explicitly documents the
452
+ // intent and keeps behaviour stable if that default ever changes.
453
+ let created: CloudKitResponse | null = null
454
+ try {
455
+ created = await this.post('/records/modify', {
456
+ atomic: true,
457
+ operations: [{ operationType: 'create', record }],
458
+ })
459
+ }
460
+ catch (e) {
461
+ // A create against a record that already exists is the normal path for
462
+ // every write after the first, so it must not surface as an error. With
463
+ // `atomic: true` CloudKit reports that at the top level, which `post`
464
+ // turns into a throw.
465
+ //
466
+ // Only an already-exists response falls through to the update below.
467
+ // Anything else - quota, auth, rate limiting, or a response this package
468
+ // could not classify - is rethrown. Swallowing an unclassified failure
469
+ // here and force-updating anyway would overwrite whatever is on the
470
+ // server on the strength of an error nobody read.
471
+ if (!isAlreadyExists(e)) throw e
472
+ }
473
+
474
+ const createdRecord = created?.records?.[0]
475
+ if (created != null && createdRecord?.serverErrorCode == null) return
476
+
477
+ if (
478
+ createdRecord?.serverErrorCode != null
479
+ && !EXISTS_CODES.has(createdRecord.serverErrorCode)
480
+ )
481
+ throw await this.toError(createdRecord.serverErrorCode, createdRecord.reason, createdRecord.retryAfter)
482
+
483
+ // Last-write-wins, matching the native provider's `.changedKeys` save policy
484
+ // so both platforms resolve concurrent writes identically.
485
+ const updated = await this.post('/records/modify', {
486
+ atomic: true,
487
+ operations: [{ operationType: 'forceUpdate', record }],
488
+ })
489
+ const updatedRecord = updated.records?.[0]
490
+ if (updatedRecord?.serverErrorCode != null) {
491
+ const serverValue = updatedRecord.serverRecord?.fields?.[VALUE_FIELD]?.value
492
+ throw await this.toError(
493
+ updatedRecord.serverErrorCode,
494
+ updatedRecord.reason,
495
+ updatedRecord.retryAfter,
496
+ typeof serverValue === 'string' ? serverValue : null
497
+ )
498
+ }
499
+ }
500
+
501
+ /**
502
+ * A write that fails instead of clobbering, when the server's copy has moved
503
+ * on since `recordChangeTag` was read.
504
+ *
505
+ * The normal `saveRecord` is last-write-wins - the right default for the
506
+ * common case, and what the native provider's `.changedKeys` save policy
507
+ * does, so both platforms agree. But last-write-wins means a genuine
508
+ * concurrent edit is destroyed silently, and `ERR_CONFLICT` carries
509
+ * `serverValue` precisely so an app can merge instead. Without a conditional
510
+ * write, that error could never actually fire and the merge path was
511
+ * unreachable.
512
+ *
513
+ * Read the tag with {@link getRecordWithMeta}, pass it here, and handle
514
+ * `ERR_CONFLICT` by merging `serverValue` and retrying.
515
+ */
516
+ async saveRecordIfUnchanged(
517
+ recordName: string,
518
+ value: string,
519
+ recordChangeTag: string,
520
+ recordType = RECORD_TYPE_DEFAULT
521
+ ): Promise<void> {
522
+ const bytes = byteLength(value)
523
+ if (bytes > MAX_RECORD_BYTES)
524
+ throw new CloudSyncError(
525
+ ErrorCode.PAYLOAD_TOO_LARGE,
526
+ `[RNCloudSync] Value is ${bytes} bytes; CloudKit records are limited to ${MAX_RECORD_BYTES}.`,
527
+ { provider: 'cloudKit', limitBytes: MAX_RECORD_BYTES, actualBytes: bytes }
528
+ )
529
+
530
+ // `update` (rather than `forceUpdate`) is the conditional form: with a
531
+ // change tag present, CloudKit rejects the write if the server's tag has
532
+ // moved on.
533
+ const json = await this.post('/records/modify', {
534
+ atomic: true,
535
+ operations: [{
536
+ operationType: 'update',
537
+ record: {
538
+ recordType,
539
+ recordName,
540
+ recordChangeTag,
541
+ fields: { [VALUE_FIELD]: { value } },
542
+ },
543
+ }],
544
+ })
545
+
546
+ const result = json.records?.[0]
547
+ if (result?.serverErrorCode == null) return
548
+
549
+ const serverValue = result.serverRecord?.fields?.[VALUE_FIELD]?.value
550
+ throw await this.toError(
551
+ result.serverErrorCode,
552
+ result.reason,
553
+ result.retryAfter,
554
+ typeof serverValue === 'string' ? serverValue : null
555
+ )
556
+ }
557
+
558
+ async deleteRecord(recordName: string, recordType = RECORD_TYPE_DEFAULT): Promise<void> {
559
+ const json = await this.post('/records/modify', {
560
+ atomic: true,
561
+ operations: [
562
+ { operationType: 'forceDelete', record: { recordType, recordName } },
563
+ ],
564
+ })
565
+ const result = json.records?.[0]
566
+ if (result?.serverErrorCode == null) return
567
+ // Deleting something that was never there is a success from the caller's
568
+ // point of view - the desired end state already holds.
569
+ if (result.serverErrorCode === 'NOT_FOUND') return
570
+ throw await this.toError(result.serverErrorCode, result.reason, result.retryAfter)
571
+ }
572
+
573
+ async queryRecordNames(recordType = RECORD_TYPE_DEFAULT): Promise<string[]> {
574
+ const names: string[] = []
575
+ const seenMarkers = new Set<string>()
576
+ let continuationMarker: string | undefined
577
+
578
+ // `/records/query` caps a response at 200 records and hands back a
579
+ // continuation marker for the rest. Taking only the first page silently
580
+ // truncated `getAllKeys()`, and `migrate()` is built on `getAllKeys()` - so
581
+ // it showed up as a migration that quietly copied part of the data and
582
+ // reported success.
583
+ do {
584
+ const json: CloudKitResponse = await this.post('/records/query', {
585
+ query: { recordType },
586
+ ...(continuationMarker != null ? { continuationMarker } : {}),
587
+ })
588
+
589
+ for (const record of json.records ?? [])
590
+ if (typeof record.recordName === 'string') names.push(record.recordName)
591
+
592
+ continuationMarker = json.continuationMarker
593
+ // A server that repeats a marker would loop forever; stop instead.
594
+ if (continuationMarker != null) {
595
+ if (seenMarkers.has(continuationMarker)) break
596
+ seenMarkers.add(continuationMarker)
597
+ }
598
+ } while (continuationMarker != null)
599
+
600
+ return names
601
+ }
602
+
603
+ /**
604
+ * Cheap reachability check backing the provider's `isAvailable()`.
605
+ *
606
+ * The probe itself is a network round trip, but `isAvailable()` is documented
607
+ * as safe on a render path and the store calls it before every provider read -
608
+ * so unmemoised, each `getItem` on Android or web cost two requests instead of
609
+ * one. Held briefly: long enough to collapse that pair, short enough that a
610
+ * token expiring mid-session is noticed.
611
+ */
612
+ async isReachable(): Promise<boolean> {
613
+ const now = Date.now()
614
+ if (this.reachability != null && now - this.reachability.at < REACHABILITY_TTL_MS)
615
+ return this.reachability.ok
616
+
617
+ let ok: boolean
618
+ try {
619
+ // A `null` result and a NOT_FOUND both mean reachable and authenticated;
620
+ // only a thrown auth/network/config error means unavailable.
621
+ await this.getRecord(AVAILABILITY_PROBE_RECORD)
622
+ ok = true
623
+ }
624
+ catch {
625
+ ok = false
626
+ }
627
+
628
+ this.reachability = { at: now, ok }
629
+ return ok
630
+ }
631
+
632
+ /**
633
+ * Drops the memoised reachability answer.
634
+ *
635
+ * Called on an account switch: that answer was recorded for the previous
636
+ * user's web auth token and says nothing about the new one.
637
+ */
638
+ clearCache(): void {
639
+ this.reachability = null
640
+ }
641
+ }
642
+
643
+ /** Splits `items` into runs of at most `size`. */
644
+ function chunk<T>(items: T[], size: number): T[][] {
645
+ if (items.length <= size) return [items]
646
+ const out: T[][] = []
647
+ for (let i = 0; i < items.length; i += size) out.push(items.slice(i, i + size))
648
+ return out
649
+ }
650
+
651
+ // Re-exported from its own module so the tiering and key-validation paths can
652
+ // use it without importing a REST client. Kept exported here because it has
653
+ // been part of this module's surface since the first release.
654
+ export { byteLength } from './bytes'
@@ -0,0 +1,35 @@
1
+ import type { AccountStatus, ChangeReason } from '../types'
2
+
3
+ const ACCOUNT_STATUSES: readonly AccountStatus[] = [
4
+ 'available',
5
+ 'noAccount',
6
+ 'restricted',
7
+ 'temporarilyUnavailable',
8
+ 'couldNotDetermine',
9
+ ]
10
+
11
+ const CHANGE_REASONS: readonly ChangeReason[] = [
12
+ 'serverChange',
13
+ 'initialSync',
14
+ 'quotaViolation',
15
+ 'accountChange',
16
+ 'unknown',
17
+ ]
18
+
19
+ /**
20
+ * Codegen has no string-union type, so enums cross the bridge as plain strings.
21
+ * Validate on the way in rather than casting - an unrecognised value from a
22
+ * newer native build should degrade to a known-safe member, not corrupt an
23
+ * exhaustive switch downstream.
24
+ */
25
+ export function toAccountStatus(raw: string): AccountStatus {
26
+ return (ACCOUNT_STATUSES as readonly string[]).includes(raw)
27
+ ? (raw as AccountStatus)
28
+ : 'couldNotDetermine'
29
+ }
30
+
31
+ export function toChangeReason(raw: string): ChangeReason {
32
+ return (CHANGE_REASONS as readonly string[]).includes(raw)
33
+ ? (raw as ChangeReason)
34
+ : 'unknown'
35
+ }