react-native-cloud-sync 0.1.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 (268) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +360 -0
  3. package/app.plugin.js +3 -0
  4. package/ios/CloudSyncError.swift +144 -0
  5. package/ios/CloudSyncImpl.swift +1263 -0
  6. package/ios/RNCloudSync.h +25 -0
  7. package/ios/RNCloudSync.mm +477 -0
  8. package/jest-mock.js +136 -0
  9. package/lib/commonjs/config.js +85 -0
  10. package/lib/commonjs/config.js.map +1 -0
  11. package/lib/commonjs/errors.js +244 -0
  12. package/lib/commonjs/errors.js.map +1 -0
  13. package/lib/commonjs/hooks.js +257 -0
  14. package/lib/commonjs/hooks.js.map +1 -0
  15. package/lib/commonjs/index.js +244 -0
  16. package/lib/commonjs/index.js.map +1 -0
  17. package/lib/commonjs/internal/autoFlush.js +65 -0
  18. package/lib/commonjs/internal/autoFlush.js.map +1 -0
  19. package/lib/commonjs/internal/base64.js +58 -0
  20. package/lib/commonjs/internal/base64.js.map +1 -0
  21. package/lib/commonjs/internal/bytes.js +32 -0
  22. package/lib/commonjs/internal/bytes.js.map +1 -0
  23. package/lib/commonjs/internal/cloudKitRest.js +527 -0
  24. package/lib/commonjs/internal/cloudKitRest.js.map +1 -0
  25. package/lib/commonjs/internal/enums.js +23 -0
  26. package/lib/commonjs/internal/enums.js.map +1 -0
  27. package/lib/commonjs/internal/googleDriveRest.js +624 -0
  28. package/lib/commonjs/internal/googleDriveRest.js.map +1 -0
  29. package/lib/commonjs/internal/keys.js +139 -0
  30. package/lib/commonjs/internal/keys.js.map +1 -0
  31. package/lib/commonjs/internal/logger.js +29 -0
  32. package/lib/commonjs/internal/logger.js.map +1 -0
  33. package/lib/commonjs/internal/nativeModule.js +125 -0
  34. package/lib/commonjs/internal/nativeModule.js.map +1 -0
  35. package/lib/commonjs/internal/timeout.js +72 -0
  36. package/lib/commonjs/internal/timeout.js.map +1 -0
  37. package/lib/commonjs/package.json +1 -0
  38. package/lib/commonjs/providers/cloudKit.js +398 -0
  39. package/lib/commonjs/providers/cloudKit.js.map +1 -0
  40. package/lib/commonjs/providers/cloudKitBackup.js +86 -0
  41. package/lib/commonjs/providers/cloudKitBackup.js.map +1 -0
  42. package/lib/commonjs/providers/cloudKitEncrypted.js +150 -0
  43. package/lib/commonjs/providers/cloudKitEncrypted.js.map +1 -0
  44. package/lib/commonjs/providers/googleDrive.js +219 -0
  45. package/lib/commonjs/providers/googleDrive.js.map +1 -0
  46. package/lib/commonjs/providers/googleDriveFiles.js +68 -0
  47. package/lib/commonjs/providers/googleDriveFiles.js.map +1 -0
  48. package/lib/commonjs/providers/icloudDocuments.js +121 -0
  49. package/lib/commonjs/providers/icloudDocuments.js.map +1 -0
  50. package/lib/commonjs/providers/icloudKV.js +171 -0
  51. package/lib/commonjs/providers/icloudKV.js.map +1 -0
  52. package/lib/commonjs/providers/icloudKV.web.js +42 -0
  53. package/lib/commonjs/providers/icloudKV.web.js.map +1 -0
  54. package/lib/commonjs/providers/memory.js +201 -0
  55. package/lib/commonjs/providers/memory.js.map +1 -0
  56. package/lib/commonjs/resolvers.js +128 -0
  57. package/lib/commonjs/resolvers.js.map +1 -0
  58. package/lib/commonjs/specs/NativeRNCloudSync.js +14 -0
  59. package/lib/commonjs/specs/NativeRNCloudSync.js.map +1 -0
  60. package/lib/commonjs/store.js +1064 -0
  61. package/lib/commonjs/store.js.map +1 -0
  62. package/lib/commonjs/testing.js +32 -0
  63. package/lib/commonjs/testing.js.map +1 -0
  64. package/lib/commonjs/types.js +86 -0
  65. package/lib/commonjs/types.js.map +1 -0
  66. package/lib/module/config.js +72 -0
  67. package/lib/module/config.js.map +1 -0
  68. package/lib/module/errors.js +231 -0
  69. package/lib/module/errors.js.map +1 -0
  70. package/lib/module/hooks.js +250 -0
  71. package/lib/module/hooks.js.map +1 -0
  72. package/lib/module/index.js +46 -0
  73. package/lib/module/index.js.map +1 -0
  74. package/lib/module/internal/autoFlush.js +62 -0
  75. package/lib/module/internal/autoFlush.js.map +1 -0
  76. package/lib/module/internal/base64.js +53 -0
  77. package/lib/module/internal/base64.js.map +1 -0
  78. package/lib/module/internal/bytes.js +28 -0
  79. package/lib/module/internal/bytes.js.map +1 -0
  80. package/lib/module/internal/cloudKitRest.js +518 -0
  81. package/lib/module/internal/cloudKitRest.js.map +1 -0
  82. package/lib/module/internal/enums.js +18 -0
  83. package/lib/module/internal/enums.js.map +1 -0
  84. package/lib/module/internal/googleDriveRest.js +620 -0
  85. package/lib/module/internal/googleDriveRest.js.map +1 -0
  86. package/lib/module/internal/keys.js +134 -0
  87. package/lib/module/internal/keys.js.map +1 -0
  88. package/lib/module/internal/logger.js +23 -0
  89. package/lib/module/internal/logger.js.map +1 -0
  90. package/lib/module/internal/nativeModule.js +117 -0
  91. package/lib/module/internal/nativeModule.js.map +1 -0
  92. package/lib/module/internal/timeout.js +67 -0
  93. package/lib/module/internal/timeout.js.map +1 -0
  94. package/lib/module/package.json +1 -0
  95. package/lib/module/providers/cloudKit.js +392 -0
  96. package/lib/module/providers/cloudKit.js.map +1 -0
  97. package/lib/module/providers/cloudKitBackup.js +82 -0
  98. package/lib/module/providers/cloudKitBackup.js.map +1 -0
  99. package/lib/module/providers/cloudKitEncrypted.js +146 -0
  100. package/lib/module/providers/cloudKitEncrypted.js.map +1 -0
  101. package/lib/module/providers/googleDrive.js +214 -0
  102. package/lib/module/providers/googleDrive.js.map +1 -0
  103. package/lib/module/providers/googleDriveFiles.js +64 -0
  104. package/lib/module/providers/googleDriveFiles.js.map +1 -0
  105. package/lib/module/providers/icloudDocuments.js +117 -0
  106. package/lib/module/providers/icloudDocuments.js.map +1 -0
  107. package/lib/module/providers/icloudKV.js +165 -0
  108. package/lib/module/providers/icloudKV.js.map +1 -0
  109. package/lib/module/providers/icloudKV.web.js +36 -0
  110. package/lib/module/providers/icloudKV.web.js.map +1 -0
  111. package/lib/module/providers/memory.js +197 -0
  112. package/lib/module/providers/memory.js.map +1 -0
  113. package/lib/module/resolvers.js +120 -0
  114. package/lib/module/resolvers.js.map +1 -0
  115. package/lib/module/specs/NativeRNCloudSync.js +12 -0
  116. package/lib/module/specs/NativeRNCloudSync.js.map +1 -0
  117. package/lib/module/store.js +1061 -0
  118. package/lib/module/store.js.map +1 -0
  119. package/lib/module/testing.js +17 -0
  120. package/lib/module/testing.js.map +1 -0
  121. package/lib/module/types.js +82 -0
  122. package/lib/module/types.js.map +1 -0
  123. package/lib/typescript/commonjs/config.d.ts +33 -0
  124. package/lib/typescript/commonjs/config.d.ts.map +1 -0
  125. package/lib/typescript/commonjs/errors.d.ts +140 -0
  126. package/lib/typescript/commonjs/errors.d.ts.map +1 -0
  127. package/lib/typescript/commonjs/hooks.d.ts +109 -0
  128. package/lib/typescript/commonjs/hooks.d.ts.map +1 -0
  129. package/lib/typescript/commonjs/index.d.ts +37 -0
  130. package/lib/typescript/commonjs/index.d.ts.map +1 -0
  131. package/lib/typescript/commonjs/internal/autoFlush.d.ts +45 -0
  132. package/lib/typescript/commonjs/internal/autoFlush.d.ts.map +1 -0
  133. package/lib/typescript/commonjs/internal/base64.d.ts +12 -0
  134. package/lib/typescript/commonjs/internal/base64.d.ts.map +1 -0
  135. package/lib/typescript/commonjs/internal/bytes.d.ts +12 -0
  136. package/lib/typescript/commonjs/internal/bytes.d.ts.map +1 -0
  137. package/lib/typescript/commonjs/internal/cloudKitRest.d.ts +149 -0
  138. package/lib/typescript/commonjs/internal/cloudKitRest.d.ts.map +1 -0
  139. package/lib/typescript/commonjs/internal/enums.d.ts +10 -0
  140. package/lib/typescript/commonjs/internal/enums.d.ts.map +1 -0
  141. package/lib/typescript/commonjs/internal/googleDriveRest.d.ts +232 -0
  142. package/lib/typescript/commonjs/internal/googleDriveRest.d.ts.map +1 -0
  143. package/lib/typescript/commonjs/internal/keys.d.ts +28 -0
  144. package/lib/typescript/commonjs/internal/keys.d.ts.map +1 -0
  145. package/lib/typescript/commonjs/internal/logger.d.ts +10 -0
  146. package/lib/typescript/commonjs/internal/logger.d.ts.map +1 -0
  147. package/lib/typescript/commonjs/internal/nativeModule.d.ts +29 -0
  148. package/lib/typescript/commonjs/internal/nativeModule.d.ts.map +1 -0
  149. package/lib/typescript/commonjs/internal/timeout.d.ts +36 -0
  150. package/lib/typescript/commonjs/internal/timeout.d.ts.map +1 -0
  151. package/lib/typescript/commonjs/package.json +1 -0
  152. package/lib/typescript/commonjs/providers/cloudKit.d.ts +86 -0
  153. package/lib/typescript/commonjs/providers/cloudKit.d.ts.map +1 -0
  154. package/lib/typescript/commonjs/providers/cloudKitBackup.d.ts +65 -0
  155. package/lib/typescript/commonjs/providers/cloudKitBackup.d.ts.map +1 -0
  156. package/lib/typescript/commonjs/providers/cloudKitEncrypted.d.ts +37 -0
  157. package/lib/typescript/commonjs/providers/cloudKitEncrypted.d.ts.map +1 -0
  158. package/lib/typescript/commonjs/providers/googleDrive.d.ts +35 -0
  159. package/lib/typescript/commonjs/providers/googleDrive.d.ts.map +1 -0
  160. package/lib/typescript/commonjs/providers/googleDriveFiles.d.ts +59 -0
  161. package/lib/typescript/commonjs/providers/googleDriveFiles.d.ts.map +1 -0
  162. package/lib/typescript/commonjs/providers/icloudDocuments.d.ts +101 -0
  163. package/lib/typescript/commonjs/providers/icloudDocuments.d.ts.map +1 -0
  164. package/lib/typescript/commonjs/providers/icloudKV.d.ts +26 -0
  165. package/lib/typescript/commonjs/providers/icloudKV.d.ts.map +1 -0
  166. package/lib/typescript/commonjs/providers/icloudKV.web.d.ts +12 -0
  167. package/lib/typescript/commonjs/providers/icloudKV.web.d.ts.map +1 -0
  168. package/lib/typescript/commonjs/providers/memory.d.ts +90 -0
  169. package/lib/typescript/commonjs/providers/memory.d.ts.map +1 -0
  170. package/lib/typescript/commonjs/resolvers.d.ts +60 -0
  171. package/lib/typescript/commonjs/resolvers.d.ts.map +1 -0
  172. package/lib/typescript/commonjs/specs/NativeRNCloudSync.d.ts +133 -0
  173. package/lib/typescript/commonjs/specs/NativeRNCloudSync.d.ts.map +1 -0
  174. package/lib/typescript/commonjs/store.d.ts +118 -0
  175. package/lib/typescript/commonjs/store.d.ts.map +1 -0
  176. package/lib/typescript/commonjs/testing.d.ts +16 -0
  177. package/lib/typescript/commonjs/testing.d.ts.map +1 -0
  178. package/lib/typescript/commonjs/types.d.ts +367 -0
  179. package/lib/typescript/commonjs/types.d.ts.map +1 -0
  180. package/lib/typescript/module/config.d.ts +33 -0
  181. package/lib/typescript/module/config.d.ts.map +1 -0
  182. package/lib/typescript/module/errors.d.ts +140 -0
  183. package/lib/typescript/module/errors.d.ts.map +1 -0
  184. package/lib/typescript/module/hooks.d.ts +109 -0
  185. package/lib/typescript/module/hooks.d.ts.map +1 -0
  186. package/lib/typescript/module/index.d.ts +37 -0
  187. package/lib/typescript/module/index.d.ts.map +1 -0
  188. package/lib/typescript/module/internal/autoFlush.d.ts +45 -0
  189. package/lib/typescript/module/internal/autoFlush.d.ts.map +1 -0
  190. package/lib/typescript/module/internal/base64.d.ts +12 -0
  191. package/lib/typescript/module/internal/base64.d.ts.map +1 -0
  192. package/lib/typescript/module/internal/bytes.d.ts +12 -0
  193. package/lib/typescript/module/internal/bytes.d.ts.map +1 -0
  194. package/lib/typescript/module/internal/cloudKitRest.d.ts +149 -0
  195. package/lib/typescript/module/internal/cloudKitRest.d.ts.map +1 -0
  196. package/lib/typescript/module/internal/enums.d.ts +10 -0
  197. package/lib/typescript/module/internal/enums.d.ts.map +1 -0
  198. package/lib/typescript/module/internal/googleDriveRest.d.ts +232 -0
  199. package/lib/typescript/module/internal/googleDriveRest.d.ts.map +1 -0
  200. package/lib/typescript/module/internal/keys.d.ts +28 -0
  201. package/lib/typescript/module/internal/keys.d.ts.map +1 -0
  202. package/lib/typescript/module/internal/logger.d.ts +10 -0
  203. package/lib/typescript/module/internal/logger.d.ts.map +1 -0
  204. package/lib/typescript/module/internal/nativeModule.d.ts +29 -0
  205. package/lib/typescript/module/internal/nativeModule.d.ts.map +1 -0
  206. package/lib/typescript/module/internal/timeout.d.ts +36 -0
  207. package/lib/typescript/module/internal/timeout.d.ts.map +1 -0
  208. package/lib/typescript/module/package.json +1 -0
  209. package/lib/typescript/module/providers/cloudKit.d.ts +86 -0
  210. package/lib/typescript/module/providers/cloudKit.d.ts.map +1 -0
  211. package/lib/typescript/module/providers/cloudKitBackup.d.ts +65 -0
  212. package/lib/typescript/module/providers/cloudKitBackup.d.ts.map +1 -0
  213. package/lib/typescript/module/providers/cloudKitEncrypted.d.ts +37 -0
  214. package/lib/typescript/module/providers/cloudKitEncrypted.d.ts.map +1 -0
  215. package/lib/typescript/module/providers/googleDrive.d.ts +35 -0
  216. package/lib/typescript/module/providers/googleDrive.d.ts.map +1 -0
  217. package/lib/typescript/module/providers/googleDriveFiles.d.ts +59 -0
  218. package/lib/typescript/module/providers/googleDriveFiles.d.ts.map +1 -0
  219. package/lib/typescript/module/providers/icloudDocuments.d.ts +101 -0
  220. package/lib/typescript/module/providers/icloudDocuments.d.ts.map +1 -0
  221. package/lib/typescript/module/providers/icloudKV.d.ts +26 -0
  222. package/lib/typescript/module/providers/icloudKV.d.ts.map +1 -0
  223. package/lib/typescript/module/providers/icloudKV.web.d.ts +12 -0
  224. package/lib/typescript/module/providers/icloudKV.web.d.ts.map +1 -0
  225. package/lib/typescript/module/providers/memory.d.ts +90 -0
  226. package/lib/typescript/module/providers/memory.d.ts.map +1 -0
  227. package/lib/typescript/module/resolvers.d.ts +60 -0
  228. package/lib/typescript/module/resolvers.d.ts.map +1 -0
  229. package/lib/typescript/module/specs/NativeRNCloudSync.d.ts +133 -0
  230. package/lib/typescript/module/specs/NativeRNCloudSync.d.ts.map +1 -0
  231. package/lib/typescript/module/store.d.ts +118 -0
  232. package/lib/typescript/module/store.d.ts.map +1 -0
  233. package/lib/typescript/module/testing.d.ts +16 -0
  234. package/lib/typescript/module/testing.d.ts.map +1 -0
  235. package/lib/typescript/module/types.d.ts +367 -0
  236. package/lib/typescript/module/types.d.ts.map +1 -0
  237. package/package.json +186 -0
  238. package/plugin/build/index.d.ts +45 -0
  239. package/plugin/build/index.js +93 -0
  240. package/react-native-cloud-sync.podspec +48 -0
  241. package/src/config.ts +94 -0
  242. package/src/errors.ts +263 -0
  243. package/src/hooks.ts +337 -0
  244. package/src/index.ts +113 -0
  245. package/src/internal/autoFlush.ts +87 -0
  246. package/src/internal/base64.ts +63 -0
  247. package/src/internal/bytes.ts +28 -0
  248. package/src/internal/cloudKitRest.ts +654 -0
  249. package/src/internal/enums.ts +35 -0
  250. package/src/internal/googleDriveRest.ts +765 -0
  251. package/src/internal/keys.ts +160 -0
  252. package/src/internal/logger.ts +23 -0
  253. package/src/internal/nativeModule.ts +149 -0
  254. package/src/internal/timeout.ts +83 -0
  255. package/src/providers/cloudKit.ts +510 -0
  256. package/src/providers/cloudKitBackup.ts +124 -0
  257. package/src/providers/cloudKitEncrypted.ts +175 -0
  258. package/src/providers/googleDrive.ts +251 -0
  259. package/src/providers/googleDriveFiles.ts +117 -0
  260. package/src/providers/icloudDocuments.ts +175 -0
  261. package/src/providers/icloudKV.ts +206 -0
  262. package/src/providers/icloudKV.web.ts +41 -0
  263. package/src/providers/memory.ts +302 -0
  264. package/src/resolvers.ts +133 -0
  265. package/src/specs/NativeRNCloudSync.ts +184 -0
  266. package/src/store.ts +1288 -0
  267. package/src/testing.ts +22 -0
  268. package/src/types.ts +426 -0
