@webority/mobile-core 0.0.25 → 0.0.27

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 (58) hide show
  1. package/LICENSE.txt +9 -0
  2. package/README.md +13 -0
  3. package/lib/commonjs/api/publicClient.js +4 -0
  4. package/lib/commonjs/api/retry.js +17 -1
  5. package/lib/commonjs/api/userClient.js +11 -3
  6. package/lib/commonjs/auth/authStore.js +49 -16
  7. package/lib/commonjs/config/index.js +8 -2
  8. package/lib/commonjs/formatters/currency.js +2 -1
  9. package/lib/commonjs/formatters/date.js +5 -6
  10. package/lib/commonjs/formatters/dateMath.js +2 -1
  11. package/lib/commonjs/formatters/intlCache.js +37 -0
  12. package/lib/commonjs/formatters/number.js +4 -3
  13. package/lib/commonjs/index.js +14 -0
  14. package/lib/commonjs/initSDK.js +1 -1
  15. package/lib/commonjs/logger/index.js +16 -6
  16. package/lib/commonjs/logger/redact.js +50 -0
  17. package/lib/commonjs/network/networkStatus.js +40 -2
  18. package/lib/commonjs/types/axios.js +4 -0
  19. package/lib/commonjs/utils/base64.js +24 -0
  20. package/lib/module/api/publicClient.js +4 -0
  21. package/lib/module/api/retry.js +17 -1
  22. package/lib/module/api/userClient.js +12 -4
  23. package/lib/module/auth/authStore.js +49 -16
  24. package/lib/module/config/index.js +7 -1
  25. package/lib/module/formatters/currency.js +2 -1
  26. package/lib/module/formatters/date.js +5 -6
  27. package/lib/module/formatters/dateMath.js +2 -1
  28. package/lib/module/formatters/intlCache.js +30 -0
  29. package/lib/module/formatters/number.js +4 -3
  30. package/lib/module/index.js +3 -0
  31. package/lib/module/initSDK.js +2 -2
  32. package/lib/module/logger/index.js +16 -6
  33. package/lib/module/logger/redact.js +44 -0
  34. package/lib/module/network/networkStatus.js +37 -0
  35. package/lib/module/types/axios.js +4 -0
  36. package/lib/module/utils/base64.js +19 -0
  37. package/lib/typescript/commonjs/api/publicClient.d.ts +1 -0
  38. package/lib/typescript/commonjs/api/userClient.d.ts +1 -0
  39. package/lib/typescript/commonjs/config/index.d.ts +6 -0
  40. package/lib/typescript/commonjs/formatters/intlCache.d.ts +6 -0
  41. package/lib/typescript/commonjs/index.d.ts +2 -0
  42. package/lib/typescript/commonjs/initSDK.d.ts +1 -1
  43. package/lib/typescript/commonjs/logger/redact.d.ts +4 -0
  44. package/lib/typescript/commonjs/network/networkStatus.d.ts +6 -0
  45. package/lib/typescript/commonjs/types/axios.d.ts +8 -0
  46. package/lib/typescript/commonjs/utils/base64.d.ts +7 -0
  47. package/lib/typescript/module/api/publicClient.d.ts +1 -0
  48. package/lib/typescript/module/api/userClient.d.ts +1 -0
  49. package/lib/typescript/module/config/index.d.ts +6 -0
  50. package/lib/typescript/module/formatters/intlCache.d.ts +6 -0
  51. package/lib/typescript/module/index.d.ts +2 -0
  52. package/lib/typescript/module/initSDK.d.ts +1 -1
  53. package/lib/typescript/module/logger/redact.d.ts +4 -0
  54. package/lib/typescript/module/network/networkStatus.d.ts +6 -0
  55. package/lib/typescript/module/types/axios.d.ts +8 -0
  56. package/lib/typescript/module/utils/base64.d.ts +7 -0
  57. package/package.json +2 -2
  58. package/LICENSE +0 -21
