@retrivora-ai/rag-engine 2.3.4 → 2.3.6

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.
Files changed (36) hide show
  1. package/dist/{BatchProcessor-CQDtlggz.d.ts → BatchProcessor-ByBl-1MA.d.ts} +81 -3
  2. package/dist/{BatchProcessor-tVzb9CdE.d.mts → BatchProcessor-Dfn23VAd.d.mts} +81 -3
  3. package/dist/{ILLMProvider-CcJ5N6XD.d.mts → ILLMProvider-B8TAVx3j.d.mts} +63 -1
  4. package/dist/{ILLMProvider-CcJ5N6XD.d.ts → ILLMProvider-B8TAVx3j.d.ts} +63 -1
  5. package/dist/handlers/index.d.mts +2 -2
  6. package/dist/handlers/index.d.ts +2 -2
  7. package/dist/handlers/index.js +419 -169
  8. package/dist/handlers/index.mjs +419 -169
  9. package/dist/{index-BwmyPJHp.d.ts → index-ejOWsaqb.d.ts} +1 -1
  10. package/dist/{index-CL-zF6bD.d.mts → index-xxQOFx-u.d.mts} +1 -1
  11. package/dist/index.css +9 -0
  12. package/dist/index.d.mts +19 -5
  13. package/dist/index.d.ts +19 -5
  14. package/dist/index.js +638 -189
  15. package/dist/index.mjs +678 -234
  16. package/dist/server.d.mts +6 -6
  17. package/dist/server.d.ts +6 -6
  18. package/dist/server.js +461 -173
  19. package/dist/server.mjs +457 -173
  20. package/package.json +2 -2
  21. package/src/components/ChatWidget.tsx +44 -19
  22. package/src/components/ChatWindow.tsx +30 -14
  23. package/src/components/ConfigProvider.tsx +86 -6
  24. package/src/components/DocumentUpload.tsx +8 -2
  25. package/src/config/RagConfig.ts +4 -0
  26. package/src/core/ConfigFetcher.ts +73 -11
  27. package/src/core/ConfigResolver.ts +1 -0
  28. package/src/core/LicenseValidator.ts +31 -13
  29. package/src/core/ProjectSettings.ts +247 -0
  30. package/src/handlers/index.ts +63 -7
  31. package/src/hooks/useProjectSettings.ts +105 -0
  32. package/src/index.css +9 -0
  33. package/src/index.ts +28 -0
  34. package/src/providers/vectordb/PineconeProvider.ts +17 -4
  35. package/src/server.ts +23 -1
  36. package/src/types/props.ts +14 -2
package/dist/server.mjs CHANGED
@@ -139,15 +139,355 @@ var init_BaseVectorProvider = __esm({
139
139
  }
140
140
  });
141
141
 
