@ethicly/react-native 0.0.0-stage → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (70) hide show
  1. package/CHANGELOG.md +75 -0
  2. package/LICENSE +21 -0
  3. package/README.md +313 -2
  4. package/core/package.json +6 -0
  5. package/interstitial/package.json +6 -0
  6. package/lib/commonjs/core/adapters.js +287 -0
  7. package/lib/commonjs/core/beacons.js +70 -0
  8. package/lib/commonjs/core/cache.js +206 -0
  9. package/lib/commonjs/core/click.js +19 -0
  10. package/lib/commonjs/core/client.js +489 -0
  11. package/lib/commonjs/core/config.js +113 -0
  12. package/lib/commonjs/core/http.js +115 -0
  13. package/lib/commonjs/core/index.js +20 -0
  14. package/lib/commonjs/core/outbox.js +192 -0
  15. package/lib/commonjs/core/tracker.js +374 -0
  16. package/lib/commonjs/core/types.js +4 -0
  17. package/lib/commonjs/index.js +22 -0
  18. package/lib/commonjs/interstitial.js +7 -0
  19. package/lib/commonjs/react/EthiclyInterstitial.js +286 -0
  20. package/lib/commonjs/react/useEthiclyInterstitial.js +54 -0
  21. package/lib/commonjs/version.js +5 -0
  22. package/lib/module/core/adapters.js +276 -0
  23. package/lib/module/core/beacons.js +64 -0
  24. package/lib/module/core/cache.js +202 -0
  25. package/lib/module/core/click.js +15 -0
  26. package/lib/module/core/client.js +485 -0
  27. package/lib/module/core/config.js +104 -0
  28. package/lib/module/core/http.js +105 -0
  29. package/lib/module/core/index.js +6 -0
  30. package/lib/module/core/outbox.js +186 -0
  31. package/lib/module/core/tracker.js +370 -0
  32. package/lib/module/core/types.js +3 -0
  33. package/lib/module/index.js +4 -0
  34. package/lib/module/interstitial.js +3 -0
  35. package/lib/module/react/EthiclyInterstitial.js +260 -0
  36. package/lib/module/react/useEthiclyInterstitial.js +51 -0
  37. package/lib/module/version.js +2 -0
  38. package/lib/typescript/core/adapters.d.ts +138 -0
  39. package/lib/typescript/core/beacons.d.ts +32 -0
  40. package/lib/typescript/core/cache.d.ts +53 -0
  41. package/lib/typescript/core/click.d.ts +8 -0
  42. package/lib/typescript/core/client.d.ts +58 -0
  43. package/lib/typescript/core/config.d.ts +24 -0
  44. package/lib/typescript/core/http.d.ts +34 -0
  45. package/lib/typescript/core/index.d.ts +8 -0
  46. package/lib/typescript/core/outbox.d.ts +56 -0
  47. package/lib/typescript/core/tracker.d.ts +95 -0
  48. package/lib/typescript/core/types.d.ts +170 -0
  49. package/lib/typescript/index.d.ts +3 -0
  50. package/lib/typescript/interstitial.d.ts +2 -0
  51. package/lib/typescript/react/EthiclyInterstitial.d.ts +39 -0
  52. package/lib/typescript/react/useEthiclyInterstitial.d.ts +20 -0
  53. package/lib/typescript/version.d.ts +2 -0
  54. package/package.json +101 -4
  55. package/src/core/adapters.ts +337 -0
  56. package/src/core/beacons.ts +81 -0
  57. package/src/core/cache.ts +216 -0
  58. package/src/core/click.ts +16 -0
  59. package/src/core/client.ts +547 -0
  60. package/src/core/config.ts +111 -0
  61. package/src/core/http.ts +115 -0
  62. package/src/core/index.ts +14 -0
  63. package/src/core/outbox.ts +193 -0
  64. package/src/core/tracker.ts +371 -0
  65. package/src/core/types.ts +180 -0
  66. package/src/index.ts +5 -0
  67. package/src/interstitial.ts +4 -0
  68. package/src/react/EthiclyInterstitial.tsx +386 -0
  69. package/src/react/useEthiclyInterstitial.ts +74 -0
  70. package/src/version.ts +2 -0
