@nomba/node-sdk 0.0.0-stage → 0.3.0

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 (201) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +577 -2
  3. package/dist/index.d.ts +86 -0
  4. package/dist/index.js +53 -0
  5. package/dist/interfaces/http/IHttpClient.d.ts +17 -0
  6. package/dist/interfaces/http/IHttpClient.js +5 -0
  7. package/dist/interfaces/http/index.d.ts +1 -0
  8. package/dist/interfaces/http/index.js +1 -0
  9. package/dist/interfaces/v1/accounts/IAccountsService.d.ts +62 -0
  10. package/dist/interfaces/v1/accounts/IAccountsService.js +5 -0
  11. package/dist/interfaces/v1/accounts/index.d.ts +1 -0
  12. package/dist/interfaces/v1/accounts/index.js +1 -0
  13. package/dist/interfaces/v1/betting/IBettingService.d.ts +20 -0
  14. package/dist/interfaces/v1/betting/IBettingService.js +5 -0
  15. package/dist/interfaces/v1/betting/index.d.ts +1 -0
  16. package/dist/interfaces/v1/betting/index.js +1 -0
  17. package/dist/interfaces/v1/cable/ICableService.d.ts +21 -0
  18. package/dist/interfaces/v1/cable/ICableService.js +5 -0
  19. package/dist/interfaces/v1/cable/index.d.ts +1 -0
  20. package/dist/interfaces/v1/cable/index.js +1 -0
  21. package/dist/interfaces/v1/charge/IChargeService.d.ts +94 -0
  22. package/dist/interfaces/v1/charge/IChargeService.js +5 -0
  23. package/dist/interfaces/v1/charge/index.d.ts +1 -0
  24. package/dist/interfaces/v1/charge/index.js +1 -0
  25. package/dist/interfaces/v1/checkout/ICheckoutService.d.ts +79 -0
  26. package/dist/interfaces/v1/checkout/ICheckoutService.js +5 -0
  27. package/dist/interfaces/v1/checkout/index.d.ts +1 -0
  28. package/dist/interfaces/v1/checkout/index.js +1 -0
  29. package/dist/interfaces/v1/data/IDataService.d.ts +14 -0
  30. package/dist/interfaces/v1/data/IDataService.js +5 -0
  31. package/dist/interfaces/v1/data/index.d.ts +1 -0
  32. package/dist/interfaces/v1/data/index.js +1 -0
  33. package/dist/interfaces/v1/direct-debits/IDirectDebitsService.d.ts +54 -0
  34. package/dist/interfaces/v1/direct-debits/IDirectDebitsService.js +5 -0
  35. package/dist/interfaces/v1/direct-debits/index.d.ts +1 -0
  36. package/dist/interfaces/v1/direct-debits/index.js +1 -0
  37. package/dist/interfaces/v1/electricity/IElectricityService.d.ts +20 -0
  38. package/dist/interfaces/v1/electricity/IElectricityService.js +5 -0
  39. package/dist/interfaces/v1/electricity/index.d.ts +1 -0
  40. package/dist/interfaces/v1/electricity/index.js +1 -0
  41. package/dist/interfaces/v1/globals/collections/IGlobalCollectionsService.d.ts +29 -0
  42. package/dist/interfaces/v1/globals/collections/IGlobalCollectionsService.js +5 -0
  43. package/dist/interfaces/v1/globals/collections/index.d.ts +1 -0
  44. package/dist/interfaces/v1/globals/collections/index.js +1 -0
  45. package/dist/interfaces/v1/globals/payouts/IGlobalPayoutService.d.ts +91 -0
  46. package/dist/interfaces/v1/globals/payouts/IGlobalPayoutService.js +5 -0
  47. package/dist/interfaces/v1/globals/payouts/index.d.ts +1 -0
  48. package/dist/interfaces/v1/globals/payouts/index.js +1 -0
  49. package/dist/interfaces/v1/requery/IRequeryService.d.ts +31 -0
  50. package/dist/interfaces/v1/requery/IRequeryService.js +5 -0
  51. package/dist/interfaces/v1/requery/index.d.ts +1 -0
  52. package/dist/interfaces/v1/requery/index.js +1 -0
  53. package/dist/interfaces/v1/terminals/ITerminalsService.d.ts +51 -0
  54. package/dist/interfaces/v1/terminals/ITerminalsService.js +5 -0
  55. package/dist/interfaces/v1/terminals/index.d.ts +1 -0
  56. package/dist/interfaces/v1/terminals/index.js +1 -0
  57. package/dist/interfaces/v1/transactions/ITransactionsService.d.ts +93 -0
  58. package/dist/interfaces/v1/transactions/ITransactionsService.js +5 -0
  59. package/dist/interfaces/v1/transactions/index.d.ts +1 -0
  60. package/dist/interfaces/v1/transactions/index.js +1 -0
  61. package/dist/interfaces/v1/virtual-accounts/IVirtualAccountsService.d.ts +65 -0
  62. package/dist/interfaces/v1/virtual-accounts/IVirtualAccountsService.js +5 -0
  63. package/dist/interfaces/v1/virtual-accounts/index.d.ts +1 -0
  64. package/dist/interfaces/v1/virtual-accounts/index.js +1 -0
  65. package/dist/interfaces/v1/webhooks/IWebhooksService.d.ts +40 -0
  66. package/dist/interfaces/v1/webhooks/IWebhooksService.js +5 -0
  67. package/dist/interfaces/v1/webhooks/index.d.ts +1 -0
  68. package/dist/interfaces/v1/webhooks/index.js +1 -0
  69. package/dist/interfaces/v2/airtime/IAirtimeV2Service.d.ts +31 -0
  70. package/dist/interfaces/v2/airtime/IAirtimeV2Service.js +5 -0
  71. package/dist/interfaces/v2/airtime/index.d.ts +1 -0
  72. package/dist/interfaces/v2/airtime/index.js +1 -0
  73. package/dist/interfaces/v2/betting/IBettingV2Service.d.ts +31 -0
  74. package/dist/interfaces/v2/betting/IBettingV2Service.js +5 -0
  75. package/dist/interfaces/v2/betting/index.d.ts +1 -0
  76. package/dist/interfaces/v2/betting/index.js +1 -0
  77. package/dist/interfaces/v2/cable/ICableV2Service.d.ts +31 -0
  78. package/dist/interfaces/v2/cable/ICableV2Service.js +5 -0
  79. package/dist/interfaces/v2/cable/index.d.ts +1 -0
  80. package/dist/interfaces/v2/cable/index.js +1 -0
  81. package/dist/interfaces/v2/data/IDataV2Service.d.ts +31 -0
  82. package/dist/interfaces/v2/data/IDataV2Service.js +5 -0
  83. package/dist/interfaces/v2/data/index.d.ts +1 -0
  84. package/dist/interfaces/v2/data/index.js +1 -0
  85. package/dist/interfaces/v2/electricity/IElectricityV2Service.d.ts +32 -0
  86. package/dist/interfaces/v2/electricity/IElectricityV2Service.js +5 -0
  87. package/dist/interfaces/v2/electricity/index.d.ts +1 -0
  88. package/dist/interfaces/v2/electricity/index.js +1 -0
  89. package/dist/interfaces/v2/transfers/ITransfersService.d.ts +71 -0
  90. package/dist/interfaces/v2/transfers/ITransfersService.js +5 -0
  91. package/dist/interfaces/v2/transfers/index.d.ts +1 -0
  92. package/dist/interfaces/v2/transfers/index.js +1 -0
  93. package/dist/lib/errors.d.ts +62 -0
  94. package/dist/lib/errors.js +92 -0
  95. package/dist/lib/outcome.d.ts +37 -0
  96. package/dist/lib/outcome.js +126 -0
  97. package/dist/lib/paginate.d.ts +21 -0
  98. package/dist/lib/paginate.js +25 -0
  99. package/dist/lib/sdk-version.d.ts +5 -0
  100. package/dist/lib/sdk-version.generated.d.ts +1 -0
  101. package/dist/lib/sdk-version.generated.js +1 -0
  102. package/dist/lib/sdk-version.js +5 -0
  103. package/dist/lib/token-store.d.ts +49 -0
  104. package/dist/lib/token-store.js +26 -0
  105. package/dist/lib/util.d.ts +31 -0
  106. package/dist/lib/util.js +31 -0
  107. package/dist/lib/webhooks.d.ts +43 -0
  108. package/dist/lib/webhooks.js +64 -0
  109. package/dist/nomba.d.ts +96 -0
  110. package/dist/nomba.js +130 -0
  111. package/dist/services/http/http-client.service.d.ts +61 -0
  112. package/dist/services/http/http-client.service.js +351 -0
  113. package/dist/services/v1/accounts/accounts.service.d.ts +76 -0
  114. package/dist/services/v1/accounts/accounts.service.js +96 -0
  115. package/dist/services/v1/betting/betting.service.d.ts +25 -0
  116. package/dist/services/v1/betting/betting.service.js +30 -0
  117. package/dist/services/v1/cable/cable.service.d.ts +26 -0
  118. package/dist/services/v1/cable/cable.service.js +33 -0
  119. package/dist/services/v1/charge/charge.service.d.ts +113 -0
  120. package/dist/services/v1/charge/charge.service.js +161 -0
  121. package/dist/services/v1/checkout/checkout.service.d.ts +92 -0
  122. package/dist/services/v1/checkout/checkout.service.js +146 -0
  123. package/dist/services/v1/data/data.service.d.ts +20 -0
  124. package/dist/services/v1/data/data.service.js +22 -0
  125. package/dist/services/v1/direct-debits/direct-debits.service.d.ts +69 -0
  126. package/dist/services/v1/direct-debits/direct-debits.service.js +91 -0
  127. package/dist/services/v1/electricity/electricity.service.d.ts +26 -0
  128. package/dist/services/v1/electricity/electricity.service.js +31 -0
  129. package/dist/services/v1/globals/collections.service.d.ts +44 -0
  130. package/dist/services/v1/globals/collections.service.js +55 -0
  131. package/dist/services/v1/globals/payout.service.d.ts +105 -0
  132. package/dist/services/v1/globals/payout.service.js +154 -0
  133. package/dist/services/v1/requery/requery.service.d.ts +31 -0
  134. package/dist/services/v1/requery/requery.service.js +41 -0
  135. package/dist/services/v1/terminals/terminals.service.d.ts +38 -0
  136. package/dist/services/v1/terminals/terminals.service.js +58 -0
  137. package/dist/services/v1/transactions/transactions.service.d.ts +48 -0
  138. package/dist/services/v1/transactions/transactions.service.js +98 -0
  139. package/dist/services/v1/virtual-accounts/virtual-accounts.service.d.ts +40 -0
  140. package/dist/services/v1/virtual-accounts/virtual-accounts.service.js +55 -0
  141. package/dist/services/v1/webhooks/webhooks.service.d.ts +35 -0
  142. package/dist/services/v1/webhooks/webhooks.service.js +59 -0
  143. package/dist/services/v2/airtime/airtime.service.d.ts +42 -0
  144. package/dist/services/v2/airtime/airtime.service.js +55 -0
  145. package/dist/services/v2/betting/betting.service.d.ts +43 -0
  146. package/dist/services/v2/betting/betting.service.js +56 -0
  147. package/dist/services/v2/cable/cable.service.d.ts +43 -0
  148. package/dist/services/v2/cable/cable.service.js +56 -0
  149. package/dist/services/v2/data/data.service.d.ts +42 -0
  150. package/dist/services/v2/data/data.service.js +55 -0
  151. package/dist/services/v2/electricity/electricity.service.d.ts +44 -0
  152. package/dist/services/v2/electricity/electricity.service.js +57 -0
  153. package/dist/services/v2/transfers/transfers.service.d.ts +75 -0
  154. package/dist/services/v2/transfers/transfers.service.js +97 -0
  155. package/dist/types/common/common.types.d.ts +74 -0
  156. package/dist/types/common/common.types.js +5 -0
  157. package/dist/types/common/outcome.types.d.ts +53 -0
  158. package/dist/types/common/outcome.types.js +5 -0
  159. package/dist/types/v1/accounts/accounts.types.d.ts +37 -0
  160. package/dist/types/v1/accounts/accounts.types.js +8 -0
  161. package/dist/types/v1/betting/betting.types.d.ts +26 -0
  162. package/dist/types/v1/betting/betting.types.js +5 -0
  163. package/dist/types/v1/cable/cable.types.d.ts +24 -0
  164. package/dist/types/v1/cable/cable.types.js +5 -0
  165. package/dist/types/v1/charge/charge.types.d.ts +102 -0
  166. package/dist/types/v1/charge/charge.types.js +5 -0
  167. package/dist/types/v1/checkout/checkout.types.d.ts +139 -0
  168. package/dist/types/v1/checkout/checkout.types.js +5 -0
  169. package/dist/types/v1/data/data.types.d.ts +14 -0
  170. package/dist/types/v1/data/data.types.js +5 -0
  171. package/dist/types/v1/direct-debits/direct-debits.types.d.ts +104 -0
  172. package/dist/types/v1/direct-debits/direct-debits.types.js +5 -0
  173. package/dist/types/v1/electricity/electricity.types.d.ts +21 -0
  174. package/dist/types/v1/electricity/electricity.types.js +5 -0
  175. package/dist/types/v1/globals/collections.types.d.ts +49 -0
  176. package/dist/types/v1/globals/collections.types.js +5 -0
  177. package/dist/types/v1/globals/payout.types.d.ts +183 -0
  178. package/dist/types/v1/globals/payout.types.js +5 -0
  179. package/dist/types/v1/requery/requery.types.d.ts +49 -0
  180. package/dist/types/v1/requery/requery.types.js +5 -0
  181. package/dist/types/v1/terminals/terminals.types.d.ts +44 -0
  182. package/dist/types/v1/terminals/terminals.types.js +5 -0
  183. package/dist/types/v1/transactions/transactions.types.d.ts +87 -0
  184. package/dist/types/v1/transactions/transactions.types.js +5 -0
  185. package/dist/types/v1/virtual-accounts/virtual-accounts.types.d.ts +64 -0
  186. package/dist/types/v1/virtual-accounts/virtual-accounts.types.js +5 -0
  187. package/dist/types/v1/webhooks/webhooks.types.d.ts +54 -0
  188. package/dist/types/v1/webhooks/webhooks.types.js +5 -0
  189. package/dist/types/v2/airtime/airtime.types.d.ts +31 -0
  190. package/dist/types/v2/airtime/airtime.types.js +5 -0
  191. package/dist/types/v2/betting/betting.types.d.ts +33 -0
  192. package/dist/types/v2/betting/betting.types.js +5 -0
  193. package/dist/types/v2/cable/cable.types.d.ts +32 -0
  194. package/dist/types/v2/cable/cable.types.js +5 -0
  195. package/dist/types/v2/data/data.types.d.ts +32 -0
  196. package/dist/types/v2/data/data.types.js +5 -0
  197. package/dist/types/v2/electricity/electricity.types.d.ts +34 -0
  198. package/dist/types/v2/electricity/electricity.types.js +5 -0
  199. package/dist/types/v2/transfers/transfers.types.d.ts +99 -0
  200. package/dist/types/v2/transfers/transfers.types.js +5 -0
  201. package/package.json +42 -5
