@ethicly/react-native 0.2.0 → 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 +92 -1
- package/README.md +246 -53
- package/lib/commonjs/core/adapters.js +44 -5
- package/lib/commonjs/core/cache.js +60 -5
- package/lib/commonjs/core/click.js +10 -0
- package/lib/commonjs/core/client.js +237 -73
- package/lib/commonjs/core/config.js +17 -2
- package/lib/commonjs/core/index.js +2 -1
- package/lib/commonjs/core/tracker.js +8 -0
- package/lib/commonjs/react/EthiclyInterstitial.js +46 -13
- package/lib/commonjs/react/useEthiclyInterstitial.js +4 -1
- package/lib/commonjs/version.js +1 -1
- package/lib/module/core/adapters.js +44 -5
- package/lib/module/core/cache.js +59 -4
- package/lib/module/core/click.js +9 -0
- package/lib/module/core/client.js +237 -73
- package/lib/module/core/config.js +15 -1
- package/lib/module/core/index.js +1 -1
- package/lib/module/core/tracker.js +9 -1
- package/lib/module/react/EthiclyInterstitial.js +45 -13
- package/lib/module/react/useEthiclyInterstitial.js +4 -1
- package/lib/module/version.js +1 -1
- package/lib/typescript/core/adapters.d.ts +2 -1
- package/lib/typescript/core/cache.d.ts +20 -2
- package/lib/typescript/core/click.d.ts +5 -0
- package/lib/typescript/core/client.d.ts +42 -3
- package/lib/typescript/core/config.d.ts +9 -0
- package/lib/typescript/core/index.d.ts +2 -2
- package/lib/typescript/core/types.d.ts +48 -0
- package/lib/typescript/react/EthiclyInterstitial.d.ts +13 -1
- package/lib/typescript/react/useEthiclyInterstitial.d.ts +4 -2
- package/lib/typescript/version.d.ts +1 -1
- package/package.json +2 -2
- package/src/core/adapters.ts +33 -5
- package/src/core/cache.ts +48 -3
- package/src/core/click.ts +10 -0
- package/src/core/client.ts +278 -76
- package/src/core/config.ts +14 -1
- package/src/core/index.ts +4 -3
- package/src/core/tracker.ts +8 -1
- package/src/core/types.ts +57 -0
- package/src/react/EthiclyInterstitial.tsx +62 -16
- package/src/react/useEthiclyInterstitial.ts +8 -3
- package/src/version.ts +1 -1
package/src/core/client.ts
CHANGED
|
@@ -5,15 +5,16 @@ import {
|
|
|
5
5
|
createMemoryFileCache, createMemoryStorage, defaultAppState, isReleaseBuild, safeLogger, type AppStateLike,
|
|
6
6
|
} from './adapters';
|
|
7
7
|
import type { BeaconContext } from './beacons';
|
|
8
|
-
import { CreativeCache } from './cache';
|
|
9
|
-
import {
|
|
8
|
+
import { CreativeCache, type CachedMedia } from './cache';
|
|
9
|
+
import { isWebUrl } from './click';
|
|
10
|
+
import { BUNDLED_BASE_URL, clampSkipAfterMs, cleanServeBase, defaultConfig, isBelowMinSdk, maxAgeSeconds, parseConfig } from './config';
|
|
10
11
|
import { httpRequest, RouteGate } from './http';
|
|
11
12
|
import { outboxFor, replayRecord, type Outbox } from './outbox';
|
|
12
13
|
import { InterstitialTracker } from './tracker';
|
|
13
14
|
import { SDK_VERSION } from '../version';
|
|
14
15
|
import type {
|
|
15
|
-
EthiclyAd, EthiclyConfig, FetchLike, FileCacheAdapter,
|
|
16
|
-
Logger, NoFillReason, Platform, WireServe,
|
|
16
|
+
AudioPolicy, EthiclyAd, EthiclyConfig, FetchLike, FileCacheAdapter, FrequencyOptions, FrequencyUpdate,
|
|
17
|
+
InterstitialResult, KeyValueStorage, Logger, NextAdReason, NextAdStatus, NoFillReason, Platform, WireServe,
|
|
17
18
|
} from './types';
|
|
18
19
|
|
|
19
20
|
export interface EthiclyOptions {
|
|
@@ -30,8 +31,33 @@ export interface EthiclyOptions {
|
|
|
30
31
|
* (`__DEV__` false), where the SDK serves and bills normally and logs an error.
|
|
31
32
|
*/
|
|
32
33
|
testMode?: boolean;
|
|
33
|
-
/**
|
|
34
|
+
/**
|
|
35
|
+
* Initial state of the ads switch, default true. Apps with a paid tier: pass
|
|
36
|
+
* false until you know the user's entitlement, then setAdsEnabled(true) for
|
|
37
|
+
* free users, so a subscriber never serves or downloads an ad.
|
|
38
|
+
*/
|
|
34
39
|
adsEnabled?: boolean;
|
|
40
|
+
/**
|
|
41
|
+
* Sound for every ad, over the server's interstitial.audio: 'on' plays with
|
|
42
|
+
* sound, 'optional' starts muted with a sound toggle, 'none' plays muted with
|
|
43
|
+
* no toggle. Unset: the server's value, which defaults to 'on'. `ad.audio`
|
|
44
|
+
* is the effective value. EthiclyInterstitial's `audio` prop overrides it per screen.
|
|
45
|
+
*/
|
|
46
|
+
audio?: AudioPolicy;
|
|
47
|
+
/**
|
|
48
|
+
* The longest loadInterstitial() waits for the creative download when no
|
|
49
|
+
* preloaded ad is ready, in ms. Default 3000 (DEFAULT_LOAD_TIMEOUT_MS). After
|
|
50
|
+
* it the ad comes back with the remote URL, so the player streams, and the
|
|
51
|
+
* download carries on in the background for next time.
|
|
52
|
+
*/
|
|
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;
|
|
35
61
|
storage?: KeyValueStorage;
|
|
36
62
|
fileCache?: FileCacheAdapter;
|
|
37
63
|
openUrl?: (url: string) => unknown;
|
|
@@ -57,7 +83,19 @@ export interface Ethicly {
|
|
|
57
83
|
* false until the stored frequency state has loaded (see `ready`).
|
|
58
84
|
*/
|
|
59
85
|
canShow(): boolean;
|
|
60
|
-
/**
|
|
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>;
|
|
98
|
+
/** false for paid users: stops serves, drops the preloaded ad and cancels a download in flight. */
|
|
61
99
|
setAdsEnabled(enabled: boolean): void;
|
|
62
100
|
isAdsEnabled(): boolean;
|
|
63
101
|
getConfig(): EthiclyConfig;
|
|
@@ -68,6 +106,8 @@ export interface Ethicly {
|
|
|
68
106
|
readonly sdkVersion: string;
|
|
69
107
|
}
|
|
70
108
|
|
|
109
|
+
/** How long loadInterstitial() waits for a creative download by default. */
|
|
110
|
+
export const DEFAULT_LOAD_TIMEOUT_MS = 3000;
|
|
71
111
|
const CONFIG_TIMEOUT_MS = 5000;
|
|
72
112
|
const SERVE_TIMEOUT_MS = 8000;
|
|
73
113
|
const SIZE_PROBE_TIMEOUT_MS = 3000;
|
|
@@ -86,6 +126,41 @@ interface StoredFrequency { lastShownAt: number }
|
|
|
86
126
|
|
|
87
127
|
interface Preloaded { result: { ad: EthiclyAd; tracker: InterstitialTracker } }
|
|
88
128
|
|
|
129
|
+
/** A served ad whose creative is downloading. Built into an ad once, by preload() or loadInterstitial(). */
|
|
130
|
+
interface Served {
|
|
131
|
+
download: Promise<CachedMedia>;
|
|
132
|
+
build(uris: Record<string, string>): Preloaded['result'];
|
|
133
|
+
expiresAt: number;
|
|
134
|
+
/** Taken by loadInterstitial(): never stored as the preloaded ad. */
|
|
135
|
+
consumed: boolean;
|
|
136
|
+
result: Preloaded['result'] | null;
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
type ServeOutcome = { served: Served; noFill?: undefined } | { served?: undefined; noFill: InterstitialResult };
|
|
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
|
+
|
|
160
|
+
function audioPolicy(v: unknown): AudioPolicy | null {
|
|
161
|
+
return v === 'on' || v === 'optional' || v === 'none' ? v : null;
|
|
162
|
+
}
|
|
163
|
+
|
|
89
164
|
export function createEthicly(options: EthiclyOptions): Ethicly {
|
|
90
165
|
return new EthiclyClient(options);
|
|
91
166
|
}
|
|
@@ -123,11 +198,19 @@ class EthiclyClient implements Ethicly {
|
|
|
123
198
|
private shownCount = 0;
|
|
124
199
|
private lastShownAt: number | null = null;
|
|
125
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;
|
|
126
204
|
/** When the app left the foreground, null while it is in it. */
|
|
127
205
|
private backgroundSince: number | null = null;
|
|
128
206
|
private outbox: Outbox;
|
|
129
207
|
private preloaded: Preloaded | null = null;
|
|
130
|
-
private serveInflight: Promise<
|
|
208
|
+
private serveInflight: Promise<ServeOutcome> | null = null;
|
|
209
|
+
/** Served, creative still downloading, not yet taken. */
|
|
210
|
+
private pendingServed: Served | null = null;
|
|
211
|
+
private loadTimeoutMs: number;
|
|
212
|
+
private audio: AudioPolicy | null;
|
|
213
|
+
private badDestinationLogged = false;
|
|
131
214
|
|
|
132
215
|
constructor(private o: EthiclyOptions) {
|
|
133
216
|
this.bundled = cleanServeBase(o.baseUrl) || BUNDLED_BASE_URL;
|
|
@@ -145,6 +228,12 @@ class EthiclyClient implements Ethicly {
|
|
|
145
228
|
);
|
|
146
229
|
this.config = defaultConfig(this.bundled);
|
|
147
230
|
this.adsOn = o.adsEnabled !== false;
|
|
231
|
+
this.audio = audioPolicy(o.audio);
|
|
232
|
+
if (o.audio !== undefined && !this.audio) this.log.warn(`audio must be 'on', 'optional' or 'none': using the server's value`);
|
|
233
|
+
this.loadTimeoutMs = typeof o.loadTimeoutMs === 'number' && Number.isFinite(o.loadTimeoutMs) && o.loadTimeoutMs >= 0
|
|
234
|
+
? o.loadTimeoutMs
|
|
235
|
+
: DEFAULT_LOAD_TIMEOUT_MS;
|
|
236
|
+
if (o.frequency) this.setFrequency(o.frequency);
|
|
148
237
|
this.testMode = !!o.testMode && !isReleaseBuild();
|
|
149
238
|
if (o.testMode && !this.testMode) this.reportReleaseTestMode();
|
|
150
239
|
if (this.testMode) this.log.warn('test mode is on: nothing is billed. Never ship a release build with testMode.');
|
|
@@ -360,12 +449,54 @@ class EthiclyClient implements Ethicly {
|
|
|
360
449
|
|
|
361
450
|
// ------------------------------------------------------------- frequency
|
|
362
451
|
|
|
363
|
-
|
|
452
|
+
getFrequency(): Required<FrequencyOptions> {
|
|
364
453
|
const it = this.config.interstitial;
|
|
365
|
-
|
|
366
|
-
|
|
367
|
-
|
|
368
|
-
|
|
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;
|
|
369
500
|
}
|
|
370
501
|
|
|
371
502
|
private onShown(): void {
|
|
@@ -379,7 +510,11 @@ class EthiclyClient implements Ethicly {
|
|
|
379
510
|
|
|
380
511
|
setAdsEnabled(enabled: boolean): void {
|
|
381
512
|
this.adsOn = !!enabled;
|
|
382
|
-
if (
|
|
513
|
+
if (this.adsOn) return;
|
|
514
|
+
this.preloaded = null;
|
|
515
|
+
this.pendingServed = null;
|
|
516
|
+
// A paid user downloads nothing: stop the creative download in flight.
|
|
517
|
+
this.cache.cancel();
|
|
383
518
|
}
|
|
384
519
|
|
|
385
520
|
isAdsEnabled(): boolean {
|
|
@@ -388,7 +523,7 @@ class EthiclyClient implements Ethicly {
|
|
|
388
523
|
|
|
389
524
|
// ------------------------------------------------------------- serve
|
|
390
525
|
|
|
391
|
-
private blockedReason():
|
|
526
|
+
private blockedReason(): Exclude<NextAdReason, 'frequency_capped' | 'session_cap' | 'ads_disabled' | 'not_ready'> | null {
|
|
392
527
|
if (this.invalidKey) return 'invalid_key';
|
|
393
528
|
if (this.unknownKey) return 'unknown_key';
|
|
394
529
|
if (this.sdkUnsupported) return 'sdk_unsupported';
|
|
@@ -403,18 +538,46 @@ class EthiclyClient implements Ethicly {
|
|
|
403
538
|
return { ad: null, tracker: null, reason };
|
|
404
539
|
}
|
|
405
540
|
|
|
541
|
+
/** The served ad waiting for its download, or a new serve. One serve at a time. */
|
|
542
|
+
private serveOnce(): Promise<ServeOutcome> {
|
|
543
|
+
const p = this.pendingServed;
|
|
544
|
+
if (p && !p.consumed && this.now() < p.expiresAt) return Promise.resolve({ served: p });
|
|
545
|
+
this.pendingServed = null;
|
|
546
|
+
if (!this.serveInflight) {
|
|
547
|
+
this.serveInflight = this.serve()
|
|
548
|
+
.then((out) => {
|
|
549
|
+
if (out.served) this.pendingServed = out.served;
|
|
550
|
+
return out;
|
|
551
|
+
})
|
|
552
|
+
.finally(() => { this.serveInflight = null; });
|
|
553
|
+
}
|
|
554
|
+
return this.serveInflight;
|
|
555
|
+
}
|
|
556
|
+
|
|
557
|
+
/** The ad and tracker of a served ad, built once, by whoever asks first. */
|
|
558
|
+
private claim(s: Served, uris: Record<string, string>): Preloaded['result'] {
|
|
559
|
+
if (!s.result) s.result = s.build(uris);
|
|
560
|
+
return s.result;
|
|
561
|
+
}
|
|
562
|
+
|
|
406
563
|
async preload(): Promise<InterstitialResult> {
|
|
407
564
|
try {
|
|
408
565
|
if (!this.adsOn) return this.noFill('ads_disabled');
|
|
409
566
|
if (this.preloaded && !this.preloaded.result.tracker.isExpired()) return this.preloaded.result;
|
|
410
567
|
this.preloaded = null;
|
|
411
|
-
if (this.shownCount >= this.
|
|
412
|
-
|
|
413
|
-
|
|
568
|
+
if (this.shownCount >= this.getFrequency().maxPerSession) return this.noFill('frequency_capped');
|
|
569
|
+
const out = await this.serveOnce();
|
|
570
|
+
if (!out.served) return out.noFill;
|
|
571
|
+
const s = out.served;
|
|
572
|
+
// In the background: wait for the whole download, so the ad plays from disk.
|
|
573
|
+
const cached = await s.download;
|
|
574
|
+
if (!this.adsOn) return this.noFill('ads_disabled');
|
|
575
|
+
const r = this.claim(s, cached.uris);
|
|
576
|
+
if (!s.consumed) {
|
|
577
|
+
this.preloaded = { result: r };
|
|
578
|
+
if (this.pendingServed === s) this.pendingServed = null;
|
|
414
579
|
}
|
|
415
|
-
|
|
416
|
-
if (r.ad && this.adsOn) this.preloaded = { result: r as Preloaded['result'] };
|
|
417
|
-
return r.ad && !this.adsOn ? this.noFill('ads_disabled') : r;
|
|
580
|
+
return r;
|
|
418
581
|
} catch (e) {
|
|
419
582
|
this.log.error('preload failed', e);
|
|
420
583
|
return this.noFill('network_error');
|
|
@@ -429,8 +592,23 @@ class EthiclyClient implements Ethicly {
|
|
|
429
592
|
const blocked = this.blockedReason();
|
|
430
593
|
if (blocked) return this.noFill(blocked);
|
|
431
594
|
if (!this.canShow()) return this.noFill('frequency_capped');
|
|
432
|
-
const
|
|
595
|
+
const pre = this.preloaded;
|
|
433
596
|
this.preloaded = null;
|
|
597
|
+
if (pre && !pre.result.tracker.isExpired()) return pre.result;
|
|
598
|
+
|
|
599
|
+
const out = await this.serveOnce();
|
|
600
|
+
if (!out.served) return out.noFill;
|
|
601
|
+
const s = out.served;
|
|
602
|
+
// The user is waiting: give the download a short budget, then stream the
|
|
603
|
+
// remote file. The download carries on in the background for next time.
|
|
604
|
+
const cached = await this.within(s.download, this.loadTimeoutMs);
|
|
605
|
+
if (!this.adsOn) return this.noFill('ads_disabled');
|
|
606
|
+
if (!cached) this.log.info(`creative not on disk after ${this.loadTimeoutMs} ms: streaming it; the download continues for next time`);
|
|
607
|
+
const r = this.claim(s, cached ? cached.uris : {});
|
|
608
|
+
s.consumed = true;
|
|
609
|
+
if (this.pendingServed === s) this.pendingServed = null;
|
|
610
|
+
// A preload that finished meanwhile may have stored this same ad.
|
|
611
|
+
if ((this.preloaded as Preloaded | null)?.result === r) this.preloaded = null;
|
|
434
612
|
return r;
|
|
435
613
|
} catch (e) {
|
|
436
614
|
this.log.error('loadInterstitial failed', e);
|
|
@@ -438,12 +616,20 @@ class EthiclyClient implements Ethicly {
|
|
|
438
616
|
}
|
|
439
617
|
}
|
|
440
618
|
|
|
441
|
-
|
|
619
|
+
/** `p`, or null once `ms` have passed first. */
|
|
620
|
+
private within<T>(p: Promise<T>, ms: number): Promise<T | null> {
|
|
621
|
+
let timer: ReturnType<typeof setTimeout> | undefined;
|
|
622
|
+
const timeout = new Promise<null>((resolve) => { timer = setTimeout(() => resolve(null), ms); });
|
|
623
|
+
return Promise.race([p, timeout]).finally(() => { if (timer) clearTimeout(timer); });
|
|
624
|
+
}
|
|
625
|
+
|
|
626
|
+
private async serve(): Promise<ServeOutcome> {
|
|
627
|
+
const noFill = (reason: NoFillReason): ServeOutcome => ({ noFill: this.noFill(reason) });
|
|
442
628
|
await this.ready;
|
|
443
629
|
if (this.configStale()) await this.refreshConfig();
|
|
444
630
|
const blocked = this.blockedReason();
|
|
445
|
-
if (blocked) return
|
|
446
|
-
if (this.gate.waitMs('serve') > 0) return
|
|
631
|
+
if (blocked) return noFill(blocked);
|
|
632
|
+
if (this.gate.waitMs('serve') > 0) return noFill('rate_limited');
|
|
447
633
|
|
|
448
634
|
const q = [
|
|
449
635
|
`key=${encodeURIComponent(this.o.apiKey)}`,
|
|
@@ -459,89 +645,105 @@ class EthiclyClient implements Ethicly {
|
|
|
459
645
|
const servedAt = this.now();
|
|
460
646
|
if (res.status === 429) {
|
|
461
647
|
this.gate.block('serve', res.retryAfterS);
|
|
462
|
-
return
|
|
648
|
+
return noFill('rate_limited');
|
|
463
649
|
}
|
|
464
650
|
if (res.status === 400 || res.status === 403) {
|
|
465
651
|
this.invalidKey = true;
|
|
466
652
|
this.log.error(`serve ${res.status}: invalid publisher key. Not retried.`, res.body);
|
|
467
|
-
return
|
|
653
|
+
return noFill('invalid_key');
|
|
468
654
|
}
|
|
469
|
-
if (res.status === 0) return
|
|
470
|
-
if (res.status !== 200 || !res.body || typeof res.body !== 'object') return
|
|
655
|
+
if (res.status === 0) return noFill('network_error');
|
|
656
|
+
if (res.status !== 200 || !res.body || typeof res.body !== 'object') return noFill('server_error');
|
|
471
657
|
|
|
472
658
|
const body = res.body as WireServe;
|
|
473
659
|
if (!body.ad) {
|
|
474
660
|
const reason = typeof body.reason === 'string' && body.reason ? body.reason : 'no_matching_ad';
|
|
475
661
|
if (reason === 'app_disabled') this.appDisabled = true;
|
|
476
662
|
if (reason === 'sdk_unsupported') this.sdkUnsupported = true;
|
|
477
|
-
return
|
|
663
|
+
return noFill(reason);
|
|
478
664
|
}
|
|
479
665
|
const ad = body.ad;
|
|
480
666
|
const m = ad.media;
|
|
481
667
|
if (typeof ad.id !== 'number' || !m || typeof m.url !== 'string' || !m.url || typeof ad.destination_url !== 'string') {
|
|
482
668
|
this.log.warn('serve answered an ad without media or destination', body.request_id);
|
|
483
|
-
return
|
|
669
|
+
return noFill('invalid_response');
|
|
670
|
+
}
|
|
671
|
+
if (!isWebUrl(ad.destination_url)) {
|
|
672
|
+
// Only web pages are opened: never tel:, intent:, javascript: or an app scheme.
|
|
673
|
+
if (!this.badDestinationLogged) {
|
|
674
|
+
this.badDestinationLogged = true;
|
|
675
|
+
this.log.error(`ad ${ad.id}: destination is not an http(s) URL, ad skipped`, body.request_id);
|
|
676
|
+
}
|
|
677
|
+
return noFill('invalid_response');
|
|
484
678
|
}
|
|
485
679
|
if (body.test === true) this.log.info(`test serve: ad ${ad.id} on site ${body.publisher_site_id}`);
|
|
486
|
-
if (!this.adsOn) return
|
|
680
|
+
if (!this.adsOn) return noFill('ads_disabled');
|
|
487
681
|
|
|
488
682
|
const kind: 'video' | 'image' = m.kind === 'video' ? 'video' : 'image';
|
|
489
683
|
const poster = kind === 'video' && typeof m.poster_url === 'string' && m.poster_url ? m.poster_url : null;
|
|
490
684
|
const pf = this.config.prefetch;
|
|
491
|
-
|
|
685
|
+
// Started now, awaited by preload() in full and by loadInterstitial() within loadTimeoutMs.
|
|
686
|
+
const download = this.cache.ensure(
|
|
492
687
|
ad.id,
|
|
493
688
|
poster ? [m.url, poster] : [m.url],
|
|
494
689
|
{ maxCreatives: pf.max_cached_creatives, maxBytes: pf.max_cache_mb * 1024 * 1024 },
|
|
495
690
|
() => this.adsOn,
|
|
496
691
|
).catch(() => ({ uris: {} as Record<string, string> }));
|
|
497
|
-
if (!this.adsOn) return this.noFill('ads_disabled');
|
|
498
|
-
|
|
499
|
-
const uri = cached.uris[m.url] || m.url;
|
|
500
692
|
const ttlS = typeof body.token_ttl_s === 'number' && body.token_ttl_s > 0 ? body.token_ttl_s : DEFAULT_TTL_S;
|
|
693
|
+
const expiresAt = servedAt + ttlS * 1000;
|
|
694
|
+
const adId = ad.id;
|
|
695
|
+
const mediaUrl = m.url;
|
|
696
|
+
const destinationUrl = ad.destination_url;
|
|
501
697
|
const label = typeof ad.cta_label === 'string' ? ad.cta_label.trim() : '';
|
|
502
698
|
const posInt = (v: unknown, d: number) => (typeof v === 'number' && v > 0 ? Math.round(v) : d);
|
|
503
|
-
|
|
504
|
-
|
|
505
|
-
|
|
506
|
-
|
|
507
|
-
|
|
508
|
-
|
|
509
|
-
|
|
510
|
-
|
|
511
|
-
|
|
512
|
-
|
|
513
|
-
|
|
514
|
-
|
|
515
|
-
|
|
516
|
-
|
|
517
|
-
|
|
518
|
-
|
|
519
|
-
|
|
520
|
-
|
|
521
|
-
|
|
522
|
-
|
|
523
|
-
|
|
524
|
-
|
|
525
|
-
|
|
699
|
+
// The ad's value wins over /config, kept within the same 8 to 15 s range.
|
|
700
|
+
const skipAfterMs = clampSkipAfterMs(ad.skip_after_ms) ?? this.config.interstitial.skip_after_ms;
|
|
701
|
+
// The app's choice (options.audio) wins over the server's interstitial.audio.
|
|
702
|
+
const audio: AudioPolicy = this.audio ?? this.config.interstitial.audio;
|
|
703
|
+
const build = (uris: Record<string, string>): Preloaded['result'] => {
|
|
704
|
+
const uri = uris[mediaUrl] || mediaUrl;
|
|
705
|
+
const result: EthiclyAd = {
|
|
706
|
+
id: adId,
|
|
707
|
+
ctaLabel: label || 'Learn more',
|
|
708
|
+
destinationUrl,
|
|
709
|
+
skipAfterMs,
|
|
710
|
+
media: {
|
|
711
|
+
kind,
|
|
712
|
+
uri,
|
|
713
|
+
videoUri: kind === 'video' ? uri : null,
|
|
714
|
+
posterUri: poster ? uris[poster] || poster : null,
|
|
715
|
+
durationMs: kind === 'video' && typeof m.duration_ms === 'number' && m.duration_ms > 0 ? m.duration_ms : null,
|
|
716
|
+
mime: kind === 'video' ? (typeof m.mime === 'string' && m.mime ? m.mime : 'video/mp4') : null,
|
|
717
|
+
width: posInt(m.width, 720),
|
|
718
|
+
height: posInt(m.height, 1280),
|
|
719
|
+
cached: uri !== mediaUrl,
|
|
720
|
+
},
|
|
721
|
+
audio,
|
|
722
|
+
title: typeof ad.title === 'string' ? ad.title : null,
|
|
723
|
+
test: body.test === true,
|
|
724
|
+
servedAt,
|
|
725
|
+
expiresAt,
|
|
726
|
+
};
|
|
727
|
+
const tracker = new InterstitialTracker({
|
|
728
|
+
ctx: this.beaconCtx(),
|
|
729
|
+
ad: result,
|
|
730
|
+
serve: {
|
|
731
|
+
publisherSiteId: typeof body.publisher_site_id === 'number' && body.publisher_site_id > 0 ? body.publisher_site_id : null,
|
|
732
|
+
countryCode: typeof body.country_code === 'string' ? body.country_code : null,
|
|
733
|
+
impressionToken: typeof body.impression_token === 'string' ? body.impression_token : null,
|
|
734
|
+
},
|
|
735
|
+
viewableAfterMs: this.config.beacon.viewable_after_ms,
|
|
736
|
+
flushIntervalS: this.config.beacon.flush_interval_s,
|
|
737
|
+
platform: this.o.platform,
|
|
738
|
+
sdkVersion: SDK_VERSION,
|
|
739
|
+
appVersion: this.o.appVersion,
|
|
740
|
+
openUrl: this.o.openUrl,
|
|
741
|
+
onShown: () => this.onShown(),
|
|
742
|
+
outbox: this.outbox,
|
|
743
|
+
});
|
|
744
|
+
return { ad: result, tracker };
|
|
526
745
|
};
|
|
527
|
-
const tracker = new InterstitialTracker({
|
|
528
|
-
ctx: this.beaconCtx(),
|
|
529
|
-
ad: result,
|
|
530
|
-
serve: {
|
|
531
|
-
publisherSiteId: typeof body.publisher_site_id === 'number' && body.publisher_site_id > 0 ? body.publisher_site_id : null,
|
|
532
|
-
countryCode: typeof body.country_code === 'string' ? body.country_code : null,
|
|
533
|
-
impressionToken: typeof body.impression_token === 'string' ? body.impression_token : null,
|
|
534
|
-
},
|
|
535
|
-
viewableAfterMs: this.config.beacon.viewable_after_ms,
|
|
536
|
-
flushIntervalS: this.config.beacon.flush_interval_s,
|
|
537
|
-
platform: this.o.platform,
|
|
538
|
-
sdkVersion: SDK_VERSION,
|
|
539
|
-
appVersion: this.o.appVersion,
|
|
540
|
-
openUrl: this.o.openUrl,
|
|
541
|
-
onShown: () => this.onShown(),
|
|
542
|
-
outbox: this.outbox,
|
|
543
|
-
});
|
|
544
746
|
this.lastNoFillReason = null;
|
|
545
|
-
return {
|
|
747
|
+
return { served: { build, download, expiresAt, consumed: false, result: null } };
|
|
546
748
|
}
|
|
547
749
|
}
|
package/src/core/config.ts
CHANGED
|
@@ -5,6 +5,19 @@ import type { AudioPolicy, EthiclyConfig } from './types';
|
|
|
5
5
|
|
|
6
6
|
export const BUNDLED_BASE_URL = 'https://ads.ethicly.ch/functions/v1/get-ad-with-geo';
|
|
7
7
|
export const DEFAULT_MAX_AGE_S = 300;
|
|
8
|
+
/**
|
|
9
|
+
* The skip delay is kept within these bounds, from /config and from the ad:
|
|
10
|
+
* the video is watched for at least 8 s before Skip appears (it still
|
|
11
|
+
* unlocks earlier when the video ends or after the call to action).
|
|
12
|
+
*/
|
|
13
|
+
export const MIN_SKIP_AFTER_MS = 8000;
|
|
14
|
+
export const MAX_SKIP_AFTER_MS = 15000;
|
|
15
|
+
|
|
16
|
+
/** A skip delay in ms within MIN_SKIP_AFTER_MS..MAX_SKIP_AFTER_MS, or null when not a number. */
|
|
17
|
+
export function clampSkipAfterMs(v: unknown): number | null {
|
|
18
|
+
if (typeof v !== 'number' || !Number.isFinite(v)) return null;
|
|
19
|
+
return Math.min(MAX_SKIP_AFTER_MS, Math.max(MIN_SKIP_AFTER_MS, Math.round(v)));
|
|
20
|
+
}
|
|
8
21
|
|
|
9
22
|
/** The defaults shown in the doc. Used when no config was ever fetched. */
|
|
10
23
|
export function defaultConfig(serveBase: string): EthiclyConfig {
|
|
@@ -59,7 +72,7 @@ export function parseConfig(body: unknown, bundledBase: string): EthiclyConfig |
|
|
|
59
72
|
min_sdk: { ios: str(ms.ios, '0.0.0'), android: str(ms.android, '0.0.0') },
|
|
60
73
|
formats: Array.isArray(b.formats) ? b.formats.filter((f): f is string => typeof f === 'string') : d.formats,
|
|
61
74
|
interstitial: {
|
|
62
|
-
skip_after_ms:
|
|
75
|
+
skip_after_ms: clampSkipAfterMs(it.skip_after_ms) ?? d.interstitial.skip_after_ms,
|
|
63
76
|
max_per_session: num(it.max_per_session, d.interstitial.max_per_session, 0, 1000),
|
|
64
77
|
min_gap_s: num(it.min_gap_s, d.interstitial.min_gap_s, 0, 86400),
|
|
65
78
|
audio,
|
package/src/core/index.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
// Headless core: pure TypeScript, no React. It uses React Native's AppState when present.
|
|
2
|
-
export { createEthicly, SESSION_TIMEOUT_MS } from './client';
|
|
2
|
+
export { createEthicly, DEFAULT_LOAD_TIMEOUT_MS, SESSION_TIMEOUT_MS } from './client';
|
|
3
3
|
export type { Ethicly, EthiclyOptions } from './client';
|
|
4
4
|
export {
|
|
5
5
|
createMemoryStorage, createMemoryFileCache, createExpoFileCache, uuidv4,
|
|
@@ -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,
|
|
12
|
+
AudioPolicy, EthiclyAd, EthiclyAdMedia, EthiclyConfig, FetchLike, FileCacheAdapter, FrequencyOptions,
|
|
13
|
+
FrequencyUpdate, InterstitialResult, KeyValueStorage, Logger, NextAdReason, NextAdStatus, NoFillReason,
|
|
14
|
+
Platform, Tracker,
|
|
14
15
|
} from './types';
|
package/src/core/tracker.ts
CHANGED
|
@@ -3,7 +3,7 @@
|
|
|
3
3
|
// method swallows its errors and reports them through the logger.
|
|
4
4
|
|
|
5
5
|
import { BEACON_TIMEOUT_MS, ONE_HOUR_MS, sendWithRetry, type BeaconContext } from './beacons';
|
|
6
|
-
import { appendClickToken, CLICK_TIMEOUT_MS } from './click';
|
|
6
|
+
import { appendClickToken, CLICK_TIMEOUT_MS, isWebUrl } from './click';
|
|
7
7
|
import { asImpressionId, httpRequest } from './http';
|
|
8
8
|
import type { Outbox } from './outbox';
|
|
9
9
|
import { uuidv4 } from './adapters';
|
|
@@ -319,6 +319,11 @@ export class InterstitialTracker implements Tracker {
|
|
|
319
319
|
clicked(): Promise<string> {
|
|
320
320
|
if (!this.clickUrl) this.clickUrl = this.resolveClickUrl().catch(() => this.d.ad.destinationUrl);
|
|
321
321
|
return this.clickUrl.then(async (url) => {
|
|
322
|
+
// The client already refuses such an ad; this guards a hand-built EthiclyAd.
|
|
323
|
+
if (!isWebUrl(url)) {
|
|
324
|
+
this.d.ctx.log.error(`ad ${this.d.ad.id}: destination is not an http(s) URL, not opened`);
|
|
325
|
+
return url;
|
|
326
|
+
}
|
|
322
327
|
try {
|
|
323
328
|
if (this.d.openUrl) await this.d.openUrl(url);
|
|
324
329
|
else this.d.ctx.log.warn('no openUrl adapter: the host must open the returned URL');
|
|
@@ -348,6 +353,8 @@ export class InterstitialTracker implements Tracker {
|
|
|
348
353
|
const body: Record<string, unknown> = { ad_id: ad.id, impression_id: imp.id };
|
|
349
354
|
if (serve.publisherSiteId) body.publisher_site_id = serve.publisherSiteId;
|
|
350
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;
|
|
351
358
|
// Never retried: one request, whatever happens.
|
|
352
359
|
const res = await httpRequest(ctx.fetch, `${ctx.serveBase()}/click`, {
|
|
353
360
|
method: 'POST', headers: ctx.headers(), body, timeoutMs: Math.min(remaining, BEACON_TIMEOUT_MS),
|
package/src/core/types.ts
CHANGED
|
@@ -42,6 +42,11 @@ export interface FileCacheAdapter {
|
|
|
42
42
|
list?(): Promise<string[]>;
|
|
43
43
|
/** The uri `download(url, fileName)` writes to, so an unfinished download can be deleted. */
|
|
44
44
|
uriFor?(fileName: string): string;
|
|
45
|
+
/**
|
|
46
|
+
* Abort every download in flight: each rejects and leaves no file. Optional;
|
|
47
|
+
* used by setAdsEnabled(false) and for a download that takes too long.
|
|
48
|
+
*/
|
|
49
|
+
cancel?(): void;
|
|
45
50
|
}
|
|
46
51
|
|
|
47
52
|
export interface Logger {
|
|
@@ -178,3 +183,55 @@ export interface WireServe {
|
|
|
178
183
|
test?: boolean;
|
|
179
184
|
request_id?: string;
|
|
180
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
|
+
}
|