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