@ethicly/react-native 0.0.0-stage → 0.2.0

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 +75 -0
  2. package/LICENSE +21 -0
  3. package/README.md +313 -2
  4. package/core/package.json +6 -0
  5. package/interstitial/package.json +6 -0
  6. package/lib/commonjs/core/adapters.js +287 -0
  7. package/lib/commonjs/core/beacons.js +70 -0
  8. package/lib/commonjs/core/cache.js +206 -0
  9. package/lib/commonjs/core/click.js +19 -0
  10. package/lib/commonjs/core/client.js +489 -0
  11. package/lib/commonjs/core/config.js +113 -0
  12. package/lib/commonjs/core/http.js +115 -0
  13. package/lib/commonjs/core/index.js +20 -0
  14. package/lib/commonjs/core/outbox.js +192 -0
  15. package/lib/commonjs/core/tracker.js +374 -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 +286 -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 +276 -0
  23. package/lib/module/core/beacons.js +64 -0
  24. package/lib/module/core/cache.js +202 -0
  25. package/lib/module/core/click.js +15 -0
  26. package/lib/module/core/client.js +485 -0
  27. package/lib/module/core/config.js +104 -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 +370 -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 +260 -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 +138 -0
  39. package/lib/typescript/core/beacons.d.ts +32 -0
  40. package/lib/typescript/core/cache.d.ts +53 -0
  41. package/lib/typescript/core/click.d.ts +8 -0
  42. package/lib/typescript/core/client.d.ts +58 -0
  43. package/lib/typescript/core/config.d.ts +24 -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 +170 -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 +39 -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 +337 -0
  56. package/src/core/beacons.ts +81 -0
  57. package/src/core/cache.ts +216 -0
  58. package/src/core/click.ts +16 -0
  59. package/src/core/client.ts +547 -0
  60. package/src/core/config.ts +111 -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 +371 -0
  65. package/src/core/types.ts +180 -0
  66. package/src/index.ts +5 -0
  67. package/src/interstitial.ts +4 -0
  68. package/src/react/EthiclyInterstitial.tsx +386 -0
  69. package/src/react/useEthiclyInterstitial.ts +74 -0
  70. package/src/version.ts +2 -0
