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