@webority/mobile-core 0.0.28 → 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.
- package/lib/commonjs/api/baseUrl.js +1 -34
- package/lib/commonjs/api/curl.js +1 -109
- package/lib/commonjs/api/multipart.js +1 -21
- package/lib/commonjs/api/publicClient.js +1 -79
- package/lib/commonjs/api/responseBodyText.js +1 -0
- package/lib/commonjs/api/retry.js +1 -91
- package/lib/commonjs/api/tokenRefresh.js +1 -205
- package/lib/commonjs/api/userClient.js +1 -265
- package/lib/commonjs/auth/authStore.js +1 -265
- package/lib/commonjs/auth/index.js +1 -44
- package/lib/commonjs/auth/jwt.js +1 -112
- package/lib/commonjs/config/index.js +1 -72
- package/lib/commonjs/deepLink/index.js +1 -286
- package/lib/commonjs/download/adapters/expoFs.js +1 -69
- package/lib/commonjs/download/adapters/shared.js +1 -13
- package/lib/commonjs/download/index.js +1 -250
- package/lib/commonjs/formatters/currency.js +1 -70
- package/lib/commonjs/formatters/date.js +1 -167
- package/lib/commonjs/formatters/dateMath.js +1 -311
- package/lib/commonjs/formatters/index.js +1 -246
- package/lib/commonjs/formatters/initials.js +1 -32
- package/lib/commonjs/formatters/intlCache.js +1 -37
- package/lib/commonjs/formatters/number.js +1 -89
- package/lib/commonjs/formatters/phone.js +1 -369
- package/lib/commonjs/formatters/windowsToIanaTable.js +1 -164
- package/lib/commonjs/geolocation/adapters/expoLocation.js +1 -126
- package/lib/commonjs/geolocation/index.js +1 -355
- package/lib/commonjs/index.js +1 -644
- package/lib/commonjs/initSDK.js +1 -66
- package/lib/commonjs/initUserAuth.js +1 -37
- package/lib/commonjs/logger/crashlytics.js +1 -0
- package/lib/commonjs/logger/index.js +1 -301
- package/lib/commonjs/logger/redact.js +1 -50
- package/lib/commonjs/network/index.js +1 -31
- package/lib/commonjs/network/networkStatus.js +1 -171
- package/lib/commonjs/permissions/calendar.js +1 -14
- package/lib/commonjs/permissions/camera.js +1 -14
- package/lib/commonjs/permissions/contacts.js +1 -10
- package/lib/commonjs/permissions/index.js +1 -133
- package/lib/commonjs/permissions/location.js +1 -14
- package/lib/commonjs/permissions/mediaLibrary.js +1 -10
- package/lib/commonjs/permissions/notifications.js +1 -10
- package/lib/commonjs/permissions/photos.js +1 -14
- package/lib/commonjs/phone/countries.js +1 -265
- package/lib/commonjs/push/index.js +1 -61
- package/lib/commonjs/push/push.js +1 -443
- package/lib/commonjs/push/status.js +1 -0
- package/lib/commonjs/push/task.js +1 -43
- package/lib/commonjs/secureScreen/index.js +1 -0
- package/lib/commonjs/share/index.js +1 -70
- package/lib/commonjs/smsRetriever/index.js +1 -91
- package/lib/commonjs/specs/NativeSmsRetriever.js +1 -15
- package/lib/commonjs/sqlite/adapters/expo.js +1 -53
- package/lib/commonjs/sqlite/index.js +1 -604
- package/lib/commonjs/storage/index.js +1 -214
- package/lib/commonjs/types/axios.js +1 -4
- package/lib/commonjs/types/globals.d.js +1 -6
- package/lib/commonjs/utils/base64.js +1 -24
- package/lib/commonjs/utils/imageCompression.js +1 -389
- package/lib/commonjs/utils/index.js +1 -19
- package/lib/commonjs/validators/index.js +1 -227
- package/lib/commonjs/versionCheck/index.js +1 -419
- package/lib/module/api/baseUrl.js +1 -30
- package/lib/module/api/curl.js +1 -104
- package/lib/module/api/multipart.js +1 -16
- package/lib/module/api/publicClient.js +1 -75
- package/lib/module/api/responseBodyText.js +1 -0
- package/lib/module/api/retry.js +1 -85
- package/lib/module/api/tokenRefresh.js +1 -192
- package/lib/module/api/userClient.js +1 -243
- package/lib/module/auth/authStore.js +1 -257
- package/lib/module/auth/index.js +1 -5
- package/lib/module/auth/jwt.js +1 -106
- package/lib/module/config/index.js +1 -64
- package/lib/module/deepLink/index.js +1 -280
- package/lib/module/download/adapters/expoFs.js +1 -64
- package/lib/module/download/adapters/shared.js +1 -8
- package/lib/module/download/index.js +1 -242
- package/lib/module/formatters/currency.js +1 -65
- package/lib/module/formatters/date.js +1 -159
- package/lib/module/formatters/dateMath.js +1 -295
- package/lib/module/formatters/index.js +1 -9
- package/lib/module/formatters/initials.js +1 -27
- package/lib/module/formatters/intlCache.js +1 -30
- package/lib/module/formatters/number.js +1 -82
- package/lib/module/formatters/phone.js +1 -302
- package/lib/module/formatters/windowsToIanaTable.js +1 -160
- package/lib/module/geolocation/adapters/expoLocation.js +1 -121
- package/lib/module/geolocation/index.js +1 -347
- package/lib/module/index.js +1 -57
- package/lib/module/initSDK.js +1 -61
- package/lib/module/initUserAuth.js +1 -33
- package/lib/module/logger/crashlytics.js +1 -0
- package/lib/module/logger/index.js +1 -295
- package/lib/module/logger/redact.js +1 -44
- package/lib/module/network/index.js +1 -4
- package/lib/module/network/networkStatus.js +1 -161
- package/lib/module/permissions/calendar.js +1 -15
- package/lib/module/permissions/camera.js +1 -15
- package/lib/module/permissions/contacts.js +1 -11
- package/lib/module/permissions/index.js +1 -128
- package/lib/module/permissions/location.js +1 -15
- package/lib/module/permissions/mediaLibrary.js +1 -11
- package/lib/module/permissions/notifications.js +1 -11
- package/lib/module/permissions/photos.js +1 -15
- package/lib/module/phone/countries.js +1 -261
- package/lib/module/push/index.js +1 -4
- package/lib/module/push/push.js +1 -427
- package/lib/module/push/status.js +1 -0
- package/lib/module/push/task.js +1 -38
- package/lib/module/secureScreen/index.js +1 -0
- package/lib/module/share/index.js +1 -64
- package/lib/module/smsRetriever/index.js +1 -86
- package/lib/module/specs/NativeSmsRetriever.js +1 -13
- package/lib/module/sqlite/adapters/expo.js +1 -48
- package/lib/module/sqlite/index.js +1 -594
- package/lib/module/storage/index.js +1 -208
- package/lib/module/types/axios.js +1 -4
- package/lib/module/types/globals.d.js +1 -10
- package/lib/module/utils/base64.js +1 -19
- package/lib/module/utils/imageCompression.js +1 -383
- package/lib/module/utils/index.js +1 -4
- package/lib/module/validators/index.js +1 -205
- package/lib/module/versionCheck/index.js +1 -413
- package/lib/typescript/commonjs/api/responseBodyText.d.ts +6 -0
- package/lib/typescript/commonjs/index.d.ts +5 -0
- package/lib/typescript/commonjs/logger/crashlytics.d.ts +31 -0
- package/lib/typescript/commonjs/push/index.d.ts +3 -1
- package/lib/typescript/commonjs/push/push.d.ts +9 -1
- package/lib/typescript/commonjs/push/status.d.ts +9 -0
- package/lib/typescript/commonjs/secureScreen/index.d.ts +25 -0
- package/lib/typescript/module/api/responseBodyText.d.ts +6 -0
- package/lib/typescript/module/index.d.ts +5 -0
- package/lib/typescript/module/logger/crashlytics.d.ts +31 -0
- package/lib/typescript/module/push/index.d.ts +3 -1
- package/lib/typescript/module/push/push.d.ts +9 -1
- package/lib/typescript/module/push/status.d.ts +9 -0
- package/lib/typescript/module/secureScreen/index.d.ts +25 -0
- package/package.json +23 -4
package/lib/commonjs/initSDK.js
CHANGED
|
@@ -1,66 +1 @@
|
|
|
1
|
-
"use strict";
|
|
2
|
-
|
|
3
|
-
Object.defineProperty(exports, "__esModule", {
|
|
4
|
-
value: true
|
|
5
|
-
});
|
|
6
|
-
exports.initWebority = void 0;
|
|
7
|
-
var _authStore = require("./auth/authStore.js");
|
|
8
|
-
var _index = require("./config/index.js");
|
|
9
|
-
var _index2 = require("./logger/index.js");
|
|
10
|
-
var _networkStatus = require("./network/networkStatus.js");
|
|
11
|
-
var _index3 = require("./storage/index.js");
|
|
12
|
-
/**
|
|
13
|
-
* Simple initialization API for Webority packages
|
|
14
|
-
* One function to configure everything needed
|
|
15
|
-
*/
|
|
16
|
-
|
|
17
|
-
/**
|
|
18
|
-
* Initialize Webority packages with your project configuration.
|
|
19
|
-
*
|
|
20
|
-
* @example
|
|
21
|
-
* // Basic setup
|
|
22
|
-
* initWebority({
|
|
23
|
-
* baseUrl: 'https://api.myapp.com'
|
|
24
|
-
* });
|
|
25
|
-
*
|
|
26
|
-
* @example
|
|
27
|
-
* // Full configuration
|
|
28
|
-
* initWebority({
|
|
29
|
-
* baseUrl: 'https://api.myapp.com',
|
|
30
|
-
* loggingEnabled: __DEV__,
|
|
31
|
-
* logLevel: 'warn',
|
|
32
|
-
* environment: __DEV__ ? 'Development' : 'Production'
|
|
33
|
-
* });
|
|
34
|
-
*/
|
|
35
|
-
const initWebority = config => {
|
|
36
|
-
if (!config.baseUrl) {
|
|
37
|
-
throw new Error('baseUrl is required for Webority packages initialization');
|
|
38
|
-
}
|
|
39
|
-
(0, _index.setConfig)({
|
|
40
|
-
baseUrl: config.baseUrl,
|
|
41
|
-
loggingEnabled: config.loggingEnabled ?? true,
|
|
42
|
-
logLevel: config.logLevel || _index.DEFAULT_LOG_LEVEL,
|
|
43
|
-
environment: config.environment || 'Development',
|
|
44
|
-
country: (config.country || 'in').toLowerCase(),
|
|
45
|
-
appId: config.appId ?? null,
|
|
46
|
-
appVersion: config.appVersion ?? null,
|
|
47
|
-
logCurl: config.logCurl ?? false
|
|
48
|
-
});
|
|
49
|
-
|
|
50
|
-
// Only what the caller actually passed is wired. Calling a setter with
|
|
51
|
-
// `undefined` would reset a backend an app had already injected by hand,
|
|
52
|
-
// which is why each is guarded rather than passed straight through.
|
|
53
|
-
const backends = config.backends;
|
|
54
|
-
if (backends?.storage) {
|
|
55
|
-
(0, _index3.setStorageImplementation)(backends.storage);
|
|
56
|
-
}
|
|
57
|
-
if (backends?.keychain) {
|
|
58
|
-
(0, _authStore.setKeychainImplementation)(backends.keychain);
|
|
59
|
-
}
|
|
60
|
-
if (backends?.network) {
|
|
61
|
-
(0, _networkStatus.setNetworkStatusImplementation)(backends.network);
|
|
62
|
-
}
|
|
63
|
-
_index2.Logger.info('[@webority/mobile-core] initialized');
|
|
64
|
-
};
|
|
65
|
-
exports.initWebority = initWebority;
|
|
66
|
-
//# sourceMappingURL=initSDK.js.map
|
|
1
|
+
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.initWebority=void 0;var _authStore=require("./auth/authStore.js"),_index=require("./config/index.js"),_index2=require("./logger/index.js"),_networkStatus=require("./network/networkStatus.js"),_index3=require("./storage/index.js");const initWebority=e=>{if(!e.baseUrl)throw new Error("baseUrl is required for Webority packages initialization");(0,_index.setConfig)({baseUrl:e.baseUrl,loggingEnabled:e.loggingEnabled??!0,logLevel:e.logLevel||_index.DEFAULT_LOG_LEVEL,environment:e.environment||"Development",country:(e.country||"in").toLowerCase(),appId:e.appId??null,appVersion:e.appVersion??null,logCurl:e.logCurl??!1});const t=e.backends;t?.storage&&(0,_index3.setStorageImplementation)(t.storage),t?.keychain&&(0,_authStore.setKeychainImplementation)(t.keychain),t?.network&&(0,_networkStatus.setNetworkStatusImplementation)(t.network),_index2.Logger.info("[@webority/mobile-core] initialized")};exports.initWebority=initWebority;
|
|
@@ -1,37 +1 @@
|
|
|
1
|
-
"use strict";
|
|
2
|
-
|
|
3
|
-
Object.defineProperty(exports, "__esModule", {
|
|
4
|
-
value: true
|
|
5
|
-
});
|
|
6
|
-
exports.initUserAuth = void 0;
|
|
7
|
-
var _userClient = require("./api/userClient.js");
|
|
8
|
-
var _index = require("./logger/index.js");
|
|
9
|
-
/** The tokens a refresh response carries, with their expiry timestamps. */
|
|
10
|
-
|
|
11
|
-
/**
|
|
12
|
-
* How the library calls the app's refresh endpoint. The call goes through
|
|
13
|
-
* `publicClient`, and the new tokens are stored under the library's own keys.
|
|
14
|
-
*/
|
|
15
|
-
|
|
16
|
-
/**
|
|
17
|
-
* Wire the user client to the app: the Redux store it dispatches `logout` to,
|
|
18
|
-
* and the refresh endpoint it calls when an access token expires or a request
|
|
19
|
-
* answers 401. Only a 400 or 401 from that endpoint, or a missing or expired
|
|
20
|
-
* refresh token, logs out; a network error, timeout or 5xx keeps the session.
|
|
21
|
-
*
|
|
22
|
-
* @example
|
|
23
|
-
* initUserAuth(store, { logout, refresh: { path: '/Account/RefreshToken' } });
|
|
24
|
-
*/
|
|
25
|
-
const initUserAuth = (store, options) => {
|
|
26
|
-
if (!store) {
|
|
27
|
-
throw new Error('Redux store is required for user package initialization');
|
|
28
|
-
}
|
|
29
|
-
if (!options.logout || !options.refresh?.path) {
|
|
30
|
-
throw new Error('initUserAuth needs a logout action and refresh.path');
|
|
31
|
-
}
|
|
32
|
-
(0, _userClient.injectStore)(store);
|
|
33
|
-
(0, _userClient.injectUserAuth)(options);
|
|
34
|
-
_index.Logger.info('[@webority/mobile-core] user auth wired to the store');
|
|
35
|
-
};
|
|
36
|
-
exports.initUserAuth = initUserAuth;
|
|
37
|
-
//# sourceMappingURL=initUserAuth.js.map
|
|
1
|
+
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.initUserAuth=void 0;var _userClient=require("./api/userClient.js"),_index=require("./logger/index.js");const initUserAuth=(e,r)=>{if(!e)throw new Error("Redux store is required for user package initialization");if(!r.logout||!r.refresh?.path)throw new Error("initUserAuth needs a logout action and refresh.path");(0,_userClient.injectStore)(e),(0,_userClient.injectUserAuth)(r),_index.Logger.info("[@webority/mobile-core] user auth wired to the store")};exports.initUserAuth=initUserAuth;
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.crashlyticsRemoteLogger=void 0;const toError=r=>r instanceof Error?r:new Error(String(r)),describe=r=>{try{return JSON.stringify(r)}catch{return String(r)}},crashlyticsRemoteLogger=r=>{const send=t=>{try{const e=t(r.getCrashlytics());e&&"function"==typeof e.catch&&e.catch(()=>{})}catch{}};return{breadcrumb:(t,e)=>send(o=>r.log(o,e?`${t} ${describe(e)}`:t)),recordError:(t,e)=>{e&&send(t=>r.log(t,`context ${describe(e)}`)),send(e=>r.recordError(e,toError(t)))},setUser:t=>send(e=>r.setUserId(e,t??"")),setAttribute:(t,e)=>send(o=>r.setAttribute(o,t,null===e?"":String(e))),log:(t,e)=>send(o=>r.log(o,`[${t.toUpperCase()}] ${e}`))}};exports.crashlyticsRemoteLogger=crashlyticsRemoteLogger;
|
|
@@ -1,301 +1 @@
|
|
|
1
|
-
"use strict";
|
|
2
|
-
|
|
3
|
-
Object.defineProperty(exports, "__esModule", {
|
|
4
|
-
value: true
|
|
5
|
-
});
|
|
6
|
-
exports.setRemoteLogger = exports.setDeviceContext = exports.getDeviceContext = exports.configureLogger = exports.Logger = void 0;
|
|
7
|
-
var _index = require("../config/index.js");
|
|
8
|
-
var _redact = require("./redact.js");
|
|
9
|
-
// ANSI color codes
|
|
10
|
-
const Colors = {
|
|
11
|
-
RESET: '\x1b[0m',
|
|
12
|
-
BLUE: '\x1b[34m',
|
|
13
|
-
YELLOW: '\x1b[33m',
|
|
14
|
-
RED_BOLD: '\x1b[31;1m'
|
|
15
|
-
};
|
|
16
|
-
const LogLevels = {
|
|
17
|
-
INFO: {
|
|
18
|
-
level: 'info',
|
|
19
|
-
color: Colors.BLUE
|
|
20
|
-
},
|
|
21
|
-
WARN: {
|
|
22
|
-
level: 'warn',
|
|
23
|
-
color: Colors.YELLOW
|
|
24
|
-
},
|
|
25
|
-
ERROR: {
|
|
26
|
-
level: 'error',
|
|
27
|
-
color: Colors.RED_BOLD
|
|
28
|
-
}
|
|
29
|
-
};
|
|
30
|
-
|
|
31
|
-
// Check if a specific log level is allowed
|
|
32
|
-
const isLogLevelAllowed = level => {
|
|
33
|
-
const levels = ['info', 'warn', 'error'];
|
|
34
|
-
const current = (0, _index.getConfigValue)('logLevel', 'info');
|
|
35
|
-
return levels.indexOf(level) >= levels.indexOf(current);
|
|
36
|
-
};
|
|
37
|
-
const isEnabled = () => (0, _index.getConfigValue)('loggingEnabled', true);
|
|
38
|
-
|
|
39
|
-
/**
|
|
40
|
-
* Optional remote sink. Apps wire this via `setRemoteLogger()` to forward errors
|
|
41
|
-
* and breadcrumbs to Crashlytics, Sentry, Bugsnag, etc. — without making the
|
|
42
|
-
* library depend on any of them.
|
|
43
|
-
*
|
|
44
|
-
* Every method is optional; the library calls only what the adapter implements.
|
|
45
|
-
*/
|
|
46
|
-
|
|
47
|
-
let remote = null;
|
|
48
|
-
|
|
49
|
-
/**
|
|
50
|
-
* Inject a remote logger adapter (e.g. Firebase Crashlytics, Sentry).
|
|
51
|
-
* Pass `null` to detach. Safe to call before or after `initWebority`.
|
|
52
|
-
*/
|
|
53
|
-
const setRemoteLogger = impl => {
|
|
54
|
-
remote = impl;
|
|
55
|
-
};
|
|
56
|
-
exports.setRemoteLogger = setRemoteLogger;
|
|
57
|
-
const safe = fn => {
|
|
58
|
-
if (!fn) {
|
|
59
|
-
return;
|
|
60
|
-
}
|
|
61
|
-
try {
|
|
62
|
-
fn();
|
|
63
|
-
} catch {
|
|
64
|
-
/* never let the remote sink break the caller */
|
|
65
|
-
}
|
|
66
|
-
};
|
|
67
|
-
const toErrorObject = input => {
|
|
68
|
-
if (input instanceof Error) {
|
|
69
|
-
return input;
|
|
70
|
-
}
|
|
71
|
-
if (typeof input === 'string') {
|
|
72
|
-
return new Error(input);
|
|
73
|
-
}
|
|
74
|
-
try {
|
|
75
|
-
return new Error(JSON.stringify(input));
|
|
76
|
-
} catch {
|
|
77
|
-
return new Error(String(input));
|
|
78
|
-
}
|
|
79
|
-
};
|
|
80
|
-
|
|
81
|
-
/**
|
|
82
|
-
* Device / app context attached once at boot (platform, OS version, app version,
|
|
83
|
-
* build number, device model, etc). Merged into every `recordError` context so
|
|
84
|
-
* every crash carries it without every call site repeating it.
|
|
85
|
-
*/
|
|
86
|
-
|
|
87
|
-
let deviceContext = null;
|
|
88
|
-
const normalizeAttributeValue = value => {
|
|
89
|
-
if (value === null || value === undefined) {
|
|
90
|
-
return null;
|
|
91
|
-
}
|
|
92
|
-
if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') {
|
|
93
|
-
return value;
|
|
94
|
-
}
|
|
95
|
-
return String(value);
|
|
96
|
-
};
|
|
97
|
-
|
|
98
|
-
/**
|
|
99
|
-
* Set (or clear, with `null`) the device/app context merged into every
|
|
100
|
-
* `recordError` call. Each key is also forwarded to `remote.setAttribute`
|
|
101
|
-
* once, at the moment it is set.
|
|
102
|
-
*/
|
|
103
|
-
const setDeviceContext = context => {
|
|
104
|
-
deviceContext = context;
|
|
105
|
-
if (context) {
|
|
106
|
-
for (const [key, value] of Object.entries(context)) {
|
|
107
|
-
safe(() => remote?.setAttribute?.(key, normalizeAttributeValue(value)));
|
|
108
|
-
}
|
|
109
|
-
}
|
|
110
|
-
};
|
|
111
|
-
exports.setDeviceContext = setDeviceContext;
|
|
112
|
-
const getDeviceContext = () => deviceContext;
|
|
113
|
-
|
|
114
|
-
/** Tuning knobs for screen history and duplicate-error suppression. */
|
|
115
|
-
exports.getDeviceContext = getDeviceContext;
|
|
116
|
-
const DEFAULT_LOGGER_OPTIONS = {
|
|
117
|
-
dedupeWindowMs: 5000,
|
|
118
|
-
dedupeMaxPerWindow: 1,
|
|
119
|
-
screenHistoryLimit: 20
|
|
120
|
-
};
|
|
121
|
-
let loggerOptions = {
|
|
122
|
-
...DEFAULT_LOGGER_OPTIONS
|
|
123
|
-
};
|
|
124
|
-
|
|
125
|
-
/** Configure dedupe window/threshold and screen history size. Merges with current options. */
|
|
126
|
-
const configureLogger = options => {
|
|
127
|
-
loggerOptions = {
|
|
128
|
-
...loggerOptions,
|
|
129
|
-
...options
|
|
130
|
-
};
|
|
131
|
-
if (screenHistory.length > loggerOptions.screenHistoryLimit) {
|
|
132
|
-
screenHistory = screenHistory.slice(screenHistory.length - loggerOptions.screenHistoryLimit);
|
|
133
|
-
}
|
|
134
|
-
};
|
|
135
|
-
exports.configureLogger = configureLogger;
|
|
136
|
-
let currentScreen = null;
|
|
137
|
-
let screenHistory = [];
|
|
138
|
-
const dedupeMap = new Map();
|
|
139
|
-
const MAX_DEDUPE_ENTRIES = 200;
|
|
140
|
-
const dedupeKeyFor = err => {
|
|
141
|
-
const firstFrame = err.stack?.split('\n')[1]?.trim();
|
|
142
|
-
return firstFrame ? `${err.message}::${firstFrame}` : err.message;
|
|
143
|
-
};
|
|
144
|
-
const capDedupeMap = () => {
|
|
145
|
-
while (dedupeMap.size > MAX_DEDUPE_ENTRIES) {
|
|
146
|
-
const oldestKey = dedupeMap.keys().next().value;
|
|
147
|
-
if (oldestKey === undefined) {
|
|
148
|
-
return;
|
|
149
|
-
}
|
|
150
|
-
dedupeMap.delete(oldestKey);
|
|
151
|
-
}
|
|
152
|
-
};
|
|
153
|
-
const shouldForward = key => {
|
|
154
|
-
if (loggerOptions.dedupeWindowMs <= 0) {
|
|
155
|
-
return {
|
|
156
|
-
forward: true
|
|
157
|
-
};
|
|
158
|
-
}
|
|
159
|
-
const now = Date.now();
|
|
160
|
-
const entry = dedupeMap.get(key);
|
|
161
|
-
if (!entry || now - entry.windowStart >= loggerOptions.dedupeWindowMs) {
|
|
162
|
-
const suppressedCount = entry?.suppressedCount ?? 0;
|
|
163
|
-
dedupeMap.set(key, {
|
|
164
|
-
windowStart: now,
|
|
165
|
-
count: 1,
|
|
166
|
-
suppressedCount: 0
|
|
167
|
-
});
|
|
168
|
-
capDedupeMap();
|
|
169
|
-
return suppressedCount > 0 ? {
|
|
170
|
-
forward: true,
|
|
171
|
-
suppressedCount
|
|
172
|
-
} : {
|
|
173
|
-
forward: true
|
|
174
|
-
};
|
|
175
|
-
}
|
|
176
|
-
entry.count += 1;
|
|
177
|
-
if (entry.count > loggerOptions.dedupeMaxPerWindow) {
|
|
178
|
-
entry.suppressedCount += 1;
|
|
179
|
-
return {
|
|
180
|
-
forward: false
|
|
181
|
-
};
|
|
182
|
-
}
|
|
183
|
-
return {
|
|
184
|
-
forward: true
|
|
185
|
-
};
|
|
186
|
-
};
|
|
187
|
-
const buildErrorContext = (context, suppressedCount) => {
|
|
188
|
-
const merged = {
|
|
189
|
-
...deviceContext
|
|
190
|
-
};
|
|
191
|
-
if (currentScreen !== null) {
|
|
192
|
-
merged.screen = currentScreen;
|
|
193
|
-
}
|
|
194
|
-
if (suppressedCount) {
|
|
195
|
-
merged.suppressedCount = suppressedCount;
|
|
196
|
-
}
|
|
197
|
-
return {
|
|
198
|
-
...merged,
|
|
199
|
-
...context
|
|
200
|
-
};
|
|
201
|
-
};
|
|
202
|
-
const forwardErrorToRemote = (err, context) => {
|
|
203
|
-
const key = dedupeKeyFor(err);
|
|
204
|
-
const {
|
|
205
|
-
forward,
|
|
206
|
-
suppressedCount
|
|
207
|
-
} = shouldForward(key);
|
|
208
|
-
if (!forward) {
|
|
209
|
-
return;
|
|
210
|
-
}
|
|
211
|
-
safe(() => remote?.recordError?.(err, buildErrorContext(context, suppressedCount)));
|
|
212
|
-
};
|
|
213
|
-
const logInfo = (rawMessage, ...rawParams) => {
|
|
214
|
-
const message = (0, _redact.redactString)(rawMessage);
|
|
215
|
-
const optionalParams = (0, _redact.redact)(rawParams);
|
|
216
|
-
if (!isEnabled() || !isLogLevelAllowed(LogLevels.INFO.level)) {
|
|
217
|
-
return;
|
|
218
|
-
}
|
|
219
|
-
console.info(`${LogLevels.INFO.color}[INFO]: ${message}${Colors.RESET}`, ...optionalParams);
|
|
220
|
-
safe(() => remote?.log?.('info', message, optionalParams));
|
|
221
|
-
};
|
|
222
|
-
const logWarning = (rawMessage, ...rawParams) => {
|
|
223
|
-
const message = (0, _redact.redactString)(rawMessage);
|
|
224
|
-
const optionalParams = (0, _redact.redact)(rawParams);
|
|
225
|
-
if (!isEnabled() || !isLogLevelAllowed(LogLevels.WARN.level)) {
|
|
226
|
-
return;
|
|
227
|
-
}
|
|
228
|
-
console.warn(`${LogLevels.WARN.color}[WARNING]: ${message}${Colors.RESET}`, ...optionalParams);
|
|
229
|
-
safe(() => remote?.log?.('warn', message, optionalParams));
|
|
230
|
-
};
|
|
231
|
-
const logError = (rawMessage, ...rawParams) => {
|
|
232
|
-
const message = (0, _redact.redactString)(rawMessage);
|
|
233
|
-
const optionalParams = (0, _redact.redact)(rawParams);
|
|
234
|
-
if (isEnabled() && isLogLevelAllowed(LogLevels.ERROR.level)) {
|
|
235
|
-
console.error(`${LogLevels.ERROR.color}[ERROR]: ${message}${Colors.RESET}`, ...optionalParams);
|
|
236
|
-
}
|
|
237
|
-
// Always forward errors to the remote sink — even when console logging is muted —
|
|
238
|
-
// so production crash reporting still works with `loggingEnabled: false`.
|
|
239
|
-
safe(() => remote?.log?.('error', message, optionalParams));
|
|
240
|
-
// First optional param is treated as the underlying error if it looks like one.
|
|
241
|
-
const candidate = optionalParams[0];
|
|
242
|
-
if (candidate !== undefined) {
|
|
243
|
-
forwardErrorToRemote(toErrorObject(candidate), {
|
|
244
|
-
source: 'Logger.error',
|
|
245
|
-
message
|
|
246
|
-
});
|
|
247
|
-
}
|
|
248
|
-
};
|
|
249
|
-
const breadcrumb = (rawMessage, rawData) => {
|
|
250
|
-
const message = (0, _redact.redactString)(rawMessage);
|
|
251
|
-
const data = (0, _redact.redact)(rawData);
|
|
252
|
-
if (isEnabled() && isLogLevelAllowed('info')) {
|
|
253
|
-
console.info(`${Colors.BLUE}[BREADCRUMB]: ${message}${Colors.RESET}`, data ?? '');
|
|
254
|
-
}
|
|
255
|
-
safe(() => remote?.breadcrumb?.(message, data));
|
|
256
|
-
};
|
|
257
|
-
const recordError = (error, rawContext) => {
|
|
258
|
-
const err = (0, _redact.redact)(toErrorObject(error));
|
|
259
|
-
const context = (0, _redact.redact)(rawContext);
|
|
260
|
-
if (isEnabled() && isLogLevelAllowed('error')) {
|
|
261
|
-
console.error(`${Colors.RED_BOLD}[RECORDED]: ${err.message}${Colors.RESET}`, context ?? '');
|
|
262
|
-
}
|
|
263
|
-
forwardErrorToRemote(err, context);
|
|
264
|
-
};
|
|
265
|
-
const setUser = (id, attrs) => {
|
|
266
|
-
safe(() => remote?.setUser?.(id, attrs));
|
|
267
|
-
};
|
|
268
|
-
const setAttribute = (key, value) => {
|
|
269
|
-
safe(() => remote?.setAttribute?.(key, value));
|
|
270
|
-
};
|
|
271
|
-
|
|
272
|
-
/**
|
|
273
|
-
* Record the active screen as a breadcrumb and remember it for subsequent
|
|
274
|
-
* `recordError` context. Re-tracking the same screen name is a no-op.
|
|
275
|
-
*/
|
|
276
|
-
const trackScreen = (name, params) => {
|
|
277
|
-
if (name === currentScreen) {
|
|
278
|
-
return;
|
|
279
|
-
}
|
|
280
|
-
currentScreen = name;
|
|
281
|
-
screenHistory.push(name);
|
|
282
|
-
if (screenHistory.length > loggerOptions.screenHistoryLimit) {
|
|
283
|
-
screenHistory = screenHistory.slice(screenHistory.length - loggerOptions.screenHistoryLimit);
|
|
284
|
-
}
|
|
285
|
-
breadcrumb(`Screen: ${name}`, params);
|
|
286
|
-
};
|
|
287
|
-
const getCurrentScreen = () => currentScreen;
|
|
288
|
-
const getScreenHistory = () => [...screenHistory];
|
|
289
|
-
const Logger = exports.Logger = {
|
|
290
|
-
info: logInfo,
|
|
291
|
-
warn: logWarning,
|
|
292
|
-
error: logError,
|
|
293
|
-
breadcrumb,
|
|
294
|
-
recordError,
|
|
295
|
-
setUser,
|
|
296
|
-
setAttribute,
|
|
297
|
-
trackScreen,
|
|
298
|
-
getCurrentScreen,
|
|
299
|
-
getScreenHistory
|
|
300
|
-
};
|
|
301
|
-
//# sourceMappingURL=index.js.map
|
|
1
|
+
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.setRemoteLogger=exports.setDeviceContext=exports.getDeviceContext=exports.configureLogger=exports.Logger=void 0;var _index=require("../config/index.js"),_redact=require("./redact.js");const Colors={RESET:"[0m",BLUE:"[34m",YELLOW:"[33m",RED_BOLD:"[31;1m"},LogLevels={INFO:{level:"info",color:Colors.BLUE},WARN:{level:"warn",color:Colors.YELLOW},ERROR:{level:"error",color:Colors.RED_BOLD}},isLogLevelAllowed=e=>{const r=["info","warn","error"],o=(0,_index.getConfigValue)("logLevel","info");return r.indexOf(e)>=r.indexOf(o)},isEnabled=()=>(0,_index.getConfigValue)("loggingEnabled",!0);let remote=null;const setRemoteLogger=e=>{remote=e};exports.setRemoteLogger=setRemoteLogger;const safe=e=>{if(e)try{e()}catch{}},toErrorObject=e=>{if(e instanceof Error)return e;if("string"==typeof e)return new Error(e);try{return new Error(JSON.stringify(e))}catch{return new Error(String(e))}};let deviceContext=null;const normalizeAttributeValue=e=>null==e?null:"string"==typeof e||"number"==typeof e||"boolean"==typeof e?e:String(e),setDeviceContext=e=>{if(deviceContext=e,e)for(const[r,o]of Object.entries(e))safe(()=>remote?.setAttribute?.(r,normalizeAttributeValue(o)))};exports.setDeviceContext=setDeviceContext;const getDeviceContext=()=>deviceContext;exports.getDeviceContext=getDeviceContext;const DEFAULT_LOGGER_OPTIONS={dedupeWindowMs:5e3,dedupeMaxPerWindow:1,screenHistoryLimit:20};let loggerOptions={...DEFAULT_LOGGER_OPTIONS};const configureLogger=e=>{loggerOptions={...loggerOptions,...e},screenHistory.length>loggerOptions.screenHistoryLimit&&(screenHistory=screenHistory.slice(screenHistory.length-loggerOptions.screenHistoryLimit))};exports.configureLogger=configureLogger;let currentScreen=null,screenHistory=[];const dedupeMap=new Map,MAX_DEDUPE_ENTRIES=200,dedupeKeyFor=e=>{const r=e.stack?.split("\n")[1]?.trim();return r?`${e.message}::${r}`:e.message},capDedupeMap=()=>{for(;dedupeMap.size>200;){const e=dedupeMap.keys().next().value;if(void 0===e)return;dedupeMap.delete(e)}},shouldForward=e=>{if(loggerOptions.dedupeWindowMs<=0)return{forward:!0};const r=Date.now(),o=dedupeMap.get(e);if(!o||r-o.windowStart>=loggerOptions.dedupeWindowMs){const t=o?.suppressedCount??0;return dedupeMap.set(e,{windowStart:r,count:1,suppressedCount:0}),capDedupeMap(),t>0?{forward:!0,suppressedCount:t}:{forward:!0}}return o.count+=1,o.count>loggerOptions.dedupeMaxPerWindow?(o.suppressedCount+=1,{forward:!1}):{forward:!0}},buildErrorContext=(e,r)=>{const o={...deviceContext};return null!==currentScreen&&(o.screen=currentScreen),r&&(o.suppressedCount=r),{...o,...e}},forwardErrorToRemote=(e,r)=>{const o=dedupeKeyFor(e),{forward:t,suppressedCount:n}=shouldForward(o);t&&safe(()=>remote?.recordError?.(e,buildErrorContext(r,n)))},logInfo=(e,...r)=>{const o=(0,_redact.redactString)(e),t=(0,_redact.redact)(r);isEnabled()&&isLogLevelAllowed(LogLevels.INFO.level)&&(console.info(`${LogLevels.INFO.color}[INFO]: ${o}${Colors.RESET}`,...t),safe(()=>remote?.log?.("info",o,t)))},logWarning=(e,...r)=>{const o=(0,_redact.redactString)(e),t=(0,_redact.redact)(r);isEnabled()&&isLogLevelAllowed(LogLevels.WARN.level)&&(console.warn(`${LogLevels.WARN.color}[WARNING]: ${o}${Colors.RESET}`,...t),safe(()=>remote?.log?.("warn",o,t)))},logError=(e,...r)=>{const o=(0,_redact.redactString)(e),t=(0,_redact.redact)(r);isEnabled()&&isLogLevelAllowed(LogLevels.ERROR.level)&&console.error(`${LogLevels.ERROR.color}[ERROR]: ${o}${Colors.RESET}`,...t),safe(()=>remote?.log?.("error",o,t));const n=t[0];void 0!==n&&forwardErrorToRemote(toErrorObject(n),{source:"Logger.error",message:o})},breadcrumb=(e,r)=>{const o=(0,_redact.redactString)(e),t=(0,_redact.redact)(r);isEnabled()&&isLogLevelAllowed("info")&&console.info(`${Colors.BLUE}[BREADCRUMB]: ${o}${Colors.RESET}`,t??""),safe(()=>remote?.breadcrumb?.(o,t))},recordError=(e,r)=>{const o=(0,_redact.redact)(toErrorObject(e)),t=(0,_redact.redact)(r);isEnabled()&&isLogLevelAllowed("error")&&console.error(`${Colors.RED_BOLD}[RECORDED]: ${o.message}${Colors.RESET}`,t??""),forwardErrorToRemote(o,t)},setUser=(e,r)=>{safe(()=>remote?.setUser?.(e,r))},setAttribute=(e,r)=>{safe(()=>remote?.setAttribute?.(e,r))},trackScreen=(e,r)=>{e!==currentScreen&&(currentScreen=e,screenHistory.push(e),screenHistory.length>loggerOptions.screenHistoryLimit&&(screenHistory=screenHistory.slice(screenHistory.length-loggerOptions.screenHistoryLimit)),breadcrumb(`Screen: ${e}`,r))},getCurrentScreen=()=>currentScreen,getScreenHistory=()=>[...screenHistory],Logger=exports.Logger={info:logInfo,warn:logWarning,error:logError,breadcrumb:breadcrumb,recordError:recordError,setUser:setUser,setAttribute:setAttribute,trackScreen:trackScreen,getCurrentScreen:getCurrentScreen,getScreenHistory:getScreenHistory};
|
|
@@ -1,50 +1 @@
|
|
|
1
|
-
"use strict";
|
|
2
|
-
|
|
3
|
-
Object.defineProperty(exports, "__esModule", {
|
|
4
|
-
value: true
|
|
5
|
-
});
|
|
6
|
-
exports.redactString = exports.redact = void 0;
|
|
7
|
-
const REDACTED = '[REDACTED]';
|
|
8
|
-
const SECRET_KEYS = /^(token|accesstoken|refreshtoken|password|authorization)$/i;
|
|
9
|
-
const BEARER = /\bBearer\s+[A-Za-z0-9._~+/-]+=*/gi;
|
|
10
|
-
const JWT = /\beyJ[A-Za-z0-9_-]*\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]*/g;
|
|
11
|
-
const KEYED_VALUE = /(["']?(?:token|accessToken|refreshToken|password|authorization)["']?\s*[:=]\s*)(?:"(?:[^"\\]|\\.)*"|'[^']*'|[^\s,;&}]+)/gi;
|
|
12
|
-
const MAX_DEPTH = 6;
|
|
13
|
-
const redactString = input => input.replace(BEARER, `Bearer ${REDACTED}`).replace(JWT, REDACTED).replace(KEYED_VALUE, (_match, prefix) => `${prefix}"${REDACTED}"`);
|
|
14
|
-
exports.redactString = redactString;
|
|
15
|
-
const redactInner = (value, depth, seen) => {
|
|
16
|
-
if (typeof value === 'string') {
|
|
17
|
-
return redactString(value);
|
|
18
|
-
}
|
|
19
|
-
if (value === null || typeof value !== 'object') {
|
|
20
|
-
return value;
|
|
21
|
-
}
|
|
22
|
-
if (value instanceof Error) {
|
|
23
|
-
value.message = redactString(value.message);
|
|
24
|
-
if (value.stack) {
|
|
25
|
-
value.stack = redactString(value.stack);
|
|
26
|
-
}
|
|
27
|
-
return value;
|
|
28
|
-
}
|
|
29
|
-
if (depth >= MAX_DEPTH || seen.has(value)) {
|
|
30
|
-
return value;
|
|
31
|
-
}
|
|
32
|
-
seen.add(value);
|
|
33
|
-
if (Array.isArray(value)) {
|
|
34
|
-
return value.map(item => redactInner(item, depth + 1, seen));
|
|
35
|
-
}
|
|
36
|
-
const proto = Object.getPrototypeOf(value);
|
|
37
|
-
if (proto !== Object.prototype && proto !== null) {
|
|
38
|
-
return value;
|
|
39
|
-
}
|
|
40
|
-
const out = {};
|
|
41
|
-
for (const [key, item] of Object.entries(value)) {
|
|
42
|
-
out[key] = SECRET_KEYS.test(key) ? REDACTED : redactInner(item, depth + 1, seen);
|
|
43
|
-
}
|
|
44
|
-
return out;
|
|
45
|
-
};
|
|
46
|
-
|
|
47
|
-
/** Returns a copy with secrets masked; Errors are masked in place so identity and stack survive. */
|
|
48
|
-
const redact = value => redactInner(value, 0, new WeakSet());
|
|
49
|
-
exports.redact = redact;
|
|
50
|
-
//# sourceMappingURL=redact.js.map
|
|
1
|
+
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.redactString=exports.redact=void 0;const REDACTED="[REDACTED]",SECRET_KEYS=/^(token|accesstoken|refreshtoken|password|authorization)$/i,BEARER=/\bBearer\s+[A-Za-z0-9._~+/-]+=*/gi,JWT=/\beyJ[A-Za-z0-9_-]*\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]*/g,KEYED_VALUE=/(["']?(?:token|accessToken|refreshToken|password|authorization)["']?\s*[:=]\s*)(?:"(?:[^"\\]|\\.)*"|'[^']*'|[^\s,;&}]+)/gi,MAX_DEPTH=6,redactString=e=>e.replace(BEARER,`Bearer ${REDACTED}`).replace(JWT,REDACTED).replace(KEYED_VALUE,(e,r)=>`${r}"${REDACTED}"`);exports.redactString=redactString;const redactInner=(e,r,t)=>{if("string"==typeof e)return redactString(e);if(null===e||"object"!=typeof e)return e;if(e instanceof Error)return e.message=redactString(e.message),e.stack&&(e.stack=redactString(e.stack)),e;if(r>=6||t.has(e))return e;if(t.add(e),Array.isArray(e))return e.map(e=>redactInner(e,r+1,t));const a=Object.getPrototypeOf(e);if(a!==Object.prototype&&null!==a)return e;const n={};for(const[a,s]of Object.entries(e))n[a]=SECRET_KEYS.test(a)?REDACTED:redactInner(s,r+1,t);return n},redact=e=>redactInner(e,0,new WeakSet);exports.redact=redact;
|
|
@@ -1,31 +1 @@
|
|
|
1
|
-
"use strict";
|
|
2
|
-
|
|
3
|
-
Object.defineProperty(exports, "__esModule", {
|
|
4
|
-
value: true
|
|
5
|
-
});
|
|
6
|
-
Object.defineProperty(exports, "addNetworkStatusListener", {
|
|
7
|
-
enumerable: true,
|
|
8
|
-
get: function () {
|
|
9
|
-
return _networkStatus.addNetworkStatusListener;
|
|
10
|
-
}
|
|
11
|
-
});
|
|
12
|
-
Object.defineProperty(exports, "getNetworkStatus", {
|
|
13
|
-
enumerable: true,
|
|
14
|
-
get: function () {
|
|
15
|
-
return _networkStatus.getNetworkStatus;
|
|
16
|
-
}
|
|
17
|
-
});
|
|
18
|
-
Object.defineProperty(exports, "setNetworkStatusImplementation", {
|
|
19
|
-
enumerable: true,
|
|
20
|
-
get: function () {
|
|
21
|
-
return _networkStatus.setNetworkStatusImplementation;
|
|
22
|
-
}
|
|
23
|
-
});
|
|
24
|
-
Object.defineProperty(exports, "useNetworkStatus", {
|
|
25
|
-
enumerable: true,
|
|
26
|
-
get: function () {
|
|
27
|
-
return _networkStatus.useNetworkStatus;
|
|
28
|
-
}
|
|
29
|
-
});
|
|
30
|
-
var _networkStatus = require("./networkStatus.js");
|
|
31
|
-
//# sourceMappingURL=index.js.map
|
|
1
|
+
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),Object.defineProperty(exports,"addNetworkStatusListener",{enumerable:!0,get:function(){return _networkStatus.addNetworkStatusListener}}),Object.defineProperty(exports,"getNetworkStatus",{enumerable:!0,get:function(){return _networkStatus.getNetworkStatus}}),Object.defineProperty(exports,"setNetworkStatusImplementation",{enumerable:!0,get:function(){return _networkStatus.setNetworkStatusImplementation}}),Object.defineProperty(exports,"useNetworkStatus",{enumerable:!0,get:function(){return _networkStatus.useNetworkStatus}});var _networkStatus=require("./networkStatus.js");
|
|
@@ -1,171 +1 @@
|
|
|
1
|
-
"use strict";
|
|
2
|
-
|
|
3
|
-
Object.defineProperty(exports, "__esModule", {
|
|
4
|
-
value: true
|
|
5
|
-
});
|
|
6
|
-
exports.useNetworkStatus = exports.setNetworkStatusImplementation = exports.getNetworkStatus = exports.getLastKnownNetworkStatus = exports.addNetworkStatusListener = void 0;
|
|
7
|
-
var ExpoNetwork = _interopRequireWildcard(require("expo-network"));
|
|
8
|
-
var _react = require("react");
|
|
9
|
-
var _index = require("../logger/index.js");
|
|
10
|
-
function _interopRequireWildcard(e, t) { if ("function" == typeof WeakMap) var r = new WeakMap(), n = new WeakMap(); return (_interopRequireWildcard = function (e, t) { if (!t && e && e.__esModule) return e; var o, i, f = { __proto__: null, default: e }; if (null === e || "object" != typeof e && "function" != typeof e) return f; if (o = t ? n : r) { if (o.has(e)) return o.get(e); o.set(e, f); } for (const t in e) "default" !== t && {}.hasOwnProperty.call(e, t) && ((i = (o = Object.defineProperty) && Object.getOwnPropertyDescriptor(e, t)) && (i.get || i.set) ? o(f, t, i) : f[t] = e[t]); return f; })(e, t); }
|
|
11
|
-
const DEFAULT_STATUS = {
|
|
12
|
-
isConnected: true,
|
|
13
|
-
isInternetReachable: null,
|
|
14
|
-
type: 'unknown'
|
|
15
|
-
};
|
|
16
|
-
/**
|
|
17
|
-
* expo-network is imported directly, not resolved through a seam.
|
|
18
|
-
*
|
|
19
|
-
* `expo` is a REQUIRED peer of this package, so every consumer has the Expo
|
|
20
|
-
* modules by construction and the static-require problem that forced the old
|
|
21
|
-
* injection design does not arise. An app wires nothing: connectivity works
|
|
22
|
-
* because the library uses Expo, which is the point of the Expo-first policy.
|
|
23
|
-
* One backend also means one behaviour, rather than each app choosing.
|
|
24
|
-
*/
|
|
25
|
-
let override = null;
|
|
26
|
-
let lastKnown = null;
|
|
27
|
-
let stopFollowing = null;
|
|
28
|
-
const stopFollowingNetwork = () => {
|
|
29
|
-
stopFollowing?.();
|
|
30
|
-
stopFollowing = null;
|
|
31
|
-
lastKnown = null;
|
|
32
|
-
};
|
|
33
|
-
|
|
34
|
-
/**
|
|
35
|
-
* Replace the backend. Intended for TESTS and for the showcase, which uses it
|
|
36
|
-
* to reach error paths that a healthy device never takes; it is not the way an
|
|
37
|
-
* app is meant to configure the library. Pass `null` to restore expo-network.
|
|
38
|
-
*/
|
|
39
|
-
const setNetworkStatusImplementation = impl => {
|
|
40
|
-
override = impl;
|
|
41
|
-
stopFollowingNetwork();
|
|
42
|
-
};
|
|
43
|
-
exports.setNetworkStatusImplementation = setNetworkStatusImplementation;
|
|
44
|
-
const resolveNetInfo = () => override ?? expoNetworkBackend;
|
|
45
|
-
|
|
46
|
-
/**
|
|
47
|
-
* expo-network in the shape this module already speaks.
|
|
48
|
-
*
|
|
49
|
-
* The conversion is not cosmetic: expo reports its type as an UPPERCASE enum
|
|
50
|
-
* where this module's vocabulary is lowercase, marks every field optional, and
|
|
51
|
-
* returns an EventSubscription where an unsubscribe function is expected.
|
|
52
|
-
*/
|
|
53
|
-
const expoNetworkBackend = {
|
|
54
|
-
fetch: async () => {
|
|
55
|
-
const state = await ExpoNetwork.getNetworkStateAsync();
|
|
56
|
-
return {
|
|
57
|
-
isConnected: state?.isConnected !== false,
|
|
58
|
-
isInternetReachable: state?.isInternetReachable ?? null,
|
|
59
|
-
type: state?.type ? String(state.type).toLowerCase() : undefined
|
|
60
|
-
};
|
|
61
|
-
},
|
|
62
|
-
addEventListener: cb => {
|
|
63
|
-
const subscription = ExpoNetwork.addNetworkStateListener(state => {
|
|
64
|
-
cb({
|
|
65
|
-
isConnected: state?.isConnected !== false,
|
|
66
|
-
isInternetReachable: state?.isInternetReachable ?? null,
|
|
67
|
-
type: state?.type ? String(state.type).toLowerCase() : undefined
|
|
68
|
-
});
|
|
69
|
-
});
|
|
70
|
-
return () => subscription.remove();
|
|
71
|
-
}
|
|
72
|
-
};
|
|
73
|
-
const normalize = state => {
|
|
74
|
-
if (!state) {
|
|
75
|
-
return DEFAULT_STATUS;
|
|
76
|
-
}
|
|
77
|
-
return {
|
|
78
|
-
isConnected: state.isConnected !== false,
|
|
79
|
-
isInternetReachable: state.isInternetReachable,
|
|
80
|
-
type: state.type ?? 'unknown'
|
|
81
|
-
};
|
|
82
|
-
};
|
|
83
|
-
|
|
84
|
-
/**
|
|
85
|
-
* Imperative one-shot fetch of current network status. Resolves to the default
|
|
86
|
-
* online status when NetInfo is unavailable so callers never crash.
|
|
87
|
-
*/
|
|
88
|
-
const getNetworkStatus = async () => {
|
|
89
|
-
const ni = resolveNetInfo();
|
|
90
|
-
if (!ni) {
|
|
91
|
-
return DEFAULT_STATUS;
|
|
92
|
-
}
|
|
93
|
-
try {
|
|
94
|
-
const state = await ni.fetch();
|
|
95
|
-
return normalize(state);
|
|
96
|
-
} catch (error) {
|
|
97
|
-
_index.Logger.error('[network] getNetworkStatus failed', error);
|
|
98
|
-
return DEFAULT_STATUS;
|
|
99
|
-
}
|
|
100
|
-
};
|
|
101
|
-
|
|
102
|
-
/**
|
|
103
|
-
* Subscribe to network status changes. Returns an unsubscribe function.
|
|
104
|
-
*/
|
|
105
|
-
exports.getNetworkStatus = getNetworkStatus;
|
|
106
|
-
const addNetworkStatusListener = listener => {
|
|
107
|
-
const ni = resolveNetInfo();
|
|
108
|
-
if (!ni) {
|
|
109
|
-
return () => undefined;
|
|
110
|
-
}
|
|
111
|
-
return ni.addEventListener(state => listener(normalize(state)));
|
|
112
|
-
};
|
|
113
|
-
|
|
114
|
-
/**
|
|
115
|
-
* The connectivity the HTTP client checks before every request. One listener,
|
|
116
|
-
* attached on first use, keeps it current, so a request costs no native probe:
|
|
117
|
-
* one probe seeds the value and the listener's events replace it.
|
|
118
|
-
*/
|
|
119
|
-
exports.addNetworkStatusListener = addNetworkStatusListener;
|
|
120
|
-
const getLastKnownNetworkStatus = async () => {
|
|
121
|
-
if (!stopFollowing) {
|
|
122
|
-
try {
|
|
123
|
-
stopFollowing = addNetworkStatusListener(status => {
|
|
124
|
-
lastKnown = status;
|
|
125
|
-
});
|
|
126
|
-
} catch (error) {
|
|
127
|
-
_index.Logger.error('[network] could not follow network changes', error);
|
|
128
|
-
return getNetworkStatus();
|
|
129
|
-
}
|
|
130
|
-
}
|
|
131
|
-
if (lastKnown) {
|
|
132
|
-
return lastKnown;
|
|
133
|
-
}
|
|
134
|
-
const following = stopFollowing;
|
|
135
|
-
const probed = await getNetworkStatus();
|
|
136
|
-
if (stopFollowing !== following) {
|
|
137
|
-
return probed;
|
|
138
|
-
}
|
|
139
|
-
// An event that arrived during the probe is newer than the probe.
|
|
140
|
-
lastKnown ??= probed;
|
|
141
|
-
return lastKnown;
|
|
142
|
-
};
|
|
143
|
-
|
|
144
|
-
/**
|
|
145
|
-
* React hook that returns the current network status and re-renders on change.
|
|
146
|
-
* Reports an optimistic online default when NetInfo is not installed.
|
|
147
|
-
*/
|
|
148
|
-
exports.getLastKnownNetworkStatus = getLastKnownNetworkStatus;
|
|
149
|
-
const useNetworkStatus = () => {
|
|
150
|
-
const [status, setStatus] = (0, _react.useState)(DEFAULT_STATUS);
|
|
151
|
-
(0, _react.useEffect)(() => {
|
|
152
|
-
let mounted = true;
|
|
153
|
-
void getNetworkStatus().then(s => {
|
|
154
|
-
if (mounted) {
|
|
155
|
-
setStatus(s);
|
|
156
|
-
}
|
|
157
|
-
});
|
|
158
|
-
const unsubscribe = addNetworkStatusListener(s => {
|
|
159
|
-
if (mounted) {
|
|
160
|
-
setStatus(s);
|
|
161
|
-
}
|
|
162
|
-
});
|
|
163
|
-
return () => {
|
|
164
|
-
mounted = false;
|
|
165
|
-
unsubscribe();
|
|
166
|
-
};
|
|
167
|
-
}, []);
|
|
168
|
-
return status;
|
|
169
|
-
};
|
|
170
|
-
exports.useNetworkStatus = useNetworkStatus;
|
|
171
|
-
//# sourceMappingURL=networkStatus.js.map
|
|
1
|
+
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.useNetworkStatus=exports.setNetworkStatusImplementation=exports.getNetworkStatus=exports.getLastKnownNetworkStatus=exports.addNetworkStatusListener=void 0;var ExpoNetwork=_interopRequireWildcard(require("expo-network")),_react=require("react"),_index=require("../logger/index.js");function _interopRequireWildcard(t,e){if("function"==typeof WeakMap)var n=new WeakMap,o=new WeakMap;return(_interopRequireWildcard=function(t,e){if(!e&&t&&t.__esModule)return t;var r,s,a={__proto__:null,default:t};if(null===t||"object"!=typeof t&&"function"!=typeof t)return a;if(r=e?o:n){if(r.has(t))return r.get(t);r.set(t,a)}for(const e in t)"default"!==e&&{}.hasOwnProperty.call(t,e)&&((s=(r=Object.defineProperty)&&Object.getOwnPropertyDescriptor(t,e))&&(s.get||s.set)?r(a,e,s):a[e]=t[e]);return a})(t,e)}const DEFAULT_STATUS={isConnected:!0,isInternetReachable:null,type:"unknown"};let override=null,lastKnown=null,stopFollowing=null;const stopFollowingNetwork=()=>{stopFollowing?.(),stopFollowing=null,lastKnown=null},setNetworkStatusImplementation=t=>{override=t,stopFollowingNetwork()};exports.setNetworkStatusImplementation=setNetworkStatusImplementation;const resolveNetInfo=()=>override??expoNetworkBackend,expoNetworkBackend={fetch:async()=>{const t=await ExpoNetwork.getNetworkStateAsync();return{isConnected:!1!==t?.isConnected,isInternetReachable:t?.isInternetReachable??null,type:t?.type?String(t.type).toLowerCase():void 0}},addEventListener:t=>{const e=ExpoNetwork.addNetworkStateListener(e=>{t({isConnected:!1!==e?.isConnected,isInternetReachable:e?.isInternetReachable??null,type:e?.type?String(e.type).toLowerCase():void 0})});return()=>e.remove()}},normalize=t=>t?{isConnected:!1!==t.isConnected,isInternetReachable:t.isInternetReachable,type:t.type??"unknown"}:DEFAULT_STATUS,getNetworkStatus=async()=>{const t=resolveNetInfo();if(!t)return DEFAULT_STATUS;try{const e=await t.fetch();return normalize(e)}catch(t){return _index.Logger.error("[network] getNetworkStatus failed",t),DEFAULT_STATUS}};exports.getNetworkStatus=getNetworkStatus;const addNetworkStatusListener=t=>{const e=resolveNetInfo();return e?e.addEventListener(e=>t(normalize(e))):()=>{}};exports.addNetworkStatusListener=addNetworkStatusListener;const getLastKnownNetworkStatus=async()=>{if(!stopFollowing)try{stopFollowing=addNetworkStatusListener(t=>{lastKnown=t})}catch(t){return _index.Logger.error("[network] could not follow network changes",t),getNetworkStatus()}if(lastKnown&&!1!==lastKnown.isConnected)return lastKnown;const t=stopFollowing,e=lastKnown,n=await getNetworkStatus();return stopFollowing!==t?n:(lastKnown===e&&(lastKnown=n),lastKnown??n)};exports.getLastKnownNetworkStatus=getLastKnownNetworkStatus;const useNetworkStatus=()=>{const[t,e]=(0,_react.useState)(DEFAULT_STATUS);return(0,_react.useEffect)(()=>{let t=!0;getNetworkStatus().then(n=>{t&&e(n)});const n=addNetworkStatusListener(n=>{t&&e(n)});return()=>{t=!1,n()}},[]),t};exports.useNetworkStatus=useNetworkStatus;
|