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,510 @@
1
+ import { Platform } from 'react-native'
2
+
3
+ import { getNativeModule, hasNativeModule, requireNativeModule, subscribeNativeEvent } from '../internal/nativeModule'
4
+ import { getCloudKitClient, isCloudKitConfigured } from '../config'
5
+ import { CloudKitRestClient, type CloudKitRestConfig } from '../internal/cloudKitRest'
6
+ import { normalizeError, unsupportedPlatform } from '../errors'
7
+ import { toAccountStatus } from '../internal/enums'
8
+ import type {
9
+ AccountChangeEvent,
10
+ AccountStatus,
11
+ AssetProgressEvent,
12
+ CloudProvider,
13
+ ProviderName,
14
+ Unsubscribe,
15
+ } from '../types'
16
+ import type {
17
+ AccountChangeNativeEvent,
18
+ AssetProgressNativeEvent,
19
+ } from '../specs/NativeRNCloudSync'
20
+
21
+ const NAME = 'cloudKit' as const
22
+
23
+ /**
24
+ * CloudKit private database.
25
+ *
26
+ * The only provider here that reaches the *same* data on every platform:
27
+ *
28
+ * iOS / macOS -> CloudKit.framework, natively, no configuration
29
+ * Android -> CloudKit Web Services REST (see configureCloudKit)
30
+ * Web -> the same REST client
31
+ *
32
+ * On Android and web the user must sign in with an Apple ID to mint a
33
+ * `ckWebAuthToken`, and that token lives 30 minutes - or 2 weeks if they ticked
34
+ * "Keep me signed in" - with no documented refresh. Treat those platforms as
35
+ * suited to a deliberate import/export ("bring my iPhone data over"), not to a
36
+ * silent always-on backup. `googleDrive` is the better continuous backend there.
37
+ */
38
+
39
+ /** True when this platform talks to CloudKit natively rather than over REST. */
40
+ function isNative(): boolean {
41
+ // `Platform?.OS` rather than `Platform.OS`: on a react-native-web build served
42
+ // by a bundler that does not resolve platform extensions, this module is what
43
+ // loads, and it has to answer 'not native' rather than throw.
44
+ const os: string | undefined = Platform?.OS
45
+ return (os === 'ios' || os === 'macos') && hasNativeModule()
46
+ }
47
+
48
+ export const cloudKit: CloudProvider = {
49
+ name: NAME,
50
+
51
+ isAvailable: async () => {
52
+ if (isNative())
53
+ try {
54
+ return await requireNativeModule().isAvailable()
55
+ }
56
+ catch {
57
+ return false
58
+ }
59
+
60
+ if (!isCloudKitConfigured()) return false
61
+ try {
62
+ // Memoised inside the client: the store asks before every provider read,
63
+ // and an unmemoised probe made each read cost two network round trips.
64
+ return await getCloudKitClient().isReachable()
65
+ }
66
+ catch {
67
+ return false
68
+ }
69
+ },
70
+
71
+ getAccountStatus: async (): Promise<AccountStatus> => {
72
+ if (isNative())
73
+ try {
74
+ return toAccountStatus(await requireNativeModule().getAccountStatus())
75
+ }
76
+ catch (e) {
77
+ throw normalizeError(e, NAME)
78
+ }
79
+
80
+ // Over REST there is no account-status endpoint; possession of a usable web
81
+ // auth token is the closest equivalent signal.
82
+ return isCloudKitConfigured() ? 'available' : 'noAccount'
83
+ },
84
+
85
+ getItem: async (key: string) => {
86
+ try {
87
+ if (isNative()) return await requireNativeModule().ckGetRecord('KVBlob', key, null, false)
88
+ return await getCloudKitClient().getRecord(key)
89
+ }
90
+ catch (e) {
91
+ throw normalizeError(e, NAME)
92
+ }
93
+ },
94
+
95
+ /**
96
+ * Server modification time, over REST only.
97
+ *
98
+ * CloudKit returns `modified.timestamp` on every lookup, so the REST path
99
+ * gets it for free. The native path would need a new bridge method and a
100
+ * second field on every response for a value only the resolver uses, so it
101
+ * reports no timestamp and falls back to preference order - which is what
102
+ * {@link resolveByModifiedAt} is built to handle.
103
+ */
104
+ getItemWithMeta: async (key: string) => {
105
+ if (isNative()) {
106
+ const value = await cloudKit.getItem(key)
107
+ return value == null ? null : { value }
108
+ }
109
+ try {
110
+ return await getCloudKitClient().getRecordWithMeta(key)
111
+ }
112
+ catch (e) {
113
+ throw normalizeError(e, NAME)
114
+ }
115
+ },
116
+
117
+ /**
118
+ * Reads many records in one request, over REST.
119
+ *
120
+ * `/records/lookup` takes an array, so this is the difference between one
121
+ * round trip and N - and between one rate-limit budget and N.
122
+ */
123
+ multiGet: async (keys: string[]) => {
124
+ if (isNative()) {
125
+ const out: (string | null)[] = []
126
+ for (const key of keys)
127
+ out.push(await requireNativeModule().ckGetRecord('KVBlob', key, null, false))
128
+ return out
129
+ }
130
+ try {
131
+ return await getCloudKitClient().getRecords(keys)
132
+ }
133
+ catch (e) {
134
+ throw normalizeError(e, NAME)
135
+ }
136
+ },
137
+
138
+ multiSet: async (entries: [string, string][]) => {
139
+ if (isNative()) {
140
+ for (const [key, value] of entries)
141
+ await requireNativeModule().ckSaveRecord('KVBlob', key, value, null, false)
142
+ return
143
+ }
144
+ try {
145
+ await getCloudKitClient().saveRecords(entries)
146
+ }
147
+ catch (e) {
148
+ throw normalizeError(e, NAME)
149
+ }
150
+ },
151
+
152
+ multiRemove: async (keys: string[]) => {
153
+ if (isNative()) {
154
+ for (const key of keys) await requireNativeModule().ckDeleteRecord(key, null)
155
+ return
156
+ }
157
+ try {
158
+ await getCloudKitClient().deleteRecords(keys)
159
+ }
160
+ catch (e) {
161
+ throw normalizeError(e, NAME)
162
+ }
163
+ },
164
+
165
+ clearCaches: () => {
166
+ // The memoised reachability answer was recorded for the previous account's
167
+ // web auth token and says nothing about the new one.
168
+ if (!isNative() && isCloudKitConfigured()) getCloudKitClient().clearCache()
169
+ },
170
+
171
+ setItem: async (key: string, value: string) => {
172
+ try {
173
+ if (isNative()) {
174
+ await requireNativeModule().ckSaveRecord('KVBlob', key, value, null, false)
175
+ return
176
+ }
177
+ await getCloudKitClient().saveRecord(key, value)
178
+ }
179
+ catch (e) {
180
+ throw normalizeError(e, NAME)
181
+ }
182
+ },
183
+
184
+ removeItem: async (key: string) => {
185
+ try {
186
+ if (isNative()) {
187
+ await requireNativeModule().ckDeleteRecord(key, null)
188
+ return
189
+ }
190
+ await getCloudKitClient().deleteRecord(key)
191
+ }
192
+ catch (e) {
193
+ throw normalizeError(e, NAME)
194
+ }
195
+ },
196
+
197
+ getAllKeys: async () => {
198
+ try {
199
+ if (isNative()) return await requireNativeModule().ckQueryRecordNames('KVBlob', null)
200
+ return await getCloudKitClient().queryRecordNames()
201
+ }
202
+ catch (e) {
203
+ throw normalizeError(e, NAME)
204
+ }
205
+ },
206
+
207
+ /**
208
+ * Deliberately absent, rather than present and silent.
209
+ *
210
+ * This provider used to expose `onRemoteChange`, and it could never fire: the
211
+ * only `remoteChange` the native layer emits comes from
212
+ * `NSUbiquitousKeyValueStore.didChangeExternallyNotification` and is tagged
213
+ * `icloudKV`, so the filter here never matched. A subscription that accepts a
214
+ * listener and never calls it is worse than no method at all - the caller has
215
+ * no way to tell it apart from "nothing has changed yet".
216
+ *
217
+ * Implementing it properly is not a small gap to paper over. CloudKit reports
218
+ * record changes through `CKFetchRecordZoneChangesOperation` with a server
219
+ * change token, and that only works in a **custom zone** - the default zone,
220
+ * which this provider uses so that record names stay addressable from the
221
+ * REST client, does not support change tokens at all. The alternatives are a
222
+ * `CKDatabaseSubscription` delivered over APNs, which needs push entitlements
223
+ * and a silent-notification handler in the host app. Either is a real feature
224
+ * with a schema or entitlement cost, not a missing line.
225
+ *
226
+ * Until then: `cloudKit.onRemoteChange == null` is checkable, `icloudKV` and
227
+ * `googleDrive` both report changes, and `onAccountChange` below does fire.
228
+ */
229
+
230
+ onAccountChange: (listener: (e: AccountChangeEvent) => void): Unsubscribe => {
231
+ if (getNativeModule() == null) return () => undefined
232
+ return subscribeNativeEvent<AccountChangeNativeEvent>(
233
+ 'onAccountChange',
234
+ 'accountChange',
235
+ (e) => {
236
+ listener({
237
+ status: toAccountStatus(e.status),
238
+ identityChanged: e.identityChanged,
239
+ provider: NAME,
240
+ })
241
+ }
242
+ )
243
+ },
244
+ }
245
+
246
+ /**
247
+ * A CloudKit provider with its own REST credentials and its own name.
248
+ *
249
+ * `configureCloudKit` sets one client for the whole process. That is right for
250
+ * a normal app, but leaves no way to reach two containers at once - a staging
251
+ * container beside production, or a migration that copies between them - and no
252
+ * way for two tests to hold different configurations.
253
+ *
254
+ * REST only, and that is not a limitation that can be lifted: the native path
255
+ * authenticates as whatever iCloud account the *device* is signed into, so
256
+ * "another set of credentials" has no meaning there. On iOS this therefore
257
+ * still talks to CloudKit Web Services rather than to `CloudKit.framework`.
258
+ */
259
+ export function createCloudKitProvider(
260
+ config: CloudKitRestConfig & { name?: ProviderName }
261
+ ): CloudProvider {
262
+ const client = new CloudKitRestClient(config)
263
+ const name = config.name ?? NAME
264
+
265
+ return {
266
+ name,
267
+
268
+ isAvailable: async () => {
269
+ try {
270
+ return await client.isReachable()
271
+ }
272
+ catch {
273
+ return false
274
+ }
275
+ },
276
+
277
+ getAccountStatus: () => Promise.resolve<AccountStatus>('available'),
278
+
279
+ getItem: async (key: string) => {
280
+ try {
281
+ return await client.getRecord(key)
282
+ }
283
+ catch (e) {
284
+ throw normalizeError(e, name)
285
+ }
286
+ },
287
+
288
+ getItemWithMeta: async (key: string) => {
289
+ try {
290
+ return await client.getRecordWithMeta(key)
291
+ }
292
+ catch (e) {
293
+ throw normalizeError(e, name)
294
+ }
295
+ },
296
+
297
+ setItem: async (key: string, value: string) => {
298
+ try {
299
+ await client.saveRecord(key, value)
300
+ }
301
+ catch (e) {
302
+ throw normalizeError(e, name)
303
+ }
304
+ },
305
+
306
+ removeItem: async (key: string) => {
307
+ try {
308
+ await client.deleteRecord(key)
309
+ }
310
+ catch (e) {
311
+ throw normalizeError(e, name)
312
+ }
313
+ },
314
+
315
+ getAllKeys: async () => {
316
+ try {
317
+ return await client.queryRecordNames()
318
+ }
319
+ catch (e) {
320
+ throw normalizeError(e, name)
321
+ }
322
+ },
323
+
324
+ multiGet: async (keys: string[]) => {
325
+ try {
326
+ return await client.getRecords(keys)
327
+ }
328
+ catch (e) {
329
+ throw normalizeError(e, name)
330
+ }
331
+ },
332
+
333
+ multiSet: async (entries: [string, string][]) => {
334
+ try {
335
+ await client.saveRecords(entries)
336
+ }
337
+ catch (e) {
338
+ throw normalizeError(e, name)
339
+ }
340
+ },
341
+
342
+ multiRemove: async (keys: string[]) => {
343
+ try {
344
+ await client.deleteRecords(keys)
345
+ }
346
+ catch (e) {
347
+ throw normalizeError(e, name)
348
+ }
349
+ },
350
+
351
+ clearCaches: () => {
352
+ client.clearCache()
353
+ },
354
+ }
355
+ }
356
+
357
+ /** Custom zones. Native only - the REST client uses the default zone. */
358
+ export const zones = {
359
+ create: async (zoneName: string): Promise<void> => {
360
+ try {
361
+ await requireNativeModule().ckCreateZone(zoneName)
362
+ }
363
+ catch (e) {
364
+ throw normalizeError(e, NAME)
365
+ }
366
+ },
367
+ remove: async (zoneName: string): Promise<void> => {
368
+ try {
369
+ await requireNativeModule().ckDeleteZone(zoneName)
370
+ }
371
+ catch (e) {
372
+ throw normalizeError(e, NAME)
373
+ }
374
+ },
375
+ list: async (): Promise<string[]> => {
376
+ try {
377
+ return await requireNativeModule().ckListZones()
378
+ }
379
+ catch (e) {
380
+ throw normalizeError(e, NAME)
381
+ }
382
+ },
383
+ }
384
+
385
+ /**
386
+ * Binary assets (`CKAsset`).
387
+ *
388
+ * Native only. CloudKit Web Services does expose an asset upload flow, but it
389
+ * is a separate multi-step protocol (request an upload URL, POST the bytes,
390
+ * then reference the returned token in a record) that this package does not
391
+ * implement yet - so on Android and web these reject with
392
+ * `ERR_UNSUPPORTED_PLATFORM` rather than appearing to work.
393
+ *
394
+ * Assets are deliberately an explicit API rather than something the store
395
+ * facade routes to automatically: the caller passes a file path, not a string,
396
+ * so there is no way to infer the intent from a `setItem` call.
397
+ */
398
+ export const assets = {
399
+ /**
400
+ * Uploads a local file as a field on a record.
401
+ *
402
+ * Progress is reported per record through {@link onProgress}; a CKAsset is
403
+ * streamed from disk, so a large file does not have to be held in memory the
404
+ * way a base64 round trip would.
405
+ */
406
+ save: async (
407
+ options: {
408
+ recordName: string
409
+ fieldName: string
410
+ /** `file://` URL or a plain path. */
411
+ fileUri: string
412
+ recordType?: string
413
+ zoneName?: string | null
414
+ }
415
+ ): Promise<void> => {
416
+ if (!isNative())
417
+ throw unsupportedPlatform(
418
+ NAME,
419
+ 'CKAsset upload is implemented natively only. On Android and web, store the file '
420
+ + 'with the googleDrive provider instead.'
421
+ )
422
+
423
+ try {
424
+ await requireNativeModule().ckSaveAsset(
425
+ options.recordType ?? 'KVBlob',
426
+ options.recordName,
427
+ options.fieldName,
428
+ options.fileUri,
429
+ options.zoneName ?? null
430
+ )
431
+ }
432
+ catch (e) {
433
+ throw normalizeError(e, NAME)
434
+ }
435
+ },
436
+
437
+ /**
438
+ * Downloads an asset field and resolves a local file path, or `null` when the
439
+ * record or field does not exist.
440
+ *
441
+ * Pass `destinationUri` for anything the user is going to keep or hand to a
442
+ * share sheet. Without it the file lands in the app's temporary directory
443
+ * under a name derived from the record, and iOS may reclaim that at any
444
+ * time - fine for restoring straight back into the app, wrong for an export.
445
+ * Parent directories are created if they do not exist.
446
+ */
447
+ fetch: async (
448
+ options: {
449
+ recordName: string
450
+ fieldName: string
451
+ zoneName?: string | null
452
+ destinationUri?: string
453
+ }
454
+ ): Promise<string | null> => {
455
+ if (!isNative())
456
+ throw unsupportedPlatform(
457
+ NAME,
458
+ 'CKAsset download is implemented natively only.'
459
+ )
460
+
461
+ try {
462
+ return await requireNativeModule().ckFetchAsset(
463
+ options.recordName,
464
+ options.fieldName,
465
+ options.zoneName ?? null,
466
+ options.destinationUri ?? null
467
+ )
468
+ }
469
+ catch (e) {
470
+ throw normalizeError(e, NAME)
471
+ }
472
+ },
473
+
474
+ /**
475
+ * Cancels an in-flight {@link save} or {@link fetch}, rejecting that call
476
+ * with `ERR_CANCELLED`. Resolves true when there was a transfer to cancel.
477
+ *
478
+ * Identified by record and field rather than by a handle, because that is
479
+ * what identifies a transfer everywhere else in this API - `onProgress`
480
+ * reports the same pair, so a UI already has it.
481
+ */
482
+ cancel: async (
483
+ options: { recordName: string; fieldName: string }
484
+ ): Promise<boolean> => {
485
+ if (!isNative()) return false
486
+ try {
487
+ return await requireNativeModule().ckCancelAsset(options.recordName, options.fieldName)
488
+ }
489
+ catch (e) {
490
+ throw normalizeError(e, NAME)
491
+ }
492
+ },
493
+
494
+ /** Upload/download progress for asset transfers. Native only. */
495
+ onProgress: (listener: (e: AssetProgressEvent) => void): Unsubscribe => {
496
+ if (getNativeModule() == null) return () => undefined
497
+ return subscribeNativeEvent<AssetProgressNativeEvent>(
498
+ 'onAssetProgress',
499
+ 'assetProgress',
500
+ (e) => {
501
+ listener({
502
+ recordName: e.recordName,
503
+ fieldName: e.fieldName,
504
+ bytesTransferred: e.bytesTransferred,
505
+ bytesTotal: e.bytesTotal,
506
+ })
507
+ }
508
+ )
509
+ },
510
+ }
@@ -0,0 +1,124 @@
1
+ import { assets } from './cloudKit'
2
+ import type { AssetProgressEvent } from '../types'
3
+
4
+ const DEFAULT_RECORD_NAME = 'backup'
5
+ const DEFAULT_FIELD_NAME = 'file'
6
+
7
+ export interface BackupProgressEvent {
8
+ bytesTransferred: number
9
+ bytesTotal: number
10
+ /**
11
+ * `bytesTransferred / bytesTotal`, or 0 while `bytesTotal` is still unknown.
12
+ * `save` knows the size from the first callback (the file is local);
13
+ * `restore` does too, as long as the backup was written by a version of this
14
+ * package that stores the size alongside the asset - older backups fall back
15
+ * to 0 until the transfer completes.
16
+ */
17
+ fraction: number
18
+ }
19
+
20
+ export interface BackupOptions {
21
+ /** CKRecord name identifying this backup. Default `'backup'`. */
22
+ recordName?: string
23
+ /** Asset field name on that record. Default `'file'`. */
24
+ fieldName?: string
25
+ zoneName?: string | null
26
+ /** Called repeatedly while the transfer is in flight, scoped to this call only. */
27
+ onProgress?: (e: BackupProgressEvent) => void
28
+ /**
29
+ * Where `restore` puts the downloaded file. Ignored by `save`.
30
+ *
31
+ * Pass one whenever the user is going to see the result - an export they
32
+ * save to Files, a database they hand to a share sheet. Without it the file
33
+ * lands in the app's temporary directory, which iOS may reclaim at any time
34
+ * and which the user cannot reach. Parent directories are created for you.
35
+ */
36
+ destinationUri?: string
37
+ }
38
+
39
+ /**
40
+ * Backup/restore built on {@link assets} (`CKAsset`), for a single named blob -
41
+ * a database export, an archive, anything too big for a `CKRecord` field.
42
+ *
43
+ * `cloudKitAssets.onProgress` is a global feed shared by every asset transfer
44
+ * in the app, keyed by `recordName`/`fieldName`, so a caller backing up one
45
+ * file would otherwise have to filter it and manage the subscription by hand.
46
+ * This scopes that to the single transfer each call makes, and unsubscribes
47
+ * when it settles - including on failure.
48
+ *
49
+ * Native only, same as `cloudKitAssets` - rejects with `ERR_UNSUPPORTED_PLATFORM`
50
+ * on Android and web.
51
+ */
52
+ export const cloudKitBackup = {
53
+ /**
54
+ * Uploads `fileUri` as this backup's CKAsset, overwriting whatever was there.
55
+ */
56
+ save: async (fileUri: string, options: BackupOptions = {}): Promise<void> => {
57
+ const recordName = options.recordName ?? DEFAULT_RECORD_NAME
58
+ const fieldName = options.fieldName ?? DEFAULT_FIELD_NAME
59
+
60
+ const unsubscribe = subscribeScoped(recordName, fieldName, options.onProgress)
61
+ try {
62
+ await assets.save({ recordName, fieldName, fileUri, zoneName: options.zoneName })
63
+ }
64
+ finally {
65
+ unsubscribe()
66
+ }
67
+ },
68
+
69
+ /**
70
+ * Downloads the backup to a local file path, or resolves `null` when none
71
+ * has been saved yet.
72
+ */
73
+ restore: async (options: BackupOptions = {}): Promise<string | null> => {
74
+ const recordName = options.recordName ?? DEFAULT_RECORD_NAME
75
+ const fieldName = options.fieldName ?? DEFAULT_FIELD_NAME
76
+
77
+ const unsubscribe = subscribeScoped(recordName, fieldName, options.onProgress)
78
+ try {
79
+ return await assets.fetch({
80
+ recordName,
81
+ fieldName,
82
+ zoneName: options.zoneName,
83
+ destinationUri: options.destinationUri,
84
+ })
85
+ }
86
+ finally {
87
+ unsubscribe()
88
+ }
89
+ },
90
+
91
+ /**
92
+ * Cancels a `save` or `restore` in progress, rejecting that call with
93
+ * `ERR_CANCELLED`. Resolves true when there was one to cancel.
94
+ *
95
+ * A backup is the transfer users are most likely to want to stop - it is the
96
+ * biggest, and it is the one they start by accident. Takes the same
97
+ * `recordName`/`fieldName` defaults as the call it cancels, so cancelling the
98
+ * default backup is `cloudKitBackup.cancel()`.
99
+ */
100
+ cancel: async (
101
+ options: Pick<BackupOptions, 'recordName' | 'fieldName'> = {}
102
+ ): Promise<boolean> =>
103
+ await assets.cancel({
104
+ recordName: options.recordName ?? DEFAULT_RECORD_NAME,
105
+ fieldName: options.fieldName ?? DEFAULT_FIELD_NAME,
106
+ }),
107
+ }
108
+
109
+ function subscribeScoped(
110
+ recordName: string,
111
+ fieldName: string,
112
+ onProgress: BackupOptions['onProgress']
113
+ ): () => void {
114
+ if (onProgress == null) return () => undefined
115
+
116
+ return assets.onProgress((e: AssetProgressEvent) => {
117
+ if (e.recordName !== recordName || e.fieldName !== fieldName) return
118
+ onProgress({
119
+ bytesTransferred: e.bytesTransferred,
120
+ bytesTotal: e.bytesTotal,
121
+ fraction: e.bytesTotal > 0 ? e.bytesTransferred / e.bytesTotal : 0,
122
+ })
123
+ })
124
+ }