@webority/mobile-core 0.0.23

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 (211) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +39 -0
  3. package/android/build.gradle +65 -0
  4. package/android/src/newarch/java/com/webority/mobilecore/smsretriever/AppSignatureHelper.kt +57 -0
  5. package/android/src/newarch/java/com/webority/mobilecore/smsretriever/SmsRetrieverModule.kt +20 -0
  6. package/android/src/newarch/java/com/webority/mobilecore/smsretriever/SmsRetrieverModuleImpl.kt +146 -0
  7. package/android/src/newarch/java/com/webority/mobilecore/smsretriever/SmsRetrieverPackage.kt +33 -0
  8. package/lib/commonjs/api/baseUrl.js +34 -0
  9. package/lib/commonjs/api/curl.js +109 -0
  10. package/lib/commonjs/api/publicClient.js +73 -0
  11. package/lib/commonjs/api/retry.js +75 -0
  12. package/lib/commonjs/api/tokenRefresh.js +205 -0
  13. package/lib/commonjs/api/userClient.js +255 -0
  14. package/lib/commonjs/auth/authStore.js +232 -0
  15. package/lib/commonjs/auth/index.js +44 -0
  16. package/lib/commonjs/auth/jwt.js +112 -0
  17. package/lib/commonjs/config/index.js +66 -0
  18. package/lib/commonjs/deepLink/index.js +286 -0
  19. package/lib/commonjs/download/adapters/expoFs.js +69 -0
  20. package/lib/commonjs/download/adapters/shared.js +13 -0
  21. package/lib/commonjs/download/index.js +250 -0
  22. package/lib/commonjs/formatters/currency.js +69 -0
  23. package/lib/commonjs/formatters/date.js +168 -0
  24. package/lib/commonjs/formatters/dateMath.js +310 -0
  25. package/lib/commonjs/formatters/index.js +246 -0
  26. package/lib/commonjs/formatters/initials.js +32 -0
  27. package/lib/commonjs/formatters/number.js +88 -0
  28. package/lib/commonjs/formatters/phone.js +369 -0
  29. package/lib/commonjs/formatters/windowsToIanaTable.js +164 -0
  30. package/lib/commonjs/geolocation/adapters/expoLocation.js +126 -0
  31. package/lib/commonjs/geolocation/index.js +355 -0
  32. package/lib/commonjs/index.js +630 -0
  33. package/lib/commonjs/initSDK.js +66 -0
  34. package/lib/commonjs/initUserAuth.js +37 -0
  35. package/lib/commonjs/logger/index.js +291 -0
  36. package/lib/commonjs/network/index.js +31 -0
  37. package/lib/commonjs/network/networkStatus.js +133 -0
  38. package/lib/commonjs/package.json +1 -0
  39. package/lib/commonjs/permissions/calendar.js +14 -0
  40. package/lib/commonjs/permissions/camera.js +14 -0
  41. package/lib/commonjs/permissions/contacts.js +10 -0
  42. package/lib/commonjs/permissions/index.js +133 -0
  43. package/lib/commonjs/permissions/location.js +14 -0
  44. package/lib/commonjs/permissions/mediaLibrary.js +10 -0
  45. package/lib/commonjs/permissions/notifications.js +10 -0
  46. package/lib/commonjs/permissions/photos.js +14 -0
  47. package/lib/commonjs/phone/countries.js +265 -0
  48. package/lib/commonjs/share/index.js +70 -0
  49. package/lib/commonjs/smsRetriever/index.js +91 -0
  50. package/lib/commonjs/specs/NativeSmsRetriever.js +15 -0
  51. package/lib/commonjs/sqlite/adapters/expo.js +53 -0
  52. package/lib/commonjs/sqlite/index.js +604 -0
  53. package/lib/commonjs/storage/index.js +214 -0
  54. package/lib/commonjs/types/globals.d.js +6 -0
  55. package/lib/commonjs/utils/imageCompression.js +389 -0
  56. package/lib/commonjs/utils/index.js +19 -0
  57. package/lib/commonjs/validators/index.js +227 -0
  58. package/lib/commonjs/versionCheck/index.js +419 -0
  59. package/lib/module/api/baseUrl.js +30 -0
  60. package/lib/module/api/curl.js +104 -0
  61. package/lib/module/api/publicClient.js +69 -0
  62. package/lib/module/api/retry.js +69 -0
  63. package/lib/module/api/tokenRefresh.js +192 -0
  64. package/lib/module/api/userClient.js +233 -0
  65. package/lib/module/auth/authStore.js +224 -0
  66. package/lib/module/auth/index.js +5 -0
  67. package/lib/module/auth/jwt.js +106 -0
  68. package/lib/module/config/index.js +58 -0
  69. package/lib/module/deepLink/index.js +280 -0
  70. package/lib/module/download/adapters/expoFs.js +64 -0
  71. package/lib/module/download/adapters/shared.js +8 -0
  72. package/lib/module/download/index.js +242 -0
  73. package/lib/module/formatters/currency.js +64 -0
  74. package/lib/module/formatters/date.js +160 -0
  75. package/lib/module/formatters/dateMath.js +294 -0
  76. package/lib/module/formatters/index.js +9 -0
  77. package/lib/module/formatters/initials.js +27 -0
  78. package/lib/module/formatters/number.js +81 -0
  79. package/lib/module/formatters/phone.js +302 -0
  80. package/lib/module/formatters/windowsToIanaTable.js +160 -0
  81. package/lib/module/geolocation/adapters/expoLocation.js +121 -0
  82. package/lib/module/geolocation/index.js +347 -0
  83. package/lib/module/index.js +54 -0
  84. package/lib/module/initSDK.js +61 -0
  85. package/lib/module/initUserAuth.js +33 -0
  86. package/lib/module/logger/index.js +285 -0
  87. package/lib/module/network/index.js +4 -0
  88. package/lib/module/network/networkStatus.js +124 -0
  89. package/lib/module/package.json +1 -0
  90. package/lib/module/permissions/calendar.js +15 -0
  91. package/lib/module/permissions/camera.js +15 -0
  92. package/lib/module/permissions/contacts.js +11 -0
  93. package/lib/module/permissions/index.js +128 -0
  94. package/lib/module/permissions/location.js +15 -0
  95. package/lib/module/permissions/mediaLibrary.js +11 -0
  96. package/lib/module/permissions/notifications.js +11 -0
  97. package/lib/module/permissions/photos.js +15 -0
  98. package/lib/module/phone/countries.js +261 -0
  99. package/lib/module/share/index.js +64 -0
  100. package/lib/module/smsRetriever/index.js +86 -0
  101. package/lib/module/specs/NativeSmsRetriever.js +13 -0
  102. package/lib/module/sqlite/adapters/expo.js +48 -0
  103. package/lib/module/sqlite/index.js +594 -0
  104. package/lib/module/storage/index.js +208 -0
  105. package/lib/module/types/globals.d.js +10 -0
  106. package/lib/module/utils/imageCompression.js +383 -0
  107. package/lib/module/utils/index.js +4 -0
  108. package/lib/module/validators/index.js +205 -0
  109. package/lib/module/versionCheck/index.js +413 -0
  110. package/lib/typescript/commonjs/api/baseUrl.d.ts +20 -0
  111. package/lib/typescript/commonjs/api/curl.d.ts +18 -0
  112. package/lib/typescript/commonjs/api/publicClient.d.ts +11 -0
  113. package/lib/typescript/commonjs/api/retry.d.ts +27 -0
  114. package/lib/typescript/commonjs/api/tokenRefresh.d.ts +43 -0
  115. package/lib/typescript/commonjs/api/userClient.d.ts +37 -0
  116. package/lib/typescript/commonjs/auth/authStore.d.ts +79 -0
  117. package/lib/typescript/commonjs/auth/index.d.ts +5 -0
  118. package/lib/typescript/commonjs/auth/jwt.d.ts +31 -0
  119. package/lib/typescript/commonjs/config/index.d.ts +55 -0
  120. package/lib/typescript/commonjs/deepLink/index.d.ts +54 -0
  121. package/lib/typescript/commonjs/download/adapters/expoFs.d.ts +38 -0
  122. package/lib/typescript/commonjs/download/adapters/shared.d.ts +3 -0
  123. package/lib/typescript/commonjs/download/index.d.ts +86 -0
  124. package/lib/typescript/commonjs/formatters/currency.d.ts +24 -0
  125. package/lib/typescript/commonjs/formatters/date.d.ts +22 -0
  126. package/lib/typescript/commonjs/formatters/dateMath.d.ts +88 -0
  127. package/lib/typescript/commonjs/formatters/index.d.ts +10 -0
  128. package/lib/typescript/commonjs/formatters/initials.d.ts +11 -0
  129. package/lib/typescript/commonjs/formatters/number.d.ts +15 -0
  130. package/lib/typescript/commonjs/formatters/phone.d.ts +133 -0
  131. package/lib/typescript/commonjs/formatters/windowsToIanaTable.d.ts +18 -0
  132. package/lib/typescript/commonjs/geolocation/adapters/expoLocation.d.ts +42 -0
  133. package/lib/typescript/commonjs/geolocation/index.d.ts +90 -0
  134. package/lib/typescript/commonjs/index.d.ts +54 -0
  135. package/lib/typescript/commonjs/initSDK.d.ts +72 -0
  136. package/lib/typescript/commonjs/initUserAuth.d.ts +41 -0
  137. package/lib/typescript/commonjs/logger/index.d.ts +81 -0
  138. package/lib/typescript/commonjs/network/index.d.ts +3 -0
  139. package/lib/typescript/commonjs/network/networkStatus.d.ts +43 -0
  140. package/lib/typescript/commonjs/package.json +1 -0
  141. package/lib/typescript/commonjs/permissions/calendar.d.ts +2 -0
  142. package/lib/typescript/commonjs/permissions/camera.d.ts +2 -0
  143. package/lib/typescript/commonjs/permissions/contacts.d.ts +2 -0
  144. package/lib/typescript/commonjs/permissions/index.d.ts +48 -0
  145. package/lib/typescript/commonjs/permissions/location.d.ts +2 -0
  146. package/lib/typescript/commonjs/permissions/mediaLibrary.d.ts +2 -0
  147. package/lib/typescript/commonjs/permissions/notifications.d.ts +2 -0
  148. package/lib/typescript/commonjs/permissions/photos.d.ts +2 -0
  149. package/lib/typescript/commonjs/phone/countries.d.ts +13 -0
  150. package/lib/typescript/commonjs/share/index.d.ts +29 -0
  151. package/lib/typescript/commonjs/smsRetriever/index.d.ts +30 -0
  152. package/lib/typescript/commonjs/specs/NativeSmsRetriever.d.ts +15 -0
  153. package/lib/typescript/commonjs/sqlite/adapters/expo.d.ts +30 -0
  154. package/lib/typescript/commonjs/sqlite/index.d.ts +113 -0
  155. package/lib/typescript/commonjs/storage/index.d.ts +64 -0
  156. package/lib/typescript/commonjs/utils/imageCompression.d.ts +152 -0
  157. package/lib/typescript/commonjs/utils/index.d.ts +3 -0
  158. package/lib/typescript/commonjs/validators/index.d.ts +51 -0
  159. package/lib/typescript/commonjs/versionCheck/index.d.ts +80 -0
  160. package/lib/typescript/module/api/baseUrl.d.ts +20 -0
  161. package/lib/typescript/module/api/curl.d.ts +18 -0
  162. package/lib/typescript/module/api/publicClient.d.ts +11 -0
  163. package/lib/typescript/module/api/retry.d.ts +27 -0
  164. package/lib/typescript/module/api/tokenRefresh.d.ts +43 -0
  165. package/lib/typescript/module/api/userClient.d.ts +37 -0
  166. package/lib/typescript/module/auth/authStore.d.ts +79 -0
  167. package/lib/typescript/module/auth/index.d.ts +5 -0
  168. package/lib/typescript/module/auth/jwt.d.ts +31 -0
  169. package/lib/typescript/module/config/index.d.ts +55 -0
  170. package/lib/typescript/module/deepLink/index.d.ts +54 -0
  171. package/lib/typescript/module/download/adapters/expoFs.d.ts +38 -0
  172. package/lib/typescript/module/download/adapters/shared.d.ts +3 -0
  173. package/lib/typescript/module/download/index.d.ts +86 -0
  174. package/lib/typescript/module/formatters/currency.d.ts +24 -0
  175. package/lib/typescript/module/formatters/date.d.ts +22 -0
  176. package/lib/typescript/module/formatters/dateMath.d.ts +88 -0
  177. package/lib/typescript/module/formatters/index.d.ts +10 -0
  178. package/lib/typescript/module/formatters/initials.d.ts +11 -0
  179. package/lib/typescript/module/formatters/number.d.ts +15 -0
  180. package/lib/typescript/module/formatters/phone.d.ts +133 -0
  181. package/lib/typescript/module/formatters/windowsToIanaTable.d.ts +18 -0
  182. package/lib/typescript/module/geolocation/adapters/expoLocation.d.ts +42 -0
  183. package/lib/typescript/module/geolocation/index.d.ts +90 -0
  184. package/lib/typescript/module/index.d.ts +54 -0
  185. package/lib/typescript/module/initSDK.d.ts +72 -0
  186. package/lib/typescript/module/initUserAuth.d.ts +41 -0
  187. package/lib/typescript/module/logger/index.d.ts +81 -0
  188. package/lib/typescript/module/network/index.d.ts +3 -0
  189. package/lib/typescript/module/network/networkStatus.d.ts +43 -0
  190. package/lib/typescript/module/package.json +1 -0
  191. package/lib/typescript/module/permissions/calendar.d.ts +2 -0
  192. package/lib/typescript/module/permissions/camera.d.ts +2 -0
  193. package/lib/typescript/module/permissions/contacts.d.ts +2 -0
  194. package/lib/typescript/module/permissions/index.d.ts +48 -0
  195. package/lib/typescript/module/permissions/location.d.ts +2 -0
  196. package/lib/typescript/module/permissions/mediaLibrary.d.ts +2 -0
  197. package/lib/typescript/module/permissions/notifications.d.ts +2 -0
  198. package/lib/typescript/module/permissions/photos.d.ts +2 -0
  199. package/lib/typescript/module/phone/countries.d.ts +13 -0
  200. package/lib/typescript/module/share/index.d.ts +29 -0
  201. package/lib/typescript/module/smsRetriever/index.d.ts +30 -0
  202. package/lib/typescript/module/specs/NativeSmsRetriever.d.ts +15 -0
  203. package/lib/typescript/module/sqlite/adapters/expo.d.ts +30 -0
  204. package/lib/typescript/module/sqlite/index.d.ts +113 -0
  205. package/lib/typescript/module/storage/index.d.ts +64 -0
  206. package/lib/typescript/module/utils/imageCompression.d.ts +152 -0
  207. package/lib/typescript/module/utils/index.d.ts +3 -0
  208. package/lib/typescript/module/validators/index.d.ts +51 -0
  209. package/lib/typescript/module/versionCheck/index.d.ts +80 -0
  210. package/package.json +298 -0
  211. package/src/specs/NativeSmsRetriever.ts +16 -0