@@ -0,0 +1,260 @@
1
+ import { jsx as _jsx, Fragment as _Fragment, jsxs as _jsxs } from "react/jsx-runtime";
2
+ // Optional ready-made fullscreen screen. Needs expo-video (Expo SDK 52+).
3
+ // Layout follows a typical in-app video player: 9:16 video, a skip control that counts
4
+ // down then reads "Skip Ad", a white call-to-action button, an optional
5
+ // "Remove ads" slot and a small "Sponsored by Ethicly.ch" line under it.
6
+ // Video starts with sound unless interstitial.audio is 'none' or 'optional'.
7
+ // The controls keep clear of the notch, status bar and home indicator: see
8
+ // useSafeInsets below.
9
+ import React, { useCallback, useContext, useEffect, useRef, useState } from 'react';
10
+ import { AppState, BackHandler, Image, Modal, Platform, Pressable, StatusBar, StyleSheet, Text, View, } from 'react-native';
11
+ import { useVideoPlayer, VideoView } from 'expo-video';
12
+ const TICK_MS = 250;
13
+ /** Space between the safe area and the controls. */
14
+ const TOP_GAP = 12;
15
+ const BOTTOM_GAP = 10;
16
+ const SIDE_GAP_TOP = 16;
17
+ const SIDE_GAP_BOTTOM = 20;
18
+ /**
19
+ * The 0.1 layout (controls 56 from the top, 44 from the bottom) is a floor:
20
+ * insets only ever move the controls inward, so a phone without a notch or a
21
+ * tall status bar looks exactly as before.
22
+ */
23
+ const MIN_TOP = 56;
24
+ const MIN_BOTTOM = 44;
25
+ /**
26
+ * react-native-safe-area-context when the app has it, else null. Metro treats
27
+ * a require inside try/catch as an optional dependency (the React Native and
28
+ * Expo Metro configs set allowOptionalDependencies), so an app without the
29
+ * package still builds.
30
+ */
31
+ function loadSafeArea() {
32
+ try {
33
+ // @ts-ignore: the build compiles without Node's types, where require is undeclared.
34
+ return typeof require === 'function' ? require('react-native-safe-area-context') : null;
35
+ }
36
+ catch {
37
+ return null;
38
+ }
39
+ }
40
+ const safeArea = loadSafeArea();
41
+ const noInsets = React.createContext(null);
42
+ // Read with useContext, which returns null without a SafeAreaProvider instead
43
+ // of throwing like useSafeAreaInsets(). Fixed at load, so hook order never changes.
44
+ const InsetsContext = safeArea && safeArea.SafeAreaInsetsContext && typeof safeArea.SafeAreaInsetsContext === 'object'
45
+ ? safeArea.SafeAreaInsetsContext
46
+ : noInsets;
47
+ function validInsets(v) {
48
+ const i = v;
49
+ if (!i || typeof i !== 'object')
50
+ return null;
51
+ const n = (x) => (typeof x === 'number' && Number.isFinite(x) && x >= 0 ? x : 0);
52
+ if (typeof i.top !== 'number' && typeof i.bottom !== 'number')
53
+ return null;
54
+ return { top: n(i.top), bottom: n(i.bottom), left: n(i.left), right: n(i.right) };
55
+ }
56
+ /** The `insets` prop, else the provider's insets, else the window's first metrics, else the status bar. */
57
+ function useSafeInsets(prop) {
58
+ var _a, _b, _c, _d, _e;
59
+ const fromProvider = useContext(InsetsContext);
60
+ return (_d = (_b = (_a = validInsets(prop)) !== null && _a !== void 0 ? _a : validInsets(fromProvider)) !== null && _b !== void 0 ? _b : validInsets((_c = safeArea === null || safeArea === void 0 ? void 0 : safeArea.initialWindowMetrics) === null || _c === void 0 ? void 0 : _c.insets)) !== null && _d !== void 0 ? _d : { top: Platform.OS === 'android' ? (_e = StatusBar.currentHeight) !== null && _e !== void 0 ? _e : 0 : 0, bottom: 0, left: 0, right: 0 };
61
+ }
62
+ export function EthiclyInterstitial(props) {
63
+ // Android back: a Modal receives it through onRequestClose, an inline screen
64
+ // through BackHandler. Either way it closes the ad only once Skip is allowed,
65
+ // and is swallowed before that.
66
+ const backRef = useRef(null);
67
+ const inline = props.modal === false;
68
+ useEffect(() => {
69
+ if (!inline)
70
+ return undefined;
71
+ const sub = BackHandler.addEventListener('hardwareBackPress', () => {
72
+ var _a;
73
+ (_a = backRef.current) === null || _a === void 0 ? void 0 : _a.call(backRef);
74
+ return true;
75
+ });
76
+ return () => sub.remove();
77
+ }, [inline]);
78
+ const body = _jsx(InterstitialBody, { ...props, backRef: backRef });
79
+ if (inline)
80
+ return body;
81
+ return (_jsx(Modal, { visible: true, animationType: "fade", presentationStyle: "fullScreen", statusBarTranslucent: true, onRequestClose: () => { var _a; return (_a = backRef.current) === null || _a === void 0 ? void 0 : _a.call(backRef); }, children: body }));
82
+ }
83
+ function useAppActive() {
84
+ const [active, setActive] = useState(AppState.currentState === 'active');
85
+ useEffect(() => {
86
+ const sub = AppState.addEventListener('change', (s) => setActive(s === 'active'));
87
+ return () => sub.remove();
88
+ }, []);
89
+ return active;
90
+ }
91
+ function InterstitialBody({ ad, tracker, onClose, onRemoveAds, removeAdsLabel, renderBelowButton, skipStyle, skipTextStyle, insets, backRef, }) {
92
+ const safe = useSafeInsets(insets);
93
+ const isVideo = ad.media.kind === 'video' && !!ad.media.videoUri;
94
+ const appActive = useAppActive();
95
+ const activeRef = useRef(appActive);
96
+ activeRef.current = appActive;
97
+ const [positionMs, setPositionMs] = useState(0);
98
+ const [ended, setEnded] = useState(false);
99
+ const [failed, setFailed] = useState(false);
100
+ const [muted, setMuted] = useState(ad.audio !== 'on');
101
+ /** Wall-clock time on screen with the app in the foreground. */
102
+ const [onScreenMs, setOnScreenMs] = useState(0);
103
+ const [clicked, setClicked] = useState(false);
104
+ const positionRef = useRef(0);
105
+ const closedRef = useRef(false);
106
+ const player = useVideoPlayer(isVideo ? ad.media.videoUri : null, (p) => {
107
+ p.loop = false;
108
+ p.muted = ad.audio !== 'on';
109
+ p.timeUpdateEventInterval = TICK_MS / 1000;
110
+ p.play();
111
+ });
112
+ const onCloseRef = useRef(onClose);
113
+ onCloseRef.current = onClose;
114
+ // The impression goes out the moment the ad is on screen. shown() refuses an
115
+ // ad past its token lifetime (nothing is recorded), so the screen closes
116
+ // itself instead of playing an ad nobody is paid for.
117
+ useEffect(() => {
118
+ const expired = tracker.isExpired();
119
+ void tracker.shown();
120
+ if (expired && !closedRef.current) {
121
+ closedRef.current = true;
122
+ void tracker.closed();
123
+ onCloseRef.current();
124
+ }
125
+ }, [tracker]);
126
+ // Video: playback position drives viewability, quartiles and the skip countdown.
127
+ useEffect(() => {
128
+ if (!isVideo)
129
+ return undefined;
130
+ const subs = [
131
+ player.addListener('timeUpdate', ({ currentTime }) => {
132
+ const ms = Math.max(0, currentTime * 1000);
133
+ positionRef.current = ms;
134
+ setPositionMs(ms);
135
+ const durationMs = player.duration > 0 ? player.duration * 1000 : undefined;
136
+ tracker.progress(ms, { visible: activeRef.current && player.playing, durationMs });
137
+ }),
138
+ player.addListener('playToEnd', () => {
139
+ setEnded(true);
140
+ tracker.complete();
141
+ }),
142
+ player.addListener('statusChange', ({ status }) => {
143
+ if (status === 'error') {
144
+ setFailed(true);
145
+ tracker.error();
146
+ }
147
+ }),
148
+ ];
149
+ return () => subs.forEach((s) => s.remove());
150
+ }, [isVideo, player, tracker]);
151
+ // Time on screen while the app is in the foreground. For a still image it is
152
+ // the playback position; for a video it is the skip countdown's fallback, so
153
+ // Skip still appears after skipAfterMs if the video stalls or never starts.
154
+ useEffect(() => {
155
+ let shownMs = 0;
156
+ const id = setInterval(() => {
157
+ if (activeRef.current)
158
+ shownMs += TICK_MS;
159
+ setOnScreenMs(shownMs);
160
+ if (isVideo)
161
+ return;
162
+ positionRef.current = shownMs;
163
+ setPositionMs(shownMs);
164
+ tracker.progress(shownMs, { visible: activeRef.current });
165
+ }, TICK_MS);
166
+ return () => clearInterval(id);
167
+ }, [isVideo, tracker]);
168
+ useEffect(() => {
169
+ if (!isVideo)
170
+ return;
171
+ if (appActive && !ended)
172
+ player.play();
173
+ else
174
+ player.pause();
175
+ }, [appActive, ended, isVideo, player]);
176
+ // Leaving the foreground ends continuous visibility right away, without
177
+ // waiting for the next player tick (which may never come while paused).
178
+ useEffect(() => {
179
+ if (appActive)
180
+ return;
181
+ const durationMs = isVideo && player.duration > 0 ? player.duration * 1000 : undefined;
182
+ tracker.progress(positionRef.current, { visible: false, durationMs });
183
+ }, [appActive, isVideo, player, tracker]);
184
+ // The tracker is closed only from close() below (or by the hook's dismiss()),
185
+ // never from an effect cleanup: React StrictMode runs every cleanup once on
186
+ // mount, and a closed tracker drops /viewable and the video events.
187
+ const close = useCallback(() => {
188
+ if (closedRef.current)
189
+ return;
190
+ closedRef.current = true;
191
+ if (isVideo && !ended && !failed)
192
+ tracker.skipped(positionRef.current);
193
+ void tracker.closed();
194
+ onClose();
195
+ }, [ended, failed, isVideo, onClose, tracker]);
196
+ const onCta = useCallback(() => {
197
+ if (isVideo)
198
+ player.pause();
199
+ // Once the user has visited the advertiser, they can always close the ad
200
+ // when they come back.
201
+ setClicked(true);
202
+ void tracker.clicked();
203
+ }, [isVideo, player, tracker]);
204
+ const toggleSound = useCallback(() => {
205
+ setMuted((m) => {
206
+ player.muted = !m;
207
+ return !m;
208
+ });
209
+ }, [player]);
210
+ const remainingS = Math.ceil(Math.max(0, ad.skipAfterMs - Math.max(positionMs, onScreenMs)) / 1000);
211
+ const canSkip = remainingS === 0 || ended || failed || clicked;
212
+ backRef.current = canSkip ? close : null;
213
+ return (_jsxs(View, { style: styles.root, children: [isVideo ? (_jsxs(_Fragment, { children: [ad.media.posterUri ? _jsx(Image, { source: { uri: ad.media.posterUri }, style: StyleSheet.absoluteFill, resizeMode: "cover" }) : null, _jsx(VideoView, { player: player, style: StyleSheet.absoluteFill, contentFit: "cover", nativeControls: false, allowsFullscreen: false, allowsPictureInPicture: false })] })) : (_jsx(Image, { source: { uri: ad.media.uri }, style: StyleSheet.absoluteFill, resizeMode: "cover" })), _jsxs(View, { style: [styles.topRow, { top: Math.max(safe.top + TOP_GAP, MIN_TOP), left: safe.left + SIDE_GAP_TOP, right: safe.right + SIDE_GAP_TOP }], pointerEvents: "box-none", children: [_jsxs(View, { style: styles.leftGroup, children: [_jsx(Text, { style: styles.adLabel, accessibilityRole: "text", children: "Ad" }), isVideo && ad.audio !== 'none' ? (_jsx(Pressable, { onPress: toggleSound, style: styles.soundButton, accessibilityRole: "button", accessibilityLabel: muted ? 'Turn sound on' : 'Mute', hitSlop: 8, children: _jsx(Text, { style: styles.soundText, children: muted ? 'Sound off' : 'Sound on' }) })) : null] }), _jsx(Pressable, { onPress: canSkip ? close : undefined, disabled: !canSkip, style: [styles.skip, skipStyle], accessibilityRole: "button", accessibilityLabel: canSkip ? 'Skip ad' : `Skip in ${remainingS} seconds`, hitSlop: 8, children: canSkip ? (_jsxs(View, { style: styles.skipRow, children: [_jsx(Text, { style: [styles.skipText, skipTextStyle], children: "Skip Ad" }), _jsx(SkipIcon, {})] })) : (_jsx(Text, { style: [styles.skipText, styles.skipTextWaiting, skipTextStyle], children: `Skip in ${remainingS}` })) })] }), _jsxs(View, { style: [styles.bottom, {
214
+ bottom: Math.max(safe.bottom + BOTTOM_GAP, MIN_BOTTOM), left: safe.left + SIDE_GAP_BOTTOM, right: safe.right + SIDE_GAP_BOTTOM,
215
+ }], pointerEvents: "box-none", children: [_jsx(Pressable, { onPress: onCta, style: ({ pressed }) => [styles.cta, pressed && styles.ctaPressed], accessibilityRole: "link", children: _jsx(Text, { style: styles.ctaText, numberOfLines: 1, children: ad.ctaLabel || 'Learn more' }) }), renderBelowButton ? renderBelowButton() : onRemoveAds ? (_jsx(Pressable, { onPress: onRemoveAds, accessibilityRole: "button", hitSlop: 8, children: _jsx(Text, { style: styles.removeAds, children: removeAdsLabel || 'Remove ads' }) })) : null, _jsx(Text, { style: styles.sponsor, children: "Sponsored by Ethicly.ch" })] })] }));
216
+ }
217
+ /** Skip-to-end mark (a play triangle against a bar), drawn so it never depends on a font glyph. */
218
+ function SkipIcon() {
219
+ return (_jsxs(View, { style: styles.skipIcon, accessibilityElementsHidden: true, importantForAccessibility: "no-hide-descendants", children: [_jsx(View, { style: styles.skipTriangle }), _jsx(View, { style: styles.skipBar })] }));
220
+ }
221
+ const styles = StyleSheet.create({
222
+ root: { flex: 1, backgroundColor: '#000' },
223
+ topRow: {
224
+ position: 'absolute',
225
+ flexDirection: 'row', justifyContent: 'space-between', alignItems: 'center',
226
+ },
227
+ leftGroup: { flexDirection: 'row', alignItems: 'center' },
228
+ adLabel: {
229
+ color: '#fff', fontSize: 11, fontWeight: '600', letterSpacing: 0.5,
230
+ backgroundColor: 'rgba(0,0,0,0.45)', paddingHorizontal: 6, paddingVertical: 2, borderRadius: 4, overflow: 'hidden',
231
+ },
232
+ soundButton: { marginLeft: 8, backgroundColor: 'rgba(0,0,0,0.45)', paddingHorizontal: 8, paddingVertical: 4, borderRadius: 6 },
233
+ soundText: { color: '#fff', fontSize: 12, fontWeight: '500' },
234
+ // Solid black, no blur or translucency. The faint hairline keeps the edge
235
+ // visible over a dark frame.
236
+ skip: {
237
+ backgroundColor: '#000', paddingHorizontal: 18, height: 40, borderRadius: 20,
238
+ justifyContent: 'center', alignItems: 'center',
239
+ borderWidth: StyleSheet.hairlineWidth, borderColor: 'rgba(255,255,255,0.22)',
240
+ },
241
+ skipRow: { flexDirection: 'row', alignItems: 'center' },
242
+ skipText: { color: '#fff', fontSize: 15, fontWeight: '500', letterSpacing: 0.2 },
243
+ skipTextWaiting: { opacity: 0.75 },
244
+ skipIcon: { flexDirection: 'row', alignItems: 'center', marginLeft: 10 },
245
+ skipTriangle: {
246
+ width: 0, height: 0,
247
+ borderTopWidth: 6, borderBottomWidth: 6, borderLeftWidth: 10,
248
+ borderTopColor: 'transparent', borderBottomColor: 'transparent', borderLeftColor: '#fff',
249
+ },
250
+ skipBar: { width: 2, height: 12, backgroundColor: '#fff', marginLeft: 2, borderRadius: 1 },
251
+ bottom: { position: 'absolute', alignItems: 'center' },
252
+ cta: {
253
+ alignSelf: 'stretch', backgroundColor: '#fff', borderRadius: 12, paddingVertical: 15,
254
+ alignItems: 'center', justifyContent: 'center',
255
+ },
256
+ ctaPressed: { opacity: 0.85 },
257
+ ctaText: { color: '#000', fontSize: 17, fontWeight: '600' },
258
+ removeAds: { color: '#fff', fontSize: 14, marginTop: 14, textDecorationLine: 'underline', opacity: 0.9 },
259
+ sponsor: { color: '#fff', fontSize: 12, marginTop: 10, opacity: 0.6 },
260
+ });
@@ -0,0 +1,51 @@
1
+ // React hook over the headless core. No React Native or Expo imports, so it
2
+ // works with any player the host app already has.
3
+ import { useCallback, useEffect, useRef, useState } from 'react';
4
+ export function useEthiclyInterstitial(ethicly, options = {}) {
5
+ var _a, _b;
6
+ const preload = options.preload !== false;
7
+ const [current, setCurrent] = useState(null);
8
+ const [reason, setReason] = useState(null);
9
+ const [loading, setLoading] = useState(false);
10
+ const mounted = useRef(true);
11
+ const currentRef = useRef(current);
12
+ currentRef.current = current;
13
+ useEffect(() => {
14
+ mounted.current = true;
15
+ if (preload)
16
+ void ethicly.preload();
17
+ return () => {
18
+ var _a;
19
+ mounted.current = false;
20
+ void ((_a = currentRef.current) === null || _a === void 0 ? void 0 : _a.tracker.closed());
21
+ };
22
+ }, [ethicly, preload]);
23
+ const show = useCallback(async () => {
24
+ setLoading(true);
25
+ try {
26
+ const r = await ethicly.loadInterstitial();
27
+ if (!mounted.current)
28
+ return false;
29
+ if (r.ad) {
30
+ setCurrent({ ad: r.ad, tracker: r.tracker });
31
+ setReason(null);
32
+ return true;
33
+ }
34
+ setReason(r.reason);
35
+ return false;
36
+ }
37
+ finally {
38
+ if (mounted.current)
39
+ setLoading(false);
40
+ }
41
+ }, [ethicly]);
42
+ const dismiss = useCallback(() => {
43
+ var _a;
44
+ void ((_a = currentRef.current) === null || _a === void 0 ? void 0 : _a.tracker.closed());
45
+ setCurrent(null);
46
+ if (preload)
47
+ void ethicly.preload();
48
+ }, [ethicly, preload]);
49
+ const canShow = useCallback(() => ethicly.canShow(), [ethicly]);
50
+ return { ad: (_a = current === null || current === void 0 ? void 0 : current.ad) !== null && _a !== void 0 ? _a : null, tracker: (_b = current === null || current === void 0 ? void 0 : current.tracker) !== null && _b !== void 0 ? _b : null, reason, loading, show, dismiss, canShow };
51
+ }
@@ -0,0 +1,2 @@
1
+ /** SDK version, sent as sdk_version and in X-Ethicly-SDK. Keep in step with package.json. */
2
+ export const SDK_VERSION = '0.2.0';
@@ -0,0 +1,138 @@
1
+ import type { FileCacheAdapter, KeyValueStorage, Logger } from './types';
2
+ /** In-memory key-value store. Lost when the process ends. */
3
+ export declare function createMemoryStorage(): KeyValueStorage & {
4
+ data: Map<string, string>;
5
+ };
6
+ /**
7
+ * In-memory "cache" that downloads nothing: the uri it returns is the remote
8
+ * URL, so the player streams. The default when no fileCache is given.
9
+ */
10
+ export declare function createMemoryFileCache(): FileCacheAdapter;
11
+ /** The legacy expo-file-system API (SDK 50 to 53, or `expo-file-system/legacy` on 54+). */
12
+ export interface ExpoFileSystemLike {
13
+ cacheDirectory: string | null;
14
+ downloadAsync(url: string, fileUri: string): Promise<{
15
+ uri: string;
16
+ status: number;
17
+ }>;
18
+ getInfoAsync(fileUri: string, options?: {
19
+ md5?: boolean;
20
+ size?: boolean;
21
+ }): Promise<{
22
+ exists: boolean;
23
+ size?: number;
24
+ }>;
25
+ deleteAsync(fileUri: string, options?: {
26
+ idempotent?: boolean;
27
+ }): Promise<void>;
28
+ makeDirectoryAsync(fileUri: string, options?: {
29
+ intermediates?: boolean;
30
+ }): Promise<void>;
31
+ readDirectoryAsync?(fileUri: string): Promise<string[]>;
32
+ createDownloadResumable?(url: string, fileUri: string, options?: Record<string, unknown>, callback?: (p: {
33
+ totalBytesWritten: number;
34
+ totalBytesExpectedToWrite: number;
35
+ }) => void): {
36
+ downloadAsync(): Promise<{
37
+ uri: string;
38
+ status: number;
39
+ } | undefined>;
40
+ cancelAsync?(): Promise<void>;
41
+ pauseAsync(): Promise<unknown>;
42
+ };
43
+ }
44
+ /** A file or directory of the object API (`File`, `Directory`) of expo-file-system 19+ (Expo SDK 54+). */
45
+ export interface ExpoFsEntryLike {
46
+ readonly uri: string;
47
+ readonly name?: string;
48
+ readonly exists: boolean;
49
+ delete(): void;
50
+ }
51
+ export interface ExpoFsFileLike extends ExpoFsEntryLike {
52
+ readonly size: number | null;
53
+ }
54
+ export interface ExpoFsDirectoryLike extends ExpoFsEntryLike {
55
+ create(options?: {
56
+ intermediates?: boolean;
57
+ idempotent?: boolean;
58
+ }): void;
59
+ list(): ExpoFsEntryLike[];
60
+ }
61
+ /**
62
+ * The object API that `expo-file-system` exports from Expo SDK 54 on. Its root
63
+ * export still has functions named like the legacy ones, but they throw at
64
+ * runtime, so this shape is checked first.
65
+ */
66
+ export interface ExpoFileSystemModernLike {
67
+ File: {
68
+ new (...uris: any[]): ExpoFsFileLike;
69
+ downloadFileAsync(url: string, destination: any, options?: {
70
+ idempotent?: boolean;
71
+ }): Promise<unknown>;
72
+ /** Newer versions: a download with progress and cancel. */
73
+ createDownloadTask?(url: string, destination: any, options?: {
74
+ onProgress?: (p: {
75
+ bytesWritten: number;
76
+ totalBytes: number;
77
+ }) => void;
78
+ }): {
79
+ downloadAsync(): Promise<unknown>;
80
+ cancel(): void;
81
+ };
82
+ };
83
+ Directory: {
84
+ new (...uris: any[]): ExpoFsDirectoryLike;
85
+ };
86
+ Paths: {
87
+ readonly cache: {
88
+ readonly uri: string;
89
+ };
90
+ };
91
+ }
92
+ /**
93
+ * Creative cache on disk via expo-file-system. Pass the module as your app
94
+ * imports it, on any Expo SDK from 50; the adapter works out which API it has:
95
+ * import * as FileSystem from 'expo-file-system'; // or 'expo-file-system/legacy'
96
+ * createEthicly({ ..., fileCache: createExpoFileCache(FileSystem) })
97
+ */
98
+ export declare const DEFAULT_CACHE_SUBDIRECTORY = "ethicly-ads/";
99
+ /**
100
+ * The cache sweep deletes every file in this directory that the SDK's index
101
+ * does not list, so it must be a folder of its own: one plain name directly
102
+ * under the app's cache directory. An empty, nested or traversing name ('',
103
+ * '/', '..', 'a/b') would point the sweep at the host app's files, so anything
104
+ * else falls back to the default rather than risk deleting them.
105
+ */
106
+ export declare function safeCacheSubdirectory(subdirectory: unknown): string;
107
+ /**
108
+ * A file cache over either expo-file-system API: the object API of SDK 54+
109
+ * (`File`, `Directory`, `Paths`), else the legacy functions (`getInfoAsync`,
110
+ * `downloadAsync`, ...). Anything else gets the streaming cache, which writes
111
+ * nothing to disk, and one warning through `logger` (default `console`).
112
+ */
113
+ export declare function createExpoFileCache(fs: ExpoFileSystemLike | ExpoFileSystemModernLike, subdirectory?: string, logger?: Logger): FileCacheAdapter;
114
+ /**
115
+ * True only in a React Native release build (`__DEV__ === false`). Where
116
+ * `__DEV__` is not defined at all the code is not running from a Metro bundle
117
+ * (a Node script such as scripts/live-test.mjs, or tests), which is never a
118
+ * shipped app, so that counts as not release.
119
+ */
120
+ export declare function isReleaseBuild(): boolean;
121
+ /** The part of React Native's AppState the client uses for sessions. */
122
+ export interface AppStateLike {
123
+ currentState?: string | null;
124
+ addEventListener(type: 'change', listener: (state: string) => void): {
125
+ remove(): void;
126
+ } | undefined | void;
127
+ }
128
+ /**
129
+ * React Native's AppState, or null outside React Native. The core takes no
130
+ * hard dependency on react-native: a require inside try/catch is an optional
131
+ * dependency for Metro (the React Native and Expo Metro configs both set
132
+ * allowOptionalDependencies), and in Node it simply fails and returns null.
133
+ */
134
+ export declare function defaultAppState(): AppStateLike | null;
135
+ /** Wrap a logger so a throwing logger can never reach the host app. */
136
+ export declare function safeLogger(logger: Logger | undefined): Required<Logger>;
137
+ /** UUID v4. Uses the platform RNG when there is one (Hermes has none by default). */
138
+ export declare function uuidv4(): string;
@@ -0,0 +1,32 @@
1
+ import { type HttpResult, type RouteGate } from './http';
2
+ import type { FetchLike, Logger } from './types';
3
+ export type BeaconRoute = 'impression' | 'viewable' | 'video-event';
4
+ export interface BeaconContext {
5
+ fetch: FetchLike;
6
+ serveBase(): string;
7
+ headers(): Record<string, string>;
8
+ gate: RouteGate;
9
+ now(): number;
10
+ log: Required<Logger>;
11
+ }
12
+ export declare const BEACON_TIMEOUT_MS = 10000;
13
+ export declare const ONE_HOUR_MS: number;
14
+ /** The backoff ceiling for a retry: 1 s doubling per attempt, capped at 60 s. */
15
+ export declare function backoffCapMs(attempt: number): number;
16
+ /**
17
+ * Full jitter: a uniformly random wait between 0 and the ceiling, so installs
18
+ * that failed together (one outage, one carrier NAT) do not retry together.
19
+ */
20
+ export declare function backoffMs(attempt: number, random?: () => number): number;
21
+ /**
22
+ * Send one beacon, retrying timeouts, network errors and 5xx with backoff
23
+ * (full jitter under a ceiling of 1 s doubling, capped at 60 s) and 429
24
+ * after Retry-After, until the deadline (doc lifecycle rule 7: give up after
25
+ * one hour). Resolves with the last answer, or null when the deadline passed
26
+ * before it could be sent.
27
+ * `maxAttempts` is unlimited unless given. Never throws.
28
+ */
29
+ export declare function sendWithRetry(ctx: BeaconContext, route: BeaconRoute, body: unknown, opts: {
30
+ deadline: number;
31
+ maxAttempts?: number;
32
+ }): Promise<HttpResult | null>;
@@ -0,0 +1,53 @@
1
+ import type { FileCacheAdapter, KeyValueStorage, Logger } from './types';
2
+ export interface CacheLimits {
3
+ maxCreatives: number;
4
+ maxBytes: number;
5
+ }
6
+ export interface CachedMedia {
7
+ /** remote URL -> local uri, for the files that are cached. */
8
+ uris: Record<string, string>;
9
+ }
10
+ /** Content-Length of a URL, or null when unknown. */
11
+ export type SizeProbe = (url: string) => Promise<number | null>;
12
+ export declare class CreativeCache {
13
+ private files;
14
+ private storage;
15
+ private storageKey;
16
+ private now;
17
+ private log;
18
+ private probeSize;
19
+ private entries;
20
+ /** File names whose download has started but not landed. */
21
+ private pending;
22
+ private loaded;
23
+ private chain;
24
+ constructor(files: FileCacheAdapter, storage: KeyValueStorage, storageKey: string, now: () => number, log: Required<Logger>, probeSize?: SizeProbe);
25
+ private load;
26
+ private loadNow;
27
+ /**
28
+ * Delete the downloads a previous run left unfinished, and every file in the
29
+ * cache directory that the index does not list.
30
+ */
31
+ private sweep;
32
+ private persist;
33
+ /** Number of cached creatives and their total size, for tests and debugging. */
34
+ stats(): Promise<{
35
+ creatives: number;
36
+ bytes: number;
37
+ keys: string[];
38
+ }>;
39
+ /**
40
+ * Make sure the files of one creative are on disk. Never throws: a file that
41
+ * cannot be cached is simply left out of the result and streamed instead.
42
+ * `allowed()` is checked before every download so setAdsEnabled(false)
43
+ * stops a download that has not started yet.
44
+ */
45
+ ensure(adId: number, urls: string[], limits: CacheLimits, allowed: () => boolean): Promise<CachedMedia>;
46
+ private ensureNow;
47
+ private size;
48
+ /**
49
+ * LRU eviction, leaving room for `incoming` more bytes. The current entry
50
+ * goes last, and only if it alone is too big.
51
+ */
52
+ private evict;
53
+ }
@@ -0,0 +1,8 @@
1
+ /**
2
+ * Append ethicly_click=<token> to the destination. The separator is "&" when
3
+ * the URL already contains a "?" anywhere, otherwise "?". The token is
4
+ * percent-encoded and nothing else in the URL changes.
5
+ */
6
+ export declare function appendClickToken(destinationUrl: string, clickToken: string | null | undefined): string;
7
+ /** The /click budget: the website snippet aborts at exactly 500 ms. */
8
+ export declare const CLICK_TIMEOUT_MS = 500;
@@ -0,0 +1,58 @@
1
+ import { type AppStateLike } from './adapters';
2
+ import type { EthiclyConfig, FetchLike, FileCacheAdapter, InterstitialResult, KeyValueStorage, Logger, NoFillReason, Platform } from './types';
3
+ export interface EthiclyOptions {
4
+ /** Publisher API key (UUID). */
5
+ apiKey: string;
6
+ /** The OS the app runs on. Never "rn": the server ignores unknown platforms. */
7
+ platform: Platform;
8
+ /** The host app's version, sent as app_version. */
9
+ appVersion: string;
10
+ /** The bundled URL /config is fetched from. Default https://ads.ethicly.ch/functions/v1/get-ad-with-geo */
11
+ baseUrl?: string;
12
+ /**
13
+ * Adds test=1 to serve. Ignored in a React Native release build
14
+ * (`__DEV__` false), where the SDK serves and bills normally and logs an error.
15
+ */
16
+ testMode?: boolean;
17
+ /** Initial state of the ads switch, default true. */
18
+ adsEnabled?: boolean;
19
+ storage?: KeyValueStorage;
20
+ fileCache?: FileCacheAdapter;
21
+ openUrl?: (url: string) => unknown;
22
+ fetch?: FetchLike;
23
+ now?: () => number;
24
+ logger?: Logger;
25
+ /**
26
+ * App foreground and background changes, for sessions. Defaults to React
27
+ * Native's AppState; null turns sessions off (one session per process).
28
+ */
29
+ appState?: AppStateLike | null;
30
+ }
31
+ export interface Ethicly {
32
+ /** Resolves when the stored config is loaded and the first /config fetch settled. Never rejects. */
33
+ readonly ready: Promise<void>;
34
+ /** Serve and download an interstitial ahead of time. Does not consume it. */
35
+ preload(): Promise<InterstitialResult>;
36
+ /** The ad to show now: the preloaded one if still valid, else a fresh serve. Consumes it. */
37
+ loadInterstitial(): Promise<InterstitialResult>;
38
+ /**
39
+ * Frequency caps, the ads switch and the kill switch, checked client-side.
40
+ * false until the stored frequency state has loaded (see `ready`).
41
+ */
42
+ canShow(): boolean;
43
+ /** false for paid users: stops serves and downloads. */
44
+ setAdsEnabled(enabled: boolean): void;
45
+ isAdsEnabled(): boolean;
46
+ getConfig(): EthiclyConfig;
47
+ /** Refetch /config now (subject to Retry-After). */
48
+ refreshConfig(): Promise<void>;
49
+ /** Why the last load returned no ad. */
50
+ readonly lastNoFillReason: NoFillReason | null;
51
+ readonly sdkVersion: string;
52
+ }
53
+ /**
54
+ * A new session (interstitial.max_per_session counts from zero again) starts
55
+ * when the app comes back after at least this long in the background.
56
+ */
57
+ export declare const SESSION_TIMEOUT_MS: number;
58
+ export declare function createEthicly(options: EthiclyOptions): Ethicly;
@@ -0,0 +1,24 @@
1
+ import type { EthiclyConfig } from './types';
2
+ export declare const BUNDLED_BASE_URL = "https://ads.ethicly.ch/functions/v1/get-ad-with-geo";
3
+ export declare const DEFAULT_MAX_AGE_S = 300;
4
+ /** The defaults shown in the doc. Used when no config was ever fetched. */
5
+ export declare function defaultConfig(serveBase: string): EthiclyConfig;
6
+ /** An https URL, without a trailing slash, or null. */
7
+ export declare function cleanServeBase(v: unknown): string | null;
8
+ /**
9
+ * Read a /config body leniently: every field is validated and falls back to
10
+ * the default, unknown fields are ignored. Returns null when the body is not a
11
+ * config at all.
12
+ */
13
+ export declare function parseConfig(body: unknown, bundledBase: string): EthiclyConfig | null;
14
+ /** max-age from Cache-Control, default 300 s. */
15
+ export declare function maxAgeSeconds(cacheControl: string | null): number;
16
+ /**
17
+ * Doc "Versioning > Comparison": leading dot-separated numeric components,
18
+ * everything from the first other character ignored. -1, 0, 1, or null when
19
+ * either side has no leading number. Mirrors compareVersions in the server's
20
+ * appConfig.ts.
21
+ */
22
+ export declare function compareVersions(a: unknown, b: unknown): number | null;
23
+ /** True only when `sdk` parses and is below `min`. */
24
+ export declare function isBelowMinSdk(sdk: string, min: string): boolean;
@@ -0,0 +1,34 @@
1
+ import type { FetchLike, ImpressionId } from './types';
2
+ export interface HttpResult {
3
+ /** 0 for a network error or timeout. */
4
+ status: number;
5
+ body: any;
6
+ /** Seconds from Retry-After, null when absent or unparseable. */
7
+ retryAfterS: number | null;
8
+ cacheControl: string | null;
9
+ timedOut: boolean;
10
+ }
11
+ /**
12
+ * impression_id is a 64-bit integer. JSON.parse would round anything above
13
+ * 2^53, so long ids are read as strings and written back as bare numbers.
14
+ */
15
+ export declare function parseJson(text: string): unknown;
16
+ export declare function stringifyJson(value: unknown): string;
17
+ export declare function asImpressionId(v: unknown): ImpressionId | null;
18
+ export declare function parseRetryAfter(v: string | null): number | null;
19
+ export declare function httpRequest(fetchFn: FetchLike, url: string, opts: {
20
+ method?: string;
21
+ headers: Record<string, string>;
22
+ body?: unknown;
23
+ timeoutMs: number;
24
+ }): Promise<HttpResult>;
25
+ /** On a 429 the route is closed until Retry-After has passed. */
26
+ export declare class RouteGate {
27
+ private now;
28
+ private until;
29
+ constructor(now: () => number);
30
+ block(route: string, retryAfterS: number | null): void;
31
+ /** Milliseconds until the route opens, 0 when open. */
32
+ waitMs(route: string): number;
33
+ }
34
+ export declare function sleep(ms: number): Promise<void>;