@@ -0,0 +1,24 @@
1
+ "use strict";
2
+
3
+ Object.defineProperty(exports, "__esModule", {
4
+ value: true
5
+ });
6
+ exports.encodeBase64 = void 0;
7
+ // Small enough for every engine's argument limit in `String.fromCharCode.apply`.
8
+ const CHUNK = 0x2000;
9
+
10
+ /**
11
+ * Base64 of raw bytes, for a `data:` URI. Builds a Latin-1 string a chunk at a
12
+ * time and hands it to the engine's native `btoa` (Hermes ships it), which is
13
+ * many times faster on the JS thread than encoding byte by byte in JS.
14
+ */
15
+ const encodeBase64 = buffer => {
16
+ const bytes = new Uint8Array(buffer);
17
+ let binary = '';
18
+ for (let i = 0; i < bytes.length; i += CHUNK) {
19
+ binary += String.fromCharCode.apply(null, bytes.subarray(i, i + CHUNK));
20
+ }
21
+ return btoa(binary);
22
+ };
23
+ exports.encodeBase64 = encodeBase64;
24
+ //# sourceMappingURL=base64.js.map
@@ -3,6 +3,7 @@
3
3
  import axios from 'axios';
4
4
  import { getConfigValue } from "../config/index.js";
5
5
  import { Logger } from "../logger/index.js";
6
+ import "../types/axios.js";
6
7
  import { applyConfiguredBaseUrl } from "./baseUrl.js";
7
8
  import { logCurl } from "./curl.js";
8
9
  import { sendFormDataAsMultipart } from "./multipart.js";
