@sagepilot-ai/react-native-sdk 0.3.6 → 0.4.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/README.md +45 -0
- package/dist/index.d.mts +208 -1
- package/dist/index.d.ts +208 -1
- package/dist/index.js +672 -105
- package/dist/index.mjs +616 -51
- package/package.json +1 -1
package/dist/index.js
CHANGED
|
@@ -6,8 +6,8 @@ var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
|
6
6
|
var __getProtoOf = Object.getPrototypeOf;
|
|
7
7
|
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
|
8
8
|
var __export = (target, all) => {
|
|
9
|
-
for (var
|
|
10
|
-
__defProp(target,
|
|
9
|
+
for (var name2 in all)
|
|
10
|
+
__defProp(target, name2, { get: all[name2], enumerable: true });
|
|
11
11
|
};
|
|
12
12
|
var __copyProps = (to, from, except, desc) => {
|
|
13
13
|
if (from && typeof from === "object" || typeof from === "function") {
|
|
@@ -33,11 +33,13 @@ __export(index_exports, {
|
|
|
33
33
|
SAGEPILOT_DEFAULT_IMAGE_MAX_DIMENSION: () => SAGEPILOT_DEFAULT_IMAGE_MAX_DIMENSION,
|
|
34
34
|
SAGEPILOT_DEFAULT_IMAGE_MAX_FILE_SIZE_BYTES: () => SAGEPILOT_DEFAULT_IMAGE_MAX_FILE_SIZE_BYTES,
|
|
35
35
|
SAGEPILOT_DEFAULT_IMAGE_QUALITY: () => SAGEPILOT_DEFAULT_IMAGE_QUALITY,
|
|
36
|
+
SagepilotBrandPush: () => SagepilotBrandPush,
|
|
36
37
|
SagepilotChat: () => SagepilotChat,
|
|
37
38
|
SagepilotChatError: () => SagepilotChatError,
|
|
38
39
|
SagepilotChatProvider: () => SagepilotChatProvider,
|
|
39
40
|
SagepilotFilePickerError: () => SagepilotFilePickerError,
|
|
40
41
|
createAsyncStorageCacheStorage: () => createAsyncStorageCacheStorage,
|
|
42
|
+
createFirebasePushAdapter: () => createFirebasePushAdapter,
|
|
41
43
|
createKeychainTokenStorage: () => createKeychainTokenStorage,
|
|
42
44
|
createSagepilotFilePicker: () => createSagepilotFilePicker,
|
|
43
45
|
createSagepilotFileStore: () => createSagepilotFileStore,
|
|
@@ -48,6 +50,22 @@ __export(index_exports, {
|
|
|
48
50
|
module.exports = __toCommonJS(index_exports);
|
|
49
51
|
|
|
50
52
|
// src/public/SdkClient.ts
|
|
53
|
+
var import_react_native2 = require("react-native");
|
|
54
|
+
|
|
55
|
+
// package.json
|
|
56
|
+
var name = "@sagepilot-ai/react-native-sdk";
|
|
57
|
+
var version = "0.4.1";
|
|
58
|
+
|
|
59
|
+
// src/core/config/constants.ts
|
|
60
|
+
var SDK_NAME = name;
|
|
61
|
+
var SDK_VERSION = version;
|
|
62
|
+
var DEFAULT_HOST = "https://app.sagepilot.ai";
|
|
63
|
+
var DEFAULT_WIDGET_HOST = "https://app.sagepilot.ai";
|
|
64
|
+
var CUSTOMER_API_PREFIX = "/customer-api/v1";
|
|
65
|
+
var DEFAULT_UNREAD_POLL_INTERVAL_MS = 3e4;
|
|
66
|
+
var DEFAULT_HOSTED_CLAIMS_STORAGE_KEY_PREFIX = "sg_chat_claims";
|
|
67
|
+
|
|
68
|
+
// src/push.ts
|
|
51
69
|
var import_react_native = require("react-native");
|
|
52
70
|
|
|
53
71
|
// src/core/errors/SagepilotChatError.ts
|
|
@@ -65,14 +83,335 @@ var SagepilotChatError = class extends Error {
|
|
|
65
83
|
}
|
|
66
84
|
};
|
|
67
85
|
|
|
68
|
-
// src/core/
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
86
|
+
// src/core/storage/cache.ts
|
|
87
|
+
function createAsyncStorageCacheStorage(asyncStorage) {
|
|
88
|
+
return {
|
|
89
|
+
getItem: (key) => asyncStorage.getItem(key),
|
|
90
|
+
setItem: (key, value) => asyncStorage.setItem(key, value),
|
|
91
|
+
removeItem: (key) => asyncStorage.removeItem(key)
|
|
92
|
+
};
|
|
93
|
+
}
|
|
94
|
+
function createJsonCache(storage, namespace, strict = false) {
|
|
95
|
+
return {
|
|
96
|
+
async get(key) {
|
|
97
|
+
const value = await storage.getItem(`${namespace}:${key}`);
|
|
98
|
+
if (!value) return null;
|
|
99
|
+
try {
|
|
100
|
+
return JSON.parse(value);
|
|
101
|
+
} catch (error) {
|
|
102
|
+
if (strict) throw error;
|
|
103
|
+
return null;
|
|
104
|
+
}
|
|
105
|
+
},
|
|
106
|
+
async set(key, value) {
|
|
107
|
+
await storage.setItem(`${namespace}:${key}`, JSON.stringify(value));
|
|
108
|
+
},
|
|
109
|
+
async remove(key) {
|
|
110
|
+
await storage.removeItem(`${namespace}:${key}`);
|
|
111
|
+
}
|
|
112
|
+
};
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
// src/push.ts
|
|
116
|
+
var INSTALLATION_ID = /^\S{1,255}$/;
|
|
117
|
+
var MAX_EVENTS = 200;
|
|
118
|
+
var MAX_AGE_MS = 7 * 24 * 60 * 60 * 1e3;
|
|
119
|
+
function createId() {
|
|
120
|
+
return "10000000-1000-4000-8000-100000000000".replace(
|
|
121
|
+
/[018]/g,
|
|
122
|
+
(value) => (Number(value) ^ Math.floor(Math.random() * 16) >> Number(value) / 4).toString(16)
|
|
123
|
+
);
|
|
124
|
+
}
|
|
125
|
+
function eventKey(event) {
|
|
126
|
+
return JSON.stringify([event.message_id, event.endpoint_id, event.event_type, ["action", "conversion"].includes(event.event_type) ? event.action_id ?? "" : ""]);
|
|
127
|
+
}
|
|
128
|
+
var SagepilotPush = class {
|
|
129
|
+
/** Reuses a channel-specific durable cache and the SDK's authenticated request gateway. */
|
|
130
|
+
constructor(config, context) {
|
|
131
|
+
this.config = config;
|
|
132
|
+
this.context = context;
|
|
133
|
+
this.pending = Promise.resolve();
|
|
134
|
+
this.paused = false;
|
|
135
|
+
this.stopped = false;
|
|
136
|
+
this.started = false;
|
|
137
|
+
this.flushPromise = null;
|
|
138
|
+
this.retryTimer = null;
|
|
139
|
+
this.retryAttempt = 0;
|
|
140
|
+
this.subscriptions = [];
|
|
141
|
+
if (config.installationId !== void 0 && !INSTALLATION_ID.test(config.installationId)) {
|
|
142
|
+
throw new SagepilotChatError("invalid_config", "Push installationId must contain 1\u2013255 non-whitespace characters.");
|
|
143
|
+
}
|
|
144
|
+
this.cache = createJsonCache(config.storage, `sagepilot_push:${context.workspaceId}:${context.channelId}`, true);
|
|
145
|
+
}
|
|
146
|
+
/** Serializes state changes so registration, revocation and outbox writes cannot overwrite one another. */
|
|
147
|
+
mutate(operation) {
|
|
148
|
+
const next = this.pending.then(async () => {
|
|
149
|
+
if (this.stopped) throw new Error("Push has been stopped. Configure the SDK again.");
|
|
150
|
+
const saved = await this.cache.get("state");
|
|
151
|
+
if (this.stopped) throw new Error("Push has been stopped.");
|
|
152
|
+
if (saved && (!INSTALLATION_ID.test(saved.installationId) || !Array.isArray(saved.outbox) || !Array.isArray(saved.recent))) {
|
|
153
|
+
throw new Error("Invalid persisted push state; refusing to discard a possible device binding.");
|
|
154
|
+
}
|
|
155
|
+
if (saved && this.config.installationId && saved.installationId !== this.config.installationId) {
|
|
156
|
+
throw new Error("Reuse the persisted installationId; revoke and clear push storage before replacing it.");
|
|
157
|
+
}
|
|
158
|
+
const state = saved ?? { installationId: this.config.installationId || createId(), outbox: [], recent: [] };
|
|
159
|
+
if (!saved) await this.cache.set("state", state);
|
|
160
|
+
return operation(state);
|
|
161
|
+
});
|
|
162
|
+
this.pending = next.catch(() => void 0);
|
|
163
|
+
return next;
|
|
164
|
+
}
|
|
165
|
+
/** Starts optional native listeners without prompting for notification permission. */
|
|
166
|
+
async start() {
|
|
167
|
+
if (this.started) return;
|
|
168
|
+
this.started = true;
|
|
169
|
+
const binding = await this.mutate(async (state) => state.binding);
|
|
170
|
+
const adapter = this.config.adapter;
|
|
171
|
+
if (adapter) {
|
|
172
|
+
if (adapter.start) this.subscriptions.push(await adapter.start({
|
|
173
|
+
workspaceId: this.context.workspaceId,
|
|
174
|
+
channelId: this.context.channelId,
|
|
175
|
+
sdkVersion: SDK_VERSION,
|
|
176
|
+
owner: binding?.endpointId && binding.customerId === this.context.customerId() ? { customerId: binding.customerId, endpointId: binding.endpointId } : null,
|
|
177
|
+
customerId: this.context.customerId,
|
|
178
|
+
upload: (event) => this.context.request("/push/events", "POST", event),
|
|
179
|
+
onOpen: (message) => this.config.onOpen?.(message)
|
|
180
|
+
}));
|
|
181
|
+
this.subscriptions.push(
|
|
182
|
+
adapter.onTokenRefresh((token) => {
|
|
183
|
+
void this.sync(token).catch(this.context.onError);
|
|
184
|
+
}),
|
|
185
|
+
adapter.onMessage((message) => {
|
|
186
|
+
void this.handleReceived(message, true).catch(this.context.onError);
|
|
187
|
+
}),
|
|
188
|
+
adapter.onOpened((message) => {
|
|
189
|
+
void this.handleOpened(message).catch(this.context.onError);
|
|
190
|
+
})
|
|
191
|
+
);
|
|
192
|
+
const initial = await adapter.getInitialNotification();
|
|
193
|
+
if (initial) await this.handleOpened(initial);
|
|
194
|
+
}
|
|
195
|
+
void this.sync().catch(this.context.onError);
|
|
196
|
+
void this.flush().catch(this.context.onError);
|
|
197
|
+
}
|
|
198
|
+
/** Requests native permission only following an explicit host action, then resynchronizes the token. */
|
|
199
|
+
async requestPermission() {
|
|
200
|
+
if (!this.config.adapter) throw new Error("Configure a push adapter to request native permission.");
|
|
201
|
+
const permission = await this.config.adapter.requestPermission();
|
|
202
|
+
await this.sync();
|
|
203
|
+
return permission;
|
|
204
|
+
}
|
|
205
|
+
/** Refreshes an existing authorized installation after identity, token or permission changes. */
|
|
206
|
+
async sync(token) {
|
|
207
|
+
if (this.paused || this.stopped || !this.context.customerId() || !this.config.adapter) return;
|
|
208
|
+
const adapter = this.config.adapter;
|
|
209
|
+
const permission = await adapter.getPermission();
|
|
210
|
+
if (permission !== "authorized" && permission !== "provisional") {
|
|
211
|
+
await this.unregister();
|
|
212
|
+
return;
|
|
213
|
+
}
|
|
214
|
+
await this.register({ token: token ?? await adapter.getToken(), provider: adapter.provider, permission, app_id: this.config.appId });
|
|
215
|
+
}
|
|
216
|
+
/** Registers a native token only for the current identified customer; the server verifies identity. */
|
|
217
|
+
async register(input) {
|
|
218
|
+
if (!input.token.trim() || !["authorized", "provisional"].includes(input.permission)) {
|
|
219
|
+
throw new SagepilotChatError("invalid_request", "Push registration requires a token and notification permission.");
|
|
220
|
+
}
|
|
221
|
+
return this.mutate(async (state) => {
|
|
222
|
+
const customerId = this.context.customerId();
|
|
223
|
+
if (this.paused || !customerId) throw new SagepilotChatError("forbidden", "Identify a verified customer before registering push.");
|
|
224
|
+
if (state.binding && state.binding.customerId !== customerId) {
|
|
225
|
+
throw new SagepilotChatError("forbidden", "Revoke the previous customer's push binding before switching accounts.");
|
|
226
|
+
}
|
|
227
|
+
const previousBinding = state.binding;
|
|
228
|
+
state.binding = { ...state.binding, customerId };
|
|
229
|
+
await this.cache.set("state", state);
|
|
230
|
+
let result;
|
|
231
|
+
try {
|
|
232
|
+
result = await this.context.request("/push/endpoints", "POST", {
|
|
233
|
+
token: input.token,
|
|
234
|
+
provider: input.provider,
|
|
235
|
+
permission: input.permission,
|
|
236
|
+
app_id: input.app_id ?? this.config.appId,
|
|
237
|
+
installation_id: state.installationId,
|
|
238
|
+
platform: this.context.platform,
|
|
239
|
+
metadata: {
|
|
240
|
+
sdk: SDK_NAME,
|
|
241
|
+
sdk_version: SDK_VERSION,
|
|
242
|
+
app_version: this.config.appVersion,
|
|
243
|
+
capabilities: input.capabilities ?? this.config.adapter?.capabilities ?? { version: 1, display_modes: ["provider"], media: [] }
|
|
244
|
+
}
|
|
245
|
+
});
|
|
246
|
+
} catch (error) {
|
|
247
|
+
if (!this.stopped && error instanceof SagepilotChatError && [400, 401, 403, 422].includes(error.status ?? 0)) {
|
|
248
|
+
state.binding = previousBinding;
|
|
249
|
+
await this.cache.set("state", state);
|
|
250
|
+
}
|
|
251
|
+
throw error;
|
|
252
|
+
}
|
|
253
|
+
if (!result.endpoint_id) throw new Error("Push registration returned no endpoint_id.");
|
|
254
|
+
if (this.stopped) return result;
|
|
255
|
+
state.binding = { customerId, endpointId: result.endpoint_id };
|
|
256
|
+
await this.cache.set("state", state);
|
|
257
|
+
await this.config.adapter?.setOwner?.({ customerId, endpointId: result.endpoint_id });
|
|
258
|
+
return result;
|
|
259
|
+
});
|
|
260
|
+
}
|
|
261
|
+
/** Revokes this installation before credentials are discarded; failures retain the binding for retry. */
|
|
262
|
+
async unregister() {
|
|
263
|
+
await this.mutate(async (state) => {
|
|
264
|
+
if (!state.binding) {
|
|
265
|
+
await this.config.adapter?.setOwner?.(null);
|
|
266
|
+
return;
|
|
267
|
+
}
|
|
268
|
+
await this.context.request("/push/endpoints", "DELETE", { installation_id: state.installationId });
|
|
269
|
+
if (this.stopped) return;
|
|
270
|
+
delete state.binding;
|
|
271
|
+
await this.cache.set("state", state);
|
|
272
|
+
await this.config.adapter?.setOwner?.(null);
|
|
273
|
+
});
|
|
274
|
+
}
|
|
275
|
+
/** Pauses refresh callbacks and revokes the installation before logout or identity replacement. */
|
|
276
|
+
async pauseAndRevoke() {
|
|
277
|
+
this.paused = true;
|
|
278
|
+
await this.unregister();
|
|
279
|
+
}
|
|
280
|
+
/** Allows token refresh again after the identity transition has finished. */
|
|
281
|
+
resume() {
|
|
282
|
+
this.paused = false;
|
|
283
|
+
void this.sync().catch(this.context.onError);
|
|
284
|
+
void this.flush().catch(this.context.onError);
|
|
285
|
+
}
|
|
286
|
+
/** Reads notification preferences for the current verified customer. */
|
|
287
|
+
getPreferences() {
|
|
288
|
+
return this.context.request("/push/preferences", "GET");
|
|
289
|
+
}
|
|
290
|
+
/** Saves customer consent independently of the device's notification permission. */
|
|
291
|
+
setPreferences(preferences) {
|
|
292
|
+
return this.context.request("/push/preferences", "PUT", preferences);
|
|
293
|
+
}
|
|
294
|
+
/** Persists actual callback receipt and presents only foreground messages when the host opted in. */
|
|
295
|
+
async handleReceived(message, foreground = false) {
|
|
296
|
+
const recorded = await this.track("received", message);
|
|
297
|
+
if (recorded && foreground && this.config.presentForeground) {
|
|
298
|
+
if (await this.track("presentation_requested", message)) {
|
|
299
|
+
try {
|
|
300
|
+
await this.config.presentForeground(message);
|
|
301
|
+
} catch (error) {
|
|
302
|
+
await this.track("presentation_failed", message);
|
|
303
|
+
throw error;
|
|
304
|
+
}
|
|
305
|
+
}
|
|
306
|
+
}
|
|
307
|
+
return recorded;
|
|
308
|
+
}
|
|
309
|
+
/** Persists a real tap before invoking host navigation, including cold-start taps. */
|
|
310
|
+
async handleOpened(message) {
|
|
311
|
+
const recorded = await this.track("opened", message);
|
|
312
|
+
if (recorded && !this.config.adapter?.track) this.config.onOpen?.(message);
|
|
313
|
+
return recorded;
|
|
314
|
+
}
|
|
315
|
+
/** Records SDK engagement; reuse actionId for duplicate callbacks and distinct IDs for separate conversions. */
|
|
316
|
+
async track(type, message, metadata = {}, actionId) {
|
|
317
|
+
if (this.config.adapter?.track) return this.config.adapter.track(type, message, metadata, actionId);
|
|
318
|
+
const data = message.data;
|
|
319
|
+
if (this.context.brand && data?.sp_channel_id !== this.context.channelId) return false;
|
|
320
|
+
if (data?.sp_source_channel_id && data.sp_source_channel_id !== this.context.channelId) return false;
|
|
321
|
+
if (!data || data.sp_workspace_id !== this.context.workspaceId || !data.sp_message_id || !data.sp_endpoint_id || !data.sp_event_token) return false;
|
|
322
|
+
const event = {
|
|
323
|
+
event_id: createId(),
|
|
324
|
+
occurred_at: (/* @__PURE__ */ new Date()).toISOString(),
|
|
325
|
+
sdk_version: SDK_VERSION,
|
|
326
|
+
event_type: type,
|
|
327
|
+
message_id: data.sp_message_id,
|
|
328
|
+
endpoint_id: data.sp_endpoint_id,
|
|
329
|
+
event_token: data.sp_event_token,
|
|
330
|
+
...actionId ? { action_id: actionId } : {},
|
|
331
|
+
metadata: {
|
|
332
|
+
platform: this.context.platform,
|
|
333
|
+
app_id: this.config.appId,
|
|
334
|
+
app_version: this.config.appVersion,
|
|
335
|
+
app_state: import_react_native.AppState.currentState ?? "unknown",
|
|
336
|
+
...metadata,
|
|
337
|
+
sdk: SDK_NAME,
|
|
338
|
+
sdk_version: SDK_VERSION
|
|
339
|
+
}
|
|
340
|
+
};
|
|
341
|
+
const recorded = await this.mutate(async (state) => {
|
|
342
|
+
const key = eventKey(event);
|
|
343
|
+
if (state.recent.includes(key) || state.outbox.some((item) => eventKey(item) === key)) return false;
|
|
344
|
+
if (state.outbox.length >= MAX_EVENTS) throw new Error("Push analytics outbox is full; retry after connectivity is restored.");
|
|
345
|
+
state.outbox.push(event);
|
|
346
|
+
await this.cache.set("state", state);
|
|
347
|
+
return true;
|
|
348
|
+
});
|
|
349
|
+
if (recorded) void this.flush().catch(this.context.onError);
|
|
350
|
+
return recorded;
|
|
351
|
+
}
|
|
352
|
+
/** Uploads preserved event metadata with the current request version and bounded exponential retries. */
|
|
353
|
+
async flush() {
|
|
354
|
+
if (this.stopped) return;
|
|
355
|
+
if (this.config.adapter?.flush) await this.config.adapter.flush();
|
|
356
|
+
if (this.flushPromise) return this.flushPromise;
|
|
357
|
+
this.flushPromise = (async () => {
|
|
358
|
+
while (!this.stopped) {
|
|
359
|
+
const event = await this.mutate(async (state) => state.outbox[0]);
|
|
360
|
+
if (!event) break;
|
|
361
|
+
if (Date.now() - Date.parse(event.occurred_at) > MAX_AGE_MS) {
|
|
362
|
+
this.context.onError(new Error(`Push event ${event.event_id} expired before upload.`));
|
|
363
|
+
} else {
|
|
364
|
+
try {
|
|
365
|
+
await this.context.request("/push/events", "POST", event);
|
|
366
|
+
} catch (error) {
|
|
367
|
+
const status = error instanceof SagepilotChatError ? error.status : void 0;
|
|
368
|
+
const terminalTokenError = status === 401 && error instanceof SagepilotChatError && error.details?.terminal === true;
|
|
369
|
+
if (!terminalTokenError && ![400, 403, 404, 410, 422].includes(status ?? 0)) throw error;
|
|
370
|
+
this.context.onError(error);
|
|
371
|
+
}
|
|
372
|
+
}
|
|
373
|
+
if (this.stopped) return;
|
|
374
|
+
await this.mutate(async (state) => {
|
|
375
|
+
state.outbox = state.outbox.filter((queued) => queued.event_id !== event.event_id);
|
|
376
|
+
state.recent = [...state.recent, eventKey(event)].slice(-MAX_EVENTS);
|
|
377
|
+
await this.cache.set("state", state);
|
|
378
|
+
});
|
|
379
|
+
}
|
|
380
|
+
this.retryAttempt = 0;
|
|
381
|
+
})().catch((error) => {
|
|
382
|
+
if (!this.stopped && !this.retryTimer) {
|
|
383
|
+
this.retryTimer = setTimeout(() => {
|
|
384
|
+
this.retryTimer = null;
|
|
385
|
+
void this.flush().catch(this.context.onError);
|
|
386
|
+
}, Math.min(6e4, 1e3 * 2 ** Math.min(this.retryAttempt++, 6)));
|
|
387
|
+
}
|
|
388
|
+
throw error;
|
|
389
|
+
}).finally(() => {
|
|
390
|
+
this.flushPromise = null;
|
|
391
|
+
});
|
|
392
|
+
return this.flushPromise;
|
|
393
|
+
}
|
|
394
|
+
/** Removes listeners and timers without revoking an installation merely because its UI was destroyed. */
|
|
395
|
+
stop() {
|
|
396
|
+
this.stopped = true;
|
|
397
|
+
this.subscriptions.forEach((unsubscribe) => unsubscribe());
|
|
398
|
+
this.subscriptions = [];
|
|
399
|
+
if (this.retryTimer) clearTimeout(this.retryTimer);
|
|
400
|
+
this.retryTimer = null;
|
|
401
|
+
}
|
|
402
|
+
};
|
|
403
|
+
function createFirebasePushAdapter(firebase, permissions) {
|
|
404
|
+
return {
|
|
405
|
+
provider: "fcm",
|
|
406
|
+
getToken: () => firebase.getToken(),
|
|
407
|
+
getPermission: () => permissions.getPermission(),
|
|
408
|
+
requestPermission: () => permissions.requestPermission(),
|
|
409
|
+
onTokenRefresh: (callback) => firebase.onTokenRefresh(callback),
|
|
410
|
+
onMessage: (callback) => firebase.onMessage(callback),
|
|
411
|
+
onOpened: (callback) => firebase.onNotificationOpenedApp(callback),
|
|
412
|
+
getInitialNotification: () => firebase.getInitialNotification()
|
|
413
|
+
};
|
|
414
|
+
}
|
|
76
415
|
|
|
77
416
|
// src/core/auth/sessionManager.ts
|
|
78
417
|
var SagepilotSessionManager = class {
|
|
@@ -97,7 +436,7 @@ var SagepilotSessionManager = class {
|
|
|
97
436
|
return this.currentSession;
|
|
98
437
|
}
|
|
99
438
|
async setSession(session) {
|
|
100
|
-
|
|
439
|
+
const nextSession = {
|
|
101
440
|
session_id: session.session_id,
|
|
102
441
|
session_token: session.session_token,
|
|
103
442
|
customer_id: session.customer_id ?? null,
|
|
@@ -105,7 +444,8 @@ var SagepilotSessionManager = class {
|
|
|
105
444
|
authenticated: session.authenticated ?? false,
|
|
106
445
|
updated_at: (/* @__PURE__ */ new Date()).toISOString()
|
|
107
446
|
};
|
|
108
|
-
await this.tokenManager.setSession(
|
|
447
|
+
await this.tokenManager.setSession(nextSession);
|
|
448
|
+
this.currentSession = nextSession;
|
|
109
449
|
return this.currentSession;
|
|
110
450
|
}
|
|
111
451
|
async updateSession(updates) {
|
|
@@ -222,8 +562,8 @@ var SagepilotTokenManager = class {
|
|
|
222
562
|
function normalizeHost(host = DEFAULT_HOST) {
|
|
223
563
|
return host.replace(/\/+$/, "");
|
|
224
564
|
}
|
|
225
|
-
function readRuntimeEnv(
|
|
226
|
-
return globalThis.process?.env?.[
|
|
565
|
+
function readRuntimeEnv(name2) {
|
|
566
|
+
return globalThis.process?.env?.[name2]?.trim();
|
|
227
567
|
}
|
|
228
568
|
function resolveSagepilotHost(configuredHost) {
|
|
229
569
|
const envHost = readRuntimeEnv("EXPO_PUBLIC_SAGEPILOT_HOST") || readRuntimeEnv("SAGEPILOT_HOST") || readRuntimeEnv("EXPO_PUBLIC_SAGEPILOT_CUSTOMER_API_BASE_URL") || readRuntimeEnv("SAGEPILOT_CUSTOMER_API_BASE_URL");
|
|
@@ -326,6 +666,9 @@ var SagepilotHttpClient = class {
|
|
|
326
666
|
this.retryPolicy = resolveRetryPolicy(options.retryPolicy);
|
|
327
667
|
}
|
|
328
668
|
async request(url, init) {
|
|
669
|
+
const headers = mergeHeaders(this.baseHeaders, init.headers);
|
|
670
|
+
headers.set("X-Sagepilot-Sdk-Name", SDK_NAME);
|
|
671
|
+
headers.set("X-Sagepilot-Sdk-Version", SDK_VERSION);
|
|
329
672
|
const policy = resolveRetryPolicy(init.retryPolicy ?? this.retryPolicy);
|
|
330
673
|
const method = (init.method ?? "GET").toUpperCase();
|
|
331
674
|
const canRetry = RETRYABLE_METHODS.has(method);
|
|
@@ -335,7 +678,7 @@ var SagepilotHttpClient = class {
|
|
|
335
678
|
try {
|
|
336
679
|
response = await this.fetchImpl(url, {
|
|
337
680
|
...init,
|
|
338
|
-
headers
|
|
681
|
+
headers
|
|
339
682
|
});
|
|
340
683
|
} catch (error) {
|
|
341
684
|
lastNetworkError = error;
|
|
@@ -376,34 +719,6 @@ async function resolveDeviceInfo(adapter) {
|
|
|
376
719
|
return adapter.getDeviceInfo();
|
|
377
720
|
}
|
|
378
721
|
|
|
379
|
-
// src/core/storage/cache.ts
|
|
380
|
-
function createAsyncStorageCacheStorage(asyncStorage) {
|
|
381
|
-
return {
|
|
382
|
-
getItem: (key) => asyncStorage.getItem(key),
|
|
383
|
-
setItem: (key, value) => asyncStorage.setItem(key, value),
|
|
384
|
-
removeItem: (key) => asyncStorage.removeItem(key)
|
|
385
|
-
};
|
|
386
|
-
}
|
|
387
|
-
function createJsonCache(storage, namespace) {
|
|
388
|
-
return {
|
|
389
|
-
async get(key) {
|
|
390
|
-
const value = await storage.getItem(`${namespace}:${key}`);
|
|
391
|
-
if (!value) return null;
|
|
392
|
-
try {
|
|
393
|
-
return JSON.parse(value);
|
|
394
|
-
} catch {
|
|
395
|
-
return null;
|
|
396
|
-
}
|
|
397
|
-
},
|
|
398
|
-
async set(key, value) {
|
|
399
|
-
await storage.setItem(`${namespace}:${key}`, JSON.stringify(value));
|
|
400
|
-
},
|
|
401
|
-
async remove(key) {
|
|
402
|
-
await storage.removeItem(`${namespace}:${key}`);
|
|
403
|
-
}
|
|
404
|
-
};
|
|
405
|
-
}
|
|
406
|
-
|
|
407
722
|
// src/resources/channels.ts
|
|
408
723
|
function bootstrapChannel(http, host, channelId) {
|
|
409
724
|
return http.request(
|
|
@@ -427,9 +742,9 @@ function createSession(http, host, channelId, input) {
|
|
|
427
742
|
anonymous_id: input.anonymousId,
|
|
428
743
|
metadata: {
|
|
429
744
|
platform: "react_native",
|
|
745
|
+
...input.metadata,
|
|
430
746
|
sdk: SDK_NAME,
|
|
431
|
-
sdk_version: SDK_VERSION
|
|
432
|
-
...input.metadata
|
|
747
|
+
sdk_version: SDK_VERSION
|
|
433
748
|
}
|
|
434
749
|
}),
|
|
435
750
|
errorMessage: `${SDK_NAME} Failed to create customer session.`
|
|
@@ -576,6 +891,9 @@ function toPublicSessionState(session) {
|
|
|
576
891
|
var SagepilotReactNativeChat = class {
|
|
577
892
|
constructor() {
|
|
578
893
|
this.sdkName = SDK_NAME;
|
|
894
|
+
this.pushClient = null;
|
|
895
|
+
this.pushChannelId = null;
|
|
896
|
+
this.pushAppStateSubscription = null;
|
|
579
897
|
this.runtimeOptions = null;
|
|
580
898
|
this.http = null;
|
|
581
899
|
this.sessionManager = null;
|
|
@@ -605,6 +923,11 @@ var SagepilotReactNativeChat = class {
|
|
|
605
923
|
this.dismissCallbacks = /* @__PURE__ */ new Set();
|
|
606
924
|
this.errorCallbacks = /* @__PURE__ */ new Set();
|
|
607
925
|
}
|
|
926
|
+
/** Returns the configured push lifecycle and analytics API. */
|
|
927
|
+
get push() {
|
|
928
|
+
if (!this.pushClient) throw new SagepilotChatError("invalid_config", "Configure push with durable storage before using the push API.");
|
|
929
|
+
return this.pushClient;
|
|
930
|
+
}
|
|
608
931
|
async configure(config) {
|
|
609
932
|
if (this.isConfigured) {
|
|
610
933
|
throw new SagepilotChatError(
|
|
@@ -656,7 +979,38 @@ var SagepilotReactNativeChat = class {
|
|
|
656
979
|
const session = await this.resolveCustomerSession(config);
|
|
657
980
|
this.channel = channel;
|
|
658
981
|
this.session = session;
|
|
982
|
+
if (config.push) this.legacyWidgetJwt = session.legacy_jwt ?? null;
|
|
659
983
|
this.isConfigured = true;
|
|
984
|
+
if (config.push) {
|
|
985
|
+
if (import_react_native2.Platform.OS !== "ios" && import_react_native2.Platform.OS !== "android") {
|
|
986
|
+
throw new SagepilotChatError("invalid_config", "Push is supported on Android and iOS.");
|
|
987
|
+
}
|
|
988
|
+
this.pushChannelId = config.push.channelId ?? null;
|
|
989
|
+
this.pushClient = new SagepilotPush(config.push, {
|
|
990
|
+
workspaceId,
|
|
991
|
+
channelId: this.pushChannelId ?? channelId,
|
|
992
|
+
platform: import_react_native2.Platform.OS,
|
|
993
|
+
brand: Boolean(this.pushChannelId),
|
|
994
|
+
customerId: () => this.session?.authenticated ? this.session.customer_id ?? null : null,
|
|
995
|
+
request: (path, method, body) => this.requireHttp().request(
|
|
996
|
+
`${this.apiHost}${CUSTOMER_API_PREFIX}${path}`,
|
|
997
|
+
{
|
|
998
|
+
method,
|
|
999
|
+
headers: withJsonHeaders(this.requireSessionManager().getAuthorizationHeader()),
|
|
1000
|
+
...body === void 0 ? {} : { body: JSON.stringify(body) },
|
|
1001
|
+
errorMessage: `${SDK_NAME} Push request failed.`
|
|
1002
|
+
}
|
|
1003
|
+
),
|
|
1004
|
+
onError: (error) => this.emitError(error)
|
|
1005
|
+
});
|
|
1006
|
+
await this.pushClient.start();
|
|
1007
|
+
this.pushAppStateSubscription = import_react_native2.AppState.addEventListener("change", (state) => {
|
|
1008
|
+
if (state === "active") {
|
|
1009
|
+
void this.pushClient?.sync().catch((error) => this.emitError(error));
|
|
1010
|
+
void this.pushClient?.flush().catch((error) => this.emitError(error));
|
|
1011
|
+
}
|
|
1012
|
+
});
|
|
1013
|
+
}
|
|
660
1014
|
await this.restorePresentationFromCache();
|
|
661
1015
|
this.emitReady();
|
|
662
1016
|
this.emitState();
|
|
@@ -688,9 +1042,11 @@ var SagepilotReactNativeChat = class {
|
|
|
688
1042
|
async identify(identity) {
|
|
689
1043
|
const session = this.requireSession();
|
|
690
1044
|
const apiIdentity = normalizeIdentity(identity);
|
|
1045
|
+
if (this.pushClient && this.identifyPending) throw new SagepilotChatError("invalid_request", "Another identity change is in progress.");
|
|
691
1046
|
this.identifyPending = true;
|
|
692
1047
|
this.emitState();
|
|
693
1048
|
try {
|
|
1049
|
+
if (this.pushClient) await this.pushClient.pauseAndRevoke();
|
|
694
1050
|
const result = await identifySession(
|
|
695
1051
|
this.requireHttp(),
|
|
696
1052
|
this.apiHost,
|
|
@@ -726,16 +1082,58 @@ var SagepilotReactNativeChat = class {
|
|
|
726
1082
|
this.lastIdentifyResult = publicResult;
|
|
727
1083
|
this.identifyCallbacks.forEach((callback) => callback(publicResult));
|
|
728
1084
|
this.emitState();
|
|
1085
|
+
this.pushClient?.resume();
|
|
729
1086
|
return publicResult;
|
|
730
1087
|
} catch (error) {
|
|
731
1088
|
this.identifyPending = false;
|
|
1089
|
+
this.pushClient?.resume();
|
|
732
1090
|
this.emitState();
|
|
733
1091
|
this.emitError(error);
|
|
734
1092
|
throw error;
|
|
735
1093
|
}
|
|
736
1094
|
}
|
|
1095
|
+
/** Adds verified brand permission to the existing session; the host never manages another stored token. */
|
|
1096
|
+
async authorizePush(identityToken) {
|
|
1097
|
+
if (typeof identityToken !== "string" || !identityToken.trim()) {
|
|
1098
|
+
throw new SagepilotChatError("invalid_request", "A signed brand identity proof is required.");
|
|
1099
|
+
}
|
|
1100
|
+
const session = this.requireSession();
|
|
1101
|
+
if (!this.pushChannelId || !this.pushClient) throw new SagepilotChatError("invalid_config", "Configure push.channelId first.");
|
|
1102
|
+
if (this.identifyPending) throw new SagepilotChatError("invalid_request", "Another identity change is in progress.");
|
|
1103
|
+
this.identifyPending = true;
|
|
1104
|
+
try {
|
|
1105
|
+
const result = await this.requireHttp().request(
|
|
1106
|
+
`${this.apiHost}${CUSTOMER_API_PREFIX}/push/sessions`,
|
|
1107
|
+
{
|
|
1108
|
+
method: "POST",
|
|
1109
|
+
headers: withJsonHeaders(this.requireSessionManager().getAuthorizationHeader()),
|
|
1110
|
+
body: JSON.stringify({ channel_id: this.pushChannelId, identity_token: identityToken }),
|
|
1111
|
+
errorMessage: "Brand authorization failed."
|
|
1112
|
+
}
|
|
1113
|
+
);
|
|
1114
|
+
if (result.session_id !== session.session_id || result.customer_id !== session.customer_id || result.channel_id !== this.pushChannelId || result.workspace_id !== this.workspaceId || !result.session_token || !result.authenticated || this.session !== session) {
|
|
1115
|
+
throw new SagepilotChatError("forbidden", "Brand session scope changed.");
|
|
1116
|
+
}
|
|
1117
|
+
this.session = await this.requireSessionManager().setSession({ ...session, session_token: result.session_token });
|
|
1118
|
+
this.legacyWidgetJwt = result.legacy_jwt ?? this.legacyWidgetJwt;
|
|
1119
|
+
this.pushClient.resume();
|
|
1120
|
+
} finally {
|
|
1121
|
+
this.identifyPending = false;
|
|
1122
|
+
}
|
|
1123
|
+
}
|
|
737
1124
|
async logout() {
|
|
738
1125
|
const session = this.requireSession();
|
|
1126
|
+
if (this.pushClient) {
|
|
1127
|
+
if (this.identifyPending) throw new SagepilotChatError("invalid_request", "Another identity change is in progress.");
|
|
1128
|
+
this.identifyPending = true;
|
|
1129
|
+
try {
|
|
1130
|
+
await this.pushClient.pauseAndRevoke();
|
|
1131
|
+
} catch (error) {
|
|
1132
|
+
this.identifyPending = false;
|
|
1133
|
+
this.emitState();
|
|
1134
|
+
throw error;
|
|
1135
|
+
}
|
|
1136
|
+
}
|
|
739
1137
|
const wasUnreadPolling = this.unreadPollTimer !== null;
|
|
740
1138
|
let result = null;
|
|
741
1139
|
let logoutError = null;
|
|
@@ -775,6 +1173,7 @@ var SagepilotReactNativeChat = class {
|
|
|
775
1173
|
throw error;
|
|
776
1174
|
}
|
|
777
1175
|
this.session = freshSession;
|
|
1176
|
+
this.pushClient?.resume();
|
|
778
1177
|
this.setUnreadCount(0);
|
|
779
1178
|
this.emitState();
|
|
780
1179
|
this.persistPresentationState();
|
|
@@ -983,6 +1382,8 @@ var SagepilotReactNativeChat = class {
|
|
|
983
1382
|
const path = this.hostedChatView.screen === "home" ? `/chat-widget/${encodeURIComponent(this.channelId)}` : `/chat-widget/${encodeURIComponent(this.channelId)}/conversations`;
|
|
984
1383
|
const url = new URL(`${this.widgetHost}${path}`);
|
|
985
1384
|
url.searchParams.set("sdk", "react-native");
|
|
1385
|
+
url.searchParams.set("sdk_name", SDK_NAME);
|
|
1386
|
+
url.searchParams.set("sdk_version", SDK_VERSION);
|
|
986
1387
|
if (this.runtimeOptions?.presentation?.mobile ?? true) {
|
|
987
1388
|
url.searchParams.set("mobile", "1");
|
|
988
1389
|
}
|
|
@@ -1071,7 +1472,7 @@ var SagepilotReactNativeChat = class {
|
|
|
1071
1472
|
}
|
|
1072
1473
|
/** Restores the hosted route for a queued attachment batch before delivery. */
|
|
1073
1474
|
restoreHostedAttachmentTarget(target) {
|
|
1074
|
-
if (
|
|
1475
|
+
if (import_react_native2.Platform.OS !== "android") return false;
|
|
1075
1476
|
if (!target) return false;
|
|
1076
1477
|
const hostedChatView = this.readPersistedHostedChatView(target.hostedChatView);
|
|
1077
1478
|
if (!hostedChatView) return false;
|
|
@@ -1104,6 +1505,10 @@ var SagepilotReactNativeChat = class {
|
|
|
1104
1505
|
}
|
|
1105
1506
|
return true;
|
|
1106
1507
|
}
|
|
1508
|
+
if (message.type === "sagepilot:session_updated") {
|
|
1509
|
+
if (this.pushClient) void this.acceptHostedSession(message).catch((error) => this.emitError(error));
|
|
1510
|
+
return true;
|
|
1511
|
+
}
|
|
1107
1512
|
if (message.type === "sagepilot:conversation_created") {
|
|
1108
1513
|
this.handleConversationCreated(message);
|
|
1109
1514
|
return true;
|
|
@@ -1114,6 +1519,54 @@ var SagepilotReactNativeChat = class {
|
|
|
1114
1519
|
}
|
|
1115
1520
|
return true;
|
|
1116
1521
|
}
|
|
1522
|
+
/** Verifies an OTP-issued token with the Customer API before accepting a hosted identity change. */
|
|
1523
|
+
async acceptHostedSession(message) {
|
|
1524
|
+
const session = this.requireSession();
|
|
1525
|
+
const sessionToken = readStringField(message, "session_token");
|
|
1526
|
+
if (!sessionToken || readStringField(message, "session_id") !== session.session_id) return;
|
|
1527
|
+
if (message.workspace_id && message.workspace_id !== this.workspaceId) return;
|
|
1528
|
+
if (message.channel_id && message.channel_id !== this.channelId) return;
|
|
1529
|
+
if (this.identifyPending) throw new SagepilotChatError("invalid_request", "Another identity change is in progress.");
|
|
1530
|
+
this.identifyPending = true;
|
|
1531
|
+
this.emitState();
|
|
1532
|
+
try {
|
|
1533
|
+
const verified = await getSession(
|
|
1534
|
+
this.requireHttp(),
|
|
1535
|
+
this.apiHost,
|
|
1536
|
+
session.session_id,
|
|
1537
|
+
this.requireSessionManager().getAuthorizationHeader(sessionToken)
|
|
1538
|
+
);
|
|
1539
|
+
if (verified.session_id !== session.session_id || verified.channel_id && verified.channel_id !== this.channelId || !verified.authenticated) {
|
|
1540
|
+
throw new SagepilotChatError("forbidden", "Hosted token does not identify this customer session.");
|
|
1541
|
+
}
|
|
1542
|
+
if (this.session?.session_id !== session.session_id || this.session.session_token !== session.session_token) return;
|
|
1543
|
+
if (verified.customer_id !== session.customer_id) await this.pushClient?.pauseAndRevoke();
|
|
1544
|
+
let adoptedToken = sessionToken;
|
|
1545
|
+
let legacyJwt = verified.legacy_jwt ?? null;
|
|
1546
|
+
if (this.pushChannelId && verified.customer_id === session.customer_id) {
|
|
1547
|
+
const renewed = await this.requireHttp().request(`${this.apiHost}${CUSTOMER_API_PREFIX}/push/sessions`, {
|
|
1548
|
+
method: "POST",
|
|
1549
|
+
headers: withJsonHeaders(this.requireSessionManager().getAuthorizationHeader()),
|
|
1550
|
+
body: JSON.stringify({ replacement_session_token: sessionToken }),
|
|
1551
|
+
errorMessage: "Shared push session refresh failed."
|
|
1552
|
+
});
|
|
1553
|
+
if (renewed.session_id !== session.session_id || renewed.customer_id !== session.customer_id || !renewed.session_token) {
|
|
1554
|
+
throw new SagepilotChatError("forbidden", "Shared session refresh scope changed.");
|
|
1555
|
+
}
|
|
1556
|
+
adoptedToken = renewed.session_token;
|
|
1557
|
+
legacyJwt = renewed.legacy_jwt ?? legacyJwt;
|
|
1558
|
+
}
|
|
1559
|
+
this.session = await this.requireSessionManager().setSession({ ...verified, session_token: adoptedToken });
|
|
1560
|
+
this.legacyWidgetJwt = legacyJwt;
|
|
1561
|
+
this.hostedIdentityLogoutVersion = 0;
|
|
1562
|
+
this.identified = true;
|
|
1563
|
+
this.customer = verified.customer_id ? { id: verified.customer_id } : null;
|
|
1564
|
+
this.pushClient?.resume();
|
|
1565
|
+
} finally {
|
|
1566
|
+
this.identifyPending = false;
|
|
1567
|
+
this.emitState();
|
|
1568
|
+
}
|
|
1569
|
+
}
|
|
1117
1570
|
handleConversationCreated(message) {
|
|
1118
1571
|
const chatId = readStringField(message, "chat_id") ?? readStringField(message, "conversation_id");
|
|
1119
1572
|
if (!chatId) return;
|
|
@@ -1167,10 +1620,12 @@ var SagepilotReactNativeChat = class {
|
|
|
1167
1620
|
this.dismissCallbacks.clear();
|
|
1168
1621
|
this.errorCallbacks.clear();
|
|
1169
1622
|
}
|
|
1623
|
+
/** Updates both unread subscribers and the state used by React launchers. */
|
|
1170
1624
|
setUnreadCount(count) {
|
|
1171
1625
|
if (count === this.unreadCount) return;
|
|
1172
1626
|
this.unreadCount = count;
|
|
1173
1627
|
this.emitUnreadChange();
|
|
1628
|
+
this.emitState();
|
|
1174
1629
|
}
|
|
1175
1630
|
emitUnreadChange() {
|
|
1176
1631
|
const state = this.getUnreadState();
|
|
@@ -1325,6 +1780,11 @@ var SagepilotReactNativeChat = class {
|
|
|
1325
1780
|
return this.unreadCount;
|
|
1326
1781
|
}
|
|
1327
1782
|
resetRuntimeState() {
|
|
1783
|
+
this.pushClient?.stop();
|
|
1784
|
+
this.pushClient = null;
|
|
1785
|
+
this.pushChannelId = null;
|
|
1786
|
+
this.pushAppStateSubscription?.remove();
|
|
1787
|
+
this.pushAppStateSubscription = null;
|
|
1328
1788
|
this.runtimeOptions = null;
|
|
1329
1789
|
this.http = null;
|
|
1330
1790
|
this.sessionManager = null;
|
|
@@ -1421,7 +1881,7 @@ var SagepilotReactNativeChat = class {
|
|
|
1421
1881
|
/** Restores Android presentation state after configure without resetting the hosted route to Home. */
|
|
1422
1882
|
async restorePresentationFromCache() {
|
|
1423
1883
|
const cache = this.getPresentationCache();
|
|
1424
|
-
if (!cache ||
|
|
1884
|
+
if (!cache || import_react_native2.Platform.OS !== "android") return;
|
|
1425
1885
|
const persisted = await cache.get(PRESENTATION_CACHE_KEY).catch(() => null);
|
|
1426
1886
|
if (persisted?.cleanShutdown) return;
|
|
1427
1887
|
if (!isFreshPresentationState(persisted?.updatedAt)) return;
|
|
@@ -1435,9 +1895,15 @@ var SagepilotReactNativeChat = class {
|
|
|
1435
1895
|
};
|
|
1436
1896
|
var internalSagepilotChat = new SagepilotReactNativeChat();
|
|
1437
1897
|
var SagepilotChat = {
|
|
1898
|
+
/** Provides push registration, preferences and SDK engagement callbacks. */
|
|
1899
|
+
get push() {
|
|
1900
|
+
return internalSagepilotChat.push;
|
|
1901
|
+
},
|
|
1438
1902
|
configure: (config) => internalSagepilotChat.configure(config),
|
|
1439
1903
|
getSession: () => internalSagepilotChat.getSession(),
|
|
1440
1904
|
identify: (identity) => internalSagepilotChat.identify(identity),
|
|
1905
|
+
/** Authorizes the configured brand on the same customer session used by chat. */
|
|
1906
|
+
authorizePush: (identityToken) => internalSagepilotChat.authorizePush(identityToken),
|
|
1441
1907
|
logout: () => internalSagepilotChat.logout(),
|
|
1442
1908
|
getIdentityState: () => internalSagepilotChat.getIdentityState(),
|
|
1443
1909
|
onIdentify: (callback) => internalSagepilotChat.onIdentify(callback),
|
|
@@ -1467,6 +1933,7 @@ var SagepilotChat = {
|
|
|
1467
1933
|
getChannel: () => internalSagepilotChat.getChannel(),
|
|
1468
1934
|
destroy: () => internalSagepilotChat.destroy()
|
|
1469
1935
|
};
|
|
1936
|
+
Object.defineProperty(SagepilotChat, "push", { enumerable: false });
|
|
1470
1937
|
|
|
1471
1938
|
// src/core/storage/fileStore.ts
|
|
1472
1939
|
var DEFAULT_DIRECTORY_NAME = "sagepilot-attachments";
|
|
@@ -1525,7 +1992,7 @@ function createSagepilotFileStore(blobUtil, options = {}) {
|
|
|
1525
1992
|
}
|
|
1526
1993
|
|
|
1527
1994
|
// src/core/native/filePicker.ts
|
|
1528
|
-
var
|
|
1995
|
+
var import_react_native3 = require("react-native");
|
|
1529
1996
|
|
|
1530
1997
|
// src/core/native/filePickerShared.ts
|
|
1531
1998
|
var SagepilotFilePickerError = class extends Error {
|
|
@@ -1558,9 +2025,9 @@ function stripFileScheme(uri) {
|
|
|
1558
2025
|
return uri.startsWith("file://") ? uri.replace("file://", "") : uri;
|
|
1559
2026
|
}
|
|
1560
2027
|
async function promptOpenSagepilotCameraSettings() {
|
|
1561
|
-
if (
|
|
2028
|
+
if (import_react_native3.Platform.OS !== "android") return;
|
|
1562
2029
|
await new Promise((resolve) => {
|
|
1563
|
-
|
|
2030
|
+
import_react_native3.Alert.alert(
|
|
1564
2031
|
"Camera access is off",
|
|
1565
2032
|
"Enable camera access for this app in Settings to take a photo.",
|
|
1566
2033
|
[
|
|
@@ -1572,7 +2039,7 @@ async function promptOpenSagepilotCameraSettings() {
|
|
|
1572
2039
|
{
|
|
1573
2040
|
text: "Open Settings",
|
|
1574
2041
|
onPress: () => {
|
|
1575
|
-
|
|
2042
|
+
import_react_native3.Linking.openSettings().finally(resolve);
|
|
1576
2043
|
}
|
|
1577
2044
|
}
|
|
1578
2045
|
]
|
|
@@ -1580,21 +2047,21 @@ async function promptOpenSagepilotCameraSettings() {
|
|
|
1580
2047
|
});
|
|
1581
2048
|
}
|
|
1582
2049
|
async function ensureSagepilotAndroidCameraPermission() {
|
|
1583
|
-
if (
|
|
2050
|
+
if (import_react_native3.Platform.OS !== "android") return;
|
|
1584
2051
|
let result;
|
|
1585
2052
|
try {
|
|
1586
|
-
result = await
|
|
2053
|
+
result = await import_react_native3.PermissionsAndroid.request(import_react_native3.PermissionsAndroid.PERMISSIONS.CAMERA);
|
|
1587
2054
|
} catch {
|
|
1588
2055
|
return;
|
|
1589
2056
|
}
|
|
1590
|
-
if (result ===
|
|
2057
|
+
if (result === import_react_native3.PermissionsAndroid.RESULTS.NEVER_ASK_AGAIN) {
|
|
1591
2058
|
await promptOpenSagepilotCameraSettings();
|
|
1592
2059
|
throw new SagepilotFilePickerError(
|
|
1593
2060
|
"permission_denied",
|
|
1594
2061
|
"Camera access is turned off. Enable it for this app in Settings to take a photo."
|
|
1595
2062
|
);
|
|
1596
2063
|
}
|
|
1597
|
-
if (result ===
|
|
2064
|
+
if (result === import_react_native3.PermissionsAndroid.RESULTS.DENIED) {
|
|
1598
2065
|
throw new SagepilotFilePickerError(
|
|
1599
2066
|
"permission_denied",
|
|
1600
2067
|
"Camera permission is required to take a photo."
|
|
@@ -1767,13 +2234,13 @@ function createSagepilotFilePicker(options) {
|
|
|
1767
2234
|
|
|
1768
2235
|
// src/ui/SagepilotChatProvider.ts
|
|
1769
2236
|
var import_react = require("react");
|
|
1770
|
-
var
|
|
2237
|
+
var import_react_native4 = require("react-native");
|
|
1771
2238
|
var import_react_native_webview = require("react-native-webview");
|
|
1772
2239
|
|
|
1773
2240
|
// src/core/webview/mobileBridge.ts
|
|
1774
2241
|
var FILE_PICKER_PROTOCOL_VERSION = 2;
|
|
1775
2242
|
function buildBridgeCapabilitiesPayload(capabilities) {
|
|
1776
|
-
return { ...capabilities, filePickerProtocol: FILE_PICKER_PROTOCOL_VERSION };
|
|
2243
|
+
return { ...capabilities, filePickerProtocol: FILE_PICKER_PROTOCOL_VERSION, sdk: SDK_NAME, sdk_version: SDK_VERSION };
|
|
1777
2244
|
}
|
|
1778
2245
|
function buildBridgeCapabilitiesScript(capabilities) {
|
|
1779
2246
|
const payload = buildBridgeCapabilitiesPayload(capabilities);
|
|
@@ -2061,7 +2528,7 @@ function isInternalWebViewScheme(url) {
|
|
|
2061
2528
|
var hostedChatWebViewProps = {
|
|
2062
2529
|
allowFileAccess: true,
|
|
2063
2530
|
allowFileAccessFromFileURLs: true,
|
|
2064
|
-
...
|
|
2531
|
+
...import_react_native4.Platform.OS === "ios" ? {
|
|
2065
2532
|
automaticallyAdjustContentInsets: false,
|
|
2066
2533
|
contentInsetAdjustmentBehavior: "never",
|
|
2067
2534
|
hideKeyboardAccessoryView: true
|
|
@@ -2076,7 +2543,7 @@ var hostedChatWebViewProps = {
|
|
|
2076
2543
|
sharedCookiesEnabled: true,
|
|
2077
2544
|
thirdPartyCookiesEnabled: true
|
|
2078
2545
|
};
|
|
2079
|
-
var AndroidInsetsView =
|
|
2546
|
+
var AndroidInsetsView = import_react_native4.Platform.OS === "android" ? SagepilotInsetsViewNativeComponent_default : import_react_native4.View;
|
|
2080
2547
|
var emptyAndroidInsets = { top: 0, bottom: 0 };
|
|
2081
2548
|
function SagepilotChatProvider({
|
|
2082
2549
|
children,
|
|
@@ -2099,7 +2566,7 @@ function SagepilotChatProvider({
|
|
|
2099
2566
|
const livenessPausedUntilRef = (0, import_react.useRef)(0);
|
|
2100
2567
|
const pickerInFlightRef = (0, import_react.useRef)(false);
|
|
2101
2568
|
const livenessRemountCountRef = (0, import_react.useRef)(0);
|
|
2102
|
-
const appStateRef = (0, import_react.useRef)(
|
|
2569
|
+
const appStateRef = (0, import_react.useRef)(import_react_native4.AppState.currentState);
|
|
2103
2570
|
const didReconcileRef = (0, import_react.useRef)(false);
|
|
2104
2571
|
const [androidRepaintTick, setAndroidRepaintTick] = (0, import_react.useState)(0);
|
|
2105
2572
|
const [sourceChooser, setSourceChooser] = (0, import_react.useState)(null);
|
|
@@ -2241,7 +2708,7 @@ function SagepilotChatProvider({
|
|
|
2241
2708
|
setPreloadWebViewKey((key) => key + 1);
|
|
2242
2709
|
}, []);
|
|
2243
2710
|
const pauseLivenessAfterPicker = (0, import_react.useCallback)((durationMs) => {
|
|
2244
|
-
if (
|
|
2711
|
+
if (import_react_native4.Platform.OS !== "android") return;
|
|
2245
2712
|
livenessPausedUntilRef.current = Math.max(livenessPausedUntilRef.current, Date.now() + durationMs);
|
|
2246
2713
|
}, []);
|
|
2247
2714
|
const runNativeFilePicker = (0, import_react.useCallback)((source, multiple) => {
|
|
@@ -2411,7 +2878,7 @@ function SagepilotChatProvider({
|
|
|
2411
2878
|
};
|
|
2412
2879
|
}, [clearDeferredLivenessProbe]);
|
|
2413
2880
|
const runLivenessProbe = (0, import_react.useCallback)(() => {
|
|
2414
|
-
if (
|
|
2881
|
+
if (import_react_native4.Platform.OS !== "android") return;
|
|
2415
2882
|
const ref = nativeWebViewRef.current;
|
|
2416
2883
|
if (!ref || !internalSagepilotChat.isPresented()) return;
|
|
2417
2884
|
const pauseRemainingMs = livenessPausedUntilRef.current - Date.now();
|
|
@@ -2440,7 +2907,7 @@ function SagepilotChatProvider({
|
|
|
2440
2907
|
}, LIVENESS_PONG_TIMEOUT_MS);
|
|
2441
2908
|
}, [clearDeferredLivenessProbe, clearPing, recoverNativeWebView]);
|
|
2442
2909
|
(0, import_react.useEffect)(() => {
|
|
2443
|
-
const subscription =
|
|
2910
|
+
const subscription = import_react_native4.AppState.addEventListener("change", (nextState) => {
|
|
2444
2911
|
const prev = appStateRef.current;
|
|
2445
2912
|
appStateRef.current = nextState;
|
|
2446
2913
|
if (nextState === "active" && (prev === "background" || prev === "inactive")) {
|
|
@@ -2468,11 +2935,11 @@ function SagepilotChatProvider({
|
|
|
2468
2935
|
const presentationStyle = state.presentation?.style ?? "sheet";
|
|
2469
2936
|
const isFullScreenModal = presentationStyle === "fullScreen";
|
|
2470
2937
|
const animationType = presentationStyle === "fullScreen" || presentationStyle === "push" ? "slide" : "fade";
|
|
2471
|
-
const ModalContainer =
|
|
2472
|
-
const NativeModalContainer =
|
|
2473
|
-
const ChatContentContainer =
|
|
2474
|
-
const nativeModalContainerProps =
|
|
2475
|
-
const chatContentContainerProps =
|
|
2938
|
+
const ModalContainer = import_react_native4.Platform.OS === "ios" && isFullScreenModal ? import_react_native4.SafeAreaView : import_react_native4.View;
|
|
2939
|
+
const NativeModalContainer = import_react_native4.Platform.OS === "android" ? AndroidInsetsView : ModalContainer;
|
|
2940
|
+
const ChatContentContainer = import_react_native4.Platform.OS === "ios" ? import_react_native4.KeyboardAvoidingView : import_react_native4.View;
|
|
2941
|
+
const nativeModalContainerProps = import_react_native4.Platform.OS === "android" ? { style: styles.container, onInsetsChange: handleAndroidInsetsChange } : { style: styles.container };
|
|
2942
|
+
const chatContentContainerProps = import_react_native4.Platform.OS === "ios" ? {
|
|
2476
2943
|
behavior: "padding",
|
|
2477
2944
|
enabled: true,
|
|
2478
2945
|
keyboardVerticalOffset: 0,
|
|
@@ -2480,13 +2947,15 @@ function SagepilotChatProvider({
|
|
|
2480
2947
|
} : {
|
|
2481
2948
|
style: [
|
|
2482
2949
|
styles.modalContent,
|
|
2483
|
-
|
|
2950
|
+
import_react_native4.Platform.OS === "android" ? {
|
|
2484
2951
|
paddingTop: androidModalInsets.top,
|
|
2485
2952
|
paddingBottom: androidModalInsets.bottom
|
|
2486
2953
|
} : null
|
|
2487
2954
|
].filter(Boolean)
|
|
2488
2955
|
};
|
|
2489
2956
|
const handleWebViewMessage = (event) => {
|
|
2957
|
+
const origin = readUrlOrigin(state.conversationUrl ?? state.preloadUrl);
|
|
2958
|
+
if (event.nativeEvent?.url && (!origin || readUrlOrigin(event.nativeEvent.url) !== origin)) return;
|
|
2490
2959
|
const message = parseHostedBridgeMessage(event.nativeEvent?.data);
|
|
2491
2960
|
if (message?.type === "sagepilot:open_file_picker") {
|
|
2492
2961
|
logNativeFilePicker("bridge_message_open_file_picker", {
|
|
@@ -2569,43 +3038,43 @@ function SagepilotChatProvider({
|
|
|
2569
3038
|
if (widgetOrigin && readUrlOrigin(url) === widgetOrigin) {
|
|
2570
3039
|
return true;
|
|
2571
3040
|
}
|
|
2572
|
-
|
|
3041
|
+
import_react_native4.Linking.openURL(url).catch(() => void 0);
|
|
2573
3042
|
return false;
|
|
2574
3043
|
}, [state.conversationUrl, state.preloadUrl]);
|
|
2575
3044
|
(0, import_react.useEffect)(() => {
|
|
2576
|
-
if (
|
|
3045
|
+
if (import_react_native4.Platform.OS !== "web" || typeof window === "undefined") return;
|
|
2577
3046
|
const trustedWidgetOrigin = readUrlOrigin(state.conversationUrl);
|
|
2578
3047
|
if (!trustedWidgetOrigin) return;
|
|
2579
3048
|
const handleWindowMessage = (event) => {
|
|
2580
|
-
if (event.origin !== trustedWidgetOrigin) return;
|
|
3049
|
+
if (event.origin !== trustedWidgetOrigin || event.source !== webFrameRef.current?.contentWindow) return;
|
|
2581
3050
|
internalSagepilotChat.handleHostedBridgeMessage(parseHostedBridgeMessage(event.data));
|
|
2582
3051
|
};
|
|
2583
3052
|
window.addEventListener("message", handleWindowMessage);
|
|
2584
3053
|
return () => window.removeEventListener("message", handleWindowMessage);
|
|
2585
3054
|
}, [state.conversationUrl]);
|
|
2586
3055
|
(0, import_react.useEffect)(() => {
|
|
2587
|
-
if (
|
|
3056
|
+
if (import_react_native4.Platform.OS !== "web" || !state.isPresented) return;
|
|
2588
3057
|
postIdentityToWebFrame();
|
|
2589
3058
|
}, [state.isPresented, state.conversationUrl, state.configured]);
|
|
2590
3059
|
(0, import_react.useEffect)(() => {
|
|
2591
|
-
if (
|
|
3060
|
+
if (import_react_native4.Platform.OS !== "web" || !state.isPresented) return;
|
|
2592
3061
|
postIdentityLogoutToWebFrame();
|
|
2593
3062
|
}, [state.hostedIdentityLogoutVersion, state.isPresented, state.conversationUrl, state.configured]);
|
|
2594
3063
|
(0, import_react.useEffect)(() => {
|
|
2595
|
-
if (
|
|
3064
|
+
if (import_react_native4.Platform.OS === "web" || !state.isPresented) return;
|
|
2596
3065
|
postIdentityToNativeWebView();
|
|
2597
3066
|
}, [state.isPresented, state.conversationUrl, state.configured]);
|
|
2598
3067
|
(0, import_react.useEffect)(() => {
|
|
2599
|
-
if (
|
|
3068
|
+
if (import_react_native4.Platform.OS === "web" || !state.isPresented) return;
|
|
2600
3069
|
postIdentityLogoutToNativeWebView();
|
|
2601
3070
|
}, [state.hostedIdentityLogoutVersion, state.isPresented, state.conversationUrl, state.configured]);
|
|
2602
3071
|
const handleWebFrameLoad = () => {
|
|
2603
3072
|
postIdentityLogoutToWebFrame();
|
|
2604
3073
|
postIdentityToWebFrame();
|
|
2605
3074
|
};
|
|
2606
|
-
if (
|
|
3075
|
+
if (import_react_native4.Platform.OS === "web") {
|
|
2607
3076
|
return (0, import_react.createElement)(
|
|
2608
|
-
|
|
3077
|
+
import_react_native4.View,
|
|
2609
3078
|
{ style: styles.root },
|
|
2610
3079
|
children,
|
|
2611
3080
|
state.configured && !state.isPresented && state.shouldPreload && state.preloadUrl ? (0, import_react.createElement)("iframe", {
|
|
@@ -2614,20 +3083,20 @@ function SagepilotChatProvider({
|
|
|
2614
3083
|
title: "Sagepilot chat preload"
|
|
2615
3084
|
}) : null,
|
|
2616
3085
|
state.configured && state.isPresented && state.conversationUrl ? (0, import_react.createElement)(
|
|
2617
|
-
|
|
3086
|
+
import_react_native4.View,
|
|
2618
3087
|
{ style: styles.webOverlay },
|
|
2619
3088
|
(0, import_react.createElement)(
|
|
2620
|
-
|
|
3089
|
+
import_react_native4.View,
|
|
2621
3090
|
{ style: styles.webPanel },
|
|
2622
3091
|
showCloseButton ? (0, import_react.createElement)(
|
|
2623
|
-
|
|
3092
|
+
import_react_native4.Pressable,
|
|
2624
3093
|
{
|
|
2625
3094
|
accessibilityRole: "button",
|
|
2626
3095
|
accessibilityLabel: closeLabel,
|
|
2627
3096
|
onPress: () => internalSagepilotChat.dismiss(),
|
|
2628
3097
|
style: styles.webCloseButton
|
|
2629
3098
|
},
|
|
2630
|
-
(0, import_react.createElement)(
|
|
3099
|
+
(0, import_react.createElement)(import_react_native4.Text, { style: styles.closeText }, closeLabel)
|
|
2631
3100
|
) : null,
|
|
2632
3101
|
(0, import_react.createElement)("iframe", {
|
|
2633
3102
|
ref: webFrameRef,
|
|
@@ -2641,7 +3110,7 @@ function SagepilotChatProvider({
|
|
|
2641
3110
|
);
|
|
2642
3111
|
}
|
|
2643
3112
|
return (0, import_react.createElement)(
|
|
2644
|
-
|
|
3113
|
+
import_react_native4.View,
|
|
2645
3114
|
{ style: styles.root },
|
|
2646
3115
|
children,
|
|
2647
3116
|
state.configured && !state.isPresented && state.shouldPreload && state.preloadUrl ? (0, import_react.createElement)(import_react_native_webview.WebView, {
|
|
@@ -2651,7 +3120,7 @@ function SagepilotChatProvider({
|
|
|
2651
3120
|
// disrupt an in-flight delivery). onRenderProcessGone must still be
|
|
2652
3121
|
// handled here or an unhandled renderer kill crashes the whole app.
|
|
2653
3122
|
key: `sagepilot-preload-webview-${preloadWebViewKey}`,
|
|
2654
|
-
source: { uri: state.preloadUrl },
|
|
3123
|
+
source: { uri: state.preloadUrl, headers: { "X-Sagepilot-Sdk-Name": SDK_NAME, "X-Sagepilot-Sdk-Version": SDK_VERSION } },
|
|
2655
3124
|
style: styles.preloadWebview,
|
|
2656
3125
|
injectedJavaScriptBeforeContentLoaded: getInjectedWebViewScript(),
|
|
2657
3126
|
onMessage: handleWebViewMessage,
|
|
@@ -2660,13 +3129,13 @@ function SagepilotChatProvider({
|
|
|
2660
3129
|
onContentProcessDidTerminate: recoverPreloadWebView
|
|
2661
3130
|
}) : null,
|
|
2662
3131
|
(0, import_react.createElement)(
|
|
2663
|
-
|
|
3132
|
+
import_react_native4.Modal,
|
|
2664
3133
|
{
|
|
2665
3134
|
visible: state.configured && state.isPresented,
|
|
2666
3135
|
animationType,
|
|
2667
3136
|
presentationStyle: isFullScreenModal ? "fullScreen" : "pageSheet",
|
|
2668
|
-
statusBarTranslucent:
|
|
2669
|
-
navigationBarTranslucent:
|
|
3137
|
+
statusBarTranslucent: import_react_native4.Platform.OS === "android",
|
|
3138
|
+
navigationBarTranslucent: import_react_native4.Platform.OS === "android",
|
|
2670
3139
|
onRequestClose: () => internalSagepilotChat.dismiss()
|
|
2671
3140
|
},
|
|
2672
3141
|
(0, import_react.createElement)(
|
|
@@ -2676,28 +3145,28 @@ function SagepilotChatProvider({
|
|
|
2676
3145
|
ChatContentContainer,
|
|
2677
3146
|
chatContentContainerProps,
|
|
2678
3147
|
showCloseButton ? (0, import_react.createElement)(
|
|
2679
|
-
|
|
3148
|
+
import_react_native4.View,
|
|
2680
3149
|
{ style: styles.header },
|
|
2681
3150
|
(0, import_react.createElement)(
|
|
2682
|
-
|
|
3151
|
+
import_react_native4.Pressable,
|
|
2683
3152
|
{
|
|
2684
3153
|
accessibilityRole: "button",
|
|
2685
3154
|
accessibilityLabel: closeLabel,
|
|
2686
3155
|
onPress: () => internalSagepilotChat.dismiss(),
|
|
2687
3156
|
style: styles.closeButton
|
|
2688
3157
|
},
|
|
2689
|
-
(0, import_react.createElement)(
|
|
3158
|
+
(0, import_react.createElement)(import_react_native4.Text, { style: styles.closeText }, closeLabel)
|
|
2690
3159
|
)
|
|
2691
3160
|
) : null,
|
|
2692
3161
|
state.conversationUrl ? (0, import_react.createElement)(import_react_native_webview.WebView, {
|
|
2693
3162
|
...hostedChatWebViewProps,
|
|
2694
3163
|
key: `sagepilot-hosted-webview-${nativeWebViewKey}`,
|
|
2695
3164
|
ref: nativeWebViewRef,
|
|
2696
|
-
source: { uri: state.conversationUrl },
|
|
3165
|
+
source: { uri: state.conversationUrl, headers: { "X-Sagepilot-Sdk-Name": SDK_NAME, "X-Sagepilot-Sdk-Version": SDK_VERSION } },
|
|
2697
3166
|
// The imperceptible opacity toggle forces the Android WebView
|
|
2698
3167
|
// surface to re-composite on resume, clearing the blank-but-alive
|
|
2699
3168
|
// surface bug without a reload (see runLivenessProbe).
|
|
2700
|
-
style:
|
|
3169
|
+
style: import_react_native4.Platform.OS === "android" ? [styles.webview, { opacity: 1 - androidRepaintTick % 2 * 1e-3 }] : styles.webview,
|
|
2701
3170
|
startInLoadingState: true,
|
|
2702
3171
|
injectedJavaScriptBeforeContentLoaded: getInjectedWebViewScript(),
|
|
2703
3172
|
onMessage: handleWebViewMessage,
|
|
@@ -2709,10 +3178,10 @@ function SagepilotChatProvider({
|
|
|
2709
3178
|
// iOS equivalent: WKWebView content process terminated.
|
|
2710
3179
|
onContentProcessDidTerminate: recoverNativeWebView,
|
|
2711
3180
|
renderLoading: () => (0, import_react.createElement)(
|
|
2712
|
-
|
|
3181
|
+
import_react_native4.View,
|
|
2713
3182
|
{ style: styles.loading },
|
|
2714
|
-
(0, import_react.createElement)(
|
|
2715
|
-
(0, import_react.createElement)(
|
|
3183
|
+
(0, import_react.createElement)(import_react_native4.ActivityIndicator, null),
|
|
3184
|
+
(0, import_react.createElement)(import_react_native4.Text, { style: styles.loadingText }, loadingLabel)
|
|
2716
3185
|
)
|
|
2717
3186
|
}) : null
|
|
2718
3187
|
)
|
|
@@ -2721,7 +3190,7 @@ function SagepilotChatProvider({
|
|
|
2721
3190
|
// Native attachment-source chooser. Replaces the Android Alert (capped at
|
|
2722
3191
|
// 3 buttons) so camera/library/documents all show on every platform.
|
|
2723
3192
|
(0, import_react.createElement)(
|
|
2724
|
-
|
|
3193
|
+
import_react_native4.Modal,
|
|
2725
3194
|
{
|
|
2726
3195
|
visible: sourceChooser !== null,
|
|
2727
3196
|
transparent: true,
|
|
@@ -2730,39 +3199,39 @@ function SagepilotChatProvider({
|
|
|
2730
3199
|
onRequestClose: () => setSourceChooser(null)
|
|
2731
3200
|
},
|
|
2732
3201
|
(0, import_react.createElement)(
|
|
2733
|
-
|
|
3202
|
+
import_react_native4.Pressable,
|
|
2734
3203
|
{ style: styles.sheetBackdrop, onPress: () => setSourceChooser(null) },
|
|
2735
3204
|
(0, import_react.createElement)(
|
|
2736
|
-
|
|
3205
|
+
import_react_native4.View,
|
|
2737
3206
|
{ style: styles.sheetCard },
|
|
2738
|
-
(0, import_react.createElement)(
|
|
3207
|
+
(0, import_react.createElement)(import_react_native4.Text, { style: styles.sheetTitle }, "Add attachment"),
|
|
2739
3208
|
...(internalSagepilotChat.getConfig()?.filePicker?.sources ?? []).map(
|
|
2740
3209
|
(source) => (0, import_react.createElement)(
|
|
2741
|
-
|
|
3210
|
+
import_react_native4.Pressable,
|
|
2742
3211
|
{
|
|
2743
3212
|
key: source,
|
|
2744
3213
|
accessibilityRole: "button",
|
|
2745
3214
|
style: styles.sheetButton,
|
|
2746
3215
|
onPress: () => handleSourceChoice(source)
|
|
2747
3216
|
},
|
|
2748
|
-
(0, import_react.createElement)(
|
|
3217
|
+
(0, import_react.createElement)(import_react_native4.Text, { style: styles.sheetButtonText }, FILE_PICKER_SOURCE_LABELS[source])
|
|
2749
3218
|
)
|
|
2750
3219
|
),
|
|
2751
3220
|
(0, import_react.createElement)(
|
|
2752
|
-
|
|
3221
|
+
import_react_native4.Pressable,
|
|
2753
3222
|
{
|
|
2754
3223
|
accessibilityRole: "button",
|
|
2755
3224
|
style: [styles.sheetButton, styles.sheetCancelButton],
|
|
2756
3225
|
onPress: () => setSourceChooser(null)
|
|
2757
3226
|
},
|
|
2758
|
-
(0, import_react.createElement)(
|
|
3227
|
+
(0, import_react.createElement)(import_react_native4.Text, { style: styles.sheetCancelText }, "Cancel")
|
|
2759
3228
|
)
|
|
2760
3229
|
)
|
|
2761
3230
|
)
|
|
2762
3231
|
)
|
|
2763
3232
|
);
|
|
2764
3233
|
}
|
|
2765
|
-
var styles =
|
|
3234
|
+
var styles = import_react_native4.StyleSheet.create({
|
|
2766
3235
|
root: {
|
|
2767
3236
|
flex: 1
|
|
2768
3237
|
},
|
|
@@ -2848,7 +3317,7 @@ var styles = import_react_native3.StyleSheet.create({
|
|
|
2848
3317
|
borderStyle: "none"
|
|
2849
3318
|
},
|
|
2850
3319
|
loading: {
|
|
2851
|
-
...
|
|
3320
|
+
...import_react_native4.StyleSheet.absoluteFillObject,
|
|
2852
3321
|
alignItems: "center",
|
|
2853
3322
|
justifyContent: "center",
|
|
2854
3323
|
backgroundColor: "#ffffff"
|
|
@@ -2949,16 +3418,114 @@ function useSagepilotChat() {
|
|
|
2949
3418
|
onConversationCreated
|
|
2950
3419
|
};
|
|
2951
3420
|
}
|
|
3421
|
+
|
|
3422
|
+
// src/brandPush.ts
|
|
3423
|
+
var import_react_native5 = require("react-native");
|
|
3424
|
+
var SagepilotBrandPush = class {
|
|
3425
|
+
/** Keeps brand credentials separate from chat and other workspace/channel sessions. */
|
|
3426
|
+
constructor(config) {
|
|
3427
|
+
this.config = config;
|
|
3428
|
+
this.session = null;
|
|
3429
|
+
this.pending = Promise.resolve();
|
|
3430
|
+
this.started = false;
|
|
3431
|
+
this.appStateSubscription = null;
|
|
3432
|
+
this.scope = parseKey(config.key);
|
|
3433
|
+
if (import_react_native5.Platform.OS !== "android" && import_react_native5.Platform.OS !== "ios") throw new Error("Brand push requires Android or iOS.");
|
|
3434
|
+
this.tokens = new SagepilotTokenManager(`push_${this.scope.workspaceId}_${this.scope.channelId}`, config.tokenStorage);
|
|
3435
|
+
this.http = new SagepilotHttpClient({ fetch: resolveFetch(config.fetch) });
|
|
3436
|
+
this.host = resolveCustomerApiHost(config.host);
|
|
3437
|
+
this.push = new SagepilotPush(config.push, {
|
|
3438
|
+
...this.scope,
|
|
3439
|
+
platform: import_react_native5.Platform.OS,
|
|
3440
|
+
brand: true,
|
|
3441
|
+
customerId: () => this.session?.customer_id ?? null,
|
|
3442
|
+
onError: config.onError,
|
|
3443
|
+
request: (path, method, body) => this.request(path, method, body)
|
|
3444
|
+
});
|
|
3445
|
+
}
|
|
3446
|
+
/** Serializes identity transitions so an old installation is revoked with its original credentials. */
|
|
3447
|
+
transition(operation) {
|
|
3448
|
+
const next = this.pending.then(operation);
|
|
3449
|
+
this.pending = next.catch(() => void 0);
|
|
3450
|
+
return next;
|
|
3451
|
+
}
|
|
3452
|
+
/** Sends through the shared version-stamped transport using the current brand credential. */
|
|
3453
|
+
request(path, method, body) {
|
|
3454
|
+
if (!this.session) return Promise.reject(new Error("Identify a brand customer before using push."));
|
|
3455
|
+
return this.http.request(`${this.host}${CUSTOMER_API_PREFIX}${path}`, {
|
|
3456
|
+
method,
|
|
3457
|
+
headers: withJsonHeaders(this.tokens.createAuthorizationHeader(this.session.session_token)),
|
|
3458
|
+
body: body === void 0 ? void 0 : JSON.stringify(body),
|
|
3459
|
+
errorMessage: "Push request failed"
|
|
3460
|
+
});
|
|
3461
|
+
}
|
|
3462
|
+
/** Restores durable credentials before registering listeners; never prompts for permission. */
|
|
3463
|
+
start() {
|
|
3464
|
+
return this.transition(async () => {
|
|
3465
|
+
if (this.started) return;
|
|
3466
|
+
this.session = await this.tokens.getSession();
|
|
3467
|
+
await this.push.start();
|
|
3468
|
+
this.appStateSubscription = import_react_native5.AppState.addEventListener("change", (state) => {
|
|
3469
|
+
if (state === "active") {
|
|
3470
|
+
void this.push.sync().catch(this.config.onError);
|
|
3471
|
+
void this.push.flush().catch(this.config.onError);
|
|
3472
|
+
}
|
|
3473
|
+
});
|
|
3474
|
+
this.started = true;
|
|
3475
|
+
});
|
|
3476
|
+
}
|
|
3477
|
+
/** Exchanges a host-server proof, then revokes old ownership before adopting the new session. */
|
|
3478
|
+
identify(identityToken) {
|
|
3479
|
+
return this.transition(async () => {
|
|
3480
|
+
if (!this.started) throw new Error("Call start before identify.");
|
|
3481
|
+
if (typeof identityToken !== "string" || !identityToken.trim()) throw new Error("A signed brand identity proof is required.");
|
|
3482
|
+
const next = await this.http.request(
|
|
3483
|
+
`${this.host}${CUSTOMER_API_PREFIX}/push/sessions`,
|
|
3484
|
+
{
|
|
3485
|
+
method: "POST",
|
|
3486
|
+
headers: withJsonHeaders(void 0),
|
|
3487
|
+
body: JSON.stringify({ channel_id: this.scope.channelId, identity_token: identityToken }),
|
|
3488
|
+
errorMessage: "Brand identity verification failed"
|
|
3489
|
+
}
|
|
3490
|
+
);
|
|
3491
|
+
if (next.workspace_id !== this.scope.workspaceId || next.channel_id !== this.scope.channelId || !next.customer_id || !next.session_token || !next.session_id || !next.authenticated) {
|
|
3492
|
+
throw new Error("Brand session scope mismatch.");
|
|
3493
|
+
}
|
|
3494
|
+
if (this.session?.customer_id !== next.customer_id) await this.push.pauseAndRevoke();
|
|
3495
|
+
await this.tokens.setSession(next);
|
|
3496
|
+
this.session = next;
|
|
3497
|
+
this.push.resume();
|
|
3498
|
+
});
|
|
3499
|
+
}
|
|
3500
|
+
/** Retains credentials on failed revocation so logout can be retried safely. */
|
|
3501
|
+
logout() {
|
|
3502
|
+
return this.transition(async () => {
|
|
3503
|
+
if (!this.started) throw new Error("Call start before logout.");
|
|
3504
|
+
await this.push.pauseAndRevoke();
|
|
3505
|
+
await this.tokens.clearSession();
|
|
3506
|
+
this.session = null;
|
|
3507
|
+
});
|
|
3508
|
+
}
|
|
3509
|
+
/** Stops listeners; call logout first when the customer is signing out. */
|
|
3510
|
+
destroy() {
|
|
3511
|
+
return this.transition(async () => {
|
|
3512
|
+
this.appStateSubscription?.remove();
|
|
3513
|
+
this.push.stop();
|
|
3514
|
+
});
|
|
3515
|
+
}
|
|
3516
|
+
};
|
|
2952
3517
|
// Annotate the CommonJS export names for ESM import in node:
|
|
2953
3518
|
0 && (module.exports = {
|
|
2954
3519
|
SAGEPILOT_DEFAULT_IMAGE_MAX_DIMENSION,
|
|
2955
3520
|
SAGEPILOT_DEFAULT_IMAGE_MAX_FILE_SIZE_BYTES,
|
|
2956
3521
|
SAGEPILOT_DEFAULT_IMAGE_QUALITY,
|
|
3522
|
+
SagepilotBrandPush,
|
|
2957
3523
|
SagepilotChat,
|
|
2958
3524
|
SagepilotChatError,
|
|
2959
3525
|
SagepilotChatProvider,
|
|
2960
3526
|
SagepilotFilePickerError,
|
|
2961
3527
|
createAsyncStorageCacheStorage,
|
|
3528
|
+
createFirebasePushAdapter,
|
|
2962
3529
|
createKeychainTokenStorage,
|
|
2963
3530
|
createSagepilotFilePicker,
|
|
2964
3531
|
createSagepilotFileStore,
|