"use strict";
/**
 * AIB TypeScript SDK — Client.
 *
 * Usage:
 *   import { AIBClient } from 'agent-identity-bridge';
 *
 *   const client = new AIBClient({ gatewayUrl: 'http://localhost:8420' });
 *
 *   const { passport, token } = await client.createPassport({
 *     org_slug: 'mycompany',
 *     agent_slug: 'booking',
 *     display_name: 'Booking Agent',
 *     capabilities: ['booking'],
 *     bindings: { mcp: { auth_method: 'oauth2', server_card_url: '...' } },
 *   });
 *
 *   const result = await client.send('urn:aib:agent:mycompany:booking',
 *     'https://partner.com/a2a/send', { task: 'Book 3pm' });
 */
Object.defineProperty(exports, "__esModule", { value: true });
exports.AIBError = exports.AIBClient = void 0;
class AIBClient {
    baseUrl;
    apiKey;
    timeout;
    constructor(options) {
        this.baseUrl = options.gatewayUrl.replace(/\/$/, "");
        this.apiKey = options.apiKey || "";
        this.timeout = options.timeout || 30000;
    }
    // ─── Internal fetch ────────────────────────────────────────────
    async request(method, path, body) {
        const headers = {
            "Content-Type": "application/json",
        };
        if (this.apiKey) {
            headers["Authorization"] = `Bearer ${this.apiKey}`;
        }
        const controller = new AbortController();
        const timer = setTimeout(() => controller.abort(), this.timeout);
        try {
            const res = await fetch(`${this.baseUrl}${path}`, {
                method,
                headers,
                body: body ? JSON.stringify(body) : undefined,
                signal: controller.signal,
            });
            const data = await res.json();
            if (!res.ok) {
                throw new AIBError(data?.error?.code || `HTTP_${res.status}`, data?.error?.message || res.statusText, res.status);
            }
            return data;
        }
        finally {
            clearTimeout(timer);
        }
    }
    // ─── Health ────────────────────────────────────────────────────
    async health() {
        return this.request("GET", "/");
    }
    // ─── Passports ─────────────────────────────────────────────────
    async createPassport(req) {
        return this.request("POST", "/passports", req);
    }
    async listPassports() {
        const res = await this.request("GET", "/passports");
        return res.passports;
    }
    async getPassport(passportId) {
        const encoded = encodeURIComponent(passportId);
        return this.request("GET", `/passports/${encoded}`);
    }
    async revokePassport(passportId) {
        const encoded = encodeURIComponent(passportId);
        return this.request("DELETE", `/passports/${encoded}`);
    }
    // ─── Translation ───────────────────────────────────────────────
    async translate(source, fromFormat, toFormat, options) {
        return this.request("POST", "/translate", {
            source,
            from_format: fromFormat,
            to_format: toFormat,
            domain: options?.domain,
            agent_slug: options?.agent_slug,
        });
    }
    // ─── Gateway Proxy ─────────────────────────────────────────────
    async send(passportId, targetUrl, body, options) {
        const start = Date.now();
        const res = await this.request("POST", "/gateway/proxy", {
            passport_id: passportId,
            target_url: targetUrl,
            method: options?.method || "POST",
            body: body || {},
            headers: options?.headers || {},
        });
        return {
            success: res.status_code >= 200 && res.status_code < 300,
            protocol: res.protocol_used,
            trace_id: res.audit_trace_id,
            status_code: res.status_code,
            data: res.body,
            latency_ms: Date.now() - start,
        };
    }
    // ─── Audit ─────────────────────────────────────────────────────
    async getAuditTrail(passportId, options) {
        const encoded = encodeURIComponent(passportId);
        const params = new URLSearchParams();
        if (options?.protocol)
            params.set("protocol", options.protocol);
        if (options?.action)
            params.set("action", options.action);
        if (options?.limit)
            params.set("limit", String(options.limit));
        const qs = params.toString();
        return this.request("GET", `/audit/${encoded}${qs ? `?${qs}` : ""}`);
    }
    // ─── Discovery ─────────────────────────────────────────────────
    async getDiscovery() {
        return this.request("GET", "/.well-known/aib.json");
    }
    async getJWKS() {
        return this.request("GET", "/.well-known/aib-keys.json");
    }
}
exports.AIBClient = AIBClient;
// ─── Error class ─────────────────────────────────────────────────
class AIBError extends Error {
    code;
    statusCode;
    constructor(code, message, statusCode) {
        super(message);
        this.name = "AIBError";
        this.code = code;
        this.statusCode = statusCode;
    }
}
exports.AIBError = AIBError;
