@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,376 @@
1
+ // The tracker a host player drives for one rendered ad. Implements doc
2
+ // "Lifecycle and timing" steps 4 to 8 and "Click handling". Every public
3
+ // method swallows its errors and reports them through the logger.
4
+
5
+ import { BEACON_TIMEOUT_MS, ONE_HOUR_MS, sendWithRetry, type BeaconContext } from './beacons';
6
+ import { appendClickToken, CLICK_TIMEOUT_MS, isWebUrl } from './click';
7
+ import { asImpressionId, httpRequest } from './http';
8
+ import type { Outbox } from './outbox';
9
+ import { uuidv4 } from './adapters';
10
+ import type { EthiclyAd, ImpressionId, Tracker } from './types';
11
+
12
+ export interface ServeContext {
13
+ publisherSiteId: number | null;
14
+ countryCode: string | null;
15
+ impressionToken: string | null;
16
+ }
17
+
18
+ export interface TrackerDeps {
19
+ ctx: BeaconContext;
20
+ ad: EthiclyAd;
21
+ serve: ServeContext;
22
+ viewableAfterMs: number;
23
+ flushIntervalS: number;
24
+ platform: string;
25
+ sdkVersion: string;
26
+ appVersion: string;
27
+ openUrl?: (url: string) => unknown;
28
+ /** Called once when the ad is shown, for the frequency caps. */
29
+ onShown(): void;
30
+ /** Keeps unsent beacons in storage so they survive the app being killed. */
31
+ outbox?: Outbox;
32
+ }
33
+
34
+ /** Doc "Still-image interstitials": /viewable after 1000 ms on screen. */
35
+ export const STILL_VIEWABLE_MS = 1000;
36
+
37
+ /**
38
+ * A wall-clock gap between two progress() calls longer than this breaks
39
+ * "continuous" playback: a host player that stops ticking while the app is in
40
+ * the background must not count the time it was away.
41
+ */
42
+ export const MAX_TICK_GAP_MS = 1500;
43
+
44
+ type VideoEvent = 'start' | 'q1' | 'q2' | 'q3' | 'complete' | 'skip' | 'error';
45
+ interface Queued { event: VideoEvent; ms: number | null }
46
+
47
+ interface Impression { id: ImpressionId; viewableToken: string | null; at: number }
48
+
49
+ export class InterstitialTracker implements Tracker {
50
+ /** Exposed for tests and debug logs. */
51
+ clientImpressionId: string | null = null;
52
+ impression: Impression | null = null;
53
+ /** True when the impression can never bill (doc lifecycle rule 5, or a refused beacon). */
54
+ unbillable = false;
55
+
56
+ private impressionDone: Promise<Impression | null> | null = null;
57
+ private viewableSent = false;
58
+ private continuousMs = 0;
59
+ /** viewable_ms as measured when the threshold was crossed. */
60
+ private viewableMs = 0;
61
+ private last: { pos: number; wall: number; visible: boolean } | null = null;
62
+ private sentOnce = new Set<VideoEvent>();
63
+ private queue: Queued[] = [];
64
+ private timer: ReturnType<typeof setTimeout> | null = null;
65
+ private isClosed = false;
66
+ private clickUrl: Promise<string> | null = null;
67
+ private pending = new Set<Promise<unknown>>();
68
+ private flushChain: Promise<void> = Promise.resolve();
69
+ private shownAt = 0;
70
+ /** The /impression body until it has an answer. */
71
+ private impressionBody: Record<string, unknown> | null = null;
72
+ /** viewable_ms of a /viewable not yet answered. */
73
+ private viewablePending: number | null = null;
74
+ /** Video events queued or in flight. */
75
+ private unsent: Queued[] = [];
76
+
77
+ constructor(private d: TrackerDeps) {}
78
+
79
+ private get isVideo(): boolean {
80
+ return this.d.ad.media.kind === 'video';
81
+ }
82
+
83
+ private track<T>(p: Promise<T>): Promise<T> {
84
+ this.pending.add(p);
85
+ p.finally(() => this.pending.delete(p)).catch(() => undefined);
86
+ return p;
87
+ }
88
+
89
+ /** Resolves when every beacon in flight has settled. For tests and shutdown. */
90
+ async settle(): Promise<void> {
91
+ while (this.pending.size) await Promise.all(Array.from(this.pending)).catch(() => undefined);
92
+ }
93
+
94
+ isExpired(): boolean {
95
+ return this.d.ctx.now() >= this.d.ad.expiresAt;
96
+ }
97
+
98
+ shown(size?: { width?: number; height?: number }): Promise<void> {
99
+ if (this.impressionDone) return this.impressionDone.then(() => undefined);
100
+ if (this.isExpired()) {
101
+ // Rule 4: an ad served more than token_ttl_s ago must not be shown.
102
+ this.d.ctx.log.error(`ad ${this.d.ad.id} expired before it was shown; load a new one`);
103
+ this.unbillable = true;
104
+ this.impressionDone = Promise.resolve(null);
105
+ return Promise.resolve();
106
+ }
107
+ try { this.d.onShown(); } catch { /* never throw */ }
108
+ // Rule 6: one client_impression_id per rendered ad, reused only for retries.
109
+ this.clientImpressionId = uuidv4();
110
+ this.shownAt = this.d.ctx.now();
111
+ this.impressionDone = this.track(this.sendImpression(size).catch((e) => {
112
+ this.d.ctx.log.error('impression failed', e);
113
+ this.unbillable = true;
114
+ this.persist();
115
+ return null;
116
+ }));
117
+ return this.impressionDone.then(() => undefined);
118
+ }
119
+
120
+ /**
121
+ * Mirror what this ad still owes the server into the outbox, or drop it
122
+ * there once nothing is owed. Never throws.
123
+ */
124
+ private persist(): void {
125
+ const ob = this.d.outbox;
126
+ const cid = this.clientImpressionId;
127
+ if (!ob || !cid) return;
128
+ try {
129
+ const imp = this.impression;
130
+ const owed = this.impressionBody !== null
131
+ || (imp !== null && (this.viewablePending !== null || this.unsent.length > 0));
132
+ if (this.unbillable || !owed) {
133
+ ob.remove(cid);
134
+ return;
135
+ }
136
+ ob.put({
137
+ cid,
138
+ shownAt: this.shownAt,
139
+ impression: this.impressionBody ?? undefined,
140
+ impressionId: imp?.id,
141
+ viewableToken: imp?.viewableToken,
142
+ viewableMs: this.viewablePending ?? undefined,
143
+ events: this.unsent.map((q) => ({ event: q.event, ms: q.ms })),
144
+ });
145
+ } catch (e) {
146
+ this.d.ctx.log.warn('could not record unsent beacons', e);
147
+ }
148
+ }
149
+
150
+ private async sendImpression(size?: { width?: number; height?: number }): Promise<Impression | null> {
151
+ const { ad, serve, ctx } = this.d;
152
+ const body: Record<string, unknown> = {
153
+ ad_id: ad.id,
154
+ client_impression_id: this.clientImpressionId,
155
+ platform: this.d.platform,
156
+ sdk_version: this.d.sdkVersion,
157
+ app_version: this.d.appVersion,
158
+ format_width: Math.round(size?.width ?? ad.media.width),
159
+ format_height: Math.round(size?.height ?? ad.media.height),
160
+ };
161
+ if (serve.publisherSiteId) body.publisher_site_id = serve.publisherSiteId;
162
+ if (serve.countryCode) body.country_code = serve.countryCode;
163
+ if (serve.impressionToken) body.impression_token = serve.impressionToken;
164
+ this.impressionBody = body;
165
+ this.persist();
166
+
167
+ // Rule 1: sent now, never queued. Rule 7: retry timeouts, 5xx and 429 with
168
+ // the same client_impression_id, give up after one hour.
169
+ const res = await sendWithRetry(ctx, 'impression', body, { deadline: this.shownAt + ONE_HOUR_MS });
170
+ this.impressionBody = null;
171
+ if (!res || res.status !== 200) {
172
+ this.unbillable = true;
173
+ if (res?.status === 422) ctx.log.error('impression rejected (422), not retried: integration bug', res.body);
174
+ else ctx.log.warn(`impression not recorded (${res ? res.status : 'deadline passed'})`);
175
+ this.queue = [];
176
+ this.unsent = [];
177
+ this.persist();
178
+ return null;
179
+ }
180
+ const id = asImpressionId(res.body?.impression_id);
181
+ if (!id) {
182
+ this.unbillable = true;
183
+ ctx.log.warn('impression answer had no impression_id', res.body);
184
+ this.persist();
185
+ return null;
186
+ }
187
+ const viewableToken = typeof res.body?.viewable_token === 'string' ? res.body.viewable_token : null;
188
+ if (res.body?.test === true) ctx.log.info(`test impression ${id}: nothing is stored or billed`);
189
+ if (res.body?.token_expired === true) ctx.log.warn('test token expired: in production this impression would not bill');
190
+ if (serve.impressionToken && !viewableToken) {
191
+ // Rule 5: token-enforced site, no viewable_token: cannot bill, do not retry.
192
+ this.unbillable = true;
193
+ ctx.log.warn('impression stored without viewable_token: it cannot bill');
194
+ }
195
+ this.impression = { id, viewableToken, at: ctx.now() };
196
+ this.persist();
197
+ if (this.viewableSent) this.track(this.sendViewable(this.viewableMs));
198
+ if (this.queue.length) void this.flush();
199
+ return this.impression;
200
+ }
201
+
202
+ progress(positionMs: number, opts: { visible: boolean; durationMs?: number }): void {
203
+ try {
204
+ if (!this.impressionDone || this.isClosed || !Number.isFinite(positionMs)) return;
205
+ const wall = this.d.ctx.now();
206
+ const visible = !!opts.visible;
207
+ const gap = this.last ? wall - this.last.wall : 0;
208
+ if (!visible || gap > MAX_TICK_GAP_MS) {
209
+ // Not on screen, or the player stopped reporting for a while (app in
210
+ // the background): the continuous count starts again.
211
+ this.continuousMs = 0;
212
+ } else if (this.last && this.last.visible) {
213
+ const delta = positionMs - this.last.pos;
214
+ // Count real playback only: a seek forward cannot count for more than
215
+ // the wall-clock time that passed.
216
+ if (delta > 0) this.continuousMs += Math.min(delta, gap);
217
+ }
218
+ this.last = { pos: positionMs, wall, visible };
219
+
220
+ const threshold = this.isVideo ? this.d.viewableAfterMs : STILL_VIEWABLE_MS;
221
+ if (visible && !this.viewableSent && this.continuousMs >= threshold) {
222
+ // Rule 2: sent as soon as the threshold is met.
223
+ this.viewableSent = true;
224
+ this.viewableMs = this.continuousMs;
225
+ this.viewablePending = this.viewableMs;
226
+ this.persist();
227
+ if (this.impression) this.track(this.sendViewable(this.viewableMs));
228
+ }
229
+
230
+ if (!this.isVideo) return;
231
+ if (visible) this.enqueueOnce('start', Math.max(0, Math.round(positionMs)));
232
+ const duration = this.d.ad.media.durationMs ?? (opts.durationMs && opts.durationMs > 0 ? opts.durationMs : null);
233
+ if (duration) {
234
+ (['q1', 'q2', 'q3'] as const).forEach((q, i) => {
235
+ if (positionMs >= (duration * (i + 1)) / 4) this.enqueueOnce(q, Math.round(positionMs));
236
+ });
237
+ }
238
+ } catch (e) {
239
+ this.d.ctx.log.error('progress failed', e);
240
+ }
241
+ }
242
+
243
+ private async sendViewable(viewableMs: number): Promise<void> {
244
+ const imp = this.impression;
245
+ if (!imp || this.unbillable) return;
246
+ const deadline = imp.at + ONE_HOUR_MS;
247
+ try {
248
+ if (this.d.ctx.now() > deadline) return; // rule 4: drop, do not send
249
+ const body: Record<string, unknown> = { impression_id: imp.id, viewable_ms: Math.round(viewableMs) };
250
+ if (imp.viewableToken) body.viewable_token = imp.viewableToken;
251
+ await sendWithRetry(this.d.ctx, 'viewable', body, { deadline });
252
+ } finally {
253
+ this.viewablePending = null;
254
+ this.persist();
255
+ }
256
+ }
257
+
258
+ private enqueueOnce(event: VideoEvent, ms: number | null): void {
259
+ if (this.sentOnce.has(event)) return;
260
+ this.sentOnce.add(event);
261
+ const q = { event, ms };
262
+ this.queue.push(q);
263
+ this.unsent.push(q);
264
+ this.persist();
265
+ // Rule 3: reporting may wait up to flush_interval_s. The timer only runs
266
+ // while something is queued.
267
+ if (!this.timer && !this.isClosed) {
268
+ this.timer = setTimeout(() => { this.timer = null; void this.flush(); }, this.d.flushIntervalS * 1000);
269
+ }
270
+ }
271
+
272
+ complete(): void {
273
+ if (!this.isVideo || this.isClosed) return;
274
+ this.enqueueOnce('complete', this.d.ad.media.durationMs);
275
+ void this.flush();
276
+ }
277
+
278
+ skipped(positionMs: number): void {
279
+ if (!this.isVideo || this.isClosed) return;
280
+ this.enqueueOnce('skip', Number.isFinite(positionMs) ? Math.max(0, Math.round(positionMs)) : null);
281
+ void this.flush();
282
+ }
283
+
284
+ error(): void {
285
+ if (!this.isVideo || this.isClosed) return;
286
+ this.enqueueOnce('error', null);
287
+ void this.flush();
288
+ }
289
+
290
+ /** Send every queued video event, one request each (there is no batch route). */
291
+ flush(): Promise<void> {
292
+ if (this.timer) clearTimeout(this.timer);
293
+ this.timer = null;
294
+ const imp = this.impression;
295
+ if (!imp) return Promise.resolve(); // sent when /impression resolves
296
+ if (this.unbillable || this.d.ctx.now() > imp.at + ONE_HOUR_MS) {
297
+ this.queue = []; // ignored by the server, and rule 4 says drop
298
+ this.unsent = [];
299
+ this.persist();
300
+ return Promise.resolve();
301
+ }
302
+ const batch = this.queue.splice(0);
303
+ const deadline = imp.at + ONE_HOUR_MS;
304
+ // The server accepts any order, but sending in order keeps reports and
305
+ // logs readable, so flushes run one after another.
306
+ this.flushChain = this.flushChain.then(async () => {
307
+ for (const q of batch) {
308
+ const body: Record<string, unknown> = { impression_id: imp.id, event: q.event };
309
+ if (q.ms !== null && q.ms !== undefined) body.ms = q.ms;
310
+ if (imp.viewableToken) body.viewable_token = imp.viewableToken;
311
+ await sendWithRetry(this.d.ctx, 'video-event', body, { deadline });
312
+ this.unsent = this.unsent.filter((u) => u !== q);
313
+ this.persist();
314
+ }
315
+ }).catch((e) => this.d.ctx.log.error('video event flush failed', e));
316
+ return this.track(this.flushChain);
317
+ }
318
+
319
+ clicked(): Promise<string> {
320
+ if (!this.clickUrl) this.clickUrl = this.resolveClickUrl().catch(() => this.d.ad.destinationUrl);
321
+ return this.clickUrl.then(async (url) => {
322
+ // The client already refuses such an ad; this guards a hand-built EthiclyAd.
323
+ if (!isWebUrl(url)) {
324
+ this.d.ctx.log.error(`ad ${this.d.ad.id}: destination is not an http(s) URL, not opened`);
325
+ return url;
326
+ }
327
+ try {
328
+ if (this.d.openUrl) await this.d.openUrl(url);
329
+ else this.d.ctx.log.warn('no openUrl adapter: the host must open the returned URL');
330
+ } catch (e) {
331
+ this.d.ctx.log.error('openUrl failed', e);
332
+ }
333
+ return url;
334
+ });
335
+ }
336
+
337
+ private async resolveClickUrl(): Promise<string> {
338
+ const { ad, serve, ctx } = this.d;
339
+ const dest = ad.destinationUrl;
340
+ const deadline = ctx.now() + CLICK_TIMEOUT_MS;
341
+ // The impression_id is required. If /impression is still in flight, wait
342
+ // for it inside the same 500 ms budget.
343
+ const imp = this.impression ?? (this.impressionDone
344
+ ? await Promise.race([this.impressionDone, new Promise<null>((r) => setTimeout(() => r(null), CLICK_TIMEOUT_MS))])
345
+ : null);
346
+ if (!imp) {
347
+ ctx.log.warn('click before an impression_id was known: opening without a click beacon');
348
+ return dest;
349
+ }
350
+ if (this.unbillable) return dest;
351
+ if (ctx.gate.waitMs('click') > 0) return dest;
352
+ const remaining = Math.max(1, Math.min(CLICK_TIMEOUT_MS, deadline - ctx.now()));
353
+ const body: Record<string, unknown> = { ad_id: ad.id, impression_id: imp.id };
354
+ if (serve.publisherSiteId) body.publisher_site_id = serve.publisherSiteId;
355
+ if (serve.countryCode) body.country_code = serve.countryCode;
356
+ // Never retried: one request, whatever happens.
357
+ const res = await httpRequest(ctx.fetch, `${ctx.serveBase()}/click`, {
358
+ method: 'POST', headers: ctx.headers(), body, timeoutMs: Math.min(remaining, BEACON_TIMEOUT_MS),
359
+ });
360
+ if (res.status === 429) ctx.gate.block('click', res.retryAfterS);
361
+ const token = res.status === 200 && typeof res.body?.click_token === 'string' ? res.body.click_token : null;
362
+ return appendClickToken(dest, token);
363
+ }
364
+
365
+ async closed(): Promise<void> {
366
+ if (this.isClosed) return;
367
+ this.isClosed = true;
368
+ try {
369
+ // Step 8: send any video event still queued (after /impression resolves).
370
+ if (this.impressionDone) await this.impressionDone;
371
+ await this.flush();
372
+ } catch (e) {
373
+ this.d.ctx.log.error('close flush failed', e);
374
+ }
375
+ }
376
+ }
@@ -0,0 +1,185 @@
1
+ // Public and wire types for the headless core. Wire names (snake_case) follow
2
+ // docs/APP_API_V1.md; public names are camelCase.
3
+
4
+ export type Platform = 'ios' | 'android';
5
+ export type AudioPolicy = 'none' | 'optional' | 'on';
6
+
7
+ /** The /config body (doc "GET /config"). Unknown fields are ignored. */
8
+ export interface EthiclyConfig {
9
+ enabled: boolean;
10
+ min_sdk: { ios: string; android: string };
11
+ formats: string[];
12
+ interstitial: {
13
+ skip_after_ms: number;
14
+ max_per_session: number;
15
+ min_gap_s: number;
16
+ audio: AudioPolicy;
17
+ };
18
+ prefetch: { max_cached_creatives: number; max_cache_mb: number };
19
+ beacon: { viewable_after_ms: number; flush_interval_s: number };
20
+ endpoints: { serve: string };
21
+ }
22
+
23
+ /** AsyncStorage-shaped key-value store. */
24
+ export interface KeyValueStorage {
25
+ getItem(key: string): Promise<string | null>;
26
+ setItem(key: string, value: string): Promise<void>;
27
+ removeItem?(key: string): Promise<void>;
28
+ }
29
+
30
+ /** expo-file-system-shaped creative store. */
31
+ export interface FileCacheAdapter {
32
+ /**
33
+ * Download `url` into the cache under `fileName`; resolve the local uri.
34
+ * Should abort (reject, leaving no file) once more than `maxBytes` would be written.
35
+ */
36
+ download(url: string, fileName: string, opts?: { maxBytes?: number }): Promise<{ uri: string; bytes?: number }>;
37
+ exists(uri: string): Promise<boolean>;
38
+ delete(uri: string): Promise<void>;
39
+ /** Size in bytes, 0 when unknown. */
40
+ size(uri: string): Promise<number>;
41
+ /** Every file in the SDK's cache directory. Lets the cache sweep files it no longer indexes. */
42
+ list?(): Promise<string[]>;
43
+ /** The uri `download(url, fileName)` writes to, so an unfinished download can be deleted. */
44
+ uriFor?(fileName: string): string;
45
+ /**
46
+ * Abort every download in flight: each rejects and leaves no file. Optional;
47
+ * used by setAdsEnabled(false) and for a download that takes too long.
48
+ */
49
+ cancel?(): void;
50
+ }
51
+
52
+ export interface Logger {
53
+ debug?(message: string, ...rest: unknown[]): void;
54
+ info?(message: string, ...rest: unknown[]): void;
55
+ warn?(message: string, ...rest: unknown[]): void;
56
+ error?(message: string, ...rest: unknown[]): void;
57
+ }
58
+
59
+ /** The subset of a fetch Response the SDK reads. */
60
+ export interface ResponseLike {
61
+ status: number;
62
+ headers: { get(name: string): string | null };
63
+ text(): Promise<string>;
64
+ }
65
+
66
+ export interface RequestInitLike {
67
+ method?: string;
68
+ headers?: Record<string, string>;
69
+ body?: string;
70
+ signal?: unknown;
71
+ }
72
+
73
+ export type FetchLike = (url: string, init?: RequestInitLike) => Promise<ResponseLike>;
74
+
75
+ /** 64-bit impression id. A string when the value is beyond 2^53. */
76
+ export type ImpressionId = number | string;
77
+
78
+ /** Server no-ad reasons (doc "No-ad responses") plus the SDK's own. */
79
+ export type NoFillReason =
80
+ | 'publisher_not_approved'
81
+ | 'publisher_paused'
82
+ | 'publisher_blackout'
83
+ | 'app_disabled'
84
+ | 'sdk_unsupported'
85
+ | 'interstitial_disabled'
86
+ | 'classic_disabled'
87
+ | 'no_approved_ads'
88
+ | 'ads_query_error'
89
+ | 'no_matching_ad'
90
+ | 'publisher_mix'
91
+ | 'test_unavailable'
92
+ // SDK-side reasons
93
+ | 'ads_disabled'
94
+ | 'frequency_capped'
95
+ | 'unknown_key'
96
+ | 'invalid_key'
97
+ | 'rate_limited'
98
+ | 'network_error'
99
+ | 'server_error'
100
+ | 'invalid_response'
101
+ | (string & {});
102
+
103
+ export interface EthiclyAdMedia {
104
+ kind: 'video' | 'image';
105
+ /** The file to show: local file when cached, else the remote URL. */
106
+ uri: string;
107
+ /** Same as `uri` for a video, null for a still. */
108
+ videoUri: string | null;
109
+ /** Local or remote poster, null when the ad has none. */
110
+ posterUri: string | null;
111
+ durationMs: number | null;
112
+ mime: string | null;
113
+ width: number;
114
+ height: number;
115
+ /** True when `uri` points at a local cached file. */
116
+ cached: boolean;
117
+ }
118
+
119
+ export interface EthiclyAd {
120
+ id: number;
121
+ /** Button text: ad.cta_label, or "Learn more" when the server sends none. */
122
+ ctaLabel: string;
123
+ destinationUrl: string;
124
+ /** When the skip control may appear. The ad's value wins over /config. */
125
+ skipAfterMs: number;
126
+ media: EthiclyAdMedia;
127
+ /** interstitial.audio from /config. */
128
+ audio: AudioPolicy;
129
+ title: string | null;
130
+ /** True for a test-mode serve: nothing is stored or billed. */
131
+ test: boolean;
132
+ /** Epoch ms when the serve response arrived. */
133
+ servedAt: number;
134
+ /** Epoch ms after which the ad must not be shown (served + token_ttl_s). */
135
+ expiresAt: number;
136
+ }
137
+
138
+ export interface Tracker {
139
+ /** Call the moment the ad is rendered. Sends /impression immediately. */
140
+ shown(size?: { width?: number; height?: number }): Promise<void>;
141
+ /** Call on every player time update. */
142
+ progress(positionMs: number, opts: { visible: boolean; durationMs?: number }): void;
143
+ complete(): void;
144
+ skipped(positionMs: number): void;
145
+ error(): void;
146
+ /** POST /click (500 ms budget), then open the destination. Resolves with the URL opened. */
147
+ clicked(): Promise<string>;
148
+ /** Call when the ad screen goes away. Sends queued video events. */
149
+ closed(): Promise<void>;
150
+ /** True once the ad is older than token_ttl_s: it must not be shown. */
151
+ isExpired(): boolean;
152
+ }
153
+
154
+ export type InterstitialResult =
155
+ | { ad: EthiclyAd; tracker: Tracker; reason?: undefined }
156
+ | { ad: null; tracker: null; reason: NoFillReason };
157
+
158
+ /** Raw serve-response ad (only the fields the SDK reads). */
159
+ export interface WireAd {
160
+ id: number;
161
+ title?: string | null;
162
+ destination_url?: string | null;
163
+ skip_after_ms?: number | null;
164
+ cta_label?: string | null;
165
+ media?: {
166
+ kind?: string;
167
+ url?: string | null;
168
+ poster_url?: string | null;
169
+ duration_ms?: number | null;
170
+ width?: number | null;
171
+ height?: number | null;
172
+ mime?: string | null;
173
+ } | null;
174
+ }
175
+
176
+ export interface WireServe {
177
+ ad: WireAd | null;
178
+ reason?: string;
179
+ publisher_site_id?: number;
180
+ country_code?: string;
181
+ impression_token?: string;
182
+ token_ttl_s?: number;
183
+ test?: boolean;
184
+ request_id?: string;
185
+ }
package/src/index.ts ADDED
@@ -0,0 +1,5 @@
1
+ // @ethicly/react-native: the headless core and the React hook. The ready-made
2
+ // screen, which needs expo-video, is at '@ethicly/react-native/interstitial'.
3
+ export * from './core';
4
+ export { useEthiclyInterstitial } from './react/useEthiclyInterstitial';
5
+ export type { EthiclyInterstitialState, UseEthiclyInterstitialOptions } from './react/useEthiclyInterstitial';
@@ -0,0 +1,4 @@
1
+ // Optional ready-made fullscreen screen. Importing this entry needs expo-video;
2
+ // the main entry does not.
3
+ export { EthiclyInterstitial } from './react/EthiclyInterstitial';
4
+ export type { EthiclyInsets, EthiclyInterstitialProps } from './react/EthiclyInterstitial';