@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.
package/dist/server.js CHANGED
@@ -330,7 +330,7 @@ var init_package = __esm({
330
330
  "package.json"() {
331
331
  package_default = {
332
332
  name: "@retrivora-ai/rag-engine",
333
- version: "2.3.7",
333
+ version: "2.3.8",
334
334
  description: "Retrivora AI is a plug-and-play AI engine for RAG chat experiences \u2014 generic vector DB + LLM provider, embeddable or standalone.",
335
335
  author: "Abhinav Alkuchi",
336
336
  license: "UNLICENSED",
@@ -516,7 +516,12 @@ var init_ConfigFetcher = __esm({
516
516
  process.env.RETRIVORA_CONTROL_PLANE_URL,
517
517
  process.env.NEXT_PUBLIC_RETRIVORA_CONTROL_PLANE_URL,
518
518
  CONTROL_PLANE_URL
519
- ].filter((url) => Boolean(url) && !url.includes("localhost") && !url.includes("127.0.0.1")).map((url) => url.replace(/\/$/, ""));
519
+ ].filter((url) => {
520
+ if (!url) return false;
521
+ const isEnvVar = url === process.env.RETRIVORA_CONTROL_PLANE_URL || url === process.env.NEXT_PUBLIC_RETRIVORA_CONTROL_PLANE_URL;
522
+ if (!isEnvVar && (url.includes("localhost") || url.includes("127.0.0.1"))) return false;
523
+ return true;
524
+ }).map((url) => url.replace(/\/$/, ""));
520
525
  for (const baseUrl of controlPlaneUrls) {
521
526
  try {
522
527
  const url = `${baseUrl}/api/v1/config?projectId=${encodeURIComponent(projectId)}`;
@@ -537,8 +542,7 @@ var init_ConfigFetcher = __esm({
537
542
  isActive: data.isActive,
538
543
  expiresAt: data.expiresAt,
539
544
  vectorDb: {
540
- // apiKey is not returned by the config API — it's a server-only secret.
541
- // The SDK uses local PINECONE_API_KEY if available.
545
+ // Fetch apiKey from credentials API if available, else fallback to empty
542
546
  apiKey: data.vectorDb.apiKey || "",
543
547
  indexName: data.vectorDb.indexName || "retrivora-free",
544
548
  provider: data.vectorDb.provider || "pinecone",
@@ -570,6 +574,32 @@ var init_ConfigFetcher = __esm({
570
574
  data.projectSettings || data.settings
571
575
  )
572
576
  };
577
+ if (licenseKey) {
578
+ try {
579
+ const credUrl = `${baseUrl}/api/v1/credentials`;
580
+ const credRes = await fetch(credUrl, {
581
+ method: "POST",
582
+ headers: {
583
+ "Content-Type": "application/json"
584
+ },
585
+ body: JSON.stringify({ licenseKey, projectId: fetchedProjectId })
586
+ });
587
+ if (credRes.ok) {
588
+ const credData = await credRes.json();
589
+ if ((credData == null ? void 0 : credData.success) && (credData == null ? void 0 : credData.credentials)) {
590
+ if (credData.credentials.pineconeApiKey && !config.vectorDb.apiKey) {
591
+ config.vectorDb.apiKey = credData.credentials.pineconeApiKey;
592
+ }
593
+ if (credData.credentials.litellmApiKey) {
594
+ config.llm.apiKey = credData.credentials.litellmApiKey;
595
+ config.embedding.apiKey = credData.credentials.litellmApiKey;
596
+ }
597
+ }
598
+ }
599
+ } catch (e) {
600
+ console.warn("[ConfigFetcher] Failed to fetch credentials:", e);
601
+ }
602
+ }
573
603
  this.cache.set(cacheKey, { config, cachedAt: now });
574
604
  return config;
575
605
  }
@@ -609,6 +639,14 @@ var init_PineconeProvider = __esm({
609
639
  const opts = config.options || {};
610
640
  this.apiKey = opts.apiKey || process.env.PINECONE_API_KEY || "";
611
641
  }
642
+ getControlPlaneUrl() {
643
+ const urls = [
644
+ process.env.RETRIVORA_CONTROL_PLANE_URL,
645
+ process.env.NEXT_PUBLIC_RETRIVORA_CONTROL_PLANE_URL,
646
+ "https://www.retrivora.com"
647
+ ].filter((url) => Boolean(url));
648
+ return urls[0].replace(/\/$/, "");
649
+ }
612
650
  static getValidator() {
613
651
  return {
614
652
  validate(config) {
@@ -672,6 +710,7 @@ var init_PineconeProvider = __esm({
672
710
  let key = this.apiKey || process.env.PINECONE_API_KEY || "";
673
711
  if (!key) {
674
712
  const licenseKey = process.env.RETRIVORA_LICENSE_KEY || process.env.NEXT_PUBLIC_RETRIVORA_LICENSE_KEY;
713
+ this.licenseKey = licenseKey;
675
714
  const jwtProjectId = (() => {
676
715
  if (!licenseKey) return void 0;
677
716
  try {
@@ -685,6 +724,7 @@ var init_PineconeProvider = __esm({
685
724
  return void 0;
686
725
  })();
687
726
  const projectId = process.env.RAG_PROJECT_ID || process.env.NEXT_PUBLIC_RAG_PROJECT_ID || jwtProjectId || this.projectId || "default";
727
+ this.projectId = projectId;
688
728
  const remoteConfig = await ConfigFetcher.fetchRemoteVectorConfig(projectId, licenseKey);
689
729
  if (remoteConfig) {
690
730
  if (remoteConfig.apiKey) {
@@ -730,19 +770,59 @@ var init_PineconeProvider = __esm({
730
770
  return namespace ? idx.namespace(namespace) : idx.namespace("");
731
771
  }
732
772
  async upsert(doc, namespace) {
733
- var _a3;
773
+ var _a3, _b;
774
+ if (!this.client) {
775
+ if (!this.licenseKey) throw new Error("[PineconeProvider] Cannot execute vector operation: Missing API key and License key.");
776
+ const res = await fetch(`${this.getControlPlaneUrl()}/api/v1/vectors/upsert`, {
777
+ method: "POST",
778
+ headers: { "Content-Type": "application/json", "x-license-key": this.licenseKey },
779
+ body: JSON.stringify({
780
+ projectId: this.projectId,
781
+ indexName: this.indexName,
782
+ namespace: namespace || this.projectId,
783
+ records: [{ id: String(doc.id), values: doc.vector, metadata: __spreadValues({ content: doc.content }, (_a3 = doc.metadata) != null ? _a3 : {}) }]
784
+ })
785
+ });
786
+ if (!res.ok) throw new Error(`[PineconeProvider] Proxy upsert failed: ${await res.text()}`);
787
+ return;
788
+ }
734
789
  const targetIdx = await this.getActiveIndex(namespace);
735
790
  await targetIdx.upsert({
736
791
  records: [{
737
792
  id: String(doc.id),
738
793
  values: doc.vector,
739
- metadata: __spreadValues({ content: doc.content }, (_a3 = doc.metadata) != null ? _a3 : {})
794
+ metadata: __spreadValues({ content: doc.content }, (_b = doc.metadata) != null ? _b : {})
740
795
  }]
741
796
  });
742
797
  }
743
798
  async batchUpsert(docs, namespace) {
744
- const targetIdx = await this.getActiveIndex(namespace);
745
799
  const BATCH = 100;
800
+ if (!this.client) {
801
+ if (!this.licenseKey) throw new Error("[PineconeProvider] Cannot execute vector operation: Missing API key and License key.");
802
+ for (let i = 0; i < docs.length; i += BATCH) {
803
+ const records = docs.slice(i, i + BATCH).map((d) => {
804
+ var _a3;
805
+ return {
806
+ id: String(d.id),
807
+ values: d.vector,
808
+ metadata: __spreadValues({ content: d.content }, (_a3 = d.metadata) != null ? _a3 : {})
809
+ };
810
+ });
811
+ const res = await fetch(`${this.getControlPlaneUrl()}/api/v1/vectors/upsert`, {
812
+ method: "POST",
813
+ headers: { "Content-Type": "application/json", "x-license-key": this.licenseKey },
814
+ body: JSON.stringify({
815
+ projectId: this.projectId,
816
+ indexName: this.indexName,
817
+ namespace: namespace || this.projectId,
818
+ records
819
+ })
820
+ });
821
+ if (!res.ok) throw new Error(`[PineconeProvider] Proxy batch upsert failed: ${await res.text()}`);
822
+ }
823
+ return;
824
+ }
825
+ const targetIdx = await this.getActiveIndex(namespace);
746
826
  for (let i = 0; i < docs.length; i += BATCH) {
747
827
  const records = docs.slice(i, i + BATCH).map((d) => {
748
828
  var _a3;
@@ -756,20 +836,46 @@ var init_PineconeProvider = __esm({
756
836
  }
757
837
  }
758
838
  async query(vector, topK, namespace, filter) {
759
- var _a3;
760
- const targetIdx = await this.getActiveIndex(namespace);
839
+ var _a3, _b;
761
840
  const pineconeFilter = this.sanitizeFilter(filter);
841
+ if (!this.client) {
842
+ if (!this.licenseKey) throw new Error("[PineconeProvider] Cannot execute vector operation: Missing API key and License key.");
843
+ const res = await fetch(`${this.getControlPlaneUrl()}/api/v1/vectors/query`, {
844
+ method: "POST",
845
+ headers: { "Content-Type": "application/json", "x-license-key": this.licenseKey },
846
+ body: JSON.stringify({
847
+ projectId: this.projectId,
848
+ indexName: this.indexName,
849
+ namespace: namespace || this.projectId,
850
+ vector,
851
+ topK,
852
+ filter: pineconeFilter
853
+ })
854
+ });
855
+ if (!res.ok) throw new Error(`[PineconeProvider] Proxy query failed: ${await res.text()}`);
856
+ const data = await res.json();
857
+ return ((_a3 = data.matches) != null ? _a3 : []).map((m) => {
858
+ var _a4, _b2;
859
+ return {
860
+ id: m.id,
861
+ score: (_a4 = m.score) != null ? _a4 : 0,
862
+ content: ((_b2 = m.metadata) == null ? void 0 : _b2.content) || "",
863
+ metadata: m.metadata
864
+ };
865
+ });
866
+ }
867
+ const targetIdx = await this.getActiveIndex(namespace);
762
868
  const result = await targetIdx.query(__spreadValues({
763
869
  vector,
764
870
  topK,
765
871
  includeMetadata: true
766
872
  }, Object.keys(pineconeFilter).length > 0 ? { filter: pineconeFilter } : {}));
767
- return ((_a3 = result.matches) != null ? _a3 : []).map((m) => {
768
- var _a4, _b;
873
+ return ((_b = result.matches) != null ? _b : []).map((m) => {
874
+ var _a4, _b2;
769
875
  return {
770
876
  id: m.id,
771
877
  score: (_a4 = m.score) != null ? _a4 : 0,
772
- content: ((_b = m.metadata) == null ? void 0 : _b.content) || "",
878
+ content: ((_b2 = m.metadata) == null ? void 0 : _b2.content) || "",
773
879
  metadata: m.metadata
774
880
  };
775
881
  });
@@ -2661,9 +2767,6 @@ module.exports = __toCommonJS(server_exports);
2661
2767
  // src/core/ConfigResolver.ts
2662
2768
  init_templateUtils();
2663
2769
 
2664
- // src/core/LicenseVerifier.ts
2665
- var crypto = __toESM(require("crypto"));
2666
-
2667
2770
  // src/exceptions/index.ts
2668
2771
  var RetrivoraError = class extends Error {
2669
2772
  constructor(message, code, details) {
@@ -2749,29 +2852,18 @@ function wrapError(err, defaultCode, defaultMessage) {
2749
2852
  }
2750
2853
 
2751
2854
  // src/core/LicenseVerifier.ts
2752
- var LicenseVerifier = class {
2855
+ var _LicenseVerifier = class _LicenseVerifier {
2856
+ // Cache verified license for 5 minutes
2753
2857
  /**
2754
- * Decodes, verifies signature, and checks metadata of a license key.
2858
+ * Validates the license key asynchronously by calling the Retrivora backend.
2755
2859
  *
2756
2860
  * @param licenseKey - Base64url signed JWT license key.
2757
2861
  * @param currentProjectId - Project namespace ID.
2758
- * @param publicKeyOverride - Optional override for unit/integration tests.
2862
+ * @param provider - Optional provider for tier checks.
2759
2863
  */
2760
- static verify(licenseKey, currentProjectId, provider, publicKeyOverride) {
2864
+ static async verifyAsync(licenseKey, currentProjectId, provider) {
2761
2865
  const isProduction = process.env.NODE_ENV === "production";
2762
2866
  const now = Date.now();
2763
- if (licenseKey) {
2764
- const cacheKey = `${licenseKey}:${currentProjectId}:${provider || ""}:${publicKeyOverride || ""}`;
2765
- const cached = this.cache.get(cacheKey);
2766
- if (cached && now - cached.cachedAt < this.CACHE_TTL_MS) {
2767
- const currentTimestampSec = Math.floor(now / 1e3);
2768
- if (cached.payload.expiresAt && currentTimestampSec > cached.payload.expiresAt) {
2769
- this.cache.delete(cacheKey);
2770
- } else {
2771
- return cached.payload;
2772
- }
2773
- }
2774
- }
2775
2867
  if (!licenseKey) {
2776
2868
  if (isProduction) {
2777
2869
  throw new ConfigurationException(
@@ -2788,52 +2880,61 @@ var LicenseVerifier = class {
2788
2880
  tier: "hobby"
2789
2881
  };
2790
2882
  }
2791
- try {
2792
- const sanitizedKey = (licenseKey || "").trim().replace(/^["']|["']$/g, "").trim();
2793
- const rawToken = sanitizedKey.replace(/^rtv_/i, "").trim();
2794
- const parts = rawToken.split(".");
2795
- if (parts.length !== 3) {
2796
- throw new Error("Malformed token structure (expected 3 parts).");
2797
- }
2798
- const [headerB64, payloadB64, signatureB64] = parts;
2799
- const dataToVerify = `${headerB64}.${payloadB64}`;
2800
- const publicKey = publicKeyOverride != null ? publicKeyOverride : this.PUBLIC_KEY;
2801
- const signature = Buffer.from(signatureB64, "base64url");
2802
- const data = Buffer.from(dataToVerify);
2803
- const isValid = crypto.verify(
2804
- "sha256",
2805
- data,
2806
- publicKey,
2807
- signature
2808
- );
2809
- if (!isValid) {
2810
- throw new Error("Signature verification failed.");
2883
+ const cacheKey = `${licenseKey}:${currentProjectId}:${provider || ""}`;
2884
+ const cached = this.cache.get(cacheKey);
2885
+ if (cached && now - cached.cachedAt < this.CACHE_TTL_MS) {
2886
+ const currentTimestampSec = Math.floor(now / 1e3);
2887
+ if (cached.payload.expiresAt && currentTimestampSec > cached.payload.expiresAt) {
2888
+ this.cache.delete(cacheKey);
2889
+ } else {
2890
+ return cached.payload;
2811
2891
  }
2812
- const payload = JSON.parse(
2813
- Buffer.from(payloadB64, "base64url").toString("utf8")
2814
- );
2815
- if (!payload.projectId) {
2816
- throw new Error('License payload is missing "projectId".');
2892
+ }
2893
+ try {
2894
+ let baseUrl = typeof process !== "undefined" && process.env.RETRIVORA_CONTROL_PLANE_URL ? process.env.RETRIVORA_CONTROL_PLANE_URL : "https://retrivora.com";
2895
+ if (typeof process !== "undefined" && process.env.TELEMETRY_URL) {
2896
+ baseUrl = process.env.TELEMETRY_URL.replace(/\/api\/telemetry\/?$/, "");
2817
2897
  }
2818
- const isProjectMatch = payload.projectId === currentProjectId || payload.projectId === `retrivora-${currentProjectId}` || `retrivora-${payload.projectId}` === currentProjectId;
2819
- if (!isProjectMatch) {
2820
- throw new Error(
2821
- `Project ID mismatch. License is bound to project namespace "${payload.projectId}" but configuration has "${currentProjectId}".`
2822
- );
2898
+ const endpoint = `${baseUrl}/api/v1/license/validate`;
2899
+ const response = await fetch(endpoint, {
2900
+ method: "POST",
2901
+ headers: {
2902
+ "Content-Type": "application/json",
2903
+ "x-license-key": licenseKey
2904
+ },
2905
+ body: JSON.stringify({
2906
+ licenseKey,
2907
+ projectId: currentProjectId,
2908
+ provider
2909
+ })
2910
+ });
2911
+ if (!response.ok) {
2912
+ let errMessage = `HTTP ${response.status}`;
2913
+ try {
2914
+ const body = await response.json();
2915
+ if (body.message) errMessage = body.message;
2916
+ } catch (e) {
2917
+ }
2918
+ throw new Error(errMessage);
2823
2919
  }
2824
- if (!payload.expiresAt) {
2825
- throw new Error('License payload is missing expiration ("expiresAt").');
2920
+ const data = await response.json();
2921
+ if (!data.valid) {
2922
+ throw new Error(data.message || "License validation failed by server.");
2826
2923
  }
2827
- const currentTimestampSec = Math.floor(Date.now() / 1e3);
2828
- if (currentTimestampSec > payload.expiresAt) {
2829
- throw new Error(
2830
- `License key has expired. Expiration: ${new Date(
2831
- payload.expiresAt * 1e3
2832
- ).toDateString()}`
2833
- );
2924
+ let expiresAtNum = Math.floor(Date.now() / 1e3) + 100 * 365 * 24 * 60 * 60;
2925
+ if (data.expiresAt) {
2926
+ expiresAtNum = Math.floor(new Date(data.expiresAt).getTime() / 1e3);
2834
2927
  }
2928
+ const tier = _LicenseVerifier.extractTier(licenseKey);
2929
+ const payload = {
2930
+ projectId: currentProjectId,
2931
+ expiresAt: expiresAtNum,
2932
+ tier,
2933
+ licenseStatus: data.licenseStatus,
2934
+ minimumSupportedVersion: data.minimumSupportedVersion,
2935
+ forceUpgrade: data.forceUpgrade
2936
+ };
2835
2937
  if (isProduction && provider) {
2836
- const tier = (payload.tier || "").toLowerCase();
2837
2938
  const normalizedProvider = provider.toLowerCase();
2838
2939
  if (tier === "hobby") {
2839
2940
  const allowedHobby = ["postgresql", "pgvector", "supabase"];
@@ -2861,15 +2962,12 @@ var LicenseVerifier = class {
2861
2962
  }
2862
2963
  }
2863
2964
  }
2864
- if (licenseKey) {
2865
- const cacheKey = `${licenseKey}:${currentProjectId}:${provider || ""}:${publicKeyOverride || ""}`;
2866
- this.cache.set(cacheKey, { payload, cachedAt: now });
2867
- }
2965
+ this.cache.set(cacheKey, { payload, cachedAt: now });
2868
2966
  return payload;
2869
2967
  } catch (err) {
2870
2968
  const message = err instanceof Error ? err.message : String(err);
2871
2969
  throw new ConfigurationException(
2872
- `[Retrivora SDK] License key validation failed: ${message}`
2970
+ `[Retrivora SDK] License key validation failed via API: ${message}`
2873
2971
  );
2874
2972
  }
2875
2973
  }
@@ -2938,23 +3036,25 @@ var LicenseVerifier = class {
2938
3036
  }
2939
3037
  }
2940
3038
  }
3039
+ static extractTier(licenseKey) {
3040
+ if (!licenseKey) return "hobby";
3041
+ try {
3042
+ const sanitizedKey = licenseKey.trim().replace(/^["']|["']$/g, "").trim();
3043
+ const rawToken = sanitizedKey.replace(/^rtv_/i, "").trim();
3044
+ const parts = rawToken.split(".");
3045
+ if (parts.length === 3) {
3046
+ const decodedPayload = JSON.parse(Buffer.from(parts[1], "base64url").toString("utf8"));
3047
+ if (decodedPayload.tier) return decodedPayload.tier;
3048
+ }
3049
+ } catch (e) {
3050
+ }
3051
+ return "hobby";
3052
+ }
2941
3053
  };
2942
- // A simple in-memory cache to save CPU overhead of cryptographic signature checks.
2943
- LicenseVerifier.cache = /* @__PURE__ */ new Map();
2944
- LicenseVerifier.CACHE_TTL_MS = 60 * 1e3;
2945
- // Cache verified license for 60 seconds
2946
- // Retrivora's Public Key used to verify the license key signature.
2947
- // In production, this matches the private key held by Retrivora SaaS.
2948
- // Rotate this key only when the signing private key is replaced.
2949
- LicenseVerifier.PUBLIC_KEY = `-----BEGIN PUBLIC KEY-----
2950
- MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAyKvvOSYdCimG3b236ebV
2951
- jpG88xQiU8dSiaMahtBJDf4w0AewRj7hMNgmeZ1wyTOj8kVgeGBOolp1Z0QmTr6O
2952
- Tj4EDQ/zjsg12If7hSf3NiwLHCYmMLslyK0aaP6PQoTrYkBv3GNdkMecrIjKCijb
2953
- 6VvDLLF3X696melTVM0z/d2e50BW2AlRw/rf1EqYi10d0BcPo5zje0XETr/WGmqu
2954
- sDiXtsP5MlwkL9X7RQY2uovRa+l/vOAqAfdmJ+OzXuk5P7mDUPb+gCtKnoDbb1tr
2955
- 6UAu733dkUnetAcMqyT3fNPBLO66DCc6m9rGCYYAaG7piMEDwG0/ZySZBFbgllJc
2956
- 6QIDAQAB
2957
- -----END PUBLIC KEY-----`;
3054
+ // In-memory cache to save network overhead on hot paths.
3055
+ _LicenseVerifier.cache = /* @__PURE__ */ new Map();
3056
+ _LicenseVerifier.CACHE_TTL_MS = 5 * 60 * 1e3;
3057
+ var LicenseVerifier = _LicenseVerifier;
2958
3058
 
2959
3059
  // src/config/constants.ts
2960
3060
  var VECTOR_DB_PROVIDERS = [
@@ -3127,8 +3227,7 @@ function getEnvConfig(env = process.env, base) {
3127
3227
  const isFreeTier2 = (() => {
3128
3228
  if (!licenseKey) return true;
3129
3229
  try {
3130
- const payload = LicenseVerifier.verify(licenseKey, projectId);
3131
- const tier = (payload.tier || "").toLowerCase();
3230
+ const tier = LicenseVerifier.extractTier(licenseKey).toLowerCase();
3132
3231
  return tier === "free_trial" || tier === "free_tier" || tier === "free" || tier === "hobby";
3133
3232
  } catch (e) {
3134
3233
  return true;
@@ -9973,7 +10072,7 @@ var Retrivora = class {
9973
10072
  var _a3;
9974
10073
  try {
9975
10074
  await ConfigValidator.validateAndThrow(this.config);
9976
- LicenseVerifier.verify(
10075
+ await LicenseVerifier.verifyAsync(
9977
10076
  this.config.licenseKey,
9978
10077
  this.config.projectId,
9979
10078
  (_a3 = this.config.vectorDb) == null ? void 0 : _a3.provider
@@ -10339,7 +10438,7 @@ var VectorPlugin = class {
10339
10438
  this.validationPromise = (async () => {
10340
10439
  var _a3;
10341
10440
  await ConfigValidator.validateAndThrow(resolvedConfig);
10342
- LicenseVerifier.verify(
10441
+ await LicenseVerifier.verifyAsync(
10343
10442
  resolvedConfig.licenseKey,
10344
10443
  resolvedConfig.projectId,
10345
10444
  (_a3 = resolvedConfig.vectorDb) == null ? void 0 : _a3.provider
@@ -10833,7 +10932,7 @@ var DatabaseStorage = class {
10833
10932
  * In non-production (development / test) environments this is a complete no-op —
10834
10933
  * all History and Feedback features are freely accessible for local development.
10835
10934
  */
10836
- checkPremiumSubscription() {
10935
+ async checkPremiumSubscription() {
10837
10936
  if (process.env.NODE_ENV !== "production") {
10838
10937
  return;
10839
10938
  }
@@ -10843,7 +10942,7 @@ var DatabaseStorage = class {
10843
10942
  );
10844
10943
  }
10845
10944
  try {
10846
- const payload = LicenseVerifier.verify(this.config.licenseKey, this.config.projectId);
10945
+ const payload = await LicenseVerifier.verifyAsync(this.config.licenseKey, this.config.projectId);
10847
10946
  const tier = (payload.tier || "").toLowerCase();
10848
10947
  if (tier !== "premium" && tier !== "enterprise" && tier !== "growth" && tier !== "pro" && tier !== "developer_pro" && tier !== "free_trial" && tier !== "free_tier" && tier !== "free" && tier !== "hobby") {
10849
10948
  throw new Error(
@@ -10856,16 +10955,16 @@ var DatabaseStorage = class {
10856
10955
  );
10857
10956
  }
10858
10957
  }
10859
- checkHistoryEnabled() {
10958
+ async checkHistoryEnabled() {
10860
10959
  var _a3, _b;
10861
- this.checkPremiumSubscription();
10960
+ await this.checkPremiumSubscription();
10862
10961
  if (((_b = (_a3 = this.config.rag) == null ? void 0 : _a3.history) == null ? void 0 : _b.enabled) === false) {
10863
10962
  throw new Error("[Retrivora SDK] Chat History is disabled in RagConfig.");
10864
10963
  }
10865
10964
  }
10866
- checkFeedbackEnabled() {
10965
+ async checkFeedbackEnabled() {
10867
10966
  var _a3, _b;
10868
- this.checkPremiumSubscription();
10967
+ await this.checkPremiumSubscription();
10869
10968
  if (((_b = (_a3 = this.config.rag) == null ? void 0 : _a3.feedback) == null ? void 0 : _b.enabled) === false) {
10870
10969
  throw new Error("[Retrivora SDK] User Feedback is disabled in RagConfig.");
10871
10970
  }
@@ -10971,7 +11070,7 @@ var DatabaseStorage = class {
10971
11070
  }
10972
11071
  // ─── Message History Operations ──────────────────────────────────────────
10973
11072
  async saveMessage(sessionId, message) {
10974
- this.checkHistoryEnabled();
11073
+ await this.checkHistoryEnabled();
10975
11074
  const createdAt = (/* @__PURE__ */ new Date()).toISOString();
10976
11075
  const msgId = message.id || `msg_${Date.now()}_${Math.random().toString(36).slice(2, 6)}`;
10977
11076
  if (this.provider === "postgresql" || this.provider === "pgvector") {
@@ -11034,7 +11133,7 @@ var DatabaseStorage = class {
11034
11133
  }
11035
11134
  }
11036
11135
  async getHistory(sessionId, projectIds) {
11037
- this.checkHistoryEnabled();
11136
+ await this.checkHistoryEnabled();
11038
11137
  if (projectIds && projectIds.length > 0 && !this.sessionInScope(sessionId, projectIds)) {
11039
11138
  return [];
11040
11139
  }
@@ -11068,7 +11167,7 @@ var DatabaseStorage = class {
11068
11167
  }
11069
11168
  }
11070
11169
  async clearHistory(sessionId, projectIds) {
11071
- this.checkHistoryEnabled();
11170
+ await this.checkHistoryEnabled();
11072
11171
  if (projectIds && projectIds.length > 0 && !this.sessionInScope(sessionId, projectIds)) {
11073
11172
  return;
11074
11173
  }
@@ -11104,7 +11203,7 @@ var DatabaseStorage = class {
11104
11203
  );
11105
11204
  }
11106
11205
  async listSessions(projectIds) {
11107
- this.checkHistoryEnabled();
11206
+ await this.checkHistoryEnabled();
11108
11207
  let raw = [];
11109
11208
  if (this.provider === "postgresql" || this.provider === "pgvector") {
11110
11209
  const pool = await this.getPGPool();
@@ -11123,7 +11222,7 @@ var DatabaseStorage = class {
11123
11222
  }
11124
11223
  // ─── Feedback Operations ──────────────────────────────────────────────────
11125
11224
  async saveFeedback(feedback) {
11126
- this.checkFeedbackEnabled();
11225
+ await this.checkFeedbackEnabled();
11127
11226
  const id = `fb_${Date.now()}_${Math.random().toString(36).slice(2, 6)}`;
11128
11227
  const createdAt = (/* @__PURE__ */ new Date()).toISOString();
11129
11228
  if (this.provider === "postgresql" || this.provider === "pgvector") {
@@ -11173,7 +11272,7 @@ var DatabaseStorage = class {
11173
11272
  }
11174
11273
  }
11175
11274
  async getFeedback(messageId, projectIds) {
11176
- this.checkFeedbackEnabled();
11275
+ await this.checkFeedbackEnabled();
11177
11276
  let item = null;
11178
11277
  if (this.provider === "postgresql" || this.provider === "pgvector") {
11179
11278
  const pool = await this.getPGPool();
@@ -11209,7 +11308,7 @@ var DatabaseStorage = class {
11209
11308
  return item;
11210
11309
  }
11211
11310
  async listFeedback(projectIds) {
11212
- this.checkFeedbackEnabled();
11311
+ await this.checkFeedbackEnabled();
11213
11312
  let raw = [];
11214
11313
  if (this.provider === "postgresql" || this.provider === "pgvector") {
11215
11314
  const pool = await this.getPGPool();
@@ -11359,12 +11458,23 @@ function resolveLicenseKey(req, config, bodyLicenseKey) {
11359
11458
  var _a3;
11360
11459
  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 || "";
11361
11460
  }
11362
- function enforceLicense(req, config, bodyLicenseKey) {
11461
+ async function enforceLicense(req, config, bodyLicenseKey) {
11363
11462
  const rawKey = resolveLicenseKey(req, config, bodyLicenseKey);
11364
11463
  const licenseKey = (rawKey || "").trim().replace(/^["']|["']$/g, "").trim();
11365
11464
  const projectId = config.projectId || "";
11366
11465
  try {
11367
- const payload = LicenseVerifier.verify(licenseKey, projectId);
11466
+ let payload;
11467
+ try {
11468
+ payload = await LicenseVerifier.verifyAsync(licenseKey, projectId);
11469
+ } catch (err) {
11470
+ return {
11471
+ ok: false,
11472
+ response: import_server.NextResponse.json(
11473
+ { error: `License validation failed: ${err.message}` },
11474
+ { status: 401 }
11475
+ )
11476
+ };
11477
+ }
11368
11478
  return { ok: true, payload };
11369
11479
  } catch (err) {
11370
11480
  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.";
@@ -11539,7 +11649,7 @@ function createChatHandler(configOrPlugin, options) {
11539
11649
  try {
11540
11650
  const body = await req.json();
11541
11651
  const bodyObj = body != null ? body : {};
11542
- const licenseCheck = enforceLicense(req, config, bodyObj == null ? void 0 : bodyObj.licenseKey);
11652
+ const licenseCheck = await enforceLicense(req, config, bodyObj == null ? void 0 : bodyObj.licenseKey);
11543
11653
  if (!licenseCheck.ok) return licenseCheck.response;
11544
11654
  if (isFreeTier(licenseCheck.payload.tier)) {
11545
11655
  const estimatedInputTokens = Math.ceil(
@@ -11633,7 +11743,7 @@ function createStreamHandler(configOrPlugin, options) {
11633
11743
  });
11634
11744
  }
11635
11745
  const bodyObj = body != null ? body : {};
11636
- const licenseCheck = enforceLicense(req, config, bodyObj == null ? void 0 : bodyObj.licenseKey);
11746
+ const licenseCheck = await enforceLicense(req, config, bodyObj == null ? void 0 : bodyObj.licenseKey);
11637
11747
  if (!licenseCheck.ok) return licenseCheck.response;
11638
11748
  if (isFreeTier(licenseCheck.payload.tier)) {
11639
11749
  const estimatedInputTokens = Math.ceil(
@@ -11798,7 +11908,7 @@ function createIngestHandler(configOrPlugin, options) {
11798
11908
  const config = plugin.getConfig();
11799
11909
  try {
11800
11910
  const body = await req.json();
11801
- const licenseCheck = enforceLicense(req, config, body == null ? void 0 : body.licenseKey);
11911
+ const licenseCheck = await enforceLicense(req, config, body == null ? void 0 : body.licenseKey);
11802
11912
  if (!licenseCheck.ok) return licenseCheck.response;
11803
11913
  const { documents, namespace } = body;
11804
11914
  if (!Array.isArray(documents) || documents.length === 0) {
@@ -11874,7 +11984,7 @@ function createLicenseHandler(configOrPlugin, options) {
11874
11984
  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 || "";
11875
11985
  const licenseKey = (rawKey || "").trim().replace(/^["']|["']$/g, "").trim();
11876
11986
  const projectId = (body == null ? void 0 : body.projectId) || config.projectId || "";
11877
- const payload = LicenseVerifier.verify(licenseKey, projectId);
11987
+ const payload = await LicenseVerifier.verifyAsync(licenseKey, projectId);
11878
11988
  return import_server.NextResponse.json({
11879
11989
  valid: true,
11880
11990
  licenseStatus: "ACTIVE",
@@ -11908,7 +12018,7 @@ function createUploadHandler(configOrPlugin, options) {
11908
12018
  const authResult = await checkAuth(req, onAuthorize);
11909
12019
  if (authResult) return authResult;
11910
12020
  const config = plugin.getConfig();
11911
- const licenseCheck = enforceLicense(req, config);
12021
+ const licenseCheck = await enforceLicense(req, config);
11912
12022
  if (!licenseCheck.ok) return licenseCheck.response;
11913
12023
  try {
11914
12024
  const formData = await req.formData();
@@ -12052,7 +12162,7 @@ function createSuggestionsHandler(configOrPlugin, options) {
12052
12162
  const authResult = await checkAuth(req, onAuthorize);
12053
12163
  if (authResult) return authResult;
12054
12164
  const config = plugin.getConfig();
12055
- const licenseCheck = enforceLicense(req, config);
12165
+ const licenseCheck = await enforceLicense(req, config);
12056
12166
  if (!licenseCheck.ok) return licenseCheck.response;
12057
12167
  let effectiveLicensePayload = licenseCheck.payload;
12058
12168
  try {
@@ -12065,7 +12175,7 @@ function createSuggestionsHandler(configOrPlugin, options) {
12065
12175
  namespace = body.namespace;
12066
12176
  bodyLicenseKey = body.licenseKey;
12067
12177
  if (bodyLicenseKey) {
12068
- const recheck = enforceLicense(req, config, bodyLicenseKey);
12178
+ const recheck = await enforceLicense(req, config, bodyLicenseKey);
12069
12179
  if (!recheck.ok) return recheck.response;
12070
12180
  effectiveLicensePayload = recheck.payload;
12071
12181
  }
@@ -12356,6 +12466,7 @@ var _LicenseValidator = class _LicenseValidator {
12356
12466
  retrivoraApiBase,
12357
12467
  headers: customHeaders
12358
12468
  } = request;
12469
+ const effectiveProjectId = projectId || (typeof process !== "undefined" ? process.env.NEXT_PUBLIC_RETRIVORA_PROJECT_ID || process.env.RETRIVORA_PROJECT_ID : "") || "";
12359
12470
  const getHeader = (name) => {
12360
12471
  if (!customHeaders) return void 0;
12361
12472
  const target = name.toLowerCase();
@@ -12393,7 +12504,7 @@ var _LicenseValidator = class _LicenseValidator {
12393
12504
  }, customHeaders || {}),
12394
12505
  body: JSON.stringify({
12395
12506
  licenseKey: effectiveLicenseKey,
12396
- projectId,
12507
+ projectId: effectiveProjectId,
12397
12508
  sdkVersion,
12398
12509
  sdk,
12399
12510
  platform
@@ -12404,7 +12515,7 @@ var _LicenseValidator = class _LicenseValidator {
12404
12515
  if (!canUseLocalValidationFallback(base)) {
12405
12516
  throw err;
12406
12517
  }
12407
- const payload = LicenseVerifier.verify(effectiveLicenseKey, projectId || "");
12518
+ const payload = await LicenseVerifier.verifyAsync(effectiveLicenseKey, effectiveProjectId);
12408
12519
  const fallbackResp = {
12409
12520
  valid: true,
12410
12521
  licenseStatus: "ACTIVE",
@@ -12423,7 +12534,7 @@ var _LicenseValidator = class _LicenseValidator {
12423
12534
  }
12424
12535
  if (res && !res.ok && canUseLocalValidationFallback(base, res.status)) {
12425
12536
  try {
12426
- const payload = LicenseVerifier.verify(effectiveLicenseKey, projectId || "");
12537
+ const payload = await LicenseVerifier.verifyAsync(effectiveLicenseKey, effectiveProjectId);
12427
12538
  const fallbackResp = {
12428
12539
  valid: true,
12429
12540
  licenseStatus: "ACTIVE",