@sagepilot-ai/react-native-events-addon 0.0.0-stage → 0.5.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.
- package/LICENSE.md +21 -0
- package/README.md +138 -2
- package/SagepilotEventsAddon.podspec +16 -0
- package/android/build.gradle +8 -0
- package/android/src/main/AndroidManifest.xml +3 -0
- package/android/src/main/java/ai/sagepilot/events/SagepilotEventsHTTP.java +67 -0
- package/android/src/main/java/ai/sagepilot/events/SagepilotEventsModule.java +96 -0
- package/android/src/main/java/ai/sagepilot/events/SagepilotEventsPackage.java +16 -0
- package/android/src/main/java/ai/sagepilot/events/SagepilotEventsProjection.java +190 -0
- package/android/src/main/java/ai/sagepilot/events/SagepilotEventsRuntime.java +249 -0
- package/android/src/main/java/ai/sagepilot/events/SagepilotEventsStore.java +173 -0
- package/dist/index.d.mts +49 -0
- package/dist/index.d.ts +49 -0
- package/dist/index.js +1051 -0
- package/dist/index.mjs +1024 -0
- package/ios/SagepilotEventsCore.h +21 -0
- package/ios/SagepilotEventsCore.m +290 -0
- package/ios/SagepilotEventsHTTP.h +8 -0
- package/ios/SagepilotEventsHTTP.m +74 -0
- package/ios/SagepilotEventsModule.m +250 -0
- package/package.json +14 -4
- package/react-native.config.js +4 -0
package/dist/index.mjs
ADDED
|
@@ -0,0 +1,1024 @@
|
|
|
1
|
+
// src/installation.ts
|
|
2
|
+
import { NativeModules as NativeModules2, Platform as Platform2 } from "react-native";
|
|
3
|
+
|
|
4
|
+
// ../sdk-installation-client/src/capture-policy.ts
|
|
5
|
+
var kinds = /* @__PURE__ */ new Set(["navigation", "interaction", "network", "lifecycle", "screen"]);
|
|
6
|
+
var popupActions = /* @__PURE__ */ new Set(["popup_shown", "popup_submitted", "popup_dismissed"]);
|
|
7
|
+
var evidencePath = /^(?:data(?:\.[A-Za-z_][A-Za-z0-9_]*|\.[0-9]+){1,12}|(?:request|response):\$(?:\.[A-Za-z_][A-Za-z0-9_]*|\[[0-9]{1,2}\]){1,12})$/;
|
|
8
|
+
function object(value) {
|
|
9
|
+
return value !== null && typeof value === "object" && !Array.isArray(value);
|
|
10
|
+
}
|
|
11
|
+
function condition(value) {
|
|
12
|
+
if (!object(value) || typeof value.path !== "string" || value.path.length > 255 || !evidencePath.test(value.path)) return false;
|
|
13
|
+
if ("sha256" in value) return !("equals" in value) && typeof value.sha256 === "string" && /^[a-f0-9]{64}$/.test(value.sha256);
|
|
14
|
+
return "equals" in value && (value.equals === null || typeof value.equals === "boolean" || typeof value.equals === "number" && Number.isFinite(value.equals));
|
|
15
|
+
}
|
|
16
|
+
function validateCapturePolicy(value) {
|
|
17
|
+
if (!object(value) || !Array.isArray(value.rules) || value.rules.length > 32 || !Array.isArray(value.popup_actions) || value.popup_actions.length > 3 || !value.popup_actions.every((action) => popupActions.has(action)) || !(value.discovery === null || object(value.discovery) && typeof value.discovery.ends_at === "string" && Number.isFinite(Date.parse(value.discovery.ends_at))) || !value.rules.every((rule) => object(rule) && typeof rule.kind === "string" && kinds.has(rule.kind) && (rule.guard === null || rule.guard === "network_success" && rule.kind === "network" || rule.guard === "cart_click" && rule.kind === "interaction") && Array.isArray(rule.conditions) && rule.conditions.length >= 1 && rule.conditions.length <= 12 && rule.conditions.every(condition))) {
|
|
18
|
+
throw new Error("SDK session response contains an invalid capture policy.");
|
|
19
|
+
}
|
|
20
|
+
return value;
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
// ../sdk-installation-client/src/index.ts
|
|
24
|
+
var SagepilotInstallationError = class extends Error {
|
|
25
|
+
constructor(code, message, options = {}) {
|
|
26
|
+
super(message);
|
|
27
|
+
this.code = code;
|
|
28
|
+
this.name = "SagepilotInstallationError";
|
|
29
|
+
this.status = options.status;
|
|
30
|
+
this.cause = options.cause;
|
|
31
|
+
}
|
|
32
|
+
};
|
|
33
|
+
var UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
|
|
34
|
+
var VISITOR_ID = /^[A-Za-z0-9_-]{1,128}$/;
|
|
35
|
+
var TERMINAL = /* @__PURE__ */ new Set(["admitted", "duplicate", "disabled", "invalid", "retryable"]);
|
|
36
|
+
function safeURL(value) {
|
|
37
|
+
const url = new URL(value);
|
|
38
|
+
if (url.username || url.password || url.search || url.hash || url.protocol !== "https:" && !(url.protocol === "http:" && ["localhost", "127.0.0.1", "[::1]", "10.0.2.2"].includes(url.hostname))) {
|
|
39
|
+
throw new Error("SDK endpoints require HTTPS and cannot contain credentials, queries or fragments.");
|
|
40
|
+
}
|
|
41
|
+
return url;
|
|
42
|
+
}
|
|
43
|
+
function validateSagepilotInstallationReceipt(value, requestedIDs) {
|
|
44
|
+
const results = value?.results;
|
|
45
|
+
if (!Array.isArray(results)) throw new Error("SDK admission receipt is missing.");
|
|
46
|
+
const requested = new Set(requestedIDs), seen = /* @__PURE__ */ new Set();
|
|
47
|
+
if (requested.size !== requestedIDs.length) throw new Error("SDK batch contains duplicate observation IDs.");
|
|
48
|
+
for (const item of results) {
|
|
49
|
+
if (!item || !requested.has(item.event_id) || seen.has(item.event_id) || !TERMINAL.has(item.status)) {
|
|
50
|
+
throw new Error("SDK admission receipt does not match the requested observations.");
|
|
51
|
+
}
|
|
52
|
+
seen.add(item.event_id);
|
|
53
|
+
}
|
|
54
|
+
return { results };
|
|
55
|
+
}
|
|
56
|
+
var SagepilotInstallationClient = class {
|
|
57
|
+
/** Validates the public installation binding without treating it as customer authentication. */
|
|
58
|
+
constructor(options) {
|
|
59
|
+
this.options = options;
|
|
60
|
+
this.current = null;
|
|
61
|
+
this.anonymousId = null;
|
|
62
|
+
this.pending = null;
|
|
63
|
+
this.startup = null;
|
|
64
|
+
this.generation = 0;
|
|
65
|
+
this.uploadRevision = 0;
|
|
66
|
+
this.transitioning = false;
|
|
67
|
+
this.owners = /* @__PURE__ */ new Map();
|
|
68
|
+
this.requests = /* @__PURE__ */ new Set();
|
|
69
|
+
const parts = options.key.split(":");
|
|
70
|
+
if (parts.length !== 2 || !parts.every((value) => UUID.test(value))) throw new Error("SDK key must be workspace_id:installation_id UUIDs.");
|
|
71
|
+
this.workspaceId = parts[0].toLowerCase();
|
|
72
|
+
this.installationId = parts[1].toLowerCase();
|
|
73
|
+
const host = safeURL(options.apiHost ?? "https://api.sagepilot.ai");
|
|
74
|
+
if (host.pathname !== "/") throw new Error("SDK apiHost must be a gateway origin.");
|
|
75
|
+
this.apiHost = host.origin;
|
|
76
|
+
this.fetchImpl = options.fetch ?? globalThis.fetch.bind(globalThis);
|
|
77
|
+
this.storageKey = `sagepilot:sdk-session:${this.workspaceId}:${this.installationId}`;
|
|
78
|
+
}
|
|
79
|
+
/** Returns a copy of the active anonymous session without allowing mutation of capture ownership. */
|
|
80
|
+
session() {
|
|
81
|
+
return this.current ? { ...this.current } : null;
|
|
82
|
+
}
|
|
83
|
+
/** The merchant route owns the cookie path and forwards only the visitor cookie. */
|
|
84
|
+
get visitorCookiePath() {
|
|
85
|
+
return `/sagepilot/visitor/${this.workspaceId}/${this.installationId}`;
|
|
86
|
+
}
|
|
87
|
+
/** Resolves browser continuity on the storefront without sending an upload token or contact data. */
|
|
88
|
+
async syncVisitorCookie(anonymousId, analyticsAllowed, popupCompleted) {
|
|
89
|
+
if (this.options.platform !== "web" || typeof location === "undefined") throw new Error("Visitor cookies require a website.");
|
|
90
|
+
const endpoint = safeURL(location.origin + this.visitorCookiePath);
|
|
91
|
+
const value = await this.request(endpoint.href, {
|
|
92
|
+
method: "POST",
|
|
93
|
+
mode: "same-origin",
|
|
94
|
+
credentials: "same-origin",
|
|
95
|
+
body: JSON.stringify({ analytics_allowed: analyticsAllowed, anonymous_id: anonymousId, popup_completed: popupCompleted })
|
|
96
|
+
}, 2500);
|
|
97
|
+
if (!value || value.anonymous_id !== null && (typeof value.anonymous_id !== "string" || !VISITOR_ID.test(value.anonymous_id)) || typeof value.popup_completed !== "boolean" || typeof value.restored !== "boolean") {
|
|
98
|
+
throw new Error("Invalid SDK visitor cookie response.");
|
|
99
|
+
}
|
|
100
|
+
return value;
|
|
101
|
+
}
|
|
102
|
+
/** Reports whether this runtime still holds matching capture authority for a queued owner. */
|
|
103
|
+
hasCaptureOwner(owner) {
|
|
104
|
+
const session = this.owners.get(owner.session_id) ?? this.current;
|
|
105
|
+
return !!session && session.session_id === owner.session_id && session.customer_id === owner.customer_id;
|
|
106
|
+
}
|
|
107
|
+
/** Restores only the requested browser/device owner, then obtains a fresh server-authorized session. */
|
|
108
|
+
async start(anonymousId) {
|
|
109
|
+
if (!anonymousId.trim() || anonymousId.length > 128) throw new Error("SDK anonymous ID must contain 1\u2013128 characters.");
|
|
110
|
+
if (this.anonymousId && this.anonymousId !== anonymousId) throw new Error("Destroy this SDK client before changing its anonymous owner.");
|
|
111
|
+
this.anonymousId = anonymousId;
|
|
112
|
+
if (this.startup) return this.startup;
|
|
113
|
+
const generation = this.generation;
|
|
114
|
+
const startup = (async () => {
|
|
115
|
+
if (!this.current && this.options.storage) {
|
|
116
|
+
let restored = null;
|
|
117
|
+
try {
|
|
118
|
+
const raw = await this.options.storage.getItem(this.storageKey);
|
|
119
|
+
if (raw && raw.length <= 16384) restored = this.validateSession(JSON.parse(raw));
|
|
120
|
+
const previous = await this.options.storage.getItem(this.storageKey + ":owners");
|
|
121
|
+
if (previous && previous.length <= 65536) {
|
|
122
|
+
const entries = JSON.parse(previous);
|
|
123
|
+
if (Array.isArray(entries) && entries.length <= 4) for (const entry of entries) {
|
|
124
|
+
const owner = this.validateSession(entry);
|
|
125
|
+
this.owners.set(owner.session_id, owner);
|
|
126
|
+
}
|
|
127
|
+
}
|
|
128
|
+
} catch {
|
|
129
|
+
}
|
|
130
|
+
if (generation !== this.generation) throw new Error("SDK session restoration was cancelled.");
|
|
131
|
+
this.current = restored;
|
|
132
|
+
}
|
|
133
|
+
if (generation !== this.generation) throw new Error("SDK session startup was cancelled.");
|
|
134
|
+
return this.refresh(true);
|
|
135
|
+
})().finally(() => {
|
|
136
|
+
if (this.startup === startup) this.startup = null;
|
|
137
|
+
});
|
|
138
|
+
this.startup = startup;
|
|
139
|
+
return startup;
|
|
140
|
+
}
|
|
141
|
+
/** Renews capture, using separate browser proof to recover a linked web visitor after expiry. */
|
|
142
|
+
async refresh(recoverAnonymous = false) {
|
|
143
|
+
if (this.pending) return this.pending;
|
|
144
|
+
if (!this.anonymousId) throw new Error("Start the installation client before renewing it.");
|
|
145
|
+
const generation = this.generation, prior = this.current;
|
|
146
|
+
const pending = (async () => {
|
|
147
|
+
let renewing = prior;
|
|
148
|
+
let resumed = false;
|
|
149
|
+
let value;
|
|
150
|
+
try {
|
|
151
|
+
value = await this.requestSession(prior?.session_token);
|
|
152
|
+
} catch (error) {
|
|
153
|
+
if (!recoverAnonymous || !prior || this.options.platform !== "web" || generation !== this.generation || !(error instanceof SagepilotInstallationError) || error.status !== 401) throw error;
|
|
154
|
+
renewing = null;
|
|
155
|
+
if (prior.browser_resume_token) {
|
|
156
|
+
try {
|
|
157
|
+
value = await this.requestSession(prior.browser_resume_token, true);
|
|
158
|
+
resumed = true;
|
|
159
|
+
} catch (resumeError) {
|
|
160
|
+
if (generation !== this.generation || !(resumeError instanceof SagepilotInstallationError) || ![401, 403, 422].includes(resumeError.status ?? 0)) throw resumeError;
|
|
161
|
+
}
|
|
162
|
+
}
|
|
163
|
+
if (!resumed) value = await this.requestSession();
|
|
164
|
+
}
|
|
165
|
+
const next = this.validateSession(value);
|
|
166
|
+
if (generation !== this.generation) throw new Error("SDK session startup was cancelled.");
|
|
167
|
+
if (renewing && (next.session_id !== renewing.session_id || next.customer_id !== renewing.customer_id) || !renewing && (next.customer_id !== null || !resumed && next.session_id === prior?.session_id)) {
|
|
168
|
+
throw new Error("SDK session renewal changed capture ownership.");
|
|
169
|
+
}
|
|
170
|
+
if (resumed && next.browser_resume_token !== prior?.browser_resume_token) {
|
|
171
|
+
throw new Error("SDK browser recovery returned invalid proof.");
|
|
172
|
+
}
|
|
173
|
+
if (renewing && !next.browser_resume_token) next.browser_resume_token = renewing.browser_resume_token;
|
|
174
|
+
if (prior && next.session_id !== prior.session_id) this.owners.delete(prior.session_id);
|
|
175
|
+
this.current = next;
|
|
176
|
+
this.remember(next);
|
|
177
|
+
try {
|
|
178
|
+
await this.options.storage?.setItem(this.storageKey, JSON.stringify({ ...next, capture_policy: void 0 }));
|
|
179
|
+
} catch {
|
|
180
|
+
}
|
|
181
|
+
return { ...next };
|
|
182
|
+
})().finally(() => {
|
|
183
|
+
if (this.pending === pending) this.pending = null;
|
|
184
|
+
});
|
|
185
|
+
this.pending = pending;
|
|
186
|
+
return pending;
|
|
187
|
+
}
|
|
188
|
+
/** Sends only the capture token for renewal or the distinct credential for browser recovery. */
|
|
189
|
+
requestSession(token, resumeBrowser = false) {
|
|
190
|
+
const web = this.options.platform === "web";
|
|
191
|
+
return this.request(`${this.apiHost}/platform-api/v1/sdk/sessions`, {
|
|
192
|
+
method: "POST",
|
|
193
|
+
headers: {
|
|
194
|
+
...token ? { Authorization: `Bearer ${token}` } : {},
|
|
195
|
+
...web ? { "X-Sagepilot-Capture-Policy": "1" } : {}
|
|
196
|
+
},
|
|
197
|
+
body: JSON.stringify({
|
|
198
|
+
key: `${this.workspaceId}:${this.installationId}`,
|
|
199
|
+
anonymous_id: this.anonymousId,
|
|
200
|
+
platform: this.options.platform,
|
|
201
|
+
...this.options.appId ? { app_id: this.options.appId } : {},
|
|
202
|
+
...resumeBrowser ? { resume_browser: true } : {}
|
|
203
|
+
})
|
|
204
|
+
}, 15e3, web ? 192 * 1024 : 65536);
|
|
205
|
+
}
|
|
206
|
+
/** Supplies a short-lived native upload authorization only for the original capture owner. */
|
|
207
|
+
async authorize(owner) {
|
|
208
|
+
let session = this.owners.get(owner.session_id) ?? this.current;
|
|
209
|
+
if (!session || owner.customer_id !== session.customer_id || owner.session_id !== session.session_id) throw new Error("SDK capture ownership changed.");
|
|
210
|
+
if (Date.parse(session.expires_at) - Date.now() < 6e4) {
|
|
211
|
+
if (session.session_id === this.current?.session_id) session = await this.refresh();
|
|
212
|
+
else {
|
|
213
|
+
const original = session;
|
|
214
|
+
session = this.validateSession(await this.requestSession(session.session_token));
|
|
215
|
+
if (session.session_id !== original.session_id || session.customer_id !== original.customer_id) throw new Error("Historical capture ownership changed.");
|
|
216
|
+
this.remember(session);
|
|
217
|
+
}
|
|
218
|
+
}
|
|
219
|
+
if (!session.collection_enabled || owner.session_id !== session.session_id || owner.customer_id !== session.customer_id) throw new Error("SDK collection is disabled or its owner changed.");
|
|
220
|
+
return { url: session.ingestion_url, headers: {
|
|
221
|
+
Authorization: `Bearer ${session.session_token}`,
|
|
222
|
+
"Content-Type": "application/json",
|
|
223
|
+
"X-Sagepilot-Sdk-Name": this.options.sdk.name,
|
|
224
|
+
"X-Sagepilot-Sdk-Version": this.options.sdk.version
|
|
225
|
+
} };
|
|
226
|
+
}
|
|
227
|
+
/** Posts one bounded immutable batch; collectors own backoff and retain missing/retryable receipts. */
|
|
228
|
+
async upload(observations, owner, stillEligible) {
|
|
229
|
+
if (!observations.length || observations.length > 100) throw new Error("SDK batches require 1\u2013100 observations.");
|
|
230
|
+
for (const item of observations) {
|
|
231
|
+
if (item.owner.session_id !== owner.session_id || item.owner.customer_id !== owner.customer_id) throw new Error("SDK batch mixes capture ownership.");
|
|
232
|
+
}
|
|
233
|
+
const revision = this.uploadRevision;
|
|
234
|
+
const auth = await this.authorize(owner);
|
|
235
|
+
if (revision !== this.uploadRevision || stillEligible?.() === false) throw new Error("SDK upload was cancelled.");
|
|
236
|
+
const body = JSON.stringify({ schema_version: 1, observations });
|
|
237
|
+
if (new TextEncoder().encode(body).byteLength > 128 * 1024) throw new Error("SDK batch exceeds the upload limit.");
|
|
238
|
+
return validateSagepilotInstallationReceipt(await this.request(auth.url, { method: "POST", headers: auth.headers, body }), observations.map((item) => item.event_id));
|
|
239
|
+
}
|
|
240
|
+
/** Submits contact and adopts only a scoped customer session returned by the server. */
|
|
241
|
+
async submitContact(input) {
|
|
242
|
+
if (!UUID.test(input.submission_id) || !Number.isSafeInteger(input.popup_revision) || input.popup_revision < 1 || typeof input.marketing_consent !== "boolean") throw new Error("Invalid popup submission.");
|
|
243
|
+
if (this.transitioning) throw new Error("An SDK identity operation is already running.");
|
|
244
|
+
this.transitioning = true;
|
|
245
|
+
const generation = this.generation, prior = this.current;
|
|
246
|
+
try {
|
|
247
|
+
const { page, ...contact } = input;
|
|
248
|
+
const body = prior?.popup_submission_events === true ? {
|
|
249
|
+
...contact,
|
|
250
|
+
server_submission_event: true,
|
|
251
|
+
...prior.popup_submission_page === true && page ? { page } : {}
|
|
252
|
+
} : contact;
|
|
253
|
+
const result = await this.authenticated("/contact", body);
|
|
254
|
+
if (!result || !["recorded", "verification_required"].includes(result.status) || result.status === "verification_required" && (!result.challenge_id || !UUID.test(result.challenge_id) || !Number.isFinite(Date.parse(result.expires_at ?? "")))) throw new Error("Invalid popup submission response.");
|
|
255
|
+
const { session, ...acknowledgement } = result;
|
|
256
|
+
if (session != null) {
|
|
257
|
+
if (result.status !== "recorded" || prior?.customer_id !== null) throw new Error("Invalid popup customer session.");
|
|
258
|
+
await this.adoptTransition(session, prior, generation, true);
|
|
259
|
+
}
|
|
260
|
+
return acknowledgement;
|
|
261
|
+
} finally {
|
|
262
|
+
this.transitioning = false;
|
|
263
|
+
}
|
|
264
|
+
}
|
|
265
|
+
/** Adopts customer authority only from the server's completed verification operation. */
|
|
266
|
+
async verifyContact(challengeId, code) {
|
|
267
|
+
if (!UUID.test(challengeId) || !/^\d{6}$/.test(code)) throw new Error("Enter the six-digit verification code.");
|
|
268
|
+
return this.transition("/contact/verify", { challenge_id: challengeId, code }, true);
|
|
269
|
+
}
|
|
270
|
+
/** Revokes the current identified grant and establishes a fresh anonymous capture owner. */
|
|
271
|
+
async logout() {
|
|
272
|
+
return this.transition("/logout", {}, false);
|
|
273
|
+
}
|
|
274
|
+
/** Keeps a bounded credential cache separate from observations so old anonymous batches retain their owner. */
|
|
275
|
+
remember(session) {
|
|
276
|
+
this.owners.set(session.session_id, { ...session, capture_policy: void 0, browser_resume_token: void 0 });
|
|
277
|
+
while (this.owners.size > 4) this.owners.delete(this.owners.keys().next().value);
|
|
278
|
+
try {
|
|
279
|
+
void Promise.resolve(this.options.storage?.setItem(this.storageKey + ":owners", JSON.stringify([...this.owners.values()]))).catch(() => {
|
|
280
|
+
});
|
|
281
|
+
} catch {
|
|
282
|
+
}
|
|
283
|
+
}
|
|
284
|
+
/** Uses the current scoped credential for identity operations without attaching it to event records. */
|
|
285
|
+
async authenticated(path, body) {
|
|
286
|
+
const prior = this.current;
|
|
287
|
+
if (!prior) throw new Error("Start the installation client first.");
|
|
288
|
+
if (Date.parse(prior.expires_at) - Date.now() < 6e4) await this.refresh();
|
|
289
|
+
if (this.current?.session_id !== prior.session_id) throw new Error("SDK identity session changed.");
|
|
290
|
+
return this.request(`${this.apiHost}/platform-api/v1/sdk${path}`, { method: "POST", headers: { Authorization: `Bearer ${this.current.session_token}` }, body: JSON.stringify(body) });
|
|
291
|
+
}
|
|
292
|
+
/** Serializes explicit ownership transitions and rejects unrelated or stale server responses. */
|
|
293
|
+
async transition(path, body, identified) {
|
|
294
|
+
if (this.transitioning) throw new Error("An SDK identity operation is already running.");
|
|
295
|
+
this.transitioning = true;
|
|
296
|
+
const generation = this.generation, prior = this.current;
|
|
297
|
+
try {
|
|
298
|
+
return await this.adoptTransition(await this.authenticated(path, body), prior, generation, identified);
|
|
299
|
+
} finally {
|
|
300
|
+
this.transitioning = false;
|
|
301
|
+
}
|
|
302
|
+
}
|
|
303
|
+
/** Installs one new server owner and retains earlier credentials unless the owner logged out. */
|
|
304
|
+
async adoptTransition(value, prior, generation, identified) {
|
|
305
|
+
const next = this.validateSession(value);
|
|
306
|
+
if (generation !== this.generation || !prior || next.session_id === prior.session_id || (identified ? next.customer_id === null : next.customer_id !== null)) throw new Error("Invalid SDK identity transition.");
|
|
307
|
+
next.capture_policy ?? (next.capture_policy = prior.capture_policy);
|
|
308
|
+
this.generation++;
|
|
309
|
+
this.cancelPending();
|
|
310
|
+
this.pending = null;
|
|
311
|
+
if (identified) this.remember(prior);
|
|
312
|
+
else this.owners.delete(prior.session_id);
|
|
313
|
+
this.current = next;
|
|
314
|
+
this.remember(next);
|
|
315
|
+
try {
|
|
316
|
+
await this.options.storage?.setItem(this.storageKey, JSON.stringify({ ...next, capture_policy: void 0 }));
|
|
317
|
+
} catch {
|
|
318
|
+
}
|
|
319
|
+
return { ...next };
|
|
320
|
+
}
|
|
321
|
+
/** Cancels requests on permission/ownership boundaries while preserving the current session for safe renewal. */
|
|
322
|
+
cancelPending() {
|
|
323
|
+
this.uploadRevision++;
|
|
324
|
+
for (const controller of this.requests) controller.abort();
|
|
325
|
+
}
|
|
326
|
+
/** Fences in-flight session adoption and stops all outstanding requests. */
|
|
327
|
+
destroy() {
|
|
328
|
+
this.generation++;
|
|
329
|
+
this.cancelPending();
|
|
330
|
+
this.current = null;
|
|
331
|
+
this.anonymousId = null;
|
|
332
|
+
this.pending = null;
|
|
333
|
+
this.startup = null;
|
|
334
|
+
this.owners.clear();
|
|
335
|
+
}
|
|
336
|
+
/** Rejects foreign or malformed session responses before credentials are used. */
|
|
337
|
+
validateSession(value) {
|
|
338
|
+
const session = value;
|
|
339
|
+
if (!session || session.workspace_id !== this.workspaceId || session.installation_id !== this.installationId || session.platform !== this.options.platform || session.anonymous_id !== this.anonymousId || session.customer_id !== null && (typeof session.customer_id !== "string" || !UUID.test(session.customer_id)) || !UUID.test(session.session_id) || typeof session.session_token !== "string" || session.session_token.length > 16384 || !session.session_token || session.browser_resume_token != null && (session.platform !== "web" || typeof session.browser_resume_token !== "string" || !session.browser_resume_token || session.browser_resume_token.length > 8192) || !Number.isFinite(Date.parse(session.expires_at)) || typeof session.collection_enabled !== "boolean" || session.visitor_cookie_enabled !== void 0 && typeof session.visitor_cookie_enabled !== "boolean" || !Number.isSafeInteger(session.revision)) {
|
|
340
|
+
throw new Error("SDK session response has invalid scope or ownership.");
|
|
341
|
+
}
|
|
342
|
+
const url = safeURL(session.ingestion_url);
|
|
343
|
+
if (url.pathname !== "/events/v1/sdk/observations") throw new Error("SDK ingestion route is invalid.");
|
|
344
|
+
const capturePolicy = session.platform === "web" && session.capture_policy != null ? validateCapturePolicy(session.capture_policy) : void 0;
|
|
345
|
+
return { ...session, capture_policy: capturePolicy };
|
|
346
|
+
}
|
|
347
|
+
/** Performs bounded SDK HTTP requests without retrying mutations or following credential redirects. */
|
|
348
|
+
async request(url, init, timeoutMs = 15e3, maxResponseBytes = 65536) {
|
|
349
|
+
const controller = new AbortController();
|
|
350
|
+
this.requests.add(controller);
|
|
351
|
+
const timeout = setTimeout(() => controller.abort(), timeoutMs);
|
|
352
|
+
try {
|
|
353
|
+
const headers = new Headers(init.headers);
|
|
354
|
+
headers.set("Content-Type", "application/json");
|
|
355
|
+
headers.set("X-Sagepilot-Sdk-Name", this.options.sdk.name);
|
|
356
|
+
headers.set("X-Sagepilot-Sdk-Version", this.options.sdk.version);
|
|
357
|
+
const response = await this.fetchImpl(url, { ...init, headers, signal: controller.signal, redirect: "error", credentials: init.credentials ?? "omit" });
|
|
358
|
+
if (!response.ok) {
|
|
359
|
+
void response.body?.cancel().catch(() => {
|
|
360
|
+
});
|
|
361
|
+
throw new SagepilotInstallationError("invalid_response", `SDK request failed with HTTP ${response.status}.`, { status: response.status });
|
|
362
|
+
}
|
|
363
|
+
if (Number(response.headers.get("content-length") ?? 0) > maxResponseBytes) throw new Error("SDK response exceeds limit.");
|
|
364
|
+
let text = "";
|
|
365
|
+
if (response.body?.getReader) {
|
|
366
|
+
const reader = response.body.getReader(), decoder = new TextDecoder();
|
|
367
|
+
let bytes = 0;
|
|
368
|
+
try {
|
|
369
|
+
for (; ; ) {
|
|
370
|
+
const part = await reader.read();
|
|
371
|
+
if (part.done) break;
|
|
372
|
+
bytes += part.value.byteLength;
|
|
373
|
+
if (bytes > maxResponseBytes) {
|
|
374
|
+
await reader.cancel();
|
|
375
|
+
throw new Error("SDK response exceeds limit.");
|
|
376
|
+
}
|
|
377
|
+
text += decoder.decode(part.value, { stream: true });
|
|
378
|
+
}
|
|
379
|
+
text += decoder.decode();
|
|
380
|
+
} finally {
|
|
381
|
+
reader.releaseLock();
|
|
382
|
+
}
|
|
383
|
+
} else {
|
|
384
|
+
text = await response.text();
|
|
385
|
+
if (new TextEncoder().encode(text).byteLength > maxResponseBytes) throw new Error("SDK response exceeds limit.");
|
|
386
|
+
}
|
|
387
|
+
return JSON.parse(text);
|
|
388
|
+
} catch (error) {
|
|
389
|
+
if (controller.signal.aborted || error instanceof TypeError) {
|
|
390
|
+
throw new SagepilotInstallationError("network_error", "SDK request could not reach the server.", { cause: error });
|
|
391
|
+
}
|
|
392
|
+
throw error;
|
|
393
|
+
} finally {
|
|
394
|
+
clearTimeout(timeout);
|
|
395
|
+
this.requests.delete(controller);
|
|
396
|
+
}
|
|
397
|
+
}
|
|
398
|
+
};
|
|
399
|
+
function createSagepilotInstallationClient(options) {
|
|
400
|
+
return new SagepilotInstallationClient(options);
|
|
401
|
+
}
|
|
402
|
+
|
|
403
|
+
// src/collector.ts
|
|
404
|
+
import { AppState, NativeModules, Platform } from "react-native";
|
|
405
|
+
|
|
406
|
+
// src/network.ts
|
|
407
|
+
var BODY_LIMIT = 64 * 1024;
|
|
408
|
+
var installed = false;
|
|
409
|
+
function routeFor(input, excludedOrigin) {
|
|
410
|
+
if (input.length > 2048) return null;
|
|
411
|
+
try {
|
|
412
|
+
const url = new URL(input);
|
|
413
|
+
if (!/^https?:$/.test(url.protocol) || url.origin === excludedOrigin || url.username || url.password) return null;
|
|
414
|
+
return url.origin + url.pathname;
|
|
415
|
+
} catch {
|
|
416
|
+
return null;
|
|
417
|
+
}
|
|
418
|
+
}
|
|
419
|
+
function observeNetwork(options) {
|
|
420
|
+
const XHR = globalThis.XMLHttpRequest;
|
|
421
|
+
if (!XHR) return () => {
|
|
422
|
+
};
|
|
423
|
+
if (installed) throw new Error("Only one Sagepilot events collector may observe networking.");
|
|
424
|
+
installed = true;
|
|
425
|
+
const prototype = XHR.prototype;
|
|
426
|
+
const originalOpen = prototype.open;
|
|
427
|
+
const originalSend = prototype.send;
|
|
428
|
+
const states = /* @__PURE__ */ new WeakMap();
|
|
429
|
+
const cleanups = /* @__PURE__ */ new Set();
|
|
430
|
+
const originalFetch = globalThis.fetch;
|
|
431
|
+
const responsePrototype = globalThis.Response?.prototype;
|
|
432
|
+
const originalText = responsePrototype?.text;
|
|
433
|
+
const originalClone = responsePrototype?.clone;
|
|
434
|
+
const responseTokens = /* @__PURE__ */ new WeakMap();
|
|
435
|
+
const responses = /* @__PURE__ */ new Map();
|
|
436
|
+
const activeFetches = /* @__PURE__ */ new Set();
|
|
437
|
+
const retainedRequests = /* @__PURE__ */ new Set();
|
|
438
|
+
let retainedBodyUnits = 0;
|
|
439
|
+
const requestPrefix = Date.now().toString(36) + "-" + Math.random().toString(36).slice(2);
|
|
440
|
+
let requestSequence = 0;
|
|
441
|
+
let insideFetch = false;
|
|
442
|
+
let stopped = false;
|
|
443
|
+
function retainBody(state, body) {
|
|
444
|
+
if (body == null) return;
|
|
445
|
+
if (typeof body !== "string" || !/^\s*[\[{]/.test(body.slice(0, 64))) {
|
|
446
|
+
state.requestBodyOmitted = "unsupported_body_type";
|
|
447
|
+
return;
|
|
448
|
+
}
|
|
449
|
+
if (body.length > BODY_LIMIT || retainedBodyUnits + body.length > 128 * 1024) {
|
|
450
|
+
state.requestBodyOmitted = "size_or_budget_limit";
|
|
451
|
+
return;
|
|
452
|
+
}
|
|
453
|
+
state.requestBody = body;
|
|
454
|
+
retainedBodyUnits += body.length;
|
|
455
|
+
retainedRequests.add(state);
|
|
456
|
+
}
|
|
457
|
+
function releaseBody(state) {
|
|
458
|
+
if (state.requestBody) retainedBodyUnits -= state.requestBody.length;
|
|
459
|
+
state.requestBody = void 0;
|
|
460
|
+
retainedRequests.delete(state);
|
|
461
|
+
}
|
|
462
|
+
function emitFetch(state, phase, extra = {}) {
|
|
463
|
+
try {
|
|
464
|
+
if (stopped || options.epoch() !== state.epoch) {
|
|
465
|
+
options.dropped();
|
|
466
|
+
return;
|
|
467
|
+
}
|
|
468
|
+
options.emit({
|
|
469
|
+
occurred_at_ms: Date.now(),
|
|
470
|
+
method: state.method,
|
|
471
|
+
route: state.route,
|
|
472
|
+
status: state.status,
|
|
473
|
+
duration_ms: Math.max(0, Date.now() - state.start),
|
|
474
|
+
identity_epoch: state.epoch,
|
|
475
|
+
request_id: state.requestId,
|
|
476
|
+
phase,
|
|
477
|
+
outcome: "completed",
|
|
478
|
+
...extra
|
|
479
|
+
});
|
|
480
|
+
} catch {
|
|
481
|
+
options.dropped();
|
|
482
|
+
}
|
|
483
|
+
}
|
|
484
|
+
function observedFetch(...args) {
|
|
485
|
+
if (stopped) return Reflect.apply(originalFetch, this, args);
|
|
486
|
+
let state = null;
|
|
487
|
+
try {
|
|
488
|
+
const input = args[0], init = args[1], epoch = options.epoch();
|
|
489
|
+
const request = typeof Request !== "undefined" && input instanceof Request ? input : null;
|
|
490
|
+
const url = typeof input === "string" ? input : request ? request.url : typeof URL !== "undefined" && input instanceof URL ? input.href : null;
|
|
491
|
+
const route = url ? routeFor(url, options.excludedOrigin) : null;
|
|
492
|
+
const method = init?.method ?? (typeof input === "object" && "method" in input ? input.method : "GET");
|
|
493
|
+
if (!stopped && epoch && route && activeFetches.size < 128 && /^(GET|POST|PUT|PATCH|DELETE|HEAD|OPTIONS)$/i.test(method)) {
|
|
494
|
+
const body = init?.body ?? (request?.bodyUsed ? void 0 : request?._bodyInit);
|
|
495
|
+
const token = ++requestSequence;
|
|
496
|
+
state = { method: method.toUpperCase(), route, start: Date.now(), epoch, token, requestId: requestPrefix + "-" + token, status: 0 };
|
|
497
|
+
retainBody(state, body);
|
|
498
|
+
if (body == null && request?.body) state.requestBodyOmitted = "unsupported_body_type";
|
|
499
|
+
activeFetches.add(state);
|
|
500
|
+
}
|
|
501
|
+
} catch {
|
|
502
|
+
options.dropped();
|
|
503
|
+
}
|
|
504
|
+
let result;
|
|
505
|
+
const previous = insideFetch;
|
|
506
|
+
try {
|
|
507
|
+
insideFetch = !!state;
|
|
508
|
+
result = Reflect.apply(originalFetch, this, args);
|
|
509
|
+
} catch (error) {
|
|
510
|
+
if (state) {
|
|
511
|
+
releaseBody(state);
|
|
512
|
+
activeFetches.delete(state);
|
|
513
|
+
}
|
|
514
|
+
throw error;
|
|
515
|
+
} finally {
|
|
516
|
+
insideFetch = previous;
|
|
517
|
+
}
|
|
518
|
+
if (!state) return result;
|
|
519
|
+
const captured = state;
|
|
520
|
+
return result.then((response) => {
|
|
521
|
+
try {
|
|
522
|
+
captured.status = response.status;
|
|
523
|
+
emitFetch(captured, "headers", { ...captured.requestBody ? { request_body: captured.requestBody } : {}, ...captured.requestBodyOmitted ? { request_body_omitted: captured.requestBodyOmitted } : {} });
|
|
524
|
+
if (!stopped && options.epoch() === captured.epoch && /(?:application|text)\/(?:[a-z0-9.+-]*\+)?json/i.test(response.headers.get("content-type") ?? "")) {
|
|
525
|
+
if (responses.size >= 128) {
|
|
526
|
+
responses.delete(responses.keys().next().value);
|
|
527
|
+
options.dropped();
|
|
528
|
+
}
|
|
529
|
+
responseTokens.set(response, captured.token);
|
|
530
|
+
responses.set(captured.token, captured);
|
|
531
|
+
}
|
|
532
|
+
} catch {
|
|
533
|
+
options.dropped();
|
|
534
|
+
} finally {
|
|
535
|
+
releaseBody(captured);
|
|
536
|
+
activeFetches.delete(captured);
|
|
537
|
+
}
|
|
538
|
+
return response;
|
|
539
|
+
}, (error) => {
|
|
540
|
+
emitFetch(captured, "headers", { outcome: "error" });
|
|
541
|
+
releaseBody(captured);
|
|
542
|
+
activeFetches.delete(captured);
|
|
543
|
+
throw error;
|
|
544
|
+
});
|
|
545
|
+
}
|
|
546
|
+
function text() {
|
|
547
|
+
const token = responseTokens.get(this), state = token === void 0 ? void 0 : responses.get(token);
|
|
548
|
+
const result = Reflect.apply(originalText, this, []);
|
|
549
|
+
if (stopped || !state) return result;
|
|
550
|
+
return result.then((body) => {
|
|
551
|
+
if (responses.get(token) === state) {
|
|
552
|
+
responses.delete(token);
|
|
553
|
+
emitFetch(state, "body", body.length <= BODY_LIMIT ? { response_body: body } : { body_omitted: "size_limit" });
|
|
554
|
+
}
|
|
555
|
+
return body;
|
|
556
|
+
}, (error) => {
|
|
557
|
+
responses.delete(token);
|
|
558
|
+
emitFetch(state, "body", { body_omitted: "body_read_failed" });
|
|
559
|
+
throw error;
|
|
560
|
+
});
|
|
561
|
+
}
|
|
562
|
+
function clone() {
|
|
563
|
+
const result = Reflect.apply(originalClone, this, []);
|
|
564
|
+
const token = responseTokens.get(this);
|
|
565
|
+
if (!stopped && token !== void 0 && responses.has(token)) responseTokens.set(result, token);
|
|
566
|
+
return result;
|
|
567
|
+
}
|
|
568
|
+
function open(...args) {
|
|
569
|
+
const previous = states.get(this);
|
|
570
|
+
const result = Reflect.apply(originalOpen, this, args);
|
|
571
|
+
const remaining = states.get(this);
|
|
572
|
+
if (remaining && remaining !== previous) return result;
|
|
573
|
+
if (previous && remaining === previous) {
|
|
574
|
+
if (previous.cleanup) {
|
|
575
|
+
previous.cleanup();
|
|
576
|
+
options.dropped();
|
|
577
|
+
} else states.delete(this);
|
|
578
|
+
}
|
|
579
|
+
if (stopped || insideFetch) return result;
|
|
580
|
+
const epoch = options.epoch();
|
|
581
|
+
const route = typeof args[1] === "string" ? routeFor(args[1], options.excludedOrigin) : null;
|
|
582
|
+
if (!stopped && epoch && route && /^(GET|POST|PUT|PATCH|DELETE|HEAD|OPTIONS)$/i.test(args[0])) {
|
|
583
|
+
states.set(this, { method: args[0].toUpperCase(), route, epoch, start: 0 });
|
|
584
|
+
}
|
|
585
|
+
return result;
|
|
586
|
+
}
|
|
587
|
+
function send(body) {
|
|
588
|
+
const state = states.get(this);
|
|
589
|
+
if (state?.cleanup) return Reflect.apply(originalSend, this, [body]);
|
|
590
|
+
if (!state || stopped || !options.epoch() || options.epoch() !== state.epoch) {
|
|
591
|
+
states.delete(this);
|
|
592
|
+
return Reflect.apply(originalSend, this, [body]);
|
|
593
|
+
}
|
|
594
|
+
if (cleanups.size >= 128) {
|
|
595
|
+
states.delete(this);
|
|
596
|
+
options.dropped();
|
|
597
|
+
return Reflect.apply(originalSend, this, [body]);
|
|
598
|
+
}
|
|
599
|
+
state.start = Date.now();
|
|
600
|
+
retainBody(state, body);
|
|
601
|
+
let outcome = "completed";
|
|
602
|
+
const failed = (event) => {
|
|
603
|
+
outcome = event.type;
|
|
604
|
+
};
|
|
605
|
+
const cleanup = () => {
|
|
606
|
+
this.removeEventListener("loadend", complete);
|
|
607
|
+
for (const kind of ["error", "abort", "timeout"]) this.removeEventListener(kind, failed);
|
|
608
|
+
cleanups.delete(cleanup);
|
|
609
|
+
if (states.get(this) === state) states.delete(this);
|
|
610
|
+
releaseBody(state);
|
|
611
|
+
};
|
|
612
|
+
const complete = () => {
|
|
613
|
+
try {
|
|
614
|
+
if (stopped || !state.epoch || options.epoch() !== state.epoch) {
|
|
615
|
+
options.dropped();
|
|
616
|
+
return;
|
|
617
|
+
}
|
|
618
|
+
const observation = {
|
|
619
|
+
occurred_at_ms: Date.now(),
|
|
620
|
+
method: state.method,
|
|
621
|
+
route: state.route,
|
|
622
|
+
status: this.status,
|
|
623
|
+
duration_ms: Math.max(0, Date.now() - state.start),
|
|
624
|
+
outcome,
|
|
625
|
+
identity_epoch: state.epoch,
|
|
626
|
+
...state.requestBody ? { request_body: state.requestBody } : {},
|
|
627
|
+
...state.requestBodyOmitted ? { request_body_omitted: state.requestBodyOmitted } : {}
|
|
628
|
+
};
|
|
629
|
+
if (outcome === "completed" && /(?:application|text)\/(?:[a-z0-9.+-]*\+)?json/i.test(this.getResponseHeader("content-type") ?? "")) {
|
|
630
|
+
if (this.responseType === "" || this.responseType === "text") {
|
|
631
|
+
const text2 = this.responseText;
|
|
632
|
+
if (text2.length <= BODY_LIMIT) observation.response_body = text2;
|
|
633
|
+
else observation.body_omitted = "size_limit";
|
|
634
|
+
} else observation.body_omitted = "unsupported_response_type";
|
|
635
|
+
}
|
|
636
|
+
options.emit(observation);
|
|
637
|
+
} catch {
|
|
638
|
+
options.dropped();
|
|
639
|
+
} finally {
|
|
640
|
+
cleanup();
|
|
641
|
+
}
|
|
642
|
+
};
|
|
643
|
+
state.cleanup = cleanup;
|
|
644
|
+
cleanups.add(cleanup);
|
|
645
|
+
this.addEventListener("loadend", complete);
|
|
646
|
+
for (const kind of ["error", "abort", "timeout"]) this.addEventListener(kind, failed);
|
|
647
|
+
try {
|
|
648
|
+
return Reflect.apply(originalSend, this, [body]);
|
|
649
|
+
} catch (error) {
|
|
650
|
+
cleanup();
|
|
651
|
+
throw error;
|
|
652
|
+
}
|
|
653
|
+
}
|
|
654
|
+
function uninstall() {
|
|
655
|
+
stopped = true;
|
|
656
|
+
const gaps = cleanups.size + activeFetches.size + responses.size;
|
|
657
|
+
if (gaps) options.dropped(gaps);
|
|
658
|
+
for (const state of [...retainedRequests]) releaseBody(state);
|
|
659
|
+
activeFetches.clear();
|
|
660
|
+
responses.clear();
|
|
661
|
+
for (const cleanup of [...cleanups]) cleanup();
|
|
662
|
+
if (prototype.open === open) prototype.open = originalOpen;
|
|
663
|
+
if (prototype.send === send) prototype.send = originalSend;
|
|
664
|
+
if (globalThis.fetch === observedFetch) globalThis.fetch = originalFetch;
|
|
665
|
+
if (responsePrototype?.text === text) responsePrototype.text = originalText;
|
|
666
|
+
if (responsePrototype?.clone === clone) responsePrototype.clone = originalClone;
|
|
667
|
+
installed = false;
|
|
668
|
+
}
|
|
669
|
+
try {
|
|
670
|
+
prototype.open = open;
|
|
671
|
+
prototype.send = send;
|
|
672
|
+
if (typeof originalFetch === "function" && typeof originalText === "function" && responsePrototype) {
|
|
673
|
+
responsePrototype.text = text;
|
|
674
|
+
if (typeof originalClone === "function") responsePrototype.clone = clone;
|
|
675
|
+
globalThis.fetch = observedFetch;
|
|
676
|
+
}
|
|
677
|
+
} catch (error) {
|
|
678
|
+
uninstall();
|
|
679
|
+
throw error;
|
|
680
|
+
}
|
|
681
|
+
return uninstall;
|
|
682
|
+
}
|
|
683
|
+
|
|
684
|
+
// package.json
|
|
685
|
+
var name = "@sagepilot-ai/react-native-events-addon";
|
|
686
|
+
var version = "0.5.1";
|
|
687
|
+
|
|
688
|
+
// src/collector.ts
|
|
689
|
+
var activeCollector = null;
|
|
690
|
+
function createSagepilotEventsAddon(options = {}) {
|
|
691
|
+
let module = null;
|
|
692
|
+
let context = null;
|
|
693
|
+
let owner = null;
|
|
694
|
+
let epoch = null;
|
|
695
|
+
let enabled = options.collectionEnabled === true;
|
|
696
|
+
let revision = 0;
|
|
697
|
+
let timer = null;
|
|
698
|
+
let foreground = null;
|
|
699
|
+
let unobserve = null;
|
|
700
|
+
let draining = null;
|
|
701
|
+
let failures = 0;
|
|
702
|
+
let bridgeDrops = 0;
|
|
703
|
+
let networkInFlight = 0;
|
|
704
|
+
const networkQueue = [];
|
|
705
|
+
let networkBytes = 0;
|
|
706
|
+
let networkScheduled = false;
|
|
707
|
+
let nativeConfigured = false;
|
|
708
|
+
let starting = false;
|
|
709
|
+
const collector = {};
|
|
710
|
+
function report(error) {
|
|
711
|
+
try {
|
|
712
|
+
options.onError?.(error);
|
|
713
|
+
} catch {
|
|
714
|
+
}
|
|
715
|
+
}
|
|
716
|
+
function clearRetryTimer() {
|
|
717
|
+
if (timer) clearTimeout(timer);
|
|
718
|
+
timer = null;
|
|
719
|
+
}
|
|
720
|
+
function clearNetworkQueue() {
|
|
721
|
+
bridgeDrops += networkQueue.length;
|
|
722
|
+
networkQueue.length = 0;
|
|
723
|
+
networkBytes = 0;
|
|
724
|
+
}
|
|
725
|
+
function scheduleNetwork() {
|
|
726
|
+
if (networkScheduled || networkInFlight || !context || !enabled || !epoch || !networkQueue.length) return;
|
|
727
|
+
networkScheduled = true;
|
|
728
|
+
void Promise.resolve().then(() => {
|
|
729
|
+
networkScheduled = false;
|
|
730
|
+
const native = module;
|
|
731
|
+
if (!native || networkInFlight || !context || !enabled || !epoch) return;
|
|
732
|
+
const batch = [];
|
|
733
|
+
let bytes = 0;
|
|
734
|
+
while (networkQueue.length && batch.length < 32) {
|
|
735
|
+
const item = networkQueue[0];
|
|
736
|
+
if (batch.length && bytes + item.bytes > 256 * 1024) break;
|
|
737
|
+
networkQueue.shift();
|
|
738
|
+
networkBytes -= item.bytes;
|
|
739
|
+
bytes += item.bytes;
|
|
740
|
+
batch.push(item.value);
|
|
741
|
+
}
|
|
742
|
+
if (!batch.length) return;
|
|
743
|
+
networkInFlight++;
|
|
744
|
+
void Promise.resolve().then(() => native.observeNetworkBatch(batch)).catch((error) => {
|
|
745
|
+
bridgeDrops += batch.length;
|
|
746
|
+
report(error);
|
|
747
|
+
}).finally(() => {
|
|
748
|
+
networkInFlight--;
|
|
749
|
+
scheduleNetwork();
|
|
750
|
+
});
|
|
751
|
+
});
|
|
752
|
+
}
|
|
753
|
+
function queueNetwork(value) {
|
|
754
|
+
const bytes = (typeof value.request_body === "string" ? value.request_body.length * 2 : 0) + (typeof value.response_body === "string" ? value.response_body.length * 2 : 0) + 2048;
|
|
755
|
+
if (networkQueue.length >= 128 || networkBytes + bytes > 512 * 1024) {
|
|
756
|
+
bridgeDrops++;
|
|
757
|
+
return;
|
|
758
|
+
}
|
|
759
|
+
networkQueue.push({ value, bytes });
|
|
760
|
+
networkBytes += bytes;
|
|
761
|
+
scheduleNetwork();
|
|
762
|
+
}
|
|
763
|
+
function installNetworkObserver() {
|
|
764
|
+
if (!context || !enabled || !epoch || unobserve) return;
|
|
765
|
+
unobserve = observeNetwork({
|
|
766
|
+
excludedOrigin: context.excludedOrigin,
|
|
767
|
+
epoch: () => enabled ? epoch : null,
|
|
768
|
+
emit: queueNetwork,
|
|
769
|
+
dropped: (count = 1) => {
|
|
770
|
+
bridgeDrops += count;
|
|
771
|
+
}
|
|
772
|
+
});
|
|
773
|
+
}
|
|
774
|
+
function schedule() {
|
|
775
|
+
if (timer || !context || !enabled || !epoch || !owner) return;
|
|
776
|
+
const delay = failures ? Math.min(6e4, 2e3 * 2 ** Math.min(failures, 5)) * (0.8 + Math.random() * 0.4) : 2e3;
|
|
777
|
+
timer = setTimeout(() => {
|
|
778
|
+
timer = null;
|
|
779
|
+
void flush().catch(report).finally(schedule);
|
|
780
|
+
}, delay);
|
|
781
|
+
}
|
|
782
|
+
async function flush() {
|
|
783
|
+
if (draining) return draining;
|
|
784
|
+
const current = context, native = module, capturedOwner = owner, generation = revision;
|
|
785
|
+
if (!current || !native || !enabled || !epoch || !capturedOwner) return;
|
|
786
|
+
draining = (async () => {
|
|
787
|
+
for (let pass = 0; pass < 4; pass++) {
|
|
788
|
+
const batch = await native.nextBatch(bridgeDrops);
|
|
789
|
+
if (!batch || context !== current || revision !== generation || !enabled) return;
|
|
790
|
+
try {
|
|
791
|
+
const receipt = await current.upload(batch.lease, capturedOwner);
|
|
792
|
+
if (!receipt || !Array.isArray(receipt.results)) throw new Error("App-event admission receipt is missing.");
|
|
793
|
+
const requested = new Set(batch.event_ids);
|
|
794
|
+
const seen = /* @__PURE__ */ new Set();
|
|
795
|
+
const accepted = [];
|
|
796
|
+
for (const item of receipt.results) {
|
|
797
|
+
if (!requested.has(item.event_id) || seen.has(item.event_id) || !["admitted", "duplicate", "disabled", "invalid", "retryable"].includes(item.status)) {
|
|
798
|
+
throw new Error("App-event admission receipt does not match its batch.");
|
|
799
|
+
}
|
|
800
|
+
seen.add(item.event_id);
|
|
801
|
+
if (item.status !== "retryable") accepted.push(item.event_id);
|
|
802
|
+
}
|
|
803
|
+
if (accepted.length) await native.acknowledge(batch.lease, accepted);
|
|
804
|
+
failures = accepted.length === batch.event_ids.length ? 0 : Math.min(failures + 1, 6);
|
|
805
|
+
if (failures) return;
|
|
806
|
+
} catch (error) {
|
|
807
|
+
failures = Math.min(failures + 1, 6);
|
|
808
|
+
throw error;
|
|
809
|
+
}
|
|
810
|
+
}
|
|
811
|
+
})().finally(() => {
|
|
812
|
+
draining = null;
|
|
813
|
+
});
|
|
814
|
+
return draining;
|
|
815
|
+
}
|
|
816
|
+
async function setIdentity(next) {
|
|
817
|
+
unobserve?.();
|
|
818
|
+
unobserve = null;
|
|
819
|
+
clearRetryTimer();
|
|
820
|
+
clearNetworkQueue();
|
|
821
|
+
const generation = ++revision;
|
|
822
|
+
epoch = null;
|
|
823
|
+
owner = next;
|
|
824
|
+
const nextEpoch = await module?.setIdentity(next);
|
|
825
|
+
if (generation === revision && context) epoch = nextEpoch ?? null;
|
|
826
|
+
installNetworkObserver();
|
|
827
|
+
schedule();
|
|
828
|
+
}
|
|
829
|
+
function stop() {
|
|
830
|
+
++revision;
|
|
831
|
+
epoch = null;
|
|
832
|
+
owner = null;
|
|
833
|
+
context = null;
|
|
834
|
+
clearRetryTimer();
|
|
835
|
+
clearNetworkQueue();
|
|
836
|
+
foreground?.remove();
|
|
837
|
+
foreground = null;
|
|
838
|
+
unobserve?.();
|
|
839
|
+
unobserve = null;
|
|
840
|
+
if (!starting && activeCollector === collector) activeCollector = null;
|
|
841
|
+
if (nativeConfigured) {
|
|
842
|
+
nativeConfigured = false;
|
|
843
|
+
void module?.stop().catch(report);
|
|
844
|
+
}
|
|
845
|
+
}
|
|
846
|
+
return {
|
|
847
|
+
/** Attaches the native collectors to the authenticated installation. */
|
|
848
|
+
async start(next) {
|
|
849
|
+
if (context) throw new Error("Sagepilot app events are already started.");
|
|
850
|
+
if (activeCollector) throw new Error("Only one Sagepilot events add-on may run.");
|
|
851
|
+
if (Platform.OS !== "android" && Platform.OS !== "ios") throw new Error("Sagepilot app events require Android or iOS.");
|
|
852
|
+
const native = NativeModules.SagepilotEventsAddon;
|
|
853
|
+
if (!native) throw new Error("Install @sagepilot-ai/react-native-events-addon and rebuild the native app. Expo Go is not supported.");
|
|
854
|
+
module = native;
|
|
855
|
+
context = next;
|
|
856
|
+
activeCollector = collector;
|
|
857
|
+
starting = true;
|
|
858
|
+
try {
|
|
859
|
+
if (!next.installationId) throw new Error("App events require an installation ID.");
|
|
860
|
+
await native.configure({
|
|
861
|
+
workspace_id: next.workspaceId,
|
|
862
|
+
sdk_installation_id: next.installationId,
|
|
863
|
+
sdk_version: next.sdkVersion,
|
|
864
|
+
addon_version: version,
|
|
865
|
+
enabled
|
|
866
|
+
});
|
|
867
|
+
nativeConfigured = true;
|
|
868
|
+
if (context !== next) {
|
|
869
|
+
await native.stop();
|
|
870
|
+
nativeConfigured = false;
|
|
871
|
+
throw new Error("Sagepilot app-event startup was cancelled.");
|
|
872
|
+
}
|
|
873
|
+
await setIdentity(next.owner);
|
|
874
|
+
if (context !== next) throw new Error("Sagepilot app-event startup was cancelled.");
|
|
875
|
+
installNetworkObserver();
|
|
876
|
+
foreground = AppState.addEventListener("change", (state) => {
|
|
877
|
+
if (state === "active") void flush().catch(report);
|
|
878
|
+
});
|
|
879
|
+
schedule();
|
|
880
|
+
} catch (error) {
|
|
881
|
+
stop();
|
|
882
|
+
throw error;
|
|
883
|
+
} finally {
|
|
884
|
+
starting = false;
|
|
885
|
+
if (!context && activeCollector === collector) activeCollector = null;
|
|
886
|
+
}
|
|
887
|
+
},
|
|
888
|
+
setIdentity,
|
|
889
|
+
stop,
|
|
890
|
+
flush,
|
|
891
|
+
/** Applies consent locally, invalidating in-flight JS observations before the native purge. */
|
|
892
|
+
async setCollectionEnabled(next) {
|
|
893
|
+
unobserve?.();
|
|
894
|
+
unobserve = null;
|
|
895
|
+
clearRetryTimer();
|
|
896
|
+
clearNetworkQueue();
|
|
897
|
+
enabled = next;
|
|
898
|
+
const generation = ++revision;
|
|
899
|
+
epoch = null;
|
|
900
|
+
const nextEpoch = await module?.setEnabled(next);
|
|
901
|
+
if (generation === revision && context) epoch = nextEpoch ?? null;
|
|
902
|
+
installNetworkObserver();
|
|
903
|
+
if (next) schedule();
|
|
904
|
+
},
|
|
905
|
+
/** Exposes bounded counters rather than leaking raw observations into the application's UI. */
|
|
906
|
+
async diagnostics() {
|
|
907
|
+
if (!module) throw new Error("Start the events add-on before reading diagnostics.");
|
|
908
|
+
const diagnostics = await module.diagnostics();
|
|
909
|
+
return {
|
|
910
|
+
...diagnostics,
|
|
911
|
+
dropped_records: diagnostics.dropped_records + bridgeDrops,
|
|
912
|
+
network_observation_supported: typeof globalThis.XMLHttpRequest !== "undefined"
|
|
913
|
+
};
|
|
914
|
+
}
|
|
915
|
+
};
|
|
916
|
+
}
|
|
917
|
+
|
|
918
|
+
// src/installation.ts
|
|
919
|
+
function createSagepilotInstallationEvents(options) {
|
|
920
|
+
if (Platform2.OS !== "android" && Platform2.OS !== "ios") throw new Error("Native installation events require Android or iOS.");
|
|
921
|
+
const client = createSagepilotInstallationClient({ ...options, platform: Platform2.OS, sdk: { name, version } });
|
|
922
|
+
const addon = createSagepilotEventsAddon({ collectionEnabled: false, onError: options.onError });
|
|
923
|
+
let consent = options.collectionEnabled === true, started = false, generation = 0;
|
|
924
|
+
let timer = null;
|
|
925
|
+
let appliedPermission = false;
|
|
926
|
+
let permissionRevision = 0;
|
|
927
|
+
function report(error) {
|
|
928
|
+
try {
|
|
929
|
+
options.onError?.(error);
|
|
930
|
+
} catch {
|
|
931
|
+
}
|
|
932
|
+
}
|
|
933
|
+
async function applyPermission(enabled) {
|
|
934
|
+
if (!started || appliedPermission === enabled) return;
|
|
935
|
+
const revision = ++permissionRevision;
|
|
936
|
+
appliedPermission = null;
|
|
937
|
+
await addon.setCollectionEnabled(enabled);
|
|
938
|
+
if (revision === permissionRevision) appliedPermission = enabled;
|
|
939
|
+
}
|
|
940
|
+
async function syncPolicy() {
|
|
941
|
+
const revision = generation;
|
|
942
|
+
try {
|
|
943
|
+
const session = await client.refresh();
|
|
944
|
+
if (started && revision === generation) await applyPermission(consent && session.collection_enabled);
|
|
945
|
+
} catch (error) {
|
|
946
|
+
if (started && revision === generation) await applyPermission(false).catch(report);
|
|
947
|
+
report(error);
|
|
948
|
+
}
|
|
949
|
+
}
|
|
950
|
+
async function upload(lease, owner) {
|
|
951
|
+
if (!consent || owner.customer_id !== null) throw new Error("Installation capture is anonymous and requires collection permission.");
|
|
952
|
+
const revision = generation;
|
|
953
|
+
let authorization;
|
|
954
|
+
try {
|
|
955
|
+
authorization = await client.authorize({ ...owner, customer_id: null });
|
|
956
|
+
} finally {
|
|
957
|
+
if (client.session()?.collection_enabled === false) await applyPermission(false);
|
|
958
|
+
}
|
|
959
|
+
if (!consent || revision !== generation) throw new Error("Installation collection was cancelled.");
|
|
960
|
+
const native = NativeModules2.SagepilotEventsAddon;
|
|
961
|
+
if (!native?.uploadBatch) throw new Error("Rebuild the app with the native events module installed.");
|
|
962
|
+
return native.uploadBatch(lease, authorization.url, { ...authorization.headers, "Content-Encoding": "gzip" });
|
|
963
|
+
}
|
|
964
|
+
return {
|
|
965
|
+
/** Bootstraps installation scope and attaches the existing native lifecycle, projection and journal. */
|
|
966
|
+
async start() {
|
|
967
|
+
if (started) throw new Error("Installation events already started.");
|
|
968
|
+
const revision = ++generation;
|
|
969
|
+
const session = await client.start(options.anonymousId);
|
|
970
|
+
if (revision !== generation) throw new Error("Installation events startup was cancelled.");
|
|
971
|
+
const initialPermission = consent && session.collection_enabled;
|
|
972
|
+
await addon.setCollectionEnabled(initialPermission);
|
|
973
|
+
if (revision !== generation) throw new Error("Installation events startup was cancelled.");
|
|
974
|
+
appliedPermission = initialPermission;
|
|
975
|
+
await addon.start({
|
|
976
|
+
workspaceId: session.workspace_id,
|
|
977
|
+
installationId: session.installation_id,
|
|
978
|
+
sdkVersion: version,
|
|
979
|
+
excludedOrigin: new URL(client.apiHost).origin,
|
|
980
|
+
owner: { session_id: session.session_id, customer_id: null },
|
|
981
|
+
upload
|
|
982
|
+
});
|
|
983
|
+
if (revision !== generation) {
|
|
984
|
+
addon.stop();
|
|
985
|
+
throw new Error("Installation events startup was cancelled.");
|
|
986
|
+
}
|
|
987
|
+
started = true;
|
|
988
|
+
await applyPermission(consent && session.collection_enabled);
|
|
989
|
+
timer = setInterval(() => {
|
|
990
|
+
void syncPolicy();
|
|
991
|
+
}, 6e4);
|
|
992
|
+
},
|
|
993
|
+
/** Applies local permission while keeping server collection policy authoritative. */
|
|
994
|
+
async setCollectionEnabled(enabled) {
|
|
995
|
+
consent = enabled;
|
|
996
|
+
generation++;
|
|
997
|
+
client.cancelPending();
|
|
998
|
+
await applyPermission(enabled && client.session()?.collection_enabled === true);
|
|
999
|
+
},
|
|
1000
|
+
/** Flushes the existing native journal through the installation ingress. */
|
|
1001
|
+
async flush() {
|
|
1002
|
+
if (started && consent) await addon.flush();
|
|
1003
|
+
},
|
|
1004
|
+
/** Reads aggregate native diagnostics without exposing observation bodies. */
|
|
1005
|
+
async diagnostics() {
|
|
1006
|
+
return addon.diagnostics();
|
|
1007
|
+
},
|
|
1008
|
+
/** Stops the collector and its installation session. */
|
|
1009
|
+
destroy() {
|
|
1010
|
+
generation++;
|
|
1011
|
+
permissionRevision++;
|
|
1012
|
+
consent = false;
|
|
1013
|
+
started = false;
|
|
1014
|
+
appliedPermission = false;
|
|
1015
|
+
if (timer) clearInterval(timer);
|
|
1016
|
+
timer = null;
|
|
1017
|
+
addon.stop();
|
|
1018
|
+
client.destroy();
|
|
1019
|
+
}
|
|
1020
|
+
};
|
|
1021
|
+
}
|
|
1022
|
+
export {
|
|
1023
|
+
createSagepilotInstallationEvents
|
|
1024
|
+
};
|