@facta-dte/api — TypeScript SDK
The official TypeScript and JavaScript client for Facta's electronic tax document API. The server remains the fiscal authority. The SDK submits DTE data, handles credentials and retries, resolves encrypted local catalog snapshots, and can archive exact issued bytes for restart-safe recovery.
Install the official client from npm · @facta-dte/api. Source, examples, releases and issues are maintained in GitHub · Facta-DTE/facta-api-sdk. This reference describes version 0.3.0; check the published npm version before using newer methods. The latest tag selects the approved stable release. See the Spanish SDK guide.
Runtime support and installation
The portable entry supports Node.js 22+, Deno, and Bun. @facta-dte/api/node adds Node-only encrypted file archives and config loading. The @facta-dte/api/file-archive entry is also Node-only. @facta-dte/api/server mounts the signing window on your server (createFactaHandler, createFactaSession) without handing a Facta credential to the browser, and @facta-dte/api/browser and @facta-dte/api/react (with react/styles.css) hold the window and the document components, which talk only to your server. This portal checks this page against the source of the published package (npm ships src/client.ts and src/errors.ts), not against a copy: the version shown on the status page is the one that was checked.
import { Facta, type DteRequest } from "@facta-dte/api";
const facta = new Facta({
apiKey: process.env.FACTA_API_KEY!,
signKey: process.env.FACTA_SIGN_KEY!,
});
const sale: DteRequest = {
tipoDte: "01",
items: [{ descripcion: "Sample item", cantidad: 1, precioUni: 10 }],
};
const result = await facta.issue(sale, { idempotencyKey: "order-1042" });Public SDK identifiers are English. Fiscal payload properties and values such as tipoDte, codigoGeneracion, sellado, and contingencia retain the API's Spanish wire contract.
For an FSE (14), aplicarReteRenta is optional: omission or false leaves withholding at zero, while true applies the current rate to the entire discounted subtotal. It does not select lines by tipoItem; goods used as inputs to a service remain in that subtotal. A goods-only purchase is not automatically subject because it has no VAT.
To withhold on some lines only (for example, a service and a genuinely independent goods purchase in the same document), the HTTP API has a per-line mode: incomeWithholding: { mode: "per_line" } with a boolean applyIncomeWithholding on every item, available when GET /v1/status advertises capabilities.fseIncomeWithholdingPerLine. This SDK version's types do not model those fields yet; they arrive with a later package release. See the Spanish issuance guide for the per-line mode, its limits and an amounts example.
Public methods
The Facta client provides status and diagnostics: status(), diagnose(), getContract(), and region() (the Functions region the client pins its requests to, or null). Synchronization and catalog methods: syncDestinations(), listCustomers(), getCustomer(), searchCustomers(), listProducts(), getProduct(), searchProducts(); catalog writes: createCustomer(), updateCustomer(), deactivateCustomer(), createProduct(), updateProduct(), deactivateProduct(); catalogue changes and webhooks (0.6.0): listCatalogChanges(), createWebhook(), listWebhooks(), getWebhook(), updateWebhook(), deleteWebhook(), rotateWebhookSecret(), testWebhook() and the receiver-side verifyWebhook() / constructWebhookEvent(); drafts (0.6.0, scope draft): createDraft(), listDrafts(), getDraft(), getDraftByKey(), updateDraft(), cancelDraft(), issueDraft(). syncCatalog() and catalogState() were removed in 0.6.0: the server resolves customerId / productId. DTE operations: issue(), prepare(), sign(), getDocumentStatus(), listDocuments(), invalidate(), registerReturn() (from 0.4.0: registers a return event over a sealed FE, FEX or FSE; lines counted from 1; a 202 firmado is retried with the same idempotencyKey), listHolding(), downloadDocument(). Durable archive operations: issueAndArchive(), recoverOperation(), listPendingOperations(), invalidateAndArchive(), recoverInvalidation(), listPendingInvalidations(), replicateArchive(), diagnoseDestinations(). Delivery by e-mail and WhatsApp: deliverEmail(), deliverWhatsApp(), getDelivery(), waitForDelivery(). Managed storage: getStorageStatus(), getDocumentCopies(), retryDocumentStorage(). Local printing: print().
The English method reference documents each method's arguments, return values, required scope, side effects, errors, and retry/recovery behavior. The Spanish method reference retains the existing Spanish documentation. The API contract is authoritative for HTTP fields and responses.
Options beyond the credentials: config (versioned, secret-free defaults), runtime (default archive, invalidation archive, remoteDestinations, replicate, print transport) and, from 0.4.0, clock and clockFetch (the reference clock: true by default, a URL, or false for the device clock; it never fails an operation).
Safe issuance and recovery
Every operation that can reserve a fiscal control number needs a stable idempotencyKey. Reuse the same key with the same request after a timeout; a changed request with that key is rejected. An AbortSignal stops local waiting and retries but cannot prove the server cancelled an accepted request.
For process-restart recovery, use issueAndArchive with a durable archive, operationId, and idempotencyKey. It journals the request and key before sending. recoverOperation resumes the same operation without rotating its idempotency key. Remote storage copies and printing are explicit adapter operations; a returned print status means a job was submitted, not that a physical page was printed.
Readable catalog
When the owner enables «Catálogo legible por la API» for a key, the server resolves receptor.customerId and items[].productId from the catalog the app published: no unlockKey, no local sync, and a catalog change never leaves the SDK with a stale copy. status() advertises it in llave.catalogMode ("readable"; "encrypted" or absent on older servers; a company that keeps its catalog unencrypted also reports "readable"), and catalogoLegible carries the published and current revisions. Before issuing a request with references the SDK reads that mode (cached for a minute); if the read fails it resolves locally with unlockKey, so the check can never be why an issue fails. Fields you write in the request win over the catalog's, and an unknown id is refused before a control number is reserved:
not_found,details.reason: "catalog_unknown_id";details.catalogStale: truemeans the published catalog is behind (open Facta so it syncs, then retry).invalid_request,details.reason: "catalog_not_published": the readable catalog was never published.invalid_request,details.reason: "catalog_record_encrypted": the record exists but the company is still converting its catalog.
Since 0.6.0 there is no local catalogue snapshot and no syncCatalog(): in every catalogue mode (including a company that shares its data key) the server resolves the ids and the reads always call the API. The old sealed catalogue inbox answers 410 inbox_retired; the per-key snapshot is only marked deprecated (Deprecation/Sunset headers) and the SDK ignores it.
Catalog writes, deactivation and reactivation
A key with the catalog:write scope can write the catalogue when the company shares its data key with it (the owner grants the key access in Account → API) or, for a company that keeps its catalogue in plain text, when the owner enabled «Permitir administrar clientes y productos desde el API». Records read one at a time carry revision; pass it as ifMatch to updateCustomer / updateProduct and a stale write is catalog_revision_conflict (409, details.revisionActual). A read-only key hears forbidden_scope before catalog_encrypted, whose details.hint says whether the key lacks access to the shared data or the catalogue is not shared. There is no hard delete: deactivateCustomer(id) sends DELETE and keeps the record with activo: false, out of lists (listCustomers({ includeInactive: true }) shows it). Reactivate through the API with updateCustomer(id, { activo: true }) (HTTP: PATCH /v1/customers/{id} with {"activo": true}); the web app does not list deactivated customers. Creating a customer with the document of a deactivated one returns 409 catalog_duplicate with details.id and details.activo: false. Products work the same way.
Copies in your own destinations (BYOS)
With an unlockKey and no explicit remoteDestinations, issueAndArchive() and recoverOperation() open the key's destinations snapshot and replicate the archived JSON and PDF to every destination that can be written without a person present: S3-compatible buckets (S3, R2, B2, Wasabi, Spaces, MinIO) and Supabase Storage. Paths are the ones the app reads, DTE/pruebas/YYYY/MM/<numeroControl>.json|pdf in test and DTE/YYYY/MM/… in production, built from the archived legal JSON. Other kinds (OneDrive, FTP/SFTP) are skipped with a warning. Google Drive is not an API destination (security decision, 17-Oct-2026): it is never published into a key's destinations snapshot and POST /v1/destinations/{id}/drive-token answers 403 drive_not_available_for_api. replicate: false, per call or in runtime, turns it off.
Nothing here throws: the document is already sealed. Problems arrive as result.warnings, and an unconfirmed copy stays pending for recoverOperation().
warnings[].code | Meaning |
|---|---|
byos_not_replicated | The destinations snapshot could not be opened, a destination was skipped, or a copy was not confirmed. destinationId names the destination; detail is credential-free. |
copy_report_failed | The copy is stored at your destination but Facta was not told. |
Once the JSON is stored, the SDK reports it with POST /v1/storage/copies/{codigoGeneracion}/byos (scope issue), only when the server advertises capabilities.byosCopyReport (1 or higher) on GET /v1/storage/status. The outcome is remoteCopies[].report ("reported" or "failed"; failed keeps the operation pending and recoverOperation() repeats the report). A report never marks a copy verified: Facta cannot read your bucket with your credentials, so it records the copy as reported by the SDK (verified: false, writtenBy: "sdk") after checking against the database that the destination belongs to the key and that the paths are the canonical ones.
Delivery by e-mail and WhatsApp
Issuing never waits for delivery; they are separate requests. issue(request, { deliver }) only marks channels (deliver.email: true | address, deliver.whatsapp: { number, consent: true }). A sealed result then carries entrega with a token valid for five minutes (a bearer secret: keep it on your server) and the initial channel states. deliverEmail(code, token) and deliverWhatsApp(code, token) start each channel: 200 with the final state or 202 with en_proceso, and a second call returns the current state without a second message. getDelivery(code) reads every channel and works after the token expired; waitForDelivery(code, { channels?, timeoutMs?, intervalMs? }) polls until each awaited channel is final (anything but pendiente/en_proceso; esperando_sello is not awaited) and returns the last read with settled: false on timeout instead of throwing.
A channel that cannot be delivered is a state with a motivo (fallido, sin_credito, sin_consentimiento, no_permitido, vencido), never an exception, and it never changes the fiscal result. A contingency document gets no token (esperando_sello). An expired token throws entrega_vencida (410); a wrong one, entrega_token_invalido; the SDK strips the token from error messages and details. WhatsApp is billed to the company's prepaid wallet (sin_credito without balance) and sends the approved template plus the document only.
Scope and consent. Delivery is part of issuing: any key with the issue scope can mark and deliver both channels, with no re-minting. A key minted with only entrega:correo or entrega:whatsapp keeps that channel; a key with neither issue nor the channel scope still issues and the channel is no_permitido. On the wire, entrega.whatsapp.consentimiento defaults to true when omitted (asking for WhatsApp is the attestation); only an explicit false leaves sin_consentimiento. The SDK's deliver.whatsapp helper is stricter on purpose and still requires consent: true to be written out.
Return events and the reference clock (0.4.0)
registerReturn(generationCode, { items, fechaEvento? }) registers a return event over a sealed FE, FEX or FSE that this API issued. Lines are counted from 1 and each item carries exactly one of cantidad or noGravado. It sends the signing key, spends no control number, is irreversible once sealed, and several returns may be registered until they add up to what was sold; disponible (ReturnAvailability[]) says what is left. A 202 with estado: "firmado" means Hacienda did not answer: repeat with the SAME idempotencyKey and request to resend the same signed event. Refusals are return_exceeds_available (with details.lineas), return_window_closed and return_type_not_allowed; invalidate on a returned document is has_return_events (409). See Registrar un evento de retorno.
The Facta client keeps one NTP-style reference clock (facta.clock, calibrated lazily against https://clock.factadte.com/) for the timestamps in archive records and the SigV4 date of S3 uploads, and recalibrates once when S3 answers RequestTimeTooSkewed. A document's own date and time are always set by the Facta server. Share the clock with an S3 destination with createS3ArtifactDestination({ ..., clock: facta.clock ?? false }). See the reference clock.
Drafts (0.6.0)
createDraft(request, options?) leaves an invoice for a person of the company to review and issue in the app, with the same request as issue() plus an optional id and reference (up to 64 characters). Nothing is signed and no control number is spent. listDrafts() filters by state and reference, getDraft(id) and getDraftByKey(idempotencyKey) read one (an issued draft carries its document), updateDraft(id, version, request) saves a new version (version is sent as If-Match; version_mismatch when stale), cancelDraft(id) cancels a pending one, and issueDraft(id, version, request) issues it through the same road as issue() (scope issue and the signing key; draft_issuing / draft_claimed spent nothing). drafts_not_ready (409) means the owner has not opened Facta with their vault since the company began sharing its data key. See the drafts guide.
Production keys and companies still in test
A production key (facta_live_) is refused with environment_not_allowed (403) on emission and on the company-level routes (customers, products, webhooks, the change feed, drafts, destinations and templates) while the company is still in the test environment; a test key is always allowed, and document reads are filtered to the key's environment.
Error handling
| FactaErrorCode |
|---|
unauthorized |
invalid_api_key |
key_revoked |
key_expired |
key_inactive |
forbidden_scope |
dte_type_not_allowed |
ip_not_allowed |
environment_not_allowed |
sign_key_required |
sign_key_invalid |
sign_vault_locked |
sign_vault_missing |
invalid_request |
validation_failed |
not_found |
method_not_allowed |
idempotency_key_required |
idempotency_key_reuse |
idempotency_in_flight |
prepare_token_invalid |
rate_limited |
amount_limit |
mh_rejected |
mh_unreachable |
correlative_unavailable |
service_unavailable |
no_storage_destination |
storage_unsupported |
storage_unavailable |
storage_contract_invalid |
entrega_vencida |
entrega_token_invalido |
canal_no_marcado |
internal_error |
operation_outcome_unknown |
archive_integrity_error |
network_error |
Classify FactaError by its stable code, status, details, isRejection, and spent fields. Do not infer fiscal success from a localized message. A contingencia result is accepted for reconciliation and is not a FactaError. Local validation and adapter failures may throw standard or adapter-specific errors.
TypeScript types
Public request and result types use English names, including DteRequest, DteType, Recipient, Address, LineItem, IssueResult, PreparedDte, DocumentStatus, and InvalidationRequest. Their JSON properties intentionally retain the external Facta API field names. The method reference and package declarations list the complete public surface. The remission note (04) and the retention receipt (07) are typed in the next SDK release; until then send them over direct HTTP (see the guide, in Spanish).
Inline archive options
issueAndArchive preserves the exact signed JSON/PDF returned by issuance and does not download them again. Older responses fall back only for missing artifacts. includeTicket:false archives JSON/PDF/JWS without requesting a ticket; do not combine it with an explicit ticketPaperWidthMm. The default remains includeTicket:true. Recovery preserves the original choice.
Managed storage
Confirm the deployed server contract with getStorageStatus() before relying on these methods. The API server writes exact managed JSON/PDF copies; the SDK never receives bucket credentials or a web user session.
| Method | Contract and effect |
|---|---|
getStorageStatus(options?) | ManagedStorageStatus; download scope. capabilityVersion:1, managed coverage/capacity/readiness and verified BYOS readiness. No fiscal work. accessUntil describes read access, not proven backups. |
getDocumentCopies(options?) | ManagedDocumentCopy[]; download scope. Optional generationCode and signal; issuer/environment-scoped JSON/PDF receipts, including pending/failed copies. No document content or storage paths. |
retryDocumentStorage(generationCode, options?) | ManagedStorageReceipt; download scope. Repairs copies of an existing sealed UUID without signing, reissuing or spending a control number. Missing original bytes remain an explicit failure. |
const capability = await facta.getStorageStatus();
const copies = await facta.getDocumentCopies({ generationCode });
if (copies.some(copy => copy.state === "pending" || copy.state === "failed")) {
const receipt = await facta.retryDocumentStorage(generationCode);
// Inspect JSON/PDF states; never create a new fiscal identity to repair files.
}diagnose() uses positive managed readiness to satisfy durable destination checks without a BYOS vault; signing and catalog reference checks remain independent. Malformed present capability blocks issuance. Missing older routes are explicitly unknown. storage_unsupported identifies missing older routes; storage_contract_invalid identifies invalid capabilities/receipts; storage_unavailable identifies unavailable storage service.
Fiscal success and copy success are independent. An invalid attached receipt is omitted and produces storageErrorCode: "storage_contract_invalid" while preserving the sealed result. The encrypted file journal keeps this pending; recovery checks repaired receipt hashes/bytes against exact local files. A stored receipt proves a durable copy, not temporary holding.
The SDK workflow examples in source file examples/workflows.ts are invoked explicitly. issueWithCopies combines managed receipts with a local encrypted archive and optional BYOS outcomes. recoverAfterRestart reuses the saved operation. These require the corresponding source version. Managed storage covers JSON/PDF and, from 0.6.0, the invalidation event (invalidation); ticket regeneration stays outside it. Example and fixture checks do not claim live validation of every fiscal DTE variant.
To verify a managed copy while temporary holding still exists, use downloadDocument(generationCode, "pdf", { source: "managed" }) (also accepts json). It requires storageSource === "managed" without holding fallback. Tickets reject this option before HTTP; "invalidation" (0.6.0) always reads the managed copy. Missing source proof on an older server returns storage_unsupported; a contradictory source returns storage_contract_invalid. Default download selection is unchanged.