@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
@@ -10,11 +10,13 @@ import { isWebUrl } from './click';
10
10
  import { BUNDLED_BASE_URL, clampSkipAfterMs, cleanServeBase, defaultConfig, isBelowMinSdk, maxAgeSeconds, parseConfig } from './config';
11
11
  import { httpRequest, RouteGate } from './http';
12
12
  import { outboxFor, replayRecord, type Outbox } from './outbox';
13
+ import { HouseTracker } from './houseTracker';
13
14
  import { InterstitialTracker } from './tracker';
14
15
  import { SDK_VERSION } from '../version';
15
16
  import type {
16
- AudioPolicy, EthiclyAd, EthiclyConfig, FetchLike, FileCacheAdapter, InterstitialResult, KeyValueStorage,
17
- Logger, NoFillReason, Platform, WireServe,
17
+ AudioPolicy, EthiclyAd, EthiclyConfig, FetchLike, FileCacheAdapter, FrequencyOptions, FrequencyUpdate,
18
+ InterstitialResult, KeyValueStorage, LoadOptions, Logger, NextAdReason, NextAdStatus, NoFillReason, Platform,
19
+ Tracker, WireAd, WireServe,
18
20
  } from './types';
19
21
 
20
22
  export interface EthiclyOptions {
@@ -51,6 +53,27 @@ export interface EthiclyOptions {
51
53
  * download carries on in the background for next time.
52
54
  */
53
55
  loadTimeoutMs?: number;
56
+ /**
57
+ * How often ads may show, decided in code. A field set here overrides the
58
+ * dashboard value (/config interstitial.max_per_session, min_gap_s) for this
59
+ * client; an unset field uses /config, then the defaults. Unset: 0.2.x
60
+ * behaviour. Change it later with setFrequency().
61
+ */
62
+ frequency?: FrequencyOptions;
63
+ /**
64
+ * Show the publisher's house ad (uploaded in the dashboard) when no paid ad
65
+ * fills. Default true: the upload is the opt-in, so a publisher without one
66
+ * sees no change. false never asks for one, so the app can show its own.
67
+ * Change it later with setHouseAds(), or per call with { houseAds }.
68
+ */
69
+ houseAds?: boolean;
70
+ /**
71
+ * Where EthiclyInterstitial sends a tap on a house ad's button instead of
72
+ * opening its link, for example the app's premium screen. The tap is still
73
+ * counted and the ad closes first. useEthiclyInterstitial's and the
74
+ * screen's own onHouseAdPress win over this. Never used for paid ads.
75
+ */
76
+ onHouseAdPress?: (ad: EthiclyAd) => void;
54
77
  storage?: KeyValueStorage;
55
78
  fileCache?: FileCacheAdapter;
56
79
  openUrl?: (url: string) => unknown;
@@ -68,14 +91,32 @@ export interface Ethicly {
68
91
  /** Resolves when the stored config is loaded and the first /config fetch settled. Never rejects. */
69
92
  readonly ready: Promise<void>;
70
93
  /** Serve and download an interstitial ahead of time. Does not consume it. */
71
- preload(): Promise<InterstitialResult>;
72
- /** The ad to show now: the preloaded one if still valid, else a fresh serve. Consumes it. */
73
- loadInterstitial(): Promise<InterstitialResult>;
94
+ preload(opts?: LoadOptions): Promise<InterstitialResult>;
95
+ /**
96
+ * The ad to show now: the preloaded one if still valid, else a fresh serve.
97
+ * Consumes it. A preloaded house ad never stands in for a paid ad: a fresh
98
+ * serve is tried first, within loadTimeoutMs. Check `ad.house`.
99
+ */
100
+ loadInterstitial(opts?: LoadOptions): Promise<InterstitialResult>;
101
+ /** Turn house ads on or off for this client (options.houseAds). Off drops a preloaded house ad. */
102
+ setHouseAds(enabled: boolean): void;
74
103
  /**
75
104
  * Frequency caps, the ads switch and the kill switch, checked client-side.
76
105
  * false until the stored frequency state has loaded (see `ready`).
77
106
  */
78
107
  canShow(): boolean;
108
+ /**
109
+ * Whether an ad may show now and, when not, why and when it may: retryAt is
110
+ * set while the gap between ads runs. canShow() is nextAdStatus().allowed.
111
+ */
112
+ nextAdStatus(): NextAdStatus;
113
+ /**
114
+ * Change the frequency set in code, for example after an entitlement check
115
+ * or an A/B test. A field left out keeps its value; null goes back to /config.
116
+ */
117
+ setFrequency(update: FrequencyUpdate): void;
118
+ /** The effective frequency: code, else /config, else the defaults. */
119
+ getFrequency(): Required<FrequencyOptions>;
79
120
  /** false for paid users: stops serves, drops the preloaded ad and cancels a download in flight. */
80
121
  setAdsEnabled(enabled: boolean): void;
81
122
  isAdsEnabled(): boolean;
@@ -105,7 +146,7 @@ let releaseTestModeLogged = false;
105
146
  interface StoredConfig { config: EthiclyConfig; fetchedAt: number; maxAgeS: number }
106
147
  interface StoredFrequency { lastShownAt: number }
107
148
 
108
- interface Preloaded { result: { ad: EthiclyAd; tracker: InterstitialTracker } }
149
+ interface Preloaded { result: { ad: EthiclyAd; tracker: Tracker } }
109
150
 
110
151
  /** A served ad whose creative is downloading. Built into an ad once, by preload() or loadInterstitial(). */
111
152
  interface Served {
@@ -115,10 +156,33 @@ interface Served {
115
156
  /** Taken by loadInterstitial(): never stored as the preloaded ad. */
116
157
  consumed: boolean;
117
158
  result: Preloaded['result'] | null;
159
+ /** A house ad, shown only when no paid ad fills. */
160
+ house: boolean;
161
+ /** For a house ad: why no paid ad filled. */
162
+ noFillReason?: NoFillReason;
118
163
  }
119
164
 
120
165
  type ServeOutcome = { served: Served; noFill?: undefined } | { served?: undefined; noFill: InterstitialResult };
121
166
 
167
+ /** Same ceiling as the dashboard's gap between ads (24 hours). */
168
+ const MAX_MIN_GAP_S = 86400;
169
+
170
+ /**
171
+ * A frequency value from code: undefined when not a usable number, else >= 0.
172
+ * Infinity only where `allowInfinity`.
173
+ */
174
+ function frequencyValue(v: unknown, name: string, allowInfinity: boolean, log: Required<Logger>): number | undefined {
175
+ if (typeof v !== 'number' || Number.isNaN(v) || (v === Infinity && !allowInfinity) || v === -Infinity) {
176
+ log.warn(`frequency.${name} must be a number >= 0${allowInfinity ? ' or Infinity' : ''}: using the dashboard value`);
177
+ return undefined;
178
+ }
179
+ if (v < 0) {
180
+ log.warn(`frequency.${name} below 0: using 0`);
181
+ return 0;
182
+ }
183
+ return v;
184
+ }
185
+
122
186
  function audioPolicy(v: unknown): AudioPolicy | null {
123
187
  return v === 'on' || v === 'optional' || v === 'none' ? v : null;
124
188
  }
@@ -156,10 +220,14 @@ class EthiclyClient implements Ethicly {
156
220
  private sdkUnsupported = false;
157
221
 
158
222
  private adsOn: boolean;
223
+ private houseAdsOn: boolean;
159
224
  private testMode: boolean;
160
225
  private shownCount = 0;
161
226
  private lastShownAt: number | null = null;
162
227
  private frequencyLoaded = false;
228
+ /** Frequency set in code, null where /config decides. */
229
+ private maxPerSessionOverride: number | null = null;
230
+ private minGapSOverride: number | null = null;
163
231
  /** When the app left the foreground, null while it is in it. */
164
232
  private backgroundSince: number | null = null;
165
233
  private outbox: Outbox;
@@ -187,11 +255,13 @@ class EthiclyClient implements Ethicly {
187
255
  );
188
256
  this.config = defaultConfig(this.bundled);
189
257
  this.adsOn = o.adsEnabled !== false;
258
+ this.houseAdsOn = o.houseAds !== false;
190
259
  this.audio = audioPolicy(o.audio);
191
260
  if (o.audio !== undefined && !this.audio) this.log.warn(`audio must be 'on', 'optional' or 'none': using the server's value`);
192
261
  this.loadTimeoutMs = typeof o.loadTimeoutMs === 'number' && Number.isFinite(o.loadTimeoutMs) && o.loadTimeoutMs >= 0
193
262
  ? o.loadTimeoutMs
194
263
  : DEFAULT_LOAD_TIMEOUT_MS;
264
+ if (o.frequency) this.setFrequency(o.frequency);
195
265
  this.testMode = !!o.testMode && !isReleaseBuild();
196
266
  if (o.testMode && !this.testMode) this.reportReleaseTestMode();
197
267
  if (this.testMode) this.log.warn('test mode is on: nothing is billed. Never ship a release build with testMode.');
@@ -407,12 +477,54 @@ class EthiclyClient implements Ethicly {
407
477
 
408
478
  // ------------------------------------------------------------- frequency
409
479
 
410
- canShow(): boolean {
480
+ getFrequency(): Required<FrequencyOptions> {
411
481
  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;
482
+ return {
483
+ maxPerSession: this.maxPerSessionOverride ?? it.max_per_session,
484
+ minGapSeconds: this.minGapSOverride ?? it.min_gap_s,
485
+ };
486
+ }
487
+
488
+ setFrequency(update: FrequencyUpdate): void {
489
+ if (!update || typeof update !== 'object') return;
490
+ if (update.maxPerSession === null) this.maxPerSessionOverride = null;
491
+ else if (update.maxPerSession !== undefined) {
492
+ const v = frequencyValue(update.maxPerSession, 'maxPerSession', true, this.log);
493
+ if (v !== undefined) {
494
+ const whole = Math.floor(v);
495
+ if (whole !== v) this.log.warn(`frequency.maxPerSession ${v} is not a whole number: using ${whole}${whole === 0 ? ' (no ads)' : ''}`);
496
+ this.maxPerSessionOverride = whole;
497
+ }
498
+ }
499
+ if (update.minGapSeconds === null) this.minGapSOverride = null;
500
+ else if (update.minGapSeconds !== undefined) {
501
+ const v = frequencyValue(update.minGapSeconds, 'minGapSeconds', false, this.log);
502
+ if (v !== undefined) {
503
+ if (v > MAX_MIN_GAP_S) this.log.warn(`frequency.minGapSeconds above ${MAX_MIN_GAP_S}: using ${MAX_MIN_GAP_S}`);
504
+ this.minGapSOverride = Math.min(v, MAX_MIN_GAP_S);
505
+ }
506
+ }
507
+ }
508
+
509
+ nextAdStatus(): NextAdStatus {
510
+ const { maxPerSession, minGapSeconds } = this.getFrequency();
511
+ const base = { shownThisSession: this.shownCount, maxPerSession, minGapSeconds };
512
+ const no = (reason: NextAdReason, retryAt?: number): NextAdStatus =>
513
+ (retryAt === undefined ? { ...base, allowed: false, reason } : { ...base, allowed: false, reason, retryAt });
514
+ if (!this.adsOn) return no('ads_disabled');
515
+ if (!this.frequencyLoaded) return no('not_ready');
516
+ const blocked = this.blockedReason();
517
+ if (blocked) return no(blocked);
518
+ if (this.shownCount >= maxPerSession) return no('session_cap');
519
+ if (this.lastShownAt !== null) {
520
+ const retryAt = this.lastShownAt + minGapSeconds * 1000;
521
+ if (this.now() < retryAt) return no('frequency_capped', retryAt);
522
+ }
523
+ return { ...base, allowed: true };
524
+ }
525
+
526
+ canShow(): boolean {
527
+ return this.nextAdStatus().allowed;
416
528
  }
417
529
 
418
530
  private onShown(): void {
@@ -437,9 +549,25 @@ class EthiclyClient implements Ethicly {
437
549
  return this.adsOn;
438
550
  }
439
551
 
552
+ setHouseAds(enabled: boolean): void {
553
+ this.houseAdsOn = !!enabled;
554
+ if (this.houseAdsOn) return;
555
+ if (this.preloaded?.result.ad.house) this.preloaded = null;
556
+ if (this.pendingServed?.house) this.pendingServed = null;
557
+ }
558
+
559
+ /**
560
+ * Whether this call takes a house ad: the call's option, else the client's,
561
+ * and never while the dashboard switch (/config interstitial.house_ads) is off.
562
+ */
563
+ private wantHouse(opts?: LoadOptions): boolean {
564
+ if (!this.config.interstitial.house_ads) return false;
565
+ return typeof opts?.houseAds === 'boolean' ? opts.houseAds : this.houseAdsOn;
566
+ }
567
+
440
568
  // ------------------------------------------------------------- serve
441
569
 
442
- private blockedReason(): NoFillReason | null {
570
+ private blockedReason(): Exclude<NextAdReason, 'frequency_capped' | 'session_cap' | 'ads_disabled' | 'not_ready'> | null {
443
571
  if (this.invalidKey) return 'invalid_key';
444
572
  if (this.unknownKey) return 'unknown_key';
445
573
  if (this.sdkUnsupported) return 'sdk_unsupported';
@@ -454,13 +582,22 @@ class EthiclyClient implements Ethicly {
454
582
  return { ad: null, tracker: null, reason };
455
583
  }
456
584
 
457
- /** The served ad waiting for its download, or a new serve. One serve at a time. */
458
- private serveOnce(): Promise<ServeOutcome> {
585
+ /**
586
+ * The served ad waiting for its download, or a new serve. One serve at a
587
+ * time. A house ad is a no fill for a caller that does not take one.
588
+ */
589
+ private async serveFor(houseAds: boolean): Promise<ServeOutcome> {
590
+ const out = await this.serveOnce(houseAds);
591
+ if (out.served && out.served.house && !houseAds) return { noFill: this.noFill(out.served.noFillReason || 'no_matching_ad') };
592
+ return out;
593
+ }
594
+
595
+ private serveOnce(houseAds: boolean): Promise<ServeOutcome> {
459
596
  const p = this.pendingServed;
460
597
  if (p && !p.consumed && this.now() < p.expiresAt) return Promise.resolve({ served: p });
461
598
  this.pendingServed = null;
462
599
  if (!this.serveInflight) {
463
- this.serveInflight = this.serve()
600
+ this.serveInflight = this.serve(houseAds)
464
601
  .then((out) => {
465
602
  if (out.served) this.pendingServed = out.served;
466
603
  return out;
@@ -476,13 +613,19 @@ class EthiclyClient implements Ethicly {
476
613
  return s.result;
477
614
  }
478
615
 
479
- async preload(): Promise<InterstitialResult> {
616
+ async preload(opts?: LoadOptions): Promise<InterstitialResult> {
480
617
  try {
481
618
  if (!this.adsOn) return this.noFill('ads_disabled');
482
- if (this.preloaded && !this.preloaded.result.tracker.isExpired()) return this.preloaded.result;
483
- this.preloaded = null;
484
- if (this.shownCount >= this.config.interstitial.max_per_session) return this.noFill('frequency_capped');
485
- const out = await this.serveOnce();
619
+ const house = this.wantHouse(opts);
620
+ const p = this.preloaded;
621
+ if (p && !p.result.tracker.isExpired()) {
622
+ if (house || !p.result.ad.house) return p.result;
623
+ // A preloaded house ad this call does not take: kept, and a paid ad may replace it.
624
+ } else {
625
+ this.preloaded = null;
626
+ }
627
+ if (this.shownCount >= this.getFrequency().maxPerSession) return this.noFill('frequency_capped');
628
+ const out = await this.serveFor(house);
486
629
  if (!out.served) return out.noFill;
487
630
  const s = out.served;
488
631
  // In the background: wait for the whole download, so the ad plays from disk.
@@ -500,7 +643,7 @@ class EthiclyClient implements Ethicly {
500
643
  }
501
644
  }
502
645
 
503
- async loadInterstitial(): Promise<InterstitialResult> {
646
+ async loadInterstitial(opts?: LoadOptions): Promise<InterstitialResult> {
504
647
  try {
505
648
  await this.ready;
506
649
  if (!this.adsOn) return this.noFill('ads_disabled');
@@ -508,16 +651,40 @@ class EthiclyClient implements Ethicly {
508
651
  const blocked = this.blockedReason();
509
652
  if (blocked) return this.noFill(blocked);
510
653
  if (!this.canShow()) return this.noFill('frequency_capped');
654
+ const house = this.wantHouse(opts);
511
655
  const pre = this.preloaded;
512
656
  this.preloaded = null;
513
- if (pre && !pre.result.tracker.isExpired()) return pre.result;
514
-
515
- const out = await this.serveOnce();
516
- if (!out.served) return out.noFill;
657
+ const valid = pre && !pre.result.tracker.isExpired() ? pre : null;
658
+ if (valid && !valid.result.ad.house) return valid.result;
659
+ // A preloaded house ad this call does not take stays for a later one.
660
+ if (valid && !house) this.preloaded = valid;
661
+ const fallback = valid && house ? valid : null;
662
+ const started = this.now();
663
+
664
+ let out: ServeOutcome | null;
665
+ if (fallback) {
666
+ // A preloaded house ad never blocks a paid one: ask for a paid ad
667
+ // first, within the load budget, and show the house ad only without one.
668
+ out = await this.within(this.serveFor(false), this.loadTimeoutMs);
669
+ if (!out || !out.served) {
670
+ if (!this.adsOn) return this.noFill('ads_disabled');
671
+ // The paid-first serve may have hit the kill switch or the minimum SDK
672
+ // version: the server said stop, so the preloaded house ad must not show.
673
+ const nowBlocked = this.blockedReason();
674
+ if (nowBlocked) return this.noFill(nowBlocked);
675
+ // The serve may still answer: it then waits as pendingServed for next time.
676
+ this.lastNoFillReason = null;
677
+ return fallback.result;
678
+ }
679
+ } else {
680
+ out = await this.serveFor(house);
681
+ if (!out.served) return out.noFill;
682
+ }
517
683
  const s = out.served;
518
684
  // The user is waiting: give the download a short budget, then stream the
519
685
  // remote file. The download carries on in the background for next time.
520
- const cached = await this.within(s.download, this.loadTimeoutMs);
686
+ const budget = Math.max(0, this.loadTimeoutMs - (this.now() - started));
687
+ const cached = await this.within(s.download, budget);
521
688
  if (!this.adsOn) return this.noFill('ads_disabled');
522
689
  if (!cached) this.log.info(`creative not on disk after ${this.loadTimeoutMs} ms: streaming it; the download continues for next time`);
523
690
  const r = this.claim(s, cached ? cached.uris : {});
@@ -525,6 +692,8 @@ class EthiclyClient implements Ethicly {
525
692
  if (this.pendingServed === s) this.pendingServed = null;
526
693
  // A preload that finished meanwhile may have stored this same ad.
527
694
  if ((this.preloaded as Preloaded | null)?.result === r) this.preloaded = null;
695
+ // The house ad that was not needed stays preloaded for next time.
696
+ if (fallback && !this.preloaded) this.preloaded = fallback;
528
697
  return r;
529
698
  } catch (e) {
530
699
  this.log.error('loadInterstitial failed', e);
@@ -539,13 +708,15 @@ class EthiclyClient implements Ethicly {
539
708
  return Promise.race([p, timeout]).finally(() => { if (timer) clearTimeout(timer); });
540
709
  }
541
710
 
542
- private async serve(): Promise<ServeOutcome> {
711
+ private async serve(houseAds: boolean): Promise<ServeOutcome> {
543
712
  const noFill = (reason: NoFillReason): ServeOutcome => ({ noFill: this.noFill(reason) });
544
713
  await this.ready;
545
714
  if (this.configStale()) await this.refreshConfig();
546
715
  const blocked = this.blockedReason();
547
716
  if (blocked) return noFill(blocked);
548
717
  if (this.gate.waitMs('serve') > 0) return noFill('rate_limited');
718
+ // The dashboard switch, read from the config just refreshed.
719
+ const askHouse = houseAds && this.config.interstitial.house_ads;
549
720
 
550
721
  const q = [
551
722
  `key=${encodeURIComponent(this.o.apiKey)}`,
@@ -555,6 +726,8 @@ class EthiclyClient implements Ethicly {
555
726
  `app_version=${encodeURIComponent(this.o.appVersion)}`,
556
727
  ];
557
728
  if (this.testMode) q.push('test=1');
729
+ // The SDK counts a house ad itself, on show (/fallback-impression): the server must not count it at pick time.
730
+ if (askHouse) q.push('house_ads=1', 'client_fallback_tracking=1');
558
731
  const res = await httpRequest(this.fetchFn, `${this.serveBase()}?${q.join('&')}`, {
559
732
  headers: this.headers(), timeoutMs: SERVE_TIMEOUT_MS,
560
733
  });
@@ -572,54 +745,109 @@ class EthiclyClient implements Ethicly {
572
745
  if (res.status !== 200 || !res.body || typeof res.body !== 'object') return noFill('server_error');
573
746
 
574
747
  const body = res.body as WireServe;
748
+ const ttlS = typeof body.token_ttl_s === 'number' && body.token_ttl_s > 0 ? body.token_ttl_s : DEFAULT_TTL_S;
575
749
  if (!body.ad) {
576
750
  const reason = typeof body.reason === 'string' && body.reason ? body.reason : 'no_matching_ad';
577
751
  if (reason === 'app_disabled') this.appDisabled = true;
578
752
  if (reason === 'sdk_unsupported') this.sdkUnsupported = true;
753
+ const h = body.house_ad;
754
+ // A house ad only when asked for, and never past a kill switch.
755
+ if (askHouse && h && typeof h === 'object' && reason !== 'app_disabled' && reason !== 'sdk_unsupported') {
756
+ if (!this.validAd(h, 'house ad', body.request_id)) return noFill(reason);
757
+ if (!this.adsOn) return noFill('ads_disabled');
758
+ const fallbackId = h.id;
759
+ const test = this.testMode || h.test === true || body.test === true;
760
+ this.log.info(`no paid ad (${reason}): house ad ${fallbackId}`);
761
+ return {
762
+ served: this.makeServed({
763
+ wire: h, cacheKey: `house-${fallbackId}`, servedAt, ttlS, test, house: true, noFillReason: reason,
764
+ tracker: (ad) => new HouseTracker({
765
+ ctx: this.beaconCtx(), ad, fallbackId, test, openUrl: this.o.openUrl, onShown: () => this.onShown(),
766
+ onPress: this.o.onHouseAdPress,
767
+ }),
768
+ }),
769
+ };
770
+ }
579
771
  return noFill(reason);
580
772
  }
581
773
  const ad = body.ad;
774
+ if (!this.validAd(ad, 'ad', body.request_id)) return noFill('invalid_response');
775
+ if (body.test === true) this.log.info(`test serve: ad ${ad.id} on site ${body.publisher_site_id}`);
776
+ if (!this.adsOn) return noFill('ads_disabled');
777
+ return {
778
+ served: this.makeServed({
779
+ wire: ad, cacheKey: ad.id, servedAt, ttlS, test: body.test === true, house: false,
780
+ tracker: (result) => new InterstitialTracker({
781
+ ctx: this.beaconCtx(),
782
+ ad: result,
783
+ serve: {
784
+ publisherSiteId: typeof body.publisher_site_id === 'number' && body.publisher_site_id > 0 ? body.publisher_site_id : null,
785
+ countryCode: typeof body.country_code === 'string' ? body.country_code : null,
786
+ impressionToken: typeof body.impression_token === 'string' ? body.impression_token : null,
787
+ },
788
+ viewableAfterMs: this.config.beacon.viewable_after_ms,
789
+ flushIntervalS: this.config.beacon.flush_interval_s,
790
+ platform: this.o.platform,
791
+ sdkVersion: SDK_VERSION,
792
+ appVersion: this.o.appVersion,
793
+ openUrl: this.o.openUrl,
794
+ onShown: () => this.onShown(),
795
+ outbox: this.outbox,
796
+ }),
797
+ }),
798
+ };
799
+ }
800
+
801
+ /** A paid or house ad has a numeric id, media and an http(s) destination. */
802
+ private validAd(ad: WireAd, what: string, requestId?: string): boolean {
582
803
  const m = ad.media;
583
804
  if (typeof ad.id !== 'number' || !m || typeof m.url !== 'string' || !m.url || typeof ad.destination_url !== 'string') {
584
- this.log.warn('serve answered an ad without media or destination', body.request_id);
585
- return noFill('invalid_response');
805
+ this.log.warn(`serve answered a ${what} without media or destination`, requestId);
806
+ return false;
586
807
  }
587
808
  if (!isWebUrl(ad.destination_url)) {
588
809
  // Only web pages are opened: never tel:, intent:, javascript: or an app scheme.
589
810
  if (!this.badDestinationLogged) {
590
811
  this.badDestinationLogged = true;
591
- this.log.error(`ad ${ad.id}: destination is not an http(s) URL, ad skipped`, body.request_id);
812
+ this.log.error(`${what} ${ad.id}: destination is not an http(s) URL, ad skipped`, requestId);
592
813
  }
593
- return noFill('invalid_response');
814
+ return false;
594
815
  }
595
- if (body.test === true) this.log.info(`test serve: ad ${ad.id} on site ${body.publisher_site_id}`);
596
- if (!this.adsOn) return noFill('ads_disabled');
816
+ return true;
817
+ }
597
818
 
819
+ /** Start the creative download; the ad and tracker are built later by preload() or loadInterstitial(). */
820
+ private makeServed(a: {
821
+ wire: WireAd; cacheKey: string | number; servedAt: number; ttlS: number; test: boolean;
822
+ house: boolean; noFillReason?: NoFillReason; tracker(ad: EthiclyAd): Tracker;
823
+ }): Served {
824
+ const ad = a.wire;
825
+ // validAd() checked these.
826
+ const m = ad.media as NonNullable<WireAd['media']>;
827
+ const mediaUrl = m.url as string;
828
+ const destinationUrl = ad.destination_url as string;
598
829
  const kind: 'video' | 'image' = m.kind === 'video' ? 'video' : 'image';
599
830
  const poster = kind === 'video' && typeof m.poster_url === 'string' && m.poster_url ? m.poster_url : null;
600
831
  const pf = this.config.prefetch;
601
832
  // Started now, awaited by preload() in full and by loadInterstitial() within loadTimeoutMs.
602
833
  const download = this.cache.ensure(
603
- ad.id,
604
- poster ? [m.url, poster] : [m.url],
834
+ a.cacheKey,
835
+ poster ? [mediaUrl, poster] : [mediaUrl],
605
836
  { maxCreatives: pf.max_cached_creatives, maxBytes: pf.max_cache_mb * 1024 * 1024 },
606
837
  () => this.adsOn,
607
838
  ).catch(() => ({ uris: {} as Record<string, string> }));
608
- const ttlS = typeof body.token_ttl_s === 'number' && body.token_ttl_s > 0 ? body.token_ttl_s : DEFAULT_TTL_S;
609
- const expiresAt = servedAt + ttlS * 1000;
610
- const adId = ad.id;
611
- const mediaUrl = m.url;
612
- const destinationUrl = ad.destination_url;
839
+ const expiresAt = a.servedAt + a.ttlS * 1000;
613
840
  const label = typeof ad.cta_label === 'string' ? ad.cta_label.trim() : '';
614
841
  const posInt = (v: unknown, d: number) => (typeof v === 'number' && v > 0 ? Math.round(v) : d);
615
842
  // The ad's value wins over /config, kept within the same 8 to 15 s range.
616
843
  const skipAfterMs = clampSkipAfterMs(ad.skip_after_ms) ?? this.config.interstitial.skip_after_ms;
617
844
  // The app's choice (options.audio) wins over the server's interstitial.audio.
618
845
  const audio: AudioPolicy = this.audio ?? this.config.interstitial.audio;
846
+ const showSponsorLabel = !a.house && this.config.interstitial.sponsor_label;
619
847
  const build = (uris: Record<string, string>): Preloaded['result'] => {
620
848
  const uri = uris[mediaUrl] || mediaUrl;
621
849
  const result: EthiclyAd = {
622
- id: adId,
850
+ id: ad.id,
623
851
  ctaLabel: label || 'Learn more',
624
852
  destinationUrl,
625
853
  skipAfterMs,
@@ -636,30 +864,17 @@ class EthiclyClient implements Ethicly {
636
864
  },
637
865
  audio,
638
866
  title: typeof ad.title === 'string' ? ad.title : null,
639
- test: body.test === true,
640
- servedAt,
867
+ test: a.test,
868
+ servedAt: a.servedAt,
641
869
  expiresAt,
870
+ house: a.house,
871
+ showSponsorLabel,
642
872
  };
643
- const tracker = new InterstitialTracker({
644
- ctx: this.beaconCtx(),
645
- ad: result,
646
- serve: {
647
- publisherSiteId: typeof body.publisher_site_id === 'number' && body.publisher_site_id > 0 ? body.publisher_site_id : null,
648
- countryCode: typeof body.country_code === 'string' ? body.country_code : null,
649
- impressionToken: typeof body.impression_token === 'string' ? body.impression_token : null,
650
- },
651
- viewableAfterMs: this.config.beacon.viewable_after_ms,
652
- flushIntervalS: this.config.beacon.flush_interval_s,
653
- platform: this.o.platform,
654
- sdkVersion: SDK_VERSION,
655
- appVersion: this.o.appVersion,
656
- openUrl: this.o.openUrl,
657
- onShown: () => this.onShown(),
658
- outbox: this.outbox,
659
- });
660
- return { ad: result, tracker };
873
+ if (a.house) result.noFillReason = a.noFillReason;
874
+ return { ad: result, tracker: a.tracker(result) };
661
875
  };
876
+ // An ad will show, so there is no fill reason, even for a house ad (see ad.noFillReason).
662
877
  this.lastNoFillReason = null;
663
- return { served: { build, download, expiresAt, consumed: false, result: null } };
878
+ return { build, download, expiresAt, consumed: false, result: null, house: a.house, noFillReason: a.noFillReason };
664
879
  }
665
880
  }
@@ -25,7 +25,7 @@ export function defaultConfig(serveBase: string): EthiclyConfig {
25
25
  enabled: true,
26
26
  min_sdk: { ios: '0.0.0', android: '0.0.0' },
27
27
  formats: ['interstitial', '300x250'],
28
- interstitial: { skip_after_ms: 8000, max_per_session: 3, min_gap_s: 120, audio: 'on' },
28
+ interstitial: { skip_after_ms: 8000, max_per_session: 3, min_gap_s: 120, audio: 'on', sponsor_label: true, house_ads: true },
29
29
  prefetch: { max_cached_creatives: 3, max_cache_mb: 20 },
30
30
  beacon: { viewable_after_ms: 2000, flush_interval_s: 30 },
31
31
  endpoints: { serve: serveBase },
@@ -76,6 +76,9 @@ export function parseConfig(body: unknown, bundledBase: string): EthiclyConfig |
76
76
  max_per_session: num(it.max_per_session, d.interstitial.max_per_session, 0, 1000),
77
77
  min_gap_s: num(it.min_gap_s, d.interstitial.min_gap_s, 0, 86400),
78
78
  audio,
79
+ // Only an explicit false hides the line.
80
+ sponsor_label: it.sponsor_label !== false,
81
+ house_ads: it.house_ads !== false,
79
82
  },
80
83
  prefetch: {
81
84
  max_cached_creatives: num(pf.max_cached_creatives, d.prefetch.max_cached_creatives, 0, 100),
@@ -0,0 +1,108 @@
1
+ // The tracker for a house ad: the publisher's own creative, shown when no paid
2
+ // ad fills. Nothing is billed, so there is no /impression, /viewable, video
3
+ // event or click token: only the unbilled /fallback-impression and
4
+ // /fallback-click counters, fire-and-forget, and none of them in test mode.
5
+
6
+ import { BEACON_TIMEOUT_MS, type BeaconContext } from './beacons';
7
+ import { isWebUrl } from './click';
8
+ import { httpRequest } from './http';
9
+ import type { EthiclyAd, Tracker } from './types';
10
+
11
+ export interface HouseTrackerDeps {
12
+ ctx: BeaconContext;
13
+ ad: EthiclyAd;
14
+ /** The house ad id the server sent (fallback_id on the wire). */
15
+ fallbackId: number;
16
+ /** Test mode: the counters are never sent. */
17
+ test: boolean;
18
+ openUrl?: (url: string) => unknown;
19
+ /** Called once when the ad is shown: a house ad counts toward the frequency caps. */
20
+ onShown(): void;
21
+ /** createEthicly's onHouseAdPress, if any. */
22
+ onPress?: (ad: EthiclyAd) => void;
23
+ }
24
+
25
+ export class HouseTracker implements Tracker {
26
+ /**
27
+ * Where the ready-made screen sends a tap instead of opening the link:
28
+ * createEthicly's onHouseAdPress, replaced by useEthiclyInterstitial's.
29
+ * EthiclyInterstitial's own prop wins over both.
30
+ */
31
+ /** @internal Set by the SDK; apps pass onHouseAdPress instead. */
32
+ houseAdPress: ((ad: EthiclyAd) => void) | undefined;
33
+ private shownOnce = false;
34
+ private clickedOnce = false;
35
+ private pending = new Set<Promise<unknown>>();
36
+
37
+ constructor(private d: HouseTrackerDeps) {
38
+ this.houseAdPress = d.onPress;
39
+ }
40
+
41
+ /** Resolves when every counter in flight has settled. For tests. */
42
+ async settle(): Promise<void> {
43
+ while (this.pending.size) await Promise.all(Array.from(this.pending)).catch(() => undefined);
44
+ }
45
+
46
+ isExpired(): boolean {
47
+ return this.d.ctx.now() >= this.d.ad.expiresAt;
48
+ }
49
+
50
+ /**
51
+ * One POST to a house-ad counter, never retried, never awaited by the
52
+ * caller. The answer (200, 400 or 429) changes nothing. Never rejects.
53
+ */
54
+ private send(route: 'fallback-impression' | 'fallback-click'): void {
55
+ const { ctx } = this.d;
56
+ if (this.d.test) return;
57
+ const p = httpRequest(ctx.fetch, `${ctx.serveBase()}/${route}`, {
58
+ method: 'POST', headers: ctx.headers(), body: { fallback_id: this.d.fallbackId }, timeoutMs: BEACON_TIMEOUT_MS,
59
+ }).then((res) => {
60
+ if (res.status !== 200) ctx.log.debug(`/${route} answered ${res.status || 'nothing'}`);
61
+ }).catch((e) => ctx.log.debug(`/${route} failed`, e));
62
+ this.pending.add(p);
63
+ p.finally(() => this.pending.delete(p)).catch(() => undefined);
64
+ }
65
+
66
+ shown(): Promise<void> {
67
+ if (this.shownOnce) return Promise.resolve();
68
+ this.shownOnce = true;
69
+ if (this.isExpired()) {
70
+ this.d.ctx.log.error(`house ad ${this.d.fallbackId} expired before it was shown; load a new one`);
71
+ return Promise.resolve();
72
+ }
73
+ try { this.d.onShown(); } catch { /* never throw */ }
74
+ this.send('fallback-impression');
75
+ return Promise.resolve();
76
+ }
77
+
78
+ progress(_positionMs: number, _opts: { visible: boolean; durationMs?: number }): void { /* house ads report no playback */ }
79
+ complete(): void { /* no video events for house ads */ }
80
+ skipped(_positionMs: number): void { /* no video events for house ads */ }
81
+ error(): void { /* no video events for house ads */ }
82
+
83
+ /**
84
+ * Counts the tap once (fire-and-forget) and opens the destination right
85
+ * away. `{ open: false }` only counts it: the app shows its own screen.
86
+ */
87
+ async clicked(opts?: { open?: boolean }): Promise<string> {
88
+ const url = this.d.ad.destinationUrl;
89
+ if (!this.clickedOnce) {
90
+ this.clickedOnce = true;
91
+ this.send('fallback-click');
92
+ }
93
+ if (opts?.open === false) return url;
94
+ if (!isWebUrl(url)) {
95
+ this.d.ctx.log.error(`house ad ${this.d.fallbackId}: destination is not an http(s) URL, not opened`);
96
+ return url;
97
+ }
98
+ try {
99
+ if (this.d.openUrl) await this.d.openUrl(url);
100
+ else this.d.ctx.log.warn('no openUrl adapter: the host must open the returned URL');
101
+ } catch (e) {
102
+ this.d.ctx.log.error('openUrl failed', e);
103
+ }
104
+ return url;
105
+ }
106
+
107
+ async closed(): Promise<void> { /* nothing is queued for a house ad */ }
108
+ }