@retrivora-ai/rag-engine 2.3.7 → 2.3.8

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.
@@ -1,3 +1,3 @@
1
1
  import 'next/server';
2
- export { b as HandlerOptions, d as createChatHandler, e as createFeedbackHandler, f as createHealthHandler, g as createHistoryHandler, h as createIngestHandler, p as createLicenseHandler, i as createRagHandler, j as createSessionsHandler, k as createStreamHandler, q as createSuggestionsHandler, l as createUploadHandler, s as sseErrorFrame, m as sseFrame, n as sseMetaFrame, r as sseObservabilityFrame, o as sseTextFrame, t as sseUIFrame } from '../index-xxQOFx-u.mjs';
2
+ export { b as HandlerOptions, d as createChatHandler, e as createFeedbackHandler, f as createHealthHandler, g as createHistoryHandler, h as createIngestHandler, p as createLicenseHandler, i as createRagHandler, j as createSessionsHandler, k as createStreamHandler, q as createSuggestionsHandler, l as createUploadHandler, s as sseErrorFrame, m as sseFrame, n as sseMetaFrame, r as sseObservabilityFrame, o as sseTextFrame, t as sseUIFrame } from '../index-C7aHK7_g.mjs';
3
3
  import '../ILLMProvider-B8TAVx3j.mjs';
@@ -1,3 +1,3 @@
1
1
  import 'next/server';
2
- export { b as HandlerOptions, d as createChatHandler, e as createFeedbackHandler, f as createHealthHandler, g as createHistoryHandler, h as createIngestHandler, p as createLicenseHandler, i as createRagHandler, j as createSessionsHandler, k as createStreamHandler, q as createSuggestionsHandler, l as createUploadHandler, s as sseErrorFrame, m as sseFrame, n as sseMetaFrame, r as sseObservabilityFrame, o as sseTextFrame, t as sseUIFrame } from '../index-ejOWsaqb.js';
2
+ export { b as HandlerOptions, d as createChatHandler, e as createFeedbackHandler, f as createHealthHandler, g as createHistoryHandler, h as createIngestHandler, p as createLicenseHandler, i as createRagHandler, j as createSessionsHandler, k as createStreamHandler, q as createSuggestionsHandler, l as createUploadHandler, s as sseErrorFrame, m as sseFrame, n as sseMetaFrame, r as sseObservabilityFrame, o as sseTextFrame, t as sseUIFrame } from '../index-BQd6Bax0.js';
3
3
  import '../ILLMProvider-B8TAVx3j.js';
