react-native-cloud-sync 0.2.0 → 0.3.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 (45) hide show
  1. package/README.md +53 -53
  2. package/lib/commonjs/config.js +11 -1
  3. package/lib/commonjs/config.js.map +1 -1
  4. package/lib/commonjs/index.js.map +1 -1
  5. package/lib/commonjs/internal/cloudKitRest.js +205 -21
  6. package/lib/commonjs/internal/cloudKitRest.js.map +1 -1
  7. package/lib/commonjs/internal/googleDriveRest.js +173 -38
  8. package/lib/commonjs/internal/googleDriveRest.js.map +1 -1
  9. package/lib/commonjs/providers/cloudKit.js +89 -19
  10. package/lib/commonjs/providers/cloudKit.js.map +1 -1
  11. package/lib/module/config.js +10 -1
  12. package/lib/module/config.js.map +1 -1
  13. package/lib/module/index.js.map +1 -1
  14. package/lib/module/internal/cloudKitRest.js +205 -21
  15. package/lib/module/internal/cloudKitRest.js.map +1 -1
  16. package/lib/module/internal/googleDriveRest.js +174 -39
  17. package/lib/module/internal/googleDriveRest.js.map +1 -1
  18. package/lib/module/providers/cloudKit.js +92 -22
  19. package/lib/module/providers/cloudKit.js.map +1 -1
  20. package/lib/typescript/commonjs/config.d.ts +8 -0
  21. package/lib/typescript/commonjs/config.d.ts.map +1 -1
  22. package/lib/typescript/commonjs/index.d.ts +1 -1
  23. package/lib/typescript/commonjs/index.d.ts.map +1 -1
  24. package/lib/typescript/commonjs/internal/cloudKitRest.d.ts +90 -0
  25. package/lib/typescript/commonjs/internal/cloudKitRest.d.ts.map +1 -1
  26. package/lib/typescript/commonjs/internal/googleDriveRest.d.ts +73 -8
  27. package/lib/typescript/commonjs/internal/googleDriveRest.d.ts.map +1 -1
  28. package/lib/typescript/commonjs/providers/cloudKit.d.ts +32 -13
  29. package/lib/typescript/commonjs/providers/cloudKit.d.ts.map +1 -1
  30. package/lib/typescript/module/config.d.ts +8 -0
  31. package/lib/typescript/module/config.d.ts.map +1 -1
  32. package/lib/typescript/module/index.d.ts +1 -1
  33. package/lib/typescript/module/index.d.ts.map +1 -1
  34. package/lib/typescript/module/internal/cloudKitRest.d.ts +90 -0
  35. package/lib/typescript/module/internal/cloudKitRest.d.ts.map +1 -1
  36. package/lib/typescript/module/internal/googleDriveRest.d.ts +73 -8
  37. package/lib/typescript/module/internal/googleDriveRest.d.ts.map +1 -1
  38. package/lib/typescript/module/providers/cloudKit.d.ts +32 -13
  39. package/lib/typescript/module/providers/cloudKit.d.ts.map +1 -1
  40. package/package.json +1 -1
  41. package/src/config.ts +12 -2
  42. package/src/index.ts +3 -1
  43. package/src/internal/cloudKitRest.ts +272 -29
  44. package/src/internal/googleDriveRest.ts +196 -42
  45. package/src/providers/cloudKit.ts +138 -41
package/README.md CHANGED
@@ -13,7 +13,7 @@
13
13
  <h1 align="center">react-native-cloud-sync</h1>
14
14
 
15
15
  <p align="center">
16
- iCloud key-value store, CloudKit and Google Drive behind one API - on iOS, Android and the web, on both React Native architectures.
16
+ iCloud key-value store, CloudKit and Google Drive behind one API - iOS, Android, web, both architectures.
17
17
  </p>
18
18
 
19
19
  <p align="center">
@@ -27,42 +27,42 @@
27
27
 
28
28
  ## ✨ Features
29
29
 
