facturapi
Version:
Librería oficial de Facturapi. Crea CFDIs timbrados y enviados al SAT, XML y PDF
1,389 lines • 50.9 kB
JavaScript
class le {
constructor(e) {
this.client = e;
}
/**
* Creates a new customer in your organization
* @param data Customer data
* @param params Query params
* @returns Customer object
*/
create(e, n = null) {
return this.client.post("/customers", { body: e, params: n });
}
/**
* Gets a paginated list of customers that belong to your organization
* @param params Search parameters
* @returns List of customers
*/
list(e) {
return e || (e = {}), this.client.get("/customers", { params: e });
}
/**
* Gets a single customer object
* @param id Customer Id
* @returns Customer object
*/
retrieve(e) {
return e ? this.client.get("/customers/" + e) : 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(e, n, u = null) {
return this.client.put("/customers/" + e, { body: n, params: u });
}
/**
* Permanently removes a customer from your organization.
* @param id Customer Id
* @returns Deleted customer
*/
del(e) {
return this.client.delete("/customers/" + e);
}
/**
* Validate customer with SAT validation.
* @param id Customer Id
* @returns Validation result
*/
validateTaxInfo(e) {
return this.client.get("/customers/" + e + "/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(e, n) {
return this.client.post("/customers/" + e + "/email-edit-link", {
body: n
});
}
}
class ue {
constructor(e) {
this.client = e;
}
/**
* Creates a new product in your organization
* @param data - Product data
* @returns Product object
*/
create(e) {
return this.client.post("/products", { body: e });
}
/**
* 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(e) {
return this.client.get("/products", { params: e });
}
/**
* Gets a single product object
* @param id - Product Id
* @returns Product object
*/
retrieve(e) {
return e ? this.client.get("/products/" + e) : Promise.reject(new Error("id is required"));
}
/**
* Updates a product
* @param id - Product Id
* @param data - Product data to update
* @returns Updated product
*/
update(e, n) {
return this.client.put("/products/" + e, { body: n });
}
/**
* Permanently removes a product from your organization.
* @param id - Product Id
* @returns Deleted product
*/
del(e) {
return this.client.delete("/products/" + e);
}
}
class fe {
constructor(e) {
this.client = e;
}
/**
* Creates a new valid invoice (CFDI).
* @param body Invoice data
* @param params Query params
* @returns Invoice object
*/
create(e, n) {
return this.client.post("/invoices", { body: e, 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(e) {
return e || (e = {}), this.client.get("/invoices", { params: e });
}
/**
* Gets a single invoice object
* @param id Invoice Id
* @returns Invoice object
*/
retrieve(e) {
return e ? this.client.get("/invoices/" + e) : 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(e, n) {
return this.client.delete("/invoices/" + e, { 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(e, n) {
return this.client.post("/invoices/" + e + "/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(e) {
return this.client.get("/invoices/" + e + "/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(e) {
return this.client.get("/invoices/" + e + "/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(e) {
return this.client.get("/invoices/" + e + "/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(e) {
return this.client.get("/invoices/" + e + "/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(e) {
return this.client.get("/invoices/" + e + "/cancellation_receipt/pdf");
}
/**
* Edits an invoice with "draft" status.
* @param id Invoice Id
* @param data Invoice data to edit
* @returns Edited invoice
*/
updateDraft(e, n) {
return this.client.put("/invoices/" + e, { body: n });
}
/**
* Stamps an invoice with "draft" status.
* @param id Invoice Id
* @param params Query params
* @returns Stamped invoice
*/
stampDraft(e, n) {
return this.client.post("/invoices/" + e + "/stamp", { params: n });
}
/**
* Updates the latest status of the invoice from the SAT
* @param id Invoice Id
* @returns Updated invoice
*/
updateStatus(e) {
return this.client.put("/invoices/" + e + "/status");
}
/**
* Creates a draft invoice from any other invoice
* @param id Invoice Id
* @returns Draft invoice
*/
copyToDraft(e) {
return this.client.post("/invoices/" + e + "/copy");
}
/**
* Previews an invoice PDF before stamping it
* @param body Invoice data
* @returns PDF file in a stream (Node.js) or Blob (browser)
*/
previewPdf(e) {
return this.client.post("/invoices/preview/pdf", { body: e });
}
}
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", T = typeof process < "u" && !!process?.versions?.node, H = typeof navigator < "u" && navigator?.product === "ReactNative";
function _e(t) {
return new Promise((e, n) => {
const u = [];
t.on("data", (d) => u.push(d)), t.on("end", () => e(Buffer.concat(u))), t.on("error", n);
});
}
const B = async (t, e, n) => {
if (T) {
const u = t instanceof Buffer ? t : await _e(t);
return new he([u], e, {
type: n
});
}
return t;
};
class Oe {
constructor(e) {
this.client = e;
}
/**
* Creates a new organization for your account
* @param data - Organization data
* @returns Organization object
*/
create(e) {
return this.client.post("/organizations", { body: e });
}
/**
* 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(e) {
return e || (e = {}), this.client.get("/organizations", { params: e });
}
/**
* Gets a single organization object
* @param id
* @returns
*/
retrieve(e) {
return e ? this.client.get("/organizations/" + e) : Promise.reject(new Error("id is required"));
}
/**
* Updates the organization's legal information
* @param id Organization Id
* @param data
* @returns
*/
updateLegal(e, n) {
return e ? this.client.put("/organizations/" + e + "/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(e, n) {
return this.client.put("/organizations/" + e + "/customization", {
body: n
});
}
/**
* Updates the organization's customization information
* @param id Organization Id
* @param data Receipt settings
* @returns Organization object
*/
updateReceiptSettings(e, n) {
return this.client.put("/organizations/" + e + "/receipts", {
body: n
});
}
/**
* Updates the organization's customization information
* @param id Organization Id
* @param data Domain data
* @returns Organization object
*/
updateDomain(e, n) {
return this.client.put("/organizations/" + e + "/domain", { body: n });
}
/**
* Checks if a domain is available for self invoices
* @param data Domain data
* @returns Domain availability
*/
checkDomainIsAvailable(e) {
return this.client.put("/organizations/domain-check", { body: e });
}
/**
* Uploads the organization's logo
* @param id Organization Id
* @param file Logo file
* @returns Organization object
*/
async uploadLogo(e, n) {
const u = await B(
n,
"file",
"application/octet-stream"
), d = new j();
return d.append("file", u, "file"), this.client.put("/organizations/" + e + "/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(e, n, u, d) {
let a = new j();
const [c, f] = await Promise.all([
B(n, "cer.cer", "application/octet-stream"),
B(u, "key.key", "application/octet-stream")
]);
return a.append("cer", c, "cer.cer"), a.append("key", f, "key.key"), a.append("password", d), this.client.put("/organizations/" + e + "/certificate", {
formData: a
});
}
/**
* Deletes the organization's certificate (CSD)
* @param id Organization Id
* @returns Organization object
*/
deleteCertificate(e) {
return this.client.delete("/organizations/" + e + "/certificate");
}
/**
* Permanently removes a organization from your account.
* @param id Organization Id
* @returns Deleted organization object
*/
del(e) {
return e ? this.client.delete("/organizations/" + e) : Promise.reject(new Error("id is required"));
}
/**
* Gets the test api key for an organization
* @param id Organization Id
* @returns Test api key
*/
getTestApiKey(e) {
return this.client.get("/organizations/" + e + "/apikeys/test");
}
/**
* Renews the test api key and makes the previous one unusable
* @param id Organization Id
* @returns New test api key
*/
renewTestApiKey(e) {
return this.client.put("/organizations/" + e + "/apikeys/test");
}
/**
* List live api keys
* @param id Organization Id
* @returns List of live api keys
*/
async listLiveApiKeys(e) {
return this.client.get("/organizations/" + e + "/apikeys/live");
}
/**
* Renews the live api key and makes the previous one unusable
* @param id Organization Id
* @returns New live api key
*/
renewLiveApiKey(e) {
return this.client.put("/organizations/" + e + "/apikeys/live");
}
/**
* Delete a live api key
* @param organizationId Organization Id
* @param apiKeyId Api Key Id
* @returns List of live api keys
*/
async deleteLiveApiKey(e, n) {
return this.client.delete(
"/organizations/" + e + "/apikeys/live/" + n
);
}
/**
* Get list of Series Organization
* @param organization_id Organization Id
* @returns Series object
*/
listSeriesGroup(e) {
return this.client.get(
"/organizations/" + e + "/series-group"
);
}
/**
* Creates a Series Organization
* @param organization_id Organization Id
* @param seriesData - Series data
* @returns Series object
*/
createSeriesGroup(e, n) {
return this.client.post(
"/organizations/" + e + "/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(e, n, u) {
return this.client.put(
`/organizations/${e}/series-group/${n}`,
{
body: u
}
);
}
/**
* Update a Series Organization
* @param organization_id Organization Id
* @param seriesName Series seriesName
* @returns Series object
*/
deleteSeriesGroup(e, n) {
return this.client.delete(
`/organizations/${e}/series-group/${n}`
);
}
/**
* Get the organization that belongs to the authenticated API key
* @returns Organization object
*/
me() {
return this.client.get("/organizations/me");
}
/**
* Updates the organization's self-invoice settings
* @param id Organization Id
* @param data Self-invoice settings
* @returns Organization object
*/
updateSelfInvoiceSettings(e, n) {
return this.client.put("/organizations/" + e + "/self-invoice", {
body: n
});
}
}
class Ae {
constructor(e) {
this.client = e;
}
/**
* Creates a new product in your organization
* @param {Object} params - Search parameters
* @returns {Promise}
*/
searchProducts(e) {
return this.client.get("/catalogs/products", { params: e });
}
/**
* Gets a paginated list of products that belong to your organization
* @param {[Object]} params - Search parameters
* @returns {Promise}
*/
searchUnits(e) {
return this.client.get("/catalogs/units", { params: e });
}
}
class ge {
constructor(e) {
this.client = e;
}
/**
* Creates a new receipt
* @param data Receipt data
* @returns Receipt object
*/
create(e) {
return this.client.post("/receipts", { body: e });
}
/**
* 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(e) {
return e || (e = {}), this.client.get("/receipts", { params: e });
}
/**
* Gets a single receipt object
* @param id Receipt Id
* @returns Receipt object
*/
retrieve(e) {
return e ? this.client.get("/receipts/" + e) : 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(e, n) {
return this.client.post("/receipts/" + e + "/invoice", { body: n });
}
/**
* Creates a global invoice for open receipts
* @param data
* @returns
*/
createGlobalInvoice(e) {
return this.client.post("/receipts/global-invoice", { body: e });
}
/**
* Marks a receipt as canceled. The receipt won't be available for invoicing anymore.
* @param id
* @returns
*/
cancel(e) {
return this.client.delete("/receipts/" + e);
}
/**
* 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(e, n) {
return this.client.post("/receipts/" + e + "/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(e) {
return this.client.get("/receipts/" + e + "/pdf");
}
}
class ye {
constructor(e) {
this.client = e;
}
/**
* Creates a new valid retention (CFDI).
* @param data
* @returns
*/
create(e) {
return this.client.post("/retentions", { body: e });
}
/**
* Gets a paginated list of retentions created by the organization
* @param params - Search parameters
* @returns
*/
list(e) {
return e || (e = {}), this.client.get("/retentions", { params: e });
}
/**
* Gets a single retention object
* @param id
* @returns
*/
retrieve(e) {
return e ? this.client.get("/retentions/" + e) : Promise.reject(new Error("id is required"));
}
/**
* Cancels a retention.
* @param id
* @param params - Optional cancellation parameters (e.g., motive, substitution)
* @returns
*/
cancel(e, n) {
return this.client.delete("/retentions/" + e, { params: n });
}
/**
* 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(e, n) {
return this.client.post("/retentions/" + e + "/email", { body: n });
}
/**
* Downloads the specified retention in PDF format
* @param id Retention Id
* @returns PDF file in a stream
*/
downloadPdf(e) {
return this.client.get("/retentions/" + e + "/pdf");
}
/**
* Downloads the specified retention in XML format
* @param id Retention Id
* @returns XML file in a stream
*/
downloadXml(e) {
return this.client.get("/retentions/" + e + "/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(e) {
return this.client.get("/retentions/" + e + "/zip");
}
}
class be {
constructor(e) {
this.client = e;
}
/**
* Creates a new webhook in your organization
* @param data - Webhook options
* @returns Webhook object
*/
create(e) {
return this.client.post("/webhooks", { body: e });
}
/**
* 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(e) {
return e || (e = {}), this.client.get("/webhooks", { params: e });
}
/**
* Gets a single webhook object
* @param id - Webhook Id
* @returns Webhook object
*/
retrieve(e) {
return e ? this.client.get("/webhooks/" + e) : Promise.reject(new Error("id is required"));
}
/**
* Updates a webhook
* @param id - Webhook Id
* @param data Updated webhook data
* @returns
*/
update(e, n) {
return this.client.put("/webhooks/" + e, { body: n });
}
/**
* Permanently removes a webhook from your organization.
* @param id - Webhook Id
* @returns Deleted webhook
*/
del(e) {
return this.client.delete("/webhooks/" + e);
}
/**
* 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(e) {
const { secret: n, signature: u, payload: d } = e;
let a;
if (typeof d == "string")
a = d;
else if (Buffer.isBuffer(d))
a = d.toString("utf8");
else if (typeof d == "object")
a = JSON.stringify(d);
else
throw new Error("Invalid payload type");
if (H)
return this.client.post("/webhooks/validate-signature", {
body: {
secret: n,
signature: u,
payload: a
}
});
if (T) {
const c = await import("crypto"), h = c.createHmac("sha256", n).update(a).digest(), A = Buffer.from(u, "hex");
if (h.length !== A.length)
throw new Error("Invalid signature");
if (!c.timingSafeEqual(h, A))
throw new Error("Invalid signature");
return JSON.parse(a);
} else {
const c = new TextEncoder(), f = c.encode(a), h = c.encode(n), A = await crypto.subtle.sign(
"HMAC",
await crypto.subtle.importKey(
"raw",
h,
{ name: "HMAC", hash: "SHA-256" },
!1,
["sign"]
),
f
), I = Array.from(new Uint8Array(A)).map((S) => S.toString(16).padStart(2, "0")).join("").toLowerCase();
if (u !== I)
throw new Error("Invalid signature");
}
return JSON.parse(a);
}
}
class Ie {
/**
* @param {Client} client
*/
constructor(e) {
this.client = e;
}
/**
* Validates a tax_id in EFOS list
* @param {Object} taxId - Search parameters
* @returns {Promise}
*/
validateTaxId(e) {
return this.client.get("/tools/tax_id_validation", {
params: {
tax_id: e
}
});
}
}
var q = /* @__PURE__ */ ((t) => (t.EFECTIVO = "01", t.CHEQUE_NOMINATIVO = "02", t.TRANSFERENCIA_ELECTRONICA_DE_FONDOS = "03", t.TARJETA_DE_CREDITO = "04", t.MONEDERO_ELECTRONICO = "05", t.DINERO_ELECTRONICO = "06", t.VALES_DE_DESPENSA = "08", t.DACION_EN_PAGO = "12", t.PAGO_POR_SUBROGACION = "13", t.PAGO_POR_CONSIGNACION = "14", t.CONDONACION = "15", t.COMPENSACION = "17", t.NOVACION = "23", t.CONFUSION = "24", t.REMISIÓN_DE_DEUDA = "25", t.PRESCRIPCION_O_CADUCIDAD = "26", t.A_SATISFACCION_DEL_ACREEDOR = "27", t.TARJETA_DE_DEBITO = "28", t.TARJETA_DE_SERVICIOS = "29", t.APLICACION_DE_ANTICIPOS = "30", t.INTERMEDIARIO_DE_PAGOS = "31", t.POR_DEFINIR = "99", t))(q || {});
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 x = /* @__PURE__ */ ((t) => (t.IVA = "IVA", t.IEPS = "IEPS", t.ISR = "ISR", t))(x || {}), J = /* @__PURE__ */ ((t) => (t.RATE = "Tasa", t.QUOTA = "Cuota", t))(J || {}), X = /* @__PURE__ */ ((t) => (t.SUM_BEFORE_TAXES = "sum_before_taxes", t.UNIT = "unit", t.BREAK_DOWN = "break_down", t.SUBTRACT_BEFORE_BREAKDOWN = "subtract_before_break_down", t))(X || {}), K = /* @__PURE__ */ ((t) => (t.PAGO_EN_UNA_EXHIBICION = "PUE", t.PAGO_EN_PARCIALIDADES_DIFERIDO = "PPD", t))(K || {}), Q = /* @__PURE__ */ ((t) => (t.ADQUISICION_MERCANCIAS = "G01", t.DEVOLUCIONES_DESCUENTOS_BONIFICACIONES = "G02", t.GASTOS_EN_GENERAL = "G03", t.CONSTRUCCIONES = "I01", t.MOBILIARIO_Y_EQUIPO_DE_OFICINA = "I02", t.EQUIPO_DE_TRANSPORTE = "I03", t.EQUIPO_DE_COMPUTO = "I04", t.DADOS_TROQUELES_HERRAMENTAL = "I05", t.COMUNICACIONES_TELEFONICAS = "I06", t.COMUNICACIONES_SATELITALES = "I07", t.OTRA_MAQUINARIA = "I08", t.HONORARIOS_MEDICOS = "D01", t.GASTOS_MEDICOS_POR_INCAPACIDAD = "D02", t.GASTOS_FUNERALES = "D03", t.DONATIVOS = "D04", t.INTERESES_POR_CREDITOS_HIPOTECARIOS = "D05", t.APORTACIONES_VOLUNTARIAS_SAR = "D06", t.PRIMA_SEGUROS_GASTOS_MEDICOS = "D07", t.GASTOS_TRANSPORTACION_ESCOLAR = "D08", t.CUENTAS_AHORRO_PENSIONES = "D09", t.SERVICIOS_EDUCATIVOS = "D10", t.SIN_EFECTOS_FISCALES = "S01", t.PAGOS = "CP01", t.NOMINA = "CN01", t.POR_DEFINIR = "P01", t))(Q || {}), Y = /* @__PURE__ */ ((t) => (t.INGRESO = "I", t.EGRESO = "E", t.TRASLADO = "T", t.NOMINA = "N", t.PAGO = "P", t))(Y || {}), $ = /* @__PURE__ */ ((t) => (t.NOTA_DE_CREDITO = "01", t.NOTA_DE_DEBITO = "02", t.DELOVUCION_DE_MERCANCIA = "03", t.SUSTITUCION_DE_CFDI_PREVIOS = "04", t.TRASLADOS_DE_MERCANCIA_FACTURADOS_PREVIAMENTE = "05", t.FACTURA_POR_TRASLADOS_PREVIOS = "06", t.APLICACION_DE_ANTICIPO = "07", t))($ || {}), W = /* @__PURE__ */ ((t) => (t.GENERAL_LEY_DE_PERSONAS_MORALES = "601", t.PERSONAS_MORALES_CON_FINES_NO_LUCRATIVOS = "603", t.SUELDOS_Y_SALARIOS = "605", t.ARRENDAMIENTO = "606", t.REGIMEN_DE_ENAJENACION_O_ADQUISICION_DE_BIENES = "607", t.DEMAS_INGRESOS = "608", t.RESIDENTES_EN_EL_EXTRANJERO_SIN_ESTABLECIMIENTO_PERMANENTE_EN_MÉXICO = "610", t.RESIDENTES_EN_EL_EXTRANJERO = "610", t.INGRESOS_POR_DIVIDENDOS_SOCIOS_Y_ACCIONISTAS = "611", t.PERSONAS_FISICAS_CON_ACTIVIDADES_EMPRESARIALES_Y_PROFESIONALES = "612", t.INGRESOS_POR_INTERESES = "614", t.REGIMEN_DE_LOS_INGRESOS_POR_OBTENCION_DE_PREMIOS = "615", t.SIN_OBLIGACIONES_FISCALES = "616", t.SOCIEDADES_COOPERATIVAS_DE_PRODUCCION = "620", t.REGIMEN_DE_INCORPORACION_FISCAL = "621", t.ACTIVIDADES_AGRICOLAS_GANADERAS_SILVICOLAS_Y_PESQUERAS = "622", t.OPCIONAL_PARA_GRUPOS_DE_SOCIEDADES = "623", t.COORDINADOS = "624", t.ACTIVIDADES_EMPRESARIALES_CON_INGRESOS_A_TRAVÉS_DE_PLATAFORMAS_TECNOLÓGICAS = "625", t.RÉGIMEN_SIMPLIFICADO_DE_CONFIANZA = "626", t))(W || {}), Z = /* @__PURE__ */ ((t) => (t.DRAFT = "draft", t.PENDING = "pending", t.VALID = "valid", t.CANCELED = "canceled", t.FAILED = "failed", t))(Z || {}), Se = /* @__PURE__ */ ((t) => (t.DAY = "day", t.WEEK = "week", t.FORTNIGHT = "fortnight", t.MONTH = "month", t.TWO_MONTHS = "two_months", t))(Se || {}), Re = /* @__PURE__ */ ((t) => (t.OPEN = "open", t.CANCELED = "canceled", t.INVOICED_TO_CUSTOMER = "invoiced_to_customer", t.INVOICED_GLOBALLY = "invoiced_globally", t))(Re || {}), Ne = /* @__PURE__ */ ((t) => (t.ISSUING = "issuing", t.RECEIVING = "receiving", t))(Ne || {}), De = /* @__PURE__ */ ((t) => (t.NONE = "none", t.ACCEPTED = "accepted", t.PENDING = "pending", t.REJECTED = "rejected", t.EXPIRED = "expired", t))(De || {}), we = /* @__PURE__ */ ((t) => (t.DAY = "day", t.WEEK = "week", t.FORTNIGHT = "fortnight", t.MONTH = "month", t.TWO_MONTHS = "two_months", t))(we || {}), Ce = /* @__PURE__ */ ((t) => (t.CUSTOM = "custom", t.PAGO = "pago", t.NOMINA = "nomina", t))(Ce || {}), ee = /* @__PURE__ */ ((t) => (t.ERRORES_CON_RELACION = "01", t.ERRORES_SIN_RELACION = "02", t.NO_SE_CONCRETO = "03", t.FACTURA_GLOBAL = "04", t))(ee || {}), D = typeof globalThis < "u" ? globalThis : typeof window < "u" ? window : typeof global < "u" ? global : typeof self < "u" ? self : {};
function Te(t) {
return t && t.__esModule && Object.prototype.hasOwnProperty.call(t, "default") ? t.default : t;
}
var w = { exports: {} }, F;
function ve() {
return F || (F = 1, function(t, e) {
var n = typeof globalThis < "u" && globalThis || typeof self < "u" && self || typeof D < "u" && D, u = function() {
function a() {
this.fetch = !1, this.DOMException = n.DOMException;
}
return a.prototype = n, new a();
}();
(function(a) {
(function(c) {
var f = typeof a < "u" && a || 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 I = [
"[object Int8Array]",
"[object Uint8Array]",
"[object Uint8ClampedArray]",
"[object Int16Array]",
"[object Uint16Array]",
"[object Int32Array]",
"[object Uint32Array]",
"[object Float32Array]",
"[object Float64Array]"
], S = ArrayBuffer.isView || function(r) {
return r && I.indexOf(Object.prototype.toString.call(r)) > -1;
};
function g(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 s = r.shift();
return { done: s === void 0, value: s };
}
};
return h.iterable && (i[Symbol.iterator] = function() {
return i;
}), i;
}
function p(r) {
this.map = {}, r instanceof p ? r.forEach(function(i, s) {
this.append(s, 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 = g(r), i = R(i);
var s = this.map[r];
this.map[r] = s ? s + ", " + i : i;
}, p.prototype.delete = function(r) {
delete this.map[g(r)];
}, p.prototype.get = function(r) {
return r = g(r), this.has(r) ? this.map[r] : null;
}, p.prototype.has = function(r) {
return this.map.hasOwnProperty(g(r));
}, p.prototype.set = function(r, i) {
this.map[g(r)] = R(i);
}, p.prototype.forEach = function(r, i) {
for (var s in this.map)
this.map.hasOwnProperty(s) && r.call(i, this.map[s], s, this);
}, p.prototype.keys = function() {
var r = [];
return this.forEach(function(i, s) {
r.push(s);
}), 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, s) {
r.push([s, 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 U(r) {
return new Promise(function(i, s) {
r.onload = function() {
i(r.result);
}, r.onerror = function() {
s(r.error);
};
});
}
function te(r) {
var i = new FileReader(), s = U(i);
return i.readAsArrayBuffer(r), s;
}
function re(r) {
var i = new FileReader(), s = U(i), l = /charset=([A-Za-z0-9_-]+)/.exec(r.type), E = l ? l[1] : "utf-8";
return i.readAsText(r, E), s;
}
function ie(r) {
for (var i = new Uint8Array(r), s = new Array(i.length), l = 0; l < i.length; l++)
s[l] = String.fromCharCode(i[l]);
return s.join("");
}
function M(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 = M(r.buffer), this._bodyInit = new Blob([this._bodyArrayBuffer])) : h.arrayBuffer && (ArrayBuffer.prototype.isPrototypeOf(r) || S(r)) ? this._bodyArrayBuffer = M(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 y(r, i) {
if (!(this instanceof y))
throw new TypeError('Please use the "new" operator, this DOM object constructor cannot be called as a function.');
i = i || {};
var s = i.body;
if (r instanceof y) {
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, !s && r._bodyInit != null && (s = 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 o = new AbortController();
return o.signal;
}
}(), this.referrer = null, (this.method === "GET" || this.method === "HEAD") && s)
throw new TypeError("Body not allowed for GET or HEAD requests");
if (this._initBody(s), (this.method === "GET" || this.method === "HEAD") && (i.cache === "no-store" || i.cache === "no-cache")) {
var l = /([?&])_=[^&]*/;
if (l.test(this.url))
this.url = this.url.replace(l, "$1_=" + (/* @__PURE__ */ new Date()).getTime());
else {
var E = /\?/;
this.url += (E.test(this.url) ? "&" : "?") + "_=" + (/* @__PURE__ */ new Date()).getTime();
}
}
}
y.prototype.clone = function() {
return new y(this, { body: this._bodyInit });
};
function oe(r) {
var i = new FormData();
return r.trim().split("&").forEach(function(s) {
if (s) {
var l = s.split("="), E = l.shift().replace(/\+/g, " "), o = l.join("=").replace(/\+/g, " ");
i.append(decodeURIComponent(E), decodeURIComponent(o));
}
}), i;
}
function ae(r) {
var i = new p(), s = r.replace(/\r?\n[\t ]+/g, " ");
return s.split("\r").map(function(l) {
return l.indexOf(`
`) === 0 ? l.substr(1, l.length) : l;
}).forEach(function(l) {
var E = l.split(":"), o = E.shift().trim();
if (o) {
var N = E.join(":").trim();
try {
i.append(o, N);
} catch (L) {
console.warn("Response " + L.message);
}
}
}), i;
}
G.call(y.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 ce = [301, 302, 303, 307, 308];
O.redirect = function(r, i) {
if (ce.indexOf(i) === -1)
throw new RangeError("Invalid status code");
return new O(null, { status: i, headers: { location: r } });
}, c.DOMException = f.DOMException;
try {
new c.DOMException();
} catch {
c.DOMException = function(i, s) {
this.message = i, this.name = s;
var l = Error(i);
this.stack = l.stack;
}, c.DOMException.prototype = Object.create(Error.prototype), c.DOMException.prototype.constructor = c.DOMException;
}
function m(r, i) {
return new Promise(function(s, l) {
var E = new y(r, i);
if (E.signal && E.signal.aborted)
return l(new c.DOMException("Aborted", "AbortError"));
var o = new XMLHttpRequest();
function N() {
o.abort();
}
o.onload = function() {
var _ = {
statusText: o.statusText,
headers: ae(o.getAllResponseHeaders() || "")
};
E.url.indexOf("file://") === 0 && (o.status < 200 || o.status > 599) ? _.status = 200 : _.status = o.status, _.url = "responseURL" in o ? o.responseURL : _.headers.get("X-Request-URL");
var b = "response" in o ? o.response : o.responseText;
setTimeout(function() {
s(new O(b, _));
}, 0);
}, o.onerror = function() {
setTimeout(function() {
l(new TypeError("Network request failed"));
}, 0);
}, o.ontimeout = function() {
setTimeout(function() {
l(new TypeError("Network request timed out"));
}, 0);
}, o.onabort = function() {
setTimeout(function() {
l(new c.DOMException("Aborted", "AbortError"));
}, 0);
};
function L(_) {
try {
return _ === "" && f.location.href ? f.location.href : _;
} catch {
return _;
}
}
if (o.open(E.method, L(E.url), !0), E.credentials === "include" ? o.withCredentials = !0 : E.credentials === "omit" && (o.withCredentials = !1), "responseType" in o && (h.blob ? o.responseType = "blob" : h.arrayBuffer && (o.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(g(_)), o.setRequestHeader(_, R(i.headers[_]));
}), E.headers.forEach(function(_, b) {
V.indexOf(b) === -1 && o.setRequestHeader(b, _);
});
} else
E.headers.forEach(function(_, b) {
o.setRequestHeader(b, _);
});
E.signal && (E.signal.addEventListener("abort", N), o.onreadystatechange = function() {
o.readyState === 4 && E.signal.removeEventListener("abort", N);
}), o.send(typeof E._bodyInit > "u" ? null : E._bodyInit);
});
}
return m.polyfill = !0, f.fetch || (f.fetch = m, f.Headers = p, f.Request = y, f.Response = O), c.Headers = p, c.Request = y, c.Response = O, c.fetch = m, c;
})({});
})(u), u.fetch.ponyfill = !0, delete u.fetch.polyfill;
var d = n.fetch ? n : u;
e = d.fetch, e.default = d.fetch, e.fetch = d.fetch, e.Headers = d.Headers, e.Request = d.Request, e.Response = d.Response, t.exports = e;
}(w, w.exports)), w.exports;
}
var Pe = ve();
const me = /* @__PURE__ */ Te(Pe);
let C;
T ? C = (t) => Buffer.from(t).toString("base64") : H ? C = (t) => globalThis.Buffer.from(t).toString("base64") : C = globalThis.btoa;
const Le = async (t) => {
if (!t.ok) {
const n = await t.json();
throw new Error(n.message || t.statusText);
}
const e = t.headers.get("content-type");
if (e) {
if (e.includes("image/") || e.includes("application/pdf") || e.includes("application/xml") || e.includes("application/zip"))
if (T) {
const n = t.body?.getReader();
if (!n)
return t.body;
try {
const { Readable: u } = await import("stream");
return new u({
read() {
n.read().then(({ done: d, value: a }) => {
d ? this.push(null) : this.push(Buffer.from(a));
});
}
});
} catch {
throw new Error(
'Node.js streams are not available in this environment. Please install the "stream" package.'
);
}
} else
return t.blob();
else if (e.includes("application/json"))
return t.json();
}
return t.text();
};
function Be(t) {
return C(t);
}
const Ue = (t, e = z) => {
let n = e === "v1" ? pe : Ee;
const u = {
Authorization: `Basic ${Be(t + ":")}`
};
return {
get baseURL() {
return n;
},
set baseURL(a) {
n = a;
},
async request(a, c) {
const { params: f, body: h, formData: A, ...I } = c || {}, S = f ? "?" + new URLSearchParams(f).toString() : "", g = {
...I,
headers: {
...u,
...A ? {} : { "Content-Type": "application/json" }
},
body: A || (h ? JSON.stringify(h) : void 0)
}, R = await me(n + a + S, g);
return Le(R);
},
get(a, c) {
return this.request(a, { method: "GET", ...c });
},
post(a, c) {
return this.request(a, { method: "POST", ...c });
},
put(a, c) {
return this.request(a, { method: "PUT", ...c });
},
delete(a, c) {
return this.request(a, { method: "DELETE", ...c });
}
};
};
class Me {
constructor(e) {
this.client = e;
}
/**
* Air transport codes (Carta Porte 3.1)
* @param {Object} params - Search parameters
* @returns {Promise}
*/
searchAirTransportCodes(e) {
return this.client.get("/catalogs/cartaporte/3.1/air-transport-codes", {
params: e
});
}
/**
* Auto transport configurations (Carta Porte 3.1)
* @param {Object} params - Search parameters
* @returns {Promise}
*/
searchTransportConfigs(e) {
return this.client.get("/catalogs/cartaporte/3.1/transport-configs", {
params: e
});
}
/**
* Rights of passage (Carta Porte 3.1)
* @param {Object} params - Search parameters
* @returns {Promise}
*/
searchRightsOfPassage(e) {
return this.client.get("/catalogs/cartaporte/3.1/rights-of-passage", {
params: e
});
}
/**
* Customs documents (Carta Porte 3.1)
* @param {Object} params - Search parameters
* @returns {Promise}
*/
searchCustomsDocuments(e) {
return this.client.get("/catalogs/cartaporte/3.1/customs-documents", {
params: e
});
}
/**
* Packaging types (Carta Porte 3.1)
* @param {Object} params - Search parameters
* @returns {Promise}
*/
searchPackagingTypes(e) {
return this.client.get("/catalogs/cartaporte/3.1/packaging-types", {
params: e
});
}
/**
* Trailer types (Carta Porte 3.1)
* @param {Object} params - Search parameters
* @returns {Promise}
*/
searchTrailerTypes(e) {
return this.client.get("/catalogs/cartaporte/3.1/trailer-types", {
params: e
});
}
/**
* Hazardous materials (Carta Porte 3.1)
* @param {Object} params - Search parameters
* @returns {Promise}
*/
searchHazardousMaterials(e) {
return this.client.get("/catalogs/cartaporte/3.1/hazardous-materials", {
params: e
});
}
/**
* Naval authorizations (Carta Porte 3.1)
* @param {Object} params - Search parameters
* @returns {Promise}
*/
searchNavalAuthorizations(e) {
return this.client.get("/catalogs/cartaporte/3.1/naval-authorizations", {
params: e
});
}
/**
* Port stations (air/sea/land) (Carta Porte 3.1)
* @param {Object} params - Search parameters
* @returns {Promise}
*/
searchPortStations(e) {
return this.client.get("/catalogs/cartaporte/3.1/port-stations", {
params: e
});
}
/**
* Marine containers (Carta Porte 3.1)
* @param {Object} params - Search parameters
* @returns {Promise}
*/
searchMarineContainers(e) {
return this.client.get("/catalogs/cartaporte/3.1/marine-containers", {
params: e
});
}
}
var Ge = /* @__PURE__ */ ((t) => (t.RECEIPT_SELF_INVOICE_COMPLETE = "receipt.self_invoice_complete", t.INVOICE_CANCELLATION_STATUS_UPDATED = "invoice.cancellation_status_updated", t.RECEIPT_STATUS_UPDATED = "receipt.status_updated", t.GLOBAL_INVOICE = "invoice.global_invoice_created", t.INVOICES_STATUS_UPDATED = "invoice.status_updated", t.INVOICES_CREATED_FROM_DASHBOARD = "invoice.created_from_dashboard", t.CUSTOMER_EDIT_LINK_COMPLETED = "customer.edit_link_completed", t))(Ge || {}), Ve = /* @__PURE__ */ ((t) => (t.RECEIPT = "receipt", t.INVOICE = "invoice", t.CUSTOMER = "customer", t))(Ve || {}), je = /* @__PURE__ */ ((t) => (t.ENABLED = "enabled", t.DISABLED = "disabled", t))(je || {});
const k = ["v1", "v2"];
class ze {
/**
* Get or set the base URL used for API requests.
* Allows overriding the default API host, e.g. for testing.
* Usage: facturapi.BASE_URL = 'http://localhost:3000/v2'
*/
get BASE_URL() {
return this._wrapper.baseURL;
}
set BASE_URL(e) {
this._wrapper.baseURL = e;
}
static get TaxType() {
return x;
}
static get TaxFactor() {
return J;
}
static get IepsMode() {
return X;
}
static get PaymentForm() {
return q;
}
static get PaymentMethod() {
return K;
}
static get InvoiceType() {
return Y;
}
static get InvoiceUse() {
return Q;
}
static get InvoiceRelation() {
return $;
}
static get TaxSystem() {
return W;
}
static get InvoiceStatus() {
return Z;
}
static get CancellationMotive() {
return ee;
}
constructor(e, 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;
this._wrapper = Ue(e, this.apiVersion), this.customers = new le(this._wrapper), th