@ethicly/react-native 0.0.0-stage → 0.2.1

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 (70) hide show
  1. package/CHANGELOG.md +133 -0
  2. package/LICENSE +21 -0
  3. package/README.md +428 -2
  4. package/core/package.json +6 -0
  5. package/interstitial/package.json +6 -0
  6. package/lib/commonjs/core/adapters.js +326 -0
  7. package/lib/commonjs/core/beacons.js +70 -0
  8. package/lib/commonjs/core/cache.js +261 -0
  9. package/lib/commonjs/core/click.js +29 -0
  10. package/lib/commonjs/core/client.js +585 -0
  11. package/lib/commonjs/core/config.js +128 -0
  12. package/lib/commonjs/core/http.js +115 -0
  13. package/lib/commonjs/core/index.js +21 -0
  14. package/lib/commonjs/core/outbox.js +192 -0
  15. package/lib/commonjs/core/tracker.js +379 -0
  16. package/lib/commonjs/core/types.js +4 -0
  17. package/lib/commonjs/index.js +22 -0
  18. package/lib/commonjs/interstitial.js +7 -0
  19. package/lib/commonjs/react/EthiclyInterstitial.js +319 -0
  20. package/lib/commonjs/react/useEthiclyInterstitial.js +54 -0
  21. package/lib/commonjs/version.js +5 -0
  22. package/lib/module/core/adapters.js +315 -0
  23. package/lib/module/core/beacons.js +64 -0
  24. package/lib/module/core/cache.js +257 -0
  25. package/lib/module/core/click.js +24 -0
  26. package/lib/module/core/client.js +581 -0
  27. package/lib/module/core/config.js +118 -0
  28. package/lib/module/core/http.js +105 -0
  29. package/lib/module/core/index.js +6 -0
  30. package/lib/module/core/outbox.js +186 -0
  31. package/lib/module/core/tracker.js +375 -0
  32. package/lib/module/core/types.js +3 -0
  33. package/lib/module/index.js +4 -0
  34. package/lib/module/interstitial.js +3 -0
  35. package/lib/module/react/EthiclyInterstitial.js +292 -0
  36. package/lib/module/react/useEthiclyInterstitial.js +51 -0
  37. package/lib/module/version.js +2 -0
  38. package/lib/typescript/core/adapters.d.ts +139 -0
  39. package/lib/typescript/core/beacons.d.ts +32 -0
  40. package/lib/typescript/core/cache.d.ts +71 -0
  41. package/lib/typescript/core/click.d.ts +13 -0
  42. package/lib/typescript/core/client.d.ts +78 -0
  43. package/lib/typescript/core/config.d.ts +33 -0
  44. package/lib/typescript/core/http.d.ts +34 -0
  45. package/lib/typescript/core/index.d.ts +8 -0
  46. package/lib/typescript/core/outbox.d.ts +56 -0
  47. package/lib/typescript/core/tracker.d.ts +95 -0
  48. package/lib/typescript/core/types.d.ts +175 -0
  49. package/lib/typescript/index.d.ts +3 -0
  50. package/lib/typescript/interstitial.d.ts +2 -0
  51. package/lib/typescript/react/EthiclyInterstitial.d.ts +51 -0
  52. package/lib/typescript/react/useEthiclyInterstitial.d.ts +20 -0
  53. package/lib/typescript/version.d.ts +2 -0
  54. package/package.json +101 -4
  55. package/src/core/adapters.ts +365 -0
  56. package/src/core/beacons.ts +81 -0
  57. package/src/core/cache.ts +261 -0
  58. package/src/core/click.ts +26 -0
  59. package/src/core/client.ts +665 -0
  60. package/src/core/config.ts +124 -0
  61. package/src/core/http.ts +115 -0
  62. package/src/core/index.ts +14 -0
  63. package/src/core/outbox.ts +193 -0
  64. package/src/core/tracker.ts +376 -0
  65. package/src/core/types.ts +185 -0
  66. package/src/index.ts +5 -0
  67. package/src/interstitial.ts +4 -0
  68. package/src/react/EthiclyInterstitial.tsx +432 -0
  69. package/src/react/useEthiclyInterstitial.ts +74 -0
  70. package/src/version.ts +2 -0
