react-native-cloud-sync 0.1.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 (57) hide show
  1. package/README.md +58 -53
  2. package/ios/CloudSyncImpl.swift +25 -2
  3. package/lib/commonjs/config.js +11 -1
  4. package/lib/commonjs/config.js.map +1 -1
  5. package/lib/commonjs/index.js +6 -0
  6. package/lib/commonjs/index.js.map +1 -1
  7. package/lib/commonjs/internal/cloudKitRest.js +205 -21
  8. package/lib/commonjs/internal/cloudKitRest.js.map +1 -1
  9. package/lib/commonjs/internal/googleDriveRest.js +173 -38
  10. package/lib/commonjs/internal/googleDriveRest.js.map +1 -1
  11. package/lib/commonjs/providers/cloudKit.js +89 -19
  12. package/lib/commonjs/providers/cloudKit.js.map +1 -1
  13. package/lib/commonjs/resolvers.js +68 -0
  14. package/lib/commonjs/resolvers.js.map +1 -1
  15. package/lib/module/config.js +10 -1
  16. package/lib/module/config.js.map +1 -1
  17. package/lib/module/index.js +1 -1
  18. package/lib/module/index.js.map +1 -1
  19. package/lib/module/internal/cloudKitRest.js +205 -21
  20. package/lib/module/internal/cloudKitRest.js.map +1 -1
  21. package/lib/module/internal/googleDriveRest.js +174 -39
  22. package/lib/module/internal/googleDriveRest.js.map +1 -1
  23. package/lib/module/providers/cloudKit.js +92 -22
  24. package/lib/module/providers/cloudKit.js.map +1 -1
  25. package/lib/module/resolvers.js +67 -0
  26. package/lib/module/resolvers.js.map +1 -1
  27. package/lib/typescript/commonjs/config.d.ts +8 -0
  28. package/lib/typescript/commonjs/config.d.ts.map +1 -1
  29. package/lib/typescript/commonjs/index.d.ts +2 -2
  30. package/lib/typescript/commonjs/index.d.ts.map +1 -1
  31. package/lib/typescript/commonjs/internal/cloudKitRest.d.ts +90 -0
  32. package/lib/typescript/commonjs/internal/cloudKitRest.d.ts.map +1 -1
  33. package/lib/typescript/commonjs/internal/googleDriveRest.d.ts +73 -8
  34. package/lib/typescript/commonjs/internal/googleDriveRest.d.ts.map +1 -1
  35. package/lib/typescript/commonjs/providers/cloudKit.d.ts +32 -13
  36. package/lib/typescript/commonjs/providers/cloudKit.d.ts.map +1 -1
  37. package/lib/typescript/commonjs/resolvers.d.ts +39 -0
  38. package/lib/typescript/commonjs/resolvers.d.ts.map +1 -1
  39. package/lib/typescript/module/config.d.ts +8 -0
  40. package/lib/typescript/module/config.d.ts.map +1 -1
  41. package/lib/typescript/module/index.d.ts +2 -2
  42. package/lib/typescript/module/index.d.ts.map +1 -1
  43. package/lib/typescript/module/internal/cloudKitRest.d.ts +90 -0
  44. package/lib/typescript/module/internal/cloudKitRest.d.ts.map +1 -1
  45. package/lib/typescript/module/internal/googleDriveRest.d.ts +73 -8
  46. package/lib/typescript/module/internal/googleDriveRest.d.ts.map +1 -1
  47. package/lib/typescript/module/providers/cloudKit.d.ts +32 -13
  48. package/lib/typescript/module/providers/cloudKit.d.ts.map +1 -1
  49. package/lib/typescript/module/resolvers.d.ts +39 -0
  50. package/lib/typescript/module/resolvers.d.ts.map +1 -1
  51. package/package.json +15 -3
  52. package/src/config.ts +12 -2
  53. package/src/index.ts +4 -1
  54. package/src/internal/cloudKitRest.ts +272 -29
  55. package/src/internal/googleDriveRest.ts +196 -42
  56. package/src/providers/cloudKit.ts +138 -41
  57. package/src/resolvers.ts +75 -0
@@ -1,6 +1,6 @@
1
1
  "use strict";
2
2
 
3
- import { CloudSyncError, ErrorCode } from "../errors.js";
3
+ import { CloudSyncError, ErrorCode, timedOut } from "../errors.js";
4
4
  import { byteLength } from "./bytes.js";
5
5
  import { withTimeout } from "./timeout.js";
6
6
 
@@ -28,6 +28,22 @@ const DEFAULT_TIMEOUT_MS = 30_000;
28
28
  * user-token mode needs no crypto at all: two query parameters on a `fetch`.
29
29
  */
30
30
 
