@savvagent/sdk 1.0.0 → 1.0.1

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/index.js CHANGED
@@ -149,15 +149,23 @@ var TelemetryService = class {
149
149
  }
150
150
  /**
151
151
  * Send evaluation events to backend
152
+ * Per SDK Developer Guide: POST /api/telemetry/evaluations with { "evaluations": [...] }
152
153
  */
153
154
  async sendEvaluations(events) {
155
+ const evaluations = events.map((e) => ({
156
+ flag_key: e.flagKey,
157
+ result: e.result,
158
+ user_id: e.context?.user_id,
159
+ context: e.context,
160
+ timestamp: Math.floor(new Date(e.timestamp).getTime() / 1e3)
161
+ }));
154
162
  const response = await fetch(`${this.baseUrl}/api/telemetry/evaluations`, {
155
163
  method: "POST",
156
164
  headers: {
157
165
  "Content-Type": "application/json",
158
166
  Authorization: `Bearer ${this.apiKey}`
159
167
  },
160
- body: JSON.stringify({ events })
168
+ body: JSON.stringify({ evaluations })
161
169
  });
162
170
  if (!response.ok) {
163
171
  throw new Error(`Failed to send evaluations: ${response.status}`);
@@ -165,15 +173,25 @@ var TelemetryService = class {
165
173
  }
166
174
  /**
167
175
  * Send error events to backend
176
+ * Per SDK Developer Guide: POST /api/telemetry/errors with { "errors": [...] }
168
177
  */
169
178
  async sendErrors(events) {
179
+ const errors = events.map((e) => ({
180
+ flag_key: e.flagKey,
181
+ flag_enabled: e.flagEnabled,
182
+ error_type: e.errorType,
183
+ error_message: e.errorMessage,
184
+ stack_trace: e.stackTrace,
185
+ context: e.context,
186
+ timestamp: Math.floor(new Date(e.timestamp).getTime() / 1e3)
187
+ }));
170
188
  const response = await fetch(`${this.baseUrl}/api/telemetry/errors`, {
171
189
  method: "POST",
172
190
  headers: {
173
191
  "Content-Type": "application/json",
174
192
  Authorization: `Bearer ${this.apiKey}`
175
193
  },
176
- body: JSON.stringify({ events })
194
+ body: JSON.stringify({ errors })
177
195
  });
178
196
  if (!response.ok) {
179
197
  throw new Error(`Failed to send errors: ${response.status}`);
@@ -198,88 +216,144 @@ var TelemetryService = class {
198
216
  };
199
217
 
200
218
  // src/realtime.ts
219
+ var import_fetch_event_source = require("@microsoft/fetch-event-source");
220
+ var FatalError = class extends Error {
221
+ constructor(message) {
222
+ super(message);
223
+ this.name = "FatalError";
224
+ }
225
+ };
226
+ var RetriableError = class extends Error {
227
+ constructor(message) {
228
+ super(message);
229
+ this.name = "RetriableError";
230
+ }
231
+ };
201
232
  var RealtimeService = class {
233
+ // Track auth failures to prevent reconnection attempts
202
234
  constructor(baseUrl, apiKey, onConnectionChange) {
203
- this.eventSource = null;
235
+ this.abortController = null;
204
236
  this.reconnectAttempts = 0;
205
237
  this.maxReconnectAttempts = 10;
206
- // Increased from 5 to 10
207
238
  this.reconnectDelay = 1e3;
208
239
  // Start with 1 second
209
240
  this.maxReconnectDelay = 3e4;
210
241
  // Cap at 30 seconds
211
242
  this.listeners = /* @__PURE__ */ new Map();
243
+ this.connected = false;
244
+ this.authFailed = false;
212
245
  this.baseUrl = baseUrl;
213
246
  this.apiKey = apiKey;
214
247
  this.onConnectionChange = onConnectionChange;
215
248
  }
216
249
  /**
217
- * Connect to SSE stream
250
+ * Connect to SSE stream using header-based authentication
251
+ * Per SDK Developer Guide: "Never pass API keys as query parameters"
218
252
  */
219
253
  connect() {
220
- if (this.eventSource) {
254
+ if (this.abortController) {
221
255
  return;
222
256
  }
223
- const url = `${this.baseUrl}/api/flags/stream?apiKey=${encodeURIComponent(this.apiKey)}`;
224
- try {
225
- this.eventSource = new EventSource(url);
226
- this.eventSource.onopen = () => {
227
- console.log("[Savvagent] Real-time connection established");
228
- this.reconnectAttempts = 0;
229
- this.reconnectDelay = 1e3;
230
- this.onConnectionChange?.call(null, true);
231
- };
232
- this.eventSource.onerror = (error) => {
233
- console.error("[Savvagent] SSE connection error:", error);
234
- this.handleDisconnect();
235
- };
236
- this.eventSource.addEventListener("heartbeat", () => {
237
- });
238
- this.eventSource.addEventListener("flag.updated", (e) => {
239
- this.handleMessage("flag.updated", e);
240
- });
241
- this.eventSource.addEventListener("flag.deleted", (e) => {
242
- this.handleMessage("flag.deleted", e);
243
- });
244
- this.eventSource.addEventListener("flag.created", (e) => {
245
- this.handleMessage("flag.created", e);
246
- });
247
- } catch (error) {
248
- console.error("[Savvagent] Failed to create EventSource:", error);
249
- this.handleDisconnect();
257
+ if (this.authFailed) {
258
+ return;
250
259
  }
260
+ this.abortController = new AbortController();
261
+ const url = `${this.baseUrl}/api/flags/stream`;
262
+ (0, import_fetch_event_source.fetchEventSource)(url, {
263
+ method: "GET",
264
+ headers: {
265
+ "Authorization": `Bearer ${this.apiKey}`
266
+ },
267
+ signal: this.abortController.signal,
268
+ // Disable built-in retry behavior - we handle it ourselves
269
+ openWhenHidden: false,
270
+ onopen: async (response) => {
271
+ if (response.ok) {
272
+ console.log("[Savvagent] Real-time connection established");
273
+ this.reconnectAttempts = 0;
274
+ this.reconnectDelay = 1e3;
275
+ this.connected = true;
276
+ this.onConnectionChange?.(true);
277
+ } else if (response.status === 401 || response.status === 403) {
278
+ this.authFailed = true;
279
+ console.error(`[Savvagent] SSE authentication failed (${response.status}). Check your API key. Reconnection disabled.`);
280
+ throw new FatalError(`SSE authentication failed: ${response.status}`);
281
+ } else {
282
+ console.error(`[Savvagent] SSE connection failed: ${response.status}`);
283
+ throw new RetriableError(`SSE connection failed: ${response.status}`);
284
+ }
285
+ },
286
+ onmessage: (event) => {
287
+ this.handleMessage(event);
288
+ },
289
+ onerror: (err) => {
290
+ if (this.authFailed) {
291
+ throw err;
292
+ }
293
+ console.error("[Savvagent] SSE connection error:", err);
294
+ this.handleDisconnect();
295
+ },
296
+ onclose: () => {
297
+ console.log("[Savvagent] SSE connection closed");
298
+ if (!this.authFailed) {
299
+ this.handleDisconnect();
300
+ }
301
+ }
302
+ }).catch((error) => {
303
+ if (error.name !== "AbortError" && !(error instanceof FatalError)) {
304
+ console.error("[Savvagent] SSE connection error:", error);
305
+ if (!this.authFailed) {
306
+ this.handleDisconnect();
307
+ }
308
+ }
309
+ });
251
310
  }
252
311
  /**
253
312
  * Handle incoming SSE messages
254
313
  */
255
- handleMessage(type, event) {
314
+ handleMessage(event) {
315
+ if (event.event === "heartbeat") {
316
+ return;
317
+ }
318
+ if (event.event === "connected") {
319
+ return;
320
+ }
321
+ const eventType = event.event;
322
+ if (!["flag.updated", "flag.deleted", "flag.created"].includes(eventType)) {
323
+ return;
324
+ }
256
325
  try {
257
326
  const data = JSON.parse(event.data);
258
327
  const updateEvent = {
259
- type,
328
+ type: eventType,
260
329
  flagKey: data.key,
261
330
  data
262
331
  };
263
- const flagListeners = this.listeners.get(updateEvent.flagKey);
264
- if (flagListeners) {
265
- flagListeners.forEach((listener) => listener(updateEvent));
266
- }
267
332
  const wildcardListeners = this.listeners.get("*");
268
333
  if (wildcardListeners) {
269
334
  wildcardListeners.forEach((listener) => listener(updateEvent));
270
335
  }
336
+ const flagListeners = this.listeners.get(updateEvent.flagKey);
337
+ if (flagListeners) {
338
+ flagListeners.forEach((listener) => listener(updateEvent));
339
+ }
271
340
  } catch (error) {
272
341
  console.error("[Savvagent] Failed to parse SSE message:", error);
273
342
  }
274
343
  }
275
344
  /**
276
- * Handle disconnection and attempt reconnect
345
+ * Handle disconnection and attempt reconnect with exponential backoff
277
346
  */
278
347
  handleDisconnect() {
279
- this.onConnectionChange?.call(null, false);
280
- if (this.eventSource) {
281
- this.eventSource.close();
282
- this.eventSource = null;
348
+ this.connected = false;
349
+ this.onConnectionChange?.(false);
350
+ if (this.abortController) {
351
+ this.abortController.abort();
352
+ this.abortController = null;
353
+ }
354
+ if (this.authFailed) {
355
+ console.warn("[Savvagent] Authentication failed. Reconnection disabled.");
356
+ return;
283
357
  }
284
358
  if (this.reconnectAttempts < this.maxReconnectAttempts) {
285
359
  this.reconnectAttempts++;
@@ -317,28 +391,33 @@ var RealtimeService = class {
317
391
  * Disconnect from SSE stream
318
392
  */
319
393
  disconnect() {
320
- if (this.eventSource) {
321
- this.eventSource.close();
322
- this.eventSource = null;
323
- }
324
394
  this.reconnectAttempts = this.maxReconnectAttempts;
325
- this.onConnectionChange?.call(null, false);
395
+ if (this.abortController) {
396
+ this.abortController.abort();
397
+ this.abortController = null;
398
+ }
399
+ this.connected = false;
400
+ this.onConnectionChange?.(false);
326
401
  }
327
402
  /**
328
403
  * Check if connected
329
404
  */
330
405
  isConnected() {
331
- return this.eventSource !== null && this.eventSource.readyState === EventSource.OPEN;
406
+ return this.connected;
332
407
  }
333
408
  };
334
409
 
335
410
  // src/client.ts
336
411
  var FlagClient = class {
412
+ // Track auth failures to prevent request spam
337
413
  constructor(config) {
338
414
  this.realtime = null;
339
415
  this.anonymousId = null;
340
416
  this.userId = null;
341
417
  this.detectedLanguage = null;
418
+ this.overrides = /* @__PURE__ */ new Map();
419
+ this.overrideListeners = /* @__PURE__ */ new Set();
420
+ this.authFailed = false;
342
421
  this.config = {
343
422
  apiKey: config.apiKey,
344
423
  applicationId: config.applicationId || "",
@@ -363,7 +442,7 @@ var FlagClient = class {
363
442
  this.config.apiKey,
364
443
  this.config.enableTelemetry
365
444
  );
366
- if (this.config.enableRealtime && typeof EventSource !== "undefined") {
445
+ if (this.config.enableRealtime && typeof fetch !== "undefined") {
367
446
  this.realtime = new RealtimeService(
368
447
  this.config.baseUrl,
369
448
  this.config.apiKey,
@@ -474,6 +553,29 @@ var FlagClient = class {
474
553
  const startTime = Date.now();
475
554
  const traceId = TelemetryService.generateTraceId();
476
555
  try {
556
+ if (this.overrides.has(flagKey)) {
557
+ const overrideValue = this.overrides.get(flagKey);
558
+ return {
559
+ key: flagKey,
560
+ value: overrideValue,
561
+ reason: "default",
562
+ // Using 'default' to indicate override
563
+ metadata: {
564
+ description: "Local override active"
565
+ }
566
+ };
567
+ }
568
+ if (this.authFailed) {
569
+ const defaultValue = this.config.defaults[flagKey] ?? false;
570
+ return {
571
+ key: flagKey,
572
+ value: defaultValue,
573
+ reason: "error",
574
+ metadata: {
575
+ description: "Authentication failed - using default value"
576
+ }
577
+ };
578
+ }
477
579
  const cachedValue = this.cache.get(flagKey);
478
580
  if (cachedValue !== null) {
479
581
  return {
@@ -486,15 +588,27 @@ var FlagClient = class {
486
588
  const requestBody = {
487
589
  context: evaluationContext
488
590
  };
591
+ const controller = new AbortController();
592
+ const timeoutId = setTimeout(() => {
593
+ controller.abort();
594
+ }, 1e4);
489
595
  const response = await fetch(`${this.config.baseUrl}/api/flags/${flagKey}/evaluate`, {
490
596
  method: "POST",
491
597
  headers: {
492
598
  "Content-Type": "application/json",
493
599
  Authorization: `Bearer ${this.config.apiKey}`
494
600
  },
495
- body: JSON.stringify(requestBody)
601
+ body: JSON.stringify(requestBody),
602
+ signal: controller.signal
496
603
  });
604
+ clearTimeout(timeoutId);
497
605
  if (!response.ok) {
606
+ if (response.status === 401 || response.status === 403) {
607
+ this.authFailed = true;
608
+ this.realtime?.disconnect();
609
+ console.error(`[Savvagent] Authentication failed (${response.status}). Check your API key. Further requests disabled.`);
610
+ throw new Error(`Authentication failed: ${response.status}`);
611
+ }
498
612
  throw new Error(`Flag evaluation failed: ${response.status}`);
499
613
  }
500
614
  const data = await response.json();
@@ -621,6 +735,223 @@ var FlagClient = class {
621
735
  this.realtime?.disconnect();
622
736
  this.cache.clear();
623
737
  }
738
+ // =====================
739
+ // Local Override Methods
740
+ // =====================
741
+ /**
742
+ * Set a local override for a flag.
743
+ * Overrides take precedence over server values and cache.
744
+ *
745
+ * @param flagKey - The flag key to override
746
+ * @param value - The override value (true/false)
747
+ *
748
+ * @example
749
+ * ```typescript
750
+ * // Force a flag to be enabled locally
751
+ * client.setOverride('new-feature', true);
752
+ * ```
753
+ */
754
+ setOverride(flagKey, value) {
755
+ this.overrides.set(flagKey, value);
756
+ this.notifyOverrideListeners();
757
+ }
758
+ /**
759
+ * Clear a local override for a flag.
760
+ * The flag will return to using server/cached values.
761
+ *
762
+ * @param flagKey - The flag key to clear override for
763
+ */
764
+ clearOverride(flagKey) {
765
+ this.overrides.delete(flagKey);
766
+ this.notifyOverrideListeners();
767
+ }
768
+ /**
769
+ * Clear all local overrides.
770
+ */
771
+ clearAllOverrides() {
772
+ this.overrides.clear();
773
+ this.notifyOverrideListeners();
774
+ }
775
+ /**
776
+ * Check if a flag has a local override.
777
+ *
778
+ * @param flagKey - The flag key to check
779
+ * @returns true if the flag has an override
780
+ */
781
+ hasOverride(flagKey) {
782
+ return this.overrides.has(flagKey);
783
+ }
784
+ /**
785
+ * Get the override value for a flag.
786
+ *
787
+ * @param flagKey - The flag key to get override for
788
+ * @returns The override value, or undefined if not set
789
+ */
790
+ getOverride(flagKey) {
791
+ return this.overrides.get(flagKey);
792
+ }
793
+ /**
794
+ * Get all current overrides.
795
+ *
796
+ * @returns Record of flag keys to override values
797
+ */
798
+ getOverrides() {
799
+ const result = {};
800
+ this.overrides.forEach((value, key) => {
801
+ result[key] = value;
802
+ });
803
+ return result;
804
+ }
805
+ /**
806
+ * Set multiple overrides at once.
807
+ *
808
+ * @param overrides - Record of flag keys to override values
809
+ */
810
+ setOverrides(overrides) {
811
+ Object.entries(overrides).forEach(([key, value]) => {
812
+ this.overrides.set(key, value);
813
+ });
814
+ this.notifyOverrideListeners();
815
+ }
816
+ /**
817
+ * Subscribe to override changes.
818
+ * Useful for React components to re-render when overrides change.
819
+ *
820
+ * @param callback - Function to call when overrides change
821
+ * @returns Unsubscribe function
822
+ */
823
+ onOverrideChange(callback) {
824
+ this.overrideListeners.add(callback);
825
+ return () => {
826
+ this.overrideListeners.delete(callback);
827
+ };
828
+ }
829
+ /**
830
+ * Notify all override listeners of a change.
831
+ */
832
+ notifyOverrideListeners() {
833
+ this.overrideListeners.forEach((callback) => {
834
+ try {
835
+ callback();
836
+ } catch (e) {
837
+ console.error("[Savvagent] Override listener error:", e);
838
+ }
839
+ });
840
+ }
841
+ /**
842
+ * Get all flags for the application (and enterprise-scoped flags).
843
+ * Per SDK Developer Guide: GET /api/sdk/flags
844
+ *
845
+ * Use cases:
846
+ * - Local override UI: Display all available flags for developers to toggle
847
+ * - Offline mode: Pre-fetch flags for mobile/desktop apps
848
+ * - SDK initialization: Bootstrap SDK with all flag values on startup
849
+ * - DevTools integration: Show available flags in browser dev panels
850
+ *
851
+ * @param environment - Environment to evaluate enabled state for (default: 'development')
852
+ * @returns Promise<FlagDefinition[]> - List of flag definitions
853
+ *
854
+ * @example
855
+ * ```typescript
856
+ * // Fetch all flags for development
857
+ * const flags = await client.getAllFlags('development');
858
+ *
859
+ * // Bootstrap local cache
860
+ * flags.forEach(flag => {
861
+ * console.log(`${flag.key}: ${flag.enabled}`);
862
+ * });
863
+ * ```
864
+ */
865
+ async getAllFlags(environment = "development") {
866
+ if (this.authFailed) {
867
+ return [];
868
+ }
869
+ try {
870
+ const controller = new AbortController();
871
+ const timeoutId = setTimeout(() => {
872
+ controller.abort();
873
+ }, 1e4);
874
+ const response = await fetch(
875
+ `${this.config.baseUrl}/api/sdk/flags?environment=${encodeURIComponent(environment)}`,
876
+ {
877
+ method: "GET",
878
+ headers: {
879
+ Authorization: `Bearer ${this.config.apiKey}`
880
+ },
881
+ signal: controller.signal
882
+ }
883
+ );
884
+ clearTimeout(timeoutId);
885
+ if (!response.ok) {
886
+ if (response.status === 401 || response.status === 403) {
887
+ this.authFailed = true;
888
+ this.realtime?.disconnect();
889
+ console.error(`[Savvagent] Authentication failed (${response.status}). Check your API key. Further requests disabled.`);
890
+ throw new Error(`Authentication failed: ${response.status}`);
891
+ }
892
+ throw new Error(`Failed to fetch flags: ${response.status}`);
893
+ }
894
+ const data = await response.json();
895
+ data.flags.forEach((flag) => {
896
+ this.cache.set(flag.key, flag.enabled, flag.key);
897
+ });
898
+ return data.flags;
899
+ } catch (error) {
900
+ this.config.onError(error);
901
+ return [];
902
+ }
903
+ }
904
+ /**
905
+ * Get only enterprise-scoped flags for the organization.
906
+ * Per SDK Developer Guide: GET /api/sdk/enterprise-flags
907
+ *
908
+ * Enterprise flags are shared across all applications in the organization.
909
+ *
910
+ * @param environment - Environment to evaluate enabled state for (default: 'development')
911
+ * @returns Promise<FlagDefinition[]> - List of enterprise flag definitions
912
+ *
913
+ * @example
914
+ * ```typescript
915
+ * // Fetch enterprise-only flags
916
+ * const enterpriseFlags = await client.getEnterpriseFlags('production');
917
+ * ```
918
+ */
919
+ async getEnterpriseFlags(environment = "development") {
920
+ if (this.authFailed) {
921
+ return [];
922
+ }
923
+ try {
924
+ const controller = new AbortController();
925
+ const timeoutId = setTimeout(() => {
926
+ controller.abort();
927
+ }, 1e4);
928
+ const response = await fetch(
929
+ `${this.config.baseUrl}/api/sdk/enterprise-flags?environment=${encodeURIComponent(environment)}`,
930
+ {
931
+ method: "GET",
932
+ headers: {
933
+ Authorization: `Bearer ${this.config.apiKey}`
934
+ },
935
+ signal: controller.signal
936
+ }
937
+ );
938
+ clearTimeout(timeoutId);
939
+ if (!response.ok) {
940
+ if (response.status === 401 || response.status === 403) {
941
+ this.authFailed = true;
942
+ this.realtime?.disconnect();
943
+ console.error(`[Savvagent] Authentication failed (${response.status}). Check your API key. Further requests disabled.`);
944
+ throw new Error(`Authentication failed: ${response.status}`);
945
+ }
946
+ throw new Error(`Failed to fetch enterprise flags: ${response.status}`);
947
+ }
948
+ const data = await response.json();
949
+ return data.flags;
950
+ } catch (error) {
951
+ this.config.onError(error);
952
+ return [];
953
+ }
954
+ }
624
955
  };
625
956
  // Annotate the CommonJS export names for ESM import in node:
626
957
  0 && (module.exports = {