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