31
+ /**
32
+ * CloudKit Web Services' own ceiling on a single asset upload, undocumented
33
+ * anywhere except the upload endpoint's own reference page: 15 MB, and the
34
+ * upload URL it hands out is valid for 15 minutes. Native `CKAsset` has no such
35
+ * limit - this is specific to the REST upload-token protocol.
36
+ */
37
+ export const MAX_ASSET_UPLOAD_BYTES = 15 * 1024 * 1024;
38
+
39
+ /**
40
+ * The "Asset Dictionary" CloudKit Web Services deals in - what the upload
41
+ * endpoint returns after receiving bytes, and what a fetched record's Asset
42
+ * field value looks like. Passed back verbatim as a record field's value to
43
+ * attach an upload to a record; never reconstructed field-by-field, since it
44
+ * is an opaque blob the server itself validates.
45
+ */
46
+
31
47
  /**
32
48
  * How many operations one `/records/modify` or `/records/lookup` call carries.
33
49
  *
@@ -127,6 +143,27 @@ export class CloudKitRestClient {
127
143
  return new CloudSyncError(ErrorCode.UNKNOWN, message, base);
128
144
  }
129
145
  }
146
+
147
+ /**
148
+ * HTTP-status classification for a response with no CloudKit error envelope
149
+ * of its own to inspect - `post()`'s fallback tail, and the raw asset-bytes
150
+ * transfer, which talks to an opaque single-use upload/download URL rather
151
+ * than a `/records/...` JSON endpoint.
152
+ */
153
+ async classifyHttpStatus(status) {
154
+ if (status === 401 || status === 421) {
155
+ await this.handleAuthExpired();
156
+ return new CloudSyncError(ErrorCode.AUTH_EXPIRED, `[RNCloudSync] CloudKit returned HTTP ${status}; the web auth token is no longer valid.`, {
157
+ provider: 'cloudKit'
158
+ });
159
+ }
160
+ if (status === 429 || status === 503) return new CloudSyncError(ErrorCode.RATE_LIMITED, `[RNCloudSync] CloudKit returned HTTP ${status}.`, {
161
+ provider: 'cloudKit'
162
+ });
163
+ return new CloudSyncError(ErrorCode.UNKNOWN, `[RNCloudSync] CloudKit returned HTTP ${status}.`, {
164
+ provider: 'cloudKit'
165
+ });
166
+ }
130
167
  async post(path, body) {
131
168
  const token = await this.requireAuthToken();
132
169
  const url = `${this.baseUrl()}${path}` + `?ckAPIToken=${encodeURIComponent(this.config.apiToken)}` + `&ckWebAuthToken=${encodeURIComponent(token)}`;
@@ -154,21 +191,9 @@ export class CloudKitRestClient {
154
191
  // reach - 421 responses carry no `records`, so an error nested-lookup misses
155
192
  // it entirely. Check the root BEFORE looking at per-record results.
156
193
  if (json?.serverErrorCode != null) throw await this.toError(json.serverErrorCode, json.reason, json.retryAfter);
157
- if (!res.ok) {
158
- // HTTP-level failure with no parseable CloudKit error body.
159
- if (res.status === 401 || res.status === 421) {
160
- await this.handleAuthExpired();
161
- throw new CloudSyncError(ErrorCode.AUTH_EXPIRED, `[RNCloudSync] CloudKit returned HTTP ${res.status}; the web auth token is no longer valid.`, {
162
- provider: 'cloudKit'
163
- });
164
- }
165
- if (res.status === 429 || res.status === 503) throw new CloudSyncError(ErrorCode.RATE_LIMITED, `[RNCloudSync] CloudKit returned HTTP ${res.status}.`, {
166
- provider: 'cloudKit'
167
- });
168
- throw new CloudSyncError(ErrorCode.UNKNOWN, `[RNCloudSync] CloudKit returned HTTP ${res.status}.`, {
169
- provider: 'cloudKit'
170
- });
171
- }
194
+
195
+ // HTTP-level failure with no parseable CloudKit error body.
196
+ if (!res.ok) throw await this.classifyHttpStatus(res.status);
172
197
  return json ?? {};
173
198
  }
174
199
  async getRecord(recordName, recordType = RECORD_TYPE_DEFAULT) {
@@ -315,14 +340,25 @@ export class CloudKitRestClient {
315
340
  limitBytes: MAX_RECORD_BYTES,
316
341
  actualBytes: bytes
317
342
  });
343
+ await this.saveFields(recordName, {
344
+ [VALUE_FIELD]: {
345
+ value
346
+ }
347
+ }, recordType);
348
+ }
349
+
350
+ /**
351
+ * Creates `recordName`, falling back to an unconditional update when it
352
+ * already exists - the create-then-fall-back dance every write after the
353
+ * first one takes. Shared by {@link saveRecord} (a `value` field) and
354
+ * {@link uploadAsset} (an Asset field plus its `__size` sidecar), which need
355
+ * the exact same dance for a different field set.
356
+ */
357
+ async saveFields(recordName, fields, recordType) {
318
358
  const record = {
319
359
  recordType,
320
360
  recordName,
321
- fields: {
322
- [VALUE_FIELD]: {
323
- value
324
- }
325
- }
361
+ fields
326
362
  };
327
363
 
328
364
  // `atomic` defaults to true server-side. Setting it explicitly documents the
@@ -369,6 +405,154 @@ export class CloudKitRestClient {
369
405
  }
370
406
  }
371
407
 
