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
@@ -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.
@@ -1 +1 @@
1
- {"version":3,"names":["_errors","require","_bytes","_timeout","DEFAULT_TIMEOUT_MS","MAX_BATCH","RECORD_TYPE_DEFAULT","exports","VALUE_FIELD","MAX_RECORD_BYTES","EXISTS_CODES","Set","isAlreadyExists","e","CloudSyncError","serverErrorCode","has","code","ErrorCode","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","withTimeout","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","byteLength","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,IAAAA,OAAA,GAAAC,OAAA;AACA,IAAAC,MAAA,GAAAD,OAAA;AACA,IAAAE,QAAA,GAAAF,OAAA;AAEA;AACA,MAAMG,kBAAkB,GAAG,MAAM;;AAEjC;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAoCA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAMC,SAAS,GAAG,GAAG;AAEd,MAAMC,mBAAmB,GAAAC,OAAA,CAAAD,mBAAA,GAAG,QAAQ;AACpC,MAAME,WAAW,GAAAD,OAAA,CAAAC,WAAA,GAAG,OAAO;;AAElC;AACO,MAAMC,gBAAgB,GAAAF,OAAA,CAAAE,gBAAA,GAAG,IAAI,GAAG,IAAI;AAqC3C;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,YAAYC,sBAAc,CAAC,EAAE,OAAO,KAAK;EAChD,IAAID,CAAC,CAACE,eAAe,IAAI,IAAI,EAAE,OAAOL,YAAY,CAACM,GAAG,CAACH,CAAC,CAACE,eAAe,CAAC;EACzE,OAAOF,CAAC,CAACI,IAAI,KAAKC,iBAAS,CAACC,QAAQ;AACtC;;AAEA;AACA,MAAMC,mBAAmB,GAAG,MAAM;;AAElC;AACA,MAAMC,yBAAyB,GAAG,6BAA6B;AAExD,MAAMC,kBAAkB,CAAC;EAEtBC,YAAY,GAAuC,IAAI;EAE/DC,WAAWA,CAACC,MAA0B,EAAE;IACtC,IAAI,CAACA,MAAM,GAAGA,MAAM;EAC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C/E,OAAO,IAAI,CAACG,YAAY,CAAC8C,EAAE;IAE7B,IAAIA,EAAW;IACf,IAAI;MACF;MACA;MACA,MAAM,IAAI,CAACE,SAAS,CAAClD,yBAAyB,CAAC;MAC/CgD,EAAE,GAAG,IAAI;IACX,CAAC,CACD,MAAM;MACJA,EAAE,GAAG,KAAK;IACZ;IAEA,IAAI,CAAC9C,YAAY,GAAG;MAAEuG,EAAE,EAAEF,GAAG;MAAEvD;IAAG,CAAC;IACnC,OAAOA,EAAE;EACX;;EAEA;AACF;AACA;AACA;AACA;AACA;EACE0D,UAAUA,CAAA,EAAS;IACjB,IAAI,CAACxG,YAAY,GAAG,IAAI;EAC1B;AACF;;AAEA;AAAAhB,OAAA,CAAAe,kBAAA,GAAAA,kBAAA;AACA,SAASqE,KAAKA,CAAIqC,KAAU,EAAEC,IAAY,EAAS;EACjD,IAAID,KAAK,CAACzC,MAAM,IAAI0C,IAAI,EAAE,OAAO,CAACD,KAAK,CAAC;EACxC,MAAME,GAAU,GAAG,EAAE;EACrB,KAAK,IAAIC,CAAC,GAAG,CAAC,EAAEA,CAAC,GAAGH,KAAK,CAACzC,MAAM,EAAE4C,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","ignoreList":[]}
1
+ {"version":3,"names":["_errors","require","_bytes","_timeout","DEFAULT_TIMEOUT_MS","MAX_ASSET_UPLOAD_BYTES","exports","MAX_BATCH","RECORD_TYPE_DEFAULT","VALUE_FIELD","MAX_RECORD_BYTES","EXISTS_CODES","Set","isAlreadyExists","e","CloudSyncError","serverErrorCode","has","code","ErrorCode","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","withTimeout","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","byteLength","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","timedOut","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,IAAAA,OAAA,GAAAC,OAAA;AACA,IAAAC,MAAA,GAAAD,OAAA;AACA,IAAAE,QAAA,GAAAF,OAAA;AAEA;AACA,MAAMG,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;AACO,MAAMC,sBAAsB,GAAAC,OAAA,CAAAD,sBAAA,GAAG,EAAE,GAAG,IAAI,GAAG,IAA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rB,KAAK,IAAIC,CAAC,GAAG,CAAC,EAAEA,CAAC,GAAGH,KAAK,CAAClF,MAAM,EAAEqF,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","ignoreList":[]}
@@ -10,8 +10,11 @@ var _timeout = require("./timeout.js");
10
10
  * Google Drive `appDataFolder` REST client.
11
11
  *
12
12
  * `appDataFolder` is a hidden per-app, per-Google-account folder: nothing shows
13
- * up in the user's visible Drive, and the data survives an app uninstall because
14
- * it is tied to the account rather than the install.
13
+ * up in the user's visible Drive, and the data is tied to the Google account
14
+ * rather than the device or install, so reinstalling the app or switching
15
+ * devices doesn't lose it. It goes away only if the user disconnects the app
16
+ * from their Drive account or deletes the data folder directly - Google
17
+ * documents both as the ways this folder is actually removed.
15
18
  *
16
19
  * Auth is deliberately injected rather than owned. The library does not depend
17
20
  * on `@react-native-google-signin/google-signin` (or any other sign-in library),
@@ -19,6 +22,13 @@ var _timeout = require("./timeout.js");
19
22
  * unchanged in a browser where that library does not apply.
20
23
  */
21
24
 
25
+ /** What `uploadFile` needs to resume a resumable-upload session later. */
26
+
27
+ /**
28
+ * Host-supplied persistence for in-flight `uploadFile` sessions, keyed by the
29
+ * Drive file name. See {@link GoogleDriveConfig.sessionStore}.
30
+ */
31
+
22
32
  const FILES_URL = 'https://www.googleapis.com/drive/v3/files';
23
33
  const UPLOAD_URL = 'https://www.googleapis.com/upload/drive/v3/files';
24
34
  const ABOUT_URL = 'https://www.googleapis.com/drive/v3/about';
@@ -114,22 +124,39 @@ class GoogleDriveClient {
114
124
  });
115
125
  }
