@ethicly/react-native 0.0.0-stage → 0.2.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 (70) hide show
  1. package/CHANGELOG.md +75 -0
  2. package/LICENSE +21 -0
  3. package/README.md +313 -2
  4. package/core/package.json +6 -0
  5. package/interstitial/package.json +6 -0
  6. package/lib/commonjs/core/adapters.js +287 -0
  7. package/lib/commonjs/core/beacons.js +70 -0
  8. package/lib/commonjs/core/cache.js +206 -0
  9. package/lib/commonjs/core/click.js +19 -0
  10. package/lib/commonjs/core/client.js +489 -0
  11. package/lib/commonjs/core/config.js +113 -0
  12. package/lib/commonjs/core/http.js +115 -0
  13. package/lib/commonjs/core/index.js +20 -0
  14. package/lib/commonjs/core/outbox.js +192 -0
  15. package/lib/commonjs/core/tracker.js +374 -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 +286 -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 +276 -0
  23. package/lib/module/core/beacons.js +64 -0
  24. package/lib/module/core/cache.js +202 -0
  25. package/lib/module/core/click.js +15 -0
  26. package/lib/module/core/client.js +485 -0
  27. package/lib/module/core/config.js +104 -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 +370 -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 +260 -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 +138 -0
  39. package/lib/typescript/core/beacons.d.ts +32 -0
  40. package/lib/typescript/core/cache.d.ts +53 -0
  41. package/lib/typescript/core/click.d.ts +8 -0
  42. package/lib/typescript/core/client.d.ts +58 -0
  43. package/lib/typescript/core/config.d.ts +24 -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 +170 -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 +39 -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 +337 -0
  56. package/src/core/beacons.ts +81 -0
  57. package/src/core/cache.ts +216 -0
  58. package/src/core/click.ts +16 -0
  59. package/src/core/client.ts +547 -0
  60. package/src/core/config.ts +111 -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 +371 -0
  65. package/src/core/types.ts +180 -0
  66. package/src/index.ts +5 -0
  67. package/src/interstitial.ts +4 -0
  68. package/src/react/EthiclyInterstitial.tsx +386 -0
  69. package/src/react/useEthiclyInterstitial.ts +74 -0
  70. package/src/version.ts +2 -0
