@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,6 +10,7 @@ const click_1 = require("./click");
10
10
  const config_1 = require("./config");
11
11
  const http_1 = require("./http");
12
12
  const outbox_1 = require("./outbox");
13
+ const houseTracker_1 = require("./houseTracker");
13
14
  const tracker_1 = require("./tracker");
14
15
  const version_1 = require("../version");
15
16
  /** How long loadInterstitial() waits for a creative download by default. */
@@ -25,6 +26,23 @@ const DEFAULT_TTL_S = 3600;
25
26
  */
26
27
  exports.SESSION_TIMEOUT_MS = 30 * 60 * 1000;
27
28
  let releaseTestModeLogged = false;
29
+ /** Same ceiling as the dashboard's gap between ads (24 hours). */
30
+ const MAX_MIN_GAP_S = 86400;
31
+ /**
32
+ * A frequency value from code: undefined when not a usable number, else >= 0.
33
+ * Infinity only where `allowInfinity`.
34
+ */
35
+ function frequencyValue(v, name, allowInfinity, log) {
36
+ if (typeof v !== 'number' || Number.isNaN(v) || (v === Infinity && !allowInfinity) || v === -Infinity) {
37
+ log.warn(`frequency.${name} must be a number >= 0${allowInfinity ? ' or Infinity' : ''}: using the dashboard value`);
38
+ return undefined;
39
+ }
40
+ if (v < 0) {
41
+ log.warn(`frequency.${name} below 0: using 0`);
42
+ return 0;
43
+ }
44
+ return v;
45
+ }
28
46
  function audioPolicy(v) {
29
47
  return v === 'on' || v === 'optional' || v === 'none' ? v : null;
30
48
  }
