@openfeature/flagd-provider 0.13.3 → 0.13.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.
package/index.cjs.js CHANGED
@@ -5,6 +5,7 @@ var grpcJs = require('@grpc/grpc-js');
5
5
  var connectivityState = require('@grpc/grpc-js/build/src/connectivity-state');
6
6
  var lruCache = require('lru-cache');
7
7
  var node_util = require('node:util');
8
+ var node_fs = require('node:fs');
8
9
  var flagdCore = require('@openfeature/flagd-core');
9
10
  var fs = require('fs');
10
11
 
@@ -43,13 +44,23 @@ typeof SuppressedError === "function" ? SuppressedError : function (error, suppr
43
44
  const EVENT_CONFIGURATION_CHANGE = 'configuration_change';
44
45
  const EVENT_PROVIDER_READY = 'provider_ready';
45
46
  const DEFAULT_MAX_CACHE_SIZE = 1000;
47
+ const DEFAULT_RETRY_GRACE_PERIOD = 5;
48
+ const DEFAULT_MAX_BACKOFF_MS = 12000;
49
+ const FLAGD_SELECTOR_HEADER = 'flagd-selector';
46
50
 
47
51
  const DEFAULT_CONFIG = {
52
+ deadlineMs: 500,
53
+ streamDeadlineMs: 600000,
48
54
  host: 'localhost',
49
55
  tls: false,
50
56
  selector: '',
51
57
  cache: 'lru',
52
58
  maxCacheSize: DEFAULT_MAX_CACHE_SIZE,
59
+ contextEnricher: (syncContext) => syncContext !== null && syncContext !== void 0 ? syncContext : {},
60
+ retryBackoffMs: 1000,
61
+ retryBackoffMaxMs: DEFAULT_MAX_BACKOFF_MS,
62
+ keepAliveTime: 0,
63
+ retryGracePeriod: DEFAULT_RETRY_GRACE_PERIOD,
53
64
  };
54
65
  const DEFAULT_RPC_CONFIG = Object.assign(Object.assign({}, DEFAULT_CONFIG), { resolverType: 'rpc', port: 8013 });
55
66
  const DEFAULT_IN_PROCESS_CONFIG = Object.assign(Object.assign({}, DEFAULT_CONFIG), { resolverType: 'in-process', port: 8015 });
@@ -57,45 +68,82 @@ var ENV_VAR;
57
68
  (function (ENV_VAR) {
58
69
  ENV_VAR["FLAGD_HOST"] = "FLAGD_HOST";
59
70
  ENV_VAR["FLAGD_PORT"] = "FLAGD_PORT";
71
+ ENV_VAR["FLAGD_SYNC_PORT"] = "FLAGD_SYNC_PORT";
72
+ ENV_VAR["FLAGD_DEADLINE_MS"] = "FLAGD_DEADLINE_MS";
73
+ ENV_VAR["FLAGD_STREAM_DEADLINE_MS"] = "FLAGD_STREAM_DEADLINE_MS";
60
74
  ENV_VAR["FLAGD_TLS"] = "FLAGD_TLS";
61
75
  ENV_VAR["FLAGD_SOCKET_PATH"] = "FLAGD_SOCKET_PATH";
76
+ ENV_VAR["FLAGD_SERVER_CERT_PATH"] = "FLAGD_SERVER_CERT_PATH";
62
77
  ENV_VAR["FLAGD_CACHE"] = "FLAGD_CACHE";
63
78
  ENV_VAR["FLAGD_MAX_CACHE_SIZE"] = "FLAGD_MAX_CACHE_SIZE";
64
79
  ENV_VAR["FLAGD_SOURCE_SELECTOR"] = "FLAGD_SOURCE_SELECTOR";
65
80
  ENV_VAR["FLAGD_RESOLVER"] = "FLAGD_RESOLVER";
66
81
  ENV_VAR["FLAGD_OFFLINE_FLAG_SOURCE_PATH"] = "FLAGD_OFFLINE_FLAG_SOURCE_PATH";
67
82
  ENV_VAR["FLAGD_DEFAULT_AUTHORITY"] = "FLAGD_DEFAULT_AUTHORITY";
83
+ ENV_VAR["FLAGD_RETRY_BACKOFF_MS"] = "FLAGD_RETRY_BACKOFF_MS";
84
+ ENV_VAR["FLAGD_RETRY_BACKOFF_MAX_MS"] = "FLAGD_RETRY_BACKOFF_MAX_MS";
85
+ ENV_VAR["FLAGD_KEEP_ALIVE_TIME_MS"] = "FLAGD_KEEP_ALIVE_TIME_MS";
86
+ ENV_VAR["FLAGD_FATAL_STATUS_CODES"] = "FLAGD_FATAL_STATUS_CODES";
87
+ ENV_VAR["FLAGD_RETRY_GRACE_PERIOD"] = "FLAGD_RETRY_GRACE_PERIOD";
68
88
  })(ENV_VAR || (ENV_VAR = {}));
69
- const getEnvVarConfig = () => {
89
+ function getEnvVarConfig() {
70
90
  var _a;
71
- return (Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({}, (process.env[ENV_VAR.FLAGD_HOST] && {
91
+ let provider = undefined;
92
+ if (process.env[ENV_VAR.FLAGD_RESOLVER] &&
93
+ (process.env[ENV_VAR.FLAGD_RESOLVER].toLowerCase() === 'rpc' ||
94
+ process.env[ENV_VAR.FLAGD_RESOLVER].toLowerCase() === 'in-process')) {
95
+ provider = process.env[ENV_VAR.FLAGD_RESOLVER].toLowerCase();
96
+ }
97
+ return Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({}, (process.env[ENV_VAR.FLAGD_HOST] && {
72
98
  host: process.env[ENV_VAR.FLAGD_HOST],
73
99
  })), (Number(process.env[ENV_VAR.FLAGD_PORT]) && {
74
100
  port: Number(process.env[ENV_VAR.FLAGD_PORT]),
101
+ })), (Number(process.env[ENV_VAR.FLAGD_SYNC_PORT]) && {
102
+ port: Number(process.env[ENV_VAR.FLAGD_SYNC_PORT]),
103
+ })), (Number(process.env[ENV_VAR.FLAGD_DEADLINE_MS]) && {
104
+ deadlineMs: Number(process.env[ENV_VAR.FLAGD_DEADLINE_MS]),
105
+ })), (Number(process.env[ENV_VAR.FLAGD_STREAM_DEADLINE_MS]) && {
106
+ streamDeadlineMs: Number(process.env[ENV_VAR.FLAGD_STREAM_DEADLINE_MS]),
75
107
  })), (process.env[ENV_VAR.FLAGD_TLS] && {
76
- tls: ((_a = process.env[ENV_VAR.FLAGD_TLS]) === null || _a === undefined ? undefined : _a.toLowerCase()) === 'true',
108
+ tls: ((_a = process.env[ENV_VAR.FLAGD_TLS]) === null || _a === void 0 ? void 0 : _a.toLowerCase()) === 'true',
77
109
  })), (process.env[ENV_VAR.FLAGD_SOCKET_PATH] && {
78
110
  socketPath: process.env[ENV_VAR.FLAGD_SOCKET_PATH],
111
+ })), (process.env[ENV_VAR.FLAGD_SERVER_CERT_PATH] && {
112
+ certPath: process.env[ENV_VAR.FLAGD_SERVER_CERT_PATH],
79
113
  })), ((process.env[ENV_VAR.FLAGD_CACHE] === 'lru' || process.env[ENV_VAR.FLAGD_CACHE] === 'disabled') && {
80
114
  cache: process.env[ENV_VAR.FLAGD_CACHE],
81
115
  })), (process.env[ENV_VAR.FLAGD_MAX_CACHE_SIZE] && {
82
116
  maxCacheSize: Number(process.env[ENV_VAR.FLAGD_MAX_CACHE_SIZE]),
83
117
  })), (process.env[ENV_VAR.FLAGD_SOURCE_SELECTOR] && {
84
118
  selector: process.env[ENV_VAR.FLAGD_SOURCE_SELECTOR],
85
- })), ((process.env[ENV_VAR.FLAGD_RESOLVER] === 'rpc' || process.env[ENV_VAR.FLAGD_RESOLVER] === 'in-process') && {
86
- resolverType: process.env[ENV_VAR.FLAGD_RESOLVER],
119
+ })), (provider && {
120
+ resolverType: provider,
87
121
  })), (process.env[ENV_VAR.FLAGD_OFFLINE_FLAG_SOURCE_PATH] && {
88
122
  offlineFlagSourcePath: process.env[ENV_VAR.FLAGD_OFFLINE_FLAG_SOURCE_PATH],
89
123
  })), (process.env[ENV_VAR.FLAGD_DEFAULT_AUTHORITY] && {
90
124
  defaultAuthority: process.env[ENV_VAR.FLAGD_DEFAULT_AUTHORITY],
91
- })));
92
- };
125
+ })), (Number(process.env[ENV_VAR.FLAGD_RETRY_BACKOFF_MS]) && {
126
+ retryBackoffMs: Number(process.env[ENV_VAR.FLAGD_RETRY_BACKOFF_MS]),
127
+ })), (Number(process.env[ENV_VAR.FLAGD_RETRY_BACKOFF_MAX_MS]) && {
128
+ retryBackoffMaxMs: Number(process.env[ENV_VAR.FLAGD_RETRY_BACKOFF_MAX_MS]),
129
+ })), (Number(process.env[ENV_VAR.FLAGD_KEEP_ALIVE_TIME_MS]) && {
130
+ keepAliveTime: Number(process.env[ENV_VAR.FLAGD_KEEP_ALIVE_TIME_MS]),
131
+ })), (process.env[ENV_VAR.FLAGD_FATAL_STATUS_CODES] && {
132
+ fatalStatusCodes: process.env[ENV_VAR.FLAGD_FATAL_STATUS_CODES]
133
+ .split(',')
134
+ .map((code) => code.trim())
135
+ .filter((code) => code.length > 0),
136
+ })), (process.env[ENV_VAR.FLAGD_RETRY_GRACE_PERIOD] && {
137
+ retryGracePeriod: Number(process.env[ENV_VAR.FLAGD_RETRY_GRACE_PERIOD]),
138
+ }));
139
+ }
93
140
  function getConfig(options = {}) {
141
+ var _a, _b;
94
142
  const envVarConfig = getEnvVarConfig();
95
143
  const defaultConfig = options.resolverType == 'in-process' || envVarConfig.resolverType == 'in-process'
96
144
  ? DEFAULT_IN_PROCESS_CONFIG
97
145
  : DEFAULT_RPC_CONFIG;
98
- return Object.assign(Object.assign(Object.assign({}, defaultConfig), envVarConfig), options);
146
+ return Object.assign(Object.assign(Object.assign(Object.assign({}, defaultConfig), envVarConfig), options), { streamDeadlineMs: (_b = (_a = options.streamDeadlineMs) !== null && _a !== void 0 ? _a : envVarConfig.streamDeadlineMs) !== null && _b !== void 0 ? _b : DEFAULT_CONFIG.streamDeadlineMs });
99
147
  }
100
148
 
101
149
  /**
@@ -121,10 +169,85 @@ function getConfig(options = {}) {
121
169
  // WebAssembly optimizations to do native i64 multiplication and divide
122
170
  var wasm = null;
123
171
  try {
124
- wasm = new WebAssembly.Instance(new WebAssembly.Module(new Uint8Array([
125
- 0, 97, 115, 109, 1, 0, 0, 0, 1, 13, 2, 96, 0, 1, 127, 96, 4, 127, 127, 127, 127, 1, 127, 3, 7, 6, 0, 1, 1, 1, 1, 1, 6, 6, 1, 127, 1, 65, 0, 11, 7, 50, 6, 3, 109, 117, 108, 0, 1, 5, 100, 105, 118, 95, 115, 0, 2, 5, 100, 105, 118, 95, 117, 0, 3, 5, 114, 101, 109, 95, 115, 0, 4, 5, 114, 101, 109, 95, 117, 0, 5, 8, 103, 101, 116, 95, 104, 105, 103, 104, 0, 0, 10, 191, 1, 6, 4, 0, 35, 0, 11, 36, 1, 1, 126, 32, 0, 173, 32, 1, 173, 66, 32, 134, 132, 32, 2, 173, 32, 3, 173, 66, 32, 134, 132, 126, 34, 4, 66, 32, 135, 167, 36, 0, 32, 4, 167, 11, 36, 1, 1, 126, 32, 0, 173, 32, 1, 173, 66, 32, 134, 132, 32, 2, 173, 32, 3, 173, 66, 32, 134, 132, 127, 34, 4, 66, 32, 135, 167, 36, 0, 32, 4, 167, 11, 36, 1, 1, 126, 32, 0, 173, 32, 1, 173, 66, 32, 134, 132, 32, 2, 173, 32, 3, 173, 66, 32, 134, 132, 128, 34, 4, 66, 32, 135, 167, 36, 0, 32, 4, 167, 11, 36, 1, 1, 126, 32, 0, 173, 32, 1, 173, 66, 32, 134, 132, 32, 2, 173, 32, 3, 173, 66, 32, 134, 132, 129, 34, 4, 66, 32, 135, 167, 36, 0, 32, 4, 167, 11, 36, 1, 1, 126, 32, 0, 173, 32, 1, 173, 66, 32, 134, 132, 32, 2, 173, 32, 3, 173, 66, 32, 134, 132, 130, 34, 4, 66, 32, 135, 167, 36, 0, 32, 4, 167, 11
126
- ])), {}).exports;
127
- } catch (e) {
172
+ wasm = new WebAssembly.Instance(
173
+ new WebAssembly.Module(
174
+ new Uint8Array([
175
+ // \0asm
176
+ 0, 97, 115, 109,
177
+ // version 1
178
+ 1, 0, 0, 0,
179
+
180
+ // section "type"
181
+ 1, 13, 2,
182
+ // 0, () => i32
183
+ 96, 0, 1, 127,
184
+ // 1, (i32, i32, i32, i32) => i32
185
+ 96, 4, 127, 127, 127, 127, 1, 127,
186
+
187
+ // section "function"
188
+ 3, 7, 6,
189
+ // 0, type 0
190
+ 0,
191
+ // 1, type 1
192
+ 1,
193
+ // 2, type 1
194
+ 1,
195
+ // 3, type 1
196
+ 1,
197
+ // 4, type 1
198
+ 1,
199
+ // 5, type 1
200
+ 1,
201
+
202
+ // section "global"
203
+ 6, 6, 1,
204
+ // 0, "high", mutable i32
205
+ 127, 1, 65, 0, 11,
206
+
207
+ // section "export"
208
+ 7, 50, 6,
209
+ // 0, "mul"
210
+ 3, 109, 117, 108, 0, 1,
211
+ // 1, "div_s"
212
+ 5, 100, 105, 118, 95, 115, 0, 2,
213
+ // 2, "div_u"
214
+ 5, 100, 105, 118, 95, 117, 0, 3,
215
+ // 3, "rem_s"
216
+ 5, 114, 101, 109, 95, 115, 0, 4,
217
+ // 4, "rem_u"
218
+ 5, 114, 101, 109, 95, 117, 0, 5,
219
+ // 5, "get_high"
220
+ 8, 103, 101, 116, 95, 104, 105, 103, 104, 0, 0,
221
+
222
+ // section "code"
223
+ 10, 191, 1, 6,
224
+ // 0, "get_high"
225
+ 4, 0, 35, 0, 11,
226
+ // 1, "mul"
227
+ 36, 1, 1, 126, 32, 0, 173, 32, 1, 173, 66, 32, 134, 132, 32, 2, 173, 32,
228
+ 3, 173, 66, 32, 134, 132, 126, 34, 4, 66, 32, 135, 167, 36, 0, 32, 4,
229
+ 167, 11,
230
+ // 2, "div_s"
231
+ 36, 1, 1, 126, 32, 0, 173, 32, 1, 173, 66, 32, 134, 132, 32, 2, 173, 32,
232
+ 3, 173, 66, 32, 134, 132, 127, 34, 4, 66, 32, 135, 167, 36, 0, 32, 4,
233
+ 167, 11,
234
+ // 3, "div_u"
235
+ 36, 1, 1, 126, 32, 0, 173, 32, 1, 173, 66, 32, 134, 132, 32, 2, 173, 32,
236
+ 3, 173, 66, 32, 134, 132, 128, 34, 4, 66, 32, 135, 167, 36, 0, 32, 4,
237
+ 167, 11,
238
+ // 4, "rem_s"
239
+ 36, 1, 1, 126, 32, 0, 173, 32, 1, 173, 66, 32, 134, 132, 32, 2, 173, 32,
240
+ 3, 173, 66, 32, 134, 132, 129, 34, 4, 66, 32, 135, 167, 36, 0, 32, 4,
241
+ 167, 11,
242
+ // 5, "rem_u"
243
+ 36, 1, 1, 126, 32, 0, 173, 32, 1, 173, 66, 32, 134, 132, 32, 2, 173, 32,
244
+ 3, 173, 66, 32, 134, 132, 130, 34, 4, 66, 32, 135, 167, 36, 0, 32, 4,
245
+ 167, 11,
246
+ ]),
247
+ ),
248
+ {},
249
+ ).exports;
250
+ } catch {
128
251
  // no wasm support :(
129
252
  }
130
253
 
@@ -139,7 +262,6 @@ try {
139
262
  * @constructor
140
263
  */
