react-native-cloud-sync 0.2.0 → 0.4.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.
- package/README.md +120 -80
- package/lib/commonjs/config.js +11 -1
- package/lib/commonjs/config.js.map +1 -1
- package/lib/commonjs/hooks.js +242 -0
- package/lib/commonjs/hooks.js.map +1 -1
- package/lib/commonjs/index.js.map +1 -1
- package/lib/commonjs/internal/cloudKitRest.js +205 -21
- package/lib/commonjs/internal/cloudKitRest.js.map +1 -1
- package/lib/commonjs/internal/googleDriveRest.js +173 -38
- package/lib/commonjs/internal/googleDriveRest.js.map +1 -1
- package/lib/commonjs/providers/cloudKit.js +89 -19
- package/lib/commonjs/providers/cloudKit.js.map +1 -1
- package/lib/module/config.js +10 -1
- package/lib/module/config.js.map +1 -1
- package/lib/module/hooks.js +240 -0
- package/lib/module/hooks.js.map +1 -1
- package/lib/module/index.js +2 -2
- package/lib/module/index.js.map +1 -1
- package/lib/module/internal/cloudKitRest.js +205 -21
- package/lib/module/internal/cloudKitRest.js.map +1 -1
- package/lib/module/internal/googleDriveRest.js +174 -39
- package/lib/module/internal/googleDriveRest.js.map +1 -1
- package/lib/module/providers/cloudKit.js +92 -22
- package/lib/module/providers/cloudKit.js.map +1 -1
- package/lib/typescript/commonjs/config.d.ts +8 -0
- package/lib/typescript/commonjs/config.d.ts.map +1 -1
- package/lib/typescript/commonjs/hooks.d.ts +68 -0
- package/lib/typescript/commonjs/hooks.d.ts.map +1 -1
- package/lib/typescript/commonjs/index.d.ts +3 -3
- package/lib/typescript/commonjs/index.d.ts.map +1 -1
- package/lib/typescript/commonjs/internal/cloudKitRest.d.ts +90 -0
- package/lib/typescript/commonjs/internal/cloudKitRest.d.ts.map +1 -1
- package/lib/typescript/commonjs/internal/googleDriveRest.d.ts +73 -8
- package/lib/typescript/commonjs/internal/googleDriveRest.d.ts.map +1 -1
- package/lib/typescript/commonjs/providers/cloudKit.d.ts +32 -13
- package/lib/typescript/commonjs/providers/cloudKit.d.ts.map +1 -1
- package/lib/typescript/module/config.d.ts +8 -0
- package/lib/typescript/module/config.d.ts.map +1 -1
- package/lib/typescript/module/hooks.d.ts +68 -0
- package/lib/typescript/module/hooks.d.ts.map +1 -1
- package/lib/typescript/module/index.d.ts +3 -3
- package/lib/typescript/module/index.d.ts.map +1 -1
- package/lib/typescript/module/internal/cloudKitRest.d.ts +90 -0
- package/lib/typescript/module/internal/cloudKitRest.d.ts.map +1 -1
- package/lib/typescript/module/internal/googleDriveRest.d.ts +73 -8
- package/lib/typescript/module/internal/googleDriveRest.d.ts.map +1 -1
- package/lib/typescript/module/providers/cloudKit.d.ts +32 -13
- package/lib/typescript/module/providers/cloudKit.d.ts.map +1 -1
- package/package.json +5 -2
- package/src/config.ts +12 -2
- package/src/hooks.ts +294 -0
- package/src/index.ts +5 -3
- package/src/internal/cloudKitRest.ts +272 -29
- package/src/internal/googleDriveRest.ts +196 -42
- package/src/providers/cloudKit.ts +138 -41
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { CloudSyncError, ErrorCode } from '../errors'
|
|
1
|
+
import { CloudSyncError, ErrorCode, timedOut } from '../errors'
|
|
2
2
|
import { byteLength } from './bytes'
|
|
3
3
|
import { withTimeout } from './timeout'
|
|
4
4
|
|
|
@@ -50,6 +50,16 @@ export interface CloudKitRestConfig {
|
|
|
50
50
|
onAuthExpired?: () => Promise<void> | void
|
|
51
51
|
/** Overridable for tests. Defaults to global `fetch`. */
|
|
52
52
|
fetchImpl?: typeof fetch
|
|
53
|
+
/**
|
|
54
|
+
* Overridable for tests. Defaults to the global `XMLHttpRequest` constructor.
|
|
55
|
+
*
|
|
56
|
+
* Only used for the raw asset-bytes upload/download - `fetch` in React
|
|
57
|
+
* Native exposes no upload-progress events at all, and `XMLHttpRequest.upload
|
|
58
|
+
* .onprogress` (and its response-side `.onprogress`) are what the per-record
|
|
59
|
+
* progress `cloudKitAssets.onProgress` promises actually needs. Every other
|
|
60
|
+
* request in this client stays on `fetch`.
|
|
61
|
+
*/
|
|
62
|
+
xhrImpl?: () => XMLHttpRequest
|
|
53
63
|
/**
|
|
54
64
|
* Abandon a request that has not answered in this long. Default 30000.
|
|
55
65
|
*
|
|
@@ -60,6 +70,31 @@ export interface CloudKitRestConfig {
|
|
|
60
70
|
timeoutMs?: number
|
|
61
71
|
}
|
|
62
72
|
|
|
73
|
+
/**
|
|
74
|
+
* CloudKit Web Services' own ceiling on a single asset upload, undocumented
|
|
75
|
+
* anywhere except the upload endpoint's own reference page: 15 MB, and the
|
|
76
|
+
* upload URL it hands out is valid for 15 minutes. Native `CKAsset` has no such
|
|
77
|
+
* limit - this is specific to the REST upload-token protocol.
|
|
78
|
+
*/
|
|
79
|
+
export const MAX_ASSET_UPLOAD_BYTES = 15 * 1024 * 1024
|
|
80
|
+
|
|
81
|
+
/**
|
|
82
|
+
* The "Asset Dictionary" CloudKit Web Services deals in - what the upload
|
|
83
|
+
* endpoint returns after receiving bytes, and what a fetched record's Asset
|
|
84
|
+
* field value looks like. Passed back verbatim as a record field's value to
|
|
85
|
+
* attach an upload to a record; never reconstructed field-by-field, since it
|
|
86
|
+
* is an opaque blob the server itself validates.
|
|
87
|
+
*/
|
|
88
|
+
export interface CloudKitAssetDescriptor {
|
|
89
|
+
fileChecksum: string
|
|
90
|
+
size: string | number
|
|
91
|
+
receipt: string
|
|
92
|
+
referenceChecksum?: string
|
|
93
|
+
wrappingKey?: string
|
|
94
|
+
/** Present only when fetching the record that owns this field, not on upload. */
|
|
95
|
+
downloadURL?: string
|
|
96
|
+
}
|
|
97
|
+
|
|
63
98
|
/**
|
|
64
99
|
* How many operations one `/records/modify` or `/records/lookup` call carries.
|
|
65
100
|
*
|
|
@@ -108,6 +143,8 @@ interface CloudKitResponse {
|
|
|
108
143
|
redirectURL?: string
|
|
109
144
|
/** Set when a query has more results than one response can carry. */
|
|
110
145
|
continuationMarker?: string
|
|
146
|
+
/** Present only on an `/assets/upload` response. */
|
|
147
|
+
tokens?: { recordName?: string; fieldName?: string; url?: string }[]
|
|
111
148
|
}
|
|
112
149
|
|
|
113
150
|
/**
|
|
@@ -212,6 +249,35 @@ export class CloudKitRestClient {
|
|
|
212
249
|
}
|
|
213
250
|
}
|
|
214
251
|
|
|
252
|
+
/**
|
|
253
|
+
* HTTP-status classification for a response with no CloudKit error envelope
|
|
254
|
+
* of its own to inspect - `post()`'s fallback tail, and the raw asset-bytes
|
|
255
|
+
* transfer, which talks to an opaque single-use upload/download URL rather
|
|
256
|
+
* than a `/records/...` JSON endpoint.
|
|
257
|
+
*/
|
|
258
|
+
private async classifyHttpStatus(status: number): Promise<CloudSyncError> {
|
|
259
|
+
if (status === 401 || status === 421) {
|
|
260
|
+
await this.handleAuthExpired()
|
|
261
|
+
return new CloudSyncError(
|
|
262
|
+
ErrorCode.AUTH_EXPIRED,
|
|
263
|
+
`[RNCloudSync] CloudKit returned HTTP ${status}; the web auth token is no longer valid.`,
|
|
264
|
+
{ provider: 'cloudKit' }
|
|
265
|
+
)
|
|
266
|
+
}
|
|
267
|
+
if (status === 429 || status === 503)
|
|
268
|
+
return new CloudSyncError(
|
|
269
|
+
ErrorCode.RATE_LIMITED,
|
|
270
|
+
`[RNCloudSync] CloudKit returned HTTP ${status}.`,
|
|
271
|
+
{ provider: 'cloudKit' }
|
|
272
|
+
)
|
|
273
|
+
|
|
274
|
+
return new CloudSyncError(
|
|
275
|
+
ErrorCode.UNKNOWN,
|
|
276
|
+
`[RNCloudSync] CloudKit returned HTTP ${status}.`,
|
|
277
|
+
{ provider: 'cloudKit' }
|
|
278
|
+
)
|
|
279
|
+
}
|
|
280
|
+
|
|
215
281
|
private async post(path: string, body: unknown): Promise<CloudKitResponse> {
|
|
216
282
|
const token = await this.requireAuthToken()
|
|
217
283
|
const url
|
|
@@ -250,29 +316,8 @@ export class CloudKitRestClient {
|
|
|
250
316
|
if (json?.serverErrorCode != null)
|
|
251
317
|
throw await this.toError(json.serverErrorCode, json.reason, json.retryAfter)
|
|
252
318
|
|
|
253
|
-
|
|
254
|
-
|
|
255
|
-
if (res.status === 401 || res.status === 421) {
|
|
256
|
-
await this.handleAuthExpired()
|
|
257
|
-
throw new CloudSyncError(
|
|
258
|
-
ErrorCode.AUTH_EXPIRED,
|
|
259
|
-
`[RNCloudSync] CloudKit returned HTTP ${res.status}; the web auth token is no longer valid.`,
|
|
260
|
-
{ provider: 'cloudKit' }
|
|
261
|
-
)
|
|
262
|
-
}
|
|
263
|
-
if (res.status === 429 || res.status === 503)
|
|
264
|
-
throw new CloudSyncError(
|
|
265
|
-
ErrorCode.RATE_LIMITED,
|
|
266
|
-
`[RNCloudSync] CloudKit returned HTTP ${res.status}.`,
|
|
267
|
-
{ provider: 'cloudKit' }
|
|
268
|
-
)
|
|
269
|
-
|
|
270
|
-
throw new CloudSyncError(
|
|
271
|
-
ErrorCode.UNKNOWN,
|
|
272
|
-
`[RNCloudSync] CloudKit returned HTTP ${res.status}.`,
|
|
273
|
-
{ provider: 'cloudKit' }
|
|
274
|
-
)
|
|
275
|
-
}
|
|
319
|
+
// HTTP-level failure with no parseable CloudKit error body.
|
|
320
|
+
if (!res.ok) throw await this.classifyHttpStatus(res.status)
|
|
276
321
|
|
|
277
322
|
return json ?? {}
|
|
278
323
|
}
|
|
@@ -442,11 +487,22 @@ export class CloudKitRestClient {
|
|
|
442
487
|
{ provider: 'cloudKit', limitBytes: MAX_RECORD_BYTES, actualBytes: bytes }
|
|
443
488
|
)
|
|
444
489
|
|
|
445
|
-
|
|
446
|
-
|
|
447
|
-
|
|
448
|
-
|
|
449
|
-
|
|
490
|
+
await this.saveFields(recordName, { [VALUE_FIELD]: { value } }, recordType)
|
|
491
|
+
}
|
|
492
|
+
|
|
493
|
+
/**
|
|
494
|
+
* Creates `recordName`, falling back to an unconditional update when it
|
|
495
|
+
* already exists - the create-then-fall-back dance every write after the
|
|
496
|
+
* first one takes. Shared by {@link saveRecord} (a `value` field) and
|
|
497
|
+
* {@link uploadAsset} (an Asset field plus its `__size` sidecar), which need
|
|
498
|
+
* the exact same dance for a different field set.
|
|
499
|
+
*/
|
|
500
|
+
private async saveFields(
|
|
501
|
+
recordName: string,
|
|
502
|
+
fields: Record<string, { value: unknown }>,
|
|
503
|
+
recordType: string
|
|
504
|
+
): Promise<void> {
|
|
505
|
+
const record = { recordType, recordName, fields }
|
|
450
506
|
|
|
451
507
|
// `atomic` defaults to true server-side. Setting it explicitly documents the
|
|
452
508
|
// intent and keeps behaviour stable if that default ever changes.
|
|
@@ -498,6 +554,193 @@ export class CloudKitRestClient {
|
|
|
498
554
|
}
|
|
499
555
|
}
|
|
500
556
|
|
|
557
|
+
/**
|
|
558
|
+
* Uploads `bytes` as `fieldName` on `recordName`, via CloudKit Web Services'
|
|
559
|
+
* asset-upload protocol: request a single-use upload URL, POST the raw bytes
|
|
560
|
+
* to it, then attach the descriptor it returns (plus a `__size` sidecar, so
|
|
561
|
+
* a later {@link fetchAsset} can report real download progress) to the
|
|
562
|
+
* record - the same create-then-update dance {@link saveRecord} uses.
|
|
563
|
+
*
|
|
564
|
+
* `onProgress` reports real bytes transferred, via `XMLHttpRequest` rather
|
|
565
|
+
* than `fetch` - see {@link CloudKitRestConfig.xhrImpl}.
|
|
566
|
+
*/
|
|
567
|
+
async uploadAsset(
|
|
568
|
+
recordName: string,
|
|
569
|
+
fieldName: string,
|
|
570
|
+
bytes: Uint8Array,
|
|
571
|
+
onProgress?: (bytesTransferred: number, bytesTotal: number) => void,
|
|
572
|
+
recordType = RECORD_TYPE_DEFAULT
|
|
573
|
+
): Promise<void> {
|
|
574
|
+
if (bytes.length > MAX_ASSET_UPLOAD_BYTES)
|
|
575
|
+
throw new CloudSyncError(
|
|
576
|
+
ErrorCode.PAYLOAD_TOO_LARGE,
|
|
577
|
+
`[RNCloudSync] Asset is ${bytes.length} bytes; CloudKit Web Services caps a single asset `
|
|
578
|
+
+ `upload at ${MAX_ASSET_UPLOAD_BYTES} bytes. Use the googleDrive provider for larger files `
|
|
579
|
+
+ `on Android and web.`,
|
|
580
|
+
{ provider: 'cloudKit', limitBytes: MAX_ASSET_UPLOAD_BYTES, actualBytes: bytes.length }
|
|
581
|
+
)
|
|
582
|
+
|
|
583
|
+
const uploadUrl = await this.requestAssetUploadUrl(recordType, recordName, fieldName)
|
|
584
|
+
const descriptor = await this.putAssetBytes(uploadUrl, bytes, onProgress)
|
|
585
|
+
|
|
586
|
+
await this.saveFields(recordName, {
|
|
587
|
+
[fieldName]: { value: descriptor },
|
|
588
|
+
[`${fieldName}__size`]: { value: bytes.length },
|
|
589
|
+
}, recordType)
|
|
590
|
+
}
|
|
591
|
+
|
|
592
|
+
/**
|
|
593
|
+
* Downloads the bytes behind `fieldName` on `recordName`, or `null` when the
|
|
594
|
+
* record or the field's asset does not exist.
|
|
595
|
+
*
|
|
596
|
+
* A fetched record's Asset field carries a `downloadURL` - that is the only
|
|
597
|
+
* step this needs beyond the usual record lookup; there is no separate
|
|
598
|
+
* "request a download token" round trip the way upload has one.
|
|
599
|
+
*/
|
|
600
|
+
async fetchAsset(
|
|
601
|
+
recordName: string,
|
|
602
|
+
fieldName: string,
|
|
603
|
+
onProgress?: (bytesTransferred: number, bytesTotal: number) => void,
|
|
604
|
+
recordType = RECORD_TYPE_DEFAULT
|
|
605
|
+
): Promise<Uint8Array | null> {
|
|
606
|
+
void recordType
|
|
607
|
+
const json = await this.post('/records/lookup', { records: [{ recordName }] })
|
|
608
|
+
const record = json.records?.find(r => r.recordName === recordName) ?? json.records?.[0]
|
|
609
|
+
if (record == null) return null
|
|
610
|
+
|
|
611
|
+
if (record.serverErrorCode != null) {
|
|
612
|
+
if (record.serverErrorCode === 'NOT_FOUND') return null
|
|
613
|
+
throw await this.toError(record.serverErrorCode, record.reason, record.retryAfter)
|
|
614
|
+
}
|
|
615
|
+
|
|
616
|
+
const asset = record.fields?.[fieldName]?.value as CloudKitAssetDescriptor | undefined
|
|
617
|
+
if (asset?.downloadURL == null) return null
|
|
618
|
+
|
|
619
|
+
return await this.fetchAssetBytes(asset.downloadURL, onProgress)
|
|
620
|
+
}
|
|
621
|
+
|
|
622
|
+
private async requestAssetUploadUrl(
|
|
623
|
+
recordType: string, recordName: string, fieldName: string
|
|
624
|
+
): Promise<string> {
|
|
625
|
+
const json = await this.post('/assets/upload', {
|
|
626
|
+
tokens: [{ recordType, recordName, fieldName }],
|
|
627
|
+
})
|
|
628
|
+
|
|
629
|
+
const url = json.tokens?.[0]?.url
|
|
630
|
+
if (url == null)
|
|
631
|
+
throw new CloudSyncError(
|
|
632
|
+
ErrorCode.UNKNOWN,
|
|
633
|
+
'[RNCloudSync] CloudKit did not return an asset upload URL.',
|
|
634
|
+
{ provider: 'cloudKit' }
|
|
635
|
+
)
|
|
636
|
+
|
|
637
|
+
return url
|
|
638
|
+
}
|
|
639
|
+
|
|
640
|
+
private get xhr(): () => XMLHttpRequest {
|
|
641
|
+
return this.config.xhrImpl ?? (() => new XMLHttpRequest())
|
|
642
|
+
}
|
|
643
|
+
|
|
644
|
+
/**
|
|
645
|
+
* POSTs raw bytes to a single-use CKWS asset-upload URL, reporting real
|
|
646
|
+
* upload progress via `XMLHttpRequest.upload.onprogress` - `fetch` exposes no
|
|
647
|
+
* upload-progress events in React Native. Scoped to just this one call:
|
|
648
|
+
* every other CloudKit REST request stays on `fetch` through `post()`, for
|
|
649
|
+
* the timeout/error handling already built there.
|
|
650
|
+
*/
|
|
651
|
+
private putAssetBytes(
|
|
652
|
+
url: string,
|
|
653
|
+
bytes: Uint8Array,
|
|
654
|
+
onProgress?: (bytesTransferred: number, bytesTotal: number) => void
|
|
655
|
+
): Promise<CloudKitAssetDescriptor> {
|
|
656
|
+
return new Promise((resolve, reject) => {
|
|
657
|
+
const req = this.xhr()
|
|
658
|
+
req.open('POST', url)
|
|
659
|
+
req.timeout = this.config.timeoutMs ?? DEFAULT_TIMEOUT_MS
|
|
660
|
+
|
|
661
|
+
req.upload.onprogress = (e) => {
|
|
662
|
+
if (e.lengthComputable) onProgress?.(e.loaded, e.total)
|
|
663
|
+
}
|
|
664
|
+
|
|
665
|
+
req.onload = () => {
|
|
666
|
+
if (req.status < 200 || req.status >= 300) {
|
|
667
|
+
this.classifyHttpStatus(req.status).then(reject).catch(reject)
|
|
668
|
+
return
|
|
669
|
+
}
|
|
670
|
+
|
|
671
|
+
try {
|
|
672
|
+
const json = JSON.parse(req.responseText) as { singleFile?: CloudKitAssetDescriptor }
|
|
673
|
+
if (json.singleFile == null) throw new Error('response had no singleFile')
|
|
674
|
+
onProgress?.(bytes.length, bytes.length)
|
|
675
|
+
resolve(json.singleFile)
|
|
676
|
+
}
|
|
677
|
+
catch (e) {
|
|
678
|
+
reject(new CloudSyncError(
|
|
679
|
+
ErrorCode.UNKNOWN,
|
|
680
|
+
'[RNCloudSync] CloudKit did not return an asset descriptor after upload.',
|
|
681
|
+
{ provider: 'cloudKit', cause: e }
|
|
682
|
+
))
|
|
683
|
+
}
|
|
684
|
+
}
|
|
685
|
+
|
|
686
|
+
req.onerror = () => reject(new CloudSyncError(
|
|
687
|
+
ErrorCode.NETWORK_UNAVAILABLE,
|
|
688
|
+
'[RNCloudSync] CloudKit asset upload failed to reach the server.',
|
|
689
|
+
{ provider: 'cloudKit' }
|
|
690
|
+
))
|
|
691
|
+
req.ontimeout = () => reject(timedOut(req.timeout, 'cloudKit'))
|
|
692
|
+
|
|
693
|
+
req.send(bytes)
|
|
694
|
+
})
|
|
695
|
+
}
|
|
696
|
+
|
|
697
|
+
/**
|
|
698
|
+
* GETs raw bytes from a record's asset `downloadURL`, reporting real
|
|
699
|
+
* download progress via `XMLHttpRequest.onprogress`, for the same reason
|
|
700
|
+
* {@link putAssetBytes} uses XHR rather than `fetch`.
|
|
701
|
+
*
|
|
702
|
+
* Treated as self-contained, the same way the upload URL is (Apple's own
|
|
703
|
+
* reference issues that one with no `ckAPIToken`/`ckWebAuthToken` at all) -
|
|
704
|
+
* if that assumption is ever wrong for a download URL specifically, it
|
|
705
|
+
* surfaces as an HTTP-level auth failure here rather than a silent wrong
|
|
706
|
+
* answer.
|
|
707
|
+
*/
|
|
708
|
+
private fetchAssetBytes(
|
|
709
|
+
url: string,
|
|
710
|
+
onProgress?: (bytesTransferred: number, bytesTotal: number) => void
|
|
711
|
+
): Promise<Uint8Array> {
|
|
712
|
+
return new Promise((resolve, reject) => {
|
|
713
|
+
const req = this.xhr()
|
|
714
|
+
req.open('GET', url)
|
|
715
|
+
req.responseType = 'arraybuffer'
|
|
716
|
+
req.timeout = this.config.timeoutMs ?? DEFAULT_TIMEOUT_MS
|
|
717
|
+
|
|
718
|
+
req.onprogress = (e) => {
|
|
719
|
+
if (e.lengthComputable) onProgress?.(e.loaded, e.total)
|
|
720
|
+
}
|
|
721
|
+
|
|
722
|
+
req.onload = () => {
|
|
723
|
+
if (req.status < 200 || req.status >= 300) {
|
|
724
|
+
this.classifyHttpStatus(req.status).then(reject).catch(reject)
|
|
725
|
+
return
|
|
726
|
+
}
|
|
727
|
+
|
|
728
|
+
const buf = req.response as ArrayBuffer
|
|
729
|
+
onProgress?.(buf.byteLength, buf.byteLength)
|
|
730
|
+
resolve(new Uint8Array(buf))
|
|
731
|
+
}
|
|
732
|
+
|
|
733
|
+
req.onerror = () => reject(new CloudSyncError(
|
|
734
|
+
ErrorCode.NETWORK_UNAVAILABLE,
|
|
735
|
+
'[RNCloudSync] CloudKit asset download failed to reach the server.',
|
|
736
|
+
{ provider: 'cloudKit' }
|
|
737
|
+
))
|
|
738
|
+
req.ontimeout = () => reject(timedOut(req.timeout, 'cloudKit'))
|
|
739
|
+
|
|
740
|
+
req.send()
|
|
741
|
+
})
|
|
742
|
+
}
|
|
743
|
+
|
|
501
744
|
/**
|
|
502
745
|
* A write that fails instead of clobbering, when the server's copy has moved
|
|
503
746
|
* on since `recordChangeTag` was read.
|