@ethicly/react-native 0.2.1 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -5,6 +5,39 @@ follows [Keep a Changelog](https://keepachangelog.com/en/1.1.0/) and the
5
5
  package uses [Semantic Versioning](https://semver.org/). Every version speaks
6
6
  contract v1 of the Ethicly app API.
7
7
 
8
+ ## [0.3.0] - 2026-11-21
9
+
10
+ ### Added
11
+
12
+ - `/click` now carries the impression's `viewable_token`, so the server can
13
+ bill a tap made before the view was confirmed and refuse unproven clicks.
14
+ - `frequency: { maxPerSession?, minGapSeconds? }` on `createEthicly`. The
15
+ publisher decides how often ads show: each field set in code wins over the
16
+ dashboard values from `/config` (`interstitial.max_per_session`,
17
+ `min_gap_s`); a field left out falls back to `/config`, then the defaults.
18
+ Any value 0 or above is accepted: `maxPerSession: 0` shows no ads,
19
+ `Infinity` or a large number means no session limit, `minGapSeconds: 0`
20
+ means no gap. Negative values count as 0; non-numbers are ignored with a
21
+ warning.
22
+ - `setFrequency(update)` changes the frequency at runtime (after an
23
+ entitlement check or an A/B test). A field left out keeps its value; `null`
24
+ goes back to `/config`. `getFrequency()` returns the values in effect.
25
+ - `nextAdStatus()` on the client and on `useEthiclyInterstitial`: whether an
26
+ ad may show now and, when not, the reason (`frequency_capped` with
27
+ `retryAt`, `session_cap`, `ads_disabled`, `not_ready` or a server gate) plus
28
+ `shownThisSession`, `maxPerSession` and `minGapSeconds`.
29
+ - README and INTEGRATING: "What you control and what Ethicly controls". Ads
30
+ shown beyond Ethicly's anti-abuse limits still play but are not billed.
31
+ - Example app: a status line under the buttons explains every no-ad case,
32
+ with a live countdown to the next allowed ad, and a "Demo: no frequency
33
+ limit" toggle.
34
+
35
+ ### Changed
36
+
37
+ - `canShow()` is now `nextAdStatus().allowed`; its answers are unchanged.
38
+ Without `frequency`, behaviour is identical to 0.2.x. Billing and the event
39
+ outbox are unchanged.
40
+
8
41
  ## [0.2.1] - 2026-11-21
9
42
 
10
43
  ### Fixed
package/README.md CHANGED
@@ -110,8 +110,52 @@ It speaks contract v1 of the Ethicly app API. It ships no native code of its own
110
110
  time of the last ad is stored through `storage`, so `min_gap_s` also holds
111
111
  across restarts.
112
112
 
113
+ **You decide how often.** The dashboard values are only the starting point.
114
+ Set them in code and they win for this client:
115
+
116
+ ```ts
117
+ const ethicly = createEthicly({
118
+ // ...
119
+ frequency: { maxPerSession: 5, minGapSeconds: 60 },
120
+ });
121
+ // Later, for example after an A/B test or an entitlement check:
122
+ ethicly.setFrequency({ minGapSeconds: 30 }); // maxPerSession stays 5
123
+ ethicly.setFrequency({ maxPerSession: null }); // back to the dashboard value
124
+ ```
125
+
126
+ Each field you set wins over `/config`; a field you leave out uses the
127
+ dashboard value, then the defaults (3 per session, 120 s). Any number 0 or
128
+ above works: `maxPerSession: 0` shows no ads, `maxPerSession: Infinity` (or
129
+ a large number such as `1_000_000`) means no session limit,
130
+ `minGapSeconds: 0` means no gap. A negative value counts as 0; anything
131
+ that is not a number is ignored with a warning. Without `frequency` the SDK
132
+ behaves exactly as 0.2.x. `ethicly.getFrequency()` returns the values in
133
+ effect.
134
+
135
+ **Tell the user when the next ad may show.** `ethicly.nextAdStatus()` (also
136
+ on the hook) says whether an ad may show now and, when not, why:
137
+
138
+ ```ts
139
+ const s = ethicly.nextAdStatus();
140
+ // { allowed: false, reason: 'frequency_capped', retryAt: 1763730000000,
141
+ // shownThisSession: 1, maxPerSession: 3, minGapSeconds: 120 }
142
+ ```
143
+
144
+ | `reason` | Meaning |
145
+ |---|---|
146
+ | `frequency_capped` | the gap between ads is running; `retryAt` (epoch ms) is when it ends |
147
+ | `session_cap` | `maxPerSession` ads were shown this session; no `retryAt` (a new session starts after 30 minutes in the background) |
148
+ | `ads_disabled` | `setAdsEnabled(false)`, a paid user |
149
+ | `not_ready` | the stored frequency state is still loading |
150
+ | `invalid_key`, `unknown_key`, `sdk_unsupported`, `app_disabled`, `interstitial_disabled` | the same gates `loadInterstitial()` reports |
151
+
152
+ `canShow()` is `nextAdStatus().allowed`. `loadInterstitial()` still
153
+ reports both caps as `frequency_capped`, as in 0.2.x.
154
+
113
155
  5. **Call the tracker from your player.** Play `ad.media.videoUri` (a local
114
- file when cached, else the remote URL), show `ad.ctaLabel` on the button,
156
+ file when cached, else the remote URL), show `ad.ctaLabel` on the button
157
+ with a small "Sponsored by Ethicly.ch" line under it (required, as on the
158
+ ready-made screen),
115
159
  allow skipping after `ad.skipAfterMs` (always 8 to 15 seconds: the SDK
116
160
  clamps the server's value), play with sound unless `ad.audio` is `none`
117
161
  (always muted) or `optional` (start muted), then:
@@ -233,6 +277,33 @@ pass `AsyncStorage` to keep creatives across launches. A custom
233
277
  same guarantee, and `cancel()` so `setAdsEnabled(false)` and the one-minute
234
278
  limit can stop a download in flight.
235
279
 
280
+ ## What you control and what Ethicly controls
281
+
282
+ You, the publisher, decide how ads fit your app:
283
+
284
+ - **How often:** the `frequency` option or `setFrequency()` in code, or the
285
+ dashboard values when you set nothing.
286
+ - **When:** which moments in your app call `show()` or `loadInterstitial()`.
287
+ - **Paid users:** `setAdsEnabled(false)` means no serves and no downloads.
288
+ - **Sound:** the `audio` option or prop.
289
+ - **Fallback:** what to show when no Ethicly ad is available (your house ad).
290
+ - **Player:** the ready-made screen or your own player with the tracker.
291
+
292
+ Ethicly decides:
293
+
294
+ - **Which ad** is served.
295
+ - **The skip window:** Skip appears after 8 to 15 seconds.
296
+ - **The ad labels:** the "Ad" label and the "Sponsored by Ethicly.ch" line
297
+ under the button stay visible, also in your own player.
298
+ - **What counts** as a billable view or a billable click.
299
+ - **Billing** and payouts.
300
+ - **Anti-abuse limits**, such as a minimum time between billable views from
301
+ the same app.
302
+ - **The kill switch** and the **minimum SDK version**.
303
+
304
+ Ads you show beyond Ethicly's anti-abuse limits still play, but they are not
305
+ billed. Showing ads more often than those limits allow does not earn more.
306
+
236
307
  ## Test mode
237
308
 
238
309
  `testMode: true` adds `test=1` to the serve request. You get real ads and run
@@ -278,6 +349,7 @@ createEthicly(options: {
278
349
  adsEnabled?: boolean; // default true; pass false until entitlement is known (paid tier)
279
350
  audio?: 'on' | 'optional' | 'none'; // overrides the server's interstitial.audio for every ad
280
351
  loadTimeoutMs?: number; // default 3000: longest loadInterstitial() waits for a download
352
+ frequency?: { maxPerSession?: number; minGapSeconds?: number }; // wins over /config; unset: /config
281
353
  storage?: KeyValueStorage; // AsyncStorage shape; default in memory
282
354
  fileCache?: FileCacheAdapter; // download/exists/delete/size/list/cancel; default streams
283
355
  openUrl?: (url: string) => unknown;
@@ -294,6 +366,9 @@ interface Ethicly {
294
366
  preload(): Promise<InterstitialResult>;
295
367
  loadInterstitial(): Promise<InterstitialResult>;
296
368
  canShow(): boolean; // false until the stored frequency state loaded
369
+ nextAdStatus(): NextAdStatus; // allowed, reason, retryAt, shownThisSession, maxPerSession, minGapSeconds
370
+ setFrequency(update: { maxPerSession?: number | null; minGapSeconds?: number | null }): void; // null: back to /config
371
+ getFrequency(): { maxPerSession: number; minGapSeconds: number };
297
372
  setAdsEnabled(enabled: boolean): void;
298
373
  isAdsEnabled(): boolean;
299
374
  getConfig(): EthiclyConfig;
@@ -375,9 +450,12 @@ not legal advice; you are responsible for your app's declarations.
375
450
  - a two-letter country code. The server derives it from the device's IP
376
451
  address with its own database (no third party). The IP address itself is
377
452
  used in transit (country lookup, rate limiting) and is not written to
378
- Ethicly's database or to the ad server's own logs, except as a salted hash
379
- combined with the ad id, used to cap clicks per IP and deleted after two
380
- days. Request logs kept by Ethicly's hosting platform are outside this
453
+ Ethicly's database or to the ad server's own logs, except as two salted
454
+ hashes used against fraud: one combined with the ad id, used to cap clicks
455
+ per IP and deleted after two days; and one combined with your site and the
456
+ day, used to cap billable views per network and deleted after about two
457
+ hours. Neither identifies a device or links data across apps. Request logs
458
+ kept by Ethicly's hosting platform are outside this
381
459
  list.
382
460
 
383
461
  Serve and `/config` requests store nothing per request. The User-Agent header
@@ -25,6 +25,23 @@ const DEFAULT_TTL_S = 3600;
25
25
  */
26
26
  exports.SESSION_TIMEOUT_MS = 30 * 60 * 1000;
27
27
  let releaseTestModeLogged = false;
28
+ /** Same ceiling as the dashboard's gap between ads (24 hours). */
29
+ const MAX_MIN_GAP_S = 86400;
30
+ /**
31
+ * A frequency value from code: undefined when not a usable number, else >= 0.
32
+ * Infinity only where `allowInfinity`.
33
+ */
34
+ function frequencyValue(v, name, allowInfinity, log) {
35
+ if (typeof v !== 'number' || Number.isNaN(v) || (v === Infinity && !allowInfinity) || v === -Infinity) {
36
+ log.warn(`frequency.${name} must be a number >= 0${allowInfinity ? ' or Infinity' : ''}: using the dashboard value`);
37
+ return undefined;
38
+ }
39
+ if (v < 0) {
40
+ log.warn(`frequency.${name} below 0: using 0`);
41
+ return 0;
42
+ }
43
+ return v;
44
+ }
28
45
  function audioPolicy(v) {
29
46
  return v === 'on' || v === 'optional' || v === 'none' ? v : null;
30
47
  }
@@ -52,6 +69,9 @@ class EthiclyClient {
52
69
  this.shownCount = 0;
53
70
  this.lastShownAt = null;
54
71
  this.frequencyLoaded = false;
72
+ /** Frequency set in code, null where /config decides. */
73
+ this.maxPerSessionOverride = null;
74
+ this.minGapSOverride = null;
55
75
  /** When the app left the foreground, null while it is in it. */
56
76
  this.backgroundSince = null;
57
77
  this.preloaded = null;
@@ -78,6 +98,8 @@ class EthiclyClient {
78
98
  this.loadTimeoutMs = typeof o.loadTimeoutMs === 'number' && Number.isFinite(o.loadTimeoutMs) && o.loadTimeoutMs >= 0
79
99
  ? o.loadTimeoutMs
80
100
  : exports.DEFAULT_LOAD_TIMEOUT_MS;
101
+ if (o.frequency)
102
+ this.setFrequency(o.frequency);
81
103
  this.testMode = !!o.testMode && !(0, adapters_1.isReleaseBuild)();
82
104
  if (o.testMode && !this.testMode)
83
105
  this.reportReleaseTestMode();
@@ -304,15 +326,61 @@ class EthiclyClient {
304
326
  this.log.warn(`config fetch failed (${res.status || 'network'}), keeping the last known config`);
305
327
  }
306
328
  // ------------------------------------------------------------- frequency
307
- canShow() {
329
+ getFrequency() {
330
+ var _a, _b;
308
331
  const it = this.config.interstitial;
309
- if (!this.adsOn || !this.frequencyLoaded || this.blockedReason())
310
- return false;
311
- if (this.shownCount >= it.max_per_session)
312
- return false;
313
- if (this.lastShownAt !== null && this.now() - this.lastShownAt < it.min_gap_s * 1000)
314
- return false;
315
- return true;
332
+ return {
333
+ maxPerSession: (_a = this.maxPerSessionOverride) !== null && _a !== void 0 ? _a : it.max_per_session,
334
+ minGapSeconds: (_b = this.minGapSOverride) !== null && _b !== void 0 ? _b : it.min_gap_s,
335
+ };
336
+ }
337
+ setFrequency(update) {
338
+ if (!update || typeof update !== 'object')
339
+ return;
340
+ if (update.maxPerSession === null)
341
+ this.maxPerSessionOverride = null;
342
+ else if (update.maxPerSession !== undefined) {
343
+ const v = frequencyValue(update.maxPerSession, 'maxPerSession', true, this.log);
344
+ if (v !== undefined) {
345
+ const whole = Math.floor(v);
346
+ if (whole !== v)
347
+ this.log.warn(`frequency.maxPerSession ${v} is not a whole number: using ${whole}${whole === 0 ? ' (no ads)' : ''}`);
348
+ this.maxPerSessionOverride = whole;
349
+ }
350
+ }
351
+ if (update.minGapSeconds === null)
352
+ this.minGapSOverride = null;
353
+ else if (update.minGapSeconds !== undefined) {
354
+ const v = frequencyValue(update.minGapSeconds, 'minGapSeconds', false, this.log);
355
+ if (v !== undefined) {
356
+ if (v > MAX_MIN_GAP_S)
357
+ this.log.warn(`frequency.minGapSeconds above ${MAX_MIN_GAP_S}: using ${MAX_MIN_GAP_S}`);
358
+ this.minGapSOverride = Math.min(v, MAX_MIN_GAP_S);
359
+ }
360
+ }
361
+ }
362
+ nextAdStatus() {
363
+ const { maxPerSession, minGapSeconds } = this.getFrequency();
364
+ const base = { shownThisSession: this.shownCount, maxPerSession, minGapSeconds };
365
+ const no = (reason, retryAt) => (retryAt === undefined ? { ...base, allowed: false, reason } : { ...base, allowed: false, reason, retryAt });
366
+ if (!this.adsOn)
367
+ return no('ads_disabled');
368
+ if (!this.frequencyLoaded)
369
+ return no('not_ready');
370
+ const blocked = this.blockedReason();
371
+ if (blocked)
372
+ return no(blocked);
373
+ if (this.shownCount >= maxPerSession)
374
+ return no('session_cap');
375
+ if (this.lastShownAt !== null) {
376
+ const retryAt = this.lastShownAt + minGapSeconds * 1000;
377
+ if (this.now() < retryAt)
378
+ return no('frequency_capped', retryAt);
379
+ }
380
+ return { ...base, allowed: true };
381
+ }
382
+ canShow() {
383
+ return this.nextAdStatus().allowed;
316
384
  }
317
385
  onShown() {
318
386
  this.shownCount += 1;
@@ -384,7 +452,7 @@ class EthiclyClient {
384
452
  if (this.preloaded && !this.preloaded.result.tracker.isExpired())
385
453
  return this.preloaded.result;
386
454
  this.preloaded = null;
387
- if (this.shownCount >= this.config.interstitial.max_per_session)
455
+ if (this.shownCount >= this.getFrequency().maxPerSession)
388
456
  return this.noFill('frequency_capped');
389
457
  const out = await this.serveOnce();
390
458
  if (!out.served)
@@ -352,6 +352,9 @@ class InterstitialTracker {
352
352
  body.publisher_site_id = serve.publisherSiteId;
353
353
  if (serve.countryCode)
354
354
  body.country_code = serve.countryCode;
355
+ // Proof the view was served: lets the server bill a tap made before /viewable.
356
+ if (imp.viewableToken)
357
+ body.viewable_token = imp.viewableToken;
355
358
  // Never retried: one request, whatever happens.
356
359
  const res = await (0, http_1.httpRequest)(ctx.fetch, `${ctx.serveBase()}/click`, {
357
360
  method: 'POST', headers: ctx.headers(), body, timeoutMs: Math.min(remaining, beacons_1.BEACON_TIMEOUT_MS),
@@ -50,5 +50,8 @@ function useEthiclyInterstitial(ethicly, options = {}) {
50
50
  void ethicly.preload();
51
51
  }, [ethicly, preload]);
52
52
  const canShow = (0, react_1.useCallback)(() => ethicly.canShow(), [ethicly]);
53
- 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 };
53
+ const nextAdStatus = (0, react_1.useCallback)(() => ethicly.nextAdStatus(), [ethicly]);
54
+ return {
55
+ 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,
56
+ };
54
57
  }
@@ -2,4 +2,4 @@
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.SDK_VERSION = void 0;
4
4
  /** SDK version, sent as sdk_version and in X-Ethicly-SDK. Keep in step with package.json. */
5
- exports.SDK_VERSION = '0.2.1';
5
+ exports.SDK_VERSION = '0.3.0';
@@ -21,6 +21,23 @@ const DEFAULT_TTL_S = 3600;
21
21
  */
22
22
  export const SESSION_TIMEOUT_MS = 30 * 60 * 1000;
23
23
  let releaseTestModeLogged = false;
24
+ /** Same ceiling as the dashboard's gap between ads (24 hours). */
25
+ const MAX_MIN_GAP_S = 86400;
26
+ /**
27
+ * A frequency value from code: undefined when not a usable number, else >= 0.
28
+ * Infinity only where `allowInfinity`.
29
+ */
30
+ function frequencyValue(v, name, allowInfinity, log) {
31
+ if (typeof v !== 'number' || Number.isNaN(v) || (v === Infinity && !allowInfinity) || v === -Infinity) {
32
+ log.warn(`frequency.${name} must be a number >= 0${allowInfinity ? ' or Infinity' : ''}: using the dashboard value`);
33
+ return undefined;
34
+ }
35
+ if (v < 0) {
36
+ log.warn(`frequency.${name} below 0: using 0`);
37
+ return 0;
38
+ }
39
+ return v;
40
+ }
24
41
  function audioPolicy(v) {
25
42
  return v === 'on' || v === 'optional' || v === 'none' ? v : null;
26
43
  }
@@ -48,6 +65,9 @@ class EthiclyClient {
48
65
  this.shownCount = 0;
49
66
  this.lastShownAt = null;
50
67
  this.frequencyLoaded = false;
68
+ /** Frequency set in code, null where /config decides. */
69
+ this.maxPerSessionOverride = null;
70
+ this.minGapSOverride = null;
51
71
  /** When the app left the foreground, null while it is in it. */
52
72
  this.backgroundSince = null;
53
73
  this.preloaded = null;
@@ -74,6 +94,8 @@ class EthiclyClient {
74
94
  this.loadTimeoutMs = typeof o.loadTimeoutMs === 'number' && Number.isFinite(o.loadTimeoutMs) && o.loadTimeoutMs >= 0
75
95
  ? o.loadTimeoutMs
76
96
  : DEFAULT_LOAD_TIMEOUT_MS;
97
+ if (o.frequency)
98
+ this.setFrequency(o.frequency);
77
99
  this.testMode = !!o.testMode && !isReleaseBuild();
78
100
  if (o.testMode && !this.testMode)
79
101
  this.reportReleaseTestMode();
@@ -300,15 +322,61 @@ class EthiclyClient {
300
322
  this.log.warn(`config fetch failed (${res.status || 'network'}), keeping the last known config`);
301
323
  }
302
324
  // ------------------------------------------------------------- frequency
303
- canShow() {
325
+ getFrequency() {
326
+ var _a, _b;
304
327
  const it = this.config.interstitial;
305
- if (!this.adsOn || !this.frequencyLoaded || this.blockedReason())
306
- return false;
307
- if (this.shownCount >= it.max_per_session)
308
- return false;
309
- if (this.lastShownAt !== null && this.now() - this.lastShownAt < it.min_gap_s * 1000)
310
- return false;
311
- return true;
328
+ return {
329
+ maxPerSession: (_a = this.maxPerSessionOverride) !== null && _a !== void 0 ? _a : it.max_per_session,
330
+ minGapSeconds: (_b = this.minGapSOverride) !== null && _b !== void 0 ? _b : it.min_gap_s,
331
+ };
332
+ }
333
+ setFrequency(update) {
334
+ if (!update || typeof update !== 'object')
335
+ return;
336
+ if (update.maxPerSession === null)
337
+ this.maxPerSessionOverride = null;
338
+ else if (update.maxPerSession !== undefined) {
339
+ const v = frequencyValue(update.maxPerSession, 'maxPerSession', true, this.log);
340
+ if (v !== undefined) {
341
+ const whole = Math.floor(v);
342
+ if (whole !== v)
343
+ this.log.warn(`frequency.maxPerSession ${v} is not a whole number: using ${whole}${whole === 0 ? ' (no ads)' : ''}`);
344
+ this.maxPerSessionOverride = whole;
345
+ }
346
+ }
347
+ if (update.minGapSeconds === null)
348
+ this.minGapSOverride = null;
349
+ else if (update.minGapSeconds !== undefined) {
350
+ const v = frequencyValue(update.minGapSeconds, 'minGapSeconds', false, this.log);
351
+ if (v !== undefined) {
352
+ if (v > MAX_MIN_GAP_S)
353
+ this.log.warn(`frequency.minGapSeconds above ${MAX_MIN_GAP_S}: using ${MAX_MIN_GAP_S}`);
354
+ this.minGapSOverride = Math.min(v, MAX_MIN_GAP_S);
355
+ }
356
+ }
357
+ }
358
+ nextAdStatus() {
359
+ const { maxPerSession, minGapSeconds } = this.getFrequency();
360
+ const base = { shownThisSession: this.shownCount, maxPerSession, minGapSeconds };
361
+ const no = (reason, retryAt) => (retryAt === undefined ? { ...base, allowed: false, reason } : { ...base, allowed: false, reason, retryAt });
362
+ if (!this.adsOn)
363
+ return no('ads_disabled');
364
+ if (!this.frequencyLoaded)
365
+ return no('not_ready');
366
+ const blocked = this.blockedReason();
367
+ if (blocked)
368
+ return no(blocked);
369
+ if (this.shownCount >= maxPerSession)
370
+ return no('session_cap');
371
+ if (this.lastShownAt !== null) {
372
+ const retryAt = this.lastShownAt + minGapSeconds * 1000;
373
+ if (this.now() < retryAt)
374
+ return no('frequency_capped', retryAt);
375
+ }
376
+ return { ...base, allowed: true };
377
+ }
378
+ canShow() {
379
+ return this.nextAdStatus().allowed;
312
380
  }
313
381
  onShown() {
314
382
  this.shownCount += 1;
@@ -380,7 +448,7 @@ class EthiclyClient {
380
448
  if (this.preloaded && !this.preloaded.result.tracker.isExpired())
381
449
  return this.preloaded.result;
382
450
  this.preloaded = null;
383
- if (this.shownCount >= this.config.interstitial.max_per_session)
451
+ if (this.shownCount >= this.getFrequency().maxPerSession)
384
452
  return this.noFill('frequency_capped');
385
453
  const out = await this.serveOnce();
386
454
  if (!out.served)
@@ -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),
@@ -47,5 +47,8 @@ export function useEthiclyInterstitial(ethicly, options = {}) {
47
47
  void ethicly.preload();
48
48
  }, [ethicly, preload]);
49
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 };
50
+ const nextAdStatus = useCallback(() => ethicly.nextAdStatus(), [ethicly]);
51
+ return {
52
+ 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,
53
+ };
51
54
  }
@@ -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.3.0';
@@ -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, EthiclyConfig, FetchLike, FileCacheAdapter, FrequencyOptions, FrequencyUpdate, InterstitialResult, KeyValueStorage, Logger, NextAdStatus, NoFillReason, Platform } from './types';
3
3
  export interface EthiclyOptions {
4
4
  /** Publisher API key (UUID). */
5
5
  apiKey: string;
@@ -34,6 +34,13 @@ 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;
37
44
  storage?: KeyValueStorage;
38
45
  fileCache?: FileCacheAdapter;
39
46
  openUrl?: (url: string) => unknown;
@@ -58,6 +65,18 @@ export interface Ethicly {
58
65
  * false until the stored frequency state has loaded (see `ready`).
59
66
  */
60
67
  canShow(): boolean;
68
+ /**
69
+ * Whether an ad may show now and, when not, why and when it may: retryAt is
70
+ * set while the gap between ads runs. canShow() is nextAdStatus().allowed.
71
+ */
72
+ nextAdStatus(): NextAdStatus;
73
+ /**
74
+ * Change the frequency set in code, for example after an entitlement check
75
+ * or an A/B test. A field left out keeps its value; null goes back to /config.
76
+ */
77
+ setFrequency(update: FrequencyUpdate): void;
78
+ /** The effective frequency: code, else /config, else the defaults. */
79
+ getFrequency(): Required<FrequencyOptions>;
61
80
  /** false for paid users: stops serves, drops the preloaded ad and cancels a download in flight. */
62
81
  setAdsEnabled(enabled: boolean): void;
63
82
  isAdsEnabled(): boolean;
@@ -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, Logger, NextAdReason, NextAdStatus, NoFillReason, Platform, Tracker, } from './types';
@@ -173,3 +173,46 @@ export interface WireServe {
173
173
  test?: boolean;
174
174
  request_id?: string;
175
175
  }
176
+ /**
177
+ * How often ads may show, set in code. Each field set here wins over the
178
+ * dashboard value from /config (interstitial.max_per_session, min_gap_s);
179
+ * an unset field falls back to /config, then to the defaults (3 and 120).
180
+ */
181
+ export interface FrequencyOptions {
182
+ /**
183
+ * Ads per session. 0 shows none. Any integer >= 0; Infinity (or a large
184
+ * number such as 1000000) means no session limit.
185
+ */
186
+ maxPerSession?: number;
187
+ /** Seconds between two ads, kept across restarts. 0 means no gap. Finite, >= 0. */
188
+ minGapSeconds?: number;
189
+ }
190
+ /** setFrequency(): a field left out keeps its current value, null goes back to /config. */
191
+ export interface FrequencyUpdate {
192
+ maxPerSession?: number | null;
193
+ minGapSeconds?: number | null;
194
+ }
195
+ /** Why nextAdStatus() says no ad may show now. */
196
+ export type NextAdReason =
197
+ /** The gap between ads (min_gap_s) has not passed: see retryAt. */
198
+ 'frequency_capped'
199
+ /** max_per_session ads were shown this session. */
200
+ | 'session_cap'
201
+ /** setAdsEnabled(false), for example a paid user. */
202
+ | 'ads_disabled'
203
+ /** The stored frequency state is still loading (see `ready`). */
204
+ | 'not_ready' | 'invalid_key' | 'unknown_key' | 'sdk_unsupported' | 'app_disabled' | 'interstitial_disabled';
205
+ export interface NextAdStatus {
206
+ /** Same as canShow(). */
207
+ allowed: boolean;
208
+ /** Set when allowed is false. */
209
+ reason?: NextAdReason;
210
+ /** Epoch ms when the gap ends. Only with reason 'frequency_capped'. */
211
+ retryAt?: number;
212
+ /** Ads shown in the current session. */
213
+ shownThisSession: number;
214
+ /** The effective per-session limit (Infinity for none). */
215
+ maxPerSession: number;
216
+ /** The effective gap between ads, in seconds. */
217
+ minGapSeconds: number;
218
+ }
@@ -1,5 +1,5 @@
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;
@@ -16,5 +16,7 @@ export interface EthiclyInterstitialState {
16
16
  /** Close the current ad: flushes queued events and preloads the next one. */
17
17
  dismiss(): void;
18
18
  canShow(): boolean;
19
+ /** Whether an ad may show now and, when not, why and until when. Same as ethicly.nextAdStatus(). */
20
+ nextAdStatus(): NextAdStatus;
19
21
  }
20
22
  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.3.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.3.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",
@@ -13,8 +13,8 @@ import { outboxFor, replayRecord, type Outbox } from './outbox';
13
13
  import { InterstitialTracker } from './tracker';
14
14
  import { SDK_VERSION } from '../version';
15
15
  import type {
16
- AudioPolicy, EthiclyAd, EthiclyConfig, FetchLike, FileCacheAdapter, InterstitialResult, KeyValueStorage,
17
- Logger, NoFillReason, Platform, WireServe,
16
+ AudioPolicy, EthiclyAd, EthiclyConfig, FetchLike, FileCacheAdapter, FrequencyOptions, FrequencyUpdate,
17
+ InterstitialResult, KeyValueStorage, Logger, NextAdReason, NextAdStatus, NoFillReason, Platform, WireServe,
18
18
  } from './types';
19
19
 
20
20
  export interface EthiclyOptions {
@@ -51,6 +51,13 @@ export interface EthiclyOptions {
51
51
  * download carries on in the background for next time.
52
52
  */
53
53
  loadTimeoutMs?: number;
54
+ /**
55
+ * How often ads may show, decided in code. A field set here overrides the
56
+ * dashboard value (/config interstitial.max_per_session, min_gap_s) for this
57
+ * client; an unset field uses /config, then the defaults. Unset: 0.2.x
58
+ * behaviour. Change it later with setFrequency().
59
+ */
60
+ frequency?: FrequencyOptions;
54
61
  storage?: KeyValueStorage;
55
62
  fileCache?: FileCacheAdapter;
56
63
  openUrl?: (url: string) => unknown;
@@ -76,6 +83,18 @@ export interface Ethicly {
76
83
  * false until the stored frequency state has loaded (see `ready`).
77
84
  */
78
85
  canShow(): boolean;
86
+ /**
87
+ * Whether an ad may show now and, when not, why and when it may: retryAt is
88
+ * set while the gap between ads runs. canShow() is nextAdStatus().allowed.
89
+ */
90
+ nextAdStatus(): NextAdStatus;
91
+ /**
92
+ * Change the frequency set in code, for example after an entitlement check
93
+ * or an A/B test. A field left out keeps its value; null goes back to /config.
94
+ */
95
+ setFrequency(update: FrequencyUpdate): void;
96
+ /** The effective frequency: code, else /config, else the defaults. */
97
+ getFrequency(): Required<FrequencyOptions>;
79
98
  /** false for paid users: stops serves, drops the preloaded ad and cancels a download in flight. */
80
99
  setAdsEnabled(enabled: boolean): void;
81
100
  isAdsEnabled(): boolean;
@@ -119,6 +138,25 @@ interface Served {
119
138
 
120
139
  type ServeOutcome = { served: Served; noFill?: undefined } | { served?: undefined; noFill: InterstitialResult };
121
140
 
141
+ /** Same ceiling as the dashboard's gap between ads (24 hours). */
142
+ const MAX_MIN_GAP_S = 86400;
143
+
144
+ /**
145
+ * A frequency value from code: undefined when not a usable number, else >= 0.
146
+ * Infinity only where `allowInfinity`.
147
+ */
148
+ function frequencyValue(v: unknown, name: string, allowInfinity: boolean, log: Required<Logger>): number | undefined {
149
+ if (typeof v !== 'number' || Number.isNaN(v) || (v === Infinity && !allowInfinity) || v === -Infinity) {
150
+ log.warn(`frequency.${name} must be a number >= 0${allowInfinity ? ' or Infinity' : ''}: using the dashboard value`);
151
+ return undefined;
152
+ }
153
+ if (v < 0) {
154
+ log.warn(`frequency.${name} below 0: using 0`);
155
+ return 0;
156
+ }
157
+ return v;
158
+ }
159
+
122
160
  function audioPolicy(v: unknown): AudioPolicy | null {
123
161
  return v === 'on' || v === 'optional' || v === 'none' ? v : null;
124
162
  }
@@ -160,6 +198,9 @@ class EthiclyClient implements Ethicly {
160
198
  private shownCount = 0;
161
199
  private lastShownAt: number | null = null;
162
200
  private frequencyLoaded = false;
201
+ /** Frequency set in code, null where /config decides. */
202
+ private maxPerSessionOverride: number | null = null;
203
+ private minGapSOverride: number | null = null;
163
204
  /** When the app left the foreground, null while it is in it. */
164
205
  private backgroundSince: number | null = null;
165
206
  private outbox: Outbox;
@@ -192,6 +233,7 @@ class EthiclyClient implements Ethicly {
192
233
  this.loadTimeoutMs = typeof o.loadTimeoutMs === 'number' && Number.isFinite(o.loadTimeoutMs) && o.loadTimeoutMs >= 0
193
234
  ? o.loadTimeoutMs
194
235
  : DEFAULT_LOAD_TIMEOUT_MS;
236
+ if (o.frequency) this.setFrequency(o.frequency);
195
237
  this.testMode = !!o.testMode && !isReleaseBuild();
196
238
  if (o.testMode && !this.testMode) this.reportReleaseTestMode();
197
239
  if (this.testMode) this.log.warn('test mode is on: nothing is billed. Never ship a release build with testMode.');
@@ -407,12 +449,54 @@ class EthiclyClient implements Ethicly {
407
449
 
408
450
  // ------------------------------------------------------------- frequency
409
451
 
410
- canShow(): boolean {
452
+ getFrequency(): Required<FrequencyOptions> {
411
453
  const it = this.config.interstitial;
412
- if (!this.adsOn || !this.frequencyLoaded || this.blockedReason()) return false;
413
- if (this.shownCount >= it.max_per_session) return false;
414
- if (this.lastShownAt !== null && this.now() - this.lastShownAt < it.min_gap_s * 1000) return false;
415
- return true;
454
+ return {
455
+ maxPerSession: this.maxPerSessionOverride ?? it.max_per_session,
456
+ minGapSeconds: this.minGapSOverride ?? it.min_gap_s,
457
+ };
458
+ }
459
+
460
+ setFrequency(update: FrequencyUpdate): void {
461
+ if (!update || typeof update !== 'object') return;
462
+ if (update.maxPerSession === null) this.maxPerSessionOverride = null;
463
+ else if (update.maxPerSession !== undefined) {
464
+ const v = frequencyValue(update.maxPerSession, 'maxPerSession', true, this.log);
465
+ if (v !== undefined) {
466
+ const whole = Math.floor(v);
467
+ if (whole !== v) this.log.warn(`frequency.maxPerSession ${v} is not a whole number: using ${whole}${whole === 0 ? ' (no ads)' : ''}`);
468
+ this.maxPerSessionOverride = whole;
469
+ }
470
+ }
471
+ if (update.minGapSeconds === null) this.minGapSOverride = null;
472
+ else if (update.minGapSeconds !== undefined) {
473
+ const v = frequencyValue(update.minGapSeconds, 'minGapSeconds', false, this.log);
474
+ if (v !== undefined) {
475
+ if (v > MAX_MIN_GAP_S) this.log.warn(`frequency.minGapSeconds above ${MAX_MIN_GAP_S}: using ${MAX_MIN_GAP_S}`);
476
+ this.minGapSOverride = Math.min(v, MAX_MIN_GAP_S);
477
+ }
478
+ }
479
+ }
480
+
481
+ nextAdStatus(): NextAdStatus {
482
+ const { maxPerSession, minGapSeconds } = this.getFrequency();
483
+ const base = { shownThisSession: this.shownCount, maxPerSession, minGapSeconds };
484
+ const no = (reason: NextAdReason, retryAt?: number): NextAdStatus =>
485
+ (retryAt === undefined ? { ...base, allowed: false, reason } : { ...base, allowed: false, reason, retryAt });
486
+ if (!this.adsOn) return no('ads_disabled');
487
+ if (!this.frequencyLoaded) return no('not_ready');
488
+ const blocked = this.blockedReason();
489
+ if (blocked) return no(blocked);
490
+ if (this.shownCount >= maxPerSession) return no('session_cap');
491
+ if (this.lastShownAt !== null) {
492
+ const retryAt = this.lastShownAt + minGapSeconds * 1000;
493
+ if (this.now() < retryAt) return no('frequency_capped', retryAt);
494
+ }
495
+ return { ...base, allowed: true };
496
+ }
497
+
498
+ canShow(): boolean {
499
+ return this.nextAdStatus().allowed;
416
500
  }
417
501
 
418
502
  private onShown(): void {
@@ -439,7 +523,7 @@ class EthiclyClient implements Ethicly {
439
523
 
440
524
  // ------------------------------------------------------------- serve
441
525
 
442
- private blockedReason(): NoFillReason | null {
526
+ private blockedReason(): Exclude<NextAdReason, 'frequency_capped' | 'session_cap' | 'ads_disabled' | 'not_ready'> | null {
443
527
  if (this.invalidKey) return 'invalid_key';
444
528
  if (this.unknownKey) return 'unknown_key';
445
529
  if (this.sdkUnsupported) return 'sdk_unsupported';
@@ -481,7 +565,7 @@ class EthiclyClient implements Ethicly {
481
565
  if (!this.adsOn) return this.noFill('ads_disabled');
482
566
  if (this.preloaded && !this.preloaded.result.tracker.isExpired()) return this.preloaded.result;
483
567
  this.preloaded = null;
484
- if (this.shownCount >= this.config.interstitial.max_per_session) return this.noFill('frequency_capped');
568
+ if (this.shownCount >= this.getFrequency().maxPerSession) return this.noFill('frequency_capped');
485
569
  const out = await this.serveOnce();
486
570
  if (!out.served) return out.noFill;
487
571
  const s = out.served;
package/src/core/index.ts CHANGED
@@ -9,6 +9,7 @@ export { appendClickToken, CLICK_TIMEOUT_MS } from './click';
9
9
  export { compareVersions, BUNDLED_BASE_URL } from './config';
10
10
  export { SDK_VERSION } from '../version';
11
11
  export type {
12
- AudioPolicy, EthiclyAd, EthiclyAdMedia, EthiclyConfig, FetchLike, FileCacheAdapter,
13
- InterstitialResult, KeyValueStorage, Logger, NoFillReason, Platform, Tracker,
12
+ AudioPolicy, EthiclyAd, EthiclyAdMedia, EthiclyConfig, FetchLike, FileCacheAdapter, FrequencyOptions,
13
+ FrequencyUpdate, InterstitialResult, KeyValueStorage, Logger, NextAdReason, NextAdStatus, NoFillReason,
14
+ Platform, Tracker,
14
15
  } from './types';
@@ -353,6 +353,8 @@ export class InterstitialTracker implements Tracker {
353
353
  const body: Record<string, unknown> = { ad_id: ad.id, impression_id: imp.id };
354
354
  if (serve.publisherSiteId) body.publisher_site_id = serve.publisherSiteId;
355
355
  if (serve.countryCode) body.country_code = serve.countryCode;
356
+ // Proof the view was served: lets the server bill a tap made before /viewable.
357
+ if (imp.viewableToken) body.viewable_token = imp.viewableToken;
356
358
  // Never retried: one request, whatever happens.
357
359
  const res = await httpRequest(ctx.fetch, `${ctx.serveBase()}/click`, {
358
360
  method: 'POST', headers: ctx.headers(), body, timeoutMs: Math.min(remaining, BEACON_TIMEOUT_MS),
package/src/core/types.ts CHANGED
@@ -183,3 +183,55 @@ export interface WireServe {
183
183
  test?: boolean;
184
184
  request_id?: string;
185
185
  }
186
+
187
+ /**
188
+ * How often ads may show, set in code. Each field set here wins over the
189
+ * dashboard value from /config (interstitial.max_per_session, min_gap_s);
190
+ * an unset field falls back to /config, then to the defaults (3 and 120).
191
+ */
192
+ export interface FrequencyOptions {
193
+ /**
194
+ * Ads per session. 0 shows none. Any integer >= 0; Infinity (or a large
195
+ * number such as 1000000) means no session limit.
196
+ */
197
+ maxPerSession?: number;
198
+ /** Seconds between two ads, kept across restarts. 0 means no gap. Finite, >= 0. */
199
+ minGapSeconds?: number;
200
+ }
201
+
202
+ /** setFrequency(): a field left out keeps its current value, null goes back to /config. */
203
+ export interface FrequencyUpdate {
204
+ maxPerSession?: number | null;
205
+ minGapSeconds?: number | null;
206
+ }
207
+
208
+ /** Why nextAdStatus() says no ad may show now. */
209
+ export type NextAdReason =
210
+ /** The gap between ads (min_gap_s) has not passed: see retryAt. */
211
+ | 'frequency_capped'
212
+ /** max_per_session ads were shown this session. */
213
+ | 'session_cap'
214
+ /** setAdsEnabled(false), for example a paid user. */
215
+ | 'ads_disabled'
216
+ /** The stored frequency state is still loading (see `ready`). */
217
+ | 'not_ready'
218
+ | 'invalid_key'
219
+ | 'unknown_key'
220
+ | 'sdk_unsupported'
221
+ | 'app_disabled'
222
+ | 'interstitial_disabled';
223
+
224
+ export interface NextAdStatus {
225
+ /** Same as canShow(). */
226
+ allowed: boolean;
227
+ /** Set when allowed is false. */
228
+ reason?: NextAdReason;
229
+ /** Epoch ms when the gap ends. Only with reason 'frequency_capped'. */
230
+ retryAt?: number;
231
+ /** Ads shown in the current session. */
232
+ shownThisSession: number;
233
+ /** The effective per-session limit (Infinity for none). */
234
+ maxPerSession: number;
235
+ /** The effective gap between ads, in seconds. */
236
+ minGapSeconds: number;
237
+ }
@@ -3,7 +3,7 @@
3
3
 
4
4
  import { useCallback, useEffect, useRef, useState } from 'react';
5
5
  import type { Ethicly } from '../core/client';
6
- import type { EthiclyAd, NoFillReason, Tracker } from '../core/types';
6
+ import type { EthiclyAd, NextAdStatus, NoFillReason, Tracker } from '../core/types';
7
7
 
8
8
  export interface UseEthiclyInterstitialOptions {
9
9
  /** Preload on mount and after each dismiss. Default true. */
@@ -22,6 +22,8 @@ export interface EthiclyInterstitialState {
22
22
  /** Close the current ad: flushes queued events and preloads the next one. */
23
23
  dismiss(): void;
24
24
  canShow(): boolean;
25
+ /** Whether an ad may show now and, when not, why and until when. Same as ethicly.nextAdStatus(). */
26
+ nextAdStatus(): NextAdStatus;
25
27
  }
26
28
 
27
29
  export function useEthiclyInterstitial(
@@ -69,6 +71,9 @@ export function useEthiclyInterstitial(
69
71
  }, [ethicly, preload]);
70
72
 
71
73
  const canShow = useCallback(() => ethicly.canShow(), [ethicly]);
74
+ const nextAdStatus = useCallback(() => ethicly.nextAdStatus(), [ethicly]);
72
75
 
73
- return { ad: current?.ad ?? null, tracker: current?.tracker ?? null, reason, loading, show, dismiss, canShow };
76
+ return {
77
+ ad: current?.ad ?? null, tracker: current?.tracker ?? null, reason, loading, show, dismiss, canShow, nextAdStatus,
78
+ };
74
79
  }
package/src/version.ts CHANGED
@@ -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.3.0';