@@ -52,6 +70,9 @@ class EthiclyClient {
52
70
  this.shownCount = 0;
53
71
  this.lastShownAt = null;
54
72
  this.frequencyLoaded = false;
73
+ /** Frequency set in code, null where /config decides. */
74
+ this.maxPerSessionOverride = null;
75
+ this.minGapSOverride = null;
55
76
  /** When the app left the foreground, null while it is in it. */
56
77
  this.backgroundSince = null;
57
78
  this.preloaded = null;
@@ -72,12 +93,15 @@ class EthiclyClient {
72
93
  this.cache = new cache_1.CreativeCache(o.fileCache || (0, adapters_1.createMemoryFileCache)(), this.storage, 'ethicly:v1:cache', this.now, this.log, o.fileCache ? (url) => this.contentLength(url) : undefined);
73
94
  this.config = (0, config_1.defaultConfig)(this.bundled);
74
95
  this.adsOn = o.adsEnabled !== false;
96
+ this.houseAdsOn = o.houseAds !== false;
75
97
  this.audio = audioPolicy(o.audio);
76
98
  if (o.audio !== undefined && !this.audio)
77
99
  this.log.warn(`audio must be 'on', 'optional' or 'none': using the server's value`);
78
100
  this.loadTimeoutMs = typeof o.loadTimeoutMs === 'number' && Number.isFinite(o.loadTimeoutMs) && o.loadTimeoutMs >= 0
79
101
  ? o.loadTimeoutMs
80
102
  : exports.DEFAULT_LOAD_TIMEOUT_MS;
103
+ if (o.frequency)
104
+ this.setFrequency(o.frequency);
81
105
  this.testMode = !!o.testMode && !(0, adapters_1.isReleaseBuild)();
82
106
  if (o.testMode && !this.testMode)
83
107
  this.reportReleaseTestMode();
@@ -304,15 +328,61 @@ class EthiclyClient {
304
328
  this.log.warn(`config fetch failed (${res.status || 'network'}), keeping the last known config`);
305
329
  }
306
330
  // ------------------------------------------------------------- frequency
307
- canShow() {
331
+ getFrequency() {
332
+ var _a, _b;
308
333
  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;
334
+ return {
335
+ maxPerSession: (_a = this.maxPerSessionOverride) !== null && _a !== void 0 ? _a : it.max_per_session,
336
+ minGapSeconds: (_b = this.minGapSOverride) !== null && _b !== void 0 ? _b : it.min_gap_s,
337
+ };
338
+ }
339
+ setFrequency(update) {
340
+ if (!update || typeof update !== 'object')
341
+ return;
342
+ if (update.maxPerSession === null)
343
+ this.maxPerSessionOverride = null;
344
+ else if (update.maxPerSession !== undefined) {
345
+ const v = frequencyValue(update.maxPerSession, 'maxPerSession', true, this.log);
346
+ if (v !== undefined) {
347
+ const whole = Math.floor(v);
348
+ if (whole !== v)
349
+ this.log.warn(`frequency.maxPerSession ${v} is not a whole number: using ${whole}${whole === 0 ? ' (no ads)' : ''}`);
350
+ this.maxPerSessionOverride = whole;
351
+ }
352
+ }
353
+ if (update.minGapSeconds === null)
354
+ this.minGapSOverride = null;
355
+ else if (update.minGapSeconds !== undefined) {
356
+ const v = frequencyValue(update.minGapSeconds, 'minGapSeconds', false, this.log);
357
+ if (v !== undefined) {
358
+ if (v > MAX_MIN_GAP_S)
359
+ this.log.warn(`frequency.minGapSeconds above ${MAX_MIN_GAP_S}: using ${MAX_MIN_GAP_S}`);
360
+ this.minGapSOverride = Math.min(v, MAX_MIN_GAP_S);
361
+ }
362
+ }
363
+ }
364
+ nextAdStatus() {
365
+ const { maxPerSession, minGapSeconds } = this.getFrequency();
366
+ const base = { shownThisSession: this.shownCount, maxPerSession, minGapSeconds };
367
+ const no = (reason, retryAt) => (retryAt === undefined ? { ...base, allowed: false, reason } : { ...base, allowed: false, reason, retryAt });
368
+ if (!this.adsOn)
369
+ return no('ads_disabled');
370
+ if (!this.frequencyLoaded)
371
+ return no('not_ready');
372
+ const blocked = this.blockedReason();
373
+ if (blocked)
374
+ return no(blocked);
375
+ if (this.shownCount >= maxPerSession)
376
+ return no('session_cap');
377
+ if (this.lastShownAt !== null) {
378
+ const retryAt = this.lastShownAt + minGapSeconds * 1000;
379
+ if (this.now() < retryAt)
380
+ return no('frequency_capped', retryAt);
381
+ }
382
+ return { ...base, allowed: true };
383
+ }
384
+ canShow() {
385
+ return this.nextAdStatus().allowed;
316
386
  }
317
387
  onShown() {
318
388
  this.shownCount += 1;
@@ -335,6 +405,25 @@ class EthiclyClient {
335
405
  isAdsEnabled() {
336
406
  return this.adsOn;
337
407
  }
408
+ setHouseAds(enabled) {
409
+ var _a, _b;
410
+ this.houseAdsOn = !!enabled;
411
+ if (this.houseAdsOn)
412
+ return;
413
+ if ((_a = this.preloaded) === null || _a === void 0 ? void 0 : _a.result.ad.house)
414
+ this.preloaded = null;
415
+ if ((_b = this.pendingServed) === null || _b === void 0 ? void 0 : _b.house)
416
+ this.pendingServed = null;
417
+ }
418
+ /**
419
+ * Whether this call takes a house ad: the call's option, else the client's,
420
+ * and never while the dashboard switch (/config interstitial.house_ads) is off.
421
+ */
422
+ wantHouse(opts) {
423
+ if (!this.config.interstitial.house_ads)
424
+ return false;
425
+ return typeof (opts === null || opts === void 0 ? void 0 : opts.houseAds) === 'boolean' ? opts.houseAds : this.houseAdsOn;
426
+ }
338
427
  // ------------------------------------------------------------- serve
339
428
  blockedReason() {
340
429
  if (this.invalidKey)
@@ -354,14 +443,23 @@ class EthiclyClient {
354
443
  this.log.info(`no ad: ${reason}`);
355
444
  return { ad: null, tracker: null, reason };
356
445
  }
357
- /** The served ad waiting for its download, or a new serve. One serve at a time. */
358
- serveOnce() {
446
+ /**
447
+ * The served ad waiting for its download, or a new serve. One serve at a
448
+ * time. A house ad is a no fill for a caller that does not take one.
449
+ */
450
+ async serveFor(houseAds) {
451
+ const out = await this.serveOnce(houseAds);
452
+ if (out.served && out.served.house && !houseAds)
453
+ return { noFill: this.noFill(out.served.noFillReason || 'no_matching_ad') };
454
+ return out;
455
+ }
456
+ serveOnce(houseAds) {
359
457
  const p = this.pendingServed;
360
458
  if (p && !p.consumed && this.now() < p.expiresAt)
361
459
  return Promise.resolve({ served: p });
362
460
  this.pendingServed = null;
363
461
  if (!this.serveInflight) {
364
- this.serveInflight = this.serve()
462
+ this.serveInflight = this.serve(houseAds)
365
463
  .then((out) => {
366
464
  if (out.served)
367
465
  this.pendingServed = out.served;
@@ -377,16 +475,23 @@ class EthiclyClient {
377
475
  s.result = s.build(uris);
378
476
  return s.result;
379
477
  }
380
- async preload() {
478
+ async preload(opts) {
381
479
  try {
382
480
  if (!this.adsOn)
383
481
  return this.noFill('ads_disabled');
384
- if (this.preloaded && !this.preloaded.result.tracker.isExpired())
385
- return this.preloaded.result;
386
- this.preloaded = null;
387
- if (this.shownCount >= this.config.interstitial.max_per_session)
482
+ const house = this.wantHouse(opts);
483
+ const p = this.preloaded;
484
+ if (p && !p.result.tracker.isExpired()) {
485
+ if (house || !p.result.ad.house)
486
+ return p.result;
487
+ // A preloaded house ad this call does not take: kept, and a paid ad may replace it.
488
+ }
489
+ else {
490
+ this.preloaded = null;
491
+ }
492
+ if (this.shownCount >= this.getFrequency().maxPerSession)
388
493
  return this.noFill('frequency_capped');
389
- const out = await this.serveOnce();
494
+ const out = await this.serveFor(house);
390
495
  if (!out.served)
391
496
  return out.noFill;
392
497
  const s = out.served;
@@ -407,7 +512,7 @@ class EthiclyClient {
407
512
  return this.noFill('network_error');
408
513
  }
409
514
  }
410
- async loadInterstitial() {
515
+ async loadInterstitial(opts) {
411
516
  var _a;
412
517
  try {
413
518
  await this.ready;
@@ -420,17 +525,45 @@ class EthiclyClient {
420
525
  return this.noFill(blocked);
421
526
  if (!this.canShow())
422
527
  return this.noFill('frequency_capped');
528
+ const house = this.wantHouse(opts);
423
529
  const pre = this.preloaded;
424
530
  this.preloaded = null;
425
- if (pre && !pre.result.tracker.isExpired())
426
- return pre.result;
427
- const out = await this.serveOnce();
428
- if (!out.served)
429
- return out.noFill;
531
+ const valid = pre && !pre.result.tracker.isExpired() ? pre : null;
532
+ if (valid && !valid.result.ad.house)
533
+ return valid.result;
534
+ // A preloaded house ad this call does not take stays for a later one.
535
+ if (valid && !house)
536
+ this.preloaded = valid;
537
+ const fallback = valid && house ? valid : null;
538
+ const started = this.now();
539
+ let out;
540
+ if (fallback) {
541
+ // A preloaded house ad never blocks a paid one: ask for a paid ad
542
+ // first, within the load budget, and show the house ad only without one.
543
+ out = await this.within(this.serveFor(false), this.loadTimeoutMs);
544
+ if (!out || !out.served) {
545
+ if (!this.adsOn)
546
+ return this.noFill('ads_disabled');
547
+ // The paid-first serve may have hit the kill switch or the minimum SDK
548
+ // version: the server said stop, so the preloaded house ad must not show.
549
+ const nowBlocked = this.blockedReason();
550
+ if (nowBlocked)
551
+ return this.noFill(nowBlocked);
552
+ // The serve may still answer: it then waits as pendingServed for next time.
553
+ this.lastNoFillReason = null;
554
+ return fallback.result;
555
+ }
556
+ }
557
+ else {
558
+ out = await this.serveFor(house);
559
+ if (!out.served)
560
+ return out.noFill;
561
+ }
430
562
  const s = out.served;
431
563
  // The user is waiting: give the download a short budget, then stream the
432
564
  // remote file. The download carries on in the background for next time.
433
- const cached = await this.within(s.download, this.loadTimeoutMs);
565
+ const budget = Math.max(0, this.loadTimeoutMs - (this.now() - started));
566
+ const cached = await this.within(s.download, budget);
434
567
  if (!this.adsOn)
435
568
  return this.noFill('ads_disabled');
436
569
  if (!cached)
@@ -442,6 +575,9 @@ class EthiclyClient {
442
575
  // A preload that finished meanwhile may have stored this same ad.
443
576
  if (((_a = this.preloaded) === null || _a === void 0 ? void 0 : _a.result) === r)
444
577
  this.preloaded = null;
578
+ // The house ad that was not needed stays preloaded for next time.
579
+ if (fallback && !this.preloaded)
580
+ this.preloaded = fallback;
445
581
  return r;
446
582
  }
447
583
  catch (e) {
@@ -456,8 +592,7 @@ class EthiclyClient {
456
592
  return Promise.race([p, timeout]).finally(() => { if (timer)
457
593
  clearTimeout(timer); });
458
594
  }
459
- async serve() {
460
- var _a, _b;
595
+ async serve(houseAds) {
461
596
  const noFill = (reason) => ({ noFill: this.noFill(reason) });
462
597
  await this.ready;
463
598
  if (this.configStale())
@@ -467,6 +602,8 @@ class EthiclyClient {
467
602
  return noFill(blocked);
468
603
  if (this.gate.waitMs('serve') > 0)
469
604
  return noFill('rate_limited');
605
+ // The dashboard switch, read from the config just refreshed.
606
+ const askHouse = houseAds && this.config.interstitial.house_ads;
470
607
  const q = [
471
608
  `key=${encodeURIComponent(this.o.apiKey)}`,
472
609
  'format=interstitial',
@@ -476,6 +613,9 @@ class EthiclyClient {
476
613
  ];
477
614
  if (this.testMode)
478
615
  q.push('test=1');
616
+ // The SDK counts a house ad itself, on show (/fallback-impression): the server must not count it at pick time.
617
+ if (askHouse)
618
+ q.push('house_ads=1', 'client_fallback_tracking=1');
479
619
  const res = await (0, http_1.httpRequest)(this.fetchFn, `${this.serveBase()}?${q.join('&')}`, {
480
620
  headers: this.headers(), timeoutMs: SERVE_TIMEOUT_MS,
481
621
  });
@@ -494,52 +634,107 @@ class EthiclyClient {
494
634
  if (res.status !== 200 || !res.body || typeof res.body !== 'object')
495
635
  return noFill('server_error');
496
636
  const body = res.body;
637
+ const ttlS = typeof body.token_ttl_s === 'number' && body.token_ttl_s > 0 ? body.token_ttl_s : DEFAULT_TTL_S;
497
638
  if (!body.ad) {
498
639
  const reason = typeof body.reason === 'string' && body.reason ? body.reason : 'no_matching_ad';
499
640
  if (reason === 'app_disabled')
500
641
  this.appDisabled = true;
501
642
  if (reason === 'sdk_unsupported')
502
643
  this.sdkUnsupported = true;
644
+ const h = body.house_ad;
645
+ // A house ad only when asked for, and never past a kill switch.
646
+ if (askHouse && h && typeof h === 'object' && reason !== 'app_disabled' && reason !== 'sdk_unsupported') {
647
+ if (!this.validAd(h, 'house ad', body.request_id))
648
+ return noFill(reason);
649
+ if (!this.adsOn)
650
+ return noFill('ads_disabled');
651
+ const fallbackId = h.id;
652
+ const test = this.testMode || h.test === true || body.test === true;
653
+ this.log.info(`no paid ad (${reason}): house ad ${fallbackId}`);
654
+ return {
655
+ served: this.makeServed({
656
+ wire: h, cacheKey: `house-${fallbackId}`, servedAt, ttlS, test, house: true, noFillReason: reason,
657
+ tracker: (ad) => new houseTracker_1.HouseTracker({
658
+ ctx: this.beaconCtx(), ad, fallbackId, test, openUrl: this.o.openUrl, onShown: () => this.onShown(),
659
+ onPress: this.o.onHouseAdPress,
660
+ }),
661
+ }),
662
+ };
663
+ }
503
664
  return noFill(reason);
504
665
  }
505
666
  const ad = body.ad;
667
+ if (!this.validAd(ad, 'ad', body.request_id))
668
+ return noFill('invalid_response');
669
+ if (body.test === true)
670
+ this.log.info(`test serve: ad ${ad.id} on site ${body.publisher_site_id}`);
671
+ if (!this.adsOn)
672
+ return noFill('ads_disabled');
673
+ return {
674
+ served: this.makeServed({
675
+ wire: ad, cacheKey: ad.id, servedAt, ttlS, test: body.test === true, house: false,
676
+ tracker: (result) => new tracker_1.InterstitialTracker({
677
+ ctx: this.beaconCtx(),
678
+ ad: result,
679
+ serve: {
680
+ publisherSiteId: typeof body.publisher_site_id === 'number' && body.publisher_site_id > 0 ? body.publisher_site_id : null,
681
+ countryCode: typeof body.country_code === 'string' ? body.country_code : null,
682
+ impressionToken: typeof body.impression_token === 'string' ? body.impression_token : null,
683
+ },
684
+ viewableAfterMs: this.config.beacon.viewable_after_ms,
685
+ flushIntervalS: this.config.beacon.flush_interval_s,
686
+ platform: this.o.platform,
687
+ sdkVersion: version_1.SDK_VERSION,
688
+ appVersion: this.o.appVersion,
689
+ openUrl: this.o.openUrl,
690
+ onShown: () => this.onShown(),
691
+ outbox: this.outbox,
692
+ }),
693
+ }),
694
+ };
695
+ }
696
+ /** A paid or house ad has a numeric id, media and an http(s) destination. */
697
+ validAd(ad, what, requestId) {
506
698
  const m = ad.media;
507
699
  if (typeof ad.id !== 'number' || !m || typeof m.url !== 'string' || !m.url || typeof ad.destination_url !== 'string') {
508
- this.log.warn('serve answered an ad without media or destination', body.request_id);
509
- return noFill('invalid_response');
700
+ this.log.warn(`serve answered a ${what} without media or destination`, requestId);
701
+ return false;
510
702
  }
511
703
  if (!(0, click_1.isWebUrl)(ad.destination_url)) {
512
704
  // Only web pages are opened: never tel:, intent:, javascript: or an app scheme.
513
705
  if (!this.badDestinationLogged) {
514
706
  this.badDestinationLogged = true;
515
- this.log.error(`ad ${ad.id}: destination is not an http(s) URL, ad skipped`, body.request_id);
707
+ this.log.error(`${what} ${ad.id}: destination is not an http(s) URL, ad skipped`, requestId);
516
708
  }
517
- return noFill('invalid_response');
709
+ return false;
518
710
  }
519
- if (body.test === true)
520
- this.log.info(`test serve: ad ${ad.id} on site ${body.publisher_site_id}`);
521
- if (!this.adsOn)
522
- return noFill('ads_disabled');
711
+ return true;
712
+ }
713
+ /** Start the creative download; the ad and tracker are built later by preload() or loadInterstitial(). */
714
+ makeServed(a) {
715
+ var _a, _b;
716
+ const ad = a.wire;
717
+ // validAd() checked these.
718
+ const m = ad.media;
719
+ const mediaUrl = m.url;
720
+ const destinationUrl = ad.destination_url;
523
721
  const kind = m.kind === 'video' ? 'video' : 'image';
524
722
  const poster = kind === 'video' && typeof m.poster_url === 'string' && m.poster_url ? m.poster_url : null;
525
723
  const pf = this.config.prefetch;
526
724
  // Started now, awaited by preload() in full and by loadInterstitial() within loadTimeoutMs.
527
- const download = this.cache.ensure(ad.id, poster ? [m.url, poster] : [m.url], { maxCreatives: pf.max_cached_creatives, maxBytes: pf.max_cache_mb * 1024 * 1024 }, () => this.adsOn).catch(() => ({ uris: {} }));
528
- const ttlS = typeof body.token_ttl_s === 'number' && body.token_ttl_s > 0 ? body.token_ttl_s : DEFAULT_TTL_S;
529
- const expiresAt = servedAt + ttlS * 1000;
530
- const adId = ad.id;
531
- const mediaUrl = m.url;
532
- const destinationUrl = ad.destination_url;
725
+ const download = this.cache.ensure(a.cacheKey, poster ? [mediaUrl, poster] : [mediaUrl], { maxCreatives: pf.max_cached_creatives, maxBytes: pf.max_cache_mb * 1024 * 1024 }, () => this.adsOn).catch(() => ({ uris: {} }));
726
+ const expiresAt = a.servedAt + a.ttlS * 1000;
533
727
  const label = typeof ad.cta_label === 'string' ? ad.cta_label.trim() : '';
534
728
  const posInt = (v, d) => (typeof v === 'number' && v > 0 ? Math.round(v) : d);
535
729
  // The ad's value wins over /config, kept within the same 8 to 15 s range.
536
730
  const skipAfterMs = (_a = (0, config_1.clampSkipAfterMs)(ad.skip_after_ms)) !== null && _a !== void 0 ? _a : this.config.interstitial.skip_after_ms;
537
731
  // The app's choice (options.audio) wins over the server's interstitial.audio.
538
732
  const audio = (_b = this.audio) !== null && _b !== void 0 ? _b : this.config.interstitial.audio;
733
+ const showSponsorLabel = !a.house && this.config.interstitial.sponsor_label;
539
734
  const build = (uris) => {
540
735
  const uri = uris[mediaUrl] || mediaUrl;
541
736
  const result = {
542
- id: adId,
737
+ id: ad.id,
543
738
  ctaLabel: label || 'Learn more',
544
739
  destinationUrl,
545
740
  skipAfterMs,
@@ -556,30 +751,18 @@ class EthiclyClient {
556
751
  },
557
752
  audio,
558
753
  title: typeof ad.title === 'string' ? ad.title : null,
559
- test: body.test === true,
560
- servedAt,
754
+ test: a.test,
755
+ servedAt: a.servedAt,
561
756
  expiresAt,
757
+ house: a.house,
758
+ showSponsorLabel,
562
759
  };
563
- const tracker = new tracker_1.InterstitialTracker({
564
- ctx: this.beaconCtx(),
565
- ad: result,
566
- serve: {
567
- publisherSiteId: typeof body.publisher_site_id === 'number' && body.publisher_site_id > 0 ? body.publisher_site_id : null,
568
- countryCode: typeof body.country_code === 'string' ? body.country_code : null,
569
- impressionToken: typeof body.impression_token === 'string' ? body.impression_token : null,
570
- },
571
- viewableAfterMs: this.config.beacon.viewable_after_ms,
572
- flushIntervalS: this.config.beacon.flush_interval_s,
573
- platform: this.o.platform,
574
- sdkVersion: version_1.SDK_VERSION,
575
- appVersion: this.o.appVersion,
576
- openUrl: this.o.openUrl,
577
- onShown: () => this.onShown(),
578
- outbox: this.outbox,
579
- });
580
- return { ad: result, tracker };
760
+ if (a.house)
761
+ result.noFillReason = a.noFillReason;
762
+ return { ad: result, tracker: a.tracker(result) };
581
763
  };
764
+ // An ad will show, so there is no fill reason, even for a house ad (see ad.noFillReason).
582
765
  this.lastNoFillReason = null;
583
- return { served: { build, download, expiresAt, consumed: false, result: null } };
766
+ return { build, download, expiresAt, consumed: false, result: null, house: a.house, noFillReason: a.noFillReason };
584
767
  }
585
768
  }
@@ -31,7 +31,7 @@ function defaultConfig(serveBase) {
31
31
  enabled: true,
32
32
  min_sdk: { ios: '0.0.0', android: '0.0.0' },
33
33
  formats: ['interstitial', '300x250'],
34
- interstitial: { skip_after_ms: 8000, max_per_session: 3, min_gap_s: 120, audio: 'on' },
34
+ interstitial: { skip_after_ms: 8000, max_per_session: 3, min_gap_s: 120, audio: 'on', sponsor_label: true, house_ads: true },
35
35
  prefetch: { max_cached_creatives: 3, max_cache_mb: 20 },
36
36
  beacon: { viewable_after_ms: 2000, flush_interval_s: 30 },
37
37
  endpoints: { serve: serveBase },
@@ -80,6 +80,9 @@ function parseConfig(body, bundledBase) {
80
80
  max_per_session: num(it.max_per_session, d.interstitial.max_per_session, 0, 1000),
81
81
  min_gap_s: num(it.min_gap_s, d.interstitial.min_gap_s, 0, 86400),
82
82
  audio,
83
+ // Only an explicit false hides the line.
84
+ sponsor_label: it.sponsor_label !== false,
85
+ house_ads: it.house_ads !== false,
83
86
  },
84
87
  prefetch: {
85
88
  max_cached_creatives: num(pf.max_cached_creatives, d.prefetch.max_cached_creatives, 0, 100),
@@ -0,0 +1,92 @@
1
+ "use strict";
2
+ // The tracker for a house ad: the publisher's own creative, shown when no paid
3
+ // ad fills. Nothing is billed, so there is no /impression, /viewable, video
4
+ // event or click token: only the unbilled /fallback-impression and
5
+ // /fallback-click counters, fire-and-forget, and none of them in test mode.
6
+ Object.defineProperty(exports, "__esModule", { value: true });
7
+ exports.HouseTracker = void 0;
8
+ const beacons_1 = require("./beacons");
9
+ const click_1 = require("./click");
10
+ const http_1 = require("./http");
11
+ class HouseTracker {
12
+ constructor(d) {
13
+ this.d = d;
14
+ this.shownOnce = false;
15
+ this.clickedOnce = false;
16
+ this.pending = new Set();
17
+ this.houseAdPress = d.onPress;
18
+ }
19
+ /** Resolves when every counter in flight has settled. For tests. */
20
+ async settle() {
21
+ while (this.pending.size)
22
+ await Promise.all(Array.from(this.pending)).catch(() => undefined);
23
+ }
24
+ isExpired() {
25
+ return this.d.ctx.now() >= this.d.ad.expiresAt;
26
+ }
27
+ /**
28
+ * One POST to a house-ad counter, never retried, never awaited by the
29
+ * caller. The answer (200, 400 or 429) changes nothing. Never rejects.
30
+ */
31
+ send(route) {
32
+ const { ctx } = this.d;
33
+ if (this.d.test)
34
+ return;
35
+ const p = (0, http_1.httpRequest)(ctx.fetch, `${ctx.serveBase()}/${route}`, {
36
+ method: 'POST', headers: ctx.headers(), body: { fallback_id: this.d.fallbackId }, timeoutMs: beacons_1.BEACON_TIMEOUT_MS,
37
+ }).then((res) => {
38
+ if (res.status !== 200)
39
+ ctx.log.debug(`/${route} answered ${res.status || 'nothing'}`);
40
+ }).catch((e) => ctx.log.debug(`/${route} failed`, e));
41
+ this.pending.add(p);
42
+ p.finally(() => this.pending.delete(p)).catch(() => undefined);
43
+ }
44
+ shown() {
45
+ if (this.shownOnce)
46
+ return Promise.resolve();
47
+ this.shownOnce = true;
48
+ if (this.isExpired()) {
49
+ this.d.ctx.log.error(`house ad ${this.d.fallbackId} expired before it was shown; load a new one`);
50
+ return Promise.resolve();
51
+ }
52
+ try {
53
+ this.d.onShown();
54
+ }
55
+ catch { /* never throw */ }
56
+ this.send('fallback-impression');
57
+ return Promise.resolve();
58
+ }
59
+ progress(_positionMs, _opts) { }
60
+ complete() { }
61
+ skipped(_positionMs) { }
62
+ error() { }
63
+ /**
64
+ * Counts the tap once (fire-and-forget) and opens the destination right
65
+ * away. `{ open: false }` only counts it: the app shows its own screen.
66
+ */
67
+ async clicked(opts) {
68
+ const url = this.d.ad.destinationUrl;
69
+ if (!this.clickedOnce) {
70
+ this.clickedOnce = true;
71
+ this.send('fallback-click');
72
+ }
73
+ if ((opts === null || opts === void 0 ? void 0 : opts.open) === false)
74
+ return url;
75
+ if (!(0, click_1.isWebUrl)(url)) {
76
+ this.d.ctx.log.error(`house ad ${this.d.fallbackId}: destination is not an http(s) URL, not opened`);
77
+ return url;
78
+ }
79
+ try {
80
+ if (this.d.openUrl)
81
+ await this.d.openUrl(url);
82
+ else
83
+ this.d.ctx.log.warn('no openUrl adapter: the host must open the returned URL');
84
+ }
85
+ catch (e) {
86
+ this.d.ctx.log.error('openUrl failed', e);
87
+ }
88
+ return url;
89
+ }
90
+ async closed() { }
91
+ }
92
+ exports.HouseTracker = HouseTracker;
@@ -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),
@@ -29,7 +29,9 @@ const jsx_runtime_1 = require("react/jsx-runtime");
29
29
  // Optional ready-made fullscreen screen. Needs expo-video (Expo SDK 52+).
30
30
  // Layout follows a typical in-app video player: 9:16 video, a skip control that counts
31
31
  // down then reads "Skip Ad", a white call-to-action button, an optional
32
- // "Remove ads" slot and a small "Sponsored by Ethicly.ch" line under it.
32
+ // "Remove ads" slot and a small "Sponsored by Ethicly.ch" line under it. The
33
+ // line follows ad.showSponsorLabel: hidden for house ads, and for paid ads when
34
+ // the publisher switched it off in the dashboard.
33
35
  // Video starts with sound unless the effective audio (the `audio` prop, else
34
36
  // ad.audio: createEthicly's `audio` option, else /config) is 'none' or 'optional'.
35
37
  // The controls keep clear of the notch, status bar and home indicator: see
@@ -123,7 +125,7 @@ function useAppActive() {
123
125
  }, []);
124
126
  return active;
125
127
  }
126
- function InterstitialBody({ ad, tracker, onClose, onRemoveAds, removeAdsLabel, renderBelowButton, skipStyle, skipTextStyle, insets, backRef, audio: audioProp, }) {
128
+ function InterstitialBody({ ad, tracker, onClose, onRemoveAds, removeAdsLabel, onHouseAdPress, renderBelowButton, skipStyle, skipTextStyle, insets, backRef, audio: audioProp, }) {
127
129
  const audio = effectiveAudio(audioProp, ad);
128
130
  const safe = useSafeInsets(insets);
129
131
  const isVideo = ad.media.kind === 'video' && !!ad.media.videoUri;
@@ -252,13 +254,30 @@ function InterstitialBody({ ad, tracker, onClose, onRemoveAds, removeAdsLabel, r
252
254
  onClose();
253
255
  }, [ended, failed, isVideo, onClose, tracker]);
254
256
  const onCta = (0, react_1.useCallback)(() => {
257
+ // A house ad the app routes to its own screen: count the tap, close the
258
+ // ad the normal way, then hand over. Never for a paid ad.
259
+ const housePress = ad.house
260
+ ? onHouseAdPress || tracker.houseAdPress
261
+ : undefined;
262
+ if (housePress) {
263
+ // A second tap before the screen unmounts must not run the handler twice.
264
+ if (closedRef.current)
265
+ return;
266
+ void tracker.clicked({ open: false });
267
+ close();
268
+ try {
269
+ housePress(ad);
270
+ }
271
+ catch { /* the app's handler must not break the screen */ }
272
+ return;
273
+ }
255
274
  if (isVideo)
256
275
  player.pause();
257
276
  // Once the user has visited the advertiser, they can always close the ad
258
277
  // when they come back.
259
278
  setClicked(true);
260
279
  void tracker.clicked();
261
- }, [isVideo, player, tracker]);
280
+ }, [ad, close, isVideo, onHouseAdPress, player, tracker]);
262
281
  const toggleSound = (0, react_1.useCallback)(() => {
263
282
  setMuted((m) => {
264
283
  player.muted = !m;
@@ -270,7 +289,7 @@ function InterstitialBody({ ad, tracker, onClose, onRemoveAds, removeAdsLabel, r
270
289
  backRef.current = canSkip ? close : null;
271
290
  return ((0, jsx_runtime_1.jsxs)(react_native_1.View, { style: styles.root, children: [isVideo ? ((0, jsx_runtime_1.jsxs)(jsx_runtime_1.Fragment, { children: [ad.media.posterUri ? (0, jsx_runtime_1.jsx)(react_native_1.Image, { source: { uri: ad.media.posterUri }, style: react_native_1.StyleSheet.absoluteFill, resizeMode: "cover" }) : null, (0, jsx_runtime_1.jsx)(expo_video_1.VideoView, { player: player, style: react_native_1.StyleSheet.absoluteFill, contentFit: "cover", nativeControls: false, allowsPictureInPicture: false })] })) : ((0, jsx_runtime_1.jsx)(react_native_1.Image, { source: { uri: ad.media.uri }, style: react_native_1.StyleSheet.absoluteFill, resizeMode: "cover", onLoad: onImageLoad, onError: onImageError })), (0, jsx_runtime_1.jsxs)(react_native_1.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: [(0, jsx_runtime_1.jsxs)(react_native_1.View, { style: styles.leftGroup, children: [(0, jsx_runtime_1.jsx)(react_native_1.Text, { style: styles.adLabel, accessibilityRole: "text", children: "Ad" }), ad.test ? (0, jsx_runtime_1.jsx)(react_native_1.Text, { style: [styles.adLabel, styles.testLabel], accessibilityRole: "text", children: "Test ad" }) : null, isVideo && audio !== 'none' ? ((0, jsx_runtime_1.jsx)(react_native_1.Pressable, { onPress: toggleSound, style: styles.soundButton, accessibilityRole: "button", accessibilityLabel: muted ? 'Turn sound on' : 'Mute', hitSlop: 8, children: (0, jsx_runtime_1.jsx)(react_native_1.Text, { style: styles.soundText, children: muted ? 'Sound off' : 'Sound on' }) })) : null] }), (0, jsx_runtime_1.jsx)(react_native_1.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 ? ((0, jsx_runtime_1.jsxs)(react_native_1.View, { style: styles.skipRow, children: [(0, jsx_runtime_1.jsx)(react_native_1.Text, { style: [styles.skipText, skipTextStyle], children: "Skip Ad" }), (0, jsx_runtime_1.jsx)(SkipIcon, {})] })) : ((0, jsx_runtime_1.jsx)(react_native_1.Text, { style: [styles.skipText, styles.skipTextWaiting, skipTextStyle], children: `Skip in ${remainingS}` })) })] }), (0, jsx_runtime_1.jsxs)(react_native_1.View, { style: [styles.bottom, {
272
291
  bottom: Math.max(safe.bottom + BOTTOM_GAP, MIN_BOTTOM), left: safe.left + SIDE_GAP_BOTTOM, right: safe.right + SIDE_GAP_BOTTOM,
273
- }], pointerEvents: "box-none", children: [(0, jsx_runtime_1.jsx)(react_native_1.Pressable, { onPress: onCta, style: ({ pressed }) => [styles.cta, pressed && styles.ctaPressed], accessibilityRole: "link", children: (0, jsx_runtime_1.jsx)(react_native_1.Text, { style: styles.ctaText, numberOfLines: 1, children: ad.ctaLabel || 'Learn more' }) }), renderBelowButton ? renderBelowButton() : onRemoveAds ? ((0, jsx_runtime_1.jsx)(react_native_1.Pressable, { onPress: onRemoveAds, accessibilityRole: "button", hitSlop: 8, children: (0, jsx_runtime_1.jsx)(react_native_1.Text, { style: styles.removeAds, children: removeAdsLabel || 'Remove ads' }) })) : null, (0, jsx_runtime_1.jsx)(react_native_1.Text, { style: styles.sponsor, children: "Sponsored by Ethicly.ch" })] })] }));
292
+ }], pointerEvents: "box-none", children: [(0, jsx_runtime_1.jsx)(react_native_1.Pressable, { onPress: onCta, style: ({ pressed }) => [styles.cta, pressed && styles.ctaPressed], accessibilityRole: "link", children: (0, jsx_runtime_1.jsx)(react_native_1.Text, { style: styles.ctaText, numberOfLines: 1, children: ad.ctaLabel || 'Learn more' }) }), renderBelowButton ? renderBelowButton() : onRemoveAds ? ((0, jsx_runtime_1.jsx)(react_native_1.Pressable, { onPress: onRemoveAds, accessibilityRole: "button", hitSlop: 8, children: (0, jsx_runtime_1.jsx)(react_native_1.Text, { style: styles.removeAds, children: removeAdsLabel || 'Remove ads' }) })) : null, ad.showSponsorLabel ? (0, jsx_runtime_1.jsx)(react_native_1.Text, { style: styles.sponsor, children: "Sponsored by Ethicly.ch" }) : null] })] }));
274
293
  }
275
294
  /** Skip-to-end mark (a play triangle against a bar), drawn so it never depends on a font glyph. */
276
295
  function SkipIcon() {