// EXNO REST SDK 1.0.0 ยท server-side Node.js 18+ import { randomUUID } from "node:crypto"; export class ExnoError extends Error { constructor(status, detail, headers) { super(detail?.message || `EXNO returned HTTP ${status}`); this.name = "ExnoError"; this.status = status; this.code = detail?.code; this.param = detail?.param; this.requestId = headers.get("x-request-id") || detail?.request_id; this.retryAfter = headers.get("retry-after"); } } export class Exno { #key; #base; constructor(apiKey, { environment = "production" } = {}) { if (typeof apiKey !== "string" || !apiKey.trim()) throw new TypeError("An API key is required"); if (!["production", "staging"].includes(environment)) throw new TypeError("Unknown EXNO environment"); this.#key = apiKey; this.#base = environment === "production" ? "https://exno.app/api/v1/" : "https://staging.exno.app/api/v1/"; } async request(method, resource, { query = {}, body, idempotencyKey, signal } = {}) { if (!["GET", "POST", "PATCH", "DELETE"].includes(method)) throw new TypeError("Unsupported HTTP method"); if (typeof resource !== "string" || !/^[A-Za-z0-9_-]+(?:\/[A-Za-z0-9_-]+)*$/.test(resource)) { throw new TypeError("Use an API resource such as products or sales/ID"); } if (method === "GET" && body !== undefined) throw new TypeError("GET does not take a body"); const url = new URL(resource, this.#base); for (const [key, value] of Object.entries(query)) { if (value != null) url.searchParams.set(key, String(value)); } const headers = { Authorization: `Bearer ${this.#key}`, Accept: "application/json" }; if (body !== undefined) headers["Content-Type"] = "application/json"; if (method !== "GET") headers["Idempotency-Key"] = idempotencyKey ?? randomUUID(); const response = await fetch(url, { method, headers, body: JSON.stringify(body), signal: signal ?? AbortSignal.timeout(30000), redirect: "error" }); const raw = await response.text(); let payload; try { payload = raw ? JSON.parse(raw) : null; } catch { if (response.ok) throw new Error("Invalid JSON from EXNO"); } if (!response.ok) throw new ExnoError(response.status, payload?.error, response.headers); return payload; } me() { return this.request("GET", "me"); } products(query) { return this.request("GET", "products", { query }); } sales(query) { return this.request("GET", "sales", { query }); } async *pages(resource, query = {}) { const params = { ...query }; const seen = new Set(params.cursor ? [params.cursor] : []); while (true) { const page = await this.request("GET", resource, { query: params }); yield page; if (!page.has_more) return; if (!page.next_cursor || seen.has(page.next_cursor)) throw new Error("Invalid EXNO pagination cursor"); params.cursor = page.next_cursor; seen.add(params.cursor); } } }