@lukadriel/wave-sdk 0.0.0-stage → 0.1.2

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 (185) hide show
  1. package/CHANGELOG.md +30 -0
  2. package/LICENSE +201 -0
  3. package/NOTICE +2 -0
  4. package/README.md +523 -2
  5. package/dist/client/wave-client-options.d.ts +29 -0
  6. package/dist/client/wave-client-options.d.ts.map +1 -0
  7. package/dist/client/wave-client-options.js +58 -0
  8. package/dist/client/wave-client-options.js.map +1 -0
  9. package/dist/client/wave-client.d.ts +47 -0
  10. package/dist/client/wave-client.d.ts.map +1 -0
  11. package/dist/client/wave-client.js +66 -0
  12. package/dist/client/wave-client.js.map +1 -0
  13. package/dist/core/auth/authentication.d.ts +8 -0
  14. package/dist/core/auth/authentication.d.ts.map +1 -0
  15. package/dist/core/auth/authentication.js +10 -0
  16. package/dist/core/auth/authentication.js.map +1 -0
  17. package/dist/core/auth/request-signer.d.ts +26 -0
  18. package/dist/core/auth/request-signer.d.ts.map +1 -0
  19. package/dist/core/auth/request-signer.js +39 -0
  20. package/dist/core/auth/request-signer.js.map +1 -0
  21. package/dist/core/errors/error-parser.d.ts +25 -0
  22. package/dist/core/errors/error-parser.d.ts.map +1 -0
  23. package/dist/core/errors/error-parser.js +198 -0
  24. package/dist/core/errors/error-parser.js.map +1 -0
  25. package/dist/core/errors/redact.d.ts +11 -0
  26. package/dist/core/errors/redact.d.ts.map +1 -0
  27. package/dist/core/errors/redact.js +20 -0
  28. package/dist/core/errors/redact.js.map +1 -0
  29. package/dist/core/errors/wave-api-error.d.ts +116 -0
  30. package/dist/core/errors/wave-api-error.d.ts.map +1 -0
  31. package/dist/core/errors/wave-api-error.js +114 -0
  32. package/dist/core/errors/wave-api-error.js.map +1 -0
  33. package/dist/core/errors/wave-error.d.ts +27 -0
  34. package/dist/core/errors/wave-error.d.ts.map +1 -0
  35. package/dist/core/errors/wave-error.js +22 -0
  36. package/dist/core/errors/wave-error.js.map +1 -0
  37. package/dist/core/errors/wave-network-error.d.ts +24 -0
  38. package/dist/core/errors/wave-network-error.d.ts.map +1 -0
  39. package/dist/core/errors/wave-network-error.js +24 -0
  40. package/dist/core/errors/wave-network-error.js.map +1 -0
  41. package/dist/core/errors/wave-webhook-verification-error.d.ts +18 -0
  42. package/dist/core/errors/wave-webhook-verification-error.d.ts.map +1 -0
  43. package/dist/core/errors/wave-webhook-verification-error.js +17 -0
  44. package/dist/core/errors/wave-webhook-verification-error.js.map +1 -0
  45. package/dist/core/http/fetch-transport.d.ts +23 -0
  46. package/dist/core/http/fetch-transport.d.ts.map +1 -0
  47. package/dist/core/http/fetch-transport.js +34 -0
  48. package/dist/core/http/fetch-transport.js.map +1 -0
  49. package/dist/core/http/http-client.d.ts +57 -0
  50. package/dist/core/http/http-client.d.ts.map +1 -0
  51. package/dist/core/http/http-client.js +254 -0
  52. package/dist/core/http/http-client.js.map +1 -0
  53. package/dist/core/http/http-request.d.ts +35 -0
  54. package/dist/core/http/http-request.d.ts.map +1 -0
  55. package/dist/core/http/http-request.js +2 -0
  56. package/dist/core/http/http-request.js.map +1 -0
  57. package/dist/core/http/http-response.d.ts +26 -0
  58. package/dist/core/http/http-response.d.ts.map +1 -0
  59. package/dist/core/http/http-response.js +23 -0
  60. package/dist/core/http/http-response.js.map +1 -0
  61. package/dist/core/http/query.d.ts +14 -0
  62. package/dist/core/http/query.d.ts.map +1 -0
  63. package/dist/core/http/query.js +23 -0
  64. package/dist/core/http/query.js.map +1 -0
  65. package/dist/core/http/transport.d.ts +44 -0
  66. package/dist/core/http/transport.d.ts.map +1 -0
  67. package/dist/core/http/transport.js +2 -0
  68. package/dist/core/http/transport.js.map +1 -0
  69. package/dist/core/idempotency/idempotency.d.ts +16 -0
  70. package/dist/core/idempotency/idempotency.d.ts.map +1 -0
  71. package/dist/core/idempotency/idempotency.js +27 -0
  72. package/dist/core/idempotency/idempotency.js.map +1 -0
  73. package/dist/core/retry/backoff.d.ts +18 -0
  74. package/dist/core/retry/backoff.d.ts.map +1 -0
  75. package/dist/core/retry/backoff.js +46 -0
  76. package/dist/core/retry/backoff.js.map +1 -0
  77. package/dist/core/retry/retry-policy.d.ts +43 -0
  78. package/dist/core/retry/retry-policy.d.ts.map +1 -0
  79. package/dist/core/retry/retry-policy.js +90 -0
  80. package/dist/core/retry/retry-policy.js.map +1 -0
  81. package/dist/core/types/common.d.ts +59 -0
  82. package/dist/core/types/common.d.ts.map +1 -0
  83. package/dist/core/types/common.js +2 -0
  84. package/dist/core/types/common.js.map +1 -0
  85. package/dist/core/types/configuration.d.ts +82 -0
  86. package/dist/core/types/configuration.d.ts.map +1 -0
  87. package/dist/core/types/configuration.js +2 -0
  88. package/dist/core/types/configuration.js.map +1 -0
  89. package/dist/core/types/json.d.ts +15 -0
  90. package/dist/core/types/json.d.ts.map +1 -0
  91. package/dist/core/types/json.js +2 -0
  92. package/dist/core/types/json.js.map +1 -0
  93. package/dist/index.d.ts +39 -0
  94. package/dist/index.d.ts.map +1 -0
  95. package/dist/index.js +24 -0
  96. package/dist/index.js.map +1 -0
  97. package/dist/resources/aggregated-merchants/aggregated-merchant-types.d.ts +82 -0
  98. package/dist/resources/aggregated-merchants/aggregated-merchant-types.d.ts.map +1 -0
  99. package/dist/resources/aggregated-merchants/aggregated-merchant-types.js +2 -0
  100. package/dist/resources/aggregated-merchants/aggregated-merchant-types.js.map +1 -0
  101. package/dist/resources/aggregated-merchants/aggregated-merchants.d.ts +67 -0
  102. package/dist/resources/aggregated-merchants/aggregated-merchants.d.ts.map +1 -0
  103. package/dist/resources/aggregated-merchants/aggregated-merchants.js +111 -0
  104. package/dist/resources/aggregated-merchants/aggregated-merchants.js.map +1 -0
  105. package/dist/resources/balance/balance-types.d.ts +18 -0
  106. package/dist/resources/balance/balance-types.d.ts.map +1 -0
  107. package/dist/resources/balance/balance-types.js +2 -0
  108. package/dist/resources/balance/balance-types.js.map +1 -0
  109. package/dist/resources/balance/balance.d.ts +20 -0
  110. package/dist/resources/balance/balance.d.ts.map +1 -0
  111. package/dist/resources/balance/balance.js +28 -0
  112. package/dist/resources/balance/balance.js.map +1 -0
  113. package/dist/resources/checkout/checkout-types.d.ts +96 -0
  114. package/dist/resources/checkout/checkout-types.d.ts.map +1 -0
  115. package/dist/resources/checkout/checkout-types.js +2 -0
  116. package/dist/resources/checkout/checkout-types.js.map +1 -0
  117. package/dist/resources/checkout/checkout.d.ts +66 -0
  118. package/dist/resources/checkout/checkout.d.ts.map +1 -0
  119. package/dist/resources/checkout/checkout.js +95 -0
  120. package/dist/resources/checkout/checkout.js.map +1 -0
  121. package/dist/resources/payout-batches/payout-batches.d.ts +31 -0
  122. package/dist/resources/payout-batches/payout-batches.d.ts.map +1 -0
  123. package/dist/resources/payout-batches/payout-batches.js +36 -0
  124. package/dist/resources/payout-batches/payout-batches.js.map +1 -0
  125. package/dist/resources/payouts/payout-types.d.ts +158 -0
  126. package/dist/resources/payouts/payout-types.d.ts.map +1 -0
  127. package/dist/resources/payouts/payout-types.js +2 -0
  128. package/dist/resources/payouts/payout-types.js.map +1 -0
  129. package/dist/resources/payouts/payouts.d.ts +63 -0
  130. package/dist/resources/payouts/payouts.d.ts.map +1 -0
  131. package/dist/resources/payouts/payouts.js +80 -0
  132. package/dist/resources/payouts/payouts.js.map +1 -0
  133. package/dist/resources/reconciliation/reconciliation-types.d.ts +86 -0
  134. package/dist/resources/reconciliation/reconciliation-types.d.ts.map +1 -0
  135. package/dist/resources/reconciliation/reconciliation-types.js +2 -0
  136. package/dist/resources/reconciliation/reconciliation-types.js.map +1 -0
  137. package/dist/resources/reconciliation/reconciliation.d.ts +41 -0
  138. package/dist/resources/reconciliation/reconciliation.d.ts.map +1 -0
  139. package/dist/resources/reconciliation/reconciliation.js +81 -0
  140. package/dist/resources/reconciliation/reconciliation.js.map +1 -0
  141. package/dist/resources/webhooks/webhook-types.d.ts +159 -0
  142. package/dist/resources/webhooks/webhook-types.d.ts.map +1 -0
  143. package/dist/resources/webhooks/webhook-types.js +36 -0
  144. package/dist/resources/webhooks/webhook-types.js.map +1 -0
  145. package/dist/resources/webhooks/webhook-verifier.d.ts +104 -0
  146. package/dist/resources/webhooks/webhook-verifier.d.ts.map +1 -0
  147. package/dist/resources/webhooks/webhook-verifier.js +188 -0
  148. package/dist/resources/webhooks/webhook-verifier.js.map +1 -0
  149. package/package.json +70 -4
  150. package/src/client/wave-client-options.ts +91 -0
  151. package/src/client/wave-client.ts +70 -0
  152. package/src/core/auth/authentication.ts +9 -0
  153. package/src/core/auth/request-signer.ts +42 -0
  154. package/src/core/errors/error-parser.ts +258 -0
  155. package/src/core/errors/redact.ts +20 -0
  156. package/src/core/errors/wave-api-error.ts +148 -0
  157. package/src/core/errors/wave-error.ts +32 -0
  158. package/src/core/errors/wave-network-error.ts +24 -0
  159. package/src/core/errors/wave-webhook-verification-error.ts +28 -0
  160. package/src/core/http/fetch-transport.ts +48 -0
  161. package/src/core/http/http-client.ts +352 -0
  162. package/src/core/http/http-request.ts +37 -0
  163. package/src/core/http/http-response.ts +37 -0
  164. package/src/core/http/query.ts +31 -0
  165. package/src/core/http/transport.ts +45 -0
  166. package/src/core/idempotency/idempotency.ts +31 -0
  167. package/src/core/retry/backoff.ts +61 -0
  168. package/src/core/retry/retry-policy.ts +106 -0
  169. package/src/core/types/common.ts +65 -0
  170. package/src/core/types/configuration.ts +85 -0
  171. package/src/core/types/json.ts +16 -0
  172. package/src/index.ts +146 -0
  173. package/src/resources/aggregated-merchants/aggregated-merchant-types.ts +87 -0
  174. package/src/resources/aggregated-merchants/aggregated-merchants.ts +171 -0
  175. package/src/resources/balance/balance-types.ts +19 -0
  176. package/src/resources/balance/balance.ts +39 -0
  177. package/src/resources/checkout/checkout-types.ts +102 -0
  178. package/src/resources/checkout/checkout.ts +144 -0
  179. package/src/resources/payout-batches/payout-batches.ts +58 -0
  180. package/src/resources/payouts/payout-types.ts +171 -0
  181. package/src/resources/payouts/payouts.ts +120 -0
  182. package/src/resources/reconciliation/reconciliation-types.ts +102 -0
  183. package/src/resources/reconciliation/reconciliation.ts +116 -0
  184. package/src/resources/webhooks/webhook-types.ts +222 -0
  185. package/src/resources/webhooks/webhook-verifier.ts +297 -0
