@ethicly/react-native 0.0.0-stage → 0.2.1

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 +133 -0
  2. package/LICENSE +21 -0
  3. package/README.md +428 -2
  4. package/core/package.json +6 -0
  5. package/interstitial/package.json +6 -0
  6. package/lib/commonjs/core/adapters.js +326 -0
  7. package/lib/commonjs/core/beacons.js +70 -0
  8. package/lib/commonjs/core/cache.js +261 -0
  9. package/lib/commonjs/core/click.js +29 -0
  10. package/lib/commonjs/core/client.js +585 -0
  11. package/lib/commonjs/core/config.js +128 -0
  12. package/lib/commonjs/core/http.js +115 -0
  13. package/lib/commonjs/core/index.js +21 -0
  14. package/lib/commonjs/core/outbox.js +192 -0
  15. package/lib/commonjs/core/tracker.js +379 -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 +319 -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 +315 -0
  23. package/lib/module/core/beacons.js +64 -0
  24. package/lib/module/core/cache.js +257 -0
  25. package/lib/module/core/click.js +24 -0
  26. package/lib/module/core/client.js +581 -0
  27. package/lib/module/core/config.js +118 -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 +375 -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 +292 -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 +139 -0
  39. package/lib/typescript/core/beacons.d.ts +32 -0
  40. package/lib/typescript/core/cache.d.ts +71 -0
  41. package/lib/typescript/core/click.d.ts +13 -0
  42. package/lib/typescript/core/client.d.ts +78 -0
  43. package/lib/typescript/core/config.d.ts +33 -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 +175 -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 +51 -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 +365 -0
  56. package/src/core/beacons.ts +81 -0
  57. package/src/core/cache.ts +261 -0
  58. package/src/core/click.ts +26 -0
  59. package/src/core/client.ts +665 -0
  60. package/src/core/config.ts +124 -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 +376 -0
  65. package/src/core/types.ts +185 -0
  66. package/src/index.ts +5 -0
  67. package/src/interstitial.ts +4 -0
  68. package/src/react/EthiclyInterstitial.tsx +432 -0
  69. package/src/react/useEthiclyInterstitial.ts +74 -0
  70. package/src/version.ts +2 -0