116
126
  if (res.ok || extraOkStatuses.includes(res.status)) return res;
117
- if (res.status === 401 || res.status === 403) {
127
+ if (res.status === 401) {
118
128
  await this.config.onAuthExpired?.();
119
- throw new _errors.CloudSyncError(_errors.ErrorCode.AUTH_EXPIRED, `[RNCloudSync] Google Drive returned HTTP ${res.status}; the access token is not valid.`, {
129
+ throw new _errors.CloudSyncError(_errors.ErrorCode.AUTH_EXPIRED, '[RNCloudSync] Google Drive returned HTTP 401; the access token is not valid.', {
130
+ provider: 'googleDrive'
131
+ });
132
+ }
133
+ if (res.status === 403) {
134
+ // Drive overloads 403 for three unrelated conditions, distinguished only by
135
+ // `error.errors[0].reason` in the body - never by a different status code.
136
+ // Quota-exceeded in particular is NOT the 507 a WebDAV-flavoured API might
137
+ // use; Drive documents it as 403 `storageQuotaExceeded`, so treating it as
138
+ // an auth failure (and wrongly prompting reconnect) is the wrong default.
139
+ const reason = await this.driveErrorReason(res);
140
+ if (reason === 'storageQuotaExceeded') throw new _errors.CloudSyncError(_errors.ErrorCode.QUOTA_EXCEEDED, '[RNCloudSync] Google Drive storage quota exceeded.', {
141
+ provider: 'googleDrive'
142
+ });
143
+ if (reason === 'userRateLimitExceeded' || reason === 'rateLimitExceeded') throw new _errors.CloudSyncError(_errors.ErrorCode.RATE_LIMITED, '[RNCloudSync] Google Drive rate limited the request.', {
144
+ provider: 'googleDrive'
145
+ });
146
+ await this.config.onAuthExpired?.();
147
+ throw new _errors.CloudSyncError(_errors.ErrorCode.AUTH_EXPIRED, '[RNCloudSync] Google Drive returned HTTP 403; the access token is not valid or lacks permission.', {
120
148
  provider: 'googleDrive'
121
149
  });
122
150
  }
123
151
  if (res.status === 429) {
152
+ // The request-frequency case, distinct from the per-user 403 variants
153
+ // above - this one really is a plain 429, no reason string to parse.
124
154
  const retryAfter = Number(res.headers.get('Retry-After'));
125
155
  throw new _errors.CloudSyncError(_errors.ErrorCode.RATE_LIMITED, '[RNCloudSync] Google Drive rate limited the request.', {
126
156
  provider: 'googleDrive',
127
157
  retryAfterMs: Number.isFinite(retryAfter) ? retryAfter * 1000 : undefined
128
158
  });
129
159
  }
130
- if (res.status === 507) throw new _errors.CloudSyncError(_errors.ErrorCode.QUOTA_EXCEEDED, '[RNCloudSync] Google Drive storage quota exceeded.', {
131
- provider: 'googleDrive'
132
- });
133
160
  // Tagged so callers can tell "this file id is gone" from a generic failure.
134
161
  // Without the tag a stale memoised id was indistinguishable from a real
135
162
  // error, so it could never be recovered from.
@@ -142,6 +169,22 @@ class GoogleDriveClient {
142
169
  });
143
170
  }
144
171
 
172
+ /**
173
+ * Best-effort read of Drive's `error.errors[0].reason` from a failed
174
+ * response body - the only way a 403 status distinguishes an invalid token
175
+ * from quota-exceeded from a rate limit. Returns undefined for a body that
176
+ * is missing, unparseable, or doesn't carry the shape Drive documents,
177
+ * rather than throwing a second error while already handling one.
178
+ */
179
+ async driveErrorReason(res) {
180
+ try {
181
+ const json = await res.json();
182
+ return json.error?.errors?.[0]?.reason;
183
+ } catch {
184
+ return undefined;
185
+ }
186
+ }
187
+
145
188
  /**
146
189
  * Resolves a file name to its id within appDataFolder, or null if absent.
147
190
  *
@@ -155,8 +198,11 @@ class GoogleDriveClient {
155
198
  this.idCache.delete(name);
156
199
 
157
200
  // Scope the query server-side. Escaping matters: an apostrophe in a key
158
- // would otherwise terminate the quoted literal and produce a malformed query.
159
- const q = encodeURIComponent(`name='${name.replace(/'/g, '\\\'')}' and trashed=false`);
201
+ // would otherwise terminate the quoted literal and produce a malformed
202
+ // query - and a literal backslash needs the same treatment, escaped FIRST
203
+ // so it doesn't double-escape the backslash the quote-escaping just added.
204
+ const escaped = name.replace(/\\/g, '\\\\').replace(/'/g, '\\\'');
205
+ const q = encodeURIComponent(`name='${escaped}' and trashed=false`);
160
206
  const url = `${FILES_URL}?spaces=appDataFolder&q=${q}&fields=files(${FILE_FIELDS})&pageSize=10`;
161
207
  const res = await this.request(url, {
162
208
  method: 'GET'
@@ -322,37 +368,97 @@ class GoogleDriveClient {
322
368
  * how many bytes it actually has and resuming from there - rather than
323
369
  * restarting the transfer.
324
370
  *
325
- * That resumability is scoped to this call: the session lives only in
326
- * memory, so if the process dies mid-upload, the next call to `uploadFile`
327
- * starts a fresh session from byte 0. Persisting the session URI so a
328
- * restart can resume it too is future scope, not something callers should
329
- * assume works today.
371
+ * That resumability spans a process restart too, when {@link
372
+ * GoogleDriveConfig.sessionStore} is configured: the session URI is persisted
373
+ * before the first chunk goes out, and a later `uploadFile` for the same name
374
+ * finds it, asks Drive for the real offset, and resumes from there instead of
375
+ * byte 0. Without a `sessionStore`, the session lives only in memory, exactly
376
+ * as before - a process that dies mid-upload loses it, and the next call
377
+ * starts fresh.
330
378
  */
331
379
  async uploadFile(name, source, onProgress, signal) {
332
380
  (0, _timeout.throwIfAborted)(signal, 'googleDrive');
333
- const existingId = await this.findFileId(name);
334
- const sessionUrl = await this.startResumableSession(name, existingId);
335
- let offset = 0;
336
- let newId;
337
381
  const total = source.size;
338
-
339
- // A zero-byte file still needs one request to actually create it.
340
- do {
341
- // Checked between chunks rather than only up front: a cancel during a
342
- // multi-hundred-megabyte transfer has to take effect while it is running,
343
- // which is the entire point of being able to cancel one.
344
- (0, _timeout.throwIfAborted)(signal, 'googleDrive');
345
- const length = Math.min(this.chunkBytes, total - offset);
346
- const step = await this.putChunkWithRetry(sessionUrl, source, offset, length, total, onProgress);
347
- offset = step.nextOffset;
348
- if (step.id != null) newId = step.id;
349
- } while (offset < total);
382
+ const resumed = await this.resumeOrStartSession(name, total);
383
+
384
+ // The resumed session was already complete server-side - most likely the
385
+ // last chunk's own response was what got lost to the process dying, not
386
+ // the chunk itself. Nothing left to send.
387
+ if (resumed.completed) {
388
+ if (resumed.id != null) this.idCache.set(name, resumed.id);
389
+ await this.config.sessionStore?.remove(name);
390
+ onProgress?.(total, total);
391
+ return;
392
+ }
393
+ const sessionUrl = resumed.sessionUrl;
394
+ let offset = resumed.offset;
395
+ let newId;
396
+ try {
397
+ // A zero-byte file still needs one request to actually create it.
398
+ do {
399
+ // Checked between chunks rather than only up front: a cancel during a
400
+ // multi-hundred-megabyte transfer has to take effect while it is running,
401
+ // which is the entire point of being able to cancel one.
402
+ (0, _timeout.throwIfAborted)(signal, 'googleDrive');
403
+ const length = Math.min(this.chunkBytes, total - offset);
404
+ const step = await this.putChunkWithRetry(sessionUrl, source, offset, length, total, onProgress);
405
+ offset = step.nextOffset;
406
+ if (step.id != null) newId = step.id;
407
+ } while (offset < total);
408
+ } catch (e) {
409
+ // A deliberate cancel abandons the session - the caller asked to stop,
410
+ // not to resume later. Any other failure (network drop, timeout, the
411
+ // process itself dying) leaves the persisted session in place, since
412
+ // that is precisely what lets the next call resume instead of restarting.
413
+ if ((0, _errors.isCancelled)(e)) await this.config.sessionStore?.remove(name);
414
+ throw e;
415
+ }
350
416
 
351
417
  // A create only learns its id from the final response; an update already
352
418
  // had one via `existingId`.
353
419
  if (newId != null) this.idCache.set(name, newId);
420
+ await this.config.sessionStore?.remove(name);
354
421
  onProgress?.(total, total);
355
422
  }
423
+
424
+ /**
425
+ * Finds an existing session to resume, or starts a new one.
426
+ *
427
+ * A persisted session is trusted only when its recorded size still matches
428
+ * `total` - resuming a byte-range PUT into a file that has since changed
429
+ * would corrupt it, so a mismatch is treated the same as no session at all.
430
+ * A persisted session Drive no longer recognises (expired, or the upload id
431
+ * was never valid) is also treated as absent: `queryUploadOffset` failing is
432
+ * the signal, since there is no cheaper way to ask than trying to use it.
433
+ */
434
+ async resumeOrStartSession(name, total) {
435
+ const persisted = await this.config.sessionStore?.get(name);
436
+ if (persisted != null && persisted.size === total) try {
437
+ const {
438
+ offset,
439
+ id
440
+ } = await this.queryUploadOffset(persisted.sessionUrl, total);
441
+ return {
442
+ sessionUrl: persisted.sessionUrl,
443
+ offset,
444
+ completed: offset >= total,
445
+ id
446
+ };
447
+ } catch {
448
+ // Falls through to starting a fresh session below.
449
+ }
450
+ const existingId = await this.findFileId(name);
451
+ const sessionUrl = await this.startResumableSession(name, existingId);
452
+ await this.config.sessionStore?.set(name, {
453
+ sessionUrl,
454
+ size: total
455
+ });
456
+ return {
457
+ sessionUrl,
458
+ offset: 0,
459
+ completed: false
460
+ };
461
+ }
356
462
  async startResumableSession(name, existingId) {
357
463
  const url = existingId != null ? `${UPLOAD_URL}/${existingId}?uploadType=resumable` : `${UPLOAD_URL}?uploadType=resumable&fields=id`;
358
464
  const metadata = existingId != null ? {} : {
@@ -379,9 +485,19 @@ class GoogleDriveClient {
379
485
  return await this.putChunk(sessionUrl, source, offset, length, total, onProgress);
380
486
  } catch (e) {
381
487
  if (!isRetryableTransfer(e)) throw e;
382
- const resumeFrom = await this.queryUploadOffset(sessionUrl, total);
383
- const retryLength = Math.min(this.chunkBytes, total - resumeFrom);
384
- return await this.putChunk(sessionUrl, source, resumeFrom, retryLength, total, onProgress);
488
+ const resumed = await this.queryUploadOffset(sessionUrl, total);
489
+ // The dropped chunk's own response was what got lost, not the chunk -
490
+ // Drive already has everything. A retry PUT here would send a zero-length,
491
+ // malformed Content-Range (end before start).
492
+ if (resumed.offset >= total) {
493
+ onProgress?.(total, total);
494
+ return {
495
+ nextOffset: total,
496
+ id: resumed.id
497
+ };
498
+ }
499
+ const retryLength = Math.min(this.chunkBytes, total - resumed.offset);
500
+ return await this.putChunk(sessionUrl, source, resumed.offset, retryLength, total, onProgress);
385
501
  }
386
502
  }
387
503
  async putChunk(sessionUrl, source, offset, length, total, onProgress) {
@@ -413,7 +529,17 @@ class GoogleDriveClient {
413
529
  };
414
530
  }
415
531
 
416
- /** Asks Drive how much of an in-flight resumable session it actually has. */
532
+ /**
533
+ * Asks Drive how much of an in-flight resumable session it actually has, or
534
+ * discovers the upload was already complete server-side - the completing
535
+ * chunk's own response can be lost the same way any other one can, and this
536
+ * status check gets the same completion response back in that case,
537
+ * `id` included.
538
+ *
539
+ * Throws (via `request`) when `sessionUrl` is not a session Drive
540
+ * recognises any more - expired, or never valid. Callers treat that as the
541
+ * signal to stop trusting it, since there is no cheaper way to ask.
542
+ */
417
543
  async queryUploadOffset(sessionUrl, total) {
418
544
  const res = await this.request(sessionUrl, {
419
545
  method: 'PUT',
@@ -421,12 +547,21 @@ class GoogleDriveClient {
421
547
  'Content-Range': `bytes */${total}`
422
548
  }
423
549
  }, [308]);
424
- if (res.status !== 308) return total; // already complete, unexpectedly
425
-
550
+ if (res.status !== 308) {
551
+ const json = await res.json().catch(() => null);
552
+ return {
553
+ offset: total,
554
+ id: json?.id ?? undefined
555
+ };
556
+ }
426
557
  const range = res.headers.get('Range'); // "bytes=0-8388607"
427
- if (range == null) return 0;
558
+ if (range == null) return {
559
+ offset: 0
560
+ };
428
561
  const match = /bytes=0-(\d+)/.exec(range);
429
- return match ? Number(match[1]) + 1 : 0;
562
+ return {
563
+ offset: match ? Number(match[1]) + 1 : 0
564
+ };
430
565
  }
431
566
 
432
567
  /**