@ethicly/react-native 0.0.0-stage → 0.2.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (70) hide show
  1. package/CHANGELOG.md +133 -0
  2. package/LICENSE +21 -0
  3. package/README.md +428 -2
  4. package/core/package.json +6 -0
  5. package/interstitial/package.json +6 -0
  6. package/lib/commonjs/core/adapters.js +326 -0
  7. package/lib/commonjs/core/beacons.js +70 -0
  8. package/lib/commonjs/core/cache.js +261 -0
  9. package/lib/commonjs/core/click.js +29 -0
  10. package/lib/commonjs/core/client.js +585 -0
  11. package/lib/commonjs/core/config.js +128 -0
  12. package/lib/commonjs/core/http.js +115 -0
  13. package/lib/commonjs/core/index.js +21 -0
  14. package/lib/commonjs/core/outbox.js +192 -0
  15. package/lib/commonjs/core/tracker.js +379 -0
  16. package/lib/commonjs/core/types.js +4 -0
  17. package/lib/commonjs/index.js +22 -0
  18. package/lib/commonjs/interstitial.js +7 -0
  19. package/lib/commonjs/react/EthiclyInterstitial.js +319 -0
  20. package/lib/commonjs/react/useEthiclyInterstitial.js +54 -0
  21. package/lib/commonjs/version.js +5 -0
  22. package/lib/module/core/adapters.js +315 -0
  23. package/lib/module/core/beacons.js +64 -0
  24. package/lib/module/core/cache.js +257 -0
  25. package/lib/module/core/click.js +24 -0
  26. package/lib/module/core/client.js +581 -0
  27. package/lib/module/core/config.js +118 -0
  28. package/lib/module/core/http.js +105 -0
  29. package/lib/module/core/index.js +6 -0
  30. package/lib/module/core/outbox.js +186 -0
  31. package/lib/module/core/tracker.js +375 -0
  32. package/lib/module/core/types.js +3 -0
  33. package/lib/module/index.js +4 -0
  34. package/lib/module/interstitial.js +3 -0
  35. package/lib/module/react/EthiclyInterstitial.js +292 -0
  36. package/lib/module/react/useEthiclyInterstitial.js +51 -0
  37. package/lib/module/version.js +2 -0
  38. package/lib/typescript/core/adapters.d.ts +139 -0
  39. package/lib/typescript/core/beacons.d.ts +32 -0
  40. package/lib/typescript/core/cache.d.ts +71 -0
  41. package/lib/typescript/core/click.d.ts +13 -0
  42. package/lib/typescript/core/client.d.ts +78 -0
  43. package/lib/typescript/core/config.d.ts +33 -0
  44. package/lib/typescript/core/http.d.ts +34 -0
  45. package/lib/typescript/core/index.d.ts +8 -0
  46. package/lib/typescript/core/outbox.d.ts +56 -0
  47. package/lib/typescript/core/tracker.d.ts +95 -0
  48. package/lib/typescript/core/types.d.ts +175 -0
  49. package/lib/typescript/index.d.ts +3 -0
  50. package/lib/typescript/interstitial.d.ts +2 -0
  51. package/lib/typescript/react/EthiclyInterstitial.d.ts +51 -0
  52. package/lib/typescript/react/useEthiclyInterstitial.d.ts +20 -0
  53. package/lib/typescript/version.d.ts +2 -0
  54. package/package.json +101 -4
  55. package/src/core/adapters.ts +365 -0
  56. package/src/core/beacons.ts +81 -0
  57. package/src/core/cache.ts +261 -0
  58. package/src/core/click.ts +26 -0
  59. package/src/core/client.ts +665 -0
  60. package/src/core/config.ts +124 -0
  61. package/src/core/http.ts +115 -0
  62. package/src/core/index.ts +14 -0
  63. package/src/core/outbox.ts +193 -0
  64. package/src/core/tracker.ts +376 -0
  65. package/src/core/types.ts +185 -0
  66. package/src/index.ts +5 -0
  67. package/src/interstitial.ts +4 -0
  68. package/src/react/EthiclyInterstitial.tsx +432 -0
  69. package/src/react/useEthiclyInterstitial.ts +74 -0
  70. package/src/version.ts +2 -0