@@ -0,0 +1,292 @@
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 the effective audio (the `audio` prop, else
7
+ // ad.audio: createEthicly's `audio` option, else /config) is 'none' or 'optional'.
8
+ // The controls keep clear of the notch, status bar and home indicator: see
9
+ // useSafeInsets below.
10
+ import React, { useCallback, useContext, useEffect, useRef, useState } from 'react';
11
+ import { AppState, BackHandler, Image, Modal, Platform, Pressable, StatusBar, StyleSheet, Text, View, } from 'react-native';
12
+ import { useVideoPlayer, VideoView } from 'expo-video';
13
+ /** The sound a screen plays with: the prop, else ad.audio, else 'on'. */
14
+ export function effectiveAudio(prop, ad) {
15
+ for (const v of [prop, ad.audio])
16
+ if (v === 'on' || v === 'optional' || v === 'none')
17
+ return v;
18
+ return 'on';
19
+ }
20
+ const TICK_MS = 250;
21
+ /** Space between the safe area and the controls. */
22
+ const TOP_GAP = 12;
23
+ const BOTTOM_GAP = 10;
24
+ const SIDE_GAP_TOP = 16;
25
+ const SIDE_GAP_BOTTOM = 20;
26
+ /**
27
+ * The 0.1 layout (controls 56 from the top, 44 from the bottom) is a floor:
28
+ * insets only ever move the controls inward, so a phone without a notch or a
29
+ * tall status bar looks exactly as before.
30
+ */
31
+ const MIN_TOP = 56;
32
+ const MIN_BOTTOM = 44;
33
+ /**
34
+ * react-native-safe-area-context when the app has it, else null. Metro treats
35
+ * a require inside try/catch as an optional dependency (the React Native and
36
+ * Expo Metro configs set allowOptionalDependencies), so an app without the
37
+ * package still builds.
38
+ */
39
+ function loadSafeArea() {
40
+ try {
41
+ // @ts-ignore: the build compiles without Node's types, where require is undeclared.
42
+ return typeof require === 'function' ? require('react-native-safe-area-context') : null;
43
+ }
44
+ catch {
45
+ return null;
46
+ }
47
+ }
48
+ const safeArea = loadSafeArea();
49
+ const noInsets = React.createContext(null);
50
+ // Read with useContext, which returns null without a SafeAreaProvider instead
51
+ // of throwing like useSafeAreaInsets(). Fixed at load, so hook order never changes.
52
+ const InsetsContext = safeArea && safeArea.SafeAreaInsetsContext && typeof safeArea.SafeAreaInsetsContext === 'object'
53
+ ? safeArea.SafeAreaInsetsContext
54
+ : noInsets;
55
+ function validInsets(v) {
56
+ const i = v;
57
+ if (!i || typeof i !== 'object')
58
+ return null;
59
+ const n = (x) => (typeof x === 'number' && Number.isFinite(x) && x >= 0 ? x : 0);
60
+ if (typeof i.top !== 'number' && typeof i.bottom !== 'number')
61
+ return null;
62
+ return { top: n(i.top), bottom: n(i.bottom), left: n(i.left), right: n(i.right) };
63
+ }
64
+ /** The `insets` prop, else the provider's insets, else the window's first metrics, else the status bar. */
65
+ function useSafeInsets(prop) {
66
+ var _a, _b, _c, _d, _e;
67
+ const fromProvider = useContext(InsetsContext);
68
+ 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 };
69
+ }
70
+ export function EthiclyInterstitial(props) {
71
+ // Android back: a Modal receives it through onRequestClose, an inline screen
72
+ // through BackHandler. Either way it closes the ad only once Skip is allowed,
73
+ // and is swallowed before that.
74
+ const backRef = useRef(null);
75
+ const inline = props.modal === false;
76
+ useEffect(() => {
77
+ if (!inline)
78
+ return undefined;
79
+ const sub = BackHandler.addEventListener('hardwareBackPress', () => {
80
+ var _a;
81
+ (_a = backRef.current) === null || _a === void 0 ? void 0 : _a.call(backRef);
82
+ return true;
83
+ });
84
+ return () => sub.remove();
85
+ }, [inline]);
86
+ const body = _jsx(InterstitialBody, { ...props, backRef: backRef });
87
+ if (inline)
88
+ return body;
89
+ 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 }));
90
+ }
91
+ function useAppActive() {
92
+ const [active, setActive] = useState(AppState.currentState === 'active');
93
+ useEffect(() => {
94
+ const sub = AppState.addEventListener('change', (s) => setActive(s === 'active'));
95
+ return () => sub.remove();
96
+ }, []);
97
+ return active;
98
+ }
99
+ function InterstitialBody({ ad, tracker, onClose, onRemoveAds, removeAdsLabel, renderBelowButton, skipStyle, skipTextStyle, insets, backRef, audio: audioProp, }) {
100
+ const audio = effectiveAudio(audioProp, ad);
101
+ const safe = useSafeInsets(insets);
102
+ const isVideo = ad.media.kind === 'video' && !!ad.media.videoUri;
103
+ const appActive = useAppActive();
104
+ const activeRef = useRef(appActive);
105
+ activeRef.current = appActive;
106
+ const [positionMs, setPositionMs] = useState(0);
107
+ const [ended, setEnded] = useState(false);
108
+ const [failed, setFailed] = useState(false);
109
+ const [muted, setMuted] = useState(audio !== 'on');
110
+ /**
111
+ * A still image counts as visible only once it has loaded: an image that
112
+ * never arrives is never billed as viewable.
113
+ */
114
+ const imageLoadedRef = useRef(false);
115
+ /** Wall-clock time on screen with the app in the foreground. */
116
+ const [onScreenMs, setOnScreenMs] = useState(0);
117
+ const [clicked, setClicked] = useState(false);
118
+ const positionRef = useRef(0);
119
+ const closedRef = useRef(false);
120
+ const failedRef = useRef(false);
121
+ const player = useVideoPlayer(isVideo ? ad.media.videoUri : null, (p) => {
122
+ p.loop = false;
123
+ p.muted = audio !== 'on';
124
+ p.timeUpdateEventInterval = TICK_MS / 1000;
125
+ p.play();
126
+ });
127
+ const onCloseRef = useRef(onClose);
128
+ onCloseRef.current = onClose;
129
+ // The impression goes out the moment the ad is on screen. shown() refuses an
130
+ // ad past its token lifetime (nothing is recorded), so the screen closes
131
+ // itself instead of playing an ad nobody is paid for.
132
+ useEffect(() => {
133
+ const expired = tracker.isExpired();
134
+ void tracker.shown();
135
+ if (expired && !closedRef.current) {
136
+ closedRef.current = true;
137
+ void tracker.closed();
138
+ onCloseRef.current();
139
+ }
140
+ }, [tracker]);
141
+ // Video: playback position drives viewability, quartiles and the skip countdown.
142
+ useEffect(() => {
143
+ if (!isVideo)
144
+ return undefined;
145
+ const subs = [
146
+ player.addListener('timeUpdate', ({ currentTime }) => {
147
+ const ms = Math.max(0, currentTime * 1000);
148
+ positionRef.current = ms;
149
+ setPositionMs(ms);
150
+ const durationMs = player.duration > 0 ? player.duration * 1000 : undefined;
151
+ tracker.progress(ms, { visible: activeRef.current && player.playing, durationMs });
152
+ }),
153
+ player.addListener('playToEnd', () => {
154
+ setEnded(true);
155
+ tracker.complete();
156
+ }),
157
+ player.addListener('statusChange', ({ status }) => {
158
+ if (status === 'error' && !failedRef.current) {
159
+ failedRef.current = true;
160
+ setFailed(true);
161
+ tracker.error();
162
+ }
163
+ }),
164
+ ];
165
+ return () => subs.forEach((s) => s.remove());
166
+ }, [isVideo, player, tracker]);
167
+ // Time on screen while the app is in the foreground: the skip countdown, so
168
+ // Skip appears after skipAfterMs even if the video stalls or the image never
169
+ // loads. For a still image, the time since it loaded is the playback position.
170
+ useEffect(() => {
171
+ let shownMs = 0;
172
+ let loadedMs = 0;
173
+ const id = setInterval(() => {
174
+ if (activeRef.current)
175
+ shownMs += TICK_MS;
176
+ setOnScreenMs(shownMs);
177
+ if (isVideo || !imageLoadedRef.current || failedRef.current)
178
+ return;
179
+ if (activeRef.current)
180
+ loadedMs += TICK_MS;
181
+ positionRef.current = loadedMs;
182
+ setPositionMs(loadedMs);
183
+ tracker.progress(loadedMs, { visible: activeRef.current });
184
+ }, TICK_MS);
185
+ return () => clearInterval(id);
186
+ }, [isVideo, tracker]);
187
+ const onImageLoad = useCallback(() => {
188
+ imageLoadedRef.current = true;
189
+ }, []);
190
+ const onImageError = useCallback(() => {
191
+ if (failedRef.current)
192
+ return;
193
+ failedRef.current = true;
194
+ setFailed(true);
195
+ tracker.error();
196
+ }, [tracker]);
197
+ useEffect(() => {
198
+ if (!isVideo)
199
+ return;
200
+ if (appActive && !ended)
201
+ player.play();
202
+ else
203
+ player.pause();
204
+ }, [appActive, ended, isVideo, player]);
205
+ // Leaving the foreground ends continuous visibility right away, without
206
+ // waiting for the next player tick (which may never come while paused).
207
+ useEffect(() => {
208
+ if (appActive)
209
+ return;
210
+ if (!isVideo && (!imageLoadedRef.current || failedRef.current))
211
+ return;
212
+ const durationMs = isVideo && player.duration > 0 ? player.duration * 1000 : undefined;
213
+ tracker.progress(positionRef.current, { visible: false, durationMs });
214
+ }, [appActive, isVideo, player, tracker]);
215
+ // The tracker is closed only from close() below (or by the hook's dismiss()),
216
+ // never from an effect cleanup: React StrictMode runs every cleanup once on
217
+ // mount, and a closed tracker drops /viewable and the video events.
218
+ const close = useCallback(() => {
219
+ if (closedRef.current)
220
+ return;
221
+ closedRef.current = true;
222
+ if (isVideo && !ended && !failed)
223
+ tracker.skipped(positionRef.current);
224
+ void tracker.closed();
225
+ onClose();
226
+ }, [ended, failed, isVideo, onClose, tracker]);
227
+ const onCta = useCallback(() => {
228
+ if (isVideo)
229
+ player.pause();
230
+ // Once the user has visited the advertiser, they can always close the ad
231
+ // when they come back.
232
+ setClicked(true);
233
+ void tracker.clicked();
234
+ }, [isVideo, player, tracker]);
235
+ const toggleSound = useCallback(() => {
236
+ setMuted((m) => {
237
+ player.muted = !m;
238
+ return !m;
239
+ });
240
+ }, [player]);
241
+ const remainingS = Math.ceil(Math.max(0, ad.skipAfterMs - Math.max(positionMs, onScreenMs)) / 1000);
242
+ const canSkip = remainingS === 0 || ended || failed || clicked;
243
+ backRef.current = canSkip ? close : null;
244
+ 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, allowsPictureInPicture: false })] })) : (_jsx(Image, { source: { uri: ad.media.uri }, style: StyleSheet.absoluteFill, resizeMode: "cover", onLoad: onImageLoad, onError: onImageError })), _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" }), ad.test ? _jsx(Text, { style: [styles.adLabel, styles.testLabel], accessibilityRole: "text", children: "Test ad" }) : null, isVideo && 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, {
245
+ bottom: Math.max(safe.bottom + BOTTOM_GAP, MIN_BOTTOM), left: safe.left + SIDE_GAP_BOTTOM, right: safe.right + SIDE_GAP_BOTTOM,
246
+ }], 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" })] })] }));
247
+ }
248
+ /** Skip-to-end mark (a play triangle against a bar), drawn so it never depends on a font glyph. */
249
+ function SkipIcon() {
250
+ return (_jsxs(View, { style: styles.skipIcon, accessibilityElementsHidden: true, importantForAccessibility: "no-hide-descendants", children: [_jsx(View, { style: styles.skipTriangle }), _jsx(View, { style: styles.skipBar })] }));
251
+ }
252
+ const styles = StyleSheet.create({
253
+ root: { flex: 1, backgroundColor: '#000' },
254
+ topRow: {
255
+ position: 'absolute',
256
+ flexDirection: 'row', justifyContent: 'space-between', alignItems: 'center',
257
+ },
258
+ leftGroup: { flexDirection: 'row', alignItems: 'center' },
259
+ adLabel: {
260
+ color: '#fff', fontSize: 11, fontWeight: '600', letterSpacing: 0.5,
261
+ backgroundColor: 'rgba(0,0,0,0.45)', paddingHorizontal: 6, paddingVertical: 2, borderRadius: 4, overflow: 'hidden',
262
+ },
263
+ testLabel: { marginLeft: 8, backgroundColor: 'rgba(196,120,0,0.85)' },
264
+ soundButton: { marginLeft: 8, backgroundColor: 'rgba(0,0,0,0.45)', paddingHorizontal: 8, paddingVertical: 4, borderRadius: 6 },
265
+ soundText: { color: '#fff', fontSize: 12, fontWeight: '500' },
266
+ // Solid black, no blur or translucency. The faint hairline keeps the edge
267
+ // visible over a dark frame.
268
+ skip: {
269
+ backgroundColor: '#000', paddingHorizontal: 18, height: 40, borderRadius: 20,
270
+ justifyContent: 'center', alignItems: 'center',
271
+ borderWidth: StyleSheet.hairlineWidth, borderColor: 'rgba(255,255,255,0.22)',
272
+ },
273
+ skipRow: { flexDirection: 'row', alignItems: 'center' },
274
+ skipText: { color: '#fff', fontSize: 15, fontWeight: '500', letterSpacing: 0.2 },
275
+ skipTextWaiting: { opacity: 0.75 },
276
+ skipIcon: { flexDirection: 'row', alignItems: 'center', marginLeft: 10 },
277
+ skipTriangle: {
278
+ width: 0, height: 0,
279
+ borderTopWidth: 6, borderBottomWidth: 6, borderLeftWidth: 10,
280
+ borderTopColor: 'transparent', borderBottomColor: 'transparent', borderLeftColor: '#fff',
281
+ },
282
+ skipBar: { width: 2, height: 12, backgroundColor: '#fff', marginLeft: 2, borderRadius: 1 },
283
+ bottom: { position: 'absolute', alignItems: 'center' },
284
+ cta: {
285
+ alignSelf: 'stretch', backgroundColor: '#fff', borderRadius: 12, paddingVertical: 15,
286
+ alignItems: 'center', justifyContent: 'center',
287
+ },
288
+ ctaPressed: { opacity: 0.85 },
289
+ ctaText: { color: '#000', fontSize: 17, fontWeight: '600' },
290
+ removeAds: { color: '#fff', fontSize: 14, marginTop: 14, textDecorationLine: 'underline', opacity: 0.9 },
291
+ sponsor: { color: '#fff', fontSize: 12, marginTop: 10, opacity: 0.6 },
292
+ });
@@ -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.1';
@@ -0,0 +1,139 @@
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` in
112
+ * development, nothing in a release build).
113
+ */
114
+ export declare function createExpoFileCache(fs: ExpoFileSystemLike | ExpoFileSystemModernLike, subdirectory?: string, logger?: Logger): FileCacheAdapter;
115
+ /**
116
+ * True only in a React Native release build (`__DEV__ === false`). Where
117
+ * `__DEV__` is not defined at all the code is not running from a Metro bundle
118
+ * (a Node script such as scripts/live-test.mjs, or tests), which is never a
119
+ * shipped app, so that counts as not release.
120
+ */
121
+ export declare function isReleaseBuild(): boolean;
122
+ /** The part of React Native's AppState the client uses for sessions. */
123
+ export interface AppStateLike {
124
+ currentState?: string | null;
125
+ addEventListener(type: 'change', listener: (state: string) => void): {
126
+ remove(): void;
127
+ } | undefined | void;
128
+ }
129
+ /**
130
+ * React Native's AppState, or null outside React Native. The core takes no
131
+ * hard dependency on react-native: a require inside try/catch is an optional
132
+ * dependency for Metro (the React Native and Expo Metro configs both set
133
+ * allowOptionalDependencies), and in Node it simply fails and returns null.
134
+ */
135
+ export declare function defaultAppState(): AppStateLike | null;
136
+ /** Wrap a logger so a throwing logger can never reach the host app. */
137
+ export declare function safeLogger(logger: Logger | undefined): Required<Logger>;
138
+ /** UUID v4. Uses the platform RNG when there is one (Hermes has none by default). */
139
+ 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,71 @@
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
+ /**
11
+ * The longest one creative file may take to download. A slower (trickling)
12
+ * download is cancelled when the adapter supports it, else abandoned: the
13
+ * creative streams and later downloads are not held up behind it. A file it
14
+ * still writes afterwards is not indexed, so the next launch's sweep deletes it.
15
+ */
16
+ export declare const DOWNLOAD_TIMEOUT_MS = 60000;
17
+ /** Content-Length of a URL, or null when unknown. */
18
+ export type SizeProbe = (url: string) => Promise<number | null>;
19
+ export declare class CreativeCache {
20
+ private files;
21
+ private storage;
22
+ private storageKey;
23
+ private now;
24
+ private log;
25
+ private probeSize;
26
+ private downloadTimeoutMs;
27
+ private entries;
28
+ /** File names whose download has started but not landed. */
29
+ private pending;
30
+ private loaded;
31
+ private chain;
32
+ /** Bumped by cancel(): a download started before it no longer counts. */
33
+ private generation;
34
+ constructor(files: FileCacheAdapter, storage: KeyValueStorage, storageKey: string, now: () => number, log: Required<Logger>, probeSize?: SizeProbe, downloadTimeoutMs?: number);
35
+ /**
36
+ * Stop the download in flight, when the adapter can (FileCacheAdapter.cancel),
37
+ * and skip the files not started yet. For setAdsEnabled(false).
38
+ */
39
+ cancel(): void;
40
+ /** The adapter's download, given up on after downloadTimeoutMs. */
41
+ private downloadWithin;
42
+ private load;
43
+ private loadNow;
44
+ /**
45
+ * Delete the downloads a previous run left unfinished, and every file in the
46
+ * cache directory that the index does not list.
47
+ */
48
+ private sweep;
49
+ private persist;
50
+ /** Number of cached creatives and their total size, for tests and debugging. */
51
+ stats(): Promise<{
52
+ creatives: number;
53
+ bytes: number;
54
+ keys: string[];
55
+ }>;
56
+ /**
57
+ * Make sure the files of one creative are on disk. Never throws: a file that
58
+ * cannot be cached is simply left out of the result and streamed instead.
59
+ * `allowed()` is checked before every download so setAdsEnabled(false)
60
+ * stops a download that has not started yet; cancel() also stops the one in
61
+ * flight when the adapter supports it.
62
+ */
63
+ ensure(adId: number, urls: string[], limits: CacheLimits, allowed: () => boolean): Promise<CachedMedia>;
64
+ private ensureNow;
65
+ private size;
66
+ /**
67
+ * LRU eviction, leaving room for `incoming` more bytes. The current entry
68
+ * goes last, and only if it alone is too big.
69
+ */
70
+ private evict;
71
+ }
@@ -0,0 +1,13 @@
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;
9
+ /**
10
+ * True for an absolute http: or https: URL with a host. Anything else (tel:,
11
+ * intent:, javascript:, a custom app scheme, a relative path) is never opened.
12
+ */
13
+ export declare function isWebUrl(url: unknown): url is string;