@ethicly/react-native 0.2.0 → 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 (42) hide show
  1. package/CHANGELOG.md +59 -1
  2. package/README.md +168 -53
  3. package/lib/commonjs/core/adapters.js +44 -5
  4. package/lib/commonjs/core/cache.js +60 -5
  5. package/lib/commonjs/core/click.js +10 -0
  6. package/lib/commonjs/core/client.js +160 -64
  7. package/lib/commonjs/core/config.js +17 -2
  8. package/lib/commonjs/core/index.js +2 -1
  9. package/lib/commonjs/core/tracker.js +5 -0
  10. package/lib/commonjs/react/EthiclyInterstitial.js +46 -13
  11. package/lib/commonjs/version.js +1 -1
  12. package/lib/module/core/adapters.js +44 -5
  13. package/lib/module/core/cache.js +59 -4
  14. package/lib/module/core/click.js +9 -0
  15. package/lib/module/core/client.js +160 -64
  16. package/lib/module/core/config.js +15 -1
  17. package/lib/module/core/index.js +1 -1
  18. package/lib/module/core/tracker.js +6 -1
  19. package/lib/module/react/EthiclyInterstitial.js +45 -13
  20. package/lib/module/version.js +1 -1
  21. package/lib/typescript/core/adapters.d.ts +2 -1
  22. package/lib/typescript/core/cache.d.ts +20 -2
  23. package/lib/typescript/core/click.d.ts +5 -0
  24. package/lib/typescript/core/client.d.ts +23 -3
  25. package/lib/typescript/core/config.d.ts +9 -0
  26. package/lib/typescript/core/index.d.ts +1 -1
  27. package/lib/typescript/core/types.d.ts +5 -0
  28. package/lib/typescript/react/EthiclyInterstitial.d.ts +13 -1
  29. package/lib/typescript/react/useEthiclyInterstitial.d.ts +1 -1
  30. package/lib/typescript/version.d.ts +1 -1
  31. package/package.json +2 -2
  32. package/src/core/adapters.ts +33 -5
  33. package/src/core/cache.ts +48 -3
  34. package/src/core/click.ts +10 -0
  35. package/src/core/client.ts +186 -68
  36. package/src/core/config.ts +14 -1
  37. package/src/core/index.ts +1 -1
  38. package/src/core/tracker.ts +6 -1
  39. package/src/core/types.ts +5 -0
  40. package/src/react/EthiclyInterstitial.tsx +62 -16
  41. package/src/react/useEthiclyInterstitial.ts +1 -1
  42. package/src/version.ts +1 -1
