@kissmyappss/react-native 0.0.0-stage → 1.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.
@@ -0,0 +1,2 @@
1
+ import type { DeviceInfo } from './client';
2
+ export declare function deviceInfo(): DeviceInfo;
package/lib/device.js ADDED
@@ -0,0 +1,59 @@
1
+ "use strict";
2
+ // What React Native itself can tell about the device, with no native module to link.
3
+ Object.defineProperty(exports, "__esModule", { value: true });
4
+ exports.deviceInfo = deviceInfo;
5
+ const react_native_1 = require("react-native");
6
+ function timezone() {
7
+ try {
8
+ return Intl.DateTimeFormat().resolvedOptions().timeZone || 'UTC';
9
+ }
10
+ catch {
11
+ return 'UTC';
12
+ }
13
+ }
14
+ function language() {
15
+ var _a, _b, _c, _d, _e, _f, _g;
16
+ const fromSettings = react_native_1.Platform.OS === 'ios'
17
+ ? ((_c = (_b = (_a = react_native_1.NativeModules.SettingsManager) === null || _a === void 0 ? void 0 : _a.settings) === null || _b === void 0 ? void 0 : _b.AppleLocale) !== null && _c !== void 0 ? _c : (_f = (_e = (_d = react_native_1.NativeModules.SettingsManager) === null || _d === void 0 ? void 0 : _d.settings) === null || _e === void 0 ? void 0 : _e.AppleLanguages) === null || _f === void 0 ? void 0 : _f[0])
18
+ : (_g = react_native_1.NativeModules.I18nManager) === null || _g === void 0 ? void 0 : _g.localeIdentifier;
19
+ if (typeof fromSettings === 'string' && fromSettings)
20
+ return fromSettings.replace(/_/g, '-').split('@')[0];
21
+ try {
22
+ return Intl.DateTimeFormat().resolvedOptions().locale || 'en';
23
+ }
24
+ catch {
25
+ return 'en';
26
+ }
27
+ }
28
+ function deviceInfo() {
29
+ var _a, _b, _c;
30
+ const screen = react_native_1.Dimensions.get('screen');
31
+ const shortSide = Math.min(screen.width, screen.height);
32
+ const constants = ((_a = react_native_1.Platform.constants) !== null && _a !== void 0 ? _a : {});
33
+ if (react_native_1.Platform.OS === 'ios') {
34
+ const pad = react_native_1.Platform.isPad === true || constants.interfaceIdiom === 'pad';
35
+ return {
36
+ platform: 'ios',
37
+ os_name: pad ? 'iPadOS' : 'iOS',
38
+ os_version: String((_b = constants.osVersion) !== null && _b !== void 0 ? _b : react_native_1.Platform.Version),
39
+ device_type: pad ? 'tablet' : 'mobile',
40
+ device_model: pad ? 'iPad' : 'iPhone',
41
+ screen_width: screen.width,
42
+ screen_height: screen.height,
43
+ timezone: timezone(),
44
+ language: language(),
45
+ };
46
+ }
47
+ const model = typeof constants.Model === 'string' ? constants.Model : undefined;
48
+ return {
49
+ platform: 'android',
50
+ os_name: 'Android',
51
+ os_version: String((_c = constants.Release) !== null && _c !== void 0 ? _c : react_native_1.Platform.Version),
52
+ device_type: shortSide >= 600 ? 'tablet' : 'mobile',
53
+ device_model: model,
54
+ screen_width: screen.width,
55
+ screen_height: screen.height,
56
+ timezone: timezone(),
57
+ language: language(),
58
+ };
59
+ }
package/lib/index.d.ts ADDED
@@ -0,0 +1,57 @@
1
+ import type { DeepLink } from './attribution';
2
+ import { KmaClient } from './client';
3
+ import type { ClientOptions, Properties, RevenueOptions, Storage } from './client';
4
+ import type { NavigationRefLike } from './navigation';
5
+ export { KmaClient, SDK_VERSION } from './client';
6
+ export type { ClientOptions, DeviceInfo, Properties, RevenueOptions, Storage } from './client';
7
+ export type { AttributionInfo, DeepLink } from './attribution';
8
+ export type { NavigationRefLike } from './navigation';
9
+ export interface InitOptions extends ClientOptions {
10
+ /** Where the SDK keeps its IDs and offline queue, such as AsyncStorage. */
11
+ storage?: Storage;
12
+ /**
13
+ * Read the link that opened the app (Linking.getInitialURL) and links opened while it runs
14
+ * (Linking's `url` events). Default true. Turn it off to call handleDeepLink yourself.
15
+ */
16
+ deepLinks?: boolean;
17
+ }
18
+ export declare const KissMyApps: {
19
+ /** Starts the SDK once, as early as possible, with the project's client key. */
20
+ init(options: InitOptions): KmaClient;
21
+ /**
22
+ * Reports a link that opened the app. With `deepLinks` on (the default) the SDK already
23
+ * reads Linking, so call this only for links that reach the app another way. Returns false
24
+ * when the link is not sent (not an https link, attribution off, opted out).
25
+ */
26
+ handleDeepLink(url: string): boolean;
27
+ /**
28
+ * Where deep links go: the deferred one after an install, and one each time a link opens
29
+ * the app. Each is handed over once; one that arrives before a handler is set waits for it.
30
+ * Returns a function that removes the handler.
31
+ */
32
+ onDeepLink(handler: (link: DeepLink) => void): () => void;
33
+ track(name: string, properties?: Properties): void;
34
+ /**
35
+ * Records a payment: the amount in major units (9.99, not 999), negative for a refund, and
36
+ * its ISO 4217 currency code, such as `revenue(9.99, 'USD', { transactionId })`.
37
+ */
38
+ revenue(amount: number, currency: string, options?: RevenueOptions): void;
39
+ screen(name: string, properties?: Properties): void;
40
+ identify(userId: string | number, traits?: Properties): void;
41
+ setTraits(traits: Properties): void;
42
+ reset(): void;
43
+ flush(): Promise<void>;
44
+ optOut(): void;
45
+ optIn(): void;
46
+ getAnonymousId(): string | null;
47
+ getSessionId(): string | null;
48
+ };
49
+ /**
50
+ * Screen views from React Navigation:
51
+ * `<NavigationContainer ref={ref} {...trackNavigation(ref)}>`.
52
+ */
53
+ export declare function trackNavigation(ref: NavigationRefLike): {
54
+ onReady: () => void;
55
+ onStateChange: () => void;
56
+ };
57
+ export default KissMyApps;
package/lib/index.js ADDED
@@ -0,0 +1,154 @@
1
+ "use strict";
2
+ // KissMyApps analytics for React Native: sessions, installs, opens, screens and your own
3
+ // events, sent to your KissMyApps project, plus install attribution and deep links. Plain
4
+ // JavaScript; the optional native module KissMyAppsAttribution adds the device key, the
5
+ // Google Play install referrer and the Apple Ads token when it is linked.
6
+ Object.defineProperty(exports, "__esModule", { value: true });
7
+ exports.KissMyApps = exports.SDK_VERSION = exports.KmaClient = void 0;
8
+ exports.trackNavigation = trackNavigation;
9
+ const react_native_1 = require("react-native");
10
+ const attribution_1 = require("./attribution");
11
+ const client_1 = require("./client");
12
+ const device_1 = require("./device");
13
+ const navigation_1 = require("./navigation");
14
+ var client_2 = require("./client");
15
+ Object.defineProperty(exports, "KmaClient", { enumerable: true, get: function () { return client_2.KmaClient; } });
16
+ Object.defineProperty(exports, "SDK_VERSION", { enumerable: true, get: function () { return client_2.SDK_VERSION; } });
17
+ /** The link that opened the app, unless Android reopened the activity from Recents. */
18
+ async function openingLink(native) {
19
+ const url = await react_native_1.Linking.getInitialURL();
20
+ if (!url || !(native === null || native === void 0 ? void 0 : native.launchedFromHistory))
21
+ return url;
22
+ const old = await native.launchedFromHistory().catch(() => false);
23
+ return old === true ? null : url;
24
+ }
25
+ /** The optional native module, when the app has it linked (not in Expo Go). */
26
+ function nativeAttribution() {
27
+ const module = react_native_1.NativeModules.KissMyAppsAttribution;
28
+ return module && typeof module.getAttributionInfo === 'function'
29
+ ? module
30
+ : null;
31
+ }
32
+ let client = null;
33
+ let deepLinkHandler = null;
34
+ // Calls made before init run once it is called.
35
+ const early = [];
36
+ function call(run) {
37
+ if (client)
38
+ run(client);
39
+ else if (early.length < 100)
40
+ early.push(run);
41
+ }
42
+ exports.KissMyApps = {
43
+ /** Starts the SDK once, as early as possible, with the project's client key. */
44
+ init(options) {
45
+ var _a, _b;
46
+ if (client)
47
+ return client;
48
+ const native = nativeAttribution();
49
+ // Linking is there in every React Native app; a test's stand-in may leave it out.
50
+ const links = options.deepLinks !== false &&
51
+ options.attribution !== false &&
52
+ Boolean(react_native_1.Linking === null || react_native_1.Linking === void 0 ? void 0 : react_native_1.Linking.getInitialURL);
53
+ const started = new client_1.KmaClient(options, {
54
+ storage: (_a = options.storage) !== null && _a !== void 0 ? _a : null,
55
+ device: device_1.deviceInfo,
56
+ fetch: (url, init) => fetch(url, init),
57
+ sdk: `kma-react-native/${client_1.SDK_VERSION}`,
58
+ initialLink: links ? () => openingLink(native) : undefined,
59
+ attributionInfo: native ? (request) => native.getAttributionInfo(request) : undefined,
60
+ });
61
+ client = started;
62
+ if (deepLinkHandler)
63
+ started.onDeepLink(deepLinkHandler);
64
+ if (react_native_1.AppState.currentState !== 'background')
65
+ started.foreground();
66
+ react_native_1.AppState.addEventListener('change', (state) => {
67
+ if (state === 'active')
68
+ started.foreground();
69
+ else if (state === 'background')
70
+ started.background();
71
+ });
72
+ if (links)
73
+ (_b = react_native_1.Linking.addEventListener) === null || _b === void 0 ? void 0 : _b.call(react_native_1.Linking, 'url', ({ url }) => started.handleDeepLink(url));
74
+ for (const run of early.splice(0))
75
+ run(started);
76
+ return started;
77
+ },
78
+ /**
79
+ * Reports a link that opened the app. With `deepLinks` on (the default) the SDK already
80
+ * reads Linking, so call this only for links that reach the app another way. Returns false
81
+ * when the link is not sent (not an https link, attribution off, opted out).
82
+ */
83
+ handleDeepLink(url) {
84
+ if (client)
85
+ return client.handleDeepLink(url);
86
+ if (!(0, attribution_1.httpsLink)(url))
87
+ return false;
88
+ call((kma) => kma.handleDeepLink(url));
89
+ return true;
90
+ },
91
+ /**
92
+ * Where deep links go: the deferred one after an install, and one each time a link opens
93
+ * the app. Each is handed over once; one that arrives before a handler is set waits for it.
94
+ * Returns a function that removes the handler.
95
+ */
96
+ onDeepLink(handler) {
97
+ deepLinkHandler = handler;
98
+ client === null || client === void 0 ? void 0 : client.onDeepLink(handler);
99
+ return () => {
100
+ if (deepLinkHandler !== handler)
101
+ return;
102
+ deepLinkHandler = null;
103
+ client === null || client === void 0 ? void 0 : client.onDeepLink(null);
104
+ };
105
+ },
106
+ track(name, properties) {
107
+ call((kma) => kma.track(name, properties));
108
+ },
109
+ /**
110
+ * Records a payment: the amount in major units (9.99, not 999), negative for a refund, and
111
+ * its ISO 4217 currency code, such as `revenue(9.99, 'USD', { transactionId })`.
112
+ */
113
+ revenue(amount, currency, options) {
114
+ call((kma) => kma.revenue(amount, currency, options));
115
+ },
116
+ screen(name, properties) {
117
+ call((kma) => kma.screen(name, properties));
118
+ },
119
+ identify(userId, traits) {
120
+ call((kma) => kma.identify(userId, traits));
121
+ },
122
+ setTraits(traits) {
123
+ call((kma) => kma.setTraits(traits));
124
+ },
125
+ reset() {
126
+ call((kma) => kma.reset());
127
+ },
128
+ flush() {
129
+ var _a;
130
+ return (_a = client === null || client === void 0 ? void 0 : client.flush()) !== null && _a !== void 0 ? _a : Promise.resolve();
131
+ },
132
+ optOut() {
133
+ call((kma) => kma.optOut());
134
+ },
135
+ optIn() {
136
+ call((kma) => kma.optIn());
137
+ },
138
+ getAnonymousId() {
139
+ var _a;
140
+ return (_a = client === null || client === void 0 ? void 0 : client.getAnonymousId()) !== null && _a !== void 0 ? _a : null;
141
+ },
142
+ getSessionId() {
143
+ var _a;
144
+ return (_a = client === null || client === void 0 ? void 0 : client.getSessionId()) !== null && _a !== void 0 ? _a : null;
145
+ },
146
+ };
147
+ /**
148
+ * Screen views from React Navigation:
149
+ * `<NavigationContainer ref={ref} {...trackNavigation(ref)}>`.
150
+ */
151
+ function trackNavigation(ref) {
152
+ return (0, navigation_1.navigationTracker)(ref, (name) => exports.KissMyApps.screen(name));
153
+ }
154
+ exports.default = exports.KissMyApps;
@@ -0,0 +1,10 @@
1
+ export interface NavigationRefLike {
2
+ getCurrentRoute(): {
3
+ name: string;
4
+ } | undefined;
5
+ }
6
+ /** Handlers for NavigationContainer's onReady and onStateChange that report each new screen. */
7
+ export declare function navigationTracker(ref: NavigationRefLike, onScreen: (name: string) => void): {
8
+ onReady: () => void;
9
+ onStateChange: () => void;
10
+ };
@@ -0,0 +1,18 @@
1
+ "use strict";
2
+ // Screen views from React Navigation, without depending on it: anything with
3
+ // getCurrentRoute(), such as the ref from createNavigationContainerRef(), works.
4
+ Object.defineProperty(exports, "__esModule", { value: true });
5
+ exports.navigationTracker = navigationTracker;
6
+ /** Handlers for NavigationContainer's onReady and onStateChange that report each new screen. */
7
+ function navigationTracker(ref, onScreen) {
8
+ let last;
9
+ const report = () => {
10
+ var _a;
11
+ const name = (_a = ref.getCurrentRoute()) === null || _a === void 0 ? void 0 : _a.name;
12
+ if (!name || name === last)
13
+ return;
14
+ last = name;
15
+ onScreen(name);
16
+ };
17
+ return { onReady: report, onStateChange: report };
18
+ }
package/package.json CHANGED
@@ -1,6 +1,45 @@
1
1
  {
2
2
  "name": "@kissmyappss/react-native",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "1.1.0",
4
+ "description": "KissMyApps analytics for React Native apps: sessions, installs, screens, events, install attribution and deep links.",
5
+ "license": "MIT",
6
+ "homepage": "https://kissmyapps.dev",
7
+ "main": "lib/index.js",
8
+ "types": "lib/index.d.ts",
9
+ "react-native": "src/index.ts",
10
+ "files": [
11
+ "lib",
12
+ "src",
13
+ "android/build.gradle",
14
+ "android/src",
15
+ "ios",
16
+ "KissMyAppsReactNative.podspec",
17
+ "react-native.config.js",
18
+ "README.md",
19
+ "CHANGELOG.md",
20
+ "LICENSE"
21
+ ],
22
+ "sideEffects": false,
23
+ "scripts": {
24
+ "build": "tsc -p tsconfig.build.json",
25
+ "prepack": "npm run build"
26
+ },
27
+ "peerDependencies": {
28
+ "react-native": ">=0.70"
29
+ },
30
+ "devDependencies": {
31
+ "typescript": "^5.6.0"
32
+ },
33
+ "keywords": [
34
+ "analytics",
35
+ "react-native",
36
+ "expo",
37
+ "mobile-analytics",
38
+ "deep-links",
39
+ "attribution",
40
+ "kissmyapps"
41
+ ],
42
+ "publishConfig": {
43
+ "access": "public"
44
+ }
45
+ }
@@ -0,0 +1,13 @@
1
+ // Autolinking for the optional native module KissMyAppsAttribution (React Native CLI and
2
+ // Expo prebuild). iOS finds KissMyAppsReactNative.podspec on its own.
3
+ module.exports = {
4
+ dependency: {
5
+ platforms: {
6
+ android: {
7
+ sourceDir: './android',
8
+ packageImportPath: 'import com.kissmyapps.reactnative.KissMyAppsAttributionPackage;',
9
+ packageInstance: 'new KissMyAppsAttributionPackage()',
10
+ },
11
+ },
12
+ },
13
+ }
@@ -0,0 +1,207 @@
1
+ // The two attribution calls every KissMyApps app SDK makes: one install call on the first
2
+ // launch, and one open call for each link that opens the app later. What goes in them, and
3
+ // what comes back, is the `attribution` section of
4
+ // integrations/analytics-mobile/contract/app-events.json.
5
+
6
+ /** A deep link from KissMyApps, handed to `onDeepLink` once. */
7
+ export interface DeepLink {
8
+ /** The link's deep link value, such as `lesson`, or null when it has only parameters. */
9
+ value: string | null
10
+ /** The deep link's parameters, such as `{ id: '4' }`. */
11
+ params: Record<string, string>
12
+ /** True when it came through an install (a deferred deep link), false when a link opened the app. */
13
+ deferred: boolean
14
+ /** The link that opened the app, or null when the deep link came from the store install. */
15
+ url: string | null
16
+ }
17
+
18
+ /** What the optional native module `KissMyAppsAttribution` reads on the device. */
19
+ export interface AttributionInfo {
20
+ /** Lowercase hex SHA-256 of identifierForVendor (iOS) or ANDROID_ID (Android). */
21
+ deviceKey?: string | null
22
+ /** The Google Play install referrer (Android). */
23
+ referrer?: string | null
24
+ /** Seconds since 1970, from the Install Referrer API (Android). */
25
+ referrerClickTs?: number | null
26
+ /** Seconds since 1970, from the Install Referrer API (Android). */
27
+ installBeginTs?: number | null
28
+ /** AAAttribution.attributionToken() (iOS 14.3+). */
29
+ appleAdsToken?: string | null
30
+ /** The click ID after `kma:` on the clipboard, read only when clipboard handoff is on (iOS). */
31
+ clipboardClick?: string | null
32
+ /** True when Google Play did not answer in time: the next try reads the referrer again. */
33
+ retryReferrer?: boolean
34
+ }
35
+
36
+ /** What the SDK asks the native module for. */
37
+ export interface AttributionRequest {
38
+ /** The first launch: also the install referrer or Apple Ads token; otherwise the device key only. */
39
+ install: boolean
40
+ /** Read a `kma:` click ID from the clipboard (iOS, clipboard handoff on). */
41
+ clipboard: boolean
42
+ }
43
+
44
+ export const INSTALL_PATH = '/v1/attribution/install'
45
+ export const OPEN_PATH = '/v1/attribution/open'
46
+
47
+ const MAX_URL = 2048
48
+ const MAX_PARAMS = 10
49
+ const MAX_REFERRER = 1024
50
+ const MAX_APPLE_ADS = 4096
51
+ const DEVICE_KEY = /^[0-9a-f]{64}$/
52
+ const CLICK_ID = /^[A-Za-z0-9_-]{16,40}$/
53
+ // React Native's URL class leaves most of its parts unimplemented, so links are read by hand.
54
+ const HTTPS_URL = /^https:\/\/[^\s/?#@]+(?:[/?#]\S*)?$/i
55
+
56
+ /** The link as the SDK sends it: an https URL of at most 2,048 characters, or null. */
57
+ export function httpsLink(value: unknown): string | null {
58
+ if (typeof value !== 'string') return null
59
+ const link = value.trim()
60
+ return link.length <= MAX_URL && HTTPS_URL.test(link) ? link : null
61
+ }
62
+
63
+ function text(value: unknown, max: number): string | null {
64
+ return typeof value === 'string' && value.length > 0 && value.length <= max ? value : null
65
+ }
66
+
67
+ function seconds(value: unknown): number | null {
68
+ // Play answers 0 when it does not know.
69
+ return typeof value === 'number' && Number.isFinite(value) && value > 0 ? Math.floor(value) : null
70
+ }
71
+
72
+ /** The device key when it is one: 64 lowercase hex characters. */
73
+ export function deviceKey(value: unknown): string | null {
74
+ return typeof value === 'string' && DEVICE_KEY.test(value) ? value : null
75
+ }
76
+
77
+ export interface InstallInput {
78
+ anonymousId: string
79
+ sessionId: string
80
+ platform: 'ios' | 'android'
81
+ /** When app_installed was queued, in milliseconds since 1970. */
82
+ installedAt: number
83
+ sdk: string
84
+ userId?: string | null
85
+ appVersion?: string
86
+ /** The link that opened the app on this launch, if any. */
87
+ link?: string | null
88
+ info: AttributionInfo
89
+ /** Whether the app turned clipboard handoff on. */
90
+ clipboard: boolean
91
+ }
92
+
93
+ /** The body of POST /v1/attribution/install. */
94
+ export function installBody(input: InstallInput): Record<string, unknown> {
95
+ const { info } = input
96
+ const body: Record<string, unknown> = {
97
+ anonymous_id: input.anonymousId,
98
+ session_id: input.sessionId,
99
+ platform: input.platform,
100
+ installed_at: new Date(input.installedAt).toISOString(),
101
+ sdk: input.sdk,
102
+ }
103
+ if (input.userId) body.user_id = input.userId
104
+ if (input.appVersion) body.app_version = input.appVersion
105
+ const key = deviceKey(info.deviceKey)
106
+ if (key) body.device_key = key
107
+ const link = httpsLink(input.link)
108
+ if (link) body.link_url = link
109
+ if (input.platform === 'android') {
110
+ // A longer referrer is cut to the contract's 1,024 characters.
111
+ const referrer =
112
+ typeof info.referrer === 'string' && info.referrer
113
+ ? info.referrer.slice(0, MAX_REFERRER)
114
+ : null
115
+ const clicked = seconds(info.referrerClickTs)
116
+ const began = seconds(info.installBeginTs)
117
+ if (referrer) body.referrer = referrer
118
+ if (clicked !== null) body.referrer_click_ts = clicked
119
+ if (began !== null) body.install_begin_ts = began
120
+ } else {
121
+ const appleAds = text(info.appleAdsToken, MAX_APPLE_ADS)
122
+ if (appleAds) body.apple_ads_token = appleAds
123
+ const click = typeof info.clipboardClick === 'string' ? info.clipboardClick.trim() : ''
124
+ if (input.clipboard && CLICK_ID.test(click)) body.clipboard_click = click
125
+ }
126
+ return body
127
+ }
128
+
129
+ export interface OpenInput {
130
+ anonymousId: string
131
+ sessionId: string
132
+ platform: 'ios' | 'android'
133
+ url: string
134
+ /** When the link opened the app, in milliseconds since 1970. */
135
+ openedAt: number
136
+ sdk: string
137
+ userId?: string | null
138
+ appVersion?: string
139
+ deviceKey?: string | null
140
+ }
141
+
142
+ /** The body of POST /v1/attribution/open. */
143
+ export function openBody(input: OpenInput): Record<string, unknown> {
144
+ const body: Record<string, unknown> = {
145
+ anonymous_id: input.anonymousId,
146
+ session_id: input.sessionId,
147
+ platform: input.platform,
148
+ url: input.url,
149
+ opened_at: new Date(input.openedAt).toISOString(),
150
+ sdk: input.sdk,
151
+ }
152
+ if (input.userId) body.user_id = input.userId
153
+ if (input.appVersion) body.app_version = input.appVersion
154
+ const key = deviceKey(input.deviceKey)
155
+ if (key) body.device_key = key
156
+ return body
157
+ }
158
+
159
+ /** The deep link in an answer from either call, or null when it has none. */
160
+ export function deepLinkFrom(answer: unknown, url: string | null): DeepLink | null {
161
+ if (!answer || typeof answer !== 'object') return null
162
+ const link = (answer as { deep_link?: unknown }).deep_link
163
+ if (!link || typeof link !== 'object' || Array.isArray(link)) return null
164
+ const { value, params, deferred } = link as Record<string, unknown>
165
+ const clean: Record<string, string> = {}
166
+ if (params && typeof params === 'object' && !Array.isArray(params)) {
167
+ for (const [name, item] of Object.entries(params)) {
168
+ if (Object.keys(clean).length >= MAX_PARAMS) break
169
+ // Text as it is; numbers and true/false as text; anything else is left out.
170
+ if (typeof item === 'string' || typeof item === 'number' || typeof item === 'boolean') {
171
+ clean[name] = String(item)
172
+ }
173
+ }
174
+ }
175
+ return {
176
+ value: typeof value === 'string' ? value : null,
177
+ params: clean,
178
+ deferred: deferred === true,
179
+ url,
180
+ }
181
+ }
182
+
183
+ /** The answer's JSON, or null when it is not JSON. */
184
+ export function parseAnswer(body: string): unknown {
185
+ try {
186
+ return JSON.parse(body)
187
+ } catch {
188
+ return null
189
+ }
190
+ }
191
+
192
+ /** Settles with the promise's value, or with `fallback` after `ms` or when it fails. */
193
+ export function within<T>(promise: Promise<T>, ms: number, fallback: T): Promise<T> {
194
+ return new Promise((resolve) => {
195
+ const timer = setTimeout(() => resolve(fallback), ms)
196
+ promise.then(
197
+ (value) => {
198
+ clearTimeout(timer)
199
+ resolve(value)
200
+ },
201
+ () => {
202
+ clearTimeout(timer)
203
+ resolve(fallback)
204
+ },
205
+ )
206
+ })
207
+ }