@@ -54,6 +55,9 @@ publicClient.interceptors.response.use(response => {
54
55
  }, error => {
55
56
  if (axios.isAxiosError(error)) {
56
57
  const originalRequest = error.config;
58
+ if (originalRequest?.skipErrorLog) {
59
+ return Promise.reject(error);
60
+ }
57
61
  if (!error.response) {
58
62
  Logger.error(`Network error or no response from server: ${error.message}, URL: ${originalRequest?.url}`);
59
63
  } else {
@@ -11,10 +11,26 @@
11
11
  * as readily as GETs.
12
12
  */
13
13
  export const isRetryableStatus = status => typeof status === 'number' && (status === 429 || status >= 500 && status <= 599);
14
+ const IDEMPOTENT_METHODS = new Set(['get', 'head', 'options', 'put', 'delete']);
15
+
16
+ /**
17
+ * The same reasoning reaches status codes on a write. A 500 on a POST or PATCH
18
+ * can follow a partial commit, so replaying it can duplicate the record; only
19
+ * 429 and 503 say the server refused the request before doing the work. A
20
+ * request that knows its write is safe to repeat passes its own `shouldRetry`.
21
+ */
22
+ const isRetryableFailure = error => {
23
+ const status = error.response?.status;
24
+ if (!isRetryableStatus(status)) {
25
+ return false;
26
+ }
27
+ const method = (error.config?.method ?? 'get').toLowerCase();
28
+ return IDEMPOTENT_METHODS.has(method) || status === 429 || status === 503;
29
+ };
14
30
  const DEFAULT_POLICY = {
15
31
  retries: 3,
16
32
  retryDelayMs: attempt => attempt <= 1 ? 0 : 2 ** attempt * 1000,
17
- shouldRetry: error => isRetryableStatus(error.response?.status),
33
+ shouldRetry: isRetryableFailure,
18
34
  onRetry: () => undefined
19
35
  };
20
36
  const waitOrAbort = (delay, signal) => new Promise(resolve => {
@@ -4,7 +4,8 @@ import axios, { AxiosHeaders } from 'axios';
4
4
  import { ACCESS_TOKEN_KEY, getToken } from "../auth/authStore.js";
5
5
  import { getConfigValue } from "../config/index.js";
6
6
  import { Logger } from "../logger/index.js";
7
- import { getNetworkStatus } from "../network/networkStatus.js";
7
+ import { getLastKnownNetworkStatus } from "../network/networkStatus.js";
8
+ import "../types/axios.js";
8
9
  import { applyConfiguredBaseUrl } from "./baseUrl.js";
9
10
  import { logCurl } from "./curl.js";
10
11
  import { sendFormDataAsMultipart } from "./multipart.js";
@@ -25,6 +26,9 @@ export class RequestOfflineError extends Error {
25
26
  constructor(message = 'Request blocked: device is offline') {
26
27
  super(message);
27
28
  this.name = 'RequestOfflineError';
29
+ // Babel's class transform can drop the prototype link, which makes
30
+ // `instanceof RequestOfflineError` false in the transpiled build.
31
+ Object.setPrototypeOf(this, RequestOfflineError.prototype);
28
32
  }
29
33
  }
30
34
 
@@ -131,7 +135,7 @@ userClient.interceptors.request.use(async config => {
131
135
  // Reject before any network call when the device is known to be offline.
132
136
  // Unknown connectivity (netinfo not installed, or undetermined) is treated
133
137
  // as online — never block a request on an unavailable probe.
134
- const network = await getNetworkStatus();
138
+ const network = await getLastKnownNetworkStatus();
135
139
  if (network.isConnected === false) {
136
140
  Logger.warn(`Request blocked: device is offline. URL: ${config.url}`);
137
141
  return Promise.reject(new RequestOfflineError());
@@ -186,7 +190,9 @@ userClient.interceptors.response.use(response => response, async error => {
186
190
  const axiosError = error;
187
191
  const originalRequest = axiosError.config;
188
192
  if (!axiosError.response) {
189
- Logger.error(`Network error or no response from server: ${axiosError.message}, URL: ${originalRequest?.url}`);
193
+ if (!originalRequest?.skipErrorLog) {
194
+ Logger.error(`Network error or no response from server: ${axiosError.message}, URL: ${originalRequest?.url}`);
195
+ }
190
196
  return Promise.reject(error);
191
197
  }
192
198
  if (axiosError.response.status === 401 && originalRequest && !originalRequest._retry) {
@@ -228,7 +234,9 @@ userClient.interceptors.response.use(response => response, async error => {
228
234
  return Promise.reject(err);
229
235
  }
230
236
  }
231
- Logger.error(`Response error: ${axiosError.response?.data ?? axiosError.message}, URL: ${originalRequest?.url}, Status: ${axiosError.response.status}`);
237
+ if (!originalRequest?.skipErrorLog) {
238
+ Logger.error(`Response error: ${axiosError.response?.data ?? axiosError.message}, URL: ${originalRequest?.url}, Status: ${axiosError.response.status}`);
239
+ }
232
240
  return Promise.reject(error);
233
241
  });
234
242
  export default userClient;
@@ -83,6 +83,24 @@ const expoSecureStoreBackend = {
83
83
  }
84
84
  };
85
85
  const resolveBackend = () => backend ?? expoSecureStoreBackend;
86
+
87
+ /**
88
+ * Every request reads the access token, and a secure-store read is a native
89
+ * keychain/keystore decrypt. Reads are therefore served from memory, written
90
+ * through by `storeToken` and dropped by `removeToken`. `generation` moves on
91
+ * every write, removal and backend swap, so a read that started before one of
92
+ * those cannot cache the value it saw.
93
+ */
94
+ const memo = new Map();
95
+ let generation = 0;
96
+ const forget = key => {
97
+ generation += 1;
98
+ if (key === undefined) {
99
+ memo.clear();
100
+ } else {
101
+ memo.delete(key);
102
+ }
103
+ };
86
104
  const requireBackend = op => {
87
105
  const b = resolveBackend();
88
106
  if (!b) {
@@ -100,6 +118,7 @@ const requireBackend = op => {
100
118
  */
101
119
  export const setKeychainImplementation = impl => {
102
120
  backend = impl;
121
+ forget();
103
122
  };
104
123
 
105
124
  /**
@@ -109,6 +128,7 @@ export const storeToken = async (key, token, expiry) => {
109
128
  // Never log the token or expiry values: Logger forwards to whatever remote
110
129
  // sink the app wired (Crashlytics/Sentry), so a token here leaves the device.
111
130
  Logger.info(`Storing token for key: ${key}`);
131
+ forget(key);
112
132
  try {
113
133
  const data = JSON.stringify({
114
134
  token,
@@ -117,8 +137,14 @@ export const storeToken = async (key, token, expiry) => {
117
137
  await requireBackend('store a token').setGenericPassword('token', data, {
118
138
  service: key
119
139
  });
140
+ forget(key);
141
+ memo.set(key, {
142
+ token,
143
+ expiry
144
+ });
120
145
  Logger.info(`Token stored successfully for key: ${key}`);
121
146
  } catch (error) {
147
+ forget(key);
122
148
  // Log AND rethrow. Swallowing this told the caller the token was persisted
123
149
  // when it was not, so an app would show a signed-in user holding a token
124
150
  // that never reached the keychain — the session then dies at the next
@@ -156,6 +182,10 @@ const parseTokenData = credentials => {
156
182
  * Retrieve token and check if expired.
157
183
  */
158
184
  export const getToken = async key => {
185
+ if (memo.has(key)) {
186
+ return memo.get(key) ?? null;
187
+ }
188
+ const seen = generation;
159
189
  try {
160
190
  const credentials = await requireBackend('read a token').getGenericPassword({
161
191
  service: key
@@ -164,24 +194,24 @@ export const getToken = async key => {
164
194
  // token, and every authenticated request, image and download asks for one.
165
195
  // Warning here put three info lines and a warning into the log, and into the
166
196
  // remote crash sink, on every one of those calls.
167
- if (!credentials) {
168
- return null;
197
+ let value = null;
198
+ if (credentials) {
199
+ const parsedData = parseTokenData(credentials);
200
+ if (parsedData) {
201
+ value = {
202
+ token: parsedData.token,
203
+ expiry: parsedData.expiry
204
+ };
205
+ } else {
206
+ // Something IS stored and it is not a token. That is corruption worth
207
+ // hearing about, and it is a different event from having no token.
208
+ Logger.warn(`Stored credentials for key "${key}" are not a valid token; ignoring them.`);
209
+ }
169
210
  }
170
- const parsedData = parseTokenData(credentials);
171
- if (!parsedData) {
172
- // Something IS stored and it is not a token. That is corruption worth
173
- // hearing about, and it is a different event from having no token.
174
- Logger.warn(`Stored credentials for key "${key}" are not a valid token; ignoring them.`);
175
- return null;
211
+ if (seen === generation) {
212
+ memo.set(key, value);
176
213
  }
177
- const {
178
- token,
179
- expiry
180
- } = parsedData;
181
- return {
182
- token,
183
- expiry
184
- };
214
+ return value;
185
215
  } catch (error) {
186
216
  const message = error instanceof Error ? error.message : String(error);
187
217
  // Both spellings matter. Android throws "Key permanently invalidated" when
@@ -204,6 +234,7 @@ export const getToken = async key => {
204
234
  * Remove token by key.
205
235
  */
206
236
  export const removeToken = async key => {
237
+ forget(key);
207
238
  try {
208
239
  await requireBackend('remove a token').resetGenericPassword({
209
240
  service: key
@@ -219,6 +250,8 @@ export const removeToken = async key => {
219
250
  return;
220
251
  }
221
252
  Logger.error(`Failed to remove token for key: ${key}`, error);
253
+ } finally {
254
+ forget(key);
222
255
  }
223
256
  };
224
257
  //# sourceMappingURL=authStore.js.map
@@ -5,10 +5,16 @@
5
5
  * Provides a flexible way to inject configuration without hard dependencies
6
6
  */
7
7
 
8
+ /**
9
+ * Info lines (each token refresh, each unauthorised URL) reach the device log
10
+ * and any remote sink, so a release build that sets nothing logs warnings and
11
+ * errors only.
12
+ */
13
+ export const DEFAULT_LOG_LEVEL = __DEV__ ? 'info' : 'warn';
8
14
  const DEFAULT_CONFIG = {
9
15
  baseUrl: null,
10
16
  loggingEnabled: true,
11
- logLevel: 'info',
17
+ logLevel: DEFAULT_LOG_LEVEL,
12
18
  environment: 'Development',
13
19
  country: 'in',
14
20
  appId: null,
@@ -1,5 +1,6 @@
1
1
  "use strict";
2
2
 
3
+ import { numberFormat } from "./intlCache.js";
3
4
  const hasIntlNumber = () => typeof Intl !== 'undefined' && typeof Intl.NumberFormat === 'function';
4
5
  const indianGroupingFallback = (n, fractionDigits) => {
5
6
  // Indian numbering: 1,23,45,678.90 (last 3 digits, then groups of 2).
@@ -37,7 +38,7 @@ export const formatCurrency = (amount, options = {}) => {
37
38
  const minFrac = minimumFractionDigits ?? (Number.isInteger(amount) ? 0 : 2);
38
39
  if (hasIntlNumber()) {
39
40
  try {
40
- const formatted = new Intl.NumberFormat(locale, {
41
+ const formatted = numberFormat(locale, {
41
42
  style: 'currency',
42
43
  currency,
43
44
  minimumFractionDigits: minFrac,
@@ -1,5 +1,6 @@
1
1
  "use strict";
2
2
 
3
+ import { dateTimeFormat, relativeTimeFormat } from "./intlCache.js";
3
4
  const toDate = value => {
4
5
  if (value instanceof Date) {
5
6
  return Number.isNaN(value.getTime()) ? null : value;
@@ -48,7 +49,7 @@ export const formatDate = (value, style = 'medium', locale = 'en-IN') => {
48
49
  }
49
50
  if (hasIntl()) {
50
51
  try {
51
- return new Intl.DateTimeFormat(locale, {
52
+ return dateTimeFormat(locale, {
52
53
  dateStyle: style
53
54
  }).format(d);
54
55
  } catch {
@@ -68,7 +69,7 @@ export const formatTime = (value, style = 'short', locale = 'en-IN') => {
68
69
  }
69
70
  if (hasIntl()) {
70
71
  try {
71
- return new Intl.DateTimeFormat(locale, {
72
+ return dateTimeFormat(locale, {
72
73
  timeStyle: style
73
74
  }).format(d);
74
75
  } catch {
@@ -88,7 +89,7 @@ export const formatDateTime = (value, dateStyle = 'medium', timeStyle = 'short',
88
89
  }
89
90
  if (hasIntl()) {
90
91
  try {
91
- return new Intl.DateTimeFormat(locale, {
92
+ return dateTimeFormat(locale, {
92
93
  dateStyle,
93
94
  timeStyle
94
95
  }).format(d);
@@ -145,9 +146,7 @@ export const formatRelativeTime = (value, base = new Date(), locale = 'en-IN') =
145
146
  const Rtf = hasIntl() ? Intl.RelativeTimeFormat : undefined;
146
147
  if (typeof Rtf === 'function') {
147
148
  try {
148
- return new Rtf(locale, {
149
- numeric: 'auto'
150
- }).format(amount, unit);
149
+ return relativeTimeFormat(Rtf, locale).format(amount, unit);
151
150
  } catch {
152
151
  /* fall through */
153
152
  }
@@ -1,5 +1,6 @@
1
1
  "use strict";
2
2
 
3
+ import { dateTimeFormat } from "./intlCache.js";
3
4
  import { WINDOWS_TO_IANA } from "./windowsToIanaTable.js";
4
5
  const toDate = value => {
5
6
  if (value instanceof Date) {
@@ -263,7 +264,7 @@ export const formatTimeInZone = (value, ianaTimeZone) => {
263
264
  // answer available, not a genuine timezone conversion.
264
265
  return formatTime12h(d);
265
266
  }
266
- const parts = new Intl.DateTimeFormat('en-US', {
267
+ const parts = dateTimeFormat('en-US', {
267
268
  timeZone: ianaTimeZone,
268
269
  hour: 'numeric',
269
270
  minute: '2-digit',
@@ -0,0 +1,30 @@
1
+ "use strict";
2
+
3
+ /**
4
+ * Building an Intl formatter costs far more than using one (and on Hermes for
5
+ * Android it goes through ICU over JNI), while list rows and slider frames call
6
+ * the formatters many times with the same arguments. Formatters are therefore
7
+ * built once per locale and options. The limit only guards against unbounded
8
+ * input such as arbitrary time zones; real apps use a handful of keys.
9
+ */
10
+ const LIMIT = 100;
11
+ const cached = (cache, key, create) => {
12
+ let formatter = cache.get(key);
13
+ if (formatter === undefined) {
14
+ formatter = create();
15
+ if (cache.size >= LIMIT) {
16
+ cache.clear();
17
+ }
18
+ cache.set(key, formatter);
19
+ }
20
+ return formatter;
21
+ };
22
+ const numberFormats = new Map();
23
+ const dateTimeFormats = new Map();
24
+ const relativeTimeFormats = new Map();
25
+ export const numberFormat = (locale, options = {}) => cached(numberFormats, `${locale}|${JSON.stringify(options)}`, () => new Intl.NumberFormat(locale, options));
26
+ export const dateTimeFormat = (locale, options) => cached(dateTimeFormats, `${locale}|${JSON.stringify(options)}`, () => new Intl.DateTimeFormat(locale, options));
27
+ export const relativeTimeFormat = (RelativeTimeFormat, locale) => cached(relativeTimeFormats, locale, () => new RelativeTimeFormat(locale, {
28
+ numeric: 'auto'
29
+ }));
30
+ //# sourceMappingURL=intlCache.js.map
@@ -1,5 +1,6 @@
1
1
  "use strict";
2
2
 
3
+ import { numberFormat } from "./intlCache.js";
3
4
  const hasIntlNumber = () => typeof Intl !== 'undefined' && typeof Intl.NumberFormat === 'function';
4
5
 
5
6
  /**
@@ -16,7 +17,7 @@ export const formatNumber = (value, fractionDigits, locale = 'en-IN') => {
16
17
  opts.minimumFractionDigits = fractionDigits;
17
18
  opts.maximumFractionDigits = fractionDigits;
18
19
  }
19
- return new Intl.NumberFormat(locale, opts).format(value);
20
+ return numberFormat(locale, opts).format(value);
20
21
  } catch {
21
22
  /* fall through */
22
23
  }
@@ -35,7 +36,7 @@ export const formatPercent = (value, fractionDigits = 0, asRatio = true, locale
35
36
  const ratio = asRatio ? value : value / 100;
36
37
  if (hasIntlNumber()) {
37
38
  try {
38
- return new Intl.NumberFormat(locale, {
39
+ return numberFormat(locale, {
39
40
  style: 'percent',
40
41
  minimumFractionDigits: fractionDigits,
41
42
  maximumFractionDigits: fractionDigits
@@ -57,7 +58,7 @@ export const formatCompactNumber = (value, locale = 'en-IN') => {
57
58
  }
58
59
  if (hasIntlNumber()) {
59
60
  try {
60
- return new Intl.NumberFormat(locale, {
61
+ return numberFormat(locale, {
61
62
  notation: 'compact',
62
63
  maximumFractionDigits: 1
63
64
  }).format(value);
@@ -27,6 +27,7 @@
27
27
  export { buildCurl, logCurl } from "./api/curl.js";
28
28
  export { default as publicClient } from "./api/publicClient.js";
29
29
  export { attachRetry, isRetryableStatus } from "./api/retry.js";
30
+ export { refreshAccessToken } from "./api/tokenRefresh.js";
30
31
  export { default as userClient, injectStore, injectUserAuth, RequestOfflineError, resetRefreshState, SESSION_TERMINATION_CODES } from "./api/userClient.js";
31
32
  // Auth / token storage
32
33
  export { ACCESS_TOKEN_KEY, getToken, REFRESH_TOKEN_KEY, removeToken, setKeychainImplementation, storeToken } from "./auth/authStore.js";
@@ -47,6 +48,8 @@ export { addNetworkStatusListener, getNetworkStatus, setNetworkStatusImplementat
47
48
  // Storage: the API and the seam. No native package is required; wire one with
48
49
  // setStorageImplementation to get persistence.
49
50
  export { isStorageAvailable, Storage, setStorageImplementation } from "./storage/index.js";
51
+ // Bytes
52
+ export { encodeBase64 } from "./utils/base64.js";
50
53
  // Validators
51
54
  export { isAadhaar, isAlphanumeric, isBetween, isEmail, isGstin, isHexColor, isIfsc, isIndianMobile, isIndianPincode, isInteger, isNonEmpty, isNumeric, isPan, isPhone, isStrongPassword, isUrl, maxLength, minLength } from "./validators/index.js";
52
55
  // Version check (the ForceUpdateDialog UI lives in @webority/mobile-ui)
@@ -6,7 +6,7 @@
6
6
  */
7
7
 
8
8
  import { setKeychainImplementation } from "./auth/authStore.js";
9
- import { setConfig } from "./config/index.js";
9
+ import { DEFAULT_LOG_LEVEL, setConfig } from "./config/index.js";
10
10
  import { Logger } from "./logger/index.js";
11
11
  import { setNetworkStatusImplementation } from "./network/networkStatus.js";
12
12
  import { setStorageImplementation } from "./storage/index.js";
@@ -35,7 +35,7 @@ export const initWebority = config => {
35
35
  setConfig({
36
36
  baseUrl: config.baseUrl,
37
37
  loggingEnabled: config.loggingEnabled ?? true,
38
- logLevel: config.logLevel || 'info',
38
+ logLevel: config.logLevel || DEFAULT_LOG_LEVEL,
39
39
  environment: config.environment || 'Development',
40
40
  country: (config.country || 'in').toLowerCase(),
41
41
  appId: config.appId ?? null,
@@ -1,6 +1,7 @@
1
1
  "use strict";
2
2
 
3
3
  import { getConfigValue } from "../config/index.js";
4
+ import { redact, redactString } from "./redact.js";
4
5
 
5
6
  // ANSI color codes
6
7
  const Colors = {
@@ -203,21 +204,27 @@ const forwardErrorToRemote = (err, context) => {
203
204
  }
204
205
  safe(() => remote?.recordError?.(err, buildErrorContext(context, suppressedCount)));
205
206
  };
206
- const logInfo = (message, ...optionalParams) => {
207
+ const logInfo = (rawMessage, ...rawParams) => {
208
+ const message = redactString(rawMessage);
209
+ const optionalParams = redact(rawParams);
207
210
  if (!isEnabled() || !isLogLevelAllowed(LogLevels.INFO.level)) {
208
211
  return;
209
212
  }
210
213
  console.info(`${LogLevels.INFO.color}[INFO]: ${message}${Colors.RESET}`, ...optionalParams);
211
214
  safe(() => remote?.log?.('info', message, optionalParams));
212
215
  };
213
- const logWarning = (message, ...optionalParams) => {
216
+ const logWarning = (rawMessage, ...rawParams) => {
217
+ const message = redactString(rawMessage);
218
+ const optionalParams = redact(rawParams);
214
219
  if (!isEnabled() || !isLogLevelAllowed(LogLevels.WARN.level)) {
215
220
  return;
216
221
  }
217
222
  console.warn(`${LogLevels.WARN.color}[WARNING]: ${message}${Colors.RESET}`, ...optionalParams);
218
223
  safe(() => remote?.log?.('warn', message, optionalParams));
219
224
  };
220
- const logError = (message, ...optionalParams) => {
225
+ const logError = (rawMessage, ...rawParams) => {
226
+ const message = redactString(rawMessage);
227
+ const optionalParams = redact(rawParams);
221
228
  if (isEnabled() && isLogLevelAllowed(LogLevels.ERROR.level)) {
222
229
  console.error(`${LogLevels.ERROR.color}[ERROR]: ${message}${Colors.RESET}`, ...optionalParams);
223
230
  }
@@ -233,14 +240,17 @@ const logError = (message, ...optionalParams) => {
233
240
  });
234
241
  }
235
242
  };
236
- const breadcrumb = (message, data) => {
243
+ const breadcrumb = (rawMessage, rawData) => {
244
+ const message = redactString(rawMessage);
245
+ const data = redact(rawData);
237
246
  if (isEnabled() && isLogLevelAllowed('info')) {
238
247
  console.info(`${Colors.BLUE}[BREADCRUMB]: ${message}${Colors.RESET}`, data ?? '');
239
248
  }
240
249
  safe(() => remote?.breadcrumb?.(message, data));
241
250
  };
242
- const recordError = (error, context) => {
243
- const err = toErrorObject(error);
251
+ const recordError = (error, rawContext) => {
252
+ const err = redact(toErrorObject(error));
253
+ const context = redact(rawContext);
244
254
  if (isEnabled() && isLogLevelAllowed('error')) {
245
255
  console.error(`${Colors.RED_BOLD}[RECORDED]: ${err.message}${Colors.RESET}`, context ?? '');
246
256
  }
@@ -0,0 +1,44 @@
1
+ "use strict";
2
+
3
+ const REDACTED = '[REDACTED]';
4
+ const SECRET_KEYS = /^(token|accesstoken|refreshtoken|password|authorization)$/i;
5
+ const BEARER = /\bBearer\s+[A-Za-z0-9._~+/-]+=*/gi;
6
+ const JWT = /\beyJ[A-Za-z0-9_-]*\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]*/g;
7
+ const KEYED_VALUE = /(["']?(?:token|accessToken|refreshToken|password|authorization)["']?\s*[:=]\s*)(?:"(?:[^"\\]|\\.)*"|'[^']*'|[^\s,;&}]+)/gi;
8
+ const MAX_DEPTH = 6;
9
+ export const redactString = input => input.replace(BEARER, `Bearer ${REDACTED}`).replace(JWT, REDACTED).replace(KEYED_VALUE, (_match, prefix) => `${prefix}"${REDACTED}"`);
10
+ const redactInner = (value, depth, seen) => {
11
+ if (typeof value === 'string') {
12
+ return redactString(value);
13
+ }
14
+ if (value === null || typeof value !== 'object') {
15
+ return value;
16
+ }
17
+ if (value instanceof Error) {
18
+ value.message = redactString(value.message);
19
+ if (value.stack) {
20
+ value.stack = redactString(value.stack);
21
+ }
22
+ return value;
23
+ }
24
+ if (depth >= MAX_DEPTH || seen.has(value)) {
25
+ return value;
26
+ }
27
+ seen.add(value);
28
+ if (Array.isArray(value)) {
29
+ return value.map(item => redactInner(item, depth + 1, seen));
30
+ }
31
+ const proto = Object.getPrototypeOf(value);
32
+ if (proto !== Object.prototype && proto !== null) {
33
+ return value;
34
+ }
35
+ const out = {};
36
+ for (const [key, item] of Object.entries(value)) {
37
+ out[key] = SECRET_KEYS.test(key) ? REDACTED : redactInner(item, depth + 1, seen);
38
+ }
39
+ return out;
40
+ };
41
+
42
+ /** Returns a copy with secrets masked; Errors are masked in place so identity and stack survive. */
43
+ export const redact = value => redactInner(value, 0, new WeakSet());
44
+ //# sourceMappingURL=redact.js.map
@@ -18,6 +18,13 @@ const DEFAULT_STATUS = {
18
18
  * One backend also means one behaviour, rather than each app choosing.
19
19
  */
20
20
  let override = null;
21
+ let lastKnown = null;
22
+ let stopFollowing = null;
23
+ const stopFollowingNetwork = () => {
24
+ stopFollowing?.();
25
+ stopFollowing = null;
26
+ lastKnown = null;
27
+ };
21
28
 
22
29
  /**
23
30
  * Replace the backend. Intended for TESTS and for the showcase, which uses it
@@ -26,6 +33,7 @@ let override = null;
26
33
  */
27
34
  export const setNetworkStatusImplementation = impl => {
28
35
  override = impl;
36
+ stopFollowingNetwork();
29
37
  };
30
38
  const resolveNetInfo = () => override ?? expoNetworkBackend;
31
39
 
@@ -96,6 +104,35 @@ export const addNetworkStatusListener = listener => {
96
104
  return ni.addEventListener(state => listener(normalize(state)));
97
105
  };
98
106
 
107
+ /**
108
+ * The connectivity the HTTP client checks before every request. One listener,
109
+ * attached on first use, keeps it current, so a request costs no native probe:
110
+ * one probe seeds the value and the listener's events replace it.
111
+ */
112
+ export const getLastKnownNetworkStatus = async () => {
113
+ if (!stopFollowing) {
114
+ try {
115
+ stopFollowing = addNetworkStatusListener(status => {
116
+ lastKnown = status;
117
+ });
118
+ } catch (error) {
119
+ Logger.error('[network] could not follow network changes', error);
120
+ return getNetworkStatus();
121
+ }
122
+ }
123
+ if (lastKnown) {
124
+ return lastKnown;
125
+ }
126
+ const following = stopFollowing;
127
+ const probed = await getNetworkStatus();
128
+ if (stopFollowing !== following) {
129
+ return probed;
130
+ }
131
+ // An event that arrived during the probe is newer than the probe.
132
+ lastKnown ??= probed;
133
+ return lastKnown;
134
+ };
135
+
99
136
  /**
100
137
  * React hook that returns the current network status and re-renders on change.
101
138
  * Reports an optimistic online default when NetInfo is not installed.
@@ -0,0 +1,4 @@
1
+ "use strict";
2
+
3
+ import 'axios';
4
+ //# sourceMappingURL=axios.js.map
@@ -0,0 +1,19 @@
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,4 +1,5 @@
1
1
  import { type AxiosInstance } from 'axios';
2
+ import '../types/axios';
2
3
  /**
3
4
  * Public Axios Client
4
5
  * - Base URL: Set your public API base URL.
@@ -1,4 +1,5 @@
1
1
  import { type AxiosInstance } from 'axios';
2
+ import '../types/axios';
2
3
  export type { RefreshableStore } from './tokenRefresh';
3
4
  export { injectStore, injectUserAuth, resetRefreshState } from './tokenRefresh';
4
5
  /**
@@ -34,6 +34,12 @@ export interface Config {
34
34
  */
35
35
  logCurl: boolean;
36
36
  }
37
+ /**
38
+ * Info lines (each token refresh, each unauthorised URL) reach the device log
39
+ * and any remote sink, so a release build that sets nothing logs warnings and
40
+ * errors only.
41
+ */
42
+ export declare const DEFAULT_LOG_LEVEL: LogLevel;
37
43
  /**
38
44
  * Set global configuration for all Webority packages
39
45
  */
@@ -0,0 +1,6 @@
1
+ export declare const numberFormat: (locale: string, options?: Intl.NumberFormatOptions) => Intl.NumberFormat;
2
+ export declare const dateTimeFormat: (locale: string, options: Intl.DateTimeFormatOptions) => Intl.DateTimeFormat;
3
+ export declare const relativeTimeFormat: (RelativeTimeFormat: new (locale: string, options?: {
4
+ numeric?: "always" | "auto";
5
+ }) => Intl.RelativeTimeFormat, locale: string) => Intl.RelativeTimeFormat;
6
+ //# sourceMappingURL=intlCache.d.ts.map