@ethicly/react-native 0.2.1 → 0.4.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 (37) hide show
  1. package/CHANGELOG.md +92 -0
  2. package/README.md +189 -12
  3. package/lib/commonjs/core/cache.js +2 -0
  4. package/lib/commonjs/core/client.js +245 -62
  5. package/lib/commonjs/core/config.js +4 -1
  6. package/lib/commonjs/core/houseTracker.js +92 -0
  7. package/lib/commonjs/core/tracker.js +3 -0
  8. package/lib/commonjs/react/EthiclyInterstitial.js +23 -4
  9. package/lib/commonjs/react/useEthiclyInterstitial.js +26 -7
  10. package/lib/commonjs/version.js +1 -1
  11. package/lib/module/core/cache.js +2 -0
  12. package/lib/module/core/client.js +245 -62
  13. package/lib/module/core/config.js +4 -1
  14. package/lib/module/core/houseTracker.js +88 -0
  15. package/lib/module/core/tracker.js +3 -0
  16. package/lib/module/react/EthiclyInterstitial.js +23 -4
  17. package/lib/module/react/useEthiclyInterstitial.js +26 -7
  18. package/lib/module/version.js +1 -1
  19. package/lib/typescript/core/cache.d.ts +3 -1
  20. package/lib/typescript/core/client.d.ts +43 -4
  21. package/lib/typescript/core/houseTracker.d.ts +53 -0
  22. package/lib/typescript/core/index.d.ts +1 -1
  23. package/lib/typescript/core/types.d.ts +87 -2
  24. package/lib/typescript/react/EthiclyInterstitial.d.ts +7 -0
  25. package/lib/typescript/react/useEthiclyInterstitial.d.ts +19 -3
  26. package/lib/typescript/version.d.ts +1 -1
  27. package/package.json +1 -1
  28. package/src/core/cache.ts +4 -2
  29. package/src/core/client.ts +277 -62
  30. package/src/core/config.ts +4 -1
  31. package/src/core/houseTracker.ts +108 -0
  32. package/src/core/index.ts +3 -2
  33. package/src/core/tracker.ts +2 -0
  34. package/src/core/types.ts +96 -2
  35. package/src/react/EthiclyInterstitial.tsx +26 -4
  36. package/src/react/useEthiclyInterstitial.ts +45 -10
  37. package/src/version.ts +1 -1