141
264
  function Long(low, high, unsigned) {
142
-
143
265
  /**
144
266
  * The low 32 bits as a signed value.
145
267
  * @type {number}
@@ -239,25 +361,21 @@ function fromInt(value, unsigned) {
239
361
  var obj, cachedObj, cache;
240
362
  if (unsigned) {
241
363
  value >>>= 0;
242
- if (cache = (0 <= value && value < 256)) {
364
+ if ((cache = 0 <= value && value < 256)) {
243
365
  cachedObj = UINT_CACHE[value];
244
- if (cachedObj)
245
- return cachedObj;
366
+ if (cachedObj) return cachedObj;
246
367
  }
247
368
  obj = fromBits(value, 0, true);
248
- if (cache)
249
- UINT_CACHE[value] = obj;
369
+ if (cache) UINT_CACHE[value] = obj;
250
370
  return obj;
251
371
  } else {
252
372
  value |= 0;
253
- if (cache = (-128 <= value && value < 128)) {
373
+ if ((cache = -128 <= value && value < 128)) {
254
374
  cachedObj = INT_CACHE[value];
255
- if (cachedObj)
256
- return cachedObj;
375
+ if (cachedObj) return cachedObj;
257
376
  }
258
377
  obj = fromBits(value, value < 0 ? -1 : 0, false);
259
- if (cache)
260
- INT_CACHE[value] = obj;
378
+ if (cache) INT_CACHE[value] = obj;
261
379
  return obj;
262
380
  }
263
381
  }
@@ -278,22 +396,20 @@ Long.fromInt = fromInt;
278
396
  * @inner
279
397
  */
280
398
  function fromNumber(value, unsigned) {
281
- if (isNaN(value))
282
- return unsigned ? UZERO : ZERO;
399
+ if (isNaN(value)) return unsigned ? UZERO : ZERO;
283
400
  if (unsigned) {
284
- if (value < 0)
285
- return UZERO;
286
- if (value >= TWO_PWR_64_DBL)
287
- return MAX_UNSIGNED_VALUE;
401
+ if (value < 0) return UZERO;
402
+ if (value >= TWO_PWR_64_DBL) return MAX_UNSIGNED_VALUE;
288
403
  } else {
289
- if (value <= -9223372036854776e3)
290
- return MIN_VALUE;
291
- if (value + 1 >= TWO_PWR_63_DBL)
292
- return MAX_VALUE;
404
+ if (value <= -9223372036854776e3) return MIN_VALUE;
405
+ if (value + 1 >= TWO_PWR_63_DBL) return MAX_VALUE;
293
406
  }
294
- if (value < 0)
295
- return fromNumber(-value, unsigned).neg();
296
- return fromBits((value % TWO_PWR_32_DBL) | 0, (value / TWO_PWR_32_DBL) | 0, unsigned);
407
+ if (value < 0) return fromNumber(-value, unsigned).neg();
408
+ return fromBits(
409
+ value % TWO_PWR_32_DBL | 0,
410
+ (value / TWO_PWR_32_DBL) | 0,
411
+ unsigned,
412
+ );
297
413
  }
298
414
 
299
415
  /**
@@ -344,24 +460,26 @@ var pow_dbl = Math.pow; // Used 4 times (4*8 to 15+4)
344
460
  * @inner
345
461
  */
346
462
  function fromString(str, unsigned, radix) {
347
- if (str.length === 0)
348
- throw Error('empty string');
349
- if (typeof unsigned === 'number') {
463
+ if (str.length === 0) throw Error("empty string");
464
+ if (typeof unsigned === "number") {
350
465
  // For goog.math.long compatibility
351
466
  radix = unsigned;
352
467
  unsigned = false;
353
468
  } else {
354
469
  unsigned = !!unsigned;
355
470
  }
356
- if (str === "NaN" || str === "Infinity" || str === "+Infinity" || str === "-Infinity")
471
+ if (
472
+ str === "NaN" ||
473
+ str === "Infinity" ||
474
+ str === "+Infinity" ||
475
+ str === "-Infinity"
476
+ )
357
477
  return unsigned ? UZERO : ZERO;
358
478
  radix = radix || 10;
359
- if (radix < 2 || 36 < radix)
360
- throw RangeError('radix');
479
+ if (radix < 2 || 36 < radix) throw RangeError("radix");
361
480
 
362
481
  var p;
363
- if ((p = str.indexOf('-')) > 0)
364
- throw Error('interior hyphen');
482
+ if ((p = str.indexOf("-")) > 0) throw Error("interior hyphen");
365
483
  else if (p === 0) {
366
484
  return fromString(str.substring(1), unsigned, radix).neg();
367
485
  }
@@ -404,18 +522,20 @@ Long.fromString = fromString;
404
522
  * @inner
405
523
  */
406
524
  function fromValue(val, unsigned) {
407
- if (typeof val === 'number')
408
- return fromNumber(val, unsigned);
409
- if (typeof val === 'string')
410
- return fromString(val, unsigned);
525
+ if (typeof val === "number") return fromNumber(val, unsigned);
526
+ if (typeof val === "string") return fromString(val, unsigned);
411
527
  // Throws for non-objects, converts non-instanceof Long:
412
- return fromBits(val.low, val.high, typeof unsigned === 'boolean' ? unsigned : val.unsigned);
528
+ return fromBits(
529
+ val.low,
530
+ val.high,
531
+ typeof unsigned === "boolean" ? unsigned : val.unsigned,
532
+ );
413
533
  }
414
534
 
415
535
  /**
416
536
  * Converts the specified value to a Long using the appropriate from* function for its type.
417
537
  * @function
418
- * @param {!Long|number|string|!{low: number, high: number, unsigned: boolean}} val Value
538
+ * @param {!Long|number|bigint|string|!{low: number, high: number, unsigned: boolean}} val Value
419
539
  * @param {boolean=} unsigned Whether unsigned or not, defaults to signed
420
540
  * @returns {!Long}
421
541
  */
@@ -530,7 +650,7 @@ Long.NEG_ONE = NEG_ONE;
530
650
  * @type {!Long}
531
651
  * @inner
532
652
  */
533
- var MAX_VALUE = fromBits(0xFFFFFFFF | 0, 0x7FFFFFFF | 0, false);
653
+ var MAX_VALUE = fromBits(0xffffffff | 0, 0x7fffffff | 0, false);
534
654
 
535
655
  /**
536
656
  * Maximum signed value.
@@ -542,7 +662,7 @@ Long.MAX_VALUE = MAX_VALUE;
542
662
  * @type {!Long}
543
663
  * @inner
544
664
  */
545
- var MAX_UNSIGNED_VALUE = fromBits(0xFFFFFFFF | 0, 0xFFFFFFFF | 0, true);
665
+ var MAX_UNSIGNED_VALUE = fromBits(0xffffffff | 0, 0xffffffff | 0, true);
546
666
 
547
667
  /**
548
668
  * Maximum unsigned value.
@@ -584,7 +704,7 @@ LongPrototype.toInt = function toInt() {
584
704
  */
585
705
  LongPrototype.toNumber = function toNumber() {
586
706
  if (this.unsigned)
587
- return ((this.high >>> 0) * TWO_PWR_32_DBL) + (this.low >>> 0);
707
+ return (this.high >>> 0) * TWO_PWR_32_DBL + (this.low >>> 0);
588
708
  return this.high * TWO_PWR_32_DBL + (this.low >>> 0);
589
709
  };
590
710
 
@@ -598,11 +718,10 @@ LongPrototype.toNumber = function toNumber() {
598
718
  */
599
719
  LongPrototype.toString = function toString(radix) {
600
720
  radix = radix || 10;
601
- if (radix < 2 || 36 < radix)
602
- throw RangeError('radix');
603
- if (this.isZero())
604
- return '0';
605
- if (this.isNegative()) { // Unsigned Longs are never negative
721
+ if (radix < 2 || 36 < radix) throw RangeError("radix");
722
+ if (this.isZero()) return "0";
723
+ if (this.isNegative()) {
724
+ // Unsigned Longs are never negative
606
725
  if (this.eq(MIN_VALUE)) {
607
726
  // We need to change the Long value before it can be negated, so we remove
608
727
  // the bottom-most digit in this base and then recurse to do the rest.
@@ -610,26 +729,23 @@ LongPrototype.toString = function toString(radix) {
610
729
  div = this.div(radixLong),
611
730
  rem1 = div.mul(radixLong).sub(this);
612
731
  return div.toString(radix) + rem1.toInt().toString(radix);
613
- } else
614
- return '-' + this.neg().toString(radix);
732
+ } else return "-" + this.neg().toString(radix);
615
733
  }
616
734
 
617
735
  // Do several (6) digits each time through the loop, so as to
618
736
  // minimize the calls to the very expensive emulated div.
619
737
  var radixToPower = fromNumber(pow_dbl(radix, 6), this.unsigned),
620
738
  rem = this;
621
- var result = '';
739
+ var result = "";
622
740
  while (true) {
623
741
  var remDiv = rem.div(radixToPower),
624
742
  intval = rem.sub(remDiv.mul(radixToPower)).toInt() >>> 0,
625
743
  digits = intval.toString(radix);
626
744
  rem = remDiv;
627
- if (rem.isZero())
628
- return digits + result;
745
+ if (rem.isZero()) return digits + result;
629
746
  else {
630
- while (digits.length < 6)
631
- digits = '0' + digits;
632
- result = '' + digits + result;
747
+ while (digits.length < 6) digits = "0" + digits;
748
+ result = "" + digits + result;
633
749
  }
634
750
  }
635
751
  };
@@ -676,15 +792,30 @@ LongPrototype.getLowBitsUnsigned = function getLowBitsUnsigned() {
676
792
  * @returns {number}
677
793
  */
678
794
  LongPrototype.getNumBitsAbs = function getNumBitsAbs() {
679
- if (this.isNegative()) // Unsigned Longs are never negative
795
+ if (this.isNegative())
796
+ // Unsigned Longs are never negative
680
797
  return this.eq(MIN_VALUE) ? 64 : this.neg().getNumBitsAbs();
681
798
  var val = this.high != 0 ? this.high : this.low;
682
- for (var bit = 31; bit > 0; bit--)
683
- if ((val & (1 << bit)) != 0)
684
- break;
799
+ for (var bit = 31; bit > 0; bit--) if ((val & (1 << bit)) != 0) break;
685
800
  return this.high != 0 ? bit + 33 : bit + 1;
686
801
  };
687
802
 
803
+ /**
804
+ * Tests if this Long can be safely represented as a JavaScript number.
805
+ * @this {!Long}
806
+ * @returns {boolean}
807
+ */
808
+ LongPrototype.isSafeInteger = function isSafeInteger() {
809
+ // 2^53-1 is the maximum safe value
810
+ var top11Bits = this.high >> 21;
811
+ // [0, 2^53-1]
812
+ if (!top11Bits) return true;
813
+ // > 2^53-1
814
+ if (this.unsigned) return false;
815
+ // [-2^53, -1] except -2^53
816
+ return top11Bits === -1 && !(this.low === 0 && this.high === -2097152);
817
+ };
818
+
688
819
  /**
689
820
  * Tests if this Long's value equals zero.
690
821
  * @this {!Long}
@@ -739,13 +870,16 @@ LongPrototype.isEven = function isEven() {
739
870
  /**
740
871
  * Tests if this Long's value equals the specified's.
741
872
  * @this {!Long}
742
- * @param {!Long|number|string} other Other value
873
+ * @param {!Long|number|bigint|string} other Other value
743
874
  * @returns {boolean}
744
875
  */
745
876
  LongPrototype.equals = function equals(other) {
746
- if (!isLong(other))
747
- other = fromValue(other);
748
- if (this.unsigned !== other.unsigned && (this.high >>> 31) === 1 && (other.high >>> 31) === 1)
877
+ if (!isLong(other)) other = fromValue(other);
878
+ if (
879
+ this.unsigned !== other.unsigned &&
880
+ this.high >>> 31 === 1 &&
881
+ other.high >>> 31 === 1
882
+ )
749
883
  return false;
750
884
  return this.high === other.high && this.low === other.low;
751
885
  };
@@ -753,7 +887,7 @@ LongPrototype.equals = function equals(other) {
753
887
  /**
754
888
  * Tests if this Long's value equals the specified's. This is an alias of {@link Long#equals}.
755
889
  * @function
756
- * @param {!Long|number|string} other Other value
890
+ * @param {!Long|number|bigint|string} other Other value
757
891
  * @returns {boolean}
758
892
  */
759
893
  LongPrototype.eq = LongPrototype.equals;
@@ -761,7 +895,7 @@ LongPrototype.eq = LongPrototype.equals;
761
895
  /**
762
896
  * Tests if this Long's value differs from the specified's.
763
897
  * @this {!Long}
764
- * @param {!Long|number|string} other Other value
898
+ * @param {!Long|number|bigint|string} other Other value
765
899
  * @returns {boolean}
766
900
  */
767
901
  LongPrototype.notEquals = function notEquals(other) {
@@ -771,7 +905,7 @@ LongPrototype.notEquals = function notEquals(other) {
771
905
  /**
772
906
  * Tests if this Long's value differs from the specified's. This is an alias of {@link Long#notEquals}.
773
907
  * @function
774
- * @param {!Long|number|string} other Other value
908
+ * @param {!Long|number|bigint|string} other Other value
775
909
  * @returns {boolean}
776
910
  */
777
911
  LongPrototype.neq = LongPrototype.notEquals;
@@ -779,7 +913,7 @@ LongPrototype.neq = LongPrototype.notEquals;
779
913
  /**
780
914
  * Tests if this Long's value differs from the specified's. This is an alias of {@link Long#notEquals}.
781
915
  * @function
782
- * @param {!Long|number|string} other Other value
916
+ * @param {!Long|number|bigint|string} other Other value
783
917
  * @returns {boolean}
784
918
  */
785
919
  LongPrototype.ne = LongPrototype.notEquals;
@@ -787,7 +921,7 @@ LongPrototype.ne = LongPrototype.notEquals;
787
921
  /**
788
922
  * Tests if this Long's value is less than the specified's.
789
923
  * @this {!Long}
790
- * @param {!Long|number|string} other Other value
924
+ * @param {!Long|number|bigint|string} other Other value
791
925
  * @returns {boolean}
792
926
  */
793
927
  LongPrototype.lessThan = function lessThan(other) {
@@ -797,7 +931,7 @@ LongPrototype.lessThan = function lessThan(other) {
797
931
  /**
798
932
  * Tests if this Long's value is less than the specified's. This is an alias of {@link Long#lessThan}.
799
933
  * @function
800
- * @param {!Long|number|string} other Other value
934
+ * @param {!Long|number|bigint|string} other Other value
801
935
  * @returns {boolean}
802
936
  */
803
937
  LongPrototype.lt = LongPrototype.lessThan;
@@ -805,7 +939,7 @@ LongPrototype.lt = LongPrototype.lessThan;
805
939
  /**
806
940
  * Tests if this Long's value is less than or equal the specified's.
807
941
  * @this {!Long}
808
- * @param {!Long|number|string} other Other value
942
+ * @param {!Long|number|bigint|string} other Other value
809
943
  * @returns {boolean}
810
944
  */
811
945
  LongPrototype.lessThanOrEqual = function lessThanOrEqual(other) {
@@ -815,7 +949,7 @@ LongPrototype.lessThanOrEqual = function lessThanOrEqual(other) {
815
949
  /**
816
950
  * Tests if this Long's value is less than or equal the specified's. This is an alias of {@link Long#lessThanOrEqual}.
817
951
  * @function
818
- * @param {!Long|number|string} other Other value
952
+ * @param {!Long|number|bigint|string} other Other value
819
953
  * @returns {boolean}
820
954
  */
821
955
  LongPrototype.lte = LongPrototype.lessThanOrEqual;
@@ -823,7 +957,7 @@ LongPrototype.lte = LongPrototype.lessThanOrEqual;
823
957
  /**
824
958
  * Tests if this Long's value is less than or equal the specified's. This is an alias of {@link Long#lessThanOrEqual}.
825
959
  * @function
826
- * @param {!Long|number|string} other Other value
960
+ * @param {!Long|number|bigint|string} other Other value
827
961
  * @returns {boolean}
828
962
  */
829
963
  LongPrototype.le = LongPrototype.lessThanOrEqual;
@@ -831,7 +965,7 @@ LongPrototype.le = LongPrototype.lessThanOrEqual;
831
965
  /**
832
966
  * Tests if this Long's value is greater than the specified's.
833
967
  * @this {!Long}
834
- * @param {!Long|number|string} other Other value
968
+ * @param {!Long|number|bigint|string} other Other value
835
969
  * @returns {boolean}
836
970
  */
837
971
  LongPrototype.greaterThan = function greaterThan(other) {
@@ -841,7 +975,7 @@ LongPrototype.greaterThan = function greaterThan(other) {
841
975
  /**
842
976
  * Tests if this Long's value is greater than the specified's. This is an alias of {@link Long#greaterThan}.
843
977
  * @function
844
- * @param {!Long|number|string} other Other value
978
+ * @param {!Long|number|bigint|string} other Other value
845
979
  * @returns {boolean}
846
980
  */
847
981
  LongPrototype.gt = LongPrototype.greaterThan;
@@ -849,7 +983,7 @@ LongPrototype.gt = LongPrototype.greaterThan;
849
983
  /**
850
984
  * Tests if this Long's value is greater than or equal the specified's.
851
985
  * @this {!Long}
852
- * @param {!Long|number|string} other Other value
986
+ * @param {!Long|number|bigint|string} other Other value
853
987
  * @returns {boolean}
854
988
  */
855
989
  LongPrototype.greaterThanOrEqual = function greaterThanOrEqual(other) {
@@ -859,7 +993,7 @@ LongPrototype.greaterThanOrEqual = function greaterThanOrEqual(other) {
859
993
  /**
860
994
  * Tests if this Long's value is greater than or equal the specified's. This is an alias of {@link Long#greaterThanOrEqual}.
861
995
  * @function
862
- * @param {!Long|number|string} other Other value
996
+ * @param {!Long|number|bigint|string} other Other value
863
997
  * @returns {boolean}
864
998
  */
865
999
  LongPrototype.gte = LongPrototype.greaterThanOrEqual;
@@ -867,7 +1001,7 @@ LongPrototype.gte = LongPrototype.greaterThanOrEqual;
867
1001
  /**
868
1002
  * Tests if this Long's value is greater than or equal the specified's. This is an alias of {@link Long#greaterThanOrEqual}.
869
1003
  * @function
870
- * @param {!Long|number|string} other Other value
1004
+ * @param {!Long|number|bigint|string} other Other value
871
1005
  * @returns {boolean}
872
1006
  */
873
1007
  LongPrototype.ge = LongPrototype.greaterThanOrEqual;
@@ -875,32 +1009,30 @@ LongPrototype.ge = LongPrototype.greaterThanOrEqual;
875
1009
  /**
876
1010
  * Compares this Long's value with the specified's.
877
1011
  * @this {!Long}
878
- * @param {!Long|number|string} other Other value
1012
+ * @param {!Long|number|bigint|string} other Other value
879
1013
  * @returns {number} 0 if they are the same, 1 if the this is greater and -1
880
1014
  * if the given one is greater
881
1015
  */
882
1016
  LongPrototype.compare = function compare(other) {
883
- if (!isLong(other))
884
- other = fromValue(other);
885
- if (this.eq(other))
886
- return 0;
1017
+ if (!isLong(other)) other = fromValue(other);
1018
+ if (this.eq(other)) return 0;
887
1019
  var thisNeg = this.isNegative(),
888
1020
  otherNeg = other.isNegative();
889
- if (thisNeg && !otherNeg)
890
- return -1;
891
- if (!thisNeg && otherNeg)
892
- return 1;
1021
+ if (thisNeg && !otherNeg) return -1;
1022
+ if (!thisNeg && otherNeg) return 1;
893
1023
  // At this point the sign bits are the same
894
- if (!this.unsigned)
895
- return this.sub(other).isNegative() ? -1 : 1;
1024
+ if (!this.unsigned) return this.sub(other).isNegative() ? -1 : 1;
896
1025
  // Both are positive if at least one is unsigned
897
- return (other.high >>> 0) > (this.high >>> 0) || (other.high === this.high && (other.low >>> 0) > (this.low >>> 0)) ? -1 : 1;
1026
+ return other.high >>> 0 > this.high >>> 0 ||
1027
+ (other.high === this.high && other.low >>> 0 > this.low >>> 0)
1028
+ ? -1
1029
+ : 1;
898
1030
  };
899
1031
 
900
1032
  /**
901
1033
  * Compares this Long's value with the specified's. This is an alias of {@link Long#compare}.
902
1034
  * @function
903
- * @param {!Long|number|string} other Other value
1035
+ * @param {!Long|number|bigint|string} other Other value
904
1036
  * @returns {number} 0 if they are the same, 1 if the this is greater and -1
905
1037
  * if the given one is greater
906
1038
  */
@@ -912,8 +1044,7 @@ LongPrototype.comp = LongPrototype.compare;
912
1044
  * @returns {!Long} Negated Long
913
1045
  */
914
1046
  LongPrototype.negate = function negate() {
915
- if (!this.unsigned && this.eq(MIN_VALUE))
916
- return MIN_VALUE;
1047
+ if (!this.unsigned && this.eq(MIN_VALUE)) return MIN_VALUE;
917
1048
  return this.not().add(ONE);
918
1049
  };
919
1050
 
@@ -927,56 +1058,57 @@ LongPrototype.neg = LongPrototype.negate;
927
1058
  /**
928
1059
  * Returns the sum of this and the specified Long.
929
1060
  * @this {!Long}
930
- * @param {!Long|number|string} addend Addend
1061
+ * @param {!Long|number|bigint|string} addend Addend
931
1062
  * @returns {!Long} Sum
932
1063
  */
933
1064
  LongPrototype.add = function add(addend) {
934
- if (!isLong(addend))
935
- addend = fromValue(addend);
1065
+ if (!isLong(addend)) addend = fromValue(addend);
936
1066
 
937
1067
  // Divide each number into 4 chunks of 16 bits, and then sum the chunks.
938
1068
 
939
1069
  var a48 = this.high >>> 16;
940
- var a32 = this.high & 0xFFFF;
1070
+ var a32 = this.high & 0xffff;
941
1071
  var a16 = this.low >>> 16;
942
- var a00 = this.low & 0xFFFF;
1072
+ var a00 = this.low & 0xffff;
943
1073
 
944
1074
  var b48 = addend.high >>> 16;
945
- var b32 = addend.high & 0xFFFF;
1075
+ var b32 = addend.high & 0xffff;
946
1076
  var b16 = addend.low >>> 16;
947
- var b00 = addend.low & 0xFFFF;
1077
+ var b00 = addend.low & 0xffff;
948
1078
 
949
- var c48 = 0, c32 = 0, c16 = 0, c00 = 0;
1079
+ var c48 = 0,
1080
+ c32 = 0,
1081
+ c16 = 0,
1082
+ c00 = 0;
950
1083
  c00 += a00 + b00;
951
1084
  c16 += c00 >>> 16;
952
- c00 &= 0xFFFF;
1085
+ c00 &= 0xffff;
953
1086
  c16 += a16 + b16;
954
1087
  c32 += c16 >>> 16;
955
- c16 &= 0xFFFF;
1088
+ c16 &= 0xffff;
956
1089
  c32 += a32 + b32;
957
1090
  c48 += c32 >>> 16;
958
- c32 &= 0xFFFF;
1091
+ c32 &= 0xffff;
959
1092
  c48 += a48 + b48;
960
- c48 &= 0xFFFF;
1093
+ c48 &= 0xffff;
961
1094
  return fromBits((c16 << 16) | c00, (c48 << 16) | c32, this.unsigned);
962
1095
  };
963
1096
 
964
1097
  /**
965
1098
  * Returns the difference of this and the specified Long.
966
1099
  * @this {!Long}
967
- * @param {!Long|number|string} subtrahend Subtrahend
1100
+ * @param {!Long|number|bigint|string} subtrahend Subtrahend
968
1101
  * @returns {!Long} Difference
969
1102
  */
970
1103
  LongPrototype.subtract = function subtract(subtrahend) {
971
- if (!isLong(subtrahend))
972
- subtrahend = fromValue(subtrahend);
1104
+ if (!isLong(subtrahend)) subtrahend = fromValue(subtrahend);
973
1105
  return this.add(subtrahend.neg());
974
1106
  };
975
1107
 
976
1108
  /**
977
1109
  * Returns the difference of this and the specified Long. This is an alias of {@link Long#subtract}.
978
1110
  * @function
979
- * @param {!Long|number|string} subtrahend Subtrahend
1111
+ * @param {!Long|number|bigint|string} subtrahend Subtrahend
980
1112
  * @returns {!Long} Difference
981
1113
  */
982
1114
  LongPrototype.sub = LongPrototype.subtract;
@@ -984,38 +1116,27 @@ LongPrototype.sub = LongPrototype.subtract;
984
1116
  /**
985
1117
  * Returns the product of this and the specified Long.
986
1118
  * @this {!Long}
987
- * @param {!Long|number|string} multiplier Multiplier
1119
+ * @param {!Long|number|bigint|string} multiplier Multiplier
988
1120
  * @returns {!Long} Product
989
1121
  */
990
1122
  LongPrototype.multiply = function multiply(multiplier) {
991
- if (this.isZero())
992
- return this;
993
- if (!isLong(multiplier))
994
- multiplier = fromValue(multiplier);
1123
+ if (this.isZero()) return this;
1124
+ if (!isLong(multiplier)) multiplier = fromValue(multiplier);
995
1125
 
996
1126
  // use wasm support if present
997
1127
  if (wasm) {
998
- var low = wasm["mul"](this.low,
999
- this.high,
1000
- multiplier.low,
1001
- multiplier.high);
1128
+ var low = wasm["mul"](this.low, this.high, multiplier.low, multiplier.high);
1002
1129
  return fromBits(low, wasm["get_high"](), this.unsigned);
1003
1130
  }
1004
1131
 
1005
- if (multiplier.isZero())
1006
- return this.unsigned ? UZERO : ZERO;
1007
- if (this.eq(MIN_VALUE))
1008
- return multiplier.isOdd() ? MIN_VALUE : ZERO;
1009
- if (multiplier.eq(MIN_VALUE))
1010
- return this.isOdd() ? MIN_VALUE : ZERO;
1132
+ if (multiplier.isZero()) return this.unsigned ? UZERO : ZERO;
1133
+ if (this.eq(MIN_VALUE)) return multiplier.isOdd() ? MIN_VALUE : ZERO;
1134
+ if (multiplier.eq(MIN_VALUE)) return this.isOdd() ? MIN_VALUE : ZERO;
1011
1135
 
1012
1136
  if (this.isNegative()) {
1013
- if (multiplier.isNegative())
1014
- return this.neg().mul(multiplier.neg());
1015
- else
1016
- return this.neg().mul(multiplier).neg();
1017
- } else if (multiplier.isNegative())
1018
- return this.mul(multiplier.neg()).neg();
1137
+ if (multiplier.isNegative()) return this.neg().mul(multiplier.neg());
1138
+ else return this.neg().mul(multiplier).neg();
1139
+ } else if (multiplier.isNegative()) return this.mul(multiplier.neg()).neg();
1019
1140
 
1020
1141
  // If both longs are small, use float multiplication
1021
1142
  if (this.lt(TWO_PWR_24) && multiplier.lt(TWO_PWR_24))
@@ -1025,43 +1146,46 @@ LongPrototype.multiply = function multiply(multiplier) {
1025
1146
  // We can skip products that would overflow.
1026
1147
 
1027
1148
  var a48 = this.high >>> 16;
1028
- var a32 = this.high & 0xFFFF;
1149
+ var a32 = this.high & 0xffff;
1029
1150
  var a16 = this.low >>> 16;
1030
- var a00 = this.low & 0xFFFF;
1151
+ var a00 = this.low & 0xffff;
1031
1152
 
1032
1153
  var b48 = multiplier.high >>> 16;
1033
- var b32 = multiplier.high & 0xFFFF;
1154
+ var b32 = multiplier.high & 0xffff;
1034
1155
  var b16 = multiplier.low >>> 16;
1035
- var b00 = multiplier.low & 0xFFFF;
1156
+ var b00 = multiplier.low & 0xffff;
1036
1157
 
1037
- var c48 = 0, c32 = 0, c16 = 0, c00 = 0;
1158
+ var c48 = 0,
1159
+ c32 = 0,
1160
+ c16 = 0,
1161
+ c00 = 0;
1038
1162
  c00 += a00 * b00;
1039
1163
  c16 += c00 >>> 16;
1040
- c00 &= 0xFFFF;
1164
+ c00 &= 0xffff;
1041
1165
  c16 += a16 * b00;
1042
1166
  c32 += c16 >>> 16;
1043
- c16 &= 0xFFFF;
1167
+ c16 &= 0xffff;
1044
1168
  c16 += a00 * b16;
1045
1169
  c32 += c16 >>> 16;
1046
- c16 &= 0xFFFF;
1170
+ c16 &= 0xffff;
1047
1171
  c32 += a32 * b00;
1048
1172
  c48 += c32 >>> 16;
1049
- c32 &= 0xFFFF;
1173
+ c32 &= 0xffff;
1050
1174
  c32 += a16 * b16;
1051
1175
  c48 += c32 >>> 16;
1052
- c32 &= 0xFFFF;
1176
+ c32 &= 0xffff;
1053
1177
  c32 += a00 * b32;
1054
1178
  c48 += c32 >>> 16;
1055
- c32 &= 0xFFFF;
1179
+ c32 &= 0xffff;
1056
1180
  c48 += a48 * b00 + a32 * b16 + a16 * b32 + a00 * b48;
1057
- c48 &= 0xFFFF;
1181
+ c48 &= 0xffff;
1058
1182
  return fromBits((c16 << 16) | c00, (c48 << 16) | c32, this.unsigned);
1059
1183
  };
1060
1184
 
1061
1185
  /**
1062
1186
  * Returns the product of this and the specified Long. This is an alias of {@link Long#multiply}.
1063
1187
  * @function
1064
- * @param {!Long|number|string} multiplier Multiplier
1188
+ * @param {!Long|number|bigint|string} multiplier Multiplier
1065
1189
  * @returns {!Long} Product
1066
1190
  */
1067
1191
  LongPrototype.mul = LongPrototype.multiply;
@@ -1070,23 +1194,24 @@ LongPrototype.mul = LongPrototype.multiply;
1070
1194
  * Returns this Long divided by the specified. The result is signed if this Long is signed or
1071
1195
  * unsigned if this Long is unsigned.
1072
1196
  * @this {!Long}
1073
- * @param {!Long|number|string} divisor Divisor
1197
+ * @param {!Long|number|bigint|string} divisor Divisor
1074
1198
  * @returns {!Long} Quotient
1075
1199
  */
1076
1200
  LongPrototype.divide = function divide(divisor) {
1077
- if (!isLong(divisor))
1078
- divisor = fromValue(divisor);
1079
- if (divisor.isZero())
1080
- throw Error('division by zero');
1201
+ if (!isLong(divisor)) divisor = fromValue(divisor);
1202
+ if (divisor.isZero()) throw Error("division by zero");
1081
1203
 
1082
1204
  // use wasm support if present
1083
1205
  if (wasm) {
1084
1206
  // guard against signed division overflow: the largest
1085
1207
  // negative number / -1 would be 1 larger than the largest
1086
1208
  // positive number, due to two's complement.
1087
- if (!this.unsigned &&
1209
+ if (
1210
+ !this.unsigned &&
1088
1211
  this.high === -2147483648 &&
1089
- divisor.low === -1 && divisor.high === -1) {
1212
+ divisor.low === -1 &&
1213
+ divisor.high === -1
1214
+ ) {
1090
1215
  // be consistent with non-wasm code path
1091
1216
  return this;
1092
1217
  }
@@ -1094,22 +1219,20 @@ LongPrototype.divide = function divide(divisor) {
1094
1219
  this.low,
1095
1220
  this.high,
1096
1221
  divisor.low,
1097
- divisor.high
1222
+ divisor.high,
1098
1223
  );
1099
1224
  return fromBits(low, wasm["get_high"](), this.unsigned);
1100
1225
  }
1101
1226
 
1102
- if (this.isZero())
1103
- return this.unsigned ? UZERO : ZERO;
1227
+ if (this.isZero()) return this.unsigned ? UZERO : ZERO;
1104
1228
  var approx, rem, res;
1105
1229
  if (!this.unsigned) {
1106
1230
  // This section is only relevant for signed longs and is derived from the
1107
1231
  // closure library as a whole.
1108
1232
  if (this.eq(MIN_VALUE)) {
1109
1233
  if (divisor.eq(ONE) || divisor.eq(NEG_ONE))
1110
- return MIN_VALUE; // recall that -MIN_VALUE == MIN_VALUE
1111
- else if (divisor.eq(MIN_VALUE))
1112
- return ONE;
1234
+ return MIN_VALUE; // recall that -MIN_VALUE == MIN_VALUE
1235
+ else if (divisor.eq(MIN_VALUE)) return ONE;
1113
1236
  else {
1114
1237
  // At this point, we have |other| >= 2, so |this/other| < |MIN_VALUE|.
1115
1238
  var halfThis = this.shr(1);
@@ -1122,23 +1245,19 @@ LongPrototype.divide = function divide(divisor) {
1122
1245
  return res;
1123
1246
  }
1124
1247
  }
1125
- } else if (divisor.eq(MIN_VALUE))
1126
- return this.unsigned ? UZERO : ZERO;
1248
+ } else if (divisor.eq(MIN_VALUE)) return this.unsigned ? UZERO : ZERO;
1127
1249
  if (this.isNegative()) {
1128
- if (divisor.isNegative())
1129
- return this.neg().div(divisor.neg());
1250
+ if (divisor.isNegative()) return this.neg().div(divisor.neg());
1130
1251
  return this.neg().div(divisor).neg();
1131
- } else if (divisor.isNegative())
1132
- return this.div(divisor.neg()).neg();
1252
+ } else if (divisor.isNegative()) return this.div(divisor.neg()).neg();
1133
1253
  res = ZERO;
1134
1254
  } else {
1135
1255
  // The algorithm below has not been made for unsigned longs. It's therefore
1136
1256
  // required to take special care of the MSB prior to running it.
1137
- if (!divisor.unsigned)
1138
- divisor = divisor.toUnsigned();
1139
- if (divisor.gt(this))
1140
- return UZERO;
1141
- if (divisor.gt(this.shru(1))) // 15 >>> 1 = 7 ; with divisor = 8 ; true
1257
+ if (!divisor.unsigned) divisor = divisor.toUnsigned();
1258
+ if (divisor.gt(this)) return UZERO;
1259
+ if (divisor.gt(this.shru(1)))
1260
+ // 15 >>> 1 = 7 ; with divisor = 8 ; true
1142
1261
  return UONE;
1143
1262
  res = UZERO;
1144
1263
  }
@@ -1157,8 +1276,7 @@ LongPrototype.divide = function divide(divisor) {
1157
1276
  // We will tweak the approximate result by changing it in the 48-th digit or
1158
1277
  // the smallest non-fractional digit, whichever is larger.
1159
1278
  var log2 = Math.ceil(Math.log(approx) / Math.LN2),
1160
- delta = (log2 <= 48) ? 1 : pow_dbl(2, log2 - 48),
1161
-
1279
+ delta = log2 <= 48 ? 1 : pow_dbl(2, log2 - 48),
1162
1280
  // Decrease the approximation until it is smaller than the remainder. Note
1163
1281
  // that if it is too large, the product overflows and is negative.
1164
1282
  approxRes = fromNumber(approx),
@@ -1171,8 +1289,7 @@ LongPrototype.divide = function divide(divisor) {
1171
1289
 
1172
1290
  // We know the answer can't be zero... and actually, zero would cause
1173
1291
  // infinite recursion since we would make no progress.
1174
- if (approxRes.isZero())
1175
- approxRes = ONE;
1292
+ if (approxRes.isZero()) approxRes = ONE;
1176
1293
 
1177
1294
  res = res.add(approxRes);
1178
1295
  rem = rem.sub(approxRem);
@@ -1183,7 +1300,7 @@ LongPrototype.divide = function divide(divisor) {
1183
1300
  /**
1184
1301
  * Returns this Long divided by the specified. This is an alias of {@link Long#divide}.
1185
1302
  * @function
1186
- * @param {!Long|number|string} divisor Divisor
1303
+ * @param {!Long|number|bigint|string} divisor Divisor
1187
1304
  * @returns {!Long} Quotient
1188
1305
  */
1189
1306
  LongPrototype.div = LongPrototype.divide;
@@ -1191,12 +1308,11 @@ LongPrototype.div = LongPrototype.divide;
1191
1308
  /**
1192
1309
  * Returns this Long modulo the specified.
1193
1310
  * @this {!Long}
1194
- * @param {!Long|number|string} divisor Divisor
1311
+ * @param {!Long|number|bigint|string} divisor Divisor
1195
1312
  * @returns {!Long} Remainder
1196
1313
  */
1197
1314
  LongPrototype.modulo = function modulo(divisor) {
1198
- if (!isLong(divisor))
1199
- divisor = fromValue(divisor);
1315
+ if (!isLong(divisor)) divisor = fromValue(divisor);
1200
1316
 
1201
1317
  // use wasm support if present
1202
1318
  if (wasm) {
@@ -1204,7 +1320,7 @@ LongPrototype.modulo = function modulo(divisor) {
1204
1320
  this.low,
1205
1321
  this.high,
1206
1322
  divisor.low,
1207
- divisor.high
1323
+ divisor.high,
1208
1324
  );
1209
1325
  return fromBits(low, wasm["get_high"](), this.unsigned);
1210
1326
  }
@@ -1215,7 +1331,7 @@ LongPrototype.modulo = function modulo(divisor) {
1215
1331
  /**
1216
1332
  * Returns this Long modulo the specified. This is an alias of {@link Long#modulo}.
1217
1333
  * @function
1218
- * @param {!Long|number|string} divisor Divisor
1334
+ * @param {!Long|number|bigint|string} divisor Divisor
1219
1335
  * @returns {!Long} Remainder
1220
1336
  */
1221
1337
  LongPrototype.mod = LongPrototype.modulo;
@@ -1223,7 +1339,7 @@ LongPrototype.mod = LongPrototype.modulo;
1223
1339
  /**
1224
1340
  * Returns this Long modulo the specified. This is an alias of {@link Long#modulo}.
1225
1341
  * @function
1226
- * @param {!Long|number|string} divisor Divisor
1342
+ * @param {!Long|number|bigint|string} divisor Divisor
1227
1343
  * @returns {!Long} Remainder
1228
1344
  */
1229
1345
  LongPrototype.rem = LongPrototype.modulo;
@@ -1274,36 +1390,33 @@ LongPrototype.ctz = LongPrototype.countTrailingZeros;
1274
1390
  /**
1275
1391
  * Returns the bitwise AND of this Long and the specified.
1276
1392
  * @this {!Long}
1277
- * @param {!Long|number|string} other Other Long
1393
+ * @param {!Long|number|bigint|string} other Other Long
1278
1394
  * @returns {!Long}
1279
1395
  */
1280
1396
  LongPrototype.and = function and(other) {
1281
- if (!isLong(other))
1282
- other = fromValue(other);
1397
+ if (!isLong(other)) other = fromValue(other);
1283
1398
  return fromBits(this.low & other.low, this.high & other.high, this.unsigned);
1284
1399
  };
1285
1400
 
1286
1401
  /**
1287
1402
  * Returns the bitwise OR of this Long and the specified.
1288
1403
  * @this {!Long}
1289
- * @param {!Long|number|string} other Other Long
1404
+ * @param {!Long|number|bigint|string} other Other Long
1290
1405
  * @returns {!Long}
1291
1406
  */
1292
1407
  LongPrototype.or = function or(other) {
1293
- if (!isLong(other))
1294
- other = fromValue(other);
1408
+ if (!isLong(other)) other = fromValue(other);
1295
1409
  return fromBits(this.low | other.low, this.high | other.high, this.unsigned);
1296
1410
  };
1297
1411
 
1298
1412
  /**
1299
1413
  * Returns the bitwise XOR of this Long and the given one.
1300
1414
  * @this {!Long}
1301
- * @param {!Long|number|string} other Other Long
1415
+ * @param {!Long|number|bigint|string} other Other Long
1302
1416
  * @returns {!Long}
1303
1417
  */
1304
1418
  LongPrototype.xor = function xor(other) {
1305
- if (!isLong(other))
1306
- other = fromValue(other);
1419
+ if (!isLong(other)) other = fromValue(other);
1307
1420
  return fromBits(this.low ^ other.low, this.high ^ other.high, this.unsigned);
1308
1421
  };
1309
1422
 
@@ -1314,14 +1427,15 @@ LongPrototype.xor = function xor(other) {
1314
1427
  * @returns {!Long} Shifted Long
1315
1428
  */
1316
1429
  LongPrototype.shiftLeft = function shiftLeft(numBits) {
1317
- if (isLong(numBits))
1318
- numBits = numBits.toInt();
1319
- if ((numBits &= 63) === 0)
1320
- return this;
1430
+ if (isLong(numBits)) numBits = numBits.toInt();
1431
+ if ((numBits &= 63) === 0) return this;
1321
1432
  else if (numBits < 32)
1322
- return fromBits(this.low << numBits, (this.high << numBits) | (this.low >>> (32 - numBits)), this.unsigned);
1323
- else
1324
- return fromBits(0, this.low << (numBits - 32), this.unsigned);
1433
+ return fromBits(
1434
+ this.low << numBits,
1435
+ (this.high << numBits) | (this.low >>> (32 - numBits)),
1436
+ this.unsigned,
1437
+ );
1438
+ else return fromBits(0, this.low << (numBits - 32), this.unsigned);
1325
1439
  };
1326
1440
 
1327
1441
  /**
@@ -1339,14 +1453,20 @@ LongPrototype.shl = LongPrototype.shiftLeft;
1339
1453
  * @returns {!Long} Shifted Long
1340
1454
  */
1341
1455
  LongPrototype.shiftRight = function shiftRight(numBits) {
1342
- if (isLong(numBits))
1343
- numBits = numBits.toInt();
1344
- if ((numBits &= 63) === 0)
1345
- return this;
1456
+ if (isLong(numBits)) numBits = numBits.toInt();
1457
+ if ((numBits &= 63) === 0) return this;
1346
1458
  else if (numBits < 32)
1347
- return fromBits((this.low >>> numBits) | (this.high << (32 - numBits)), this.high >> numBits, this.unsigned);
1459
+ return fromBits(
1460
+ (this.low >>> numBits) | (this.high << (32 - numBits)),
1461
+ this.high >> numBits,
1462
+ this.unsigned,
1463
+ );
1348
1464
  else
1349
- return fromBits(this.high >> (numBits - 32), this.high >= 0 ? 0 : -1, this.unsigned);
1465
+ return fromBits(
1466
+ this.high >> (numBits - 32),
1467
+ this.high >= 0 ? 0 : -1,
1468
+ this.unsigned,
1469
+ );
1350
1470
  };
1351
1471
 
1352
1472
  /**
@@ -1366,7 +1486,12 @@ LongPrototype.shr = LongPrototype.shiftRight;
1366
1486
  LongPrototype.shiftRightUnsigned = function shiftRightUnsigned(numBits) {
1367
1487
  if (isLong(numBits)) numBits = numBits.toInt();
1368
1488
  if ((numBits &= 63) === 0) return this;
1369
- if (numBits < 32) return fromBits((this.low >>> numBits) | (this.high << (32 - numBits)), this.high >>> numBits, this.unsigned);
1489
+ if (numBits < 32)
1490
+ return fromBits(
1491
+ (this.low >>> numBits) | (this.high << (32 - numBits)),
1492
+ this.high >>> numBits,
1493
+ this.unsigned,
1494
+ );
1370
1495
  if (numBits === 32) return fromBits(this.high, 0, this.unsigned);
1371
1496
  return fromBits(this.high >>> (numBits - 32), 0, this.unsigned);
1372
1497
  };
@@ -1399,12 +1524,20 @@ LongPrototype.rotateLeft = function rotateLeft(numBits) {
1399
1524
  if ((numBits &= 63) === 0) return this;
1400
1525
  if (numBits === 32) return fromBits(this.high, this.low, this.unsigned);
1401
1526
  if (numBits < 32) {
1402
- b = (32 - numBits);
1403
- return fromBits(((this.low << numBits) | (this.high >>> b)), ((this.high << numBits) | (this.low >>> b)), this.unsigned);
1527
+ b = 32 - numBits;
1528
+ return fromBits(
1529
+ (this.low << numBits) | (this.high >>> b),
1530
+ (this.high << numBits) | (this.low >>> b),
1531
+ this.unsigned,
1532
+ );
1404
1533
  }
1405
1534
  numBits -= 32;
1406
- b = (32 - numBits);
1407
- return fromBits(((this.high << numBits) | (this.low >>> b)), ((this.low << numBits) | (this.high >>> b)), this.unsigned);
1535
+ b = 32 - numBits;
1536
+ return fromBits(
1537
+ (this.high << numBits) | (this.low >>> b),
1538
+ (this.low << numBits) | (this.high >>> b),
1539
+ this.unsigned,
1540
+ );
1408
1541
  };
1409
1542
  /**
1410
1543
  * Returns this Long with bits rotated to the left by the given amount. This is an alias of {@link Long#rotateLeft}.
@@ -1426,12 +1559,20 @@ LongPrototype.rotateRight = function rotateRight(numBits) {
1426
1559
  if ((numBits &= 63) === 0) return this;
1427
1560
  if (numBits === 32) return fromBits(this.high, this.low, this.unsigned);
1428
1561
  if (numBits < 32) {
1429
- b = (32 - numBits);
1430
- return fromBits(((this.high << b) | (this.low >>> numBits)), ((this.low << b) | (this.high >>> numBits)), this.unsigned);
1562
+ b = 32 - numBits;
1563
+ return fromBits(
1564
+ (this.high << b) | (this.low >>> numBits),
1565
+ (this.low << b) | (this.high >>> numBits),
1566
+ this.unsigned,
1567
+ );
1431
1568
  }
1432
1569
  numBits -= 32;
1433
- b = (32 - numBits);
1434
- return fromBits(((this.low << b) | (this.high >>> numBits)), ((this.high << b) | (this.low >>> numBits)), this.unsigned);
1570
+ b = 32 - numBits;
1571
+ return fromBits(
1572
+ (this.low << b) | (this.high >>> numBits),
1573
+ (this.high << b) | (this.low >>> numBits),
1574
+ this.unsigned,
1575
+ );
1435
1576
  };
1436
1577
  /**
1437
1578
  * Returns this Long with bits rotated to the right by the given amount. This is an alias of {@link Long#rotateRight}.
@@ -1447,8 +1588,7 @@ LongPrototype.rotr = LongPrototype.rotateRight;
1447
1588
  * @returns {!Long} Signed long
1448
1589
  */
1449
1590
  LongPrototype.toSigned = function toSigned() {
1450
- if (!this.unsigned)
1451
- return this;
1591
+ if (!this.unsigned) return this;
1452
1592
  return fromBits(this.low, this.high, false);
1453
1593
  };
1454
1594
 
@@ -1458,8 +1598,7 @@ LongPrototype.toSigned = function toSigned() {
1458
1598
  * @returns {!Long} Unsigned long
1459
1599
  */
1460
1600
  LongPrototype.toUnsigned = function toUnsigned() {
1461
- if (this.unsigned)
1462
- return this;
1601
+ if (this.unsigned) return this;
1463
1602
  return fromBits(this.low, this.high, true);
1464
1603
  };
1465
1604
 
@@ -1483,13 +1622,13 @@ LongPrototype.toBytesLE = function toBytesLE() {
1483
1622
  lo = this.low;
1484
1623
  return [
1485
1624
  lo & 0xff,
1486
- lo >>> 8 & 0xff,
1487
- lo >>> 16 & 0xff,
1625
+ (lo >>> 8) & 0xff,
1626
+ (lo >>> 16) & 0xff,
1488
1627
  lo >>> 24,
1489
1628
  hi & 0xff,
1490
- hi >>> 8 & 0xff,
1491
- hi >>> 16 & 0xff,
1492
- hi >>> 24
1629
+ (hi >>> 8) & 0xff,
1630
+ (hi >>> 16) & 0xff,
1631
+ hi >>> 24,
1493
1632
  ];
1494
1633
  };
1495
1634
 
@@ -1503,13 +1642,13 @@ LongPrototype.toBytesBE = function toBytesBE() {
1503
1642
  lo = this.low;
1504
1643
  return [
1505
1644
  hi >>> 24,
1506
- hi >>> 16 & 0xff,
1507
- hi >>> 8 & 0xff,
1645
+ (hi >>> 16) & 0xff,
1646
+ (hi >>> 8) & 0xff,
1508
1647
  hi & 0xff,
1509
1648
  lo >>> 24,
1510
- lo >>> 16 & 0xff,
1511
- lo >>> 8 & 0xff,
1512
- lo & 0xff
1649
+ (lo >>> 16) & 0xff,
1650
+ (lo >>> 8) & 0xff,
1651
+ lo & 0xff,
1513
1652
  ];
1514
1653
  };
1515
1654
 
@@ -1521,7 +1660,9 @@ LongPrototype.toBytesBE = function toBytesBE() {
1521
1660
  * @returns {Long} The corresponding Long value
1522
1661
  */
1523
1662
  Long.fromBytes = function fromBytes(bytes, unsigned, le) {
1524
- return le ? Long.fromBytesLE(bytes, unsigned) : Long.fromBytesBE(bytes, unsigned);
1663
+ return le
1664
+ ? Long.fromBytesLE(bytes, unsigned)
1665
+ : Long.fromBytesBE(bytes, unsigned);
1525
1666
  };
1526
1667
 
1527
1668
  /**
@@ -1532,15 +1673,9 @@ Long.fromBytes = function fromBytes(bytes, unsigned, le) {
1532
1673
  */
1533
1674
  Long.fromBytesLE = function fromBytesLE(bytes, unsigned) {
1534
1675
  return new Long(
1535
- bytes[0] |
1536
- bytes[1] << 8 |
1537
- bytes[2] << 16 |
1538
- bytes[3] << 24,
1539
- bytes[4] |
1540
- bytes[5] << 8 |
1541
- bytes[6] << 16 |
1542
- bytes[7] << 24,
1543
- unsigned
1676
+ bytes[0] | (bytes[1] << 8) | (bytes[2] << 16) | (bytes[3] << 24),
1677
+ bytes[4] | (bytes[5] << 8) | (bytes[6] << 16) | (bytes[7] << 24),
1678
+ unsigned,
1544
1679
  );
1545
1680
  };
1546
1681
 
@@ -1552,18 +1687,45 @@ Long.fromBytesLE = function fromBytesLE(bytes, unsigned) {
1552
1687
  */
1553
1688
  Long.fromBytesBE = function fromBytesBE(bytes, unsigned) {
1554
1689
  return new Long(
1555
- bytes[4] << 24 |
1556
- bytes[5] << 16 |
1557
- bytes[6] << 8 |
1558
- bytes[7],
1559
- bytes[0] << 24 |
1560
- bytes[1] << 16 |
1561
- bytes[2] << 8 |
1562
- bytes[3],
1563
- unsigned
1690
+ (bytes[4] << 24) | (bytes[5] << 16) | (bytes[6] << 8) | bytes[7],
1691
+ (bytes[0] << 24) | (bytes[1] << 16) | (bytes[2] << 8) | bytes[3],
1692
+ unsigned,
1564
1693
  );
1565
1694
  };
1566
1695
 
1696
+ // Support conversion to/from BigInt where available
1697
+ if (typeof BigInt === "function") {
1698
+ /**
1699
+ * Returns a Long representing the given big integer.
1700
+ * @function
1701
+ * @param {number} value The big integer value
1702
+ * @param {boolean=} unsigned Whether unsigned or not, defaults to signed
1703
+ * @returns {!Long} The corresponding Long value
1704
+ */
1705
+ Long.fromBigInt = function fromBigInt(value, unsigned) {
1706
+ var lowBits = Number(BigInt.asIntN(32, value));
1707
+ var highBits = Number(BigInt.asIntN(32, value >> BigInt(32)));
1708
+ return fromBits(lowBits, highBits, unsigned);
1709
+ };
1710
+
1711
+ // Override
1712
+ Long.fromValue = function fromValueWithBigInt(value, unsigned) {
1713
+ if (typeof value === "bigint") return fromBigInt(value, unsigned);
1714
+ return fromValue(value, unsigned);
1715
+ };
1716
+
1717
+ /**
1718
+ * Converts the Long to its big integer representation.
1719
+ * @this {!Long}
1720
+ * @returns {bigint}
1721
+ */
1722
+ LongPrototype.toBigInt = function toBigInt() {
1723
+ var lowBigInt = BigInt(this.low >>> 0);
1724
+ var highBigInt = BigInt(this.unsigned ? this.high >>> 0 : this.high);
1725
+ return (highBigInt << BigInt(32)) | lowBigInt;
1726
+ };
1727
+ }
1728
+
1567
1729
  var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {};
1568
1730
 
1569
1731
  function getDefaultExportFromCjs (x) {
@@ -4399,12 +4561,12 @@ const Struct = {
4399
4561
  return obj;
4400
4562
  },
4401
4563
  create(base) {
4402
- return Struct.fromPartial(base !== null && base !== undefined ? base : {});
4564
+ return Struct.fromPartial(base !== null && base !== void 0 ? base : {});
4403
4565
  },
4404
4566
  fromPartial(object) {
4405
4567
  var _a;
4406
4568
  const message = createBaseStruct();
4407
- message.fields = Object.entries((_a = object.fields) !== null && _a !== undefined ? _a : {}).reduce((acc, [key, value]) => {
4569
+ message.fields = Object.entries((_a = object.fields) !== null && _a !== void 0 ? _a : {}).reduce((acc, [key, value]) => {
4408
4570
  if (value !== undefined) {
4409
4571
  acc[key] = value;
4410
4572
  }
@@ -4472,7 +4634,7 @@ const Struct_FieldsEntry = {
4472
4634
  return message;
4473
4635
  },
4474
4636
  fromJSON(object) {
4475
- return { key: isSet$2(object.key) ? String(object.key) : "", value: isSet$2(object === null || object === undefined ? undefined : object.value) ? object.value : undefined };
4637
+ return { key: isSet$2(object.key) ? String(object.key) : "", value: isSet$2(object === null || object === void 0 ? void 0 : object.value) ? object.value : undefined };
4476
4638
  },
4477
4639
  toJSON(message) {
4478
4640
  const obj = {};
@@ -4485,13 +4647,13 @@ const Struct_FieldsEntry = {
4485
4647
  return obj;
4486
4648
  },
4487
4649
  create(base) {
4488
- return Struct_FieldsEntry.fromPartial(base !== null && base !== undefined ? base : {});
4650
+ return Struct_FieldsEntry.fromPartial(base !== null && base !== void 0 ? base : {});
4489
4651
  },
4490
4652
  fromPartial(object) {
4491
4653
  var _a, _b;
4492
4654
  const message = createBaseStruct_FieldsEntry();
4493
- message.key = (_a = object.key) !== null && _a !== undefined ? _a : "";
4494
- message.value = (_b = object.value) !== null && _b !== undefined ? _b : undefined;
4655
+ message.key = (_a = object.key) !== null && _a !== void 0 ? _a : "";
4656
+ message.value = (_b = object.value) !== null && _b !== void 0 ? _b : undefined;
4495
4657
  return message;
4496
4658
  },
4497
4659
  };
@@ -4611,17 +4773,17 @@ const Value = {
4611
4773
  return obj;
4612
4774
  },
4613
4775
  create(base) {
4614
- return Value.fromPartial(base !== null && base !== undefined ? base : {});
4776
+ return Value.fromPartial(base !== null && base !== void 0 ? base : {});
4615
4777
  },
4616
4778
  fromPartial(object) {
4617
4779
  var _a, _b, _c, _d, _e, _f;
4618
4780
  const message = createBaseValue();
4619
- message.nullValue = (_a = object.nullValue) !== null && _a !== undefined ? _a : undefined;
4620
- message.numberValue = (_b = object.numberValue) !== null && _b !== undefined ? _b : undefined;
4621
- message.stringValue = (_c = object.stringValue) !== null && _c !== undefined ? _c : undefined;
4622
- message.boolValue = (_d = object.boolValue) !== null && _d !== undefined ? _d : undefined;
4623
- message.structValue = (_e = object.structValue) !== null && _e !== undefined ? _e : undefined;
4624
- message.listValue = (_f = object.listValue) !== null && _f !== undefined ? _f : undefined;
4781
+ message.nullValue = (_a = object.nullValue) !== null && _a !== void 0 ? _a : undefined;
4782
+ message.numberValue = (_b = object.numberValue) !== null && _b !== void 0 ? _b : undefined;
4783
+ message.stringValue = (_c = object.stringValue) !== null && _c !== void 0 ? _c : undefined;
4784
+ message.boolValue = (_d = object.boolValue) !== null && _d !== void 0 ? _d : undefined;
4785
+ message.structValue = (_e = object.structValue) !== null && _e !== void 0 ? _e : undefined;
4786
+ message.listValue = (_f = object.listValue) !== null && _f !== void 0 ? _f : undefined;
4625
4787
  return message;
4626
4788
  },
4627
4789
  wrap(value) {
@@ -4653,19 +4815,19 @@ const Value = {
4653
4815
  if (message.stringValue !== undefined) {
4654
4816
  return message.stringValue;
4655
4817
  }
4656
- else if ((message === null || message === undefined ? undefined : message.numberValue) !== undefined) {
4818
+ else if ((message === null || message === void 0 ? void 0 : message.numberValue) !== undefined) {
4657
4819
  return message.numberValue;
4658
4820
  }
4659
- else if ((message === null || message === undefined ? undefined : message.boolValue) !== undefined) {
4821
+ else if ((message === null || message === void 0 ? void 0 : message.boolValue) !== undefined) {
4660
4822
  return message.boolValue;
4661
4823
  }
4662
- else if ((message === null || message === undefined ? undefined : message.structValue) !== undefined) {
4824
+ else if ((message === null || message === void 0 ? void 0 : message.structValue) !== undefined) {
4663
4825
  return message.structValue;
4664
4826
  }
4665
- else if ((message === null || message === undefined ? undefined : message.listValue) !== undefined) {
4827
+ else if ((message === null || message === void 0 ? void 0 : message.listValue) !== undefined) {
4666
4828
  return message.listValue;
4667
4829
  }
4668
- else if ((message === null || message === undefined ? undefined : message.nullValue) !== undefined) {
4830
+ else if ((message === null || message === void 0 ? void 0 : message.nullValue) !== undefined) {
4669
4831
  return null;
4670
4832
  }
4671
4833
  return undefined;
@@ -4703,32 +4865,32 @@ const ListValue = {
4703
4865
  return message;
4704
4866
  },
4705
4867
  fromJSON(object) {
4706
- return { values: Array.isArray(object === null || object === undefined ? undefined : object.values) ? [...object.values] : [] };
4868
+ return { values: Array.isArray(object === null || object === void 0 ? void 0 : object.values) ? [...object.values] : [] };
4707
4869
  },
4708
4870
  toJSON(message) {
4709
4871
  var _a;
4710
4872
  const obj = {};
4711
- if ((_a = message.values) === null || _a === undefined ? undefined : _a.length) {
4873
+ if ((_a = message.values) === null || _a === void 0 ? void 0 : _a.length) {
4712
4874
  obj.values = message.values;
4713
4875
  }
4714
4876
  return obj;
4715
4877
  },
4716
4878
  create(base) {
4717
- return ListValue.fromPartial(base !== null && base !== undefined ? base : {});
4879
+ return ListValue.fromPartial(base !== null && base !== void 0 ? base : {});
4718
4880
  },
4719
4881
  fromPartial(object) {
4720
4882
  var _a;
4721
4883
  const message = createBaseListValue();
4722
- message.values = ((_a = object.values) === null || _a === undefined ? undefined : _a.map((e) => e)) || [];
4884
+ message.values = ((_a = object.values) === null || _a === void 0 ? void 0 : _a.map((e) => e)) || [];
4723
4885
  return message;
4724
4886
  },
4725
4887
  wrap(array) {
4726
4888
  const result = createBaseListValue();
4727
- result.values = array !== null && array !== undefined ? array : [];
4889
+ result.values = array !== null && array !== void 0 ? array : [];
4728
4890
  return result;
4729
4891
  },
4730
4892
  unwrap(message) {
4731
- if ((message === null || message === undefined ? undefined : message.hasOwnProperty("values")) && Array.isArray(message.values)) {
4893
+ if ((message === null || message === void 0 ? void 0 : message.hasOwnProperty("values")) && Array.isArray(message.values)) {
4732
4894
  return message.values;
4733
4895
  }
4734
4896
  else {
@@ -4786,12 +4948,12 @@ const ResolveAllRequest = {
4786
4948
  return obj;
4787
4949
  },
4788
4950
  create(base) {
4789
- return ResolveAllRequest.fromPartial(base !== null && base !== undefined ? base : {});
4951
+ return ResolveAllRequest.fromPartial(base !== null && base !== void 0 ? base : {});
4790
4952
  },
4791
4953
  fromPartial(object) {
4792
4954
  var _a;
4793
4955
  const message = createBaseResolveAllRequest();
4794
- message.context = (_a = object.context) !== null && _a !== undefined ? _a : undefined;
4956
+ message.context = (_a = object.context) !== null && _a !== void 0 ? _a : undefined;
4795
4957
  return message;
4796
4958
  },
4797
4959
  };
@@ -4866,18 +5028,18 @@ const ResolveAllResponse = {
4866
5028
  return obj;
4867
5029
  },
4868
5030
  create(base) {
4869
- return ResolveAllResponse.fromPartial(base !== null && base !== undefined ? base : {});
5031
+ return ResolveAllResponse.fromPartial(base !== null && base !== void 0 ? base : {});
4870
5032
  },
4871
5033
  fromPartial(object) {
4872
5034
  var _a, _b;
4873
5035
  const message = createBaseResolveAllResponse();
4874
- message.flags = Object.entries((_a = object.flags) !== null && _a !== undefined ? _a : {}).reduce((acc, [key, value]) => {
5036
+ message.flags = Object.entries((_a = object.flags) !== null && _a !== void 0 ? _a : {}).reduce((acc, [key, value]) => {
4875
5037
  if (value !== undefined) {
4876
5038
  acc[key] = AnyFlag.fromPartial(value);
4877
5039
  }
4878
5040
  return acc;
4879
5041
  }, {});
4880
- message.metadata = (_b = object.metadata) !== null && _b !== undefined ? _b : undefined;
5042
+ message.metadata = (_b = object.metadata) !== null && _b !== void 0 ? _b : undefined;
4881
5043
  return message;
4882
5044
  },
4883
5045
  };
@@ -4938,12 +5100,12 @@ const ResolveAllResponse_FlagsEntry = {
4938
5100
  return obj;
4939
5101
  },
4940
5102
  create(base) {
4941
- return ResolveAllResponse_FlagsEntry.fromPartial(base !== null && base !== undefined ? base : {});
5103
+ return ResolveAllResponse_FlagsEntry.fromPartial(base !== null && base !== void 0 ? base : {});
4942
5104
  },
4943
5105
  fromPartial(object) {
4944
5106
  var _a;
4945
5107
  const message = createBaseResolveAllResponse_FlagsEntry();
4946
- message.key = (_a = object.key) !== null && _a !== undefined ? _a : "";
5108
+ message.key = (_a = object.key) !== null && _a !== void 0 ? _a : "";
4947
5109
  message.value = (object.value !== undefined && object.value !== null)
4948
5110
  ? AnyFlag.fromPartial(object.value)
4949
5111
  : undefined;
@@ -5080,18 +5242,18 @@ const AnyFlag = {
5080
5242
  return obj;
5081
5243
  },
5082
5244
  create(base) {
5083
- return AnyFlag.fromPartial(base !== null && base !== undefined ? base : {});
5245
+ return AnyFlag.fromPartial(base !== null && base !== void 0 ? base : {});
5084
5246
  },
5085
5247
  fromPartial(object) {
5086
5248
  var _a, _b, _c, _d, _e, _f, _g;
5087
5249
  const message = createBaseAnyFlag();
5088
- message.reason = (_a = object.reason) !== null && _a !== undefined ? _a : "";
5089
- message.variant = (_b = object.variant) !== null && _b !== undefined ? _b : "";
5090
- message.boolValue = (_c = object.boolValue) !== null && _c !== undefined ? _c : undefined;
5091
- message.stringValue = (_d = object.stringValue) !== null && _d !== undefined ? _d : undefined;
5092
- message.doubleValue = (_e = object.doubleValue) !== null && _e !== undefined ? _e : undefined;
5093
- message.objectValue = (_f = object.objectValue) !== null && _f !== undefined ? _f : undefined;
5094
- message.metadata = (_g = object.metadata) !== null && _g !== undefined ? _g : undefined;
5250
+ message.reason = (_a = object.reason) !== null && _a !== void 0 ? _a : "";
5251
+ message.variant = (_b = object.variant) !== null && _b !== void 0 ? _b : "";
5252
+ message.boolValue = (_c = object.boolValue) !== null && _c !== void 0 ? _c : undefined;
5253
+ message.stringValue = (_d = object.stringValue) !== null && _d !== void 0 ? _d : undefined;
5254
+ message.doubleValue = (_e = object.doubleValue) !== null && _e !== void 0 ? _e : undefined;
5255
+ message.objectValue = (_f = object.objectValue) !== null && _f !== void 0 ? _f : undefined;
5256
+ message.metadata = (_g = object.metadata) !== null && _g !== void 0 ? _g : undefined;
5095
5257
  return message;
5096
5258
  },
5097
5259
  };
@@ -5152,13 +5314,13 @@ const ResolveBooleanRequest = {
5152
5314
  return obj;
5153
5315
  },
5154
5316
  create(base) {
5155
- return ResolveBooleanRequest.fromPartial(base !== null && base !== undefined ? base : {});
5317
+ return ResolveBooleanRequest.fromPartial(base !== null && base !== void 0 ? base : {});
5156
5318
  },
5157
5319
  fromPartial(object) {
5158
5320
  var _a, _b;
5159
5321
  const message = createBaseResolveBooleanRequest();
5160
- message.flagKey = (_a = object.flagKey) !== null && _a !== undefined ? _a : "";
5161
- message.context = (_b = object.context) !== null && _b !== undefined ? _b : undefined;
5322
+ message.flagKey = (_a = object.flagKey) !== null && _a !== void 0 ? _a : "";
5323
+ message.context = (_b = object.context) !== null && _b !== void 0 ? _b : undefined;
5162
5324
  return message;
5163
5325
  },
5164
5326
  };
@@ -5245,15 +5407,15 @@ const ResolveBooleanResponse = {
5245
5407
  return obj;
5246
5408
  },
5247
5409
  create(base) {
5248
- return ResolveBooleanResponse.fromPartial(base !== null && base !== undefined ? base : {});
5410
+ return ResolveBooleanResponse.fromPartial(base !== null && base !== void 0 ? base : {});
5249
5411
  },
5250
5412
  fromPartial(object) {
5251
5413
  var _a, _b, _c, _d;
5252
5414
  const message = createBaseResolveBooleanResponse();
5253
- message.value = (_a = object.value) !== null && _a !== undefined ? _a : false;
5254
- message.reason = (_b = object.reason) !== null && _b !== undefined ? _b : "";
5255
- message.variant = (_c = object.variant) !== null && _c !== undefined ? _c : "";
5256
- message.metadata = (_d = object.metadata) !== null && _d !== undefined ? _d : undefined;
5415
+ message.value = (_a = object.value) !== null && _a !== void 0 ? _a : false;
5416
+ message.reason = (_b = object.reason) !== null && _b !== void 0 ? _b : "";
5417
+ message.variant = (_c = object.variant) !== null && _c !== void 0 ? _c : "";
5418
+ message.metadata = (_d = object.metadata) !== null && _d !== void 0 ? _d : undefined;
5257
5419
  return message;
5258
5420
  },
5259
5421
  };
@@ -5314,13 +5476,13 @@ const ResolveStringRequest = {
5314
5476
  return obj;
5315
5477
  },
5316
5478
  create(base) {
5317
- return ResolveStringRequest.fromPartial(base !== null && base !== undefined ? base : {});
5479
+ return ResolveStringRequest.fromPartial(base !== null && base !== void 0 ? base : {});
5318
5480
  },
5319
5481
  fromPartial(object) {
5320
5482
  var _a, _b;
5321
5483
  const message = createBaseResolveStringRequest();
5322
- message.flagKey = (_a = object.flagKey) !== null && _a !== undefined ? _a : "";
5323
- message.context = (_b = object.context) !== null && _b !== undefined ? _b : undefined;
5484
+ message.flagKey = (_a = object.flagKey) !== null && _a !== void 0 ? _a : "";
5485
+ message.context = (_b = object.context) !== null && _b !== void 0 ? _b : undefined;
5324
5486
  return message;
5325
5487
  },
5326
5488
  };
@@ -5407,15 +5569,15 @@ const ResolveStringResponse = {
5407
5569
  return obj;
5408
5570
  },
5409
5571
  create(base) {
5410
- return ResolveStringResponse.fromPartial(base !== null && base !== undefined ? base : {});
5572
+ return ResolveStringResponse.fromPartial(base !== null && base !== void 0 ? base : {});
5411
5573
  },
5412
5574
  fromPartial(object) {
5413
5575
  var _a, _b, _c, _d;
5414
5576
  const message = createBaseResolveStringResponse();
5415
- message.value = (_a = object.value) !== null && _a !== undefined ? _a : "";
5416
- message.reason = (_b = object.reason) !== null && _b !== undefined ? _b : "";
5417
- message.variant = (_c = object.variant) !== null && _c !== undefined ? _c : "";
5418
- message.metadata = (_d = object.metadata) !== null && _d !== undefined ? _d : undefined;
5577
+ message.value = (_a = object.value) !== null && _a !== void 0 ? _a : "";
5578
+ message.reason = (_b = object.reason) !== null && _b !== void 0 ? _b : "";
5579
+ message.variant = (_c = object.variant) !== null && _c !== void 0 ? _c : "";
5580
+ message.metadata = (_d = object.metadata) !== null && _d !== void 0 ? _d : undefined;
5419
5581
  return message;
5420
5582
  },
5421
5583
  };
@@ -5476,13 +5638,13 @@ const ResolveFloatRequest = {
5476
5638
  return obj;
5477
5639
  },
5478
5640
  create(base) {
5479
- return ResolveFloatRequest.fromPartial(base !== null && base !== undefined ? base : {});
5641
+ return ResolveFloatRequest.fromPartial(base !== null && base !== void 0 ? base : {});
5480
5642
  },
5481
5643
  fromPartial(object) {
5482
5644
  var _a, _b;
5483
5645
  const message = createBaseResolveFloatRequest();
5484
- message.flagKey = (_a = object.flagKey) !== null && _a !== undefined ? _a : "";
5485
- message.context = (_b = object.context) !== null && _b !== undefined ? _b : undefined;
5646
+ message.flagKey = (_a = object.flagKey) !== null && _a !== void 0 ? _a : "";
5647
+ message.context = (_b = object.context) !== null && _b !== void 0 ? _b : undefined;
5486
5648
  return message;
5487
5649
  },
5488
5650
  };
@@ -5569,15 +5731,15 @@ const ResolveFloatResponse = {
5569
5731
  return obj;
5570
5732
  },
5571
5733
  create(base) {
5572
- return ResolveFloatResponse.fromPartial(base !== null && base !== undefined ? base : {});
5734
+ return ResolveFloatResponse.fromPartial(base !== null && base !== void 0 ? base : {});
5573
5735
  },
5574
5736
  fromPartial(object) {
5575
5737
  var _a, _b, _c, _d;
5576
5738
  const message = createBaseResolveFloatResponse();
5577
- message.value = (_a = object.value) !== null && _a !== undefined ? _a : 0;
5578
- message.reason = (_b = object.reason) !== null && _b !== undefined ? _b : "";
5579
- message.variant = (_c = object.variant) !== null && _c !== undefined ? _c : "";
5580
- message.metadata = (_d = object.metadata) !== null && _d !== undefined ? _d : undefined;
5739
+ message.value = (_a = object.value) !== null && _a !== void 0 ? _a : 0;
5740
+ message.reason = (_b = object.reason) !== null && _b !== void 0 ? _b : "";
5741
+ message.variant = (_c = object.variant) !== null && _c !== void 0 ? _c : "";
5742
+ message.metadata = (_d = object.metadata) !== null && _d !== void 0 ? _d : undefined;
5581
5743
  return message;
5582
5744
  },
5583
5745
  };
@@ -5638,13 +5800,13 @@ const ResolveIntRequest = {
5638
5800
  return obj;
5639
5801
  },
5640
5802
  create(base) {
5641
- return ResolveIntRequest.fromPartial(base !== null && base !== undefined ? base : {});
5803
+ return ResolveIntRequest.fromPartial(base !== null && base !== void 0 ? base : {});
5642
5804
  },
5643
5805
  fromPartial(object) {
5644
5806
  var _a, _b;
5645
5807
  const message = createBaseResolveIntRequest();
5646
- message.flagKey = (_a = object.flagKey) !== null && _a !== undefined ? _a : "";
5647
- message.context = (_b = object.context) !== null && _b !== undefined ? _b : undefined;
5808
+ message.flagKey = (_a = object.flagKey) !== null && _a !== void 0 ? _a : "";
5809
+ message.context = (_b = object.context) !== null && _b !== void 0 ? _b : undefined;
5648
5810
  return message;
5649
5811
  },
5650
5812
  };
@@ -5731,15 +5893,15 @@ const ResolveIntResponse = {
5731
5893
  return obj;
5732
5894
  },
5733
5895
  create(base) {
5734
- return ResolveIntResponse.fromPartial(base !== null && base !== undefined ? base : {});
5896
+ return ResolveIntResponse.fromPartial(base !== null && base !== void 0 ? base : {});
5735
5897
  },
5736
5898
  fromPartial(object) {
5737
5899
  var _a, _b, _c, _d;
5738
5900
  const message = createBaseResolveIntResponse();
5739
- message.value = (_a = object.value) !== null && _a !== undefined ? _a : "0";
5740
- message.reason = (_b = object.reason) !== null && _b !== undefined ? _b : "";
5741
- message.variant = (_c = object.variant) !== null && _c !== undefined ? _c : "";
5742
- message.metadata = (_d = object.metadata) !== null && _d !== undefined ? _d : undefined;
5901
+ message.value = (_a = object.value) !== null && _a !== void 0 ? _a : "0";
5902
+ message.reason = (_b = object.reason) !== null && _b !== void 0 ? _b : "";
5903
+ message.variant = (_c = object.variant) !== null && _c !== void 0 ? _c : "";
5904
+ message.metadata = (_d = object.metadata) !== null && _d !== void 0 ? _d : undefined;
5743
5905
  return message;
5744
5906
  },
5745
5907
  };
@@ -5800,13 +5962,13 @@ const ResolveObjectRequest = {
5800
5962
  return obj;
5801
5963
  },
5802
5964
  create(base) {
5803
- return ResolveObjectRequest.fromPartial(base !== null && base !== undefined ? base : {});
5965
+ return ResolveObjectRequest.fromPartial(base !== null && base !== void 0 ? base : {});
5804
5966
  },
5805
5967
  fromPartial(object) {
5806
5968
  var _a, _b;
5807
5969
  const message = createBaseResolveObjectRequest();
5808
- message.flagKey = (_a = object.flagKey) !== null && _a !== undefined ? _a : "";
5809
- message.context = (_b = object.context) !== null && _b !== undefined ? _b : undefined;
5970
+ message.flagKey = (_a = object.flagKey) !== null && _a !== void 0 ? _a : "";
5971
+ message.context = (_b = object.context) !== null && _b !== void 0 ? _b : undefined;
5810
5972
  return message;
5811
5973
  },
5812
5974
  };
@@ -5893,15 +6055,15 @@ const ResolveObjectResponse = {
5893
6055
  return obj;
5894
6056
  },
5895
6057
  create(base) {
5896
- return ResolveObjectResponse.fromPartial(base !== null && base !== undefined ? base : {});
6058
+ return ResolveObjectResponse.fromPartial(base !== null && base !== void 0 ? base : {});
5897
6059
  },
5898
6060
  fromPartial(object) {
5899
6061
  var _a, _b, _c, _d;
5900
6062
  const message = createBaseResolveObjectResponse();
5901
- message.value = (_a = object.value) !== null && _a !== undefined ? _a : undefined;
5902
- message.reason = (_b = object.reason) !== null && _b !== undefined ? _b : "";
5903
- message.variant = (_c = object.variant) !== null && _c !== undefined ? _c : "";
5904
- message.metadata = (_d = object.metadata) !== null && _d !== undefined ? _d : undefined;
6063
+ message.value = (_a = object.value) !== null && _a !== void 0 ? _a : undefined;
6064
+ message.reason = (_b = object.reason) !== null && _b !== void 0 ? _b : "";
6065
+ message.variant = (_c = object.variant) !== null && _c !== void 0 ? _c : "";
6066
+ message.metadata = (_d = object.metadata) !== null && _d !== void 0 ? _d : undefined;
5905
6067
  return message;
5906
6068
  },
5907
6069
  };
@@ -5962,13 +6124,13 @@ const EventStreamResponse = {
5962
6124
  return obj;
5963
6125
  },
5964
6126
  create(base) {
5965
- return EventStreamResponse.fromPartial(base !== null && base !== undefined ? base : {});
6127
+ return EventStreamResponse.fromPartial(base !== null && base !== void 0 ? base : {});
5966
6128
  },
5967
6129
  fromPartial(object) {
5968
6130
  var _a, _b;
5969
6131
  const message = createBaseEventStreamResponse();
5970
- message.type = (_a = object.type) !== null && _a !== undefined ? _a : "";
5971
- message.data = (_b = object.data) !== null && _b !== undefined ? _b : undefined;
6132
+ message.type = (_a = object.type) !== null && _a !== void 0 ? _a : "";
6133
+ message.data = (_b = object.data) !== null && _b !== void 0 ? _b : undefined;
5972
6134
  return message;
5973
6135
  },
5974
6136
  };
@@ -6000,7 +6162,7 @@ const EventStreamRequest = {
6000
6162
  return obj;
6001
6163
  },
6002
6164
  create(base) {
6003
- return EventStreamRequest.fromPartial(base !== null && base !== undefined ? base : {});
6165
+ return EventStreamRequest.fromPartial(base !== null && base !== void 0 ? base : {});
6004
6166
  },
6005
6167
  fromPartial(_) {
6006
6168
  const message = createBaseEventStreamRequest();
@@ -6087,6 +6249,10 @@ function isSet$1(value) {
6087
6249
  return value !== null && value !== undefined;
6088
6250
  }
6089
6251
 
6252
+ /**
6253
+ * Get the string name of a gRPC status code.
6254
+ */
6255
+ const statusName = (code) => grpcJs.status[code];
6090
6256
  const closeStreamIfDefined = (stream) => {
6091
6257
  /**
6092
6258
  * cancel() is necessary to prevent calls from hanging the process, so we need to we need to remove all the
@@ -6101,6 +6267,122 @@ const closeStreamIfDefined = (stream) => {
6101
6267
  stream.destroy();
6102
6268
  }
6103
6269
  };
6270
+ /**
6271
+ * Creates gRPC channel credentials based on TLS and certificate path configuration.
6272
+ * @returns Channel credentials for gRPC connection
6273
+ */
6274
+ const createChannelCredentials = (tls, certPath) => {
6275
+ if (!tls) {
6276
+ return grpcJs.credentials.createInsecure();
6277
+ }
6278
+ if (certPath && node_fs.existsSync(certPath)) {
6279
+ const rootCerts = node_fs.readFileSync(certPath);
6280
+ return grpcJs.credentials.createSsl(rootCerts);
6281
+ }
6282
+ return grpcJs.credentials.createSsl();
6283
+ };
6284
+ /**
6285
+ * Mapping of configuration options to gRPC client options.
6286
+ */
6287
+ const CONFIG_TO_GRPC_OPTIONS = [
6288
+ { configKey: 'defaultAuthority', grpcKey: 'grpc.default_authority' },
6289
+ { configKey: 'keepAliveTime', grpcKey: 'grpc.keepalive_time_ms', condition: (time) => Number(time) > 0 },
6290
+ ];
6291
+ /**
6292
+ * Builds gRPC client options from config.
6293
+ */
6294
+ function buildClientOptions(config) {
6295
+ const options = {
6296
+ 'grpc.service_config': buildRetryPolicy(['flagd.evaluation.v1.Service', 'flagd.sync.v1.FlagSyncService'], config.retryBackoffMs, config.retryBackoffMaxMs),
6297
+ };
6298
+ for (const { configKey, grpcKey, condition } of CONFIG_TO_GRPC_OPTIONS) {
6299
+ const value = config[configKey];
6300
+ if (value !== undefined && (!condition || condition(value))) {
6301
+ options[grpcKey] = value;
6302
+ }
6303
+ }
6304
+ return options;
6305
+ }
6306
+ /**
6307
+ * Builds RetryPolicy for gRPC client options.
6308
+ * @param serviceNames Array of service names to configure retry policy for
6309
+ * @param retryBackoffMs Initial backoff duration in milliseconds
6310
+ * @param retryBackoffMaxMs Maximum backoff duration in milliseconds
6311
+ * @returns gRPC client options with retry policy
6312
+ */
6313
+ const buildRetryPolicy = (serviceNames, retryBackoffMs, retryBackoffMaxMs) => {
6314
+ const initialBackoff = retryBackoffMs !== null && retryBackoffMs !== void 0 ? retryBackoffMs : 1000;
6315
+ const maxBackoff = retryBackoffMaxMs !== null && retryBackoffMaxMs !== void 0 ? retryBackoffMaxMs : 120000;
6316
+ const retryPolicy = {
6317
+ maxAttempts: 3,
6318
+ initialBackoff: `${Math.round(initialBackoff / 1000).toFixed(2)}s`,
6319
+ maxBackoff: `${Math.round(maxBackoff / 1000).toFixed(2)}s`,
6320
+ backoffMultiplier: 2,
6321
+ retryableStatusCodes: [statusName(grpcJs.status.UNAVAILABLE), statusName(grpcJs.status.UNKNOWN)],
6322
+ };
6323
+ return JSON.stringify({
6324
+ loadBalancingConfig: [],
6325
+ methodConfig: [
6326
+ {
6327
+ name: serviceNames.map((serviceName) => ({ service: serviceName })),
6328
+ retryPolicy,
6329
+ },
6330
+ ],
6331
+ });
6332
+ };
6333
+ /**
6334
+ * Converts an array of gRPC status code strings to a Set of numeric codes.
6335
+ * @param fatalStatusCodes Array of status code strings.
6336
+ * @param logger Optional logger for warning about unknown codes
6337
+ * @returns Set of numeric status codes
6338
+ */
6339
+ const createFatalStatusCodesSet = (fatalStatusCodes, logger) => {
6340
+ if (!(fatalStatusCodes === null || fatalStatusCodes === void 0 ? void 0 : fatalStatusCodes.length)) {
6341
+ return new Set();
6342
+ }
6343
+ return fatalStatusCodes.reduce((codes, codeStr) => {
6344
+ const numericCode = grpcJs.status[codeStr];
6345
+ if (typeof numericCode === 'number') {
6346
+ codes.add(numericCode);
6347
+ }
6348
+ else {
6349
+ logger === null || logger === void 0 ? void 0 : logger.warn(`Unknown gRPC status code: "${codeStr}"`);
6350
+ }
6351
+ return codes;
6352
+ }, new Set());
6353
+ };
6354
+ /**
6355
+ * Checks if an error is a fatal gRPC status code that should not be retried.
6356
+ * This should only be checked on the first connection attempt.
6357
+ *
6358
+ * @param err The error to check
6359
+ * @param initialized Whether the connection has been successfully initialized
6360
+ * @param fatalStatusCodes Set of numeric status codes considered fatal
6361
+ * @returns True if the error is fatal and should not be retried
6362
+ */
6363
+ const isFatalStatusCodeError = (err, initialized, fatalStatusCodes) => {
6364
+ if (initialized) {
6365
+ return false;
6366
+ }
6367
+ const serviceError = err;
6368
+ return (serviceError === null || serviceError === void 0 ? void 0 : serviceError.code) !== undefined && fatalStatusCodes.has(serviceError.code);
6369
+ };
6370
+ /**
6371
+ * Handles a fatal gRPC status code error by logging it.
6372
+ * Should only be called when isFatalStatusCodeError returns true.
6373
+ *
6374
+ * @param err The error to handle
6375
+ * @param logger Optional logger for error logging
6376
+ * @param disconnectCallback Callback to invoke with the error message
6377
+ * @param rejectConnect Optional callback to reject the connection promise
6378
+ */
6379
+ const handleFatalStatusCodeError = (err, logger, disconnectCallback, rejectConnect) => {
6380
+ const serviceError = err;
6381
+ logger === null || logger === void 0 ? void 0 : logger.error(`Encountered fatal status code ${serviceError.code} (${serviceError.message}) on first connection, will not retry`);
6382
+ const errorMessage = `PROVIDER_FATAL: ${serviceError.message}`;
6383
+ disconnectCallback(errorMessage);
6384
+ rejectConnect === null || rejectConnect === void 0 ? void 0 : rejectConnect(new serverSdk.ProviderFatalError(serviceError.message));
6385
+ };
6104
6386
 
6105
6387
  class GRPCService {
6106
6388
  get _cacheActive() {
@@ -6111,9 +6393,11 @@ class GRPCService {
6111
6393
  this.logger = logger;
6112
6394
  this._cacheEnabled = false;
6113
6395
  this._eventStream = undefined;
6396
+ this._initialized = false;
6397
+ this._errorThrottled = false;
6114
6398
  this.onRejected = (err) => {
6115
6399
  // map the errors
6116
- switch (err === null || err === undefined ? undefined : err.code) {
6400
+ switch (err === null || err === void 0 ? void 0 : err.code) {
6117
6401
  case grpcJs.status.DATA_LOSS:
6118
6402
  throw new serverSdk.ParseError(err.details);
6119
6403
  case grpcJs.status.INVALID_ARGUMENT:
@@ -6123,95 +6407,128 @@ class GRPCService {
6123
6407
  case grpcJs.status.UNAVAILABLE:
6124
6408
  throw new serverSdk.FlagNotFoundError(err.details);
6125
6409
  default:
6126
- throw new serverSdk.GeneralError(err === null || err === undefined ? undefined : err.details);
6410
+ throw new serverSdk.GeneralError(err === null || err === void 0 ? void 0 : err.details);
6127
6411
  }
6128
6412
  };
6129
- const { host, port, tls, socketPath, defaultAuthority } = config;
6130
- let clientOptions;
6131
- if (defaultAuthority) {
6132
- clientOptions = {
6133
- 'grpc.default_authority': defaultAuthority,
6134
- };
6135
- }
6413
+ const { host, port, tls, socketPath, certPath } = config;
6414
+ const clientOptions = buildClientOptions(config);
6415
+ const channelCredentials = createChannelCredentials(tls, certPath);
6416
+ this._maxBackoffMs = config.retryBackoffMaxMs || DEFAULT_MAX_BACKOFF_MS;
6136
6417
  this._client = client
6137
6418
  ? client
6138
- : new ServiceClient(socketPath ? `unix://${socketPath}` : `${host}:${port}`, tls ? grpcJs.credentials.createSsl() : grpcJs.credentials.createInsecure(), clientOptions);
6419
+ : new ServiceClient(socketPath ? `unix://${socketPath}` : `${host}:${port}`, channelCredentials, clientOptions);
6420
+ this._deadline = config.deadlineMs;
6421
+ this._streamDeadline = config.streamDeadlineMs;
6139
6422
  if (config.cache === 'lru') {
6140
6423
  this._cacheEnabled = true;
6141
6424
  this._cache = new lruCache.LRUCache({ maxSize: config.maxCacheSize || DEFAULT_MAX_CACHE_SIZE, sizeCalculation: () => 1 });
6142
6425
  }
6426
+ this._fatalStatusCodes = createFatalStatusCodesSet(config.fatalStatusCodes, logger);
6427
+ // create metadata with the flagd-selector header if selector is configured
6428
+ this._metadata = new grpcJs.Metadata();
6429
+ if (config.selector) {
6430
+ this._metadata.set(FLAGD_SELECTOR_HEADER, config.selector);
6431
+ }
6432
+ }
6433
+ clearCache() {
6434
+ var _a;
6435
+ (_a = this._cache) === null || _a === void 0 ? void 0 : _a.clear();
6143
6436
  }
6144
6437
  connect(reconnectCallback, changedCallback, disconnectCallback) {
6145
6438
  return new Promise((resolve, reject) => this.listen(reconnectCallback, changedCallback, disconnectCallback, resolve, reject));
6146
6439
  }
6147
6440
  disconnect() {
6148
- return __awaiter(this, undefined, undefined, function* () {
6441
+ return __awaiter(this, void 0, void 0, function* () {
6149
6442
  closeStreamIfDefined(this._eventStream);
6150
6443
  this._client.close();
6151
6444
  });
6152
6445
  }
6153
6446
  resolveBoolean(flagKey, _, context, logger) {
6154
- return __awaiter(this, undefined, undefined, function* () {
6447
+ return __awaiter(this, void 0, void 0, function* () {
6155
6448
  return this.resolve(this._client.resolveBoolean, flagKey, context, logger);
6156
6449
  });
6157
6450
  }
6158
6451
  resolveString(flagKey, _, context, logger) {
6159
- return __awaiter(this, undefined, undefined, function* () {
6452
+ return __awaiter(this, void 0, void 0, function* () {
6160
6453
  return this.resolve(this._client.resolveString, flagKey, context, logger);
6161
6454
  });
6162
6455
  }
6163
6456
  resolveNumber(flagKey, _, context, logger) {
6164
- return __awaiter(this, undefined, undefined, function* () {
6457
+ return __awaiter(this, void 0, void 0, function* () {
6165
6458
  return this.resolve(this._client.resolveFloat, flagKey, context, logger);
6166
6459
  });
6167
6460
  }
6168
6461
  resolveObject(flagKey, _, context, logger) {
6169
- return __awaiter(this, undefined, undefined, function* () {
6462
+ return __awaiter(this, void 0, void 0, function* () {
6170
6463
  return this.resolve(this._client.resolveObject, flagKey, context, logger);
6171
6464
  });
6172
6465
  }
6173
6466
  listen(reconnectCallback, changedCallback, disconnectCallback, resolveConnect, rejectConnect) {
6174
6467
  var _a;
6175
- (_a = this.logger) === null || _a === undefined ? undefined : _a.debug(`${FlagdProvider.name}: connecting stream...`);
6468
+ (_a = this.logger) === null || _a === void 0 ? void 0 : _a.debug(`${FlagdProvider.name}: connecting stream...`);
6176
6469
  // close the previous stream if we're reconnecting
6177
6470
  closeStreamIfDefined(this._eventStream);
6178
- const stream = this._client.eventStream({}, {});
6179
- stream.on('error', (err) => {
6180
- rejectConnect === null || rejectConnect === undefined ? undefined : rejectConnect(err);
6181
- this.handleError(reconnectCallback, changedCallback, disconnectCallback);
6182
- });
6183
- stream.on('data', (message) => {
6184
- var _a;
6185
- if (message.type === EVENT_PROVIDER_READY) {
6186
- (_a = this.logger) === null || _a === undefined ? undefined : _a.debug(`${FlagdProvider.name}: streaming connection established with flagd`);
6187
- // if resolveConnect is undefined, this is a reconnection; we only want to fire the reconnect callback in that case
6188
- if (resolveConnect) {
6189
- resolveConnect();
6190
- }
6191
- else {
6192
- reconnectCallback();
6471
+ // wait for connection to be stable
6472
+ this._client.waitForReady(Date.now() + this._deadline, (err) => {
6473
+ if (err) {
6474
+ // Check if error is a fatal status code on first connection only
6475
+ if (isFatalStatusCodeError(err, this._initialized, this._fatalStatusCodes)) {
6476
+ handleFatalStatusCodeError(err, this.logger, disconnectCallback, rejectConnect);
6477
+ return;
6193
6478
  }
6479
+ rejectConnect === null || rejectConnect === void 0 ? void 0 : rejectConnect(err);
6480
+ this.handleError(reconnectCallback, changedCallback, disconnectCallback);
6194
6481
  }
6195
- else if (message.type === EVENT_CONFIGURATION_CHANGE) {
6196
- this.handleFlagsChanged(message, changedCallback);
6482
+ else {
6483
+ const streamDeadline = this._streamDeadline != 0 ? Date.now() + this._streamDeadline : undefined;
6484
+ const stream = this._client.eventStream({}, { deadline: streamDeadline });
6485
+ stream.on('error', (err) => {
6486
+ // In cases where we get an explicit error status, we add a delay.
6487
+ // This prevents tight loops when errors are returned immediately, typically by intervening proxies like Envoy.
6488
+ this._errorThrottled = true;
6489
+ // Check if error is a fatal status code on first connection only
6490
+ if (isFatalStatusCodeError(err, this._initialized, this._fatalStatusCodes)) {
6491
+ handleFatalStatusCodeError(err, this.logger, disconnectCallback, rejectConnect);
6492
+ return;
6493
+ }
6494
+ rejectConnect === null || rejectConnect === void 0 ? void 0 : rejectConnect(err);
6495
+ this.handleError(reconnectCallback, changedCallback, disconnectCallback);
6496
+ });
6497
+ stream.on('data', (message) => {
6498
+ var _a;
6499
+ if (message.type === EVENT_PROVIDER_READY) {
6500
+ (_a = this.logger) === null || _a === void 0 ? void 0 : _a.debug(`${FlagdProvider.name}: streaming connection established with flagd`);
6501
+ this._initialized = true;
6502
+ // if resolveConnect is undefined, this is a reconnection; we only want to fire the reconnect callback in that case
6503
+ if (resolveConnect) {
6504
+ resolveConnect();
6505
+ }
6506
+ else {
6507
+ reconnectCallback();
6508
+ }
6509
+ }
6510
+ else if (message.type === EVENT_CONFIGURATION_CHANGE) {
6511
+ this.handleFlagsChanged(message, changedCallback);
6512
+ }
6513
+ });
6514
+ this._eventStream = stream;
6197
6515
  }
6198
6516
  });
6199
- this._eventStream = stream;
6200
6517
  }
6201
6518
  handleFlagsChanged(message, changedCallback) {
6202
6519
  var _a;
6203
6520
  if (message.data) {
6204
6521
  const data = message.data;
6205
- (_a = this.logger) === null || _a === undefined ? undefined : _a.debug(`${FlagdProvider.name}: got message: ${JSON.stringify(data, undefined, 2)}`);
6206
- if (data && typeof data === 'object' && 'flags' in data && (data === null || data === undefined ? undefined : data['flags'])) {
6522
+ (_a = this.logger) === null || _a === void 0 ? void 0 : _a.debug(`${FlagdProvider.name}: got message: ${JSON.stringify(data, undefined, 2)}`);
6523
+ if (data && typeof data === 'object' && 'flags' in data && (data === null || data === void 0 ? void 0 : data['flags'])) {
6207
6524
  const flagChangeMessage = data;
6208
6525
  const flagsChanged = Object.keys(flagChangeMessage.flags || []);
6209
6526
  if (this._cacheEnabled) {
6210
6527
  // remove each changed key from cache
6211
6528
  flagsChanged.forEach((key) => {
6212
6529
  var _a, _b;
6213
- if ((_a = this._cache) === null || _a === undefined ? undefined : _a.delete(key)) {
6214
- (_b = this.logger) === null || _b === undefined ? undefined : _b.debug(`${FlagdProvider.name}: evicted key: ${key} from cache.`);
6530
+ if ((_a = this._cache) === null || _a === void 0 ? void 0 : _a.delete(key)) {
6531
+ (_b = this.logger) === null || _b === void 0 ? void 0 : _b.debug(`${FlagdProvider.name}: evicted key: ${key} from cache.`);
6215
6532
  }
6216
6533
  });
6217
6534
  }
@@ -6220,31 +6537,29 @@ class GRPCService {
6220
6537
  }
6221
6538
  }
6222
6539
  reconnect(reconnectCallback, changedCallback, disconnectCallback) {
6223
- const channel = this._client.getChannel();
6224
- channel.watchConnectivityState(channel.getConnectivityState(true), Infinity, () => {
6225
- this.listen(reconnectCallback, changedCallback, disconnectCallback);
6226
- });
6540
+ setTimeout(() => this.listen(reconnectCallback, changedCallback, disconnectCallback), this._errorThrottled ? this._maxBackoffMs : 0);
6541
+ this._errorThrottled = false;
6227
6542
  }
6228
6543
  handleError(reconnectCallback, changedCallback, disconnectCallback) {
6229
6544
  var _a, _b;
6230
6545
  disconnectCallback('streaming connection error, will attempt reconnect...');
6231
- (_a = this.logger) === null || _a === undefined ? undefined : _a.error(`${FlagdProvider.name}: streaming connection error, will attempt reconnect...`);
6232
- (_b = this._cache) === null || _b === undefined ? undefined : _b.clear();
6546
+ (_a = this.logger) === null || _a === void 0 ? void 0 : _a.error(`${FlagdProvider.name}: streaming connection error, will attempt reconnect...`);
6547
+ (_b = this._cache) === null || _b === void 0 ? void 0 : _b.clear();
6233
6548
  this.reconnect(reconnectCallback, changedCallback, disconnectCallback);
6234
6549
  }
6235
6550
  resolve(promise, flagKey, context, logger) {
6236
- return __awaiter(this, undefined, undefined, function* () {
6551
+ return __awaiter(this, void 0, void 0, function* () {
6237
6552
  var _a, _b;
6238
6553
  const resolver = node_util.promisify(promise);
6239
6554
  if (this._cacheActive) {
6240
- const cached = (_a = this._cache) === null || _a === undefined ? undefined : _a.get(flagKey);
6555
+ const cached = (_a = this._cache) === null || _a === void 0 ? void 0 : _a.get(flagKey);
6241
6556
  if (cached) {
6242
6557
  return Object.assign(Object.assign({}, cached), { reason: serverSdk.StandardResolutionReasons.CACHED });
6243
6558
  }
6244
6559
  }
6245
- // invoke the passed resolver method
6560
+ // invoke the passed resolver method with metadata for selector support
6246
6561
  const response = yield resolver
6247
- .call(this._client, { flagKey, context })
6562
+ .call(this._client, { flagKey, context }, this._metadata)
6248
6563
  .then((resolved) => resolved, this.onRejected);
6249
6564
  const resolved = {
6250
6565
  value: response.value,
@@ -6255,7 +6570,7 @@ class GRPCService {
6255
6570
  logger.debug(`${FlagdProvider.name}: resolved flag with key: ${resolved.value}, variant: ${response.variant}, reason: ${response.reason}`);
6256
6571
  if (this._cacheActive && response.reason === serverSdk.StandardResolutionReasons.STATIC) {
6257
6572
  // cache this static value
6258
- (_b = this._cache) === null || _b === undefined ? undefined : _b.set(flagKey, resolved);
6573
+ (_b = this._cache) === null || _b === void 0 ? void 0 : _b.set(flagKey, resolved);
6259
6574
  }
6260
6575
  return resolved;
6261
6576
  });
@@ -6269,9 +6584,9 @@ class FileFetch {
6269
6584
  this._logger = logger;
6270
6585
  }
6271
6586
  connect(dataFillCallback, _, changedCallback) {
6272
- return __awaiter(this, undefined, undefined, function* () {
6587
+ return __awaiter(this, void 0, void 0, function* () {
6273
6588
  var _a, _b;
6274
- (_a = this._logger) === null || _a === undefined ? undefined : _a.debug('Starting file sync connection');
6589
+ (_a = this._logger) === null || _a === void 0 ? void 0 : _a.debug('Starting file sync connection');
6275
6590
  try {
6276
6591
  const output = yield fs.promises.readFile(this._filename, encoding);
6277
6592
  // Don't emit the change event for the initial read
@@ -6296,13 +6611,13 @@ class FileFetch {
6296
6611
  throw err;
6297
6612
  }
6298
6613
  else {
6299
- switch (err === null || err === undefined ? undefined : err.code) {
6614
+ switch (err === null || err === void 0 ? void 0 : err.code) {
6300
6615
  case 'ENOENT':
6301
6616
  throw new serverSdk.GeneralError(`File not found: ${this._filename}`);
6302
6617
  case 'EACCES':
6303
6618
  throw new serverSdk.GeneralError(`File not accessible: ${this._filename}`);
6304
6619
  default:
6305
- (_b = this._logger) === null || _b === undefined ? undefined : _b.debug(`Error reading file: ${err}`);
6620
+ (_b = this._logger) === null || _b === void 0 ? void 0 : _b.debug(`Error reading file: ${err}`);
6306
6621
  throw new serverSdk.GeneralError();
6307
6622
  }
6308
6623
  }
@@ -6310,7 +6625,7 @@ class FileFetch {
6310
6625
  });
6311
6626
  }
6312
6627
  disconnect() {
6313
- return __awaiter(this, undefined, undefined, function* () {
6628
+ return __awaiter(this, void 0, void 0, function* () {
6314
6629
  fs.unwatchFile(this._filename);
6315
6630
  });
6316
6631
  }
@@ -6374,24 +6689,27 @@ const SyncFlagsRequest = {
6374
6689
  return obj;
6375
6690
  },
6376
6691
  create(base) {
6377
- return SyncFlagsRequest.fromPartial(base !== null && base !== undefined ? base : {});
6692
+ return SyncFlagsRequest.fromPartial(base !== null && base !== void 0 ? base : {});
6378
6693
  },
6379
6694
  fromPartial(object) {
6380
6695
  var _a, _b;
6381
6696
  const message = createBaseSyncFlagsRequest();
6382
- message.providerId = (_a = object.providerId) !== null && _a !== undefined ? _a : "";
6383
- message.selector = (_b = object.selector) !== null && _b !== undefined ? _b : "";
6697
+ message.providerId = (_a = object.providerId) !== null && _a !== void 0 ? _a : "";
6698
+ message.selector = (_b = object.selector) !== null && _b !== void 0 ? _b : "";
6384
6699
  return message;
6385
6700
  },
6386
6701
  };
6387
6702
  function createBaseSyncFlagsResponse() {
6388
- return { flagConfiguration: "" };
6703
+ return { flagConfiguration: "", syncContext: undefined };
6389
6704
  }
6390
6705
  const SyncFlagsResponse = {
6391
6706
  encode(message, writer = _m0.Writer.create()) {
6392
6707
  if (message.flagConfiguration !== "") {
6393
6708
  writer.uint32(10).string(message.flagConfiguration);
6394
6709
  }
6710
+ if (message.syncContext !== undefined) {
6711
+ Struct.encode(Struct.wrap(message.syncContext), writer.uint32(18).fork()).ldelim();
6712
+ }
6395
6713
  return writer;
6396
6714
  },
6397
6715
  decode(input, length) {
@@ -6407,6 +6725,12 @@ const SyncFlagsResponse = {
6407
6725
  }
6408
6726
  message.flagConfiguration = reader.string();
6409
6727
  continue;
6728
+ case 2:
6729
+ if (tag !== 18) {
6730
+ break;
6731
+ }
6732
+ message.syncContext = Struct.unwrap(Struct.decode(reader, reader.uint32()));
6733
+ continue;
6410
6734
  }
6411
6735
  if ((tag & 7) === 4 || tag === 0) {
6412
6736
  break;
@@ -6416,22 +6740,29 @@ const SyncFlagsResponse = {
6416
6740
  return message;
6417
6741
  },
6418
6742
  fromJSON(object) {
6419
- return { flagConfiguration: isSet(object.flagConfiguration) ? String(object.flagConfiguration) : "" };
6743
+ return {
6744
+ flagConfiguration: isSet(object.flagConfiguration) ? String(object.flagConfiguration) : "",
6745
+ syncContext: isObject(object.syncContext) ? object.syncContext : undefined,
6746
+ };
6420
6747
  },
6421
6748
  toJSON(message) {
6422
6749
  const obj = {};
6423
6750
  if (message.flagConfiguration !== "") {
6424
6751
  obj.flagConfiguration = message.flagConfiguration;
6425
6752
  }
6753
+ if (message.syncContext !== undefined) {
6754
+ obj.syncContext = message.syncContext;
6755
+ }
6426
6756
  return obj;
6427
6757
  },
6428
6758
  create(base) {
6429
- return SyncFlagsResponse.fromPartial(base !== null && base !== undefined ? base : {});
6759
+ return SyncFlagsResponse.fromPartial(base !== null && base !== void 0 ? base : {});
6430
6760
  },
6431
6761
  fromPartial(object) {
6432
- var _a;
6762
+ var _a, _b;
6433
6763
  const message = createBaseSyncFlagsResponse();
6434
- message.flagConfiguration = (_a = object.flagConfiguration) !== null && _a !== undefined ? _a : "";
6764
+ message.flagConfiguration = (_a = object.flagConfiguration) !== null && _a !== void 0 ? _a : "";
6765
+ message.syncContext = (_b = object.syncContext) !== null && _b !== void 0 ? _b : undefined;
6435
6766
  return message;
6436
6767
  },
6437
6768
  };
@@ -6492,13 +6823,13 @@ const FetchAllFlagsRequest = {
6492
6823
  return obj;
6493
6824
  },
6494
6825
  create(base) {
6495
- return FetchAllFlagsRequest.fromPartial(base !== null && base !== undefined ? base : {});
6826
+ return FetchAllFlagsRequest.fromPartial(base !== null && base !== void 0 ? base : {});
6496
6827
  },
6497
6828
  fromPartial(object) {
6498
6829
  var _a, _b;
6499
6830
  const message = createBaseFetchAllFlagsRequest();
6500
- message.providerId = (_a = object.providerId) !== null && _a !== undefined ? _a : "";
6501
- message.selector = (_b = object.selector) !== null && _b !== undefined ? _b : "";
6831
+ message.providerId = (_a = object.providerId) !== null && _a !== void 0 ? _a : "";
6832
+ message.selector = (_b = object.selector) !== null && _b !== void 0 ? _b : "";
6502
6833
  return message;
6503
6834
  },
6504
6835
  };
@@ -6544,12 +6875,12 @@ const FetchAllFlagsResponse = {
6544
6875
  return obj;
6545
6876
  },
6546
6877
  create(base) {
6547
- return FetchAllFlagsResponse.fromPartial(base !== null && base !== undefined ? base : {});
6878
+ return FetchAllFlagsResponse.fromPartial(base !== null && base !== void 0 ? base : {});
6548
6879
  },
6549
6880
  fromPartial(object) {
6550
6881
  var _a;
6551
6882
  const message = createBaseFetchAllFlagsResponse();
6552
- message.flagConfiguration = (_a = object.flagConfiguration) !== null && _a !== undefined ? _a : "";
6883
+ message.flagConfiguration = (_a = object.flagConfiguration) !== null && _a !== void 0 ? _a : "";
6553
6884
  return message;
6554
6885
  },
6555
6886
  };
@@ -6581,7 +6912,7 @@ const GetMetadataRequest = {
6581
6912
  return obj;
6582
6913
  },
6583
6914
  create(base) {
6584
- return GetMetadataRequest.fromPartial(base !== null && base !== undefined ? base : {});
6915
+ return GetMetadataRequest.fromPartial(base !== null && base !== void 0 ? base : {});
6585
6916
  },
6586
6917
  fromPartial(_) {
6587
6918
  const message = createBaseGetMetadataRequest();
@@ -6630,12 +6961,12 @@ const GetMetadataResponse = {
6630
6961
  return obj;
6631
6962
  },
6632
6963
  create(base) {
6633
- return GetMetadataResponse.fromPartial(base !== null && base !== undefined ? base : {});
6964
+ return GetMetadataResponse.fromPartial(base !== null && base !== void 0 ? base : {});
6634
6965
  },
6635
6966
  fromPartial(object) {
6636
6967
  var _a;
6637
6968
  const message = createBaseGetMetadataResponse();
6638
- message.metadata = (_a = object.metadata) !== null && _a !== undefined ? _a : undefined;
6969
+ message.metadata = (_a = object.metadata) !== null && _a !== void 0 ? _a : undefined;
6639
6970
  return message;
6640
6971
  },
6641
6972
  };
@@ -6658,6 +6989,7 @@ const FlagSyncServiceService = {
6658
6989
  responseSerialize: (value) => Buffer.from(FetchAllFlagsResponse.encode(value).finish()),
6659
6990
  responseDeserialize: (value) => FetchAllFlagsResponse.decode(value),
6660
6991
  },
6992
+ /** @deprecated */
6661
6993
  getMetadata: {
6662
6994
  path: "/flagd.sync.v1.FlagSyncService/GetMetadata",
6663
6995
  requestStream: false,
@@ -6680,7 +7012,8 @@ function isSet(value) {
6680
7012
  * Implements the gRPC sync contract to fetch flag data.
6681
7013
  */
6682
7014
  class GrpcFetch {
6683
- constructor(config, syncServiceClient, logger) {
7015
+ constructor(config, setSyncContext, syncServiceClient, logger) {
7016
+ this._errorThrottled = false;
6684
7017
  /**
6685
7018
  * Initialized will be set to true once the initial connection is successful
6686
7019
  * and the first payload has been received. Subsequent reconnects will not
@@ -6693,63 +7026,88 @@ class GrpcFetch {
6693
7026
  * false if the connection is lost.
6694
7027
  */
6695
7028
  this._isConnected = false;
6696
- const { host, port, tls, socketPath, selector, defaultAuthority } = config;
6697
- let clientOptions;
6698
- if (defaultAuthority) {
6699
- clientOptions = {
6700
- 'grpc.default_authority': defaultAuthority,
6701
- };
6702
- }
7029
+ const { host, port, tls, socketPath, certPath, selector } = config;
7030
+ const clientOptions = buildClientOptions(config);
7031
+ const channelCredentials = createChannelCredentials(tls, certPath);
6703
7032
  this._syncClient = syncServiceClient
6704
7033
  ? syncServiceClient
6705
- : new FlagSyncServiceClient(socketPath ? `unix://${socketPath}` : `${host}:${port}`, tls ? grpcJs.credentials.createSsl() : grpcJs.credentials.createInsecure(), clientOptions);
7034
+ : new FlagSyncServiceClient(socketPath ? `unix://${socketPath}` : `${host}:${port}`, channelCredentials, clientOptions);
7035
+ this._deadlineMs = config.deadlineMs;
7036
+ this._maxBackoffMs = config.retryBackoffMaxMs || DEFAULT_MAX_BACKOFF_MS;
7037
+ this._streamDeadlineMs = config.streamDeadlineMs;
7038
+ this._setSyncContext = setSyncContext;
6706
7039
  this._logger = logger;
7040
+ // For backward compatibility during the deprecation period, we send the selector in both:
7041
+ // 1. The request field (deprecated, for older flagd versions)
7042
+ // 2. The gRPC metadata header 'flagd-selector' (new standard)
6707
7043
  this._request = { providerId: '', selector: selector ? selector : '' };
7044
+ this._fatalStatusCodes = createFatalStatusCodesSet(config.fatalStatusCodes, logger);
7045
+ // Create metadata with the flagd-selector header
7046
+ this._metadata = new grpcJs.Metadata();
7047
+ if (selector) {
7048
+ this._metadata.set(FLAGD_SELECTOR_HEADER, selector);
7049
+ }
6708
7050
  }
6709
7051
  connect(dataCallback, reconnectCallback, changedCallback, disconnectCallback) {
6710
- return __awaiter(this, undefined, undefined, function* () {
7052
+ return __awaiter(this, void 0, void 0, function* () {
6711
7053
  yield new Promise((resolve, reject) => this.listen(dataCallback, reconnectCallback, changedCallback, disconnectCallback, resolve, reject));
6712
7054
  this._initialized = true;
6713
7055
  });
6714
7056
  }
6715
7057
  disconnect() {
6716
- return __awaiter(this, undefined, undefined, function* () {
7058
+ return __awaiter(this, void 0, void 0, function* () {
6717
7059
  var _a;
6718
- (_a = this._logger) === null || _a === undefined ? undefined : _a.debug('Disconnecting gRPC sync connection');
7060
+ (_a = this._logger) === null || _a === void 0 ? void 0 : _a.debug('Disconnecting gRPC sync connection');
6719
7061
  closeStreamIfDefined(this._syncStream);
6720
7062
  this._syncClient.close();
6721
7063
  });
6722
7064
  }
6723
7065
  listen(dataCallback, reconnectCallback, changedCallback, disconnectCallback, resolveConnect, rejectConnect) {
6724
7066
  var _a;
6725
- (_a = this._logger) === null || _a === undefined ? undefined : _a.debug('Starting gRPC sync connection');
7067
+ (_a = this._logger) === null || _a === void 0 ? void 0 : _a.debug('Starting gRPC sync connection');
6726
7068
  closeStreamIfDefined(this._syncStream);
6727
7069
  try {
6728
- this._syncStream = this._syncClient.syncFlags(this._request);
6729
- this._syncStream.on('data', (data) => {
6730
- var _a, _b, _c, _d;
6731
- (_a = this._logger) === null || _a === void 0 ? void 0 : _a.debug(`Received sync payload`);
6732
- try {
6733
- const changes = dataCallback(data.flagConfiguration);
6734
- if (this._initialized && changes.length > 0) {
6735
- changedCallback(changes);
6736
- }
6737
- }
6738
- catch (err) {
6739
- (_b = this._logger) === null || _b === void 0 ? void 0 : _b.debug('Error processing sync payload: ', (_c = err === null || err === void 0 ? void 0 : err.message) !== null && _c !== void 0 ? _c : 'unknown error');
6740
- }
6741
- if (resolveConnect) {
6742
- resolveConnect();
7070
+ // wait for connection to be stable
7071
+ this._syncClient.waitForReady(Date.now() + this._deadlineMs, (err) => {
7072
+ if (err) {
7073
+ this.handleError(err, dataCallback, reconnectCallback, changedCallback, disconnectCallback, rejectConnect);
6743
7074
  }
6744
- else if (!this._isConnected) {
6745
- // Not the first connection and there's no active connection.
6746
- (_d = this._logger) === null || _d === void 0 ? void 0 : _d.debug('Reconnected to gRPC sync');
6747
- reconnectCallback();
7075
+ else {
7076
+ const streamDeadline = this._streamDeadlineMs != 0 ? Date.now() + this._streamDeadlineMs : undefined;
7077
+ const stream = this._syncClient.syncFlags(this._request, this._metadata, { deadline: streamDeadline });
7078
+ stream.on('data', (data) => {
7079
+ var _a, _b, _c, _d;
7080
+ (_a = this._logger) === null || _a === void 0 ? void 0 : _a.debug(`Received sync payload`);
7081
+ try {
7082
+ if (data.syncContext) {
7083
+ this._setSyncContext(data.syncContext);
7084
+ }
7085
+ const changes = dataCallback(data.flagConfiguration);
7086
+ if (this._initialized && changes.length > 0) {
7087
+ changedCallback(changes);
7088
+ }
7089
+ }
7090
+ catch (err) {
7091
+ (_b = this._logger) === null || _b === void 0 ? void 0 : _b.debug('Error processing sync payload: ', (_c = err === null || err === void 0 ? void 0 : err.message) !== null && _c !== void 0 ? _c : 'unknown error');
7092
+ }
7093
+ if (resolveConnect) {
7094
+ resolveConnect();
7095
+ }
7096
+ else if (!this._isConnected) {
7097
+ // Not the first connection and there's no active connection.
7098
+ (_d = this._logger) === null || _d === void 0 ? void 0 : _d.debug('Reconnected to gRPC sync');
7099
+ reconnectCallback();
7100
+ }
7101
+ this._isConnected = true;
7102
+ });
7103
+ stream.on('error', (err) => {
7104
+ // In cases where we get an explicit error status, we add a delay.
7105
+ // This prevents tight loops when errors are returned immediately, typically by intervening proxies like Envoy.
7106
+ this._errorThrottled = true;
7107
+ this.handleError(err, dataCallback, reconnectCallback, changedCallback, disconnectCallback, rejectConnect);
7108
+ });
7109
+ this._syncStream = stream;
6748
7110
  }
6749
- this._isConnected = true;
6750
- });
6751
- this._syncStream.on('error', (err) => {
6752
- this.handleError(err, dataCallback, reconnectCallback, changedCallback, disconnectCallback, rejectConnect);
6753
7111
  });
6754
7112
  }
6755
7113
  catch (err) {
@@ -6758,57 +7116,64 @@ class GrpcFetch {
6758
7116
  }
6759
7117
  handleError(err, dataCallback, reconnectCallback, changedCallback, disconnectCallback, rejectConnect) {
6760
7118
  var _a, _b, _c;
6761
- (_a = this._logger) === null || _a === undefined ? undefined : _a.error('Connection error, attempting to reconnect');
6762
- (_b = this._logger) === null || _b === undefined ? undefined : _b.debug(err);
7119
+ // Check if error is a fatal status code on first connection only
7120
+ if (isFatalStatusCodeError(err, this._initialized, this._fatalStatusCodes)) {
7121
+ this._isConnected = false;
7122
+ handleFatalStatusCodeError(err, this._logger, disconnectCallback, rejectConnect);
7123
+ return;
7124
+ }
7125
+ (_a = this._logger) === null || _a === void 0 ? void 0 : _a.error('Connection error, attempting to reconnect');
7126
+ (_b = this._logger) === null || _b === void 0 ? void 0 : _b.debug(err);
6763
7127
  this._isConnected = false;
6764
- const errorMessage = (_c = err === null || err === undefined ? undefined : err.message) !== null && _c !== undefined ? _c : 'Failed to connect to syncFlags stream';
7128
+ const errorMessage = (_c = err === null || err === void 0 ? void 0 : err.message) !== null && _c !== void 0 ? _c : 'Failed to connect to syncFlags stream';
6765
7129
  disconnectCallback(errorMessage);
6766
- rejectConnect === null || rejectConnect === undefined ? undefined : rejectConnect(new serverSdk.GeneralError(errorMessage));
7130
+ rejectConnect === null || rejectConnect === void 0 ? void 0 : rejectConnect(new serverSdk.GeneralError(errorMessage));
6767
7131
  this.reconnect(dataCallback, reconnectCallback, changedCallback, disconnectCallback);
6768
7132
  }
6769
7133
  reconnect(dataCallback, reconnectCallback, changedCallback, disconnectCallback) {
6770
- const channel = this._syncClient.getChannel();
6771
- channel.watchConnectivityState(channel.getConnectivityState(true), Infinity, () => {
6772
- this.listen(dataCallback, reconnectCallback, changedCallback, disconnectCallback);
6773
- });
7134
+ setTimeout(() => this.listen(dataCallback, reconnectCallback, changedCallback, disconnectCallback), this._errorThrottled ? this._maxBackoffMs : 0);
7135
+ this._errorThrottled = false;
6774
7136
  }
6775
7137
  }
6776
7138
 
6777
7139
  class InProcessService {
6778
- constructor(config, dataFetcher, logger) {
7140
+ constructor(config, setSyncContext, dataFetcher, logger) {
6779
7141
  this.config = config;
6780
7142
  this._flagdCore = new flagdCore.FlagdCore(undefined, logger);
6781
7143
  this._dataFetcher = dataFetcher
6782
7144
  ? dataFetcher
6783
7145
  : config.offlineFlagSourcePath
6784
7146
  ? new FileFetch(config.offlineFlagSourcePath, logger)
6785
- : new GrpcFetch(config, undefined, logger);
7147
+ : new GrpcFetch(config, setSyncContext, undefined, logger);
7148
+ }
7149
+ clearCache() {
7150
+ // in-process service does not cache flags
6786
7151
  }
6787
7152
  connect(reconnectCallback, changedCallback, disconnectCallback) {
6788
7153
  return this._dataFetcher.connect(this.setFlagConfiguration.bind(this), reconnectCallback, changedCallback, disconnectCallback);
6789
7154
  }
6790
7155
  disconnect() {
6791
- return __awaiter(this, undefined, undefined, function* () {
7156
+ return __awaiter(this, void 0, void 0, function* () {
6792
7157
  this._dataFetcher.disconnect();
6793
7158
  });
6794
7159
  }
6795
7160
  resolveBoolean(flagKey, defaultValue, context, logger) {
6796
- return __awaiter(this, undefined, undefined, function* () {
7161
+ return __awaiter(this, void 0, void 0, function* () {
6797
7162
  return this.evaluate('boolean', flagKey, defaultValue, context, logger);
6798
7163
  });
6799
7164
  }
6800
7165
  resolveNumber(flagKey, defaultValue, context, logger) {
6801
- return __awaiter(this, undefined, undefined, function* () {
7166
+ return __awaiter(this, void 0, void 0, function* () {
6802
7167
  return this.evaluate('number', flagKey, defaultValue, context, logger);
6803
7168
  });
6804
7169
  }
6805
7170
  resolveString(flagKey, defaultValue, context, logger) {
6806
- return __awaiter(this, undefined, undefined, function* () {
7171
+ return __awaiter(this, void 0, void 0, function* () {
6807
7172
  return this.evaluate('string', flagKey, defaultValue, context, logger);
6808
7173
  });
6809
7174
  }
6810
7175
  resolveObject(flagKey, defaultValue, context, logger) {
6811
- return __awaiter(this, undefined, undefined, function* () {
7176
+ return __awaiter(this, void 0, void 0, function* () {
6812
7177
  return this.evaluate('object', flagKey, defaultValue, context, logger);
6813
7178
  });
6814
7179
  }
@@ -6831,6 +7196,15 @@ class InProcessService {
6831
7196
  }
6832
7197
  }
6833
7198
 
7199
+ class SyncMetadataHook {
7200
+ constructor(enrichedContext) {
7201
+ this.enrichedContext = enrichedContext;
7202
+ }
7203
+ before(hookContext, hookHints) {
7204
+ return this.enrichedContext();
7205
+ }
7206
+ }
7207
+
6834
7208
  class FlagdProvider {
6835
7209
  /**
6836
7210
  * Construct a new flagd provider.
@@ -6840,36 +7214,58 @@ class FlagdProvider {
6840
7214
  * @param service optional internal service implementation, should not be needed for production
6841
7215
  */
6842
7216
  constructor(options, logger, service) {
7217
+ var _a;
6843
7218
  this.logger = logger;
6844
7219
  this.metadata = {
6845
7220
  name: 'flagd',
6846
7221
  };
6847
7222
  this.runsOn = 'server';
6848
7223
  this.events = new serverSdk.OpenFeatureEventEmitter();
7224
+ this.syncContext = null;
7225
+ this._isErrorState = false;
6849
7226
  const config = getConfig(options);
6850
- this._service = service
6851
- ? service
6852
- : config.resolverType === 'in-process'
6853
- ? new InProcessService(config, undefined, logger)
6854
- : new GRPCService(config, undefined, logger);
7227
+ this._retryGracePeriod = (_a = config.retryGracePeriod) !== null && _a !== void 0 ? _a : DEFAULT_RETRY_GRACE_PERIOD;
7228
+ if (service === undefined) {
7229
+ if (config.resolverType === 'in-process') {
7230
+ this._service = new InProcessService(config, this.setSyncContext.bind(this), undefined, logger);
7231
+ if ((config === null || config === void 0 ? void 0 : config.offlineFlagSourcePath) === undefined) {
7232
+ this.hooks = [new SyncMetadataHook(() => config.contextEnricher(this.getSyncContext()))];
7233
+ }
7234
+ }
7235
+ else {
7236
+ this._service = new GRPCService(config, undefined, logger);
7237
+ }
7238
+ }
7239
+ else {
7240
+ this._service = service;
7241
+ }
7242
+ }
7243
+ setSyncContext(context) {
7244
+ this.syncContext = context;
7245
+ }
7246
+ getSyncContext() {
7247
+ return this.syncContext;
6855
7248
  }
6856
7249
  initialize() {
6857
- return __awaiter(this, undefined, undefined, function* () {
7250
+ return __awaiter(this, void 0, void 0, function* () {
6858
7251
  var _a, _b, _c;
6859
7252
  try {
6860
7253
  yield this._service.connect(this.handleReconnect.bind(this), this.handleChanged.bind(this), this.handleError.bind(this));
7254
+ this.clearErrorTimer();
7255
+ this._isErrorState = false;
6861
7256
  (_a = this.logger) === null || _a === void 0 ? void 0 : _a.debug(`${this.metadata.name}: ready`);
6862
7257
  }
6863
7258
  catch (err) {
6864
- (_b = this.logger) === null || _b === undefined ? undefined : _b.error(`${this.metadata.name}: error during initialization: ${err === null || err === undefined ? undefined : err.message}`);
6865
- (_c = this.logger) === null || _c === undefined ? undefined : _c.debug(err);
7259
+ (_b = this.logger) === null || _b === void 0 ? void 0 : _b.error(`${this.metadata.name}: error during initialization: ${err === null || err === void 0 ? void 0 : err.message}`);
7260
+ (_c = this.logger) === null || _c === void 0 ? void 0 : _c.debug(err);
6866
7261
  throw err;
6867
7262
  }
6868
7263
  });
6869
7264
  }
6870
7265
  onClose() {
6871
7266
  var _a;
6872
- (_a = this.logger) === null || _a === undefined ? undefined : _a.debug(`${this.metadata.name}: shutting down`);
7267
+ (_a = this.logger) === null || _a === void 0 ? void 0 : _a.debug(`${this.metadata.name}: shutting down`);
7268
+ this.clearErrorTimer();
6873
7269
  return this._service.disconnect();
6874
7270
  }
6875
7271
  resolveBooleanEvaluation(flagKey, defaultValue, transformedContext, logger) {
@@ -6885,14 +7281,35 @@ class FlagdProvider {
6885
7281
  return this._service.resolveObject(flagKey, defaultValue, transformedContext, logger);
6886
7282
  }
6887
7283
  handleReconnect() {
7284
+ this.clearErrorTimer();
7285
+ this._isErrorState = false;
6888
7286
  this.events.emit(serverSdk.ProviderEvents.Ready);
6889
7287
  }
6890
7288
  handleError(message) {
6891
- this.events.emit(serverSdk.ProviderEvents.Error, { message });
7289
+ if (this._isErrorState) {
7290
+ return;
7291
+ }
7292
+ this._isErrorState = true;
7293
+ this.events.emit(serverSdk.ProviderEvents.Stale, { message });
7294
+ this._errorTimer = setTimeout(() => {
7295
+ var _a;
7296
+ if (this._isErrorState) {
7297
+ (_a = this.logger) === null || _a === void 0 ? void 0 : _a.error(`${this.metadata.name}: not reconnected within ${this._retryGracePeriod}s grace period, emitting ERROR`);
7298
+ this._service.clearCache();
7299
+ this.events.emit(serverSdk.ProviderEvents.Error, { message });
7300
+ }
7301
+ this._errorTimer = undefined;
7302
+ }, this._retryGracePeriod * 1000);
6892
7303
  }
6893
7304
  handleChanged(flagsChanged) {
6894
7305
  this.events.emit(serverSdk.ProviderEvents.ConfigurationChanged, { flagsChanged });
6895
7306
  }
7307
+ clearErrorTimer() {
7308
+ if (this._errorTimer) {
7309
+ clearTimeout(this._errorTimer);
7310
+ this._errorTimer = undefined;
7311
+ }
7312
+ }
6896
7313
  }
6897
7314
 
6898
7315
  exports.FlagdProvider = FlagdProvider;