@@ -0,0 +1,585 @@
1
+ "use strict";
2
+ // createEthicly: config, serve, prefetch, frequency caps and the ads switch.
3
+ // Pure TypeScript; every native capability comes in through an adapter.
4
+ Object.defineProperty(exports, "__esModule", { value: true });
5
+ exports.SESSION_TIMEOUT_MS = exports.DEFAULT_LOAD_TIMEOUT_MS = void 0;
6
+ exports.createEthicly = createEthicly;
7
+ const adapters_1 = require("./adapters");
8
+ const cache_1 = require("./cache");
9
+ const click_1 = require("./click");
10
+ const config_1 = require("./config");
11
+ const http_1 = require("./http");
12
+ const outbox_1 = require("./outbox");
13
+ const tracker_1 = require("./tracker");
14
+ const version_1 = require("../version");
15
+ /** How long loadInterstitial() waits for a creative download by default. */
16
+ exports.DEFAULT_LOAD_TIMEOUT_MS = 3000;
17
+ const CONFIG_TIMEOUT_MS = 5000;
18
+ const SERVE_TIMEOUT_MS = 8000;
19
+ const SIZE_PROBE_TIMEOUT_MS = 3000;
20
+ const CONFIG_RETRY_AFTER_FAILURE_MS = 30000;
21
+ const DEFAULT_TTL_S = 3600;
22
+ /**
23
+ * A new session (interstitial.max_per_session counts from zero again) starts
24
+ * when the app comes back after at least this long in the background.
25
+ */
26
+ exports.SESSION_TIMEOUT_MS = 30 * 60 * 1000;
27
+ let releaseTestModeLogged = false;
28
+ function audioPolicy(v) {
29
+ return v === 'on' || v === 'optional' || v === 'none' ? v : null;
30
+ }
31
+ function createEthicly(options) {
32
+ return new EthiclyClient(options);
33
+ }
34
+ class EthiclyClient {
35
+ constructor(o) {
36
+ this.o = o;
37
+ this.sdkVersion = version_1.SDK_VERSION;
38
+ this.lastNoFillReason = null;
39
+ this.configSource = 'default';
40
+ this.configFetchedAt = 0;
41
+ this.configMaxAgeS = 300;
42
+ this.configRetryAt = 0;
43
+ this.configInflight = null;
44
+ /** 404 unknown_key with no stored config. */
45
+ this.unknownKey = false;
46
+ /** 400 or 403 on a key: integration bug, stop for this process. */
47
+ this.invalidKey = false;
48
+ /** app_disabled from serve: until a later /config says enabled. */
49
+ this.appDisabled = false;
50
+ /** sdk_unsupported: for the rest of the process lifetime. */
51
+ this.sdkUnsupported = false;
52
+ this.shownCount = 0;
53
+ this.lastShownAt = null;
54
+ this.frequencyLoaded = false;
55
+ /** When the app left the foreground, null while it is in it. */
56
+ this.backgroundSince = null;
57
+ this.preloaded = null;
58
+ this.serveInflight = null;
59
+ /** Served, creative still downloading, not yet taken. */
60
+ this.pendingServed = null;
61
+ this.badDestinationLogged = false;
62
+ this.bundled = (0, config_1.cleanServeBase)(o.baseUrl) || config_1.BUNDLED_BASE_URL;
63
+ const f = o.fetch || globalThis.fetch;
64
+ if (!f)
65
+ throw new Error('[ethicly] no fetch available: pass options.fetch');
66
+ this.fetchFn = f;
67
+ this.now = o.now || Date.now;
68
+ this.log = (0, adapters_1.safeLogger)(o.logger);
69
+ this.storage = o.storage || (0, adapters_1.createMemoryStorage)();
70
+ this.gate = new http_1.RouteGate(this.now);
71
+ // The size probe only matters when files really land on disk.
72
+ 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
+ this.config = (0, config_1.defaultConfig)(this.bundled);
74
+ this.adsOn = o.adsEnabled !== false;
75
+ this.audio = audioPolicy(o.audio);
76
+ if (o.audio !== undefined && !this.audio)
77
+ this.log.warn(`audio must be 'on', 'optional' or 'none': using the server's value`);
78
+ this.loadTimeoutMs = typeof o.loadTimeoutMs === 'number' && Number.isFinite(o.loadTimeoutMs) && o.loadTimeoutMs >= 0
79
+ ? o.loadTimeoutMs
80
+ : exports.DEFAULT_LOAD_TIMEOUT_MS;
81
+ this.testMode = !!o.testMode && !(0, adapters_1.isReleaseBuild)();
82
+ if (o.testMode && !this.testMode)
83
+ this.reportReleaseTestMode();
84
+ if (this.testMode)
85
+ this.log.warn('test mode is on: nothing is billed. Never ship a release build with testMode.');
86
+ this.outbox = (0, outbox_1.outboxFor)(this.storage, o.apiKey, this.log);
87
+ this.watchAppState(o.appState === undefined ? (0, adapters_1.defaultAppState)() : o.appState);
88
+ this.ready = this.init().catch((e) => this.log.error('init failed', e));
89
+ }
90
+ /** testMode in a release build would earn the publisher nothing: ignore it, loudly, once. */
91
+ reportReleaseTestMode() {
92
+ var _a, _b;
93
+ const msg = 'testMode is set in a release build: ignored, ads are served and billed normally. Set testMode: __DEV__.';
94
+ this.log.error(msg);
95
+ if (releaseTestModeLogged)
96
+ return;
97
+ releaseTestModeLogged = true;
98
+ try {
99
+ (_b = (_a = globalThis.console) === null || _a === void 0 ? void 0 : _a.error) === null || _b === void 0 ? void 0 : _b.call(_a, `[ethicly] ${msg}`);
100
+ }
101
+ catch { /* never throw */ }
102
+ }
103
+ /** Sessions: back in the foreground after SESSION_TIMEOUT_MS or more starts a new one. */
104
+ watchAppState(appState) {
105
+ if (!appState)
106
+ return;
107
+ const onChange = (state) => {
108
+ if (state === 'active') {
109
+ if (this.backgroundSince !== null && this.now() - this.backgroundSince >= exports.SESSION_TIMEOUT_MS) {
110
+ this.shownCount = 0;
111
+ this.log.debug('new session after time in the background');
112
+ }
113
+ this.backgroundSince = null;
114
+ }
115
+ else if (this.backgroundSince === null) {
116
+ this.backgroundSince = this.now();
117
+ }
118
+ };
119
+ try {
120
+ if (appState.currentState && appState.currentState !== 'active')
121
+ onChange(appState.currentState);
122
+ // Kept for the life of the client, which is the life of the process.
123
+ appState.addEventListener('change', (s) => { try {
124
+ onChange(s);
125
+ }
126
+ catch { /* never throw */ } });
127
+ }
128
+ catch (e) {
129
+ this.log.warn('could not watch AppState: one session per process', e);
130
+ }
131
+ }
132
+ /** Content-Length from a HEAD request, so an oversized creative is never written. */
133
+ async contentLength(url) {
134
+ let timer;
135
+ try {
136
+ const timeout = new Promise((resolve) => { timer = setTimeout(() => resolve(null), SIZE_PROBE_TIMEOUT_MS); });
137
+ const res = await Promise.race([this.fetchFn(url, { method: 'HEAD' }), timeout]);
138
+ if (!res)
139
+ return null;
140
+ const n = Number(res.headers.get('content-length'));
141
+ return res.status >= 200 && res.status < 300 && Number.isFinite(n) && n > 0 ? n : null;
142
+ }
143
+ catch {
144
+ return null;
145
+ }
146
+ finally {
147
+ if (timer)
148
+ clearTimeout(timer);
149
+ }
150
+ }
151
+ // ------------------------------------------------------------- headers
152
+ headers() {
153
+ return { 'X-Ethicly-SDK': `${this.o.platform}/${version_1.SDK_VERSION}` };
154
+ }
155
+ serveBase() {
156
+ return this.configSource === 'default' ? this.bundled : this.config.endpoints.serve;
157
+ }
158
+ beaconCtx() {
159
+ return {
160
+ fetch: this.fetchFn,
161
+ serveBase: () => this.serveBase(),
162
+ headers: () => this.headers(),
163
+ gate: this.gate,
164
+ now: this.now,
165
+ log: this.log,
166
+ };
167
+ }
168
+ // ------------------------------------------------------------- config
169
+ get storageKey() {
170
+ return `ethicly:v1:config:${this.o.apiKey}`;
171
+ }
172
+ get frequencyKey() {
173
+ return `ethicly:v1:frequency:${this.o.apiKey}`;
174
+ }
175
+ /** The last shown time survives restarts, so min_gap_s does too. Never rejects. */
176
+ async loadFrequency() {
177
+ var _a;
178
+ try {
179
+ const raw = await this.storage.getItem(this.frequencyKey);
180
+ const t = raw ? JSON.parse(raw).lastShownAt : null;
181
+ // A time in the future (the clock moved back) is ignored.
182
+ if (typeof t === 'number' && Number.isFinite(t) && t <= this.now()) {
183
+ this.lastShownAt = Math.max((_a = this.lastShownAt) !== null && _a !== void 0 ? _a : 0, t);
184
+ }
185
+ }
186
+ catch (e) {
187
+ this.log.warn('stored frequency state unreadable', e);
188
+ }
189
+ finally {
190
+ this.frequencyLoaded = true;
191
+ }
192
+ }
193
+ async init() {
194
+ await Promise.all([this.loadFrequency(), this.outbox.load()]);
195
+ try {
196
+ const raw = await this.storage.getItem(this.storageKey);
197
+ if (raw) {
198
+ const s = JSON.parse(raw);
199
+ const parsed = (0, config_1.parseConfig)(s.config, this.bundled);
200
+ if (parsed) {
201
+ this.config = parsed;
202
+ this.configSource = 'stored';
203
+ this.configFetchedAt = s.fetchedAt;
204
+ this.configMaxAgeS = s.maxAgeS;
205
+ }
206
+ }
207
+ }
208
+ catch (e) {
209
+ this.log.warn('stored config unreadable', e);
210
+ }
211
+ this.applyConfigGates();
212
+ if (this.configStale())
213
+ await this.refreshConfig();
214
+ void this.replayOutbox();
215
+ }
216
+ /**
217
+ * Send what a previous run left unsent, one ad at a time. Not while a kill
218
+ * switch is on (app_disabled, sdk_unsupported) or the key is refused: the
219
+ * records then stay stored and expire one hour after their ad was shown.
220
+ * Never rejects.
221
+ */
222
+ async replayOutbox() {
223
+ const blocked = this.blockedReason();
224
+ if (blocked && blocked !== 'interstitial_disabled') {
225
+ this.log.info(`unsent beacons from the last run held back: ${blocked}`);
226
+ return;
227
+ }
228
+ const orphans = this.outbox.claimOrphans(this.now());
229
+ if (orphans.length)
230
+ this.log.info(`sending ${orphans.length} unsent beacon set(s) from the last run`);
231
+ for (const rec of orphans)
232
+ await (0, outbox_1.replayRecord)(this.beaconCtx(), this.outbox, rec);
233
+ }
234
+ configStale() {
235
+ return this.configSource !== 'network' && this.configSource !== 'stored'
236
+ ? true
237
+ : this.now() - this.configFetchedAt >= this.configMaxAgeS * 1000;
238
+ }
239
+ applyConfigGates() {
240
+ if (this.configSource === 'default')
241
+ return;
242
+ if (this.config.enabled)
243
+ this.appDisabled = false;
244
+ const min = this.o.platform === 'ios' ? this.config.min_sdk.ios : this.config.min_sdk.android;
245
+ if ((0, config_1.isBelowMinSdk)(version_1.SDK_VERSION, min)) {
246
+ if (!this.sdkUnsupported)
247
+ this.log.error(`SDK ${version_1.SDK_VERSION} is below min_sdk ${min}: no ads until the app updates`);
248
+ this.sdkUnsupported = true;
249
+ }
250
+ }
251
+ getConfig() {
252
+ return this.config;
253
+ }
254
+ refreshConfig() {
255
+ if (this.invalidKey || this.now() < this.configRetryAt)
256
+ return Promise.resolve();
257
+ if (!this.configInflight) {
258
+ this.configInflight = this.fetchConfig().catch((e) => this.log.error('config fetch failed', e))
259
+ .finally(() => { this.configInflight = null; });
260
+ }
261
+ return this.configInflight;
262
+ }
263
+ async fetchConfig() {
264
+ var _a;
265
+ const url = `${this.bundled}/config?key=${encodeURIComponent(this.o.apiKey)}&platform=${this.o.platform}`;
266
+ const res = await (0, http_1.httpRequest)(this.fetchFn, url, { headers: this.headers(), timeoutMs: CONFIG_TIMEOUT_MS });
267
+ if (res.status === 200) {
268
+ const parsed = (0, config_1.parseConfig)(res.body, this.bundled);
269
+ if (parsed) {
270
+ this.config = parsed;
271
+ this.configSource = 'network';
272
+ this.configFetchedAt = this.now();
273
+ this.configMaxAgeS = (0, config_1.maxAgeSeconds)(res.cacheControl);
274
+ this.unknownKey = false;
275
+ this.applyConfigGates();
276
+ const stored = { config: parsed, fetchedAt: this.configFetchedAt, maxAgeS: this.configMaxAgeS };
277
+ await this.storage.setItem(this.storageKey, JSON.stringify(stored)).catch(() => undefined);
278
+ return;
279
+ }
280
+ this.log.warn('config body unreadable, keeping the last known config');
281
+ this.configRetryAt = this.now() + CONFIG_RETRY_AFTER_FAILURE_MS;
282
+ return;
283
+ }
284
+ if (res.status === 429) {
285
+ this.configRetryAt = this.now() + Math.max(1, (_a = res.retryAfterS) !== null && _a !== void 0 ? _a : 1) * 1000;
286
+ this.log.warn('config rate limited, keeping the last known config');
287
+ return;
288
+ }
289
+ if (res.status === 404) {
290
+ // Kept for this session; with nothing stored there is no ad.
291
+ if (this.configSource === 'default')
292
+ this.unknownKey = true;
293
+ this.configRetryAt = this.now() + this.configMaxAgeS * 1000;
294
+ this.log.warn('config 404 unknown_key (unknown or not approved site)');
295
+ return;
296
+ }
297
+ if (res.status === 400) {
298
+ this.invalidKey = true;
299
+ this.log.error('config 400: the API key is missing or not a UUID. Not retried.');
300
+ return;
301
+ }
302
+ // 5xx, timeout, network error: keep the last known config, retry later.
303
+ this.configRetryAt = this.now() + CONFIG_RETRY_AFTER_FAILURE_MS;
304
+ this.log.warn(`config fetch failed (${res.status || 'network'}), keeping the last known config`);
305
+ }
306
+ // ------------------------------------------------------------- frequency
307
+ canShow() {
308
+ 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;
316
+ }
317
+ onShown() {
318
+ this.shownCount += 1;
319
+ this.lastShownAt = this.now();
320
+ const stored = { lastShownAt: this.lastShownAt };
321
+ try {
322
+ this.storage.setItem(this.frequencyKey, JSON.stringify(stored)).catch(() => undefined);
323
+ }
324
+ catch { /* a storage that throws synchronously must not reach the host */ }
325
+ }
326
+ setAdsEnabled(enabled) {
327
+ this.adsOn = !!enabled;
328
+ if (this.adsOn)
329
+ return;
330
+ this.preloaded = null;
331
+ this.pendingServed = null;
332
+ // A paid user downloads nothing: stop the creative download in flight.
333
+ this.cache.cancel();
334
+ }
335
+ isAdsEnabled() {
336
+ return this.adsOn;
337
+ }
338
+ // ------------------------------------------------------------- serve
339
+ blockedReason() {
340
+ if (this.invalidKey)
341
+ return 'invalid_key';
342
+ if (this.unknownKey)
343
+ return 'unknown_key';
344
+ if (this.sdkUnsupported)
345
+ return 'sdk_unsupported';
346
+ if (this.appDisabled || (this.configSource !== 'default' && !this.config.enabled))
347
+ return 'app_disabled';
348
+ if (this.configSource !== 'default' && this.config.formats.indexOf('interstitial') === -1)
349
+ return 'interstitial_disabled';
350
+ return null;
351
+ }
352
+ noFill(reason) {
353
+ this.lastNoFillReason = reason;
354
+ this.log.info(`no ad: ${reason}`);
355
+ return { ad: null, tracker: null, reason };
356
+ }
357
+ /** The served ad waiting for its download, or a new serve. One serve at a time. */
358
+ serveOnce() {
359
+ const p = this.pendingServed;
360
+ if (p && !p.consumed && this.now() < p.expiresAt)
361
+ return Promise.resolve({ served: p });
362
+ this.pendingServed = null;
363
+ if (!this.serveInflight) {
364
+ this.serveInflight = this.serve()
365
+ .then((out) => {
366
+ if (out.served)
367
+ this.pendingServed = out.served;
368
+ return out;
369
+ })
370
+ .finally(() => { this.serveInflight = null; });
371
+ }
372
+ return this.serveInflight;
373
+ }
374
+ /** The ad and tracker of a served ad, built once, by whoever asks first. */
375
+ claim(s, uris) {
376
+ if (!s.result)
377
+ s.result = s.build(uris);
378
+ return s.result;
379
+ }
380
+ async preload() {
381
+ try {
382
+ if (!this.adsOn)
383
+ 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)
388
+ return this.noFill('frequency_capped');
389
+ const out = await this.serveOnce();
390
+ if (!out.served)
391
+ return out.noFill;
392
+ const s = out.served;
393
+ // In the background: wait for the whole download, so the ad plays from disk.
394
+ const cached = await s.download;
395
+ if (!this.adsOn)
396
+ return this.noFill('ads_disabled');
397
+ const r = this.claim(s, cached.uris);
398
+ if (!s.consumed) {
399
+ this.preloaded = { result: r };
400
+ if (this.pendingServed === s)
401
+ this.pendingServed = null;
402
+ }
403
+ return r;
404
+ }
405
+ catch (e) {
406
+ this.log.error('preload failed', e);
407
+ return this.noFill('network_error');
408
+ }
409
+ }
410
+ async loadInterstitial() {
411
+ var _a;
412
+ try {
413
+ await this.ready;
414
+ if (!this.adsOn)
415
+ return this.noFill('ads_disabled');
416
+ if (this.configStale())
417
+ await this.refreshConfig();
418
+ const blocked = this.blockedReason();
419
+ if (blocked)
420
+ return this.noFill(blocked);
421
+ if (!this.canShow())
422
+ return this.noFill('frequency_capped');
423
+ const pre = this.preloaded;
424
+ 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;
430
+ const s = out.served;
431
+ // The user is waiting: give the download a short budget, then stream the
432
+ // remote file. The download carries on in the background for next time.
433
+ const cached = await this.within(s.download, this.loadTimeoutMs);
434
+ if (!this.adsOn)
435
+ return this.noFill('ads_disabled');
436
+ if (!cached)
437
+ this.log.info(`creative not on disk after ${this.loadTimeoutMs} ms: streaming it; the download continues for next time`);
438
+ const r = this.claim(s, cached ? cached.uris : {});
439
+ s.consumed = true;
440
+ if (this.pendingServed === s)
441
+ this.pendingServed = null;
442
+ // A preload that finished meanwhile may have stored this same ad.
443
+ if (((_a = this.preloaded) === null || _a === void 0 ? void 0 : _a.result) === r)
444
+ this.preloaded = null;
445
+ return r;
446
+ }
447
+ catch (e) {
448
+ this.log.error('loadInterstitial failed', e);
449
+ return this.noFill('network_error');
450
+ }
451
+ }
452
+ /** `p`, or null once `ms` have passed first. */
453
+ within(p, ms) {
454
+ let timer;
455
+ const timeout = new Promise((resolve) => { timer = setTimeout(() => resolve(null), ms); });
456
+ return Promise.race([p, timeout]).finally(() => { if (timer)
457
+ clearTimeout(timer); });
458
+ }
459
+ async serve() {
460
+ var _a, _b;
461
+ const noFill = (reason) => ({ noFill: this.noFill(reason) });
462
+ await this.ready;
463
+ if (this.configStale())
464
+ await this.refreshConfig();
465
+ const blocked = this.blockedReason();
466
+ if (blocked)
467
+ return noFill(blocked);
468
+ if (this.gate.waitMs('serve') > 0)
469
+ return noFill('rate_limited');
470
+ const q = [
471
+ `key=${encodeURIComponent(this.o.apiKey)}`,
472
+ 'format=interstitial',
473
+ `platform=${this.o.platform}`,
474
+ `sdk_version=${encodeURIComponent(version_1.SDK_VERSION)}`,
475
+ `app_version=${encodeURIComponent(this.o.appVersion)}`,
476
+ ];
477
+ if (this.testMode)
478
+ q.push('test=1');
479
+ const res = await (0, http_1.httpRequest)(this.fetchFn, `${this.serveBase()}?${q.join('&')}`, {
480
+ headers: this.headers(), timeoutMs: SERVE_TIMEOUT_MS,
481
+ });
482
+ const servedAt = this.now();
483
+ if (res.status === 429) {
484
+ this.gate.block('serve', res.retryAfterS);
485
+ return noFill('rate_limited');
486
+ }
487
+ if (res.status === 400 || res.status === 403) {
488
+ this.invalidKey = true;
489
+ this.log.error(`serve ${res.status}: invalid publisher key. Not retried.`, res.body);
490
+ return noFill('invalid_key');
491
+ }
492
+ if (res.status === 0)
493
+ return noFill('network_error');
494
+ if (res.status !== 200 || !res.body || typeof res.body !== 'object')
495
+ return noFill('server_error');
496
+ const body = res.body;
497
+ if (!body.ad) {
498
+ const reason = typeof body.reason === 'string' && body.reason ? body.reason : 'no_matching_ad';
499
+ if (reason === 'app_disabled')
500
+ this.appDisabled = true;
501
+ if (reason === 'sdk_unsupported')
502
+ this.sdkUnsupported = true;
503
+ return noFill(reason);
504
+ }
505
+ const ad = body.ad;
506
+ const m = ad.media;
507
+ 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');
510
+ }
511
+ if (!(0, click_1.isWebUrl)(ad.destination_url)) {
512
+ // Only web pages are opened: never tel:, intent:, javascript: or an app scheme.
513
+ if (!this.badDestinationLogged) {
514
+ this.badDestinationLogged = true;
515
+ this.log.error(`ad ${ad.id}: destination is not an http(s) URL, ad skipped`, body.request_id);
516
+ }
517
+ return noFill('invalid_response');
518
+ }
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');
523
+ const kind = m.kind === 'video' ? 'video' : 'image';
524
+ const poster = kind === 'video' && typeof m.poster_url === 'string' && m.poster_url ? m.poster_url : null;
525
+ const pf = this.config.prefetch;
526
+ // 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;
533
+ const label = typeof ad.cta_label === 'string' ? ad.cta_label.trim() : '';
534
+ const posInt = (v, d) => (typeof v === 'number' && v > 0 ? Math.round(v) : d);
535
+ // The ad's value wins over /config, kept within the same 8 to 15 s range.
536
+ const skipAfterMs = (_a = (0, config_1.clampSkipAfterMs)(ad.skip_after_ms)) !== null && _a !== void 0 ? _a : this.config.interstitial.skip_after_ms;
537
+ // The app's choice (options.audio) wins over the server's interstitial.audio.
538
+ const audio = (_b = this.audio) !== null && _b !== void 0 ? _b : this.config.interstitial.audio;
539
+ const build = (uris) => {
540
+ const uri = uris[mediaUrl] || mediaUrl;
541
+ const result = {
542
+ id: adId,
543
+ ctaLabel: label || 'Learn more',
544
+ destinationUrl,
545
+ skipAfterMs,
546
+ media: {
547
+ kind,
548
+ uri,
549
+ videoUri: kind === 'video' ? uri : null,
550
+ posterUri: poster ? uris[poster] || poster : null,
551
+ durationMs: kind === 'video' && typeof m.duration_ms === 'number' && m.duration_ms > 0 ? m.duration_ms : null,
552
+ mime: kind === 'video' ? (typeof m.mime === 'string' && m.mime ? m.mime : 'video/mp4') : null,
553
+ width: posInt(m.width, 720),
554
+ height: posInt(m.height, 1280),
555
+ cached: uri !== mediaUrl,
556
+ },
557
+ audio,
558
+ title: typeof ad.title === 'string' ? ad.title : null,
559
+ test: body.test === true,
560
+ servedAt,
561
+ expiresAt,
562
+ };
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 };
581
+ };
582
+ this.lastNoFillReason = null;
583
+ return { served: { build, download, expiresAt, consumed: false, result: null } };
584
+ }
585
+ }