@retrivora-ai/rag-engine 2.6.3 → 2.6.4

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,219 +0,0 @@
1
- import {
2
- LicenseValidationError,
3
- LicenseVerifier,
4
- SDKVersionUnsupportedError
5
- } from "./chunk-XYBKDJDW.mjs";
6
- import {
7
- SDK_VERSION
8
- } from "./chunk-XP6NJMX4.mjs";
9
- import {
10
- __spreadValues
11
- } from "./chunk-UT6SZZEC.mjs";
12
-
13
- // src/core/LicenseValidator.ts
14
- function canUseLocalValidationFallback(baseUrl, status) {
15
- const explicitFallback = typeof process !== "undefined" && process.env.RETRIVORA_ALLOW_LOCAL_LICENSE_FALLBACK === "true";
16
- const isLocalSdkRoute = baseUrl.startsWith("/api/retrivora") || baseUrl.includes("/api/retrivora");
17
- if (status !== void 0) {
18
- return status === 404 && (explicitFallback || isLocalSdkRoute);
19
- }
20
- return explicitFallback || isLocalSdkRoute;
21
- }
22
- var _LicenseValidator = class _LicenseValidator {
23
- // 5-minute TTL for successful validation only
24
- constructor() {
25
- this.cache = /* @__PURE__ */ new Map();
26
- /** In-flight deduplication: concurrent calls for same key share one network request */
27
- this.inflight = /* @__PURE__ */ new Map();
28
- }
29
- /** @returns Singleton instance of the validator (shared cache across all consumers). */
30
- static getInstance() {
31
- if (!_LicenseValidator.instance) {
32
- _LicenseValidator.instance = new _LicenseValidator();
33
- }
34
- return _LicenseValidator.instance;
35
- }
36
- /**
37
- * Purge entries from the local success cache.
38
- *
39
- * @param licenseKey - Optional. If provided, only that key's cache entry is
40
- * removed. If omitted the entire cache is cleared.
41
- * Callers use this after any 401/403 to ensure the next
42
- * validate() call re-validates against the server.
43
- */
44
- purgeCache(licenseKey) {
45
- if (licenseKey) {
46
- this.cache.delete(licenseKey);
47
- } else {
48
- this.cache.clear();
49
- }
50
- }
51
- /**
52
- * Primary validation entry-point for UI / hook consumers.
53
- *
54
- * Resolves the license key, consults the local success cache, performs a
55
- * server POST for authoritative status, and falls back to `LicenseVerifier.verifyAsync()`
56
- * if the server can't be reached.
57
- *
58
- * @throws LicenseValidationError - When no key is provided OR both the
59
- * server call AND the fallback report an invalid/expired key.
60
- * @throws SDKVersionUnsupportedError - When server reports forceUpgrade=true.
61
- * @returns A `LicenseValidationResponse` that the UI can use to enable or
62
- * lock the chat widget.
63
- */
64
- async validate(request) {
65
- const {
66
- licenseKey,
67
- projectId,
68
- sdkVersion = SDK_VERSION,
69
- sdk = "@retrivora-ai/rag-engine",
70
- platform = typeof window !== "undefined" ? "browser" : "node",
71
- retrivoraApiBase,
72
- headers: customHeaders
73
- } = request;
74
- const effectiveProjectId = projectId || (typeof process !== "undefined" ? process.env.NEXT_PUBLIC_RETRIVORA_PROJECT_ID || process.env.RETRIVORA_PROJECT_ID : "") || "";
75
- const getHeader = (name) => {
76
- if (!customHeaders) return void 0;
77
- const target = name.toLowerCase();
78
- for (const [k, v] of Object.entries(customHeaders)) {
79
- if (k.toLowerCase() === target) return v;
80
- }
81
- return void 0;
82
- };
83
- const authHeader = getHeader("authorization");
84
- let authHeaderKey = "";
85
- if (authHeader && authHeader.toLowerCase().startsWith("bearer ")) {
86
- authHeaderKey = authHeader.replace(/^Bearer\s+/i, "");
87
- if (authHeaderKey) {
88
- console.warn(
89
- '[Retrivora SDK] DEPRECATION WARNING (SEC-7): Repurposing the standard "Authorization: Bearer" header to carry the license key is deprecated and will be removed in a future release. Please use the custom "x-license-key" header instead.'
90
- );
91
- }
92
- }
93
- const rawKey = licenseKey || getHeader("x-license-key") || authHeaderKey || (typeof process !== "undefined" ? process.env.NEXT_PUBLIC_RETRIVORA_LICENSE_KEY || process.env.RETRIVORA_LICENSE_KEY : "") || "";
94
- const effectiveLicenseKey = (rawKey || "").trim().replace(/^["']|["']$/g, "").trim();
95
- if (!effectiveLicenseKey) {
96
- this.purgeCache(effectiveLicenseKey);
97
- throw new LicenseValidationError("Missing RETRIVORA_LICENSE_KEY in request. Set NEXT_PUBLIC_RETRIVORA_LICENSE_KEY in your environment or pass licenseKey as a prop.");
98
- }
99
- const cached = this.cache.get(effectiveLicenseKey);
100
- if (cached) {
101
- const isFresh = Date.now() - cached.timestamp < _LicenseValidator.SUCCESS_CACHE_TTL_MS;
102
- if (isFresh && cached.response.valid && cached.response.licenseStatus === "ACTIVE" && !cached.response.forceUpgrade) {
103
- return cached.response;
104
- } else {
105
- this.cache.delete(effectiveLicenseKey);
106
- }
107
- }
108
- const existing = this.inflight.get(effectiveLicenseKey);
109
- if (existing) return existing;
110
- const inflightPromise = this._doNetworkValidate(
111
- effectiveLicenseKey,
112
- effectiveProjectId,
113
- sdkVersion,
114
- sdk,
115
- platform,
116
- retrivoraApiBase,
117
- customHeaders
118
- );
119
- this.inflight.set(effectiveLicenseKey, inflightPromise);
120
- try {
121
- return await inflightPromise;
122
- } finally {
123
- this.inflight.delete(effectiveLicenseKey);
124
- }
125
- }
126
- /** Performs the actual network request. Called once; result shared by in-flight dedup. */
127
- async _doNetworkValidate(effectiveLicenseKey, effectiveProjectId, sdkVersion, sdk, platform, retrivoraApiBase, customHeaders) {
128
- const base = retrivoraApiBase || (typeof process !== "undefined" ? process.env.NEXT_PUBLIC_RETRIVORA_API_BASE || process.env.RETRIVORA_API_BASE : "") || "https://www.retrivora.com/api";
129
- const validateUrl = `${base.replace(/\/$/, "")}/v1/license/validate`;
130
- let res = null;
131
- try {
132
- res = await fetch(validateUrl, {
133
- method: "POST",
134
- cache: "no-store",
135
- headers: __spreadValues({
136
- "Content-Type": "application/json",
137
- "x-license-key": effectiveLicenseKey,
138
- "x-sdk-version": sdkVersion
139
- }, customHeaders || {}),
140
- body: JSON.stringify({
141
- licenseKey: effectiveLicenseKey,
142
- projectId: effectiveProjectId,
143
- sdkVersion,
144
- sdk,
145
- platform
146
- })
147
- });
148
- } catch (err) {
149
- try {
150
- if (!canUseLocalValidationFallback(base)) {
151
- throw err;
152
- }
153
- const payload = await LicenseVerifier.verifyAsync(effectiveLicenseKey, effectiveProjectId);
154
- const fallbackResp = {
155
- valid: true,
156
- licenseStatus: "ACTIVE",
157
- minimumSupportedVersion: "2.1.0",
158
- latestVersion: SDK_VERSION,
159
- forceUpgrade: false,
160
- expiresAt: payload.expiresAt ? new Date(payload.expiresAt * 1e3).toISOString() : null,
161
- message: "Local license verification active."
162
- };
163
- this.cache.set(effectiveLicenseKey, { response: fallbackResp, timestamp: Date.now() });
164
- return fallbackResp;
165
- } catch (e) {
166
- this.purgeCache(effectiveLicenseKey);
167
- throw new LicenseValidationError(`License validation request failed: ${(err == null ? void 0 : err.message) || "Network error"}`);
168
- }
169
- }
170
- if (res && !res.ok && canUseLocalValidationFallback(base, res.status)) {
171
- try {
172
- const payload = await LicenseVerifier.verifyAsync(effectiveLicenseKey, effectiveProjectId);
173
- const fallbackResp = {
174
- valid: true,
175
- licenseStatus: "ACTIVE",
176
- minimumSupportedVersion: "2.1.0",
177
- latestVersion: SDK_VERSION,
178
- forceUpgrade: false,
179
- expiresAt: payload.expiresAt ? new Date(payload.expiresAt * 1e3).toISOString() : null,
180
- message: "Local license verification active."
181
- };
182
- this.cache.set(effectiveLicenseKey, { response: fallbackResp, timestamp: Date.now() });
183
- return fallbackResp;
184
- } catch (e) {
185
- }
186
- }
187
- const data = await res.json().catch(() => ({
188
- valid: false,
189
- licenseStatus: "REVOKED",
190
- minimumSupportedVersion: "2.1.0",
191
- latestVersion: SDK_VERSION,
192
- forceUpgrade: false,
193
- expiresAt: null,
194
- message: "Failed to parse license validation response."
195
- }));
196
- if (!res.ok || !data.valid || data.licenseStatus !== "ACTIVE" || data.forceUpgrade) {
197
- this.purgeCache(effectiveLicenseKey);
198
- if (data.forceUpgrade || res.status === 426) {
199
- throw new SDKVersionUnsupportedError(
200
- data.message || `This SDK version (${sdkVersion}) is no longer supported. Upgrade to version ${data.latestVersion || "2.2.6"} or later.`,
201
- data
202
- );
203
- }
204
- const errMsg = data.message || `License validation failed with status: ${data.licenseStatus}. Access denied.`;
205
- throw new LicenseValidationError(errMsg, data);
206
- }
207
- this.cache.set(effectiveLicenseKey, {
208
- response: data,
209
- timestamp: Date.now()
210
- });
211
- return data;
212
- }
213
- };
214
- _LicenseValidator.SUCCESS_CACHE_TTL_MS = 5 * 60 * 1e3;
215
- var LicenseValidator = _LicenseValidator;
216
-
217
- export {
218
- LicenseValidator
219
- };
@@ -1,334 +0,0 @@
1
- import {
2
- SDK_VERSION
3
- } from "./chunk-QUY3E6HJ.mjs";
4
- import {
5
- __spreadValues
6
- } from "./chunk-UT6SZZEC.mjs";
7
-
8
- // src/core/ProjectSettings.ts
9
- var DEFAULT_LIFECYCLE_HOOKS = [
10
- "beforeInitialize",
11
- "afterInitialize",
12
- "beforeSend",
13
- "afterResponse",
14
- "onMessage",
15
- "onCitationClick",
16
- "onFeedback",
17
- "onError",
18
- "onReconnect",
19
- "onFileUpload"
20
- ];
21
- var DEFAULT_CONVERSATION_FEATURES = [
22
- "History",
23
- "Resume",
24
- "Search",
25
- "Export",
26
- "Rename",
27
- "Delete",
28
- "Tags",
29
- "Pinned",
30
- "Unread",
31
- "Ratings"
32
- ];
33
- function createDefaultProjectSettings(projectId) {
34
- return {
35
- projectId,
36
- branding: {
37
- companyName: "Retrivora AI",
38
- botName: "Retrivora Assistant",
39
- welcomeMessage: "Hi, I can help you search your knowledge base.",
40
- primaryColor: "#6366f1",
41
- secondaryColor: "#8b5cf6",
42
- fontFamily: "Inter",
43
- borderRadius: 14,
44
- logoUrl: "",
45
- avatarUrl: "",
46
- customCss: ""
47
- },
48
- ai: {
49
- defaultModel: "llama-3.1-8b-instant",
50
- embeddingModel: "text-embedding-3-small",
51
- systemPrompt: "Answer using the connected knowledge base. Cite sources when available.",
52
- memoryEnabled: true,
53
- multiModelEnabled: true,
54
- citationsEnabled: true,
55
- fileUploadEnabled: true
56
- },
57
- auth: {
58
- mode: "public",
59
- allowedOrigins: [],
60
- requireVerifiedEmail: false,
61
- sessionTtlMinutes: 1440
62
- },
63
- widget: {
64
- position: "bottom-right",
65
- theme: "light",
66
- lazyLoad: true,
67
- autoReconnect: true,
68
- persistConversations: true,
69
- showRetrivoraBranding: false
70
- },
71
- telemetry: {
72
- enabled: true,
73
- collectBrowser: true,
74
- collectCountry: false,
75
- redactPii: true,
76
- retentionDays: 30
77
- },
78
- lifecycleHooks: DEFAULT_LIFECYCLE_HOOKS,
79
- conversationFeatures: DEFAULT_CONVERSATION_FEATURES
80
- };
81
- }
82
- function cleanString(value, fallback, maxLength = 2e3) {
83
- if (typeof value !== "string") return fallback;
84
- return value.trim().slice(0, maxLength);
85
- }
86
- function cleanBoolean(value, fallback) {
87
- return typeof value === "boolean" ? value : fallback;
88
- }
89
- function cleanNumber(value, fallback, min, max) {
90
- const num = typeof value === "number" ? value : Number(value);
91
- if (!Number.isFinite(num)) return fallback;
92
- return Math.min(Math.max(Math.round(num), min), max);
93
- }
94
- function cleanEnum(value, fallback, allowed) {
95
- return typeof value === "string" && allowed.includes(value) ? value : fallback;
96
- }
97
- function cleanStringList(value, fallback, maxItems = 20) {
98
- if (!Array.isArray(value)) return fallback;
99
- const cleaned = value.filter((item) => typeof item === "string").map((item) => item.trim()).filter(Boolean).slice(0, maxItems);
100
- return cleaned.length > 0 ? Array.from(new Set(cleaned)) : fallback;
101
- }
102
- function normalizeProjectSettings(projectId, input) {
103
- const defaults = createDefaultProjectSettings(projectId);
104
- const branding = (input == null ? void 0 : input.branding) || {};
105
- const ai = (input == null ? void 0 : input.ai) || {};
106
- const auth = (input == null ? void 0 : input.auth) || {};
107
- const widget = (input == null ? void 0 : input.widget) || {};
108
- const telemetry = (input == null ? void 0 : input.telemetry) || {};
109
- return {
110
- projectId,
111
- branding: {
112
- companyName: cleanString(branding.companyName, defaults.branding.companyName, 120),
113
- botName: cleanString(branding.botName, defaults.branding.botName, 120),
114
- welcomeMessage: cleanString(branding.welcomeMessage, defaults.branding.welcomeMessage, 500),
115
- primaryColor: cleanString(branding.primaryColor, defaults.branding.primaryColor, 32),
116
- secondaryColor: cleanString(branding.secondaryColor, defaults.branding.secondaryColor, 32),
117
- fontFamily: cleanString(branding.fontFamily, defaults.branding.fontFamily, 80),
118
- borderRadius: cleanNumber(branding.borderRadius, defaults.branding.borderRadius, 0, 32),
119
- logoUrl: cleanString(branding.logoUrl, defaults.branding.logoUrl, 500),
120
- avatarUrl: cleanString(branding.avatarUrl, defaults.branding.avatarUrl, 500),
121
- customCss: cleanString(branding.customCss, defaults.branding.customCss, 5e3)
122
- },
123
- ai: {
124
- defaultModel: cleanString(ai.defaultModel, defaults.ai.defaultModel, 120),
125
- embeddingModel: cleanString(ai.embeddingModel, defaults.ai.embeddingModel, 120),
126
- systemPrompt: cleanString(ai.systemPrompt, defaults.ai.systemPrompt, 5e3),
127
- memoryEnabled: cleanBoolean(ai.memoryEnabled, defaults.ai.memoryEnabled),
128
- multiModelEnabled: cleanBoolean(ai.multiModelEnabled, defaults.ai.multiModelEnabled),
129
- citationsEnabled: cleanBoolean(ai.citationsEnabled, defaults.ai.citationsEnabled),
130
- fileUploadEnabled: cleanBoolean(ai.fileUploadEnabled, defaults.ai.fileUploadEnabled)
131
- },
132
- auth: {
133
- mode: cleanEnum(auth.mode, defaults.auth.mode, ["public", "anonymous", "jwt", "oauth", "okta", "auth0", "supabase", "firebase", "sso", "custom_token"]),
134
- allowedOrigins: cleanStringList(auth.allowedOrigins, defaults.auth.allowedOrigins, 25),
135
- requireVerifiedEmail: cleanBoolean(auth.requireVerifiedEmail, defaults.auth.requireVerifiedEmail),
136
- sessionTtlMinutes: cleanNumber(auth.sessionTtlMinutes, defaults.auth.sessionTtlMinutes, 15, 43200)
137
- },
138
- widget: {
139
- position: cleanEnum(widget.position, defaults.widget.position, ["bottom-right", "bottom-left", "top-right", "top-left"]),
140
- theme: cleanEnum(widget.theme, defaults.widget.theme, ["light", "dark", "system"]),
141
- lazyLoad: cleanBoolean(widget.lazyLoad, defaults.widget.lazyLoad),
142
- autoReconnect: cleanBoolean(widget.autoReconnect, defaults.widget.autoReconnect),
143
- persistConversations: cleanBoolean(widget.persistConversations, defaults.widget.persistConversations),
144
- showRetrivoraBranding: cleanBoolean(widget.showRetrivoraBranding, defaults.widget.showRetrivoraBranding)
145
- },
146
- telemetry: {
147
- enabled: cleanBoolean(telemetry.enabled, defaults.telemetry.enabled),
148
- collectBrowser: cleanBoolean(telemetry.collectBrowser, defaults.telemetry.collectBrowser),
149
- collectCountry: cleanBoolean(telemetry.collectCountry, defaults.telemetry.collectCountry),
150
- redactPii: cleanBoolean(telemetry.redactPii, defaults.telemetry.redactPii),
151
- retentionDays: cleanNumber(telemetry.retentionDays, defaults.telemetry.retentionDays, 1, 365)
152
- },
153
- lifecycleHooks: cleanStringList(input == null ? void 0 : input.lifecycleHooks, defaults.lifecycleHooks, 30),
154
- conversationFeatures: cleanStringList(input == null ? void 0 : input.conversationFeatures, defaults.conversationFeatures, 30),
155
- updatedAt: input == null ? void 0 : input.updatedAt
156
- };
157
- }
158
- function projectSettingsToUiConfig(settings) {
159
- return {
160
- title: settings.branding.botName,
161
- subtitle: settings.branding.companyName,
162
- primaryColor: settings.branding.primaryColor,
163
- accentColor: settings.branding.secondaryColor,
164
- logoUrl: settings.branding.logoUrl || settings.branding.avatarUrl,
165
- welcomeMessage: settings.branding.welcomeMessage,
166
- poweredBy: settings.widget.showRetrivoraBranding ? "Retrivora AI" : "",
167
- allowUpload: settings.ai.fileUploadEnabled,
168
- showSources: settings.ai.citationsEnabled,
169
- borderRadius: settings.branding.borderRadius <= 4 ? "sm" : settings.branding.borderRadius <= 8 ? "md" : settings.branding.borderRadius <= 16 ? "xl" : "full"
170
- };
171
- }
172
-
173
- // src/core/ConfigFetcher.ts
174
- var CONTROL_PLANE_URL = "https://www.retrivora.com";
175
- var LLM_PROXY_BASE_URL = "https://llm.retrivora.com/api/v1";
176
- var ConfigFetcher = class {
177
- // 5-minute in-memory session cache
178
- /**
179
- * Fetch full project configuration (vectorDb + embedding + llm + workspace) from Retrivora Control Plane.
180
- *
181
- * The SDK calls https://www.retrivora.com/api/v1/config with the project ID and license key.
182
- * The server validates the license against the database and returns:
183
- * - validity (tier, isActive, expiresAt)
184
- * - LLM model info
185
- * - embedding model info
186
- * - Pinecone index name and workspace/namespace
187
- *
188
- * The Pinecone API key is NOT returned (server-only). The SDK uses local
189
- * PINECONE_API_KEY if available, or vector operations are handled server-side.
190
- */
191
- static async fetchRemoteConfig(projectId, licenseKey) {
192
- const cacheKey = `${projectId}:${licenseKey || ""}`;
193
- const now = Date.now();
194
- const cached = this.cache.get(cacheKey);
195
- if (cached && now - cached.cachedAt < this.TTL_MS) {
196
- return cached.config;
197
- }
198
- const existingInflight = this.inflight.get(cacheKey);
199
- if (existingInflight) {
200
- return existingInflight;
201
- }
202
- const promise = this._doFetch(projectId, licenseKey, cacheKey, now);
203
- this.inflight.set(cacheKey, promise);
204
- try {
205
- return await promise;
206
- } finally {
207
- this.inflight.delete(cacheKey);
208
- }
209
- }
210
- /** Internal: performs the actual HTTP fetch. Shared by all callers via inflight dedup. */
211
- static async _doFetch(projectId, licenseKey, cacheKey, now) {
212
- var _a, _b, _c, _d, _e, _f, _g, _h, _i, _j, _k;
213
- const controlPlaneUrls = [
214
- process.env.RETRIVORA_CONTROL_PLANE_URL,
215
- process.env.NEXT_PUBLIC_RETRIVORA_CONTROL_PLANE_URL,
216
- CONTROL_PLANE_URL
217
- ].filter((url) => {
218
- if (!url) return false;
219
- const isEnvVar = url === process.env.RETRIVORA_CONTROL_PLANE_URL || url === process.env.NEXT_PUBLIC_RETRIVORA_CONTROL_PLANE_URL;
220
- if (!isEnvVar && (url.includes("localhost") || url.includes("127.0.0.1"))) return false;
221
- return true;
222
- }).map((url) => url.replace(/\/$/, ""));
223
- for (const baseUrl of controlPlaneUrls) {
224
- try {
225
- const url = `${baseUrl}/api/v1/config?projectId=${encodeURIComponent(projectId)}`;
226
- const res = await fetch(url, {
227
- method: "GET",
228
- headers: __spreadValues(__spreadValues({
229
- "Content-Type": "application/json",
230
- "x-sdk-version": SDK_VERSION
231
- }, licenseKey ? { "x-license-key": licenseKey } : {}), projectId ? { "x-project-id": projectId } : {})
232
- });
233
- if (!res.ok) {
234
- console.warn(`[ConfigFetcher] Error text: ${await res.text()}`);
235
- }
236
- if (res.ok) {
237
- const data = await res.json();
238
- if ((data == null ? void 0 : data.success) && (data == null ? void 0 : data.vectorDb)) {
239
- const fetchedProjectId = data.projectId || projectId;
240
- const config = {
241
- projectId: fetchedProjectId,
242
- tier: data.tier,
243
- isActive: data.isActive,
244
- expiresAt: data.expiresAt,
245
- vectorDb: {
246
- // Fetch apiKey from credentials API if available, else fallback to empty
247
- apiKey: data.vectorDb.apiKey || "",
248
- indexName: data.vectorDb.indexName || "retrivora-free",
249
- provider: data.vectorDb.provider || "pinecone",
250
- projectId: fetchedProjectId,
251
- namespace: ((_a = data.workspace) == null ? void 0 : _a.namespace) || data.vectorDb.namespace || fetchedProjectId
252
- },
253
- embedding: {
254
- provider: ((_b = data.embedding) == null ? void 0 : _b.provider) || "universal_rest",
255
- model: ((_c = data.embedding) == null ? void 0 : _c.model) || "text-embedding-004",
256
- // Route through www.retrivora.com proxy, not llm.retrivora.com directly.
257
- baseUrl: ((_d = data.embedding) == null ? void 0 : _d.baseUrl) || LLM_PROXY_BASE_URL,
258
- apiKey: ((_e = data.embedding) == null ? void 0 : _e.apiKey) || licenseKey || "",
259
- profile: ((_f = data.embedding) == null ? void 0 : _f.profile) || "litellm"
260
- },
261
- llm: {
262
- provider: ((_g = data.llm) == null ? void 0 : _g.provider) || "universal_rest",
263
- model: ((_h = data.llm) == null ? void 0 : _h.model) || "llama-3.1-8b-instant",
264
- // Route through www.retrivora.com proxy, not llm.retrivora.com directly.
265
- baseUrl: ((_i = data.llm) == null ? void 0 : _i.baseUrl) || LLM_PROXY_BASE_URL,
266
- apiKey: ((_j = data.llm) == null ? void 0 : _j.apiKey) || licenseKey || "",
267
- profile: ((_k = data.llm) == null ? void 0 : _k.profile) || "litellm"
268
- },
269
- workspace: data.workspace || {
270
- namespace: fetchedProjectId,
271
- indexName: data.vectorDb.indexName || "retrivora-free"
272
- },
273
- projectSettings: normalizeProjectSettings(
274
- fetchedProjectId,
275
- data.projectSettings || data.settings
276
- )
277
- };
278
- if (licenseKey) {
279
- try {
280
- const credUrl = `${baseUrl}/api/v1/credentials`;
281
- const credRes = await fetch(credUrl, {
282
- method: "POST",
283
- headers: __spreadValues(__spreadValues({
284
- "Content-Type": "application/json"
285
- }, licenseKey ? { "x-license-key": licenseKey } : {}), fetchedProjectId ? { "x-project-id": fetchedProjectId } : {}),
286
- body: JSON.stringify({ licenseKey, projectId: fetchedProjectId })
287
- });
288
- if (credRes.ok) {
289
- const credData = await credRes.json();
290
- if ((credData == null ? void 0 : credData.success) && (credData == null ? void 0 : credData.credentials)) {
291
- if (credData.credentials.pineconeApiKey && !config.vectorDb.apiKey) {
292
- config.vectorDb.apiKey = credData.credentials.pineconeApiKey;
293
- }
294
- if (credData.credentials.litellmApiKey) {
295
- config.llm.apiKey = credData.credentials.litellmApiKey;
296
- config.embedding.apiKey = credData.credentials.litellmApiKey;
297
- }
298
- }
299
- }
300
- } catch (e) {
301
- console.warn("[ConfigFetcher] Failed to fetch credentials:", e);
302
- }
303
- }
304
- this.cache.set(cacheKey, { config, cachedAt: now });
305
- return config;
306
- }
307
- }
308
- } catch (err) {
309
- console.warn(
310
- `[ConfigFetcher] Failed to fetch config from ${baseUrl}:`,
311
- err instanceof Error ? err.message : String(err)
312
- );
313
- }
314
- }
315
- return null;
316
- }
317
- /** Convenience: fetch only vector DB config (backwards compat). */
318
- static async fetchRemoteVectorConfig(projectId, licenseKey) {
319
- var _a;
320
- const config = await this.fetchRemoteConfig(projectId, licenseKey);
321
- return (_a = config == null ? void 0 : config.vectorDb) != null ? _a : null;
322
- }
323
- };
324
- ConfigFetcher.cache = /* @__PURE__ */ new Map();
325
- /** In-flight deduplication: concurrent callers for the same key share one network request */
326
- ConfigFetcher.inflight = /* @__PURE__ */ new Map();
327
- ConfigFetcher.TTL_MS = 5 * 60 * 1e3;
328
-
329
- export {
330
- createDefaultProjectSettings,
331
- normalizeProjectSettings,
332
- projectSettingsToUiConfig,
333
- ConfigFetcher
334
- };