UNPKG

facturapi

Version:

Librería oficial de Facturapi. Crea CFDIs timbrados y enviados al SAT, XML y PDF

1,274 lines (1,273 loc) 47.1 kB
class ce { constructor(t) { this.client = t; } /** * Creates a new customer in your organization * @param data Customer data * @param params Query params * @returns Customer object */ create(t, n = null) { return this.client.post("/customers", { body: t, params: n }); } /** * Gets a paginated list of customers that belong to your organization * @param params Search parameters * @returns List of customers */ list(t) { return t || (t = {}), this.client.get("/customers", { params: t }); } /** * Gets a single customer object * @param id Customer Id * @returns Customer object */ retrieve(t) { return t ? this.client.get("/customers/" + t) : Promise.reject(new Error("id is required")); } /** * Updates a customer * @param id Customer Id * @param data Customer data to update * @param params Query params * @returns Updated customer */ update(t, n, s = null) { return this.client.put("/customers/" + t, { body: n, params: s }); } /** * Permanently removes a customer from your organization. * @param id Customer Id * @returns Deleted customer */ del(t) { return this.client.delete("/customers/" + t); } /** * Validate customer with SAT validation. * @param id Customer Id * @returns Validation result */ validateTaxInfo(t) { return this.client.get("/customers/" + t + "/tax-info-validation"); } /** * Send the customer an email with a link to edit their information. * @param id Customer Id * @param options Email options * @param options.email Email address to send the link to */ sendEditLinkByEmail(t, n) { return this.client.post("/customers/" + t + "/email-edit-link", { body: n }); } } class ue { constructor(t) { this.client = t; } /** * Creates a new product in your organization * @param data - Product data * @returns Product object */ create(t) { return this.client.post("/products", { body: t }); } /** * Gets a paginated list of products that belong to your organization * @param params - Search parameters * @returns Search results object. The object contains a `data` property with the list of products. */ list(t) { return this.client.get("/products", { params: t }); } /** * Gets a single product object * @param id - Product Id * @returns Product object */ retrieve(t) { return t ? this.client.get("/products/" + t) : Promise.reject(new Error("id is required")); } /** * Updates a product * @param id - Product Id * @param data - Product data to update * @returns Updated product */ update(t, n) { return this.client.put("/products/" + t, { body: n }); } /** * Permanently removes a product from your organization. * @param id - Product Id * @returns Deleted product */ del(t) { return this.client.delete("/products/" + t); } } class fe { constructor(t) { this.client = t; } /** * Creates a new valid invoice (CFDI). * @param body Invoice data * @param params Query params * @returns Invoice object */ create(t, n) { return this.client.post("/invoices", { body: t, params: n }); } /** * Gets a paginated list of invoices created by your organization * @param params - Search parameters * @returns Search results object. The object contains a `data` property with the list of invoices. */ list(t) { return t || (t = {}), this.client.get("/invoices", { params: t }); } /** * Gets a single invoice object * @param id Invoice Id * @returns Invoice object */ retrieve(t) { return t ? this.client.get("/invoices/" + t) : Promise.reject(new Error("id is required")); } /** * Cancels an invoice. The invoice will not be valid anymore and will change its status to canceled. * @param id Invoice Id * @param params Cancel options * @returns Canceled invoice */ cancel(t, n) { return this.client.delete("/invoices/" + t, { params: n }); } /** * Sends the invoice to the customer's email * @param id Invoice Id * @param options Additional arguments * @param options.email Email address to send the invoice to * @returns Object with 'ok' property set to true if the email was sent successfully */ sendByEmail(t, n) { return this.client.post("/invoices/" + t + "/email", { body: n }); } /** * Downloads the specified invoice in PDF format * @param id Invoice Id * @returns PDF file in a stream (Node.js) or Blob (browser) */ async downloadPdf(t) { return this.client.get("/invoices/" + t + "/pdf"); } /** * Downloads the specified invoice in XML format * @param id Invoice Id * @returns XML file in a stream (Node.js) or Blob (browser) */ async downloadXml(t) { return this.client.get("/invoices/" + t + "/xml"); } /** * Downloads the specified invoice in a ZIP package containing both PDF and XML files * @param id Invoice Id * @returns ZIP file in a stream (Node.js) or Blob (browser) */ downloadZip(t) { return this.client.get("/invoices/" + t + "/zip"); } /** * Downloads the cancellation receipt of a canceled invoice in XML format * @param id Invoice Id * @returns XML file in a stream (Node.js) or Blob (browser) */ downloadCancellationReceiptXml(t) { return this.client.get("/invoices/" + t + "/cancellation_receipt/xml"); } /** * Downloads the cancellation receipt of a canceled invoice in PDF format * @param id Invoice Id * @returns PDF file in a stream (Node.js) or Blob (browser) */ downloadCancellationReceiptPdf(t) { return this.client.get("/invoices/" + t + "/cancellation_receipt/pdf"); } /** * Edits an invoice with "draft" status. * @param id Invoice Id * @param data Invoice data to edit * @returns Edited invoice */ updateDraft(t, n) { return this.client.put("/invoices/" + t, { body: n }); } /** * Stamps an invoice with "draft" status. * @param id Invoice Id * @param params Query params * @returns Stamped invoice */ stampDraft(t, n) { return this.client.post("/invoices/" + t + "/stamp", { params: n }); } /** * Updates the latest status of the invoice from the SAT * @param id Invoice Id * @returns Updated invoice */ updateStatus(t) { return this.client.put("/invoices/" + t + "/status"); } /** * Creates a draft invoice from any other invoice * @param id Invoice Id * @returns Draft invoice */ copyToDraft(t) { return this.client.post("/invoices/" + t + "/copy"); } } var de = /* @__PURE__ */ function() { return typeof globalThis < "u" ? globalThis : typeof self < "u" ? self : window; }(), { FormData: j, Blob: Fe, File: he } = de; const Ee = "https://www.facturapi.io/v2", pe = "https://www.facturapi.io/v1", z = "v2"; var H; const T = typeof process < "u" && !!((H = process == null ? void 0 : process.versions) != null && H.node), q = typeof navigator < "u" && (navigator == null ? void 0 : navigator.product) === "ReactNative"; function _e(e) { return new Promise((t, n) => { const s = []; e.on("data", (d) => s.push(d)), e.on("end", () => t(Buffer.concat(s))), e.on("error", n); }); } const L = async (e, t, n) => { if (T) { const s = e instanceof Buffer ? e : await _e(e); return new he([s], t, { type: n }); } return e; }; class Oe { constructor(t) { this.client = t; } /** * Creates a new organization for your account * @param data - Organization data * @returns Organization object */ create(t) { return this.client.post("/organizations", { body: t }); } /** * Gets a paginated list of organizations that belong to your account * @param params - Search parameters * @returns Search results object. The object contains a `data` property with the list of organizations. */ list(t) { return t || (t = {}), this.client.get("/organizations", { params: t }); } /** * Gets a single organization object * @param id * @returns */ retrieve(t) { return t ? this.client.get("/organizations/" + t) : Promise.reject(new Error("id is required")); } /** * Updates the organization's legal information * @param id Organization Id * @param data * @returns */ updateLegal(t, n) { return t ? this.client.put("/organizations/" + t + "/legal", { body: n }) : Promise.reject(new Error("id is required")); } /** * Updates the organization's customization information * @param id Organization Id * @param data Customization settings * @returns Organization object */ updateCustomization(t, n) { return this.client.put("/organizations/" + t + "/customization", { body: n }); } /** * Updates the organization's customization information * @param id Organization Id * @param data Receipt settings * @returns Organization object */ updateReceiptSettings(t, n) { return this.client.put("/organizations/" + t + "/receipts", { body: n }); } /** * Updates the organization's customization information * @param id Organization Id * @param data Domain data * @returns Organization object */ updateDomain(t, n) { return this.client.put("/organizations/" + t + "/domain", { body: n }); } /** * Checks if a domain is available for self invoices * @param data Domain data * @returns Domain availability */ checkDomainIsAvailable(t) { return this.client.put("/organizations/domain-check", { body: t }); } /** * Uploads the organization's logo * @param id Organization Id * @param file Logo file * @returns Organization object */ async uploadLogo(t, n) { const s = await L( n, "file", "application/octet-stream" ), d = new j(); return d.append("file", s, "file"), this.client.put("/organizations/" + t + "/logo", { formData: d }); } /** * Uploads the organization's certificate (CSD) * @param id Organization Id * @param cerFile Certificate file * @param keyFile Key file * @param password Certificate password * @returns Organization object */ async uploadCertificate(t, n, s, d) { let c = new j(); const [l, f] = await Promise.all([ L(n, "cer.cer", "application/octet-stream"), L(s, "key.key", "application/octet-stream") ]); return c.append("cer", l, "cer.cer"), c.append("key", f, "key.key"), c.append("password", d), this.client.put("/organizations/" + t + "/certificate", { formData: c }); } /** * Deletes the organization's certificate (CSD) * @param id Organization Id * @returns Organization object */ deleteCertificate(t) { return this.client.delete("/organizations/" + t + "/certificate"); } /** * Permanently removes a organization from your account. * @param id Organization Id * @returns Deleted organization object */ del(t) { return t ? this.client.delete("/organizations/" + t) : Promise.reject(new Error("id is required")); } /** * Gets the test api key for an organization * @param id Organization Id * @returns Test api key */ getTestApiKey(t) { return this.client.get("/organizations/" + t + "/apikeys/test"); } /** * Renews the test api key and makes the previous one unusable * @param id Organization Id * @returns New test api key */ renewTestApiKey(t) { return this.client.put("/organizations/" + t + "/apikeys/test"); } /** * List live api keys * @param id Organization Id * @returns List of live api keys */ async listLiveApiKeys(t) { return this.client.get("/organizations/" + t + "/apikeys/live"); } /** * Renews the live api key and makes the previous one unusable * @param id Organization Id * @returns New live api key */ renewLiveApiKey(t) { return this.client.put("/organizations/" + t + "/apikeys/live"); } /** * Delete a live api key * @param organizationId Organization Id * @param apiKeyId Api Key Id * @returns List of live api keys */ async deleteLiveApiKey(t, n) { return this.client.delete( "/organizations/" + t + "/apikeys/live/" + n ); } /** * Get list of Series Organization * @param organization_id Organization Id * @returns Series object */ listSeriesGroup(t) { return this.client.get( "/organizations/" + t + "/series-group" ); } /** * Creates a Series Organization * @param organization_id Organization Id * @param seriesData - Series data * @returns Series object */ createSeriesGroup(t, n) { return this.client.post( "/organizations/" + t + "/series-group", { body: n } ); } /** * Update a Series Organization * @param organization_id Organization Id * @param seriesName Series seriesName * @param data - Series data * @returns Series object */ updateSeriesGroup(t, n, s) { return this.client.put( `/organizations/${t}/series-group/${n}`, { body: s } ); } /** * Update a Series Organization * @param organization_id Organization Id * @param seriesName Series seriesName * @returns Series object */ deleteSeriesGroup(t, n) { return this.client.delete( `/organizations/${t}/series-group/${n}` ); } /** * Get the organization that belongs to the authenticated API key * @returns Organization object */ me() { return this.client.get("/organizations/me"); } } class Ae { constructor(t) { this.client = t; } /** * Creates a new product in your organization * @param {Object} params - Search parameters * @returns {Promise} */ searchProducts(t) { return this.client.get("/catalogs/products", { params: t }); } /** * Gets a paginated list of products that belong to your organization * @param {[Object]} params - Search parameters * @returns {Promise} */ searchUnits(t) { return this.client.get("/catalogs/units", { params: t }); } } class ye { constructor(t) { this.client = t; } /** * Creates a new receipt * @param data Receipt data * @returns Receipt object */ create(t) { return this.client.post("/receipts", { body: t }); } /** * Gets a paginated list of receipts that belong to your organization * @param params Search parameters * @returns Search results object. The object contains a `data` property with the list of receipts. */ list(t) { return t || (t = {}), this.client.get("/receipts", { params: t }); } /** * Gets a single receipt object * @param id Receipt Id * @returns Receipt object */ retrieve(t) { return t ? this.client.get("/receipts/" + t) : Promise.reject(new Error("id is required")); } /** * Creates an invoice for this receipt * @param id Receipt Id * @param data Invoice data * @returns Invoice object */ invoice(t, n) { return this.client.post("/receipts/" + t + "/invoice", { body: n }); } /** * Creates a global invoice for open receipts * @param data * @returns */ createGlobalInvoice(t) { return this.client.post("/receipts/global-invoice", { body: t }); } /** * Marks a receipt as canceled. The receipt won't be available for invoicing anymore. * @param id * @returns */ cancel(t) { return this.client.delete("/receipts/" + t); } /** * Sends the receipt to the customer's email * @param id Receipt Id * @param data Additional arguments * @param data.email Email address to send the receipt to * @returns Email sent confirmation */ sendByEmail(t, n) { return this.client.post("/receipts/" + t + "/email", { body: n }); } /** * Downloads the specified receipt in PDF format * @param id Receipt Id * @returns PDF file in a stream (Node.js) or Blob (browser) */ downloadPdf(t) { return this.client.get("/receipts/" + t + "/pdf"); } } class Ie { constructor(t) { this.client = t; } /** * Creates a new valid retention (CFDI). * @param data * @returns */ create(t) { return this.client.post("/retentions", { body: t }); } /** * Gets a paginated list of retentions created by the organization * @param params - Search parameters * @returns */ list(t) { return t || (t = {}), this.client.get("/retentions", { params: t }); } /** * Gets a single retention object * @param id * @returns */ retrieve(t) { return t ? this.client.get("/retentions/" + t) : Promise.reject(new Error("id is required")); } /** * Cancels a retention. * @param id * @returns */ cancel(t) { return this.client.delete("/retentions/" + t); } /** * Sends a retention to the customer's email * @param id Retention Id * @param data Additional arguments * @param data.email Email address to send the retention to * @returns */ sendByEmail(t, n) { return this.client.post("/retentions/" + t + "/email", { body: n }); } /** * Downloads the specified retention in PDF format * @param id Retention Id * @returns PDF file in a stream */ downloadPdf(t) { return this.client.get("/retentions/" + t + "/pdf"); } /** * Downloads the specified retention in XML format * @param id Retention Id * @returns XML file in a stream */ downloadXml(t) { return this.client.get("/retentions/" + t + "/xml"); } /** * Downloads the specified retention in a ZIP package containing both PDF and XML files * @param id Retention Id * @returns ZIP file in a stream */ downloadZip(t) { return this.client.get("/retentions/" + t + "/zip"); } } class be { constructor(t) { this.client = t; } /** * Creates a new webhook in your organization * @param data - Webhook options * @returns Webhook object */ create(t) { return this.client.post("/webhooks", { body: t }); } /** * Gets a paginated list of webhooks that belong to your organization * @param params - Search parameters * @returns Search results object. The object contains a `data` property with the list of webhooks. */ list(t) { return t || (t = {}), this.client.get("/webhooks", { params: t }); } /** * Gets a single webhook object * @param id - Webhook Id * @returns Webhook object */ retrieve(t) { return t ? this.client.get("/webhooks/" + t) : Promise.reject(new Error("id is required")); } /** * Updates a webhook * @param id - Webhook Id * @param data Updated webhook data * @returns */ update(t, n) { return this.client.put("/webhooks/" + t, { body: n }); } /** * Permanently removes a webhook from your organization. * @param id - Webhook Id * @returns Deleted webhook */ del(t) { return this.client.delete("/webhooks/" + t); } /** * Validate the response of webhook with the secret and facturapi-signature * @param secret - Webhook Secret, received in the webhook creation * @param signature - Facturapi Signature Header * @param payload - Received event object to validate * @returns When the signature is valid, it returns the event object */ async validateSignature(t) { const { secret: n, signature: s, payload: d } = t; let c; if (typeof d == "string") c = d; else if (Buffer.isBuffer(d)) c = d.toString("utf8"); else if (typeof d == "object") c = JSON.stringify(d); else throw new Error("Invalid payload type"); if (q) return this.client.post("/webhooks/validate-signature", { body: { secret: n, signature: s, payload: c } }); if (T) { const l = await import("crypto"), h = l.createHmac("sha256", n).update(c).digest(), A = Buffer.from(s, "hex"); if (h.length !== A.length) throw new Error("Invalid signature"); if (!l.timingSafeEqual(h, A)) throw new Error("Invalid signature"); return JSON.parse(c); } else { const l = new TextEncoder(), f = l.encode(c), h = l.encode(n), A = await crypto.subtle.sign( "HMAC", await crypto.subtle.importKey( "raw", h, { name: "HMAC", hash: "SHA-256" }, !1, ["sign"] ), f ), S = Array.from(new Uint8Array(A)).map((N) => N.toString(16).padStart(2, "0")).join("").toLowerCase(); if (s !== S) throw new Error("Invalid signature"); } return JSON.parse(c); } } class Se { /** * @param {Client} client */ constructor(t) { this.client = t; } /** * Validates a tax_id in EFOS list * @param {Object} taxId - Search parameters * @returns {Promise} */ validateTaxId(t) { return this.client.get("/tools/tax_id_validation", { params: { tax_id: t } }); } } var x = /* @__PURE__ */ ((e) => (e.EFECTIVO = "01", e.CHEQUE_NOMINATIVO = "02", e.TRANSFERENCIA_ELECTRONICA_DE_FONDOS = "03", e.TARJETA_DE_CREDITO = "04", e.MONEDERO_ELECTRONICO = "05", e.DINERO_ELECTRONICO = "06", e.VALES_DE_DESPENSA = "08", e.DACION_EN_PAGO = "12", e.PAGO_POR_SUBROGACION = "13", e.PAGO_POR_CONSIGNACION = "14", e.CONDONACION = "15", e.COMPENSACION = "17", e.NOVACION = "23", e.CONFUSION = "24", e.REMISIÓN_DE_DEUDA = "25", e.PRESCRIPCION_O_CADUCIDAD = "26", e.A_SATISFACCION_DEL_ACREEDOR = "27", e.TARJETA_DE_DEBITO = "28", e.TARJETA_DE_SERVICIOS = "29", e.APLICACION_DE_ANTICIPOS = "30", e.INTERMEDIARIO_DE_PAGOS = "31", e.POR_DEFINIR = "99", e))(x || {}); const ke = [ { value: "01", label: "Efectivo" }, { value: "02", label: "Cheque nominativo" }, { value: "03", label: "Transferencia electrónica de fondos" }, { value: "04", label: "Tarjeta de crédito" }, { value: "05", label: "Monedero electrónico" }, { value: "06", label: "Dinero electrónico" }, { value: "08", label: "Vales de despensa" }, { value: "12", label: "Dación en pago" }, { value: "13", label: "Pago por subrogación" }, { value: "14", label: "Pago por consignación" }, { value: "15", label: "Condonación" }, { value: "17", label: "Compensación" }, { value: "23", label: "Novación" }, { value: "24", label: "Confusión" }, { value: "25", label: "Remisión de deuda" }, { value: "26", label: "Prescripción o caducidad" }, { value: "27", label: "A satisfacción del acreedor" }, { value: "28", label: "Tarjeta de débito" }, { value: "29", label: "Tarjeta de servicios" }, { value: "30", label: "Aplicación de anticipos" }, { value: "31", label: "Intermediario de pagos" }, { value: "99", label: "Por definir" } ]; var J = /* @__PURE__ */ ((e) => (e.IVA = "IVA", e.IEPS = "IEPS", e.ISR = "ISR", e))(J || {}), X = /* @__PURE__ */ ((e) => (e.RATE = "Tasa", e.QUOTA = "Cuota", e))(X || {}), K = /* @__PURE__ */ ((e) => (e.SUM_BEFORE_TAXES = "sum_before_taxes", e.UNIT = "unit", e.BREAK_DOWN = "break_down", e.SUBTRACT_BEFORE_BREAKDOWN = "subtract_before_break_down", e))(K || {}), Q = /* @__PURE__ */ ((e) => (e.PAGO_EN_UNA_EXHIBICION = "PUE", e.PAGO_EN_PARCIALIDADES_DIFERIDO = "PPD", e))(Q || {}), Y = /* @__PURE__ */ ((e) => (e.ADQUISICION_MERCANCIAS = "G01", e.DEVOLUCIONES_DESCUENTOS_BONIFICACIONES = "G02", e.GASTOS_EN_GENERAL = "G03", e.CONSTRUCCIONES = "I01", e.MOBILIARIO_Y_EQUIPO_DE_OFICINA = "I02", e.EQUIPO_DE_TRANSPORTE = "I03", e.EQUIPO_DE_COMPUTO = "I04", e.DADOS_TROQUELES_HERRAMENTAL = "I05", e.COMUNICACIONES_TELEFONICAS = "I06", e.COMUNICACIONES_SATELITALES = "I07", e.OTRA_MAQUINARIA = "I08", e.HONORARIOS_MEDICOS = "D01", e.GASTOS_MEDICOS_POR_INCAPACIDAD = "D02", e.GASTOS_FUNERALES = "D03", e.DONATIVOS = "D04", e.INTERESES_POR_CREDITOS_HIPOTECARIOS = "D05", e.APORTACIONES_VOLUNTARIAS_SAR = "D06", e.PRIMA_SEGUROS_GASTOS_MEDICOS = "D07", e.GASTOS_TRANSPORTACION_ESCOLAR = "D08", e.CUENTAS_AHORRO_PENSIONES = "D09", e.SERVICIOS_EDUCATIVOS = "D10", e.SIN_EFECTOS_FISCALES = "S01", e.PAGOS = "CP01", e.NOMINA = "CN01", e.POR_DEFINIR = "P01", e))(Y || {}), $ = /* @__PURE__ */ ((e) => (e.INGRESO = "I", e.EGRESO = "E", e.TRASLADO = "T", e.NOMINA = "N", e.PAGO = "P", e))($ || {}), W = /* @__PURE__ */ ((e) => (e.NOTA_DE_CREDITO = "01", e.NOTA_DE_DEBITO = "02", e.DELOVUCION_DE_MERCANCIA = "03", e.SUSTITUCION_DE_CFDI_PREVIOS = "04", e.TRASLADOS_DE_MERCANCIA_FACTURADOS_PREVIAMENTE = "05", e.FACTURA_POR_TRASLADOS_PREVIOS = "06", e.APLICACION_DE_ANTICIPO = "07", e))(W || {}), Z = /* @__PURE__ */ ((e) => (e.GENERAL_LEY_DE_PERSONAS_MORALES = "601", e.PERSONAS_MORALES_CON_FINES_NO_LUCRATIVOS = "603", e.SUELDOS_Y_SALARIOS = "605", e.ARRENDAMIENTO = "606", e.REGIMEN_DE_ENAJENACION_O_ADQUISICION_DE_BIENES = "607", e.DEMAS_INGRESOS = "608", e.RESIDENTES_EN_EL_EXTRANJERO_SIN_ESTABLECIMIENTO_PERMANENTE_EN_MÉXICO = "610", e.RESIDENTES_EN_EL_EXTRANJERO = "610", e.INGRESOS_POR_DIVIDENDOS_SOCIOS_Y_ACCIONISTAS = "611", e.PERSONAS_FISICAS_CON_ACTIVIDADES_EMPRESARIALES_Y_PROFESIONALES = "612", e.INGRESOS_POR_INTERESES = "614", e.REGIMEN_DE_LOS_INGRESOS_POR_OBTENCION_DE_PREMIOS = "615", e.SIN_OBLIGACIONES_FISCALES = "616", e.SOCIEDADES_COOPERATIVAS_DE_PRODUCCION = "620", e.REGIMEN_DE_INCORPORACION_FISCAL = "621", e.ACTIVIDADES_AGRICOLAS_GANADERAS_SILVICOLAS_Y_PESQUERAS = "622", e.OPCIONAL_PARA_GRUPOS_DE_SOCIEDADES = "623", e.COORDINADOS = "624", e.ACTIVIDADES_EMPRESARIALES_CON_INGRESOS_A_TRAVÉS_DE_PLATAFORMAS_TECNOLÓGICAS = "625", e.RÉGIMEN_SIMPLIFICADO_DE_CONFIANZA = "626", e))(Z || {}), ee = /* @__PURE__ */ ((e) => (e.DRAFT = "draft", e.PENDING = "pending", e.VALID = "valid", e.CANCELED = "canceled", e.FAILED = "failed", e))(ee || {}), Ne = /* @__PURE__ */ ((e) => (e.DAY = "day", e.WEEK = "week", e.FORTNIGHT = "fortnight", e.MONTH = "month", e.TWO_MONTHS = "two_months", e))(Ne || {}), Re = /* @__PURE__ */ ((e) => (e.OPEN = "open", e.CANCELED = "canceled", e.INVOICED_TO_CUSTOMER = "invoiced_to_customer", e.INVOICED_GLOBALLY = "invoiced_globally", e))(Re || {}), ge = /* @__PURE__ */ ((e) => (e.ISSUING = "issuing", e.RECEIVING = "receiving", e))(ge || {}), De = /* @__PURE__ */ ((e) => (e.NONE = "none", e.ACCEPTED = "accepted", e.PENDING = "pending", e.REJECTED = "rejected", e.EXPIRED = "expired", e))(De || {}), Ce = /* @__PURE__ */ ((e) => (e.DAY = "day", e.WEEK = "week", e.FORTNIGHT = "fortnight", e.MONTH = "month", e.TWO_MONTHS = "two_months", e))(Ce || {}), we = /* @__PURE__ */ ((e) => (e.CUSTOM = "custom", e.PAGO = "pago", e.NOMINA = "nomina", e))(we || {}), Te = /* @__PURE__ */ ((e) => (e.ERRORES_CON_RELACION = "01", e.ERRORES_SIN_RELACION = "02", e.NO_SE_CONCRETO = "03", e.FACTURA_GLOBAL = "04", e))(Te || {}), D = typeof globalThis < "u" ? globalThis : typeof window < "u" ? window : typeof global < "u" ? global : typeof self < "u" ? self : {}; function ve(e) { return e && e.__esModule && Object.prototype.hasOwnProperty.call(e, "default") ? e.default : e; } var C = { exports: {} }, F; function Pe() { return F || (F = 1, function(e, t) { var n = typeof globalThis < "u" && globalThis || typeof self < "u" && self || typeof D < "u" && D, s = function() { function c() { this.fetch = !1, this.DOMException = n.DOMException; } return c.prototype = n, new c(); }(); (function(c) { (function(l) { var f = typeof c < "u" && c || typeof self < "u" && self || // eslint-disable-next-line no-undef typeof D < "u" && D || {}, h = { searchParams: "URLSearchParams" in f, iterable: "Symbol" in f && "iterator" in Symbol, blob: "FileReader" in f && "Blob" in f && function() { try { return new Blob(), !0; } catch { return !1; } }(), formData: "FormData" in f, arrayBuffer: "ArrayBuffer" in f }; function A(r) { return r && DataView.prototype.isPrototypeOf(r); } if (h.arrayBuffer) var S = [ "[object Int8Array]", "[object Uint8Array]", "[object Uint8ClampedArray]", "[object Int16Array]", "[object Uint16Array]", "[object Int32Array]", "[object Uint32Array]", "[object Float32Array]", "[object Float64Array]" ], N = ArrayBuffer.isView || function(r) { return r && S.indexOf(Object.prototype.toString.call(r)) > -1; }; function y(r) { if (typeof r != "string" && (r = String(r)), /[^a-z0-9\-#$%&'*+.^_`|~!]/i.test(r) || r === "") throw new TypeError('Invalid character in header field name: "' + r + '"'); return r.toLowerCase(); } function R(r) { return typeof r != "string" && (r = String(r)), r; } function v(r) { var i = { next: function() { var o = r.shift(); return { done: o === void 0, value: o }; } }; return h.iterable && (i[Symbol.iterator] = function() { return i; }), i; } function p(r) { this.map = {}, r instanceof p ? r.forEach(function(i, o) { this.append(o, i); }, this) : Array.isArray(r) ? r.forEach(function(i) { if (i.length != 2) throw new TypeError("Headers constructor: expected name/value pair to be length 2, found" + i.length); this.append(i[0], i[1]); }, this) : r && Object.getOwnPropertyNames(r).forEach(function(i) { this.append(i, r[i]); }, this); } p.prototype.append = function(r, i) { r = y(r), i = R(i); var o = this.map[r]; this.map[r] = o ? o + ", " + i : i; }, p.prototype.delete = function(r) { delete this.map[y(r)]; }, p.prototype.get = function(r) { return r = y(r), this.has(r) ? this.map[r] : null; }, p.prototype.has = function(r) { return this.map.hasOwnProperty(y(r)); }, p.prototype.set = function(r, i) { this.map[y(r)] = R(i); }, p.prototype.forEach = function(r, i) { for (var o in this.map) this.map.hasOwnProperty(o) && r.call(i, this.map[o], o, this); }, p.prototype.keys = function() { var r = []; return this.forEach(function(i, o) { r.push(o); }), v(r); }, p.prototype.values = function() { var r = []; return this.forEach(function(i) { r.push(i); }), v(r); }, p.prototype.entries = function() { var r = []; return this.forEach(function(i, o) { r.push([o, i]); }), v(r); }, h.iterable && (p.prototype[Symbol.iterator] = p.prototype.entries); function P(r) { if (!r._noBody) { if (r.bodyUsed) return Promise.reject(new TypeError("Already read")); r.bodyUsed = !0; } } function M(r) { return new Promise(function(i, o) { r.onload = function() { i(r.result); }, r.onerror = function() { o(r.error); }; }); } function te(r) { var i = new FileReader(), o = M(i); return i.readAsArrayBuffer(r), o; } function re(r) { var i = new FileReader(), o = M(i), u = /charset=([A-Za-z0-9_-]+)/.exec(r.type), E = u ? u[1] : "utf-8"; return i.readAsText(r, E), o; } function ie(r) { for (var i = new Uint8Array(r), o = new Array(i.length), u = 0; u < i.length; u++) o[u] = String.fromCharCode(i[u]); return o.join(""); } function U(r) { if (r.slice) return r.slice(0); var i = new Uint8Array(r.byteLength); return i.set(new Uint8Array(r)), i.buffer; } function G() { return this.bodyUsed = !1, this._initBody = function(r) { this.bodyUsed = this.bodyUsed, this._bodyInit = r, r ? typeof r == "string" ? this._bodyText = r : h.blob && Blob.prototype.isPrototypeOf(r) ? this._bodyBlob = r : h.formData && FormData.prototype.isPrototypeOf(r) ? this._bodyFormData = r : h.searchParams && URLSearchParams.prototype.isPrototypeOf(r) ? this._bodyText = r.toString() : h.arrayBuffer && h.blob && A(r) ? (this._bodyArrayBuffer = U(r.buffer), this._bodyInit = new Blob([this._bodyArrayBuffer])) : h.arrayBuffer && (ArrayBuffer.prototype.isPrototypeOf(r) || N(r)) ? this._bodyArrayBuffer = U(r) : this._bodyText = r = Object.prototype.toString.call(r) : (this._noBody = !0, this._bodyText = ""), this.headers.get("content-type") || (typeof r == "string" ? this.headers.set("content-type", "text/plain;charset=UTF-8") : this._bodyBlob && this._bodyBlob.type ? this.headers.set("content-type", this._bodyBlob.type) : h.searchParams && URLSearchParams.prototype.isPrototypeOf(r) && this.headers.set("content-type", "application/x-www-form-urlencoded;charset=UTF-8")); }, h.blob && (this.blob = function() { var r = P(this); if (r) return r; if (this._bodyBlob) return Promise.resolve(this._bodyBlob); if (this._bodyArrayBuffer) return Promise.resolve(new Blob([this._bodyArrayBuffer])); if (this._bodyFormData) throw new Error("could not read FormData body as blob"); return Promise.resolve(new Blob([this._bodyText])); }), this.arrayBuffer = function() { if (this._bodyArrayBuffer) { var r = P(this); return r || (ArrayBuffer.isView(this._bodyArrayBuffer) ? Promise.resolve( this._bodyArrayBuffer.buffer.slice( this._bodyArrayBuffer.byteOffset, this._bodyArrayBuffer.byteOffset + this._bodyArrayBuffer.byteLength ) ) : Promise.resolve(this._bodyArrayBuffer)); } else { if (h.blob) return this.blob().then(te); throw new Error("could not read as ArrayBuffer"); } }, this.text = function() { var r = P(this); if (r) return r; if (this._bodyBlob) return re(this._bodyBlob); if (this._bodyArrayBuffer) return Promise.resolve(ie(this._bodyArrayBuffer)); if (this._bodyFormData) throw new Error("could not read FormData body as text"); return Promise.resolve(this._bodyText); }, h.formData && (this.formData = function() { return this.text().then(oe); }), this.json = function() { return this.text().then(JSON.parse); }, this; } var ne = ["CONNECT", "DELETE", "GET", "HEAD", "OPTIONS", "PATCH", "POST", "PUT", "TRACE"]; function se(r) { var i = r.toUpperCase(); return ne.indexOf(i) > -1 ? i : r; } function I(r, i) { if (!(this instanceof I)) throw new TypeError('Please use the "new" operator, this DOM object constructor cannot be called as a function.'); i = i || {}; var o = i.body; if (r instanceof I) { if (r.bodyUsed) throw new TypeError("Already read"); this.url = r.url, this.credentials = r.credentials, i.headers || (this.headers = new p(r.headers)), this.method = r.method, this.mode = r.mode, this.signal = r.signal, !o && r._bodyInit != null && (o = r._bodyInit, r.bodyUsed = !0); } else this.url = String(r); if (this.credentials = i.credentials || this.credentials || "same-origin", (i.headers || !this.headers) && (this.headers = new p(i.headers)), this.method = se(i.method || this.method || "GET"), this.mode = i.mode || this.mode || null, this.signal = i.signal || this.signal || function() { if ("AbortController" in f) { var a = new AbortController(); return a.signal; } }(), this.referrer = null, (this.method === "GET" || this.method === "HEAD") && o) throw new TypeError("Body not allowed for GET or HEAD requests"); if (this._initBody(o), (this.method === "GET" || this.method === "HEAD") && (i.cache === "no-store" || i.cache === "no-cache")) { var u = /([?&])_=[^&]*/; if (u.test(this.url)) this.url = this.url.replace(u, "$1_=" + (/* @__PURE__ */ new Date()).getTime()); else { var E = /\?/; this.url += (E.test(this.url) ? "&" : "?") + "_=" + (/* @__PURE__ */ new Date()).getTime(); } } } I.prototype.clone = function() { return new I(this, { body: this._bodyInit }); }; function oe(r) { var i = new FormData(); return r.trim().split("&").forEach(function(o) { if (o) { var u = o.split("="), E = u.shift().replace(/\+/g, " "), a = u.join("=").replace(/\+/g, " "); i.append(decodeURIComponent(E), decodeURIComponent(a)); } }), i; } function ae(r) { var i = new p(), o = r.replace(/\r?\n[\t ]+/g, " "); return o.split("\r").map(function(u) { return u.indexOf(` `) === 0 ? u.substr(1, u.length) : u; }).forEach(function(u) { var E = u.split(":"), a = E.shift().trim(); if (a) { var g = E.join(":").trim(); try { i.append(a, g); } catch (B) { console.warn("Response " + B.message); } } }), i; } G.call(I.prototype); function O(r, i) { if (!(this instanceof O)) throw new TypeError('Please use the "new" operator, this DOM object constructor cannot be called as a function.'); if (i || (i = {}), this.type = "default", this.status = i.status === void 0 ? 200 : i.status, this.status < 200 || this.status > 599) throw new RangeError("Failed to construct 'Response': The status provided (0) is outside the range [200, 599]."); this.ok = this.status >= 200 && this.status < 300, this.statusText = i.statusText === void 0 ? "" : "" + i.statusText, this.headers = new p(i.headers), this.url = i.url || "", this._initBody(r); } G.call(O.prototype), O.prototype.clone = function() { return new O(this._bodyInit, { status: this.status, statusText: this.statusText, headers: new p(this.headers), url: this.url }); }, O.error = function() { var r = new O(null, { status: 200, statusText: "" }); return r.ok = !1, r.status = 0, r.type = "error", r; }; var le = [301, 302, 303, 307, 308]; O.redirect = function(r, i) { if (le.indexOf(i) === -1) throw new RangeError("Invalid status code"); return new O(null, { status: i, headers: { location: r } }); }, l.DOMException = f.DOMException; try { new l.DOMException(); } catch { l.DOMException = function(i, o) { this.message = i, this.name = o; var u = Error(i); this.stack = u.stack; }, l.DOMException.prototype = Object.create(Error.prototype), l.DOMException.prototype.constructor = l.DOMException; } function m(r, i) { return new Promise(function(o, u) { var E = new I(r, i); if (E.signal && E.signal.aborted) return u(new l.DOMException("Aborted", "AbortError")); var a = new XMLHttpRequest(); function g() { a.abort(); } a.onload = function() { var _ = { statusText: a.statusText, headers: ae(a.getAllResponseHeaders() || "") }; E.url.indexOf("file://") === 0 && (a.status < 200 || a.status > 599) ? _.status = 200 : _.status = a.status, _.url = "responseURL" in a ? a.responseURL : _.headers.get("X-Request-URL"); var b = "response" in a ? a.response : a.responseText; setTimeout(function() { o(new O(b, _)); }, 0); }, a.onerror = function() { setTimeout(function() { u(new TypeError("Network request failed")); }, 0); }, a.ontimeout = function() { setTimeout(function() { u(new TypeError("Network request timed out")); }, 0); }, a.onabort = function() { setTimeout(function() { u(new l.DOMException("Aborted", "AbortError")); }, 0); }; function B(_) { try { return _ === "" && f.location.href ? f.location.href : _; } catch { return _; } } if (a.open(E.method, B(E.url), !0), E.credentials === "include" ? a.withCredentials = !0 : E.credentials === "omit" && (a.withCredentials = !1), "responseType" in a && (h.blob ? a.responseType = "blob" : h.arrayBuffer && (a.responseType = "arraybuffer")), i && typeof i.headers == "object" && !(i.headers instanceof p || f.Headers && i.headers instanceof f.Headers)) { var V = []; Object.getOwnPropertyNames(i.headers).forEach(function(_) { V.push(y(_)), a.setRequestHeader(_, R(i.headers[_])); }), E.headers.forEach(function(_, b) { V.indexOf(b) === -1 && a.setRequestHeader(b, _); }); } else E.headers.forEach(function(_, b) { a.setRequestHeader(b, _); }); E.signal && (E.signal.addEventListener("abort", g), a.onreadystatechange = function() { a.readyState === 4 && E.signal.removeEventListener("abort", g); }), a.send(typeof E._bodyInit > "u" ? null : E._bodyInit); }); } return m.polyfill = !0, f.fetch || (f.fetch = m, f.Headers = p, f.Request = I, f.Response = O), l.Headers = p, l.Request = I, l.Response = O, l.fetch = m, l; })({}); })(s), s.fetch.ponyfill = !0, delete s.fetch.polyfill; var d = n.fetch ? n : s; t = d.fetch, t.default = d.fetch, t.fetch = d.fetch, t.Headers = d.Headers, t.Request = d.Request, t.Response = d.Response, e.exports = t; }(C, C.exports)), C.exports; } var me = Pe(); const Be = /* @__PURE__ */ ve(me); let w; T ? w = (e) => Buffer.from(e).toString("base64") : q ? w = (e) => globalThis.Buffer.from(e).toString("base64") : w = globalThis.btoa; const Le = async (e) => { var n; if (!e.ok) { const s = await e.json(); throw new Error(s.message || e.statusText); } const t = e.headers.get("content-type"); if (t) { if (t.includes("image/") || t.includes("application/pdf") || t.includes("application/xml") || t.includes("application/zip")) if (T) { const s = (n = e.body) == null ? void 0 : n.getReader(); if (!s) return e.body; try { const { Readable: d } = await import("stream"); return new d({ read() { s.read().then(({ done: c, value: l }) => { c ? this.push(null) : this.push(Buffer.from(l)); }); } }); } catch { throw new Error( 'Node.js streams are not available in this environment. Please install the "stream" package.' ); } } else return e.blob(); else if (t.includes("application/json")) return e.json(); } return e.text(); }; function Me(e) { return w(e); } const Ue = (e, t = z) => { const n = t === "v1" ? pe : Ee, s = { Authorization: `Basic ${Me(e + ":")}` }; return { async request(c, l) { const { params: f, body: h, formData: A, ...S } = l || {}, N = f ? "?" + new URLSearchParams(f).toString() : "", y = { ...S, headers: { ...s, ...A ? {} : { "Content-Type": "application/json" } }, body: A || (h ? JSON.stringify(h) : void 0) }, R = await Be(n + c + N, y); return Le(R); }, get(c, l) { return this.request(c, { method: "GET", ...l }); }, post(c, l) { return this.request(c, { method: "POST", ...l }); }, put(c, l) { return this.request(c, { method: "PUT", ...l }); }, delete(c, l) { return this.request(c, { method: "DELETE", ...l }); } }; }; var Ge = /* @__PURE__ */ ((e) => (e.RECEIPT_SELF_INVOICE_COMPLETE = "receipt.self_invoice_complete", e.INVOICE_CANCELLATION_STATUS_UPDATED = "invoice.cancellation_status_updated", e.RECEIPT_STATUS_UPDATED = "receipt.status_updated", e.GLOBAL_INVOICE = "invoice.global_invoice_created", e.INVOICES_STATUS_UPDATED = "invoice.status_updated", e.INVOICES_CREATED_FROM_DASHBOARD = "invoice.created_from_dashboard", e.CUSTOMER_EDIT_LINK_COMPLETED = "customer.edit_link_completed", e))(Ge || {}), Ve = /* @__PURE__ */ ((e) => (e.RECEIPT = "receipt", e.INVOICE = "invoice", e.CUSTOMER = "customer", e))(Ve || {}), je = /* @__PURE__ */ ((e) => (e.ENABLED = "enabled", e.DISABLED = "disabled", e))(je || {}); const k = ["v1", "v2"]; class He { static get TaxType() { return J; } static get TaxFactor() { return X; } static get IepsMode() { return K; } static get PaymentForm() { return x; } static get PaymentMethod() { return Q; } static get InvoiceType() { return $; } static get InvoiceUse() { return Y; } static get InvoiceRelation() { return W; } static get TaxSystem() { return Z; } static get InvoiceStatus() { return ee; } constructor(t, n = {}) { if (n.apiVersion) { if (!k.includes(n.apiVersion)) throw new Error( "Invalid API version. Valid values are: " + k.join(", ") ); this.apiVersion = n.apiVersion; } else this.apiVersion = z; const s = Ue(t, this.apiVersion); this.customers = new ce(s), this.products = new ue(s), this.invoices = new fe(s), this.organizations = new Oe(s), this.catalogs = new Ae(s), this.receipts = new ye(s), this.retentions = new Ie(s), this.tools = new Se(s), this.webhooks = new be(s); } } export { Ve as ApiEventDataType, Ge as ApiEventType, Te as CancellationMotive, De as CancellationStatus, Ne as GlobalInvoicePeriodicity, K as IepsMode, we as InvoiceComplementType, W as InvoiceRelation, ee as InvoiceStatus, $ as InvoiceType, Y as InvoiceUse, Ce as InvoicingPeriod, ge as IssuingType, x as PaymentForm, ke as PaymentFormList, Q as PaymentMethod, Re as ReceiptStatus, X as TaxFactor, Z as TaxSystem, J as TaxType, je as WebhookEndpointStatus, He as default };