142
+ // src/core/ProjectSettings.ts
143
+ function createDefaultProjectSettings(projectId) {
144
+ return {
145
+ projectId,
146
+ branding: {
147
+ companyName: "Retrivora AI",
148
+ botName: "Retrivora Assistant",
149
+ welcomeMessage: "Hi, I can help you search your knowledge base.",
150
+ primaryColor: "#6366f1",
151
+ secondaryColor: "#8b5cf6",
152
+ fontFamily: "Inter",
153
+ borderRadius: 14,
154
+ logoUrl: "",
155
+ avatarUrl: "",
156
+ customCss: ""
157
+ },
158
+ ai: {
159
+ defaultModel: "llama-3.1-8b-instant",
160
+ embeddingModel: "text-embedding-3-small",
161
+ systemPrompt: "Answer using the connected knowledge base. Cite sources when available.",
162
+ memoryEnabled: true,
163
+ multiModelEnabled: true,
164
+ citationsEnabled: true,
165
+ fileUploadEnabled: true
166
+ },
167
+ auth: {
168
+ mode: "public",
169
+ allowedOrigins: [],
170
+ requireVerifiedEmail: false,
171
+ sessionTtlMinutes: 1440
172
+ },
173
+ widget: {
174
+ position: "bottom-right",
175
+ theme: "light",
176
+ lazyLoad: true,
177
+ autoReconnect: true,
178
+ persistConversations: true,
179
+ showRetrivoraBranding: false
180
+ },
181
+ telemetry: {
182
+ enabled: true,
183
+ collectBrowser: true,
184
+ collectCountry: false,
185
+ redactPii: true,
186
+ retentionDays: 30
187
+ },
188
+ lifecycleHooks: DEFAULT_LIFECYCLE_HOOKS,
189
+ conversationFeatures: DEFAULT_CONVERSATION_FEATURES
190
+ };
191
+ }
192
+ function cleanString(value, fallback, maxLength = 2e3) {
193
+ if (typeof value !== "string") return fallback;
194
+ return value.trim().slice(0, maxLength);
195
+ }
196
+ function cleanBoolean(value, fallback) {
197
+ return typeof value === "boolean" ? value : fallback;
198
+ }
199
+ function cleanNumber(value, fallback, min, max) {
200
+ const num = typeof value === "number" ? value : Number(value);
201
+ if (!Number.isFinite(num)) return fallback;
202
+ return Math.min(Math.max(Math.round(num), min), max);
203
+ }
204
+ function cleanEnum(value, fallback, allowed) {
205
+ return typeof value === "string" && allowed.includes(value) ? value : fallback;
206
+ }
207
+ function cleanStringList(value, fallback, maxItems = 20) {
208
+ if (!Array.isArray(value)) return fallback;
209
+ const cleaned = value.filter((item) => typeof item === "string").map((item) => item.trim()).filter(Boolean).slice(0, maxItems);
210
+ return cleaned.length > 0 ? Array.from(new Set(cleaned)) : fallback;
211
+ }
212
+ function normalizeProjectSettings(projectId, input) {
213
+ const defaults = createDefaultProjectSettings(projectId);
214
+ const branding = (input == null ? void 0 : input.branding) || {};
215
+ const ai = (input == null ? void 0 : input.ai) || {};
216
+ const auth = (input == null ? void 0 : input.auth) || {};
217
+ const widget = (input == null ? void 0 : input.widget) || {};
218
+ const telemetry = (input == null ? void 0 : input.telemetry) || {};
219
+ return {
220
+ projectId,
221
+ branding: {
222
+ companyName: cleanString(branding.companyName, defaults.branding.companyName, 120),
223
+ botName: cleanString(branding.botName, defaults.branding.botName, 120),
224
+ welcomeMessage: cleanString(branding.welcomeMessage, defaults.branding.welcomeMessage, 500),
225
+ primaryColor: cleanString(branding.primaryColor, defaults.branding.primaryColor, 32),
226
+ secondaryColor: cleanString(branding.secondaryColor, defaults.branding.secondaryColor, 32),
227
+ fontFamily: cleanString(branding.fontFamily, defaults.branding.fontFamily, 80),
228
+ borderRadius: cleanNumber(branding.borderRadius, defaults.branding.borderRadius, 0, 32),
229
+ logoUrl: cleanString(branding.logoUrl, defaults.branding.logoUrl, 500),
230
+ avatarUrl: cleanString(branding.avatarUrl, defaults.branding.avatarUrl, 500),
231
+ customCss: cleanString(branding.customCss, defaults.branding.customCss, 5e3)
232
+ },
233
+ ai: {
234
+ defaultModel: cleanString(ai.defaultModel, defaults.ai.defaultModel, 120),
235
+ embeddingModel: cleanString(ai.embeddingModel, defaults.ai.embeddingModel, 120),
236
+ systemPrompt: cleanString(ai.systemPrompt, defaults.ai.systemPrompt, 5e3),
237
+ memoryEnabled: cleanBoolean(ai.memoryEnabled, defaults.ai.memoryEnabled),
238
+ multiModelEnabled: cleanBoolean(ai.multiModelEnabled, defaults.ai.multiModelEnabled),
239
+ citationsEnabled: cleanBoolean(ai.citationsEnabled, defaults.ai.citationsEnabled),
240
+ fileUploadEnabled: cleanBoolean(ai.fileUploadEnabled, defaults.ai.fileUploadEnabled)
241
+ },
242
+ auth: {
243
+ mode: cleanEnum(auth.mode, defaults.auth.mode, ["public", "anonymous", "jwt", "oauth", "okta", "auth0", "supabase", "firebase", "sso", "custom_token"]),
244
+ allowedOrigins: cleanStringList(auth.allowedOrigins, defaults.auth.allowedOrigins, 25),
245
+ requireVerifiedEmail: cleanBoolean(auth.requireVerifiedEmail, defaults.auth.requireVerifiedEmail),
246
+ sessionTtlMinutes: cleanNumber(auth.sessionTtlMinutes, defaults.auth.sessionTtlMinutes, 15, 43200)
247
+ },
248
+ widget: {
249
+ position: cleanEnum(widget.position, defaults.widget.position, ["bottom-right", "bottom-left", "top-right", "top-left"]),
250
+ theme: cleanEnum(widget.theme, defaults.widget.theme, ["light", "dark", "system"]),
251
+ lazyLoad: cleanBoolean(widget.lazyLoad, defaults.widget.lazyLoad),
252
+ autoReconnect: cleanBoolean(widget.autoReconnect, defaults.widget.autoReconnect),
253
+ persistConversations: cleanBoolean(widget.persistConversations, defaults.widget.persistConversations),
254
+ showRetrivoraBranding: cleanBoolean(widget.showRetrivoraBranding, defaults.widget.showRetrivoraBranding)
255
+ },
256
+ telemetry: {
257
+ enabled: cleanBoolean(telemetry.enabled, defaults.telemetry.enabled),
258
+ collectBrowser: cleanBoolean(telemetry.collectBrowser, defaults.telemetry.collectBrowser),
259
+ collectCountry: cleanBoolean(telemetry.collectCountry, defaults.telemetry.collectCountry),
260
+ redactPii: cleanBoolean(telemetry.redactPii, defaults.telemetry.redactPii),
261
+ retentionDays: cleanNumber(telemetry.retentionDays, defaults.telemetry.retentionDays, 1, 365)
262
+ },
263
+ lifecycleHooks: cleanStringList(input == null ? void 0 : input.lifecycleHooks, defaults.lifecycleHooks, 30),
264
+ conversationFeatures: cleanStringList(input == null ? void 0 : input.conversationFeatures, defaults.conversationFeatures, 30),
265
+ updatedAt: input == null ? void 0 : input.updatedAt
266
+ };
267
+ }
268
+ function projectSettingsToUiConfig(settings) {
269
+ return {
270
+ title: settings.branding.botName,
271
+ subtitle: settings.branding.companyName,
272
+ primaryColor: settings.branding.primaryColor,
273
+ accentColor: settings.branding.secondaryColor,
274
+ logoUrl: settings.branding.logoUrl || settings.branding.avatarUrl,
275
+ welcomeMessage: settings.branding.welcomeMessage,
276
+ poweredBy: settings.widget.showRetrivoraBranding ? "Retrivora AI" : "",
277
+ allowUpload: settings.ai.fileUploadEnabled,
278
+ borderRadius: settings.branding.borderRadius <= 4 ? "sm" : settings.branding.borderRadius <= 8 ? "md" : settings.branding.borderRadius <= 16 ? "xl" : "full"
279
+ };
280
+ }
281
+ var DEFAULT_LIFECYCLE_HOOKS, DEFAULT_CONVERSATION_FEATURES;
282
+ var init_ProjectSettings = __esm({
283
+ "src/core/ProjectSettings.ts"() {
284
+ "use strict";
285
+ DEFAULT_LIFECYCLE_HOOKS = [
286
+ "beforeInitialize",
287
+ "afterInitialize",
288
+ "beforeSend",
289
+ "afterResponse",
290
+ "onMessage",
291
+ "onCitationClick",
292
+ "onFeedback",
293
+ "onError",
294
+ "onReconnect",
295
+ "onFileUpload"
296
+ ];
297
+ DEFAULT_CONVERSATION_FEATURES = [
298
+ "History",
299
+ "Resume",
300
+ "Search",
301
+ "Export",
302
+ "Rename",
303
+ "Delete",
304
+ "Tags",
305
+ "Pinned",
306
+ "Unread",
307
+ "Ratings"
308
+ ];
309
+ }
310
+ });
311
+
312
+ // package.json
313
+ var package_default;
314
+ var init_package = __esm({
315
+ "package.json"() {
316
+ package_default = {
317
+ name: "@retrivora-ai/rag-engine",
318
+ version: "2.3.6",
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
+ author: "Abhinav Alkuchi",
321
+ license: "UNLICENSED",
322
+ keywords: [
323
+ "rag",
324
+ "retrieval-augmented-generation",
325
+ "chatbot",
326
+ "vector-database",
327
+ "pinecone",
328
+ "pgvector",
329
+ "postgresql",
330
+ "milvus",
331
+ "qdrant",
332
+ "chromadb",
333
+ "redis",
334
+ "weaviate",
335
+ "mongodb",
336
+ "openai",
337
+ "anthropic",
338
+ "ollama",
339
+ "nextjs",
340
+ "react",
341
+ "ai",
342
+ "llm",
343
+ "embeddings"
344
+ ],
345
+ main: "dist/index.js",
346
+ module: "dist/index.mjs",
347
+ types: "dist/index.d.ts",
348
+ exports: {
349
+ ".": {
350
+ types: "./dist/index.d.ts",
351
+ require: "./dist/index.js",
352
+ import: "./dist/index.mjs"
353
+ },
354
+ "./style.css": "./dist/index.css",
355
+ "./index.css": "./dist/index.css",
356
+ "./styles.css": "./dist/index.css",
357
+ "./handlers": {
358
+ types: "./dist/handlers/index.d.ts",
359
+ require: "./dist/handlers/index.js",
360
+ import: "./dist/handlers/index.mjs"
361
+ },
362
+ "./server": {
363
+ types: "./dist/server.d.ts",
364
+ require: "./dist/server.js",
365
+ import: "./dist/server.mjs"
366
+ }
367
+ },
368
+ browser: {
369
+ child_process: false,
370
+ fs: false,
371
+ net: false,
372
+ tls: false,
373
+ crypto: false,
374
+ os: false,
375
+ path: false,
376
+ stream: false,
377
+ http: false,
378
+ https: false,
379
+ zlib: false,
380
+ mongodb: false,
381
+ pg: false,
382
+ "pdf-parse": false,
383
+ mammoth: false
384
+ },
385
+ files: [
386
+ "dist",
387
+ "src",
388
+ ".env.example",
389
+ "README.md",
390
+ "FREE_TIER_ARCHITECTURE.md"
391
+ ],
392
+ scripts: {
393
+ dev: "npx @tailwindcss/cli -i src/tailwind.css -o src/index.css && tsup src/index.ts src/handlers/index.ts src/server.ts --format cjs,esm --watch --tsconfig tsconfig.build.json --external react,react-dom,next,mongodb,pg,openai,@anthropic-ai/sdk,@pinecone-database/pinecone,axios,lucide-react,mammoth,pdf-parse,xlsx,react-markdown,remark-gfm,next-themes,langchain,@langchain/core,@langchain/openai,llamaindex --inject-style",
394
+ build: "npm run build:pkg",
395
+ "build:pkg": "npx @tailwindcss/cli -i src/tailwind.css -o src/index.css && tsup src/index.ts src/handlers/index.ts src/server.ts --format cjs,esm --dts --clean --no-splitting --tsconfig tsconfig.build.json --external react,react-dom,next,mongodb,pg,openai,@anthropic-ai/sdk,@pinecone-database/pinecone,axios,lucide-react,mammoth,pdf-parse,xlsx,react-markdown,remark-gfm,next-themes,langchain,@langchain/core,@langchain/openai,llamaindex --inject-style && npx @tailwindcss/cli -i src/tailwind.css -o dist/index.css",
396
+ lint: "eslint",
397
+ typecheck: "tsc --noEmit -p tsconfig.build.json",
398
+ clean: "rm -rf dist"
399
+ },
400
+ peerDependencies: {
401
+ next: ">=15.0.0",
402
+ react: ">=18.0.0",
403
+ "react-dom": ">=18.0.0"
404
+ },
405
+ peerDependenciesMeta: {
406
+ next: {
407
+ optional: true
408
+ }
409
+ },
410
+ dependencies: {
411
+ "@anthropic-ai/sdk": "^0.95.1",
412
+ "@google/genai": "^0.8.0",
413
+ "@google/generative-ai": "^0.24.1",
414
+ "@pinecone-database/pinecone": "^7.2.0",
415
+ "@types/papaparse": "^5.5.2",
416
+ axios: "^1.15.0",
417
+ "lucide-react": "^1.8.0",
418
+ "next-themes": "^0.4.6",
419
+ openai: "^6.34.0",
420
+ papaparse: "^5.5.3",
421
+ "react-is": "^18.3.1",
422
+ "react-markdown": "^10.1.0",
423
+ recharts: "^3.8.1",
424
+ "remark-gfm": "^4.0.1",
425
+ xlsx: "^0.18.5"
426
+ },
427
+ optionalDependencies: {
428
+ "@langchain/core": "^1.1.42",
429
+ "@langchain/openai": "^1.4.5",
430
+ langchain: "^1.3.5",
431
+ llamaindex: "^0.11.9",
432
+ mammoth: "^1.8.0",
433
+ mongodb: "^7.1.1",
434
+ "pdf-parse": "^1.1.1",
435
+ pg: "^8.20.0"
436
+ },
437
+ devDependencies: {
438
+ "@tailwindcss/cli": "^4",
439
+ "@tailwindcss/postcss": "^4",
440
+ "@types/estree": "^1.0.9",
441
+ "@types/node": "^20",
442
+ "@types/pdf-parse": "^1.1.5",
443
+ "@types/pg": "^8.20.0",
444
+ "@types/react": "^19.2.14",
445
+ "@types/react-dom": "^19.2.3",
446
+ dotenv: "^17.4.2",
447
+ eslint: "^9",
448
+ "eslint-config-next": "16.2.4",
449
+ next: "16.2.10",
450
+ tailwindcss: "^4",
451
+ tsup: "^8.5.1",
452
+ typescript: "^5"
453
+ }
454
+ };
455
+ }
456
+ });
457
+
458
+ // src/version.ts
459
+ var SDK_VERSION;
460
+ var init_version = __esm({
461
+ "src/version.ts"() {
462
+ "use strict";
463
+ init_package();
464
+ SDK_VERSION = package_default.version || "2.1.3";
465
+ }
466
+ });
467
+
142
468
  // src/core/ConfigFetcher.ts
