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
@@ -1,12 +1,15 @@
1
- import { CloudSyncError, ErrorCode } from '../errors'
1
+ import { CloudSyncError, ErrorCode, isCancelled } from '../errors'
2
2
  import { throwIfAborted, withTimeout, type AbortLike } from './timeout'
3
3
 
4
4
  /**
5
5
  * Google Drive `appDataFolder` REST client.
6
6
  *
7
7
  * `appDataFolder` is a hidden per-app, per-Google-account folder: nothing shows
8
- * up in the user's visible Drive, and the data survives an app uninstall because
9
- * it is tied to the account rather than the install.
8
+ * up in the user's visible Drive, and the data is tied to the Google account
9
+ * rather than the device or install, so reinstalling the app or switching
10
+ * devices doesn't lose it. It goes away only if the user disconnects the app
11
+ * from their Drive account or deletes the data folder directly - Google
12
+ * documents both as the ways this folder is actually removed.
10
13
  *
11
14
  * Auth is deliberately injected rather than owned. The library does not depend
12
15
  * on `@react-native-google-signin/google-signin` (or any other sign-in library),
@@ -55,6 +58,39 @@ export interface GoogleDriveConfig {
55
58
  * its own, so without this a dead socket hangs the transfer forever.
56
59
  */
57
60
  timeoutMs?: number
61
+ /**
62
+ * Persists `uploadFile`'s resumable-session URI across process restarts.
63
+ *
64
+ * Without this, the session lives only in memory: a process killed mid-upload
65
+ * loses it, and the next `uploadFile` for the same name starts over from byte
66
+ * 0 even though Drive still has the bytes already accepted. With it, the next
67
+ * call finds the persisted session, asks Drive for the real offset, and
68
+ * resumes from there instead.
69
+ *
70
+ * A tiny JSON record, not file I/O - back it with AsyncStorage, MMKV, or a
71
+ * single row in whatever the host app already uses. Optional; omitting it
72
+ * keeps today's in-memory-only behaviour.
73
+ */
74
+ sessionStore?: GoogleDriveSessionStore
75
+ }
76
+
77
+ /** What `uploadFile` needs to resume a resumable-upload session later. */
78
+ export interface GoogleDriveUploadSession {
79
+ sessionUrl: string
80
+ /** The source size the session was started against - resuming into a file
81
+ * that has since changed size would corrupt it, so a mismatch is treated
82
+ * as "start fresh" rather than resumed. */
83
+ size: number
84
+ }
85
+
86
+ /**
87
+ * Host-supplied persistence for in-flight `uploadFile` sessions, keyed by the
88
+ * Drive file name. See {@link GoogleDriveConfig.sessionStore}.
89
+ */
90
+ export interface GoogleDriveSessionStore {
91
+ get: (name: string) => Promise<GoogleDriveUploadSession | null>
92
+ set: (name: string, session: GoogleDriveUploadSession) => Promise<void>
93
+ remove: (name: string) => Promise<void>
58
94
  }
59
95
 
60
96
  const FILES_URL = 'https://www.googleapis.com/drive/v3/files'
@@ -104,7 +140,8 @@ interface DriveFile {
104
140
  name: string
105
141
  /** RFC 3339. Requested explicitly - Drive omits it unless `fields` asks. */
106
142
  modifiedTime?: string
107
- /** Drive's version counter. Increments on every content change. */
143
+ /** Drive's version counter. Increments on every server-side change to the
144
+ * file, not just content - a rename bumps it too. */
108
145
  version?: string
109
146
  }
110
147
 
