New:Microsoft Teams Notifications Are Now Available in Socket.Learn more →
Get Started

@factuarea/sdk

Package Overview
Dependencies
Maintainers
1
Versions
9
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

@factuarea/sdk

Official TypeScript SDK for the Factuarea API — Spanish e-invoicing & VeriFactu.

latest
Source
npmnpm
Version
0.8.0
Version published
Weekly downloads
190
120.93%
Maintainers
1
Weekly downloads
 
Created
Source

Factuarea Node.js / TypeScript SDK

npm License: MIT Spec Sync

The official TypeScript SDK for the Factuarea API — Spanish e‑invoicing, VeriFactu, quotes, delivery notes and more.

It wraps the v1 REST API, including canonical contacts, with automatic retries, automatic idempotency keys, transparent cursor auto‑pagination, a typed error hierarchy, typed webhook verification and binary (PDF) downloads. Ships as dual ESM + CommonJS with full type declarations.

Status: 0.x (pre‑GA). The public surface is stable and SemVer‑protected, but minor breaking changes may occur before 1.0.0 (which tracks the API's GA event).

Installation

npm install @factuarea/sdk

Requires Node 20 or newer. The SDK is runtime‑agnostic (built on the Web fetch standard) and also runs on Deno, Bun and Cloudflare Workers.

Quickstart

import { Factuarea, type BusinessContact } from "@factuarea/sdk";

const factuarea = new Factuarea({ apiKey: process.env.FACTUAREA_API_KEY! });
const { data: contact } = (await factuarea.contacts.create({
  name: "Cliente Demo SL",
  kind: "company",
  tax_id: "B12345674",
  roles: ["customer"],
})) as { data: BusinessContact };

// Create an invoice. Single-resource calls (create/show/update) return the API
// envelope `{ data, ... }`; read `.data` to get the resource. Operation
// results are typed `unknown` in 0.x, so cast to the shape you expect.
const created = (await factuarea.invoices.create({
  // client_id is the invoice field; its value is the canonical contact UUID.
  client_id: contact.id,
  series_id: "01931b3e-7c4a-7f2e-9a8b-000000000001",
  issued_on: "2026-06-05",
  due_on: "2026-07-05",
  lines: [
    // Pass `tax_rate` (a percentage) or `tax_rate_id` (a tax UUID).
    { description: "Consulting", quantity: 1, unit_price: 1000, tax_rate: 21 },
  ],
})) as { data: { id: string } };
const invoice = created.data;

// List with transparent auto-pagination (list yields the resources directly).
for await (const inv of await factuarea.invoices.list({ status: "paid" })) {
  console.log((inv as { id: string }).id);
}

// Download a PDF
const pdf = await factuarea.invoices.pdf(invoice.id);
await require("node:fs/promises").writeFile("invoice.pdf", pdf.toBuffer());

Server‑side only. Your API key is a secret. Never ship it to a browser or a public client — use this SDK from your backend.

Authentication & environments

Pass your API key to the constructor. The key prefix selects the environment — there is no separate flag:

PrefixEnvironmentEffects
fact_test_…SandboxIsolated test company; no real VeriFactu/email/webhooks
fact_live_…ProductionReal data and side effects
const sandbox = new Factuarea({ apiKey: "fact_test_…" });
sandbox.environment; // "test"

const prod = new Factuarea({ apiKey: "fact_live_…" });
prod.environment;    // "live"

Configuration

new Factuarea({
  apiKey: "fact_live_…",        // required
  baseUrl: "https://api.factuarea.com/v1", // override for self-hosted/staging
  timeout: 60_000,              // per-request timeout in ms (default 60s)
  maxRetries: 2,                // retry attempts after the first try (default 2)
  factuareaVersion: "2026-06-04", // pinned API version header (default: this release's)
  defaultHeaders: {},           // extra headers on every request
});

The SDK pins the Factuarea-Version header to the API version this release was built against, so the API's behaviour stays stable until you upgrade the SDK.

Resources

Use factuarea.contacts for customer, supplier and lead identities. A contact can hold multiple roles, so creating a supplier relationship does not require duplicating an existing customer's identity. Sales documents still name their reference client_id, and purchases use supplier_id; both accept the canonical contact UUID with the corresponding active role.

Operations follow the SDK method-naming contract. Other resources include account, products, invoices, quotes, proformas, deliveryNotes, purchaseInvoices, purchaseScans, purchaseScanEmails, recurringInvoices, series, taxes, taxReports, verifactu, events, eventCatalog, webhookEndpoints, projects, tasks, taskLabels, taskTimers, users, notifications and agenda. Nested groups are available too, such as factuarea.products.gallery.upload(...).

Contacts

TaskMethod
Create, list, search, retrieve, updatecreate, list, search, show, update
Discover filter optionsoptions
Assign/remove a role, change its statusassignContactRole, removeContactRole, changeContactRoleStatus
Customer/supplier preferencesupdateCustomerProfile, updateSupplierProfile
Bank accountsupdateBankAccounts
Archive/restore the identitydelete, restore
Bulk archive/role statusbulkArchive, bulkChangeContactRoleStatus
Preview/import a CSVpreviewImport, import
// Reuse the same contact when it also becomes a supplier.
await factuarea.contacts.assignContactRole(contact.id, "supplier");
await factuarea.contacts.updateSupplierProfile(contact.id, { payment_terms_days: 30 });

// This only deactivates its customer role; its supplier role remains unchanged.
await factuarea.contacts.changeContactRoleStatus(contact.id, "customer", { status: "inactive" });

// delete archives the whole identity and preserves history. The API rejects
// archiving when blocking documents/contracts exist. Restore is reversible.
await factuarea.contacts.delete(contact.id);
await factuarea.contacts.restore(contact.id);

Filter list and search with roles, tags, search or is_archived. Arrays are serialized as roles[] / tags[] and kept across cursor pages. Use roles: ["customer"], roles: ["supplier"], roles: ["lead"] or roles: ["none"] for unassigned contacts. The public Contact migration guide covers request fields, scopes and historical IDs.

BusinessContact, the contact list/import response types and contact request types are exported from @factuarea/sdk. The resource wrappers return unknown in 0.x, so use the exported types for request validation and response casts.

Migrating from clients and suppliers

The legacy /v1/clients and /v1/suppliers routes were retired from the public API on 2026-09-16, so the clients and suppliers resources were removed from the SDK in 0.6.0. Every operation has a contacts equivalent: filter by roles: ["customer"] or roles: ["supplier"] where the legacy resource implied the role, and use contacts.stats, contacts.activities, contacts.bulkCreate, contacts.bulkDelete, contacts.import, contacts.verifyCensus, contacts.findByTaxId and contacts.findByExternalId for the role-specific helpers. Legacy client/supplier IDs are not contact UUIDs; resolve them through the Contact migration guide instead of assuming equality.

Purchase scans

purchaseScans supports create (multipart batch), list, show, stats, review, convert, duplicateResolution, retry, archive, restore and source (binary). purchaseScanEmails.list returns inbound messages and attachment outcomes. Read operations require purchase_invoices:read, mutations purchase_invoices:write, and archive purchase_invoices:delete; the company's scanner/OCR entitlement must also be active.

Uploads take one multipart part per file, every part named files[] (the API accepts PDF, JPEG or PNG originals), with limits of 20 files per batch, 20.0 MiB per file and 100.0 MiB per batch. create, retry, duplicateResolution, convert, archive and restore require Idempotency-Key; the SDK generates one automatically when you do not pass idempotencyKey yourself. review does not require it.

import { readFile, writeFile } from "node:fs/promises";
import type { PurchaseScanUploadBatch, PurchaseScan } from "@factuarea/sdk";

const form = new FormData();
form.append("files[]", new Blob([await readFile("invoice.pdf")], {
  type: "application/pdf",
}), "invoice.pdf");
const { data: batch } = await factuarea.purchaseScans.create(form, {
  idempotencyKey: "purchase-upload-batch-001",
}) as { data: PurchaseScanUploadBatch };
console.log(batch.accepted, batch.rejected);

// Processing is asynchronous. Read the current state before editing.
const id = batch.accepted[0].id;
const { data: scan } = await factuarea.purchaseScans.show(id) as { data: PurchaseScan };
console.log(scan.status, scan.available_actions, scan.extraction, scan.issues);
const original = await factuarea.purchaseScans.source(id);
await writeFile("original.pdf", original.toBuffer());

An upload accepts up to 20 PDF/JPEG/PNG originals (20 MiB each, 100 MiB total). A partial rejection still returns 202; if all files are rejected, ValidationError.data retains the batch result. Preserve the same idempotency key and file order when retrying that batch.

Use purchaseInvoices.expenseCategories() to discover company category IDs for the review field expense_category; category names are not accepted as identifiers.

Only edit when can_save_review is true. review(id, { expected_version, fields, lines }) accepts partial field patches ({ value: "..." }), explicit null to clear, and line operations update, add (without line_id) or remove. Omitted values remain unchanged. Use the new returned version for the next mutation; a stale version returns 409. On conversion failure, ValidationError.fields exposes the review fields that need correction.

convert(id, { expected_version }, { idempotencyKey }) creates a draft expense, including its original attachment; it does not issue an invoice or mark the expense paid. Follow purchase_invoice_id to the created expense. EUR and resolved fiscal data are required. retry also starts a received document when automatic scanning is disabled. Respect available_actions; duplicate override and supplier creation are reserved for an interactive administrator. The public duplicate resolutions are link_existing (with purchase_invoice_id) and archive.

Tasks and projects

projects and tasks cover the task workspace: projects with their board columns and custom fields, tasks with comments, relations, labels, attachments, time entries and links to documents or contacts, plus bulk changes. taskLabels manages the shared label catalog, taskTimers reads and stops the running timer, users lists the members you can assign, notifications reads the API key owner's notifications and agenda returns a combined calendar of due tasks, document due dates, tax deadlines and absences. Keys need the projects:*, tasks:*, users:read and notifications:* scopes. Writes send an Idempotency-Key like the rest of the SDK, and every list is a Page.

import type { Project, Task, TaskTimeEntry } from "@factuarea/sdk";

// Create a project and a task in it. `entity_link` links the task to an invoice,
// quote, contact… in the same call; `custom_fields` maps a field id to its value.
const { data: project } = (await factuarea.projects.create({ name: "Website", key: "WEB" })) as { data: Project };
const { data: task } = (await factuarea.tasks.create(
  {
    project_id: project.id,
    title: "Chase the unpaid invoice",
    priority: "high",
    due_on: "2026-10-15",
    entity_link: { type: "invoice", id: invoice.id },
  },
  { idempotencyKey: "chase-invoice-4711" },
)) as { data: Task };

// Log time on it: a closed period, or a live timer that you stop later.
await factuarea.tasks.timeEntries.create(task.id, {
  started_at: "2026-10-01T09:00:00+02:00",
  ended_at: "2026-10-01T10:30:00+02:00",
  description: "Called the customer",
  billable: true,
});
await factuarea.tasks.timer.start(task.id);
const { data: entry } = (await factuarea.taskTimers.stop()) as { data: TaskTimeEntry };
console.log(entry.duration_seconds);

tasks.search filters by q, project_id, status, column_id, priority, assignee_id (a member id or me), label_id, due_before, due_after, completed and sort, and follows the cursor across pages. taskTimers.current() resolves to { data: null } when no timer is running. Deleting a board column that still holds tasks needs a destination: projects.columns.delete(project.id, column.id, { move_to_column_id }), otherwise the API answers 409 column_has_tasks. agenda.list({ from, to, sources: "tasks,invoice_due" }) takes its layers as a comma-separated string.

Pagination

List methods return a Page, which is itself an async iterable. Iterate everything, or walk page by page:

const page = await factuarea.contacts.list({ roles: ["customer"], limit: 50 });

// (a) iterate all items across all pages
for await (const contact of page) {
  console.log((contact as BusinessContact).id);
}

// (b) page-by-page
page.data;       // items on this page
page.hasMore;    // boolean
page.nextCursor; // opaque cursor or null
const next = await page.getNextPage(); // Page | null

// (c) collect everything into an array
const all = await page.toArray();

The SDK manages cursors for you using the API's next_cursor / has_more.

Automatic retries

Transient failures — 429 (rate limit), 5xx and network errors — are retried automatically with exponential backoff and full jitter, honouring the Retry-After header. Deterministic client errors (e.g. 422 validation) are never retried and surface immediately. Tune with maxRetries (globally or per request).

Idempotency

Every POST automatically gets an Idempotency-Key (UUID), so a retried request never double‑creates a resource. The same key is reused across the retries of one logical call. Override per request:

await factuarea.invoices.create(body, { idempotencyKey: "order-4711" });

Typed errors

Errors map the API's error envelope to a typed hierarchy. Every error exposes .code, .type, .requestId and .status.

import {
  FactuareaError,
  ValidationError,
  AuthenticationError,
  NotFoundError,
  ConflictError,
  RateLimitError,
  ServerError,
  ConnectionError,
} from "@factuarea/sdk";

try {
  await factuarea.invoices.create(body);
} catch (error) {
  if (error instanceof ValidationError) {
    console.error(error.fields);     // { tax_id: ["NIF inválido"], … }
  } else if (error instanceof RateLimitError) {
    console.error(error.retryAfter); // seconds to wait
  } else if (error instanceof FactuareaError) {
    console.error(error.code, error.requestId);
  }
}

Your API key is never included in any error message, stack or property — only the request_id (safe to log and share with support).

Webhooks

Verify the signature of an incoming webhook and get the typed event back. Pass the raw request body (a string), not a re‑serialized object:

import { Factuarea, WebhookSignatureError, SIGNATURE_HEADER } from "@factuarea/sdk";

const factuarea = new Factuarea({ apiKey: process.env.FACTUAREA_API_KEY! });

// Express, with express.raw({ type: "application/json" }) on the route:
app.post("/webhooks/factuarea", (req, res) => {
  try {
    const event = factuarea.webhooks.verify(
      req.body.toString("utf8"),
      req.headers[SIGNATURE_HEADER.toLowerCase()] as string,
      process.env.FACTUAREA_WEBHOOK_SECRET!,
    );
    // event is typed by its `type`
    if (event.type === "invoice.paid") { /* … */ }
    res.sendStatus(200);
  } catch (e) {
    if (e instanceof WebhookSignatureError) return res.sendStatus(400);
    throw e;
  }
});

Verification uses HMAC‑SHA256 with a constant‑time comparison and a configurable timestamp tolerance (default 5 minutes) to reject replays. It also accepts both signatures during a secret‑rotation grace window.

Binary downloads

PDF and other binary endpoints return a BinaryResponse (not JSON):

const pdf = await factuarea.invoices.pdf(invoiceId);
pdf.contentType;     // "application/pdf"
pdf.toBuffer();      // Node Buffer
pdf.toBlob();        // Blob (type preserved)
pdf.body;            // raw ArrayBuffer

Examples

Runnable examples live in examples/:

Supported runtimes & deprecation policy

RuntimeStatus
Node 20✅ supported (CI)
Node 22 (LTS)✅ supported (CI, recommended)
Node 24✅ supported (CI)
Deno / Bun / Workers✅ works (Web fetch based)

Minimum Node 20. The full support matrix, the Node-version policy and the deprecation / breaking-change policy live in SUPPORT.md.

Versioning

This SDK follows SemVer and is aligned with the API's date-based Factuarea-Version. Each release pins one Factuarea-Version and sends it on every request, so the API's behaviour is stable until you upgrade the SDK — upgrading is how you adopt a newer API version. The pinned value per release is recorded in the CHANGELOG, and the full policy + version mapping is in docs/VERSIONING.md. While in 0.x, minor versions may include breaking changes.

Releases & spec sync

Releases are automated with Changesets and published to npm via Trusted Publishing (OIDC) with build provenance — see docs/RELEASING.md. The generated layer is kept in sync with the public OpenAPI spec automatically — see docs/SPEC_SYNC.md.

The Spec Sync badge above is when that check last ran, not when the repo was last committed to: a check that finds nothing to sync leaves no commit. Click it for the date of the latest run.

Contributing & spec

The typed surface in src/generated/ is generated from the OpenAPI spec; the hand‑written runtime lives in src/core/. The pinned spec is committed at spec/openapi.json (frozen against the private spec at commit e822661bc). Do not edit src/generated/ by hand — run npm run generate.

License

MIT © Factuarea

Keywords

factuarea

FAQs

Package last updated on 30 Sep 2026

Related posts