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,160 @@
1
+ import { CloudSyncError, ErrorCode } from '../errors'
2
+ import type { ProviderName } from '../types'
3
+ import { byteLength } from './bytes'
4
+
5
+ /**
6
+ * Key validation.
7
+ *
8
+ * One key string has to be three different things at once - an
9
+ * `NSUbiquitousKeyValueStore` key, a CloudKit `recordName` and a Google Drive
10
+ * file name - and the three disagree about what is legal. Nothing checked, a
11
+ * key that is fine on iOS comes back from CloudKit Web Services as
12
+ * `BAD_REQUEST`, which this package maps to `ERR_CONTAINER_MISCONFIGURED`, and
13
+ * the developer goes looking at their entitlements.
14
+ *
15
+ * So the rules are stated here, checked before the request, and reported with
16
+ * the offending key and the specific rule it broke.
17
+ */
18
+
19
+ /**
20
+ * Apple: "The maximum length for a key string is 64 bytes using UTF8 encoding."
21
+ * Note *bytes*, not characters - a key of emoji is four times longer than it
22
+ * looks.
23
+ */
24
+ const KV_MAX_KEY_BYTES = 64
25
+
26
+ /** CloudKit's documented ceiling for a record name. */
27
+ const CK_MAX_RECORD_NAME = 255
28
+
29
+ /**
30
+ * CloudKit accepts ASCII letters, digits, `-`, `_` and `.` in a record name.
31
+ *
32
+ * Checked **only when a CloudKit provider is configured**. It is a CloudKit
33
+ * restriction, not a universal one: `NSUbiquitousKeyValueStore` keys are plain
34
+ * strings with no character rules at all, and Drive file names are nearly as
35
+ * permissive. Applying it everywhere rejected keys that had been working in
36
+ * production for years - `auth/anonymousUserId/v1` in an app that only ever
37
+ * used the key-value store - which is a far worse outcome than the server
38
+ * error this check exists to pre-empt.
39
+ */
40
+ const SAFE_KEY = /^[A-Za-z0-9._-]+$/
41
+
42
+ /** CloudKit reserves the leading underscore for its own system record names. */
43
+ const RESERVED_PREFIX = '_'
44
+
45
+ /** Providers whose keys become CloudKit record names. */
46
+ const CLOUDKIT_PROVIDERS: readonly ProviderName[] = ['cloudKit', 'cloudKitEncrypted']
47
+
48
+ function usesCloudKit(providers: readonly ProviderName[]): ProviderName | null {
49
+ return providers.find(p => CLOUDKIT_PROVIDERS.includes(p)) ?? null
50
+ }
51
+
52
+ export interface KeyRule {
53
+ /** Human-readable statement of what was violated. */
54
+ reason: string
55
+ /** The provider whose limit this is, or null when every provider shares it. */
56
+ provider: ProviderName | null
57
+ }
58
+
59
+ /**
60
+ * The first rule `key` breaks for this set of providers, or null when it is
61
+ * usable everywhere.
62
+ *
63
+ * Provider-aware on purpose: the 64-byte ceiling is the key-value store's
64
+ * alone, and rejecting a 100-character key for an app that only configured
65
+ * Drive would be a false alarm.
66
+ */
67
+ export function checkKey(key: string, providers: readonly ProviderName[]): KeyRule | null {
68
+ if (typeof key !== 'string' || key.length === 0)
69
+ return { reason: 'a key must be a non-empty string', provider: null }
70
+
71
+ // Every rule below this line belongs to a specific provider, and is only
72
+ // applied when that provider is actually configured. Rejecting a key for a
73
+ // restriction that cannot apply is not caution, it is a false alarm - and one
74
+ // that breaks working apps rather than pre-empting a server error.
75
+ const cloudKitProvider = usesCloudKit(providers)
76
+
77
+ if (cloudKitProvider != null) {
78
+ if (!SAFE_KEY.test(key))
79
+ return {
80
+ reason:
81
+ 'a key may contain only ASCII letters, digits, and the characters . _ - '
82
+ + 'once it has to serve as a CloudKit record name',
83
+ provider: cloudKitProvider,
84
+ }
85
+
86
+ if (key.startsWith(RESERVED_PREFIX))
87
+ return {
88
+ reason: 'a key may not start with "_", which CloudKit reserves for system records',
89
+ provider: cloudKitProvider,
90
+ }
91
+
92
+ if (key.length > CK_MAX_RECORD_NAME)
93
+ return {
94
+ reason:
95
+ `a CloudKit record name is limited to ${CK_MAX_RECORD_NAME} characters `
96
+ + `(got ${key.length})`,
97
+ provider: cloudKitProvider,
98
+ }
99
+ }
100
+
101
+ if (providers.includes('icloudKV')) {
102
+ const bytes = byteLength(key)
103
+ if (bytes > KV_MAX_KEY_BYTES)
104
+ return {
105
+ reason:
106
+ `an iCloud key-value store key is limited to ${KV_MAX_KEY_BYTES} UTF-8 bytes `
107
+ + `(got ${bytes})`,
108
+ provider: 'icloudKV',
109
+ }
110
+ }
111
+
112
+ return null
113
+ }
114
+
115
+ /** Throws {@link ErrorCode.INVALID_KEY} when `key` is unusable. */
116
+ export function assertKey(key: string, providers: readonly ProviderName[]): void {
117
+ const broken = checkKey(key, providers)
118
+ if (broken == null) return
119
+
120
+ throw new CloudSyncError(
121
+ ErrorCode.INVALID_KEY,
122
+ `[RNCloudSync] Invalid key ${JSON.stringify(key)}: ${broken.reason}.`,
123
+ { provider: broken.provider ?? undefined }
124
+ )
125
+ }
126
+
127
+ /**
128
+ * Rewrites an arbitrary string into a key that passes {@link checkKey}.
129
+ *
130
+ * For callers whose keys come from somewhere they do not control - a file name,
131
+ * a user-entered label, an id from another system. Illegal characters become
132
+ * `-`, and anything too long is truncated and suffixed with a short hash of the
133
+ * original so two different long keys cannot collide.
134
+ */
135
+ export function sanitizeKey(raw: string, maxBytes = KV_MAX_KEY_BYTES): string {
136
+ const cleaned = raw
137
+ .replace(/[^A-Za-z0-9._-]/g, '-')
138
+ .replace(/^_+/, '')
139
+
140
+ const base = cleaned.length > 0 ? cleaned : 'key'
141
+ if (byteLength(base) <= maxBytes) return base
142
+
143
+ // Truncating alone would map every long key with a shared prefix onto the
144
+ // same short key, silently merging unrelated values.
145
+ const suffix = `-${hash(raw)}`
146
+ const room = Math.max(1, maxBytes - suffix.length)
147
+ let head = base.slice(0, room)
148
+ while (byteLength(head) > room) head = head.slice(0, -1)
149
+ return head + suffix
150
+ }
151
+
152
+ /** FNV-1a, base36. Not cryptographic - only needs to separate collisions. */
153
+ function hash(s: string): string {
154
+ let h = 0x811c9dc5
155
+ for (let i = 0; i < s.length; i += 1) {
156
+ h ^= s.charCodeAt(i)
157
+ h = Math.imul(h, 0x01000193) >>> 0
158
+ }
159
+ return h.toString(36)
160
+ }
@@ -0,0 +1,23 @@
1
+ import { getNativeModule } from './nativeModule'
2
+
3
+ let enabled = false
4
+
5
+ /**
6
+ * Toggles verbose logging in both JS and the native layer.
7
+ *
8
+ * Off by default: a storage library logging every read on a hot path is noise,
9
+ * and cloud payloads can contain user data that should not land in a device log.
10
+ */
11
+ export function setLogsEnabled(value: boolean): void {
12
+ enabled = value
13
+ getNativeModule()?.setLogsEnabled(value)
14
+ }
15
+
16
+ export function isLogsEnabled(): boolean {
17
+ return enabled
18
+ }
19
+
20
+ export function log(...args: unknown[]): void {
21
+ if (!enabled) return
22
+ console.warn('[RNCloudSync]', ...args)
23
+ }
@@ -0,0 +1,149 @@
1
+ import { NativeEventEmitter, NativeModules, Platform, TurboModuleRegistry } from 'react-native'
2
+
3
+ import type { Spec } from '../specs/NativeRNCloudSync'
4
+ import { CloudSyncError, ErrorCode } from '../errors'
5
+ import type { Unsubscribe } from '../types'
6
+
7
+ const MODULE_NAME = 'RNCloudSync'
8
+
9
+ const LINKING_ERROR
10
+ = `[RNCloudSync] The native module doesn't seem to be linked. Make sure you have:\n\n`
11
+ + ` - run 'pod install' (iOS) or rebuilt the app (Android) after installing\n`
12
+ + ` - rebuilt the app after installing, not just restarted Metro\n`
13
+ + ` - not using Expo Go, which cannot load custom native modules\n`
14
+
15
+ let cached: Spec | null = null
16
+ let resolved = false
17
+
18
+ /**
19
+ * Whether the running app is on the New Architecture.
20
+ *
21
+ * Detected from which registry produced the module rather than from a global
22
+ * flag, because `global.__turboModuleProxy` is not reliable across the RN
23
+ * versions this package supports (0.71 through 0.86+).
24
+ */
25
+ let isNewArch = false
26
+
27
+ /**
28
+ * Resolves the native module lazily.
29
+ *
30
+ * New arch exposes it through TurboModuleRegistry; old arch through the
31
+ * NativeModules proxy. Resolution is deferred rather than done at import time
32
+ * so that merely importing this package on a platform without the native module
33
+ * (web, or Android for the iCloud provider) does not throw at bundle-evaluation
34
+ * time - which is exactly the crash cryptoc had to work around with a
35
+ * `Platform.OS === 'ios' ? requireNativeModule(...) : null` guard.
36
+ */
37
+ export function getNativeModule(): Spec | null {
38
+ if (resolved) return cached
39
+ resolved = true
40
+
41
+ // Everything here is wrapped, because "there is no native module" has to be a
42
+ // `null`, never a throw. react-native-web exports no `TurboModuleRegistry` at
43
+ // all, so on a web build served by webpack/Vite/Next - which, unlike Metro,
44
+ // do not resolve the `.web.ts` platform extension - `TurboModuleRegistry` is
45
+ // `undefined` and calling `.get` on it is a TypeError. That surfaced as a
46
+ // crash inside `cloudKit.isAvailable()`, a method documented as safe to call
47
+ // on a render path.
48
+ try {
49
+ // TurboModuleRegistry.get is safe on the old architecture too - it simply
50
+ // returns null there rather than throwing (unlike getEnforcing).
51
+ const turbo = TurboModuleRegistry?.get<Spec>(MODULE_NAME)
52
+ if (turbo != null) {
53
+ cached = turbo
54
+ isNewArch = true
55
+ return cached
56
+ }
57
+ }
58
+ catch {
59
+ // Fall through to the legacy registry.
60
+ }
61
+
62
+ try {
63
+ const legacy = (NativeModules as Record<string, unknown> | undefined)?.[MODULE_NAME]
64
+ if (legacy != null) {
65
+ cached = legacy as Spec
66
+ isNewArch = false
67
+ return cached
68
+ }
69
+ }
70
+ catch {
71
+ // No registry either. Treated as "no native module", same as web.
72
+ }
73
+
74
+ cached = null
75
+ return null
76
+ }
77
+
78
+ /** Like {@link getNativeModule} but throws a diagnostic instead of returning null. */
79
+ export function requireNativeModule(): Spec {
80
+ const m = getNativeModule()
81
+ if (m == null)
82
+ throw new CloudSyncError(
83
+ ErrorCode.UNSUPPORTED_PLATFORM,
84
+ Platform.OS === 'web'
85
+ ? '[RNCloudSync] This provider requires a native module and is not available on web.'
86
+ : LINKING_ERROR
87
+ )
88
+
89
+ return m
90
+ }
91
+
92
+ export function hasNativeModule(): boolean {
93
+ return getNativeModule() != null
94
+ }
95
+
96
+ let legacyEmitter: NativeEventEmitter | null = null
97
+
98
+ function getLegacyEmitter(): NativeEventEmitter {
99
+ if (legacyEmitter == null)
100
+ // The old-architecture module is an RCTEventEmitter, so it is a valid
101
+ // NativeEventEmitter argument. On Android events always travel over
102
+ // RCTDeviceEventEmitter, which NativeEventEmitter also handles.
103
+ legacyEmitter = new NativeEventEmitter(
104
+ (NativeModules as Record<string, never>)[MODULE_NAME]
105
+ )
106
+
107
+ return legacyEmitter
108
+ }
109
+
110
+ /**
111
+ * Event names differ per architecture.
112
+ *
113
+ * Codegen's EventEmitter properties must be named `onSomething`, while the old
114
+ * architecture's `supportedEvents` list uses the bare name. Rather than leak
115
+ * that split into every call site, subscribe through this helper.
116
+ * (react-native-background-downloader carries the same `onDownloadBegin` vs
117
+ * `downloadBegin` split for the same reason.)
118
+ */
119
+ export function subscribeNativeEvent<T>(
120
+ newArchName: 'onRemoteChange' | 'onAccountChange' | 'onAssetProgress',
121
+ legacyName: 'remoteChange' | 'accountChange' | 'assetProgress',
122
+ listener: (e: T) => void
123
+ ): Unsubscribe {
124
+ const m = getNativeModule()
125
+ if (m == null) return () => undefined
126
+
127
+ if (isNewArch) {
128
+ const emitter = m[newArchName] as unknown as {
129
+ (cb: (e: T) => void): { remove: () => void }
130
+ }
131
+ const sub = emitter(listener)
132
+ return () => {
133
+ sub.remove()
134
+ }
135
+ }
136
+
137
+ const sub = getLegacyEmitter().addListener(legacyName, listener as (e: unknown) => void)
138
+ return () => {
139
+ sub.remove()
140
+ }
141
+ }
142
+
143
+ /** Exposed for tests and diagnostics only. */
144
+ export function __resetNativeModuleCache(): void {
145
+ cached = null
146
+ resolved = false
147
+ legacyEmitter = null
148
+ isNewArch = false
149
+ }
@@ -0,0 +1,83 @@
1
+ import { cancelled, timedOut } from '../errors'
2
+
3
+ /**
4
+ * Rejects with {@link ErrorCode.TIMEOUT} if `promise` has not settled in time.
5
+ *
6
+ * React Native's `fetch` has no default timeout, and neither does CloudKit's
7
+ * native stack, so an unanswered socket hangs an operation forever. That is
8
+ * worse than an error: the store calls `isAvailable()` before every operation,
9
+ * so one hung probe stalls reads and writes that would otherwise have fallen
10
+ * through to a working provider.
11
+ *
12
+ * The underlying work is *not* cancelled - a promise cannot be. This only stops
13
+ * the caller waiting on it, which is why the timeout error is classified as
14
+ * retryable rather than as a failure.
15
+ */
16
+ export function withTimeout<T>(promise: Promise<T>, ms: number, provider?: string): Promise<T> {
17
+ if (!Number.isFinite(ms) || ms <= 0) return promise
18
+
19
+ return new Promise<T>((resolve, reject) => {
20
+ const timer = setTimeout(() => reject(timedOut(ms, provider)), ms)
21
+
22
+ promise.then(
23
+ (value) => {
24
+ clearTimeout(timer)
25
+ resolve(value)
26
+ },
27
+ (error: Error) => {
28
+ clearTimeout(timer)
29
+ reject(error)
30
+ }
31
+ )
32
+ })
33
+ }
34
+
35
+ /**
36
+ * The subset of `AbortSignal` this package needs.
37
+ *
38
+ * Typed structurally rather than as the DOM `AbortSignal` so a caller can pass
39
+ * one from any polyfill, and so the package does not require `lib.dom` to be in
40
+ * a consumer's `tsconfig`.
41
+ */
42
+ export interface AbortLike {
43
+ readonly aborted: boolean
44
+ addEventListener: (type: 'abort', listener: () => void) => void
45
+ removeEventListener: (type: 'abort', listener: () => void) => void
46
+ }
47
+
48
+ /** Throws {@link ErrorCode.CANCELLED} if the signal is already aborted. */
49
+ export function throwIfAborted(signal: AbortLike | undefined, provider?: string): void {
50
+ if (signal?.aborted === true) throw cancelled(provider)
51
+ }
52
+
53
+ /**
54
+ * Races `promise` against an abort signal.
55
+ *
56
+ * Used by the chunked transfer paths, where "cancel" has to take effect between
57
+ * chunks rather than only once the whole multi-hundred-megabyte file has moved.
58
+ */
59
+ export function withAbort<T>(
60
+ promise: Promise<T>,
61
+ signal: AbortLike | undefined,
62
+ provider?: string
63
+ ): Promise<T> {
64
+ if (signal == null) return promise
65
+ if (signal.aborted) return Promise.reject(cancelled(provider))
66
+
67
+ return new Promise<T>((resolve, reject) => {
68
+ const onAbort = (): void => reject(cancelled(provider))
69
+ signal.addEventListener('abort', onAbort)
70
+
71
+ const done = (): void => signal.removeEventListener('abort', onAbort)
72
+ promise.then(
73
+ (value) => {
74
+ done()
75
+ resolve(value)
76
+ },
77
+ (error: Error) => {
78
+ done()
79
+ reject(error)
80
+ }
81
+ )
82
+ })
83
+ }