@@ -0,0 +1,115 @@
1
+ "use strict";
2
+ // One HTTP request with a timeout, JSON that keeps 64-bit impression ids exact,
3
+ // and the per-route 429 gate (doc "Rules that hold for every route").
4
+ Object.defineProperty(exports, "__esModule", { value: true });
5
+ exports.RouteGate = void 0;
6
+ exports.parseJson = parseJson;
7
+ exports.stringifyJson = stringifyJson;
8
+ exports.asImpressionId = asImpressionId;
9
+ exports.parseRetryAfter = parseRetryAfter;
10
+ exports.httpRequest = httpRequest;
11
+ exports.sleep = sleep;
12
+ /**
13
+ * impression_id is a 64-bit integer. JSON.parse would round anything above
14
+ * 2^53, so long ids are read as strings and written back as bare numbers.
15
+ */
16
+ function parseJson(text) {
17
+ return JSON.parse(text.replace(/("impression_id"\s*:\s*)(\d{16,})/g, '$1"$2"'));
18
+ }
19
+ function stringifyJson(value) {
20
+ return JSON.stringify(value).replace(/("impression_id":)"(\d+)"/g, '$1$2');
21
+ }
22
+ function asImpressionId(v) {
23
+ if (typeof v === 'number' && Number.isInteger(v) && v > 0)
24
+ return v;
25
+ if (typeof v === 'string' && /^\d+$/.test(v) && !/^0+$/.test(v)) {
26
+ const n = Number(v);
27
+ return Number.isSafeInteger(n) ? n : v;
28
+ }
29
+ return null;
30
+ }
31
+ function parseRetryAfter(v) {
32
+ if (!v)
33
+ return null;
34
+ const n = Number(v.trim());
35
+ if (Number.isFinite(n) && n >= 0)
36
+ return n;
37
+ const date = Date.parse(v);
38
+ return Number.isFinite(date) ? Math.max(0, Math.ceil((date - Date.now()) / 1000)) : null;
39
+ }
40
+ async function httpRequest(fetchFn, url, opts) {
41
+ const Ctrl = globalThis.AbortController;
42
+ const ctrl = Ctrl ? new Ctrl() : null;
43
+ let timer;
44
+ let timedOut = false;
45
+ const timeout = new Promise((resolve) => {
46
+ timer = setTimeout(() => {
47
+ timedOut = true;
48
+ try {
49
+ ctrl === null || ctrl === void 0 ? void 0 : ctrl.abort();
50
+ }
51
+ catch { /* ignore */ }
52
+ resolve(null);
53
+ }, opts.timeoutMs);
54
+ });
55
+ const headers = { ...opts.headers };
56
+ let body;
57
+ if (opts.body !== undefined) {
58
+ headers['Content-Type'] = 'application/json';
59
+ body = stringifyJson(opts.body);
60
+ }
61
+ const fail = { status: 0, body: null, retryAfterS: null, cacheControl: null, timedOut: false };
62
+ try {
63
+ const work = (async () => {
64
+ const res = await fetchFn(url, { method: opts.method || 'GET', headers, body, signal: ctrl === null || ctrl === void 0 ? void 0 : ctrl.signal });
65
+ const text = await res.text();
66
+ let parsed = null;
67
+ try {
68
+ parsed = text ? parseJson(text) : null;
69
+ }
70
+ catch {
71
+ parsed = null;
72
+ }
73
+ return {
74
+ status: res.status,
75
+ body: parsed,
76
+ retryAfterS: parseRetryAfter(res.headers.get('retry-after')),
77
+ cacheControl: res.headers.get('cache-control'),
78
+ timedOut: false,
79
+ };
80
+ })();
81
+ const out = await Promise.race([work, timeout]);
82
+ if (out === null) {
83
+ work.catch(() => undefined);
84
+ return { ...fail, timedOut: true };
85
+ }
86
+ return out;
87
+ }
88
+ catch {
89
+ return { ...fail, timedOut };
90
+ }
91
+ finally {
92
+ if (timer !== undefined)
93
+ clearTimeout(timer);
94
+ }
95
+ }
96
+ /** On a 429 the route is closed until Retry-After has passed. */
97
+ class RouteGate {
98
+ constructor(now) {
99
+ this.now = now;
100
+ this.until = new Map();
101
+ }
102
+ block(route, retryAfterS) {
103
+ const ms = Math.max(1, retryAfterS !== null && retryAfterS !== void 0 ? retryAfterS : 1) * 1000;
104
+ this.until.set(route, Math.max(this.until.get(route) || 0, this.now() + ms));
105
+ }
106
+ /** Milliseconds until the route opens, 0 when open. */
107
+ waitMs(route) {
108
+ const t = this.until.get(route);
109
+ return t ? Math.max(0, t - this.now()) : 0;
110
+ }
111
+ }
112
+ exports.RouteGate = RouteGate;
113
+ function sleep(ms) {
114
+ return new Promise((resolve) => setTimeout(resolve, ms));
115
+ }
@@ -0,0 +1,20 @@
1
+ "use strict";
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;
4
+ // Headless core: pure TypeScript, no React. It uses React Native's AppState when present.
5
+ var client_1 = require("./client");
6
+ Object.defineProperty(exports, "createEthicly", { enumerable: true, get: function () { return client_1.createEthicly; } });
7
+ Object.defineProperty(exports, "SESSION_TIMEOUT_MS", { enumerable: true, get: function () { return client_1.SESSION_TIMEOUT_MS; } });
8
+ var adapters_1 = require("./adapters");
9
+ Object.defineProperty(exports, "createMemoryStorage", { enumerable: true, get: function () { return adapters_1.createMemoryStorage; } });
10
+ Object.defineProperty(exports, "createMemoryFileCache", { enumerable: true, get: function () { return adapters_1.createMemoryFileCache; } });
11
+ Object.defineProperty(exports, "createExpoFileCache", { enumerable: true, get: function () { return adapters_1.createExpoFileCache; } });
12
+ Object.defineProperty(exports, "uuidv4", { enumerable: true, get: function () { return adapters_1.uuidv4; } });
13
+ var click_1 = require("./click");
14
+ Object.defineProperty(exports, "appendClickToken", { enumerable: true, get: function () { return click_1.appendClickToken; } });
15
+ Object.defineProperty(exports, "CLICK_TIMEOUT_MS", { enumerable: true, get: function () { return click_1.CLICK_TIMEOUT_MS; } });
16
+ var config_1 = require("./config");
17
+ Object.defineProperty(exports, "compareVersions", { enumerable: true, get: function () { return config_1.compareVersions; } });
18
+ Object.defineProperty(exports, "BUNDLED_BASE_URL", { enumerable: true, get: function () { return config_1.BUNDLED_BASE_URL; } });
19
+ var version_1 = require("../version");
20
+ Object.defineProperty(exports, "SDK_VERSION", { enumerable: true, get: function () { return version_1.SDK_VERSION; } });
@@ -0,0 +1,192 @@
1
+ "use strict";
2
+ // The beacon outbox: what a rendered ad still owes the server, kept in
3
+ // `storage` so it survives the app being killed, and sent on the next start.
4
+ //
5
+ // Only beacons the server treats as idempotent are kept, so a replay can never
6
+ // count anything twice (docs/APP_API_V1.md):
7
+ // - /impression with its client_impression_id: a retry of a row that did land
8
+ // is answered `duplicate: true`, nothing new is recorded (rule 7);
9
+ // - /viewable: billing happens at most once per impression;
10
+ // - /video-event: applied monotonically, repeats change nothing.
11
+ // /click is never kept: it is never retried (doc "Click handling", step 5).
12
+ // Everything expires one hour after the ad was shown (rule 4), and the outbox
13
+ // holds at most MAX_OUTBOX_RECORDS ads.
14
+ Object.defineProperty(exports, "__esModule", { value: true });
15
+ exports.Outbox = exports.MAX_OUTBOX_RECORDS = void 0;
16
+ exports.outboxFor = outboxFor;
17
+ exports.replayRecord = replayRecord;
18
+ const beacons_1 = require("./beacons");
19
+ const http_1 = require("./http");
20
+ exports.MAX_OUTBOX_RECORDS = 20;
21
+ const VIDEO_EVENTS = ['start', 'q1', 'q2', 'q3', 'complete', 'skip', 'error'];
22
+ function validRecord(r) {
23
+ const o = r;
24
+ if (!o || typeof o.cid !== 'string' || !o.cid || typeof o.shownAt !== 'number' || !Array.isArray(o.events))
25
+ return false;
26
+ if (!o.impression && (0, http_1.asImpressionId)(o.impressionId) === null)
27
+ return false;
28
+ return o.events.every((e) => e && VIDEO_EVENTS.indexOf(e.event) >= 0);
29
+ }
30
+ /**
31
+ * One outbox per storage and API key in this JS runtime, shared by every
32
+ * client created on them, so two clients never replay the same record.
33
+ */
34
+ const registry = new WeakMap();
35
+ function outboxFor(storage, apiKey, log) {
36
+ let byKey = registry.get(storage);
37
+ if (!byKey) {
38
+ byKey = new Map();
39
+ registry.set(storage, byKey);
40
+ }
41
+ let ob = byKey.get(apiKey);
42
+ if (!ob) {
43
+ ob = new Outbox(storage, `ethicly:v1:outbox:${apiKey}`, log);
44
+ byKey.set(apiKey, ob);
45
+ }
46
+ return ob;
47
+ }
48
+ class Outbox {
49
+ constructor(storage, key, log) {
50
+ this.storage = storage;
51
+ this.key = key;
52
+ this.log = log;
53
+ this.records = new Map();
54
+ /** Records a tracker or a replay in this runtime is already sending. */
55
+ this.owned = new Set();
56
+ this.loaded = null;
57
+ this.dirty = false;
58
+ this.writing = null;
59
+ }
60
+ /** Read what a previous run left. Never rejects. */
61
+ load() {
62
+ if (!this.loaded) {
63
+ this.loaded = (async () => {
64
+ try {
65
+ const raw = await this.storage.getItem(this.key);
66
+ const list = raw ? JSON.parse(raw) : [];
67
+ if (Array.isArray(list)) {
68
+ const valid = list.filter(validRecord).sort((a, b) => b.shownAt - a.shownAt).slice(0, exports.MAX_OUTBOX_RECORDS);
69
+ for (const r of valid)
70
+ if (!this.records.has(r.cid))
71
+ this.records.set(r.cid, r);
72
+ }
73
+ }
74
+ catch (e) {
75
+ this.log.warn('stored beacon outbox unreadable, starting empty', e);
76
+ }
77
+ })();
78
+ }
79
+ return this.loaded;
80
+ }
81
+ /** Save or replace a record owned by this runtime. */
82
+ put(rec) {
83
+ this.owned.add(rec.cid);
84
+ this.records.set(rec.cid, rec);
85
+ this.save();
86
+ }
87
+ remove(cid) {
88
+ if (this.records.delete(cid))
89
+ this.save();
90
+ }
91
+ /**
92
+ * Unexpired records nobody in this runtime is sending, now owned by the
93
+ * caller. Expired ones are dropped.
94
+ */
95
+ claimOrphans(now) {
96
+ const out = [];
97
+ let changed = false;
98
+ for (const r of Array.from(this.records.values())) {
99
+ if (this.owned.has(r.cid))
100
+ continue;
101
+ // A time in the future (clock moved back) cannot be trusted either.
102
+ if (now > r.shownAt + beacons_1.ONE_HOUR_MS || r.shownAt > now + 60000) {
103
+ this.records.delete(r.cid);
104
+ changed = true;
105
+ continue;
106
+ }
107
+ this.owned.add(r.cid);
108
+ out.push(r);
109
+ }
110
+ if (changed)
111
+ this.save();
112
+ return out;
113
+ }
114
+ /** Coalesced write of the whole outbox, after the stored one was read. Never rejects. */
115
+ save() {
116
+ this.dirty = true;
117
+ if (this.writing)
118
+ return;
119
+ this.writing = (async () => {
120
+ await this.load();
121
+ while (this.dirty) {
122
+ this.dirty = false;
123
+ // Newest first, so the bound drops the oldest.
124
+ const list = Array.from(this.records.values()).sort((a, b) => b.shownAt - a.shownAt);
125
+ for (const r of list.slice(exports.MAX_OUTBOX_RECORDS))
126
+ this.records.delete(r.cid);
127
+ try {
128
+ await this.storage.setItem(this.key, JSON.stringify(list.slice(0, exports.MAX_OUTBOX_RECORDS)));
129
+ }
130
+ catch (e) {
131
+ this.log.warn('could not save the beacon outbox', e);
132
+ }
133
+ }
134
+ })().finally(() => { this.writing = null; });
135
+ }
136
+ /** Resolves when nothing is waiting to be written. For tests. */
137
+ async flushed() {
138
+ while (this.writing)
139
+ await this.writing;
140
+ }
141
+ }
142
+ exports.Outbox = Outbox;
143
+ /**
144
+ * Send what a previous run left for one ad, with the live tracker's rules:
145
+ * /impression first (same client_impression_id), then /viewable, then the
146
+ * video events. Anything the server refuses, or that is past one hour, is
147
+ * dropped. Never throws.
148
+ */
149
+ async function replayRecord(ctx, outbox, rec) {
150
+ var _a, _b;
151
+ const deadline = rec.shownAt + beacons_1.ONE_HOUR_MS;
152
+ try {
153
+ let id = (0, http_1.asImpressionId)(rec.impressionId);
154
+ let token = typeof rec.viewableToken === 'string' ? rec.viewableToken : null;
155
+ if (id === null && rec.impression) {
156
+ const res = await (0, beacons_1.sendWithRetry)(ctx, 'impression', rec.impression, { deadline });
157
+ id = res && res.status === 200 ? (0, http_1.asImpressionId)((_a = res.body) === null || _a === void 0 ? void 0 : _a.impression_id) : null;
158
+ if (id === null)
159
+ return;
160
+ token = typeof ((_b = res.body) === null || _b === void 0 ? void 0 : _b.viewable_token) === 'string' ? res.body.viewable_token : null;
161
+ // Rule 5: a token-enforced serve with no viewable_token cannot bill.
162
+ if (rec.impression.impression_token && !token)
163
+ return;
164
+ outbox.put({ ...rec, impression: undefined, impressionId: id, viewableToken: token });
165
+ }
166
+ if (id === null)
167
+ return;
168
+ if (typeof rec.viewableMs === 'number') {
169
+ const body = { impression_id: id, viewable_ms: Math.round(rec.viewableMs) };
170
+ if (token)
171
+ body.viewable_token = token;
172
+ if (ctx.now() <= deadline)
173
+ await (0, beacons_1.sendWithRetry)(ctx, 'viewable', body, { deadline });
174
+ }
175
+ for (const e of rec.events) {
176
+ if (ctx.now() > deadline)
177
+ break;
178
+ const body = { impression_id: id, event: e.event };
179
+ if (e.ms !== null && e.ms !== undefined)
180
+ body.ms = e.ms;
181
+ if (token)
182
+ body.viewable_token = token;
183
+ await (0, beacons_1.sendWithRetry)(ctx, 'video-event', body, { deadline });
184
+ }
185
+ }
186
+ catch (e) {
187
+ ctx.log.error('beacon replay failed', e);
188
+ }
189
+ finally {
190
+ outbox.remove(rec.cid);
191
+ }
192
+ }