@@ -349,6 +349,9 @@ export class InterstitialTracker {
349
349
  body.publisher_site_id = serve.publisherSiteId;
350
350
  if (serve.countryCode)
351
351
  body.country_code = serve.countryCode;
352
+ // Proof the view was served: lets the server bill a tap made before /viewable.
353
+ if (imp.viewableToken)
354
+ body.viewable_token = imp.viewableToken;
352
355
  // Never retried: one request, whatever happens.
353
356
  const res = await httpRequest(ctx.fetch, `${ctx.serveBase()}/click`, {
354
357
  method: 'POST', headers: ctx.headers(), body, timeoutMs: Math.min(remaining, BEACON_TIMEOUT_MS),
@@ -2,7 +2,9 @@ import { jsx as _jsx, Fragment as _Fragment, jsxs as _jsxs } from "react/jsx-run
2
2
  // Optional ready-made fullscreen screen. Needs expo-video (Expo SDK 52+).
3
3
  // Layout follows a typical in-app video player: 9:16 video, a skip control that counts
4
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.
5
+ // "Remove ads" slot and a small "Sponsored by Ethicly.ch" line under it. The
6
+ // line follows ad.showSponsorLabel: hidden for house ads, and for paid ads when
7
+ // the publisher switched it off in the dashboard.
6
8
  // Video starts with sound unless the effective audio (the `audio` prop, else
7
9
  // ad.audio: createEthicly's `audio` option, else /config) is 'none' or 'optional'.
8
10
  // The controls keep clear of the notch, status bar and home indicator: see
@@ -96,7 +98,7 @@ function useAppActive() {
96
98
  }, []);
97
99
  return active;
98
100
  }
99
- function InterstitialBody({ ad, tracker, onClose, onRemoveAds, removeAdsLabel, renderBelowButton, skipStyle, skipTextStyle, insets, backRef, audio: audioProp, }) {
101
+ function InterstitialBody({ ad, tracker, onClose, onRemoveAds, removeAdsLabel, onHouseAdPress, renderBelowButton, skipStyle, skipTextStyle, insets, backRef, audio: audioProp, }) {
100
102
  const audio = effectiveAudio(audioProp, ad);
101
103
  const safe = useSafeInsets(insets);
102
104
  const isVideo = ad.media.kind === 'video' && !!ad.media.videoUri;
@@ -225,13 +227,30 @@ function InterstitialBody({ ad, tracker, onClose, onRemoveAds, removeAdsLabel, r
225
227
  onClose();
226
228
  }, [ended, failed, isVideo, onClose, tracker]);
227
229
  const onCta = useCallback(() => {
230
+ // A house ad the app routes to its own screen: count the tap, close the
231
+ // ad the normal way, then hand over. Never for a paid ad.
232
+ const housePress = ad.house
233
+ ? onHouseAdPress || tracker.houseAdPress
234
+ : undefined;
235
+ if (housePress) {
236
+ // A second tap before the screen unmounts must not run the handler twice.
237
+ if (closedRef.current)
238
+ return;
239
+ void tracker.clicked({ open: false });
240
+ close();
241
+ try {
242
+ housePress(ad);
243
+ }
244
+ catch { /* the app's handler must not break the screen */ }
245
+ return;
246
+ }
228
247
  if (isVideo)
229
248
  player.pause();
230
249
  // Once the user has visited the advertiser, they can always close the ad
231
250
  // when they come back.
232
251
  setClicked(true);
233
252
  void tracker.clicked();
234
- }, [isVideo, player, tracker]);
253
+ }, [ad, close, isVideo, onHouseAdPress, player, tracker]);
235
254
  const toggleSound = useCallback(() => {
236
255
  setMuted((m) => {
237
256
  player.muted = !m;
@@ -243,7 +262,7 @@ function InterstitialBody({ ad, tracker, onClose, onRemoveAds, removeAdsLabel, r
243
262
  backRef.current = canSkip ? close : null;
244
263
  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
264
  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" })] })] }));
265
+ }], 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, ad.showSponsorLabel ? _jsx(Text, { style: styles.sponsor, children: "Sponsored by Ethicly.ch" }) : null] })] }));
247
266
  }
248
267
  /** Skip-to-end mark (a play triangle against a bar), drawn so it never depends on a font glyph. */
249
268
  function SkipIcon() {
@@ -4,6 +4,9 @@ import { useCallback, useEffect, useRef, useState } from 'react';
4
4
  export function useEthiclyInterstitial(ethicly, options = {}) {
5
5
  var _a, _b;
6
6
  const preload = options.preload !== false;
7
+ const houseAds = options.houseAds;
8
+ const housePressRef = useRef(options.onHouseAdPress);
9
+ housePressRef.current = options.onHouseAdPress;
7
10
  const [current, setCurrent] = useState(null);
8
11
  const [reason, setReason] = useState(null);
9
12
  const [loading, setLoading] = useState(false);
@@ -13,20 +16,33 @@ export function useEthiclyInterstitial(ethicly, options = {}) {
13
16
  useEffect(() => {
14
17
  mounted.current = true;
15
18
  if (preload)
16
- void ethicly.preload();
19
+ void ethicly.preload({ houseAds });
17
20
  return () => {
18
21
  var _a;
19
22
  mounted.current = false;
20
23
  void ((_a = currentRef.current) === null || _a === void 0 ? void 0 : _a.tracker.closed());
21
24
  };
22
- }, [ethicly, preload]);
25
+ }, [ethicly, preload, houseAds]);
23
26
  const show = useCallback(async () => {
24
27
  setLoading(true);
25
28
  try {
26
- const r = await ethicly.loadInterstitial();
29
+ const r = await ethicly.loadInterstitial({ houseAds });
27
30
  if (!mounted.current)
28
31
  return false;
29
32
  if (r.ad) {
33
+ if (r.ad.house) {
34
+ // Read at tap time: the hook's latest handler wins, else the client's
35
+ // (set when the ad was built), else the link opens. A handler added or
36
+ // removed after the ad loaded is respected.
37
+ const t = r.tracker;
38
+ const clientPress = t.houseAdPress;
39
+ Object.defineProperty(t, 'houseAdPress', {
40
+ configurable: true,
41
+ enumerable: true,
42
+ get: () => { var _a; return (_a = housePressRef.current) !== null && _a !== void 0 ? _a : clientPress; },
43
+ set: () => { },
44
+ });
45
+ }
30
46
  setCurrent({ ad: r.ad, tracker: r.tracker });
31
47
  setReason(null);
32
48
  return true;
@@ -38,14 +54,17 @@ export function useEthiclyInterstitial(ethicly, options = {}) {
38
54
  if (mounted.current)
39
55
  setLoading(false);
40
56
  }
41
- }, [ethicly]);
57
+ }, [ethicly, houseAds]);
42
58
  const dismiss = useCallback(() => {
43
59
  var _a;
44
60
  void ((_a = currentRef.current) === null || _a === void 0 ? void 0 : _a.tracker.closed());
45
61
  setCurrent(null);
46
62
  if (preload)
47
- void ethicly.preload();
48
- }, [ethicly, preload]);
63
+ void ethicly.preload({ houseAds });
64
+ }, [ethicly, preload, houseAds]);
49
65
  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 };