@@ -0,0 +1,91 @@
1
+ import { WaveConfigurationError } from '../core/errors/wave-error.js';
2
+ import { DEFAULT_BASE_URL, DEFAULT_TIMEOUT_MS } from '../core/http/http-client.js';
3
+ import { FetchTransport } from '../core/http/fetch-transport.js';
4
+ import type { WaveTransport } from '../core/http/transport.js';
5
+ import { normalizeRetryOptions } from '../core/retry/retry-policy.js';
6
+ import type { RetryOptions, WaveClientOptions, WaveLogger } from '../core/types/configuration.js';
7
+
8
+ /**
9
+ * Validated client configuration used internally.
10
+ */
11
+ export interface ResolvedClientOptions {
12
+ /** Normalized base URL without a trailing slash. */
13
+ readonly baseUrl: string;
14
+ /** Wave Business API key. */
15
+ readonly apiKey: string;
16
+ /** Optional signing secret. */
17
+ readonly signingSecret: string | undefined;
18
+ /** HTTP transport. */
19
+ readonly transport: WaveTransport;
20
+ /** Default request timeout in milliseconds. */
21
+ readonly timeoutMs: number;
22
+ /** Default retry policy, or `false` when disabled. */
23
+ readonly retry: RetryOptions | false;
24
+ /** Optional diagnostics logger. */
25
+ readonly logger: WaveLogger | undefined;
26
+ }
27
+
28
+ /**
29
+ * Validates and normalizes {@link WaveClientOptions}.
30
+ *
31
+ * @param options - Caller-provided client options.
32
+ * @returns Resolved configuration with defaults applied.
33
+ */
34
+ export function resolveClientOptions(options: WaveClientOptions): ResolvedClientOptions {
35
+ if (typeof options !== 'object' || options === null) {
36
+ throw new WaveConfigurationError('WaveClient options are required.');
37
+ }
38
+
39
+ if (typeof options.apiKey !== 'string' || options.apiKey.trim().length === 0) {
40
+ throw new WaveConfigurationError('apiKey must be a non-empty string.');
41
+ }
42
+
43
+ if (
44
+ options.signingSecret !== undefined &&
45
+ (typeof options.signingSecret !== 'string' || options.signingSecret.trim().length === 0)
46
+ ) {
47
+ throw new WaveConfigurationError('signingSecret must be a non-empty string when provided.');
48
+ }
49
+
50
+ const baseUrl = normalizeBaseUrl(options.baseUrl ?? DEFAULT_BASE_URL);
51
+
52
+ const timeoutMs = options.timeoutMs ?? DEFAULT_TIMEOUT_MS;
53
+ if (!Number.isFinite(timeoutMs) || timeoutMs <= 0) {
54
+ throw new WaveConfigurationError('timeoutMs must be a positive finite number.');
55
+ }
56
+
57
+ const retry = options.retry === false ? false : normalizeRetryOptions(options.retry ?? {});
58
+ const transport = options.transport ?? new FetchTransport();
59
+
60
+ if (typeof transport.send !== 'function') {
61
+ throw new WaveConfigurationError('transport must implement send(request).');
62
+ }
63
+
64
+ return {
65
+ baseUrl,
66
+ apiKey: options.apiKey,
67
+ signingSecret: options.signingSecret,
68
+ transport,
69
+ timeoutMs,
70
+ retry,
71
+ logger: options.logger,
72
+ };
73
+ }
74
+
75
+ function normalizeBaseUrl(value: string): string {
76
+ let url: URL;
77
+ try {
78
+ url = new URL(value);
79
+ } catch {
80
+ throw new WaveConfigurationError('baseUrl must be a valid absolute URL.');
81
+ }
82
+
83
+ if (url.protocol !== 'https:' && url.protocol !== 'http:') {
84
+ throw new WaveConfigurationError('baseUrl must use the http or https scheme.');
85
+ }
86
+ if (url.search.length > 0 || url.hash.length > 0) {
87
+ throw new WaveConfigurationError('baseUrl must not contain a query string or fragment.');
88
+ }
89
+
90
+ return url.toString().replace(/\/+$/u, '');
91
+ }
@@ -0,0 +1,70 @@
1
+ import { HttpClient } from '../core/http/http-client.js';
2
+ import type { WaveClientOptions } from '../core/types/configuration.js';
3
+ import { AggregatedMerchantsResource } from '../resources/aggregated-merchants/aggregated-merchants.js';
4
+ import { BalanceResource } from '../resources/balance/balance.js';
5
+ import { CheckoutResource } from '../resources/checkout/checkout.js';
6
+ import { PayoutBatchesResource } from '../resources/payout-batches/payout-batches.js';
7
+ import { PayoutsResource } from '../resources/payouts/payouts.js';
8
+ import { ReconciliationResource } from '../resources/reconciliation/reconciliation.js';
9
+ import { WaveWebhooks } from '../resources/webhooks/webhook-verifier.js';
10
+ import { resolveClientOptions } from './wave-client-options.js';
11
+
12
+ /**
13
+ * Unified entry point for the Wave Business APIs.
14
+ *
15
+ * The client is intended for trusted server-side environments. It never persists credentials and
16
+ * never exposes them through errors or logs.
17
+ *
18
+ * @example
19
+ * ```ts
20
+ * const wave = new WaveClient({ apiKey: process.env.WAVE_API_KEY! });
21
+ * const payout = await wave.payouts.create({
22
+ * currency: 'XOF',
23
+ * receive_amount: '5000',
24
+ * name: 'John Doe',
25
+ * mobile: '+2250700000000',
26
+ * });
27
+ * ```
28
+ */
29
+ export class WaveClient {
30
+ /** Payout API operations. */
31
+ readonly payouts: PayoutsResource;
32
+ /** Payout batch operations. */
33
+ readonly payoutBatches: PayoutBatchesResource;
34
+ /** Balance API operations. */
35
+ readonly balance: BalanceResource;
36
+ /** Transaction listing and refund operations. */
37
+ readonly reconciliation: ReconciliationResource;
38
+ /** Checkout API operations. */
39
+ readonly checkout: CheckoutResource;
40
+ /** Aggregated Merchants API operations. */
41
+ readonly aggregatedMerchants: AggregatedMerchantsResource;
42
+ /** Local webhook signature verification helpers; no HTTP calls are made. */
43
+ readonly webhooks: WaveWebhooks;
44
+
45
+ /**
46
+ * @param options - API credentials and transport configuration.
47
+ * @throws WaveConfigurationError when required options are missing or invalid.
48
+ */
49
+ constructor(options: WaveClientOptions) {
50
+ const resolved = resolveClientOptions(options);
51
+
52
+ const http = new HttpClient({
53
+ baseUrl: resolved.baseUrl,
54
+ apiKey: resolved.apiKey,
55
+ signingSecret: resolved.signingSecret,
56
+ transport: resolved.transport,
57
+ timeoutMs: resolved.timeoutMs,
58
+ retry: resolved.retry,
59
+ logger: resolved.logger,
60
+ });
61
+
62
+ this.payouts = new PayoutsResource(http);
63
+ this.payoutBatches = new PayoutBatchesResource(http);
64
+ this.balance = new BalanceResource(http);
65
+ this.reconciliation = new ReconciliationResource(http);
66
+ this.checkout = new CheckoutResource(http);
67
+ this.aggregatedMerchants = new AggregatedMerchantsResource(http);
68
+ this.webhooks = new WaveWebhooks();
69
+ }
70
+ }
@@ -0,0 +1,9 @@
1
+ /**
2
+ * Builds the documented bearer authorization header.
3
+ *
4
+ * @param apiKey - Wave Business API key.
5
+ * @returns The header value, for example `Bearer wave_sn_prod_...`.
6
+ */
7
+ export function buildAuthorizationHeader(apiKey: string): string {
8
+ return `Bearer ${apiKey}`;
9
+ }
@@ -0,0 +1,42 @@
1
+ import { createHmac } from 'node:crypto';
2
+ import { WaveConfigurationError } from '../errors/wave-error.js';
3
+
4
+ /**
5
+ * Header carrying the request signature.
6
+ */
7
+ export const SIGNATURE_HEADER = 'Wave-Signature';
8
+
9
+ /**
10
+ * Signs outgoing requests with Wave's documented HMAC-SHA256 algorithm.
11
+ *
12
+ * The payload is the Unix timestamp in seconds concatenated with the exact request body. For GET
13
+ * requests without a body, the payload is the timestamp alone.
14
+ */
15
+ export class RequestSigner {
16
+ readonly #secret: string;
17
+
18
+ /**
19
+ * @param signingSecret - Signing secret configured on the API key.
20
+ */
21
+ constructor(signingSecret: string) {
22
+ if (typeof signingSecret !== 'string' || signingSecret.length === 0) {
23
+ throw new WaveConfigurationError('signingSecret must be a non-empty string when provided.');
24
+ }
25
+ this.#secret = signingSecret;
26
+ }
27
+
28
+ /**
29
+ * Produces the `Wave-Signature` header value.
30
+ *
31
+ * @param body - Exact serialized request body; use an empty string for GET requests.
32
+ * @param timestampSeconds - Unix timestamp in seconds; a fresh value must be used per attempt.
33
+ * @returns Header value in the documented `t={timestamp},v1={signature}` form.
34
+ */
35
+ sign(body: string, timestampSeconds: number = Math.floor(Date.now() / 1000)): string {
36
+ const signature = createHmac('sha256', this.#secret)
37
+ .update(String(timestampSeconds), 'utf8')
38
+ .update(body, 'utf8')
39
+ .digest('hex');
40
+ return `t=${timestampSeconds},v1=${signature}`;
41
+ }
42
+ }
@@ -0,0 +1,258 @@
1
+ import { parseRetryAfter } from '../retry/retry-policy.js';
2
+ import type { ValidationErrorDetail } from '../types/common.js';
3
+ import type { JsonObject, JsonValue } from '../types/json.js';
4
+ import {
5
+ WaveApiError,
6
+ WaveAuthenticationError,
7
+ WaveAuthorizationError,
8
+ WaveConflictError,
9
+ WaveNotFoundError,
10
+ WaveRateLimitError,
11
+ WaveServerError,
12
+ WaveValidationError,
13
+ type WaveApiErrorOptions,
14
+ } from './wave-api-error.js';
15
+ import { redactSecrets } from './redact.js';
16
+
17
+ /**
18
+ * Raw inputs used to construct an API error.
19
+ */
20
+ export interface ParseApiErrorInput {
21
+ /** HTTP status code returned by Wave. */
22
+ readonly statusCode: number;
23
+ /** Raw response body. */
24
+ readonly bodyText: string;
25
+ /** Response headers with lowercase names. */
26
+ readonly headers: Readonly<Record<string, string>>;
27
+ /** Credential values that must never appear in the resulting message. */
28
+ readonly secrets: readonly string[];
29
+ }
30
+
31
+ interface ErrorEnvelope {
32
+ readonly code: string | undefined;
33
+ readonly message: string | undefined;
34
+ readonly details: readonly ValidationErrorDetail[] | undefined;
35
+ }
36
+
37
+ /**
38
+ * Parses a documented Wave error response into the matching error class.
39
+ *
40
+ * Wave documents several envelopes (`code`/`message`/`details`, `error_code`/`error_message`, and a
41
+ * legacy `error` field), so all of them are accepted.
42
+ *
43
+ * @param input - Status, body, headers and secrets to redact.
44
+ * @returns The matching {@link WaveApiError} subclass.
45
+ */
46
+ export function parseApiError(input: ParseApiErrorInput): WaveApiError {
47
+ const envelope = parseEnvelope(input.bodyText);
48
+ const fallbackMessage = `Wave API request failed with HTTP ${input.statusCode}.`;
49
+ const message = redactSecrets(envelope.message ?? fallbackMessage, input.secrets);
50
+
51
+ const options: Omit<WaveApiErrorOptions, 'statusCode'> = {
52
+ rawBody: redactSecrets(input.bodyText, input.secrets),
53
+ responseHeaders: redactHeaderValues(input.headers, input.secrets),
54
+ ...(envelope.code === undefined ? {} : { code: envelope.code }),
55
+ ...(envelope.details === undefined
56
+ ? {}
57
+ : { details: envelope.details.map((detail) => redactDetail(detail, input.secrets)) }),
58
+ };
59
+
60
+ switch (input.statusCode) {
61
+ case 401:
62
+ return new WaveAuthenticationError(message, options);
63
+ case 403:
64
+ return new WaveAuthorizationError(message, options);
65
+ case 404:
66
+ return new WaveNotFoundError(message, options);
67
+ case 400:
68
+ case 422:
69
+ return new WaveValidationError(message, { ...options, statusCode: input.statusCode });
70
+ case 409:
71
+ return new WaveConflictError(message, options);
72
+ case 429: {
73
+ const retryAfterSeconds = parseRetryAfter(input.headers['retry-after']);
74
+ return new WaveRateLimitError(message, {
75
+ ...options,
76
+ ...(retryAfterSeconds === undefined ? {} : { retryAfterSeconds }),
77
+ });
78
+ }
79
+ default:
80
+ if (input.statusCode >= 500) {
81
+ return new WaveServerError(message, { ...options, statusCode: input.statusCode });
82
+ }
83
+ return new WaveApiError(message, { ...options, statusCode: input.statusCode });
84
+ }
85
+ }
86
+
87
+ function parseEnvelope(bodyText: string): ErrorEnvelope {
88
+ const parsed = tryParseJson(bodyText);
89
+ if (!isRecord(parsed)) {
90
+ return { code: undefined, message: undefined, details: undefined };
91
+ }
92
+
93
+ const code = firstString(parsed['code'], parsed['error'], parsed['error_code']);
94
+ const message = firstString(parsed['message'], parsed['error_message']);
95
+ const details = parseDetails(parsed['details']);
96
+
97
+ return { code, message, details };
98
+ }
99
+
100
+ function parseDetails(value: unknown): readonly ValidationErrorDetail[] | undefined {
101
+ if (!Array.isArray(value)) {
102
+ return undefined;
103
+ }
104
+
105
+ const details: ValidationErrorDetail[] = [];
106
+ for (const item of value) {
107
+ const detail = parseDetail(item);
108
+ if (detail !== undefined) {
109
+ details.push(detail);
110
+ }
111
+ }
112
+ return details.length > 0 ? details : undefined;
113
+ }
114
+
115
+ function parseDetail(value: unknown): ValidationErrorDetail | undefined {
116
+ if (!isRecord(value)) {
117
+ return undefined;
118
+ }
119
+
120
+ const loc = value['loc'];
121
+ const msg = value['msg'];
122
+ if (!Array.isArray(loc) || typeof msg !== 'string') {
123
+ return undefined;
124
+ }
125
+
126
+ const location: (string | number)[] = [];
127
+ for (const segment of loc) {
128
+ if (typeof segment === 'string' || typeof segment === 'number') {
129
+ location.push(segment);
130
+ }
131
+ }
132
+
133
+ const type = value['type'];
134
+ const ctx = toJsonObject(value['ctx']);
135
+
136
+ return {
137
+ loc: location,
138
+ msg,
139
+ ...(typeof type === 'string' ? { type } : {}),
140
+ ...(ctx === undefined ? {} : { ctx }),
141
+ };
142
+ }
143
+
144
+ function toJsonObject(value: unknown): JsonObject | undefined {
145
+ const parsed = toJsonValue(value);
146
+ if (
147
+ parsed === undefined ||
148
+ parsed === null ||
149
+ Array.isArray(parsed) ||
150
+ typeof parsed !== 'object'
151
+ ) {
152
+ return undefined;
153
+ }
154
+ return parsed;
155
+ }
156
+
157
+ function toJsonValue(value: unknown): JsonValue | undefined {
158
+ if (value === null || typeof value === 'string' || typeof value === 'boolean') {
159
+ return value;
160
+ }
161
+ if (typeof value === 'number') {
162
+ return Number.isFinite(value) ? value : undefined;
163
+ }
164
+ if (Array.isArray(value)) {
165
+ const items: JsonValue[] = [];
166
+ for (const item of value) {
167
+ const parsed = toJsonValue(item);
168
+ if (parsed === undefined) {
169
+ return undefined;
170
+ }
171
+ items.push(parsed);
172
+ }
173
+ return items;
174
+ }
175
+ if (isRecord(value)) {
176
+ const result: Record<string, JsonValue> = {};
177
+ for (const [key, item] of Object.entries(value)) {
178
+ const parsed = toJsonValue(item);
179
+ if (parsed === undefined) {
180
+ return undefined;
181
+ }
182
+ result[key] = parsed;
183
+ }
184
+ return result;
185
+ }
186
+ return undefined;
187
+ }
188
+
189
+ function redactHeaderValues(
190
+ headers: Readonly<Record<string, string>>,
191
+ secrets: readonly string[],
192
+ ): Readonly<Record<string, string>> {
193
+ const redacted: Record<string, string> = {};
194
+ for (const [name, value] of Object.entries(headers)) {
195
+ redacted[name] = redactSecrets(value, secrets);
196
+ }
197
+ return redacted;
198
+ }
199
+
200
+ function redactDetail(
201
+ detail: ValidationErrorDetail,
202
+ secrets: readonly string[],
203
+ ): ValidationErrorDetail {
204
+ return {
205
+ ...detail,
206
+ msg: redactSecrets(detail.msg, secrets),
207
+ ...(detail.ctx === undefined ? {} : { ctx: redactJsonObject(detail.ctx, secrets) }),
208
+ };
209
+ }
210
+
211
+ function redactJsonObject(value: JsonObject, secrets: readonly string[]): JsonObject {
212
+ const result: Record<string, JsonValue> = {};
213
+ for (const [key, item] of Object.entries(value)) {
214
+ result[key] = redactJson(item, secrets);
215
+ }
216
+ return result;
217
+ }
218
+
219
+ function redactJson(value: JsonValue, secrets: readonly string[]): JsonValue {
220
+ if (typeof value === 'string') {
221
+ return redactSecrets(value, secrets);
222
+ }
223
+ if (Array.isArray(value)) {
224
+ return value.map((item) => redactJson(item, secrets));
225
+ }
226
+ if (value !== null && typeof value === 'object') {
227
+ const result: Record<string, JsonValue> = {};
228
+ for (const [key, item] of Object.entries(value)) {
229
+ result[key] = redactJson(item, secrets);
230
+ }
231
+ return result;
232
+ }
233
+ return value;
234
+ }
235
+
236
+ function tryParseJson(value: string): unknown {
237
+ if (value.trim().length === 0) {
238
+ return undefined;
239
+ }
240
+ try {
241
+ return JSON.parse(value) as unknown;
242
+ } catch {
243
+ return undefined;
244
+ }
245
+ }
246
+
247
+ function isRecord(value: unknown): value is Record<string, unknown> {
248
+ return typeof value === 'object' && value !== null && !Array.isArray(value);
249
+ }
250
+
251
+ function firstString(...values: unknown[]): string | undefined {
252
+ for (const value of values) {
253
+ if (typeof value === 'string' && value.length > 0) {
254
+ return value;
255
+ }
256
+ }
257
+ return undefined;
258
+ }
@@ -0,0 +1,20 @@
1
+ /** Replacement text used when a credential would otherwise appear in output. */
2
+ export const REDACTED = '[REDACTED]';
3
+
4
+ /**
5
+ * Removes known secrets from a string.
6
+ *
7
+ * @param value - Text that may contain a credential.
8
+ * @param secrets - Credential values to remove; empty entries are ignored.
9
+ * @returns The text with every occurrence of each secret replaced by `[REDACTED]`.
10
+ */
11
+ export function redactSecrets(value: string, secrets: readonly string[]): string {
12
+ let result = value;
13
+ for (const secret of secrets) {
14
+ if (secret.length === 0 || result.length === 0) {
15
+ continue;
16
+ }
17
+ result = result.split(secret).join(REDACTED);
18
+ }
19
+ return result;
20
+ }
@@ -0,0 +1,148 @@
1
+ import type { ValidationErrorDetail } from '../types/common.js';
2
+ import { WaveError } from './wave-error.js';
3
+
4
+ /**
5
+ * Options for API errors.
6
+ */
7
+ export interface WaveApiErrorOptions {
8
+ /** HTTP status code returned by Wave. */
9
+ readonly statusCode: number;
10
+ /** Wave error code, preserved verbatim. */
11
+ readonly code?: string;
12
+ /** Field-level validation details, when documented. */
13
+ readonly details?: readonly ValidationErrorDetail[];
14
+ /** Raw response body, preserved for diagnostics. */
15
+ readonly rawBody?: string;
16
+ /** Response headers with lowercase names. */
17
+ readonly responseHeaders?: Readonly<Record<string, string>>;
18
+ }
19
+
20
+ /**
21
+ * Base class for errors returned by the Wave API.
22
+ */
23
+ export class WaveApiError extends WaveError {
24
+ /** HTTP status code returned by Wave. */
25
+ readonly statusCode: number;
26
+ /** Field-level validation details, when documented. */
27
+ readonly details: readonly ValidationErrorDetail[] | undefined;
28
+ /** Raw response body preserved for diagnostics, with known credentials redacted. */
29
+ readonly rawBody: string | undefined;
30
+ /** Response headers with lowercase names. */
31
+ readonly responseHeaders: Readonly<Record<string, string>> | undefined;
32
+
33
+ /**
34
+ * @param message - Human-readable description that never contains credentials.
35
+ * @param options - Status code and preserved API error metadata.
36
+ */
37
+ constructor(message: string, options: WaveApiErrorOptions) {
38
+ super(message, options.code === undefined ? {} : { code: options.code });
39
+ this.statusCode = options.statusCode;
40
+ this.details = options.details;
41
+ this.rawBody = options.rawBody;
42
+ this.responseHeaders = options.responseHeaders;
43
+ }
44
+ }
45
+
46
+ /**
47
+ * Error returned when the API key or request signature is rejected (HTTP 401).
48
+ */
49
+ export class WaveAuthenticationError extends WaveApiError {
50
+ /**
51
+ * @param message - Human-readable description.
52
+ * @param options - Preserved API error metadata.
53
+ */
54
+ constructor(message: string, options: Omit<WaveApiErrorOptions, 'statusCode'>) {
55
+ super(message, { ...options, statusCode: 401 });
56
+ }
57
+ }
58
+
59
+ /**
60
+ * Error returned when the key lacks permission for the request, the wallet cannot use the API, or
61
+ * the source IP is not allowlisted (HTTP 403).
62
+ */
63
+ export class WaveAuthorizationError extends WaveApiError {
64
+ /**
65
+ * @param message - Human-readable description.
66
+ * @param options - Preserved API error metadata.
67
+ */
68
+ constructor(message: string, options: Omit<WaveApiErrorOptions, 'statusCode'>) {
69
+ super(message, { ...options, statusCode: 403 });
70
+ }
71
+ }
72
+
73
+ /**
74
+ * Error returned when the requested resource does not exist (HTTP 404).
75
+ */
76
+ export class WaveNotFoundError extends WaveApiError {
77
+ /**
78
+ * @param message - Human-readable description.
79
+ * @param options - Preserved API error metadata.
80
+ */
81
+ constructor(message: string, options: Omit<WaveApiErrorOptions, 'statusCode'>) {
82
+ super(message, { ...options, statusCode: 404 });
83
+ }
84
+ }
85
+
86
+ /**
87
+ * Error returned for a malformed or semantically invalid request (HTTP 400 or 422).
88
+ */
89
+ export class WaveValidationError extends WaveApiError {
90
+ /**
91
+ * @param message - Human-readable description.
92
+ * @param options - Preserved API error metadata.
93
+ */
94
+ constructor(message: string, options: WaveApiErrorOptions) {
95
+ super(message, options);
96
+ }
97
+ }
98
+
99
+ /**
100
+ * Error returned when the request conflicts with the current resource state (HTTP 409).
101
+ */
102
+ export class WaveConflictError extends WaveApiError {
103
+ /**
104
+ * @param message - Human-readable description.
105
+ * @param options - Preserved API error metadata.
106
+ */
107
+ constructor(message: string, options: Omit<WaveApiErrorOptions, 'statusCode'>) {
108
+ super(message, { ...options, statusCode: 409 });
109
+ }
110
+ }
111
+
112
+ /**
113
+ * Options for rate-limit errors.
114
+ */
115
+ export interface WaveRateLimitErrorOptions extends Omit<WaveApiErrorOptions, 'statusCode'> {
116
+ /** Retry delay parsed from a `Retry-After` response header, when present. */
117
+ readonly retryAfterSeconds?: number;
118
+ }
119
+
120
+ /**
121
+ * Error returned when the rate limit is exceeded (HTTP 429).
122
+ */
123
+ export class WaveRateLimitError extends WaveApiError {
124
+ /** Retry delay parsed from `Retry-After`, when Wave provides one. */
125
+ readonly retryAfterSeconds: number | undefined;
126
+
127
+ /**
128
+ * @param message - Human-readable description.
129
+ * @param options - Preserved API error metadata and optional retry delay.
130
+ */
131
+ constructor(message: string, options: WaveRateLimitErrorOptions) {
132
+ super(message, { ...options, statusCode: 429 });
133
+ this.retryAfterSeconds = options.retryAfterSeconds;
134
+ }
135
+ }
136
+
137
+ /**
138
+ * Error returned when Wave fails to process a valid request (HTTP 5xx).
139
+ */
140
+ export class WaveServerError extends WaveApiError {
141
+ /**
142
+ * @param message - Human-readable description.
143
+ * @param options - Preserved API error metadata.
144
+ */
145
+ constructor(message: string, options: WaveApiErrorOptions) {
146
+ super(message, options);
147
+ }
148
+ }
@@ -0,0 +1,32 @@
1
+ /**
2
+ * Options shared by all SDK errors.
3
+ */
4
+ export interface WaveErrorOptions {
5
+ /** Machine-readable error code, when the API or SDK provides one. */
6
+ readonly code?: string;
7
+ /** Underlying error that caused this one. */
8
+ readonly cause?: unknown;
9
+ }
10
+
11
+ /**
12
+ * Base class for every error thrown by the SDK.
13
+ */
14
+ export class WaveError extends Error {
15
+ /** Machine-readable error code, when available. */
16
+ readonly code: string | undefined;
17
+
18
+ /**
19
+ * @param message - Human-readable description that never contains credentials.
20
+ * @param options - Optional error code and cause.
21
+ */
22
+ constructor(message: string, options: WaveErrorOptions = {}) {
23
+ super(message, options.cause === undefined ? undefined : { cause: options.cause });
24
+ this.name = new.target.name;
25
+ this.code = options.code;
26
+ }
27
+ }
28
+
29
+ /**
30
+ * Configuration or caller-input error raised before any request is sent.
31
+ */
32
+ export class WaveConfigurationError extends WaveError {}
@@ -0,0 +1,24 @@
1
+ import { WaveError } from './wave-error.js';
2
+
3
+ /**
4
+ * Error raised when a request cannot reach Wave or the connection fails.
5
+ */
6
+ export class WaveNetworkError extends WaveError {
7
+ /**
8
+ * @param message - Human-readable description.
9
+ * @param options - Optional underlying cause.
10
+ */
11
+ constructor(message: string, options: { readonly cause?: unknown } = {}) {
12
+ super(message, options.cause === undefined ? {} : { cause: options.cause });
13
+ }
14
+ }
15
+
16
+ /**
17
+ * Error raised when a request exceeds its configured timeout.
18
+ */
19
+ export class WaveTimeoutError extends WaveNetworkError {}
20
+
21
+ /**
22
+ * Error raised when the caller aborts a request through an `AbortSignal`.
23
+ */
24
+ export class WaveAbortError extends WaveError {}