@@ -0,0 +1,765 @@
1
+ import { CloudSyncError, ErrorCode } from '../errors'
2
+ import { throwIfAborted, withTimeout, type AbortLike } from './timeout'
3
+
4
+ /**
5
+ * Google Drive `appDataFolder` REST client.
6
+ *
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.
10
+ *
11
+ * Auth is deliberately injected rather than owned. The library does not depend
12
+ * on `@react-native-google-signin/google-signin` (or any other sign-in library),
13
+ * so the host app keeps control of the consent flow, and the same client works
14
+ * unchanged in a browser where that library does not apply.
15
+ */
16
+
17
+ export interface GoogleDriveConfig {
18
+ /**
19
+ * Returns a valid OAuth access token with the `drive.appdata` scope, or null
20
+ * if the user is not connected. Called before every request, so implementers
21
+ * should refresh silently here rather than caching a stale token.
22
+ */
23
+ getAccessToken: () => Promise<string | null> | string | null
24
+ /** Called when Drive rejects the token, so the host can prompt for reconnect. */
25
+ onAuthExpired?: () => Promise<void> | void
26
+ fetchImpl?: typeof fetch
27
+ /**
28
+ * Bytes per chunk for `uploadFile`/`downloadFile`. Default 8 MiB.
29
+ *
30
+ * Must be a multiple of 256 KiB (262144) - Google's resumable upload
31
+ * protocol requires that for every chunk but the last. Lowered in tests to
32
+ * exercise the multi-chunk path without a multi-MB fixture.
33
+ */
34
+ chunkBytes?: number
35
+ /**
36
+ * What to do when `appDataFolder` holds more than one file with the same
37
+ * name. Default `'newest'`.
38
+ *
39
+ * Drive names are not unique - it is a file store with ids, not a key-value
40
+ * store - so two devices creating the same key while both are offline
41
+ * genuinely produce two files. Picking whichever the API happened to list
42
+ * first is the worst option: the choice is unspecified, so two devices can
43
+ * settle on different files and diverge permanently with no error anywhere.
44
+ *
45
+ * `'newest'` picks the most recently modified, which every device agrees on.
46
+ * `'error'` raises {@link ErrorCode.CONFLICT} instead, for apps that would
47
+ * rather reconcile explicitly than have one copy quietly win.
48
+ */
49
+ onDuplicateName?: 'newest' | 'error'
50
+ /**
51
+ * Abandon a request that has not answered in this long. Default 60000.
52
+ *
53
+ * Longer than the CloudKit client's because one "request" here can be a whole
54
+ * 8 MiB chunk on a slow connection. `fetch` in React Native has no timeout of
55
+ * its own, so without this a dead socket hangs the transfer forever.
56
+ */
57
+ timeoutMs?: number
58
+ }
59
+
60
+ const FILES_URL = 'https://www.googleapis.com/drive/v3/files'
61
+ const UPLOAD_URL = 'https://www.googleapis.com/upload/drive/v3/files'
62
+ const ABOUT_URL = 'https://www.googleapis.com/drive/v3/about'
63
+ const CHANGES_URL = 'https://www.googleapis.com/drive/v3/changes'
64
+ const DEFAULT_CHUNK_BYTES = 8 * 1024 * 1024
65
+ const DEFAULT_TIMEOUT_MS = 60_000
66
+
67
+ /** A local file `uploadFile` reads from, in fixed-size pieces. */
68
+ export interface DriveChunkSource {
69
+ size: number
70
+ read: (start: number, length: number) => Promise<Uint8Array>
71
+ }
72
+
73
+ /** A local file `downloadFile` writes into, one piece at a time. */
74
+ export interface DriveChunkSink {
75
+ write: (bytes: Uint8Array, isFirstChunk: boolean) => Promise<void>
76
+ }
77
+
78
+ /**
79
+ * Local file I/O for `googleDriveFiles`, supplied by the host app rather than
80
+ * this package depending on a filesystem library.
81
+ *
82
+ * base64 in and out - not a stream or a byte array - because that is the
83
+ * primitive RN filesystem libraries actually expose for a chunked read/write
84
+ * (`expo-file-system`'s `readAsStringAsync`/`writeAsStringAsync` with
85
+ * `EncodingType.Base64` and `position`/`length`/`append`), so the adapter
86
+ * mirrors that rather than inventing an abstraction nothing implements
87
+ * natively. `googleDriveFiles` does the base64 <-> bytes conversion at the
88
+ * boundary; a chunk is capped at `chunkBytes` (8 MiB default), so the base64
89
+ * string is never larger than that either.
90
+ */
91
+ export interface GoogleDriveFileAdapter {
92
+ /** Size in bytes of the local file at `uri`. */
93
+ statSize: (uri: string) => Promise<number>
94
+ /** Reads `length` bytes starting at `position` from the local file at `uri`, base64-encoded. */
95
+ readChunk: (uri: string, position: number, length: number) => Promise<string>
96
+ /** Creates (or overwrites) the local file at `uri` with these base64-encoded bytes. */
97
+ writeChunk: (uri: string, base64: string) => Promise<void>
98
+ /** Appends base64-encoded bytes to a file `writeChunk` already created. */
99
+ appendChunk: (uri: string, base64: string) => Promise<void>
100
+ }
101
+
102
+ interface DriveFile {
103
+ id: string
104
+ name: string
105
+ /** RFC 3339. Requested explicitly - Drive omits it unless `fields` asks. */
106
+ modifiedTime?: string
107
+ /** Drive's version counter. Increments on every content change. */
108
+ version?: string
109
+ }
110
+
111
+ /** The `fields` mask every listing uses, so a read also learns modification time. */
112
+ const FILE_FIELDS = 'id,name,modifiedTime,version'
113
+
114
+ /** True for the 404 the client tags when a file id no longer resolves. */
115
+ function isNotFound(e: unknown): boolean {
116
+ return e instanceof CloudSyncError && e.serverErrorCode === 'NOT_FOUND'
117
+ }
118
+
119
+ /** True for a transfer failure worth retrying after re-querying the real offset. */
120
+ function isRetryableTransfer(e: unknown): boolean {
121
+ return e instanceof CloudSyncError
122
+ && (e.code === ErrorCode.NETWORK_UNAVAILABLE || e.code === ErrorCode.RATE_LIMITED)
123
+ }
124
+
125
+ export class GoogleDriveClient {
126
+ private readonly config: GoogleDriveConfig
127
+ /**
128
+ * name -> fileId.
129
+ *
130
+ * Drive has no "get by name" endpoint, so every read would otherwise cost a
131
+ * list query. react-native-cloud-storage's Drive backend does exactly that and
132
+ * additionally lists the *whole* drive before filtering client-side, which its
133
+ * users measured in minutes (kuatsu#49) and which can loop forever (kuatsu#39).
134
+ * A scoped `q=` query plus this cache keeps a read to one request, usually zero.
135
+ */
136
+ private readonly idCache = new Map<string, string>()
137
+ /**
138
+ * name -> the metadata the last listing reported.
139
+ *
140
+ * Kept beside the id cache so `getItemWithMeta` does not need a second round
141
+ * trip to learn a modification time the `q=` query already returned.
142
+ */
143
+ private readonly metaCache = new Map<string, { modifiedAt?: number; version?: string }>()
144
+ private readonly chunkBytes: number
145
+
146
+ constructor(config: GoogleDriveConfig) {
147
+ this.config = config
148
+ this.chunkBytes = config.chunkBytes ?? DEFAULT_CHUNK_BYTES
149
+ }
150
+
151
+ private get fetch(): typeof fetch {
152
+ return this.config.fetchImpl ?? globalThis.fetch
153
+ }
154
+
155
+ private async requireToken(): Promise<string> {
156
+ const token = await this.config.getAccessToken()
157
+ if (!token)
158
+ throw new CloudSyncError(
159
+ ErrorCode.NOT_SIGNED_IN,
160
+ '[RNCloudSync] No Google Drive access token. Connect a Google account first.',
161
+ { provider: 'googleDrive' }
162
+ )
163
+
164
+ return token
165
+ }
166
+
167
+ /**
168
+ * `extraOkStatuses` is for the resumable-upload protocol, where 308 ("Resume
169
+ * Incomplete") is an expected, successful outcome rather than an error - the
170
+ * caller inspects the response itself rather than getting a thrown rejection.
171
+ */
172
+ private async request(url: string, init: RequestInit, extraOkStatuses: number[] = []): Promise<Response> {
173
+ const token = await this.requireToken()
174
+ const headers = new Headers(init.headers)
175
+ headers.set('Authorization', `Bearer ${token}`)
176
+
177
+ let res: Response
178
+ try {
179
+ res = await withTimeout(
180
+ this.fetch(url, { ...init, headers }),
181
+ this.config.timeoutMs ?? DEFAULT_TIMEOUT_MS,
182
+ 'googleDrive'
183
+ )
184
+ }
185
+ catch (e) {
186
+ // A timeout is already classified and retryable; re-wrapping it as a
187
+ // network failure would throw the distinction away.
188
+ if (e instanceof CloudSyncError) throw e
189
+ throw new CloudSyncError(
190
+ ErrorCode.NETWORK_UNAVAILABLE,
191
+ '[RNCloudSync] Google Drive request failed to reach the server.',
192
+ { provider: 'googleDrive', cause: e }
193
+ )
194
+ }
195
+
196
+ if (res.ok || extraOkStatuses.includes(res.status)) return res
197
+
198
+ if (res.status === 401 || res.status === 403) {
199
+ await this.config.onAuthExpired?.()
200
+ throw new CloudSyncError(
201
+ ErrorCode.AUTH_EXPIRED,
202
+ `[RNCloudSync] Google Drive returned HTTP ${res.status}; the access token is not valid.`,
203
+ { provider: 'googleDrive' }
204
+ )
205
+ }
206
+ if (res.status === 429) {
207
+ const retryAfter = Number(res.headers.get('Retry-After'))
208
+ throw new CloudSyncError(
209
+ ErrorCode.RATE_LIMITED,
210
+ '[RNCloudSync] Google Drive rate limited the request.',
211
+ {
212
+ provider: 'googleDrive',
213
+ retryAfterMs: Number.isFinite(retryAfter) ? retryAfter * 1000 : undefined,
214
+ }
215
+ )
216
+ }
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
+ // Tagged so callers can tell "this file id is gone" from a generic failure.
224
+ // Without the tag a stale memoised id was indistinguishable from a real
225
+ // error, so it could never be recovered from.
226
+ if (res.status === 404)
227
+ throw new CloudSyncError(
228
+ ErrorCode.UNKNOWN,
229
+ '[RNCloudSync] Google Drive has no file with that id.',
230
+ { provider: 'googleDrive', serverErrorCode: 'NOT_FOUND' }
231
+ )
232
+
233
+ throw new CloudSyncError(
234
+ ErrorCode.UNKNOWN,
235
+ `[RNCloudSync] Google Drive returned HTTP ${res.status}.`,
236
+ { provider: 'googleDrive' }
237
+ )
238
+ }
239
+
240
+ /**
241
+ * Resolves a file name to its id within appDataFolder, or null if absent.
242
+ *
243
+ * Pass `refresh` to bypass the memo after a cached id turned out to be stale.
244
+ */
245
+ private async findFileId(name: string, refresh = false): Promise<string | null> {
246
+ if (!refresh) {
247
+ const cached = this.idCache.get(name)
248
+ if (cached != null) return cached
249
+ }
250
+ this.idCache.delete(name)
251
+
252
+ // 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`)
255
+ const url = `${FILES_URL}?spaces=appDataFolder&q=${q}&fields=files(${FILE_FIELDS})&pageSize=10`
256
+
257
+ const res = await this.request(url, { method: 'GET' })
258
+ const json = (await res.json()) as { files?: DriveFile[] }
259
+ const matches = (json.files ?? []).filter(f => f.name === name)
260
+
261
+ if (matches.length === 0) {
262
+ this.metaCache.delete(name)
263
+ return null
264
+ }
265
+
266
+ const file = matches.length === 1 ? matches[0] : this.pickAmongDuplicates(name, matches)
267
+ this.remember(file)
268
+ return file.id
269
+ }
270
+
271
+ /**
272
+ * Chooses between several files that share a name.
273
+ *
274
+ * Deterministically, and that is the whole point: the list order Drive
275
+ * returns is unspecified, so picking the first match lets two devices settle
276
+ * on two different files for the same key and diverge forever, silently.
277
+ * Ordering by modification time - newest first, ties broken by id - gives
278
+ * every device the same answer.
279
+ */
280
+ private pickAmongDuplicates(name: string, matches: DriveFile[]): DriveFile {
281
+ if (this.config.onDuplicateName === 'error')
282
+ throw new CloudSyncError(
283
+ ErrorCode.CONFLICT,
284
+ `[RNCloudSync] Google Drive holds ${matches.length} files named '${name}'. `
285
+ + `Reconcile them, or configure onDuplicateName: 'newest' to always take the `
286
+ + `most recently modified.`,
287
+ { provider: 'googleDrive', serverErrorCode: 'DUPLICATE_NAME' }
288
+ )
289
+
290
+ return [...matches].sort((a, b) => {
291
+ const at = a.modifiedTime == null ? 0 : Date.parse(a.modifiedTime)
292
+ const bt = b.modifiedTime == null ? 0 : Date.parse(b.modifiedTime)
293
+ if (bt !== at) return bt - at
294
+ // Same timestamp: id is stable and unique, so this still agrees across
295
+ // devices rather than depending on response order.
296
+ return a.id < b.id ? -1 : 1
297
+ })[0]
298
+ }
299
+
300
+ /** Records what a listing told us about a file, ids and metadata together. */
301
+ private remember(file: DriveFile): void {
302
+ this.idCache.set(file.name, file.id)
303
+ const parsed = file.modifiedTime == null ? Number.NaN : Date.parse(file.modifiedTime)
304
+ this.metaCache.set(file.name, {
305
+ modifiedAt: Number.isNaN(parsed) ? undefined : parsed,
306
+ version: file.version,
307
+ })
308
+ }
309
+
310
+ async getItem(name: string): Promise<string | null> {
311
+ const id = await this.findFileId(name)
312
+ if (id == null) return null
313
+
314
+ try {
315
+ const res = await this.request(`${FILES_URL}/${id}?alt=media`, { method: 'GET' })
316
+ return await res.text()
317
+ }
318
+ catch (e) {
319
+ if (!isNotFound(e)) throw e
320
+ }
321
+
322
+ // The memoised id pointed at a file that is no longer there - another device
323
+ // deleted it. Look the name up again rather than throwing off a stale memo
324
+ // forever, and report a genuine absence as absent.
325
+ const fresh = await this.findFileId(name, true)
326
+ if (fresh == null) return null
327
+
328
+ const res = await this.request(`${FILES_URL}/${fresh}?alt=media`, { method: 'GET' })
329
+ return await res.text()
330
+ }
331
+
332
+ /**
333
+ * A read that also reports Drive's own `modifiedTime`.
334
+ *
335
+ * Free: resolving a name to an id is already a listing, and asking that
336
+ * listing for `modifiedTime` costs nothing extra. Surfacing it is what lets
337
+ * {@link resolveByModifiedAt} order copies without the app embedding a
338
+ * timestamp in its payload.
339
+ */
340
+ async getItemWithMeta(
341
+ name: string
342
+ ): Promise<{ value: string; modifiedAt?: number; version?: string } | null> {
343
+ const value = await this.getItem(name)
344
+ if (value == null) return null
345
+ const meta = this.metaCache.get(name)
346
+ return { value, modifiedAt: meta?.modifiedAt, version: meta?.version }
347
+ }
348
+
349
+ /**
350
+ * Storage usage for the whole Google account.
351
+ *
352
+ * Note this is the account's total, not the `appDataFolder`'s share of it -
353
+ * Drive reports no per-folder usage. Still the number a "you are running out
354
+ * of space" prompt needs, because that is the limit a write will actually hit.
355
+ * `limit` is absent for unlimited (Workspace pooled) accounts.
356
+ */
357
+ async getQuota(): Promise<{ usedBytes?: number; totalBytes?: number }> {
358
+ const res = await this.request(`${ABOUT_URL}?fields=storageQuota`, { method: 'GET' })
359
+ const json = (await res.json()) as {
360
+ storageQuota?: { usage?: string; limit?: string }
361
+ }
362
+ const usage = Number(json.storageQuota?.usage)
363
+ const limit = Number(json.storageQuota?.limit)
364
+ return {
365
+ usedBytes: Number.isFinite(usage) ? usage : undefined,
366
+ totalBytes: Number.isFinite(limit) ? limit : undefined,
367
+ }
368
+ }
369
+
370
+ async setItem(name: string, value: string): Promise<void> {
371
+ const id = await this.findFileId(name)
372
+
373
+ if (id != null)
374
+ try {
375
+ await this.request(`${UPLOAD_URL}/${id}?uploadType=media`, {
376
+ method: 'PATCH',
377
+ headers: { 'Content-Type': 'application/json' },
378
+ body: value,
379
+ })
380
+ return
381
+ }
382
+ catch (e) {
383
+ // Same stale-memo case. Fall through and create the file again instead
384
+ // of failing every future write to this key.
385
+ if (!isNotFound(e)) throw e
386
+ this.idCache.delete(name)
387
+ this.metaCache.delete(name)
388
+ }
389
+
390
+ // Multipart create: metadata part pins the file into appDataFolder, second
391
+ // part carries the content.
392
+ const boundary = `rncs-${Math.random().toString(36).slice(2)}`
393
+ const metadata = JSON.stringify({ name, parents: ['appDataFolder'] })
394
+ const body
395
+ = `--${boundary}\r\n`
396
+ + `Content-Type: application/json; charset=UTF-8\r\n\r\n${metadata}\r\n`
397
+ + `--${boundary}\r\n`
398
+ + `Content-Type: application/json\r\n\r\n${value}\r\n`
399
+ + `--${boundary}--`
400
+
401
+ const res = await this.request(`${UPLOAD_URL}?uploadType=multipart&fields=${FILE_FIELDS}`, {
402
+ method: 'POST',
403
+ headers: { 'Content-Type': `multipart/related; boundary=${boundary}` },
404
+ body,
405
+ })
406
+ const json = (await res.json()) as Partial<DriveFile>
407
+ // Remember what the create returned so the next read does not have to list.
408
+ if (json.id != null) this.remember({ ...json, id: json.id, name })
409
+ }
410
+
411
+ /**
412
+ * Uploads `source` as `name`, using Drive's resumable protocol instead of
413
+ * `setItem`'s single-request multipart body.
414
+ *
415
+ * Two things a whole-file `setItem(name, base64OfEverything)` cannot do at
416
+ * a few hundred MB: hold the payload in memory as one JS string, and recover
417
+ * from a dropped connection without starting over. Reading happens in fixed
418
+ * chunks through `source.read`, so peak memory is one chunk rather than the
419
+ * whole file, and a chunk that fails mid-flight is retried - by asking Drive
420
+ * how many bytes it actually has and resuming from there - rather than
421
+ * restarting the transfer.
422
+ *
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.
428
+ */
429
+ async uploadFile(
430
+ name: string,
431
+ source: DriveChunkSource,
432
+ onProgress?: (bytesTransferred: number, bytesTotal: number) => void,
433
+ signal?: AbortLike
434
+ ): Promise<void> {
435
+ throwIfAborted(signal, 'googleDrive')
436
+ const existingId = await this.findFileId(name)
437
+ const sessionUrl = await this.startResumableSession(name, existingId)
438
+
439
+ let offset = 0
440
+ let newId: string | undefined
441
+ const total = source.size
442
+
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)
454
+
455
+ // A create only learns its id from the final response; an update already
456
+ // had one via `existingId`.
457
+ if (newId != null) this.idCache.set(name, newId)
458
+
459
+ onProgress?.(total, total)
460
+ }
461
+
462
+ private async startResumableSession(name: string, existingId: string | null): Promise<string> {
463
+ const url = existingId != null
464
+ ? `${UPLOAD_URL}/${existingId}?uploadType=resumable`
465
+ : `${UPLOAD_URL}?uploadType=resumable&fields=id`
466
+ const metadata = existingId != null ? {} : { name, parents: ['appDataFolder'] }
467
+
468
+ const res = await this.request(url, {
469
+ method: existingId != null ? 'PATCH' : 'POST',
470
+ headers: { 'Content-Type': 'application/json; charset=UTF-8' },
471
+ body: JSON.stringify(metadata),
472
+ })
473
+
474
+ const location = res.headers.get('Location')
475
+ if (location == null)
476
+ throw new CloudSyncError(
477
+ ErrorCode.UNKNOWN,
478
+ '[RNCloudSync] Google Drive did not return a resumable session URI.',
479
+ { provider: 'googleDrive' }
480
+ )
481
+
482
+ return location
483
+ }
484
+
485
+ /** One chunk, with a single retry that re-queries the server's real offset first. */
486
+ private async putChunkWithRetry(
487
+ sessionUrl: string,
488
+ source: DriveChunkSource,
489
+ offset: number,
490
+ length: number,
491
+ total: number,
492
+ onProgress?: (bytesTransferred: number, bytesTotal: number) => void
493
+ ): Promise<{ nextOffset: number; id?: string }> {
494
+ try {
495
+ return await this.putChunk(sessionUrl, source, offset, length, total, onProgress)
496
+ }
497
+ catch (e) {
498
+ 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)
502
+ }
503
+ }
504
+
505
+ private async putChunk(
506
+ sessionUrl: string,
507
+ source: DriveChunkSource,
508
+ offset: number,
509
+ length: number,
510
+ total: number,
511
+ onProgress?: (bytesTransferred: number, bytesTotal: number) => void
512
+ ): Promise<{ nextOffset: number; id?: string }> {
513
+ const bytes = await source.read(offset, length)
514
+ const range = total === 0 ? 'bytes */0' : `bytes ${offset}-${offset + bytes.length - 1}/${total}`
515
+
516
+ const res = await this.request(sessionUrl, {
517
+ method: 'PUT',
518
+ headers: { 'Content-Range': range },
519
+ // TS's DOM lib types BodyInit's BufferSource as Uint8Array<ArrayBuffer>
520
+ // specifically, which a plain Uint8Array read doesn't structurally
521
+ // match even though every fetch implementation accepts it at runtime.
522
+ body: bytes as BodyInit,
523
+ }, [308])
524
+
525
+ const nextOffset = offset + bytes.length
526
+ if (res.status === 308) {
527
+ onProgress?.(nextOffset, total)
528
+ return { nextOffset }
529
+ }
530
+
531
+ // 200/201: the file is complete.
532
+ const json = (await res.json().catch(() => null)) as { id?: string } | null
533
+ return { nextOffset: total, id: json?.id }
534
+ }
535
+
536
+ /** Asks Drive how much of an in-flight resumable session it actually has. */
537
+ private async queryUploadOffset(sessionUrl: string, total: number): Promise<number> {
538
+ const res = await this.request(sessionUrl, {
539
+ method: 'PUT',
540
+ headers: { 'Content-Range': `bytes */${total}` },
541
+ }, [308])
542
+
543
+ if (res.status !== 308) return total // already complete, unexpectedly
544
+
545
+ const range = res.headers.get('Range') // "bytes=0-8388607"
546
+ if (range == null) return 0
547
+
548
+ const match = /bytes=0-(\d+)/.exec(range)
549
+ return match ? Number(match[1]) + 1 : 0
550
+ }
551
+
552
+ /**
553
+ * Downloads `name` into `sink`, in the same fixed-size chunks `uploadFile`
554
+ * writes in - so a restore never holds the whole file in memory either.
555
+ * Resolves `false` when no such file exists, `true` once every chunk has
556
+ * been handed to the sink.
557
+ */
558
+ async downloadFile(
559
+ name: string,
560
+ sink: DriveChunkSink,
561
+ onProgress?: (bytesTransferred: number, bytesTotal: number) => void,
562
+ signal?: AbortLike
563
+ ): Promise<boolean> {
564
+ throwIfAborted(signal, 'googleDrive')
565
+ const id = await this.findFileId(name)
566
+ if (id == null) return false
567
+
568
+ const total = await this.fileSize(id)
569
+
570
+ if (total === 0) {
571
+ await sink.write(new Uint8Array(0), true)
572
+ onProgress?.(0, 0)
573
+ return true
574
+ }
575
+
576
+ let offset = 0
577
+ let isFirstChunk = true
578
+ while (offset < total) {
579
+ throwIfAborted(signal, 'googleDrive')
580
+ const end = Math.min(offset + this.chunkBytes, total) - 1
581
+ const res = await this.request(`${FILES_URL}/${id}?alt=media`, {
582
+ method: 'GET',
583
+ headers: { Range: `bytes=${offset}-${end}` },
584
+ })
585
+ const bytes = new Uint8Array(await res.arrayBuffer())
586
+ await sink.write(bytes, isFirstChunk)
587
+ isFirstChunk = false
588
+ offset += bytes.length
589
+ onProgress?.(offset, total)
590
+ }
591
+
592
+ return true
593
+ }
594
+
595
+ private async fileSize(id: string): Promise<number> {
596
+ const res = await this.request(`${FILES_URL}/${id}?fields=size`, { method: 'GET' })
597
+ const json = (await res.json()) as { size?: string }
598
+ return json.size != null ? Number(json.size) : 0
599
+ }
600
+
601
+ async removeItem(name: string): Promise<void> {
602
+ const id = await this.findFileId(name)
603
+ // Already absent is the desired end state, not a failure.
604
+ if (id == null) return
605
+
606
+ try {
607
+ await this.request(`${FILES_URL}/${id}`, { method: 'DELETE' })
608
+ }
609
+ catch (e) {
610
+ // Deleted from under us: the end state the caller asked for already holds.
611
+ if (!isNotFound(e)) throw e
612
+ }
613
+ finally {
614
+ this.idCache.delete(name)
615
+ this.metaCache.delete(name)
616
+ }
617
+ }
618
+
619
+ async getAllKeys(): Promise<string[]> {
620
+ const names: string[] = []
621
+ let pageToken: string | undefined
622
+
623
+ // Paginate rather than assuming one page holds everything.
624
+ do {
625
+ const params = new URLSearchParams({
626
+ spaces: 'appDataFolder',
627
+ q: 'trashed=false',
628
+ fields: `nextPageToken,files(${FILE_FIELDS})`,
629
+ pageSize: '100',
630
+ })
631
+ if (pageToken != null) params.set('pageToken', pageToken)
632
+
633
+ const res = await this.request(`${FILES_URL}?${params.toString()}`, { method: 'GET' })
634
+ const json = (await res.json()) as { files?: DriveFile[]; nextPageToken?: string }
635
+
636
+ for (const f of json.files ?? []) {
637
+ names.push(f.name)
638
+ this.remember(f)
639
+ }
640
+ pageToken = json.nextPageToken
641
+ } while (pageToken != null)
642
+
643
+ return names
644
+ }
645
+
646
+ /**
647
+ * A cursor marking "everything up to now", for {@link pollChanges}.
648
+ *
649
+ * Drive's change feed is cursor-based rather than time-based, so a watcher
650
+ * has to take a starting cursor before it can ask what changed since.
651
+ */
652
+ async getStartPageToken(): Promise<string> {
653
+ const res = await this.request(
654
+ `${CHANGES_URL}/startPageToken?spaces=appDataFolder`,
655
+ { method: 'GET' }
656
+ )
657
+ const json = (await res.json()) as { startPageToken?: string }
658
+ if (json.startPageToken == null)
659
+ throw new CloudSyncError(
660
+ ErrorCode.UNKNOWN,
661
+ '[RNCloudSync] Google Drive did not return a change cursor.',
662
+ { provider: 'googleDrive' }
663
+ )
664
+
665
+ return json.startPageToken
666
+ }
667
+
668
+ /**
669
+ * What changed in `appDataFolder` since `pageToken`, and the cursor to use
670
+ * next time.
671
+ *
672
+ * This is how a non-Apple platform learns that another device wrote something
673
+ * - CloudKit gets `NSUbiquitousKeyValueStore` notifications and `CKAccountChanged`
674
+ * for free, but Drive has no push channel without a server to receive its
675
+ * webhooks, so the honest equivalent is a cursor the app polls. Cheap: a poll
676
+ * with nothing to report is one request returning an empty list.
677
+ *
678
+ * Deletions are included - `removed` entries and trashed files both surface,
679
+ * because "another device deleted this key" is exactly as important as
680
+ * "another device changed it".
681
+ */
682
+ async pollChanges(pageToken: string): Promise<{ names: string[]; nextToken: string }> {
683
+ const names = new Set<string>()
684
+ let token = pageToken
685
+ let nextToken: string
686
+
687
+ for (;;) {
688
+ const params = new URLSearchParams({
689
+ pageToken: token,
690
+ spaces: 'appDataFolder',
691
+ includeRemoved: 'true',
692
+ fields: 'newStartPageToken,nextPageToken,changes(fileId,removed,file(id,name,trashed))',
693
+ })
694
+ const res = await this.request(`${CHANGES_URL}?${params.toString()}`, { method: 'GET' })
695
+ const json = (await res.json()) as {
696
+ newStartPageToken?: string
697
+ nextPageToken?: string
698
+ changes?: {
699
+ fileId?: string
700
+ removed?: boolean
701
+ file?: { id?: string; name?: string; trashed?: boolean }
702
+ }[]
703
+ }
704
+
705
+ for (const change of json.changes ?? []) {
706
+ const name = change.file?.name
707
+ if (name != null) {
708
+ names.add(name)
709
+ // A file that went away must not keep answering reads from the id
710
+ // cache, and one that changed must be re-read rather than served
711
+ // from a stale memo.
712
+ if (change.removed === true || change.file?.trashed === true) {
713
+ this.idCache.delete(name)
714
+ this.metaCache.delete(name)
715
+ }
716
+ continue
717
+ }
718
+
719
+ // Drive omits `file` for a change the caller can no longer see. All we
720
+ // have is the id, so drop whichever cached name points at it.
721
+ if (change.fileId != null) this.forgetById(change.fileId)
722
+ }
723
+
724
+ // `nextPageToken` means more pages of the same batch; `newStartPageToken`
725
+ // means this was the last page and is the cursor for next time.
726
+ if (json.nextPageToken != null) {
727
+ token = json.nextPageToken
728
+ continue
729
+ }
730
+ nextToken = json.newStartPageToken ?? token
731
+ break
732
+ }
733
+
734
+ return { names: [...names], nextToken }
735
+ }
736
+
737
+ /** Drops whatever name currently memoises this file id. */
738
+ private forgetById(fileId: string): void {
739
+ for (const [name, id] of this.idCache)
740
+ if (id === fileId) {
741
+ this.idCache.delete(name)
742
+ this.metaCache.delete(name)
743
+ return
744
+ }
745
+ }
746
+
747
+ /**
748
+ * Whether an access token can currently be obtained, without making a network
749
+ * request. Backs the provider's `isAvailable()` probe.
750
+ */
751
+ async hasToken(): Promise<boolean> {
752
+ try {
753
+ return (await this.config.getAccessToken()) != null
754
+ }
755
+ catch {
756
+ return false
757
+ }
758
+ }
759
+
760
+ /** Drops memoised file ids. Call after an account switch. */
761
+ clearCache(): void {
762
+ this.idCache.clear()
763
+ this.metaCache.clear()
764
+ }
765
+ }