@@ -0,0 +1,214 @@
1
+ "use strict";
2
+
3
+ Object.defineProperty(exports, "__esModule", {
4
+ value: true
5
+ });
6
+ exports.setStorageImplementation = exports.isStorageAvailable = exports.Storage = void 0;
7
+ var _kvStore = _interopRequireDefault(require("expo-sqlite/kv-store"));
8
+ var _index = require("../logger/index.js");
9
+ function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; }
10
+ /**
11
+ * Minimal AsyncStorage shape we depend on.
12
+ * Lets us avoid a hard import on `@react-native-async-storage/async-storage`.
13
+ */
14
+
15
+ /** Only what a test or the showcase injected; null means use expo-sqlite/kv-store. */
16
+ let backend = null;
17
+
18
+ /**
19
+ * expo-sqlite's key/value store, imported directly.
20
+ *
21
+ * It deliberately implements the AsyncStorage v1 surface — `getItem`,
22
+ * `setItem`, `removeItem`, `multiGet`, `multiSet`, `multiRemove`, `clear`,
23
+ * `getAllKeys`, with v1's shapes — which is exactly what this module already
24
+ * speaks, so there is nothing to convert. Verified against expo-sqlite 57.0.2.
25
+ */
26
+ const resolveBackend = () => backend ?? _kvStore.default;
27
+
28
+ /**
29
+ * Always true now that the backend ships with the library. Kept because callers
30
+ * whose use of storage is an OPTIMISATION branch on it, and removing it would
31
+ * be a breaking change for no gain.
32
+ */
33
+ const isStorageAvailable = () => resolveBackend() !== null;
34
+ exports.isStorageAvailable = isStorageAvailable;
35
+ const requireBackend = op => {
36
+ const b = resolveBackend();
37
+ if (!b) {
38
+ // Only reachable if a caller injected something falsy; the default backend
39
+ // ships with the library, so there is no "not installed" case any more.
40
+ const err = new Error(`[Storage] no storage backend available; cannot ${op}.`);
41
+ _index.Logger.error(err.message);
42
+ throw err;
43
+ }
44
+ return b;
45
+ };
46
+
47
+ /**
48
+ * Replace the storage backend. Intended for TESTS and for the showcase; an app
49
+ * gets expo-sqlite/kv-store without wiring anything. Pass `null` to restore it.
50
+ */
51
+ const setStorageImplementation = impl => {
52
+ backend = impl;
53
+ };
54
+ exports.setStorageImplementation = setStorageImplementation;
55
+ const safeJsonParse = raw => {
56
+ if (raw == null) {
57
+ return null;
58
+ }
59
+ try {
60
+ return JSON.parse(raw);
61
+ } catch (error) {
62
+ _index.Logger.warn('[Storage] Failed to parse JSON value, returning null', error);
63
+ return null;
64
+ }
65
+ };
66
+ const getItem = async key => {
67
+ try {
68
+ return await requireBackend('getItem').getItem(key);
69
+ } catch (error) {
70
+ _index.Logger.error(`[Storage] getItem failed for key "${key}"`, error);
71
+ return null;
72
+ }
73
+ };
74
+ const setItem = async (key, value) => {
75
+ try {
76
+ await requireBackend('setItem').setItem(key, value);
77
+ return true;
78
+ } catch (error) {
79
+ _index.Logger.error(`[Storage] setItem failed for key "${key}"`, error);
80
+ return false;
81
+ }
82
+ };
83
+ const removeItem = async key => {
84
+ try {
85
+ await requireBackend('removeItem').removeItem(key);
86
+ return true;
87
+ } catch (error) {
88
+ _index.Logger.error(`[Storage] removeItem failed for key "${key}"`, error);
89
+ return false;
90
+ }
91
+ };
92
+ const getJson = async key => {
93
+ const raw = await getItem(key);
94
+ return safeJsonParse(raw);
95
+ };
96
+ const setJson = async (key, value) => {
97
+ try {
98
+ return await setItem(key, JSON.stringify(value));
99
+ } catch (error) {
100
+ _index.Logger.error(`[Storage] setJson failed for key "${key}"`, error);
101
+ return false;
102
+ }
103
+ };
104
+ const multiGet = async keys => {
105
+ try {
106
+ const b = requireBackend('multiGet');
107
+ // v3 first: its Record is already this function's return shape.
108
+ if (b.getMany) {
109
+ return await b.getMany([...keys]);
110
+ }
111
+ if (!b.multiGet) {
112
+ const out = {};
113
+ await Promise.all(keys.map(async k => {
114
+ out[k] = await b.getItem(k);
115
+ }));
116
+ return out;
117
+ }
118
+ const pairs = await b.multiGet(keys);
119
+ const out = {};
120
+ for (const [k, v] of pairs) {
121
+ out[k] = v;
122
+ }
123
+ return out;
124
+ } catch (error) {
125
+ _index.Logger.error('[Storage] multiGet failed', error);
126
+ return {};
127
+ }
128
+ };
129
+ const multiSet = async entries => {
130
+ try {
131
+ const b = requireBackend('multiSet');
132
+ // v3 first: it takes the Record this function already receives.
133
+ if (b.setMany) {
134
+ await b.setMany(entries);
135
+ return true;
136
+ }
137
+ const pairs = Object.entries(entries);
138
+ if (!b.multiSet) {
139
+ await Promise.all(pairs.map(([k, v]) => b.setItem(k, v)));
140
+ return true;
141
+ }
142
+ await b.multiSet(pairs);
143
+ return true;
144
+ } catch (error) {
145
+ _index.Logger.error('[Storage] multiSet failed', error);
146
+ return false;
147
+ }
148
+ };
149
+ const multiRemove = async keys => {
150
+ try {
151
+ const b = requireBackend('multiRemove');
152
+ if (b.removeMany) {
153
+ await b.removeMany([...keys]);
154
+ return true;
155
+ }
156
+ if (!b.multiRemove) {
157
+ await Promise.all(keys.map(k => b.removeItem(k)));
158
+ return true;
159
+ }
160
+ await b.multiRemove(keys);
161
+ return true;
162
+ } catch (error) {
163
+ _index.Logger.error('[Storage] multiRemove failed', error);
164
+ return false;
165
+ }
166
+ };
167
+ const clear = async () => {
168
+ try {
169
+ const b = requireBackend('clear');
170
+ if (!b.clear) {
171
+ _index.Logger.warn('[Storage] backend does not support clear()');
172
+ return false;
173
+ }
174
+ await b.clear();
175
+ return true;
176
+ } catch (error) {
177
+ _index.Logger.error('[Storage] clear failed', error);
178
+ return false;
179
+ }
180
+ };
181
+ const getAllKeys = async () => {
182
+ try {
183
+ const b = requireBackend('getAllKeys');
184
+ if (!b.getAllKeys) {
185
+ return [];
186
+ }
187
+ const keys = await b.getAllKeys();
188
+ return [...keys];
189
+ } catch (error) {
190
+ _index.Logger.error('[Storage] getAllKeys failed', error);
191
+ return [];
192
+ }
193
+ };
194
+ /**
195
+ * Typed AsyncStorage wrapper with safe JSON helpers.
196
+ * All operations swallow errors (logging them) and return a falsy result
197
+ * so that storage problems never crash the app.
198
+ *
199
+ * Backed by `expo-sqlite/kv-store` by default;
200
+ * override with `setStorageImplementation()` for MMKV or custom adapters.
201
+ */
202
+ const Storage = exports.Storage = {
203
+ getItem,
204
+ setItem,
205
+ removeItem,
206
+ getJson,
207
+ setJson,
208
+ multiGet,
209
+ multiSet,
210
+ multiRemove,
211
+ clear,
212
+ getAllKeys
213
+ };
214
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1,6 @@
1
+ "use strict";
2
+
3
+ Object.defineProperty(exports, "__esModule", {
4
+ value: true
5
+ });
6
+ //# sourceMappingURL=globals.d.js.map
@@ -0,0 +1,389 @@
1
+ "use strict";
2
+
3
+ Object.defineProperty(exports, "__esModule", {
4
+ value: true
5
+ });
6
+ exports.setImageCompressorImplementation = exports.qualityForFileSize = exports.compressImage = exports.ImageUnreadableError = void 0;
7
+ var _expoFileSystem = require("expo-file-system");
8
+ var _expoImageManipulator = require("expo-image-manipulator");
9
+ var _index = require("../logger/index.js");
10
+ /**
11
+ * Image compression for uploads: the whole shell an app needs around a
12
+ * picked photo, so an app calls this once and uploads what comes back.
13
+ *
14
+ * What it does, in order:
15
+ *
16
+ * 1. Measures the source. A missing or EMPTY file throws `ImageUnreadableError`
17
+ * so the user is asked to retake: the OS evicts a camera temp file between
18
+ * capture and a delayed save, and uploading the empty result is a certain
19
+ * server rejection that can wedge an outbox.
20
+ * 2. Decodes the photo ONCE and reads its size. The longer side is brought
21
+ * down to `maxSize` (1500 by default, the fleet standard); a photo already
22
+ * within it is never enlarged.
23
+ * 3. Re-encodes at a quality picked from the source's real byte size (bigger
24
+ * files are compressed harder), or at the `quality` given. The re-encode
25
+ * drops EXIF as a side effect; location and time travel as payload fields,
26
+ * never add a second stripping step.
27
+ * 4. With `maxBytes`, keeps re-encoding at a lower quality, then a smaller
28
+ * size, until the output fits, deleting each superseded file.
29
+ * 5. Measures the output the same way as the source and returns everything
30
+ * an upload needs: uri, pixel size, byte size, mime type, extension, file
31
+ * name and a ready `FormData` part.
32
+ *
33
+ * Only an ENCODER failure falls back to the original file, reported through
34
+ * `compressed: false` with the original's own type and size; the reference
35
+ * apps upload the original rather than lose the photo. An unreadable file is
36
+ * never a fallback, it throws.
37
+ *
38
+ * Backed by `expo-image-manipulator` and `expo-file-system`; an app wires
39
+ * nothing. Tests and the showcase inject a backend through
40
+ * `setImageCompressorImplementation`.
41
+ */
42
+
43
+ /** The source was missing or empty, or the encoder produced an empty file. */
44
+ class ImageUnreadableError extends Error {
45
+ constructor(uri, reason) {
46
+ super(`Image is unreadable (${reason}): ${uri || '<empty uri>'}`);
47
+ this.name = 'ImageUnreadableError';
48
+ this.uri = uri;
49
+ }
50
+ }
51
+
52
+ /** A decoded image, held in memory until `close`. */
53
+
54
+ /**
55
+ * What the algorithm needs from a backend. The default is built on
56
+ * expo-image-manipulator and expo-file-system.
57
+ */
58
+ exports.ImageUnreadableError = ImageUnreadableError;
59
+ const release = object => {
60
+ try {
61
+ object?.release?.();
62
+ } catch {
63
+ // A shared object released twice throws; nothing to do.
64
+ }
65
+ };
66
+
67
+ /**
68
+ * expo-image-manipulator's contextual API plus expo-file-system's File
69
+ * class. `manipulate` accepts the decoded ImageRef as well as a URI (checked
70
+ * in the Android and iOS module sources for SDK 57), which is what makes the
71
+ * single decode possible: every encode, including each step of the byte
72
+ * ceiling ladder, resizes the in-memory image rather than re-reading and
73
+ * re-decoding the file.
74
+ */
75
+ const expoBackend = {
76
+ stat: async uri => {
77
+ const file = new _expoFileSystem.File(uri);
78
+ if (!file.exists) {
79
+ return {
80
+ exists: false,
81
+ size: 0
82
+ };
83
+ }
84
+ // Both native modules hand back null when the size attribute cannot be
85
+ // read (a provider-backed URI). That is UNKNOWN, never empty: reading it
86
+ // as 0 would send a user to retake a perfectly good photo.
87
+ return file.size == null ? null : {
88
+ exists: true,
89
+ size: file.size
90
+ };
91
+ },
92
+ remove: async uri => {
93
+ new _expoFileSystem.File(uri).delete();
94
+ },
95
+ open: async uri => {
96
+ const source = _expoImageManipulator.ImageManipulator.manipulate(uri);
97
+ let image;
98
+ try {
99
+ image = await source.renderAsync();
100
+ } finally {
101
+ release(source);
102
+ }
103
+ return {
104
+ width: image.width,
105
+ height: image.height,
106
+ encode: async ({
107
+ width,
108
+ height,
109
+ quality,
110
+ format
111
+ }) => {
112
+ const context = _expoImageManipulator.ImageManipulator.manipulate(image);
113
+ let rendered = null;
114
+ try {
115
+ if (width !== undefined || height !== undefined) {
116
+ context.resize({
117
+ width: width ?? null,
118
+ height: height ?? null
119
+ });
120
+ }
121
+ rendered = await context.renderAsync();
122
+ const saved = await rendered.saveAsync({
123
+ compress: quality,
124
+ // expo's SaveFormat enum spells the same three strings.
125
+ format: format
126
+ });
127
+ return {
128
+ uri: saved.uri,
129
+ width: saved.width,
130
+ height: saved.height
131
+ };
132
+ } finally {
133
+ release(rendered);
134
+ release(context);
135
+ }
136
+ },
137
+ close: () => release(image)
138
+ };
139
+ }
140
+ };
141
+
142
+ /** Only what a test or the showcase injected; null means the expo backend. */
143
+ let backend = null;
144
+
145
+ /**
146
+ * Replace the backend. Intended for TESTS and for the showcase; an app gets
147
+ * the expo modules without wiring anything. Pass `null` to restore them.
148
+ */
149
+ const setImageCompressorImplementation = impl => {
150
+ backend = impl;
151
+ };
152
+ exports.setImageCompressorImplementation = setImageCompressorImplementation;
153
+ const resolveBackend = () => backend ?? expoBackend;
154
+ const EIGHT_MB = 8 * 1024 * 1024;
155
+ const THREE_MB = 3 * 1024 * 1024;
156
+
157
+ /**
158
+ * Bigger source files get compressed harder: a fixed quality either
159
+ * over-compresses small photos or leaves large ones too heavy to upload
160
+ * quickly. Unknown size falls back to the middle rung rather than assuming
161
+ * either extreme. The fleet ladder (`react-native.md`).
162
+ */
163
+ const qualityForFileSize = fileSize => {
164
+ if (fileSize == null) {
165
+ return 0.7;
166
+ }
167
+ if (fileSize > EIGHT_MB) {
168
+ return 0.6;
169
+ }
170
+ if (fileSize > THREE_MB) {
171
+ return 0.7;
172
+ }
173
+ return 0.8;
174
+ };
175
+ exports.qualityForFileSize = qualityForFileSize;
176
+ const DEFAULT_MAX_SIZE = 1500;
177
+ const DEFAULT_MIN_QUALITY = 0.4;
178
+ /** One step of the byte ceiling ladder. */
179
+ const QUALITY_STEP = 0.1;
180
+ /** How much the longer side shrinks per step once quality is at its floor. */
181
+ const SIZE_STEP = 0.75;
182
+ /** The ladder stops shrinking here; below it a document photo is unreadable. */
183
+ const MIN_SIDE = 320;
184
+ const FORMAT = {
185
+ jpg: {
186
+ encode: 'jpeg',
187
+ mimeType: 'image/jpeg'
188
+ },
189
+ png: {
190
+ encode: 'png',
191
+ mimeType: 'image/png'
192
+ },
193
+ webp: {
194
+ encode: 'webp',
195
+ mimeType: 'image/webp'
196
+ }
197
+ };
198
+
199
+ /** The mime type an untouched original is uploaded with, from its extension. */
200
+ const MIME_BY_EXTENSION = {
201
+ jpg: 'image/jpeg',
202
+ jpeg: 'image/jpeg',
203
+ png: 'image/png',
204
+ webp: 'image/webp',
205
+ gif: 'image/gif',
206
+ heic: 'image/heic',
207
+ heif: 'image/heif',
208
+ bmp: 'image/bmp',
209
+ tif: 'image/tiff',
210
+ tiff: 'image/tiff'
211
+ };
212
+
213
+ /** The last path segment of a URI, without query or fragment. */
214
+ const lastSegment = uri => {
215
+ const path = uri.split(/[?#]/)[0] ?? '';
216
+ return decodeURIComponentSafe(path.slice(path.lastIndexOf('/') + 1));
217
+ };
218
+ const decodeURIComponentSafe = value => {
219
+ try {
220
+ return decodeURIComponent(value);
221
+ } catch {
222
+ return value;
223
+ }
224
+ };
225
+ const extensionOf = fileName => {
226
+ const dot = fileName.lastIndexOf('.');
227
+ return dot > 0 ? fileName.slice(dot + 1).toLowerCase() : '';
228
+ };
229
+ const withoutExtension = fileName => {
230
+ const dot = fileName.lastIndexOf('.');
231
+ return dot > 0 ? fileName.slice(0, dot) : fileName;
232
+ };
233
+ const baseNameFor = (uri, name) => withoutExtension(name?.trim() || lastSegment(uri)) || 'image';
234
+ const round1 = value => Math.round(value * 10) / 10;
235
+
236
+ /** A stat that throws (an unsupported scheme) is UNKNOWN, not missing. */
237
+ const safeStat = async (lib, uri) => {
238
+ try {
239
+ return await lib.stat(uri);
240
+ } catch {
241
+ return null;
242
+ }
243
+ };
244
+ const safeRemove = async (lib, uri) => {
245
+ try {
246
+ await lib.remove(uri);
247
+ } catch {
248
+ // A superseded temp file that will not delete is the cache's problem, not the upload's.
249
+ }
250
+ };
251
+ /**
252
+ * Encode the decoded image with its longer side inside `bound`, then measure
253
+ * the file. Only the longer side is given to the encoder: expo treats a given
254
+ * width AND height as targets and would distort the image.
255
+ */
256
+ const renderWithin = async (lib, image, bound, quality, format) => {
257
+ const longer = Math.max(image.width, image.height);
258
+ const resize = longer > bound ? image.width >= image.height ? {
259
+ width: bound
260
+ } : {
261
+ height: bound
262
+ } : {};
263
+ const encoded = await image.encode({
264
+ ...resize,
265
+ quality,
266
+ format
267
+ });
268
+ const stat = await safeStat(lib, encoded.uri);
269
+ if (stat && (!stat.exists || stat.size === 0)) {
270
+ await safeRemove(lib, encoded.uri);
271
+ throw new ImageUnreadableError(encoded.uri, 'the encoder wrote an empty file');
272
+ }
273
+ return {
274
+ ...encoded,
275
+ size: stat?.size ?? null
276
+ };
277
+ };
278
+ const originalResult = (uri, size, baseName, dimensions) => {
279
+ const extension = extensionOf(lastSegment(uri)) || 'jpg';
280
+ const mimeType = MIME_BY_EXTENSION[extension] ?? 'image/jpeg';
281
+ const fileName = `${baseName}.${extension}`;
282
+ return {
283
+ uri,
284
+ width: dimensions?.width ?? null,
285
+ height: dimensions?.height ?? null,
286
+ size,
287
+ mimeType,
288
+ extension,
289
+ fileName,
290
+ compressed: false,
291
+ quality: null,
292
+ part: {
293
+ uri,
294
+ name: fileName,
295
+ type: mimeType
296
+ }
297
+ };
298
+ };
299
+
300
+ /**
301
+ * Compress an image for upload. See the module comment for the contract.
302
+ *
303
+ * @throws ImageUnreadableError when the source is missing or empty, or the
304
+ * encoder produced an empty file. Any other failure returns the original with
305
+ * `compressed: false`.
306
+ */
307
+ const compressImage = async (uri, options = {}) => {
308
+ if (!uri) {
309
+ throw new ImageUnreadableError(uri, 'no uri');
310
+ }
311
+ const lib = resolveBackend();
312
+ const {
313
+ maxSize = DEFAULT_MAX_SIZE,
314
+ output = 'jpg',
315
+ maxBytes,
316
+ minQuality = DEFAULT_MIN_QUALITY,
317
+ name
318
+ } = options;
319
+ const format = FORMAT[output] ?? FORMAT.jpg;
320
+ const baseName = baseNameFor(uri, name);
321
+ const source = await safeStat(lib, uri);
322
+ if (source && !source.exists) {
323
+ throw new ImageUnreadableError(uri, 'the file does not exist');
324
+ }
325
+ if (source && source.size === 0) {
326
+ throw new ImageUnreadableError(uri, 'the file is empty');
327
+ }
328
+ const sourceSize = source?.size ?? options.fileSize ?? null;
329
+ let image;
330
+ try {
331
+ image = await lib.open(uri);
332
+ } catch (error) {
333
+ _index.Logger.error('[imageCompression] could not decode the image; uploading the original', error);
334
+ return originalResult(uri, sourceSize, baseName, null);
335
+ }
336
+ try {
337
+ let quality = options.quality ?? qualityForFileSize(sourceSize);
338
+ let bound = maxSize;
339
+ let rendered = await renderWithin(lib, image, bound, quality, format.encode);
340
+ if (maxBytes !== undefined) {
341
+ // Quality first, then size: a smaller file at the same pixel size
342
+ // keeps the document legible longer than a shrunken one.
343
+ while (rendered.size !== null && rendered.size > maxBytes) {
344
+ if (output !== 'png' && round1(quality - QUALITY_STEP) >= minQuality) {
345
+ quality = round1(quality - QUALITY_STEP);
346
+ } else {
347
+ const longer = Math.max(rendered.width, rendered.height);
348
+ if (longer <= MIN_SIDE) {
349
+ break;
350
+ }
351
+ bound = Math.max(MIN_SIDE, Math.floor(longer * SIZE_STEP));
352
+ }
353
+ const next = await renderWithin(lib, image, bound, quality, format.encode);
354
+ await safeRemove(lib, rendered.uri);
355
+ rendered = next;
356
+ }
357
+ }
358
+ const fileName = `${baseName}.${output}`;
359
+ return {
360
+ uri: rendered.uri,
361
+ width: rendered.width,
362
+ height: rendered.height,
363
+ size: rendered.size,
364
+ mimeType: format.mimeType,
365
+ extension: output,
366
+ fileName,
367
+ compressed: true,
368
+ quality: output === 'png' ? null : quality,
369
+ part: {
370
+ uri: rendered.uri,
371
+ name: fileName,
372
+ type: format.mimeType
373
+ }
374
+ };
375
+ } catch (error) {
376
+ if (error instanceof ImageUnreadableError) {
377
+ throw error;
378
+ }
379
+ _index.Logger.error('[imageCompression] encoding failed; uploading the original', error);
380
+ return originalResult(uri, sourceSize, baseName, {
381
+ width: image.width,
382
+ height: image.height
383
+ });
384
+ } finally {
385
+ image.close();
386
+ }
387
+ };
388
+ exports.compressImage = compressImage;
389
+ //# sourceMappingURL=imageCompression.js.map
@@ -0,0 +1,19 @@
1
+ "use strict";
2
+
3
+ Object.defineProperty(exports, "__esModule", {
4
+ value: true
5
+ });
6
+ Object.defineProperty(exports, "compressImage", {
7
+ enumerable: true,
8
+ get: function () {
9
+ return _imageCompression.compressImage;
10
+ }
11
+ });
12
+ Object.defineProperty(exports, "setImageCompressorImplementation", {
13
+ enumerable: true,
14
+ get: function () {
15
+ return _imageCompression.setImageCompressorImplementation;
16
+ }
17
+ });
18
+ var _imageCompression = require("./imageCompression.js");
19
+ //# sourceMappingURL=index.js.map