@metamask-previews/base-data-service 1.0.0-preview-8bfa290fb → 2.0.0-preview-0a30e47

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.
Files changed (53) hide show
  1. package/CHANGELOG.md +10 -8
  2. package/dist/{BaseDataService.d.mts → BaseDataService.d.ts} +10 -41
  3. package/dist/BaseDataService.d.ts.map +1 -0
  4. package/dist/BaseDataService.js +212 -0
  5. package/dist/BaseDataService.js.map +1 -0
  6. package/dist/{createServicePolicy.d.mts → createServicePolicy.d.ts} +3 -3
  7. package/dist/createServicePolicy.d.ts.map +1 -0
  8. package/dist/{createServicePolicy.mjs → createServicePolicy.js} +3 -3
  9. package/dist/createServicePolicy.js.map +1 -0
  10. package/dist/{index.d.cts → index.d.ts} +7 -7
  11. package/dist/index.d.ts.map +1 -0
  12. package/dist/{index.mjs → index.js} +4 -4
  13. package/dist/index.js.map +1 -0
  14. package/dist/utils.d.ts +13 -0
  15. package/dist/utils.d.ts.map +1 -0
  16. package/dist/utils.js +21 -0
  17. package/dist/utils.js.map +1 -0
  18. package/package.json +16 -20
  19. package/dist/BaseDataService.cjs +0 -300
  20. package/dist/BaseDataService.cjs.map +0 -1
  21. package/dist/BaseDataService.d.cts +0 -146
  22. package/dist/BaseDataService.d.cts.map +0 -1
  23. package/dist/BaseDataService.d.mts.map +0 -1
  24. package/dist/BaseDataService.mjs +0 -301
  25. package/dist/BaseDataService.mjs.map +0 -1
  26. package/dist/createServicePolicy.cjs +0 -228
  27. package/dist/createServicePolicy.cjs.map +0 -1
  28. package/dist/createServicePolicy.d.cts +0 -179
  29. package/dist/createServicePolicy.d.cts.map +0 -1
  30. package/dist/createServicePolicy.d.mts.map +0 -1
  31. package/dist/createServicePolicy.mjs.map +0 -1
  32. package/dist/index.cjs +0 -20
  33. package/dist/index.cjs.map +0 -1
  34. package/dist/index.d.cts.map +0 -1
  35. package/dist/index.d.mts +0 -7
  36. package/dist/index.d.mts.map +0 -1
  37. package/dist/index.mjs.map +0 -1
  38. package/dist/loggers.cjs +0 -7
  39. package/dist/loggers.cjs.map +0 -1
  40. package/dist/loggers.d.cts +0 -5
  41. package/dist/loggers.d.cts.map +0 -1
  42. package/dist/loggers.d.mts +0 -5
  43. package/dist/loggers.d.mts.map +0 -1
  44. package/dist/loggers.mjs +0 -4
  45. package/dist/loggers.mjs.map +0 -1
  46. package/dist/utils.cjs +0 -56
  47. package/dist/utils.cjs.map +0 -1
  48. package/dist/utils.d.cts +0 -26
  49. package/dist/utils.d.cts.map +0 -1
  50. package/dist/utils.d.mts +0 -26
  51. package/dist/utils.d.mts.map +0 -1
  52. package/dist/utils.mjs +0 -51
  53. package/dist/utils.mjs.map +0 -1