408
+ /**
409
+ * Uploads `bytes` as `fieldName` on `recordName`, via CloudKit Web Services'
410
+ * asset-upload protocol: request a single-use upload URL, POST the raw bytes
411
+ * to it, then attach the descriptor it returns (plus a `__size` sidecar, so
412
+ * a later {@link fetchAsset} can report real download progress) to the
413
+ * record - the same create-then-update dance {@link saveRecord} uses.
414
+ *
415
+ * `onProgress` reports real bytes transferred, via `XMLHttpRequest` rather
416
+ * than `fetch` - see {@link CloudKitRestConfig.xhrImpl}.
417
+ */
418
+ async uploadAsset(recordName, fieldName, bytes, onProgress, recordType = RECORD_TYPE_DEFAULT) {
419
+ if (bytes.length > MAX_ASSET_UPLOAD_BYTES) throw new CloudSyncError(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.`, {
420
+ provider: 'cloudKit',
421
+ limitBytes: MAX_ASSET_UPLOAD_BYTES,
422
+ actualBytes: bytes.length
423
+ });
424
+ const uploadUrl = await this.requestAssetUploadUrl(recordType, recordName, fieldName);
425
+ const descriptor = await this.putAssetBytes(uploadUrl, bytes, onProgress);
426
+ await this.saveFields(recordName, {
427
+ [fieldName]: {
428
+ value: descriptor
429
+ },
430
+ [`${fieldName}__size`]: {
431
+ value: bytes.length
432
+ }
433
+ }, recordType);
434
+ }
435
+
436
+ /**
437
+ * Downloads the bytes behind `fieldName` on `recordName`, or `null` when the
438
+ * record or the field's asset does not exist.
439
+ *
440
+ * A fetched record's Asset field carries a `downloadURL` - that is the only
441
+ * step this needs beyond the usual record lookup; there is no separate
442
+ * "request a download token" round trip the way upload has one.
443
+ */
444
+ async fetchAsset(recordName, fieldName, onProgress, recordType = RECORD_TYPE_DEFAULT) {
445
+ void recordType;
446
+ const json = await this.post('/records/lookup', {
447
+ records: [{
448
+ recordName
449
+ }]
450
+ });
451
+ const record = json.records?.find(r => r.recordName === recordName) ?? json.records?.[0];
452
+ if (record == null) return null;
453
+ if (record.serverErrorCode != null) {
454
+ if (record.serverErrorCode === 'NOT_FOUND') return null;
455
+ throw await this.toError(record.serverErrorCode, record.reason, record.retryAfter);
456
+ }
457
+ const asset = record.fields?.[fieldName]?.value;
458
+ if (asset?.downloadURL == null) return null;
459
+ return await this.fetchAssetBytes(asset.downloadURL, onProgress);
460
+ }
461
+ async requestAssetUploadUrl(recordType, recordName, fieldName) {
462
+ const json = await this.post('/assets/upload', {
463
+ tokens: [{
464
+ recordType,
465
+ recordName,
466
+ fieldName
467
+ }]
468
+ });
469
+ const url = json.tokens?.[0]?.url;
470
+ if (url == null) throw new CloudSyncError(ErrorCode.UNKNOWN, '[RNCloudSync] CloudKit did not return an asset upload URL.', {
471
+ provider: 'cloudKit'
472
+ });
473
+ return url;
474
+ }
475
+ get xhr() {
476
+ return this.config.xhrImpl ?? (() => new XMLHttpRequest());
477
+ }
478
+
479
+ /**
480
+ * POSTs raw bytes to a single-use CKWS asset-upload URL, reporting real
481
+ * upload progress via `XMLHttpRequest.upload.onprogress` - `fetch` exposes no
482
+ * upload-progress events in React Native. Scoped to just this one call:
483
+ * every other CloudKit REST request stays on `fetch` through `post()`, for
484
+ * the timeout/error handling already built there.
485
+ */
486
+ putAssetBytes(url, bytes, onProgress) {
487
+ return new Promise((resolve, reject) => {
488
+ const req = this.xhr();
489
+ req.open('POST', url);
490
+ req.timeout = this.config.timeoutMs ?? DEFAULT_TIMEOUT_MS;
491
+ req.upload.onprogress = e => {
492
+ if (e.lengthComputable) onProgress?.(e.loaded, e.total);
493
+ };
494
+ req.onload = () => {
495
+ if (req.status < 200 || req.status >= 300) {
496
+ this.classifyHttpStatus(req.status).then(reject).catch(reject);
497
+ return;
498
+ }
499
+ try {
500
+ const json = JSON.parse(req.responseText);
501
+ if (json.singleFile == null) throw new Error('response had no singleFile');
502
+ onProgress?.(bytes.length, bytes.length);
503
+ resolve(json.singleFile);
504
+ } catch (e) {
505
+ reject(new CloudSyncError(ErrorCode.UNKNOWN, '[RNCloudSync] CloudKit did not return an asset descriptor after upload.', {
506
+ provider: 'cloudKit',
507
+ cause: e
508
+ }));
509
+ }
510
+ };
511
+ req.onerror = () => reject(new CloudSyncError(ErrorCode.NETWORK_UNAVAILABLE, '[RNCloudSync] CloudKit asset upload failed to reach the server.', {
512
+ provider: 'cloudKit'
513
+ }));
514
+ req.ontimeout = () => reject(timedOut(req.timeout, 'cloudKit'));
515
+ req.send(bytes);
516
+ });
517
+ }
518
+
519
+ /**
520
+ * GETs raw bytes from a record's asset `downloadURL`, reporting real
521
+ * download progress via `XMLHttpRequest.onprogress`, for the same reason
522
+ * {@link putAssetBytes} uses XHR rather than `fetch`.
523
+ *
524
+ * Treated as self-contained, the same way the upload URL is (Apple's own
525
+ * reference issues that one with no `ckAPIToken`/`ckWebAuthToken` at all) -
526
+ * if that assumption is ever wrong for a download URL specifically, it
527
+ * surfaces as an HTTP-level auth failure here rather than a silent wrong
528
+ * answer.
529
+ */
530
+ fetchAssetBytes(url, onProgress) {
531
+ return new Promise((resolve, reject) => {
532
+ const req = this.xhr();
533
+ req.open('GET', url);
534
+ req.responseType = 'arraybuffer';
535
+ req.timeout = this.config.timeoutMs ?? DEFAULT_TIMEOUT_MS;
536
+ req.onprogress = e => {
537
+ if (e.lengthComputable) onProgress?.(e.loaded, e.total);
538
+ };
539
+ req.onload = () => {
540
+ if (req.status < 200 || req.status >= 300) {
541
+ this.classifyHttpStatus(req.status).then(reject).catch(reject);
542
+ return;
543
+ }
544
+ const buf = req.response;
545
+ onProgress?.(buf.byteLength, buf.byteLength);
546
+ resolve(new Uint8Array(buf));
547
+ };
548
+ req.onerror = () => reject(new CloudSyncError(ErrorCode.NETWORK_UNAVAILABLE, '[RNCloudSync] CloudKit asset download failed to reach the server.', {
549
+ provider: 'cloudKit'
550
+ }));
551
+ req.ontimeout = () => reject(timedOut(req.timeout, 'cloudKit'));
552
+ req.send();
553
+ });
554
+ }
555
+
372
556
  /**
373
557
  * A write that fails instead of clobbering, when the server's copy has moved
374
558
  * on since `recordChangeTag` was read.
@@ -1 +1 @@
1
- {"version":3,"names":["CloudSyncError","ErrorCode","byteLength","withTimeout","DEFAULT_TIMEOUT_MS","MAX_BATCH","RECORD_TYPE_DEFAULT","VALUE_FIELD","MAX_RECORD_BYTES","EXISTS_CODES","Set","isAlreadyExists","e","serverErrorCode","has","code","CONFLICT","REACHABILITY_TTL_MS","AVAILABILITY_PROBE_RECORD","CloudKitRestClient","reachability","constructor","config","baseUrl","containerIdentifier","environment","fetch","fetchImpl","globalThis","requireAuthToken","apiToken","CONTAINER_MISCONFIGURED","provider","token","getAuthToken","NOT_SIGNED_IN","handleAuthExpired","onAuthExpired","toError","reason","retryAfter","serverValue","message","base","AUTH_EXPIRED","QUOTA_EXCEEDED","RATE_LIMITED","retryAfterMs","undefined","UNKNOWN","post","path","body","url","encodeURIComponent","res","method","headers","JSON","stringify","timeoutMs","NETWORK_UNAVAILABLE","cause","json","catch","ok","status","getRecord","recordName","recordType","getRecordWithMeta","value","records","record","find","r","fields","modifiedAt","modified","timestamp","recordChangeTag","getRecords","recordNames","length","found","Map","batch","chunk","map","set","name","get","saveRecords","entries","bytes","PAYLOAD_TOO_LARGE","limitBytes","actualBytes","atomic","operations","operationType","deleteRecords","saveRecord","created","createdRecord","updated","updatedRecord","serverRecord","saveRecordIfUnchanged","result","deleteRecord","queryRecordNames","names","seenMarkers","continuationMarker","query","push","add","isReachable","now","Date","at","clearCache","items","size","out","i","slice"],"sourceRoot":"../../../src","sources":["internal/cloudKitRest.ts"],"mappings":";;AAAA,SAASA,cAAc,EAAEC,SAAS,QAAQ,cAAW;AACrD,SAASC,UAAU,QAAQ,YAAS;AACpC,SAASC,WAAW,QAAQ,cAAW;;AAEvC;AACA,MAAMC,kBAAkB,GAAG,MAAM;;AAEjC;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAC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A,CAAIoC,KAAU,EAAEC,IAAY,EAAS;EACjD,IAAID,KAAK,CAACxC,MAAM,IAAIyC,IAAI,EAAE,OAAO,CAACD,KAAK,CAAC;EACxC,MAAME,GAAU,GAAG,EAAE;EACrB,KAAK,IAAIC,CAAC,GAAG,CAAC,EAAEA,CAAC,GAAGH,KAAK,CAACxC,MAAM,EAAE2C,CAAC,IAAIF,IAAI,EAAEC,GAAG,CAACT,IAAI,CAACO,KAAK,CAACI,KAAK,CAACD,CAAC,EAAEA,CAAC,GAAGF,IAAI,CAAC,CAAC;EAC/E,OAAOC,GAAG;AACZ;;AAEA;AACA;AACA;AACA,SAAS3H,UAAU,QAAQ,YAAS","ignoreList":[]}
1
+ {"version":3,"names":["CloudSyncError","ErrorCode","timedOut","byteLength","withTimeout","DEFAULT_TIMEOUT_MS","MAX_ASSET_UPLOAD_BYTES","MAX_BATCH","RECORD_TYPE_DEFAULT","VALUE_FIELD","MAX_RECORD_BYTES","EXISTS_CODES","Set","isAlreadyExists","e","serverErrorCode","has","code","CONFLICT","REACHABILITY_TTL_MS","AVAILABILITY_PROBE_RECORD","CloudKitRestClient","reachability","constructor","config","baseUrl","containerIdentifier","environment","fetch","fetchImpl","globalThis","requireAuthToken","apiToken","CONTAINER_MISCONFIGURED","provider","token","getAuthToken","NOT_SIGNED_IN","handleAuthExpired","onAuthExpired","toError","reason","retryAfter","serverValue","message","base","AUTH_EXPIRED","QUOTA_EXCEEDED","RATE_LIMITED","retryAfterMs","undefined","UNKNOWN","classifyHttpStatus","status","post","path","body","url","encodeURIComponent","res","method","headers","JSON","stringify","timeoutMs","NETWORK_UNAVAILABLE","cause","json","catch","ok","getRecord","recordName","recordType","getRecordWithMeta","value","records","record","find","r","fields","modifiedAt","modified","timestamp","recordChangeTag","getRecords","recordNames","length","found","Map","batch","chunk","map","set","name","get","saveRecords","entries","bytes","PAYLOAD_TOO_LARGE","limitBytes","actualBytes","atomic","operations","operationType","deleteRecords","saveRecord","saveFields","created","createdRecord","updated","updatedRecord","serverRecord","uploadAsset","fieldName","onProgress","uploadUrl","requestAssetUploadUrl","descriptor","putAssetBytes","fetchAsset","asset","downloadURL","fetchAssetBytes","tokens","xhr","xhrImpl","XMLHttpRequest","Promise","resolve","reject","req","open","timeout","upload","onprogress","lengthComputable","loaded","total","onload","then","parse","responseText","singleFile","Error","onerror","ontimeout","send","responseType","buf","response","Uint8Array","saveRecordIfUnchanged","result","deleteRecord","queryRecordNames","names","seenMarkers","continuationMarker","query","push","add","isReachable","now","Date","at","clearCache","items","size","out","i","slice"],"sourceRoot":"../../../src","sources":["internal/cloudKitRest.ts"],"mappings":";;AAAA,SAASA,cAAc,EAAEC,SAAS,EAAEC,QAAQ,QAAQ,cAAW;AAC/D,SAASC,UAAU,QAAQ,YAAS;AACpC,SAASC,WAAW,QAAQ,cAAW;;AAEvC;AACA,MAAMC,kBAAkB,GAAG,MAAM;;AAEjC;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AA8CA;AACA;AACA;AACA;AACA;AACA;AACA,OAAO,MAAMC,sBAAsB,GAAG,EAAE,GAAG,IAAI,GAAG,IAAI;;AAEtD;AACA;AACA;AACA;AACA;AACA;AACA;;AAWA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAMC,SAAS,GAAG,GAAG;AAErB,OAAO,MAAMC,mBAAmB,GAAG,QAAQ;AAC3C,OAAO,MAAMC,WAAW,GAAG,OAAO;;AAElC;AACA,OAAO,MAAMC,gBAAgB,GAAG,IAAI,GAAG,IAAI;AAuC3C;AACA;AACA;AACA;AACA;AACA;AACA,MAAMC,YAAY,GAAG,IAAIC,GAAG,CAAC,CAAC,QAAQ,EAAE,UAAU,EAAE,cAAc,CAAC,CAAC;AAEpE,SAASC,eAAeA,CAACC,CAAU,EAAW;EAC5C,IAAI,EAAEA,CAAC,YAAYd,cAAc,CAAC,EAAE,OAAO,KAAK;EAChD,IAAIc,CAA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AAE;IAE7B,IAAIA,EAAW;IACf,IAAI;MACF;MACA;MACA,MAAM,IAAI,CAACC,SAAS,CAAClD,yBAAyB,CAAC;MAC/CiD,EAAE,GAAG,IAAI;IACX,CAAC,CACD,MAAM;MACJA,EAAE,GAAG,KAAK;IACZ;IAEA,IAAI,CAAC/C,YAAY,GAAG;MAAE8I,EAAE,EAAEF,GAAG;MAAE7F;IAAG,CAAC;IACnC,OAAOA,EAAE;EACX;;EAEA;AACF;AACA;AACA;AACA;AACA;EACEgG,UAAUA,CAAA,EAAS;IACjB,IAAI,CAAC/I,YAAY,GAAG,IAAI;EAC1B;AACF;;AAEA;AACA,SAASoE,KAAKA,CAAI4E,KAAU,EAAEC,IAAY,EAAS;EACjD,IAAID,KAAK,CAAChF,MAAM,IAAIiF,IAAI,EAAE,OAAO,CAACD,KAAK,CAAC;EACxC,MAAME,GAAU,GAAG,EAAE;EACrB,KAAK,IAAIC,CAAC,GAAG,CAAC,EAAEA,CAAC,GAAGH,KAAK,CAAChF,MAAM,EAAEmF,CAAC,IAAIF,IAAI,EAAEC,GAAG,CAACT,IAAI,CAACO,KAAK,CAACI,KAAK,CAACD,CAAC,EAAEA,CAAC,GAAGF,IAAI,CAAC,CAAC;EAC/E,OAAOC,GAAG;AACZ;;AAEA;AACA;AACA;AACA,SAASrK,UAAU,QAAQ,YAAS","ignoreList":[]}
@@ -1,14 +1,17 @@
1
1
  "use strict";
2
2
 
3
- import { CloudSyncError, ErrorCode } from "../errors.js";
3
+ import { CloudSyncError, ErrorCode, isCancelled } from "../errors.js";
4
4
  import { throwIfAborted, withTimeout } from "./timeout.js";
5
5
 
6
6
  /**
7
7
  * Google Drive `appDataFolder` REST client.
8
8
  *
9
9
  * `appDataFolder` is a hidden per-app, per-Google-account folder: nothing shows
10
- * up in the user's visible Drive, and the data survives an app uninstall because
11
- * it is tied to the account rather than the install.
10
+ * up in the user's visible Drive, and the data is tied to the Google account
11
+ * rather than the device or install, so reinstalling the app or switching
12
+ * devices doesn't lose it. It goes away only if the user disconnects the app
13
+ * from their Drive account or deletes the data folder directly - Google
14
+ * documents both as the ways this folder is actually removed.
12
15
  *
13
16
  * Auth is deliberately injected rather than owned. The library does not depend
14
17
  * on `@react-native-google-signin/google-signin` (or any other sign-in library),
@@ -16,6 +19,13 @@ import { throwIfAborted, withTimeout } from "./timeout.js";
16
19
  * unchanged in a browser where that library does not apply.
17
20
  */
18
21
 
22
+ /** What `uploadFile` needs to resume a resumable-upload session later. */
23
+
24
+ /**
25
+ * Host-supplied persistence for in-flight `uploadFile` sessions, keyed by the
26
+ * Drive file name. See {@link GoogleDriveConfig.sessionStore}.
27
+ */
28
+
19
29
  const FILES_URL = 'https://www.googleapis.com/drive/v3/files';
20
30
  const UPLOAD_URL = 'https://www.googleapis.com/upload/drive/v3/files';
21
31
  const ABOUT_URL = 'https://www.googleapis.com/drive/v3/about';
@@ -111,22 +121,39 @@ export class GoogleDriveClient {
111
121
  });
112
122
  }
113
123
  if (res.ok || extraOkStatuses.includes(res.status)) return res;
114
- if (res.status === 401 || res.status === 403) {
124
+ if (res.status === 401) {
115
125
  await this.config.onAuthExpired?.();
116
- throw new CloudSyncError(ErrorCode.AUTH_EXPIRED, `[RNCloudSync] Google Drive returned HTTP ${res.status}; the access token is not valid.`, {
126
+ throw new CloudSyncError(ErrorCode.AUTH_EXPIRED, '[RNCloudSync] Google Drive returned HTTP 401; the access token is not valid.', {
127
+ provider: 'googleDrive'
128
+ });
129
+ }
130
+ if (res.status === 403) {
131
+ // Drive overloads 403 for three unrelated conditions, distinguished only by
132
+ // `error.errors[0].reason` in the body - never by a different status code.
133
+ // Quota-exceeded in particular is NOT the 507 a WebDAV-flavoured API might
134
+ // use; Drive documents it as 403 `storageQuotaExceeded`, so treating it as
135
+ // an auth failure (and wrongly prompting reconnect) is the wrong default.
136
+ const reason = await this.driveErrorReason(res);
137
+ if (reason === 'storageQuotaExceeded') throw new CloudSyncError(ErrorCode.QUOTA_EXCEEDED, '[RNCloudSync] Google Drive storage quota exceeded.', {
138
+ provider: 'googleDrive'
139
+ });
140
+ if (reason === 'userRateLimitExceeded' || reason === 'rateLimitExceeded') throw new CloudSyncError(ErrorCode.RATE_LIMITED, '[RNCloudSync] Google Drive rate limited the request.', {
141
+ provider: 'googleDrive'
142
+ });
143
+ await this.config.onAuthExpired?.();
144
+ throw new CloudSyncError(ErrorCode.AUTH_EXPIRED, '[RNCloudSync] Google Drive returned HTTP 403; the access token is not valid or lacks permission.', {
117
145
  provider: 'googleDrive'
118
146
  });
119
147
  }
120
148
  if (res.status === 429) {
149
+ // The request-frequency case, distinct from the per-user 403 variants
150
+ // above - this one really is a plain 429, no reason string to parse.
121
151
  const retryAfter = Number(res.headers.get('Retry-After'));
122
152
  throw new CloudSyncError(ErrorCode.RATE_LIMITED, '[RNCloudSync] Google Drive rate limited the request.', {
123
153
  provider: 'googleDrive',
124
154
  retryAfterMs: Number.isFinite(retryAfter) ? retryAfter * 1000 : undefined
125
155
  });
126
156
  }
127
- if (res.status === 507) throw new CloudSyncError(ErrorCode.QUOTA_EXCEEDED, '[RNCloudSync] Google Drive storage quota exceeded.', {
128
- provider: 'googleDrive'
129
- });
130
157
  // Tagged so callers can tell "this file id is gone" from a generic failure.
131
158
  // Without the tag a stale memoised id was indistinguishable from a real
132
159
  // error, so it could never be recovered from.
@@ -139,6 +166,22 @@ export class GoogleDriveClient {
139
166
  });
140
167
  }
141
168
 
169
+ /**
170
+ * Best-effort read of Drive's `error.errors[0].reason` from a failed
171
+ * response body - the only way a 403 status distinguishes an invalid token
172
+ * from quota-exceeded from a rate limit. Returns undefined for a body that
173
+ * is missing, unparseable, or doesn't carry the shape Drive documents,
174
+ * rather than throwing a second error while already handling one.
175
+ */
176
+ async driveErrorReason(res) {
177
+ try {
178
+ const json = await res.json();
179
+ return json.error?.errors?.[0]?.reason;
180
+ } catch {
181
+ return undefined;
182
+ }
183
+ }
184
+
142
185
  /**
143
186
  * Resolves a file name to its id within appDataFolder, or null if absent.
144
187
  *
@@ -152,8 +195,11 @@ export class GoogleDriveClient {
152
195
  this.idCache.delete(name);
153
196
 
154
197
  // Scope the query server-side. Escaping matters: an apostrophe in a key
155
- // would otherwise terminate the quoted literal and produce a malformed query.
156
- const q = encodeURIComponent(`name='${name.replace(/'/g, '\\\'')}' and trashed=false`);
198
+ // would otherwise terminate the quoted literal and produce a malformed
199
+ // query - and a literal backslash needs the same treatment, escaped FIRST
200
+ // so it doesn't double-escape the backslash the quote-escaping just added.
201
+ const escaped = name.replace(/\\/g, '\\\\').replace(/'/g, '\\\'');
202
+ const q = encodeURIComponent(`name='${escaped}' and trashed=false`);
157
203
  const url = `${FILES_URL}?spaces=appDataFolder&q=${q}&fields=files(${FILE_FIELDS})&pageSize=10`;