@@ -317,7 +317,7 @@ var init_package = __esm({
317
317
  "package.json"() {
318
318
  package_default = {
319
319
  name: "@retrivora-ai/rag-engine",
320
- version: "2.3.7",
320
+ version: "2.3.8",
321
321
  description: "Retrivora AI is a plug-and-play AI engine for RAG chat experiences \u2014 generic vector DB + LLM provider, embeddable or standalone.",
322
322
  author: "Abhinav Alkuchi",
323
323
  license: "UNLICENSED",
@@ -503,7 +503,12 @@ var init_ConfigFetcher = __esm({
503
503
  process.env.RETRIVORA_CONTROL_PLANE_URL,
504
504
  process.env.NEXT_PUBLIC_RETRIVORA_CONTROL_PLANE_URL,
505
505
  CONTROL_PLANE_URL
506
- ].filter((url) => Boolean(url) && !url.includes("localhost") && !url.includes("127.0.0.1")).map((url) => url.replace(/\/$/, ""));
506
+ ].filter((url) => {
507
+ if (!url) return false;
508
+ const isEnvVar = url === process.env.RETRIVORA_CONTROL_PLANE_URL || url === process.env.NEXT_PUBLIC_RETRIVORA_CONTROL_PLANE_URL;
509
+ if (!isEnvVar && (url.includes("localhost") || url.includes("127.0.0.1"))) return false;
510
+ return true;
511
+ }).map((url) => url.replace(/\/$/, ""));
507
512
  for (const baseUrl of controlPlaneUrls) {
508
513
  try {
509
514
  const url = `${baseUrl}/api/v1/config?projectId=${encodeURIComponent(projectId)}`;
@@ -524,8 +529,7 @@ var init_ConfigFetcher = __esm({
524
529
  isActive: data.isActive,
525
530
  expiresAt: data.expiresAt,
526
531
  vectorDb: {
527
- // apiKey is not returned by the config API — it's a server-only secret.
528
- // The SDK uses local PINECONE_API_KEY if available.
532
+ // Fetch apiKey from credentials API if available, else fallback to empty
529
533
  apiKey: data.vectorDb.apiKey || "",
530
534
  indexName: data.vectorDb.indexName || "retrivora-free",
531
535
  provider: data.vectorDb.provider || "pinecone",
@@ -557,6 +561,32 @@ var init_ConfigFetcher = __esm({
557
561
  data.projectSettings || data.settings
558
562
  )
559
563
  };
564
+ if (licenseKey) {
565
+ try {
566
+ const credUrl = `${baseUrl}/api/v1/credentials`;
567
+ const credRes = await fetch(credUrl, {
568
+ method: "POST",
569
+ headers: {
570
+ "Content-Type": "application/json"
571
+ },
572
+ body: JSON.stringify({ licenseKey, projectId: fetchedProjectId })
573
+ });
574
+ if (credRes.ok) {
575
+ const credData = await credRes.json();
576
+ if ((credData == null ? void 0 : credData.success) && (credData == null ? void 0 : credData.credentials)) {
577
+ if (credData.credentials.pineconeApiKey && !config.vectorDb.apiKey) {
578
+ config.vectorDb.apiKey = credData.credentials.pineconeApiKey;
579
+ }
580
+ if (credData.credentials.litellmApiKey) {
581
+ config.llm.apiKey = credData.credentials.litellmApiKey;
582
+ config.embedding.apiKey = credData.credentials.litellmApiKey;
583
+ }
584
+ }
585
+ }
586
+ } catch (e) {
587
+ console.warn("[ConfigFetcher] Failed to fetch credentials:", e);
588
+ }
589
+ }
560
590
  this.cache.set(cacheKey, { config, cachedAt: now });
561
591
  return config;
562
592
  }
@@ -596,6 +626,14 @@ var init_PineconeProvider = __esm({
596
626
  const opts = config.options || {};
597
627
  this.apiKey = opts.apiKey || process.env.PINECONE_API_KEY || "";
598
628
  }
629
+ getControlPlaneUrl() {
630
+ const urls = [
631
+ process.env.RETRIVORA_CONTROL_PLANE_URL,
632
+ process.env.NEXT_PUBLIC_RETRIVORA_CONTROL_PLANE_URL,
633
+ "https://www.retrivora.com"
634
+ ].filter((url) => Boolean(url));
635
+ return urls[0].replace(/\/$/, "");
636
+ }
599
637
  static getValidator() {
600
638
  return {
601
639
  validate(config) {
@@ -659,6 +697,7 @@ var init_PineconeProvider = __esm({
659
697
  let key = this.apiKey || process.env.PINECONE_API_KEY || "";
660
698
  if (!key) {
661
699
  const licenseKey = process.env.RETRIVORA_LICENSE_KEY || process.env.NEXT_PUBLIC_RETRIVORA_LICENSE_KEY;
700
+ this.licenseKey = licenseKey;
662
701
  const jwtProjectId = (() => {
663
702
  if (!licenseKey) return void 0;
664
703
  try {
@@ -672,6 +711,7 @@ var init_PineconeProvider = __esm({
672
711
  return void 0;
673
712
  })();
674
713
  const projectId = process.env.RAG_PROJECT_ID || process.env.NEXT_PUBLIC_RAG_PROJECT_ID || jwtProjectId || this.projectId || "default";
714
+ this.projectId = projectId;
675
715
  const remoteConfig = await ConfigFetcher.fetchRemoteVectorConfig(projectId, licenseKey);
676
716
  if (remoteConfig) {
677
717
  if (remoteConfig.apiKey) {
@@ -717,19 +757,59 @@ var init_PineconeProvider = __esm({
717
757
  return namespace ? idx.namespace(namespace) : idx.namespace("");
718
758
  }
719
759
  async upsert(doc, namespace) {
720
- var _a3;
760
+ var _a3, _b;
761
+ if (!this.client) {
762
+ if (!this.licenseKey) throw new Error("[PineconeProvider] Cannot execute vector operation: Missing API key and License key.");
763
+ const res = await fetch(`${this.getControlPlaneUrl()}/api/v1/vectors/upsert`, {
764
+ method: "POST",
765
+ headers: { "Content-Type": "application/json", "x-license-key": this.licenseKey },
766
+ body: JSON.stringify({
767
+ projectId: this.projectId,
768
+ indexName: this.indexName,
769
+ namespace: namespace || this.projectId,
770
+ records: [{ id: String(doc.id), values: doc.vector, metadata: __spreadValues({ content: doc.content }, (_a3 = doc.metadata) != null ? _a3 : {}) }]
771
+ })
772
+ });
773
+ if (!res.ok) throw new Error(`[PineconeProvider] Proxy upsert failed: ${await res.text()}`);
774
+ return;
775
+ }
721
776
  const targetIdx = await this.getActiveIndex(namespace);
722
777
  await targetIdx.upsert({
723
778
  records: [{
724
779
  id: String(doc.id),
725
780
  values: doc.vector,
726
- metadata: __spreadValues({ content: doc.content }, (_a3 = doc.metadata) != null ? _a3 : {})
781
+ metadata: __spreadValues({ content: doc.content }, (_b = doc.metadata) != null ? _b : {})
727
782
  }]
728
783
  });
729
784
  }
730
785
  async batchUpsert(docs, namespace) {
731
- const targetIdx = await this.getActiveIndex(namespace);
732
786
  const BATCH = 100;
787
+ if (!this.client) {
788
+ if (!this.licenseKey) throw new Error("[PineconeProvider] Cannot execute vector operation: Missing API key and License key.");
789
+ for (let i = 0; i < docs.length; i += BATCH) {
790
+ const records = docs.slice(i, i + BATCH).map((d) => {
791
+ var _a3;
792
+ return {
793
+ id: String(d.id),
794
+ values: d.vector,
795
+ metadata: __spreadValues({ content: d.content }, (_a3 = d.metadata) != null ? _a3 : {})
796
+ };
797
+ });
798
+ const res = await fetch(`${this.getControlPlaneUrl()}/api/v1/vectors/upsert`, {
799
+ method: "POST",
800
+ headers: { "Content-Type": "application/json", "x-license-key": this.licenseKey },
801
+ body: JSON.stringify({
802
+ projectId: this.projectId,
803
+ indexName: this.indexName,
804
+ namespace: namespace || this.projectId,
805
+ records
806
+ })
807
+ });
808
+ if (!res.ok) throw new Error(`[PineconeProvider] Proxy batch upsert failed: ${await res.text()}`);
809
+ }
810
+ return;
811
+ }
812
+ const targetIdx = await this.getActiveIndex(namespace);
733
813
  for (let i = 0; i < docs.length; i += BATCH) {
734
814
  const records = docs.slice(i, i + BATCH).map((d) => {
735
815
  var _a3;
@@ -743,20 +823,46 @@ var init_PineconeProvider = __esm({
743
823
  }
744
824
  }
745
825
  async query(vector, topK, namespace, filter) {
746
- var _a3;
747
- const targetIdx = await this.getActiveIndex(namespace);
826
+ var _a3, _b;
748
827
  const pineconeFilter = this.sanitizeFilter(filter);
828
+ if (!this.client) {
829
+ if (!this.licenseKey) throw new Error("[PineconeProvider] Cannot execute vector operation: Missing API key and License key.");
830
+ const res = await fetch(`${this.getControlPlaneUrl()}/api/v1/vectors/query`, {
831
+ method: "POST",
832
+ headers: { "Content-Type": "application/json", "x-license-key": this.licenseKey },
833
+ body: JSON.stringify({
834
+ projectId: this.projectId,
835
+ indexName: this.indexName,
836
+ namespace: namespace || this.projectId,
837
+ vector,
838
+ topK,
839
+ filter: pineconeFilter
840
+ })
841
+ });
842
+ if (!res.ok) throw new Error(`[PineconeProvider] Proxy query failed: ${await res.text()}`);
843
+ const data = await res.json();
844
+ return ((_a3 = data.matches) != null ? _a3 : []).map((m) => {
845
+ var _a4, _b2;
846
+ return {
847
+ id: m.id,
848
+ score: (_a4 = m.score) != null ? _a4 : 0,
849
+ content: ((_b2 = m.metadata) == null ? void 0 : _b2.content) || "",
850
+ metadata: m.metadata
851
+ };
852
+ });
853
+ }
854
+ const targetIdx = await this.getActiveIndex(namespace);
749
855
  const result = await targetIdx.query(__spreadValues({
750
856
  vector,
751
857
  topK,
752
858
  includeMetadata: true
753
859
  }, Object.keys(pineconeFilter).length > 0 ? { filter: pineconeFilter } : {}));
754
- return ((_a3 = result.matches) != null ? _a3 : []).map((m) => {
755
- var _a4, _b;
860
+ return ((_b = result.matches) != null ? _b : []).map((m) => {
861
+ var _a4, _b2;
756
862
  return {
757
863
  id: m.id,
758
864
  score: (_a4 = m.score) != null ? _a4 : 0,
759
- content: ((_b = m.metadata) == null ? void 0 : _b.content) || "",
865
+ content: ((_b2 = m.metadata) == null ? void 0 : _b2.content) || "",
760
866
  metadata: m.metadata
761
867
  };
762
868
  });
@@ -2573,9 +2679,6 @@ var import_server = require("next/server");
2573
2679
  // src/core/ConfigResolver.ts
2574
2680
  init_templateUtils();
2575
2681
 
2576
- // src/core/LicenseVerifier.ts
2577
- var crypto = __toESM(require("crypto"));
2578
-
2579
2682
  // src/exceptions/index.ts
2580
2683
  var RetrivoraError = class extends Error {
2581
2684
  constructor(message, code, details) {
@@ -2651,29 +2754,18 @@ function wrapError(err, defaultCode, defaultMessage) {
2651
2754
  }
2652
2755
 
2653
2756
  // src/core/LicenseVerifier.ts
2654
- var LicenseVerifier = class {
2757
+ var _LicenseVerifier = class _LicenseVerifier {
2758
+ // Cache verified license for 5 minutes
2655
2759
  /**
2656
- * Decodes, verifies signature, and checks metadata of a license key.
2760
+ * Validates the license key asynchronously by calling the Retrivora backend.
2657
2761
  *
2658
2762
  * @param licenseKey - Base64url signed JWT license key.
2659
2763
  * @param currentProjectId - Project namespace ID.
2660
- * @param publicKeyOverride - Optional override for unit/integration tests.
2764
+ * @param provider - Optional provider for tier checks.
2661
2765
  */
2662
- static verify(licenseKey, currentProjectId, provider, publicKeyOverride) {
2766
+ static async verifyAsync(licenseKey, currentProjectId, provider) {
2663
2767
  const isProduction = process.env.NODE_ENV === "production";
2664
2768
  const now = Date.now();
2665
- if (licenseKey) {
2666
- const cacheKey = `${licenseKey}:${currentProjectId}:${provider || ""}:${publicKeyOverride || ""}`;
2667
- const cached = this.cache.get(cacheKey);
2668
- if (cached && now - cached.cachedAt < this.CACHE_TTL_MS) {
2669
- const currentTimestampSec = Math.floor(now / 1e3);
2670
- if (cached.payload.expiresAt && currentTimestampSec > cached.payload.expiresAt) {
2671
- this.cache.delete(cacheKey);
2672
- } else {
2673
- return cached.payload;
2674
- }
2675
- }
2676
- }
2677
2769
  if (!licenseKey) {
2678
2770
  if (isProduction) {
2679
2771
  throw new ConfigurationException(
@@ -2690,52 +2782,61 @@ var LicenseVerifier = class {
2690
2782
  tier: "hobby"
2691
2783
  };
2692
2784
  }
2693
- try {
2694
- const sanitizedKey = (licenseKey || "").trim().replace(/^["']|["']$/g, "").trim();
2695
- const rawToken = sanitizedKey.replace(/^rtv_/i, "").trim();
2696
- const parts = rawToken.split(".");
2697
- if (parts.length !== 3) {
2698
- throw new Error("Malformed token structure (expected 3 parts).");
2699
- }
2700
- const [headerB64, payloadB64, signatureB64] = parts;
2701
- const dataToVerify = `${headerB64}.${payloadB64}`;
2702
- const publicKey = publicKeyOverride != null ? publicKeyOverride : this.PUBLIC_KEY;
2703
- const signature = Buffer.from(signatureB64, "base64url");
2704
- const data = Buffer.from(dataToVerify);
2705
- const isValid = crypto.verify(
2706
- "sha256",
2707
- data,
2708
- publicKey,
2709
- signature
2710
- );
2711
- if (!isValid) {
2712
- throw new Error("Signature verification failed.");
2785
+ const cacheKey = `${licenseKey}:${currentProjectId}:${provider || ""}`;
2786
+ const cached = this.cache.get(cacheKey);
2787
+ if (cached && now - cached.cachedAt < this.CACHE_TTL_MS) {
2788
+ const currentTimestampSec = Math.floor(now / 1e3);
2789
+ if (cached.payload.expiresAt && currentTimestampSec > cached.payload.expiresAt) {
2790
+ this.cache.delete(cacheKey);
2791
+ } else {
2792
+ return cached.payload;
2713
2793
  }
2714
- const payload = JSON.parse(
2715
- Buffer.from(payloadB64, "base64url").toString("utf8")
2716
- );
2717
- if (!payload.projectId) {
2718
- throw new Error('License payload is missing "projectId".');
2794
+ }
2795
+ try {
2796
+ let baseUrl = typeof process !== "undefined" && process.env.RETRIVORA_CONTROL_PLANE_URL ? process.env.RETRIVORA_CONTROL_PLANE_URL : "https://retrivora.com";
2797
+ if (typeof process !== "undefined" && process.env.TELEMETRY_URL) {
2798
+ baseUrl = process.env.TELEMETRY_URL.replace(/\/api\/telemetry\/?$/, "");
2719
2799
  }
2720
- const isProjectMatch = payload.projectId === currentProjectId || payload.projectId === `retrivora-${currentProjectId}` || `retrivora-${payload.projectId}` === currentProjectId;
2721
- if (!isProjectMatch) {
2722
- throw new Error(
2723
- `Project ID mismatch. License is bound to project namespace "${payload.projectId}" but configuration has "${currentProjectId}".`
2724
- );
2800
+ const endpoint = `${baseUrl}/api/v1/license/validate`;
2801
+ const response = await fetch(endpoint, {
2802
+ method: "POST",
2803
+ headers: {
2804
+ "Content-Type": "application/json",
2805
+ "x-license-key": licenseKey
2806
+ },
2807
+ body: JSON.stringify({
2808
+ licenseKey,
2809
+ projectId: currentProjectId,
2810
+ provider
2811
+ })
2812
+ });
2813
+ if (!response.ok) {
2814
+ let errMessage = `HTTP ${response.status}`;
2815
+ try {
2816
+ const body = await response.json();
2817
+ if (body.message) errMessage = body.message;
2818
+ } catch (e) {
2819
+ }
2820
+ throw new Error(errMessage);
2725
2821
  }
2726
- if (!payload.expiresAt) {
2727
- throw new Error('License payload is missing expiration ("expiresAt").');
2822
+ const data = await response.json();
2823
+ if (!data.valid) {
2824
+ throw new Error(data.message || "License validation failed by server.");
2728
2825
  }
2729
- const currentTimestampSec = Math.floor(Date.now() / 1e3);
2730
- if (currentTimestampSec > payload.expiresAt) {
2731
- throw new Error(
2732
- `License key has expired. Expiration: ${new Date(
2733
- payload.expiresAt * 1e3
2734
- ).toDateString()}`
2735
- );
2826
+ let expiresAtNum = Math.floor(Date.now() / 1e3) + 100 * 365 * 24 * 60 * 60;
2827
+ if (data.expiresAt) {
2828
+ expiresAtNum = Math.floor(new Date(data.expiresAt).getTime() / 1e3);
2736
2829
  }
2830
+ const tier = _LicenseVerifier.extractTier(licenseKey);
2831
+ const payload = {
2832
+ projectId: currentProjectId,
2833
+ expiresAt: expiresAtNum,
2834
+ tier,
2835
+ licenseStatus: data.licenseStatus,
2836
+ minimumSupportedVersion: data.minimumSupportedVersion,
2837
+ forceUpgrade: data.forceUpgrade
2838
+ };
2737
2839
  if (isProduction && provider) {
2738
- const tier = (payload.tier || "").toLowerCase();
2739
2840
  const normalizedProvider = provider.toLowerCase();
2740
2841
  if (tier === "hobby") {
2741
2842
  const allowedHobby = ["postgresql", "pgvector", "supabase"];
@@ -2763,15 +2864,12 @@ var LicenseVerifier = class {
2763
2864
  }
2764
2865
  }
2765
2866
  }
2766
- if (licenseKey) {
2767
- const cacheKey = `${licenseKey}:${currentProjectId}:${provider || ""}:${publicKeyOverride || ""}`;
2768
- this.cache.set(cacheKey, { payload, cachedAt: now });
2769
- }
2867
+ this.cache.set(cacheKey, { payload, cachedAt: now });
2770
2868
  return payload;
2771
2869
  } catch (err) {
2772
2870
  const message = err instanceof Error ? err.message : String(err);
2773
2871
  throw new ConfigurationException(
2774
- `[Retrivora SDK] License key validation failed: ${message}`
2872
+ `[Retrivora SDK] License key validation failed via API: ${message}`
2775
2873
  );
2776
2874
  }
2777
2875
  }
@@ -2840,23 +2938,25 @@ var LicenseVerifier = class {
2840
2938
  }
2841
2939
  }
2842
2940
  }
2941
+ static extractTier(licenseKey) {
2942
+ if (!licenseKey) return "hobby";
2943
+ try {
2944
+ const sanitizedKey = licenseKey.trim().replace(/^["']|["']$/g, "").trim();
2945
+ const rawToken = sanitizedKey.replace(/^rtv_/i, "").trim();
2946
+ const parts = rawToken.split(".");
2947
+ if (parts.length === 3) {
2948
+ const decodedPayload = JSON.parse(Buffer.from(parts[1], "base64url").toString("utf8"));
2949
+ if (decodedPayload.tier) return decodedPayload.tier;
2950
+ }
2951
+ } catch (e) {
2952
+ }
2953
+ return "hobby";
2954
+ }
2843
2955
  };
2844
- // A simple in-memory cache to save CPU overhead of cryptographic signature checks.
2845
- LicenseVerifier.cache = /* @__PURE__ */ new Map();
2846
- LicenseVerifier.CACHE_TTL_MS = 60 * 1e3;
2847
- // Cache verified license for 60 seconds
2848
- // Retrivora's Public Key used to verify the license key signature.
2849
- // In production, this matches the private key held by Retrivora SaaS.
2850
- // Rotate this key only when the signing private key is replaced.
2851
- LicenseVerifier.PUBLIC_KEY = `-----BEGIN PUBLIC KEY-----
2852
- MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAyKvvOSYdCimG3b236ebV
2853
- jpG88xQiU8dSiaMahtBJDf4w0AewRj7hMNgmeZ1wyTOj8kVgeGBOolp1Z0QmTr6O
2854
- Tj4EDQ/zjsg12If7hSf3NiwLHCYmMLslyK0aaP6PQoTrYkBv3GNdkMecrIjKCijb
2855
- 6VvDLLF3X696melTVM0z/d2e50BW2AlRw/rf1EqYi10d0BcPo5zje0XETr/WGmqu
2856
- sDiXtsP5MlwkL9X7RQY2uovRa+l/vOAqAfdmJ+OzXuk5P7mDUPb+gCtKnoDbb1tr
2857
- 6UAu733dkUnetAcMqyT3fNPBLO66DCc6m9rGCYYAaG7piMEDwG0/ZySZBFbgllJc
2858
- 6QIDAQAB
2859
- -----END PUBLIC KEY-----`;
2956
+ // In-memory cache to save network overhead on hot paths.
2957
+ _LicenseVerifier.cache = /* @__PURE__ */ new Map();
2958
+ _LicenseVerifier.CACHE_TTL_MS = 5 * 60 * 1e3;
2959
+ var LicenseVerifier = _LicenseVerifier;
2860
2960
 
2861
2961
  // src/config/constants.ts
2862
2962
  var VECTOR_DB_PROVIDERS = [
@@ -3013,8 +3113,7 @@ function getEnvConfig(env = process.env, base) {
3013
3113
  const isFreeTier2 = (() => {
3014
3114
  if (!licenseKey) return true;
3015
3115
  try {
3016
- const payload = LicenseVerifier.verify(licenseKey, projectId);
3017
- const tier = (payload.tier || "").toLowerCase();
3116
+ const tier = LicenseVerifier.extractTier(licenseKey).toLowerCase();
3018
3117
  return tier === "free_trial" || tier === "free_tier" || tier === "free" || tier === "hobby";
3019
3118
  } catch (e) {
3020
3119
  return true;
@@ -10089,7 +10188,7 @@ var VectorPlugin = class {
10089
10188
  this.validationPromise = (async () => {
10090
10189
  var _a3;
10091
10190
  await ConfigValidator.validateAndThrow(resolvedConfig);
10092
- LicenseVerifier.verify(
10191
+ await LicenseVerifier.verifyAsync(
10093
10192
  resolvedConfig.licenseKey,
10094
10193
  resolvedConfig.projectId,
10095
10194
  (_a3 = resolvedConfig.vectorDb) == null ? void 0 : _a3.provider
@@ -10362,7 +10461,7 @@ var DatabaseStorage = class {
10362
10461
  * In non-production (development / test) environments this is a complete no-op —
10363
10462
  * all History and Feedback features are freely accessible for local development.
10364
10463
  */
10365
- checkPremiumSubscription() {
10464
+ async checkPremiumSubscription() {
10366
10465
  if (process.env.NODE_ENV !== "production") {
10367
10466
  return;
10368
10467
  }
@@ -10372,7 +10471,7 @@ var DatabaseStorage = class {
10372
10471
  );
10373
10472
  }
10374
10473
  try {
10375
- const payload = LicenseVerifier.verify(this.config.licenseKey, this.config.projectId);
10474
+ const payload = await LicenseVerifier.verifyAsync(this.config.licenseKey, this.config.projectId);
10376
10475
  const tier = (payload.tier || "").toLowerCase();
10377
10476
  if (tier !== "premium" && tier !== "enterprise" && tier !== "growth" && tier !== "pro" && tier !== "developer_pro" && tier !== "free_trial" && tier !== "free_tier" && tier !== "free" && tier !== "hobby") {
10378
10477
  throw new Error(
@@ -10385,16 +10484,16 @@ var DatabaseStorage = class {
10385
10484
  );
10386
10485
  }
10387
10486
  }
10388
- checkHistoryEnabled() {
10487
+ async checkHistoryEnabled() {
10389
10488
  var _a3, _b;
10390
- this.checkPremiumSubscription();
10489
+ await this.checkPremiumSubscription();
10391
10490
  if (((_b = (_a3 = this.config.rag) == null ? void 0 : _a3.history) == null ? void 0 : _b.enabled) === false) {
10392
10491
  throw new Error("[Retrivora SDK] Chat History is disabled in RagConfig.");
10393
10492
  }
10394
10493
  }
10395
- checkFeedbackEnabled() {
10494
+ async checkFeedbackEnabled() {
10396
10495
  var _a3, _b;
10397
- this.checkPremiumSubscription();
10496
+ await this.checkPremiumSubscription();
10398
10497
  if (((_b = (_a3 = this.config.rag) == null ? void 0 : _a3.feedback) == null ? void 0 : _b.enabled) === false) {
10399
10498
  throw new Error("[Retrivora SDK] User Feedback is disabled in RagConfig.");
10400
10499
  }
@@ -10500,7 +10599,7 @@ var DatabaseStorage = class {
10500
10599
  }
10501
10600
  // ─── Message History Operations ──────────────────────────────────────────
10502
10601
  async saveMessage(sessionId, message) {
10503
- this.checkHistoryEnabled();
10602
+ await this.checkHistoryEnabled();
10504
10603
  const createdAt = (/* @__PURE__ */ new Date()).toISOString();
10505
10604
  const msgId = message.id || `msg_${Date.now()}_${Math.random().toString(36).slice(2, 6)}`;
10506
10605
  if (this.provider === "postgresql" || this.provider === "pgvector") {
@@ -10563,7 +10662,7 @@ var DatabaseStorage = class {
10563
10662
  }
10564
10663
  }
10565
10664
  async getHistory(sessionId, projectIds) {
10566
- this.checkHistoryEnabled();
10665
+ await this.checkHistoryEnabled();
10567
10666
  if (projectIds && projectIds.length > 0 && !this.sessionInScope(sessionId, projectIds)) {
10568
10667
  return [];
10569
10668
  }
@@ -10597,7 +10696,7 @@ var DatabaseStorage = class {
10597
10696
  }
10598
10697
  }
10599
10698
  async clearHistory(sessionId, projectIds) {
10600
- this.checkHistoryEnabled();
10699
+ await this.checkHistoryEnabled();
10601
10700
  if (projectIds && projectIds.length > 0 && !this.sessionInScope(sessionId, projectIds)) {
10602
10701
  return;
10603
10702
  }
@@ -10633,7 +10732,7 @@ var DatabaseStorage = class {
10633
10732
  );
10634
10733
  }
10635
10734
  async listSessions(projectIds) {
10636
- this.checkHistoryEnabled();
10735
+ await this.checkHistoryEnabled();
10637
10736
  let raw = [];
10638
10737
  if (this.provider === "postgresql" || this.provider === "pgvector") {
10639
10738
  const pool = await this.getPGPool();
@@ -10652,7 +10751,7 @@ var DatabaseStorage = class {
10652
10751
  }
10653
10752
  // ─── Feedback Operations ──────────────────────────────────────────────────
10654
10753
  async saveFeedback(feedback) {
10655
- this.checkFeedbackEnabled();
10754
+ await this.checkFeedbackEnabled();
10656
10755
  const id = `fb_${Date.now()}_${Math.random().toString(36).slice(2, 6)}`;
10657
10756
  const createdAt = (/* @__PURE__ */ new Date()).toISOString();
10658
10757
  if (this.provider === "postgresql" || this.provider === "pgvector") {
@@ -10702,7 +10801,7 @@ var DatabaseStorage = class {
10702
10801
  }
10703
10802
  }
10704
10803
  async getFeedback(messageId, projectIds) {
10705
- this.checkFeedbackEnabled();
10804
+ await this.checkFeedbackEnabled();
10706
10805
  let item = null;
10707
10806
  if (this.provider === "postgresql" || this.provider === "pgvector") {
10708
10807
  const pool = await this.getPGPool();
@@ -10738,7 +10837,7 @@ var DatabaseStorage = class {
10738
10837
  return item;
10739
10838
  }
10740
10839
  async listFeedback(projectIds) {
10741
- this.checkFeedbackEnabled();
10840
+ await this.checkFeedbackEnabled();
10742
10841
  let raw = [];
10743
10842
  if (this.provider === "postgresql" || this.provider === "pgvector") {
10744
10843
  const pool = await this.getPGPool();
@@ -10888,12 +10987,23 @@ function resolveLicenseKey(req, config, bodyLicenseKey) {
10888
10987
  var _a3;
10889
10988
  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 || "";
10890
10989
  }
10891
- function enforceLicense(req, config, bodyLicenseKey) {
10990
+ async function enforceLicense(req, config, bodyLicenseKey) {
10892
10991
  const rawKey = resolveLicenseKey(req, config, bodyLicenseKey);
10893
10992
  const licenseKey = (rawKey || "").trim().replace(/^["']|["']$/g, "").trim();
10894
10993
  const projectId = config.projectId || "";
10895
10994
  try {
10896
- const payload = LicenseVerifier.verify(licenseKey, projectId);
10995
+ let payload;
10996
+ try {
10997
+ payload = await LicenseVerifier.verifyAsync(licenseKey, projectId);
10998
+ } catch (err) {
10999
+ return {
11000
+ ok: false,
11001
+ response: import_server.NextResponse.json(
11002
+ { error: `License validation failed: ${err.message}` },
11003
+ { status: 401 }
11004
+ )
11005
+ };
11006
+ }
10897
11007
  return { ok: true, payload };
10898
11008
  } catch (err) {
10899
11009
  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.";
@@ -11068,7 +11178,7 @@ function createChatHandler(configOrPlugin, options) {
11068
11178
  try {
11069
11179
  const body = await req.json();
11070
11180
  const bodyObj = body != null ? body : {};
11071
- const licenseCheck = enforceLicense(req, config, bodyObj == null ? void 0 : bodyObj.licenseKey);
11181
+ const licenseCheck = await enforceLicense(req, config, bodyObj == null ? void 0 : bodyObj.licenseKey);
11072
11182
  if (!licenseCheck.ok) return licenseCheck.response;
11073
11183
  if (isFreeTier(licenseCheck.payload.tier)) {
11074
11184
  const estimatedInputTokens = Math.ceil(
@@ -11162,7 +11272,7 @@ function createStreamHandler(configOrPlugin, options) {
11162
11272
  });
11163
11273
  }
11164
11274
  const bodyObj = body != null ? body : {};
11165
- const licenseCheck = enforceLicense(req, config, bodyObj == null ? void 0 : bodyObj.licenseKey);
11275
+ const licenseCheck = await enforceLicense(req, config, bodyObj == null ? void 0 : bodyObj.licenseKey);
11166
11276
  if (!licenseCheck.ok) return licenseCheck.response;
11167
11277
  if (isFreeTier(licenseCheck.payload.tier)) {
11168
11278
  const estimatedInputTokens = Math.ceil(
@@ -11327,7 +11437,7 @@ function createIngestHandler(configOrPlugin, options) {
11327
11437
  const config = plugin.getConfig();
11328
11438
  try {
11329
11439
  const body = await req.json();
11330
- const licenseCheck = enforceLicense(req, config, body == null ? void 0 : body.licenseKey);
11440
+ const licenseCheck = await enforceLicense(req, config, body == null ? void 0 : body.licenseKey);
11331
11441
  if (!licenseCheck.ok) return licenseCheck.response;
11332
11442
  const { documents, namespace } = body;
11333
11443
  if (!Array.isArray(documents) || documents.length === 0) {
@@ -11403,7 +11513,7 @@ function createLicenseHandler(configOrPlugin, options) {
11403
11513
  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 || "";
11404
11514
  const licenseKey = (rawKey || "").trim().replace(/^["']|["']$/g, "").trim();
11405
11515
  const projectId = (body == null ? void 0 : body.projectId) || config.projectId || "";
11406
- const payload = LicenseVerifier.verify(licenseKey, projectId);
11516
+ const payload = await LicenseVerifier.verifyAsync(licenseKey, projectId);
11407
11517
  return import_server.NextResponse.json({
11408
11518
  valid: true,
11409
11519
  licenseStatus: "ACTIVE",
@@ -11437,7 +11547,7 @@ function createUploadHandler(configOrPlugin, options) {
11437
11547
  const authResult = await checkAuth(req, onAuthorize);
11438
11548
  if (authResult) return authResult;
11439
11549
  const config = plugin.getConfig();
11440
- const licenseCheck = enforceLicense(req, config);
11550
+ const licenseCheck = await enforceLicense(req, config);
11441
11551
  if (!licenseCheck.ok) return licenseCheck.response;
11442
11552
  try {
11443
11553
  const formData = await req.formData();
@@ -11581,7 +11691,7 @@ function createSuggestionsHandler(configOrPlugin, options) {
11581
11691
  const authResult = await checkAuth(req, onAuthorize);
11582
11692
  if (authResult) return authResult;
11583
11693
  const config = plugin.getConfig();
11584
- const licenseCheck = enforceLicense(req, config);
11694
+ const licenseCheck = await enforceLicense(req, config);
11585
11695
  if (!licenseCheck.ok) return licenseCheck.response;
11586
11696
  let effectiveLicensePayload = licenseCheck.payload;
11587
11697
  try {
@@ -11594,7 +11704,7 @@ function createSuggestionsHandler(configOrPlugin, options) {
11594
11704
  namespace = body.namespace;
11595
11705
  bodyLicenseKey = body.licenseKey;
11596
11706
  if (bodyLicenseKey) {
11597
- const recheck = enforceLicense(req, config, bodyLicenseKey);
11707
+ const recheck = await enforceLicense(req, config, bodyLicenseKey);
11598
11708
  if (!recheck.ok) return recheck.response;
11599
11709
  effectiveLicensePayload = recheck.payload;
11600
11710
  }