@@ -62,7 +62,8 @@ function isLegacyFs(fs) {
62
62
  * A file cache over either expo-file-system API: the object API of SDK 54+
63
63
  * (`File`, `Directory`, `Paths`), else the legacy functions (`getInfoAsync`,
64
64
  * `downloadAsync`, ...). Anything else gets the streaming cache, which writes
65
- * nothing to disk, and one warning through `logger` (default `console`).
65
+ * nothing to disk, and one warning through `logger` (default `console` in
66
+ * development, nothing in a release build).
66
67
  */
67
68
  export function createExpoFileCache(fs, subdirectory = DEFAULT_CACHE_SUBDIRECTORY, logger) {
68
69
  const sub = safeCacheSubdirectory(subdirectory);
@@ -70,7 +71,8 @@ export function createExpoFileCache(fs, subdirectory = DEFAULT_CACHE_SUBDIRECTOR
70
71
  return modernFileCache(fs, sub);
71
72
  if (isLegacyFs(fs))
72
73
  return legacyFileCache(fs, sub);
73
- safeLogger(logger || consoleLogger()).warn('createExpoFileCache: not an expo-file-system module (no File/Directory/Paths, no cacheDirectory); creatives will stream');
74
+ // console only in development: a release build stays quiet unless the app passes a logger.
75
+ safeLogger(logger || (isReleaseBuild() ? undefined : consoleLogger())).warn('createExpoFileCache: not an expo-file-system module (no File/Directory/Paths, no cacheDirectory); creatives will stream');
74
76
  return createMemoryFileCache();
75
77
  }
76
78
  function consoleLogger() {
@@ -80,6 +82,8 @@ function consoleLogger() {
80
82
  function legacyFileCache(fs, sub) {
81
83
  const dir = `${fs.cacheDirectory}${sub}`;
82
84
  let made = null;
85
+ /** Cancels for the downloads in flight (only resumable downloads can be cancelled). */
86
+ const inflight = new Set();
83
87
  const sizeOf = async (uri) => {
84
88
  const info = await fs.getInfoAsync(uri, { size: true });
85
89
  return info.exists && typeof info.size === 'number' ? info.size : 0;
@@ -95,15 +99,22 @@ function legacyFileCache(fs, sub) {
95
99
  let tooBig = false;
96
100
  if (max !== undefined && fs.createDownloadResumable) {
97
101
  // Stop as soon as the server announces, or we have written, more than the budget.
102
+ const stop = () => { void (dl.cancelAsync ? dl.cancelAsync() : dl.pauseAsync()).catch(() => undefined); };
98
103
  const dl = fs.createDownloadResumable(url, target, {}, (p) => {
99
104
  if (tooBig)
100
105
  return;
101
106
  if (p.totalBytesExpectedToWrite > max || p.totalBytesWritten > max) {
102
107
  tooBig = true;
103
- void (dl.cancelAsync ? dl.cancelAsync() : dl.pauseAsync()).catch(() => undefined);
108
+ stop();
104
109
  }
105
110
  });
106
- res = await dl.downloadAsync().catch(() => undefined);
111
+ inflight.add(stop);
112
+ try {
113
+ res = await dl.downloadAsync().catch(() => undefined);
114
+ }
115
+ finally {
116
+ inflight.delete(stop);
117
+ }
107
118
  }
108
119
  else {
109
120
  res = await fs.downloadAsync(url, target);
@@ -118,6 +129,12 @@ function legacyFileCache(fs, sub) {
118
129
  async delete(uri) { await fs.deleteAsync(uri, { idempotent: true }); },
119
130
  size: sizeOf,
120
131
  uriFor: (fileName) => dir + fileName,
132
+ cancel() {
133
+ inflight.forEach((stop) => { try {
134
+ stop();
135
+ }
136
+ catch { /* already settled */ } });
137
+ },
121
138
  async list() {
122
139
  if (!fs.readDirectoryAsync)
123
140
  return [];
@@ -152,6 +169,7 @@ function modernFileCache(fs, sub) {
152
169
  return f.exists && typeof f.size === 'number' && f.size > 0 ? f.size : 0;
153
170
  };
154
171
  let made = false;
172
+ const inflight = new Set();
155
173
  return {
156
174
  async download(url, fileName, opts) {
157
175
  if (!made) {
@@ -163,6 +181,7 @@ function modernFileCache(fs, sub) {
163
181
  const target = dir() + fileName;
164
182
  const max = opts === null || opts === void 0 ? void 0 : opts.maxBytes;
165
183
  let tooBig = false;
184
+ let cancelled = false;
166
185
  try {
167
186
  remove(target);
168
187
  const createTask = fs.File.createDownloadTask;
@@ -179,7 +198,14 @@ function modernFileCache(fs, sub) {
179
198
  catch { /* already settled */ }
180
199
  },
181
200
  });
182
- await task.downloadAsync();
201
+ const handle = { cancel: () => { cancelled = true; task.cancel(); } };
202
+ inflight.add(handle);
203
+ try {
204
+ await task.downloadAsync();
205
+ }
206
+ finally {
207
+ inflight.delete(handle);
208
+ }
183
209
  }
184
210
  else {
185
211
  await fs.File.downloadFileAsync(url, file(target), { idempotent: true });
@@ -195,6 +221,13 @@ function modernFileCache(fs, sub) {
195
221
  // Without a progress callback the whole file lands first: check it now
196
222
  // and delete it if it is over the budget.
197
223
  const bytes = await sizeOf(target);
224
+ if (cancelled) {
225
+ try {
226
+ remove(target);
227
+ }
228
+ catch { /* ignore */ }
229
+ throw new Error('download cancelled');
230
+ }
198
231
  if (tooBig || (max !== undefined && bytes > max)) {
199
232
  try {
200
233
  remove(target);
@@ -208,6 +241,12 @@ function modernFileCache(fs, sub) {
208
241
  async delete(uri) { remove(uri); },
209
242
  size: sizeOf,
210
243
  uriFor: (fileName) => dir() + fileName,
244
+ cancel() {
245
+ inflight.forEach((t) => { try {
246
+ t.cancel();
247
+ }
248
+ catch { /* already settled */ } });
249
+ },
211
250
  async list() {
212
251
  const d = new fs.Directory(dir());
213
252
  if (!d.exists)
@@ -10,6 +10,13 @@
10
10
  // and is written again as soon as the download lands;
11
11
  // - on first use every pending file, and every file in the SDK's cache
12
12
  // directory that the index does not list, is deleted.
13
+ /**
14
+ * The longest one creative file may take to download. A slower (trickling)
15
+ * download is cancelled when the adapter supports it, else abandoned: the
16
+ * creative streams and later downloads are not held up behind it. A file it
17
+ * still writes afterwards is not indexed, so the next launch's sweep deletes it.
18
+ */
19
+ export const DOWNLOAD_TIMEOUT_MS = 60000;
13
20
  function hash(s) {
14
21
  let h = 5381;
15
22
  for (let i = 0; i < s.length; i++)
@@ -24,18 +31,59 @@ function baseName(uri) {
24
31
  return uri.replace(/[?#].*$/, '').split('/').pop() || uri;
25
32
  }
26
33
  export class CreativeCache {
27
- constructor(files, storage, storageKey, now, log, probeSize = async () => null) {
34
+ constructor(files, storage, storageKey, now, log, probeSize = async () => null, downloadTimeoutMs = DOWNLOAD_TIMEOUT_MS) {
28
35
  this.files = files;
29
36
  this.storage = storage;
30
37
  this.storageKey = storageKey;
31
38
  this.now = now;
32
39
  this.log = log;
33
40
  this.probeSize = probeSize;
41
+ this.downloadTimeoutMs = downloadTimeoutMs;
34
42
  this.entries = [];
35
43
  /** File names whose download has started but not landed. */
36
44
  this.pending = [];
37
45
  this.loaded = null;
38
46
  this.chain = Promise.resolve();
47
+ /** Bumped by cancel(): a download started before it no longer counts. */
48
+ this.generation = 0;
49
+ }
50
+ /**
51
+ * Stop the download in flight, when the adapter can (FileCacheAdapter.cancel),
52
+ * and skip the files not started yet. For setAdsEnabled(false).
53
+ */
54
+ cancel() {
55
+ var _a, _b;
56
+ this.generation += 1;
57
+ try {
58
+ (_b = (_a = this.files).cancel) === null || _b === void 0 ? void 0 : _b.call(_a);
59
+ }
60
+ catch (e) {
61
+ this.log.warn('could not cancel the creative download', e);
62
+ }
63
+ }
64
+ /** The adapter's download, given up on after downloadTimeoutMs. */
65
+ async downloadWithin(url, name, maxBytes) {
66
+ let timer;
67
+ const timeout = new Promise((_, reject) => {
68
+ timer = setTimeout(() => {
69
+ var _a, _b;
70
+ try {
71
+ (_b = (_a = this.files).cancel) === null || _b === void 0 ? void 0 : _b.call(_a);
72
+ }
73
+ catch { /* best effort */ }
74
+ reject(new Error(`download took longer than ${this.downloadTimeoutMs} ms`));
75
+ }, this.downloadTimeoutMs);
76
+ });
77
+ const dl = this.files.download(url, name, { maxBytes });
78
+ // A late rejection of an abandoned download must not go unhandled.
79
+ dl.catch(() => undefined);
80
+ try {
81
+ return await Promise.race([dl, timeout]);
82
+ }
83
+ finally {
84
+ if (timer)
85
+ clearTimeout(timer);
86
+ }
39
87
  }
40
88
  load() {
41
89
  if (!this.loaded)
@@ -108,7 +156,8 @@ export class CreativeCache {
108
156
  * Make sure the files of one creative are on disk. Never throws: a file that
109
157
  * cannot be cached is simply left out of the result and streamed instead.
110
158
  * `allowed()` is checked before every download so setAdsEnabled(false)
111
- * stops a download that has not started yet.
159
+ * stops a download that has not started yet; cancel() also stops the one in
160
+ * flight when the adapter supports it.
112
161
  */
113
162
  ensure(adId, urls, limits, allowed) {
114
163
  const run = this.chain.then(() => this.ensureNow(adId, urls, limits, allowed));
@@ -130,10 +179,12 @@ export class CreativeCache {
130
179
  this.entries.push(entry);
131
180
  }
132
181
  entry.lastUsed = this.now();
182
+ const generation = this.generation;
183
+ const go = () => allowed() && generation === this.generation;
133
184
  for (const url of urls) {
134
185
  if (entry.files.some((f) => f.url === url))
135
186
  continue;
136
- if (!allowed())
187
+ if (!go())
137
188
  break;
138
189
  // One creative may use the whole budget (older ones are evicted), never more.
139
190
  const budget = limits.maxBytes - this.size(entry);
@@ -149,12 +200,16 @@ export class CreativeCache {
149
200
  this.pending = [name];
150
201
  await this.persist();
151
202
  try {
152
- const res = await this.files.download(url, name, { maxBytes: budget });
203
+ const res = await this.downloadWithin(url, name, budget);
153
204
  const bytes = typeof res.bytes === 'number' && res.bytes > 0 ? res.bytes : await this.files.size(res.uri).catch(() => 0);
154
205
  if (bytes > budget) {
155
206
  await this.files.delete(res.uri).catch(() => undefined);
156
207
  this.log.info(`${url} is over the cache budget: it will stream`);
157
208
  }
209
+ else if (!go()) {
210
+ // Cancelled while it was landing: keep nothing for a paid user.
211
+ await this.files.delete(res.uri).catch(() => undefined);
212
+ }
158
213
  else {
159
214
  entry.files.push({ url, uri: res.uri, bytes });
160
215
  }
@@ -13,3 +13,12 @@ export function appendClickToken(destinationUrl, clickToken) {
13
13
  }
14
14
  /** The /click budget: the website snippet aborts at exactly 500 ms. */
15
15
  export const CLICK_TIMEOUT_MS = 500;
16
+ /**
17
+ * True for an absolute http: or https: URL with a host. Anything else (tel:,
18
+ * intent:, javascript:, a custom app scheme, a relative path) is never opened.
19
+ */
20
+ export function isWebUrl(url) {
21
+ return typeof url === 'string'
22
+ && /^https?:\/\/[^\s/?#@]+(?:[/?#]|$)/i.test(url)
23
+ && !/[\s\u0000-\u001f\u007f]/.test(url);
24
+ }
@@ -2,11 +2,14 @@
2
2
  // Pure TypeScript; every native capability comes in through an adapter.
3
3
  import { createMemoryFileCache, createMemoryStorage, defaultAppState, isReleaseBuild, safeLogger, } from './adapters';
4
4
  import { CreativeCache } from './cache';
5
- import { BUNDLED_BASE_URL, cleanServeBase, defaultConfig, isBelowMinSdk, maxAgeSeconds, parseConfig } from './config';
5
+ import { isWebUrl } from './click';
6
+ import { BUNDLED_BASE_URL, clampSkipAfterMs, cleanServeBase, defaultConfig, isBelowMinSdk, maxAgeSeconds, parseConfig } from './config';
6
7
  import { httpRequest, RouteGate } from './http';
7
8
  import { outboxFor, replayRecord } from './outbox';
8
9
  import { InterstitialTracker } from './tracker';
9
10
  import { SDK_VERSION } from '../version';
11
+ /** How long loadInterstitial() waits for a creative download by default. */
12
+ export const DEFAULT_LOAD_TIMEOUT_MS = 3000;
10
13
  const CONFIG_TIMEOUT_MS = 5000;
11
14
  const SERVE_TIMEOUT_MS = 8000;
12
15
  const SIZE_PROBE_TIMEOUT_MS = 3000;
@@ -18,6 +21,9 @@ const DEFAULT_TTL_S = 3600;
18
21
  */
19
22
  export const SESSION_TIMEOUT_MS = 30 * 60 * 1000;
20
23
  let releaseTestModeLogged = false;
24
+ function audioPolicy(v) {
25
+ return v === 'on' || v === 'optional' || v === 'none' ? v : null;
26
+ }
21
27
  export function createEthicly(options) {
22
28
  return new EthiclyClient(options);
23
29
  }
@@ -46,6 +52,9 @@ class EthiclyClient {
46
52
  this.backgroundSince = null;
47
53
  this.preloaded = null;
48
54
  this.serveInflight = null;
55
+ /** Served, creative still downloading, not yet taken. */
56
+ this.pendingServed = null;
57
+ this.badDestinationLogged = false;
49
58
  this.bundled = cleanServeBase(o.baseUrl) || BUNDLED_BASE_URL;
50
59
  const f = o.fetch || globalThis.fetch;
51
60
  if (!f)
@@ -59,6 +68,12 @@ class EthiclyClient {
59
68
  this.cache = new CreativeCache(o.fileCache || createMemoryFileCache(), this.storage, 'ethicly:v1:cache', this.now, this.log, o.fileCache ? (url) => this.contentLength(url) : undefined);
60
69
  this.config = defaultConfig(this.bundled);
61
70
  this.adsOn = o.adsEnabled !== false;
71
+ this.audio = audioPolicy(o.audio);
72
+ if (o.audio !== undefined && !this.audio)
73
+ this.log.warn(`audio must be 'on', 'optional' or 'none': using the server's value`);
74
+ this.loadTimeoutMs = typeof o.loadTimeoutMs === 'number' && Number.isFinite(o.loadTimeoutMs) && o.loadTimeoutMs >= 0
75
+ ? o.loadTimeoutMs
76
+ : DEFAULT_LOAD_TIMEOUT_MS;
62
77
  this.testMode = !!o.testMode && !isReleaseBuild();
63
78
  if (o.testMode && !this.testMode)
64
79
  this.reportReleaseTestMode();
@@ -306,8 +321,12 @@ class EthiclyClient {
306
321
  }
307
322
  setAdsEnabled(enabled) {
308
323
  this.adsOn = !!enabled;
309
- if (!this.adsOn)
310
- this.preloaded = null;
324
+ if (this.adsOn)
325
+ return;
326
+ this.preloaded = null;
327
+ this.pendingServed = null;
328
+ // A paid user downloads nothing: stop the creative download in flight.
329
+ this.cache.cancel();
311
330
  }
312
331
  isAdsEnabled() {
313
332
  return this.adsOn;
@@ -331,6 +350,29 @@ class EthiclyClient {
331
350
  this.log.info(`no ad: ${reason}`);
332
351
  return { ad: null, tracker: null, reason };
333
352
  }
353
+ /** The served ad waiting for its download, or a new serve. One serve at a time. */
354
+ serveOnce() {
355
+ const p = this.pendingServed;
356
+ if (p && !p.consumed && this.now() < p.expiresAt)
357
+ return Promise.resolve({ served: p });
358
+ this.pendingServed = null;
359
+ if (!this.serveInflight) {
360
+ this.serveInflight = this.serve()
361
+ .then((out) => {
362
+ if (out.served)
363
+ this.pendingServed = out.served;
364
+ return out;
365
+ })
366
+ .finally(() => { this.serveInflight = null; });
367
+ }
368
+ return this.serveInflight;
369
+ }
370
+ /** The ad and tracker of a served ad, built once, by whoever asks first. */
371
+ claim(s, uris) {
372
+ if (!s.result)
373
+ s.result = s.build(uris);
374
+ return s.result;
375
+ }
334
376
  async preload() {
335
377
  try {
336
378
  if (!this.adsOn)
@@ -340,13 +382,21 @@ class EthiclyClient {
340
382
  this.preloaded = null;
341
383
  if (this.shownCount >= this.config.interstitial.max_per_session)
342
384
  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)
385
+ const out = await this.serveOnce();
386
+ if (!out.served)
387
+ return out.noFill;
388
+ const s = out.served;
389
+ // In the background: wait for the whole download, so the ad plays from disk.
390
+ const cached = await s.download;
391
+ if (!this.adsOn)
392
+ return this.noFill('ads_disabled');
393
+ const r = this.claim(s, cached.uris);
394
+ if (!s.consumed) {
348
395
  this.preloaded = { result: r };
349
- return r.ad && !this.adsOn ? this.noFill('ads_disabled') : r;
396
+ if (this.pendingServed === s)
397
+ this.pendingServed = null;
398
+ }
399
+ return r;
350
400
  }
351
401
  catch (e) {
352
402
  this.log.error('preload failed', e);
@@ -354,6 +404,7 @@ class EthiclyClient {
354
404
  }
355
405
  }
356
406
  async loadInterstitial() {
407
+ var _a;
357
408
  try {
358
409
  await this.ready;
359
410
  if (!this.adsOn)
@@ -365,8 +416,28 @@ class EthiclyClient {
365
416
  return this.noFill(blocked);
366
417
  if (!this.canShow())
367
418
  return this.noFill('frequency_capped');
368
- const r = await this.preload();
419
+ const pre = this.preloaded;
369
420
  this.preloaded = null;
421
+ if (pre && !pre.result.tracker.isExpired())
422
+ return pre.result;
423
+ const out = await this.serveOnce();
424
+ if (!out.served)
425
+ return out.noFill;
426
+ const s = out.served;
427
+ // The user is waiting: give the download a short budget, then stream the
428
+ // remote file. The download carries on in the background for next time.
429
+ const cached = await this.within(s.download, this.loadTimeoutMs);
430
+ if (!this.adsOn)
431
+ return this.noFill('ads_disabled');
432
+ if (!cached)
433
+ this.log.info(`creative not on disk after ${this.loadTimeoutMs} ms: streaming it; the download continues for next time`);
434
+ const r = this.claim(s, cached ? cached.uris : {});
435
+ s.consumed = true;
436
+ if (this.pendingServed === s)
437
+ this.pendingServed = null;
438
+ // A preload that finished meanwhile may have stored this same ad.
439
+ if (((_a = this.preloaded) === null || _a === void 0 ? void 0 : _a.result) === r)
440
+ this.preloaded = null;
370
441
  return r;
371
442
  }
372
443
  catch (e) {
@@ -374,15 +445,24 @@ class EthiclyClient {
374
445
  return this.noFill('network_error');
375
446
  }
376
447
  }
448
+ /** `p`, or null once `ms` have passed first. */
449
+ within(p, ms) {
450
+ let timer;
451
+ const timeout = new Promise((resolve) => { timer = setTimeout(() => resolve(null), ms); });
452
+ return Promise.race([p, timeout]).finally(() => { if (timer)
453
+ clearTimeout(timer); });
454
+ }
377
455
  async serve() {
456
+ var _a, _b;
457
+ const noFill = (reason) => ({ noFill: this.noFill(reason) });
378
458
  await this.ready;
379
459
  if (this.configStale())
380
460
  await this.refreshConfig();
381
461
  const blocked = this.blockedReason();
382
462
  if (blocked)
383
- return this.noFill(blocked);
463
+ return noFill(blocked);
384
464
  if (this.gate.waitMs('serve') > 0)
385
- return this.noFill('rate_limited');
465
+ return noFill('rate_limited');
386
466
  const q = [
387
467
  `key=${encodeURIComponent(this.o.apiKey)}`,
388
468
  'format=interstitial',
@@ -398,17 +478,17 @@ class EthiclyClient {
398
478
  const servedAt = this.now();
399
479
  if (res.status === 429) {
400
480
  this.gate.block('serve', res.retryAfterS);
401
- return this.noFill('rate_limited');
481
+ return noFill('rate_limited');
402
482
  }
403
483
  if (res.status === 400 || res.status === 403) {
404
484
  this.invalidKey = true;
405
485
  this.log.error(`serve ${res.status}: invalid publisher key. Not retried.`, res.body);
406
- return this.noFill('invalid_key');
486
+ return noFill('invalid_key');
407
487
  }
408
488
  if (res.status === 0)
409
- return this.noFill('network_error');
489
+ return noFill('network_error');
410
490
  if (res.status !== 200 || !res.body || typeof res.body !== 'object')
411
- return this.noFill('server_error');
491
+ return noFill('server_error');
412
492
  const body = res.body;
413
493
  if (!body.ad) {
414
494
  const reason = typeof body.reason === 'string' && body.reason ? body.reason : 'no_matching_ad';
@@ -416,70 +496,86 @@ class EthiclyClient {
416
496
  this.appDisabled = true;
417
497
  if (reason === 'sdk_unsupported')
418
498
  this.sdkUnsupported = true;
419
- return this.noFill(reason);
499
+ return noFill(reason);
420
500
  }
421
501
  const ad = body.ad;
422
502
  const m = ad.media;
423
503
  if (typeof ad.id !== 'number' || !m || typeof m.url !== 'string' || !m.url || typeof ad.destination_url !== 'string') {
424
504
  this.log.warn('serve answered an ad without media or destination', body.request_id);
425
- return this.noFill('invalid_response');
505
+ return noFill('invalid_response');
506
+ }
507
+ if (!isWebUrl(ad.destination_url)) {
508
+ // Only web pages are opened: never tel:, intent:, javascript: or an app scheme.
509
+ if (!this.badDestinationLogged) {
510
+ this.badDestinationLogged = true;
511
+ this.log.error(`ad ${ad.id}: destination is not an http(s) URL, ad skipped`, body.request_id);
512
+ }
513
+ return noFill('invalid_response');
426
514
  }
427
515
  if (body.test === true)
428
516
  this.log.info(`test serve: ad ${ad.id} on site ${body.publisher_site_id}`);
429
517
  if (!this.adsOn)
430
- return this.noFill('ads_disabled');
518
+ return noFill('ads_disabled');
431
519
  const kind = m.kind === 'video' ? 'video' : 'image';
432
520
  const poster = kind === 'video' && typeof m.poster_url === 'string' && m.poster_url ? m.poster_url : null;
433
521
  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;
522
+ // Started now, awaited by preload() in full and by loadInterstitial() within loadTimeoutMs.
523
+ 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: {} }));
438
524
  const ttlS = typeof body.token_ttl_s === 'number' && body.token_ttl_s > 0 ? body.token_ttl_s : DEFAULT_TTL_S;
525
+ const expiresAt = servedAt + ttlS * 1000;
526
+ const adId = ad.id;
527
+ const mediaUrl = m.url;
528
+ const destinationUrl = ad.destination_url;
439
529
  const label = typeof ad.cta_label === 'string' ? ad.cta_label.trim() : '';
440
530
  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,
531
+ // The ad's value wins over /config, kept within the same 8 to 15 s range.
532
+ const skipAfterMs = (_a = clampSkipAfterMs(ad.skip_after_ms)) !== null && _a !== void 0 ? _a : this.config.interstitial.skip_after_ms;
533
+ // The app's choice (options.audio) wins over the server's interstitial.audio.
534
+ const audio = (_b = this.audio) !== null && _b !== void 0 ? _b : this.config.interstitial.audio;
535
+ const build = (uris) => {
536
+ const uri = uris[mediaUrl] || mediaUrl;
537
+ const result = {
538
+ id: adId,
539
+ ctaLabel: label || 'Learn more',
540
+ destinationUrl,
541
+ skipAfterMs,
542
+ media: {
543
+ kind,
544
+ uri,
545
+ videoUri: kind === 'video' ? uri : null,
546
+ posterUri: poster ? uris[poster] || poster : null,
547
+ durationMs: kind === 'video' && typeof m.duration_ms === 'number' && m.duration_ms > 0 ? m.duration_ms : null,
548
+ mime: kind === 'video' ? (typeof m.mime === 'string' && m.mime ? m.mime : 'video/mp4') : null,
549
+ width: posInt(m.width, 720),
550
+ height: posInt(m.height, 1280),
551
+ cached: uri !== mediaUrl,
552
+ },
553
+ audio,
554
+ title: typeof ad.title === 'string' ? ad.title : null,
555
+ test: body.test === true,
556
+ servedAt,
557
+ expiresAt,
558
+ };
559
+ const tracker = new InterstitialTracker({
560
+ ctx: this.beaconCtx(),
561
+ ad: result,
562
+ serve: {
563
+ publisherSiteId: typeof body.publisher_site_id === 'number' && body.publisher_site_id > 0 ? body.publisher_site_id : null,
564
+ countryCode: typeof body.country_code === 'string' ? body.country_code : null,
565
+ impressionToken: typeof body.impression_token === 'string' ? body.impression_token : null,
566
+ },
567
+ viewableAfterMs: this.config.beacon.viewable_after_ms,
568
+ flushIntervalS: this.config.beacon.flush_interval_s,
569
+ platform: this.o.platform,
570
+ sdkVersion: SDK_VERSION,
571
+ appVersion: this.o.appVersion,
572
+ openUrl: this.o.openUrl,
573
+ onShown: () => this.onShown(),
574
+ outbox: this.outbox,
575
+ });
576
+ return { ad: result, tracker };
464
577
  };
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
578
  this.lastNoFillReason = null;
483
- return { ad: result, tracker };
579
+ return { served: { build, download, expiresAt, consumed: false, result: null } };
484
580
  }
485
581
  }
@@ -2,6 +2,19 @@
2
2
  // "Versioning").
3
3
  export const BUNDLED_BASE_URL = 'https://ads.ethicly.ch/functions/v1/get-ad-with-geo';
4
4
  export const DEFAULT_MAX_AGE_S = 300;
5
+ /**
6
+ * The skip delay is kept within these bounds, from /config and from the ad:
7
+ * the video is watched for at least 8 s before Skip appears (it still
8
+ * unlocks earlier when the video ends or after the call to action).
9
+ */
10
+ export const MIN_SKIP_AFTER_MS = 8000;
11
+ export const MAX_SKIP_AFTER_MS = 15000;
12
+ /** A skip delay in ms within MIN_SKIP_AFTER_MS..MAX_SKIP_AFTER_MS, or null when not a number. */
13
+ export function clampSkipAfterMs(v) {
14
+ if (typeof v !== 'number' || !Number.isFinite(v))
15
+ return null;
16
+ return Math.min(MAX_SKIP_AFTER_MS, Math.max(MIN_SKIP_AFTER_MS, Math.round(v)));
17
+ }
5
18
  /** The defaults shown in the doc. Used when no config was ever fetched. */
6
19
  export function defaultConfig(serveBase) {
7
20
  return {
@@ -36,6 +49,7 @@ export function cleanServeBase(v) {
36
49
  * config at all.
37
50
  */
38
51
  export function parseConfig(body, bundledBase) {
52
+ var _a;
39
53
  const b = obj(body);
40
54
  if (typeof b.enabled !== 'boolean')
41
55
  return null;
@@ -52,7 +66,7 @@ export function parseConfig(body, bundledBase) {
52
66
  min_sdk: { ios: str(ms.ios, '0.0.0'), android: str(ms.android, '0.0.0') },
53
67
  formats: Array.isArray(b.formats) ? b.formats.filter((f) => typeof f === 'string') : d.formats,
54
68
  interstitial: {
55
- skip_after_ms: num(it.skip_after_ms, d.interstitial.skip_after_ms, 0, 15000),
69
+ skip_after_ms: (_a = clampSkipAfterMs(it.skip_after_ms)) !== null && _a !== void 0 ? _a : d.interstitial.skip_after_ms,
56
70
  max_per_session: num(it.max_per_session, d.interstitial.max_per_session, 0, 1000),
57
71
  min_gap_s: num(it.min_gap_s, d.interstitial.min_gap_s, 0, 86400),
58
72
  audio,
@@ -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 { createMemoryStorage, createMemoryFileCache, createExpoFileCache, uuidv4, } from './adapters';
4
4
  export { appendClickToken, CLICK_TIMEOUT_MS } from './click';
5
5
  export { compareVersions, BUNDLED_BASE_URL } from './config';
@@ -2,7 +2,7 @@
2
2
  // "Lifecycle and timing" steps 4 to 8 and "Click handling". Every public
3
3
  // method swallows its errors and reports them through the logger.
4
4
  import { BEACON_TIMEOUT_MS, ONE_HOUR_MS, sendWithRetry } from './beacons';
5
- import { appendClickToken, CLICK_TIMEOUT_MS } from './click';
5
+ import { appendClickToken, CLICK_TIMEOUT_MS, isWebUrl } from './click';
6
6
  import { asImpressionId, httpRequest } from './http';
7
7
  import { uuidv4 } from './adapters';
8
8
  /** Doc "Still-image interstitials": /viewable after 1000 ms on screen. */
@@ -308,6 +308,11 @@ export class InterstitialTracker {
308
308
  if (!this.clickUrl)
309
309
  this.clickUrl = this.resolveClickUrl().catch(() => this.d.ad.destinationUrl);
310
310
  return this.clickUrl.then(async (url) => {
311
+ // The client already refuses such an ad; this guards a hand-built EthiclyAd.
312
+ if (!isWebUrl(url)) {
313
+ this.d.ctx.log.error(`ad ${this.d.ad.id}: destination is not an http(s) URL, not opened`);
314
+ return url;
315
+ }
311
316
  try {
312
317
  if (this.d.openUrl)
313
318
  await this.d.openUrl(url);