158
204
  const res = await this.request(url, {
159
205
  method: 'GET'
@@ -319,37 +365,97 @@ export class GoogleDriveClient {
319
365
  * how many bytes it actually has and resuming from there - rather than
320
366
  * restarting the transfer.
321
367
  *
322
- * That resumability is scoped to this call: the session lives only in
323
- * memory, so if the process dies mid-upload, the next call to `uploadFile`
324
- * starts a fresh session from byte 0. Persisting the session URI so a
325
- * restart can resume it too is future scope, not something callers should
326
- * assume works today.
368
+ * That resumability spans a process restart too, when {@link
369
+ * GoogleDriveConfig.sessionStore} is configured: the session URI is persisted
370
+ * before the first chunk goes out, and a later `uploadFile` for the same name
371
+ * finds it, asks Drive for the real offset, and resumes from there instead of
372
+ * byte 0. Without a `sessionStore`, the session lives only in memory, exactly
373
+ * as before - a process that dies mid-upload loses it, and the next call
374
+ * starts fresh.
327
375
  */
328
376
  async uploadFile(name, source, onProgress, signal) {
329
377
  throwIfAborted(signal, 'googleDrive');
330
- const existingId = await this.findFileId(name);
331
- const sessionUrl = await this.startResumableSession(name, existingId);
332
- let offset = 0;
333
- let newId;
334
378
  const total = source.size;
335
-
336
- // A zero-byte file still needs one request to actually create it.
337
- do {
338
- // Checked between chunks rather than only up front: a cancel during a
339
- // multi-hundred-megabyte transfer has to take effect while it is running,
340
- // which is the entire point of being able to cancel one.
341
- throwIfAborted(signal, 'googleDrive');
342
- const length = Math.min(this.chunkBytes, total - offset);
343
- const step = await this.putChunkWithRetry(sessionUrl, source, offset, length, total, onProgress);
344
- offset = step.nextOffset;
345
- if (step.id != null) newId = step.id;
346
- } while (offset < total);
379
+ const resumed = await this.resumeOrStartSession(name, total);
380
+
381
+ // The resumed session was already complete server-side - most likely the
382
+ // last chunk's own response was what got lost to the process dying, not
383
+ // the chunk itself. Nothing left to send.
384
+ if (resumed.completed) {
385
+ if (resumed.id != null) this.idCache.set(name, resumed.id);
386
+ await this.config.sessionStore?.remove(name);
387
+ onProgress?.(total, total);
388
+ return;
389
+ }
390
+ const sessionUrl = resumed.sessionUrl;
391
+ let offset = resumed.offset;
392
+ let newId;
393
+ try {
394
+ // A zero-byte file still needs one request to actually create it.
395
+ do {
396
+ // Checked between chunks rather than only up front: a cancel during a
397
+ // multi-hundred-megabyte transfer has to take effect while it is running,
398
+ // which is the entire point of being able to cancel one.
399
+ throwIfAborted(signal, 'googleDrive');
400
+ const length = Math.min(this.chunkBytes, total - offset);
401
+ const step = await this.putChunkWithRetry(sessionUrl, source, offset, length, total, onProgress);
402
+ offset = step.nextOffset;
403
+ if (step.id != null) newId = step.id;
404
+ } while (offset < total);
405
+ } catch (e) {
406
+ // A deliberate cancel abandons the session - the caller asked to stop,
407
+ // not to resume later. Any other failure (network drop, timeout, the
408
+ // process itself dying) leaves the persisted session in place, since
409
+ // that is precisely what lets the next call resume instead of restarting.
410
+ if (isCancelled(e)) await this.config.sessionStore?.remove(name);
411
+ throw e;
412
+ }
347
413
 
348
414
  // A create only learns its id from the final response; an update already
349
415
  // had one via `existingId`.
350
416
  if (newId != null) this.idCache.set(name, newId);
417
+ await this.config.sessionStore?.remove(name);
351
418
  onProgress?.(total, total);
352
419
  }
420
+
421
+ /**
422
+ * Finds an existing session to resume, or starts a new one.
423
+ *
424
+ * A persisted session is trusted only when its recorded size still matches
425
+ * `total` - resuming a byte-range PUT into a file that has since changed
426
+ * would corrupt it, so a mismatch is treated the same as no session at all.
427
+ * A persisted session Drive no longer recognises (expired, or the upload id
428
+ * was never valid) is also treated as absent: `queryUploadOffset` failing is
429
+ * the signal, since there is no cheaper way to ask than trying to use it.
430
+ */
431
+ async resumeOrStartSession(name, total) {
432
+ const persisted = await this.config.sessionStore?.get(name);
433
+ if (persisted != null && persisted.size === total) try {
434
+ const {
435
+ offset,
436
+ id
437
+ } = await this.queryUploadOffset(persisted.sessionUrl, total);
438
+ return {
439
+ sessionUrl: persisted.sessionUrl,
440
+ offset,
441
+ completed: offset >= total,
442
+ id
443
+ };
444
+ } catch {
445
+ // Falls through to starting a fresh session below.
446
+ }
447
+ const existingId = await this.findFileId(name);
448
+ const sessionUrl = await this.startResumableSession(name, existingId);
449
+ await this.config.sessionStore?.set(name, {
450
+ sessionUrl,
451
+ size: total
452
+ });
453
+ return {
454
+ sessionUrl,
455
+ offset: 0,
456
+ completed: false
457
+ };
458
+ }
353
459
  async startResumableSession(name, existingId) {
354
460
  const url = existingId != null ? `${UPLOAD_URL}/${existingId}?uploadType=resumable` : `${UPLOAD_URL}?uploadType=resumable&fields=id`;
355
461
  const metadata = existingId != null ? {} : {
@@ -376,9 +482,19 @@ export class GoogleDriveClient {
376
482
  return await this.putChunk(sessionUrl, source, offset, length, total, onProgress);
377
483
  } catch (e) {
378
484
  if (!isRetryableTransfer(e)) throw e;
379
- const resumeFrom = await this.queryUploadOffset(sessionUrl, total);
380
- const retryLength = Math.min(this.chunkBytes, total - resumeFrom);
381
- return await this.putChunk(sessionUrl, source, resumeFrom, retryLength, total, onProgress);
485
+ const resumed = await this.queryUploadOffset(sessionUrl, total);
486
+ // The dropped chunk's own response was what got lost, not the chunk -
487
+ // Drive already has everything. A retry PUT here would send a zero-length,
488
+ // malformed Content-Range (end before start).
489
+ if (resumed.offset >= total) {
490
+ onProgress?.(total, total);
491
+ return {
492
+ nextOffset: total,
493
+ id: resumed.id
494
+ };
495
+ }
496
+ const retryLength = Math.min(this.chunkBytes, total - resumed.offset);
497
+ return await this.putChunk(sessionUrl, source, resumed.offset, retryLength, total, onProgress);
382
498
  }
383
499
  }
384
500
  async putChunk(sessionUrl, source, offset, length, total, onProgress) {
@@ -410,7 +526,17 @@ export class GoogleDriveClient {
410
526
  };
411
527
  }
412
528
 
413
- /** Asks Drive how much of an in-flight resumable session it actually has. */
529
+ /**
530
+ * Asks Drive how much of an in-flight resumable session it actually has, or
531
+ * discovers the upload was already complete server-side - the completing
532
+ * chunk's own response can be lost the same way any other one can, and this
533
+ * status check gets the same completion response back in that case,
534
+ * `id` included.
535
+ *
536
+ * Throws (via `request`) when `sessionUrl` is not a session Drive
537
+ * recognises any more - expired, or never valid. Callers treat that as the
538
+ * signal to stop trusting it, since there is no cheaper way to ask.
539
+ */
414
540
  async queryUploadOffset(sessionUrl, total) {
415
541
  const res = await this.request(sessionUrl, {
416
542
  method: 'PUT',
@@ -418,12 +544,21 @@ export class GoogleDriveClient {
418
544
  'Content-Range': `bytes */${total}`
419
545
  }
420
546
  }, [308]);
421
- if (res.status !== 308) return total; // already complete, unexpectedly
422
-
547
+ if (res.status !== 308) {
548
+ const json = await res.json().catch(() => null);
549
+ return {
550
+ offset: total,
551
+ id: json?.id ?? undefined
552
+ };
553
+ }
423
554
  const range = res.headers.get('Range'); // "bytes=0-8388607"
424
- if (range == null) return 0;
555
+ if (range == null) return {
556
+ offset: 0
557
+ };
425
558
  const match = /bytes=0-(\d+)/.exec(range);
426
- return match ? Number(match[1]) + 1 : 0;
559
+ return {
560
+ offset: match ? Number(match[1]) + 1 : 0
561
+ };
427
562
  }
428
563
 
429
564
  /**