@@ -0,0 +1,489 @@
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 = void 0;
6
+ exports.createEthicly = createEthicly;
7
+ const adapters_1 = require("./adapters");
8
+ const cache_1 = require("./cache");
9
+ const config_1 = require("./config");
10
+ const http_1 = require("./http");
11
+ const outbox_1 = require("./outbox");
12
+ const tracker_1 = require("./tracker");
13
+ const version_1 = require("../version");
14
+ const CONFIG_TIMEOUT_MS = 5000;
15
+ const SERVE_TIMEOUT_MS = 8000;
16
+ const SIZE_PROBE_TIMEOUT_MS = 3000;
17
+ const CONFIG_RETRY_AFTER_FAILURE_MS = 30000;
18
+ const DEFAULT_TTL_S = 3600;
19
+ /**
20
+ * A new session (interstitial.max_per_session counts from zero again) starts
21
+ * when the app comes back after at least this long in the background.
22
+ */
23
+ exports.SESSION_TIMEOUT_MS = 30 * 60 * 1000;
24
+ let releaseTestModeLogged = false;
25
+ function createEthicly(options) {
26
+ return new EthiclyClient(options);
27
+ }
28
+ class EthiclyClient {
29
+ constructor(o) {
30
+ this.o = o;
31
+ this.sdkVersion = version_1.SDK_VERSION;
32
+ this.lastNoFillReason = null;
33
+ this.configSource = 'default';
34
+ this.configFetchedAt = 0;
35
+ this.configMaxAgeS = 300;
36
+ this.configRetryAt = 0;
37
+ this.configInflight = null;
38
+ /** 404 unknown_key with no stored config. */
39
+ this.unknownKey = false;
40
+ /** 400 or 403 on a key: integration bug, stop for this process. */
41
+ this.invalidKey = false;
42
+ /** app_disabled from serve: until a later /config says enabled. */
43
+ this.appDisabled = false;
44
+ /** sdk_unsupported: for the rest of the process lifetime. */
45
+ this.sdkUnsupported = false;
46
+ this.shownCount = 0;
47
+ this.lastShownAt = null;
48
+ this.frequencyLoaded = false;
49
+ /** When the app left the foreground, null while it is in it. */
50
+ this.backgroundSince = null;
51
+ this.preloaded = null;
52
+ this.serveInflight = null;
53
+ this.bundled = (0, config_1.cleanServeBase)(o.baseUrl) || config_1.BUNDLED_BASE_URL;
54
+ const f = o.fetch || globalThis.fetch;
55
+ if (!f)
56
+ throw new Error('[ethicly] no fetch available: pass options.fetch');
57
+ this.fetchFn = f;
58
+ this.now = o.now || Date.now;
59
+ this.log = (0, adapters_1.safeLogger)(o.logger);
60
+ this.storage = o.storage || (0, adapters_1.createMemoryStorage)();
61
+ this.gate = new http_1.RouteGate(this.now);
62
+ // The size probe only matters when files really land on disk.
63
+ 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);
64
+ this.config = (0, config_1.defaultConfig)(this.bundled);
65
+ this.adsOn = o.adsEnabled !== false;
66
+ this.testMode = !!o.testMode && !(0, adapters_1.isReleaseBuild)();
67
+ if (o.testMode && !this.testMode)
68
+ this.reportReleaseTestMode();
69
+ if (this.testMode)
70
+ this.log.warn('test mode is on: nothing is billed. Never ship a release build with testMode.');
71
+ this.outbox = (0, outbox_1.outboxFor)(this.storage, o.apiKey, this.log);
72
+ this.watchAppState(o.appState === undefined ? (0, adapters_1.defaultAppState)() : o.appState);
73
+ this.ready = this.init().catch((e) => this.log.error('init failed', e));
74
+ }
75
+ /** testMode in a release build would earn the publisher nothing: ignore it, loudly, once. */
76
+ reportReleaseTestMode() {
77
+ var _a, _b;
78
+ const msg = 'testMode is set in a release build: ignored, ads are served and billed normally. Set testMode: __DEV__.';
79
+ this.log.error(msg);
80
+ if (releaseTestModeLogged)
81
+ return;
82
+ releaseTestModeLogged = true;
83
+ try {
84
+ (_b = (_a = globalThis.console) === null || _a === void 0 ? void 0 : _a.error) === null || _b === void 0 ? void 0 : _b.call(_a, `[ethicly] ${msg}`);
85
+ }
86
+ catch { /* never throw */ }
87
+ }
88
+ /** Sessions: back in the foreground after SESSION_TIMEOUT_MS or more starts a new one. */
89
+ watchAppState(appState) {
90
+ if (!appState)
91
+ return;
92
+ const onChange = (state) => {
93
+ if (state === 'active') {
94
+ if (this.backgroundSince !== null && this.now() - this.backgroundSince >= exports.SESSION_TIMEOUT_MS) {
95
+ this.shownCount = 0;
96
+ this.log.debug('new session after time in the background');
97
+ }
98
+ this.backgroundSince = null;
99
+ }
100
+ else if (this.backgroundSince === null) {
101
+ this.backgroundSince = this.now();
102
+ }
103
+ };
104
+ try {
105
+ if (appState.currentState && appState.currentState !== 'active')
106
+ onChange(appState.currentState);
107
+ // Kept for the life of the client, which is the life of the process.
108
+ appState.addEventListener('change', (s) => { try {
109
+ onChange(s);
110
+ }
111
+ catch { /* never throw */ } });
112
+ }
113
+ catch (e) {
114
+ this.log.warn('could not watch AppState: one session per process', e);
115
+ }
116
+ }
117
+ /** Content-Length from a HEAD request, so an oversized creative is never written. */
118
+ async contentLength(url) {
119
+ let timer;
120
+ try {
121
+ const timeout = new Promise((resolve) => { timer = setTimeout(() => resolve(null), SIZE_PROBE_TIMEOUT_MS); });
122
+ const res = await Promise.race([this.fetchFn(url, { method: 'HEAD' }), timeout]);
123
+ if (!res)
124
+ return null;
125
+ const n = Number(res.headers.get('content-length'));
126
+ return res.status >= 200 && res.status < 300 && Number.isFinite(n) && n > 0 ? n : null;
127
+ }
128
+ catch {
129
+ return null;
130
+ }
131
+ finally {
132
+ if (timer)
133
+ clearTimeout(timer);
134
+ }
135
+ }
136
+ // ------------------------------------------------------------- headers
137
+ headers() {
138
+ return { 'X-Ethicly-SDK': `${this.o.platform}/${version_1.SDK_VERSION}` };
139
+ }
140
+ serveBase() {
141
+ return this.configSource === 'default' ? this.bundled : this.config.endpoints.serve;
142
+ }
143
+ beaconCtx() {
144
+ return {
145
+ fetch: this.fetchFn,
146
+ serveBase: () => this.serveBase(),
147
+ headers: () => this.headers(),
148
+ gate: this.gate,
149
+ now: this.now,
150
+ log: this.log,
151
+ };
152
+ }
153
+ // ------------------------------------------------------------- config
154
+ get storageKey() {
155
+ return `ethicly:v1:config:${this.o.apiKey}`;
156
+ }
157
+ get frequencyKey() {
158
+ return `ethicly:v1:frequency:${this.o.apiKey}`;
159
+ }
160
+ /** The last shown time survives restarts, so min_gap_s does too. Never rejects. */
161
+ async loadFrequency() {
162
+ var _a;
163
+ try {
164
+ const raw = await this.storage.getItem(this.frequencyKey);
165
+ const t = raw ? JSON.parse(raw).lastShownAt : null;
166
+ // A time in the future (the clock moved back) is ignored.
167
+ if (typeof t === 'number' && Number.isFinite(t) && t <= this.now()) {
168
+ this.lastShownAt = Math.max((_a = this.lastShownAt) !== null && _a !== void 0 ? _a : 0, t);
169
+ }
170
+ }
171
+ catch (e) {
172
+ this.log.warn('stored frequency state unreadable', e);
173
+ }
174
+ finally {
175
+ this.frequencyLoaded = true;
176
+ }
177
+ }
178
+ async init() {
179
+ await Promise.all([this.loadFrequency(), this.outbox.load()]);
180
+ try {
181
+ const raw = await this.storage.getItem(this.storageKey);
182
+ if (raw) {
183
+ const s = JSON.parse(raw);
184
+ const parsed = (0, config_1.parseConfig)(s.config, this.bundled);
185
+ if (parsed) {
186
+ this.config = parsed;
187
+ this.configSource = 'stored';
188
+ this.configFetchedAt = s.fetchedAt;
189
+ this.configMaxAgeS = s.maxAgeS;
190
+ }
191
+ }
192
+ }
193
+ catch (e) {
194
+ this.log.warn('stored config unreadable', e);
195
+ }
196
+ this.applyConfigGates();
197
+ if (this.configStale())
198
+ await this.refreshConfig();
199
+ void this.replayOutbox();
200
+ }
201
+ /**
202
+ * Send what a previous run left unsent, one ad at a time. Not while a kill
203
+ * switch is on (app_disabled, sdk_unsupported) or the key is refused: the
204
+ * records then stay stored and expire one hour after their ad was shown.
205
+ * Never rejects.
206
+ */
207
+ async replayOutbox() {
208
+ const blocked = this.blockedReason();
209
+ if (blocked && blocked !== 'interstitial_disabled') {
210
+ this.log.info(`unsent beacons from the last run held back: ${blocked}`);
211
+ return;
212
+ }
213
+ const orphans = this.outbox.claimOrphans(this.now());
214
+ if (orphans.length)
215
+ this.log.info(`sending ${orphans.length} unsent beacon set(s) from the last run`);
216
+ for (const rec of orphans)
217
+ await (0, outbox_1.replayRecord)(this.beaconCtx(), this.outbox, rec);
218
+ }
219
+ configStale() {
220
+ return this.configSource !== 'network' && this.configSource !== 'stored'
221
+ ? true
222
+ : this.now() - this.configFetchedAt >= this.configMaxAgeS * 1000;
223
+ }
224
+ applyConfigGates() {
225
+ if (this.configSource === 'default')
226
+ return;
227
+ if (this.config.enabled)
228
+ this.appDisabled = false;
229
+ const min = this.o.platform === 'ios' ? this.config.min_sdk.ios : this.config.min_sdk.android;
230
+ if ((0, config_1.isBelowMinSdk)(version_1.SDK_VERSION, min)) {
231
+ if (!this.sdkUnsupported)
232
+ this.log.error(`SDK ${version_1.SDK_VERSION} is below min_sdk ${min}: no ads until the app updates`);
233
+ this.sdkUnsupported = true;
234
+ }
235
+ }
236
+ getConfig() {
237
+ return this.config;
238
+ }
239
+ refreshConfig() {
240
+ if (this.invalidKey || this.now() < this.configRetryAt)
241
+ return Promise.resolve();
242
+ if (!this.configInflight) {
243
+ this.configInflight = this.fetchConfig().catch((e) => this.log.error('config fetch failed', e))
244
+ .finally(() => { this.configInflight = null; });
245
+ }
246
+ return this.configInflight;
247
+ }
248
+ async fetchConfig() {
249
+ var _a;
250
+ const url = `${this.bundled}/config?key=${encodeURIComponent(this.o.apiKey)}&platform=${this.o.platform}`;
251
+ const res = await (0, http_1.httpRequest)(this.fetchFn, url, { headers: this.headers(), timeoutMs: CONFIG_TIMEOUT_MS });
252
+ if (res.status === 200) {
253
+ const parsed = (0, config_1.parseConfig)(res.body, this.bundled);
254
+ if (parsed) {
255
+ this.config = parsed;
256
+ this.configSource = 'network';
257
+ this.configFetchedAt = this.now();
258
+ this.configMaxAgeS = (0, config_1.maxAgeSeconds)(res.cacheControl);
259
+ this.unknownKey = false;
260
+ this.applyConfigGates();
261
+ const stored = { config: parsed, fetchedAt: this.configFetchedAt, maxAgeS: this.configMaxAgeS };
262
+ await this.storage.setItem(this.storageKey, JSON.stringify(stored)).catch(() => undefined);
263
+ return;
264
+ }
265
+ this.log.warn('config body unreadable, keeping the last known config');
266
+ this.configRetryAt = this.now() + CONFIG_RETRY_AFTER_FAILURE_MS;
267
+ return;
268
+ }
269
+ if (res.status === 429) {
270
+ this.configRetryAt = this.now() + Math.max(1, (_a = res.retryAfterS) !== null && _a !== void 0 ? _a : 1) * 1000;
271
+ this.log.warn('config rate limited, keeping the last known config');
272
+ return;
273
+ }
274
+ if (res.status === 404) {
275
+ // Kept for this session; with nothing stored there is no ad.
276
+ if (this.configSource === 'default')
277
+ this.unknownKey = true;
278
+ this.configRetryAt = this.now() + this.configMaxAgeS * 1000;
279
+ this.log.warn('config 404 unknown_key (unknown or not approved site)');
280
+ return;
281
+ }
282
+ if (res.status === 400) {
283
+ this.invalidKey = true;
284
+ this.log.error('config 400: the API key is missing or not a UUID. Not retried.');
285
+ return;
286
+ }
287
+ // 5xx, timeout, network error: keep the last known config, retry later.
288
+ this.configRetryAt = this.now() + CONFIG_RETRY_AFTER_FAILURE_MS;
289
+ this.log.warn(`config fetch failed (${res.status || 'network'}), keeping the last known config`);
290
+ }
291
+ // ------------------------------------------------------------- frequency
292
+ canShow() {
293
+ const it = this.config.interstitial;
294
+ if (!this.adsOn || !this.frequencyLoaded || this.blockedReason())
295
+ return false;
296
+ if (this.shownCount >= it.max_per_session)
297
+ return false;
298
+ if (this.lastShownAt !== null && this.now() - this.lastShownAt < it.min_gap_s * 1000)
299
+ return false;
300
+ return true;
301
+ }
302
+ onShown() {
303
+ this.shownCount += 1;
304
+ this.lastShownAt = this.now();
305
+ const stored = { lastShownAt: this.lastShownAt };
306
+ try {
307
+ this.storage.setItem(this.frequencyKey, JSON.stringify(stored)).catch(() => undefined);
308
+ }
309
+ catch { /* a storage that throws synchronously must not reach the host */ }
310
+ }
311
+ setAdsEnabled(enabled) {
312
+ this.adsOn = !!enabled;
313
+ if (!this.adsOn)
314
+ this.preloaded = null;
315
+ }
316
+ isAdsEnabled() {
317
+ return this.adsOn;
318
+ }
319
+ // ------------------------------------------------------------- serve
320
+ blockedReason() {
321
+ if (this.invalidKey)
322
+ return 'invalid_key';
323
+ if (this.unknownKey)
324
+ return 'unknown_key';
325
+ if (this.sdkUnsupported)
326
+ return 'sdk_unsupported';
327
+ if (this.appDisabled || (this.configSource !== 'default' && !this.config.enabled))
328
+ return 'app_disabled';
329
+ if (this.configSource !== 'default' && this.config.formats.indexOf('interstitial') === -1)
330
+ return 'interstitial_disabled';
331
+ return null;
332
+ }
333
+ noFill(reason) {
334
+ this.lastNoFillReason = reason;
335
+ this.log.info(`no ad: ${reason}`);
336
+ return { ad: null, tracker: null, reason };
337
+ }
338
+ async preload() {
339
+ try {
340
+ if (!this.adsOn)
341
+ return this.noFill('ads_disabled');
342
+ if (this.preloaded && !this.preloaded.result.tracker.isExpired())
343
+ return this.preloaded.result;
344
+ this.preloaded = null;
345
+ if (this.shownCount >= this.config.interstitial.max_per_session)
346
+ return this.noFill('frequency_capped');
347
+ if (!this.serveInflight) {
348
+ this.serveInflight = this.serve().finally(() => { this.serveInflight = null; });
349
+ }
350
+ const r = await this.serveInflight;
351
+ if (r.ad && this.adsOn)
352
+ this.preloaded = { result: r };
353
+ return r.ad && !this.adsOn ? this.noFill('ads_disabled') : r;
354
+ }
355
+ catch (e) {
356
+ this.log.error('preload failed', e);
357
+ return this.noFill('network_error');
358
+ }
359
+ }
360
+ async loadInterstitial() {
361
+ try {
362
+ await this.ready;
363
+ if (!this.adsOn)
364
+ return this.noFill('ads_disabled');
365
+ if (this.configStale())
366
+ await this.refreshConfig();
367
+ const blocked = this.blockedReason();
368
+ if (blocked)
369
+ return this.noFill(blocked);
370
+ if (!this.canShow())
371
+ return this.noFill('frequency_capped');
372
+ const r = await this.preload();
373
+ this.preloaded = null;
374
+ return r;
375
+ }
376
+ catch (e) {
377
+ this.log.error('loadInterstitial failed', e);
378
+ return this.noFill('network_error');
379
+ }
380
+ }
381
+ async serve() {
382
+ await this.ready;
383
+ if (this.configStale())
384
+ await this.refreshConfig();
385
+ const blocked = this.blockedReason();
386
+ if (blocked)
387
+ return this.noFill(blocked);
388
+ if (this.gate.waitMs('serve') > 0)
389
+ return this.noFill('rate_limited');
390
+ const q = [
391
+ `key=${encodeURIComponent(this.o.apiKey)}`,
392
+ 'format=interstitial',
393
+ `platform=${this.o.platform}`,
394
+ `sdk_version=${encodeURIComponent(version_1.SDK_VERSION)}`,
395
+ `app_version=${encodeURIComponent(this.o.appVersion)}`,
396
+ ];
397
+ if (this.testMode)
398
+ q.push('test=1');
399
+ const res = await (0, http_1.httpRequest)(this.fetchFn, `${this.serveBase()}?${q.join('&')}`, {
400
+ headers: this.headers(), timeoutMs: SERVE_TIMEOUT_MS,
401
+ });
402
+ const servedAt = this.now();
403
+ if (res.status === 429) {
404
+ this.gate.block('serve', res.retryAfterS);
405
+ return this.noFill('rate_limited');
406
+ }
407
+ if (res.status === 400 || res.status === 403) {
408
+ this.invalidKey = true;
409
+ this.log.error(`serve ${res.status}: invalid publisher key. Not retried.`, res.body);
410
+ return this.noFill('invalid_key');
411
+ }
412
+ if (res.status === 0)
413
+ return this.noFill('network_error');
414
+ if (res.status !== 200 || !res.body || typeof res.body !== 'object')
415
+ return this.noFill('server_error');
416
+ const body = res.body;
417
+ if (!body.ad) {
418
+ const reason = typeof body.reason === 'string' && body.reason ? body.reason : 'no_matching_ad';
419
+ if (reason === 'app_disabled')
420
+ this.appDisabled = true;
421
+ if (reason === 'sdk_unsupported')
422
+ this.sdkUnsupported = true;
423
+ return this.noFill(reason);
424
+ }
425
+ const ad = body.ad;
426
+ const m = ad.media;
427
+ if (typeof ad.id !== 'number' || !m || typeof m.url !== 'string' || !m.url || typeof ad.destination_url !== 'string') {
428
+ this.log.warn('serve answered an ad without media or destination', body.request_id);
429
+ return this.noFill('invalid_response');
430
+ }
431
+ if (body.test === true)
432
+ this.log.info(`test serve: ad ${ad.id} on site ${body.publisher_site_id}`);
433
+ if (!this.adsOn)
434
+ return this.noFill('ads_disabled');
435
+ const kind = m.kind === 'video' ? 'video' : 'image';
436
+ const poster = kind === 'video' && typeof m.poster_url === 'string' && m.poster_url ? m.poster_url : null;
437
+ const pf = this.config.prefetch;
438
+ const cached = await 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: {} }));
439
+ if (!this.adsOn)
440
+ return this.noFill('ads_disabled');
441
+ const uri = cached.uris[m.url] || m.url;
442
+ const ttlS = typeof body.token_ttl_s === 'number' && body.token_ttl_s > 0 ? body.token_ttl_s : DEFAULT_TTL_S;
443
+ const label = typeof ad.cta_label === 'string' ? ad.cta_label.trim() : '';
444
+ const posInt = (v, d) => (typeof v === 'number' && v > 0 ? Math.round(v) : d);
445
+ const result = {
446
+ id: ad.id,
447
+ ctaLabel: label || 'Learn more',
448
+ destinationUrl: ad.destination_url,
449
+ skipAfterMs: typeof ad.skip_after_ms === 'number' && ad.skip_after_ms >= 0
450
+ ? ad.skip_after_ms
451
+ : this.config.interstitial.skip_after_ms,
452
+ media: {
453
+ kind,
454
+ uri,
455
+ videoUri: kind === 'video' ? uri : null,
456
+ posterUri: poster ? cached.uris[poster] || poster : null,
457
+ durationMs: kind === 'video' && typeof m.duration_ms === 'number' && m.duration_ms > 0 ? m.duration_ms : null,
458
+ mime: kind === 'video' ? (typeof m.mime === 'string' && m.mime ? m.mime : 'video/mp4') : null,
459
+ width: posInt(m.width, 720),
460
+ height: posInt(m.height, 1280),
461
+ cached: uri !== m.url,
462
+ },
463
+ audio: this.config.interstitial.audio,
464
+ title: typeof ad.title === 'string' ? ad.title : null,
465
+ test: body.test === true,
466
+ servedAt,
467
+ expiresAt: servedAt + ttlS * 1000,
468
+ };
469
+ const tracker = new tracker_1.InterstitialTracker({
470
+ ctx: this.beaconCtx(),
471
+ ad: result,
472
+ serve: {
473
+ publisherSiteId: typeof body.publisher_site_id === 'number' && body.publisher_site_id > 0 ? body.publisher_site_id : null,
474
+ countryCode: typeof body.country_code === 'string' ? body.country_code : null,
475
+ impressionToken: typeof body.impression_token === 'string' ? body.impression_token : null,
476
+ },
477
+ viewableAfterMs: this.config.beacon.viewable_after_ms,
478
+ flushIntervalS: this.config.beacon.flush_interval_s,
479
+ platform: this.o.platform,
480
+ sdkVersion: version_1.SDK_VERSION,
481
+ appVersion: this.o.appVersion,
482
+ openUrl: this.o.openUrl,
483
+ onShown: () => this.onShown(),
484
+ outbox: this.outbox,
485
+ });
486
+ this.lastNoFillReason = null;
487
+ return { ad: result, tracker };
488
+ }
489
+ }
@@ -0,0 +1,113 @@
1
+ "use strict";
2
+ // /config parsing, defaults and version comparison (doc "GET /config",
3
+ // "Versioning").
4
+ Object.defineProperty(exports, "__esModule", { value: true });
5
+ exports.DEFAULT_MAX_AGE_S = exports.BUNDLED_BASE_URL = void 0;
6
+ exports.defaultConfig = defaultConfig;
7
+ exports.cleanServeBase = cleanServeBase;
8
+ exports.parseConfig = parseConfig;
9
+ exports.maxAgeSeconds = maxAgeSeconds;
10
+ exports.compareVersions = compareVersions;
11
+ exports.isBelowMinSdk = isBelowMinSdk;
12
+ exports.BUNDLED_BASE_URL = 'https://ads.ethicly.ch/functions/v1/get-ad-with-geo';
13
+ exports.DEFAULT_MAX_AGE_S = 300;
14
+ /** The defaults shown in the doc. Used when no config was ever fetched. */
15
+ function defaultConfig(serveBase) {
16
+ return {
17
+ enabled: true,
18
+ min_sdk: { ios: '0.0.0', android: '0.0.0' },
19
+ formats: ['interstitial', '300x250'],
20
+ interstitial: { skip_after_ms: 8000, max_per_session: 3, min_gap_s: 120, audio: 'on' },
21
+ prefetch: { max_cached_creatives: 3, max_cache_mb: 20 },
22
+ beacon: { viewable_after_ms: 2000, flush_interval_s: 30 },
23
+ endpoints: { serve: serveBase },
24
+ };
25
+ }
26
+ function obj(v) {
27
+ return v && typeof v === 'object' && !Array.isArray(v) ? v : {};
28
+ }
29
+ function num(v, fallback, min, max) {
30
+ return typeof v === 'number' && Number.isFinite(v) ? Math.min(max, Math.max(min, v)) : fallback;
31
+ }
32
+ function str(v, fallback) {
33
+ return typeof v === 'string' && v.trim() ? v.trim() : fallback;
34
+ }
35
+ /** An https URL, without a trailing slash, or null. */
36
+ function cleanServeBase(v) {
37
+ if (typeof v !== 'string')
38
+ return null;
39
+ const s = v.trim().replace(/\/+$/, '');
40
+ return /^https:\/\/[^/\s]+\/\S*$/.test(s) ? s : null;
41
+ }
42
+ /**
43
+ * Read a /config body leniently: every field is validated and falls back to
44
+ * the default, unknown fields are ignored. Returns null when the body is not a
45
+ * config at all.
46
+ */
47
+ function parseConfig(body, bundledBase) {
48
+ const b = obj(body);
49
+ if (typeof b.enabled !== 'boolean')
50
+ return null;
51
+ const d = defaultConfig(bundledBase);
52
+ const ms = obj(b.min_sdk);
53
+ const it = obj(b.interstitial);
54
+ const pf = obj(b.prefetch);
55
+ const bc = obj(b.beacon);
56
+ // Sound on is the default; 'none' (always muted) and 'optional' (start muted)
57
+ // are the publisher's explicit choices.
58
+ const audio = it.audio === 'none' || it.audio === 'optional' ? it.audio : 'on';
59
+ return {
60
+ enabled: b.enabled,
61
+ min_sdk: { ios: str(ms.ios, '0.0.0'), android: str(ms.android, '0.0.0') },
62
+ formats: Array.isArray(b.formats) ? b.formats.filter((f) => typeof f === 'string') : d.formats,
63
+ interstitial: {
64
+ skip_after_ms: num(it.skip_after_ms, d.interstitial.skip_after_ms, 0, 15000),
65
+ max_per_session: num(it.max_per_session, d.interstitial.max_per_session, 0, 1000),
66
+ min_gap_s: num(it.min_gap_s, d.interstitial.min_gap_s, 0, 86400),
67
+ audio,
68
+ },
69
+ prefetch: {
70
+ max_cached_creatives: num(pf.max_cached_creatives, d.prefetch.max_cached_creatives, 0, 100),
71
+ max_cache_mb: num(pf.max_cache_mb, d.prefetch.max_cache_mb, 0, 10000),
72
+ },
73
+ beacon: {
74
+ viewable_after_ms: num(bc.viewable_after_ms, d.beacon.viewable_after_ms, 0, 60000),
75
+ flush_interval_s: num(bc.flush_interval_s, d.beacon.flush_interval_s, 1, 3600),
76
+ },
77
+ endpoints: { serve: cleanServeBase(obj(b.endpoints).serve) || bundledBase },
78
+ };
79
+ }
80
+ /** max-age from Cache-Control, default 300 s. */
81
+ function maxAgeSeconds(cacheControl) {
82
+ const m = cacheControl ? /max-age=(\d+)/i.exec(cacheControl) : null;
83
+ return m ? Number(m[1]) : exports.DEFAULT_MAX_AGE_S;
84
+ }
85
+ /**
86
+ * Doc "Versioning > Comparison": leading dot-separated numeric components,
87
+ * everything from the first other character ignored. -1, 0, 1, or null when
88
+ * either side has no leading number. Mirrors compareVersions in the server's
89
+ * appConfig.ts.
90
+ */
91
+ function compareVersions(a, b) {
92
+ const parse = (v) => {
93
+ if (typeof v !== 'string')
94
+ return null;
95
+ const m = /^\d+(\.\d+)*/.exec(v.trim());
96
+ return m ? m[0].split('.').map(Number) : null;
97
+ };
98
+ const pa = parse(a);
99
+ const pb = parse(b);
100
+ if (!pa || !pb)
101
+ return null;
102
+ for (let i = 0; i < Math.max(pa.length, pb.length); i++) {
103
+ const d = (pa[i] || 0) - (pb[i] || 0);
104
+ if (d !== 0)
105
+ return d < 0 ? -1 : 1;
106
+ }
107
+ return 0;
108
+ }
109
+ /** True only when `sdk` parses and is below `min`. */
110
+ function isBelowMinSdk(sdk, min) {
111
+ const c = compareVersions(sdk, min);
112
+ return c !== null && c < 0;
113
+ }