66
+ const nextAdStatus = useCallback(() => ethicly.nextAdStatus(), [ethicly]);
67
+ return {
68
+ 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, nextAdStatus,
69
+ };
51
70
  }
@@ -1,2 +1,2 @@
1
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';
2
+ export const SDK_VERSION = '0.4.0';
@@ -59,8 +59,10 @@ export declare class CreativeCache {
59
59
  * `allowed()` is checked before every download so setAdsEnabled(false)
60
60
  * stops a download that has not started yet; cancel() also stops the one in
61
61
  * flight when the adapter supports it.
62
+ * `adId` keys the entry and names the files: house ads pass `house-<id>`
63
+ * because their ids can collide with paid ad ids.
62
64
  */
63
- ensure(adId: number, urls: string[], limits: CacheLimits, allowed: () => boolean): Promise<CachedMedia>;
65
+ ensure(adId: string | number, urls: string[], limits: CacheLimits, allowed: () => boolean): Promise<CachedMedia>;
64
66
  private ensureNow;
65
67
  private size;
66
68
  /**
@@ -1,5 +1,5 @@
1
1
  import { type AppStateLike } from './adapters';
2
- import type { AudioPolicy, EthiclyConfig, FetchLike, FileCacheAdapter, InterstitialResult, KeyValueStorage, Logger, NoFillReason, Platform } from './types';
2
+ import type { AudioPolicy, EthiclyAd, EthiclyConfig, FetchLike, FileCacheAdapter, FrequencyOptions, FrequencyUpdate, InterstitialResult, KeyValueStorage, LoadOptions, Logger, NextAdStatus, NoFillReason, Platform } from './types';
3
3
  export interface EthiclyOptions {
4
4
  /** Publisher API key (UUID). */
5
5
  apiKey: string;
@@ -34,6 +34,27 @@ export interface EthiclyOptions {
34
34
  * download carries on in the background for next time.
35
35
  */
36
36
  loadTimeoutMs?: number;
37
+ /**
38
+ * How often ads may show, decided in code. A field set here overrides the
39
+ * dashboard value (/config interstitial.max_per_session, min_gap_s) for this
40
+ * client; an unset field uses /config, then the defaults. Unset: 0.2.x
41
+ * behaviour. Change it later with setFrequency().
42
+ */
43
+ frequency?: FrequencyOptions;
44
+ /**
45
+ * Show the publisher's house ad (uploaded in the dashboard) when no paid ad
46
+ * fills. Default true: the upload is the opt-in, so a publisher without one
47
+ * sees no change. false never asks for one, so the app can show its own.
48
+ * Change it later with setHouseAds(), or per call with { houseAds }.
49
+ */
50
+ houseAds?: boolean;
51
+ /**
52
+ * Where EthiclyInterstitial sends a tap on a house ad's button instead of
53
+ * opening its link, for example the app's premium screen. The tap is still
54
+ * counted and the ad closes first. useEthiclyInterstitial's and the
55
+ * screen's own onHouseAdPress win over this. Never used for paid ads.
56
+ */
57
+ onHouseAdPress?: (ad: EthiclyAd) => void;
37
58
  storage?: KeyValueStorage;
38
59
  fileCache?: FileCacheAdapter;
39
60
  openUrl?: (url: string) => unknown;
@@ -50,14 +71,32 @@ export interface Ethicly {
50
71
  /** Resolves when the stored config is loaded and the first /config fetch settled. Never rejects. */
51
72
  readonly ready: Promise<void>;
52
73
  /** Serve and download an interstitial ahead of time. Does not consume it. */
53
- preload(): Promise<InterstitialResult>;
54
- /** The ad to show now: the preloaded one if still valid, else a fresh serve. Consumes it. */
55
- loadInterstitial(): Promise<InterstitialResult>;
74
+ preload(opts?: LoadOptions): Promise<InterstitialResult>;
75
+ /**
76
+ * The ad to show now: the preloaded one if still valid, else a fresh serve.
77
+ * Consumes it. A preloaded house ad never stands in for a paid ad: a fresh
78
+ * serve is tried first, within loadTimeoutMs. Check `ad.house`.
79
+ */
80
+ loadInterstitial(opts?: LoadOptions): Promise<InterstitialResult>;
81
+ /** Turn house ads on or off for this client (options.houseAds). Off drops a preloaded house ad. */
82
+ setHouseAds(enabled: boolean): void;
56
83
  /**
57
84
  * Frequency caps, the ads switch and the kill switch, checked client-side.
58
85
  * false until the stored frequency state has loaded (see `ready`).
59
86
  */
60
87
  canShow(): boolean;
88
+ /**
89
+ * Whether an ad may show now and, when not, why and when it may: retryAt is
90
+ * set while the gap between ads runs. canShow() is nextAdStatus().allowed.
91
+ */
92
+ nextAdStatus(): NextAdStatus;
93
+ /**
94
+ * Change the frequency set in code, for example after an entitlement check
95
+ * or an A/B test. A field left out keeps its value; null goes back to /config.
96
+ */
97
+ setFrequency(update: FrequencyUpdate): void;
98
+ /** The effective frequency: code, else /config, else the defaults. */
99
+ getFrequency(): Required<FrequencyOptions>;
61
100
  /** false for paid users: stops serves, drops the preloaded ad and cancels a download in flight. */
62
101
  setAdsEnabled(enabled: boolean): void;
63
102
  isAdsEnabled(): boolean;
@@ -0,0 +1,53 @@
1
+ import { type BeaconContext } from './beacons';
2
+ import type { EthiclyAd, Tracker } from './types';
3
+ export interface HouseTrackerDeps {
4
+ ctx: BeaconContext;
5
+ ad: EthiclyAd;
6
+ /** The house ad id the server sent (fallback_id on the wire). */
7
+ fallbackId: number;
8
+ /** Test mode: the counters are never sent. */
9
+ test: boolean;
10
+ openUrl?: (url: string) => unknown;
11
+ /** Called once when the ad is shown: a house ad counts toward the frequency caps. */
12
+ onShown(): void;
13
+ /** createEthicly's onHouseAdPress, if any. */
14
+ onPress?: (ad: EthiclyAd) => void;
15
+ }
16
+ export declare class HouseTracker implements Tracker {
17
+ private d;
18
+ /**
19
+ * Where the ready-made screen sends a tap instead of opening the link:
20
+ * createEthicly's onHouseAdPress, replaced by useEthiclyInterstitial's.
21
+ * EthiclyInterstitial's own prop wins over both.
22
+ */
23
+ /** @internal Set by the SDK; apps pass onHouseAdPress instead. */
24
+ houseAdPress: ((ad: EthiclyAd) => void) | undefined;
25
+ private shownOnce;
26
+ private clickedOnce;
27
+ private pending;
28
+ constructor(d: HouseTrackerDeps);
29
+ /** Resolves when every counter in flight has settled. For tests. */
30
+ settle(): Promise<void>;
31
+ isExpired(): boolean;
32
+ /**
33
+ * One POST to a house-ad counter, never retried, never awaited by the
34
+ * caller. The answer (200, 400 or 429) changes nothing. Never rejects.
35
+ */
36
+ private send;
37
+ shown(): Promise<void>;
38
+ progress(_positionMs: number, _opts: {
39
+ visible: boolean;
40
+ durationMs?: number;
41
+ }): void;
42
+ complete(): void;
43
+ skipped(_positionMs: number): void;
44
+ error(): void;
45
+ /**
46
+ * Counts the tap once (fire-and-forget) and opens the destination right
47
+ * away. `{ open: false }` only counts it: the app shows its own screen.
48
+ */
49
+ clicked(opts?: {
50
+ open?: boolean;
51
+ }): Promise<string>;
52
+ closed(): Promise<void>;
53
+ }
@@ -5,4 +5,4 @@ export type { AppStateLike, ExpoFileSystemLike, ExpoFileSystemModernLike } from
5
5
  export { appendClickToken, CLICK_TIMEOUT_MS } from './click';
6
6
  export { compareVersions, BUNDLED_BASE_URL } from './config';
7
7
  export { SDK_VERSION } from '../version';
8
- export type { AudioPolicy, EthiclyAd, EthiclyAdMedia, EthiclyConfig, FetchLike, FileCacheAdapter, InterstitialResult, KeyValueStorage, Logger, NoFillReason, Platform, Tracker, } from './types';
8
+ export type { AudioPolicy, EthiclyAd, EthiclyAdMedia, EthiclyConfig, FetchLike, FileCacheAdapter, FrequencyOptions, FrequencyUpdate, InterstitialResult, KeyValueStorage, LoadOptions, Logger, NextAdReason, NextAdStatus, NoFillReason, Platform, Tracker, } from './types';
@@ -13,6 +13,16 @@ export interface EthiclyConfig {
13
13
  max_per_session: number;
14
14
  min_gap_s: number;
15
15
  audio: AudioPolicy;
16
+ /**
17
+ * Whether the paid-ad screen shows "Sponsored by Ethicly.ch", set in the
18
+ * publisher's dashboard. Absent from the server: true.
19
+ */
20
+ sponsor_label: boolean;
21
+ /**
22
+ * The publisher's dashboard master switch for house ads. false: the SDK
23
+ * never asks for one. Absent from the server: true.
24
+ */
25
+ house_ads: boolean;
16
26
  };
17
27
  prefetch: {
18
28
  max_cached_creatives: number;
@@ -115,6 +125,18 @@ export interface EthiclyAd {
115
125
  servedAt: number;
116
126
  /** Epoch ms after which the ad must not be shown (served + token_ttl_s). */
117
127
  expiresAt: number;
128
+ /**
129
+ * True for the publisher's own house ad, uploaded in the dashboard and shown
130
+ * when no paid ad fills. Unbilled, but it counts toward the frequency caps.
131
+ */
132
+ house: boolean;
133
+ /** For a house ad: why no paid ad filled (the server's reason). Unset for a paid ad. */
134
+ noFillReason?: NoFillReason;
135
+ /**
136
+ * Show "Sponsored by Ethicly.ch" with this ad. false for house ads, else the
137
+ * dashboard setting (/config interstitial.sponsor_label, default true).
138
+ */
139
+ showSponsorLabel: boolean;
118
140
  }
119
141
  export interface Tracker {
120
142
  /** Call the moment the ad is rendered. Sends /impression immediately. */
@@ -130,13 +152,28 @@ export interface Tracker {
130
152
  complete(): void;
131
153
  skipped(positionMs: number): void;
132
154
  error(): void;
133
- /** POST /click (500 ms budget), then open the destination. Resolves with the URL opened. */
134
- clicked(): Promise<string>;
155
+ /**
156
+ * POST /click (500 ms budget), then open the destination. Resolves with the URL opened.
157
+ * House ads only: `{ open: false }` counts the tap without opening anything,
158
+ * for an app that sends it to its own screen. A paid ad always opens the
159
+ * advertiser's page.
160
+ */
161
+ clicked(opts?: {
162
+ open?: boolean;
163
+ }): Promise<string>;
135
164
  /** Call when the ad screen goes away. Sends queued video events. */
136
165
  closed(): Promise<void>;
137
166
  /** True once the ad is older than token_ttl_s: it must not be shown. */
138
167
  isExpired(): boolean;
139
168
  }
169
+ /** Per-call options for preload() and loadInterstitial(). */
170
+ export interface LoadOptions {
171
+ /**
172
+ * false treats a house ad as no fill for this call, so the app can show its
173
+ * own fallback. Default: the client's setting (options.houseAds, default true).
174
+ */
175
+ houseAds?: boolean;
176
+ }
140
177
  export type InterstitialResult = {
141
178
  ad: EthiclyAd;
142
179
  tracker: Tracker;
@@ -163,9 +200,14 @@ export interface WireAd {
163
200
  mime?: string | null;
164
201
  } | null;
165
202
  }
203
+ /** Raw house ad, sent next to `ad: null` on an interstitial no-fill when the serve asked with house_ads=1. */
204
+ export interface WireHouseAd extends WireAd {
205
+ test?: boolean;
206
+ }
166
207
  export interface WireServe {
167
208
  ad: WireAd | null;
168
209
  reason?: string;
210
+ house_ad?: WireHouseAd | null;
169
211
  publisher_site_id?: number;
170
212
  country_code?: string;
171
213
  impression_token?: string;
@@ -173,3 +215,46 @@ export interface WireServe {
173
215
  test?: boolean;
174
216
  request_id?: string;
175
217
  }
218
+ /**
219
+ * How often ads may show, set in code. Each field set here wins over the
220
+ * dashboard value from /config (interstitial.max_per_session, min_gap_s);
221
+ * an unset field falls back to /config, then to the defaults (3 and 120).
222
+ */
223
+ export interface FrequencyOptions {
224
+ /**
225
+ * Ads per session. 0 shows none. Any integer >= 0; Infinity (or a large
226
+ * number such as 1000000) means no session limit.
227
+ */
228
+ maxPerSession?: number;
229
+ /** Seconds between two ads, kept across restarts. 0 means no gap. Finite, >= 0. */
230
+ minGapSeconds?: number;
231
+ }
232
+ /** setFrequency(): a field left out keeps its current value, null goes back to /config. */
233
+ export interface FrequencyUpdate {
234
+ maxPerSession?: number | null;
235
+ minGapSeconds?: number | null;
236
+ }
237
+ /** Why nextAdStatus() says no ad may show now. */
238
+ export type NextAdReason =
239
+ /** The gap between ads (min_gap_s) has not passed: see retryAt. */
240
+ 'frequency_capped'
241
+ /** max_per_session ads were shown this session. */
242
+ | 'session_cap'
243
+ /** setAdsEnabled(false), for example a paid user. */
244
+ | 'ads_disabled'
245
+ /** The stored frequency state is still loading (see `ready`). */
246
+ | 'not_ready' | 'invalid_key' | 'unknown_key' | 'sdk_unsupported' | 'app_disabled' | 'interstitial_disabled';
247
+ export interface NextAdStatus {
248
+ /** Same as canShow(). */
249
+ allowed: boolean;
250
+ /** Set when allowed is false. */
251
+ reason?: NextAdReason;
252
+ /** Epoch ms when the gap ends. Only with reason 'frequency_capped'. */
253
+ retryAt?: number;
254
+ /** Ads shown in the current session. */
255
+ shownThisSession: number;
256
+ /** The effective per-session limit (Infinity for none). */
257
+ maxPerSession: number;
258
+ /** The effective gap between ads, in seconds. */
259
+ minGapSeconds: number;
260
+ }
@@ -16,6 +16,13 @@ export interface EthiclyInterstitialProps {
16
16
  /** Shows a "Remove ads" link under the button that calls this. */
17
17
  onRemoveAds?(): void;
18
18
  removeAdsLabel?: string;
19
+ /**
20
+ * House ads only: a tap on the button counts the tap, closes the ad (as
21
+ * onClose does) and calls this instead of opening the house ad's link, for
22
+ * example to open the app's premium screen. Wins over the hook's and
23
+ * createEthicly's onHouseAdPress. Paid ads always open the advertiser's page.
24
+ */
25
+ onHouseAdPress?(ad: EthiclyAd): void;
19
26
  /** Replaces the "Remove ads" link with anything the app wants. */
20
27
  renderBelowButton?(): React.ReactNode;
21
28
  /** Default true: wraps the screen in a fullscreen Modal. */
@@ -1,14 +1,28 @@
1
1
  import type { Ethicly } from '../core/client';
2
- import type { EthiclyAd, NoFillReason, Tracker } from '../core/types';
2
+ import type { EthiclyAd, NextAdStatus, NoFillReason, Tracker } from '../core/types';
3
3
  export interface UseEthiclyInterstitialOptions {
4
4
  /** Preload on mount and after each dismiss. Default true. */
5
5
  preload?: boolean;
6
+ /**
7
+ * false treats a house ad as no fill, so `reason` is set and the app shows
8
+ * its own fallback. Default: the client's setting (createEthicly houseAds).
9
+ */
10
+ houseAds?: boolean;
11
+ /**
12
+ * House ads only: where EthiclyInterstitial sends a tap on the button
13
+ * instead of opening the link (the ad closes first). Wins over
14
+ * createEthicly's onHouseAdPress; the screen's own prop wins over this.
15
+ */
16
+ onHouseAdPress?: (ad: EthiclyAd) => void;
6
17
  }
7
18
  export interface EthiclyInterstitialState {
8
- /** The ad to render, set by a successful show(). */
19
+ /** The ad to render, set by a successful show(). `ad.house` is true for the publisher's house ad. */
9
20
  ad: EthiclyAd | null;
10
21
  tracker: Tracker | null;
11
- /** Why the last show() found no ad: show your house ad, except for 'ads_disabled' (a paid user). */
22
+ /**
23
+ * Why the last show() found no ad: show your own fallback if you have one,
24
+ * except for 'ads_disabled' (a paid user). Null when a house ad was shown.
25
+ */
12
26
  reason: NoFillReason | null;
13
27
  loading: boolean;
14
28
  /** Load the ad to show now. Resolves true when `ad` is set, false on no fill. */
@@ -16,5 +30,7 @@ export interface EthiclyInterstitialState {
16
30
  /** Close the current ad: flushes queued events and preloads the next one. */
17
31
  dismiss(): void;
18
32
  canShow(): boolean;
33
+ /** Whether an ad may show now and, when not, why and until when. Same as ethicly.nextAdStatus(). */
34
+ nextAdStatus(): NextAdStatus;
19
35
  }
20
36
  export declare function useEthiclyInterstitial(ethicly: Ethicly, options?: UseEthiclyInterstitialOptions): EthiclyInterstitialState;
@@ -1,2 +1,2 @@
1
1
  /** SDK version, sent as sdk_version and in X-Ethicly-SDK. Keep in step with package.json. */
2
- export declare const SDK_VERSION = "0.2.1";
2
+ export declare const SDK_VERSION = "0.4.0";
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ethicly/react-native",
3
- "version": "0.2.1",
3
+ "version": "0.4.0",
4
4
  "description": "Ethicly fullscreen video ads for React Native and Expo. Headless core plus an optional ready-made screen.",
5
5
  "license": "MIT",
6
6
  "homepage": "https://ethicly.ch",
package/src/core/cache.ts CHANGED
@@ -168,14 +168,16 @@ export class CreativeCache {
168
168
  * `allowed()` is checked before every download so setAdsEnabled(false)
169
169
  * stops a download that has not started yet; cancel() also stops the one in
170
170
  * flight when the adapter supports it.
171
+ * `adId` keys the entry and names the files: house ads pass `house-<id>`
172
+ * because their ids can collide with paid ad ids.
171
173
  */
172
- ensure(adId: number, urls: string[], limits: CacheLimits, allowed: () => boolean): Promise<CachedMedia> {
174
+ ensure(adId: string | number, urls: string[], limits: CacheLimits, allowed: () => boolean): Promise<CachedMedia> {
173
175
  const run = this.chain.then(() => this.ensureNow(adId, urls, limits, allowed));
174
176
  this.chain = run.catch(() => undefined);
175
177
  return run;
176
178
  }
177
179
 
178
- private async ensureNow(adId: number, urls: string[], limits: CacheLimits, allowed: () => boolean): Promise<CachedMedia> {
180
+ private async ensureNow(adId: string | number, urls: string[], limits: CacheLimits, allowed: () => boolean): Promise<CachedMedia> {
179
181
  await this.load();
180
182
  if (limits.maxCreatives <= 0 || limits.maxBytes <= 0) return { uris: {} };
181
183
  const key = `${adId}:${hash(urls.join('|'))}`;