@retrivora-ai/rag-engine 2.3.7 → 2.3.9

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/dist/server.mjs CHANGED
@@ -315,7 +315,7 @@ var init_package = __esm({
315
315
  "package.json"() {
316
316
  package_default = {
317
317
  name: "@retrivora-ai/rag-engine",
318
- version: "2.3.7",
318
+ version: "2.3.9",
319
319
  description: "Retrivora AI is a plug-and-play AI engine for RAG chat experiences \u2014 generic vector DB + LLM provider, embeddable or standalone.",
320
320
  author: "Abhinav Alkuchi",
321
321
  license: "UNLICENSED",
@@ -501,10 +501,16 @@ var init_ConfigFetcher = __esm({
501
501
  process.env.RETRIVORA_CONTROL_PLANE_URL,
502
502
  process.env.NEXT_PUBLIC_RETRIVORA_CONTROL_PLANE_URL,
503
503
  CONTROL_PLANE_URL
504
- ].filter((url) => Boolean(url) && !url.includes("localhost") && !url.includes("127.0.0.1")).map((url) => url.replace(/\/$/, ""));
504
+ ].filter((url) => {
505
+ if (!url) return false;
506
+ const isEnvVar = url === process.env.RETRIVORA_CONTROL_PLANE_URL || url === process.env.NEXT_PUBLIC_RETRIVORA_CONTROL_PLANE_URL;
507
+ if (!isEnvVar && (url.includes("localhost") || url.includes("127.0.0.1"))) return false;
508
+ return true;
509
+ }).map((url) => url.replace(/\/$/, ""));
505
510
  for (const baseUrl of controlPlaneUrls) {
506
511
  try {
507
512
  const url = `${baseUrl}/api/v1/config?projectId=${encodeURIComponent(projectId)}`;
513
+ console.log(`[ConfigFetcher] Fetching config from: ${url}`);
508
514
  const res = await fetch(url, {
509
515
  method: "GET",
510
516
  headers: __spreadValues({
@@ -512,6 +518,10 @@ var init_ConfigFetcher = __esm({
512
518
  "x-sdk-version": SDK_VERSION
513
519
  }, licenseKey ? { "x-license-key": licenseKey } : {})
514
520
  });
521
+ console.log(`[ConfigFetcher] Response status: ${res.status}`);
522
+ if (!res.ok) {
523
+ console.warn(`[ConfigFetcher] Error text: ${await res.text()}`);
524
+ }
515
525
  if (res.ok) {
516
526
  const data = await res.json();
517
527
  if ((data == null ? void 0 : data.success) && (data == null ? void 0 : data.vectorDb)) {
@@ -522,8 +532,7 @@ var init_ConfigFetcher = __esm({
522
532
  isActive: data.isActive,
523
533
  expiresAt: data.expiresAt,
524
534
  vectorDb: {
525
- // apiKey is not returned by the config API — it's a server-only secret.
526
- // The SDK uses local PINECONE_API_KEY if available.
535
+ // Fetch apiKey from credentials API if available, else fallback to empty
527
536
  apiKey: data.vectorDb.apiKey || "",
528
537
  indexName: data.vectorDb.indexName || "retrivora-free",
529
538
  provider: data.vectorDb.provider || "pinecone",
@@ -555,6 +564,32 @@ var init_ConfigFetcher = __esm({
555
564
  data.projectSettings || data.settings
556
565
  )
557
566
  };
567
+ if (licenseKey) {
568
+ try {
569
+ const credUrl = `${baseUrl}/api/v1/credentials`;
570
+ const credRes = await fetch(credUrl, {
571
+ method: "POST",
572
+ headers: {
573
+ "Content-Type": "application/json"
574
+ },
575
+ body: JSON.stringify({ licenseKey, projectId: fetchedProjectId })
576
+ });
577
+ if (credRes.ok) {
578
+ const credData = await credRes.json();
579
+ if ((credData == null ? void 0 : credData.success) && (credData == null ? void 0 : credData.credentials)) {
580
+ if (credData.credentials.pineconeApiKey && !config.vectorDb.apiKey) {
581
+ config.vectorDb.apiKey = credData.credentials.pineconeApiKey;
582
+ }
583
+ if (credData.credentials.litellmApiKey) {
584
+ config.llm.apiKey = credData.credentials.litellmApiKey;
585
+ config.embedding.apiKey = credData.credentials.litellmApiKey;
586
+ }
587
+ }
588
+ }
589
+ } catch (e) {
590
+ console.warn("[ConfigFetcher] Failed to fetch credentials:", e);
591
+ }
592
+ }
558
593
  this.cache.set(cacheKey, { config, cachedAt: now });
559
594
  return config;
560
595
  }
@@ -594,6 +629,14 @@ var init_PineconeProvider = __esm({
594
629
  const opts = config.options || {};
595
630
  this.apiKey = opts.apiKey || process.env.PINECONE_API_KEY || "";
596
631
  }
632
+ getControlPlaneUrl() {
633
+ const urls = [
634
+ process.env.RETRIVORA_CONTROL_PLANE_URL,
635
+ process.env.NEXT_PUBLIC_RETRIVORA_CONTROL_PLANE_URL,
636
+ "https://www.retrivora.com"
637
+ ].filter((url) => Boolean(url));
638
+ return urls[0].replace(/\/$/, "");
639
+ }
597
640
  static getValidator() {
598
641
  return {
599
642
  validate(config) {
@@ -657,6 +700,7 @@ var init_PineconeProvider = __esm({
657
700
  let key = this.apiKey || process.env.PINECONE_API_KEY || "";
658
701
  if (!key) {
659
702
  const licenseKey = process.env.RETRIVORA_LICENSE_KEY || process.env.NEXT_PUBLIC_RETRIVORA_LICENSE_KEY;
703
+ this.licenseKey = licenseKey;
660
704
  const jwtProjectId = (() => {
661
705
  if (!licenseKey) return void 0;
662
706
  try {
@@ -670,6 +714,7 @@ var init_PineconeProvider = __esm({
670
714
  return void 0;
671
715
  })();
672
716
  const projectId = process.env.RAG_PROJECT_ID || process.env.NEXT_PUBLIC_RAG_PROJECT_ID || jwtProjectId || this.projectId || "default";
717
+ this.projectId = projectId;
673
718
  const remoteConfig = await ConfigFetcher.fetchRemoteVectorConfig(projectId, licenseKey);
674
719
  if (remoteConfig) {
675
720
  if (remoteConfig.apiKey) {
@@ -715,19 +760,59 @@ var init_PineconeProvider = __esm({
715
760
  return namespace ? idx.namespace(namespace) : idx.namespace("");
716
761
  }
717
762
  async upsert(doc, namespace) {
718
- var _a3;
763
+ var _a3, _b;
764
+ if (!this.client) {
765
+ if (!this.licenseKey) throw new Error("[PineconeProvider] Cannot execute vector operation: Missing API key and License key.");
766
+ const res = await fetch(`${this.getControlPlaneUrl()}/api/v1/vectors/upsert`, {
767
+ method: "POST",
768
+ headers: { "Content-Type": "application/json", "x-license-key": this.licenseKey },
769
+ body: JSON.stringify({
770
+ projectId: this.projectId,
771
+ indexName: this.indexName,
772
+ namespace: namespace || this.projectId,
773
+ records: [{ id: String(doc.id), values: doc.vector, metadata: __spreadValues({ content: doc.content }, (_a3 = doc.metadata) != null ? _a3 : {}) }]
774
+ })
775
+ });
776
+ if (!res.ok) throw new Error(`[PineconeProvider] Proxy upsert failed: ${await res.text()}`);
777
+ return;
778
+ }
719
779
  const targetIdx = await this.getActiveIndex(namespace);
720
780
  await targetIdx.upsert({
721
781
  records: [{
722
782
  id: String(doc.id),
723
783
  values: doc.vector,
724
- metadata: __spreadValues({ content: doc.content }, (_a3 = doc.metadata) != null ? _a3 : {})
784
+ metadata: __spreadValues({ content: doc.content }, (_b = doc.metadata) != null ? _b : {})
725
785
  }]
726
786
  });
727
787
  }
728
788
  async batchUpsert(docs, namespace) {
729
- const targetIdx = await this.getActiveIndex(namespace);
730
789
  const BATCH = 100;
790
+ if (!this.client) {
791
+ if (!this.licenseKey) throw new Error("[PineconeProvider] Cannot execute vector operation: Missing API key and License key.");
792
+ for (let i = 0; i < docs.length; i += BATCH) {
793
+ const records = docs.slice(i, i + BATCH).map((d) => {
794
+ var _a3;
795
+ return {
796
+ id: String(d.id),
797
+ values: d.vector,
798
+ metadata: __spreadValues({ content: d.content }, (_a3 = d.metadata) != null ? _a3 : {})
799
+ };
800
+ });
801
+ const res = await fetch(`${this.getControlPlaneUrl()}/api/v1/vectors/upsert`, {
802
+ method: "POST",
803
+ headers: { "Content-Type": "application/json", "x-license-key": this.licenseKey },
804
+ body: JSON.stringify({
805
+ projectId: this.projectId,
806
+ indexName: this.indexName,
807
+ namespace: namespace || this.projectId,
808
+ records
809
+ })
810
+ });
811
+ if (!res.ok) throw new Error(`[PineconeProvider] Proxy batch upsert failed: ${await res.text()}`);
812
+ }
813
+ return;
814
+ }
815
+ const targetIdx = await this.getActiveIndex(namespace);
731
816
  for (let i = 0; i < docs.length; i += BATCH) {
732
817
  const records = docs.slice(i, i + BATCH).map((d) => {
733
818
  var _a3;
@@ -741,20 +826,46 @@ var init_PineconeProvider = __esm({
741
826
  }
742
827
  }
743
828
  async query(vector, topK, namespace, filter) {
744
- var _a3;
745
- const targetIdx = await this.getActiveIndex(namespace);
829
+ var _a3, _b;
746
830
  const pineconeFilter = this.sanitizeFilter(filter);
831
+ if (!this.client) {
832
+ if (!this.licenseKey) throw new Error("[PineconeProvider] Cannot execute vector operation: Missing API key and License key.");
833
+ const res = await fetch(`${this.getControlPlaneUrl()}/api/v1/vectors/query`, {
834
+ method: "POST",
835
+ headers: { "Content-Type": "application/json", "x-license-key": this.licenseKey },
836
+ body: JSON.stringify({
837
+ projectId: this.projectId,
838
+ indexName: this.indexName,
839
+ namespace: namespace || this.projectId,
840
+ vector,
841
+ topK,
842
+ filter: pineconeFilter
843
+ })
844
+ });
845
+ if (!res.ok) throw new Error(`[PineconeProvider] Proxy query failed: ${await res.text()}`);
846
+ const data = await res.json();
847
+ return ((_a3 = data.matches) != null ? _a3 : []).map((m) => {
848
+ var _a4, _b2;
849
+ return {
850
+ id: m.id,
851
+ score: (_a4 = m.score) != null ? _a4 : 0,
852
+ content: ((_b2 = m.metadata) == null ? void 0 : _b2.content) || "",
853
+ metadata: m.metadata
854
+ };
855
+ });
856
+ }
857
+ const targetIdx = await this.getActiveIndex(namespace);
747
858
  const result = await targetIdx.query(__spreadValues({
748
859
  vector,
749
860
  topK,
750
861
  includeMetadata: true
751
862
  }, Object.keys(pineconeFilter).length > 0 ? { filter: pineconeFilter } : {}));
752
- return ((_a3 = result.matches) != null ? _a3 : []).map((m) => {
753
- var _a4, _b;
863
+ return ((_b = result.matches) != null ? _b : []).map((m) => {
864
+ var _a4, _b2;
754
865
  return {
755
866
  id: m.id,
756
867
  score: (_a4 = m.score) != null ? _a4 : 0,
757
- content: ((_b = m.metadata) == null ? void 0 : _b.content) || "",
868
+ content: ((_b2 = m.metadata) == null ? void 0 : _b2.content) || "",
758
869
  metadata: m.metadata
759
870
  };
760
871
  });
@@ -1733,7 +1844,7 @@ __export(QdrantProvider_exports, {
1733
1844
  QdrantProvider: () => QdrantProvider
1734
1845
  });
1735
1846
  import axios4 from "axios";
1736
- import crypto2 from "crypto";
1847
+ import crypto from "crypto";
1737
1848
  var QdrantProvider;
1738
1849
  var init_QdrantProvider = __esm({
1739
1850
  "src/providers/vectordb/QdrantProvider.ts"() {
@@ -1965,7 +2076,7 @@ var init_QdrantProvider = __esm({
1965
2076
  if (typeof id === "number") return id;
1966
2077
  const uuidRegex = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
1967
2078
  if (uuidRegex.test(id)) return id.toLowerCase();
1968
- const hash = crypto2.createHash("md5").update(id).digest("hex");
2079
+ const hash = crypto.createHash("md5").update(id).digest("hex");
1969
2080
  return `${hash.slice(0, 8)}-${hash.slice(8, 12)}-${hash.slice(12, 16)}-${hash.slice(16, 20)}-${hash.slice(20, 32)}`;
1970
2081
  }
1971
2082
  async disconnect() {
@@ -2547,9 +2658,6 @@ var init_SimpleGraphProvider = __esm({
2547
2658
  // src/core/ConfigResolver.ts
2548
2659
  init_templateUtils();
2549
2660
 
2550
- // src/core/LicenseVerifier.ts
2551
- import * as crypto from "crypto";
2552
-
2553
2661
  // src/exceptions/index.ts
2554
2662
  var RetrivoraError = class extends Error {
2555
2663
  constructor(message, code, details) {
@@ -2635,29 +2743,18 @@ function wrapError(err, defaultCode, defaultMessage) {
2635
2743
  }
2636
2744
 
2637
2745
  // src/core/LicenseVerifier.ts
2638
- var LicenseVerifier = class {
2746
+ var _LicenseVerifier = class _LicenseVerifier {
2747
+ // Cache verified license for 5 minutes
2639
2748
  /**
2640
- * Decodes, verifies signature, and checks metadata of a license key.
2749
+ * Validates the license key asynchronously by calling the Retrivora backend.
2641
2750
  *
2642
2751
  * @param licenseKey - Base64url signed JWT license key.
2643
2752
  * @param currentProjectId - Project namespace ID.
2644
- * @param publicKeyOverride - Optional override for unit/integration tests.
2753
+ * @param provider - Optional provider for tier checks.
2645
2754
  */
2646
- static verify(licenseKey, currentProjectId, provider, publicKeyOverride) {
2755
+ static async verifyAsync(licenseKey, currentProjectId, provider) {
2647
2756
  const isProduction = process.env.NODE_ENV === "production";
2648
2757
  const now = Date.now();
2649
- if (licenseKey) {
2650
- const cacheKey = `${licenseKey}:${currentProjectId}:${provider || ""}:${publicKeyOverride || ""}`;
2651
- const cached = this.cache.get(cacheKey);
2652
- if (cached && now - cached.cachedAt < this.CACHE_TTL_MS) {
2653
- const currentTimestampSec = Math.floor(now / 1e3);
2654
- if (cached.payload.expiresAt && currentTimestampSec > cached.payload.expiresAt) {
2655
- this.cache.delete(cacheKey);
2656
- } else {
2657
- return cached.payload;
2658
- }
2659
- }
2660
- }
2661
2758
  if (!licenseKey) {
2662
2759
  if (isProduction) {
2663
2760
  throw new ConfigurationException(
@@ -2674,52 +2771,61 @@ var LicenseVerifier = class {
2674
2771
  tier: "hobby"
2675
2772
  };
2676
2773
  }
2677
- try {
2678
- const sanitizedKey = (licenseKey || "").trim().replace(/^["']|["']$/g, "").trim();
2679
- const rawToken = sanitizedKey.replace(/^rtv_/i, "").trim();
2680
- const parts = rawToken.split(".");
2681
- if (parts.length !== 3) {
2682
- throw new Error("Malformed token structure (expected 3 parts).");
2683
- }
2684
- const [headerB64, payloadB64, signatureB64] = parts;
2685
- const dataToVerify = `${headerB64}.${payloadB64}`;
2686
- const publicKey = publicKeyOverride != null ? publicKeyOverride : this.PUBLIC_KEY;
2687
- const signature = Buffer.from(signatureB64, "base64url");
2688
- const data = Buffer.from(dataToVerify);
2689
- const isValid = crypto.verify(
2690
- "sha256",
2691
- data,
2692
- publicKey,
2693
- signature
2694
- );
2695
- if (!isValid) {
2696
- throw new Error("Signature verification failed.");
2774
+ const cacheKey = `${licenseKey}:${currentProjectId}:${provider || ""}`;
2775
+ const cached = this.cache.get(cacheKey);
2776
+ if (cached && now - cached.cachedAt < this.CACHE_TTL_MS) {
2777
+ const currentTimestampSec = Math.floor(now / 1e3);
2778
+ if (cached.payload.expiresAt && currentTimestampSec > cached.payload.expiresAt) {
2779
+ this.cache.delete(cacheKey);
2780
+ } else {
2781
+ return cached.payload;
2697
2782
  }
2698
- const payload = JSON.parse(
2699
- Buffer.from(payloadB64, "base64url").toString("utf8")
2700
- );
2701
- if (!payload.projectId) {
2702
- throw new Error('License payload is missing "projectId".');
2783
+ }
2784
+ try {
2785
+ let baseUrl = typeof process !== "undefined" && process.env.RETRIVORA_CONTROL_PLANE_URL ? process.env.RETRIVORA_CONTROL_PLANE_URL : "https://retrivora.com";
2786
+ if (typeof process !== "undefined" && process.env.TELEMETRY_URL) {
2787
+ baseUrl = process.env.TELEMETRY_URL.replace(/\/api\/telemetry\/?$/, "");
2703
2788
  }
2704
- const isProjectMatch = payload.projectId === currentProjectId || payload.projectId === `retrivora-${currentProjectId}` || `retrivora-${payload.projectId}` === currentProjectId;
2705
- if (!isProjectMatch) {
2706
- throw new Error(
2707
- `Project ID mismatch. License is bound to project namespace "${payload.projectId}" but configuration has "${currentProjectId}".`
2708
- );
2789
+ const endpoint = `${baseUrl}/api/v1/license/validate`;
2790
+ const response = await fetch(endpoint, {
2791
+ method: "POST",
2792
+ headers: {
2793
+ "Content-Type": "application/json",
2794
+ "x-license-key": licenseKey
2795
+ },
2796
+ body: JSON.stringify({
2797
+ licenseKey,
2798
+ projectId: currentProjectId,
2799
+ provider
2800
+ })
2801
+ });
2802
+ if (!response.ok) {
2803
+ let errMessage = `HTTP ${response.status}`;
2804
+ try {
2805
+ const body = await response.json();
2806
+ if (body.message) errMessage = body.message;
2807
+ } catch (e) {
2808
+ }
2809
+ throw new Error(errMessage);
2709
2810
  }
2710
- if (!payload.expiresAt) {
2711
- throw new Error('License payload is missing expiration ("expiresAt").');
2811
+ const data = await response.json();
2812
+ if (!data.valid) {
2813
+ throw new Error(data.message || "License validation failed by server.");
2712
2814
  }
2713
- const currentTimestampSec = Math.floor(Date.now() / 1e3);
2714
- if (currentTimestampSec > payload.expiresAt) {
2715
- throw new Error(
2716
- `License key has expired. Expiration: ${new Date(
2717
- payload.expiresAt * 1e3
2718
- ).toDateString()}`
2719
- );
2815
+ let expiresAtNum = Math.floor(Date.now() / 1e3) + 100 * 365 * 24 * 60 * 60;
2816
+ if (data.expiresAt) {
2817
+ expiresAtNum = Math.floor(new Date(data.expiresAt).getTime() / 1e3);
2720
2818
  }
2819
+ const tier = _LicenseVerifier.extractTier(licenseKey);
2820
+ const payload = {
2821
+ projectId: currentProjectId,
2822
+ expiresAt: expiresAtNum,
2823
+ tier,
2824
+ licenseStatus: data.licenseStatus,
2825
+ minimumSupportedVersion: data.minimumSupportedVersion,
2826
+ forceUpgrade: data.forceUpgrade
2827
+ };
2721
2828
  if (isProduction && provider) {
2722
- const tier = (payload.tier || "").toLowerCase();
2723
2829
  const normalizedProvider = provider.toLowerCase();
2724
2830
  if (tier === "hobby") {
2725
2831
  const allowedHobby = ["postgresql", "pgvector", "supabase"];
@@ -2747,15 +2853,12 @@ var LicenseVerifier = class {
2747
2853
  }
2748
2854
  }
2749
2855
  }
2750
- if (licenseKey) {
2751
- const cacheKey = `${licenseKey}:${currentProjectId}:${provider || ""}:${publicKeyOverride || ""}`;
2752
- this.cache.set(cacheKey, { payload, cachedAt: now });
2753
- }
2856
+ this.cache.set(cacheKey, { payload, cachedAt: now });
2754
2857
  return payload;
2755
2858
  } catch (err) {
2756
2859
  const message = err instanceof Error ? err.message : String(err);
2757
2860
  throw new ConfigurationException(
2758
- `[Retrivora SDK] License key validation failed: ${message}`
2861
+ `[Retrivora SDK] License key validation failed via API: ${message}`
2759
2862
  );
2760
2863
  }
2761
2864
  }
@@ -2824,23 +2927,25 @@ var LicenseVerifier = class {
2824
2927
  }
2825
2928
  }
2826
2929
  }
2930
+ static extractTier(licenseKey) {
2931
+ if (!licenseKey) return "hobby";
2932
+ try {
2933
+ const sanitizedKey = licenseKey.trim().replace(/^["']|["']$/g, "").trim();
2934
+ const rawToken = sanitizedKey.replace(/^rtv_/i, "").trim();
2935
+ const parts = rawToken.split(".");
2936
+ if (parts.length === 3) {
2937
+ const decodedPayload = JSON.parse(Buffer.from(parts[1], "base64url").toString("utf8"));
2938
+ if (decodedPayload.tier) return decodedPayload.tier;
2939
+ }
2940
+ } catch (e) {
2941
+ }
2942
+ return "hobby";
2943
+ }
2827
2944
  };
2828
- // A simple in-memory cache to save CPU overhead of cryptographic signature checks.
2829
- LicenseVerifier.cache = /* @__PURE__ */ new Map();
2830
- LicenseVerifier.CACHE_TTL_MS = 60 * 1e3;
2831
- // Cache verified license for 60 seconds
2832
- // Retrivora's Public Key used to verify the license key signature.
2833
- // In production, this matches the private key held by Retrivora SaaS.
2834
- // Rotate this key only when the signing private key is replaced.
2835
- LicenseVerifier.PUBLIC_KEY = `-----BEGIN PUBLIC KEY-----
2836
- MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAyKvvOSYdCimG3b236ebV
2837
- jpG88xQiU8dSiaMahtBJDf4w0AewRj7hMNgmeZ1wyTOj8kVgeGBOolp1Z0QmTr6O
2838
- Tj4EDQ/zjsg12If7hSf3NiwLHCYmMLslyK0aaP6PQoTrYkBv3GNdkMecrIjKCijb
2839
- 6VvDLLF3X696melTVM0z/d2e50BW2AlRw/rf1EqYi10d0BcPo5zje0XETr/WGmqu
2840
- sDiXtsP5MlwkL9X7RQY2uovRa+l/vOAqAfdmJ+OzXuk5P7mDUPb+gCtKnoDbb1tr
2841
- 6UAu733dkUnetAcMqyT3fNPBLO66DCc6m9rGCYYAaG7piMEDwG0/ZySZBFbgllJc
2842
- 6QIDAQAB
2843
- -----END PUBLIC KEY-----`;
2945
+ // In-memory cache to save network overhead on hot paths.
2946
+ _LicenseVerifier.cache = /* @__PURE__ */ new Map();
2947
+ _LicenseVerifier.CACHE_TTL_MS = 5 * 60 * 1e3;
2948
+ var LicenseVerifier = _LicenseVerifier;
2844
2949
 
2845
2950
  // src/config/constants.ts
2846
2951
  var VECTOR_DB_PROVIDERS = [
@@ -2928,7 +3033,7 @@ function getRagConfig(baseConfig, env = process.env) {
2928
3033
  return getEnvConfig(env, baseConfig);
2929
3034
  }
2930
3035
  function getEnvConfig(env = process.env, base) {
2931
- var _a3, _b, _c, _d, _e, _f, _g2, _h, _i, _j, _k, _l, _m, _n, _o, _p, _q, _r, _s, _t, _u, _v, _w, _x, _y, _z, _A, _B, _C, _D, _E, _F, _G, _H, _I, _J, _K, _L, _M, _N, _O, _P, _Q, _R, _S, _T, _U, _V, _W, _X, _Y, _Z, __, _$, _aa, _ba, _ca, _da, _ea, _fa, _ga, _ha, _ia, _ja, _ka, _la, _ma, _na, _oa, _pa, _qa, _ra, _sa, _ta, _ua, _va, _wa, _xa, _ya, _za, _Aa, _Ba, _Ca, _Da, _Ea, _Fa, _Ga, _Ha, _Ia, _Ja, _Ka, _La, _Ma, _Na, _Oa, _Pa, _Qa, _Ra, _Sa, _Ta, _Ua, _Va, _Wa, _Xa, _Ya, _Za, __a, _$a, _ab, _bb, _cb, _db, _eb, _fb, _gb, _hb, _ib, _jb, _kb, _lb, _mb, _nb, _ob, _pb, _qb, _rb, _sb, _tb, _ub, _vb, _wb, _xb, _yb, _zb, _Ab, _Bb, _Cb, _Db, _Eb, _Fb, _Gb, _Hb;
3036
+ var _a3, _b, _c, _d, _e, _f, _g2, _h, _i, _j, _k, _l, _m, _n, _o, _p, _q, _r, _s, _t, _u, _v, _w, _x, _y, _z, _A, _B, _C, _D, _E, _F, _G, _H, _I, _J, _K, _L, _M, _N, _O, _P, _Q, _R, _S, _T, _U, _V, _W, _X, _Y, _Z, __, _$, _aa, _ba, _ca, _da, _ea, _fa, _ga, _ha, _ia, _ja, _ka, _la, _ma, _na, _oa, _pa, _qa, _ra, _sa, _ta, _ua, _va, _wa, _xa, _ya, _za, _Aa, _Ba, _Ca, _Da, _Ea, _Fa, _Ga, _Ha, _Ia, _Ja, _Ka, _La, _Ma, _Na, _Oa, _Pa, _Qa, _Ra, _Sa, _Ta, _Ua, _Va, _Wa, _Xa, _Ya, _Za, __a, _$a, _ab, _bb, _cb, _db, _eb, _fb, _gb, _hb, _ib, _jb, _kb, _lb, _mb, _nb, _ob, _pb, _qb, _rb, _sb, _tb, _ub, _vb, _wb, _xb, _yb, _zb, _Ab, _Bb, _Cb, _Db, _Eb, _Fb, _Gb, _Hb, _Ib;
2932
3037
  const licenseKey = (_d = (_c = (_b = (_a3 = readString(env, "RAG_LICENSE_KEY")) != null ? _a3 : readString(env, "RETRIVORA_LICENSE_KEY")) != null ? _b : readString(env, "NEXT_PUBLIC_RETRIVORA_LICENSE_KEY")) != null ? _c : readString(env, "LICENSE_KEY")) != null ? _d : base == null ? void 0 : base.licenseKey;
2933
3038
  const jwtProjectId = (() => {
2934
3039
  if (!licenseKey) return void 0;
@@ -3013,8 +3118,7 @@ function getEnvConfig(env = process.env, base) {
3013
3118
  const isFreeTier2 = (() => {
3014
3119
  if (!licenseKey) return true;
3015
3120
  try {
3016
- const payload = LicenseVerifier.verify(licenseKey, projectId);
3017
- const tier = (payload.tier || "").toLowerCase();
3121
+ const tier = LicenseVerifier.extractTier(licenseKey).toLowerCase();
3018
3122
  return tier === "free_trial" || tier === "free_tier" || tier === "free" || tier === "hobby";
3019
3123
  } catch (e) {
3020
3124
  return true;
@@ -3022,14 +3126,15 @@ function getEnvConfig(env = process.env, base) {
3022
3126
  })();
3023
3127
  const tierBasedLLMModel = isFreeTier2 ? "llama-3.1-8b-instant" : "llama-3.3-70b-versatile";
3024
3128
  const tierBasedEmbeddingModel = isFreeTier2 ? "text-embedding-004" : "text-embedding-004";
3025
- const defaultGatewayUrl = "https://llm.retrivora.com/api/v1";
3129
+ const controlPlaneUrl = (_qa = readString(env, "RETRIVORA_CONTROL_PLANE_URL")) != null ? _qa : readString(env, "NEXT_PUBLIC_RETRIVORA_CONTROL_PLANE_URL");
3130
+ const defaultGatewayUrl = controlPlaneUrl ? `${controlPlaneUrl.replace(/\/$/, "")}/api/v1` : "https://llm.retrivora.com/api/v1";
3026
3131
  const rt = _runtimeConfig;
3027
3132
  const defaultLlmProvider = "universal_rest";
3028
- const llmProvider = (_sa = (_ra = readEnum(env, "LLM_PROVIDER", defaultLlmProvider, LLM_PROVIDERS)) != null ? _ra : (_qa = base == null ? void 0 : base.llm) == null ? void 0 : _qa.provider) != null ? _sa : defaultLlmProvider;
3029
- const llmBaseUrl = (_xa = (_wa = (_va = (_ta = readString(env, "LITELLM_BASE_URL")) != null ? _ta : readString(env, "LLM_BASE_URL")) != null ? _va : (_ua = base == null ? void 0 : base.llm) == null ? void 0 : _ua.baseUrl) != null ? _wa : rt == null ? void 0 : rt.llmBaseUrl) != null ? _xa : defaultGatewayUrl;
3030
- const llmModel = (_Ba = (_Aa = (_za = readString(env, "LLM_MODEL")) != null ? _za : (_ya = base == null ? void 0 : base.llm) == null ? void 0 : _ya.model) != null ? _Aa : rt == null ? void 0 : rt.llmModel) != null ? _Ba : tierBasedLLMModel;
3031
- const llmApiKey = (_Fa = (_Ea = (_Ca = readString(env, "LITELLM_MASTER_KEY")) != null ? _Ca : rt == null ? void 0 : rt.litellmApiKey) != null ? _Ea : (_Da = base == null ? void 0 : base.llm) == null ? void 0 : _Da.apiKey) != null ? _Fa : licenseKey;
3032
- const llmProfile = (_Ja = (_Ia = readString(env, "LLM_UNIVERSAL_PROFILE")) != null ? _Ia : (_Ha = (_Ga = base == null ? void 0 : base.llm) == null ? void 0 : _Ga.options) == null ? void 0 : _Ha.profile) != null ? _Ja : "litellm";
3133
+ const llmProvider = (_ta = (_sa = readEnum(env, "LLM_PROVIDER", defaultLlmProvider, LLM_PROVIDERS)) != null ? _sa : (_ra = base == null ? void 0 : base.llm) == null ? void 0 : _ra.provider) != null ? _ta : defaultLlmProvider;
3134
+ const llmBaseUrl = (_ya = (_xa = (_wa = (_ua = readString(env, "LITELLM_BASE_URL")) != null ? _ua : readString(env, "LLM_BASE_URL")) != null ? _wa : (_va = base == null ? void 0 : base.llm) == null ? void 0 : _va.baseUrl) != null ? _xa : rt == null ? void 0 : rt.llmBaseUrl) != null ? _ya : defaultGatewayUrl;
3135
+ const llmModel = (_Ca = (_Ba = (_Aa = readString(env, "LLM_MODEL")) != null ? _Aa : (_za = base == null ? void 0 : base.llm) == null ? void 0 : _za.model) != null ? _Ba : rt == null ? void 0 : rt.llmModel) != null ? _Ca : tierBasedLLMModel;
3136
+ const llmApiKey = (_Ga = (_Fa = (_Da = readString(env, "LITELLM_MASTER_KEY")) != null ? _Da : rt == null ? void 0 : rt.litellmApiKey) != null ? _Fa : (_Ea = base == null ? void 0 : base.llm) == null ? void 0 : _Ea.apiKey) != null ? _Ga : licenseKey;
3137
+ const llmProfile = (_Ka = (_Ja = readString(env, "LLM_UNIVERSAL_PROFILE")) != null ? _Ja : (_Ia = (_Ha = base == null ? void 0 : base.llm) == null ? void 0 : _Ha.options) == null ? void 0 : _Ia.profile) != null ? _Ka : "litellm";
3033
3138
  console.log("[serverConfig] \u{1F527} LLM Configuration:", {
3034
3139
  baseUrl: llmBaseUrl,
3035
3140
  model: llmModel,
@@ -3038,17 +3143,24 @@ function getEnvConfig(env = process.env, base) {
3038
3143
  source: (rt == null ? void 0 : rt.llmModel) ? "runtime-injected" : "env/fallback"
3039
3144
  });
3040
3145
  const defaultEmbeddingProvider = "universal_rest";
3041
- const embeddingProvider = (_Ma = (_La = readEnum(env, "EMBEDDING_PROVIDER", defaultEmbeddingProvider, EMBEDDING_PROVIDERS)) != null ? _La : (_Ka = base == null ? void 0 : base.embedding) == null ? void 0 : _Ka.provider) != null ? _Ma : defaultEmbeddingProvider;
3042
- const embeddingBaseUrl = (_Ta = (_Sa = (_Ra = (_Qa = (_Oa = (_Na = readString(env, "LITELLM_BASE_URL")) != null ? _Na : readString(env, "EMBEDDING_BASE_URL")) != null ? _Oa : readString(env, "LLM_BASE_URL")) != null ? _Qa : (_Pa = base == null ? void 0 : base.embedding) == null ? void 0 : _Pa.baseUrl) != null ? _Ra : rt == null ? void 0 : rt.embeddingBaseUrl) != null ? _Sa : rt == null ? void 0 : rt.llmBaseUrl) != null ? _Ta : defaultGatewayUrl;
3043
- const embeddingModel = (_Xa = (_Wa = (_Va = readString(env, "EMBEDDING_MODEL")) != null ? _Va : (_Ua = base == null ? void 0 : base.embedding) == null ? void 0 : _Ua.model) != null ? _Wa : rt == null ? void 0 : rt.embeddingModel) != null ? _Xa : tierBasedEmbeddingModel;
3044
- const embeddingApiKey = (_$a = (__a = (_Ya = readString(env, "LITELLM_MASTER_KEY")) != null ? _Ya : rt == null ? void 0 : rt.litellmApiKey) != null ? __a : (_Za = base == null ? void 0 : base.embedding) == null ? void 0 : _Za.apiKey) != null ? _$a : licenseKey;
3045
- const embeddingProfile = (_db = (_cb = readString(env, "EMBEDDING_UNIVERSAL_PROFILE")) != null ? _cb : (_bb = (_ab = base == null ? void 0 : base.embedding) == null ? void 0 : _ab.options) == null ? void 0 : _bb.profile) != null ? _db : "litellm";
3146
+ const embeddingProvider = (_Na = (_Ma = readEnum(env, "EMBEDDING_PROVIDER", defaultEmbeddingProvider, EMBEDDING_PROVIDERS)) != null ? _Ma : (_La = base == null ? void 0 : base.embedding) == null ? void 0 : _La.provider) != null ? _Na : defaultEmbeddingProvider;
3147
+ const embeddingBaseUrl = (_Ua = (_Ta = (_Sa = (_Ra = (_Pa = (_Oa = readString(env, "LITELLM_BASE_URL")) != null ? _Oa : readString(env, "EMBEDDING_BASE_URL")) != null ? _Pa : readString(env, "LLM_BASE_URL")) != null ? _Ra : (_Qa = base == null ? void 0 : base.embedding) == null ? void 0 : _Qa.baseUrl) != null ? _Sa : rt == null ? void 0 : rt.embeddingBaseUrl) != null ? _Ta : rt == null ? void 0 : rt.llmBaseUrl) != null ? _Ua : defaultGatewayUrl;
3148
+ const embeddingModel = (_Ya = (_Xa = (_Wa = readString(env, "EMBEDDING_MODEL")) != null ? _Wa : (_Va = base == null ? void 0 : base.embedding) == null ? void 0 : _Va.model) != null ? _Xa : rt == null ? void 0 : rt.embeddingModel) != null ? _Ya : tierBasedEmbeddingModel;
3149
+ const embeddingApiKey = (_ab = (_$a = (_Za = readString(env, "LITELLM_MASTER_KEY")) != null ? _Za : rt == null ? void 0 : rt.litellmApiKey) != null ? _$a : (__a = base == null ? void 0 : base.embedding) == null ? void 0 : __a.apiKey) != null ? _ab : licenseKey;
3150
+ const embeddingProfile = (_eb = (_db = readString(env, "EMBEDDING_UNIVERSAL_PROFILE")) != null ? _db : (_cb = (_bb = base == null ? void 0 : base.embedding) == null ? void 0 : _bb.options) == null ? void 0 : _cb.profile) != null ? _eb : "litellm";
3151
+ console.log("[serverConfig] \u{1F527} Embedding Configuration:", {
3152
+ baseUrl: embeddingBaseUrl,
3153
+ model: embeddingModel,
3154
+ provider: embeddingProvider,
3155
+ hasApiKey: !!embeddingApiKey,
3156
+ source: (rt == null ? void 0 : rt.embeddingModel) ? "runtime-injected" : "env/fallback"
3157
+ });
3046
3158
  return __spreadProps(__spreadValues({
3047
3159
  projectId,
3048
3160
  licenseKey,
3049
3161
  vectorDb: {
3050
3162
  provider: vectorProvider,
3051
- indexName: (_fb = (_eb = readString(env, "VECTOR_DB_INDEX")) != null ? _eb : vectorDbOptions.indexName) != null ? _fb : "rag-index",
3163
+ indexName: (_gb = (_fb = readString(env, "VECTOR_DB_INDEX")) != null ? _fb : vectorDbOptions.indexName) != null ? _gb : "rag-index",
3052
3164
  options: vectorDbOptions
3053
3165
  },
3054
3166
  llm: {
@@ -3078,30 +3190,30 @@ function getEnvConfig(env = process.env, base) {
3078
3190
  }
3079
3191
  },
3080
3192
  ui: {
3081
- title: (_hb = (_gb = readString(env, "NEXT_PUBLIC_UI_TITLE")) != null ? _gb : readString(env, "UI_TITLE")) != null ? _hb : "AI Assistant",
3082
- subtitle: (_jb = (_ib = readString(env, "NEXT_PUBLIC_UI_SUBTITLE")) != null ? _ib : readString(env, "UI_SUBTITLE")) != null ? _jb : "Powered by RAG",
3083
- primaryColor: (_lb = (_kb = readString(env, "NEXT_PUBLIC_PRIMARY_COLOR")) != null ? _kb : readString(env, "UI_PRIMARY_COLOR")) != null ? _lb : "#10b981",
3084
- accentColor: (_nb = (_mb = readString(env, "NEXT_PUBLIC_ACCENT_COLOR")) != null ? _mb : readString(env, "UI_ACCENT_COLOR")) != null ? _nb : "#3b82f6",
3085
- logoUrl: (_ob = readString(env, "NEXT_PUBLIC_LOGO_URL")) != null ? _ob : readString(env, "UI_LOGO_URL"),
3086
- placeholder: (_qb = (_pb = readString(env, "NEXT_PUBLIC_PLACEHOLDER")) != null ? _pb : readString(env, "UI_PLACEHOLDER")) != null ? _qb : "Ask me anything\u2026",
3087
- showSources: ((_sb = (_rb = readString(env, "NEXT_PUBLIC_SHOW_SOURCES")) != null ? _rb : readString(env, "UI_SHOW_SOURCES")) != null ? _sb : "true") !== "false",
3088
- welcomeMessage: (_ub = (_tb = readString(env, "NEXT_PUBLIC_WELCOME_MESSAGE")) != null ? _tb : readString(env, "UI_WELCOME_MESSAGE")) != null ? _ub : "Hello! I'm your AI assistant. Ask me anything about your documents.",
3089
- visualStyle: (_wb = (_vb = readString(env, "NEXT_PUBLIC_UI_VISUAL_STYLE")) != null ? _vb : readString(env, "UI_VISUAL_STYLE")) != null ? _wb : "glass",
3090
- borderRadius: (_yb = (_xb = readString(env, "NEXT_PUBLIC_UI_BORDER_RADIUS")) != null ? _xb : readString(env, "UI_BORDER_RADIUS")) != null ? _yb : "xl",
3091
- allowUpload: ((_Ab = (_zb = readString(env, "NEXT_PUBLIC_ALLOW_UPLOAD")) != null ? _zb : readString(env, "UI_ALLOW_UPLOAD")) != null ? _Ab : "false") === "true"
3193
+ title: (_ib = (_hb = readString(env, "NEXT_PUBLIC_UI_TITLE")) != null ? _hb : readString(env, "UI_TITLE")) != null ? _ib : "AI Assistant",
3194
+ subtitle: (_kb = (_jb = readString(env, "NEXT_PUBLIC_UI_SUBTITLE")) != null ? _jb : readString(env, "UI_SUBTITLE")) != null ? _kb : "Powered by RAG",
3195
+ primaryColor: (_mb = (_lb = readString(env, "NEXT_PUBLIC_PRIMARY_COLOR")) != null ? _lb : readString(env, "UI_PRIMARY_COLOR")) != null ? _mb : "#10b981",
3196
+ accentColor: (_ob = (_nb = readString(env, "NEXT_PUBLIC_ACCENT_COLOR")) != null ? _nb : readString(env, "UI_ACCENT_COLOR")) != null ? _ob : "#3b82f6",
3197
+ logoUrl: (_pb = readString(env, "NEXT_PUBLIC_LOGO_URL")) != null ? _pb : readString(env, "UI_LOGO_URL"),
3198
+ placeholder: (_rb = (_qb = readString(env, "NEXT_PUBLIC_PLACEHOLDER")) != null ? _qb : readString(env, "UI_PLACEHOLDER")) != null ? _rb : "Ask me anything\u2026",
3199
+ showSources: ((_tb = (_sb = readString(env, "NEXT_PUBLIC_SHOW_SOURCES")) != null ? _sb : readString(env, "UI_SHOW_SOURCES")) != null ? _tb : "true") !== "false",
3200
+ welcomeMessage: (_vb = (_ub = readString(env, "NEXT_PUBLIC_WELCOME_MESSAGE")) != null ? _ub : readString(env, "UI_WELCOME_MESSAGE")) != null ? _vb : "Hello! I'm your AI assistant. Ask me anything about your documents.",
3201
+ visualStyle: (_xb = (_wb = readString(env, "NEXT_PUBLIC_UI_VISUAL_STYLE")) != null ? _wb : readString(env, "UI_VISUAL_STYLE")) != null ? _xb : "glass",
3202
+ borderRadius: (_zb = (_yb = readString(env, "NEXT_PUBLIC_UI_BORDER_RADIUS")) != null ? _yb : readString(env, "UI_BORDER_RADIUS")) != null ? _zb : "xl",
3203
+ allowUpload: ((_Bb = (_Ab = readString(env, "NEXT_PUBLIC_ALLOW_UPLOAD")) != null ? _Ab : readString(env, "UI_ALLOW_UPLOAD")) != null ? _Bb : "false") === "true"
3092
3204
  },
3093
3205
  rag: {
3094
3206
  topK: readNumber(env, "RAG_TOP_K", 5),
3095
3207
  scoreThreshold: readNumber(env, "RAG_SCORE_THRESHOLD", 0),
3096
3208
  chunkSize: readNumber(env, "RAG_CHUNK_SIZE", 1e3),
3097
3209
  chunkOverlap: readNumber(env, "RAG_CHUNK_OVERLAP", 200),
3098
- filterableFields: (_Bb = readString(env, "RAG_FILTERABLE_FIELDS")) == null ? void 0 : _Bb.split(",").map((f) => f.trim()),
3210
+ filterableFields: (_Cb = readString(env, "RAG_FILTERABLE_FIELDS")) == null ? void 0 : _Cb.split(",").map((f) => f.trim()),
3099
3211
  // Query pipeline toggles — read from .env.local
3100
3212
  useQueryTransformation: readString(env, "RAG_USE_QUERY_TRANSFORMATION") === "true",
3101
3213
  useReranking: readString(env, "RAG_USE_RERANKING") === "true",
3102
3214
  useGraphRetrieval: readString(env, "RAG_USE_GRAPH_RETRIEVAL") === "true",
3103
- architecture: (_Cb = readString(env, "RAG_ARCHITECTURE")) != null ? _Cb : "simple",
3104
- chunkingStrategy: (_Db = readString(env, "RAG_CHUNKING_STRATEGY")) != null ? _Db : "recursive",
3215
+ architecture: (_Db = readString(env, "RAG_ARCHITECTURE")) != null ? _Db : "simple",
3216
+ chunkingStrategy: (_Eb = readString(env, "RAG_CHUNKING_STRATEGY")) != null ? _Eb : "recursive",
3105
3217
  uiMapping: (() => {
3106
3218
  const raw = readString(env, "RAG_UI_MAPPING");
3107
3219
  if (!raw) return void 0;
@@ -3114,7 +3226,7 @@ function getEnvConfig(env = process.env, base) {
3114
3226
  },
3115
3227
  telemetry: {
3116
3228
  enabled: telemetryEnabled,
3117
- url: (_Hb = (_Gb = (_Eb = readString(env, "TELEMETRY_URL")) != null ? _Eb : readString(env, "NEXT_PUBLIC_TELEMETRY_URL")) != null ? _Gb : (_Fb = base == null ? void 0 : base.telemetry) == null ? void 0 : _Fb.url) != null ? _Hb : "https://www.retrivora.com/api/telemetry"
3229
+ url: (_Ib = (_Hb = (_Fb = readString(env, "TELEMETRY_URL")) != null ? _Fb : readString(env, "NEXT_PUBLIC_TELEMETRY_URL")) != null ? _Hb : (_Gb = base == null ? void 0 : base.telemetry) == null ? void 0 : _Gb.url) != null ? _Ib : "https://www.retrivora.com/api/telemetry"
3118
3230
  }
3119
3231
  }, readString(env, "GRAPH_DB_PROVIDER") ? {
3120
3232
  graphDb: {
@@ -4464,6 +4576,12 @@ var UniversalLLMAdapter = class {
4464
4576
  this.resolvedHeaders = __spreadValues(__spreadValues({
4465
4577
  "Content-Type": "application/json"
4466
4578
  }, config.apiKey ? { Authorization: `Bearer ${config.apiKey}` } : {}), this.opts.headers || {});
4579
+ console.log("[UniversalLLMAdapter] Initialized with:", {
4580
+ model: this.model,
4581
+ baseUrl: this.baseUrl,
4582
+ hasApiKey: !!this.apiKey,
4583
+ apiKeyPrefix: this.apiKey ? `${this.apiKey.slice(0, 12)}...` : void 0
4584
+ });
4467
4585
  this.http = axios2.create({
4468
4586
  baseURL: this.baseUrl,
4469
4587
  headers: this.resolvedHeaders,
@@ -4676,14 +4794,21 @@ ${context != null ? context : "None"}` },
4676
4794
  });
4677
4795
  }
4678
4796
  async embed(text) {
4679
- var _a3, _b, _c, _d, _e, _f, _g2;
4797
+ var _a3, _b, _c, _d, _e, _f, _g2, _h;
4680
4798
  const path2 = (_a3 = this.opts.embedPath) != null ? _a3 : "/embeddings";
4681
4799
  const payload = this.opts.embedPayloadTemplate ? buildPayload(this.opts.embedPayloadTemplate, { input: text, model: this.model }) : { input: text, model: this.model };
4682
4800
  try {
4801
+ console.log(`[UniversalLLMAdapter] Posting to embedding endpoint: ${this.baseUrl}${path2}`, {
4802
+ model: this.model,
4803
+ inputLength: typeof text === "string" ? text.length : "unknown"
4804
+ });
4683
4805
  const { data } = await this.http.post(path2, payload);
4684
4806
  const extractPath = (_b = this.opts.embedExtractPath) != null ? _b : "data[0].embedding";
4685
4807
  const vector = resolvePath(data, extractPath);
4686
- if (Array.isArray(vector)) return vector;
4808
+ if (Array.isArray(vector)) {
4809
+ console.log(`[UniversalLLMAdapter] Embedding HTTP request successful. Vector size: ${vector.length}`);
4810
+ return vector;
4811
+ }
4687
4812
  console.warn(
4688
4813
  `[UniversalLLMAdapter] Embedding API returned unexpected format for path '${extractPath}'. Response:`,
4689
4814
  data
@@ -4691,14 +4816,14 @@ ${context != null ? context : "None"}` },
4691
4816
  } catch (err) {
4692
4817
  console.warn(
4693
4818
  `[UniversalLLMAdapter] HTTP embedding request failed: ${(err == null ? void 0 : err.message) || err}`,
4694
- { path: path2, model: this.model }
4819
+ { path: path2, model: this.model, response: (_c = err == null ? void 0 : err.response) == null ? void 0 : _c.data }
4695
4820
  );
4696
4821
  const _g3 = globalThis;
4697
4822
  const dispatchEmbed = _g3.__retrivoraDispatchEmbedding;
4698
4823
  if (typeof dispatchEmbed === "function") {
4699
4824
  try {
4700
4825
  const res = await dispatchEmbed({ input: text, model: this.model }, this.apiKey);
4701
- if ((_d = (_c = res == null ? void 0 : res.data) == null ? void 0 : _c[0]) == null ? void 0 : _d.embedding) {
4826
+ if ((_e = (_d = res == null ? void 0 : res.data) == null ? void 0 : _d[0]) == null ? void 0 : _e.embedding) {
4702
4827
  return res.data[0].embedding;
4703
4828
  }
4704
4829
  } catch (dispatchErr) {
@@ -4707,10 +4832,12 @@ ${context != null ? context : "None"}` },
4707
4832
  }
4708
4833
  }
4709
4834
  try {
4835
+ console.log(`[UniversalLLMAdapter] Retrying embedding request to: ${this.baseUrl}${path2}`);
4710
4836
  const { data } = await this.http.post(path2, payload);
4711
- const extractPath = (_e = this.opts.embedExtractPath) != null ? _e : "data[0].embedding";
4837
+ const extractPath = (_f = this.opts.embedExtractPath) != null ? _f : "data[0].embedding";
4712
4838
  const vector = resolvePath(data, extractPath);
4713
4839
  if (Array.isArray(vector)) {
4840
+ console.log(`[UniversalLLMAdapter] Retry embedding HTTP request successful. Vector size: ${vector.length}`);
4714
4841
  return vector;
4715
4842
  }
4716
4843
  console.error(
@@ -4723,7 +4850,7 @@ ${context != null ? context : "None"}` },
4723
4850
  } catch (err) {
4724
4851
  console.error(
4725
4852
  `[UniversalLLMAdapter] Both embedding attempts failed. Path: ${path2}, Model: ${this.model}`,
4726
- { error: err == null ? void 0 : err.message, statusCode: (_f = err == null ? void 0 : err.response) == null ? void 0 : _f.status, response: (_g2 = err == null ? void 0 : err.response) == null ? void 0 : _g2.data }
4853
+ { error: err == null ? void 0 : err.message, statusCode: (_g2 = err == null ? void 0 : err.response) == null ? void 0 : _g2.status, response: (_h = err == null ? void 0 : err.response) == null ? void 0 : _h.data }
4727
4854
  );
4728
4855
  throw new Error(
4729
4856
  `[UniversalLLMAdapter] Failed to generate embedding after 2 attempts: ${(err == null ? void 0 : err.message) || err}`
@@ -9859,7 +9986,7 @@ var Retrivora = class {
9859
9986
  var _a3;
9860
9987
  try {
9861
9988
  await ConfigValidator.validateAndThrow(this.config);
9862
- LicenseVerifier.verify(
9989
+ await LicenseVerifier.verifyAsync(
9863
9990
  this.config.licenseKey,
9864
9991
  this.config.projectId,
9865
9992
  (_a3 = this.config.vectorDb) == null ? void 0 : _a3.provider
@@ -10225,7 +10352,7 @@ var VectorPlugin = class {
10225
10352
  this.validationPromise = (async () => {
10226
10353
  var _a3;
10227
10354
  await ConfigValidator.validateAndThrow(resolvedConfig);
10228
- LicenseVerifier.verify(
10355
+ await LicenseVerifier.verifyAsync(
10229
10356
  resolvedConfig.licenseKey,
10230
10357
  resolvedConfig.projectId,
10231
10358
  (_a3 = resolvedConfig.vectorDb) == null ? void 0 : _a3.provider
@@ -10719,7 +10846,7 @@ var DatabaseStorage = class {
10719
10846
  * In non-production (development / test) environments this is a complete no-op —
10720
10847
  * all History and Feedback features are freely accessible for local development.
10721
10848
  */
10722
- checkPremiumSubscription() {
10849
+ async checkPremiumSubscription() {
10723
10850
  if (process.env.NODE_ENV !== "production") {
10724
10851
  return;
10725
10852
  }
@@ -10729,7 +10856,7 @@ var DatabaseStorage = class {
10729
10856
  );
10730
10857
  }
10731
10858
  try {
10732
- const payload = LicenseVerifier.verify(this.config.licenseKey, this.config.projectId);
10859
+ const payload = await LicenseVerifier.verifyAsync(this.config.licenseKey, this.config.projectId);
10733
10860
  const tier = (payload.tier || "").toLowerCase();
10734
10861
  if (tier !== "premium" && tier !== "enterprise" && tier !== "growth" && tier !== "pro" && tier !== "developer_pro" && tier !== "free_trial" && tier !== "free_tier" && tier !== "free" && tier !== "hobby") {
10735
10862
  throw new Error(
@@ -10742,16 +10869,16 @@ var DatabaseStorage = class {
10742
10869
  );
10743
10870
  }
10744
10871
  }
10745
- checkHistoryEnabled() {
10872
+ async checkHistoryEnabled() {
10746
10873
  var _a3, _b;
10747
- this.checkPremiumSubscription();
10874
+ await this.checkPremiumSubscription();
10748
10875
  if (((_b = (_a3 = this.config.rag) == null ? void 0 : _a3.history) == null ? void 0 : _b.enabled) === false) {
10749
10876
  throw new Error("[Retrivora SDK] Chat History is disabled in RagConfig.");
10750
10877
  }
10751
10878
  }
10752
- checkFeedbackEnabled() {
10879
+ async checkFeedbackEnabled() {
10753
10880
  var _a3, _b;
10754
- this.checkPremiumSubscription();
10881
+ await this.checkPremiumSubscription();
10755
10882
  if (((_b = (_a3 = this.config.rag) == null ? void 0 : _a3.feedback) == null ? void 0 : _b.enabled) === false) {
10756
10883
  throw new Error("[Retrivora SDK] User Feedback is disabled in RagConfig.");
10757
10884
  }
@@ -10857,7 +10984,7 @@ var DatabaseStorage = class {
10857
10984
  }
10858
10985
  // ─── Message History Operations ──────────────────────────────────────────
10859
10986
  async saveMessage(sessionId, message) {
10860
- this.checkHistoryEnabled();
10987
+ await this.checkHistoryEnabled();
10861
10988
  const createdAt = (/* @__PURE__ */ new Date()).toISOString();
10862
10989
  const msgId = message.id || `msg_${Date.now()}_${Math.random().toString(36).slice(2, 6)}`;
10863
10990
  if (this.provider === "postgresql" || this.provider === "pgvector") {
@@ -10920,7 +11047,7 @@ var DatabaseStorage = class {
10920
11047
  }
10921
11048
  }
10922
11049
  async getHistory(sessionId, projectIds) {
10923
- this.checkHistoryEnabled();
11050
+ await this.checkHistoryEnabled();
10924
11051
  if (projectIds && projectIds.length > 0 && !this.sessionInScope(sessionId, projectIds)) {
10925
11052
  return [];
10926
11053
  }
@@ -10954,7 +11081,7 @@ var DatabaseStorage = class {
10954
11081
  }
10955
11082
  }
10956
11083
  async clearHistory(sessionId, projectIds) {
10957
- this.checkHistoryEnabled();
11084
+ await this.checkHistoryEnabled();
10958
11085
  if (projectIds && projectIds.length > 0 && !this.sessionInScope(sessionId, projectIds)) {
10959
11086
  return;
10960
11087
  }
@@ -10990,7 +11117,7 @@ var DatabaseStorage = class {
10990
11117
  );
10991
11118
  }
10992
11119
  async listSessions(projectIds) {
10993
- this.checkHistoryEnabled();
11120
+ await this.checkHistoryEnabled();
10994
11121
  let raw = [];
10995
11122
  if (this.provider === "postgresql" || this.provider === "pgvector") {
10996
11123
  const pool = await this.getPGPool();
@@ -11009,7 +11136,7 @@ var DatabaseStorage = class {
11009
11136
  }
11010
11137
  // ─── Feedback Operations ──────────────────────────────────────────────────
11011
11138
  async saveFeedback(feedback) {
11012
- this.checkFeedbackEnabled();
11139
+ await this.checkFeedbackEnabled();
11013
11140
  const id = `fb_${Date.now()}_${Math.random().toString(36).slice(2, 6)}`;
11014
11141
  const createdAt = (/* @__PURE__ */ new Date()).toISOString();
11015
11142
  if (this.provider === "postgresql" || this.provider === "pgvector") {
@@ -11059,7 +11186,7 @@ var DatabaseStorage = class {
11059
11186
  }
11060
11187
  }
11061
11188
  async getFeedback(messageId, projectIds) {
11062
- this.checkFeedbackEnabled();
11189
+ await this.checkFeedbackEnabled();
11063
11190
  let item = null;
11064
11191
  if (this.provider === "postgresql" || this.provider === "pgvector") {
11065
11192
  const pool = await this.getPGPool();
@@ -11095,7 +11222,7 @@ var DatabaseStorage = class {
11095
11222
  return item;
11096
11223
  }
11097
11224
  async listFeedback(projectIds) {
11098
- this.checkFeedbackEnabled();
11225
+ await this.checkFeedbackEnabled();
11099
11226
  let raw = [];
11100
11227
  if (this.provider === "postgresql" || this.provider === "pgvector") {
11101
11228
  const pool = await this.getPGPool();
@@ -11245,12 +11372,23 @@ function resolveLicenseKey(req, config, bodyLicenseKey) {
11245
11372
  var _a3;
11246
11373
  return req.headers.get("x-license-key") || bodyLicenseKey || ((_a3 = req.headers.get("authorization")) == null ? void 0 : _a3.replace(/^Bearer\s+/i, "")) || config.licenseKey || process.env.NEXT_PUBLIC_RETRIVORA_LICENSE_KEY || process.env.RETRIVORA_LICENSE_KEY || process.env.RAG_LICENSE_KEY || "";
11247
11374
  }
11248
- function enforceLicense(req, config, bodyLicenseKey) {
11375
+ async function enforceLicense(req, config, bodyLicenseKey) {
11249
11376
  const rawKey = resolveLicenseKey(req, config, bodyLicenseKey);
11250
11377
  const licenseKey = (rawKey || "").trim().replace(/^["']|["']$/g, "").trim();
11251
11378
  const projectId = config.projectId || "";
11252
11379
  try {
11253
- const payload = LicenseVerifier.verify(licenseKey, projectId);
11380
+ let payload;
11381
+ try {
11382
+ payload = await LicenseVerifier.verifyAsync(licenseKey, projectId);
11383
+ } catch (err) {
11384
+ return {
11385
+ ok: false,
11386
+ response: NextResponse.json(
11387
+ { error: `License validation failed: ${err.message}` },
11388
+ { status: 401 }
11389
+ )
11390
+ };
11391
+ }
11254
11392
  return { ok: true, payload };
11255
11393
  } catch (err) {
11256
11394
  const message = err instanceof Error ? err.message : "Missing or invalid RETRIVORA_LICENSE_KEY. Set NEXT_PUBLIC_RETRIVORA_LICENSE_KEY in your environment or contact your administrator.";
@@ -11425,7 +11563,7 @@ function createChatHandler(configOrPlugin, options) {
11425
11563
  try {
11426
11564
  const body = await req.json();
11427
11565
  const bodyObj = body != null ? body : {};
11428
- const licenseCheck = enforceLicense(req, config, bodyObj == null ? void 0 : bodyObj.licenseKey);
11566
+ const licenseCheck = await enforceLicense(req, config, bodyObj == null ? void 0 : bodyObj.licenseKey);
11429
11567
  if (!licenseCheck.ok) return licenseCheck.response;
11430
11568
  if (isFreeTier(licenseCheck.payload.tier)) {
11431
11569
  const estimatedInputTokens = Math.ceil(
@@ -11519,7 +11657,7 @@ function createStreamHandler(configOrPlugin, options) {
11519
11657
  });
11520
11658
  }
11521
11659
  const bodyObj = body != null ? body : {};
11522
- const licenseCheck = enforceLicense(req, config, bodyObj == null ? void 0 : bodyObj.licenseKey);
11660
+ const licenseCheck = await enforceLicense(req, config, bodyObj == null ? void 0 : bodyObj.licenseKey);
11523
11661
  if (!licenseCheck.ok) return licenseCheck.response;
11524
11662
  if (isFreeTier(licenseCheck.payload.tier)) {
11525
11663
  const estimatedInputTokens = Math.ceil(
@@ -11684,7 +11822,7 @@ function createIngestHandler(configOrPlugin, options) {
11684
11822
  const config = plugin.getConfig();
11685
11823
  try {
11686
11824
  const body = await req.json();
11687
- const licenseCheck = enforceLicense(req, config, body == null ? void 0 : body.licenseKey);
11825
+ const licenseCheck = await enforceLicense(req, config, body == null ? void 0 : body.licenseKey);
11688
11826
  if (!licenseCheck.ok) return licenseCheck.response;
11689
11827
  const { documents, namespace } = body;
11690
11828
  if (!Array.isArray(documents) || documents.length === 0) {
@@ -11760,7 +11898,8 @@ function createLicenseHandler(configOrPlugin, options) {
11760
11898
  const rawKey = req.headers.get("x-license-key") || (body == null ? void 0 : body.licenseKey) || ((_a3 = req.headers.get("authorization")) == null ? void 0 : _a3.replace(/^Bearer\s+/i, "")) || config.licenseKey || process.env.NEXT_PUBLIC_RETRIVORA_LICENSE_KEY || process.env.RETRIVORA_LICENSE_KEY || "";
11761
11899
  const licenseKey = (rawKey || "").trim().replace(/^["']|["']$/g, "").trim();
11762
11900
  const projectId = (body == null ? void 0 : body.projectId) || config.projectId || "";
11763
- const payload = LicenseVerifier.verify(licenseKey, projectId);
11901
+ console.log(`[DEBUG] createLicenseHandler: projectId="${projectId}", body.projectId="${body == null ? void 0 : body.projectId}", config.projectId="${config.projectId}"`);
11902
+ const payload = await LicenseVerifier.verifyAsync(licenseKey, projectId);
11764
11903
  return NextResponse.json({
11765
11904
  valid: true,
11766
11905
  licenseStatus: "ACTIVE",
@@ -11794,7 +11933,7 @@ function createUploadHandler(configOrPlugin, options) {
11794
11933
  const authResult = await checkAuth(req, onAuthorize);
11795
11934
  if (authResult) return authResult;
11796
11935
  const config = plugin.getConfig();
11797
- const licenseCheck = enforceLicense(req, config);
11936
+ const licenseCheck = await enforceLicense(req, config);
11798
11937
  if (!licenseCheck.ok) return licenseCheck.response;
11799
11938
  try {
11800
11939
  const formData = await req.formData();
@@ -11938,7 +12077,7 @@ function createSuggestionsHandler(configOrPlugin, options) {
11938
12077
  const authResult = await checkAuth(req, onAuthorize);
11939
12078
  if (authResult) return authResult;
11940
12079
  const config = plugin.getConfig();
11941
- const licenseCheck = enforceLicense(req, config);
12080
+ const licenseCheck = await enforceLicense(req, config);
11942
12081
  if (!licenseCheck.ok) return licenseCheck.response;
11943
12082
  let effectiveLicensePayload = licenseCheck.payload;
11944
12083
  try {
@@ -11951,7 +12090,7 @@ function createSuggestionsHandler(configOrPlugin, options) {
11951
12090
  namespace = body.namespace;
11952
12091
  bodyLicenseKey = body.licenseKey;
11953
12092
  if (bodyLicenseKey) {
11954
- const recheck = enforceLicense(req, config, bodyLicenseKey);
12093
+ const recheck = await enforceLicense(req, config, bodyLicenseKey);
11955
12094
  if (!recheck.ok) return recheck.response;
11956
12095
  effectiveLicensePayload = recheck.payload;
11957
12096
  }
@@ -12242,6 +12381,7 @@ var _LicenseValidator = class _LicenseValidator {
12242
12381
  retrivoraApiBase,
12243
12382
  headers: customHeaders
12244
12383
  } = request;
12384
+ const effectiveProjectId = projectId || (typeof process !== "undefined" ? process.env.NEXT_PUBLIC_RETRIVORA_PROJECT_ID || process.env.RETRIVORA_PROJECT_ID : "") || "";
12245
12385
  const getHeader = (name) => {
12246
12386
  if (!customHeaders) return void 0;
12247
12387
  const target = name.toLowerCase();
@@ -12279,7 +12419,7 @@ var _LicenseValidator = class _LicenseValidator {
12279
12419
  }, customHeaders || {}),
12280
12420
  body: JSON.stringify({
12281
12421
  licenseKey: effectiveLicenseKey,
12282
- projectId,
12422
+ projectId: effectiveProjectId,
12283
12423
  sdkVersion,
12284
12424
  sdk,
12285
12425
  platform
@@ -12290,7 +12430,7 @@ var _LicenseValidator = class _LicenseValidator {
12290
12430
  if (!canUseLocalValidationFallback(base)) {
12291
12431
  throw err;
12292
12432
  }
12293
- const payload = LicenseVerifier.verify(effectiveLicenseKey, projectId || "");
12433
+ const payload = await LicenseVerifier.verifyAsync(effectiveLicenseKey, effectiveProjectId);
12294
12434
  const fallbackResp = {
12295
12435
  valid: true,
12296
12436
  licenseStatus: "ACTIVE",
@@ -12309,7 +12449,7 @@ var _LicenseValidator = class _LicenseValidator {
12309
12449
  }
12310
12450
  if (res && !res.ok && canUseLocalValidationFallback(base, res.status)) {
12311
12451
  try {
12312
- const payload = LicenseVerifier.verify(effectiveLicenseKey, projectId || "");
12452
+ const payload = await LicenseVerifier.verifyAsync(effectiveLicenseKey, effectiveProjectId);
12313
12453
  const fallbackResp = {
12314
12454
  valid: true,
12315
12455
  licenseStatus: "ACTIVE",