@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
@@ -4,6 +4,7 @@
4
4
  Object.defineProperty(exports, "__esModule", { value: true });
5
5
  exports.CLICK_TIMEOUT_MS = void 0;
6
6
  exports.appendClickToken = appendClickToken;
7
+ exports.isWebUrl = isWebUrl;
7
8
  /**
8
9
  * Append ethicly_click=<token> to the destination. The separator is "&" when
9
10
  * the URL already contains a "?" anywhere, otherwise "?". The token is
@@ -17,3 +18,12 @@ function appendClickToken(destinationUrl, clickToken) {
17
18
  }
18
19
  /** The /click budget: the website snippet aborts at exactly 500 ms. */
19
20
  exports.CLICK_TIMEOUT_MS = 500;
21
+ /**
22
+ * True for an absolute http: or https: URL with a host. Anything else (tel:,
23
+ * intent:, javascript:, a custom app scheme, a relative path) is never opened.
24
+ */
25
+ function isWebUrl(url) {
26
+ return typeof url === 'string'
27
+ && /^https?:\/\/[^\s/?#@]+(?:[/?#]|$)/i.test(url)
28
+ && !/[\s\u0000-\u001f\u007f]/.test(url);
29
+ }
@@ -2,15 +2,18 @@
2
2
  // createEthicly: config, serve, prefetch, frequency caps and the ads switch.
3
3
  // Pure TypeScript; every native capability comes in through an adapter.
4
4
  Object.defineProperty(exports, "__esModule", { value: true });
5
- exports.SESSION_TIMEOUT_MS = void 0;
5
+ exports.SESSION_TIMEOUT_MS = exports.DEFAULT_LOAD_TIMEOUT_MS = void 0;
6
6
  exports.createEthicly = createEthicly;
7
7
  const adapters_1 = require("./adapters");
8
8
  const cache_1 = require("./cache");
9
+ const click_1 = require("./click");
9
10
  const config_1 = require("./config");
10
11
  const http_1 = require("./http");
11
12
  const outbox_1 = require("./outbox");
12
13
  const tracker_1 = require("./tracker");
13
14
  const version_1 = require("../version");
15
+ /** How long loadInterstitial() waits for a creative download by default. */
16
+ exports.DEFAULT_LOAD_TIMEOUT_MS = 3000;
14
17
  const CONFIG_TIMEOUT_MS = 5000;
15
18
  const SERVE_TIMEOUT_MS = 8000;
16
19
  const SIZE_PROBE_TIMEOUT_MS = 3000;
@@ -22,6 +25,9 @@ const DEFAULT_TTL_S = 3600;
22
25
  */
23
26
  exports.SESSION_TIMEOUT_MS = 30 * 60 * 1000;
24
27
  let releaseTestModeLogged = false;
28
+ function audioPolicy(v) {
29
+ return v === 'on' || v === 'optional' || v === 'none' ? v : null;
30
+ }
25
31
  function createEthicly(options) {
26
32
  return new EthiclyClient(options);
27
33
  }
@@ -50,6 +56,9 @@ class EthiclyClient {
50
56
  this.backgroundSince = null;
51
57
  this.preloaded = null;
52
58
  this.serveInflight = null;
59
+ /** Served, creative still downloading, not yet taken. */
60
+ this.pendingServed = null;
61
+ this.badDestinationLogged = false;
53
62
  this.bundled = (0, config_1.cleanServeBase)(o.baseUrl) || config_1.BUNDLED_BASE_URL;
54
63
  const f = o.fetch || globalThis.fetch;
55
64
  if (!f)
@@ -63,6 +72,12 @@ class EthiclyClient {
63
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);
64
73
  this.config = (0, config_1.defaultConfig)(this.bundled);
65
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;
66
81
  this.testMode = !!o.testMode && !(0, adapters_1.isReleaseBuild)();
67
82
  if (o.testMode && !this.testMode)
68
83
  this.reportReleaseTestMode();
@@ -310,8 +325,12 @@ class EthiclyClient {
310
325
  }
311
326
  setAdsEnabled(enabled) {
312
327
  this.adsOn = !!enabled;
313
- if (!this.adsOn)
314
- this.preloaded = null;
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();
315
334
  }
316
335
  isAdsEnabled() {
317
336
  return this.adsOn;
@@ -335,6 +354,29 @@ class EthiclyClient {
335
354
  this.log.info(`no ad: ${reason}`);
336
355
  return { ad: null, tracker: null, reason };
337
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
+ }
338
380
  async preload() {
339
381
  try {
340
382
  if (!this.adsOn)
@@ -344,13 +386,21 @@ class EthiclyClient {
344
386
  this.preloaded = null;
345
387
  if (this.shownCount >= this.config.interstitial.max_per_session)
346
388
  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)
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) {
352
399
  this.preloaded = { result: r };
353
- return r.ad && !this.adsOn ? this.noFill('ads_disabled') : r;
400
+ if (this.pendingServed === s)
401
+ this.pendingServed = null;
402
+ }
403
+ return r;
354
404
  }
355
405
  catch (e) {
356
406
  this.log.error('preload failed', e);
@@ -358,6 +408,7 @@ class EthiclyClient {
358
408
  }
359
409
  }
360
410
  async loadInterstitial() {
411
+ var _a;
361
412
  try {
362
413
  await this.ready;
363
414
  if (!this.adsOn)
@@ -369,8 +420,28 @@ class EthiclyClient {
369
420
  return this.noFill(blocked);
370
421
  if (!this.canShow())
371
422
  return this.noFill('frequency_capped');
372
- const r = await this.preload();
423
+ const pre = this.preloaded;
373
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;
374
445
  return r;
375
446
  }
376
447
  catch (e) {
@@ -378,15 +449,24 @@ class EthiclyClient {
378
449
  return this.noFill('network_error');
379
450
  }
380
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
+ }
381
459
  async serve() {
460
+ var _a, _b;
461
+ const noFill = (reason) => ({ noFill: this.noFill(reason) });
382
462
  await this.ready;
383
463
  if (this.configStale())
384
464
  await this.refreshConfig();
385
465
  const blocked = this.blockedReason();
386
466
  if (blocked)
387
- return this.noFill(blocked);
467
+ return noFill(blocked);
388
468
  if (this.gate.waitMs('serve') > 0)
389
- return this.noFill('rate_limited');
469
+ return noFill('rate_limited');
390
470
  const q = [
391
471
  `key=${encodeURIComponent(this.o.apiKey)}`,
392
472
  'format=interstitial',
@@ -402,17 +482,17 @@ class EthiclyClient {
402
482
  const servedAt = this.now();
403
483
  if (res.status === 429) {
404
484
  this.gate.block('serve', res.retryAfterS);
405
- return this.noFill('rate_limited');
485
+ return noFill('rate_limited');
406
486
  }
407
487
  if (res.status === 400 || res.status === 403) {
408
488
  this.invalidKey = true;
409
489
  this.log.error(`serve ${res.status}: invalid publisher key. Not retried.`, res.body);
410
- return this.noFill('invalid_key');
490
+ return noFill('invalid_key');
411
491
  }
412
492
  if (res.status === 0)
413
- return this.noFill('network_error');
493
+ return noFill('network_error');
414
494
  if (res.status !== 200 || !res.body || typeof res.body !== 'object')
415
- return this.noFill('server_error');
495
+ return noFill('server_error');
416
496
  const body = res.body;
417
497
  if (!body.ad) {
418
498
  const reason = typeof body.reason === 'string' && body.reason ? body.reason : 'no_matching_ad';
@@ -420,70 +500,86 @@ class EthiclyClient {
420
500
  this.appDisabled = true;
421
501
  if (reason === 'sdk_unsupported')
422
502
  this.sdkUnsupported = true;
423
- return this.noFill(reason);
503
+ return noFill(reason);
424
504
  }
425
505
  const ad = body.ad;
426
506
  const m = ad.media;
427
507
  if (typeof ad.id !== 'number' || !m || typeof m.url !== 'string' || !m.url || typeof ad.destination_url !== 'string') {
428
508
  this.log.warn('serve answered an ad without media or destination', body.request_id);
429
- return this.noFill('invalid_response');
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');
430
518
  }
431
519
  if (body.test === true)
432
520
  this.log.info(`test serve: ad ${ad.id} on site ${body.publisher_site_id}`);
433
521
  if (!this.adsOn)
434
- return this.noFill('ads_disabled');
522
+ return noFill('ads_disabled');
435
523
  const kind = m.kind === 'video' ? 'video' : 'image';
436
524
  const poster = kind === 'video' && typeof m.poster_url === 'string' && m.poster_url ? m.poster_url : null;
437
525
  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;
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: {} }));
442
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;
443
533
  const label = typeof ad.cta_label === 'string' ? ad.cta_label.trim() : '';
444
534
  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,
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 };
468
581
  };
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
582
  this.lastNoFillReason = null;
487
- return { ad: result, tracker };
583
+ return { served: { build, download, expiresAt, consumed: false, result: null } };
488
584
  }
489
585
  }
@@ -2,7 +2,8 @@
2
2
  // /config parsing, defaults and version comparison (doc "GET /config",
3
3
  // "Versioning").
4
4
  Object.defineProperty(exports, "__esModule", { value: true });
5
- exports.DEFAULT_MAX_AGE_S = exports.BUNDLED_BASE_URL = void 0;
5
+ exports.MAX_SKIP_AFTER_MS = exports.MIN_SKIP_AFTER_MS = exports.DEFAULT_MAX_AGE_S = exports.BUNDLED_BASE_URL = void 0;
6
+ exports.clampSkipAfterMs = clampSkipAfterMs;
6
7
  exports.defaultConfig = defaultConfig;
7
8
  exports.cleanServeBase = cleanServeBase;
8
9
  exports.parseConfig = parseConfig;
@@ -11,6 +12,19 @@ exports.compareVersions = compareVersions;
11
12
  exports.isBelowMinSdk = isBelowMinSdk;
12
13
  exports.BUNDLED_BASE_URL = 'https://ads.ethicly.ch/functions/v1/get-ad-with-geo';
13
14
  exports.DEFAULT_MAX_AGE_S = 300;
15
+ /**
16
+ * The skip delay is kept within these bounds, from /config and from the ad:
17
+ * the video is watched for at least 8 s before Skip appears (it still
18
+ * unlocks earlier when the video ends or after the call to action).
19
+ */
20
+ exports.MIN_SKIP_AFTER_MS = 8000;
21
+ exports.MAX_SKIP_AFTER_MS = 15000;
22
+ /** A skip delay in ms within MIN_SKIP_AFTER_MS..MAX_SKIP_AFTER_MS, or null when not a number. */
23
+ function clampSkipAfterMs(v) {
24
+ if (typeof v !== 'number' || !Number.isFinite(v))
25
+ return null;
26
+ return Math.min(exports.MAX_SKIP_AFTER_MS, Math.max(exports.MIN_SKIP_AFTER_MS, Math.round(v)));
27
+ }
14
28
  /** The defaults shown in the doc. Used when no config was ever fetched. */
15
29
  function defaultConfig(serveBase) {
16
30
  return {
@@ -45,6 +59,7 @@ function cleanServeBase(v) {
45
59
  * config at all.
46
60
  */
47
61
  function parseConfig(body, bundledBase) {
62
+ var _a;
48
63
  const b = obj(body);
49
64
  if (typeof b.enabled !== 'boolean')
50
65
  return null;
@@ -61,7 +76,7 @@ function parseConfig(body, bundledBase) {
61
76
  min_sdk: { ios: str(ms.ios, '0.0.0'), android: str(ms.android, '0.0.0') },
62
77
  formats: Array.isArray(b.formats) ? b.formats.filter((f) => typeof f === 'string') : d.formats,
63
78
  interstitial: {
64
- skip_after_ms: num(it.skip_after_ms, d.interstitial.skip_after_ms, 0, 15000),
79
+ skip_after_ms: (_a = clampSkipAfterMs(it.skip_after_ms)) !== null && _a !== void 0 ? _a : d.interstitial.skip_after_ms,
65
80
  max_per_session: num(it.max_per_session, d.interstitial.max_per_session, 0, 1000),
66
81
  min_gap_s: num(it.min_gap_s, d.interstitial.min_gap_s, 0, 86400),
67
82
  audio,
@@ -1,9 +1,10 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.SDK_VERSION = exports.BUNDLED_BASE_URL = exports.compareVersions = exports.CLICK_TIMEOUT_MS = exports.appendClickToken = exports.uuidv4 = exports.createExpoFileCache = exports.createMemoryFileCache = exports.createMemoryStorage = exports.SESSION_TIMEOUT_MS = exports.createEthicly = void 0;
3
+ exports.SDK_VERSION = exports.BUNDLED_BASE_URL = exports.compareVersions = exports.CLICK_TIMEOUT_MS = exports.appendClickToken = exports.uuidv4 = exports.createExpoFileCache = exports.createMemoryFileCache = exports.createMemoryStorage = exports.SESSION_TIMEOUT_MS = exports.DEFAULT_LOAD_TIMEOUT_MS = exports.createEthicly = void 0;
4
4
  // Headless core: pure TypeScript, no React. It uses React Native's AppState when present.
5
5
  var client_1 = require("./client");
6
6
  Object.defineProperty(exports, "createEthicly", { enumerable: true, get: function () { return client_1.createEthicly; } });
7
+ Object.defineProperty(exports, "DEFAULT_LOAD_TIMEOUT_MS", { enumerable: true, get: function () { return client_1.DEFAULT_LOAD_TIMEOUT_MS; } });
7
8
  Object.defineProperty(exports, "SESSION_TIMEOUT_MS", { enumerable: true, get: function () { return client_1.SESSION_TIMEOUT_MS; } });
8
9
  var adapters_1 = require("./adapters");
9
10
  Object.defineProperty(exports, "createMemoryStorage", { enumerable: true, get: function () { return adapters_1.createMemoryStorage; } });
@@ -311,6 +311,11 @@ class InterstitialTracker {
311
311
  if (!this.clickUrl)
312
312
  this.clickUrl = this.resolveClickUrl().catch(() => this.d.ad.destinationUrl);
313
313
  return this.clickUrl.then(async (url) => {
314
+ // The client already refuses such an ad; this guards a hand-built EthiclyAd.
315
+ if (!(0, click_1.isWebUrl)(url)) {
316
+ this.d.ctx.log.error(`ad ${this.d.ad.id}: destination is not an http(s) URL, not opened`);
317
+ return url;
318
+ }
314
319
  try {
315
320
  if (this.d.openUrl)
316
321
  await this.d.openUrl(url);
@@ -23,18 +23,27 @@ var __importStar = (this && this.__importStar) || function (mod) {
23
23
  return result;
24
24
  };
25
25
  Object.defineProperty(exports, "__esModule", { value: true });
26
+ exports.effectiveAudio = effectiveAudio;
26
27
  exports.EthiclyInterstitial = EthiclyInterstitial;
27
28
  const jsx_runtime_1 = require("react/jsx-runtime");
28
29
  // Optional ready-made fullscreen screen. Needs expo-video (Expo SDK 52+).
29
30
  // Layout follows a typical in-app video player: 9:16 video, a skip control that counts
30
31
  // down then reads "Skip Ad", a white call-to-action button, an optional
31
32
  // "Remove ads" slot and a small "Sponsored by Ethicly.ch" line under it.
32
- // Video starts with sound unless interstitial.audio is 'none' or 'optional'.
33
+ // Video starts with sound unless the effective audio (the `audio` prop, else
34
+ // ad.audio: createEthicly's `audio` option, else /config) is 'none' or 'optional'.
33
35
  // The controls keep clear of the notch, status bar and home indicator: see
34
36
  // useSafeInsets below.
35
37
  const react_1 = __importStar(require("react"));
36
38
  const react_native_1 = require("react-native");
37
39
  const expo_video_1 = require("expo-video");
40
+ /** The sound a screen plays with: the prop, else ad.audio, else 'on'. */
41
+ function effectiveAudio(prop, ad) {
42
+ for (const v of [prop, ad.audio])
43
+ if (v === 'on' || v === 'optional' || v === 'none')
44
+ return v;
45
+ return 'on';
46
+ }
38
47
  const TICK_MS = 250;
39
48
  /** Space between the safe area and the controls. */
40
49
  const TOP_GAP = 12;
@@ -114,7 +123,8 @@ function useAppActive() {
114
123
  }, []);
115
124
  return active;
116
125
  }
117
- function InterstitialBody({ ad, tracker, onClose, onRemoveAds, removeAdsLabel, renderBelowButton, skipStyle, skipTextStyle, insets, backRef, }) {
126
+ function InterstitialBody({ ad, tracker, onClose, onRemoveAds, removeAdsLabel, renderBelowButton, skipStyle, skipTextStyle, insets, backRef, audio: audioProp, }) {
127
+ const audio = effectiveAudio(audioProp, ad);
118
128
  const safe = useSafeInsets(insets);
119
129
  const isVideo = ad.media.kind === 'video' && !!ad.media.videoUri;
120
130
  const appActive = useAppActive();
@@ -123,15 +133,21 @@ function InterstitialBody({ ad, tracker, onClose, onRemoveAds, removeAdsLabel, r
123
133
  const [positionMs, setPositionMs] = (0, react_1.useState)(0);
124
134
  const [ended, setEnded] = (0, react_1.useState)(false);
125
135
  const [failed, setFailed] = (0, react_1.useState)(false);
126
- const [muted, setMuted] = (0, react_1.useState)(ad.audio !== 'on');
136
+ const [muted, setMuted] = (0, react_1.useState)(audio !== 'on');
137
+ /**
138
+ * A still image counts as visible only once it has loaded: an image that
139
+ * never arrives is never billed as viewable.
140
+ */
141
+ const imageLoadedRef = (0, react_1.useRef)(false);
127
142
  /** Wall-clock time on screen with the app in the foreground. */
128
143
  const [onScreenMs, setOnScreenMs] = (0, react_1.useState)(0);
129
144
  const [clicked, setClicked] = (0, react_1.useState)(false);
130
145
  const positionRef = (0, react_1.useRef)(0);
131
146
  const closedRef = (0, react_1.useRef)(false);
147
+ const failedRef = (0, react_1.useRef)(false);
132
148
  const player = (0, expo_video_1.useVideoPlayer)(isVideo ? ad.media.videoUri : null, (p) => {
133
149
  p.loop = false;
134
- p.muted = ad.audio !== 'on';
150
+ p.muted = audio !== 'on';
135
151
  p.timeUpdateEventInterval = TICK_MS / 1000;
136
152
  p.play();
137
153
  });
@@ -166,7 +182,8 @@ function InterstitialBody({ ad, tracker, onClose, onRemoveAds, removeAdsLabel, r
166
182
  tracker.complete();
167
183
  }),
168
184
  player.addListener('statusChange', ({ status }) => {
169
- if (status === 'error') {
185
+ if (status === 'error' && !failedRef.current) {
186
+ failedRef.current = true;
170
187
  setFailed(true);
171
188
  tracker.error();
172
189
  }
@@ -174,23 +191,36 @@ function InterstitialBody({ ad, tracker, onClose, onRemoveAds, removeAdsLabel, r
174
191
  ];
175
192
  return () => subs.forEach((s) => s.remove());
176
193
  }, [isVideo, player, tracker]);
177
- // Time on screen while the app is in the foreground. For a still image it is
178
- // the playback position; for a video it is the skip countdown's fallback, so
179
- // Skip still appears after skipAfterMs if the video stalls or never starts.
194
+ // Time on screen while the app is in the foreground: the skip countdown, so
195
+ // Skip appears after skipAfterMs even if the video stalls or the image never
196
+ // loads. For a still image, the time since it loaded is the playback position.
180
197
  (0, react_1.useEffect)(() => {
181
198
  let shownMs = 0;
199
+ let loadedMs = 0;
182
200
  const id = setInterval(() => {
183
201
  if (activeRef.current)
184
202
  shownMs += TICK_MS;
185
203
  setOnScreenMs(shownMs);
186
- if (isVideo)
204
+ if (isVideo || !imageLoadedRef.current || failedRef.current)
187
205
  return;
188
- positionRef.current = shownMs;
189
- setPositionMs(shownMs);
190
- tracker.progress(shownMs, { visible: activeRef.current });
206
+ if (activeRef.current)
207
+ loadedMs += TICK_MS;
208
+ positionRef.current = loadedMs;
209
+ setPositionMs(loadedMs);
210
+ tracker.progress(loadedMs, { visible: activeRef.current });
191
211
  }, TICK_MS);
192
212
  return () => clearInterval(id);
193
213
  }, [isVideo, tracker]);
214
+ const onImageLoad = (0, react_1.useCallback)(() => {
215
+ imageLoadedRef.current = true;
216
+ }, []);
217
+ const onImageError = (0, react_1.useCallback)(() => {
218
+ if (failedRef.current)
219
+ return;
220
+ failedRef.current = true;
221
+ setFailed(true);
222
+ tracker.error();
223
+ }, [tracker]);
194
224
  (0, react_1.useEffect)(() => {
195
225
  if (!isVideo)
196
226
  return;
@@ -204,6 +234,8 @@ function InterstitialBody({ ad, tracker, onClose, onRemoveAds, removeAdsLabel, r
204
234
  (0, react_1.useEffect)(() => {
205
235
  if (appActive)
206
236
  return;
237
+ if (!isVideo && (!imageLoadedRef.current || failedRef.current))
238
+ return;
207
239
  const durationMs = isVideo && player.duration > 0 ? player.duration * 1000 : undefined;
208
240
  tracker.progress(positionRef.current, { visible: false, durationMs });
209
241
  }, [appActive, isVideo, player, tracker]);
@@ -236,7 +268,7 @@ function InterstitialBody({ ad, tracker, onClose, onRemoveAds, removeAdsLabel, r
236
268
  const remainingS = Math.ceil(Math.max(0, ad.skipAfterMs - Math.max(positionMs, onScreenMs)) / 1000);
237
269
  const canSkip = remainingS === 0 || ended || failed || clicked;
238
270
  backRef.current = canSkip ? close : null;
239
- return ((0, jsx_runtime_1.jsxs)(react_native_1.View, { style: styles.root, children: [isVideo ? ((0, jsx_runtime_1.jsxs)(jsx_runtime_1.Fragment, { children: [ad.media.posterUri ? (0, jsx_runtime_1.jsx)(react_native_1.Image, { source: { uri: ad.media.posterUri }, style: react_native_1.StyleSheet.absoluteFill, resizeMode: "cover" }) : null, (0, jsx_runtime_1.jsx)(expo_video_1.VideoView, { player: player, style: react_native_1.StyleSheet.absoluteFill, contentFit: "cover", nativeControls: false, allowsFullscreen: false, allowsPictureInPicture: false })] })) : ((0, jsx_runtime_1.jsx)(react_native_1.Image, { source: { uri: ad.media.uri }, style: react_native_1.StyleSheet.absoluteFill, resizeMode: "cover" })), (0, jsx_runtime_1.jsxs)(react_native_1.View, { style: [styles.topRow, { top: Math.max(safe.top + TOP_GAP, MIN_TOP), left: safe.left + SIDE_GAP_TOP, right: safe.right + SIDE_GAP_TOP }], pointerEvents: "box-none", children: [(0, jsx_runtime_1.jsxs)(react_native_1.View, { style: styles.leftGroup, children: [(0, jsx_runtime_1.jsx)(react_native_1.Text, { style: styles.adLabel, accessibilityRole: "text", children: "Ad" }), isVideo && ad.audio !== 'none' ? ((0, jsx_runtime_1.jsx)(react_native_1.Pressable, { onPress: toggleSound, style: styles.soundButton, accessibilityRole: "button", accessibilityLabel: muted ? 'Turn sound on' : 'Mute', hitSlop: 8, children: (0, jsx_runtime_1.jsx)(react_native_1.Text, { style: styles.soundText, children: muted ? 'Sound off' : 'Sound on' }) })) : null] }), (0, jsx_runtime_1.jsx)(react_native_1.Pressable, { onPress: canSkip ? close : undefined, disabled: !canSkip, style: [styles.skip, skipStyle], accessibilityRole: "button", accessibilityLabel: canSkip ? 'Skip ad' : `Skip in ${remainingS} seconds`, hitSlop: 8, children: canSkip ? ((0, jsx_runtime_1.jsxs)(react_native_1.View, { style: styles.skipRow, children: [(0, jsx_runtime_1.jsx)(react_native_1.Text, { style: [styles.skipText, skipTextStyle], children: "Skip Ad" }), (0, jsx_runtime_1.jsx)(SkipIcon, {})] })) : ((0, jsx_runtime_1.jsx)(react_native_1.Text, { style: [styles.skipText, styles.skipTextWaiting, skipTextStyle], children: `Skip in ${remainingS}` })) })] }), (0, jsx_runtime_1.jsxs)(react_native_1.View, { style: [styles.bottom, {
271
+ return ((0, jsx_runtime_1.jsxs)(react_native_1.View, { style: styles.root, children: [isVideo ? ((0, jsx_runtime_1.jsxs)(jsx_runtime_1.Fragment, { children: [ad.media.posterUri ? (0, jsx_runtime_1.jsx)(react_native_1.Image, { source: { uri: ad.media.posterUri }, style: react_native_1.StyleSheet.absoluteFill, resizeMode: "cover" }) : null, (0, jsx_runtime_1.jsx)(expo_video_1.VideoView, { player: player, style: react_native_1.StyleSheet.absoluteFill, contentFit: "cover", nativeControls: false, allowsPictureInPicture: false })] })) : ((0, jsx_runtime_1.jsx)(react_native_1.Image, { source: { uri: ad.media.uri }, style: react_native_1.StyleSheet.absoluteFill, resizeMode: "cover", onLoad: onImageLoad, onError: onImageError })), (0, jsx_runtime_1.jsxs)(react_native_1.View, { style: [styles.topRow, { top: Math.max(safe.top + TOP_GAP, MIN_TOP), left: safe.left + SIDE_GAP_TOP, right: safe.right + SIDE_GAP_TOP }], pointerEvents: "box-none", children: [(0, jsx_runtime_1.jsxs)(react_native_1.View, { style: styles.leftGroup, children: [(0, jsx_runtime_1.jsx)(react_native_1.Text, { style: styles.adLabel, accessibilityRole: "text", children: "Ad" }), ad.test ? (0, jsx_runtime_1.jsx)(react_native_1.Text, { style: [styles.adLabel, styles.testLabel], accessibilityRole: "text", children: "Test ad" }) : null, isVideo && audio !== 'none' ? ((0, jsx_runtime_1.jsx)(react_native_1.Pressable, { onPress: toggleSound, style: styles.soundButton, accessibilityRole: "button", accessibilityLabel: muted ? 'Turn sound on' : 'Mute', hitSlop: 8, children: (0, jsx_runtime_1.jsx)(react_native_1.Text, { style: styles.soundText, children: muted ? 'Sound off' : 'Sound on' }) })) : null] }), (0, jsx_runtime_1.jsx)(react_native_1.Pressable, { onPress: canSkip ? close : undefined, disabled: !canSkip, style: [styles.skip, skipStyle], accessibilityRole: "button", accessibilityLabel: canSkip ? 'Skip ad' : `Skip in ${remainingS} seconds`, hitSlop: 8, children: canSkip ? ((0, jsx_runtime_1.jsxs)(react_native_1.View, { style: styles.skipRow, children: [(0, jsx_runtime_1.jsx)(react_native_1.Text, { style: [styles.skipText, skipTextStyle], children: "Skip Ad" }), (0, jsx_runtime_1.jsx)(SkipIcon, {})] })) : ((0, jsx_runtime_1.jsx)(react_native_1.Text, { style: [styles.skipText, styles.skipTextWaiting, skipTextStyle], children: `Skip in ${remainingS}` })) })] }), (0, jsx_runtime_1.jsxs)(react_native_1.View, { style: [styles.bottom, {
240
272
  bottom: Math.max(safe.bottom + BOTTOM_GAP, MIN_BOTTOM), left: safe.left + SIDE_GAP_BOTTOM, right: safe.right + SIDE_GAP_BOTTOM,
241
273
  }], pointerEvents: "box-none", children: [(0, jsx_runtime_1.jsx)(react_native_1.Pressable, { onPress: onCta, style: ({ pressed }) => [styles.cta, pressed && styles.ctaPressed], accessibilityRole: "link", children: (0, jsx_runtime_1.jsx)(react_native_1.Text, { style: styles.ctaText, numberOfLines: 1, children: ad.ctaLabel || 'Learn more' }) }), renderBelowButton ? renderBelowButton() : onRemoveAds ? ((0, jsx_runtime_1.jsx)(react_native_1.Pressable, { onPress: onRemoveAds, accessibilityRole: "button", hitSlop: 8, children: (0, jsx_runtime_1.jsx)(react_native_1.Text, { style: styles.removeAds, children: removeAdsLabel || 'Remove ads' }) })) : null, (0, jsx_runtime_1.jsx)(react_native_1.Text, { style: styles.sponsor, children: "Sponsored by Ethicly.ch" })] })] }));
242
274
  }
@@ -255,6 +287,7 @@ const styles = react_native_1.StyleSheet.create({
255
287
  color: '#fff', fontSize: 11, fontWeight: '600', letterSpacing: 0.5,
256
288
  backgroundColor: 'rgba(0,0,0,0.45)', paddingHorizontal: 6, paddingVertical: 2, borderRadius: 4, overflow: 'hidden',
257
289
  },
290
+ testLabel: { marginLeft: 8, backgroundColor: 'rgba(196,120,0,0.85)' },
258
291
  soundButton: { marginLeft: 8, backgroundColor: 'rgba(0,0,0,0.45)', paddingHorizontal: 8, paddingVertical: 4, borderRadius: 6 },
259
292
  soundText: { color: '#fff', fontSize: 12, fontWeight: '500' },
260
293
  // Solid black, no blur or translucency. The faint hairline keeps the edge
@@ -2,4 +2,4 @@
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.SDK_VERSION = void 0;
4
4
  /** SDK version, sent as sdk_version and in X-Ethicly-SDK. Keep in step with package.json. */
5
- exports.SDK_VERSION = '0.2.0';
5
+ exports.SDK_VERSION = '0.2.1';