@@ -195,15 +232,45 @@ export class GoogleDriveClient {
195
232
 
196
233
  if (res.ok || extraOkStatuses.includes(res.status)) return res
197
234
 
198
- if (res.status === 401 || res.status === 403) {
235
+ if (res.status === 401) {
199
236
  await this.config.onAuthExpired?.()
200
237
  throw new CloudSyncError(
201
238
  ErrorCode.AUTH_EXPIRED,
202
- `[RNCloudSync] Google Drive returned HTTP ${res.status}; the access token is not valid.`,
239
+ '[RNCloudSync] Google Drive returned HTTP 401; the access token is not valid.',
240
+ { provider: 'googleDrive' }
241
+ )
242
+ }
243
+ if (res.status === 403) {
244
+ // Drive overloads 403 for three unrelated conditions, distinguished only by
245
+ // `error.errors[0].reason` in the body - never by a different status code.
246
+ // Quota-exceeded in particular is NOT the 507 a WebDAV-flavoured API might
247
+ // use; Drive documents it as 403 `storageQuotaExceeded`, so treating it as
248
+ // an auth failure (and wrongly prompting reconnect) is the wrong default.
249
+ const reason = await this.driveErrorReason(res)
250
+
251
+ if (reason === 'storageQuotaExceeded')
252
+ throw new CloudSyncError(
253
+ ErrorCode.QUOTA_EXCEEDED,
254
+ '[RNCloudSync] Google Drive storage quota exceeded.',
255
+ { provider: 'googleDrive' }
256
+ )
257
+ if (reason === 'userRateLimitExceeded' || reason === 'rateLimitExceeded')
258
+ throw new CloudSyncError(
259
+ ErrorCode.RATE_LIMITED,
260
+ '[RNCloudSync] Google Drive rate limited the request.',
261
+ { provider: 'googleDrive' }
262
+ )
263
+
264
+ await this.config.onAuthExpired?.()
265
+ throw new CloudSyncError(
266
+ ErrorCode.AUTH_EXPIRED,
267
+ '[RNCloudSync] Google Drive returned HTTP 403; the access token is not valid or lacks permission.',
203
268
  { provider: 'googleDrive' }
204
269
  )
205
270
  }
206
271
  if (res.status === 429) {
272
+ // The request-frequency case, distinct from the per-user 403 variants
273
+ // above - this one really is a plain 429, no reason string to parse.
207
274
  const retryAfter = Number(res.headers.get('Retry-After'))
208
275
  throw new CloudSyncError(
209
276
  ErrorCode.RATE_LIMITED,
@@ -214,12 +281,6 @@ export class GoogleDriveClient {
214
281
  }
215
282
  )
216
283
  }
217
- if (res.status === 507)
218
- throw new CloudSyncError(
219
- ErrorCode.QUOTA_EXCEEDED,
220
- '[RNCloudSync] Google Drive storage quota exceeded.',
221
- { provider: 'googleDrive' }
222
- )
223
284
  // Tagged so callers can tell "this file id is gone" from a generic failure.
224
285
  // Without the tag a stale memoised id was indistinguishable from a real
225
286
  // error, so it could never be recovered from.
@@ -237,6 +298,23 @@ export class GoogleDriveClient {
237
298
  )
238
299
  }
239
300
 
301
+ /**
302
+ * Best-effort read of Drive's `error.errors[0].reason` from a failed
303
+ * response body - the only way a 403 status distinguishes an invalid token
304
+ * from quota-exceeded from a rate limit. Returns undefined for a body that
305
+ * is missing, unparseable, or doesn't carry the shape Drive documents,
306
+ * rather than throwing a second error while already handling one.
307
+ */
308
+ private async driveErrorReason(res: Response): Promise<string | undefined> {
309
+ try {
310
+ const json = await res.json() as { error?: { errors?: { reason?: string }[] } }
311
+ return json.error?.errors?.[0]?.reason
312
+ }
313
+ catch {
314
+ return undefined
315
+ }
316
+ }
317
+
240
318
  /**
241
319
  * Resolves a file name to its id within appDataFolder, or null if absent.
242
320
  *
@@ -250,8 +328,11 @@ export class GoogleDriveClient {
250
328
  this.idCache.delete(name)
251
329
 
252
330
  // Scope the query server-side. Escaping matters: an apostrophe in a key
253
- // would otherwise terminate the quoted literal and produce a malformed query.
254
- const q = encodeURIComponent(`name='${name.replace(/'/g, '\\\'')}' and trashed=false`)
331
+ // would otherwise terminate the quoted literal and produce a malformed
332
+ // query - and a literal backslash needs the same treatment, escaped FIRST
333
+ // so it doesn't double-escape the backslash the quote-escaping just added.
334
+ const escaped = name.replace(/\\/g, '\\\\').replace(/'/g, '\\\'')
335
+ const q = encodeURIComponent(`name='${escaped}' and trashed=false`)
255
336
  const url = `${FILES_URL}?spaces=appDataFolder&q=${q}&fields=files(${FILE_FIELDS})&pageSize=10`
256
337
 
257
338
  const res = await this.request(url, { method: 'GET' })
@@ -420,11 +501,13 @@ export class GoogleDriveClient {
420
501
  * how many bytes it actually has and resuming from there - rather than
421
502
  * restarting the transfer.
422
503
  *
423
- * That resumability is scoped to this call: the session lives only in
424
- * memory, so if the process dies mid-upload, the next call to `uploadFile`
425
- * starts a fresh session from byte 0. Persisting the session URI so a
426
- * restart can resume it too is future scope, not something callers should
427
- * assume works today.
504
+ * That resumability spans a process restart too, when {@link
505
+ * GoogleDriveConfig.sessionStore} is configured: the session URI is persisted
506
+ * before the first chunk goes out, and a later `uploadFile` for the same name
507
+ * finds it, asks Drive for the real offset, and resumes from there instead of
508
+ * byte 0. Without a `sessionStore`, the session lives only in memory, exactly
509
+ * as before - a process that dies mid-upload loses it, and the next call
510
+ * starts fresh.
428
511
  */
429
512
  async uploadFile(
430
513
  name: string,
@@ -433,32 +516,83 @@ export class GoogleDriveClient {
433
516
  signal?: AbortLike
434
517
  ): Promise<void> {
435
518
  throwIfAborted(signal, 'googleDrive')
436
- const existingId = await this.findFileId(name)
437
- const sessionUrl = await this.startResumableSession(name, existingId)
519
+ const total = source.size
520
+ const resumed = await this.resumeOrStartSession(name, total)
521
+
522
+ // The resumed session was already complete server-side - most likely the
523
+ // last chunk's own response was what got lost to the process dying, not
524
+ // the chunk itself. Nothing left to send.
525
+ if (resumed.completed) {
526
+ if (resumed.id != null) this.idCache.set(name, resumed.id)
527
+ await this.config.sessionStore?.remove(name)
528
+ onProgress?.(total, total)
529
+ return
530
+ }
438
531
 
439
- let offset = 0
532
+ const sessionUrl = resumed.sessionUrl
533
+ let offset = resumed.offset
440
534
  let newId: string | undefined
441
- const total = source.size
442
535
 
443
- // A zero-byte file still needs one request to actually create it.
444
- do {
445
- // Checked between chunks rather than only up front: a cancel during a
446
- // multi-hundred-megabyte transfer has to take effect while it is running,
447
- // which is the entire point of being able to cancel one.
448
- throwIfAborted(signal, 'googleDrive')
449
- const length = Math.min(this.chunkBytes, total - offset)
450
- const step = await this.putChunkWithRetry(sessionUrl, source, offset, length, total, onProgress)
451
- offset = step.nextOffset
452
- if (step.id != null) newId = step.id
453
- } while (offset < total)
536
+ try {
537
+ // A zero-byte file still needs one request to actually create it.
538
+ do {
539
+ // Checked between chunks rather than only up front: a cancel during a
540
+ // multi-hundred-megabyte transfer has to take effect while it is running,
541
+ // which is the entire point of being able to cancel one.
542
+ throwIfAborted(signal, 'googleDrive')
543
+ const length = Math.min(this.chunkBytes, total - offset)
544
+ const step = await this.putChunkWithRetry(sessionUrl, source, offset, length, total, onProgress)
545
+ offset = step.nextOffset
546
+ if (step.id != null) newId = step.id
547
+ } while (offset < total)
548
+ }
549
+ catch (e) {
550
+ // A deliberate cancel abandons the session - the caller asked to stop,
551
+ // not to resume later. Any other failure (network drop, timeout, the
552
+ // process itself dying) leaves the persisted session in place, since
553
+ // that is precisely what lets the next call resume instead of restarting.
554
+ if (isCancelled(e)) await this.config.sessionStore?.remove(name)
555
+ throw e
556
+ }
454
557
 
455
558
  // A create only learns its id from the final response; an update already
456
559
  // had one via `existingId`.
457
560
  if (newId != null) this.idCache.set(name, newId)
458
561
 
562
+ await this.config.sessionStore?.remove(name)
459
563
  onProgress?.(total, total)
460
564
  }
461
565
 
566
+ /**
567
+ * Finds an existing session to resume, or starts a new one.
568
+ *
569
+ * A persisted session is trusted only when its recorded size still matches
570
+ * `total` - resuming a byte-range PUT into a file that has since changed
571
+ * would corrupt it, so a mismatch is treated the same as no session at all.
572
+ * A persisted session Drive no longer recognises (expired, or the upload id
573
+ * was never valid) is also treated as absent: `queryUploadOffset` failing is
574
+ * the signal, since there is no cheaper way to ask than trying to use it.
575
+ */
576
+ private async resumeOrStartSession(
577
+ name: string, total: number
578
+ ): Promise<{ sessionUrl: string; offset: number; completed: boolean; id?: string }> {
579
+ const persisted = await this.config.sessionStore?.get(name)
580
+
581
+ if (persisted != null && persisted.size === total)
582
+ try {
583
+ const { offset, id } = await this.queryUploadOffset(persisted.sessionUrl, total)
584
+ return { sessionUrl: persisted.sessionUrl, offset, completed: offset >= total, id }
585
+ }
586
+ catch {
587
+ // Falls through to starting a fresh session below.
588
+ }
589
+
590
+ const existingId = await this.findFileId(name)
591
+ const sessionUrl = await this.startResumableSession(name, existingId)
592
+ await this.config.sessionStore?.set(name, { sessionUrl, size: total })
593
+ return { sessionUrl, offset: 0, completed: false }
594
+ }
595
+
462
596
  private async startResumableSession(name: string, existingId: string | null): Promise<string> {
463
597
  const url = existingId != null
464
598
  ? `${UPLOAD_URL}/${existingId}?uploadType=resumable`
@@ -496,9 +630,16 @@ export class GoogleDriveClient {
496
630
  }
497
631
  catch (e) {
498
632
  if (!isRetryableTransfer(e)) throw e
499
- const resumeFrom = await this.queryUploadOffset(sessionUrl, total)
500
- const retryLength = Math.min(this.chunkBytes, total - resumeFrom)
501
- return await this.putChunk(sessionUrl, source, resumeFrom, retryLength, total, onProgress)
633
+ const resumed = await this.queryUploadOffset(sessionUrl, total)
634
+ // The dropped chunk's own response was what got lost, not the chunk -
635
+ // Drive already has everything. A retry PUT here would send a zero-length,
636
+ // malformed Content-Range (end before start).
637
+ if (resumed.offset >= total) {
638
+ onProgress?.(total, total)
639
+ return { nextOffset: total, id: resumed.id }
640
+ }
641
+ const retryLength = Math.min(this.chunkBytes, total - resumed.offset)
642
+ return await this.putChunk(sessionUrl, source, resumed.offset, retryLength, total, onProgress)
502
643
  }
503
644
  }
504
645
 
@@ -533,20 +674,33 @@ export class GoogleDriveClient {
533
674
  return { nextOffset: total, id: json?.id }
534
675
  }
535
676
 
536
- /** Asks Drive how much of an in-flight resumable session it actually has. */
537
- private async queryUploadOffset(sessionUrl: string, total: number): Promise<number> {
677
+ /**
678
+ * Asks Drive how much of an in-flight resumable session it actually has, or
679
+ * discovers the upload was already complete server-side - the completing
680
+ * chunk's own response can be lost the same way any other one can, and this
681
+ * status check gets the same completion response back in that case,
682
+ * `id` included.
683
+ *
684
+ * Throws (via `request`) when `sessionUrl` is not a session Drive
685
+ * recognises any more - expired, or never valid. Callers treat that as the
686
+ * signal to stop trusting it, since there is no cheaper way to ask.
687
+ */
688
+ private async queryUploadOffset(sessionUrl: string, total: number): Promise<{ offset: number; id?: string }> {
538
689
  const res = await this.request(sessionUrl, {
539
690
  method: 'PUT',
540
691
  headers: { 'Content-Range': `bytes */${total}` },
541
692
  }, [308])
542
693
 
543
- if (res.status !== 308) return total // already complete, unexpectedly
694
+ if (res.status !== 308) {
695
+ const json = (await res.json().catch(() => null)) as { id?: string } | null
696
+ return { offset: total, id: json?.id ?? undefined }
697
+ }
544
698
 
545
699
  const range = res.headers.get('Range') // "bytes=0-8388607"
546
- if (range == null) return 0
700
+ if (range == null) return { offset: 0 }
547
701
 
548
702
  const match = /bytes=0-(\d+)/.exec(range)
549
- return match ? Number(match[1]) + 1 : 0
703
+ return { offset: match ? Number(match[1]) + 1 : 0 }
550
704
  }
551
705
 
552
706
  /**
@@ -1,10 +1,11 @@
1
1
  import { Platform } from 'react-native'
2
2
 
3
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'
4
+ import { getCloudKitClient, getSharedFileAdapter, isCloudKitConfigured } from '../config'
5
+ import { CloudKitRestClient, type CloudKitRestConfig, MAX_ASSET_UPLOAD_BYTES } from '../internal/cloudKitRest'
6
+ import { CloudSyncError, ErrorCode, normalizeError, unsupportedPlatform } from '../errors'
7
7
  import { toAccountStatus } from '../internal/enums'
8
+ import { base64ToBytes, bytesToBase64 } from '../internal/base64'
8
9
  import type {
9
10
  AccountChangeEvent,
10
11
  AccountStatus,
@@ -382,14 +383,27 @@ export const zones = {
382
383
  },
383
384
  }
384
385
 
386
+ /**
387
+ * Listeners for asset progress on Android/web, where there is no native event
388
+ * emitter to bridge - {@link assets.onProgress} subscribes here instead when
389
+ * not native, and the REST upload/download path publishes into it.
390
+ */
391
+ const restAssetProgressListeners = new Set<(e: AssetProgressEvent) => void>()
392
+
393
+ function publishRestAssetProgress(e: AssetProgressEvent): void {
394
+ for (const listener of restAssetProgressListeners) listener(e)
395
+ }
396
+
385
397
  /**
386
398
  * Binary assets (`CKAsset`).
387
399
  *
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.
400
+ * Native on iOS/macOS. On Android and web, `save`/`fetch` go through CloudKit
401
+ * Web Services' own asset-upload protocol (request a single-use upload URL,
402
+ * POST the bytes, attach the returned descriptor to the record) - see
403
+ * {@link MAX_ASSET_UPLOAD_BYTES} for the one hard limit that comes with it.
404
+ * Custom zones and the native temporary-directory fallback remain native-only
405
+ * (`ERR_UNSUPPORTED_PLATFORM`), since the REST client has no equivalent of
406
+ * either.
393
407
  *
394
408
  * Assets are deliberately an explicit API rather than something the store
395
409
  * facade routes to automatically: the caller passes a file path, not a string,
@@ -399,9 +413,12 @@ export const assets = {
399
413
  /**
400
414
  * Uploads a local file as a field on a record.
401
415
  *
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.
416
+ * Progress is reported per record through {@link onProgress}. Natively, a
417
+ * `CKAsset` is streamed from disk so a large file never has to be held in
418
+ * memory; over REST the whole file is read once, which is fine given
419
+ * {@link MAX_ASSET_UPLOAD_BYTES} - CloudKit Web Services itself caps a
420
+ * single asset upload at 15 MB, so nothing this package could stream would
421
+ * ever be large enough to need it.
405
422
  */
406
423
  save: async (
407
424
  options: {
@@ -413,20 +430,56 @@ export const assets = {
413
430
  zoneName?: string | null
414
431
  }
415
432
  ): Promise<void> => {
416
- if (!isNative())
433
+ if (isNative()) {
434
+ try {
435
+ await requireNativeModule().ckSaveAsset(
436
+ options.recordType ?? 'KVBlob',
437
+ options.recordName,
438
+ options.fieldName,
439
+ options.fileUri,
440
+ options.zoneName ?? null
441
+ )
442
+ }
443
+ catch (e) {
444
+ throw normalizeError(e, NAME)
445
+ }
446
+ return
447
+ }
448
+
449
+ if (options.zoneName != null)
417
450
  throw unsupportedPlatform(
418
451
  NAME,
419
- 'CKAsset upload is implemented natively only. On Android and web, store the file '
420
- + 'with the googleDrive provider instead.'
452
+ 'Custom zones are implemented natively only; the REST client uses the default zone.'
421
453
  )
422
454
 
423
455
  try {
424
- await requireNativeModule().ckSaveAsset(
425
- options.recordType ?? 'KVBlob',
456
+ // Checked in this order deliberately: whether CloudKit itself is even
457
+ // reachable is the more fundamental requirement, so it should surface
458
+ // first rather than being masked by a missing file adapter.
459
+ const client = getCloudKitClient()
460
+ const adapter = getSharedFileAdapter()
461
+ const size = await adapter.statSize(options.fileUri)
462
+ if (size > MAX_ASSET_UPLOAD_BYTES)
463
+ throw new CloudSyncError(
464
+ ErrorCode.PAYLOAD_TOO_LARGE,
465
+ `[RNCloudSync] '${options.fileUri}' is ${size} bytes; CloudKit Web Services caps a single `
466
+ + `asset upload at ${MAX_ASSET_UPLOAD_BYTES} bytes. Use the googleDrive provider for larger `
467
+ + `files on Android and web.`,
468
+ { provider: NAME, limitBytes: MAX_ASSET_UPLOAD_BYTES, actualBytes: size }
469
+ )
470
+
471
+ const bytes = base64ToBytes(await adapter.readChunk(options.fileUri, 0, size))
472
+ await client.uploadAsset(
426
473
  options.recordName,
427
474
  options.fieldName,
428
- options.fileUri,
429
- options.zoneName ?? null
475
+ bytes,
476
+ (bytesTransferred, bytesTotal) => publishRestAssetProgress({
477
+ recordName: options.recordName,
478
+ fieldName: options.fieldName,
479
+ bytesTransferred,
480
+ bytesTotal,
481
+ }),
482
+ options.recordType
430
483
  )
431
484
  }
432
485
  catch (e) {
@@ -439,10 +492,12 @@ export const assets = {
439
492
  * record or field does not exist.
440
493
  *
441
494
  * 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.
495
+ * share sheet. Natively, without it the file lands in the app's temporary
496
+ * directory under a name derived from the record, and iOS may reclaim that
497
+ * at any time - fine for restoring straight back into the app, wrong for an
498
+ * export. Parent directories are created if they do not exist. Over REST,
499
+ * `destinationUri` is required: there is no OS-managed temporary directory
500
+ * this package can fall back to without a native module.
446
501
  */
447
502
  fetch: async (
448
503
  options: {
@@ -452,19 +507,46 @@ export const assets = {
452
507
  destinationUri?: string
453
508
  }
454
509
  ): Promise<string | null> => {
455
- if (!isNative())
510
+ if (isNative())
511
+ try {
512
+ return await requireNativeModule().ckFetchAsset(
513
+ options.recordName,
514
+ options.fieldName,
515
+ options.zoneName ?? null,
516
+ options.destinationUri ?? null
517
+ )
518
+ }
519
+ catch (e) {
520
+ throw normalizeError(e, NAME)
521
+ }
522
+
523
+ if (options.zoneName != null)
456
524
  throw unsupportedPlatform(
457
525
  NAME,
458
- 'CKAsset download is implemented natively only.'
526
+ 'Custom zones are implemented natively only; the REST client uses the default zone.'
527
+ )
528
+ if (options.destinationUri == null)
529
+ throw unsupportedPlatform(
530
+ NAME,
531
+ 'A default temporary-directory destination is implemented natively only. Pass '
532
+ + 'destinationUri explicitly on Android and web.'
459
533
  )
460
534
 
461
535
  try {
462
- return await requireNativeModule().ckFetchAsset(
536
+ const bytes = await getCloudKitClient().fetchAsset(
463
537
  options.recordName,
464
538
  options.fieldName,
465
- options.zoneName ?? null,
466
- options.destinationUri ?? null
539
+ (bytesTransferred, bytesTotal) => publishRestAssetProgress({
540
+ recordName: options.recordName,
541
+ fieldName: options.fieldName,
542
+ bytesTransferred,
543
+ bytesTotal,
544
+ })
467
545
  )
546
+ if (bytes == null) return null
547
+
548
+ await getSharedFileAdapter().writeChunk(options.destinationUri, bytesToBase64(bytes))
549
+ return options.destinationUri
468
550
  }
469
551
  catch (e) {
470
552
  throw normalizeError(e, NAME)
@@ -478,6 +560,11 @@ export const assets = {
478
560
  * Identified by record and field rather than by a handle, because that is
479
561
  * what identifies a transfer everywhere else in this API - `onProgress`
480
562
  * reports the same pair, so a UI already has it.
563
+ *
564
+ * Native only, still - the REST transfer has no in-flight handle to cancel
565
+ * yet. Resolves `false` on Android/web rather than throwing, the same as
566
+ * before, so this is a known gap rather than a broken promise: a REST
567
+ * `save`/`fetch` cannot currently be stopped once started.
481
568
  */
482
569
  cancel: async (
483
570
  options: { recordName: string; fieldName: string }
@@ -491,20 +578,30 @@ export const assets = {
491
578
  }
492
579
  },
493
580
 
494
- /** Upload/download progress for asset transfers. Native only. */
581
+ /**
582
+ * Upload/download progress for asset transfers.
583
+ *
584
+ * Native on iOS/macOS, bridged from the same event every transfer already
585
+ * reports. On Android/web there is no native module to bridge, so this
586
+ * subscribes to the in-JS feed the REST `save`/`fetch` path publishes into
587
+ * instead - same event shape either way.
588
+ */
495
589
  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
- )
590
+ if (isNative())
591
+ return subscribeNativeEvent<AssetProgressNativeEvent>(
592
+ 'onAssetProgress',
593
+ 'assetProgress',
594
+ (e) => {
595
+ listener({
596
+ recordName: e.recordName,
597
+ fieldName: e.fieldName,
598
+ bytesTransferred: e.bytesTransferred,
599
+ bytesTotal: e.bytesTotal,
600
+ })
601
+ }
602
+ )
603
+
604
+ restAssetProgressListeners.add(listener)
605
+ return () => restAssetProgressListeners.delete(listener)
509
606
  },
510
607
  }