// @moolre/sdk single-file ESM bundle. https://docs.moolre.com/sdks // src/errors.ts var MoolreError = class extends Error { constructor(message, options) { super(message); this.name = new.target.name; if (options?.cause !== void 0) this.cause = options.cause; } }; var ConfigurationError = class extends MoolreError { }; var ConnectionError = class extends MoolreError { }; var TimeoutError = class extends ConnectionError { }; var InvalidResponseError = class extends MoolreError { constructor(message, httpStatus, body, requestId) { super(message); this.httpStatus = httpStatus; this.body = body; this.requestId = requestId; } }; var ApiError = class extends MoolreError { code; apiMessage; /** Names of the request fields the API complained about (from `data`). */ fields; requestId; httpStatus; notices; result; constructor(result) { const msg = Array.isArray(result.message) ? result.message.join(" ") : String(result.message ?? ""); super(`${result.code}: ${msg}`); this.code = result.code; this.apiMessage = msg; this.fields = fieldsOf(result.data); this.requestId = result.requestId; this.httpStatus = result.httpStatus; this.notices = result.notices; this.result = result; } }; var AuthenticationError = class extends ApiError { }; var NotFoundError = class extends ApiError { }; var ValidationError = class extends ApiError { }; var IdempotencyError = class extends ApiError { }; var RateLimitError = class extends ApiError { }; var ServerError = class extends ApiError { }; var WebhookSignatureError = class extends MoolreError { constructor(reason, message) { super(message); this.reason = reason; } }; function fieldsOf(data) { if (typeof data === "string" && data !== "" && data !== "all") return [data]; if (Array.isArray(data)) return data.filter((x) => typeof x === "string"); return []; } var AUTH_CODES = /* @__PURE__ */ new Set(["AIN01", "AIN03", "IN01", "SW05"]); function classify(result) { const http = result.httpStatus; if (result.code === "IDEM01" || http === 409) return new IdempotencyError(result); if (result.code === "OTP429" || http === 429) return new RateLimitError(result); if (http === 401 || AUTH_CODES.has(result.code)) return new AuthenticationError(result); if (http === 404) return new NotFoundError(result); if (http === 400 || http === 422) return new ValidationError(result); if (http >= 500) return new ServerError(result); return new ApiError(result); } // src/http.ts var VERSION = "0.1.2"; var BASE_URLS = { live: "https://api.moolre.com", sandbox: "https://sandbox.moolre.com" }; var KEY_RE = /^[\x20-\x7e]{1,128}$/; function clean(obj) { const out = {}; for (const [k, v] of Object.entries(obj)) if (v !== void 0 && v !== null) out[k] = v; return out; } function requestIdOf(raw, headerReqId) { const m = raw.meta; if (m && typeof m === "object" && typeof m.requestid === "string") return m.requestid; return typeof raw.request_id === "string" ? raw.request_id : headerReqId; } function replayedOf(raw) { const m = raw.meta; if (m && typeof m === "object" && m.replayed === true) return true; return raw.replayed === true; } function noticesOf(raw) { const m = raw.meta; if (m && typeof m === "object" && Array.isArray(m.notices)) return m.notices; return Array.isArray(raw.notices) ? raw.notices : []; } var Transport = class { constructor(opts) { this.opts = opts; const env = opts.environment ?? "live"; if (env !== "live" && env !== "sandbox") throw new ConfigurationError(`environment must be "live" or "sandbox", got ${String(env)}`); this.baseUrl = (opts.baseUrl ?? BASE_URLS[env]).replace(/\/+$/, ""); this.logger = opts.logger === void 0 ? console : opts.logger; const f = opts.fetch ?? globalThis.fetch; if (!f) throw new ConfigurationError("No fetch implementation found. Use Node 18+ or pass options.fetch."); this.fetchImpl = f; } baseUrl; seenNotices = /* @__PURE__ */ new Set(); logger; fetchImpl; headers(spec) { const o = this.opts; const h = { Accept: "application/json", "User-Agent": `moolre-node/${VERSION}` }; if (spec.method !== "GET") h["Content-Type"] = "application/json"; if (o.user) h["X-API-USER"] = o.user; if (o.apiKey) h["X-API-KEY"] = o.apiKey; if (o.pubKey) h["X-API-PUBKEY"] = o.pubKey; if (o.vasKey) h["X-API-VASKEY"] = o.vasKey; if (o.strictHttpStatus) h["X-Moolre-Http-Status"] = "strict"; if (spec.idempotencyKey !== void 0) { if (!KEY_RE.test(spec.idempotencyKey)) { throw new ConfigurationError("idempotencyKey must be 1-128 printable ASCII characters"); } h["Idempotency-Key"] = spec.idempotencyKey; } return h; } async call(spec) { const o = this.opts; if (!o.user) throw new ConfigurationError("`user` (X-API-USER) is required"); if (spec.needs && !spec.needs.some((n) => o[n])) { const names = { apiKey: "apiKey (X-API-KEY)", pubKey: "pubKey (X-API-PUBKEY)", vasKey: "vasKey (X-API-VASKEY)" }; throw new ConfigurationError(`This call needs ${spec.needs.map((n) => names[n]).join(" or ")}`); } const method = spec.method ?? "POST"; let url = this.baseUrl + spec.path; if (spec.query) { const q = new URLSearchParams(); for (const [k, v] of Object.entries(clean(spec.query))) q.set(k, String(v)); const qs = q.toString(); if (qs) url += "?" + qs; } const headers = this.headers({ ...spec, method }); const payload = method === "POST" ? JSON.stringify(clean(spec.body ?? {})) : void 0; const retryable = spec.retry === "read" || spec.retry === "idempotent" && spec.idempotencyKey !== void 0; const maxRetries = retryable ? o.maxRetries ?? 2 : 0; const baseDelay = o.retryDelayMs ?? 500; for (let attempt = 0; ; attempt++) { let res; let text; try { const ctl = new AbortController(); const timer = setTimeout(() => ctl.abort(), o.timeoutMs ?? 6e4); try { res = await this.fetchImpl(url, { method, headers, body: payload, signal: ctl.signal }); text = await res.text(); } finally { clearTimeout(timer); } } catch (err) { const aborted = err?.name === "AbortError"; if (attempt < maxRetries) { await sleep(backoff(baseDelay, attempt)); continue; } throw aborted ? new TimeoutError(`Request to ${spec.path} timed out after ${o.timeoutMs ?? 6e4} ms`, { cause: err }) : new ConnectionError(`Request to ${spec.path} failed: ${err?.message ?? err}`, { cause: err }); } const reqId = res.headers.get("x-request-id"); if (res.status >= 500 && attempt < maxRetries) { await sleep(backoff(baseDelay, attempt)); continue; } let json; try { json = JSON.parse(text); } catch { json = void 0; } if (json === null || typeof json !== "object" || Array.isArray(json)) { throw new InvalidResponseError( `Moolre returned a non-JSON response (HTTP ${res.status})`, res.status, text.slice(0, 500), reqId ); } const result = this.toResult(json, res.status, reqId); this.logNotices(result.notices, result.requestId); if (!result.ok && o.throwOnError !== false) throw classify(result); return result; } } toResult(raw, httpStatus, headerReqId) { const status = raw.status ?? (httpStatus >= 200 && httpStatus < 300 ? 1 : 0); return { ok: String(status) === "1", status, code: raw.code === void 0 || raw.code === null ? "" : String(raw.code), message: raw.message ?? null, data: raw.data ?? null, go: raw.go ?? null, requestId: requestIdOf(raw, headerReqId), notices: noticesOf(raw), replayed: replayedOf(raw), httpStatus, raw }; } logNotices(notices, requestId) { if (!this.logger) return; for (const n of notices) { const code = String(n?.code ?? ""); if (this.seenNotices.has(code)) continue; this.seenNotices.add(code); this.logger.warn(`[moolre] ${code}: ${n?.message ?? ""}${n?.docs ? " (" + n.docs + ")" : ""}`, { requestId, notice: n }); } } }; function backoff(base, attempt) { return base * 2 ** attempt * (0.75 + Math.random() * 0.5); } var sleep = (ms) => new Promise((r) => setTimeout(r, ms)); // src/webhooks.ts import { createHmac, timingSafeEqual } from "node:crypto"; function toBytes(body) { return typeof body === "string" ? new TextEncoder().encode(body) : body; } function checkWebhook(rawBody, signatureHeader, secret, toleranceSec = 300, nowSec = Math.floor(Date.now() / 1e3)) { if (typeof signatureHeader !== "string" || signatureHeader === "" || !secret) return "malformed"; let t = null; const sigs = []; for (const part of signatureHeader.split(",")) { const i = part.indexOf("="); if (i < 0) continue; const k = part.slice(0, i).trim(); const v = part.slice(i + 1).trim(); if (k === "t" && t === null) t = v; else if (k === "v1") sigs.push(v); } if (t === null || !/^\d{1,15}$/.test(t)) return "malformed"; const valid = sigs.filter((s) => /^[0-9a-fA-F]{64}$/.test(s)); if (valid.length === 0) return "malformed"; const expected = createHmac("sha256", secret).update(`${t}.`).update(toBytes(rawBody)).digest(); let match = false; for (const s of valid) { if (timingSafeEqual(expected, Buffer.from(s, "hex"))) match = true; } if (!match) return "mismatch"; if (toleranceSec > 0 && Math.abs(nowSec - Number(t)) > toleranceSec) return "timestamp"; return null; } function verifyWebhook(rawBody, signatureHeader, secret, toleranceSec = 300, nowSec) { return checkWebhook(rawBody, signatureHeader, secret, toleranceSec, nowSec) === null; } function parseWebhook(rawBody) { const text = typeof rawBody === "string" ? rawBody : new TextDecoder().decode(rawBody); const raw = JSON.parse(text); if (raw === null || typeof raw !== "object" || Array.isArray(raw)) { throw new WebhookSignatureError("malformed", "Webhook body is not a JSON object"); } return { eventId: raw.event_id ?? null, event: raw.event ?? null, created: raw.created ?? null, status: raw.status ?? null, code: raw.code ?? null, message: raw.message ?? null, data: raw.data, notices: raw.meta && typeof raw.meta === "object" && Array.isArray(raw.meta.notices) ? raw.meta.notices : Array.isArray(raw.notices) ? raw.notices : [], raw }; } function constructEvent(rawBody, signatureHeader, secret, toleranceSec = 300, nowSec) { const failure = checkWebhook(rawBody, signatureHeader, secret, toleranceSec, nowSec); if (failure) throw new WebhookSignatureError(failure, `Invalid Moolre webhook signature (${failure})`); return parseWebhook(rawBody); } function signWebhook(rawBody, secret, nowSec = Math.floor(Date.now() / 1e3)) { const v1 = createHmac("sha256", secret).update(`${nowSec}.`).update(toBytes(rawBody)).digest("hex"); return `t=${nowSec},v1=${v1}`; } // src/client.ts var CHANNELS = ["MTN", "TELECEL", "AT", "BANK"]; var LEGACY_VALIDATE_ID = { MTN: "1", TELECEL: "6", AT: "7", BANK: "2" }; function channelName(c) { const s = String(c).trim(); return CHANNELS.includes(s.toUpperCase()) ? s.toUpperCase() : s; } function amountStr(a) { return typeof a === "number" ? a.toFixed(2) : String(a); } function newIdempotencyKey() { return globalThis.crypto.randomUUID(); } var Ctx = class { constructor(t) { this.t = t; } call(spec) { return this.t.call(spec); } account(p) { const a = p?.accountNumber ?? this.t.opts.accountNumber; if (!a) throw new ConfigurationError("accountNumber is required (pass it to the call or to the client)"); return a; } }; var Resource = class { constructor(c) { this.c = c; } }; function lookup(id) { if (id.externalRef !== void 0) return { idtype: 1, id: id.externalRef }; if (id.transactionId !== void 0) return { idtype: 2, id: id.transactionId }; throw new ConfigurationError("Pass { externalRef } or { transactionId }"); } var Payments = class extends Resource { /** * Request a mobile money payment. If the customer's number needs verifying the API answers * code TP14 (result.otpRequired): ask the customer for the SMS code and call verifyOtp(). */ async initiate(p, o = {}) { const r = await this.c.call({ path: "/open/transact/payment", needs: ["pubKey"], retry: "idempotent", idempotencyKey: o.idempotencyKey, body: { type: 1, channel: channelName(p.channel), currency: p.currency, payer: p.payer, amount: amountStr(p.amount), externalref: p.externalRef, reference: p.reference, otpcode: p.otpCode, sessionid: p.sessionId, accountnumber: this.c.account(p), skipotp: p.skipOtp } }); return Object.assign(r, { otpRequired: r.code === "TP14", otpVerified: r.code === "TP17" }); } /** Second step of the OTP flow (same call with otpCode). After TP17, call initiate() once more without otpCode. */ verifyOtp(p, o = {}) { return this.initiate(p, o); } /** Status of a collection by your externalRef or Moolre's transactionId. */ status(id, p = {}) { return this.c.call({ path: "/open/transact/status", needs: ["apiKey", "pubKey"], retry: "read", body: { type: 1, ...lookup(id), accountnumber: this.c.account(p) } }); } createPaymentId(p) { return this.c.call({ path: "/open/account/create", needs: ["pubKey"], retry: "never", body: { type: 2, phone: p.phone, name: p.name, currency: p.currency, amount: p.amount === void 0 ? void 0 : amountStr(p.amount), externalref: p.externalRef, accountnumber: this.c.account(p) } }); } createBankAccount(p) { return this.c.call({ path: "/open/account/create", needs: ["pubKey"], retry: "never", body: { type: 9, currency: p.currency, amount: p.amount === void 0 ? void 0 : Number(p.amount), firstname: p.firstName, lastname: p.lastName, phone: p.phone, email: p.email, externalref: p.externalRef, accountnumber: this.c.account(p) } }); } listBankAccounts(p = {}) { return this.c.call({ path: "/open/transact/status", needs: ["pubKey"], retry: "read", body: { type: 3, accountnumber: this.c.account(p) } }); } /** Payments received on a Payment ID or bank account, and its status. */ accountTransactions(externalRef, p = {}) { return this.c.call({ path: "/open/transact/status", needs: ["pubKey"], retry: "read", body: { type: 2, externalref: externalRef, accountnumber: this.c.account(p) } }); } }; var PaymentLinks = class extends Resource { create(p) { return this.c.call({ path: "/embed/link", needs: ["pubKey"], retry: "never", body: { type: 1, amount: amountStr(p.amount), email: p.email, externalref: p.externalRef, callback: p.callback, redirect: p.redirect, reusable: p.reusable ? "1" : "0", expiration_time: p.expirationTime, currency: p.currency, accountnumber: this.c.account(p), metadata: p.metadata } }); } }; var Transfers = class extends Resource { /** Pay out to a mobile money wallet or bank account. Pass idempotencyKey to make retries safe. */ create(p, o = {}) { return this.c.call({ path: "/open/transact/transfer", needs: ["apiKey"], retry: "idempotent", idempotencyKey: o.idempotencyKey, body: { type: 1, channel: channelName(p.channel), currency: p.currency, amount: amountStr(p.amount), receiver: p.receiver, sublistid: p.subListId, externalref: p.externalRef, reference: p.reference, sendername: p.senderName, accountnumber: this.c.account(p) } }); } status(id, p = {}) { return this.c.call({ path: "/open/transact/status", needs: ["apiKey", "pubKey"], retry: "read", body: { type: 1, ...lookup(id), accountnumber: this.c.account(p) } }); } /** Confirm the account holder's name before paying out. */ validateName(p) { const ch = LEGACY_VALIDATE_ID[channelName(p.channel)] ?? channelName(p.channel); return this.c.call({ path: "/open/transact/validate", needs: ["apiKey", "pubKey"], retry: "read", body: { type: 1, receiver: p.receiver, channel: ch, sublistid: p.subListId, currency: p.currency, accountnumber: this.c.account(p) } }); } /** Move money between two Moolre accounts. */ internal(p) { return this.c.call({ path: "/open/transact/internal", needs: ["apiKey"], retry: "never", body: { type: 1, currency: p.currency, amount: amountStr(p.amount), receiver: p.receiver, externalref: p.externalRef, reference: p.reference, accountnumber: this.c.account(p) } }); } }; var Accounts = class extends Resource { status(p = {}) { return this.c.call({ path: "/open/account/status", needs: ["apiKey"], retry: "read", body: { type: 1, accountnumber: this.c.account(p) } }); } update(p) { return this.c.call({ path: "/open/account/update", needs: ["apiKey"], retry: "never", body: { type: 1, accountnumber: this.c.account(p), accountname: p.accountName, currency: p.currency ?? "GHS", api: p.api, callback: p.callback, settlement: p.settlement } }); } /** Sandbox only: create a test wallet. */ create(p) { return this.c.call({ path: "/open/account/create", retry: "never", body: { type: 1, accountname: p.accountName, currency: p.currency, api: p.api, callback: p.callback, settlement: p.settlement ?? { currency: p.currency, frequency: "", channel: "", recipient: "", sublist: "" } } }); } /** One page of transactions. Use iterateTransactions() to walk all of them. */ transactions(p = {}) { return this.c.call({ path: "/open/account/status", needs: ["apiKey"], retry: "read", body: { type: 2, accountnumber: this.c.account(p), startdate: p.startDate, enddate: p.endDate, limit: p.limit, status: p.status, descending: p.descending === void 0 ? void 0 : p.descending ? 1 : 0, startid: p.startId, endid: p.endId } }); } /** * Async iterator over every matching transaction, using the id cursor (startid/endid) so pages never overlap. * Newest first unless `descending: false`. */ async *iterateTransactions(p = {}, page = {}) { const size = Math.min(Math.max(page.pageSize ?? 100, 2), 1e3); const desc = p.descending !== false; let startId = p.startId === void 0 ? void 0 : Number(p.startId); let endId = p.endId === void 0 ? void 0 : Number(p.endId); let seen = 0; for (; ; ) { const r = await this.transactions({ ...p, descending: desc, limit: size, startId, endId }); const rows = r.data?.transactions ?? []; for (const row of rows) { if (page.maxItems !== void 0 && seen >= page.maxItems) return; seen++; yield row; } if (rows.length < size) return; const ids = rows.map((x) => Number(x.transactionid)).filter((n) => Number.isFinite(n)); if (ids.length === 0) return; if (desc) { endId = Math.min(...ids) - 1; if (endId <= 1) return; } else { startId = Math.max(...ids) + 1; } } } }; var Sales = class extends Resource { airtime(p) { return this.c.call({ path: "/open/sales/airtime", needs: ["apiKey"], retry: "never", body: { type: 1, channel: channelName(p.channel), receiver: p.receiver, amount: amountStr(p.amount), currency: "GHS", accountnumber: this.c.account(p), externalref: p.externalRef, reference: p.reference } }); } data(p) { return this.c.call({ path: "/open/sales/data", needs: ["apiKey"], retry: "never", body: { type: 1, channel: channelName(p.channel), receiver: p.receiver, bundle: p.bundle, currency: "GHS", accountnumber: this.c.account(p), externalref: p.externalRef, reference: p.reference } }); } bundles(p = {}) { return this.c.call({ path: "/open/sales/bundles", needs: ["apiKey"], retry: "read", body: { accountnumber: this.c.account(p), network: p.network === void 0 ? void 0 : channelName(p.network) } }); } /** Look up a sale by externalRef, transactionId or the reference returned by the sale. */ status(id, p = {}) { const l = "reference" in id && id.reference !== void 0 ? { idtype: 3, id: id.reference } : lookup(id); return this.c.call({ path: "/open/sales/status", needs: ["apiKey"], retry: "read", body: { type: 1, accountnumber: this.c.account(p), ...l } }); } }; var Sms = class extends Resource { send(p) { return this.c.call({ path: "/open/sms/send", needs: ["vasKey"], retry: "never", body: { type: 1, senderid: p.senderId, network: p.network, messages: p.messages } }); } /** Delivery status by message ref: 0 unknown, 1 sent, 2 delivered, 3 failed. */ status(refs) { return this.c.call({ path: "/open/sms/status", needs: ["vasKey"], retry: "read", body: { type: 5, ref: refs } }); } balance() { return this.c.call({ path: "/open/sms/status", needs: ["vasKey"], retry: "read", body: { type: 2 } }); } senderIdStatus(senderId) { return this.c.call({ path: "/open/sms/status", needs: ["vasKey"], retry: "read", body: { type: 1, senderid: senderId } }); } listSenderIds() { return this.c.call({ path: "/open/sms/status", needs: ["vasKey"], retry: "read", body: { type: 7 } }); } createSenderIds(senderIds) { return this.c.call({ path: "/open/sms/query", needs: ["vasKey"], retry: "never", body: { type: 3, senderids: senderIds } }); } /** Reseller permission required. approve: 0 pending, 1 approved, 2 rejected. */ approveSenderIds(senderIds) { return this.c.call({ path: "/open/sms/status", needs: ["vasKey"], retry: "never", body: { type: 6, senderids: senderIds } }); } }; var WhatsApp = class extends Resource { /** One page of approved templates. `next` is the cursor from the previous page (result.raw.next). */ templates(next) { return this.c.call({ method: "GET", path: "/open/whatsapp/template", needs: ["vasKey"], retry: "read", query: { next } }); } async *iterateTemplates(page = {}) { let next; let seen = 0; do { const r = await this.templates(next); for (const t of r.data ?? []) { if (page.maxItems !== void 0 && seen >= page.maxItems) return; seen++; yield t; } next = typeof r.raw.next === "string" && r.raw.next !== "" ? r.raw.next : void 0; } while (next); } send(p) { return this.c.call({ path: "/open/whatsapp/send", needs: ["vasKey"], retry: "never", body: { template_name: p.templateName, language: p.language, messages: p.messages } }); } status(refs) { return this.c.call({ path: "/open/whatsapp/status", needs: ["vasKey"], retry: "read", body: { ref: refs } }); } }; var Reference = class extends Resource { /** Supported banks and their codes (use as subListId). */ banks(country = "gha") { return this.c.call({ method: "GET", path: "/open/transact/data", needs: ["apiKey", "pubKey"], retry: "read", query: { country, data: "banks" } }); } }; function bulkItem(i) { return clean({ externalref: i.externalRef, receiver: i.receiver, channel: channelName(i.channel), amount: amountStr(i.amount), sublistid: i.subListId, sendername: i.senderName, reference: i.reference }); } var Bulk = class extends Resource { /** * Submit 1 to 500 payouts. Every row is validated synchronously; data holds * { batchid, batchref, accepted, rejected: [{ index, code, message, externalref }], total_amount, status: "queued", * balance_warning? }. Sending the same batchRef and body again replays the batch (code BLK02, replayed: true). */ create(p, o = {}) { return this.c.call({ path: "/open/transact/bulk", needs: ["apiKey"], retry: "idempotent", idempotencyKey: o.idempotencyKey, body: { type: 1, accountnumber: this.c.account(p), currency: p.currency, batchref: p.batchRef, callback: p.callback, atomic: p.atomic, items: p.items.map(bulkItem) } }); } /** Batch summary plus one page of items. Use iterateItems() to walk them all. */ status(id, p = {}) { return this.c.call({ path: "/open/transact/bulk_status", needs: ["apiKey"], retry: "read", body: { accountnumber: this.c.account(p), batchid: id.batchId, batchref: id.batchRef, status: p.status, after: p.after, limit: p.limit } }); } /** Walk every item of a batch (follows data.next_after). */ async *iterateItems(id, p = {}, page = {}) { const size = Math.min(Math.max(page.pageSize ?? 100, 1), 500); let after; let seen = 0; for (; ; ) { const r = await this.status(id, { ...p, after, limit: size }); for (const item of r.data?.items ?? []) { if (page.maxItems !== void 0 && seen >= page.maxItems) return; seen++; yield item; } const next = r.data?.next_after; if (next === null || next === void 0) return; after = Number(next); } } /** Recent batches, newest first. data = { batches, has_more, next_cursor }. */ list(p = {}) { return this.c.call({ path: "/open/transact/bulk_list", needs: ["apiKey"], retry: "read", body: { accountnumber: this.c.account(p), limit: p.limit, starting_after: p.startingAfter, status: p.status } }); } async *iterateBatches(p = {}, page = {}) { let after; let seen = 0; for (; ; ) { const r = await this.list({ ...p, limit: Math.min(page.pageSize ?? 25, 100), startingAfter: after }); for (const b of r.data?.batches ?? []) { if (page.maxItems !== void 0 && seen >= page.maxItems) return; seen++; yield b; } if (!r.data?.has_more || !r.data?.next_cursor) return; after = String(r.data.next_cursor); } } }; var Invoices = class extends Resource { /** * Create an invoice (the same invoices the dashboard shows). Give the customer result.data.payment_link. * The same `reference` with the same body replays the original (code INV02, replayed: true). */ create(p, o = {}) { return this.c.call({ path: "/open/invoice/create", needs: ["apiKey"], retry: "idempotent", idempotencyKey: o.idempotencyKey, body: { accountnumber: this.c.account(p), currency: p.currency, service_id: p.serviceId, invoice_name: p.invoiceName, customer: p.customer, amount: p.amount === void 0 ? void 0 : amountStr(p.amount), items: p.items?.map((i) => clean({ description: i.description, quantity: i.quantity, amount: amountStr(i.amount) })), tax: p.tax, due_date: p.dueDate, narration: p.narration, reference: p.reference, metadata: p.metadata } }); } /** By { invoiceId } ("5-1") or { reference }. */ status(id, p = {}) { return this.c.call({ path: "/open/invoice/status", needs: ["apiKey"], retry: "read", body: { accountnumber: this.c.account(p), invoiceid: id.invoiceId, reference: id.reference } }); } /** data = { invoices, has_more, next_cursor }, newest first. */ list(p = {}) { return this.c.call({ path: "/open/invoice/list", needs: ["apiKey"], retry: "read", body: { accountnumber: this.c.account(p), limit: p.limit, starting_after: p.startingAfter, status: p.status, reference: p.reference, service_id: p.serviceId } }); } async *iterate(p = {}, page = {}) { let after; let seen = 0; for (; ; ) { const r = await this.list({ ...p, limit: Math.min(page.pageSize ?? 25, 100), startingAfter: after }); for (const inv of r.data?.invoices ?? []) { if (page.maxItems !== void 0 && seen >= page.maxItems) return; seen++; yield inv; } if (!r.data?.has_more || !r.data?.next_cursor) return; after = String(r.data.next_cursor); } } /** Cancel an unpaid invoice (its hosted link stops working). INV18 if it has payments. */ cancel(invoiceId, p = {}) { return this.c.call({ path: "/open/invoice/cancel", needs: ["apiKey"], retry: "never", body: { accountnumber: this.c.account(p), invoiceid: invoiceId } }); } }; var Webhooks = class extends Resource { /** Webhooks Moolre has sent (or is retrying) to this wallet, newest first. data = { items, has_more, next_cursor }. */ deliveries(p = {}) { return this.c.call({ path: "/open/webhook/deliveries", needs: ["apiKey"], retry: "read", body: { accountnumber: this.c.account(p), event: p.event, state: p.state, from: p.from, to: p.to, limit: p.limit, starting_after: p.startingAfter, include_payload: p.includePayload ? 1 : void 0 } }); } /** Walk all deliveries (follows data.next_cursor). */ async *iterateDeliveries(p = {}, page = {}) { let after = p.startingAfter; let seen = 0; for (; ; ) { const r = await this.deliveries({ ...p, limit: Math.min(page.pageSize ?? 25, 100), startingAfter: after }); for (const row of r.data?.items ?? []) { if (page.maxItems !== void 0 && seen >= page.maxItems) return; seen++; yield row; } if (!r.data?.has_more || !r.data?.next_cursor) return; after = String(r.data.next_cursor); } } /** Put an event back in the delivery queue (same event_id, full retry schedule). */ resend(eventId, p = {}) { return this.c.call({ path: "/open/webhook/resend", needs: ["apiKey"], retry: "never", body: { accountnumber: this.c.account(p), event_id: eventId } }); } /** Send a signed `webhook.test` event to the wallet's callback URL now; data = { event_id, delivered, http, error }. */ test(p = {}) { return this.c.call({ path: "/open/webhook/test", needs: ["apiKey"], retry: "never", body: { accountnumber: this.c.account(p) } }); } verify = verifyWebhook; constructEvent = constructEvent; parse = parseWebhook; }; var Moolre = class _Moolre { payments; paymentLinks; transfers; accounts; sales; sms; whatsapp; reference; /** Bulk payouts. */ bulk; /** Invoices: the same invoices the dashboard shows. */ invoices; /** Webhook deliveries, resend and test events. */ webhooks; constructor(options) { const ctx = new Ctx(new Transport(options)); this.payments = new Payments(ctx); this.paymentLinks = new PaymentLinks(ctx); this.transfers = new Transfers(ctx); this.accounts = new Accounts(ctx); this.sales = new Sales(ctx); this.sms = new Sms(ctx); this.whatsapp = new WhatsApp(ctx); this.reference = new Reference(ctx); this.bulk = new Bulk(ctx); this.invoices = new Invoices(ctx); this.webhooks = new Webhooks(ctx); } /** Build a client from MOOLRE_ENV, MOOLRE_USER, MOOLRE_API_KEY, MOOLRE_PUBKEY, MOOLRE_VASKEY, MOOLRE_ACCOUNT. */ static fromEnv(overrides = {}) { const e = globalThis.process?.env ?? {}; return new _Moolre({ environment: e.MOOLRE_ENV === "sandbox" ? "sandbox" : "live", user: e.MOOLRE_USER, apiKey: e.MOOLRE_API_KEY, pubKey: e.MOOLRE_PUBKEY, vasKey: e.MOOLRE_VASKEY, accountNumber: e.MOOLRE_ACCOUNT, ...overrides }); } static verifyWebhook = verifyWebhook; static constructEvent = constructEvent; static parseWebhook = parseWebhook; static newIdempotencyKey = newIdempotencyKey; }; export { Accounts, ApiError, AuthenticationError, BASE_URLS, Bulk, ConfigurationError, ConnectionError, IdempotencyError, InvalidResponseError, Invoices, Moolre, MoolreError, NotFoundError, PaymentLinks, Payments, RateLimitError, Reference, Sales, ServerError, Sms, TimeoutError, Transfers, VERSION, ValidationError, WebhookSignatureError, Webhooks, WhatsApp, checkWebhook, classify, constructEvent, newIdempotencyKey, parseWebhook, signWebhook, verifyWebhook };