@@ -0,0 +1,124 @@
1
+ // /config parsing, defaults and version comparison (doc "GET /config",
2
+ // "Versioning").
3
+
4
+ import type { AudioPolicy, EthiclyConfig } from './types';
5
+
6
+ export const BUNDLED_BASE_URL = 'https://ads.ethicly.ch/functions/v1/get-ad-with-geo';
7
+ export const DEFAULT_MAX_AGE_S = 300;
8
+ /**
9
+ * The skip delay is kept within these bounds, from /config and from the ad:
10
+ * the video is watched for at least 8 s before Skip appears (it still
11
+ * unlocks earlier when the video ends or after the call to action).
12
+ */
13
+ export const MIN_SKIP_AFTER_MS = 8000;
14
+ export const MAX_SKIP_AFTER_MS = 15000;
15
+
16
+ /** A skip delay in ms within MIN_SKIP_AFTER_MS..MAX_SKIP_AFTER_MS, or null when not a number. */
17
+ export function clampSkipAfterMs(v: unknown): number | null {
18
+ if (typeof v !== 'number' || !Number.isFinite(v)) return null;
19
+ return Math.min(MAX_SKIP_AFTER_MS, Math.max(MIN_SKIP_AFTER_MS, Math.round(v)));
20
+ }
21
+
22
+ /** The defaults shown in the doc. Used when no config was ever fetched. */
23
+ export function defaultConfig(serveBase: string): EthiclyConfig {
24
+ return {
25
+ enabled: true,
26
+ min_sdk: { ios: '0.0.0', android: '0.0.0' },
27
+ formats: ['interstitial', '300x250'],
28
+ interstitial: { skip_after_ms: 8000, max_per_session: 3, min_gap_s: 120, audio: 'on' },
29
+ prefetch: { max_cached_creatives: 3, max_cache_mb: 20 },
30
+ beacon: { viewable_after_ms: 2000, flush_interval_s: 30 },
31
+ endpoints: { serve: serveBase },
32
+ };
33
+ }
34
+
35
+ function obj(v: unknown): Record<string, unknown> {
36
+ return v && typeof v === 'object' && !Array.isArray(v) ? (v as Record<string, unknown>) : {};
37
+ }
38
+
39
+ function num(v: unknown, fallback: number, min: number, max: number): number {
40
+ return typeof v === 'number' && Number.isFinite(v) ? Math.min(max, Math.max(min, v)) : fallback;
41
+ }
42
+
43
+ function str(v: unknown, fallback: string): string {
44
+ return typeof v === 'string' && v.trim() ? v.trim() : fallback;
45
+ }
46
+
47
+ /** An https URL, without a trailing slash, or null. */
48
+ export function cleanServeBase(v: unknown): string | null {
49
+ if (typeof v !== 'string') return null;
50
+ const s = v.trim().replace(/\/+$/, '');
51
+ return /^https:\/\/[^/\s]+\/\S*$/.test(s) ? s : null;
52
+ }
53
+
54
+ /**
55
+ * Read a /config body leniently: every field is validated and falls back to
56
+ * the default, unknown fields are ignored. Returns null when the body is not a
57
+ * config at all.
58
+ */
59
+ export function parseConfig(body: unknown, bundledBase: string): EthiclyConfig | null {
60
+ const b = obj(body);
61
+ if (typeof b.enabled !== 'boolean') return null;
62
+ const d = defaultConfig(bundledBase);
63
+ const ms = obj(b.min_sdk);
64
+ const it = obj(b.interstitial);
65
+ const pf = obj(b.prefetch);
66
+ const bc = obj(b.beacon);
67
+ // Sound on is the default; 'none' (always muted) and 'optional' (start muted)
68
+ // are the publisher's explicit choices.
69
+ const audio = it.audio === 'none' || it.audio === 'optional' ? (it.audio as AudioPolicy) : 'on';
70
+ return {
71
+ enabled: b.enabled,
72
+ min_sdk: { ios: str(ms.ios, '0.0.0'), android: str(ms.android, '0.0.0') },
73
+ formats: Array.isArray(b.formats) ? b.formats.filter((f): f is string => typeof f === 'string') : d.formats,
74
+ interstitial: {
75
+ skip_after_ms: clampSkipAfterMs(it.skip_after_ms) ?? d.interstitial.skip_after_ms,
76
+ max_per_session: num(it.max_per_session, d.interstitial.max_per_session, 0, 1000),
77
+ min_gap_s: num(it.min_gap_s, d.interstitial.min_gap_s, 0, 86400),
78
+ audio,
79
+ },
80
+ prefetch: {
81
+ max_cached_creatives: num(pf.max_cached_creatives, d.prefetch.max_cached_creatives, 0, 100),
82
+ max_cache_mb: num(pf.max_cache_mb, d.prefetch.max_cache_mb, 0, 10000),
83
+ },
84
+ beacon: {
85
+ viewable_after_ms: num(bc.viewable_after_ms, d.beacon.viewable_after_ms, 0, 60000),
86
+ flush_interval_s: num(bc.flush_interval_s, d.beacon.flush_interval_s, 1, 3600),
87
+ },
88
+ endpoints: { serve: cleanServeBase(obj(b.endpoints).serve) || bundledBase },
89
+ };
90
+ }
91
+
92
+ /** max-age from Cache-Control, default 300 s. */
93
+ export function maxAgeSeconds(cacheControl: string | null): number {
94
+ const m = cacheControl ? /max-age=(\d+)/i.exec(cacheControl) : null;
95
+ return m ? Number(m[1]) : DEFAULT_MAX_AGE_S;
96
+ }
97
+
98
+ /**
99
+ * Doc "Versioning > Comparison": leading dot-separated numeric components,
100
+ * everything from the first other character ignored. -1, 0, 1, or null when
101
+ * either side has no leading number. Mirrors compareVersions in the server's
102
+ * appConfig.ts.
103
+ */
104
+ export function compareVersions(a: unknown, b: unknown): number | null {
105
+ const parse = (v: unknown): number[] | null => {
106
+ if (typeof v !== 'string') return null;
107
+ const m = /^\d+(\.\d+)*/.exec(v.trim());
108
+ return m ? m[0].split('.').map(Number) : null;
109
+ };
110
+ const pa = parse(a);
111
+ const pb = parse(b);
112
+ if (!pa || !pb) return null;
113
+ for (let i = 0; i < Math.max(pa.length, pb.length); i++) {
114
+ const d = (pa[i] || 0) - (pb[i] || 0);
115
+ if (d !== 0) return d < 0 ? -1 : 1;
116
+ }
117
+ return 0;
118
+ }
119
+
120
+ /** True only when `sdk` parses and is below `min`. */
121
+ export function isBelowMinSdk(sdk: string, min: string): boolean {
122
+ const c = compareVersions(sdk, min);
123
+ return c !== null && c < 0;
124
+ }
@@ -0,0 +1,115 @@
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
+ import type { FetchLike, ImpressionId } from './types';
5
+
6
+ export interface HttpResult {
7
+ /** 0 for a network error or timeout. */
8
+ status: number;
9
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
10
+ body: any;
11
+ /** Seconds from Retry-After, null when absent or unparseable. */
12
+ retryAfterS: number | null;
13
+ cacheControl: string | null;
14
+ timedOut: boolean;
15
+ }
16
+
17
+ /**
18
+ * impression_id is a 64-bit integer. JSON.parse would round anything above
19
+ * 2^53, so long ids are read as strings and written back as bare numbers.
20
+ */
21
+ export function parseJson(text: string): unknown {
22
+ return JSON.parse(text.replace(/("impression_id"\s*:\s*)(\d{16,})/g, '$1"$2"'));
23
+ }
24
+
25
+ export function stringifyJson(value: unknown): string {
26
+ return JSON.stringify(value).replace(/("impression_id":)"(\d+)"/g, '$1$2');
27
+ }
28
+
29
+ export function asImpressionId(v: unknown): ImpressionId | null {
30
+ if (typeof v === 'number' && Number.isInteger(v) && v > 0) return v;
31
+ if (typeof v === 'string' && /^\d+$/.test(v) && !/^0+$/.test(v)) {
32
+ const n = Number(v);
33
+ return Number.isSafeInteger(n) ? n : v;
34
+ }
35
+ return null;
36
+ }
37
+
38
+ export function parseRetryAfter(v: string | null): number | null {
39
+ if (!v) return null;
40
+ const n = Number(v.trim());
41
+ if (Number.isFinite(n) && n >= 0) return n;
42
+ const date = Date.parse(v);
43
+ return Number.isFinite(date) ? Math.max(0, Math.ceil((date - Date.now()) / 1000)) : null;
44
+ }
45
+
46
+ export async function httpRequest(
47
+ fetchFn: FetchLike,
48
+ url: string,
49
+ opts: { method?: string; headers: Record<string, string>; body?: unknown; timeoutMs: number },
50
+ ): Promise<HttpResult> {
51
+ const Ctrl = (globalThis as { AbortController?: typeof AbortController }).AbortController;
52
+ const ctrl = Ctrl ? new Ctrl() : null;
53
+ let timer: ReturnType<typeof setTimeout> | undefined;
54
+ let timedOut = false;
55
+ const timeout = new Promise<null>((resolve) => {
56
+ timer = setTimeout(() => {
57
+ timedOut = true;
58
+ try { ctrl?.abort(); } catch { /* ignore */ }
59
+ resolve(null);
60
+ }, opts.timeoutMs);
61
+ });
62
+ const headers = { ...opts.headers };
63
+ let body: string | undefined;
64
+ if (opts.body !== undefined) {
65
+ headers['Content-Type'] = 'application/json';
66
+ body = stringifyJson(opts.body);
67
+ }
68
+ const fail: HttpResult = { status: 0, body: null, retryAfterS: null, cacheControl: null, timedOut: false };
69
+ try {
70
+ const work = (async (): Promise<HttpResult> => {
71
+ const res = await fetchFn(url, { method: opts.method || 'GET', headers, body, signal: ctrl?.signal });
72
+ const text = await res.text();
73
+ let parsed: unknown = null;
74
+ try { parsed = text ? parseJson(text) : null; } catch { parsed = null; }
75
+ return {
76
+ status: res.status,
77
+ body: parsed,
78
+ retryAfterS: parseRetryAfter(res.headers.get('retry-after')),
79
+ cacheControl: res.headers.get('cache-control'),
80
+ timedOut: false,
81
+ };
82
+ })();
83
+ const out = await Promise.race([work, timeout]);
84
+ if (out === null) {
85
+ work.catch(() => undefined);
86
+ return { ...fail, timedOut: true };
87
+ }
88
+ return out;
89
+ } catch {
90
+ return { ...fail, timedOut };
91
+ } finally {
92
+ if (timer !== undefined) clearTimeout(timer);
93
+ }
94
+ }
95
+
96
+ /** On a 429 the route is closed until Retry-After has passed. */
97
+ export class RouteGate {
98
+ private until = new Map<string, number>();
99
+ constructor(private now: () => number) {}
100
+
101
+ block(route: string, retryAfterS: number | null): void {
102
+ const ms = Math.max(1, retryAfterS ?? 1) * 1000;
103
+ this.until.set(route, Math.max(this.until.get(route) || 0, this.now() + ms));
104
+ }
105
+
106
+ /** Milliseconds until the route opens, 0 when open. */
107
+ waitMs(route: string): number {
108
+ const t = this.until.get(route);
109
+ return t ? Math.max(0, t - this.now()) : 0;
110
+ }
111
+ }
112
+
113
+ export function sleep(ms: number): Promise<void> {
114
+ return new Promise((resolve) => setTimeout(resolve, ms));
115
+ }
@@ -0,0 +1,14 @@
1
+ // Headless core: pure TypeScript, no React. It uses React Native's AppState when present.
2
+ export { createEthicly, DEFAULT_LOAD_TIMEOUT_MS, SESSION_TIMEOUT_MS } from './client';
3
+ export type { Ethicly, EthiclyOptions } from './client';
4
+ export {
5
+ createMemoryStorage, createMemoryFileCache, createExpoFileCache, uuidv4,
6
+ } from './adapters';
7
+ export type { AppStateLike, ExpoFileSystemLike, ExpoFileSystemModernLike } from './adapters';
8
+ export { appendClickToken, CLICK_TIMEOUT_MS } from './click';
9
+ export { compareVersions, BUNDLED_BASE_URL } from './config';
10
+ export { SDK_VERSION } from '../version';
11
+ export type {
12
+ AudioPolicy, EthiclyAd, EthiclyAdMedia, EthiclyConfig, FetchLike, FileCacheAdapter,
13
+ InterstitialResult, KeyValueStorage, Logger, NoFillReason, Platform, Tracker,
14
+ } from './types';
@@ -0,0 +1,193 @@
1
+ // The beacon outbox: what a rendered ad still owes the server, kept in
2
+ // `storage` so it survives the app being killed, and sent on the next start.
3
+ //
4
+ // Only beacons the server treats as idempotent are kept, so a replay can never
5
+ // count anything twice (docs/APP_API_V1.md):
6
+ // - /impression with its client_impression_id: a retry of a row that did land
7
+ // is answered `duplicate: true`, nothing new is recorded (rule 7);
8
+ // - /viewable: billing happens at most once per impression;
9
+ // - /video-event: applied monotonically, repeats change nothing.
10
+ // /click is never kept: it is never retried (doc "Click handling", step 5).
11
+ // Everything expires one hour after the ad was shown (rule 4), and the outbox
12
+ // holds at most MAX_OUTBOX_RECORDS ads.
13
+
14
+ import { ONE_HOUR_MS, sendWithRetry, type BeaconContext } from './beacons';
15
+ import { asImpressionId } from './http';
16
+ import type { ImpressionId, KeyValueStorage, Logger } from './types';
17
+
18
+ export const MAX_OUTBOX_RECORDS = 20;
19
+
20
+ const VIDEO_EVENTS = ['start', 'q1', 'q2', 'q3', 'complete', 'skip', 'error'];
21
+
22
+ export interface OutboxEvent { event: string; ms: number | null }
23
+
24
+ /** One rendered ad's unsent beacons. */
25
+ export interface OutboxRecord {
26
+ /** client_impression_id. */
27
+ cid: string;
28
+ /** Epoch ms the ad was shown. Every beacon below is dropped one hour later. */
29
+ shownAt: number;
30
+ /** The /impression body while it has no answer. */
31
+ impression?: Record<string, unknown>;
32
+ /** Known once /impression answered. */
33
+ impressionId?: ImpressionId;
34
+ viewableToken?: string | null;
35
+ /** viewable_ms of a /viewable still to send. */
36
+ viewableMs?: number;
37
+ events: OutboxEvent[];
38
+ }
39
+
40
+ function validRecord(r: unknown): r is OutboxRecord {
41
+ const o = r as Partial<OutboxRecord> | null;
42
+ if (!o || typeof o.cid !== 'string' || !o.cid || typeof o.shownAt !== 'number' || !Array.isArray(o.events)) return false;
43
+ if (!o.impression && asImpressionId(o.impressionId) === null) return false;
44
+ return o.events.every((e) => e && VIDEO_EVENTS.indexOf(e.event) >= 0);
45
+ }
46
+
47
+ /**
48
+ * One outbox per storage and API key in this JS runtime, shared by every
49
+ * client created on them, so two clients never replay the same record.
50
+ */
51
+ const registry = new WeakMap<object, Map<string, Outbox>>();
52
+
53
+ export function outboxFor(storage: KeyValueStorage, apiKey: string, log: Required<Logger>): Outbox {
54
+ let byKey = registry.get(storage);
55
+ if (!byKey) {
56
+ byKey = new Map();
57
+ registry.set(storage, byKey);
58
+ }
59
+ let ob = byKey.get(apiKey);
60
+ if (!ob) {
61
+ ob = new Outbox(storage, `ethicly:v1:outbox:${apiKey}`, log);
62
+ byKey.set(apiKey, ob);
63
+ }
64
+ return ob;
65
+ }
66
+
67
+ export class Outbox {
68
+ private records = new Map<string, OutboxRecord>();
69
+ /** Records a tracker or a replay in this runtime is already sending. */
70
+ private owned = new Set<string>();
71
+ private loaded: Promise<void> | null = null;
72
+ private dirty = false;
73
+ private writing: Promise<void> | null = null;
74
+
75
+ constructor(private storage: KeyValueStorage, private key: string, private log: Required<Logger>) {}
76
+
77
+ /** Read what a previous run left. Never rejects. */
78
+ load(): Promise<void> {
79
+ if (!this.loaded) {
80
+ this.loaded = (async () => {
81
+ try {
82
+ const raw = await this.storage.getItem(this.key);
83
+ const list = raw ? JSON.parse(raw) : [];
84
+ if (Array.isArray(list)) {
85
+ const valid = list.filter(validRecord).sort((a, b) => b.shownAt - a.shownAt).slice(0, MAX_OUTBOX_RECORDS);
86
+ for (const r of valid) if (!this.records.has(r.cid)) this.records.set(r.cid, r);
87
+ }
88
+ } catch (e) {
89
+ this.log.warn('stored beacon outbox unreadable, starting empty', e);
90
+ }
91
+ })();
92
+ }
93
+ return this.loaded;
94
+ }
95
+
96
+ /** Save or replace a record owned by this runtime. */
97
+ put(rec: OutboxRecord): void {
98
+ this.owned.add(rec.cid);
99
+ this.records.set(rec.cid, rec);
100
+ this.save();
101
+ }
102
+
103
+ remove(cid: string): void {
104
+ if (this.records.delete(cid)) this.save();
105
+ }
106
+
107
+ /**
108
+ * Unexpired records nobody in this runtime is sending, now owned by the
109
+ * caller. Expired ones are dropped.
110
+ */
111
+ claimOrphans(now: number): OutboxRecord[] {
112
+ const out: OutboxRecord[] = [];
113
+ let changed = false;
114
+ for (const r of Array.from(this.records.values())) {
115
+ if (this.owned.has(r.cid)) continue;
116
+ // A time in the future (clock moved back) cannot be trusted either.
117
+ if (now > r.shownAt + ONE_HOUR_MS || r.shownAt > now + 60000) {
118
+ this.records.delete(r.cid);
119
+ changed = true;
120
+ continue;
121
+ }
122
+ this.owned.add(r.cid);
123
+ out.push(r);
124
+ }
125
+ if (changed) this.save();
126
+ return out;
127
+ }
128
+
129
+ /** Coalesced write of the whole outbox, after the stored one was read. Never rejects. */
130
+ private save(): void {
131
+ this.dirty = true;
132
+ if (this.writing) return;
133
+ this.writing = (async () => {
134
+ await this.load();
135
+ while (this.dirty) {
136
+ this.dirty = false;
137
+ // Newest first, so the bound drops the oldest.
138
+ const list = Array.from(this.records.values()).sort((a, b) => b.shownAt - a.shownAt);
139
+ for (const r of list.slice(MAX_OUTBOX_RECORDS)) this.records.delete(r.cid);
140
+ try {
141
+ await this.storage.setItem(this.key, JSON.stringify(list.slice(0, MAX_OUTBOX_RECORDS)));
142
+ } catch (e) {
143
+ this.log.warn('could not save the beacon outbox', e);
144
+ }
145
+ }
146
+ })().finally(() => { this.writing = null; });
147
+ }
148
+
149
+ /** Resolves when nothing is waiting to be written. For tests. */
150
+ async flushed(): Promise<void> {
151
+ while (this.writing) await this.writing;
152
+ }
153
+ }
154
+
155
+ /**
156
+ * Send what a previous run left for one ad, with the live tracker's rules:
157
+ * /impression first (same client_impression_id), then /viewable, then the
158
+ * video events. Anything the server refuses, or that is past one hour, is
159
+ * dropped. Never throws.
160
+ */
161
+ export async function replayRecord(ctx: BeaconContext, outbox: Outbox, rec: OutboxRecord): Promise<void> {
162
+ const deadline = rec.shownAt + ONE_HOUR_MS;
163
+ try {
164
+ let id = asImpressionId(rec.impressionId);
165
+ let token = typeof rec.viewableToken === 'string' ? rec.viewableToken : null;
166
+ if (id === null && rec.impression) {
167
+ const res = await sendWithRetry(ctx, 'impression', rec.impression, { deadline });
168
+ id = res && res.status === 200 ? asImpressionId(res.body?.impression_id) : null;
169
+ if (id === null) return;
170
+ token = typeof res!.body?.viewable_token === 'string' ? res!.body.viewable_token : null;
171
+ // Rule 5: a token-enforced serve with no viewable_token cannot bill.
172
+ if (rec.impression.impression_token && !token) return;
173
+ outbox.put({ ...rec, impression: undefined, impressionId: id, viewableToken: token });
174
+ }
175
+ if (id === null) return;
176
+ if (typeof rec.viewableMs === 'number') {
177
+ const body: Record<string, unknown> = { impression_id: id, viewable_ms: Math.round(rec.viewableMs) };
178
+ if (token) body.viewable_token = token;
179
+ if (ctx.now() <= deadline) await sendWithRetry(ctx, 'viewable', body, { deadline });
180
+ }
181
+ for (const e of rec.events) {
182
+ if (ctx.now() > deadline) break;
183
+ const body: Record<string, unknown> = { impression_id: id, event: e.event };
184
+ if (e.ms !== null && e.ms !== undefined) body.ms = e.ms;
185
+ if (token) body.viewable_token = token;
186
+ await sendWithRetry(ctx, 'video-event', body, { deadline });
187
+ }
188
+ } catch (e) {
189
+ ctx.log.error('beacon replay failed', e);
190
+ } finally {
191
+ outbox.remove(rec.cid);
192
+ }
193
+ }