@akropolys/sdk 1.0.2 → 1.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,1100 @@
1
+ 'use client';
2
+
3
+ // src/api.ts
4
+ var MAX_RETRIES = 3;
5
+ var RETRY_DELAYS = [500, 1e3, 2e3];
6
+ function log(level, msg, data) {
7
+ const prefix = "[Akropolys]";
8
+ if (level === "error") console.error(prefix, msg, data ?? "");
9
+ else if (level === "warn") console.warn(prefix, msg, data ?? "");
10
+ else console.log(prefix, msg, data ?? "");
11
+ }
12
+ async function sleep(ms) {
13
+ return new Promise((r) => setTimeout(r, ms));
14
+ }
15
+ var AkropolysAPI = class {
16
+ constructor(apiUrl, siteId, apiToken, getShopperId, getSessionId, vertical) {
17
+ this.apiUrl = apiUrl;
18
+ this.siteId = siteId;
19
+ this.apiToken = apiToken;
20
+ this.getShopperId = getShopperId;
21
+ this.getSessionId = getSessionId;
22
+ this.vertical = vertical;
23
+ }
24
+ async post(path, body, attempt = 0) {
25
+ const url = `${this.apiUrl}${path}`;
26
+ try {
27
+ const headers = {
28
+ "Content-Type": "application/json",
29
+ "X-Akropolys-Token": this.apiToken,
30
+ "X-Akropolys-Site": this.siteId
31
+ };
32
+ const shopperId = this.getShopperId?.();
33
+ if (shopperId) {
34
+ headers["X-Akropolys-Shopper-Id"] = shopperId;
35
+ }
36
+ const sessionId = this.getSessionId?.();
37
+ if (sessionId) {
38
+ headers["X-Akropolys-Session-Id"] = sessionId;
39
+ }
40
+ if (typeof window !== "undefined") {
41
+ const phone = localStorage.getItem("akropolys_user_phone");
42
+ if (phone) {
43
+ headers["X-Akropolys-Shopper-Phone"] = phone;
44
+ }
45
+ }
46
+ const res = await fetch(url, {
47
+ method: "POST",
48
+ headers,
49
+ body: JSON.stringify(body)
50
+ });
51
+ if (!res.ok) {
52
+ const text = await res.text();
53
+ let message = text;
54
+ try {
55
+ const parsed = JSON.parse(text);
56
+ if (parsed && typeof parsed.error === "string") {
57
+ message = parsed.error;
58
+ }
59
+ } catch {
60
+ }
61
+ const err = { status: res.status, message };
62
+ if (res.status >= 400 && res.status < 500) {
63
+ log("error", `${path} failed [${res.status}]`, text);
64
+ throw err;
65
+ }
66
+ if (attempt < MAX_RETRIES - 1) {
67
+ log("warn", `${path} [${res.status}] retrying (${attempt + 1}/${MAX_RETRIES})...`);
68
+ await sleep(RETRY_DELAYS[attempt]);
69
+ return this.post(path, body, attempt + 1);
70
+ }
71
+ log("error", `${path} failed after ${MAX_RETRIES} attempts`, err);
72
+ throw err;
73
+ }
74
+ return res.json();
75
+ } catch (e) {
76
+ if (e.status === void 0) {
77
+ if (attempt < MAX_RETRIES - 1) {
78
+ log("warn", `${path} network error, retrying (${attempt + 1}/${MAX_RETRIES})...`);
79
+ await sleep(RETRY_DELAYS[attempt]);
80
+ return this.post(path, body, attempt + 1);
81
+ }
82
+ log("error", `${path} unreachable after ${MAX_RETRIES} attempts`);
83
+ }
84
+ throw e;
85
+ }
86
+ }
87
+ async ingest(product) {
88
+ log("info", "ingesting product", product.name || product.id || "");
89
+ return this.post("/ingest", { siteId: this.siteId, product });
90
+ }
91
+ async ingestBatch(products) {
92
+ log("info", `ingesting batch of ${products.length} products`);
93
+ return this.post("/ingest/batch", { siteId: this.siteId, products });
94
+ }
95
+ async search(query, limit = 10) {
96
+ log("info", "search query", query);
97
+ return this.post("/search", { query, siteId: this.siteId, limit });
98
+ }
99
+ // Pure vector search — no LLM, instant results.
100
+ async searchVector(query, limit = 10) {
101
+ return this.post("/search/vector", { query, siteId: this.siteId, limit });
102
+ }
103
+ // Autocomplete — pure in-memory Trie, <1ms, no Upstash call. Only true prefix matches.
104
+ async searchAutocomplete(query, limit = 8) {
105
+ return this.post("/search/autocomplete", { query, siteId: this.siteId, limit });
106
+ }
107
+ // LLM chat — conversational search with history context.
108
+ async chat(query, history = []) {
109
+ log("info", "chat query", query);
110
+ const path = !this.vertical || this.vertical === "commerce" ? "/chat" : `/chat/${this.vertical}`;
111
+ return this.post(path, { query, siteId: this.siteId, history });
112
+ }
113
+ // Streaming variant — returns the raw fetch Response.
114
+ // The caller reads body as a ReadableStream of SSE frames.
115
+ async chatStream(query, history = [], signal) {
116
+ log("info", "chatStream query", query);
117
+ const headers = {
118
+ "Content-Type": "application/json",
119
+ "X-Akropolys-Token": this.apiToken,
120
+ "X-Akropolys-Site": this.siteId
121
+ };
122
+ const shopperId = this.getShopperId?.();
123
+ if (shopperId) headers["X-Akropolys-Shopper-Id"] = shopperId;
124
+ const sessionId = this.getSessionId?.();
125
+ if (sessionId) headers["X-Akropolys-Session-Id"] = sessionId;
126
+ if (typeof window !== "undefined") {
127
+ const phone = localStorage.getItem("akropolys_user_phone");
128
+ if (phone) headers["X-Akropolys-Shopper-Phone"] = phone;
129
+ }
130
+ const path = !this.vertical || this.vertical === "commerce" ? "/chat/stream" : `/chat/stream/${this.vertical}`;
131
+ const res = await fetch(`${this.apiUrl}${path}`, {
132
+ method: "POST",
133
+ headers,
134
+ body: JSON.stringify({ query, siteId: this.siteId, history }),
135
+ signal
136
+ });
137
+ if (!res.ok || !res.body) {
138
+ throw new Error(`Stream request failed: ${res.status}`);
139
+ }
140
+ return res;
141
+ }
142
+ // --- Cart System ---
143
+ buildHeaders() {
144
+ const headers = {
145
+ "Content-Type": "application/json",
146
+ "X-Akropolys-Token": this.apiToken,
147
+ "X-Akropolys-Site": this.siteId
148
+ };
149
+ const shopperId = this.getShopperId?.();
150
+ if (shopperId) headers["X-Akropolys-Shopper-Id"] = shopperId;
151
+ const sessionId = this.getSessionId?.();
152
+ if (sessionId) headers["X-Akropolys-Session-Id"] = sessionId;
153
+ if (typeof window !== "undefined") {
154
+ const phone = localStorage.getItem("akropolys_user_phone");
155
+ if (phone) {
156
+ headers["X-Akropolys-Shopper-Phone"] = phone;
157
+ }
158
+ }
159
+ return headers;
160
+ }
161
+ async getCart() {
162
+ const res = await fetch(`${this.apiUrl}/cart?siteId=${this.siteId}`, {
163
+ headers: this.buildHeaders()
164
+ });
165
+ if (!res.ok) throw new Error("Failed to fetch cart");
166
+ return res.json();
167
+ }
168
+ async clearCart() {
169
+ const res = await fetch(`${this.apiUrl}/cart?siteId=${this.siteId}`, {
170
+ method: "DELETE",
171
+ headers: this.buildHeaders()
172
+ });
173
+ if (!res.ok) throw new Error("Failed to clear cart");
174
+ return res.json();
175
+ }
176
+ async checkoutCart() {
177
+ const res = await fetch(`${this.apiUrl}/cart/checkout`, {
178
+ method: "POST",
179
+ headers: this.buildHeaders(),
180
+ body: JSON.stringify({ siteId: this.siteId })
181
+ });
182
+ if (!res.ok) throw new Error("Failed to checkout cart");
183
+ return res.json();
184
+ }
185
+ async getCheckoutConfig() {
186
+ const res = await fetch(`${this.apiUrl}/checkout/config?site_id=${this.siteId}`, {
187
+ method: "GET",
188
+ headers: this.buildHeaders()
189
+ });
190
+ if (!res.ok) throw new Error("Failed to fetch checkout config");
191
+ return res.json();
192
+ }
193
+ async initiatePayment(phoneNumber, email, firstName, lastName) {
194
+ const res = await fetch(`${this.apiUrl}/payment/initiate`, {
195
+ method: "POST",
196
+ headers: this.buildHeaders(),
197
+ body: JSON.stringify({
198
+ siteId: this.siteId,
199
+ phoneNumber,
200
+ email,
201
+ firstName,
202
+ lastName
203
+ })
204
+ });
205
+ if (!res.ok) {
206
+ const errText = await res.text();
207
+ throw new Error("Failed to initiate payment: " + errText);
208
+ }
209
+ return res.json();
210
+ }
211
+ async getPaymentStatus(ref) {
212
+ const res = await fetch(`${this.apiUrl}/payment/status?ref=${ref}`, {
213
+ method: "GET",
214
+ headers: this.buildHeaders()
215
+ });
216
+ if (!res.ok) throw new Error("Failed to get payment status");
217
+ return res.json();
218
+ }
219
+ };
220
+
221
+ // src/stream.ts
222
+ function parseSSEChunk(raw) {
223
+ const frames = [];
224
+ const blocks = raw.split(/\n\n+/);
225
+ for (const block of blocks) {
226
+ if (!block.trim()) continue;
227
+ let event = "";
228
+ let data = "";
229
+ for (const line of block.split("\n")) {
230
+ if (line.startsWith("event:")) event = line.slice(6).trim();
231
+ else if (line.startsWith("data:")) data = line.slice(5);
232
+ }
233
+ if (data !== "") frames.push({ event, data });
234
+ }
235
+ return frames;
236
+ }
237
+ var KikuStream = class {
238
+ constructor(responsePromise, abortController) {
239
+ this.listeners = {};
240
+ this.aborted = false;
241
+ this.responsePromise = responsePromise;
242
+ this.abortController = abortController;
243
+ this.startReading();
244
+ }
245
+ on(event, callback) {
246
+ if (!this.listeners[event]) {
247
+ this.listeners[event] = [];
248
+ }
249
+ this.listeners[event].push(callback);
250
+ return this;
251
+ }
252
+ off(event, callback) {
253
+ if (!this.listeners[event]) return this;
254
+ this.listeners[event] = this.listeners[event].filter((cb) => cb !== callback);
255
+ return this;
256
+ }
257
+ destroy() {
258
+ this.aborted = true;
259
+ this.abortController.abort();
260
+ }
261
+ emit(event, ...args) {
262
+ const list = this.listeners[event];
263
+ if (!list) return;
264
+ for (const cb of list) {
265
+ try {
266
+ cb(...args);
267
+ } catch (err) {
268
+ console.error(`[Akropolys] Error in KikuStream event listener for "${event}":`, err);
269
+ }
270
+ }
271
+ }
272
+ async startReading() {
273
+ try {
274
+ const response = await this.responsePromise;
275
+ if (this.aborted) return;
276
+ const reader = response.body?.getReader();
277
+ if (!reader) {
278
+ throw new Error("Response body is not readable");
279
+ }
280
+ const decoder = new TextDecoder();
281
+ let buffer = "";
282
+ let accumulatedMessage = "";
283
+ while (true) {
284
+ const { done, value } = await reader.read();
285
+ if (done || this.aborted) break;
286
+ buffer += decoder.decode(value, { stream: true });
287
+ const lastBoundary = buffer.lastIndexOf("\n\n");
288
+ if (lastBoundary === -1) continue;
289
+ const complete = buffer.slice(0, lastBoundary + 2);
290
+ buffer = buffer.slice(lastBoundary + 2);
291
+ const frames = parseSSEChunk(complete);
292
+ for (const { event, data } of frames) {
293
+ if (this.aborted) return;
294
+ if (event === "meta") {
295
+ try {
296
+ const meta = JSON.parse(data);
297
+ this.emit("meta", meta);
298
+ } catch {
299
+ }
300
+ continue;
301
+ }
302
+ if (event === "done") {
303
+ break;
304
+ }
305
+ if (event === "error") {
306
+ let msg = "Stream error";
307
+ try {
308
+ msg = JSON.parse(data).error ?? msg;
309
+ } catch {
310
+ msg = data;
311
+ }
312
+ throw new Error(msg);
313
+ }
314
+ const token = data.replace(/\\n/g, "\n");
315
+ accumulatedMessage += token;
316
+ this.emit("token", token);
317
+ }
318
+ }
319
+ if (!this.aborted) {
320
+ this.emit("done", accumulatedMessage);
321
+ }
322
+ } catch (err) {
323
+ if (!this.aborted) {
324
+ this.emit("error", err);
325
+ }
326
+ }
327
+ }
328
+ };
329
+
330
+ // src/client.ts
331
+ var defaultVertical = "commerce";
332
+ function setSDKDefaultVertical(v) {
333
+ defaultVertical = v;
334
+ }
335
+ function getEnvVar(key) {
336
+ if (key === "NEXT_PUBLIC_AKROPOLYS_SITE_ID") {
337
+ try {
338
+ return process.env.NEXT_PUBLIC_AKROPOLYS_SITE_ID;
339
+ } catch {
340
+ }
341
+ }
342
+ if (key === "NEXT_PUBLIC_AKROPOLYS_API_URL") {
343
+ try {
344
+ return process.env.NEXT_PUBLIC_AKROPOLYS_API_URL;
345
+ } catch {
346
+ }
347
+ }
348
+ if (key === "NEXT_PUBLIC_AKROPOLYS_API_TOKEN") {
349
+ try {
350
+ return process.env.NEXT_PUBLIC_AKROPOLYS_API_TOKEN;
351
+ } catch {
352
+ }
353
+ }
354
+ try {
355
+ const metaEnv = import.meta.env;
356
+ if (metaEnv) {
357
+ if (key === "NEXT_PUBLIC_AKROPOLYS_SITE_ID") return metaEnv.NEXT_PUBLIC_AKROPOLYS_SITE_ID || metaEnv.VITE_AKROPOLYS_SITE_ID;
358
+ if (key === "NEXT_PUBLIC_AKROPOLYS_API_URL") return metaEnv.NEXT_PUBLIC_AKROPOLYS_API_URL || metaEnv.VITE_AKROPOLYS_API_URL;
359
+ if (key === "NEXT_PUBLIC_AKROPOLYS_API_TOKEN") return metaEnv.NEXT_PUBLIC_AKROPOLYS_API_TOKEN || metaEnv.VITE_AKROPOLYS_API_TOKEN;
360
+ }
361
+ } catch {
362
+ }
363
+ if (typeof globalThis !== "undefined") {
364
+ const g = globalThis;
365
+ if (g.process && g.process.env) {
366
+ return g.process.env[key];
367
+ }
368
+ }
369
+ return void 0;
370
+ }
371
+ function generateUUID() {
372
+ if (typeof crypto !== "undefined" && crypto.randomUUID) {
373
+ return crypto.randomUUID();
374
+ }
375
+ return "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, (c) => {
376
+ const r = Math.random() * 16 | 0;
377
+ const v = c === "x" ? r : r & 3 | 8;
378
+ return v.toString(16);
379
+ });
380
+ }
381
+ var _AkropolysClient = class _AkropolysClient {
382
+ constructor(config) {
383
+ this.ingestQueue = [];
384
+ this.ingestTimer = null;
385
+ this.ingestedUrls = /* @__PURE__ */ new Set();
386
+ this.onlineHandler = null;
387
+ this.sessionId = "";
388
+ this.isFlushing = false;
389
+ this.retryCount = 0;
390
+ const siteId = config.siteId || getEnvVar("NEXT_PUBLIC_AKROPOLYS_SITE_ID") || "";
391
+ const apiUrl = config.apiUrl || getEnvVar("NEXT_PUBLIC_AKROPOLYS_API_URL") || "";
392
+ const apiToken = config.apiToken || getEnvVar("NEXT_PUBLIC_AKROPOLYS_API_TOKEN") || "";
393
+ if (!siteId) console.error('[Akropolys] Missing siteId. Set it via <AkropolysProvider siteId="..."> or NEXT_PUBLIC_AKROPOLYS_SITE_ID.');
394
+ if (!apiUrl) console.error('[Akropolys] Missing apiUrl. Set it via <AkropolysProvider apiUrl="..."> or NEXT_PUBLIC_AKROPOLYS_API_URL.');
395
+ if (!apiToken) console.error('[Akropolys] Missing apiToken. Set it via <AkropolysProvider apiToken="..."> or NEXT_PUBLIC_AKROPOLYS_API_TOKEN.');
396
+ this.shopperId = config.shopperId;
397
+ this.authLoading = config.authLoading;
398
+ this.onCheckout = config.onCheckout;
399
+ this.onError = config.onError;
400
+ this.vertical = config.vertical || defaultVertical;
401
+ this.initSession();
402
+ this.loadIngestedCache();
403
+ this.api = new AkropolysAPI(
404
+ apiUrl,
405
+ siteId,
406
+ apiToken,
407
+ () => this.getShopperId(),
408
+ () => this.sessionId,
409
+ this.vertical
410
+ );
411
+ instance = this;
412
+ if (typeof window !== "undefined") {
413
+ this.onlineHandler = () => {
414
+ console.log("[Akropolys] Connectivity restored, flushing queued ingestions.");
415
+ this.flushQueue();
416
+ };
417
+ window.addEventListener("online", this.onlineHandler);
418
+ }
419
+ }
420
+ // 24h
421
+ loadIngestedCache() {
422
+ if (typeof window === "undefined") return;
423
+ try {
424
+ const raw = localStorage.getItem(_AkropolysClient.INGEST_CACHE_KEY);
425
+ if (!raw) return;
426
+ const { ts, urls } = JSON.parse(raw);
427
+ if (Date.now() - ts > _AkropolysClient.INGEST_CACHE_TTL) {
428
+ localStorage.removeItem(_AkropolysClient.INGEST_CACHE_KEY);
429
+ return;
430
+ }
431
+ this.ingestedUrls = new Set(urls);
432
+ } catch {
433
+ }
434
+ }
435
+ saveIngestedCache() {
436
+ if (typeof window === "undefined") return;
437
+ try {
438
+ localStorage.setItem(
439
+ _AkropolysClient.INGEST_CACHE_KEY,
440
+ JSON.stringify({ ts: Date.now(), urls: [...this.ingestedUrls] })
441
+ );
442
+ } catch {
443
+ }
444
+ }
445
+ chat(query, history = []) {
446
+ const abortController = new AbortController();
447
+ const responsePromise = this.api.chatStream(query, history, abortController.signal);
448
+ return new KikuStream(responsePromise, abortController);
449
+ }
450
+ reRegister() {
451
+ instance = this;
452
+ if (typeof window !== "undefined" && !this.onlineHandler) {
453
+ this.onlineHandler = () => this.flushQueue();
454
+ window.addEventListener("online", this.onlineHandler);
455
+ }
456
+ }
457
+ setShopperId(id) {
458
+ this.shopperId = id;
459
+ if (!this.authLoading) {
460
+ this.flushQueue();
461
+ }
462
+ }
463
+ setAuthLoading(loading) {
464
+ const wasLoading = this.authLoading;
465
+ this.authLoading = loading;
466
+ if (wasLoading && !loading) {
467
+ this.flushQueue();
468
+ }
469
+ }
470
+ getShopperId() {
471
+ return this.shopperId || "guest_" + this.sessionId;
472
+ }
473
+ getSessionId() {
474
+ return this.sessionId;
475
+ }
476
+ initSession() {
477
+ if (typeof window !== "undefined" && window.sessionStorage) {
478
+ try {
479
+ let sid = window.sessionStorage.getItem("akropolys_session_id");
480
+ if (!sid) {
481
+ sid = generateUUID();
482
+ window.sessionStorage.setItem("akropolys_session_id", sid);
483
+ }
484
+ this.sessionId = sid;
485
+ return;
486
+ } catch (e) {
487
+ }
488
+ }
489
+ this.sessionId = generateUUID();
490
+ }
491
+ destroy() {
492
+ if (typeof window !== "undefined" && this.onlineHandler) {
493
+ window.removeEventListener("online", this.onlineHandler);
494
+ this.onlineHandler = null;
495
+ }
496
+ if (this.ingestTimer) {
497
+ clearTimeout(this.ingestTimer);
498
+ this.ingestTimer = null;
499
+ }
500
+ if (instance === this) instance = null;
501
+ }
502
+ async queueIngest(rawItem) {
503
+ const id = rawItem.id ?? rawItem.productId ?? rawItem.slug ?? rawItem.url ?? rawItem.name ?? "";
504
+ const url = rawItem.url || (typeof window !== "undefined" ? window.location.href : "");
505
+ if (!id && !url) {
506
+ console.warn("[Akropolys] Ingestion warning: Item is missing both a stable identifier and a URL. Skipping.");
507
+ return;
508
+ }
509
+ if (url) {
510
+ if (this.ingestedUrls.has(url)) {
511
+ return;
512
+ }
513
+ this.ingestedUrls.add(url);
514
+ this.saveIngestedCache();
515
+ }
516
+ this.ingestQueue.push(rawItem);
517
+ this.scheduleFlush();
518
+ }
519
+ async queueIngestBatch(rawItems) {
520
+ let hasNew = false;
521
+ rawItems.forEach((rawItem) => {
522
+ const id = rawItem.id ?? rawItem.productId ?? rawItem.slug ?? rawItem.url ?? rawItem.name ?? "";
523
+ const url = rawItem.url || (typeof window !== "undefined" ? window.location.href : "");
524
+ if (!id && !url) {
525
+ console.warn("[Akropolys] Ingestion warning: Item is missing both a stable identifier and a URL. Skipping.");
526
+ return;
527
+ }
528
+ if (url) {
529
+ if (this.ingestedUrls.has(url)) {
530
+ return;
531
+ }
532
+ this.ingestedUrls.add(url);
533
+ hasNew = true;
534
+ }
535
+ this.ingestQueue.push(rawItem);
536
+ });
537
+ if (hasNew) {
538
+ this.saveIngestedCache();
539
+ }
540
+ if (this.ingestQueue.length > 0) {
541
+ this.scheduleFlush();
542
+ }
543
+ }
544
+ scheduleFlush() {
545
+ if (this.ingestTimer || this.isFlushing) return;
546
+ this.ingestTimer = setTimeout(() => {
547
+ this.flushQueue();
548
+ }, 300);
549
+ }
550
+ async flushQueue() {
551
+ if (this.isFlushing) return;
552
+ this.isFlushing = true;
553
+ if (this.ingestTimer) {
554
+ clearTimeout(this.ingestTimer);
555
+ this.ingestTimer = null;
556
+ }
557
+ if (this.authLoading) {
558
+ console.log("[Akropolys] Authentication is loading. Deferring ingestion flush.");
559
+ this.isFlushing = false;
560
+ return;
561
+ }
562
+ if (typeof navigator !== "undefined" && !navigator.onLine) {
563
+ console.warn("[Akropolys] Browser offline. Postponing ingestion.");
564
+ this.isFlushing = false;
565
+ return;
566
+ }
567
+ const maxBatchSize = 50;
568
+ try {
569
+ while (this.ingestQueue.length > 0) {
570
+ const batch = this.ingestQueue.slice(0, maxBatchSize);
571
+ try {
572
+ await this.api.ingestBatch(batch);
573
+ this.ingestQueue.splice(0, batch.length);
574
+ this.retryCount = 0;
575
+ } catch (e) {
576
+ const status = e.status || 500;
577
+ const message = e.message || "Unknown network error";
578
+ if (this.onError) {
579
+ try {
580
+ this.onError({ status, message });
581
+ } catch (err) {
582
+ console.error("[Akropolys] Error inside onError callback:", err);
583
+ }
584
+ }
585
+ if (status >= 400 && status < 500 && status !== 429) {
586
+ console.error("[Akropolys] Ingestion discarded due to client error:", message);
587
+ this.ingestQueue.splice(0, batch.length);
588
+ continue;
589
+ } else {
590
+ console.warn("[Akropolys] Ingestion temporarily failed. Retrying later.", message);
591
+ this.scheduleFlushWithBackoff();
592
+ break;
593
+ }
594
+ }
595
+ }
596
+ } finally {
597
+ this.isFlushing = false;
598
+ }
599
+ }
600
+ scheduleFlushWithBackoff() {
601
+ if (this.ingestTimer) return;
602
+ const baseDelay = 1e3;
603
+ const jitter = Math.random() * 1e3;
604
+ const delay = Math.min(baseDelay * Math.pow(2, this.retryCount), 3e4) + jitter;
605
+ this.retryCount++;
606
+ this.ingestTimer = setTimeout(() => {
607
+ this.flushQueue();
608
+ }, delay);
609
+ }
610
+ };
611
+ _AkropolysClient.INGEST_CACHE_KEY = "akropolys_ingested_v2";
612
+ _AkropolysClient.INGEST_CACHE_TTL = 24 * 60 * 60 * 1e3;
613
+ var AkropolysClient = _AkropolysClient;
614
+ var instance = null;
615
+ function initAkropolys(config) {
616
+ instance = new AkropolysClient(config);
617
+ return instance;
618
+ }
619
+ function getAkropolysClient() {
620
+ if (!instance) {
621
+ const siteId = getEnvVar("NEXT_PUBLIC_AKROPOLYS_SITE_ID");
622
+ const apiUrl = getEnvVar("NEXT_PUBLIC_AKROPOLYS_API_URL");
623
+ const apiToken = getEnvVar("NEXT_PUBLIC_AKROPOLYS_API_TOKEN");
624
+ if (siteId && apiUrl && apiToken) {
625
+ instance = new AkropolysClient({ siteId, apiUrl, apiToken });
626
+ } else {
627
+ throw new Error("[Akropolys] Call initAkropolys() or set NEXT_PUBLIC_AKROPOLYS_* environment variables before using the client.");
628
+ }
629
+ }
630
+ return instance;
631
+ }
632
+
633
+ // src/Provider.tsx
634
+ import { createContext, useContext, useEffect, useRef } from "react";
635
+ import { jsx } from "react/jsx-runtime";
636
+ var AkropolysContext = createContext(null);
637
+ function AkropolysProvider({
638
+ siteId,
639
+ apiUrl,
640
+ apiToken,
641
+ shopperId,
642
+ vertical,
643
+ authLoading,
644
+ onCheckout,
645
+ onError,
646
+ children
647
+ }) {
648
+ const clientRef = useRef(null);
649
+ if (!clientRef.current) {
650
+ clientRef.current = new AkropolysClient({
651
+ siteId,
652
+ apiUrl,
653
+ apiToken,
654
+ shopperId,
655
+ vertical,
656
+ authLoading,
657
+ onCheckout,
658
+ onError
659
+ });
660
+ } else {
661
+ clientRef.current.reRegister();
662
+ }
663
+ useEffect(() => {
664
+ clientRef.current?.setShopperId(shopperId);
665
+ }, [shopperId]);
666
+ useEffect(() => {
667
+ clientRef.current?.setAuthLoading(!!authLoading);
668
+ }, [authLoading]);
669
+ useEffect(() => {
670
+ if (clientRef.current) {
671
+ clientRef.current.onError = onError;
672
+ clientRef.current.onCheckout = onCheckout;
673
+ }
674
+ }, [onError, onCheckout]);
675
+ useEffect(() => {
676
+ clientRef.current?.reRegister();
677
+ }, []);
678
+ useEffect(() => {
679
+ return () => {
680
+ clientRef.current?.destroy();
681
+ };
682
+ }, []);
683
+ return /* @__PURE__ */ jsx(AkropolysContext.Provider, { value: clientRef.current, children });
684
+ }
685
+ function useAkropolysContext() {
686
+ const context = useContext(AkropolysContext);
687
+ if (!context) {
688
+ return getAkropolysClient();
689
+ }
690
+ return context;
691
+ }
692
+
693
+ // src/hooks/useAkropolys.ts
694
+ import { useRef as useRef2 } from "react";
695
+ function useAkropolys(config) {
696
+ const clientRef = useRef2(null);
697
+ if (!clientRef.current) {
698
+ console.warn("[Akropolys] useAkropolys() is deprecated. Please wrap your application in <AkropolysProvider> instead.");
699
+ clientRef.current = initAkropolys(config);
700
+ }
701
+ return clientRef.current;
702
+ }
703
+
704
+ // src/hooks/useSearch.ts
705
+ import { useState, useCallback, useRef as useRef3 } from "react";
706
+ function useSearch() {
707
+ const client = useAkropolysContext();
708
+ const [results, setResults] = useState([]);
709
+ const [loading, setLoading] = useState(false);
710
+ const [error, setError] = useState(null);
711
+ const genRef = useRef3(0);
712
+ const search = useCallback(async (query, limit = 8) => {
713
+ if (!query.trim()) {
714
+ setResults([]);
715
+ setLoading(false);
716
+ return;
717
+ }
718
+ const gen = ++genRef.current;
719
+ setLoading(true);
720
+ setError(null);
721
+ try {
722
+ const res = await client.api.searchAutocomplete(query, limit);
723
+ if (gen === genRef.current) {
724
+ setResults(res.results ?? []);
725
+ }
726
+ } catch (e) {
727
+ if (gen === genRef.current) {
728
+ let msg = e?.message ?? "Search failed";
729
+ try {
730
+ const parsed = JSON.parse(msg);
731
+ if (parsed && parsed.error) {
732
+ msg = parsed.error;
733
+ }
734
+ } catch {
735
+ }
736
+ setError(msg);
737
+ }
738
+ } finally {
739
+ if (gen === genRef.current) setLoading(false);
740
+ }
741
+ }, [client]);
742
+ const clear = useCallback(() => {
743
+ genRef.current++;
744
+ setResults([]);
745
+ setError(null);
746
+ setLoading(false);
747
+ }, []);
748
+ return { results, loading, error, search, clear };
749
+ }
750
+
751
+ // src/hooks/useIngest.ts
752
+ import { useCallback as useCallback2 } from "react";
753
+
754
+ // src/utils/TTLCache.ts
755
+ var TTLCache = class {
756
+ constructor(ttlMs = 24 * 60 * 60 * 1e3) {
757
+ this.cache = /* @__PURE__ */ new Map();
758
+ this.ttl = ttlMs;
759
+ }
760
+ add(key) {
761
+ this.cache.set(key, Date.now());
762
+ this.evictExpired();
763
+ }
764
+ has(key) {
765
+ const timestamp = this.cache.get(key);
766
+ if (timestamp === void 0) return false;
767
+ if (Date.now() - timestamp > this.ttl) {
768
+ this.cache.delete(key);
769
+ return false;
770
+ }
771
+ return true;
772
+ }
773
+ evictExpired() {
774
+ const now = Date.now();
775
+ for (const [key, timestamp] of this.cache.entries()) {
776
+ if (now - timestamp > this.ttl) {
777
+ this.cache.delete(key);
778
+ }
779
+ }
780
+ }
781
+ };
782
+
783
+ // src/hooks/useIngest.ts
784
+ var recentlyIngested = new TTLCache(24 * 60 * 60 * 1e3);
785
+ function getProductKey(p) {
786
+ return p.id || p.productId || p.slug || p.url || p.name || p.title || p.productName || null;
787
+ }
788
+ function useIngest() {
789
+ const client = useAkropolysContext();
790
+ const ingest = useCallback2((product) => {
791
+ const key = getProductKey(product);
792
+ if (key) {
793
+ if (recentlyIngested.has(key)) return;
794
+ recentlyIngested.add(key);
795
+ }
796
+ client.queueIngest(product).catch(() => {
797
+ });
798
+ }, [client]);
799
+ const ingestBatch = useCallback2((products) => {
800
+ const toIngest = products.filter((p) => {
801
+ const key = getProductKey(p);
802
+ if (!key) return true;
803
+ if (recentlyIngested.has(key)) return false;
804
+ recentlyIngested.add(key);
805
+ return true;
806
+ });
807
+ if (!toIngest.length) return;
808
+ client.queueIngestBatch(toIngest).catch(() => {
809
+ });
810
+ }, [client]);
811
+ return { ingest, ingestBatch, loading: false, error: null };
812
+ }
813
+
814
+ // src/hooks/useListIngest.ts
815
+ import { useEffect as useEffect2, useRef as useRef4 } from "react";
816
+ function useListIngest(items) {
817
+ const { ingestBatch } = useIngest();
818
+ const processedIdsRef = useRef4(/* @__PURE__ */ new Set());
819
+ const listKey = (items || []).map((p) => p.id ?? p.productId ?? p.slug ?? p.url ?? p.name ?? "").join(",");
820
+ useEffect2(() => {
821
+ if (!items || !items.length) return;
822
+ const newItems = items.filter((item) => {
823
+ const id = item.id ?? item.productId ?? item.slug ?? item.url ?? item.name ?? "";
824
+ if (!id) return true;
825
+ if (processedIdsRef.current.has(id)) {
826
+ return false;
827
+ }
828
+ processedIdsRef.current.add(id);
829
+ return true;
830
+ });
831
+ if (newItems.length > 0) {
832
+ ingestBatch(newItems);
833
+ }
834
+ }, [listKey, ingestBatch]);
835
+ }
836
+
837
+ // src/hooks/usePageIngest.ts
838
+ import { useEffect as useEffect3, useRef as useRef5 } from "react";
839
+ function usePageIngest(product) {
840
+ const lastIngestedKey = useRef5(null);
841
+ const uniqueId = product ? product.id ?? product.productId ?? product.slug ?? product.url ?? "" : "";
842
+ useEffect3(() => {
843
+ if (!product || !uniqueId) return;
844
+ if (lastIngestedKey.current === uniqueId) return;
845
+ lastIngestedKey.current = uniqueId;
846
+ try {
847
+ getAkropolysClient().queueIngest(product);
848
+ } catch (err) {
849
+ if (typeof process !== "undefined" && process.env && process.env.NODE_ENV !== "production") {
850
+ console.warn("[Akropolys] Ingestion failed inside usePageIngest:", err);
851
+ }
852
+ }
853
+ }, [uniqueId]);
854
+ }
855
+
856
+ // src/hooks/useKiku.ts
857
+ import { useState as useState2, useCallback as useCallback3, useRef as useRef6, useEffect as useEffect4 } from "react";
858
+ function useKiku(options = {}) {
859
+ const client = useAkropolysContext();
860
+ const [messages, setMessages] = useState2(options.initialMessages ?? []);
861
+ const [sources, setSources] = useState2([]);
862
+ const [loading, setLoading] = useState2(false);
863
+ const [streaming, setStreaming] = useState2(false);
864
+ const [error, setError] = useState2(null);
865
+ const [lastAction, setLastAction] = useState2(null);
866
+ const [lastIntent, setLastIntent] = useState2(null);
867
+ const activeStreamRef = useRef6(null);
868
+ const onTokenRef = useRef6(options.onToken);
869
+ const onMetaRef = useRef6(options.onMeta);
870
+ const onDoneRef = useRef6(options.onDone);
871
+ const onErrorRef = useRef6(options.onError);
872
+ useEffect4(() => {
873
+ onTokenRef.current = options.onToken;
874
+ onMetaRef.current = options.onMeta;
875
+ onDoneRef.current = options.onDone;
876
+ onErrorRef.current = options.onError;
877
+ }, [options.onToken, options.onMeta, options.onDone, options.onError]);
878
+ useEffect4(() => {
879
+ return () => {
880
+ activeStreamRef.current?.destroy();
881
+ };
882
+ }, []);
883
+ const send = useCallback3(async (query, displayQuery) => {
884
+ if (!query.trim() || loading) return;
885
+ activeStreamRef.current?.destroy();
886
+ const userMsg = { role: "user", content: displayQuery ?? query };
887
+ setMessages((prev) => [...prev, userMsg]);
888
+ setLoading(true);
889
+ setStreaming(false);
890
+ setError(null);
891
+ try {
892
+ const history = messages.map((m) => ({ role: m.role, content: m.content }));
893
+ const stream = client.chat(query, history);
894
+ activeStreamRef.current = stream;
895
+ let messageInitialized = false;
896
+ let lastMeta = null;
897
+ stream.on("meta", (meta) => {
898
+ lastMeta = meta;
899
+ setSources(meta.sources ?? []);
900
+ if (meta.intent) setLastIntent(meta.intent);
901
+ if (meta.action) setLastAction(meta.action);
902
+ onMetaRef.current?.(meta);
903
+ });
904
+ stream.on("token", (token) => {
905
+ if (!messageInitialized) {
906
+ setLoading(false);
907
+ setStreaming(true);
908
+ setMessages((prev) => [...prev, { role: "assistant", content: token }]);
909
+ messageInitialized = true;
910
+ } else {
911
+ setMessages((prev) => {
912
+ const next = [...prev];
913
+ if (next.length > 0 && next[next.length - 1].role === "assistant") {
914
+ next[next.length - 1] = {
915
+ ...next[next.length - 1],
916
+ content: next[next.length - 1].content + token
917
+ };
918
+ }
919
+ return next;
920
+ });
921
+ }
922
+ onTokenRef.current?.(token);
923
+ });
924
+ stream.on("done", (fullMessage) => {
925
+ setLoading(false);
926
+ setStreaming(false);
927
+ const metaAction = lastMeta?.action;
928
+ const metaCheckout = lastMeta?.checkout;
929
+ const isCartAction = metaAction?.type === "add_to_cart" || metaAction?.type === "remove_from_cart" || metaAction?.type === "clear_cart" || metaAction?.type === "view_cart";
930
+ if (isCartAction || metaCheckout) {
931
+ setMessages((prev) => {
932
+ const next = [...prev];
933
+ if (next.length > 0 && next[next.length - 1].role === "assistant") {
934
+ next[next.length - 1] = {
935
+ ...next[next.length - 1],
936
+ cartSnapshot: metaCheckout,
937
+ actionType: metaAction?.type
938
+ };
939
+ }
940
+ return next;
941
+ });
942
+ window.dispatchEvent(new CustomEvent("akropolys:cart_updated", { detail: metaCheckout }));
943
+ }
944
+ if (metaAction?.type === "checkout") {
945
+ window.dispatchEvent(new CustomEvent("akropolys:trigger_checkout", { detail: metaCheckout }));
946
+ }
947
+ if (metaAction?.type === "awaiting_payment") {
948
+ window.dispatchEvent(new CustomEvent("akropolys:awaiting_payment", { detail: metaAction }));
949
+ }
950
+ if (metaCheckout && client.onCheckout) {
951
+ client.onCheckout(metaCheckout);
952
+ }
953
+ onDoneRef.current?.(fullMessage);
954
+ });
955
+ stream.on("error", (err) => {
956
+ setLoading(false);
957
+ setStreaming(false);
958
+ setError(err.message);
959
+ setMessages((prev) => prev.slice(0, -1));
960
+ onErrorRef.current?.(err);
961
+ });
962
+ } catch (err) {
963
+ setLoading(false);
964
+ setStreaming(false);
965
+ setError(err?.message ?? "Chat request failed");
966
+ setMessages((prev) => prev.slice(0, -1));
967
+ onErrorRef.current?.(err);
968
+ }
969
+ }, [client, messages, loading]);
970
+ const reset = useCallback3(() => {
971
+ activeStreamRef.current?.destroy();
972
+ setMessages([]);
973
+ setSources([]);
974
+ setStreaming(false);
975
+ setError(null);
976
+ setLoading(false);
977
+ setLastAction(null);
978
+ setLastIntent(null);
979
+ }, []);
980
+ return { messages, sources, loading, streaming, error, lastAction, lastIntent, send, reset };
981
+ }
982
+
983
+ // src/hooks/useCart.ts
984
+ import { useState as useState3, useEffect as useEffect5, useCallback as useCallback4 } from "react";
985
+ function useCart() {
986
+ const client = useAkropolysContext();
987
+ const [cart, setCart] = useState3(null);
988
+ const [loading, setLoading] = useState3(false);
989
+ const shopperId = client.getShopperId();
990
+ const fetchCart = useCallback4(async () => {
991
+ if (!shopperId) return;
992
+ setLoading(true);
993
+ try {
994
+ const res = await client.api.getCart();
995
+ setCart(res);
996
+ } catch (e) {
997
+ console.error("[Akropolys] Failed to fetch cart", e);
998
+ } finally {
999
+ setLoading(false);
1000
+ }
1001
+ }, [client, shopperId]);
1002
+ useEffect5(() => {
1003
+ fetchCart();
1004
+ const handleCartUpdate = (e) => {
1005
+ if (e.detail) {
1006
+ setCart(e.detail);
1007
+ } else {
1008
+ fetchCart();
1009
+ }
1010
+ };
1011
+ if (typeof window !== "undefined") {
1012
+ window.addEventListener("akropolys:cart_updated", handleCartUpdate);
1013
+ return () => window.removeEventListener("akropolys:cart_updated", handleCartUpdate);
1014
+ }
1015
+ }, [fetchCart, shopperId]);
1016
+ return { cart, loading, fetchCart };
1017
+ }
1018
+
1019
+ // src/hooks/usePaymentPolling.ts
1020
+ import { useState as useState4, useEffect as useEffect6, useRef as useRef7 } from "react";
1021
+ function usePaymentPolling({
1022
+ client,
1023
+ merchantReference,
1024
+ onSuccess,
1025
+ onFailure,
1026
+ intervalMs = 3e3,
1027
+ timeoutMs = 3e5
1028
+ // 5 minutes default
1029
+ }) {
1030
+ const [status, setStatus] = useState4("IDLE");
1031
+ const [error, setError] = useState4(null);
1032
+ const onSuccessRef = useRef7(onSuccess);
1033
+ const onFailureRef = useRef7(onFailure);
1034
+ useEffect6(() => {
1035
+ onSuccessRef.current = onSuccess;
1036
+ onFailureRef.current = onFailure;
1037
+ }, [onSuccess, onFailure]);
1038
+ useEffect6(() => {
1039
+ if (!merchantReference) {
1040
+ setStatus("IDLE");
1041
+ setError(null);
1042
+ return;
1043
+ }
1044
+ setStatus("PENDING");
1045
+ setError(null);
1046
+ const startTime = Date.now();
1047
+ let timerId = null;
1048
+ async function checkStatus() {
1049
+ try {
1050
+ if (Date.now() - startTime >= timeoutMs) {
1051
+ setStatus("FAILED");
1052
+ setError("Payment session timed out");
1053
+ if (onFailureRef.current) onFailureRef.current("Payment session timed out");
1054
+ return;
1055
+ }
1056
+ const res = await client.getPaymentStatus(merchantReference);
1057
+ if (res.status === "COMPLETED") {
1058
+ setStatus("COMPLETED");
1059
+ if (onSuccessRef.current) onSuccessRef.current();
1060
+ } else if (res.status === "FAILED") {
1061
+ setStatus("FAILED");
1062
+ setError("Payment failed");
1063
+ if (onFailureRef.current) onFailureRef.current("Payment failed");
1064
+ } else {
1065
+ timerId = setTimeout(checkStatus, intervalMs);
1066
+ }
1067
+ } catch (err) {
1068
+ console.error("[Akropolys Polling Error]", err);
1069
+ timerId = setTimeout(checkStatus, intervalMs);
1070
+ }
1071
+ }
1072
+ timerId = setTimeout(checkStatus, intervalMs);
1073
+ return () => {
1074
+ if (timerId) {
1075
+ clearTimeout(timerId);
1076
+ }
1077
+ };
1078
+ }, [client, merchantReference, intervalMs, timeoutMs]);
1079
+ return { status, error };
1080
+ }
1081
+
1082
+ export {
1083
+ AkropolysAPI,
1084
+ KikuStream,
1085
+ setSDKDefaultVertical,
1086
+ AkropolysClient,
1087
+ initAkropolys,
1088
+ getAkropolysClient,
1089
+ AkropolysProvider,
1090
+ useAkropolysContext,
1091
+ useAkropolys,
1092
+ useSearch,
1093
+ useIngest,
1094
+ useListIngest,
1095
+ usePageIngest,
1096
+ useKiku,
1097
+ useCart,
1098
+ usePaymentPolling
1099
+ };
1100
+ //# sourceMappingURL=chunk-UKF434HE.mjs.map