@scalemule/sdk 0.0.14 → 0.0.16

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.
@@ -79,6 +79,8 @@ declare class FlagClient {
79
79
  private environment;
80
80
  private gatewayUrl;
81
81
  private config;
82
+ private flagIndex;
83
+ private segmentIndex;
82
84
  private lastETag;
83
85
  private streamState;
84
86
  private pollTimer;
@@ -87,9 +89,12 @@ declare class FlagClient {
87
89
  private abortController;
88
90
  private initPromise;
89
91
  private telemetryCounters;
92
+ private isShuttingDown;
93
+ private streamConnectInFlight;
90
94
  constructor(options: FlagClientOptions);
91
95
  init(): Promise<void>;
92
96
  private doInit;
97
+ private buildIndexes;
93
98
  evaluate(flagKey: string, context: EvaluationContext): FlagEvaluation;
94
99
  evaluateBatch(flagKeys: string[], context: EvaluationContext): Record<string, FlagEvaluation>;
95
100
  shutdown(): Promise<void>;
@@ -108,7 +113,7 @@ declare class FlagClient {
108
113
  * Produces identical results to the server-side evaluation.
109
114
  */
110
115
 
111
- declare function evaluateFlag(flag: FlagWire, config: FlagConfigWire, context: EvaluationContext): FlagEvaluation;
116
+ declare function evaluateFlag(flag: FlagWire, config: FlagConfigWire, context: EvaluationContext, segmentIndex?: Map<string, SegmentWire>): FlagEvaluation;
112
117
 
113
118
  /**
114
119
  * Hash-to-bucket matching Rust: SHA256(salt.flag_key.identifier) → first 4 bytes → u32 BE → mod 10_000
@@ -79,6 +79,8 @@ declare class FlagClient {
79
79
  private environment;
80
80
  private gatewayUrl;
81
81
  private config;
82
+ private flagIndex;
83
+ private segmentIndex;
82
84
  private lastETag;
83
85
  private streamState;
84
86
  private pollTimer;
@@ -87,9 +89,12 @@ declare class FlagClient {
87
89
  private abortController;
88
90
  private initPromise;
89
91
  private telemetryCounters;
92
+ private isShuttingDown;
93
+ private streamConnectInFlight;
90
94
  constructor(options: FlagClientOptions);
91
95
  init(): Promise<void>;
92
96
  private doInit;
97
+ private buildIndexes;
93
98
  evaluate(flagKey: string, context: EvaluationContext): FlagEvaluation;
94
99
  evaluateBatch(flagKeys: string[], context: EvaluationContext): Record<string, FlagEvaluation>;
95
100
  shutdown(): Promise<void>;
@@ -108,7 +113,7 @@ declare class FlagClient {
108
113
  * Produces identical results to the server-side evaluation.
109
114
  */
110
115
 
111
- declare function evaluateFlag(flag: FlagWire, config: FlagConfigWire, context: EvaluationContext): FlagEvaluation;
116
+ declare function evaluateFlag(flag: FlagWire, config: FlagConfigWire, context: EvaluationContext, segmentIndex?: Map<string, SegmentWire>): FlagEvaluation;
112
117
 
113
118
  /**
114
119
  * Hash-to-bucket matching Rust: SHA256(salt.flag_key.identifier) → first 4 bytes → u32 BE → mod 10_000
@@ -181,7 +181,7 @@ function semverCmp(actual, expected) {
181
181
  }
182
182
 
183
183
  // src/flags/evaluator.ts
184
- function evaluateFlag(flag, config, context) {
184
+ function evaluateFlag(flag, config, context, segmentIndex) {
185
185
  const effectiveDefault = flag.environment_default_value ?? flag.default_value;
186
186
  if (flag.status !== "active") {
187
187
  return result(flag, config.environment, effectiveDefault, "disabled");
@@ -194,7 +194,7 @@ function evaluateFlag(flag, config, context) {
194
194
  if (!rule.enabled) continue;
195
195
  if (rule.segment_ids.length > 0) {
196
196
  const segmentMatched = rule.segment_ids.some((segId) => {
197
- const segment = config.segments.find((s) => s.id === segId);
197
+ const segment = segmentIndex ? segmentIndex.get(segId) : config.segments.find((s) => s.id === segId);
198
198
  if (!segment) return false;
199
199
  return userMatchesSegment(segment, context);
200
200
  });
@@ -283,6 +283,8 @@ function result(flag, environment, value, reason) {
283
283
  var FlagClient = class {
284
284
  constructor(options) {
285
285
  this.config = null;
286
+ this.flagIndex = /* @__PURE__ */ new Map();
287
+ this.segmentIndex = /* @__PURE__ */ new Map();
286
288
  this.lastETag = "";
287
289
  this.streamState = "idle";
288
290
  this.pollTimer = null;
@@ -291,11 +293,14 @@ var FlagClient = class {
291
293
  this.abortController = null;
292
294
  this.initPromise = null;
293
295
  this.telemetryCounters = /* @__PURE__ */ new Map();
296
+ this.isShuttingDown = false;
297
+ this.streamConnectInFlight = false;
294
298
  this.apiKey = options.apiKey;
295
299
  this.environment = options.environment;
296
300
  this.gatewayUrl = options.gatewayUrl;
297
301
  }
298
302
  async init() {
303
+ this.isShuttingDown = false;
299
304
  if (this.config) return;
300
305
  if (this.initPromise) return this.initPromise;
301
306
  this.initPromise = this.doInit();
@@ -306,29 +311,32 @@ var FlagClient = class {
306
311
  }
307
312
  }
308
313
  async doInit() {
309
- for (let attempt = 0; attempt < 3; attempt++) {
310
- try {
311
- const resp = await fetch(
312
- `${this.gatewayUrl}/v1/flags/config?environment=${encodeURIComponent(this.environment)}`,
313
- { headers: { "x-api-key": this.apiKey } }
314
- );
315
- if (resp.status === 403) throw new Error("Secret API key required for /config");
316
- if (!resp.ok) throw new Error(`Config fetch failed: ${resp.status}`);
317
- const json = await resp.json();
318
- this.config = json.data;
319
- this.lastETag = resp.headers.get("etag") || "";
320
- this.connectStream();
321
- this.startTelemetryFlush();
322
- return;
323
- } catch (e) {
324
- if (attempt < 2) await sleep(1e3 * 2 ** attempt);
325
- else throw e;
326
- }
314
+ const resp = await fetch(`${this.gatewayUrl}/v1/flags/config?environment=${encodeURIComponent(this.environment)}`, {
315
+ headers: { "x-api-key": this.apiKey }
316
+ });
317
+ if (resp.status === 403) throw new Error("Secret API key required for /config");
318
+ if (!resp.ok) throw new Error(`Config fetch failed: ${resp.status}`);
319
+ const json = await resp.json();
320
+ this.config = json.data;
321
+ this.buildIndexes();
322
+ this.lastETag = resp.headers.get("etag") || "";
323
+ this.connectStream();
324
+ this.startTelemetryFlush();
325
+ }
326
+ buildIndexes() {
327
+ this.flagIndex.clear();
328
+ this.segmentIndex.clear();
329
+ if (!this.config) return;
330
+ for (const flag of this.config.flags) {
331
+ this.flagIndex.set(flag.flag_key, flag);
332
+ }
333
+ for (const segment of this.config.segments) {
334
+ this.segmentIndex.set(segment.id, segment);
327
335
  }
328
336
  }
329
337
  evaluate(flagKey, context) {
330
338
  if (!this.config) throw new Error("FlagClient not initialized \u2014 call init() first");
331
- const flagConfig = this.config.flags.find((f) => f.flag_key === flagKey);
339
+ const flagConfig = this.flagIndex.get(flagKey);
332
340
  if (!flagConfig) {
333
341
  return {
334
342
  flag_id: "",
@@ -341,7 +349,7 @@ var FlagClient = class {
341
349
  bucket: null
342
350
  };
343
351
  }
344
- const result2 = evaluateFlag(flagConfig, this.config, context);
352
+ const result2 = evaluateFlag(flagConfig, this.config, context, this.segmentIndex);
345
353
  this.recordTelemetry(result2);
346
354
  return result2;
347
355
  }
@@ -349,9 +357,9 @@ var FlagClient = class {
349
357
  if (!this.config) throw new Error("FlagClient not initialized \u2014 call init() first");
350
358
  const results = {};
351
359
  for (const key of flagKeys) {
352
- const flagConfig = this.config.flags.find((f) => f.flag_key === key);
360
+ const flagConfig = this.flagIndex.get(key);
353
361
  if (flagConfig) {
354
- const result2 = evaluateFlag(flagConfig, this.config, context);
362
+ const result2 = evaluateFlag(flagConfig, this.config, context, this.segmentIndex);
355
363
  this.recordTelemetry(result2);
356
364
  results[key] = result2;
357
365
  }
@@ -359,6 +367,7 @@ var FlagClient = class {
359
367
  return results;
360
368
  }
361
369
  async shutdown() {
370
+ this.isShuttingDown = true;
362
371
  this.streamState = "idle";
363
372
  this.abortController?.abort();
364
373
  this.abortController = null;
@@ -378,9 +387,13 @@ var FlagClient = class {
378
387
  }
379
388
  // ======== SSE Streaming ========
380
389
  async connectStream() {
381
- if (this.streamState === "streaming") return;
390
+ if (this.isShuttingDown || this.streamState === "streaming" || this.streamConnectInFlight) return;
391
+ this.streamConnectInFlight = true;
382
392
  this.abortController?.abort();
383
- this.abortController = new AbortController();
393
+ const abortController = new AbortController();
394
+ this.abortController = abortController;
395
+ const shouldResumePolling = this.streamState !== "polling";
396
+ let startPolling = shouldResumePolling;
384
397
  try {
385
398
  const resp = await fetch(
386
399
  `${this.gatewayUrl}/v1/flags/stream?environment=${encodeURIComponent(this.environment)}`,
@@ -389,33 +402,38 @@ var FlagClient = class {
389
402
  "x-api-key": this.apiKey,
390
403
  "Last-Event-ID": String(this.config?.version ?? 0)
391
404
  },
392
- signal: this.abortController.signal
405
+ signal: abortController.signal
393
406
  }
394
407
  );
395
- if (!resp.ok || !resp.body) {
396
- this.startPolling();
397
- return;
398
- }
399
- this.streamState = "streaming";
400
- this.stopPolling();
401
- const reader = resp.body.getReader();
402
- const decoder = new TextDecoder();
403
- let buffer = "";
404
- while (true) {
405
- const { done, value } = await reader.read();
406
- if (done) break;
407
- buffer += decoder.decode(value, { stream: true });
408
- let idx;
409
- while ((idx = buffer.indexOf("\n\n")) !== -1) {
410
- const frame = buffer.slice(0, idx);
411
- buffer = buffer.slice(idx + 2);
412
- this.handleSseFrame(frame);
408
+ if (resp.ok && resp.body) {
409
+ this.streamState = "streaming";
410
+ this.stopPolling();
411
+ startPolling = false;
412
+ const reader = resp.body.getReader();
413
+ const decoder = new TextDecoder();
414
+ let buffer = "";
415
+ while (true) {
416
+ const { done, value } = await reader.read();
417
+ if (done) break;
418
+ buffer += decoder.decode(value, { stream: true });
419
+ let idx;
420
+ while ((idx = buffer.indexOf("\n\n")) !== -1) {
421
+ const frame = buffer.slice(0, idx);
422
+ buffer = buffer.slice(idx + 2);
423
+ this.handleSseFrame(frame);
424
+ }
425
+ }
426
+ if (this.streamState === "streaming") {
427
+ this.streamState = "idle";
428
+ startPolling = true;
413
429
  }
414
430
  }
415
431
  } catch {
432
+ startPolling = !abortController.signal.aborted && shouldResumePolling;
433
+ } finally {
434
+ this.streamConnectInFlight = false;
416
435
  }
417
- if (this.streamState === "streaming") {
418
- this.streamState = "idle";
436
+ if (!this.isShuttingDown && startPolling) {
419
437
  this.startPolling();
420
438
  }
421
439
  }
@@ -432,6 +450,7 @@ var FlagClient = class {
432
450
  const newConfig = parsed.data;
433
451
  if (newConfig && newConfig.version !== void 0) {
434
452
  this.config = newConfig;
453
+ this.buildIndexes();
435
454
  }
436
455
  } catch {
437
456
  }
@@ -466,6 +485,7 @@ var FlagClient = class {
466
485
  if (!resp.ok) return;
467
486
  const json = await resp.json();
468
487
  this.config = json.data;
488
+ this.buildIndexes();
469
489
  this.lastETag = resp.headers.get("etag") || "";
470
490
  } catch {
471
491
  }
@@ -523,9 +543,6 @@ var FlagClient = class {
523
543
  }
524
544
  }
525
545
  };
526
- function sleep(ms) {
527
- return new Promise((resolve) => setTimeout(resolve, ms));
528
- }
529
546
  // Annotate the CommonJS export names for ESM import in node:
530
547
  0 && (module.exports = {
531
548
  FlagClient,
@@ -152,7 +152,7 @@ function semverCmp(actual, expected) {
152
152
  }
153
153
 
154
154
  // src/flags/evaluator.ts
155
- function evaluateFlag(flag, config, context) {
155
+ function evaluateFlag(flag, config, context, segmentIndex) {
156
156
  const effectiveDefault = flag.environment_default_value ?? flag.default_value;
157
157
  if (flag.status !== "active") {
158
158
  return result(flag, config.environment, effectiveDefault, "disabled");
@@ -165,7 +165,7 @@ function evaluateFlag(flag, config, context) {
165
165
  if (!rule.enabled) continue;
166
166
  if (rule.segment_ids.length > 0) {
167
167
  const segmentMatched = rule.segment_ids.some((segId) => {
168
- const segment = config.segments.find((s) => s.id === segId);
168
+ const segment = segmentIndex ? segmentIndex.get(segId) : config.segments.find((s) => s.id === segId);
169
169
  if (!segment) return false;
170
170
  return userMatchesSegment(segment, context);
171
171
  });
@@ -254,6 +254,8 @@ function result(flag, environment, value, reason) {
254
254
  var FlagClient = class {
255
255
  constructor(options) {
256
256
  this.config = null;
257
+ this.flagIndex = /* @__PURE__ */ new Map();
258
+ this.segmentIndex = /* @__PURE__ */ new Map();
257
259
  this.lastETag = "";
258
260
  this.streamState = "idle";
259
261
  this.pollTimer = null;
@@ -262,11 +264,14 @@ var FlagClient = class {
262
264
  this.abortController = null;
263
265
  this.initPromise = null;
264
266
  this.telemetryCounters = /* @__PURE__ */ new Map();
267
+ this.isShuttingDown = false;
268
+ this.streamConnectInFlight = false;
265
269
  this.apiKey = options.apiKey;
266
270
  this.environment = options.environment;
267
271
  this.gatewayUrl = options.gatewayUrl;
268
272
  }
269
273
  async init() {
274
+ this.isShuttingDown = false;
270
275
  if (this.config) return;
271
276
  if (this.initPromise) return this.initPromise;
272
277
  this.initPromise = this.doInit();
@@ -277,29 +282,32 @@ var FlagClient = class {
277
282
  }
278
283
  }
279
284
  async doInit() {
280
- for (let attempt = 0; attempt < 3; attempt++) {
281
- try {
282
- const resp = await fetch(
283
- `${this.gatewayUrl}/v1/flags/config?environment=${encodeURIComponent(this.environment)}`,
284
- { headers: { "x-api-key": this.apiKey } }
285
- );
286
- if (resp.status === 403) throw new Error("Secret API key required for /config");
287
- if (!resp.ok) throw new Error(`Config fetch failed: ${resp.status}`);
288
- const json = await resp.json();
289
- this.config = json.data;
290
- this.lastETag = resp.headers.get("etag") || "";
291
- this.connectStream();
292
- this.startTelemetryFlush();
293
- return;
294
- } catch (e) {
295
- if (attempt < 2) await sleep(1e3 * 2 ** attempt);
296
- else throw e;
297
- }
285
+ const resp = await fetch(`${this.gatewayUrl}/v1/flags/config?environment=${encodeURIComponent(this.environment)}`, {
286
+ headers: { "x-api-key": this.apiKey }
287
+ });
288
+ if (resp.status === 403) throw new Error("Secret API key required for /config");
289
+ if (!resp.ok) throw new Error(`Config fetch failed: ${resp.status}`);
290
+ const json = await resp.json();
291
+ this.config = json.data;
292
+ this.buildIndexes();
293
+ this.lastETag = resp.headers.get("etag") || "";
294
+ this.connectStream();
295
+ this.startTelemetryFlush();
296
+ }
297
+ buildIndexes() {
298
+ this.flagIndex.clear();
299
+ this.segmentIndex.clear();
300
+ if (!this.config) return;
301
+ for (const flag of this.config.flags) {
302
+ this.flagIndex.set(flag.flag_key, flag);
303
+ }
304
+ for (const segment of this.config.segments) {
305
+ this.segmentIndex.set(segment.id, segment);
298
306
  }
299
307
  }
300
308
  evaluate(flagKey, context) {
301
309
  if (!this.config) throw new Error("FlagClient not initialized \u2014 call init() first");
302
- const flagConfig = this.config.flags.find((f) => f.flag_key === flagKey);
310
+ const flagConfig = this.flagIndex.get(flagKey);
303
311
  if (!flagConfig) {
304
312
  return {
305
313
  flag_id: "",
@@ -312,7 +320,7 @@ var FlagClient = class {
312
320
  bucket: null
313
321
  };
314
322
  }
315
- const result2 = evaluateFlag(flagConfig, this.config, context);
323
+ const result2 = evaluateFlag(flagConfig, this.config, context, this.segmentIndex);
316
324
  this.recordTelemetry(result2);
317
325
  return result2;
318
326
  }
@@ -320,9 +328,9 @@ var FlagClient = class {
320
328
  if (!this.config) throw new Error("FlagClient not initialized \u2014 call init() first");
321
329
  const results = {};
322
330
  for (const key of flagKeys) {
323
- const flagConfig = this.config.flags.find((f) => f.flag_key === key);
331
+ const flagConfig = this.flagIndex.get(key);
324
332
  if (flagConfig) {
325
- const result2 = evaluateFlag(flagConfig, this.config, context);
333
+ const result2 = evaluateFlag(flagConfig, this.config, context, this.segmentIndex);
326
334
  this.recordTelemetry(result2);
327
335
  results[key] = result2;
328
336
  }
@@ -330,6 +338,7 @@ var FlagClient = class {
330
338
  return results;
331
339
  }
332
340
  async shutdown() {
341
+ this.isShuttingDown = true;
333
342
  this.streamState = "idle";
334
343
  this.abortController?.abort();
335
344
  this.abortController = null;
@@ -349,9 +358,13 @@ var FlagClient = class {
349
358
  }
350
359
  // ======== SSE Streaming ========
351
360
  async connectStream() {
352
- if (this.streamState === "streaming") return;
361
+ if (this.isShuttingDown || this.streamState === "streaming" || this.streamConnectInFlight) return;
362
+ this.streamConnectInFlight = true;
353
363
  this.abortController?.abort();
354
- this.abortController = new AbortController();
364
+ const abortController = new AbortController();
365
+ this.abortController = abortController;
366
+ const shouldResumePolling = this.streamState !== "polling";
367
+ let startPolling = shouldResumePolling;
355
368
  try {
356
369
  const resp = await fetch(
357
370
  `${this.gatewayUrl}/v1/flags/stream?environment=${encodeURIComponent(this.environment)}`,
@@ -360,33 +373,38 @@ var FlagClient = class {
360
373
  "x-api-key": this.apiKey,
361
374
  "Last-Event-ID": String(this.config?.version ?? 0)
362
375
  },
363
- signal: this.abortController.signal
376
+ signal: abortController.signal
364
377
  }
365
378
  );
366
- if (!resp.ok || !resp.body) {
367
- this.startPolling();
368
- return;
369
- }
370
- this.streamState = "streaming";
371
- this.stopPolling();
372
- const reader = resp.body.getReader();
373
- const decoder = new TextDecoder();
374
- let buffer = "";
375
- while (true) {
376
- const { done, value } = await reader.read();
377
- if (done) break;
378
- buffer += decoder.decode(value, { stream: true });
379
- let idx;
380
- while ((idx = buffer.indexOf("\n\n")) !== -1) {
381
- const frame = buffer.slice(0, idx);
382
- buffer = buffer.slice(idx + 2);
383
- this.handleSseFrame(frame);
379
+ if (resp.ok && resp.body) {
380
+ this.streamState = "streaming";
381
+ this.stopPolling();
382
+ startPolling = false;
383
+ const reader = resp.body.getReader();
384
+ const decoder = new TextDecoder();
385
+ let buffer = "";
386
+ while (true) {
387
+ const { done, value } = await reader.read();
388
+ if (done) break;
389
+ buffer += decoder.decode(value, { stream: true });
390
+ let idx;
391
+ while ((idx = buffer.indexOf("\n\n")) !== -1) {
392
+ const frame = buffer.slice(0, idx);
393
+ buffer = buffer.slice(idx + 2);
394
+ this.handleSseFrame(frame);
395
+ }
396
+ }
397
+ if (this.streamState === "streaming") {
398
+ this.streamState = "idle";
399
+ startPolling = true;
384
400
  }
385
401
  }
386
402
  } catch {
403
+ startPolling = !abortController.signal.aborted && shouldResumePolling;
404
+ } finally {
405
+ this.streamConnectInFlight = false;
387
406
  }
388
- if (this.streamState === "streaming") {
389
- this.streamState = "idle";
407
+ if (!this.isShuttingDown && startPolling) {
390
408
  this.startPolling();
391
409
  }
392
410
  }
@@ -403,6 +421,7 @@ var FlagClient = class {
403
421
  const newConfig = parsed.data;
404
422
  if (newConfig && newConfig.version !== void 0) {
405
423
  this.config = newConfig;
424
+ this.buildIndexes();
406
425
  }
407
426
  } catch {
408
427
  }
@@ -437,6 +456,7 @@ var FlagClient = class {
437
456
  if (!resp.ok) return;
438
457
  const json = await resp.json();
439
458
  this.config = json.data;
459
+ this.buildIndexes();
440
460
  this.lastETag = resp.headers.get("etag") || "";
441
461
  } catch {
442
462
  }
@@ -494,9 +514,6 @@ var FlagClient = class {
494
514
  }
495
515
  }
496
516
  };
497
- function sleep(ms) {
498
- return new Promise((resolve) => setTimeout(resolve, ms));
499
- }
500
517
  export {
501
518
  FlagClient,
502
519
  allConditionsMatch,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@scalemule/sdk",
3
- "version": "0.0.14",
3
+ "version": "0.0.16",
4
4
  "description": "Official TypeScript/JavaScript SDK for ScaleMule Backend-as-a-Service",
5
5
  "main": "dist/index.js",
6
6
  "module": "dist/index.mjs",