facturapi
Version:
Librería oficial de Facturapi. Crea CFDIs timbrados y enviados al SAT, XML y PDF
1,191 lines (1,190 loc) • 43.7 kB
JavaScript
class se {
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, o = null) {
return this.client.put("/customers/" + t, { body: n, params: o });
}
/**
* 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 oe {
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 ae {
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");
}
}
const le = "https://www.facturapi.io/v2", ce = "https://www.facturapi.io/v1", j = "v2";
var V;
const I = typeof process < "u" && !!((V = process == null ? void 0 : process.versions) != null && V.node), ue = typeof navigator < "u" && (navigator == null ? void 0 : navigator.product) === "ReactNative";
var U = typeof globalThis < "u" ? globalThis : typeof window < "u" ? window : typeof global < "u" ? global : typeof self < "u" ? self : {};
function de(e) {
return e && e.__esModule && Object.prototype.hasOwnProperty.call(e, "default") ? e.default : e;
}
var P = { exports: {} };
(function(e, t) {
var n = typeof globalThis < "u" && globalThis || typeof self < "u" && self || typeof U < "u" && U, o = function() {
function c() {
this.fetch = !1, this.DOMException = n.DOMException;
}
return c.prototype = n, new c();
}();
(function(c) {
(function(l) {
var h = typeof c < "u" && c || typeof self < "u" && self || typeof h < "u" && h, E = {
searchParams: "URLSearchParams" in h,
iterable: "Symbol" in h && "iterator" in Symbol,
blob: "FileReader" in h && "Blob" in h && function() {
try {
return new Blob(), !0;
} catch {
return !1;
}
}(),
formData: "FormData" in h,
arrayBuffer: "ArrayBuffer" in h
};
function b(r) {
return r && DataView.prototype.isPrototypeOf(r);
}
if (E.arrayBuffer)
var T = [
"[object Int8Array]",
"[object Uint8Array]",
"[object Uint8ClampedArray]",
"[object Int16Array]",
"[object Uint16Array]",
"[object Int32Array]",
"[object Uint32Array]",
"[object Float32Array]",
"[object Float64Array]"
], g = ArrayBuffer.isView || function(r) {
return r && T.indexOf(Object.prototype.toString.call(r)) > -1;
};
function S(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 N(r) {
return typeof r != "string" && (r = String(r)), r;
}
function y(r) {
var i = {
next: function() {
var s = r.shift();
return { done: s === void 0, value: s };
}
};
return E.iterable && (i[Symbol.iterator] = function() {
return i;
}), i;
}
function f(r) {
this.map = {}, r instanceof f ? r.forEach(function(i, s) {
this.append(s, i);
}, this) : Array.isArray(r) ? r.forEach(function(i) {
this.append(i[0], i[1]);
}, this) : r && Object.getOwnPropertyNames(r).forEach(function(i) {
this.append(i, r[i]);
}, this);
}
f.prototype.append = function(r, i) {
r = S(r), i = N(i);
var s = this.map[r];
this.map[r] = s ? s + ", " + i : i;
}, f.prototype.delete = function(r) {
delete this.map[S(r)];
}, f.prototype.get = function(r) {
return r = S(r), this.has(r) ? this.map[r] : null;
}, f.prototype.has = function(r) {
return this.map.hasOwnProperty(S(r));
}, f.prototype.set = function(r, i) {
this.map[S(r)] = N(i);
}, f.prototype.forEach = function(r, i) {
for (var s in this.map)
this.map.hasOwnProperty(s) && r.call(i, this.map[s], s, this);
}, f.prototype.keys = function() {
var r = [];
return this.forEach(function(i, s) {
r.push(s);
}), y(r);
}, f.prototype.values = function() {
var r = [];
return this.forEach(function(i) {
r.push(i);
}), y(r);
}, f.prototype.entries = function() {
var r = [];
return this.forEach(function(i, s) {
r.push([s, i]);
}), y(r);
}, E.iterable && (f.prototype[Symbol.iterator] = f.prototype.entries);
function w(r) {
if (r.bodyUsed)
return Promise.reject(new TypeError("Already read"));
r.bodyUsed = !0;
}
function m(r) {
return new Promise(function(i, s) {
r.onload = function() {
i(r.result);
}, r.onerror = function() {
s(r.error);
};
});
}
function Y(r) {
var i = new FileReader(), s = m(i);
return i.readAsArrayBuffer(r), s;
}
function W(r) {
var i = new FileReader(), s = m(i);
return i.readAsText(r), s;
}
function $(r) {
for (var i = new Uint8Array(r), s = new Array(i.length), u = 0; u < i.length; u++)
s[u] = String.fromCharCode(i[u]);
return s.join("");
}
function B(r) {
if (r.slice)
return r.slice(0);
var i = new Uint8Array(r.byteLength);
return i.set(new Uint8Array(r)), i.buffer;
}
function M() {
return this.bodyUsed = !1, this._initBody = function(r) {
this.bodyUsed = this.bodyUsed, this._bodyInit = r, r ? typeof r == "string" ? this._bodyText = r : E.blob && Blob.prototype.isPrototypeOf(r) ? this._bodyBlob = r : E.formData && FormData.prototype.isPrototypeOf(r) ? this._bodyFormData = r : E.searchParams && URLSearchParams.prototype.isPrototypeOf(r) ? this._bodyText = r.toString() : E.arrayBuffer && E.blob && b(r) ? (this._bodyArrayBuffer = B(r.buffer), this._bodyInit = new Blob([this._bodyArrayBuffer])) : E.arrayBuffer && (ArrayBuffer.prototype.isPrototypeOf(r) || g(r)) ? this._bodyArrayBuffer = B(r) : this._bodyText = r = Object.prototype.toString.call(r) : 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) : E.searchParams && URLSearchParams.prototype.isPrototypeOf(r) && this.headers.set("content-type", "application/x-www-form-urlencoded;charset=UTF-8"));
}, E.blob && (this.blob = function() {
var r = w(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 = w(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
return this.blob().then(Y);
}), this.text = function() {
var r = w(this);
if (r)
return r;
if (this._bodyBlob)
return W(this._bodyBlob);
if (this._bodyArrayBuffer)
return Promise.resolve($(this._bodyArrayBuffer));
if (this._bodyFormData)
throw new Error("could not read FormData body as text");
return Promise.resolve(this._bodyText);
}, E.formData && (this.formData = function() {
return this.text().then(te);
}), this.json = function() {
return this.text().then(JSON.parse);
}, this;
}
var Z = ["DELETE", "GET", "HEAD", "OPTIONS", "POST", "PUT"];
function ee(r) {
var i = r.toUpperCase();
return Z.indexOf(i) > -1 ? i : r;
}
function A(r, i) {
if (!(this instanceof A))
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 A) {
if (r.bodyUsed)
throw new TypeError("Already read");
this.url = r.url, this.credentials = r.credentials, i.headers || (this.headers = new f(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 f(i.headers)), this.method = ee(i.method || this.method || "GET"), this.mode = i.mode || this.mode || null, this.signal = i.signal || this.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 u = /([?&])_=[^&]*/;
if (u.test(this.url))
this.url = this.url.replace(u, "$1_=" + (/* @__PURE__ */ new Date()).getTime());
else {
var d = /\?/;
this.url += (d.test(this.url) ? "&" : "?") + "_=" + (/* @__PURE__ */ new Date()).getTime();
}
}
}
A.prototype.clone = function() {
return new A(this, { body: this._bodyInit });
};
function te(r) {
var i = new FormData();
return r.trim().split("&").forEach(function(s) {
if (s) {
var u = s.split("="), d = u.shift().replace(/\+/g, " "), a = u.join("=").replace(/\+/g, " ");
i.append(decodeURIComponent(d), decodeURIComponent(a));
}
}), i;
}
function re(r) {
var i = new f(), s = r.replace(/\r?\n[\t ]+/g, " ");
return s.split("\r").map(function(u) {
return u.indexOf(`
`) === 0 ? u.substr(1, u.length) : u;
}).forEach(function(u) {
var d = u.split(":"), a = d.shift().trim();
if (a) {
var R = d.join(":").trim();
i.append(a, R);
}
}), i;
}
M.call(A.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.');
i || (i = {}), this.type = "default", this.status = i.status === void 0 ? 200 : i.status, this.ok = this.status >= 200 && this.status < 300, this.statusText = i.statusText === void 0 ? "" : "" + i.statusText, this.headers = new f(i.headers), this.url = i.url || "", this._initBody(r);
}
M.call(O.prototype), O.prototype.clone = function() {
return new O(this._bodyInit, {
status: this.status,
statusText: this.statusText,
headers: new f(this.headers),
url: this.url
});
}, O.error = function() {
var r = new O(null, { status: 0, statusText: "" });
return r.type = "error", r;
};
var ie = [301, 302, 303, 307, 308];
O.redirect = function(r, i) {
if (ie.indexOf(i) === -1)
throw new RangeError("Invalid status code");
return new O(null, { status: i, headers: { location: r } });
}, l.DOMException = h.DOMException;
try {
new l.DOMException();
} catch {
l.DOMException = function(i, s) {
this.message = i, this.name = s;
var u = Error(i);
this.stack = u.stack;
}, l.DOMException.prototype = Object.create(Error.prototype), l.DOMException.prototype.constructor = l.DOMException;
}
function v(r, i) {
return new Promise(function(s, u) {
var d = new A(r, i);
if (d.signal && d.signal.aborted)
return u(new l.DOMException("Aborted", "AbortError"));
var a = new XMLHttpRequest();
function R() {
a.abort();
}
a.onload = function() {
var p = {
status: a.status,
statusText: a.statusText,
headers: re(a.getAllResponseHeaders() || "")
};
p.url = "responseURL" in a ? a.responseURL : p.headers.get("X-Request-URL");
var D = "response" in a ? a.response : a.responseText;
setTimeout(function() {
s(new O(D, p));
}, 0);
}, a.onerror = function() {
setTimeout(function() {
u(new TypeError("Network request failed"));
}, 0);
}, a.ontimeout = function() {
setTimeout(function() {
u(new TypeError("Network request failed"));
}, 0);
}, a.onabort = function() {
setTimeout(function() {
u(new l.DOMException("Aborted", "AbortError"));
}, 0);
};
function ne(p) {
try {
return p === "" && h.location.href ? h.location.href : p;
} catch {
return p;
}
}
a.open(d.method, ne(d.url), !0), d.credentials === "include" ? a.withCredentials = !0 : d.credentials === "omit" && (a.withCredentials = !1), "responseType" in a && (E.blob ? a.responseType = "blob" : E.arrayBuffer && d.headers.get("Content-Type") && d.headers.get("Content-Type").indexOf("application/octet-stream") !== -1 && (a.responseType = "arraybuffer")), i && typeof i.headers == "object" && !(i.headers instanceof f) ? Object.getOwnPropertyNames(i.headers).forEach(function(p) {
a.setRequestHeader(p, N(i.headers[p]));
}) : d.headers.forEach(function(p, D) {
a.setRequestHeader(D, p);
}), d.signal && (d.signal.addEventListener("abort", R), a.onreadystatechange = function() {
a.readyState === 4 && d.signal.removeEventListener("abort", R);
}), a.send(typeof d._bodyInit > "u" ? null : d._bodyInit);
});
}
return v.polyfill = !0, h.fetch || (h.fetch = v, h.Headers = f, h.Request = A, h.Response = O), l.Headers = f, l.Request = A, l.Response = O, l.fetch = v, l;
})({});
})(o), o.fetch.ponyfill = !0, delete o.fetch.polyfill;
var _ = n.fetch ? n : o;
t = _.fetch, t.default = _.fetch, t.fetch = _.fetch, t.Headers = _.Headers, t.Request = _.Request, t.Response = _.Response, e.exports = t;
})(P, P.exports);
var fe = P.exports;
const he = /* @__PURE__ */ de(fe);
let C, L;
I ? (C = (e) => Buffer.from(e).toString("base64"), L = require("form-data")) : ue ? C = (e) => globalThis.Buffer.from(e).toString("base64") : C = globalThis.btoa;
const Ee = async (e) => {
var n;
if (!e.ok) {
const o = await e.json();
throw new Error(o.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 (I) {
const o = (n = e.body) == null ? void 0 : n.getReader();
if (!o)
return e.body;
try {
const { Readable: _ } = await import("stream");
return new _({
read() {
o.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 _e(e) {
return C(e);
}
const pe = (e, t = j) => {
const n = t === "v1" ? ce : le, o = {
Authorization: `Basic ${_e(e + ":")}`,
"Content-Type": "application/json"
};
return {
async request(c, l) {
const { params: h, body: E, formData: b, ...T } = l || {}, g = h ? "?" + new URLSearchParams(h).toString() : "", S = b && I ? {
...o,
...b.getHeaders()
} : o, N = {
...T,
headers: S,
body: b || (E ? JSON.stringify(E) : void 0)
}, y = await he(n + c + g, N);
return Ee(y);
},
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 });
}
};
};
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
*/
uploadLogo(t, n) {
const o = new (I ? L : FormData)();
return I ? o.append("file", n, {
filename: "file",
contentType: "application/octet-stream"
}) : o.append("file", n, "file"), this.client.put("/organizations/" + t + "/logo", { formData: o });
}
/**
* 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
*/
uploadCertificate(t, n, o, _) {
const c = new (I ? L : FormData)();
return I ? c.append("cer", n, {
filename: "cer.cer",
contentType: "application/octet-stream"
}) : c.append("cer", n, "cer.cer"), I ? c.append("key", o, {
filename: "key.key",
contentType: "application/octet-stream"
}) : c.append("key", o, "key.key"), c.append("password", _), 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, o) {
return this.client.put(
`/organizations/${t}/series-group/${n}`,
{
body: o
}
);
}
/**
* 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 Ie {
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 Se {
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) {
return this.client.post("/webhooks/validate-signature", { body: t });
}
}
class Ne {
/**
* @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 F = /* @__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))(F || {});
const me = [
{ 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 k = /* @__PURE__ */ ((e) => (e.IVA = "IVA", e.IEPS = "IEPS", e.ISR = "ISR", e))(k || {}), z = /* @__PURE__ */ ((e) => (e.RATE = "Tasa", e.QUOTA = "Cuota", e))(z || {}), q = /* @__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))(q || {}), H = /* @__PURE__ */ ((e) => (e.PAGO_EN_UNA_EXHIBICION = "PUE", e.PAGO_EN_PARCIALIDADES_DIFERIDO = "PPD", e))(H || {}), x = /* @__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))(x || {}), X = /* @__PURE__ */ ((e) => (e.INGRESO = "I", e.EGRESO = "E", e.TRASLADO = "T", e.NOMINA = "N", e.PAGO = "P", e))(X || {}), K = /* @__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))(K || {}), Q = /* @__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))(Q || {}), J = /* @__PURE__ */ ((e) => (e.DRAFT = "draft", e.PENDING = "pending", e.VALID = "valid", e.CANCELED = "canceled", e.FAILED = "failed", e))(J || {}), ye = /* @__PURE__ */ ((e) => (e.DAY = "day", e.WEEK = "week", e.FORTNIGHT = "fortnight", e.MONTH = "month", e.TWO_MONTHS = "two_months", e))(ye || {}), Re = /* @__PURE__ */ ((e) => (e.OPEN = "open", e.CANCELED = "canceled", e.INVOICED_TO_CUSTOMER = "invoiced_to_customer", e.INVOICED_GLOBALLY = "invoiced_globally", e))(Re || {}), De = /* @__PURE__ */ ((e) => (e.ISSUING = "issuing", e.RECEIVING = "receiving", e))(De || {}), Ce = /* @__PURE__ */ ((e) => (e.NONE = "none", e.ACCEPTED = "accepted", e.PENDING = "pending", e.REJECTED = "rejected", e.EXPIRED = "expired", e))(Ce || {}), Te = /* @__PURE__ */ ((e) => (e.DAY = "day", e.WEEK = "week", e.FORTNIGHT = "fortnight", e.MONTH = "month", e.TWO_MONTHS = "two_months", e))(Te || {}), ge = /* @__PURE__ */ ((e) => (e.CUSTOM = "custom", e.PAGO = "pago", e.NOMINA = "nomina", e))(ge || {}), we = /* @__PURE__ */ ((e) => (e.ERRORES_CON_RELACION = "01", e.ERRORES_SIN_RELACION = "02", e.NO_SE_CONCRETO = "03", e.FACTURA_GLOBAL = "04", e))(we || {}), ve = /* @__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))(ve || {}), Pe = /* @__PURE__ */ ((e) => (e.RECEIPT = "receipt", e.INVOICE = "invoice", e.CUSTOMER = "customer", e))(Pe || {}), Le = /* @__PURE__ */ ((e) => (e.ENABLED = "enabled", e.DISABLED = "disabled", e))(Le || {});
const G = ["v1", "v2"];
class Be {
static get TaxType() {
return k;
}
static get TaxFactor() {
return z;
}
static get IepsMode() {
return q;
}
static get PaymentForm() {
return F;
}
static get PaymentMethod() {
return H;
}
static get InvoiceType() {
return X;
}
static get InvoiceUse() {
return x;
}
static get InvoiceRelation() {
return K;
}
static get TaxSystem() {
return Q;
}
static get InvoiceStatus() {
return J;
}
constructor(t, n = {}) {
if (n.apiVersion) {
if (!G.includes(n.apiVersion))
throw new Error(
"Invalid API version. Valid values are: " + G.join(", ")
);
this.apiVersion = n.apiVersion;
} else
this.apiVersion = j;
const o = pe(t, this.apiVersion);
this.customers = new se(o), this.products = new oe(o), this.invoices = new ae(o), this.organizations = new Oe(o), this.catalogs = new Ae(o), this.receipts = new Ie(o), this.retentions = new Se(o), this.tools = new Ne(o), this.webhooks = new be(o);
}
}
export {
Pe as ApiEventDataType,
ve as ApiEventType,
we as CancellationMotive,
Ce as CancellationStatus,
ye as GlobalInvoicePeriodicity,
q as IepsMode,
ge as InvoiceComplementType,
K as InvoiceRelation,
J as InvoiceStatus,
X as InvoiceType,
x as InvoiceUse,
Te as InvoicingPeriod,
De as IssuingType,
F as PaymentForm,
me as PaymentFormList,
H as PaymentMethod,
Re as ReceiptStatus,
z as TaxFactor,
Q as TaxSystem,
k as TaxType,
Le as WebhookEndpointStatus,
Be as default
};