@@ -0,0 +1,351 @@
1
+ /**
2
+ * @module nomba/services/http
3
+ * @description Authenticated HTTP transport: token lifecycle, retries, response envelope
4
+ */
5
+ import { randomUUID } from "node:crypto";
6
+ import { NombaError, OutcomeUnknownError, TokenError, } from "../../lib/errors.js";
7
+ import { SDK_VERSION } from "../../lib/sdk-version.js";
8
+ import { MemoryTokenStore, } from "../../lib/token-store.js";
9
+ import { assertKey, sleep } from "../../lib/util.js";
10
+ const BASE_URLS = {
11
+ production: "https://api.nomba.com",
12
+ sandbox: "https://sandbox.nomba.com",
13
+ };
14
+ // Docs: refresh the access_token at least 5 minutes before it expires.
15
+ const REFRESH_MARGIN_MS = 5 * 60_000;
16
+ // A failed store.set() is retried this many times (100ms, 200ms apart) before giving up on the shared copy.
17
+ const SET_RETRIES = 2;
18
+ /**
19
+ * Authenticated HTTP transport for the Nomba API: owns the token lifecycle (issue, refresh, revoke,
20
+ * sharing via `TokenStore`) and the retry/idempotency rules for `request`.
21
+ */
22
+ export class HttpClient {
23
+ environment;
24
+ #options;
25
+ #baseUrl;
26
+ #store;
27
+ #pending;
28
+ // This process's copy of the latest token, used when the shared store is failing.
29
+ #local;
30
+ // True when the last store.set() failed, so #local is newer than whatever the store holds.
31
+ #unsynced = false;
32
+ constructor(options) {
33
+ this.#options = options;
34
+ this.#store = options.tokenStore ?? new MemoryTokenStore();
35
+ const env = options.environment ?? "production";
36
+ if (!Object.hasOwn(BASE_URLS, env))
37
+ throw new Error(`Unknown environment "${env}"; use "production" or "sandbox"`);
38
+ this.environment = env;
39
+ this.#baseUrl = BASE_URLS[env];
40
+ }
41
+ /**
42
+ * `POST /v1/auth/token/issue`.
43
+ * @returns The issued token data, saved to the configured `TokenStore`.
44
+ * @throws {NombaError} The credentials were rejected.
45
+ */
46
+ issueToken() {
47
+ return this.#locked(() => this.#issue());
48
+ }
49
+ /**
50
+ * `POST /v1/auth/token/refresh`.
51
+ * @returns The refreshed token data, saved to the configured `TokenStore`.
52
+ * @throws {Error} No token is held yet; call `issueToken()` first.
53
+ * @throws {NombaError} The refresh token was rejected.
54
+ */
55
+ refreshToken() {
56
+ return this.#locked(async () => {
57
+ const t = await this.#read();
58
+ if (!t)
59
+ throw new Error("No token to refresh; call issueToken() first");
60
+ return this.#refresh(t);
61
+ });
62
+ }
63
+ /**
64
+ * `POST /v1/auth/token/revoke`. A no-op if no token is held.
65
+ * @throws {NombaError} Nomba rejected the revoke call.
66
+ */
67
+ revokeToken() {
68
+ return this.#locked(async () => {
69
+ const t = await this.#read();
70
+ if (!t)
71
+ return;
72
+ await this.#send("POST", "/v1/auth/token/revoke", {
73
+ body: {
74
+ clientId: this.#options.clientId,
75
+ access_token: t.access_token,
76
+ },
77
+ });
78
+ this.#local = undefined;
79
+ this.#unsynced = false;
80
+ try {
81
+ await this.#store.clear();
82
+ }
83
+ catch (e) {
84
+ this.#onStoreError(e);
85
+ }
86
+ });
87
+ }
88
+ /**
89
+ * Authenticated call. Issues or refreshes the token as needed.
90
+ * Every non-GET call carries an idempotency key, so failures that leave the outcome unknown are retried
91
+ * safely, and surface as `OutcomeUnknownError` once retries run out.
92
+ * @param method The HTTP method.
93
+ * @param path The endpoint path, starting with `/`.
94
+ * @param options.body The JSON request body.
95
+ * @param options.query Query string parameters; entries with a `undefined` value are omitted.
96
+ * @param options.okCodes Body codes that are not errors. Defaults to `["00"]`.
97
+ * @param options.idempotencyKey Tracked in `OutcomeUnknownError` for non-GET calls; this generic
98
+ * transport does not send it to Nomba. Put the endpoint's actual idempotency field (for example
99
+ * `merchantTxRef`) in `options.body`. A random UUID is generated if omitted.
100
+ * @param options.codeField The response field holding the result code. Defaults to `"code"`.
101
+ * @param options.descriptionField The response field holding the error description. Defaults to
102
+ * `"description"`.
103
+ * @param options.envelope When true, resolves to `{ code, data }` instead of just `data`.
104
+ * @returns The response body's `data` field (or `{ code, data }` with `envelope: true`).
105
+ * @throws {TypeError} `path` does not start with `/`.
106
+ * @throws {TokenError} Getting or refreshing the access token failed; the request was never sent.
107
+ * @throws {NombaError} A non-2xx response, or a 2xx whose body code is not in `okCodes`.
108
+ * @throws {OutcomeUnknownError} A non-GET call failed in a way that does not say whether it was
109
+ * processed (timeout, network error, 5xx, or a 409); check its status before retrying.
110
+ */
111
+ async request(method, path, { body, query, okCodes, idempotencyKey, codeField, descriptionField, envelope, } = {}) {
112
+ // The URL is base + path, so a path not starting with "/" (".evil.com", "@evil.com") would change the host
113
+ // and send the bearer token there. Checked before the token is even read.
114
+ if (!path.startsWith("/"))
115
+ throw new TypeError(`path must start with "/", like "/v1/...", got ${JSON.stringify(path)}`);
116
+ const qs = new URLSearchParams(Object.entries(query ?? {}).flatMap(([k, v]) => v === undefined ? [] : [[k, String(v)]])).toString();
117
+ const url = qs ? `${path}?${qs}` : path;
118
+ // One key for every attempt of this call, including the retry after a 401 token renewal.
119
+ const key = method === "GET" ? undefined : idempotencyKey || randomUUID();
120
+ if (key !== undefined)
121
+ assertKey(key);
122
+ const token = await this.#tokenForRequest();
123
+ try {
124
+ return await this.#send(method, url, {
125
+ body,
126
+ bearer: token,
127
+ okCodes,
128
+ idempotencyKey: key,
129
+ codeField,
130
+ descriptionField,
131
+ envelope,
132
+ });
133
+ }
134
+ catch (e) {
135
+ // Docs: a 401 signals the access_token expired; renew it and retry once.
136
+ if (!(e instanceof NombaError && e.status === 401))
137
+ throw e;
138
+ return this.#send(method, url, {
139
+ body,
140
+ bearer: await this.#tokenForRequest(token),
141
+ okCodes,
142
+ idempotencyKey: key,
143
+ codeField,
144
+ descriptionField,
145
+ envelope,
146
+ });
147
+ }
148
+ }
149
+ /** Invokes the configured `onOutcome` hook, if any, swallowing any error it throws. */
150
+ reportOutcome(event) {
151
+ this.#hook(() => this.#options.onOutcome?.(event));
152
+ }
153
+ // A caller's hook must never break a request: its errors are logged instead.
154
+ #hook(fn) {
155
+ try {
156
+ fn();
157
+ }
158
+ catch (e) {
159
+ console.warn("nomba: hook threw", e);
160
+ }
161
+ }
162
+ // The store's lock (if any) makes every auth call exclusive across instances.
163
+ #locked(fn) {
164
+ return this.#store.lock ? this.#store.lock(fn) : fn();
165
+ }
166
+ async #issue() {
167
+ return this.#save(await this.#send("POST", "/v1/auth/token/issue", {
168
+ body: {
169
+ grant_type: "client_credentials",
170
+ client_id: this.#options.clientId,
171
+ client_secret: this.#options.clientSecret,
172
+ },
173
+ }));
174
+ }
175
+ async #refresh(t) {
176
+ return this.#save(await this.#send("POST", "/v1/auth/token/refresh", {
177
+ body: { grant_type: "refresh_token", refresh_token: t.refresh_token },
178
+ bearer: t.access_token,
179
+ }));
180
+ }
181
+ #onStoreError(e) {
182
+ (this.#options.onStoreError ?? console.warn)(e);
183
+ }
184
+ async #save(token) {
185
+ // Nomba has already rotated the session, so this token must not be lost even if the store fails.
186
+ this.#local = token;
187
+ for (let attempt = 0;; attempt++) {
188
+ try {
189
+ await this.#store.set(token);
190
+ this.#unsynced = false;
191
+ return token;
192
+ }
193
+ catch (e) {
194
+ if (attempt === SET_RETRIES) {
195
+ this.#unsynced = true;
196
+ this.#onStoreError(e);
197
+ return token;
198
+ }
199
+ await sleep(100 * (attempt + 1));
200
+ }
201
+ }
202
+ }
203
+ /** The shared store's token, or this process's newer copy when the store is failing or behind. */
204
+ async #read() {
205
+ let stored;
206
+ try {
207
+ stored = await this.#store.get();
208
+ }
209
+ catch (e) {
210
+ this.#onStoreError(e);
211
+ return this.#local;
212
+ }
213
+ const local = this.#local;
214
+ // The store is authoritative unless our last write to it failed.
215
+ if (!local || !this.#unsynced)
216
+ return stored;
217
+ return !stored || Date.parse(local.expiresAt) > Date.parse(stored.expiresAt)
218
+ ? local
219
+ : stored;
220
+ }
221
+ /** A stored token that is not `rejected` and is not within 5 minutes of expiry, else renew. */
222
+ // Token failures happen before the request is sent, so they must never look like a request's outcome.
223
+ async #tokenForRequest(rejected) {
224
+ try {
225
+ return await this.#accessToken(rejected);
226
+ }
227
+ catch (e) {
228
+ throw new TokenError(e);
229
+ }
230
+ }
231
+ async #accessToken(rejected) {
232
+ const usable = (t) => !!t &&
233
+ t.access_token !== rejected &&
234
+ Date.parse(t.expiresAt) - Date.now() > REFRESH_MARGIN_MS;
235
+ const cached = await this.#read();
236
+ if (usable(cached))
237
+ return cached.access_token;
238
+ // One in-flight renewal per process; the lock covers other instances.
239
+ const joined = !!this.#pending;
240
+ this.#pending ??= this.#locked(async () => {
241
+ // Another instance may have renewed while we waited for the lock.
242
+ const current = await this.#read();
243
+ if (usable(current))
244
+ return current;
245
+ if (!current)
246
+ return this.#issue();
247
+ try {
248
+ return await this.#refresh(current);
249
+ }
250
+ catch (e) {
251
+ // Only a rejected refresh_token warrants a full re-issue; not network, 429 or 5xx errors.
252
+ if (e instanceof NombaError && [400, 401, 403].includes(e.status))
253
+ return this.#issue();
254
+ throw e;
255
+ }
256
+ }).finally(() => {
257
+ this.#pending = undefined;
258
+ });
259
+ const renewed = await this.#pending;
260
+ // A renewal started by a caller that did not know `rejected` may hand back that same token.
261
+ if (joined && renewed.access_token === rejected)
262
+ return this.#accessToken(rejected);
263
+ return renewed.access_token;
264
+ }
265
+ /**
266
+ * One logical request, retried where that is verified safe:
267
+ * - 429: never processed (rejected before reaching business logic), so always retried, on GETs and
268
+ * mutating calls alike.
269
+ * - GET: also retried on a timeout, network error, 5xx or 409, since reading data twice is harmless.
270
+ * - A mutating call (has an idempotencyKey): NOT auto-retried on a timeout, network error, 5xx or 409.
271
+ * Nomba uses merchantTxRef in the request body for idempotency, not headers. Retrying automatically
272
+ * with a different merchantTxRef could double-execute payments. Such a call fails after one attempt
273
+ * with OutcomeUnknownError; the caller decides whether and how to retry (using the same merchantTxRef).
274
+ * - Any other 4xx, or a non-ok body code: a definite rejection, thrown as is, no retry, for either kind.
275
+ */
276
+ async #send(method, path, { body, bearer, okCodes = ["00"], idempotencyKey, codeField = "code", descriptionField = "description", envelope = false, } = {}) {
277
+ const maxAttempts = this.#options.maxAttempts ?? 3;
278
+ const baseDelay = this.#options.retryDelayMs ?? 500;
279
+ const payload = body === undefined ? undefined : JSON.stringify(body);
280
+ for (let attempt = 1;; attempt++) {
281
+ try {
282
+ const hookPath = path.split("?")[0] ?? path;
283
+ this.#hook(() => this.#options.onRequest?.({ method, path: hookPath, attempt }));
284
+ const started = Date.now();
285
+ const res = await (this.#options.fetch ?? fetch)(this.#baseUrl + path, {
286
+ method,
287
+ headers: {
288
+ accountId: this.#options.accountId,
289
+ "X-Nomba-Sdk-Version": SDK_VERSION,
290
+ ...(payload === undefined
291
+ ? {}
292
+ : { "Content-Type": "application/json" }),
293
+ ...(bearer ? { Authorization: `Bearer ${bearer}` } : {}),
294
+ },
295
+ ...(payload === undefined ? {} : { body: payload }),
296
+ signal: AbortSignal.timeout(this.#options.timeoutMs ?? 30_000),
297
+ });
298
+ let json = null;
299
+ try {
300
+ json = (await res.json());
301
+ }
302
+ catch {
303
+ // A 2xx we could not read (cut off, timed out mid-body, not JSON): whether it took effect is unknown.
304
+ if (res.ok)
305
+ throw new Error(`Unreadable response (HTTP ${res.status})`);
306
+ }
307
+ // Docs: a 200 does not always mean success; the body's code field must be "00" (or one the
308
+ // caller accepts). Most endpoints call it `code`; codeField lets one call it something else.
309
+ const code = json?.[codeField];
310
+ this.#hook(() => this.#options.onResponse?.({
311
+ method,
312
+ path: hookPath,
313
+ attempt,
314
+ httpStatus: res.status,
315
+ ...(typeof code === "string" ? { code } : {}),
316
+ durationMs: Date.now() - started,
317
+ }));
318
+ if (!res.ok ||
319
+ !json ||
320
+ typeof code !== "string" ||
321
+ !okCodes.includes(code)) {
322
+ throw new NombaError(res.status, typeof code === "string" ? code : String(res.status), json?.[descriptionField] ?? res.statusText);
323
+ }
324
+ return (envelope ? { code, data: json.data } : json.data);
325
+ }
326
+ catch (e) {
327
+ const status = e instanceof NombaError ? e.status : undefined;
328
+ // 409 is "same key still being processed" (retry) or a real key conflict (definite): only the
329
+ // message tells them apart.
330
+ const inFlight = status === 409 &&
331
+ /being processed|retry/i.test(e.description);
332
+ if (status !== undefined &&
333
+ status < 500 &&
334
+ status !== 408 &&
335
+ status !== 429 &&
336
+ !inFlight)
337
+ throw e;
338
+ // Verified unsafe to retry a mutating call on anything but 429 (see #send's doc comment).
339
+ const safeToRepeat = status === 429 || method === "GET";
340
+ if (attempt < maxAttempts && safeToRepeat) {
341
+ const delay = baseDelay * 2 ** (attempt - 1);
342
+ await sleep(delay + Math.random() * delay * 0.2);
343
+ continue;
344
+ }
345
+ if (status === 429 || !idempotencyKey)
346
+ throw e;
347
+ throw new OutcomeUnknownError(method, path, idempotencyKey, attempt, e);
348
+ }
349
+ }
350
+ }
351
+ }
@@ -0,0 +1,76 @@
1
+ /**
2
+ * @module nomba/accounts
3
+ * @description Nomba SDK for Node.js
4
+ * @description Accounts resource
5
+ * @author Nomba Financial Services
6
+ * @version 1.0.0
7
+ * @license MIT
8
+ * @copyright 2026 Nomba
9
+ * @homepage https://nomba.com
10
+ * @support https://nomba.com/support
11
+ * @repository https://github.com/kudi-inc/nomba-sdk-node
12
+ * @docs https://developer.nomba.com
13
+ * @see https://developer.nomba.com/docs/api-reference/accounts
14
+ */
15
+ import type { IHttpClient } from "../../../interfaces/http/IHttpClient.js";
16
+ import type { IAccountsService } from "../../../interfaces/v1/accounts/index.js";
17
+ import type { AccountBalance, AccountDetails, SubAccountLookup } from "../../../types/v1/accounts/accounts.types.js";
18
+ import type { Terminal, TerminalList, TerminalListParams } from "../../../types/v1/terminals/terminals.types.js";
19
+ export declare class AccountsService implements IAccountsService {
20
+ private readonly http;
21
+ constructor(http: IHttpClient);
22
+ /**
23
+ * `GET /v1/accounts/parent`.
24
+ * @returns The parent account's details.
25
+ * @throws {NombaError} The call failed.
26
+ */
27
+ getParentAccount(): Promise<AccountDetails>;
28
+ /**
29
+ * `GET /v1/accounts/balance`.
30
+ * @returns The parent account's balance.
31
+ * @throws {NombaError} The call failed.
32
+ */
33
+ getParentBalance(): Promise<AccountBalance>;
34
+ /**
35
+ * `GET /v1/accounts/sub-account-details`.
36
+ * @param lookup Which sub account to fetch, by account ID or account number.
37
+ * @returns The sub account's details.
38
+ * @throws {NombaError} The call failed, e.g. no sub account matches `lookup`.
39
+ */
40
+ getSubAccount(lookup?: SubAccountLookup): Promise<AccountDetails>;
41
+ /**
42
+ * `GET /v1/accounts/{subAccountId}/balance`.
43
+ * @param subAccountId The sub account's ID.
44
+ * @returns The sub account's balance.
45
+ * @throws {NombaError} The call failed, e.g. `subAccountId` does not exist.
46
+ */
47
+ getSubAccountBalance(subAccountId: string): Promise<AccountBalance>;
48
+ /**
49
+ * `GET /v1/accounts/terminals`.
50
+ * @param params Pagination (`cursor`, `size`) and other list filters.
51
+ * @returns One page of the parent account's terminals.
52
+ * @throws {NombaError} The call failed.
53
+ */
54
+ listParentTerminals(params?: TerminalListParams): Promise<TerminalList>;
55
+ /**
56
+ * `GET /v1/accounts/{accountId}/terminals`.
57
+ * @param accountId The sub account's ID.
58
+ * @param params Pagination (`cursor`, `size`) and other list filters.
59
+ * @returns One page of the sub account's terminals.
60
+ * @throws {NombaError} The call failed, e.g. `accountId` does not exist.
61
+ */
62
+ listSubAccountTerminals(accountId: string, params?: TerminalListParams): Promise<TerminalList>;
63
+ /**
64
+ * Every terminal of the parent account, across all pages. Starts at `params.cursor` if given.
65
+ * @param params Starting cursor and other list filters.
66
+ * @throws {NombaError} A page request failed.
67
+ */
68
+ iterateParentTerminals(params?: TerminalListParams): AsyncGenerator<Terminal>;
69
+ /**
70
+ * Every terminal of a sub account, across all pages. Starts at `params.cursor` if given.
71
+ * @param accountId The sub account's ID.
72
+ * @param params Starting cursor and other list filters.
73
+ * @throws {NombaError} A page request failed, e.g. `accountId` does not exist.
74
+ */
75
+ iterateSubAccountTerminals(accountId: string, params?: TerminalListParams): AsyncGenerator<Terminal>;
76
+ }
@@ -0,0 +1,96 @@
1
+ /**
2
+ * @module nomba/accounts
3
+ * @description Nomba SDK for Node.js
4
+ * @description Accounts resource
5
+ * @author Nomba Financial Services
6
+ * @version 1.0.0
7
+ * @license MIT
8
+ * @copyright 2026 Nomba
9
+ * @homepage https://nomba.com
10
+ * @support https://nomba.com/support
11
+ * @repository https://github.com/kudi-inc/nomba-sdk-node
12
+ * @docs https://developer.nomba.com
13
+ * @see https://developer.nomba.com/docs/api-reference/accounts
14
+ */
15
+ import { paginate } from "../../../lib/paginate.js";
16
+ import { pageQuery, pathId } from "../../../lib/util.js";
17
+ export class AccountsService {
18
+ http;
19
+ constructor(http) {
20
+ this.http = http;
21
+ }
22
+ /**
23
+ * `GET /v1/accounts/parent`.
24
+ * @returns The parent account's details.
25
+ * @throws {NombaError} The call failed.
26
+ */
27
+ getParentAccount() {
28
+ return this.http.request("GET", "/v1/accounts/parent");
29
+ }
30
+ /**
31
+ * `GET /v1/accounts/balance`.
32
+ * @returns The parent account's balance.
33
+ * @throws {NombaError} The call failed.
34
+ */
35
+ getParentBalance() {
36
+ return this.http.request("GET", "/v1/accounts/balance");
37
+ }
38
+ /**
39
+ * `GET /v1/accounts/sub-account-details`.
40
+ * @param lookup Which sub account to fetch, by account ID or account number.
41
+ * @returns The sub account's details.
42
+ * @throws {NombaError} The call failed, e.g. no sub account matches `lookup`.
43
+ */
44
+ getSubAccount(lookup = {}) {
45
+ return this.http.request("GET", "/v1/accounts/sub-account-details", {
46
+ query: lookup,
47
+ });
48
+ }
49
+ /**
50
+ * `GET /v1/accounts/{subAccountId}/balance`.
51
+ * @param subAccountId The sub account's ID.
52
+ * @returns The sub account's balance.
53
+ * @throws {NombaError} The call failed, e.g. `subAccountId` does not exist.
54
+ */
55
+ async getSubAccountBalance(subAccountId) {
56
+ return this.http.request("GET", `/v1/accounts/${pathId(subAccountId)}/balance`);
57
+ }
58
+ /**
59
+ * `GET /v1/accounts/terminals`.
60
+ * @param params Pagination (`cursor`, `size`) and other list filters.
61
+ * @returns One page of the parent account's terminals.
62
+ * @throws {NombaError} The call failed.
63
+ */
64
+ listParentTerminals(params = {}) {
65
+ return this.http.request("GET", "/v1/accounts/terminals", {
66
+ query: pageQuery(params),
67
+ });
68
+ }
69
+ /**
70
+ * `GET /v1/accounts/{accountId}/terminals`.
71
+ * @param accountId The sub account's ID.
72
+ * @param params Pagination (`cursor`, `size`) and other list filters.
73
+ * @returns One page of the sub account's terminals.
74
+ * @throws {NombaError} The call failed, e.g. `accountId` does not exist.
75
+ */
76
+ async listSubAccountTerminals(accountId, params = {}) {
77
+ return this.http.request("GET", `/v1/accounts/${pathId(accountId)}/terminals`, { query: pageQuery(params) });
78
+ }
79
+ /**
80
+ * Every terminal of the parent account, across all pages. Starts at `params.cursor` if given.
81
+ * @param params Starting cursor and other list filters.
82
+ * @throws {NombaError} A page request failed.
83
+ */
84
+ iterateParentTerminals(params = {}) {
85
+ return paginate((cursor) => this.listParentTerminals(cursor ? { ...params, cursor } : params));
86
+ }
87
+ /**
88
+ * Every terminal of a sub account, across all pages. Starts at `params.cursor` if given.
89
+ * @param accountId The sub account's ID.
90
+ * @param params Starting cursor and other list filters.
91
+ * @throws {NombaError} A page request failed, e.g. `accountId` does not exist.
92
+ */
93
+ iterateSubAccountTerminals(accountId, params = {}) {
94
+ return paginate((cursor) => this.listSubAccountTerminals(accountId, cursor ? { ...params, cursor } : params));
95
+ }
96
+ }
@@ -0,0 +1,25 @@
1
+ /**
2
+ * @module nomba/services/v1/betting
3
+ * @description Betting (v1): GET /v1/bill/betting/providers, GET /v1/bill/betting/lookup
4
+ * @see https://developer.nomba.com/docs/api-reference/bills
5
+ */
6
+ import type { IHttpClient } from "../../../interfaces/http/IHttpClient.js";
7
+ import type { IBettingService } from "../../../interfaces/v1/betting/index.js";
8
+ import type { BettingCustomerLookupParams, BettingCustomerLookupResult, BettingProvidersResult } from "../../../types/v1/betting/betting.types.js";
9
+ export declare class BettingService implements IBettingService {
10
+ private readonly http;
11
+ constructor(http: IHttpClient);
12
+ /**
13
+ * `GET /v1/bill/betting/providers`.
14
+ * @returns The supported betting providers.
15
+ * @throws {NombaError} The call failed.
16
+ */
17
+ getBettingProviders(): Promise<BettingProvidersResult>;
18
+ /**
19
+ * `GET /v1/bill/betting/lookup`. Validates a customer ID and returns the account name.
20
+ * @param params The provider and customer ID to look up.
21
+ * @returns The customer's account name.
22
+ * @throws {NombaError} The call failed, e.g. the customer ID is invalid.
23
+ */
24
+ lookupCustomer(params: BettingCustomerLookupParams): Promise<BettingCustomerLookupResult>;
25
+ }
@@ -0,0 +1,30 @@
1
+ /**
2
+ * @module nomba/services/v1/betting
3
+ * @description Betting (v1): GET /v1/bill/betting/providers, GET /v1/bill/betting/lookup
4
+ * @see https://developer.nomba.com/docs/api-reference/bills
5
+ */
6
+ export class BettingService {
7
+ http;
8
+ constructor(http) {
9
+ this.http = http;
10
+ }
11
+ /**
12
+ * `GET /v1/bill/betting/providers`.
13
+ * @returns The supported betting providers.
14
+ * @throws {NombaError} The call failed.
15
+ */
16
+ getBettingProviders() {
17
+ return this.http.request("GET", "/v1/bill/betting/providers");
18
+ }
19
+ /**
20
+ * `GET /v1/bill/betting/lookup`. Validates a customer ID and returns the account name.
21
+ * @param params The provider and customer ID to look up.
22
+ * @returns The customer's account name.
23
+ * @throws {NombaError} The call failed, e.g. the customer ID is invalid.
24
+ */
25
+ lookupCustomer(params) {
26
+ return this.http.request("GET", "/v1/bill/betting/lookup", {
27
+ query: params,
28
+ });
29
+ }
30
+ }
@@ -0,0 +1,26 @@
1
+ /**
2
+ * @module nomba/services/v1/cable
3
+ * @description Cable TV (v1): GET /v1/bill/cableTvProduct, GET /v1/bill/cable/lookup
4
+ * @see https://developer.nomba.com/docs/api-reference/bills
5
+ */
6
+ import type { IHttpClient } from "../../../interfaces/http/IHttpClient.js";
7
+ import type { ICableService } from "../../../interfaces/v1/cable/index.js";
8
+ import type { CableCustomerLookupParams, CableCustomerLookupResult, CablePlansParams, CablePlansResult } from "../../../types/v1/cable/cable.types.js";
9
+ export declare class CableService implements ICableService {
10
+ private readonly http;
11
+ constructor(http: IHttpClient);
12
+ /**
13
+ * `GET /v1/bill/cableTvProduct`.
14
+ * @param params The provider whose plans to fetch.
15
+ * @returns The provider's cable TV plans.
16
+ * @throws {NombaError} The call failed.
17
+ */
18
+ getCablePlans(params: CablePlansParams): Promise<CablePlansResult>;
19
+ /**
20
+ * `GET /v1/bill/cable/lookup`. Validates a smartcard number and returns the account name.
21
+ * @param params The provider and smartcard number to look up.
22
+ * @returns The customer's account name.
23
+ * @throws {NombaError} The call failed, e.g. the smartcard number is invalid.
24
+ */
25
+ lookupCustomer(params: CableCustomerLookupParams): Promise<CableCustomerLookupResult>;
26
+ }
@@ -0,0 +1,33 @@
1
+ /**
2
+ * @module nomba/services/v1/cable
3
+ * @description Cable TV (v1): GET /v1/bill/cableTvProduct, GET /v1/bill/cable/lookup
4
+ * @see https://developer.nomba.com/docs/api-reference/bills
5
+ */
6
+ export class CableService {
7
+ http;
8
+ constructor(http) {
9
+ this.http = http;
10
+ }
11
+ /**
12
+ * `GET /v1/bill/cableTvProduct`.
13
+ * @param params The provider whose plans to fetch.
14
+ * @returns The provider's cable TV plans.
15
+ * @throws {NombaError} The call failed.
16
+ */
17
+ getCablePlans(params) {
18
+ return this.http.request("GET", "/v1/bill/cableTvProduct", {
19
+ query: params,
20
+ });
21
+ }
22
+ /**
23
+ * `GET /v1/bill/cable/lookup`. Validates a smartcard number and returns the account name.
24
+ * @param params The provider and smartcard number to look up.
25
+ * @returns The customer's account name.
26
+ * @throws {NombaError} The call failed, e.g. the smartcard number is invalid.
27
+ */
28
+ lookupCustomer(params) {
29
+ return this.http.request("GET", "/v1/bill/cable/lookup", {
30
+ query: params,
31
+ });
32
+ }
33
+ }