@metamask-previews/controller-utils 11.15.0-preview-96f3a4d7 → 11.15.0-preview-e493d3e8

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/CHANGELOG.md CHANGED
@@ -7,17 +7,6 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
7
7
 
8
8
  ## [Unreleased]
9
9
 
10
- ### Added
11
-
12
- - Add `getCircuitState` method to `ServicePolicy` ([#7164](https://github.com/MetaMask/core/pull/7164))
13
- - This can be used when working with a chain of services to know whether a service's underlying circuit is open or closed.
14
- - Add `onAvailable` method to `ServicePolicy` ([#7164](https://github.com/MetaMask/core/pull/7164))
15
- - This can be used to listen for the initial successful execution of the service, or the first successful execution after the service becomes degraded or the circuit breaks.
16
- - Add `reset` method to `ServicePolicy` ([#7164](https://github.com/MetaMask/core/pull/7164))
17
- - This can be used when working with a chain of services to reset the state of the circuit breaker policy (e.g. if a primary recovers and we want to reset the failovers).
18
- - Export `CockatielEventEmitter` and `CockatielFailureReason` from Cockatiel ([#7164](https://github.com/MetaMask/core/pull/7164))
19
- - These can be used to further transform types for event emitters/listeners.
20
-
21
10
  ## [11.15.0]
22
11
 
23
12
  ### Added
@@ -1,25 +1,13 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.createServicePolicy = exports.DEFAULT_DEGRADED_THRESHOLD = exports.DEFAULT_CIRCUIT_BREAK_DURATION = exports.DEFAULT_MAX_CONSECUTIVE_FAILURES = exports.DEFAULT_MAX_RETRIES = exports.handleWhen = exports.handleAll = exports.ExponentialBackoff = exports.ConstantBackoff = exports.CircuitState = exports.CockatielEventEmitter = exports.BrokenCircuitError = void 0;
3
+ exports.createServicePolicy = exports.DEFAULT_DEGRADED_THRESHOLD = exports.DEFAULT_CIRCUIT_BREAK_DURATION = exports.DEFAULT_MAX_CONSECUTIVE_FAILURES = exports.DEFAULT_MAX_RETRIES = exports.handleWhen = exports.handleAll = exports.ExponentialBackoff = exports.ConstantBackoff = exports.CircuitState = exports.BrokenCircuitError = void 0;
4
4
  const cockatiel_1 = require("cockatiel");
5
5
  Object.defineProperty(exports, "BrokenCircuitError", { enumerable: true, get: function () { return cockatiel_1.BrokenCircuitError; } });
6
6
  Object.defineProperty(exports, "CircuitState", { enumerable: true, get: function () { return cockatiel_1.CircuitState; } });
7
- Object.defineProperty(exports, "CockatielEventEmitter", { enumerable: true, get: function () { return cockatiel_1.EventEmitter; } });
8
7
  Object.defineProperty(exports, "ExponentialBackoff", { enumerable: true, get: function () { return cockatiel_1.ExponentialBackoff; } });
9
8
  Object.defineProperty(exports, "ConstantBackoff", { enumerable: true, get: function () { return cockatiel_1.ConstantBackoff; } });
10
9
  Object.defineProperty(exports, "handleAll", { enumerable: true, get: function () { return cockatiel_1.handleAll; } });
11
10
  Object.defineProperty(exports, "handleWhen", { enumerable: true, get: function () { return cockatiel_1.handleWhen; } });
12
- /**
13
- * Availability statuses that the service can be in.
14
- *
15
- * Used to keep track of whether the `onAvailable` event should be fired.
16
- */
17
- const AVAILABILITY_STATUSES = {
18
- Available: 'available',
19
- Degraded: 'degraded',
20
- Unavailable: 'unavailable',
21
- Unknown: 'unknown',
22
- };
23
11
  /**
24
12
  * The maximum number of times that a failing service should be re-run before
25
13
  * giving up.
@@ -123,7 +111,6 @@ function getInternalCircuitState(state) {
123
111
  */
124
112
  function createServicePolicy(options = {}) {
125
113
  const { maxRetries = exports.DEFAULT_MAX_RETRIES, retryFilterPolicy = cockatiel_1.handleAll, maxConsecutiveFailures = exports.DEFAULT_MAX_CONSECUTIVE_FAILURES, circuitBreakDuration = exports.DEFAULT_CIRCUIT_BREAK_DURATION, degradedThreshold = exports.DEFAULT_DEGRADED_THRESHOLD, backoff = new cockatiel_1.ExponentialBackoff(), } = options;
126
- let availabilityStatus = AVAILABILITY_STATUSES.Unknown;
127
114
  const retryPolicy = (0, cockatiel_1.retry)(retryFilterPolicy, {
128
115
  // Note that although the option here is called "max attempts", it's really
129
116
  // maximum number of *retries* (attempts past the initial attempt).
@@ -133,7 +120,6 @@ function createServicePolicy(options = {}) {
133
120
  backoff,
134
121
  });
135
122
  const onRetry = retryPolicy.onRetry.bind(retryPolicy);
136
- const consecutiveBreaker = new cockatiel_1.ConsecutiveBreaker(maxConsecutiveFailures);
137
123
  const circuitBreakerPolicy = (0, cockatiel_1.circuitBreaker)((0, cockatiel_1.handleWhen)(isServiceFailure), {
138
124
  // While the circuit is open, any additional invocations of the service
139
125
  // passed to the policy (either via automatic retries or by manually
@@ -142,59 +128,28 @@ function createServicePolicy(options = {}) {
142
128
  // service will be allowed to run again. If the service succeeds, the
143
129
  // circuit will close, otherwise it will remain open.
144
130
  halfOpenAfter: circuitBreakDuration,
145
- breaker: consecutiveBreaker,
131
+ breaker: new cockatiel_1.ConsecutiveBreaker(maxConsecutiveFailures),
146
132
  });
147
133
  let internalCircuitState = getInternalCircuitState(circuitBreakerPolicy.state);
148
134
  circuitBreakerPolicy.onStateChange((state) => {
149
135
  internalCircuitState = getInternalCircuitState(state);
150
136
  });
151
- circuitBreakerPolicy.onBreak(() => {
152
- availabilityStatus = AVAILABILITY_STATUSES.Unavailable;
153
- });
154
137
  const onBreak = circuitBreakerPolicy.onBreak.bind(circuitBreakerPolicy);
155
138
  const onDegradedEventEmitter = new cockatiel_1.EventEmitter();
156
- const onDegraded = onDegradedEventEmitter.addListener;
157
- const onAvailableEventEmitter = new cockatiel_1.EventEmitter();
158
- const onAvailable = onAvailableEventEmitter.addListener;
159
139
  retryPolicy.onGiveUp((data) => {
160
140
  if (circuitBreakerPolicy.state === cockatiel_1.CircuitState.Closed) {
161
- availabilityStatus = AVAILABILITY_STATUSES.Degraded;
162
141
  onDegradedEventEmitter.emit(data);
163
142
  }
164
143
  });
165
144
  retryPolicy.onSuccess(({ duration }) => {
166
- if (circuitBreakerPolicy.state === cockatiel_1.CircuitState.Closed) {
167
- if (duration > degradedThreshold) {
168
- availabilityStatus = AVAILABILITY_STATUSES.Degraded;
169
- onDegradedEventEmitter.emit();
170
- }
171
- else if (availabilityStatus !== AVAILABILITY_STATUSES.Available) {
172
- availabilityStatus = AVAILABILITY_STATUSES.Available;
173
- onAvailableEventEmitter.emit();
174
- }
145
+ if (circuitBreakerPolicy.state === cockatiel_1.CircuitState.Closed &&
146
+ duration > degradedThreshold) {
147
+ onDegradedEventEmitter.emit();
175
148
  }
176
149
  });
150
+ const onDegraded = onDegradedEventEmitter.addListener;
177
151
  // Every time the retry policy makes an attempt, it executes the circuit
178
152
  // breaker policy, which executes the service.
179
- //
180
- // Calling:
181
- //
182
- // policy.execute(() => {
183
- // // do what the service does
184
- // })
185
- //
186
- // is equivalent to:
187
- //
188
- // retryPolicy.execute(() => {
189
- // circuitBreakerPolicy.execute(() => {
190
- // // do what the service does
191
- // });
192
- // });
193
- //
194
- // So if the retry policy succeeds or fails, it is because the circuit breaker
195
- // policy succeeded or failed. And if there are any event listeners registered
196
- // on the retry policy, by the time they are called, the state of the circuit
197
- // breaker will have already changed.
198
153
  const policy = (0, cockatiel_1.wrap)(retryPolicy, circuitBreakerPolicy);
199
154
  const getRemainingCircuitOpenDuration = () => {
200
155
  if (internalCircuitState.state === cockatiel_1.CircuitState.Open) {
@@ -202,31 +157,14 @@ function createServicePolicy(options = {}) {
202
157
  }
203
158
  return null;
204
159
  };
205
- const getCircuitState = () => {
206
- return circuitBreakerPolicy.state;
207
- };
208
- const reset = () => {
209
- // Set the state of the policy to "isolated" regardless of its current state
210
- const { dispose } = circuitBreakerPolicy.isolate();
211
- // Reset the state to "closed"
212
- dispose();
213
- // Reset the counter on the breaker as well
214
- consecutiveBreaker.success();
215
- // Re-initialize the availability status so that if the service is executed
216
- // successfully, onAvailable listeners will be called again
217
- availabilityStatus = AVAILABILITY_STATUSES.Unknown;
218
- };
219
160
  return {
220
161
  ...policy,
221
162
  circuitBreakerPolicy,
222
163
  circuitBreakDuration,
223
- getCircuitState,
224
164
  getRemainingCircuitOpenDuration,
225
- reset,
226
165
  retryPolicy,
227
166
  onBreak,
228
167
  onDegraded,
229
- onAvailable,
230
168
  onRetry,
231
169
  };
232
170
  }
@@ -1 +1 @@
1
- {"version":3,"file":"create-service-policy.cjs","sourceRoot":"","sources":["../src/create-service-policy.ts"],"names":[],"mappings":";;;AAAA,yCAYmB;AAYjB,mGAvBA,8BAAkB,OAuBA;AAElB,6FAxBA,wBAAY,OAwBA;AADZ,sGAtBgB,wBAAqB,OAsBhB;AAGrB,mGAvBA,8BAAkB,OAuBA;AADlB,gGArBA,2BAAe,OAqBA;AAEf,0FArBA,qBAAS,OAqBA;AACT,2FArBA,sBAAU,OAqBA;AAmHZ;;;;GAIG;AACH,MAAM,qBAAqB,GAAG;IAC5B,SAAS,EAAE,WAAW;IACtB,QAAQ,EAAE,UAAU;IACpB,WAAW,EAAE,aAAa;IAC1B,OAAO,EAAE,SAAS;CACV,CAAC;AAUX;;;GAGG;AACU,QAAA,mBAAmB,GAAG,CAAC,CAAC;AAErC;;;;;GAKG;AACU,QAAA,gCAAgC,GAAG,CAAC,CAAC,GAAG,2BAAmB,CAAC,GAAG,CAAC,CAAC;AAE9E;;;GAGG;AACU,QAAA,8BAA8B,GAAG,EAAE,GAAG,EAAE,GAAG,IAAI,CAAC;AAE7D;;;GAGG;AACU,QAAA,0BAA0B,GAAG,IAAK,CAAC;AAEhD,MAAM,gBAAgB,GAAG,CAAC,KAAc,EAAE,EAAE;IAC1C,IACE,OAAO,KAAK,KAAK,QAAQ;QACzB,KAAK,KAAK,IAAI;QACd,YAAY,IAAI,KAAK;QACrB,OAAO,KAAK,CAAC,UAAU,KAAK,QAAQ,EACpC,CAAC;QACD,OAAO,KAAK,CAAC,UAAU,IAAI,GAAG,CAAC;IACjC,CAAC;IAED,0EAA0E;IAC1E,uEAAuE;IACvE,OAAO,IAAI,CAAC;AACd,CAAC,CAAC;AAEF;;;;;;;;;;;GAWG;AACH,SAAS,uBAAuB,CAAC,KAAmB;IAClD,IAAI,KAAK,KAAK,wBAAY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State,\n EventEmitter as CockatielEventEmitter,\n ConsecutiveBreaker,\n ExponentialBackoff,\n ConstantBackoff,\n circuitBreaker,\n handleAll,\n handleWhen,\n retry,\n wrap,\n} from 'cockatiel';\nimport type {\n CircuitBreakerPolicy,\n Event as CockatielEvent,\n FailureReason,\n IBackoffFactory,\n IPolicy,\n Policy,\n RetryPolicy,\n} from 'cockatiel';\n\nexport {\n BrokenCircuitError,\n CockatielEventEmitter,\n CircuitState,\n ConstantBackoff,\n ExponentialBackoff,\n handleAll,\n handleWhen,\n};\n\nexport type { CockatielEvent, FailureReason as CockatielFailureReason };\n\n/**\n * The options for `createServicePolicy`.\n */\nexport type CreateServicePolicyOptions = {\n /**\n * The backoff strategy to use. Mainly useful for testing so that a constant\n * backoff can be used when mocking timers. Defaults to an instance of\n * ExponentialBackoff.\n */\n backoff?: IBackoffFactory<unknown>;\n /**\n * The length of time (in milliseconds) to pause retries of the action after\n * the number of failures reaches `maxConsecutiveFailures`.\n */\n circuitBreakDuration?: number;\n /**\n * The length of time (in milliseconds) that governs when the service is\n * regarded as degraded (affecting when `onDegraded` is called).\n */\n degradedThreshold?: number;\n /**\n * The maximum number of times that the service is allowed to fail before\n * pausing further retries.\n */\n maxConsecutiveFailures?: number;\n /**\n * The maximum number of times that a failing service should be re-invoked\n * before giving up.\n */\n maxRetries?: number;\n /**\n * The policy used to control when the service should be retried based on\n * either the result of the service or an error that it throws. For instance,\n * you could use this to retry only certain errors. See `handleWhen` and\n * friends from Cockatiel for more.\n */\n retryFilterPolicy?: Policy;\n};\n\n/**\n * The service policy object.\n */\nexport type ServicePolicy = IPolicy & {\n /**\n * The Cockatiel circuit breaker policy that the service policy uses\n * internally.\n */\n circuitBreakerPolicy: CircuitBreakerPolicy;\n /**\n * The amount of time to pause requests to the service if the number of\n * maximum consecutive failures is reached.\n */\n circuitBreakDuration: number;\n /**\n * @returns The state of the underlying circuit.\n */\n getCircuitState: () => CircuitState;\n /**\n * If the circuit is open and ongoing requests are paused, returns the number\n * of milliseconds before the requests will be attempted again. If the circuit\n * is not open, returns null.\n */\n getRemainingCircuitOpenDuration: () => number | null;\n /**\n * Resets the internal circuit breaker policy (if it is open, it will now be\n * closed).\n */\n reset: () => void;\n /**\n * The Cockatiel retry policy that the service policy uses internally.\n */\n retryPolicy: RetryPolicy;\n /**\n * A function which is called when the number of times that the service fails\n * in a row meets the set maximum number of consecutive failures.\n */\n onBreak: CircuitBreakerPolicy['onBreak'];\n /**\n * A function which is called in two circumstances: 1) when the service\n * succeeds before the maximum number of consecutive failures is reached, but\n * takes more time than the `degradedThreshold` to run, or 2) if the service\n * never succeeds before the retry policy gives up and before the maximum\n * number of consecutive failures has been reached.\n */\n onDegraded: CockatielEvent<FailureReason<unknown> | void>;\n /**\n * A function which is called when the service succeeds for the first time,\n * or when the service fails enough times to cause the circuit to break and\n * then recovers.\n */\n onAvailable: CockatielEvent<void>;\n /**\n * A function which will be called by the retry policy each time the service\n * fails and the policy kicks off a timer to re-run the service. This is\n * primarily useful in tests where we are mocking timers.\n */\n onRetry: RetryPolicy['onRetry'];\n};\n\n/**\n * Parts of the circuit breaker's internal and external state as necessary in\n * order to compute the time remaining before the circuit will reopen.\n */\ntype InternalCircuitState =\n | {\n state: CircuitState.Open;\n openedAt: number;\n }\n | { state: Exclude<CircuitState, CircuitState.Open> };\n\n/**\n * Availability statuses that the service can be in.\n *\n * Used to keep track of whether the `onAvailable` event should be fired.\n */\nconst AVAILABILITY_STATUSES = {\n Available: 'available',\n Degraded: 'degraded',\n Unavailable: 'unavailable',\n Unknown: 'unknown',\n} as const;\n\n/**\n * Availability statuses that the service can be in.\n *\n * Used to keep track of whether the `onAvailable` event should be fired.\n */\ntype AvailabilityStatus =\n (typeof AVAILABILITY_STATUSES)[keyof typeof AVAILABILITY_STATUSES];\n\n/**\n * The maximum number of times that a failing service should be re-run before\n * giving up.\n */\nexport const DEFAULT_MAX_RETRIES = 3;\n\n/**\n * The maximum number of times that the service is allowed to fail before\n * pausing further retries. This is set to a value such that if given a\n * service that continually fails, the policy needs to be executed 3 times\n * before further retries are paused.\n */\nexport const DEFAULT_MAX_CONSECUTIVE_FAILURES = (1 + DEFAULT_MAX_RETRIES) * 3;\n\n/**\n * The default length of time (in milliseconds) to temporarily pause retries of\n * the service after enough consecutive failures.\n */\nexport const DEFAULT_CIRCUIT_BREAK_DURATION = 30 * 60 * 1000;\n\n/**\n * The default length of time (in milliseconds) that governs when the service is\n * regarded as degraded (affecting when `onDegraded` is called).\n */\nexport const DEFAULT_DEGRADED_THRESHOLD = 5_000;\n\nconst isServiceFailure = (error: unknown) => {\n if (\n typeof error === 'object' &&\n error !== null &&\n 'httpStatus' in error &&\n typeof error.httpStatus === 'number'\n ) {\n return error.httpStatus >= 500;\n }\n\n // If the error is not an object, or doesn't have a numeric code property,\n // consider it a service failure (e.g., network errors, timeouts, etc.)\n return true;\n};\n\n/**\n * The circuit breaker policy inside of the Cockatiel library exposes some of\n * its state, but not all of it. Notably, the time that the circuit opened is\n * not publicly accessible. So we have to record this ourselves.\n *\n * This function therefore allows us to obtain the circuit breaker state that we\n * wish we could access.\n *\n * @param state - The public state of a circuit breaker policy.\n * @returns if the circuit is open, the state of the circuit breaker policy plus\n * the time that it opened, otherwise just the circuit state.\n */\nfunction getInternalCircuitState(state: CircuitState): InternalCircuitState {\n if (state === CircuitState.Open) {\n return { state, openedAt: Date.now() };\n }\n return { state };\n}\n\n/**\n * Constructs an object exposing an `execute` method which, given a function —\n * hereafter called the \"service\" — will retry that service with ever increasing\n * delays until it succeeds. If the policy detects too many consecutive\n * failures, it will block further retries until a designated time period has\n * passed; this particular behavior is primarily designed for services that wrap\n * API calls so as not to make needless HTTP requests when the API is down and\n * to be able to recover when the API comes back up. In addition, hooks allow\n * for responding to certain events, one of which can be used to detect when an\n * HTTP request is performing slowly.\n *\n * Internally, this function makes use of the retry and circuit breaker policies\n * from the [Cockatiel](https://www.npmjs.com/package/cockatiel) library; see\n * there for more.\n *\n * @param options - The options to this function. See\n * {@link CreateServicePolicyOptions}.\n * @returns The service policy.\n * @example\n * This function is designed to be used in the context of a service class like\n * this:\n * ``` ts\n * class Service {\n * constructor() {\n * this.#policy = createServicePolicy({\n * maxRetries: 3,\n * retryFilterPolicy: handleWhen((error) => {\n * return error.message.includes('oops');\n * }),\n * maxConsecutiveFailures: 3,\n * circuitBreakDuration: 5000,\n * degradedThreshold: 2000,\n * onBreak: () => {\n * console.log('Circuit broke');\n * },\n * onDegraded: () => {\n * console.log('Service is degraded');\n * },\n * });\n * }\n *\n * async fetch() {\n * return await this.#policy.execute(async () => {\n * const response = await fetch('https://some/url');\n * return await response.json();\n * });\n * }\n * }\n * ```\n */\nexport function createServicePolicy(\n options: CreateServicePolicyOptions = {},\n): ServicePolicy {\n const {\n maxRetries = DEFAULT_MAX_RETRIES,\n retryFilterPolicy = handleAll,\n maxConsecutiveFailures = DEFAULT_MAX_CONSECUTIVE_FAILURES,\n circuitBreakDuration = DEFAULT_CIRCUIT_BREAK_DURATION,\n degradedThreshold = DEFAULT_DEGRADED_THRESHOLD,\n backoff = new ExponentialBackoff(),\n } = options;\n\n let availabilityStatus: AvailabilityStatus = AVAILABILITY_STATUSES.Unknown;\n\n const retryPolicy = retry(retryFilterPolicy, {\n // Note that although the option here is called \"max attempts\", it's really\n // maximum number of *retries* (attempts past the initial attempt).\n maxAttempts: maxRetries,\n // Retries of the service will be executed following ever increasing delays,\n // determined by a backoff formula.\n backoff,\n });\n const onRetry = retryPolicy.onRetry.bind(retryPolicy);\n\n const consecutiveBreaker = new ConsecutiveBreaker(maxConsecutiveFailures);\n const circuitBreakerPolicy = circuitBreaker(handleWhen(isServiceFailure), {\n // While the circuit is open, any additional invocations of the service\n // passed to the policy (either via automatic retries or by manually\n // executing the policy again) will result in a BrokenCircuitError. This\n // will remain the case until `circuitBreakDuration` passes, after which the\n // service will be allowed to run again. If the service succeeds, the\n // circuit will close, otherwise it will remain open.\n halfOpenAfter: circuitBreakDuration,\n breaker: consecutiveBreaker,\n });\n\n let internalCircuitState: InternalCircuitState = getInternalCircuitState(\n circuitBreakerPolicy.state,\n );\n circuitBreakerPolicy.onStateChange((state) => {\n internalCircuitState = getInternalCircuitState(state);\n });\n\n circuitBreakerPolicy.onBreak(() => {\n availabilityStatus = AVAILABILITY_STATUSES.Unavailable;\n });\n const onBreak = circuitBreakerPolicy.onBreak.bind(circuitBreakerPolicy);\n\n const onDegradedEventEmitter =\n new CockatielEventEmitter<FailureReason<unknown> | void>();\n const onDegraded = onDegradedEventEmitter.addListener;\n\n const onAvailableEventEmitter = new CockatielEventEmitter<void>();\n const onAvailable = onAvailableEventEmitter.addListener;\n\n retryPolicy.onGiveUp((data) => {\n if (circuitBreakerPolicy.state === CircuitState.Closed) {\n availabilityStatus = AVAILABILITY_STATUSES.Degraded;\n onDegradedEventEmitter.emit(data);\n }\n });\n retryPolicy.onSuccess(({ duration }) => {\n if (circuitBreakerPolicy.state === CircuitState.Closed) {\n if (duration > degradedThreshold) {\n availabilityStatus = AVAILABILITY_STATUSES.Degraded;\n onDegradedEventEmitter.emit();\n } else if (availabilityStatus !== AVAILABILITY_STATUSES.Available) {\n availabilityStatus = AVAILABILITY_STATUSES.Available;\n onAvailableEventEmitter.emit();\n }\n }\n });\n\n // Every time the retry policy makes an attempt, it executes the circuit\n // breaker policy, which executes the service.\n //\n // Calling:\n //\n // policy.execute(() => {\n // // do what the service does\n // })\n //\n // is equivalent to:\n //\n // retryPolicy.execute(() => {\n // circuitBreakerPolicy.execute(() => {\n // // do what the service does\n // });\n // });\n //\n // So if the retry policy succeeds or fails, it is because the circuit breaker\n // policy succeeded or failed. And if there are any event listeners registered\n // on the retry policy, by the time they are called, the state of the circuit\n // breaker will have already changed.\n const policy = wrap(retryPolicy, circuitBreakerPolicy);\n\n const getRemainingCircuitOpenDuration = () => {\n if (internalCircuitState.state === CircuitState.Open) {\n return internalCircuitState.openedAt + circuitBreakDuration - Date.now();\n }\n return null;\n };\n\n const getCircuitState = () => {\n return circuitBreakerPolicy.state;\n };\n\n const reset = () => {\n // Set the state of the policy to \"isolated\" regardless of its current state\n const { dispose } = circuitBreakerPolicy.isolate();\n // Reset the state to \"closed\"\n dispose();\n\n // Reset the counter on the breaker as well\n consecutiveBreaker.success();\n\n // Re-initialize the availability status so that if the service is executed\n // successfully, onAvailable listeners will be called again\n availabilityStatus = AVAILABILITY_STATUSES.Unknown;\n };\n\n return {\n ...policy,\n circuitBreakerPolicy,\n circuitBreakDuration,\n getCircuitState,\n getRemainingCircuitOpenDuration,\n reset,\n retryPolicy,\n onBreak,\n onDegraded,\n onAvailable,\n onRetry,\n };\n}\n"]}
1
+ {"version":3,"file":"create-service-policy.cjs","sourceRoot":"","sources":["../src/create-service-policy.ts"],"names":[],"mappings":";;;AAAA,yCAYmB;AAYjB,mGAvBA,8BAAkB,OAuBA;AAClB,6FAvBA,wBAAY,OAuBA;AAEZ,mGAtBA,8BAAkB,OAsBA;AADlB,gGApBA,2BAAe,OAoBA;AAEf,0FApBA,qBAAS,OAoBA;AACT,2FApBA,sBAAU,OAoBA;AAoGZ;;;GAGG;AACU,QAAA,mBAAmB,GAAG,CAAC,CAAC;AAErC;;;;;GAKG;AACU,QAAA,gCAAgC,GAAG,CAAC,CAAC,GAAG,2BAAmB,CAAC,GAAG,CAAC,CAAC;AAE9E;;;GAGG;AACU,QAAA,8BAA8B,GAAG,EAAE,GAAG,EAAE,GAAG,IAAI,CAAC;AAE7D;;;GAGG;AACU,QAAA,0BAA0B,GAAG,IAAK,CAAC;AAEhD,MAAM,gBAAgB,GAAG,CAAC,KAAc,EAAE,EAAE;IAC1C,IACE,OAAO,KAAK,KAAK,QAAQ;QACzB,KAAK,KAAK,IAAI;QACd,YAAY,IAAI,KAAK;QACrB,OAAO,KAAK,CAAC,UAAU,KAAK,QAAQ,EACpC,CAAC;QACD,OAAO,KAAK,CAAC,UAAU,IAAI,GAAG,CAAC;IACjC,CAAC;IAED,0EAA0E;IAC1E,uEAAuE;IACvE,OAAO,IAAI,CAAC;AACd,CAAC,CAA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":["import {\n BrokenCircuitError,\n CircuitState,\n EventEmitter as CockatielEventEmitter,\n ConsecutiveBreaker,\n ExponentialBackoff,\n ConstantBackoff,\n circuitBreaker,\n handleAll,\n handleWhen,\n retry,\n wrap,\n} from 'cockatiel';\nimport type {\n CircuitBreakerPolicy,\n Event as CockatielEvent,\n FailureReason,\n IBackoffFactory,\n IPolicy,\n Policy,\n RetryPolicy,\n} from 'cockatiel';\n\nexport {\n BrokenCircuitError,\n CircuitState,\n ConstantBackoff,\n ExponentialBackoff,\n handleAll,\n handleWhen,\n};\n\nexport type { CockatielEvent };\n\n/**\n * The options for `createServicePolicy`.\n */\nexport type CreateServicePolicyOptions = {\n /**\n * The backoff strategy to use. Mainly useful for testing so that a constant\n * backoff can be used when mocking timers. Defaults to an instance of\n * ExponentialBackoff.\n */\n backoff?: IBackoffFactory<unknown>;\n /**\n * The length of time (in milliseconds) to pause retries of the action after\n * the number of failures reaches `maxConsecutiveFailures`.\n */\n circuitBreakDuration?: number;\n /**\n * The length of time (in milliseconds) that governs when the service is\n * regarded as degraded (affecting when `onDegraded` is called).\n */\n degradedThreshold?: number;\n /**\n * The maximum number of times that the service is allowed to fail before\n * pausing further retries.\n */\n maxConsecutiveFailures?: number;\n /**\n * The maximum number of times that a failing service should be re-invoked\n * before giving up.\n */\n maxRetries?: number;\n /**\n * The policy used to control when the service should be retried based on\n * either the result of the service or an error that it throws. For instance,\n * you could use this to retry only certain errors. See `handleWhen` and\n * friends from Cockatiel for more.\n */\n retryFilterPolicy?: Policy;\n};\n\n/**\n * The service policy object.\n */\nexport type ServicePolicy = IPolicy & {\n /**\n * The Cockatiel circuit breaker policy that the service policy uses\n * internally.\n */\n circuitBreakerPolicy: CircuitBreakerPolicy;\n /**\n * The amount of time to pause requests to the service if the number of\n * maximum consecutive failures is reached.\n */\n circuitBreakDuration: number;\n /**\n * If the circuit is open and ongoing requests are paused, returns the number\n * of milliseconds before the requests will be attempted again. If the circuit\n * is not open, returns null.\n */\n getRemainingCircuitOpenDuration: () => number | null;\n /**\n * The Cockatiel retry policy that the service policy uses internally.\n */\n retryPolicy: RetryPolicy;\n /**\n * A function which is called when the number of times that the service fails\n * in a row meets the set maximum number of consecutive failures.\n */\n onBreak: CircuitBreakerPolicy['onBreak'];\n /**\n * A function which is called in two circumstances: 1) when the service\n * succeeds before the maximum number of consecutive failures is reached, but\n * takes more time than the `degradedThreshold` to run, or 2) if the service\n * never succeeds before the retry policy gives up and before the maximum\n * number of consecutive failures has been reached.\n */\n onDegraded: CockatielEvent<FailureReason<unknown> | void>;\n /**\n * A function which will be called by the retry policy each time the service\n * fails and the policy kicks off a timer to re-run the service. This is\n * primarily useful in tests where we are mocking timers.\n */\n onRetry: RetryPolicy['onRetry'];\n};\n\n/**\n * Parts of the circuit breaker's internal and external state as necessary in\n * order to compute the time remaining before the circuit will reopen.\n */\ntype InternalCircuitState =\n | {\n state: CircuitState.Open;\n openedAt: number;\n }\n | { state: Exclude<CircuitState, CircuitState.Open> };\n\n/**\n * The maximum number of times that a failing service should be re-run before\n * giving up.\n */\nexport const DEFAULT_MAX_RETRIES = 3;\n\n/**\n * The maximum number of times that the service is allowed to fail before\n * pausing further retries. This is set to a value such that if given a\n * service that continually fails, the policy needs to be executed 3 times\n * before further retries are paused.\n */\nexport const DEFAULT_MAX_CONSECUTIVE_FAILURES = (1 + DEFAULT_MAX_RETRIES) * 3;\n\n/**\n * The default length of time (in milliseconds) to temporarily pause retries of\n * the service after enough consecutive failures.\n */\nexport const DEFAULT_CIRCUIT_BREAK_DURATION = 30 * 60 * 1000;\n\n/**\n * The default length of time (in milliseconds) that governs when the service is\n * regarded as degraded (affecting when `onDegraded` is called).\n */\nexport const DEFAULT_DEGRADED_THRESHOLD = 5_000;\n\nconst isServiceFailure = (error: unknown) => {\n if (\n typeof error === 'object' &&\n error !== null &&\n 'httpStatus' in error &&\n typeof error.httpStatus === 'number'\n ) {\n return error.httpStatus >= 500;\n }\n\n // If the error is not an object, or doesn't have a numeric code property,\n // consider it a service failure (e.g., network errors, timeouts, etc.)\n return true;\n};\n\n/**\n * The circuit breaker policy inside of the Cockatiel library exposes some of\n * its state, but not all of it. Notably, the time that the circuit opened is\n * not publicly accessible. So we have to record this ourselves.\n *\n * This function therefore allows us to obtain the circuit breaker state that we\n * wish we could access.\n *\n * @param state - The public state of a circuit breaker policy.\n * @returns if the circuit is open, the state of the circuit breaker policy plus\n * the time that it opened, otherwise just the circuit state.\n */\nfunction getInternalCircuitState(state: CircuitState): InternalCircuitState {\n if (state === CircuitState.Open) {\n return { state, openedAt: Date.now() };\n }\n return { state };\n}\n\n/**\n * Constructs an object exposing an `execute` method which, given a function —\n * hereafter called the \"service\" — will retry that service with ever increasing\n * delays until it succeeds. If the policy detects too many consecutive\n * failures, it will block further retries until a designated time period has\n * passed; this particular behavior is primarily designed for services that wrap\n * API calls so as not to make needless HTTP requests when the API is down and\n * to be able to recover when the API comes back up. In addition, hooks allow\n * for responding to certain events, one of which can be used to detect when an\n * HTTP request is performing slowly.\n *\n * Internally, this function makes use of the retry and circuit breaker policies\n * from the [Cockatiel](https://www.npmjs.com/package/cockatiel) library; see\n * there for more.\n *\n * @param options - The options to this function. See\n * {@link CreateServicePolicyOptions}.\n * @returns The service policy.\n * @example\n * This function is designed to be used in the context of a service class like\n * this:\n * ``` ts\n * class Service {\n * constructor() {\n * this.#policy = createServicePolicy({\n * maxRetries: 3,\n * retryFilterPolicy: handleWhen((error) => {\n * return error.message.includes('oops');\n * }),\n * maxConsecutiveFailures: 3,\n * circuitBreakDuration: 5000,\n * degradedThreshold: 2000,\n * onBreak: () => {\n * console.log('Circuit broke');\n * },\n * onDegraded: () => {\n * console.log('Service is degraded');\n * },\n * });\n * }\n *\n * async fetch() {\n * return await this.#policy.execute(async () => {\n * const response = await fetch('https://some/url');\n * return await response.json();\n * });\n * }\n * }\n * ```\n */\nexport function createServicePolicy(\n options: CreateServicePolicyOptions = {},\n): ServicePolicy {\n const {\n maxRetries = DEFAULT_MAX_RETRIES,\n retryFilterPolicy = handleAll,\n maxConsecutiveFailures = DEFAULT_MAX_CONSECUTIVE_FAILURES,\n circuitBreakDuration = DEFAULT_CIRCUIT_BREAK_DURATION,\n degradedThreshold = DEFAULT_DEGRADED_THRESHOLD,\n backoff = new ExponentialBackoff(),\n } = options;\n\n const retryPolicy = retry(retryFilterPolicy, {\n // Note that although the option here is called \"max attempts\", it's really\n // maximum number of *retries* (attempts past the initial attempt).\n maxAttempts: maxRetries,\n // Retries of the service will be executed following ever increasing delays,\n // determined by a backoff formula.\n backoff,\n });\n const onRetry = retryPolicy.onRetry.bind(retryPolicy);\n\n const circuitBreakerPolicy = circuitBreaker(handleWhen(isServiceFailure), {\n // While the circuit is open, any additional invocations of the service\n // passed to the policy (either via automatic retries or by manually\n // executing the policy again) will result in a BrokenCircuitError. This\n // will remain the case until `circuitBreakDuration` passes, after which the\n // service will be allowed to run again. If the service succeeds, the\n // circuit will close, otherwise it will remain open.\n halfOpenAfter: circuitBreakDuration,\n breaker: new ConsecutiveBreaker(maxConsecutiveFailures),\n });\n\n let internalCircuitState: InternalCircuitState = getInternalCircuitState(\n circuitBreakerPolicy.state,\n );\n circuitBreakerPolicy.onStateChange((state) => {\n internalCircuitState = getInternalCircuitState(state);\n });\n const onBreak = circuitBreakerPolicy.onBreak.bind(circuitBreakerPolicy);\n\n const onDegradedEventEmitter =\n new CockatielEventEmitter<FailureReason<unknown> | void>();\n retryPolicy.onGiveUp((data) => {\n if (circuitBreakerPolicy.state === CircuitState.Closed) {\n onDegradedEventEmitter.emit(data);\n }\n });\n retryPolicy.onSuccess(({ duration }) => {\n if (\n circuitBreakerPolicy.state === CircuitState.Closed &&\n duration > degradedThreshold\n ) {\n onDegradedEventEmitter.emit();\n }\n });\n const onDegraded = onDegradedEventEmitter.addListener;\n\n // Every time the retry policy makes an attempt, it executes the circuit\n // breaker policy, which executes the service.\n const policy = wrap(retryPolicy, circuitBreakerPolicy);\n\n const getRemainingCircuitOpenDuration = () => {\n if (internalCircuitState.state === CircuitState.Open) {\n return internalCircuitState.openedAt + circuitBreakDuration - Date.now();\n }\n return null;\n };\n\n return {\n ...policy,\n circuitBreakerPolicy,\n circuitBreakDuration,\n getRemainingCircuitOpenDuration,\n retryPolicy,\n onBreak,\n onDegraded,\n onRetry,\n };\n}\n"]}
@@ -1,7 +1,7 @@
1
- import { BrokenCircuitError, CircuitState, EventEmitter as CockatielEventEmitter, ExponentialBackoff, ConstantBackoff, handleAll, handleWhen } from "cockatiel";
1
+ import { BrokenCircuitError, CircuitState, ExponentialBackoff, ConstantBackoff, handleAll, handleWhen } from "cockatiel";
2
2
  import type { CircuitBreakerPolicy, Event as CockatielEvent, FailureReason, IBackoffFactory, IPolicy, Policy, RetryPolicy } from "cockatiel";
3
- export { BrokenCircuitError, CockatielEventEmitter, CircuitState, ConstantBackoff, ExponentialBackoff, handleAll, handleWhen, };
4
- export type { CockatielEvent, FailureReason as CockatielFailureReason };
3
+ export { BrokenCircuitError, CircuitState, ConstantBackoff, ExponentialBackoff, handleAll, handleWhen, };
4
+ export type { CockatielEvent };
5
5
  /**
6
6
  * The options for `createServicePolicy`.
7
7
  */
@@ -54,21 +54,12 @@ export type ServicePolicy = IPolicy & {
54
54
  * maximum consecutive failures is reached.
55
55
  */
56
56
  circuitBreakDuration: number;
57
- /**
58
- * @returns The state of the underlying circuit.
59
- */
60
- getCircuitState: () => CircuitState;
61
57
  /**
62
58
  * If the circuit is open and ongoing requests are paused, returns the number
63
59
  * of milliseconds before the requests will be attempted again. If the circuit
64
60
  * is not open, returns null.
65
61
  */
66
62
  getRemainingCircuitOpenDuration: () => number | null;
67
- /**
68
- * Resets the internal circuit breaker policy (if it is open, it will now be
69
- * closed).
70
- */
71
- reset: () => void;
72
63
  /**
73
64
  * The Cockatiel retry policy that the service policy uses internally.
74
65
  */
@@ -86,12 +77,6 @@ export type ServicePolicy = IPolicy & {
86
77
  * number of consecutive failures has been reached.
87
78
  */
88
79
  onDegraded: CockatielEvent<FailureReason<unknown> | void>;
89
- /**
90
- * A function which is called when the service succeeds for the first time,
91
- * or when the service fails enough times to cause the circuit to break and
92
- * then recovers.
93
- */
94
- onAvailable: CockatielEvent<void>;
95
80
  /**
96
81
  * A function which will be called by the retry policy each time the service
97
82
  * fails and the policy kicks off a timer to re-run the service. This is
@@ -1 +1 @@
1
- {"version":3,"file":"create-service-policy.d.cts","sourceRoot":"","sources":["../src/create-service-policy.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,kBAAkB,EAClB,YAAY,EACZ,YAAY,IAAI,qBAAqB,EAErC,kBAAkB,EAClB,eAAe,EAEf,SAAS,EACT,UAAU,EAGX,kBAAkB;AACnB,OAAO,KAAK,EACV,oBAAoB,EACpB,KAAK,IAAI,cAAc,EACvB,aAAa,EACb,eAAe,EACf,OAAO,EACP,MAAM,EACN,WAAW,EACZ,kBAAkB;AAEnB,OAAO,EACL,kBAAkB,EAClB,qBAAqB,EACrB,YAAY,EACZ,eAAe,EACf,kBAAkB,EAClB,SAAS,EACT,UAAU,GACX,CAAC;AAEF,YAAY,EAAE,cAAc,EAAE,aAAa,IAAI,sBAAsB,EAAE,CAAC;AAExE;;GAEG;AACH,MAAM,MAAM,0BAA0B,GAAG;IACvC;;;;OAIG;IACH,OAAO,CAAC,EAAE,eAAe,CAAC,OAAO,CAAC,CAAC;IACnC;;;OAGG;IACH,oBAAoB,CAAC,EAAE,MAAM,CAAC;IAC9B;;;OAGG;IACH,iBAAiB,CAAC,EAAE,MAAM,CAAC;IAC3B;;;OAGG;IACH,sBAAsB,CAAC,EAAE,MAAM,CAAC;IAChC;;;OAGG;IACH,UAAU,CAAC,EAAE,MAAM,CAAC;IACpB;;;;;OAKG;IACH,iBAAiB,CAAC,EAAE,MAAM,CAAC;CAC5B,CAAC;AAEF;;GAEG;AACH,MAAM,MAAM,aAAa,GAAG,OAAO,GAAG;IACpC;;;OAGG;IACH,oBAAoB,EAAE,oBAAoB,CAAC;IAC3C;;;OAGG;IACH,oBAAoB,EAAE,MAAM,CAAC;IAC7B;;OAEG;IACH,eAAe,EAAE,MAAM,YAAY,CAAC;IACpC;;;;OAIG;IACH,+BAA+B,EAAE,MAAM,MAAM,GAAG,IAAI,CAAC;IACrD;;;OAGG;IACH,KAAK,EAAE,MAAM,IAAI,CAAC;IAClB;;OAEG;IACH,WAAW,EAAE,WAAW,CAAC;IACzB;;;OAGG;IACH,OAAO,EAAE,oBAAoB,CAAC,SAAS,CAAC,CAAC;IACzC;;;;;;OAMG;IACH,UAAU,EAAE,cAAc,CAAC,aAAa,CAAC,OAAO,CAAC,GAAG,IAAI,CAAC,CAAC;IAC1D;;;;OAIG;IACH,WAAW,EAAE,cAAc,CAAC,IAAI,CAAC,CAAC;IAClC;;;;OAIG;IACH,OAAO,EAAE,WAAW,CAAC,SAAS,CAAC,CAAC;CACjC,CAAC;AAiCF;;;GAGG;AACH,eAAO,MAAM,mBAAmB,IAAI,CAAC;AAErC;;;;;GAKG;AACH,eAAO,MAAM,gCAAgC,QAAgC,CAAC;AAE9E;;;GAGG;AACH,eAAO,MAAM,8BAA8B,QAAiB,CAAC;AAE7D;;;GAGG;AACH,eAAO,MAAM,0BAA0B,OAAQ,CAAC;AAoChD;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAiDG;AACH,wBAAgB,mBAAmB,CACjC,OAAO,GAAE,0BAA+B,GACvC,aAAa,CAoIf"}
1
+ {"version":3,"file":"create-service-policy.d.cts","sourceRoot":"","sources":["../src/create-service-policy.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,kBAAkB,EAClB,YAAY,EAGZ,kBAAkB,EAClB,eAAe,EAEf,SAAS,EACT,UAAU,EAGX,kBAAkB;AACnB,OAAO,KAAK,EACV,oBAAoB,EACpB,KAAK,IAAI,cAAc,EACvB,aAAa,EACb,eAAe,EACf,OAAO,EACP,MAAM,EACN,WAAW,EACZ,kBAAkB;AAEnB,OAAO,EACL,kBAAkB,EAClB,YAAY,EACZ,eAAe,EACf,kBAAkB,EAClB,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AACH,wBAAgB,mBAAmB,CACjC,OAAO,GAAE,0BAA+B,GACvC,aAAa,CA6Ef"}
@@ -1,7 +1,7 @@
1
- import { BrokenCircuitError, CircuitState, EventEmitter as CockatielEventEmitter, ExponentialBackoff, ConstantBackoff, handleAll, handleWhen } from "cockatiel";
1
+ import { BrokenCircuitError, CircuitState, ExponentialBackoff, ConstantBackoff, handleAll, handleWhen } from "cockatiel";
2
2
  import type { CircuitBreakerPolicy, Event as CockatielEvent, FailureReason, IBackoffFactory, IPolicy, Policy, RetryPolicy } from "cockatiel";
3
- export { BrokenCircuitError, CockatielEventEmitter, CircuitState, ConstantBackoff, ExponentialBackoff, handleAll, handleWhen, };
4
- export type { CockatielEvent, FailureReason as CockatielFailureReason };
3
+ export { BrokenCircuitError, CircuitState, ConstantBackoff, ExponentialBackoff, handleAll, handleWhen, };
4
+ export type { CockatielEvent };
5
5
  /**
6
6
  * The options for `createServicePolicy`.
7
7
  */
@@ -54,21 +54,12 @@ export type ServicePolicy = IPolicy & {
54
54
  * maximum consecutive failures is reached.
55
55
  */
56
56
  circuitBreakDuration: number;
57
- /**
58
- * @returns The state of the underlying circuit.
59
- */
60
- getCircuitState: () => CircuitState;
61
57
  /**
62
58
  * If the circuit is open and ongoing requests are paused, returns the number
63
59
  * of milliseconds before the requests will be attempted again. If the circuit
64
60
  * is not open, returns null.
65
61
  */
66
62
  getRemainingCircuitOpenDuration: () => number | null;
67
- /**
68
- * Resets the internal circuit breaker policy (if it is open, it will now be
69
- * closed).
70
- */
71
- reset: () => void;
72
63
  /**
73
64
  * The Cockatiel retry policy that the service policy uses internally.
74
65
  */
@@ -86,12 +77,6 @@ export type ServicePolicy = IPolicy & {
86
77
  * number of consecutive failures has been reached.
87
78
  */
88
79
  onDegraded: CockatielEvent<FailureReason<unknown> | void>;
89
- /**
90
- * A function which is called when the service succeeds for the first time,
91
- * or when the service fails enough times to cause the circuit to break and
92
- * then recovers.
93
- */
94
- onAvailable: CockatielEvent<void>;
95
80
  /**
96
81
  * A function which will be called by the retry policy each time the service
97
82
  * fails and the policy kicks off a timer to re-run the service. This is
@@ -1 +1 @@
1
- {"version":3,"file":"create-service-policy.d.mts","sourceRoot":"","sources":["../src/create-service-policy.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,kBAAkB,EAClB,YAAY,EACZ,YAAY,IAAI,qBAAqB,EAErC,kBAAkB,EAClB,eAAe,EAEf,SAAS,EACT,UAAU,EAGX,kBAAkB;AACnB,OAAO,KAAK,EACV,oBAAoB,EACpB,KAAK,IAAI,cAAc,EACvB,aAAa,EACb,eAAe,EACf,OAAO,EACP,MAAM,EACN,WAAW,EACZ,kBAAkB;AAEnB,OAAO,EACL,kBAAkB,EAClB,qBAAqB,EACrB,YAAY,EACZ,eAAe,EACf,kBAAkB,EAClB,SAAS,EACT,UAAU,GACX,CAAC;AAEF,YAAY,EAAE,cAAc,EAAE,aAAa,IAAI,sBAAsB,EAAE,CAAC;AAExE;;GAEG;AACH,MAAM,MAAM,0BAA0B,GAAG;IACvC;;;;OAIG;IACH,OAAO,CAAC,EAAE,eAAe,CAAC,OAAO,CAAC,CAAC;IACnC;;;OAGG;IACH,oBAAoB,CAAC,EAAE,MAAM,CAAC;IAC9B;;;OAGG;IACH,iBAAiB,CAAC,EAAE,MAAM,CAAC;IAC3B;;;OAGG;IACH,sBAAsB,CAAC,EAAE,MAAM,CAAC;IAChC;;;OAGG;IACH,UAAU,CAAC,EAAE,MAAM,CAAC;IACpB;;;;;OAKG;IACH,iBAAiB,CAAC,EAAE,MAAM,CAAC;CAC5B,CAAC;AAEF;;GAEG;AACH,MAAM,MAAM,aAAa,GAAG,OAAO,GAAG;IACpC;;;OAGG;IACH,oBAAoB,EAAE,oBAAoB,CAAC;IAC3C;;;OAGG;IACH,oBAAoB,EAAE,MAAM,CAAC;IAC7B;;OAEG;IACH,eAAe,EAAE,MAAM,YAAY,CAAC;IACpC;;;;OAIG;IACH,+BAA+B,EAAE,MAAM,MAAM,GAAG,IAAI,CAAC;IACrD;;;OAGG;IACH,KAAK,EAAE,MAAM,IAAI,CAAC;IAClB;;OAEG;IACH,WAAW,EAAE,WAAW,CAAC;IACzB;;;OAGG;IACH,OAAO,EAAE,oBAAoB,CAAC,SAAS,CAAC,CAAC;IACzC;;;;;;OAMG;IACH,UAAU,EAAE,cAAc,CAAC,aAAa,CAAC,OAAO,CAAC,GAAG,IAAI,CAAC,CAAC;IAC1D;;;;OAIG;IACH,WAAW,EAAE,cAAc,CAAC,IAAI,CAAC,CAAC;IAClC;;;;OAIG;IACH,OAAO,EAAE,WAAW,CAAC,SAAS,CAAC,CAAC;CACjC,CAAC;AAiCF;;;GAGG;AACH,eAAO,MAAM,mBAAmB,IAAI,CAAC;AAErC;;;;;GAKG;AACH,eAAO,MAAM,gCAAgC,QAAgC,CAAC;AAE9E;;;GAGG;AACH,eAAO,MAAM,8BAA8B,QAAiB,CAAC;AAE7D;;;GAGG;AACH,eAAO,MAAM,0BAA0B,OAAQ,CAAC;AAoChD;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAiDG;AACH,wBAAgB,mBAAmB,CACjC,OAAO,GAAE,0BAA+B,GACvC,aAAa,CAoIf"}
1
+ {"version":3,"file":"create-service-policy.d.mts","sourceRoot":"","sources":["../src/create-service-policy.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,kBAAkB,EAClB,YAAY,EAGZ,kBAAkB,EAClB,eAAe,EAEf,SAAS,EACT,UAAU,EAGX,kBAAkB;AACnB,OAAO,KAAK,EACV,oBAAoB,EACpB,KAAK,IAAI,cAAc,EACvB,aAAa,EACb,eAAe,EACf,OAAO,EACP,MAAM,EACN,WAAW,EACZ,kBAAkB;AAEnB,OAAO,EACL,kBAAkB,EAClB,YAAY,EACZ,eAAe,EACf,kBAAkB,EAClB,SAAS,EACT,UAAU,GACX,CAAC;AAEF,YAAY,EAAE,cAAc,EAAE,CAAC;AAE/B;;GAEG;AACH,MAAM,MAAM,0BAA0B,GAAG;I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CircuitState, EventEmitter as CockatielEventEmitter, ConsecutiveBreaker, ExponentialBackoff, ConstantBackoff, circuitBreaker, handleAll, handleWhen, retry, wrap } from "cockatiel";
2
- export { BrokenCircuitError, CockatielEventEmitter, CircuitState, ConstantBackoff, ExponentialBackoff, handleAll, handleWhen };
3
- /**
4
- * Availability statuses that the service can be in.
5
- *
6
- * Used to keep track of whether the `onAvailable` event should be fired.
7
- */
8
- const AVAILABILITY_STATUSES = {
9
- Available: 'available',
10
- Degraded: 'degraded',
11
- Unavailable: 'unavailable',
12
- Unknown: 'unknown',
13
- };
2
+ export { BrokenCircuitError, CircuitState, ConstantBackoff, ExponentialBackoff, handleAll, handleWhen };
14
3
  /**
15
4
  * The maximum number of times that a failing service should be re-run before
16
5
  * giving up.
@@ -114,7 +103,6 @@ function getInternalCircuitState(state) {
114
103
  */
115
104
  export function createServicePolicy(options = {}) {
116
105
  const { maxRetries = DEFAULT_MAX_RETRIES, retryFilterPolicy = handleAll, maxConsecutiveFailures = DEFAULT_MAX_CONSECUTIVE_FAILURES, circuitBreakDuration = DEFAULT_CIRCUIT_BREAK_DURATION, degradedThreshold = DEFAULT_DEGRADED_THRESHOLD, backoff = new ExponentialBackoff(), } = options;
117
- let availabilityStatus = AVAILABILITY_STATUSES.Unknown;
118
106
  const retryPolicy = retry(retryFilterPolicy, {
119
107
  // Note that although the option here is called "max attempts", it's really
120
108
  // maximum number of *retries* (attempts past the initial attempt).
@@ -124,7 +112,6 @@ export function createServicePolicy(options = {}) {
124
112
  backoff,
125
113
  });
126
114
  const onRetry = retryPolicy.onRetry.bind(retryPolicy);
127
- const consecutiveBreaker = new ConsecutiveBreaker(maxConsecutiveFailures);
128
115
  const circuitBreakerPolicy = circuitBreaker(handleWhen(isServiceFailure), {
129
116
  // While the circuit is open, any additional invocations of the service
130
117
  // passed to the policy (either via automatic retries or by manually
@@ -133,59 +120,28 @@ export function createServicePolicy(options = {}) {
133
120
  // service will be allowed to run again. If the service succeeds, the
134
121
  // circuit will close, otherwise it will remain open.
135
122
  halfOpenAfter: circuitBreakDuration,
136
- breaker: consecutiveBreaker,
123
+ breaker: new ConsecutiveBreaker(maxConsecutiveFailures),
137
124
  });
138
125
  let internalCircuitState = getInternalCircuitState(circuitBreakerPolicy.state);
139
126
  circuitBreakerPolicy.onStateChange((state) => {
140
127
  internalCircuitState = getInternalCircuitState(state);
141
128
  });
142
- circuitBreakerPolicy.onBreak(() => {
143
- availabilityStatus = AVAILABILITY_STATUSES.Unavailable;
144
- });
145
129
  const onBreak = circuitBreakerPolicy.onBreak.bind(circuitBreakerPolicy);
146
130
  const onDegradedEventEmitter = new CockatielEventEmitter();
147
- const onDegraded = onDegradedEventEmitter.addListener;
148
- const onAvailableEventEmitter = new CockatielEventEmitter();
149
- const onAvailable = onAvailableEventEmitter.addListener;
150
131
  retryPolicy.onGiveUp((data) => {
151
132
  if (circuitBreakerPolicy.state === CircuitState.Closed) {
152
- availabilityStatus = AVAILABILITY_STATUSES.Degraded;
153
133
  onDegradedEventEmitter.emit(data);
154
134
  }
155
135
  });
156
136
  retryPolicy.onSuccess(({ duration }) => {
157
- if (circuitBreakerPolicy.state === CircuitState.Closed) {
158
- if (duration > degradedThreshold) {
159
- availabilityStatus = AVAILABILITY_STATUSES.Degraded;
160
- onDegradedEventEmitter.emit();
161
- }
162
- else if (availabilityStatus !== AVAILABILITY_STATUSES.Available) {
163
- availabilityStatus = AVAILABILITY_STATUSES.Available;
164
- onAvailableEventEmitter.emit();
165
- }
137
+ if (circuitBreakerPolicy.state === CircuitState.Closed &&
138
+ duration > degradedThreshold) {
139
+ onDegradedEventEmitter.emit();
166
140
  }
167
141
  });
142
+ const onDegraded = onDegradedEventEmitter.addListener;
168
143
  // Every time the retry policy makes an attempt, it executes the circuit
169
144
  // breaker policy, which executes the service.
170
- //
171
- // Calling:
172
- //
173
- // policy.execute(() => {
174
- // // do what the service does
175
- // })
176
- //
177
- // is equivalent to:
178
- //
179
- // retryPolicy.execute(() => {
180
- // circuitBreakerPolicy.execute(() => {
181
- // // do what the service does
182
- // });
183
- // });
184
- //
185
- // So if the retry policy succeeds or fails, it is because the circuit breaker
186
- // policy succeeded or failed. And if there are any event listeners registered
187
- // on the retry policy, by the time they are called, the state of the circuit
188
- // breaker will have already changed.
189
145
  const policy = wrap(retryPolicy, circuitBreakerPolicy);
190
146
  const getRemainingCircuitOpenDuration = () => {
191
147
  if (internalCircuitState.state === CircuitState.Open) {
@@ -193,31 +149,14 @@ export function createServicePolicy(options = {}) {
193
149
  }
194
150
  return null;
195
151
  };
196
- const getCircuitState = () => {
197
- return circuitBreakerPolicy.state;
198
- };
199
- const reset = () => {
200
- // Set the state of the policy to "isolated" regardless of its current state
201
- const { dispose } = circuitBreakerPolicy.isolate();
202
- // Reset the state to "closed"
203
- dispose();
204
- // Reset the counter on the breaker as well
205
- consecutiveBreaker.success();
206
- // Re-initialize the availability status so that if the service is executed
207
- // successfully, onAvailable listeners will be called again
208
- availabilityStatus = AVAILABILITY_STATUSES.Unknown;
209
- };
210
152
  return {
211
153
  ...policy,
212
154
  circuitBreakerPolicy,
213
155
  circuitBreakDuration,
214
- getCircuitState,
215
156
  getRemainingCircuitOpenDuration,
216
- reset,
217
157
  retryPolicy,
218
158
  onBreak,
219
159
  onDegraded,
220
- onAvailable,
221
160
  onRetry,
222
161
  };
223
162
  }
@@ -1 +1 @@
1
- {"version":3,"file":"create-service-policy.mjs","sourceRoot":"","sources":["../src/create-service-policy.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,kBAAkB,EAClB,YAAY,EACZ,YAAY,IAAI,qBAAqB,EACrC,kBAAkB,EAClB,kBAAkB,EAClB,eAAe,EACf,cAAc,EACd,SAAS,EACT,UAAU,EACV,KAAK,EACL,IAAI,EACL,kBAAkB;AAWnB,OAAO,EACL,kBAAkB,EAClB,qBAAqB,EACrB,YAAY,EACZ,eAAe,EACf,kBAAkB,EAClB,SAAS,EACT,UAAU,EACX,CAAC;AAkHF;;;;GAIG;AACH,MAAM,qBAAqB,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AoB,CAAC,KAAK,KAAK,YAAY,CAAC,IAAI,EAAE,CAAC;YACrD,OAAO,oBAAoB,CAAC,QAAQ,GAAG,oBAAoB,GAAG,IAAI,CAAC,GAAG,EAAE,CAAC;QAC3E,CAAC;QACD,OAAO,IAAI,CAAC;IACd,CAAC,CAAC;IAEF,MAAM,eAAe,GAAG,GAAG,EAAE;QAC3B,OAAO,oBAAoB,CAAC,KAAK,CAAC;IACpC,CAAC,CAAC;IAEF,MAAM,KAAK,GAAG,GAAG,EAAE;QACjB,4EAA4E;QAC5E,MAAM,EAAE,OAAO,EAAE,GAAG,oBAAoB,CAAC,OAAO,EAAE,CAAC;QACnD,8BAA8B;QAC9B,OAAO,EAAE,CAAC;QAEV,2CAA2C;QAC3C,kBAAkB,CAAC,OAAO,EAAE,CAAC;QAE7B,2EAA2E;QAC3E,2DAA2D;QAC3D,kBAAkB,GAAG,qBAAqB,CAAC,OAAO,CAAC;IACrD,CAAC,CAAC;IAEF,OAAO;QACL,GAAG,MAAM;QACT,oBAAoB;QACpB,oBAAoB;QACpB,eAAe;QACf,+BAA+B;QAC/B,KAAK;QACL,WAAW;QACX,OAAO;QACP,UAAU;QACV,WAAW;QACX,OAAO;KACR,CAAC;AACJ,CAAC","sourcesContent":["import {\n BrokenCircuitError,\n CircuitState,\n EventEmitter as CockatielEventEmitter,\n ConsecutiveBreaker,\n ExponentialBackoff,\n ConstantBackoff,\n circuitBreaker,\n handleAll,\n handleWhen,\n retry,\n wrap,\n} from 'cockatiel';\nimport type {\n CircuitBreakerPolicy,\n Event as CockatielEvent,\n FailureReason,\n IBackoffFactory,\n IPolicy,\n Policy,\n RetryPolicy,\n} from 'cockatiel';\n\nexport {\n BrokenCircuitError,\n CockatielEventEmitter,\n CircuitState,\n ConstantBackoff,\n ExponentialBackoff,\n handleAll,\n handleWhen,\n};\n\nexport type { CockatielEvent, FailureReason as CockatielFailureReason };\n\n/**\n * The options for `createServicePolicy`.\n */\nexport type CreateServicePolicyOptions = {\n /**\n * The backoff strategy to use. Mainly useful for testing so that a constant\n * backoff can be used when mocking timers. Defaults to an instance of\n * ExponentialBackoff.\n */\n backoff?: IBackoffFactory<unknown>;\n /**\n * The length of time (in milliseconds) to pause retries of the action after\n * the number of failures reaches `maxConsecutiveFailures`.\n */\n circuitBreakDuration?: number;\n /**\n * The length of time (in milliseconds) that governs when the service is\n * regarded as degraded (affecting when `onDegraded` is called).\n */\n degradedThreshold?: number;\n /**\n * The maximum number of times that the service is allowed to fail before\n * pausing further retries.\n */\n maxConsecutiveFailures?: number;\n /**\n * The maximum number of times that a failing service should be re-invoked\n * before giving up.\n */\n maxRetries?: number;\n /**\n * The policy used to control when the service should be retried based on\n * either the result of the service or an error that it throws. For instance,\n * you could use this to retry only certain errors. See `handleWhen` and\n * friends from Cockatiel for more.\n */\n retryFilterPolicy?: Policy;\n};\n\n/**\n * The service policy object.\n */\nexport type ServicePolicy = IPolicy & {\n /**\n * The Cockatiel circuit breaker policy that the service policy uses\n * internally.\n */\n circuitBreakerPolicy: CircuitBreakerPolicy;\n /**\n * The amount of time to pause requests to the service if the number of\n * maximum consecutive failures is reached.\n */\n circuitBreakDuration: number;\n /**\n * @returns The state of the underlying circuit.\n */\n getCircuitState: () => CircuitState;\n /**\n * If the circuit is open and ongoing requests are paused, returns the number\n * of milliseconds before the requests will be attempted again. If the circuit\n * is not open, returns null.\n */\n getRemainingCircuitOpenDuration: () => number | null;\n /**\n * Resets the internal circuit breaker policy (if it is open, it will now be\n * closed).\n */\n reset: () => void;\n /**\n * The Cockatiel retry policy that the service policy uses internally.\n */\n retryPolicy: RetryPolicy;\n /**\n * A function which is called when the number of times that the service fails\n * in a row meets the set maximum number of consecutive failures.\n */\n onBreak: CircuitBreakerPolicy['onBreak'];\n /**\n * A function which is called in two circumstances: 1) when the service\n * succeeds before the maximum number of consecutive failures is reached, but\n * takes more time than the `degradedThreshold` to run, or 2) if the service\n * never succeeds before the retry policy gives up and before the maximum\n * number of consecutive failures has been reached.\n */\n onDegraded: CockatielEvent<FailureReason<unknown> | void>;\n /**\n * A function which is called when the service succeeds for the first time,\n * or when the service fails enough times to cause the circuit to break and\n * then recovers.\n */\n onAvailable: CockatielEvent<void>;\n /**\n * A function which will be called by the retry policy each time the service\n * fails and the policy kicks off a timer to re-run the service. This is\n * primarily useful in tests where we are mocking timers.\n */\n onRetry: RetryPolicy['onRetry'];\n};\n\n/**\n * Parts of the circuit breaker's internal and external state as necessary in\n * order to compute the time remaining before the circuit will reopen.\n */\ntype InternalCircuitState =\n | {\n state: CircuitState.Open;\n openedAt: number;\n }\n | { state: Exclude<CircuitState, CircuitState.Open> };\n\n/**\n * Availability statuses that the service can be in.\n *\n * Used to keep track of whether the `onAvailable` event should be fired.\n */\nconst AVAILABILITY_STATUSES = {\n Available: 'available',\n Degraded: 'degraded',\n Unavailable: 'unavailable',\n Unknown: 'unknown',\n} as const;\n\n/**\n * Availability statuses that the service can be in.\n *\n * Used to keep track of whether the `onAvailable` event should be fired.\n */\ntype AvailabilityStatus =\n (typeof AVAILABILITY_STATUSES)[keyof typeof AVAILABILITY_STATUSES];\n\n/**\n * The maximum number of times that a failing service should be re-run before\n * giving up.\n */\nexport const DEFAULT_MAX_RETRIES = 3;\n\n/**\n * The maximum number of times that the service is allowed to fail before\n * pausing further retries. This is set to a value such that if given a\n * service that continually fails, the policy needs to be executed 3 times\n * before further retries are paused.\n */\nexport const DEFAULT_MAX_CONSECUTIVE_FAILURES = (1 + DEFAULT_MAX_RETRIES) * 3;\n\n/**\n * The default length of time (in milliseconds) to temporarily pause retries of\n * the service after enough consecutive failures.\n */\nexport const DEFAULT_CIRCUIT_BREAK_DURATION = 30 * 60 * 1000;\n\n/**\n * The default length of time (in milliseconds) that governs when the service is\n * regarded as degraded (affecting when `onDegraded` is called).\n */\nexport const DEFAULT_DEGRADED_THRESHOLD = 5_000;\n\nconst isServiceFailure = (error: unknown) => {\n if (\n typeof error === 'object' &&\n error !== null &&\n 'httpStatus' in error &&\n typeof error.httpStatus === 'number'\n ) {\n return error.httpStatus >= 500;\n }\n\n // If the error is not an object, or doesn't have a numeric code property,\n // consider it a service failure (e.g., network errors, timeouts, etc.)\n return true;\n};\n\n/**\n * The circuit breaker policy inside of the Cockatiel library exposes some of\n * its state, but not all of it. Notably, the time that the circuit opened is\n * not publicly accessible. So we have to record this ourselves.\n *\n * This function therefore allows us to obtain the circuit breaker state that we\n * wish we could access.\n *\n * @param state - The public state of a circuit breaker policy.\n * @returns if the circuit is open, the state of the circuit breaker policy plus\n * the time that it opened, otherwise just the circuit state.\n */\nfunction getInternalCircuitState(state: CircuitState): InternalCircuitState {\n if (state === CircuitState.Open) {\n return { state, openedAt: Date.now() };\n }\n return { state };\n}\n\n/**\n * Constructs an object exposing an `execute` method which, given a function —\n * hereafter called the \"service\" — will retry that service with ever increasing\n * delays until it succeeds. If the policy detects too many consecutive\n * failures, it will block further retries until a designated time period has\n * passed; this particular behavior is primarily designed for services that wrap\n * API calls so as not to make needless HTTP requests when the API is down and\n * to be able to recover when the API comes back up. In addition, hooks allow\n * for responding to certain events, one of which can be used to detect when an\n * HTTP request is performing slowly.\n *\n * Internally, this function makes use of the retry and circuit breaker policies\n * from the [Cockatiel](https://www.npmjs.com/package/cockatiel) library; see\n * there for more.\n *\n * @param options - The options to this function. See\n * {@link CreateServicePolicyOptions}.\n * @returns The service policy.\n * @example\n * This function is designed to be used in the context of a service class like\n * this:\n * ``` ts\n * class Service {\n * constructor() {\n * this.#policy = createServicePolicy({\n * maxRetries: 3,\n * retryFilterPolicy: handleWhen((error) => {\n * return error.message.includes('oops');\n * }),\n * maxConsecutiveFailures: 3,\n * circuitBreakDuration: 5000,\n * degradedThreshold: 2000,\n * onBreak: () => {\n * console.log('Circuit broke');\n * },\n * onDegraded: () => {\n * console.log('Service is degraded');\n * },\n * });\n * }\n *\n * async fetch() {\n * return await this.#policy.execute(async () => {\n * const response = await fetch('https://some/url');\n * return await response.json();\n * });\n * }\n * }\n * ```\n */\nexport function createServicePolicy(\n options: CreateServicePolicyOptions = {},\n): ServicePolicy {\n const {\n maxRetries = DEFAULT_MAX_RETRIES,\n retryFilterPolicy = handleAll,\n maxConsecutiveFailures = DEFAULT_MAX_CONSECUTIVE_FAILURES,\n circuitBreakDuration = DEFAULT_CIRCUIT_BREAK_DURATION,\n degradedThreshold = DEFAULT_DEGRADED_THRESHOLD,\n backoff = new ExponentialBackoff(),\n } = options;\n\n let availabilityStatus: AvailabilityStatus = AVAILABILITY_STATUSES.Unknown;\n\n const retryPolicy = retry(retryFilterPolicy, {\n // Note that although the option here is called \"max attempts\", it's really\n // maximum number of *retries* (attempts past the initial attempt).\n maxAttempts: maxRetries,\n // Retries of the service will be executed following ever increasing delays,\n // determined by a backoff formula.\n backoff,\n });\n const onRetry = retryPolicy.onRetry.bind(retryPolicy);\n\n const consecutiveBreaker = new ConsecutiveBreaker(maxConsecutiveFailures);\n const circuitBreakerPolicy = circuitBreaker(handleWhen(isServiceFailure), {\n // While the circuit is open, any additional invocations of the service\n // passed to the policy (either via automatic retries or by manually\n // executing the policy again) will result in a BrokenCircuitError. This\n // will remain the case until `circuitBreakDuration` passes, after which the\n // service will be allowed to run again. If the service succeeds, the\n // circuit will close, otherwise it will remain open.\n halfOpenAfter: circuitBreakDuration,\n breaker: consecutiveBreaker,\n });\n\n let internalCircuitState: InternalCircuitState = getInternalCircuitState(\n circuitBreakerPolicy.state,\n );\n circuitBreakerPolicy.onStateChange((state) => {\n internalCircuitState = getInternalCircuitState(state);\n });\n\n circuitBreakerPolicy.onBreak(() => {\n availabilityStatus = AVAILABILITY_STATUSES.Unavailable;\n });\n const onBreak = circuitBreakerPolicy.onBreak.bind(circuitBreakerPolicy);\n\n const onDegradedEventEmitter =\n new CockatielEventEmitter<FailureReason<unknown> | void>();\n const onDegraded = onDegradedEventEmitter.addListener;\n\n const onAvailableEventEmitter = new CockatielEventEmitter<void>();\n const onAvailable = onAvailableEventEmitter.addListener;\n\n retryPolicy.onGiveUp((data) => {\n if (circuitBreakerPolicy.state === CircuitState.Closed) {\n availabilityStatus = AVAILABILITY_STATUSES.Degraded;\n onDegradedEventEmitter.emit(data);\n }\n });\n retryPolicy.onSuccess(({ duration }) => {\n if (circuitBreakerPolicy.state === CircuitState.Closed) {\n if (duration > degradedThreshold) {\n availabilityStatus = AVAILABILITY_STATUSES.Degraded;\n onDegradedEventEmitter.emit();\n } else if (availabilityStatus !== AVAILABILITY_STATUSES.Available) {\n availabilityStatus = AVAILABILITY_STATUSES.Available;\n onAvailableEventEmitter.emit();\n }\n }\n });\n\n // Every time the retry policy makes an attempt, it executes the circuit\n // breaker policy, which executes the service.\n //\n // Calling:\n //\n // policy.execute(() => {\n // // do what the service does\n // })\n //\n // is equivalent to:\n //\n // retryPolicy.execute(() => {\n // circuitBreakerPolicy.execute(() => {\n // // do what the service does\n // });\n // });\n //\n // So if the retry policy succeeds or fails, it is because the circuit breaker\n // policy succeeded or failed. And if there are any event listeners registered\n // on the retry policy, by the time they are called, the state of the circuit\n // breaker will have already changed.\n const policy = wrap(retryPolicy, circuitBreakerPolicy);\n\n const getRemainingCircuitOpenDuration = () => {\n if (internalCircuitState.state === CircuitState.Open) {\n return internalCircuitState.openedAt + circuitBreakDuration - Date.now();\n }\n return null;\n };\n\n const getCircuitState = () => {\n return circuitBreakerPolicy.state;\n };\n\n const reset = () => {\n // Set the state of the policy to \"isolated\" regardless of its current state\n const { dispose } = circuitBreakerPolicy.isolate();\n // Reset the state to \"closed\"\n dispose();\n\n // Reset the counter on the breaker as well\n consecutiveBreaker.success();\n\n // Re-initialize the availability status so that if the service is executed\n // successfully, onAvailable listeners will be called again\n availabilityStatus = AVAILABILITY_STATUSES.Unknown;\n };\n\n return {\n ...policy,\n circuitBreakerPolicy,\n circuitBreakDuration,\n getCircuitState,\n getRemainingCircuitOpenDuration,\n reset,\n retryPolicy,\n onBreak,\n onDegraded,\n onAvailable,\n onRetry,\n };\n}\n"]}
1
+ {"version":3,"file":"create-service-policy.mjs","sourceRoot":"","sources":["../src/create-service-policy.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,MAAM,EAAE,CAAC;YACvD,sBAAsB,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;QACpC,CAAC;IACH,CAAC,CAAC,CAAC;IACH,WAAW,CAAC,SAAS,CAAC,CAAC,EAAE,QAAQ,EAAE,EAAE,EAAE;QACrC,IACE,oBAAoB,CAAC,KAAK,KAAK,YAAY,CAAC,MAAM;YAClD,QAAQ,GAAG,iBAAiB,EAC5B,CAAC;YACD,sBAAsB,CAAC,IAAI,EAAE,CAAC;QAChC,CAAC;IACH,CAAC,CAAC,CAAC;IACH,MAAM,UAAU,GAAG,sBAAsB,CAAC,WAAW,CAAC;IAEtD,wEAAwE;IACxE,8CAA8C;IAC9C,MAAM,MAAM,GAAG,IAAI,CAAC,WAAW,EAAE,oBAAoB,CAAC,CAAC;IAEvD,MAAM,+BAA+B,GAAG,GAAG,EAAE;QAC3C,IAAI,oBAAoB,CAAC,KAAK,KAAK,YAAY,CAAC,IAAI,EAAE,CAAC;YACrD,OAAO,oBAAoB,CAAC,QAAQ,GAAG,oBAAoB,GAAG,IAAI,CAAC,GAAG,EAAE,CAAC;QAC3E,CAAC;QACD,OAAO,IAAI,CAAC;IACd,CAAC,CAAC;IAEF,OAAO;QACL,GAAG,MAAM;QACT,oBAAoB;QACpB,oBAAoB;QACpB,+BAA+B;QAC/B,WAAW;QACX,OAAO;QACP,UAAU;QACV,OAAO;KACR,CAAC;AACJ,CAAC","sourcesContent":["import {\n BrokenCircuitError,\n CircuitState,\n EventEmitter as CockatielEventEmitter,\n ConsecutiveBreaker,\n ExponentialBackoff,\n ConstantBackoff,\n circuitBreaker,\n handleAll,\n handleWhen,\n retry,\n wrap,\n} from 'cockatiel';\nimport type {\n CircuitBreakerPolicy,\n Event as CockatielEvent,\n FailureReason,\n IBackoffFactory,\n IPolicy,\n Policy,\n RetryPolicy,\n} from 'cockatiel';\n\nexport {\n BrokenCircuitError,\n CircuitState,\n ConstantBackoff,\n ExponentialBackoff,\n handleAll,\n handleWhen,\n};\n\nexport type { CockatielEvent };\n\n/**\n * The options for `createServicePolicy`.\n */\nexport type CreateServicePolicyOptions = {\n /**\n * The backoff strategy to use. Mainly useful for testing so that a constant\n * backoff can be used when mocking timers. Defaults to an instance of\n * ExponentialBackoff.\n */\n backoff?: IBackoffFactory<unknown>;\n /**\n * The length of time (in milliseconds) to pause retries of the action after\n * the number of failures reaches `maxConsecutiveFailures`.\n */\n circuitBreakDuration?: number;\n /**\n * The length of time (in milliseconds) that governs when the service is\n * regarded as degraded (affecting when `onDegraded` is called).\n */\n degradedThreshold?: number;\n /**\n * The maximum number of times that the service is allowed to fail before\n * pausing further retries.\n */\n maxConsecutiveFailures?: number;\n /**\n * The maximum number of times that a failing service should be re-invoked\n * before giving up.\n */\n maxRetries?: number;\n /**\n * The policy used to control when the service should be retried based on\n * either the result of the service or an error that it throws. For instance,\n * you could use this to retry only certain errors. See `handleWhen` and\n * friends from Cockatiel for more.\n */\n retryFilterPolicy?: Policy;\n};\n\n/**\n * The service policy object.\n */\nexport type ServicePolicy = IPolicy & {\n /**\n * The Cockatiel circuit breaker policy that the service policy uses\n * internally.\n */\n circuitBreakerPolicy: CircuitBreakerPolicy;\n /**\n * The amount of time to pause requests to the service if the number of\n * maximum consecutive failures is reached.\n */\n circuitBreakDuration: number;\n /**\n * If the circuit is open and ongoing requests are paused, returns the number\n * of milliseconds before the requests will be attempted again. If the circuit\n * is not open, returns null.\n */\n getRemainingCircuitOpenDuration: () => number | null;\n /**\n * The Cockatiel retry policy that the service policy uses internally.\n */\n retryPolicy: RetryPolicy;\n /**\n * A function which is called when the number of times that the service fails\n * in a row meets the set maximum number of consecutive failures.\n */\n onBreak: CircuitBreakerPolicy['onBreak'];\n /**\n * A function which is called in two circumstances: 1) when the service\n * succeeds before the maximum number of consecutive failures is reached, but\n * takes more time than the `degradedThreshold` to run, or 2) if the service\n * never succeeds before the retry policy gives up and before the maximum\n * number of consecutive failures has been reached.\n */\n onDegraded: CockatielEvent<FailureReason<unknown> | void>;\n /**\n * A function which will be called by the retry policy each time the service\n * fails and the policy kicks off a timer to re-run the service. This is\n * primarily useful in tests where we are mocking timers.\n */\n onRetry: RetryPolicy['onRetry'];\n};\n\n/**\n * Parts of the circuit breaker's internal and external state as necessary in\n * order to compute the time remaining before the circuit will reopen.\n */\ntype InternalCircuitState =\n | {\n state: CircuitState.Open;\n openedAt: number;\n }\n | { state: Exclude<CircuitState, CircuitState.Open> };\n\n/**\n * The maximum number of times that a failing service should be re-run before\n * giving up.\n */\nexport const DEFAULT_MAX_RETRIES = 3;\n\n/**\n * The maximum number of times that the service is allowed to fail before\n * pausing further retries. This is set to a value such that if given a\n * service that continually fails, the policy needs to be executed 3 times\n * before further retries are paused.\n */\nexport const DEFAULT_MAX_CONSECUTIVE_FAILURES = (1 + DEFAULT_MAX_RETRIES) * 3;\n\n/**\n * The default length of time (in milliseconds) to temporarily pause retries of\n * the service after enough consecutive failures.\n */\nexport const DEFAULT_CIRCUIT_BREAK_DURATION = 30 * 60 * 1000;\n\n/**\n * The default length of time (in milliseconds) that governs when the service is\n * regarded as degraded (affecting when `onDegraded` is called).\n */\nexport const DEFAULT_DEGRADED_THRESHOLD = 5_000;\n\nconst isServiceFailure = (error: unknown) => {\n if (\n typeof error === 'object' &&\n error !== null &&\n 'httpStatus' in error &&\n typeof error.httpStatus === 'number'\n ) {\n return error.httpStatus >= 500;\n }\n\n // If the error is not an object, or doesn't have a numeric code property,\n // consider it a service failure (e.g., network errors, timeouts, etc.)\n return true;\n};\n\n/**\n * The circuit breaker policy inside of the Cockatiel library exposes some of\n * its state, but not all of it. Notably, the time that the circuit opened is\n * not publicly accessible. So we have to record this ourselves.\n *\n * This function therefore allows us to obtain the circuit breaker state that we\n * wish we could access.\n *\n * @param state - The public state of a circuit breaker policy.\n * @returns if the circuit is open, the state of the circuit breaker policy plus\n * the time that it opened, otherwise just the circuit state.\n */\nfunction getInternalCircuitState(state: CircuitState): InternalCircuitState {\n if (state === CircuitState.Open) {\n return { state, openedAt: Date.now() };\n }\n return { state };\n}\n\n/**\n * Constructs an object exposing an `execute` method which, given a function —\n * hereafter called the \"service\" — will retry that service with ever increasing\n * delays until it succeeds. If the policy detects too many consecutive\n * failures, it will block further retries until a designated time period has\n * passed; this particular behavior is primarily designed for services that wrap\n * API calls so as not to make needless HTTP requests when the API is down and\n * to be able to recover when the API comes back up. In addition, hooks allow\n * for responding to certain events, one of which can be used to detect when an\n * HTTP request is performing slowly.\n *\n * Internally, this function makes use of the retry and circuit breaker policies\n * from the [Cockatiel](https://www.npmjs.com/package/cockatiel) library; see\n * there for more.\n *\n * @param options - The options to this function. See\n * {@link CreateServicePolicyOptions}.\n * @returns The service policy.\n * @example\n * This function is designed to be used in the context of a service class like\n * this:\n * ``` ts\n * class Service {\n * constructor() {\n * this.#policy = createServicePolicy({\n * maxRetries: 3,\n * retryFilterPolicy: handleWhen((error) => {\n * return error.message.includes('oops');\n * }),\n * maxConsecutiveFailures: 3,\n * circuitBreakDuration: 5000,\n * degradedThreshold: 2000,\n * onBreak: () => {\n * console.log('Circuit broke');\n * },\n * onDegraded: () => {\n * console.log('Service is degraded');\n * },\n * });\n * }\n *\n * async fetch() {\n * return await this.#policy.execute(async () => {\n * const response = await fetch('https://some/url');\n * return await response.json();\n * });\n * }\n * }\n * ```\n */\nexport function createServicePolicy(\n options: CreateServicePolicyOptions = {},\n): ServicePolicy {\n const {\n maxRetries = DEFAULT_MAX_RETRIES,\n retryFilterPolicy = handleAll,\n maxConsecutiveFailures = DEFAULT_MAX_CONSECUTIVE_FAILURES,\n circuitBreakDuration = DEFAULT_CIRCUIT_BREAK_DURATION,\n degradedThreshold = DEFAULT_DEGRADED_THRESHOLD,\n backoff = new ExponentialBackoff(),\n } = options;\n\n const retryPolicy = retry(retryFilterPolicy, {\n // Note that although the option here is called \"max attempts\", it's really\n // maximum number of *retries* (attempts past the initial attempt).\n maxAttempts: maxRetries,\n // Retries of the service will be executed following ever increasing delays,\n // determined by a backoff formula.\n backoff,\n });\n const onRetry = retryPolicy.onRetry.bind(retryPolicy);\n\n const circuitBreakerPolicy = circuitBreaker(handleWhen(isServiceFailure), {\n // While the circuit is open, any additional invocations of the service\n // passed to the policy (either via automatic retries or by manually\n // executing the policy again) will result in a BrokenCircuitError. This\n // will remain the case until `circuitBreakDuration` passes, after which the\n // service will be allowed to run again. If the service succeeds, the\n // circuit will close, otherwise it will remain open.\n halfOpenAfter: circuitBreakDuration,\n breaker: new ConsecutiveBreaker(maxConsecutiveFailures),\n });\n\n let internalCircuitState: InternalCircuitState = getInternalCircuitState(\n circuitBreakerPolicy.state,\n );\n circuitBreakerPolicy.onStateChange((state) => {\n internalCircuitState = getInternalCircuitState(state);\n });\n const onBreak = circuitBreakerPolicy.onBreak.bind(circuitBreakerPolicy);\n\n const onDegradedEventEmitter =\n new CockatielEventEmitter<FailureReason<unknown> | void>();\n retryPolicy.onGiveUp((data) => {\n if (circuitBreakerPolicy.state === CircuitState.Closed) {\n onDegradedEventEmitter.emit(data);\n }\n });\n retryPolicy.onSuccess(({ duration }) => {\n if (\n circuitBreakerPolicy.state === CircuitState.Closed &&\n duration > degradedThreshold\n ) {\n onDegradedEventEmitter.emit();\n }\n });\n const onDegraded = onDegradedEventEmitter.addListener;\n\n // Every time the retry policy makes an attempt, it executes the circuit\n // breaker policy, which executes the service.\n const policy = wrap(retryPolicy, circuitBreakerPolicy);\n\n const getRemainingCircuitOpenDuration = () => {\n if (internalCircuitState.state === CircuitState.Open) {\n return internalCircuitState.openedAt + circuitBreakDuration - Date.now();\n }\n return null;\n };\n\n return {\n ...policy,\n circuitBreakerPolicy,\n circuitBreakDuration,\n getRemainingCircuitOpenDuration,\n retryPolicy,\n onBreak,\n onDegraded,\n onRetry,\n };\n}\n"]}
package/dist/index.cjs CHANGED
@@ -14,12 +14,11 @@ var __exportStar = (this && this.__exportStar) || function(m, exports) {
14
14
  for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
15
15
  };
16
16
  Object.defineProperty(exports, "__esModule", { value: true });
17
- exports.fetchWithErrorHandling = exports.convertHexToDecimal = exports.BNToHex = exports.NETWORKS_BYPASSING_VALIDATION = exports.DAYS = exports.DAY = exports.HOURS = exports.HOUR = exports.MINUTES = exports.MINUTE = exports.SECONDS = exports.SECOND = exports.CHAIN_ID_TO_ETHERS_NETWORK_NAME_MAP = exports.ApprovalType = exports.ORIGIN_METAMASK = exports.NFT_API_TIMEOUT = exports.NFT_API_VERSION = exports.NFT_API_BASE_URL = exports.OPENSEA_PROXY_URL = exports.BUILT_IN_NETWORKS = exports.BUILT_IN_CUSTOM_NETWORKS_RPC = exports.TESTNET_TICKER_SYMBOLS = exports.ASSET_TYPES = exports.GWEI = exports.ERC1155_TOKEN_RECEIVER_INTERFACE_ID = exports.ERC1155_METADATA_URI_INTERFACE_ID = exports.ERC1155_INTERFACE_ID = exports.ERC721_ENUMERABLE_INTERFACE_ID = exports.ERC721_METADATA_INTERFACE_ID = exports.ERC721_INTERFACE_ID = exports.ERC20 = exports.ERC1155 = exports.ERC721 = exports.MAX_SAFE_CHAIN_ID = exports.GANACHE_CHAIN_ID = exports.IPFS_DEFAULT_GATEWAY_URL = exports.FALL_BACK_VS_CURRENCY = exports.RPC = exports.handleWhen = exports.handleAll = exports.createServicePolicy = exports.ExponentialBackoff = exports.DEFAULT_MAX_RETRIES = exports.DEFAULT_MAX_CONSECUTIVE_FAILURES = exports.DEFAULT_DEGRADED_THRESHOLD = exports.DEFAULT_CIRCUIT_BREAK_DURATION = exports.ConstantBackoff = exports.CockatielEventEmitter = exports.CircuitState = exports.BrokenCircuitError = void 0;
18
- exports.isEqualCaseInsensitive = exports.weiHexToGweiDec = exports.toHex = exports.toChecksumHexAddress = exports.timeoutFetch = exports.successfulFetch = exports.safelyExecuteWithTimeout = exports.safelyExecute = exports.query = exports.normalizeEnsName = exports.isValidHexAddress = exports.isValidJson = exports.isSmartContractCode = exports.isSafeDynamicKey = exports.isSafeChainId = exports.isPlainObject = exports.isNonEmptyArray = exports.HttpError = exports.hexToText = exports.hexToBN = exports.handleFetch = exports.gweiDecToWEIBN = exports.getBuyURL = exports.fromHex = exports.fractionBN = void 0;
17
+ exports.fractionBN = exports.fetchWithErrorHandling = exports.convertHexToDecimal = exports.BNToHex = exports.NETWORKS_BYPASSING_VALIDATION = exports.DAYS = exports.DAY = exports.HOURS = exports.HOUR = exports.MINUTES = exports.MINUTE = exports.SECONDS = exports.SECOND = exports.CHAIN_ID_TO_ETHERS_NETWORK_NAME_MAP = exports.ApprovalType = exports.ORIGIN_METAMASK = exports.NFT_API_TIMEOUT = exports.NFT_API_VERSION = exports.NFT_API_BASE_URL = exports.OPENSEA_PROXY_URL = exports.BUILT_IN_NETWORKS = exports.BUILT_IN_CUSTOM_NETWORKS_RPC = exports.TESTNET_TICKER_SYMBOLS = exports.ASSET_TYPES = exports.GWEI = exports.ERC1155_TOKEN_RECEIVER_INTERFACE_ID = exports.ERC1155_METADATA_URI_INTERFACE_ID = exports.ERC1155_INTERFACE_ID = exports.ERC721_ENUMERABLE_INTERFACE_ID = exports.ERC721_METADATA_INTERFACE_ID = exports.ERC721_INTERFACE_ID = exports.ERC20 = exports.ERC1155 = exports.ERC721 = exports.MAX_SAFE_CHAIN_ID = exports.GANACHE_CHAIN_ID = exports.IPFS_DEFAULT_GATEWAY_URL = exports.FALL_BACK_VS_CURRENCY = exports.RPC = exports.handleWhen = exports.handleAll = exports.createServicePolicy = exports.ExponentialBackoff = exports.DEFAULT_MAX_RETRIES = exports.DEFAULT_MAX_CONSECUTIVE_FAILURES = exports.DEFAULT_DEGRADED_THRESHOLD = exports.DEFAULT_CIRCUIT_BREAK_DURATION = exports.ConstantBackoff = exports.CircuitState = exports.BrokenCircuitError = void 0;
18
+ exports.isEqualCaseInsensitive = exports.weiHexToGweiDec = exports.toHex = exports.toChecksumHexAddress = exports.timeoutFetch = exports.successfulFetch = exports.safelyExecuteWithTimeout = exports.safelyExecute = exports.query = exports.normalizeEnsName = exports.isValidHexAddress = exports.isValidJson = exports.isSmartContractCode = exports.isSafeDynamicKey = exports.isSafeChainId = exports.isPlainObject = exports.isNonEmptyArray = exports.HttpError = exports.hexToText = exports.hexToBN = exports.handleFetch = exports.gweiDecToWEIBN = exports.getBuyURL = exports.fromHex = void 0;
19
19
  var create_service_policy_1 = require("./create-service-policy.cjs");
20
20
  Object.defineProperty(exports, "BrokenCircuitError", { enumerable: true, get: function () { return create_service_policy_1.BrokenCircuitError; } });
21
21
  Object.defineProperty(exports, "CircuitState", { enumerable: true, get: function () { return create_service_policy_1.CircuitState; } });
22
- Object.defineProperty(exports, "CockatielEventEmitter", { enumerable: true, get: function () { return create_service_policy_1.CockatielEventEmitter; } });
23
22
  Object.defineProperty(exports, "ConstantBackoff", { enumerable: true, get: function () { return create_service_policy_1.ConstantBackoff; } });
24
23
  Object.defineProperty(exports, "DEFAULT_CIRCUIT_BREAK_DURATION", { enumerable: true, get: function () { return create_service_policy_1.DEFAULT_CIRCUIT_BREAK_DURATION; } });
25
24
  Object.defineProperty(exports, "DEFAULT_DEGRADED_THRESHOLD", { enumerable: true, get: function () { return create_service_policy_1.DEFAULT_DEGRADED_THRESHOLD; } });
@@ -1 +1 @@
1
- {"version":3,"file":"index.cjs","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;AAAA,qEAaiC;AAZ/B,2HAAA,kBAAkB,OAAA;AAClB,qHAAA,YAAY,OAAA;AACZ,8HAAA,qBAAqB,OAAA;AACrB,wHAAA,eAAe,OAAA;AACf,uIAAA,8BAA8B,OAAA;AAC9B,mIAAA,0BAA0B,OAAA;AAC1B,yIAAA,gCAAgC,OAAA;AAChC,4HAAA,mBAAmB,OAAA;AACnB,2HAAA,kBAAkB,OAAA;AAClB,4HAAA,mBAAmB,OAAA;AACnB,kHAAA,SAAS,OAAA;AACT,mHAAA,UAAU,OAAA;AAQZ,6CAoCqB;AAnCnB,gGAAA,GAAG,OAAA;AACH,kHAAA,qBAAqB,OAAA;AACrB,qH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AgB,OAAA;AAChB,2GAAA,mBAAmB,OAAA;AACnB,mGAAA,WAAW,OAAA;AACX,yGAAA,iBAAiB,OAAA;AACjB,wGAAA,gBAAgB,OAAA;AAChB,6FAAA,KAAK,OAAA;AACL,qGAAA,aAAa,OAAA;AACb,gHAAA,wBAAwB,OAAA;AACxB,uGAAA,eAAe,OAAA;AACf,oGAAA,YAAY,OAAA;AACZ,4GAAA,oBAAoB,OAAA;AACpB,6FAAA,KAAK,OAAA;AACL,uGAAA,eAAe,OAAA;AACf,8GAAA,sBAAsB,OAAA;AAExB,8CAAwB;AACxB,6CAAuB","sourcesContent":["export {\n BrokenCircuitError,\n CircuitState,\n CockatielEventEmitter,\n ConstantBackoff,\n DEFAULT_CIRCUIT_BREAK_DURATION,\n DEFAULT_DEGRADED_THRESHOLD,\n DEFAULT_MAX_CONSECUTIVE_FAILURES,\n DEFAULT_MAX_RETRIES,\n ExponentialBackoff,\n createServicePolicy,\n handleAll,\n handleWhen,\n} from './create-service-policy';\nexport type {\n CockatielEvent,\n CreateServicePolicyOptions,\n CockatielFailureReason,\n ServicePolicy,\n} from './create-service-policy';\nexport {\n RPC,\n FALL_BACK_VS_CURRENCY,\n IPFS_DEFAULT_GATEWAY_URL,\n GANACHE_CHAIN_ID,\n MAX_SAFE_CHAIN_ID,\n ERC721,\n ERC1155,\n ERC20,\n ERC721_INTERFACE_ID,\n ERC721_METADATA_INTERFACE_ID,\n ERC721_ENUMERABLE_INTERFACE_ID,\n ERC1155_INTERFACE_ID,\n ERC1155_METADATA_URI_INTERFACE_ID,\n ERC1155_TOKEN_RECEIVER_INTERFACE_ID,\n GWEI,\n ASSET_TYPES,\n TESTNET_TICKER_SYMBOLS,\n BUILT_IN_CUSTOM_NETWORKS_RPC,\n BUILT_IN_NETWORKS,\n OPENSEA_PROXY_URL,\n NFT_API_BASE_URL,\n NFT_API_VERSION,\n NFT_API_TIMEOUT,\n ORIGIN_METAMASK,\n ApprovalType,\n CHAIN_ID_TO_ETHERS_NETWORK_NAME_MAP,\n SECOND,\n SECONDS,\n MINUTE,\n MINUTES,\n HOUR,\n HOURS,\n DAY,\n DAYS,\n NETWORKS_BYPASSING_VALIDATION,\n} from './constants';\nexport type { NonEmptyArray } from './util';\nexport {\n BNToHex,\n convertHexToDecimal,\n fetchWithErrorHandling,\n fractionBN,\n fromHex,\n getBuyURL,\n gweiDecToWEIBN,\n handleFetch,\n hexToBN,\n hexToText,\n HttpError,\n isNonEmptyArray,\n isPlainObject,\n isSafeChainId,\n isSafeDynamicKey,\n isSmartContractCode,\n isValidJson,\n isValidHexAddress,\n normalizeEnsName,\n query,\n safelyExecute,\n safelyExecuteWithTimeout,\n successfulFetch,\n timeoutFetch,\n toChecksumHexAddress,\n toHex,\n weiHexToGweiDec,\n isEqualCaseInsensitive,\n} from './util';\nexport * from './types';\nexport * from './siwe';\n"]}
1
+ {"version":3,"file":"index.cjs","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;AAAA,qEAYiC;AAX/B,2HAAA,kBAAkB,OAAA;AAClB,qHAAA,YAAY,OAAA;AACZ,wHAAA,eAAe,OAAA;AACf,uIAAA,8BAA8B,OAAA;AAC9B,mIAAA,0BAA0B,OAAA;AAC1B,yIAAA,gCAAgC,OAAA;AAChC,4HAAA,mBAAmB,OAAA;AACnB,2HAAA,kBAAkB,OAAA;AAClB,4HAAA,mBAAmB,OAAA;AACnB,kHAAA,SAAS,OAAA;AACT,mHAAA,UAAU,OAAA;AAOZ,6CAoCqB;AAnCnB,gGAAA,GAAG,OAAA;AACH,kHAAA,qBAAqB,OAAA;AACrB,qHAAA,wBAAwB,OAAA;AACxB,6GAAA,gBAAgB,OAAA;AAChB,8GAAA,iBAAiB,OAAA;AACjB,mGAAA,MAAM,OAAA;AACN,oGAAA,OAAO,OAAA;AACP,kGAAA,KAAK,OAAA;AACL,gHAAA,mBAAmB,OAAA;AACnB,yHAAA,4BAA4B,OAAA;AAC5B,2HAAA,8BAA8B,OA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AA,YAAY,OAAA;AACZ,4GAAA,oBAAoB,OAAA;AACpB,6FAAA,KAAK,OAAA;AACL,uGAAA,eAAe,OAAA;AACf,8GAAA,sBAAsB,OAAA;AAExB,8CAAwB;AACxB,6CAAuB","sourcesContent":["export {\n BrokenCircuitError,\n CircuitState,\n ConstantBackoff,\n DEFAULT_CIRCUIT_BREAK_DURATION,\n DEFAULT_DEGRADED_THRESHOLD,\n DEFAULT_MAX_CONSECUTIVE_FAILURES,\n DEFAULT_MAX_RETRIES,\n ExponentialBackoff,\n createServicePolicy,\n handleAll,\n handleWhen,\n} from './create-service-policy';\nexport type {\n CockatielEvent,\n CreateServicePolicyOptions,\n ServicePolicy,\n} from './create-service-policy';\nexport {\n RPC,\n FALL_BACK_VS_CURRENCY,\n IPFS_DEFAULT_GATEWAY_URL,\n GANACHE_CHAIN_ID,\n MAX_SAFE_CHAIN_ID,\n ERC721,\n ERC1155,\n ERC20,\n ERC721_INTERFACE_ID,\n ERC721_METADATA_INTERFACE_ID,\n ERC721_ENUMERABLE_INTERFACE_ID,\n ERC1155_INTERFACE_ID,\n ERC1155_METADATA_URI_INTERFACE_ID,\n ERC1155_TOKEN_RECEIVER_INTERFACE_ID,\n GWEI,\n ASSET_TYPES,\n TESTNET_TICKER_SYMBOLS,\n BUILT_IN_CUSTOM_NETWORKS_RPC,\n BUILT_IN_NETWORKS,\n OPENSEA_PROXY_URL,\n NFT_API_BASE_URL,\n NFT_API_VERSION,\n NFT_API_TIMEOUT,\n ORIGIN_METAMASK,\n ApprovalType,\n CHAIN_ID_TO_ETHERS_NETWORK_NAME_MAP,\n SECOND,\n SECONDS,\n MINUTE,\n MINUTES,\n HOUR,\n HOURS,\n DAY,\n DAYS,\n NETWORKS_BYPASSING_VALIDATION,\n} from './constants';\nexport type { NonEmptyArray } from './util';\nexport {\n BNToHex,\n convertHexToDecimal,\n fetchWithErrorHandling,\n fractionBN,\n fromHex,\n getBuyURL,\n gweiDecToWEIBN,\n handleFetch,\n hexToBN,\n hexToText,\n HttpError,\n isNonEmptyArray,\n isPlainObject,\n isSafeChainId,\n isSafeDynamicKey,\n isSmartContractCode,\n isValidJson,\n isValidHexAddress,\n normalizeEnsName,\n query,\n safelyExecute,\n safelyExecuteWithTimeout,\n successfulFetch,\n timeoutFetch,\n toChecksumHexAddress,\n toHex,\n weiHexToGweiDec,\n isEqualCaseInsensitive,\n} from './util';\nexport * from './types';\nexport * from './siwe';\n"]}
package/dist/index.d.cts CHANGED
@@ -1,5 +1,5 @@
1
- export { BrokenCircuitError, CircuitState, CockatielEventEmitter, ConstantBackoff, DEFAULT_CIRCUIT_BREAK_DURATION, DEFAULT_DEGRADED_THRESHOLD, DEFAULT_MAX_CONSECUTIVE_FAILURES, DEFAULT_MAX_RETRIES, ExponentialBackoff, createServicePolicy, handleAll, handleWhen, } from "./create-service-policy.cjs";
2
- export type { CockatielEvent, CreateServicePolicyOptions, CockatielFailureReason, ServicePolicy, } from "./create-service-policy.cjs";
1
+ export { BrokenCircuitError, CircuitState, ConstantBackoff, DEFAULT_CIRCUIT_BREAK_DURATION, DEFAULT_DEGRADED_THRESHOLD, DEFAULT_MAX_CONSECUTIVE_FAILURES, DEFAULT_MAX_RETRIES, ExponentialBackoff, createServicePolicy, handleAll, handleWhen, } from "./create-service-policy.cjs";
2
+ export type { CockatielEvent, CreateServicePolicyOptions, ServicePolicy, } from "./create-service-policy.cjs";
3
3
  export { RPC, FALL_BACK_VS_CURRENCY, IPFS_DEFAULT_GATEWAY_URL, GANACHE_CHAIN_ID, MAX_SAFE_CHAIN_ID, ERC721, ERC1155, ERC20, ERC721_INTERFACE_ID, ERC721_METADATA_INTERFACE_ID, ERC721_ENUMERABLE_INTERFACE_ID, ERC1155_INTERFACE_ID, ERC1155_METADATA_URI_INTERFACE_ID, ERC1155_TOKEN_RECEIVER_INTERFACE_ID, GWEI, ASSET_TYPES, TESTNET_TICKER_SYMBOLS, BUILT_IN_CUSTOM_NETWORKS_RPC, BUILT_IN_NETWORKS, OPENSEA_PROXY_URL, NFT_API_BASE_URL, NFT_API_VERSION, NFT_API_TIMEOUT, ORIGIN_METAMASK, ApprovalType, CHAIN_ID_TO_ETHERS_NETWORK_NAME_MAP, SECOND, SECONDS, MINUTE, MINUTES, HOUR, HOURS, DAY, DAYS, NETWORKS_BYPASSING_VALIDATION, } from "./constants.cjs";
4
4
  export type { NonEmptyArray } from "./util.cjs";
5
5
  export { BNToHex, convertHexToDecimal, fetchWithErrorHandling, fractionBN, fromHex, getBuyURL, gweiDecToWEIBN, handleFetch, hexToBN, hexToText, HttpError, isNonEmptyArray, isPlainObject, isSafeChainId, isSafeDynamicKey, isSmartContractCode, isValidJson, isValidHexAddress, normalizeEnsName, query, safelyExecute, safelyExecuteWithTimeout, successfulFetch, timeoutFetch, toChecksumHexAddress, toHex, weiHexToGweiDec, isEqualCaseInsensitive, } from "./util.cjs";
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.cts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,kBAAkB,EAClB,YAAY,EACZ,qBAAqB,EACrB,eAAe,EACf,8BAA8B,EAC9B,0BAA0B,EAC1B,gCAAgC,EAChC,mBAAmB,EACnB,kBAAkB,EAClB,mBAAmB,EACnB,SAAS,EACT,UAAU,GACX,oCAAgC;AACjC,YAAY,EACV,cAAc,EACd,0BAA0B,EAC1B,sBAAsB,EACtB,aAAa,GACd,oCAAgC;AACjC,OAAO,EACL,GAAG,EACH,qBAAqB,EACrB,wBAAwB,EACxB,gBAAgB,EAChB,iBAAiB,EACjB,MAAM,EACN,OAAO,EACP,KAAK,EACL,mBAAmB,EACnB,4BAA4B,EAC5B,8BAA8B,EAC9B,oBAAoB,EACpB,iCAAiC,EACjC,mCAAmC,EACnC,IAAI,EACJ,WAAW,EACX,sBAAsB,EACtB,4BAA4B,EAC5B,iBAAiB,EACjB,iBAAiB,EACjB,gBAAgB,EAChB,eAAe,EACf,eAAe,EACf,eAAe,EACf,YAAY,EACZ,mCAAmC,EACnC,MAAM,EACN,OAAO,EACP,MAAM,EACN,OAAO,EACP,IAAI,EACJ,KAAK,EACL,GAAG,EACH,IAAI,EACJ,6BAA6B,GAC9B,wBAAoB;AACrB,YAAY,EAAE,aAAa,EAAE,mBAAe;AAC5C,OAAO,EACL,OAAO,EACP,mBAAmB,EACnB,sBAAsB,EACtB,UAAU,EACV,OAAO,EACP,SAAS,EACT,cAAc,EACd,WAAW,EACX,OAAO,EACP,SAAS,EACT,SAAS,EACT,eAAe,EACf,aAAa,EACb,aAAa,EACb,gBAAgB,EAChB,mBAAmB,EACnB,WAAW,EACX,iBAAiB,EACjB,gBAAgB,EAChB,KAAK,EACL,aAAa,EACb,wBAAwB,EACxB,eAAe,EACf,YAAY,EACZ,oBAAoB,EACpB,KAAK,EACL,eAAe,EACf,sBAAsB,GACvB,mBAAe;AAChB,4BAAwB;AACxB,2BAAuB"}
1
+ {"version":3,"file":"index.d.cts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,kBAAkB,EAClB,YAAY,EACZ,eAAe,EACf,8BAA8B,EAC9B,0BAA0B,EAC1B,gCAAgC,EAChC,mBAAmB,EACnB,kBAAkB,EAClB,mBAAmB,EACnB,SAAS,EACT,UAAU,GACX,oCAAgC;AACjC,YAAY,EACV,cAAc,EACd,0BAA0B,EAC1B,aAAa,GACd,oCAAgC;AACjC,OAAO,EACL,GAAG,EACH,qBAAqB,EACrB,wBAAwB,EACxB,gBAAgB,EAChB,iBAAiB,EACjB,MAAM,EACN,OAAO,EACP,KAAK,EACL,mBAAmB,EACnB,4BAA4B,EAC5B,8BAA8B,EAC9B,oBAAoB,EACpB,iCAAiC,EACjC,mCAAmC,EACnC,IAAI,EACJ,WAAW,EACX,sBAAsB,EACtB,4BAA4B,EAC5B,iBAAiB,EACjB,iBAAiB,EACjB,gBAAgB,EAChB,eAAe,EACf,eAAe,EACf,eAAe,EACf,YAAY,EACZ,mCAAmC,EACnC,MAAM,EACN,OAAO,EACP,MAAM,EACN,OAAO,EACP,IAAI,EACJ,KAAK,EACL,GAAG,EACH,IAAI,EACJ,6BAA6B,GAC9B,wBAAoB;AACrB,YAAY,EAAE,aAAa,EAAE,mBAAe;AAC5C,OAAO,EACL,OAAO,EACP,mBAAmB,EACnB,sBAAsB,EACtB,UAAU,EACV,OAAO,EACP,SAAS,EACT,cAAc,EACd,WAAW,EACX,OAAO,EACP,SAAS,EACT,SAAS,EACT,eAAe,EACf,aAAa,EACb,aAAa,EACb,gBAAgB,EAChB,mBAAmB,EACnB,WAAW,EACX,iBAAiB,EACjB,gBAAgB,EAChB,KAAK,EACL,aAAa,EACb,wBAAwB,EACxB,eAAe,EACf,YAAY,EACZ,oBAAoB,EACpB,KAAK,EACL,eAAe,EACf,sBAAsB,GACvB,mBAAe;AAChB,4BAAwB;AACxB,2BAAuB"}
package/dist/index.d.mts CHANGED
@@ -1,5 +1,5 @@
1
- export { BrokenCircuitError, CircuitState, CockatielEventEmitter, ConstantBackoff, DEFAULT_CIRCUIT_BREAK_DURATION, DEFAULT_DEGRADED_THRESHOLD, DEFAULT_MAX_CONSECUTIVE_FAILURES, DEFAULT_MAX_RETRIES, ExponentialBackoff, createServicePolicy, handleAll, handleWhen, } from "./create-service-policy.mjs";
2
- export type { CockatielEvent, CreateServicePolicyOptions, CockatielFailureReason, ServicePolicy, } from "./create-service-policy.mjs";
1
+ export { BrokenCircuitError, CircuitState, ConstantBackoff, DEFAULT_CIRCUIT_BREAK_DURATION, DEFAULT_DEGRADED_THRESHOLD, DEFAULT_MAX_CONSECUTIVE_FAILURES, DEFAULT_MAX_RETRIES, ExponentialBackoff, createServicePolicy, handleAll, handleWhen, } from "./create-service-policy.mjs";
2
+ export type { CockatielEvent, CreateServicePolicyOptions, ServicePolicy, } from "./create-service-policy.mjs";
3
3
  export { RPC, FALL_BACK_VS_CURRENCY, IPFS_DEFAULT_GATEWAY_URL, GANACHE_CHAIN_ID, MAX_SAFE_CHAIN_ID, ERC721, ERC1155, ERC20, ERC721_INTERFACE_ID, ERC721_METADATA_INTERFACE_ID, ERC721_ENUMERABLE_INTERFACE_ID, ERC1155_INTERFACE_ID, ERC1155_METADATA_URI_INTERFACE_ID, ERC1155_TOKEN_RECEIVER_INTERFACE_ID, GWEI, ASSET_TYPES, TESTNET_TICKER_SYMBOLS, BUILT_IN_CUSTOM_NETWORKS_RPC, BUILT_IN_NETWORKS, OPENSEA_PROXY_URL, NFT_API_BASE_URL, NFT_API_VERSION, NFT_API_TIMEOUT, ORIGIN_METAMASK, ApprovalType, CHAIN_ID_TO_ETHERS_NETWORK_NAME_MAP, SECOND, SECONDS, MINUTE, MINUTES, HOUR, HOURS, DAY, DAYS, NETWORKS_BYPASSING_VALIDATION, } from "./constants.mjs";
4
4
  export type { NonEmptyArray } from "./util.mjs";
5
5
  export { BNToHex, convertHexToDecimal, fetchWithErrorHandling, fractionBN, fromHex, getBuyURL, gweiDecToWEIBN, handleFetch, hexToBN, hexToText, HttpError, isNonEmptyArray, isPlainObject, isSafeChainId, isSafeDynamicKey, isSmartContractCode, isValidJson, isValidHexAddress, normalizeEnsName, query, safelyExecute, safelyExecuteWithTimeout, successfulFetch, timeoutFetch, toChecksumHexAddress, toHex, weiHexToGweiDec, isEqualCaseInsensitive, } from "./util.mjs";
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.mts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,kBAAkB,EAClB,YAAY,EACZ,qBAAqB,EACrB,eAAe,EACf,8BAA8B,EAC9B,0BAA0B,EAC1B,gCAAgC,EAChC,mBAAmB,EACnB,kBAAkB,EAClB,mBAAmB,EACnB,SAAS,EACT,UAAU,GACX,oCAAgC;AACjC,YAAY,EACV,cAAc,EACd,0BAA0B,EAC1B,sBAAsB,EACtB,aAAa,GACd,oCAAgC;AACjC,OAAO,EACL,GAAG,EACH,qBAAqB,EACrB,wBAAwB,EACxB,gBAAgB,EAChB,iBAAiB,EACjB,MAAM,EACN,OAAO,EACP,KAAK,EACL,mBAAmB,EACnB,4BAA4B,EAC5B,8BAA8B,EAC9B,oBAAoB,EACpB,iCAAiC,EACjC,mCAAmC,EACnC,IAAI,EACJ,WAAW,EACX,sBAAsB,EACtB,4BAA4B,EAC5B,iBAAiB,EACjB,iBAAiB,EACjB,gBAAgB,EAChB,eAAe,EACf,eAAe,EACf,eAAe,EACf,YAAY,EACZ,mCAAmC,EACnC,MAAM,EACN,OAAO,EACP,MAAM,EACN,OAAO,EACP,IAAI,EACJ,KAAK,EACL,GAAG,EACH,IAAI,EACJ,6BAA6B,GAC9B,wBAAoB;AACrB,YAAY,EAAE,aAAa,EAAE,mBAAe;AAC5C,OAAO,EACL,OAAO,EACP,mBAAmB,EACnB,sBAAsB,EACtB,UAAU,EACV,OAAO,EACP,SAAS,EACT,cAAc,EACd,WAAW,EACX,OAAO,EACP,SAAS,EACT,SAAS,EACT,eAAe,EACf,aAAa,EACb,aAAa,EACb,gBAAgB,EAChB,mBAAmB,EACnB,WAAW,EACX,iBAAiB,EACjB,gBAAgB,EAChB,KAAK,EACL,aAAa,EACb,wBAAwB,EACxB,eAAe,EACf,YAAY,EACZ,oBAAoB,EACpB,KAAK,EACL,eAAe,EACf,sBAAsB,GACvB,mBAAe;AAChB,4BAAwB;AACxB,2BAAuB"}
1
+ {"version":3,"file":"index.d.mts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,kBAAkB,EAClB,YAAY,EACZ,eAAe,EACf,8BAA8B,EAC9B,0BAA0B,EAC1B,gCAAgC,EAChC,mBAAmB,EACnB,kBAAkB,EAClB,mBAAmB,EACnB,SAAS,EACT,UAAU,GACX,oCAAgC;AACjC,YAAY,EACV,cAAc,EACd,0BAA0B,EAC1B,aAAa,GACd,oCAAgC;AACjC,OAAO,EACL,GAAG,EACH,qBAAqB,EACrB,wBAAwB,EACxB,gBAAgB,EAChB,iBAAiB,EACjB,MAAM,EACN,OAAO,EACP,KAAK,EACL,mBAAmB,EACnB,4BAA4B,EAC5B,8BAA8B,EAC9B,oBAAoB,EACpB,iCAAiC,EACjC,mCAAmC,EACnC,IAAI,EACJ,WAAW,EACX,sBAAsB,EACtB,4BAA4B,EAC5B,iBAAiB,EACjB,iBAAiB,EACjB,gBAAgB,EAChB,eAAe,EACf,eAAe,EACf,eAAe,EACf,YAAY,EACZ,mCAAmC,EACnC,MAAM,EACN,OAAO,EACP,MAAM,EACN,OAAO,EACP,IAAI,EACJ,KAAK,EACL,GAAG,EACH,IAAI,EACJ,6BAA6B,GAC9B,wBAAoB;AACrB,YAAY,EAAE,aAAa,EAAE,mBAAe;AAC5C,OAAO,EACL,OAAO,EACP,mBAAmB,EACnB,sBAAsB,EACtB,UAAU,EACV,OAAO,EACP,SAAS,EACT,cAAc,EACd,WAAW,EACX,OAAO,EACP,SAAS,EACT,SAAS,EACT,eAAe,EACf,aAAa,EACb,aAAa,EACb,gBAAgB,EAChB,mBAAmB,EACnB,WAAW,EACX,iBAAiB,EACjB,gBAAgB,EAChB,KAAK,EACL,aAAa,EACb,wBAAwB,EACxB,eAAe,EACf,YAAY,EACZ,oBAAoB,EACpB,KAAK,EACL,eAAe,EACf,sBAAsB,GACvB,mBAAe;AAChB,4BAAwB;AACxB,2BAAuB"}
package/dist/index.mjs CHANGED
@@ -1,4 +1,4 @@
1
- export { BrokenCircuitError, CircuitState, CockatielEventEmitter, ConstantBackoff, DEFAULT_CIRCUIT_BREAK_DURATION, DEFAULT_DEGRADED_THRESHOLD, DEFAULT_MAX_CONSECUTIVE_FAILURES, DEFAULT_MAX_RETRIES, ExponentialBackoff, createServicePolicy, handleAll, handleWhen } from "./create-service-policy.mjs";
1
+ export { BrokenCircuitError, CircuitState, ConstantBackoff, DEFAULT_CIRCUIT_BREAK_DURATION, DEFAULT_DEGRADED_THRESHOLD, DEFAULT_MAX_CONSECUTIVE_FAILURES, DEFAULT_MAX_RETRIES, ExponentialBackoff, createServicePolicy, handleAll, handleWhen } from "./create-service-policy.mjs";
2
2
  export { RPC, FALL_BACK_VS_CURRENCY, IPFS_DEFAULT_GATEWAY_URL, GANACHE_CHAIN_ID, MAX_SAFE_CHAIN_ID, ERC721, ERC1155, ERC20, ERC721_INTERFACE_ID, ERC721_METADATA_INTERFACE_ID, ERC721_ENUMERABLE_INTERFACE_ID, ERC1155_INTERFACE_ID, ERC1155_METADATA_URI_INTERFACE_ID, ERC1155_TOKEN_RECEIVER_INTERFACE_ID, GWEI, ASSET_TYPES, TESTNET_TICKER_SYMBOLS, BUILT_IN_CUSTOM_NETWORKS_RPC, BUILT_IN_NETWORKS, OPENSEA_PROXY_URL, NFT_API_BASE_URL, NFT_API_VERSION, NFT_API_TIMEOUT, ORIGIN_METAMASK, ApprovalType, CHAIN_ID_TO_ETHERS_NETWORK_NAME_MAP, SECOND, SECONDS, MINUTE, MINUTES, HOUR, HOURS, DAY, DAYS, NETWORKS_BYPASSING_VALIDATION } from "./constants.mjs";
3
3
  export { BNToHex, convertHexToDecimal, fetchWithErrorHandling, fractionBN, fromHex, getBuyURL, gweiDecToWEIBN, handleFetch, hexToBN, hexToText, HttpError, isNonEmptyArray, isPlainObject, isSafeChainId, isSafeDynamicKey, isSmartContractCode, isValidJson, isValidHexAddress, normalizeEnsName, query, safelyExecute, safelyExecuteWithTimeout, successfulFetch, timeoutFetch, toChecksumHexAddress, toHex, weiHexToGweiDec, isEqualCaseInsensitive } from "./util.mjs";
4
4
  export * from "./types.mjs";
@@ -1 +1 @@
1
- {"version":3,"file":"index.mjs","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,kBAAkB,EAClB,YAAY,EACZ,qBAAqB,EACrB,eAAe,EACf,8BAA8B,EAC9B,0BAA0B,EAC1B,gCAAgC,EAChC,mBAAmB,EACnB,kBAAkB,EAClB,mBAAmB,EACnB,SAAS,EACT,UAAU,EACX,oCAAgC;AAOjC,OAAO,EACL,GAAG,EACH,qBAAqB,EACrB,wBAAwB,EACxB,gBAAgB,EAChB,iBAAiB,EACjB,MAAM,EACN,OAAO,EACP,KAAK,EACL,mBAAmB,EACnB,4BAA4B,EAC5B,8BAA8B,EAC9B,oBAAoB,EACpB,iCAAiC,EACjC,mCAAmC,EACnC,IAAI,EACJ,WAAW,EACX,sBAAsB,EACtB,4BAA4B,EAC5B,iBAAiB,EACjB,iBAAiB,EACjB,gBAAgB,EAChB,eAAe,EACf,eAAe,EACf,eAAe,EACf,YAAY,EACZ,mCAAmC,EACnC,MAAM,EACN,OAAO,EACP,MAAM,EACN,OAAO,EACP,IAAI,EACJ,KAAK,EACL,GAAG,EACH,IAAI,EACJ,6BAA6B,EAC9B,wBAAoB;AAErB,OAAO,EACL,OAAO,EACP,mBAAmB,EACnB,sBAAsB,EACtB,UAAU,EACV,OAAO,EACP,SAAS,EACT,cAAc,EACd,WAAW,EACX,OAAO,EACP,SAAS,EACT,SAAS,EACT,eAAe,EACf,aAAa,EACb,aAAa,EACb,gBAAgB,EAChB,mBAAmB,EACnB,WAAW,EACX,iBAAiB,EACjB,gBAAgB,EAChB,KAAK,EACL,aAAa,EACb,wBAAwB,EACxB,eAAe,EACf,YAAY,EACZ,oBAAoB,EACpB,KAAK,EACL,eAAe,EACf,sBAAsB,EACvB,mBAAe;AAChB,4BAAwB;AACxB,2BAAuB","sourcesContent":["export {\n BrokenCircuitError,\n CircuitState,\n CockatielEventEmitter,\n ConstantBackoff,\n DEFAULT_CIRCUIT_BREAK_DURATION,\n DEFAULT_DEGRADED_THRESHOLD,\n DEFAULT_MAX_CONSECUTIVE_FAILURES,\n DEFAULT_MAX_RETRIES,\n ExponentialBackoff,\n createServicePolicy,\n handleAll,\n handleWhen,\n} from './create-service-policy';\nexport type {\n CockatielEvent,\n CreateServicePolicyOptions,\n CockatielFailureReason,\n ServicePolicy,\n} from './create-service-policy';\nexport {\n RPC,\n FALL_BACK_VS_CURRENCY,\n IPFS_DEFAULT_GATEWAY_URL,\n GANACHE_CHAIN_ID,\n MAX_SAFE_CHAIN_ID,\n ERC721,\n ERC1155,\n ERC20,\n ERC721_INTERFACE_ID,\n ERC721_METADATA_INTERFACE_ID,\n ERC721_ENUMERABLE_INTERFACE_ID,\n ERC1155_INTERFACE_ID,\n ERC1155_METADATA_URI_INTERFACE_ID,\n ERC1155_TOKEN_RECEIVER_INTERFACE_ID,\n GWEI,\n ASSET_TYPES,\n TESTNET_TICKER_SYMBOLS,\n BUILT_IN_CUSTOM_NETWORKS_RPC,\n BUILT_IN_NETWORKS,\n OPENSEA_PROXY_URL,\n NFT_API_BASE_URL,\n NFT_API_VERSION,\n NFT_API_TIMEOUT,\n ORIGIN_METAMASK,\n ApprovalType,\n CHAIN_ID_TO_ETHERS_NETWORK_NAME_MAP,\n SECOND,\n SECONDS,\n MINUTE,\n MINUTES,\n HOUR,\n HOURS,\n DAY,\n DAYS,\n NETWORKS_BYPASSING_VALIDATION,\n} from './constants';\nexport type { NonEmptyArray } from './util';\nexport {\n BNToHex,\n convertHexToDecimal,\n fetchWithErrorHandling,\n fractionBN,\n fromHex,\n getBuyURL,\n gweiDecToWEIBN,\n handleFetch,\n hexToBN,\n hexToText,\n HttpError,\n isNonEmptyArray,\n isPlainObject,\n isSafeChainId,\n isSafeDynamicKey,\n isSmartContractCode,\n isValidJson,\n isValidHexAddress,\n normalizeEnsName,\n query,\n safelyExecute,\n safelyExecuteWithTimeout,\n successfulFetch,\n timeoutFetch,\n toChecksumHexAddress,\n toHex,\n weiHexToGweiDec,\n isEqualCaseInsensitive,\n} from './util';\nexport * from './types';\nexport * from './siwe';\n"]}
1
+ {"version":3,"file":"index.mjs","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,kBAAkB,EAClB,YAAY,EACZ,eAAe,EACf,8BAA8B,EAC9B,0BAA0B,EAC1B,gCAAgC,EAChC,mBAAmB,EACnB,kBAAkB,EAClB,mBAAmB,EACnB,SAAS,EACT,UAAU,EACX,oCAAgC;AAMjC,OAAO,EACL,GAAG,EACH,qBAAqB,EACrB,wBAAwB,EACxB,gBAAgB,EAChB,iBAAiB,EACjB,MAAM,EACN,OAAO,EACP,KAAK,EACL,mBAAmB,EACnB,4BAA4B,EAC5B,8BAA8B,EAC9B,oBAAoB,EACpB,iCAAiC,EACjC,mCAAmC,EACnC,IAAI,EACJ,WAAW,EACX,sBAAsB,EACtB,4BAA4B,EAC5B,iBAAiB,EACjB,iBAAiB,EACjB,gBAAgB,EAChB,eAAe,EACf,eAAe,EACf,eAAe,EACf,YAAY,EACZ,mCAAmC,EACnC,MAAM,EACN,OAAO,EACP,MAAM,EACN,OAAO,EACP,IAAI,EACJ,KAAK,EACL,GAAG,EACH,IAAI,EACJ,6BAA6B,EAC9B,wBAAoB;AAErB,OAAO,EACL,OAAO,EACP,mBAAmB,EACnB,sBAAsB,EACtB,UAAU,EACV,OAAO,EACP,SAAS,EACT,cAAc,EACd,WAAW,EACX,OAAO,EACP,SAAS,EACT,SAAS,EACT,eAAe,EACf,aAAa,EACb,aAAa,EACb,gBAAgB,EAChB,mBAAmB,EACnB,WAAW,EACX,iBAAiB,EACjB,gBAAgB,EAChB,KAAK,EACL,aAAa,EACb,wBAAwB,EACxB,eAAe,EACf,YAAY,EACZ,oBAAoB,EACpB,KAAK,EACL,eAAe,EACf,sBAAsB,EACvB,mBAAe;AAChB,4BAAwB;AACxB,2BAAuB","sourcesContent":["export {\n BrokenCircuitError,\n CircuitState,\n ConstantBackoff,\n DEFAULT_CIRCUIT_BREAK_DURATION,\n DEFAULT_DEGRADED_THRESHOLD,\n DEFAULT_MAX_CONSECUTIVE_FAILURES,\n DEFAULT_MAX_RETRIES,\n ExponentialBackoff,\n createServicePolicy,\n handleAll,\n handleWhen,\n} from './create-service-policy';\nexport type {\n CockatielEvent,\n CreateServicePolicyOptions,\n ServicePolicy,\n} from './create-service-policy';\nexport {\n RPC,\n FALL_BACK_VS_CURRENCY,\n IPFS_DEFAULT_GATEWAY_URL,\n GANACHE_CHAIN_ID,\n MAX_SAFE_CHAIN_ID,\n ERC721,\n ERC1155,\n ERC20,\n ERC721_INTERFACE_ID,\n ERC721_METADATA_INTERFACE_ID,\n ERC721_ENUMERABLE_INTERFACE_ID,\n ERC1155_INTERFACE_ID,\n ERC1155_METADATA_URI_INTERFACE_ID,\n ERC1155_TOKEN_RECEIVER_INTERFACE_ID,\n GWEI,\n ASSET_TYPES,\n TESTNET_TICKER_SYMBOLS,\n BUILT_IN_CUSTOM_NETWORKS_RPC,\n BUILT_IN_NETWORKS,\n OPENSEA_PROXY_URL,\n NFT_API_BASE_URL,\n NFT_API_VERSION,\n NFT_API_TIMEOUT,\n ORIGIN_METAMASK,\n ApprovalType,\n CHAIN_ID_TO_ETHERS_NETWORK_NAME_MAP,\n SECOND,\n SECONDS,\n MINUTE,\n MINUTES,\n HOUR,\n HOURS,\n DAY,\n DAYS,\n NETWORKS_BYPASSING_VALIDATION,\n} from './constants';\nexport type { NonEmptyArray } from './util';\nexport {\n BNToHex,\n convertHexToDecimal,\n fetchWithErrorHandling,\n fractionBN,\n fromHex,\n getBuyURL,\n gweiDecToWEIBN,\n handleFetch,\n hexToBN,\n hexToText,\n HttpError,\n isNonEmptyArray,\n isPlainObject,\n isSafeChainId,\n isSafeDynamicKey,\n isSmartContractCode,\n isValidJson,\n isValidHexAddress,\n normalizeEnsName,\n query,\n safelyExecute,\n safelyExecuteWithTimeout,\n successfulFetch,\n timeoutFetch,\n toChecksumHexAddress,\n toHex,\n weiHexToGweiDec,\n isEqualCaseInsensitive,\n} from './util';\nexport * from './types';\nexport * from './siwe';\n"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@metamask-previews/controller-utils",
3
- "version": "11.15.0-preview-96f3a4d7",
3
+ "version": "11.15.0-preview-e493d3e8",
4
4
  "description": "Data and convenience functions shared by multiple packages",
5
5
  "keywords": [
6
6
  "MetaMask",