30
- - ☁️ **Four providers, one API** - [`NSUbiquitousKeyValueStore`][kvs] (iCloud's key-value store), [CloudKit][ck] records, [iCloud Drive][icdrive] documents and Google Drive [`appDataFolder`][appdata], each usable directly or through a single facade.
31
- - 🍏 **CloudKit from Android and the web** - the same [private database][ckdb] your iOS app writes to, over [CloudKit Web Services][ckws]. No other React Native library offers this.
32
- - 📂 **Files the user can actually see** - `icloudDocuments` writes into their iCloud Drive, visible in Files.app. A `CKAsset` is invisible to the user; this is the one thing no CloudKit API can do.
33
- - 🚨 **Errors you can act on** - every failure is a typed rejection (`ERR_NOT_SIGNED_IN`, `ERR_QUOTA_EXCEEDED`, `ERR_RATE_LIMITED` with `retryAfterMs`, ...). `null` means one thing only: the key does not exist - never "we could not reach the cloud".
34
- - 👤 **Real account lifecycle** - all five [`CKAccountStatus`][ckstatus] values, plus `onAccountChange` with an `identityChanged` flag. The store acts on it too: provider caches and queued writes belonging to the previous user are dropped, not leaked into the next account.
35
- - 🔔 **Remote change events** - `onRemoteChange` on every provider *and* on the facade, including Google Drive via its change cursor.
36
- - 📦 **Automatic size tiering** - small values to the key-value store, larger to a [`CKRecord`][ckrecord] field. Binary goes in as a [`CKAsset`][ckasset] or a resumable Drive upload. Store limits stop leaking into your product code.
37
- - 🔁 **Durable outbox** - retryable failures are queued and retried with backoff that honours server retry hints, drained automatically on foreground, bounded so it cannot grow forever, and never allowed to overwrite a newer write.
38
- - 🧺 **Batch operations** - `multiGet`/`multiSet`/`multiRemove`/`clear`, one request per provider that genuinely batches rather than a loop wearing a batch's clothes.
39
- - 🪝 **React hooks** - `useCloudItem`, `useAccountStatus`, `usePendingWrites`, from `/hooks`, without the stale-response and unmounted-`setState` bugs every hand-rolled version has.
40
- - 🔐 **Real end-to-end encryption** - `cloudKitEncrypted` uses CloudKit's own `encryptedValues`, so Apple stores ciphertext and holds no key, with nothing for you to manage. Everywhere else, a `codec` seam for a cipher you chose - because Drive's `appDataFolder` is plaintext to anything holding the OAuth token.
41
- - 🧪 **A real testing story** - an in-memory provider with fault injection plus the native mock itself, both exported from the package (`/testing`, `/jest-mock`), so signed-out, offline, quota-exceeded and account-switch paths are all testable in Jest.
42
- - ⚙️ **Old and new architecture** - React Native 0.71 through 0.86+, with the `#ifdef` bridge to prove it.
30
+ - ☁️ Four providers behind one API - [`NSUbiquitousKeyValueStore`][kvs] (Apple's small key-value iCloud store), [CloudKit][ck] records, [iCloud Drive][icdrive] documents, Google Drive [`appDataFolder`][appdata] - directly or through one facade.
31
+ - 🍏 CloudKit reaches Android and web too, via [CloudKit Web Services][ckws] - the same [private database][ckdb] your iOS app uses.
32
+ - 📂 `icloudDocuments` writes into the user's real iCloud Drive, visible in Files.app - unlike an invisible `CKAsset`.
33
+ - 🚨 Every failure is a typed rejection (`ERR_NOT_SIGNED_IN`, `ERR_QUOTA_EXCEEDED`, `ERR_RATE_LIMITED` with `retryAfterMs`, ...); `null` means only "key doesn't exist".
34
+ - 👤 All five [`CKAccountStatus`][ckstatus] values surface as-is, plus `onAccountChange` with `identityChanged`, which drops the previous account's caches and queued writes.
35
+ - 🔔 `onRemoteChange` fires on every provider and the facade, including Google Drive via its change cursor.
36
+ - 📦 Small values go to the key-value store, larger ones to a [`CKRecord`][ckrecord] field, binary as a [`CKAsset`][ckasset] or a resumable Drive upload - sized automatically.
37
+ - 🔁 Retryable failures queue into a durable outbox: backoff honours retry hints, auto-drains on foreground, bounded, never overwrites a newer write.
38
+ - 🧺 `multiGet`/`multiSet`/`multiRemove`/`clear` batch for real, one request per provider.
39
+ - 🪝 React hooks - `useCloudItem`, `useAccountStatus`, `usePendingWrites` from `/hooks` - without the stale-response and unmounted-`setState` bugs.
40
+ - 🔐 `cloudKitEncrypted` uses CloudKit's own `encryptedValues` - ciphertext only, no key exposed; elsewhere, a `codec` seam for your own cipher.
41
+ - 🧪 An in-memory provider with fault injection, plus the native mock, both exported (`/testing`, `/jest-mock`) - every failure path testable in Jest.
42
+ - ⚙️ React Native 0.71 through 0.86+, old and new architecture, with the `#ifdef` bridge to prove it.
43
43
 
44
44
  ## 💡 Why?
45
45
 
46
- Cloud storage in React Native is fragmented into single-provider wrappers, and almost all of them repeat the same handful of defects. Two independent libraries in this space ship a `setItem` that **reports a failed write as a success** - one checks the wrong error variable in its completion block, the other discards the operation result entirely. A third flattens five distinct iCloud account states into one boolean. A fourth has an open issue titled *"Idea: Listening for changes"* whose author replied *"Good idea, let's do it!"*, opened the PR himself, and left it unmerged for six months.
46
+ Cloud storage in React Native is fragmented into single-provider wrappers repeating the same defects: two ship a `setItem` that **reports a failed write as a success** (one checks the wrong error variable, the other discards the result entirely), and a third flattens five iCloud account states into one boolean.
47
47
 
48
- The common thread is that failure paths are treated as an afterthought. A `catch { return null }` makes "not signed in", "offline", "out of storage" and "no such key" indistinguishable - so apps cannot tell the user anything useful, and cannot decide whether to retry.
48
+ A `catch { return null }` makes "not signed in", "offline", "out of storage" and "no such key" indistinguishable - apps can't tell the user anything useful, or decide whether to retry.
49
49
 
50
- This library starts from the opposite end: the error contract first, then the providers.
50
+ This library starts from the opposite end: the error contract first, providers second.
51
51
 
52
52
  ## 📚 Upstream documentation
53
53
 
54
- This package is a wrapper. When something behaves unexpectedly, the answer is usually in Apple's or Google's documentation rather than ours - so here is where to look.
54
+ This package is a wrapper: unexpected behavior is usually explained in Apple's or Google's docs, not ours.
55
55
 
56
56
  **Apple**
57
57
 
58
58
  | | |
59
59
  |---|---|
60
- | [`NSUbiquitousKeyValueStore`][kvs] | The iCloud key-value store, and its 1 MB / 1024-key limits |
60
+ | [`NSUbiquitousKeyValueStore`][kvs] | The iCloud key-value store; 1 MB / 1024-key limits |
61
61
  | [CloudKit][ck] · [`CKDatabase`][ckdb] · [`CKRecord`][ckrecord] | Records in the user's private database |
62
62
  | [`CKAsset`][ckasset] · [`CKRecordZone`][ckzone] | Binary assets and custom zones |
63
63
  | [`CKAccountStatus`][ckstatus] | The five account states this package surfaces verbatim |
64
64
  | [CloudKit Web Services][ckws] | The REST API behind the Android and web paths |
65
- | [Authentication][ckauth] · [Data size limits][cklimits] · [Error codes][ckerrors] | The three pages worth reading before shipping CloudKit on Android |
65
+ | [Authentication][ckauth] · [Data size limits][cklimits] · [Error codes][ckerrors] | Worth reading before shipping CloudKit on Android |
66
66
  | [iCloud entitlements][entitlements] | The keys the config plugin writes |
67
67
  | [CloudKit Console][console] | Where containers, schemas, API tokens and the sign-in callback live |
68
68
 
@@ -72,7 +72,7 @@ This package is a wrapper. When something behaves unexpectedly, the answer is us
72
72
  |---|---|
73
73
  | [The `appDataFolder`][appdata] | The hidden per-app folder this package stores into |
74
74
  | [Drive `files` resource][drivefiles] | The REST endpoints behind the provider |
75
- | [Drive API scopes][drivescopes] | Why `drive.appdata` and not something broader |
75
+ | [Drive API scopes][drivescopes] | Why `drive.appdata`, not something broader |
76
76
 
77
77
  [kvs]: https://developer.apple.com/documentation/foundation/nsubiquitouskeyvaluestore
78
78
  [ck]: https://developer.apple.com/documentation/cloudkit
@@ -100,36 +100,36 @@ This package is a wrapper. When something behaves unexpectedly, the answer is us
100
100
  | CloudKit records | ✅ | – | ✅ | ✅ | – | ✅ |
101
101
  | Google Drive | ✅ | ✅ | – | – | – | – |
102
102
  | iOS | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ |
103
- | Android | ✅ | ✅ | – | ❌ [^1] | – | – |
104
- | Web | ✅ | partial [^2] | – | – | – | – |
105
- | **CloudKit on Android/web** | ✅ | – | – | ❌ [^1] | – | – |
103
+ | Android | ✅ | ✅ | – | ❌ [[1]](#note-1) | – | – |
104
+ | Web | ✅ | partial [[2]](#note-2) | – | – | – | – |
105
+ | **CloudKit on Android/web** | ✅ | – | – | ❌ [[1]](#note-1) | – | – |
106
106
  | New Architecture | ✅ | ✅ | ✅ | ✅ | ✅ | – |
107
- | **Legacy Architecture** | ✅ | ❌ | ✅ [^3] | ✅ [^3] | ✅ [^3] | ✅ |
107
+ | **Legacy Architecture** | ✅ | ❌ | ✅ [[3]](#note-3) | ✅ [[3]](#note-3) | ✅ [[3]](#note-3) | ✅ |
108
108
  | Typed error codes | ✅ | – | partial | ✅ | – | – |
109
109
  | 5-value account status | ✅ | boolean | boolean | ✅ | – | – |
110
- | Identity-change event | ✅ | ⚠️ [^4] | – | ✅ | – | – |
111
- | Remote-change event | ✅ | ✅ | – | n/a | ❌ [^5] | ✅ |
110
+ | Identity-change event | ✅ | ⚠️ [[4]](#note-4) | – | ✅ | – | – |
111
+ | Remote-change event | ✅ | ✅ | – | n/a | ❌ [[5]](#note-5) | ✅ |
112
112
  | Offline write queue | ✅ | – | – | ✅ | – | – |
113
113
  | Size tiering | ✅ | – | – | – | – | – |
114
- | Binary / assets | ✅ [^9] | ✅ | ❌ [^6] | ✅ | – | – |
114
+ | Binary / assets | ✅ [[9]](#note-9) | ✅ | ❌ [[6]](#note-6) | ✅ | – | – |
115
115
  | User-visible iCloud Drive files | ✅ | – | – | – | ✅ | – |
116
116
  | Native end-to-end encryption | ✅ | – | – | – | – | – |
117
117
  | Batch operations | ✅ | – | – | – | – | – |
118
118
  | React hooks | ✅ | ✅ | – | – | – | – |
119
119
  | Encryption seam | ✅ | – | – | – | – | – |
120
- | Exported test harness | ✅ | – | – | ⚠️ [^7] | – | – |
120
+ | Exported test harness | ✅ | – | – | ⚠️ [[7]](#note-7) | – | – |
121
121
  | Mac Catalyst | ✅ | – | – | ⚠️ | – | – |
122
- | Actively maintained | ✅ | ✅ | ✅ | ❌ [^8] | ❌ [^5] | ❌ |
123
-
124
- [^1]: expo-cloudkit's README states Android returns `CloudKitNotSupportedError` on every call.
125
- [^2]: Text-based Google Drive operations only.
126
- [^3]: Expo Modules API supports both architectures, but these packages require `expo-modules-core`.
127
- [^4]: The event exists and has crashed with `std::bad_function_call` (SIGABRT) when it fires before JS binds the emitter - reported independently three times.
128
- [^5]: One version ever published; the change-listener PR has been open since February.
129
- [^6]: Its field type is `string | number | null`, so binary data cannot be stored at all.
130
- [^7]: A mock factory exists but is not exported from the package entry and is not mentioned in the README.
131
- [^8]: No commits since April; four npm releases shipped with Swift that did not compile.
132
- [^9]: `CKAsset`, streamed from disk, on Apple platforms. Not yet implemented over CloudKit Web Services, so on Android and web asset calls reject with `ERR_UNSUPPORTED_PLATFORM` rather than appearing to work - use [`googleDriveFiles`](https://kesha-antonov.github.io/react-native-cloud-sync/providers/google-drive#large-files) for binaries there, which chunks and resumes the same way `CKAsset` does.
122
+ | Actively maintained | ✅ | ✅ | ✅ | ❌ [[8]](#note-8) | ❌ [[5]](#note-5) | ❌ |
123
+
124
+ <a id="note-1"></a>**[1]** expo-cloudkit's README: Android throws `CloudKitNotSupportedError` on every call.
125
+ <a id="note-2"></a>**[2]** Google Drive support is text-based only.
126
+ <a id="note-3"></a>**[3]** Via the Expo Modules API - pulls in `expo-modules-core`.
127
+ <a id="note-4"></a>**[4]** Fires before JS binds the emitter, crashing with `std::bad_function_call` (SIGABRT) - hit three times.
128
+ <a id="note-5"></a>**[5]** One version ever shipped; the change-listener PR has sat open since February.
129
+ <a id="note-6"></a>**[6]** Field type is `string | number | null` - can't hold binary data.
130
+ <a id="note-7"></a>**[7]** A mock factory exists, but isn't exported or documented.
131
+ <a id="note-8"></a>**[8]** No commits since April; the last four releases shipped with Swift that didn't compile.
132
+ <a id="note-9"></a>**[9]** `CKAsset` on Apple platforms; CloudKit Web Services' upload-token protocol on Android/web, capped at 15 MB (CloudKit's limit, not this package's). Use [`googleDriveFiles`](https://kesha-antonov.github.io/react-native-cloud-sync/providers/google-drive#large-files) for anything bigger - it chunks and resumes the same way.
133
133
 
134
134
  [kuatsu]: https://github.com/kuatsu/react-native-cloud-storage
135
135
  [ik]: https://github.com/BogdanGeorgian91/react-native-icloud-kit
@@ -141,14 +141,14 @@ This package is a wrapper. When something behaves unexpectedly, the answer is us
141
141
 
142
142
  | | |
143
143
  |---|---|
144
- | [Choosing a provider](https://kesha-antonov.github.io/react-native-cloud-sync/choosing-a-provider) | Which one, what each costs you, and why to let the user pick |
144
+ | [Choosing a provider](https://kesha-antonov.github.io/react-native-cloud-sync/choosing-a-provider) | Which one, what it costs, why to let the user pick |
145
145
  | [iCloud key-value store](https://kesha-antonov.github.io/react-native-cloud-sync/providers/icloud-kv) | Small settings, zero friction, Apple only |
146
146
  | [CloudKit](https://kesha-antonov.github.io/react-native-cloud-sync/providers/cloudkit) | Records, zones, assets - and the Android/web path |
147
147
  | [iCloud Drive](https://kesha-antonov.github.io/react-native-cloud-sync/providers/icloud-drive) | Files in the user's own Drive, visible in Files.app |
148
148
  | [Google Drive](https://kesha-antonov.github.io/react-native-cloud-sync/providers/google-drive) | The always-on cross-platform backend |
149
149
  | [The store facade](https://kesha-antonov.github.io/react-native-cloud-sync/store) | Tiering, outbox, migration, fallthrough |
150
150
  | [Error handling](https://kesha-antonov.github.io/react-native-cloud-sync/errors) | The typed contract |
151
- | [Encryption](https://kesha-antonov.github.io/react-native-cloud-sync/encryption) | What is encrypted for you, and how to add end-to-end yourself |
151
+ | [Encryption](https://kesha-antonov.github.io/react-native-cloud-sync/encryption) | What's encrypted for you, and how to add your own |
152
152
  | [React hooks](https://kesha-antonov.github.io/react-native-cloud-sync/hooks) | Binding cloud state to components |
153
153
  | [Recipes](https://kesha-antonov.github.io/react-native-cloud-sync/recipes) | Backup/restore, migration, offline-first |
154
154
  | [Testing](https://kesha-antonov.github.io/react-native-cloud-sync/testing) | Fault injection without a device |
@@ -164,7 +164,7 @@ This package is a wrapper. When something behaves unexpectedly, the answer is us
164
164
  | iOS | 15.1 |
165
165
  | Node | 20 |
166
166
 
167
- Both architectures are supported. React Native 0.82 removed the Legacy Architecture, so that half matters only on 0.81 and below.
167
+ Both architectures supported; RN 0.82 removed Legacy Architecture, so that half only matters on 0.81 and below.
168
168
 
169
169
  ### Platform support per provider
170
170
 
@@ -176,7 +176,7 @@ Both architectures are supported. React Native 0.82 removed the Legacy Architect
176
176
  | `icloudDocuments` | native | – | – |
177
177
  | `googleDrive` | REST | REST | REST |
178
178
 
179
- Where a provider is unavailable it rejects with `ERR_UNSUPPORTED_PLATFORM` rather than silently doing nothing. [Choosing a provider](https://kesha-antonov.github.io/react-native-cloud-sync/choosing-a-provider) covers the trade-offs.
179
+ An unavailable provider rejects with `ERR_UNSUPPORTED_PLATFORM` rather than silently no-op'ing - [Choosing a provider](https://kesha-antonov.github.io/react-native-cloud-sync/choosing-a-provider) covers the trade-offs.
180
180
 
181
181
  ## 📦 Installation
182
182
 
@@ -198,13 +198,13 @@ Add the config plugin, then rebuild:
198
198
  }
199
199
  ```
200
200
 
201
- Bare React Native, and the raw entitlement keys if you manage `ios/` yourself: see [Installation](https://kesha-antonov.github.io/react-native-cloud-sync/installation).
201
+ Bare React Native and manual `ios/` entitlement keys: see [Installation](https://kesha-antonov.github.io/react-native-cloud-sync/installation).
202
202
 
203
203
  ## 🚀 Quick start
204
204
 
205
205
  ### iCloud key-value store
206
206
 
207
- No sign-in, no UI - it uses the account already on the device.
207
+ No sign-in, no UI - uses the device's existing account.
208
208
 
209
209
  ```ts
210
210
  import { icloudKV } from 'react-native-cloud-sync'
@@ -232,7 +232,7 @@ const raw = await cloudKit.getItem('playlist')
232
232
  await cloudKitAssets.save({ recordName: 'avatar', fieldName: 'image', fileUri })
233
233
  ```
234
234
 
235
- On Android and web this needs an Apple ID sign-in whose token lasts at most two weeks, so treat it as an explicit import rather than background sync. [Full guide →](https://kesha-antonov.github.io/react-native-cloud-sync/providers/cloudkit)
235
+ Android/web needs an Apple ID sign-in whose token lasts up to two weeks - an explicit import, not background sync. [Full guide →](https://kesha-antonov.github.io/react-native-cloud-sync/providers/cloudkit)
236
236
 
237
237
  ### Sensitive data
238
238
 
@@ -244,7 +244,7 @@ import { cloudKitEncrypted } from 'react-native-cloud-sync'
244
244
  await cloudKitEncrypted.setItem('auth.refreshToken', token)
245
245
  ```
246
246
 
247
- Apple-only by construction: the key lives in the user's iCloud Keychain, so nothing server-side can decrypt it. For cross-platform encryption, the store takes a `codec`. [Full guide →](https://kesha-antonov.github.io/react-native-cloud-sync/encryption)
247
+ Apple-only: the key lives in the user's iCloud Keychain, so nothing server-side can decrypt it. Cross-platform needs the store's `codec` seam instead. [Full guide →](https://kesha-antonov.github.io/react-native-cloud-sync/encryption)
248
248
 
249
249
  ### iCloud Drive
250
250
 
@@ -294,7 +294,7 @@ await store.setItem('playlist', json)
294
294
  await store.flushOutbox() // on reconnect
295
295
  ```
296
296
 
297
- Those two options are what make sync work in **both** directions across a mixed fleet - an Android phone and an iPad, a browser and a Mac. `mirror` puts a copy in Drive so a non-Apple device has something to read; `resolve` stops an Apple device serving its own stale iCloud copy without ever consulting Drive. Either platform can be the one the user started on. [Full guide →](https://kesha-antonov.github.io/react-native-cloud-sync/store)
297
+ Those two options make sync work in **both** directions across a mixed fleet: `mirror` copies to Drive so non-Apple devices can read it; `resolve` stops an Apple device serving a stale iCloud copy without checking Drive. Either platform can be where the user started. [Full guide →](https://kesha-antonov.github.io/react-native-cloud-sync/store)
298
298
 
299
299
  ### In a component
300
300
 
@@ -304,7 +304,7 @@ import { useCloudItem } from 'react-native-cloud-sync/hooks'
304
304
  const { value, setValue, loading, error } = useCloudItem<Settings>(store, 'settings')
305
305
  ```
306
306
 
307
- Re-reads when another device writes, drops stale responses, and never calls `setState` after unmount. [Full guide →](https://kesha-antonov.github.io/react-native-cloud-sync/hooks)
307
+ Re-reads on remote writes, drops stale responses, never calls `setState` after unmount. [Full guide →](https://kesha-antonov.github.io/react-native-cloud-sync/hooks)
308
308
 
309
309
  ### Handling failures
310
310
 
@@ -334,11 +334,11 @@ const provider = createMemoryProvider({
334
334
  provider.emitAccountChange({ status: 'available', identityChanged: true })
335
335
  ```
336
336
 
337
- Signed-out, offline, quota-exceeded, rate-limited and account-switch paths, all in Jest without a device. [Full guide →](https://kesha-antonov.github.io/react-native-cloud-sync/testing)
337
+ Signed-out, offline and account-switch paths, all in Jest without a device. [Full guide →](https://kesha-antonov.github.io/react-native-cloud-sync/testing)
338
338
 
339
339
  ## 🧪 Example App
340
340
 
341
- A playground covering every API, plus a live sync demo built for side-by-side recording:
341
+ A playground covering every API, plus a live sync demo for side-by-side recording:
342
342
 
343
343
  ```sh
344
344
  cd example
@@ -346,7 +346,7 @@ yarn installDevBuild:ios # or :android
346
346
  yarn start:web
347
347
  ```
348
348
 
349
- Tabs: **Sync** (shared counter across devices, including a one-tap mirror mode that writes to iCloud and Drive at once), **iCloud KV**, **CloudKit**, **Drive**, **Files** (large-file backup/restore, including a working `GoogleDriveFileAdapter`), **Store** and **Faults**.
349
+ Tabs: **Sync** (shared counter, one-tap mirror mode to iCloud+Drive), **iCloud KV**, **CloudKit**, **Drive**, **Files** (large-file backup/restore via `GoogleDriveFileAdapter`), **Store**, **Faults**.
350
350
 
351
351
  <p align="center">
352
352
  <img src="assets/screenshots/sync.png" width="18%" alt="Sync demo tab - shared counter with mirror provider selection" />&nbsp;&nbsp;<img src="assets/screenshots/icloud-kv.png" width="18%" alt="iCloud key-value store tab" />&nbsp;&nbsp;<img src="assets/screenshots/cloudkit.png" width="18%" alt="CloudKit tab - record read/write and oversized-write handling" />&nbsp;&nbsp;<img src="assets/screenshots/drive.png" width="18%" alt="Google Drive tab - OAuth token configuration and file operations" />&nbsp;&nbsp;<img src="assets/screenshots/store.png" width="18%" alt="Store facade tab - size tiering across providers" />
@@ -10,6 +10,7 @@ exports.configureGoogleDriveFiles = configureGoogleDriveFiles;
10
10
  exports.getCloudKitClient = getCloudKitClient;
11
11
  exports.getGoogleDriveClient = getGoogleDriveClient;
12
12
  exports.getGoogleDriveFileAdapter = getGoogleDriveFileAdapter;
13
+ exports.getSharedFileAdapter = void 0;
13
14
  exports.isCloudKitConfigured = isCloudKitConfigured;
14
15
  exports.isGoogleDriveConfigured = isGoogleDriveConfigured;
15
16
  exports.isGoogleDriveFilesConfigured = isGoogleDriveFilesConfigured;
@@ -67,11 +68,20 @@ function configureGoogleDriveFiles(adapter) {
67
68
  driveFileAdapter = adapter;
68
69
  }
69
70
  function getGoogleDriveFileAdapter() {
70
- if (driveFileAdapter == null) throw new _errors.CloudSyncError(_errors.ErrorCode.CONTAINER_MISCONFIGURED, '[RNCloudSync] googleDriveFiles needs a file adapter. Call configureGoogleDriveFiles({ ' + 'statSize, readChunk, writeChunk, appendChunk }) before saving or fetching a file.', {
71
+ if (driveFileAdapter == null) throw new _errors.CloudSyncError(_errors.ErrorCode.CONTAINER_MISCONFIGURED, '[RNCloudSync] This needs a file adapter. Call configureGoogleDriveFiles({ ' + 'statSize, readChunk, writeChunk, appendChunk }) before saving or fetching a file - shared ' + 'by googleDriveFiles and by cloudKitAssets on Android/web.', {
71
72
  provider: 'googleDrive'
72
73
  });
73
74
  return driveFileAdapter;
74
75
  }
76
+
77
+ /**
78
+ * Same adapter and same `configureGoogleDriveFiles` call, under a name that
79
+ * doesn't imply it's Drive-specific. `cloudKitAssets`'s REST path (Android/web)
80
+ * reads and writes local files the exact same way `googleDriveFiles` does, and
81
+ * asking a host app to register two near-identical adapters for that would be
82
+ * pure friction for no benefit.
83
+ */
84
+ const getSharedFileAdapter = exports.getSharedFileAdapter = getGoogleDriveFileAdapter;
75
85
  function isGoogleDriveFilesConfigured() {
76
86
  return driveFileAdapter != null;
77
87
  }
@@ -1 +1 @@
1
- {"version":3,"names":["_cloudKitRest","require","_googleDriveRest","_errors","cloudKitClient","driveClient","driveFileAdapter","configureCloudKit","config","CloudKitRestClient","getCloudKitClient","CloudSyncError","ErrorCode","CONTAINER_MISCONFIGURED","provider","isCloudKitConfigured","configureGoogleDrive","GoogleDriveClient","getGoogleDriveClient","isGoogleDriveConfigured","configureGoogleDriveFiles","adapter","getGoogleDriveFileAdapter","isGoogleDriveFilesConfigured","__resetConfig"],"sourceRoot":"../../src","sources":["config.ts"],"mappings":";;;;;;;;;;;;;;;AACA,IAAAA,aAAA,GAAAC,OAAA;AAEA,IAAAC,gBAAA,GAAAD,OAAA;AACA,IAAAE,OAAA,GAAAF,OAAA;AAEA,IAAIG,cAAyC,GAAG,IAAI;AACpD,IAAIC,WAAqC,GAAG,IAAI;AAChD,IAAIC,gBAA+C,GAAG,IAAI;;AAE1D;AACA;AACA;AACA;AACA;AACA;AACA;AACO,SAASC,iBAAiBA,CAACC,MAA0B,EAAQ;EAClEJ,cAAc,GAAG,IAAIK,gCAAkB,CAACD,MAAM,CAAC;AACjD;AAEO,SAASE,iBAAiBA,CAAA,EAAuB;EACtD,IAAIN,cAAc,IAAI,IAAI,EACxB,MAAM,IAAIO,sBAAc,CACtBC,iBAAS,CAACC,uBAAuB,EACjC,sFAAsF,GACpF,wFAAwF,GACxF,6BAA6B,EAC/B;IAAEC,QAAQ,EAAE;EAAW,CACzB,CAAC;EAEH,OAAOV,cAAc;AACvB;AAEO,SAASW,oBAAoBA,CAAA,EAAY;EAC9C,OAAOX,cAAc,IAAI,IAAI;AAC/B;;AAEA;AACO,SAASY,oBAAoBA,CAACR,MAAyB,EAAQ;EACpEH,WAAW,GAAG,IAAIY,kCAAiB,CAACT,MAAM,CAAC;AAC7C;AAEO,SAASU,oBAAoBA,CAAA,EAAsB;EACxD,IAAIb,WAAW,IAAI,IAAI,EACrB,MAAM,IAAIM,sBAAc,CACtBC,iBAAS,CAACC,uBAAuB,EACjC,4EAA4E,GAC1E,0DAA0D,EAC5D;IAAEC,QAAQ,EAAE;EAAc,CAC5B,CAAC;EAEH,OAAOT,WAAW;AACpB;AAEO,SAASc,uBAAuBA,CAAA,EAAY;EACjD,OAAOd,WAAW,IAAI,IAAI;AAC5B;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACO,SAASe,yBAAyBA,CAACC,OAA+B,EAAQ;EAC/Ef,gBAAgB,GAAGe,OAAO;AAC5B;AAEO,SAASC,yBAAyBA,CAAA,EAA2B;EAClE,IAAIhB,gBAAgB,IAAI,IAAI,EAC1B,MAAM,IAAIK,sBAAc,CACtBC,iBAAS,CAACC,uBAAuB,EACjC,wFAAwF,GACtF,mFAAmF,EACrF;IAAEC,QAAQ,EAAE;EAAc,CAC5B,CAAC;EAEH,OAAOR,gBAAgB;AACzB;AAEO,SAASiB,4BAA4BA,CAAA,EAAY;EACtD,OAAOjB,gBAAgB,IAAI,IAAI;AACjC;;AAEA;AACO,SAASkB,aAAaA,CAAA,EAAS;EACpCpB,cAAc,GAAG,IAAI;EACrBC,WAAW,GAAG,IAAI;EAClBC,gBAAgB,GAAG,IAAI;AACzB","ignoreList":[]}
1
+ {"version":3,"names":["_cloudKitRest","require","_googleDriveRest","_errors","cloudKitClient","driveClient","driveFileAdapter","configureCloudKit","config","CloudKitRestClient","getCloudKitClient","CloudSyncError","ErrorCode","CONTAINER_MISCONFIGURED","provider","isCloudKitConfigured","configureGoogleDrive","GoogleDriveClient","getGoogleDriveClient","isGoogleDriveConfigured","configureGoogleDriveFiles","adapter","getGoogleDriveFileAdapter","getSharedFileAdapter","exports","isGoogleDriveFilesConfigured","__resetConfig"],"sourceRoot":"../../src","sources":["config.ts"],"mappings":";;;;;;;;;;;;;;;;AACA,IAAAA,aAAA,GAAAC,OAAA;AAEA,IAAAC,gBAAA,GAAAD,OAAA;AACA,IAAAE,OAAA,GAAAF,OAAA;AAEA,IAAIG,cAAyC,GAAG,IAAI;AACpD,IAAIC,WAAqC,GAAG,IAAI;AAChD,IAAIC,gBAA+C,GAAG,IAAI;;AAE1D;AACA;AACA;AACA;AACA;AACA;AACA;AACO,SAASC,iBAAiBA,CAACC,MAA0B,EAAQ;EAClEJ,cAAc,GAAG,IAAIK,gCAAkB,CAACD,MAAM,CAAC;AACjD;AAEO,SAASE,iBAAiBA,CAAA,EAAuB;EACtD,IAAIN,cAAc,IAAI,IAAI,EACxB,MAAM,IAAIO,sBAAc,CACtBC,iBAAS,CAACC,uBAAuB,EACjC,sFAAsF,GACpF,wFAAwF,GACxF,6BAA6B,EAC/B;IAAEC,QAAQ,EAAE;EAAW,CACzB,CAAC;EAEH,OAAOV,cAAc;AACvB;AAEO,SAASW,oBAAoBA,CAAA,EAAY;EAC9C,OAAOX,cAAc,IAAI,IAAI;AAC/B;;AAEA;AACO,SAASY,oBAAoBA,CAACR,MAAyB,EAAQ;EACpEH,WAAW,GAAG,IAAIY,kCAAiB,CAACT,MAAM,CAAC;AAC7C;AAEO,SAASU,oBAAoBA,CAAA,EAAsB;EACxD,IAAIb,WAAW,IAAI,IAAI,EACrB,MAAM,IAAIM,sBAAc,CACtBC,iBAAS,CAACC,uBAAuB,EACjC,4EAA4E,GAC1E,0DAA0D,EAC5D;IAAEC,QAAQ,EAAE;EAAc,CAC5B,CAAC;EAEH,OAAOT,WAAW;AACpB;AAEO,SAASc,uBAAuBA,CAAA,EAAY;EACjD,OAAOd,WAAW,IAAI,IAAI;AAC5B;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACO,SAASe,yBAAyBA,CAACC,OAA+B,EAAQ;EAC/Ef,gBAAgB,GAAGe,OAAO;AAC5B;AAEO,SAASC,yBAAyBA,CAAA,EAA2B;EAClE,IAAIhB,gBAAgB,IAAI,IAAI,EAC1B,MAAM,IAAIK,sBAAc,CACtBC,iBAAS,CAACC,uBAAuB,EACjC,4EAA4E,GAC1E,4FAA4F,GAC5F,2DAA2D,EAC7D;IAAEC,QAAQ,EAAE;EAAc,CAC5B,CAAC;EAEH,OAAOR,gBAAgB;AACzB;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACO,MAAMiB,oBAAoB,GAAAC,OAAA,CAAAD,oBAAA,GAAGD,yBAAyB;AAEtD,SAASG,4BAA4BA,CAAA,EAAY;EACtD,OAAOnB,gBAAgB,IAAI,IAAI;AACjC;;AAEA;AACO,SAASoB,aAAaA,CAAA,EAAS;EACpCtB,cAAc,GAAG,IAAI;EACrBC,WAAW,GAAG,IAAI;EAClBC,gBAAgB,GAAG,IAAI;AACzB","ignoreList":[]}
@@ -1 +1 @@
1
- {"version":3,"names":["_icloudKV","require","_cloudKit","_cloudKitBackup","_cloudKitEncrypted","_icloudDocuments","_googleDrive","_googleDriveFiles","_memory","_store","_resolvers","_keys","_config","_base","_errors","_types","_logger"],"sourceRoot":"../../src","sources":["index.ts"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAQA,IAAAA,SAAA,GAAAC,OAAA;AAKA,IAAAC,SAAA,GAAAD,OAAA;AAMA,IAAAE,eAAA,GAAAF,OAAA;AACA,IAAAG,kBAAA,GAAAH,OAAA;AACA,IAAAI,gBAAA,GAAAJ,OAAA;AACA,IAAAK,YAAA,GAAAL,OAAA;AACA,IAAAM,iBAAA,GAAAN,OAAA;AACA,IAAAO,OAAA,GAAAP,OAAA;AAGA,IAAAQ,MAAA,GAAAR,OAAA;AAQA,IAAAS,UAAA,GAAAT,OAAA;AASA,IAAAU,KAAA,GAAAV,OAAA;AAWA,IAAAW,OAAA,GAAAX,OAAA;AAgBA,IAAAY,KAAA,GAAAZ,OAAA;AAGA,IAAAa,OAAA,GAAAb,OAAA;AAqCA,IAAAc,MAAA,GAAAd,OAAA;AAEA,IAAAe,OAAA,GAAAf,OAAA","ignoreList":[]}
1
+ {"version":3,"names":["_icloudKV","require","_cloudKit","_cloudKitBackup","_cloudKitEncrypted","_icloudDocuments","_googleDrive","_googleDriveFiles","_memory","_store","_resolvers","_keys","_config","_base","_errors","_types","_logger"],"sourceRoot":"../../src","sources":["index.ts"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAQA,IAAAA,SAAA,GAAAC,OAAA;AAKA,IAAAC,SAAA,GAAAD,OAAA;AAMA,IAAAE,eAAA,GAAAF,OAAA;AACA,IAAAG,kBAAA,GAAAH,OAAA;AACA,IAAAI,gBAAA,GAAAJ,OAAA;AACA,IAAAK,YAAA,GAAAL,OAAA;AACA,IAAAM,iBAAA,GAAAN,OAAA;AACA,IAAAO,OAAA,GAAAP,OAAA;AAGA,IAAAQ,MAAA,GAAAR,OAAA;AAQA,IAAAS,UAAA,GAAAT,OAAA;AASA,IAAAU,KAAA,GAAAV,OAAA;AAWA,IAAAW,OAAA,GAAAX,OAAA;AAkBA,IAAAY,KAAA,GAAAZ,OAAA;AAGA,IAAAa,OAAA,GAAAb,OAAA;AAqCA,IAAAc,MAAA,GAAAd,OAAA;AAEA,IAAAe,OAAA,GAAAf,OAAA","ignoreList":[]}
@@ -3,7 +3,7 @@
3
3
  Object.defineProperty(exports, "__esModule", {
4
4
  value: true
5
5
  });
6
- exports.VALUE_FIELD = exports.RECORD_TYPE_DEFAULT = exports.MAX_RECORD_BYTES = exports.CloudKitRestClient = void 0;
6
+ exports.VALUE_FIELD = exports.RECORD_TYPE_DEFAULT = exports.MAX_RECORD_BYTES = exports.MAX_ASSET_UPLOAD_BYTES = exports.CloudKitRestClient = void 0;
7
7
  Object.defineProperty(exports, "byteLength", {
8
8
  enumerable: true,
9
9
  get: function () {
@@ -37,6 +37,22 @@ const DEFAULT_TIMEOUT_MS = 30_000;
37
37
  * user-token mode needs no crypto at all: two query parameters on a `fetch`.
38
38
  */
39
39
 
40
+ /**
41
+ * CloudKit Web Services' own ceiling on a single asset upload, undocumented
42
+ * anywhere except the upload endpoint's own reference page: 15 MB, and the
43
+ * upload URL it hands out is valid for 15 minutes. Native `CKAsset` has no such
44
+ * limit - this is specific to the REST upload-token protocol.
45
+ */
46
+ const MAX_ASSET_UPLOAD_BYTES = exports.MAX_ASSET_UPLOAD_BYTES = 15 * 1024 * 1024;
47
+
48
+ /**
49
+ * The "Asset Dictionary" CloudKit Web Services deals in - what the upload
50
+ * endpoint returns after receiving bytes, and what a fetched record's Asset
51
+ * field value looks like. Passed back verbatim as a record field's value to
52
+ * attach an upload to a record; never reconstructed field-by-field, since it
53
+ * is an opaque blob the server itself validates.
54
+ */
55
+
40
56
  /**
41
57
  * How many operations one `/records/modify` or `/records/lookup` call carries.
42
58
  *
@@ -136,6 +152,27 @@ class CloudKitRestClient {
136
152
  return new _errors.CloudSyncError(_errors.ErrorCode.UNKNOWN, message, base);
137
153
  }
138
154
  }
155
+
156
+ /**
157
+ * HTTP-status classification for a response with no CloudKit error envelope
158
+ * of its own to inspect - `post()`'s fallback tail, and the raw asset-bytes
159
+ * transfer, which talks to an opaque single-use upload/download URL rather
160
+ * than a `/records/...` JSON endpoint.
161
+ */
162
+ async classifyHttpStatus(status) {
163
+ if (status === 401 || status === 421) {
164
+ await this.handleAuthExpired();
165
+ return new _errors.CloudSyncError(_errors.ErrorCode.AUTH_EXPIRED, `[RNCloudSync] CloudKit returned HTTP ${status}; the web auth token is no longer valid.`, {
166
+ provider: 'cloudKit'
167
+ });
168
+ }
169
+ if (status === 429 || status === 503) return new _errors.CloudSyncError(_errors.ErrorCode.RATE_LIMITED, `[RNCloudSync] CloudKit returned HTTP ${status}.`, {
170
+ provider: 'cloudKit'
171
+ });
172
+ return new _errors.CloudSyncError(_errors.ErrorCode.UNKNOWN, `[RNCloudSync] CloudKit returned HTTP ${status}.`, {
173
+ provider: 'cloudKit'
174
+ });
175
+ }
139
176
  async post(path, body) {
140
177
  const token = await this.requireAuthToken();
141
178
  const url = `${this.baseUrl()}${path}` + `?ckAPIToken=${encodeURIComponent(this.config.apiToken)}` + `&ckWebAuthToken=${encodeURIComponent(token)}`;
@@ -163,21 +200,9 @@ class CloudKitRestClient {
163
200
  // reach - 421 responses carry no `records`, so an error nested-lookup misses
164
201
  // it entirely. Check the root BEFORE looking at per-record results.
165
202
  if (json?.serverErrorCode != null) throw await this.toError(json.serverErrorCode, json.reason, json.retryAfter);
166
- if (!res.ok) {
167
- // HTTP-level failure with no parseable CloudKit error body.
168
- if (res.status === 401 || res.status === 421) {
169
- await this.handleAuthExpired();
170
- throw new _errors.CloudSyncError(_errors.ErrorCode.AUTH_EXPIRED, `[RNCloudSync] CloudKit returned HTTP ${res.status}; the web auth token is no longer valid.`, {
171
- provider: 'cloudKit'
172
- });
173
- }
174
- if (res.status === 429 || res.status === 503) throw new _errors.CloudSyncError(_errors.ErrorCode.RATE_LIMITED, `[RNCloudSync] CloudKit returned HTTP ${res.status}.`, {
175
- provider: 'cloudKit'
176
- });
177
- throw new _errors.CloudSyncError(_errors.ErrorCode.UNKNOWN, `[RNCloudSync] CloudKit returned HTTP ${res.status}.`, {
178
- provider: 'cloudKit'
179
- });
180
- }
203
+
204
+ // HTTP-level failure with no parseable CloudKit error body.
205
+ if (!res.ok) throw await this.classifyHttpStatus(res.status);
181
206
  return json ?? {};
182
207
  }
183
208
  async getRecord(recordName, recordType = RECORD_TYPE_DEFAULT) {
@@ -324,14 +349,25 @@ class CloudKitRestClient {
324
349
  limitBytes: MAX_RECORD_BYTES,
325
350
  actualBytes: bytes
326
351
  });
352
+ await this.saveFields(recordName, {
353
+ [VALUE_FIELD]: {
354
+ value
355
+ }
356
+ }, recordType);
357
+ }
358
+
359
+ /**
360
+ * Creates `recordName`, falling back to an unconditional update when it
361
+ * already exists - the create-then-fall-back dance every write after the
362
+ * first one takes. Shared by {@link saveRecord} (a `value` field) and
363
+ * {@link uploadAsset} (an Asset field plus its `__size` sidecar), which need
364
+ * the exact same dance for a different field set.
365
+ */
366
+ async saveFields(recordName, fields, recordType) {
327
367
  const record = {
328
368
  recordType,
329
369
  recordName,
330
- fields: {
331
- [VALUE_FIELD]: {
332
- value
333
- }
334
- }
370
+ fields
335
371
  };
336
372
 
337
373
  // `atomic` defaults to true server-side. Setting it explicitly documents the
@@ -378,6 +414,154 @@ class CloudKitRestClient {
378
414
  }
379
415
  }
380
416
 
417
+ /**
418
+ * Uploads `bytes` as `fieldName` on `recordName`, via CloudKit Web Services'
419
+ * asset-upload protocol: request a single-use upload URL, POST the raw bytes
420
+ * to it, then attach the descriptor it returns (plus a `__size` sidecar, so
421
+ * a later {@link fetchAsset} can report real download progress) to the
422
+ * record - the same create-then-update dance {@link saveRecord} uses.
423
+ *
424
+ * `onProgress` reports real bytes transferred, via `XMLHttpRequest` rather
425
+ * than `fetch` - see {@link CloudKitRestConfig.xhrImpl}.
426
+ */
427
+ async uploadAsset(recordName, fieldName, bytes, onProgress, recordType = RECORD_TYPE_DEFAULT) {
428
+ if (bytes.length > MAX_ASSET_UPLOAD_BYTES) throw new _errors.CloudSyncError(_errors.ErrorCode.PAYLOAD_TOO_LARGE, `[RNCloudSync] Asset is ${bytes.length} bytes; CloudKit Web Services caps a single asset ` + `upload at ${MAX_ASSET_UPLOAD_BYTES} bytes. Use the googleDrive provider for larger files ` + `on Android and web.`, {
429
+ provider: 'cloudKit',
430
+ limitBytes: MAX_ASSET_UPLOAD_BYTES,
431
+ actualBytes: bytes.length
432
+ });
433
+ const uploadUrl = await this.requestAssetUploadUrl(recordType, recordName, fieldName);
434
+ const descriptor = await this.putAssetBytes(uploadUrl, bytes, onProgress);
435
+ await this.saveFields(recordName, {
436
+ [fieldName]: {
437
+ value: descriptor
438
+ },
439
+ [`${fieldName}__size`]: {
440
+ value: bytes.length
441
+ }
442
+ }, recordType);
443
+ }
444
+
445
+ /**
446
+ * Downloads the bytes behind `fieldName` on `recordName`, or `null` when the
447
+ * record or the field's asset does not exist.
448
+ *
449
+ * A fetched record's Asset field carries a `downloadURL` - that is the only
450
+ * step this needs beyond the usual record lookup; there is no separate
451
+ * "request a download token" round trip the way upload has one.
452
+ */
453
+ async fetchAsset(recordName, fieldName, onProgress, recordType = RECORD_TYPE_DEFAULT) {
454
+ void recordType;
455
+ const json = await this.post('/records/lookup', {
456
+ records: [{
457
+ recordName
458
+ }]
459
+ });
460
+ const record = json.records?.find(r => r.recordName === recordName) ?? json.records?.[0];
461
+ if (record == null) return null;
462
+ if (record.serverErrorCode != null) {
463
+ if (record.serverErrorCode === 'NOT_FOUND') return null;
464
+ throw await this.toError(record.serverErrorCode, record.reason, record.retryAfter);
465
+ }
466
+ const asset = record.fields?.[fieldName]?.value;
467
+ if (asset?.downloadURL == null) return null;
468
+ return await this.fetchAssetBytes(asset.downloadURL, onProgress);
469
+ }
470
+ async requestAssetUploadUrl(recordType, recordName, fieldName) {
471
+ const json = await this.post('/assets/upload', {
472
+ tokens: [{
473
+ recordType,
474
+ recordName,
475
+ fieldName
476
+ }]
477
+ });
478
+ const url = json.tokens?.[0]?.url;
479
+ if (url == null) throw new _errors.CloudSyncError(_errors.ErrorCode.UNKNOWN, '[RNCloudSync] CloudKit did not return an asset upload URL.', {
480
+ provider: 'cloudKit'
481
+ });
482
+ return url;
483
+ }
484
+ get xhr() {
485
+ return this.config.xhrImpl ?? (() => new XMLHttpRequest());
486
+ }
487
+
488
+ /**
489
+ * POSTs raw bytes to a single-use CKWS asset-upload URL, reporting real
490
+ * upload progress via `XMLHttpRequest.upload.onprogress` - `fetch` exposes no
491
+ * upload-progress events in React Native. Scoped to just this one call:
492
+ * every other CloudKit REST request stays on `fetch` through `post()`, for
493
+ * the timeout/error handling already built there.
494
+ */
495
+ putAssetBytes(url, bytes, onProgress) {
496
+ return new Promise((resolve, reject) => {
497
+ const req = this.xhr();
498
+ req.open('POST', url);
499
+ req.timeout = this.config.timeoutMs ?? DEFAULT_TIMEOUT_MS;
500
+ req.upload.onprogress = e => {
501
+ if (e.lengthComputable) onProgress?.(e.loaded, e.total);
502
+ };
503
+ req.onload = () => {
504
+ if (req.status < 200 || req.status >= 300) {
505
+ this.classifyHttpStatus(req.status).then(reject).catch(reject);
506
+ return;
507
+ }
508
+ try {
509
+ const json = JSON.parse(req.responseText);
510
+ if (json.singleFile == null) throw new Error('response had no singleFile');
511
+ onProgress?.(bytes.length, bytes.length);
512
+ resolve(json.singleFile);
513
+ } catch (e) {
514
+ reject(new _errors.CloudSyncError(_errors.ErrorCode.UNKNOWN, '[RNCloudSync] CloudKit did not return an asset descriptor after upload.', {
515
+ provider: 'cloudKit',
516
+ cause: e
517
+ }));
518
+ }
519
+ };
520
+ req.onerror = () => reject(new _errors.CloudSyncError(_errors.ErrorCode.NETWORK_UNAVAILABLE, '[RNCloudSync] CloudKit asset upload failed to reach the server.', {
521
+ provider: 'cloudKit'
522
+ }));
523
+ req.ontimeout = () => reject((0, _errors.timedOut)(req.timeout, 'cloudKit'));
524
+ req.send(bytes);
525
+ });
526
+ }
527
+
528
+ /**
529
+ * GETs raw bytes from a record's asset `downloadURL`, reporting real
530
+ * download progress via `XMLHttpRequest.onprogress`, for the same reason
531
+ * {@link putAssetBytes} uses XHR rather than `fetch`.
532
+ *
533
+ * Treated as self-contained, the same way the upload URL is (Apple's own
534
+ * reference issues that one with no `ckAPIToken`/`ckWebAuthToken` at all) -
535
+ * if that assumption is ever wrong for a download URL specifically, it
536
+ * surfaces as an HTTP-level auth failure here rather than a silent wrong
537
+ * answer.
538
+ */
539
+ fetchAssetBytes(url, onProgress) {
540
+ return new Promise((resolve, reject) => {
541
+ const req = this.xhr();
542
+ req.open('GET', url);
543
+ req.responseType = 'arraybuffer';
544
+ req.timeout = this.config.timeoutMs ?? DEFAULT_TIMEOUT_MS;
545
+ req.onprogress = e => {
546
+ if (e.lengthComputable) onProgress?.(e.loaded, e.total);
547
+ };
548
+ req.onload = () => {
549
+ if (req.status < 200 || req.status >= 300) {
550
+ this.classifyHttpStatus(req.status).then(reject).catch(reject);
551
+ return;
552
+ }
553
+ const buf = req.response;
554
+ onProgress?.(buf.byteLength, buf.byteLength);
555
+ resolve(new Uint8Array(buf));
556
+ };
557
+ req.onerror = () => reject(new _errors.CloudSyncError(_errors.ErrorCode.NETWORK_UNAVAILABLE, '[RNCloudSync] CloudKit asset download failed to reach the server.', {
558
+ provider: 'cloudKit'
559
+ }));
560
+ req.ontimeout = () => reject((0, _errors.timedOut)(req.timeout, 'cloudKit'));
561
+ req.send();
562
+ });
563
+ }
564
+
381
565
  /**
382
566
  * A write that fails instead of clobbering, when the server's copy has moved
383
567
  * on since `recordChangeTag` was read.