@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,375 @@
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
+ import { BEACON_TIMEOUT_MS, ONE_HOUR_MS, sendWithRetry } from './beacons';
5
+ import { appendClickToken, CLICK_TIMEOUT_MS, isWebUrl } from './click';
6
+ import { asImpressionId, httpRequest } from './http';
7
+ import { uuidv4 } from './adapters';
8
+ /** Doc "Still-image interstitials": /viewable after 1000 ms on screen. */
9
+ export const STILL_VIEWABLE_MS = 1000;
10
+ /**
11
+ * A wall-clock gap between two progress() calls longer than this breaks
12
+ * "continuous" playback: a host player that stops ticking while the app is in
13
+ * the background must not count the time it was away.
14
+ */
15
+ export const MAX_TICK_GAP_MS = 1500;
16
+ export class InterstitialTracker {
17
+ constructor(d) {
18
+ this.d = d;
19
+ /** Exposed for tests and debug logs. */
20
+ this.clientImpressionId = null;
21
+ this.impression = null;
22
+ /** True when the impression can never bill (doc lifecycle rule 5, or a refused beacon). */
23
+ this.unbillable = false;
24
+ this.impressionDone = null;
25
+ this.viewableSent = false;
26
+ this.continuousMs = 0;
27
+ /** viewable_ms as measured when the threshold was crossed. */
28
+ this.viewableMs = 0;
29
+ this.last = null;
30
+ this.sentOnce = new Set();
31
+ this.queue = [];
32
+ this.timer = null;
33
+ this.isClosed = false;
34
+ this.clickUrl = null;
35
+ this.pending = new Set();
36
+ this.flushChain = Promise.resolve();
37
+ this.shownAt = 0;
38
+ /** The /impression body until it has an answer. */
39
+ this.impressionBody = null;
40
+ /** viewable_ms of a /viewable not yet answered. */
41
+ this.viewablePending = null;
42
+ /** Video events queued or in flight. */
43
+ this.unsent = [];
44
+ }
45
+ get isVideo() {
46
+ return this.d.ad.media.kind === 'video';
47
+ }
48
+ track(p) {
49
+ this.pending.add(p);
50
+ p.finally(() => this.pending.delete(p)).catch(() => undefined);
51
+ return p;
52
+ }
53
+ /** Resolves when every beacon in flight has settled. For tests and shutdown. */
54
+ async settle() {
55
+ while (this.pending.size)
56
+ await Promise.all(Array.from(this.pending)).catch(() => undefined);
57
+ }
58
+ isExpired() {
59
+ return this.d.ctx.now() >= this.d.ad.expiresAt;
60
+ }
61
+ shown(size) {
62
+ if (this.impressionDone)
63
+ return this.impressionDone.then(() => undefined);
64
+ if (this.isExpired()) {
65
+ // Rule 4: an ad served more than token_ttl_s ago must not be shown.
66
+ this.d.ctx.log.error(`ad ${this.d.ad.id} expired before it was shown; load a new one`);
67
+ this.unbillable = true;
68
+ this.impressionDone = Promise.resolve(null);
69
+ return Promise.resolve();
70
+ }
71
+ try {
72
+ this.d.onShown();
73
+ }
74
+ catch { /* never throw */ }
75
+ // Rule 6: one client_impression_id per rendered ad, reused only for retries.
76
+ this.clientImpressionId = uuidv4();
77
+ this.shownAt = this.d.ctx.now();
78
+ this.impressionDone = this.track(this.sendImpression(size).catch((e) => {
79
+ this.d.ctx.log.error('impression failed', e);
80
+ this.unbillable = true;
81
+ this.persist();
82
+ return null;
83
+ }));
84
+ return this.impressionDone.then(() => undefined);
85
+ }
86
+ /**
87
+ * Mirror what this ad still owes the server into the outbox, or drop it
88
+ * there once nothing is owed. Never throws.
89
+ */
90
+ persist() {
91
+ var _a, _b;
92
+ const ob = this.d.outbox;
93
+ const cid = this.clientImpressionId;
94
+ if (!ob || !cid)
95
+ return;
96
+ try {
97
+ const imp = this.impression;
98
+ const owed = this.impressionBody !== null
99
+ || (imp !== null && (this.viewablePending !== null || this.unsent.length > 0));
100
+ if (this.unbillable || !owed) {
101
+ ob.remove(cid);
102
+ return;
103
+ }
104
+ ob.put({
105
+ cid,
106
+ shownAt: this.shownAt,
107
+ impression: (_a = this.impressionBody) !== null && _a !== void 0 ? _a : undefined,
108
+ impressionId: imp === null || imp === void 0 ? void 0 : imp.id,
109
+ viewableToken: imp === null || imp === void 0 ? void 0 : imp.viewableToken,
110
+ viewableMs: (_b = this.viewablePending) !== null && _b !== void 0 ? _b : undefined,
111
+ events: this.unsent.map((q) => ({ event: q.event, ms: q.ms })),
112
+ });
113
+ }
114
+ catch (e) {
115
+ this.d.ctx.log.warn('could not record unsent beacons', e);
116
+ }
117
+ }
118
+ async sendImpression(size) {
119
+ var _a, _b, _c, _d, _e, _f;
120
+ const { ad, serve, ctx } = this.d;
121
+ const body = {
122
+ ad_id: ad.id,
123
+ client_impression_id: this.clientImpressionId,
124
+ platform: this.d.platform,
125
+ sdk_version: this.d.sdkVersion,
126
+ app_version: this.d.appVersion,
127
+ format_width: Math.round((_a = size === null || size === void 0 ? void 0 : size.width) !== null && _a !== void 0 ? _a : ad.media.width),
128
+ format_height: Math.round((_b = size === null || size === void 0 ? void 0 : size.height) !== null && _b !== void 0 ? _b : ad.media.height),
129
+ };
130
+ if (serve.publisherSiteId)
131
+ body.publisher_site_id = serve.publisherSiteId;
132
+ if (serve.countryCode)
133
+ body.country_code = serve.countryCode;
134
+ if (serve.impressionToken)
135
+ body.impression_token = serve.impressionToken;
136
+ this.impressionBody = body;
137
+ this.persist();
138
+ // Rule 1: sent now, never queued. Rule 7: retry timeouts, 5xx and 429 with
139
+ // the same client_impression_id, give up after one hour.
140
+ const res = await sendWithRetry(ctx, 'impression', body, { deadline: this.shownAt + ONE_HOUR_MS });
141
+ this.impressionBody = null;
142
+ if (!res || res.status !== 200) {
143
+ this.unbillable = true;
144
+ if ((res === null || res === void 0 ? void 0 : res.status) === 422)
145
+ ctx.log.error('impression rejected (422), not retried: integration bug', res.body);
146
+ else
147
+ ctx.log.warn(`impression not recorded (${res ? res.status : 'deadline passed'})`);
148
+ this.queue = [];
149
+ this.unsent = [];
150
+ this.persist();
151
+ return null;
152
+ }
153
+ const id = asImpressionId((_c = res.body) === null || _c === void 0 ? void 0 : _c.impression_id);
154
+ if (!id) {
155
+ this.unbillable = true;
156
+ ctx.log.warn('impression answer had no impression_id', res.body);
157
+ this.persist();
158
+ return null;
159
+ }
160
+ const viewableToken = typeof ((_d = res.body) === null || _d === void 0 ? void 0 : _d.viewable_token) === 'string' ? res.body.viewable_token : null;
161
+ if (((_e = res.body) === null || _e === void 0 ? void 0 : _e.test) === true)
162
+ ctx.log.info(`test impression ${id}: nothing is stored or billed`);
163
+ if (((_f = res.body) === null || _f === void 0 ? void 0 : _f.token_expired) === true)
164
+ ctx.log.warn('test token expired: in production this impression would not bill');
165
+ if (serve.impressionToken && !viewableToken) {
166
+ // Rule 5: token-enforced site, no viewable_token: cannot bill, do not retry.
167
+ this.unbillable = true;
168
+ ctx.log.warn('impression stored without viewable_token: it cannot bill');
169
+ }
170
+ this.impression = { id, viewableToken, at: ctx.now() };
171
+ this.persist();
172
+ if (this.viewableSent)
173
+ this.track(this.sendViewable(this.viewableMs));
174
+ if (this.queue.length)
175
+ void this.flush();
176
+ return this.impression;
177
+ }
178
+ progress(positionMs, opts) {
179
+ var _a;
180
+ try {
181
+ if (!this.impressionDone || this.isClosed || !Number.isFinite(positionMs))
182
+ return;
183
+ const wall = this.d.ctx.now();
184
+ const visible = !!opts.visible;
185
+ const gap = this.last ? wall - this.last.wall : 0;
186
+ if (!visible || gap > MAX_TICK_GAP_MS) {
187
+ // Not on screen, or the player stopped reporting for a while (app in
188
+ // the background): the continuous count starts again.
189
+ this.continuousMs = 0;
190
+ }
191
+ else if (this.last && this.last.visible) {
192
+ const delta = positionMs - this.last.pos;
193
+ // Count real playback only: a seek forward cannot count for more than
194
+ // the wall-clock time that passed.
195
+ if (delta > 0)
196
+ this.continuousMs += Math.min(delta, gap);
197
+ }
198
+ this.last = { pos: positionMs, wall, visible };
199
+ const threshold = this.isVideo ? this.d.viewableAfterMs : STILL_VIEWABLE_MS;
200
+ if (visible && !this.viewableSent && this.continuousMs >= threshold) {
201
+ // Rule 2: sent as soon as the threshold is met.
202
+ this.viewableSent = true;
203
+ this.viewableMs = this.continuousMs;
204
+ this.viewablePending = this.viewableMs;
205
+ this.persist();
206
+ if (this.impression)
207
+ this.track(this.sendViewable(this.viewableMs));
208
+ }
209
+ if (!this.isVideo)
210
+ return;
211
+ if (visible)
212
+ this.enqueueOnce('start', Math.max(0, Math.round(positionMs)));
213
+ const duration = (_a = this.d.ad.media.durationMs) !== null && _a !== void 0 ? _a : (opts.durationMs && opts.durationMs > 0 ? opts.durationMs : null);
214
+ if (duration) {
215
+ ['q1', 'q2', 'q3'].forEach((q, i) => {
216
+ if (positionMs >= (duration * (i + 1)) / 4)
217
+ this.enqueueOnce(q, Math.round(positionMs));
218
+ });
219
+ }
220
+ }
221
+ catch (e) {
222
+ this.d.ctx.log.error('progress failed', e);
223
+ }
224
+ }
225
+ async sendViewable(viewableMs) {
226
+ const imp = this.impression;
227
+ if (!imp || this.unbillable)
228
+ return;
229
+ const deadline = imp.at + ONE_HOUR_MS;
230
+ try {
231
+ if (this.d.ctx.now() > deadline)
232
+ return; // rule 4: drop, do not send
233
+ const body = { impression_id: imp.id, viewable_ms: Math.round(viewableMs) };
234
+ if (imp.viewableToken)
235
+ body.viewable_token = imp.viewableToken;
236
+ await sendWithRetry(this.d.ctx, 'viewable', body, { deadline });
237
+ }
238
+ finally {
239
+ this.viewablePending = null;
240
+ this.persist();
241
+ }
242
+ }
243
+ enqueueOnce(event, ms) {
244
+ if (this.sentOnce.has(event))
245
+ return;
246
+ this.sentOnce.add(event);
247
+ const q = { event, ms };
248
+ this.queue.push(q);
249
+ this.unsent.push(q);
250
+ this.persist();
251
+ // Rule 3: reporting may wait up to flush_interval_s. The timer only runs
252
+ // while something is queued.
253
+ if (!this.timer && !this.isClosed) {
254
+ this.timer = setTimeout(() => { this.timer = null; void this.flush(); }, this.d.flushIntervalS * 1000);
255
+ }
256
+ }
257
+ complete() {
258
+ if (!this.isVideo || this.isClosed)
259
+ return;
260
+ this.enqueueOnce('complete', this.d.ad.media.durationMs);
261
+ void this.flush();
262
+ }
263
+ skipped(positionMs) {
264
+ if (!this.isVideo || this.isClosed)
265
+ return;
266
+ this.enqueueOnce('skip', Number.isFinite(positionMs) ? Math.max(0, Math.round(positionMs)) : null);
267
+ void this.flush();
268
+ }
269
+ error() {
270
+ if (!this.isVideo || this.isClosed)
271
+ return;
272
+ this.enqueueOnce('error', null);
273
+ void this.flush();
274
+ }
275
+ /** Send every queued video event, one request each (there is no batch route). */
276
+ flush() {
277
+ if (this.timer)
278
+ clearTimeout(this.timer);
279
+ this.timer = null;
280
+ const imp = this.impression;
281
+ if (!imp)
282
+ return Promise.resolve(); // sent when /impression resolves
283
+ if (this.unbillable || this.d.ctx.now() > imp.at + ONE_HOUR_MS) {
284
+ this.queue = []; // ignored by the server, and rule 4 says drop
285
+ this.unsent = [];
286
+ this.persist();
287
+ return Promise.resolve();
288
+ }
289
+ const batch = this.queue.splice(0);
290
+ const deadline = imp.at + ONE_HOUR_MS;
291
+ // The server accepts any order, but sending in order keeps reports and
292
+ // logs readable, so flushes run one after another.
293
+ this.flushChain = this.flushChain.then(async () => {
294
+ for (const q of batch) {
295
+ const body = { impression_id: imp.id, event: q.event };
296
+ if (q.ms !== null && q.ms !== undefined)
297
+ body.ms = q.ms;
298
+ if (imp.viewableToken)
299
+ body.viewable_token = imp.viewableToken;
300
+ await sendWithRetry(this.d.ctx, 'video-event', body, { deadline });
301
+ this.unsent = this.unsent.filter((u) => u !== q);
302
+ this.persist();
303
+ }
304
+ }).catch((e) => this.d.ctx.log.error('video event flush failed', e));
305
+ return this.track(this.flushChain);
306
+ }
307
+ clicked() {
308
+ if (!this.clickUrl)
309
+ this.clickUrl = this.resolveClickUrl().catch(() => this.d.ad.destinationUrl);
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
+ }
316
+ try {
317
+ if (this.d.openUrl)
318
+ await this.d.openUrl(url);
319
+ else
320
+ this.d.ctx.log.warn('no openUrl adapter: the host must open the returned URL');
321
+ }
322
+ catch (e) {
323
+ this.d.ctx.log.error('openUrl failed', e);
324
+ }
325
+ return url;
326
+ });
327
+ }
328
+ async resolveClickUrl() {
329
+ var _a, _b;
330
+ const { ad, serve, ctx } = this.d;
331
+ const dest = ad.destinationUrl;
332
+ const deadline = ctx.now() + CLICK_TIMEOUT_MS;
333
+ // The impression_id is required. If /impression is still in flight, wait
334
+ // for it inside the same 500 ms budget.
335
+ const imp = (_a = this.impression) !== null && _a !== void 0 ? _a : (this.impressionDone
336
+ ? await Promise.race([this.impressionDone, new Promise((r) => setTimeout(() => r(null), CLICK_TIMEOUT_MS))])
337
+ : null);
338
+ if (!imp) {
339
+ ctx.log.warn('click before an impression_id was known: opening without a click beacon');
340
+ return dest;
341
+ }
342
+ if (this.unbillable)
343
+ return dest;
344
+ if (ctx.gate.waitMs('click') > 0)
345
+ return dest;
346
+ const remaining = Math.max(1, Math.min(CLICK_TIMEOUT_MS, deadline - ctx.now()));
347
+ const body = { ad_id: ad.id, impression_id: imp.id };
348
+ if (serve.publisherSiteId)
349
+ body.publisher_site_id = serve.publisherSiteId;
350
+ if (serve.countryCode)
351
+ body.country_code = serve.countryCode;
352
+ // Never retried: one request, whatever happens.
353
+ const res = await httpRequest(ctx.fetch, `${ctx.serveBase()}/click`, {
354
+ method: 'POST', headers: ctx.headers(), body, timeoutMs: Math.min(remaining, BEACON_TIMEOUT_MS),
355
+ });
356
+ if (res.status === 429)
357
+ ctx.gate.block('click', res.retryAfterS);
358
+ const token = res.status === 200 && typeof ((_b = res.body) === null || _b === void 0 ? void 0 : _b.click_token) === 'string' ? res.body.click_token : null;
359
+ return appendClickToken(dest, token);
360
+ }
361
+ async closed() {
362
+ if (this.isClosed)
363
+ return;
364
+ this.isClosed = true;
365
+ try {
366
+ // Step 8: send any video event still queued (after /impression resolves).
367
+ if (this.impressionDone)
368
+ await this.impressionDone;
369
+ await this.flush();
370
+ }
371
+ catch (e) {
372
+ this.d.ctx.log.error('close flush failed', e);
373
+ }
374
+ }
375
+ }
@@ -0,0 +1,3 @@
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
+ export {};
@@ -0,0 +1,4 @@
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';
@@ -0,0 +1,3 @@
1
+ // Optional ready-made fullscreen screen. Importing this entry needs expo-video;
2
+ // the main entry does not.
3
+ export { EthiclyInterstitial } from './react/EthiclyInterstitial';