@@ -1,179 +0,0 @@
1
- import { CircuitState } from "cockatiel";
2
- import type { CircuitBreakerPolicy, Event as CockatielEvent, FailureReason, IBackoffFactory, IPolicy, Policy, RetryPolicy } from "cockatiel";
3
- /**
4
- * The options for `createServicePolicy`.
5
- */
6
- export type CreateServicePolicyOptions = {
7
- /**
8
- * The backoff strategy to use. Mainly useful for testing so that a constant
9
- * backoff can be used when mocking timers. Defaults to an instance of
10
- * ExponentialBackoff.
11
- */
12
- backoff?: IBackoffFactory<unknown>;
13
- /**
14
- * The length of time (in milliseconds) to pause retries of the action after
15
- * the number of failures reaches `maxConsecutiveFailures`.
16
- */
17
- circuitBreakDuration?: number;
18
- /**
19
- * The length of time (in milliseconds) that governs when the service is
20
- * regarded as degraded (affecting when `onDegraded` is called).
21
- */
22
- degradedThreshold?: number;
23
- /**
24
- * Predicate function for when an error should be considered a service failure.
25
- */
26
- isServiceFailure?: (error: unknown) => boolean;
27
- /**
28
- * The maximum number of times that the service is allowed to fail before
29
- * pausing further retries.
30
- */
31
- maxConsecutiveFailures?: number;
32
- /**
33
- * The maximum number of times that a failing service should be re-invoked
34
- * before giving up.
35
- */
36
- maxRetries?: number;
37
- /**
38
- * The policy used to control when the service should be retried based on
39
- * either the result of the service or an error that it throws. For instance,
40
- * you could use this to retry only certain errors. See `handleWhen` and
41
- * friends from Cockatiel for more.
42
- */
43
- retryFilterPolicy?: Policy;
44
- };
45
- /**
46
- * The service policy object.
47
- */
48
- export type ServicePolicy = IPolicy & {
49
- /**
50
- * The Cockatiel circuit breaker policy that the service policy uses
51
- * internally.
52
- */
53
- circuitBreakerPolicy: CircuitBreakerPolicy;
54
- /**
55
- * The amount of time to pause requests to the service if the number of
56
- * maximum consecutive failures is reached.
57
- */
58
- circuitBreakDuration: number;
59
- /**
60
- * @returns The state of the underlying circuit.
61
- */
62
- getCircuitState: () => CircuitState;
63
- /**
64
- * If the circuit is open and ongoing requests are paused, returns the number
65
- * of milliseconds before the requests will be attempted again. If the circuit
66
- * is not open, returns null.
67
- */
68
- getRemainingCircuitOpenDuration: () => number | null;
69
- /**
70
- * Resets the internal circuit breaker policy (if it is open, it will now be
71
- * closed).
72
- */
73
- reset: () => void;
74
- /**
75
- * The Cockatiel retry policy that the service policy uses internally.
76
- */
77
- retryPolicy: RetryPolicy;
78
- /**
79
- * A function which is called when the number of times that the service fails
80
- * in a row meets the set maximum number of consecutive failures.
81
- */
82
- onBreak: CircuitBreakerPolicy['onBreak'];
83
- /**
84
- * A function which is called in two circumstances: 1) when the service
85
- * succeeds before the maximum number of consecutive failures is reached, but
86
- * takes more time than the `degradedThreshold` to run, or 2) if the service
87
- * never succeeds before the retry policy gives up and before the maximum
88
- * number of consecutive failures has been reached.
89
- */
90
- onDegraded: CockatielEvent<FailureReason<unknown> | {
91
- duration: number;
92
- }>;
93
- /**
94
- * A function which is called when the service succeeds for the first time,
95
- * or when the service fails enough times to cause the circuit to break and
96
- * then recovers.
97
- */
98
- onAvailable: CockatielEvent<void>;
99
- /**
100
- * A function which will be called by the retry policy each time the service
101
- * fails and the policy kicks off a timer to re-run the service. This is
102
- * primarily useful in tests where we are mocking timers.
103
- */
104
- onRetry: RetryPolicy['onRetry'];
105
- };
106
- /**
107
- * The maximum number of times that a failing service should be re-run before
108
- * giving up.
109
- */
110
- export declare const DEFAULT_MAX_RETRIES = 3;
111
- /**
112
- * The maximum number of times that the service is allowed to fail before
113
- * pausing further retries. This is set to a value such that if given a
114
- * service that continually fails, the policy needs to be executed 3 times
115
- * before further retries are paused.
116
- */
117
- export declare const DEFAULT_MAX_CONSECUTIVE_FAILURES: number;
118
- /**
119
- * The default length of time (in milliseconds) to temporarily pause retries of
120
- * the service after enough consecutive failures.
121
- */
122
- export declare const DEFAULT_CIRCUIT_BREAK_DURATION: number;
123
- /**
124
- * The default length of time (in milliseconds) that governs when the service is
125
- * regarded as degraded (affecting when `onDegraded` is called).
126
- */
127
- export declare const DEFAULT_DEGRADED_THRESHOLD = 5000;
128
- /**
129
- * Constructs an object exposing an `execute` method which, given a function —
130
- * hereafter called the "service" — will retry that service with ever increasing
131
- * delays until it succeeds. If the policy detects too many consecutive
132
- * failures, it will block further retries until a designated time period has
133
- * passed; this particular behavior is primarily designed for services that wrap
134
- * API calls so as not to make needless HTTP requests when the API is down and
135
- * to be able to recover when the API comes back up. In addition, hooks allow
136
- * for responding to certain events, one of which can be used to detect when an
137
- * HTTP request is performing slowly.
138
- *
139
- * Internally, this function makes use of the retry and circuit breaker policies
140
- * from the [Cockatiel](https://www.npmjs.com/package/cockatiel) library; see
141
- * there for more.
142
- *
143
- * @param options - The options to this function. See
144
- * {@link CreateServicePolicyOptions}.
145
- * @returns The service policy.
146
- * @example
147
- * This function is designed to be used in the context of a service class like
148
- * this:
149
- * ``` ts
150
- * class Service {
151
- * constructor() {
152
- * this.#policy = createServicePolicy({
153
- * maxRetries: 3,
154
- * retryFilterPolicy: handleWhen((error) => {
155
- * return error.message.includes('oops');
156
- * }),
157
- * maxConsecutiveFailures: 3,
158
- * circuitBreakDuration: 5000,
159
- * degradedThreshold: 2000,
160
- * onBreak: () => {
161
- * console.log('Circuit broke');
162
- * },
163
- * onDegraded: () => {
164
- * console.log('Service is degraded');
165
- * },
166
- * });
167
- * }
168
- *
169
- * async fetch() {
170
- * return await this.#policy.execute(async () => {
171
- * const response = await fetch('https://some/url');
172
- * return await response.json();
173
- * });
174
- * }
175
- * }
176
- * ```
177
- */
178
- export declare function createServicePolicy(options?: CreateServicePolicyOptions): ServicePolicy;
179
- //# sourceMappingURL=createServicePolicy.d.cts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"createServicePolicy.d.cts","sourceRoot":"","sources":["../src/createServicePolicy.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,YAAY,EASb,kBAAkB;AACnB,OAAO,KAAK,EACV,oBAAoB,EACpB,KAAK,IAAI,cAAc,EACvB,aAAa,EACb,eAAe,EACf,OAAO,EACP,MAAM,EACN,WAAW,EACZ,kBAAkB;AAEnB;;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;;OAEG;IACH,gBAAgB,CAAC,EAAE,CAAC,KAAK,EAAE,OAAO,KAAK,OAAO,CAAC;IAC/C;;;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,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;IACX,EAAE;IACF,2BAA2B;IAC3B,kCAAkC;IAClC,OAAO;IACP,EAAE;IACF,oBAAoB;IACpB,EAAE;IACF,gCAAgC;IAChC,2CAA2C;IAC3C,oCAAoC;IACpC,UAAU;IACV,QAAQ;IACR,EAAE;IACF,8EAA8E;IAC9E,8EAA8E;IAC9E,6EAA6E;IAC7E,qCAAqC;IACrC,MAAM,MAAM,GAAG,IAAI,CAAC,WAAW,EAAE,oBAAoB,CAAC,CAAC;IAEvD,MAAM,+BAA+B,GAAG,GAAkB,EAAE;QAC1D,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,MAAM,eAAe,GAAG,GAAiB,EAAE;QACzC,OAAO,oBAAoB,CAAC,KAAK,CAAC;IACpC,CAAC,CAAC;IAEF,MAAM,KAAK,GAAG,GAAS,EAAE;QACvB,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 CircuitState,\n EventEmitter as CockatielEventEmitter,\n ConsecutiveBreaker,\n ExponentialBackoff,\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\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 * Predicate function for when an error should be considered a service failure.\n */\n isServiceFailure?: (error: unknown) => boolean;\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> | { duration: number }>;\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 defaultIsServiceFailure = (error: unknown): boolean => {\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 httpStatus\n // property, consider it a service failure (e.g., network errors, timeouts,\n // 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 isServiceFailure = defaultIsServiceFailure,\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 = new CockatielEventEmitter<\n FailureReason<unknown> | { duration: number }\n >();\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({ duration });\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 = (): number | null => {\n if (internalCircuitState.state === CircuitState.Open) {\n return internalCircuitState.openedAt + circuitBreakDuration - Date.now();\n }\n return null;\n };\n\n const getCircuitState = (): CircuitState => {\n return circuitBreakerPolicy.state;\n };\n\n const reset = (): void => {\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"]}
package/dist/index.cjs DELETED
@@ -1,20 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.createServicePolicy = exports.DEFAULT_MAX_RETRIES = exports.DEFAULT_MAX_CONSECUTIVE_FAILURES = exports.DEFAULT_DEGRADED_THRESHOLD = exports.DEFAULT_CIRCUIT_BREAK_DURATION = exports.BaseDataService = exports.handleWhen = exports.handleAll = exports.ExponentialBackoff = exports.ConstantBackoff = exports.CircuitState = exports.CockatielEventEmitter = exports.BrokenCircuitError = void 0;
4
- var cockatiel_1 = require("cockatiel");
5
- Object.defineProperty(exports, "BrokenCircuitError", { enumerable: true, get: function () { return cockatiel_1.BrokenCircuitError; } });
6
- Object.defineProperty(exports, "CockatielEventEmitter", { enumerable: true, get: function () { return cockatiel_1.EventEmitter; } });
7
- Object.defineProperty(exports, "CircuitState", { enumerable: true, get: function () { return cockatiel_1.CircuitState; } });
8
- Object.defineProperty(exports, "ConstantBackoff", { enumerable: true, get: function () { return cockatiel_1.ConstantBackoff; } });
9
- Object.defineProperty(exports, "ExponentialBackoff", { enumerable: true, get: function () { return cockatiel_1.ExponentialBackoff; } });
10
- Object.defineProperty(exports, "handleAll", { enumerable: true, get: function () { return cockatiel_1.handleAll; } });
11
- Object.defineProperty(exports, "handleWhen", { enumerable: true, get: function () { return cockatiel_1.handleWhen; } });
12
- var BaseDataService_js_1 = require("./BaseDataService.cjs");
13
- Object.defineProperty(exports, "BaseDataService", { enumerable: true, get: function () { return BaseDataService_js_1.BaseDataService; } });
14
- var createServicePolicy_js_1 = require("./createServicePolicy.cjs");
15
- Object.defineProperty(exports, "DEFAULT_CIRCUIT_BREAK_DURATION", { enumerable: true, get: function () { return createServicePolicy_js_1.DEFAULT_CIRCUIT_BREAK_DURATION; } });
16
- Object.defineProperty(exports, "DEFAULT_DEGRADED_THRESHOLD", { enumerable: true, get: function () { return createServicePolicy_js_1.DEFAULT_DEGRADED_THRESHOLD; } });
17
- Object.defineProperty(exports, "DEFAULT_MAX_CONSECUTIVE_FAILURES", { enumerable: true, get: function () { return createServicePolicy_js_1.DEFAULT_MAX_CONSECUTIVE_FAILURES; } });
18
- Object.defineProperty(exports, "DEFAULT_MAX_RETRIES", { enumerable: true, get: function () { return createServicePolicy_js_1.DEFAULT_MAX_RETRIES; } });
19
- Object.defineProperty(exports, "createServicePolicy", { enumerable: true, get: function () { return createServicePolicy_js_1.createServicePolicy; } });
20
- //# sourceMappingURL=index.cjs.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"index.cjs","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":";;;AAKA,uCAQmB;AAPjB,+GAAA,kBAAkB,OAAA;AAClB,kHAAA,YAAY,OAAyB;AACrC,yGAAA,YAAY,OAAA;AACZ,4GAAA,eAAe,OAAA;AACf,+GAAA,kBAAkB,OAAA;AAClB,sGAAA,SAAS,OAAA;AACT,uGAAA,UAAU,OAAA;AAeZ,4DAAuD;AAA9C,qHAAA,eAAe,OAAA;AAExB,oEAMkC;AALhC,wIAAA,8BAA8B,OAAA;AAC9B,oIAAA,0BAA0B,OAAA;AAC1B,0IAAA,gCAAgC,OAAA;AAChC,6HAAA,mBAAmB,OAAA;AACnB,6HAAA,mBAAmB,OAAA","sourcesContent":["export type {\n Event as CockatielEvent,\n FailureReason as CockatielFailureReason,\n} from 'cockatiel';\n\nexport {\n BrokenCircuitError,\n EventEmitter as CockatielEventEmitter,\n CircuitState,\n ConstantBackoff,\n ExponentialBackoff,\n handleAll,\n handleWhen,\n} from 'cockatiel';\n\nexport type {\n DataServiceActions,\n DataServiceEvents,\n DataServiceCacheUpdatedPayload,\n DataServiceGranularCacheUpdatedPayload,\n DataServiceInvalidateQueriesAction,\n DataServiceCacheUpdatedEvent,\n DataServiceGranularCacheUpdatedEvent,\n QueryKey,\n MutationKey,\n PersistenceConfiguration,\n} from './BaseDataService.js';\nexport { BaseDataService } from './BaseDataService.js';\n\nexport {\n DEFAULT_CIRCUIT_BREAK_DURATION,\n DEFAULT_DEGRADED_THRESHOLD,\n DEFAULT_MAX_CONSECUTIVE_FAILURES,\n DEFAULT_MAX_RETRIES,\n createServicePolicy,\n} from './createServicePolicy.js';\nexport type {\n CreateServicePolicyOptions,\n ServicePolicy,\n} from './createServicePolicy.js';\n"]}
@@ -1 +0,0 @@
1
- {"version":3,"file":"index.d.cts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,YAAY,EACV,KAAK,IAAI,cAAc,EACvB,aAAa,IAAI,sBAAsB,GACxC,kBAAkB;AAEnB,OAAO,EACL,kBAAkB,EAClB,YAAY,IAAI,qBAAqB,EACrC,YAAY,EACZ,eAAe,EACf,kBAAkB,EAClB,SAAS,EACT,UAAU,GACX,kBAAkB;AAEnB,YAAY,EACV,kBAAkB,EAClB,iBAAiB,EACjB,8BAA8B,EAC9B,sCAAsC,EACtC,kCAAkC,EAClC,4BAA4B,EAC5B,oCAAoC,EACpC,QAAQ,EACR,WAAW,EACX,wBAAwB,GACzB,8BAA6B;AAC9B,OAAO,EAAE,eAAe,EAAE,8BAA6B;AAEvD,OAAO,EACL,8BAA8B,EAC9B,0BAA0B,EAC1B,gCAAgC,EAChC,mBAAmB,EACnB,mBAAmB,GACpB,kCAAiC;AAClC,YAAY,EACV,0BAA0B,EAC1B,aAAa,GACd,kCAAiC"}
package/dist/index.d.mts DELETED
@@ -1,7 +0,0 @@
1
- export type { Event as CockatielEvent, FailureReason as CockatielFailureReason, } from "cockatiel";
2
- export { BrokenCircuitError, EventEmitter as CockatielEventEmitter, CircuitState, ConstantBackoff, ExponentialBackoff, handleAll, handleWhen, } from "cockatiel";
3
- export type { DataServiceActions, DataServiceEvents, DataServiceCacheUpdatedPayload, DataServiceGranularCacheUpdatedPayload, DataServiceInvalidateQueriesAction, DataServiceCacheUpdatedEvent, DataServiceGranularCacheUpdatedEvent, QueryKey, MutationKey, PersistenceConfiguration, } from "./BaseDataService.mjs";
4
- export { BaseDataService } from "./BaseDataService.mjs";
5
- export { DEFAULT_CIRCUIT_BREAK_DURATION, DEFAULT_DEGRADED_THRESHOLD, DEFAULT_MAX_CONSECUTIVE_FAILURES, DEFAULT_MAX_RETRIES, createServicePolicy, } from "./createServicePolicy.mjs";
6
- export type { CreateServicePolicyOptions, ServicePolicy, } from "./createServicePolicy.mjs";
7
- //# sourceMappingURL=index.d.mts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"index.d.mts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,YAAY,EACV,KAAK,IAAI,cAAc,EACvB,aAAa,IAAI,sBAAsB,GACxC,kBAAkB;AAEnB,OAAO,EACL,kBAAkB,EAClB,YAAY,IAAI,qBAAqB,EACrC,YAAY,EACZ,eAAe,EACf,kBAAkB,EAClB,SAAS,EACT,UAAU,GACX,kBAAkB;AAEnB,YAAY,EACV,kBAAkB,EAClB,iBAAiB,EACjB,8BAA8B,EAC9B,sCAAsC,EACtC,kCAAkC,EAClC,4BAA4B,EAC5B,oCAAoC,EACpC,QAAQ,EACR,WAAW,EACX,wBAAwB,GACzB,8BAA6B;AAC9B,OAAO,EAAE,eAAe,EAAE,8BAA6B;AAEvD,OAAO,EACL,8BAA8B,EAC9B,0BAA0B,EAC1B,gCAAgC,EAChC,mBAAmB,EACnB,mBAAmB,GACpB,kCAAiC;AAClC,YAAY,EACV,0BAA0B,EAC1B,aAAa,GACd,kCAAiC"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"index.mjs","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAKA,OAAO,EACL,kBAAkB,EAClB,YAAY,IAAI,qBAAqB,EACrC,YAAY,EACZ,eAAe,EACf,kBAAkB,EAClB,SAAS,EACT,UAAU,EACX,kBAAkB;AAcnB,OAAO,EAAE,eAAe,EAAE,8BAA6B;AAEvD,OAAO,EACL,8BAA8B,EAC9B,0BAA0B,EAC1B,gCAAgC,EAChC,mBAAmB,EACnB,mBAAmB,EACpB,kCAAiC","sourcesContent":["export type {\n Event as CockatielEvent,\n FailureReason as CockatielFailureReason,\n} from 'cockatiel';\n\nexport {\n BrokenCircuitError,\n EventEmitter as CockatielEventEmitter,\n CircuitState,\n ConstantBackoff,\n ExponentialBackoff,\n handleAll,\n handleWhen,\n} from 'cockatiel';\n\nexport type {\n DataServiceActions,\n DataServiceEvents,\n DataServiceCacheUpdatedPayload,\n DataServiceGranularCacheUpdatedPayload,\n DataServiceInvalidateQueriesAction,\n DataServiceCacheUpdatedEvent,\n DataServiceGranularCacheUpdatedEvent,\n QueryKey,\n MutationKey,\n PersistenceConfiguration,\n} from './BaseDataService.js';\nexport { BaseDataService } from './BaseDataService.js';\n\nexport {\n DEFAULT_CIRCUIT_BREAK_DURATION,\n DEFAULT_DEGRADED_THRESHOLD,\n DEFAULT_MAX_CONSECUTIVE_FAILURES,\n DEFAULT_MAX_RETRIES,\n createServicePolicy,\n} from './createServicePolicy.js';\nexport type {\n CreateServicePolicyOptions,\n ServicePolicy,\n} from './createServicePolicy.js';\n"]}
package/dist/loggers.cjs DELETED
@@ -1,7 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.createModuleLogger = exports.projectLogger = void 0;
4
- const utils_1 = require("@metamask/utils");
5
- Object.defineProperty(exports, "createModuleLogger", { enumerable: true, get: function () { return utils_1.createModuleLogger; } });
6
- exports.projectLogger = (0, utils_1.createProjectLogger)('base-data-service');
7
- //# sourceMappingURL=loggers.cjs.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"loggers.cjs","sourceRoot":"","sources":["../src/loggers.ts"],"names":[],"mappings":";;;AAAA,2CAA0E;AAIjE,mGAJqB,0BAAkB,OAIrB;AAFd,QAAA,aAAa,GAAG,IAAA,2BAAmB,EAAC,mBAAmB,CAAC,CAAC","sourcesContent":["import { createProjectLogger, createModuleLogger } from '@metamask/utils';\n\nexport const projectLogger = createProjectLogger('base-data-service');\n\nexport { createModuleLogger };\n"]}
@@ -1,5 +0,0 @@
1
- /// <reference types="debug" />
2
- import { createModuleLogger } from "@metamask/utils";
3
- export declare const projectLogger: import("debug").Debugger;
4
- export { createModuleLogger };
5
- //# sourceMappingURL=loggers.d.cts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"loggers.d.cts","sourceRoot":"","sources":["../src/loggers.ts"],"names":[],"mappings":";AAAA,OAAO,EAAuB,kBAAkB,EAAE,wBAAwB;AAE1E,eAAO,MAAM,aAAa,0BAA2C,CAAC;AAEtE,OAAO,EAAE,kBAAkB,EAAE,CAAC"}
@@ -1,5 +0,0 @@
1
- /// <reference types="debug" />
2
- import { createModuleLogger } from "@metamask/utils";
3
- export declare const projectLogger: import("debug").Debugger;
4
- export { createModuleLogger };
5
- //# sourceMappingURL=loggers.d.mts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"loggers.d.mts","sourceRoot":"","sources":["../src/loggers.ts"],"names":[],"mappings":";AAAA,OAAO,EAAuB,kBAAkB,EAAE,wBAAwB;AAE1E,eAAO,MAAM,aAAa,0BAA2C,CAAC;AAEtE,OAAO,EAAE,kBAAkB,EAAE,CAAC"}
package/dist/loggers.mjs DELETED
@@ -1,4 +0,0 @@
1
- import { createProjectLogger, createModuleLogger } from "@metamask/utils";
2
- export const projectLogger = createProjectLogger('base-data-service');
3
- export { createModuleLogger };
4
- //# sourceMappingURL=loggers.mjs.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"loggers.mjs","sourceRoot":"","sources":["../src/loggers.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,mBAAmB,EAAE,kBAAkB,EAAE,wBAAwB;AAE1E,MAAM,CAAC,MAAM,aAAa,GAAG,mBAAmB,CAAC,mBAAmB,CAAC,CAAC;AAEtE,OAAO,EAAE,kBAAkB,EAAE,CAAC","sourcesContent":["import { createProjectLogger, createModuleLogger } from '@metamask/utils';\n\nexport const projectLogger = createProjectLogger('base-data-service');\n\nexport { createModuleLogger };\n"]}
package/dist/utils.cjs DELETED
@@ -1,56 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.processMutationResponse = exports.processQueryResponse = void 0;
4
- const superstruct_1 = require("@metamask/superstruct");
5
- /**
6
- * Process query responses, validating them using Superstruct if a struct is defined.
7
- *
8
- * @param queryKey - The query key.
9
- * @param response - The query response
10
- * @param struct - The struct defining the schema for the query response.
11
- * @returns The query response, coerced by Superstruct if needed.
12
- * @throws If the query response does not match the struct.
13
- */
14
- function processQueryResponse(queryKey, response, struct) {
15
- if (!struct) {
16
- return response;
17
- }
18
- const [error, result] = (0, superstruct_1.validate)(response, struct);
19
- if (error) {
20
- throw new Error(`Query function for "${queryKey[0]}" returned an unexpected response: ${error.message}.`);
21
- }
22
- return result;
23
- }
24
- exports.processQueryResponse = processQueryResponse;
25
- /**
26
- * Process mutation responses, validating them using Superstruct if a struct is defined.
27
- *
28
- * @param mutationKey - The mutation key.
29
- * @param response - The mutation response
30
- * @param struct - The struct defining the schema for the mutation response.
31
- * @returns The mutation response, coerced by Superstruct if needed.
32
- * @throws If the mutation response does not match the struct.
33
- * @template InputResponse - The type of the response data being validated, e.g. `Json`.
34
- * @template ResponseStruct - The struct used to validate and decode the response,
35
- * e.g. `Struct<FetchOrdersResponse>`, or `undefined` when no validation is needed.
36
- */
37
- function processMutationResponse(mutationKey, response, struct) {
38
- if (!struct) {
39
- // Type assertion: TypeScript cannot "see" that when `struct` is
40
- // `undefined`, `response` satisfies the `InputResponse` branch of
41
- // `Response` (even though we stated this fact in the conditional type
42
- // above). This is because at this point in time, `ResponseStruct` — being a
43
- // generic — is unresolved, which makes `Response` unresolved too. This is a
44
- // limitation of the way that generics work. Therefore, we need to help
45
- // TypeScript out.
46
- return response;
47
- }
48
- const [error, result] = (0, superstruct_1.validate)(response, struct);
49
- if (error) {
50
- throw new Error(`Mutation function for "${mutationKey[0]}" returned an unexpected response: ${error.message}.`);
51
- }
52
- // Type assertion: See above.
53
- return result;
54
- }
55
- exports.processMutationResponse = processMutationResponse;
56
- //# sourceMappingURL=utils.cjs.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"utils.cjs","sourceRoot":"","sources":["../src/utils.ts"],"names":[],"mappings":";;;AAAA,uDAAyD;AAIzD;;;;;;;;GAQG;AACH,SAAgB,oBAAoB,CAClC,QAAkB,EAClB,QAAkB,EAClB,MAAyB;IAEzB,IAAI,CAAC,MAAM,EAAE,CAAC;QACZ,OAAO,QAAQ,CAAC;IAClB,CAAC;IAED,MAAM,CAAC,KAAK,EAAE,MAAM,CAAC,GAAG,IAAA,sBAAQ,EAAC,QAAQ,EAAE,MAAM,CAAC,CAAC;IAEnD,IAAI,KAAK,EAAE,CAAC;QACV,MAAM,IAAI,KAAK,CACb,uBAAuB,QAAQ,CAAC,CAAC,CAAC,sCAAsC,KAAK,CAAC,OAAO,GAAG,CACzF,CAAC;IACJ,CAAC;IAED,OAAO,MAAM,CAAC;AAChB,CAAC;AAlBD,oDAkBC;AAED;;;;;;;;;;;GAWG;AACH,SAAgB,uBAAuB,CAUrC,WAAwB,EACxB,QAAuB,EACvB,MAAuB;IAavB,IAAI,CAAC,MAAM,EAAE,CAAC;QACZ,gEAAgE;QAChE,kEAAkE;QAClE,sEAAsE;QACtE,4EAA4E;QAC5E,4EAA4E;QAC5E,uEAAuE;QACvE,kBAAkB;QAClB,OAAO,QAA+B,CAAC;IACzC,CAAC;IAED,MAAM,CAAC,KAAK,EAAE,MAAM,CAAC,GAAG,IAAA,sBAAQ,EAAC,QAAQ,EAAE,MAAM,CAAC,CAAC;IAEnD,IAAI,KAAK,EAAE,CAAC;QACV,MAAM,IAAI,KAAK,CACb,0BAA0B,WAAW,CAAC,CAAC,CAAC,sCAAsC,KAAK,CAAC,OAAO,GAAG,CAC/F,CAAC;IACJ,CAAC;IAED,6BAA6B;IAC7B,OAAO,MAA6B,CAAC;AACvC,CAAC;AA9CD,0DA8CC","sourcesContent":["import { Struct, validate } from '@metamask/superstruct';\n\nimport type { MutationKey, QueryKey } from './BaseDataService.js';\n\n/**\n * Process query responses, validating them using Superstruct if a struct is defined.\n *\n * @param queryKey - The query key.\n * @param response - The query response\n * @param struct - The struct defining the schema for the query response.\n * @returns The query response, coerced by Superstruct if needed.\n * @throws If the query response does not match the struct.\n */\nexport function processQueryResponse<Response>(\n queryKey: QueryKey,\n response: Response,\n struct?: Struct<Response>,\n): Response {\n if (!struct) {\n return response;\n }\n\n const [error, result] = validate(response, struct);\n\n if (error) {\n throw new Error(\n `Query function for \"${queryKey[0]}\" returned an unexpected response: ${error.message}.`,\n );\n }\n\n return result;\n}\n\n/**\n * Process mutation responses, validating them using Superstruct if a struct is defined.\n *\n * @param mutationKey - The mutation key.\n * @param response - The mutation response\n * @param struct - The struct defining the schema for the mutation response.\n * @returns The mutation response, coerced by Superstruct if needed.\n * @throws If the mutation response does not match the struct.\n * @template InputResponse - The type of the response data being validated, e.g. `Json`.\n * @template ResponseStruct - The struct used to validate and decode the response,\n * e.g. `Struct<FetchOrdersResponse>`, or `undefined` when no validation is needed.\n */\nexport function processMutationResponse<\n InputResponse,\n // We have to use `Struct<any>` here, as using `Struct<InputResponse>` (or\n // even `Struct<unknown>`) would reject a more concrete, \"real world\" struct.\n // The reason is that `Struct` is an object type with methods whose signatures\n // feature the struct's content type, making `Struct` contravariant in its\n // content type. The only way to get around this is to use `any`.\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n ResponseStruct extends Struct<any> | undefined = undefined,\n>(\n mutationKey: MutationKey,\n response: InputResponse,\n struct?: ResponseStruct,\n // We don't want this to be a type parameter as it should not be customizable\n // (it is only derived).\n): ResponseStruct extends Struct<infer StructType>\n ? StructType\n : InputResponse {\n // Because we aren't defining the return type as a type parameter,\n // we need to restate it so we can reuse it below.\n type Response =\n ResponseStruct extends Struct<infer StructType>\n ? StructType\n : InputResponse;\n\n if (!struct) {\n // Type assertion: TypeScript cannot \"see\" that when `struct` is\n // `undefined`, `response` satisfies the `InputResponse` branch of\n // `Response` (even though we stated this fact in the conditional type\n // above). This is because at this point in time, `ResponseStruct` — being a\n // generic — is unresolved, which makes `Response` unresolved too. This is a\n // limitation of the way that generics work. Therefore, we need to help\n // TypeScript out.\n return response as unknown as Response;\n }\n\n const [error, result] = validate(response, struct);\n\n if (error) {\n throw new Error(\n `Mutation function for \"${mutationKey[0]}\" returned an unexpected response: ${error.message}.`,\n );\n }\n\n // Type assertion: See above.\n return result as unknown as Response;\n}\n"]}
package/dist/utils.d.cts DELETED
@@ -1,26 +0,0 @@
1
- import { Struct } from "@metamask/superstruct";
2
- import type { MutationKey, QueryKey } from "./BaseDataService.cjs";
3
- /**
4
- * Process query responses, validating them using Superstruct if a struct is defined.
5
- *
6
- * @param queryKey - The query key.
7
- * @param response - The query response
8
- * @param struct - The struct defining the schema for the query response.
9
- * @returns The query response, coerced by Superstruct if needed.
10
- * @throws If the query response does not match the struct.
11
- */
12
- export declare function processQueryResponse<Response>(queryKey: QueryKey, response: Response, struct?: Struct<Response>): Response;
13
- /**
14
- * Process mutation responses, validating them using Superstruct if a struct is defined.
15
- *
16
- * @param mutationKey - The mutation key.
17
- * @param response - The mutation response
18
- * @param struct - The struct defining the schema for the mutation response.
19
- * @returns The mutation response, coerced by Superstruct if needed.
20
- * @throws If the mutation response does not match the struct.
21
- * @template InputResponse - The type of the response data being validated, e.g. `Json`.
22
- * @template ResponseStruct - The struct used to validate and decode the response,
23
- * e.g. `Struct<FetchOrdersResponse>`, or `undefined` when no validation is needed.
24
- */
25
- export declare function processMutationResponse<InputResponse, ResponseStruct extends Struct<any> | undefined = undefined>(mutationKey: MutationKey, response: InputResponse, struct?: ResponseStruct): ResponseStruct extends Struct<infer StructType> ? StructType : InputResponse;
26
- //# sourceMappingURL=utils.d.cts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"utils.d.cts","sourceRoot":"","sources":["../src/utils.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,EAAY,8BAA8B;AAEzD,OAAO,KAAK,EAAE,WAAW,EAAE,QAAQ,EAAE,8BAA6B;AAElE;;;;;;;;GAQG;AACH,wBAAgB,oBAAoB,CAAC,QAAQ,EAC3C,QAAQ,EAAE,QAAQ,EAClB,QAAQ,EAAE,QAAQ,EAClB,MAAM,CAAC,EAAE,MAAM,CAAC,QAAQ,CAAC,GACxB,QAAQ,CAcV;AAED;;;;;;;;;;;GAWG;AACH,wBAAgB,uBAAuB,CACrC,aAAa,EAOb,cAAc,SAAS,MAAM,CAAC,GAAG,CAAC,GAAG,SAAS,GAAG,SAAS,EAE1D,WAAW,EAAE,WAAW,EACxB,QAAQ,EAAE,aAAa,EACvB,MAAM,CAAC,EAAE,cAAc,GAGtB,cAAc,SAAS,MAAM,CAAC,MAAM,UAAU,CAAC,GAC9C,UAAU,GACV,aAAa,CA6BhB"}
package/dist/utils.d.mts DELETED
@@ -1,26 +0,0 @@
1
- import { Struct } from "@metamask/superstruct";
2
- import type { MutationKey, QueryKey } from "./BaseDataService.mjs";
3
- /**
4
- * Process query responses, validating them using Superstruct if a struct is defined.
5
- *
6
- * @param queryKey - The query key.
7
- * @param response - The query response
8
- * @param struct - The struct defining the schema for the query response.
9
- * @returns The query response, coerced by Superstruct if needed.
10
- * @throws If the query response does not match the struct.
11
- */
12
- export declare function processQueryResponse<Response>(queryKey: QueryKey, response: Response, struct?: Struct<Response>): Response;
13
- /**
14
- * Process mutation responses, validating them using Superstruct if a struct is defined.
15
- *
16
- * @param mutationKey - The mutation key.
17
- * @param response - The mutation response
18
- * @param struct - The struct defining the schema for the mutation response.
19
- * @returns The mutation response, coerced by Superstruct if needed.
20
- * @throws If the mutation response does not match the struct.
21
- * @template InputResponse - The type of the response data being validated, e.g. `Json`.
22
- * @template ResponseStruct - The struct used to validate and decode the response,
23
- * e.g. `Struct<FetchOrdersResponse>`, or `undefined` when no validation is needed.
24
- */
25
- export declare function processMutationResponse<InputResponse, ResponseStruct extends Struct<any> | undefined = undefined>(mutationKey: MutationKey, response: InputResponse, struct?: ResponseStruct): ResponseStruct extends Struct<infer StructType> ? StructType : InputResponse;
26
- //# sourceMappingURL=utils.d.mts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"utils.d.mts","sourceRoot":"","sources":["../src/utils.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,EAAY,8BAA8B;AAEzD,OAAO,KAAK,EAAE,WAAW,EAAE,QAAQ,EAAE,8BAA6B;AAElE;;;;;;;;GAQG;AACH,wBAAgB,oBAAoB,CAAC,QAAQ,EAC3C,QAAQ,EAAE,QAAQ,EAClB,QAAQ,EAAE,QAAQ,EAClB,MAAM,CAAC,EAAE,MAAM,CAAC,QAAQ,CAAC,GACxB,QAAQ,CAcV;AAED;;;;;;;;;;;GAWG;AACH,wBAAgB,uBAAuB,CACrC,aAAa,EAOb,cAAc,SAAS,MAAM,CAAC,GAAG,CAAC,GAAG,SAAS,GAAG,SAAS,EAE1D,WAAW,EAAE,WAAW,EACxB,QAAQ,EAAE,aAAa,EACvB,MAAM,CAAC,EAAE,cAAc,GAGtB,cAAc,SAAS,MAAM,CAAC,MAAM,UAAU,CAAC,GAC9C,UAAU,GACV,aAAa,CA6BhB"}
package/dist/utils.mjs DELETED
@@ -1,51 +0,0 @@
1
- import { Struct, validate } from "@metamask/superstruct";
2
- /**
3
- * Process query responses, validating them using Superstruct if a struct is defined.
4
- *
5
- * @param queryKey - The query key.
6
- * @param response - The query response
7
- * @param struct - The struct defining the schema for the query response.
8
- * @returns The query response, coerced by Superstruct if needed.
9
- * @throws If the query response does not match the struct.
10
- */
11
- export function processQueryResponse(queryKey, response, struct) {
12
- if (!struct) {
13
- return response;
14
- }
15
- const [error, result] = validate(response, struct);
16
- if (error) {
17
- throw new Error(`Query function for "${queryKey[0]}" returned an unexpected response: ${error.message}.`);
18
- }
19
- return result;
20
- }
21
- /**
22
- * Process mutation responses, validating them using Superstruct if a struct is defined.
23
- *
24
- * @param mutationKey - The mutation key.
25
- * @param response - The mutation response
26
- * @param struct - The struct defining the schema for the mutation response.
27
- * @returns The mutation response, coerced by Superstruct if needed.
28
- * @throws If the mutation response does not match the struct.
29
- * @template InputResponse - The type of the response data being validated, e.g. `Json`.
30
- * @template ResponseStruct - The struct used to validate and decode the response,
31
- * e.g. `Struct<FetchOrdersResponse>`, or `undefined` when no validation is needed.
32
- */
33
- export function processMutationResponse(mutationKey, response, struct) {
34
- if (!struct) {
35
- // Type assertion: TypeScript cannot "see" that when `struct` is
36
- // `undefined`, `response` satisfies the `InputResponse` branch of
37
- // `Response` (even though we stated this fact in the conditional type
38
- // above). This is because at this point in time, `ResponseStruct` — being a
39
- // generic — is unresolved, which makes `Response` unresolved too. This is a
40
- // limitation of the way that generics work. Therefore, we need to help
41
- // TypeScript out.
42
- return response;
43
- }
44
- const [error, result] = validate(response, struct);
45
- if (error) {
46
- throw new Error(`Mutation function for "${mutationKey[0]}" returned an unexpected response: ${error.message}.`);
47
- }
48
- // Type assertion: See above.
49
- return result;
50
- }
51
- //# sourceMappingURL=utils.mjs.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"utils.mjs","sourceRoot":"","sources":["../src/utils.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,EAAE,QAAQ,EAAE,8BAA8B;AAIzD;;;;;;;;GAQG;AACH,MAAM,UAAU,oBAAoB,CAClC,QAAkB,EAClB,QAAkB,EAClB,MAAyB;IAEzB,IAAI,CAAC,MAAM,EAAE,CAAC;QACZ,OAAO,QAAQ,CAAC;IAClB,CAAC;IAED,MAAM,CAAC,KAAK,EAAE,MAAM,CAAC,GAAG,QAAQ,CAAC,QAAQ,EAAE,MAAM,CAAC,CAAC;IAEnD,IAAI,KAAK,EAAE,CAAC;QACV,MAAM,IAAI,KAAK,CACb,uBAAuB,QAAQ,CAAC,CAAC,CAAC,sCAAsC,KAAK,CAAC,OAAO,GAAG,CACzF,CAAC;IACJ,CAAC;IAED,OAAO,MAAM,CAAC;AAChB,CAAC;AAED;;;;;;;;;;;GAWG;AACH,MAAM,UAAU,uBAAuB,CAUrC,WAAwB,EACxB,QAAuB,EACvB,MAAuB;IAavB,IAAI,CAAC,MAAM,EAAE,CAAC;QACZ,gEAAgE;QAChE,kEAAkE;QAClE,sEAAsE;QACtE,4EAA4E;QAC5E,4EAA4E;QAC5E,uEAAuE;QACvE,kBAAkB;QAClB,OAAO,QAA+B,CAAC;IACzC,CAAC;IAED,MAAM,CAAC,KAAK,EAAE,MAAM,CAAC,GAAG,QAAQ,CAAC,QAAQ,EAAE,MAAM,CAAC,CAAC;IAEnD,IAAI,KAAK,EAAE,CAAC;QACV,MAAM,IAAI,KAAK,CACb,0BAA0B,WAAW,CAAC,CAAC,CAAC,sCAAsC,KAAK,CAAC,OAAO,GAAG,CAC/F,CAAC;IACJ,CAAC;IAED,6BAA6B;IAC7B,OAAO,MAA6B,CAAC;AACvC,CAAC","sourcesContent":["import { Struct, validate } from '@metamask/superstruct';\n\nimport type { MutationKey, QueryKey } from './BaseDataService.js';\n\n/**\n * Process query responses, validating them using Superstruct if a struct is defined.\n *\n * @param queryKey - The query key.\n * @param response - The query response\n * @param struct - The struct defining the schema for the query response.\n * @returns The query response, coerced by Superstruct if needed.\n * @throws If the query response does not match the struct.\n */\nexport function processQueryResponse<Response>(\n queryKey: QueryKey,\n response: Response,\n struct?: Struct<Response>,\n): Response {\n if (!struct) {\n return response;\n }\n\n const [error, result] = validate(response, struct);\n\n if (error) {\n throw new Error(\n `Query function for \"${queryKey[0]}\" returned an unexpected response: ${error.message}.`,\n );\n }\n\n return result;\n}\n\n/**\n * Process mutation responses, validating them using Superstruct if a struct is defined.\n *\n * @param mutationKey - The mutation key.\n * @param response - The mutation response\n * @param struct - The struct defining the schema for the mutation response.\n * @returns The mutation response, coerced by Superstruct if needed.\n * @throws If the mutation response does not match the struct.\n * @template InputResponse - The type of the response data being validated, e.g. `Json`.\n * @template ResponseStruct - The struct used to validate and decode the response,\n * e.g. `Struct<FetchOrdersResponse>`, or `undefined` when no validation is needed.\n */\nexport function processMutationResponse<\n InputResponse,\n // We have to use `Struct<any>` here, as using `Struct<InputResponse>` (or\n // even `Struct<unknown>`) would reject a more concrete, \"real world\" struct.\n // The reason is that `Struct` is an object type with methods whose signatures\n // feature the struct's content type, making `Struct` contravariant in its\n // content type. The only way to get around this is to use `any`.\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n ResponseStruct extends Struct<any> | undefined = undefined,\n>(\n mutationKey: MutationKey,\n response: InputResponse,\n struct?: ResponseStruct,\n // We don't want this to be a type parameter as it should not be customizable\n // (it is only derived).\n): ResponseStruct extends Struct<infer StructType>\n ? StructType\n : InputResponse {\n // Because we aren't defining the return type as a type parameter,\n // we need to restate it so we can reuse it below.\n type Response =\n ResponseStruct extends Struct<infer StructType>\n ? StructType\n : InputResponse;\n\n if (!struct) {\n // Type assertion: TypeScript cannot \"see\" that when `struct` is\n // `undefined`, `response` satisfies the `InputResponse` branch of\n // `Response` (even though we stated this fact in the conditional type\n // above). This is because at this point in time, `ResponseStruct` — being a\n // generic — is unresolved, which makes `Response` unresolved too. This is a\n // limitation of the way that generics work. Therefore, we need to help\n // TypeScript out.\n return response as unknown as Response;\n }\n\n const [error, result] = validate(response, struct);\n\n if (error) {\n throw new Error(\n `Mutation function for \"${mutationKey[0]}\" returned an unexpected response: ${error.message}.`,\n );\n }\n\n // Type assertion: See above.\n return result as unknown as Response;\n}\n"]}