143
- var ConfigFetcher;
469
+ var CONTROL_PLANE_URL, LLM_PROXY_BASE_URL, ConfigFetcher;
144
470
  var init_ConfigFetcher = __esm({
145
471
  "src/core/ConfigFetcher.ts"() {
146
472
  "use strict";
473
+ init_ProjectSettings();
474
+ init_version();
475
+ CONTROL_PLANE_URL = "https://www.retrivora.com";
476
+ LLM_PROXY_BASE_URL = "https://www.retrivora.com/api/v1";
147
477
  ConfigFetcher = class {
148
478
  // 5-minute in-memory session cache
149
479
  /**
150
- * Fetch full project configuration (vectorDb + embedding + llm) from Retrivora Control Plane.
480
+ * Fetch full project configuration (vectorDb + embedding + llm + workspace) from Retrivora Control Plane.
481
+ *
482
+ * The SDK calls https://www.retrivora.com/api/v1/config with the project ID and license key.
483
+ * The server validates the license against the database and returns:
484
+ * - validity (tier, isActive, expiresAt)
485
+ * - LLM model info
486
+ * - embedding model info
487
+ * - Pinecone index name and workspace/namespace
488
+ *
489
+ * The Pinecone API key is NOT returned (server-only). The SDK uses local
490
+ * PINECONE_API_KEY if available, or vector operations are handled server-side.
151
491
  */
152
492
  static async fetchRemoteConfig(projectId, licenseKey) {
153
493
  var _a3, _b, _c, _d, _e, _f, _g2, _h, _i, _j, _k;
@@ -160,46 +500,60 @@ var init_ConfigFetcher = __esm({
160
500
  const controlPlaneUrls = [
161
501
  process.env.RETRIVORA_CONTROL_PLANE_URL,
162
502
  process.env.NEXT_PUBLIC_RETRIVORA_CONTROL_PLANE_URL,
163
- "https://www.retrivora.com",
164
- "https://retrivora.com",
165
- "http://localhost:3000",
166
- "http://localhost:3001"
167
- ].filter(Boolean);
503
+ CONTROL_PLANE_URL
504
+ ].filter((url) => Boolean(url) && !url.includes("localhost") && !url.includes("127.0.0.1")).map((url) => url.replace(/\/$/, ""));
168
505
  for (const baseUrl of controlPlaneUrls) {
169
506
  try {
170
- const url = `${baseUrl.replace(/\/$/, "")}/api/v1/config?projectId=${encodeURIComponent(projectId)}${licenseKey ? `&licenseKey=${encodeURIComponent(licenseKey)}` : ""}`;
507
+ const url = `${baseUrl}/api/v1/config?projectId=${encodeURIComponent(projectId)}`;
171
508
  const res = await fetch(url, {
172
509
  method: "GET",
173
510
  headers: __spreadValues({
174
- "Content-Type": "application/json"
511
+ "Content-Type": "application/json",
512
+ "x-sdk-version": SDK_VERSION
175
513
  }, licenseKey ? { "x-license-key": licenseKey } : {})
176
514
  });
177
515
  if (res.ok) {
178
516
  const data = await res.json();
179
- if ((data == null ? void 0 : data.success) && ((_a3 = data == null ? void 0 : data.vectorDb) == null ? void 0 : _a3.apiKey)) {
517
+ if ((data == null ? void 0 : data.success) && (data == null ? void 0 : data.vectorDb)) {
180
518
  const fetchedProjectId = data.projectId || projectId;
181
519
  const config = {
182
520
  projectId: fetchedProjectId,
521
+ tier: data.tier,
522
+ isActive: data.isActive,
523
+ expiresAt: data.expiresAt,
183
524
  vectorDb: {
184
- apiKey: data.vectorDb.apiKey,
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.
527
+ apiKey: data.vectorDb.apiKey || "",
185
528
  indexName: data.vectorDb.indexName || "retrivora-free",
186
529
  provider: data.vectorDb.provider || "pinecone",
187
- projectId: fetchedProjectId
530
+ projectId: fetchedProjectId,
531
+ namespace: ((_a3 = data.workspace) == null ? void 0 : _a3.namespace) || data.vectorDb.namespace || fetchedProjectId
188
532
  },
189
533
  embedding: {
190
534
  provider: ((_b = data.embedding) == null ? void 0 : _b.provider) || "universal_rest",
191
535
  model: ((_c = data.embedding) == null ? void 0 : _c.model) || "text-embedding-004",
192
- baseUrl: ((_d = data.embedding) == null ? void 0 : _d.baseUrl) || "https://llm.retrivora.com/api/v1",
536
+ // Route through www.retrivora.com proxy, not llm.retrivora.com directly.
537
+ baseUrl: ((_d = data.embedding) == null ? void 0 : _d.baseUrl) || LLM_PROXY_BASE_URL,
193
538
  apiKey: ((_e = data.embedding) == null ? void 0 : _e.apiKey) || licenseKey || "",
194
539
  profile: ((_f = data.embedding) == null ? void 0 : _f.profile) || "litellm"
195
540
  },
196
541
  llm: {
197
542
  provider: ((_g2 = data.llm) == null ? void 0 : _g2.provider) || "universal_rest",
198
543
  model: ((_h = data.llm) == null ? void 0 : _h.model) || "llama-3.1-8b-instant",
199
- baseUrl: ((_i = data.llm) == null ? void 0 : _i.baseUrl) || "https://llm.retrivora.com/api/v1",
544
+ // Route through www.retrivora.com proxy, not llm.retrivora.com directly.
545
+ baseUrl: ((_i = data.llm) == null ? void 0 : _i.baseUrl) || LLM_PROXY_BASE_URL,
200
546
  apiKey: ((_j = data.llm) == null ? void 0 : _j.apiKey) || licenseKey || "",
201
547
  profile: ((_k = data.llm) == null ? void 0 : _k.profile) || "litellm"
202
- }
548
+ },
549
+ workspace: data.workspace || {
550
+ namespace: fetchedProjectId,
551
+ indexName: data.vectorDb.indexName || "retrivora-free"
552
+ },
553
+ projectSettings: normalizeProjectSettings(
554
+ fetchedProjectId,
555
+ data.projectSettings || data.settings
556
+ )
203
557
  };
204
558
  this.cache.set(cacheKey, { config, cachedAt: now });
205
559
  return config;
@@ -317,19 +671,26 @@ var init_PineconeProvider = __esm({
317
671
  })();
318
672
  const projectId = process.env.RAG_PROJECT_ID || process.env.NEXT_PUBLIC_RAG_PROJECT_ID || jwtProjectId || this.projectId || "default";
319
673
  const remoteConfig = await ConfigFetcher.fetchRemoteVectorConfig(projectId, licenseKey);
320
- if (remoteConfig == null ? void 0 : remoteConfig.apiKey) {
321
- key = remoteConfig.apiKey;
322
- this.apiKey = key;
674
+ if (remoteConfig) {
675
+ if (remoteConfig.apiKey) {
676
+ key = remoteConfig.apiKey;
677
+ this.apiKey = key;
678
+ }
323
679
  if (remoteConfig.indexName) {
324
680
  this.indexName = remoteConfig.indexName;
325
681
  }
326
682
  if (remoteConfig.projectId) {
327
683
  this.projectId = remoteConfig.projectId;
328
684
  }
685
+ if (remoteConfig.namespace) {
686
+ this.namespace = remoteConfig.namespace;
687
+ }
329
688
  }
330
689
  }
331
690
  if (!key) {
332
- console.warn("[PineconeProvider] Warning: No Pinecone API key available locally or remotely.");
691
+ console.warn(
692
+ "[PineconeProvider] Warning: No Pinecone API key available. Set PINECONE_API_KEY in your environment, or ensure the Retrivora Control Plane (https://www.retrivora.com) is reachable for proxy-based vector operations."
693
+ );
333
694
  return;
334
695
  }
335
696
  this.client = new Pinecone({ apiKey: key });
@@ -2778,6 +3139,7 @@ var ConfigResolver = class {
2778
3139
  options: __spreadValues(__spreadValues({}, envConfig.embedding.options || {}), hostConfig.embedding.options || {})
2779
3140
  }) : envConfig.embedding,
2780
3141
  ui: hostConfig.ui ? mergeDefined(envConfig.ui, hostConfig.ui) : envConfig.ui,
3142
+ projectSettings: hostConfig.projectSettings || envConfig.projectSettings,
2781
3143
  rag: hostConfig.rag ? __spreadValues(__spreadValues({}, envConfig.rag), hostConfig.rag) : envConfig.rag,
2782
3144
  telemetry: hostConfig.telemetry ? __spreadValues(__spreadValues({}, envConfig.telemetry), hostConfig.telemetry) : envConfig.telemetry
2783
3145
  });
@@ -4719,149 +5081,8 @@ var ConfigValidator = class {
4719
5081
  }
4720
5082
  };
4721
5083
 
4722
- // package.json
4723
- var package_default = {
4724
- name: "@retrivora-ai/rag-engine",
4725
- version: "2.3.4",
4726
- description: "Retrivora AI is a plug-and-play AI engine for RAG chat experiences \u2014 generic vector DB + LLM provider, embeddable or standalone.",
4727
- author: "Abhinav Alkuchi",
4728
- license: "UNLICENSED",
4729
- keywords: [
4730
- "rag",
4731
- "retrieval-augmented-generation",
4732
- "chatbot",
4733
- "vector-database",
4734
- "pinecone",
4735
- "pgvector",
4736
- "postgresql",
4737
- "milvus",
4738
- "qdrant",
4739
- "chromadb",
4740
- "redis",
4741
- "weaviate",
4742
- "mongodb",
4743
- "openai",
4744
- "anthropic",
4745
- "ollama",
4746
- "nextjs",
4747
- "react",
4748
- "ai",
4749
- "llm",
4750
- "embeddings"
4751
- ],
4752
- main: "dist/index.js",
4753
- module: "dist/index.mjs",
4754
- types: "dist/index.d.ts",
4755
- exports: {
4756
- ".": {
4757
- types: "./dist/index.d.ts",
4758
- require: "./dist/index.js",
4759
- import: "./dist/index.mjs"
4760
- },
4761
- "./style.css": "./dist/index.css",
4762
- "./index.css": "./dist/index.css",
4763
- "./styles.css": "./dist/index.css",
4764
- "./handlers": {
4765
- types: "./dist/handlers/index.d.ts",
4766
- require: "./dist/handlers/index.js",
4767
- import: "./dist/handlers/index.mjs"
4768
- },
4769
- "./server": {
4770
- types: "./dist/server.d.ts",
4771
- require: "./dist/server.js",
4772
- import: "./dist/server.mjs"
4773
- }
4774
- },
4775
- browser: {
4776
- child_process: false,
4777
- fs: false,
4778
- net: false,
4779
- tls: false,
4780
- crypto: false,
4781
- os: false,
4782
- path: false,
4783
- stream: false,
4784
- http: false,
4785
- https: false,
4786
- zlib: false,
4787
- mongodb: false,
4788
- pg: false,
4789
- "pdf-parse": false,
4790
- mammoth: false
4791
- },
4792
- files: [
4793
- "dist",
4794
- "src",
4795
- ".env.example",
4796
- "README.md",
4797
- "FREE_TIER_ARCHITECTURE.md"
4798
- ],
4799
- scripts: {
4800
- dev: "npx @tailwindcss/cli -i src/tailwind.css -o src/index.css && tsup src/index.ts src/handlers/index.ts src/server.ts --format cjs,esm --watch --tsconfig tsconfig.build.json --external react,react-dom,next,mongodb,pg,openai,@anthropic-ai/sdk,@pinecone-database/pinecone,axios,lucide-react,mammoth,pdf-parse,xlsx,react-markdown,remark-gfm,next-themes,langchain,@langchain/core,@langchain/openai,llamaindex --inject-style",
4801
- build: "npm run build:pkg",
4802
- "build:pkg": "npx @tailwindcss/cli -i src/tailwind.css -o src/index.css && tsup src/index.ts src/handlers/index.ts src/server.ts --format cjs,esm --dts --clean --no-splitting --tsconfig tsconfig.build.json --external react,react-dom,next,mongodb,pg,openai,@anthropic-ai/sdk,@pinecone-database/pinecone,axios,lucide-react,mammoth,pdf-parse,xlsx,react-markdown,remark-gfm,next-themes,langchain,@langchain/core,@langchain/openai,llamaindex --inject-style && npx @tailwindcss/cli -i src/tailwind.css -o dist/index.css",
4803
- lint: "eslint",
4804
- typecheck: "tsc --noEmit -p tsconfig.build.json",
4805
- clean: "rm -rf dist"
4806
- },
4807
- peerDependencies: {
4808
- next: ">=15.0.0",
4809
- react: ">=18.0.0",
4810
- "react-dom": ">=18.0.0"
4811
- },
4812
- peerDependenciesMeta: {
4813
- next: {
4814
- optional: true
4815
- }
4816
- },
4817
- dependencies: {
4818
- "@anthropic-ai/sdk": "^0.95.1",
4819
- "@google/genai": "^0.8.0",
4820
- "@google/generative-ai": "^0.24.1",
4821
- "@pinecone-database/pinecone": "^7.2.0",
4822
- "@types/papaparse": "^5.5.2",
4823
- axios: "^1.15.0",
4824
- "lucide-react": "^1.8.0",
4825
- "next-themes": "^0.4.6",
4826
- openai: "^6.34.0",
4827
- papaparse: "^5.5.3",
4828
- "react-is": "^18.3.1",
4829
- "react-markdown": "^10.1.0",
4830
- recharts: "^3.8.1",
4831
- "remark-gfm": "^4.0.1",
4832
- xlsx: "^0.18.5"
4833
- },
4834
- optionalDependencies: {
4835
- "@langchain/core": "^1.1.42",
4836
- "@langchain/openai": "^1.4.5",
4837
- langchain: "^1.3.5",
4838
- llamaindex: "^0.11.9",
4839
- mammoth: "^1.8.0",
4840
- mongodb: "^7.1.1",
4841
- "pdf-parse": "^1.1.1",
4842
- pg: "^8.20.0"
4843
- },
4844
- devDependencies: {
4845
- "@tailwindcss/cli": "^4",
4846
- "@tailwindcss/postcss": "^4",
4847
- "@types/estree": "^1.0.9",
4848
- "@types/node": "^20",
4849
- "@types/pdf-parse": "^1.1.5",
4850
- "@types/pg": "^8.20.0",
4851
- "@types/react": "^19.2.14",
4852
- "@types/react-dom": "^19.2.3",
4853
- dotenv: "^17.4.2",
4854
- eslint: "^9",
4855
- "eslint-config-next": "16.2.4",
4856
- next: "16.2.10",
4857
- tailwindcss: "^4",
4858
- tsup: "^8.5.1",
4859
- typescript: "^5"
4860
- }
4861
- };
4862
-
4863
- // src/version.ts
4864
- var SDK_VERSION = package_default.version || "2.1.3";
5084
+ // src/core/Pipeline.ts
5085
+ init_version();
4865
5086
 
4866
5087
  // src/rag/DocumentChunker.ts
4867
5088
  var DocumentChunker = class {
@@ -10097,6 +10318,11 @@ var VectorPlugin = class {
10097
10318
  }
10098
10319
  };
10099
10320
 
10321
+ // src/server.ts
10322
+ init_version();
10323
+ init_ConfigFetcher();
10324
+ init_ProjectSettings();
10325
+
10100
10326
  // src/config/ConfigBuilder.ts
10101
10327
  var ConfigBuilder = class {
10102
10328
  /**
@@ -10843,6 +11069,7 @@ var DatabaseStorage = class {
10843
11069
  };
10844
11070
 
10845
11071
  // src/handlers/index.ts
11072
+ init_version();
10846
11073
  async function checkAuth(req, onAuthorize) {
10847
11074
  if (!onAuthorize) return null;
10848
11075
  try {
@@ -10952,7 +11179,7 @@ function resolveLicenseKey(req, config, bodyLicenseKey) {
10952
11179
  function enforceLicense(req, config, bodyLicenseKey) {
10953
11180
  const rawKey = resolveLicenseKey(req, config, bodyLicenseKey);
10954
11181
  const licenseKey = (rawKey || "").trim().replace(/^["']|["']$/g, "").trim();
10955
- const projectId = config.projectId || "my-rag-app";
11182
+ const projectId = config.projectId || "";
10956
11183
  try {
10957
11184
  const payload = LicenseVerifier.verify(licenseKey, projectId);
10958
11185
  return { ok: true, payload };
@@ -10974,6 +11201,35 @@ function enforceLicense(req, config, bodyLicenseKey) {
10974
11201
  };
10975
11202
  }
10976
11203
  }
11204
+ function getAllowedNamespaces(projectId) {
11205
+ const trimmed = projectId.trim();
11206
+ const withoutPrefix = trimmed.startsWith("retrivora-") ? trimmed.replace(/^retrivora-/, "") : trimmed;
11207
+ return new Set([
11208
+ trimmed,
11209
+ withoutPrefix,
11210
+ `retrivora-${withoutPrefix}`
11211
+ ].filter(Boolean));
11212
+ }
11213
+ function resolveLicensedNamespace(payload, requestedNamespace) {
11214
+ const allowed = getAllowedNamespaces(payload.projectId);
11215
+ const requested = requestedNamespace == null ? void 0 : requestedNamespace.trim();
11216
+ if (requested && !allowed.has(requested)) {
11217
+ return {
11218
+ ok: false,
11219
+ response: new Response(JSON.stringify({
11220
+ error: {
11221
+ code: "NAMESPACE_FORBIDDEN",
11222
+ message: "Requested namespace is not authorized for this license."
11223
+ }
11224
+ }), {
11225
+ status: 403,
11226
+ headers: { "Content-Type": "application/json" }
11227
+ })
11228
+ };
11229
+ }
11230
+ const defaultNamespace = payload.projectId.startsWith("retrivora-") ? payload.projectId : `retrivora-${payload.projectId}`;
11231
+ return { ok: true, namespace: requested || defaultNamespace };
11232
+ }
10977
11233
  var MAX_MESSAGE_LENGTH = 8e3;
10978
11234
  function sanitizeInput(raw) {
10979
11235
  const stripped = raw.replace(/[\u0000-\u0008\u000B\u000C\u000E-\u001F\u007F-\u009F]/g, "");
@@ -11134,6 +11390,8 @@ function createChatHandler(configOrPlugin, options) {
11134
11390
  }
11135
11391
  const history = bodyObj.history || (Array.isArray(bodyObj.messages) ? bodyObj.messages.slice(0, -1) : []);
11136
11392
  const { namespace, sessionId = "default", messageId, userMessageId } = bodyObj;
11393
+ const namespaceCheck = resolveLicensedNamespace(licenseCheck.payload, namespace);
11394
+ if (!namespaceCheck.ok) return namespaceCheck.response;
11137
11395
  const sanitized = sanitizeInput(rawMessage != null ? rawMessage : "");
11138
11396
  if (!sanitized.ok) {
11139
11397
  return NextResponse.json({ error: { code: "INVALID_INPUT", message: sanitized.error } }, { status: 400 });
@@ -11145,7 +11403,7 @@ function createChatHandler(configOrPlugin, options) {
11145
11403
  role: "user",
11146
11404
  content: message
11147
11405
  }).catch((err) => console.warn("[createChatHandler] Failed to save user message:", err));
11148
- const result = await plugin.chat(message, history, namespace);
11406
+ const result = await plugin.chat(message, history, namespaceCheck.namespace);
11149
11407
  const assistantMsgId = messageId || `assistant_${Date.now()}_${Math.random().toString(36).slice(2, 6)}`;
11150
11408
  await storage.saveMessage(sessionId, {
11151
11409
  id: assistantMsgId,
@@ -11226,6 +11484,8 @@ function createStreamHandler(configOrPlugin, options) {
11226
11484
  }
11227
11485
  const history = bodyObj.history || (Array.isArray(bodyObj.messages) ? bodyObj.messages.slice(0, -1) : []);
11228
11486
  const { namespace, sessionId = "default", messageId, userMessageId } = bodyObj;
11487
+ const namespaceCheck = resolveLicensedNamespace(licenseCheck.payload, namespace);
11488
+ if (!namespaceCheck.ok) return namespaceCheck.response;
11229
11489
  const sanitized = sanitizeInput(rawMessage != null ? rawMessage : "");
11230
11490
  if (!sanitized.ok) {
11231
11491
  return new Response(
@@ -11255,7 +11515,7 @@ function createStreamHandler(configOrPlugin, options) {
11255
11515
  }
11256
11516
  };
11257
11517
  try {
11258
- const pipelineStream = plugin.chatStream(message, history, namespace);
11518
+ const pipelineStream = plugin.chatStream(message, history, namespaceCheck.namespace);
11259
11519
  let fullReply = "";
11260
11520
  try {
11261
11521
  for (var iter = __forAwait(pipelineStream), more, temp, error; more = !(temp = await iter.next()).done; more = false) {
@@ -11361,6 +11621,8 @@ function createIngestHandler(configOrPlugin, options) {
11361
11621
  if (!Array.isArray(documents) || documents.length === 0) {
11362
11622
  return NextResponse.json({ error: "documents array is required" }, { status: 400 });
11363
11623
  }
11624
+ const namespaceCheck = resolveLicensedNamespace(licenseCheck.payload, namespace);
11625
+ if (!namespaceCheck.ok) return namespaceCheck.response;
11364
11626
  if (isFreeTier(licenseCheck.payload.tier)) {
11365
11627
  const totalIncomingBytes = documents.reduce(
11366
11628
  (sum, d) => sum + Buffer.byteLength(d.content || "", "utf8"),
@@ -11382,7 +11644,7 @@ function createIngestHandler(configOrPlugin, options) {
11382
11644
  );
11383
11645
  }
11384
11646
  }
11385
- const results = await plugin.ingest(documents, namespace);
11647
+ const results = await plugin.ingest(documents, namespaceCheck.namespace);
11386
11648
  reportTelemetry(req, plugin, "DOCUMENT_INGESTION", "success", `Ingested ${documents.length} document(s)`);
11387
11649
  return NextResponse.json({ results });
11388
11650
  } catch (err) {
@@ -11428,7 +11690,7 @@ function createLicenseHandler(configOrPlugin, options) {
11428
11690
  const config = plugin.getConfig();
11429
11691
  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 || "";
11430
11692
  const licenseKey = (rawKey || "").trim().replace(/^["']|["']$/g, "").trim();
11431
- const projectId = (body == null ? void 0 : body.projectId) || config.projectId || "my-rag-app";
11693
+ const projectId = (body == null ? void 0 : body.projectId) || config.projectId || "";
11432
11694
  const payload = LicenseVerifier.verify(licenseKey, projectId);
11433
11695
  return NextResponse.json({
11434
11696
  valid: true,
@@ -11470,6 +11732,8 @@ function createUploadHandler(configOrPlugin, options) {
11470
11732
  const namespace = formData.get("namespace") || void 0;
11471
11733
  const dimensionRaw = formData.get("dimension");
11472
11734
  const dimension = dimensionRaw ? parseInt(dimensionRaw, 10) : void 0;
11735
+ const namespaceCheck = resolveLicensedNamespace(licenseCheck.payload, namespace);
11736
+ if (!namespaceCheck.ok) return namespaceCheck.response;
11473
11737
  if (!files || files.length === 0) {
11474
11738
  return NextResponse.json({ error: "No files provided" }, { status: 400 });
11475
11739
  }
@@ -11586,7 +11850,7 @@ function createUploadHandler(configOrPlugin, options) {
11586
11850
  });
11587
11851
  }
11588
11852
  }
11589
- const results = await plugin.ingest(documents, namespace);
11853
+ const results = await plugin.ingest(documents, namespaceCheck.namespace);
11590
11854
  reportTelemetry(req, plugin, "DOCUMENT_INGESTION", "success", `Uploaded & ingested ${files.length} file(s)`);
11591
11855
  return NextResponse.json({ message: "Upload successful", results });
11592
11856
  } catch (err) {
@@ -11605,6 +11869,7 @@ function createSuggestionsHandler(configOrPlugin, options) {
11605
11869
  const config = plugin.getConfig();
11606
11870
  const licenseCheck = enforceLicense(req, config);
11607
11871
  if (!licenseCheck.ok) return licenseCheck.response;
11872
+ let effectiveLicensePayload = licenseCheck.payload;
11608
11873
  try {
11609
11874
  let query = "";
11610
11875
  let namespace = void 0;
@@ -11617,6 +11882,7 @@ function createSuggestionsHandler(configOrPlugin, options) {
11617
11882
  if (bodyLicenseKey) {
11618
11883
  const recheck = enforceLicense(req, config, bodyLicenseKey);
11619
11884
  if (!recheck.ok) return recheck.response;
11885
+ effectiveLicensePayload = recheck.payload;
11620
11886
  }
11621
11887
  } else {
11622
11888
  const url = new URL(req.url);
@@ -11626,7 +11892,9 @@ function createSuggestionsHandler(configOrPlugin, options) {
11626
11892
  if (!query || typeof query !== "string" || !query.trim()) {
11627
11893
  return NextResponse.json({ suggestions: [] });
11628
11894
  }
11629
- const suggestions = await plugin.getSuggestions(query, namespace);
11895
+ const namespaceCheck = resolveLicensedNamespace(effectiveLicensePayload, namespace);
11896
+ if (!namespaceCheck.ok) return namespaceCheck.response;
11897
+ const suggestions = await plugin.getSuggestions(query, namespaceCheck.namespace);
11630
11898
  reportTelemetry(req, plugin, "AUTO_SUGGESTIONS", "success", `Fetched ${suggestions.length} suggestions for: ${query.slice(0, 30)}`);
11631
11899
  return NextResponse.json({ suggestions });
11632
11900
  } catch (err) {
@@ -11843,6 +12111,15 @@ function createRagHandler(configOrPlugin, options) {
11843
12111
  }
11844
12112
 
11845
12113
  // src/core/LicenseValidator.ts
12114
+ init_version();
12115
+ function canUseLocalValidationFallback(baseUrl, status) {
12116
+ const explicitFallback = typeof process !== "undefined" && process.env.RETRIVORA_ALLOW_LOCAL_LICENSE_FALLBACK === "true";
12117
+ const isLocalSdkRoute = baseUrl.startsWith("/api/retrivora") || baseUrl.includes("/api/retrivora");
12118
+ if (status !== void 0) {
12119
+ return status === 404 && (explicitFallback || isLocalSdkRoute);
12120
+ }
12121
+ return explicitFallback || isLocalSdkRoute;
12122
+ }
11846
12123
  var _LicenseValidator = class _LicenseValidator {
11847
12124
  // 5-minute TTL for successful validation only
11848
12125
  constructor() {
@@ -11917,7 +12194,7 @@ var _LicenseValidator = class _LicenseValidator {
11917
12194
  this.cache.delete(effectiveLicenseKey);
11918
12195
  }
11919
12196
  }
11920
- const base = retrivoraApiBase || (typeof process !== "undefined" ? process.env.NEXT_PUBLIC_RETRIVORA_API_BASE || process.env.RETRIVORA_API_BASE : "") || "/api/retrivora";
12197
+ const base = retrivoraApiBase || (typeof process !== "undefined" ? process.env.NEXT_PUBLIC_RETRIVORA_API_BASE || process.env.RETRIVORA_API_BASE : "") || "https://www.retrivora.com/api";
11921
12198
  const validateUrl = `${base.replace(/\/$/, "")}/v1/license/validate`;
11922
12199
  let res = null;
11923
12200
  try {
@@ -11939,7 +12216,10 @@ var _LicenseValidator = class _LicenseValidator {
11939
12216
  });
11940
12217
  } catch (err) {
11941
12218
  try {
11942
- const payload = LicenseVerifier.verify(effectiveLicenseKey, projectId || "my-rag-app");
12219
+ if (!canUseLocalValidationFallback(base)) {
12220
+ throw err;
12221
+ }
12222
+ const payload = LicenseVerifier.verify(effectiveLicenseKey, projectId || "");
11943
12223
  const fallbackResp = {
11944
12224
  valid: true,
11945
12225
  licenseStatus: "ACTIVE",
@@ -11956,9 +12236,9 @@ var _LicenseValidator = class _LicenseValidator {
11956
12236
  throw new LicenseValidationError(`License validation request failed: ${(err == null ? void 0 : err.message) || "Network error"}`);
11957
12237
  }
11958
12238
  }
11959
- if (res && !res.ok) {
12239
+ if (res && !res.ok && canUseLocalValidationFallback(base, res.status)) {
11960
12240
  try {
11961
- const payload = LicenseVerifier.verify(effectiveLicenseKey, projectId || "my-rag-app");
12241
+ const payload = LicenseVerifier.verify(effectiveLicenseKey, projectId || "");
11962
12242
  const fallbackResp = {
11963
12243
  valid: true,
11964
12244
  licenseStatus: "ACTIVE",
@@ -12011,6 +12291,7 @@ export {
12011
12291
  ChartRendererStrategy,
12012
12292
  ChromaDBProvider,
12013
12293
  ConfigBuilder,
12294
+ ConfigFetcher,
12014
12295
  ConfigResolver,
12015
12296
  ConfigValidator,
12016
12297
  ConfigurationException,
@@ -12066,6 +12347,7 @@ export {
12066
12347
  VisualizationDecisionEngine,
12067
12348
  WeaviateProvider,
12068
12349
  createChatHandler,
12350
+ createDefaultProjectSettings,
12069
12351
  createFeedbackHandler,
12070
12352
  createFromPreset,
12071
12353
  createHealthHandler,
@@ -12077,6 +12359,8 @@ export {
12077
12359
  createUploadHandler,
12078
12360
  decideVisualization,
12079
12361
  getRagConfig,
12362
+ normalizeProjectSettings,
12363
+ projectSettingsToUiConfig,
12080
12364
  sseErrorFrame,
12081
12365
  sseFrame,
12082
12366
  sseMetaFrame,