apiempresas 1.1.0 → 1.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +198 -110
- package/dist/ApiEmpresas.d.ts +22 -2
- package/dist/ApiEmpresas.js +30 -2
- package/dist/errors/ApiError.d.ts +9 -1
- package/dist/errors/ApiError.js +17 -2
- package/dist/index.d.ts +4 -0
- package/dist/index.js +10 -1
- package/dist/resources/Companies.d.ts +39 -5
- package/dist/resources/Companies.js +65 -5
- package/dist/resources/Watchlist.d.ts +38 -0
- package/dist/resources/Watchlist.js +63 -0
- package/dist/resources/Webhooks.d.ts +21 -0
- package/dist/resources/Webhooks.js +60 -0
- package/dist/types.d.ts +365 -10
- package/dist/webhooks/signature.d.ts +13 -0
- package/dist/webhooks/signature.js +49 -0
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -1,110 +1,198 @@
|
|
|
1
|
-
# APIEmpresas.es - Node.js SDK
|
|
2
|
-
|
|
3
|
-
SDK oficial para interactuar con la API de [APIEmpresas.es](https://apiempresas.es) desde Node.js utilizando TypeScript o JavaScript.
|
|
4
|
-
|
|
5
|
-
## Instalación
|
|
6
|
-
|
|
7
|
-
```bash
|
|
8
|
-
npm install apiempresas
|
|
9
|
-
```
|
|
10
|
-
|
|
11
|
-
## Inicialización
|
|
12
|
-
|
|
13
|
-
```typescript
|
|
14
|
-
import { ApiEmpresas } from 'apiempresas';
|
|
15
|
-
|
|
16
|
-
const api = new ApiEmpresas({
|
|
17
|
-
apiKey: 'TU_API_KEY', // Obligatorio
|
|
18
|
-
});
|
|
19
|
-
```
|
|
20
|
-
|
|
21
|
-
## Uso Básico
|
|
22
|
-
|
|
23
|
-
### 1. Obtener datos de una empresa
|
|
24
|
-
|
|
25
|
-
```typescript
|
|
26
|
-
async function fetchCompany() {
|
|
27
|
-
try {
|
|
28
|
-
const company = await api.companies.get('A15075062');
|
|
29
|
-
console.log(company.name);
|
|
30
|
-
} catch (error) {
|
|
31
|
-
console.error('Error fetching company:', error.message);
|
|
32
|
-
}
|
|
33
|
-
}
|
|
34
|
-
```
|
|
35
|
-
|
|
36
|
-
### 2. Historial de Actos del BORME
|
|
37
|
-
|
|
38
|
-
```typescript
|
|
39
|
-
async function fetchBorme() {
|
|
40
|
-
const bormeData = await api.companies.borme('A15075062');
|
|
41
|
-
console.log(bormeData.events);
|
|
42
|
-
}
|
|
43
|
-
```
|
|
44
|
-
|
|
45
|
-
### 3. Consulta Múltiple (Batch)
|
|
46
|
-
|
|
47
|
-
```typescript
|
|
48
|
-
async function fetchBatch() {
|
|
49
|
-
const response = await api.companies.batch({
|
|
50
|
-
cifs: ['A15075062', 'A46103834']
|
|
51
|
-
});
|
|
52
|
-
console.log('Resultados:', response.data);
|
|
53
|
-
console.log('Coste:', response.meta.cost);
|
|
54
|
-
}
|
|
55
|
-
```
|
|
56
|
-
|
|
57
|
-
### 4. Administradores, búsqueda con varios resultados, Match y Radar
|
|
58
|
-
|
|
59
|
-
```typescript
|
|
60
|
-
// Administradores y cargos (Pro/Business)
|
|
61
|
-
const conAdmins = await api.companies.get('A15075062', { admin: true });
|
|
62
|
-
|
|
63
|
-
// Varias empresas por nombre, con paginación
|
|
64
|
-
let pagina = await api.companies.searchMultiple('software', { limit: 20 });
|
|
65
|
-
while (pagina.meta.next_cursor) {
|
|
66
|
-
pagina = await api.companies.searchMultiple('software', { cursor: pagina.meta.next_cursor });
|
|
67
|
-
}
|
|
68
|
-
|
|
69
|
-
// Match (Business): el sector del vendedor es obligatorio
|
|
70
|
-
const match = await api.companies.match('A15075062', 'software');
|
|
71
|
-
|
|
72
|
-
// Radar de empresas nuevas (Business)
|
|
73
|
-
const nuevas = await api.companies.radar({ province: 'Madrid', range: '
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
```typescript
|
|
83
|
-
const
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
}
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
1
|
+
# APIEmpresas.es - Node.js SDK
|
|
2
|
+
|
|
3
|
+
SDK oficial para interactuar con la API de [APIEmpresas.es](https://apiempresas.es) desde Node.js utilizando TypeScript o JavaScript.
|
|
4
|
+
|
|
5
|
+
## Instalación
|
|
6
|
+
|
|
7
|
+
```bash
|
|
8
|
+
npm install apiempresas
|
|
9
|
+
```
|
|
10
|
+
|
|
11
|
+
## Inicialización
|
|
12
|
+
|
|
13
|
+
```typescript
|
|
14
|
+
import { ApiEmpresas } from 'apiempresas';
|
|
15
|
+
|
|
16
|
+
const api = new ApiEmpresas({
|
|
17
|
+
apiKey: 'TU_API_KEY', // Obligatorio
|
|
18
|
+
});
|
|
19
|
+
```
|
|
20
|
+
|
|
21
|
+
## Uso Básico
|
|
22
|
+
|
|
23
|
+
### 1. Obtener datos de una empresa
|
|
24
|
+
|
|
25
|
+
```typescript
|
|
26
|
+
async function fetchCompany() {
|
|
27
|
+
try {
|
|
28
|
+
const company = await api.companies.get('A15075062');
|
|
29
|
+
console.log(company.name);
|
|
30
|
+
} catch (error) {
|
|
31
|
+
console.error('Error fetching company:', error.message);
|
|
32
|
+
}
|
|
33
|
+
}
|
|
34
|
+
```
|
|
35
|
+
|
|
36
|
+
### 2. Historial de Actos del BORME
|
|
37
|
+
|
|
38
|
+
```typescript
|
|
39
|
+
async function fetchBorme() {
|
|
40
|
+
const bormeData = await api.companies.borme('A15075062');
|
|
41
|
+
console.log(bormeData.events);
|
|
42
|
+
}
|
|
43
|
+
```
|
|
44
|
+
|
|
45
|
+
### 3. Consulta Múltiple (Batch)
|
|
46
|
+
|
|
47
|
+
```typescript
|
|
48
|
+
async function fetchBatch() {
|
|
49
|
+
const response = await api.companies.batch({
|
|
50
|
+
cifs: ['A15075062', 'A46103834']
|
|
51
|
+
});
|
|
52
|
+
console.log('Resultados:', response.data);
|
|
53
|
+
console.log('Coste:', response.meta.cost);
|
|
54
|
+
}
|
|
55
|
+
```
|
|
56
|
+
|
|
57
|
+
### 4. Administradores, búsqueda con varios resultados, Match y Radar
|
|
58
|
+
|
|
59
|
+
```typescript
|
|
60
|
+
// Administradores y cargos (Pro/Business)
|
|
61
|
+
const conAdmins = await api.companies.get('A15075062', { admin: true });
|
|
62
|
+
|
|
63
|
+
// Varias empresas por nombre, con paginación
|
|
64
|
+
let pagina = await api.companies.searchMultiple('software', { limit: 20 });
|
|
65
|
+
while (pagina.meta.next_cursor) {
|
|
66
|
+
pagina = await api.companies.searchMultiple('software', { cursor: pagina.meta.next_cursor });
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
// Match (Business): el sector del vendedor es obligatorio
|
|
70
|
+
const match = await api.companies.match('A15075062', 'software');
|
|
71
|
+
|
|
72
|
+
// Radar de empresas nuevas (todos los planes: 10 resultados en Free con nombre y CIF ocultos, 100 en Pro, 1.000 en Business). range: 'hoy' (por defecto) o días atrás ('7', '30')
|
|
73
|
+
const nuevas = await api.companies.radar({ province: 'Madrid', range: '7' });
|
|
74
|
+
// Filtros añadidos en 1.2.0: cnae, min_score, main_act_type, has_phone
|
|
75
|
+
const software = await api.companies.radar({ cnae: '62', min_score: 70, has_phone: true });
|
|
76
|
+
```
|
|
77
|
+
|
|
78
|
+
Requiere Node.js 18 o superior (usa `fetch` nativo).
|
|
79
|
+
|
|
80
|
+
### 5. Verificación KYB (Pro) — 2 consultas
|
|
81
|
+
|
|
82
|
+
```typescript
|
|
83
|
+
const v = await api.companies.verify('A46103834', {
|
|
84
|
+
name: 'Mercadona SA', // se compara con la razón social
|
|
85
|
+
person: 'Juan Roig Alfonso', // ¿es administrador vigente?
|
|
86
|
+
vat: true // NIF-IVA en VIES
|
|
87
|
+
});
|
|
88
|
+
console.log(v.decision_hint); // 'pass' | 'review' | 'fail'
|
|
89
|
+
console.log(v.flags); // alertas con code, severity y message
|
|
90
|
+
```
|
|
91
|
+
|
|
92
|
+
Cada empresa trae además `status_code` (ACTIVE, INSOLVENCY, EXTINCT...), `status_source`, `status_date` y, en Pro/Business, `financials` (tramo de tamaño y último año de cuentas). Los administradores traen `since`. Desde la 1.3.0 la respuesta lleva también `identifiers` (código LEI) y `legal_form` (forma jurídica con su código ISO 20275) en todos los planes, y en Pro/Business `group` (matriz directa y última según GLEIF) y `ownership` (socio único según el BORME). En `verify`, con `person`, `checks.person.is_sole_shareholder` dice si quien firma es el socio único.
|
|
93
|
+
|
|
94
|
+
### Nombre a CIF (Pro)
|
|
95
|
+
|
|
96
|
+
```typescript
|
|
97
|
+
const { data, meta } = await api.companies.reconcile(['Mercadona', { name: 'Talleres Pérez', province: 'Madrid' }]);
|
|
98
|
+
// data[i].status: match (con company.cif) | ambiguous (candidates) | no_match. Solo se cobran los match.
|
|
99
|
+
```
|
|
100
|
+
|
|
101
|
+
### Segmentos de empresas
|
|
102
|
+
|
|
103
|
+
```typescript
|
|
104
|
+
const total = await api.companies.count({ cnae: ['62'], province: 'MADRID', has_phone: true }); // gratis
|
|
105
|
+
const { data, meta } = await api.companies.filter({ cnae: ['62'], province: 'MADRID', limit: 100 }); // Business: 5 consultas por fila
|
|
106
|
+
// Siguiente página: api.companies.filter({ ...mismosFiltros, cursor: meta.next_cursor })
|
|
107
|
+
```
|
|
108
|
+
|
|
109
|
+
### 6. Vigilancia de empresas (Pro: 100, Business: 1.000) — sin coste
|
|
110
|
+
|
|
111
|
+
```typescript
|
|
112
|
+
await api.watchlist.add(['A46103834', 'A28015865']);
|
|
113
|
+
const { data: vigiladas, meta } = await api.watchlist.list(); // meta.watch_limit
|
|
114
|
+
const { data: cambios } = await api.watchlist.events({ since: '2026-09-01', types: ['borme_act', 'status_change'] });
|
|
115
|
+
await api.watchlist.remove('A28015865');
|
|
116
|
+
```
|
|
117
|
+
|
|
118
|
+
### 7. Webhooks (Business)
|
|
119
|
+
|
|
120
|
+
```typescript
|
|
121
|
+
const hook = await api.webhooks.create({ url: 'https://tu-servidor.com/apiempresas', event: 'watchlist.*' });
|
|
122
|
+
// Guarda hook.secret: con él se comprueba la firma.
|
|
123
|
+
await api.webhooks.test(hook.id); // envía un test.ping y devuelve lo que respondió tu servidor
|
|
124
|
+
|
|
125
|
+
// Historial de entregas (lo más reciente primero): estado, intentos, código HTTP y error
|
|
126
|
+
const { data, meta } = await api.webhooks.deliveries(hook.id, { status: 'dead', limit: 20 });
|
|
127
|
+
```
|
|
128
|
+
|
|
129
|
+
En tu servidor, comprueba la firma con el cuerpo **en bruto** (no el JSON ya parseado):
|
|
130
|
+
|
|
131
|
+
```typescript
|
|
132
|
+
import express from 'express';
|
|
133
|
+
import { constructWebhookEvent } from 'apiempresas';
|
|
134
|
+
|
|
135
|
+
app.post('/apiempresas', express.raw({ type: 'application/json' }), (req, res) => {
|
|
136
|
+
try {
|
|
137
|
+
const evento = constructWebhookEvent(req.body, req.header('X-ApiEmpresas-Signature'), process.env.APIEMPRESAS_WEBHOOK_SECRET!);
|
|
138
|
+
// evento.event: company.borme_act | company.status_changed | company.risk_level_changed | test.ping
|
|
139
|
+
// Usa evento.id (o la cabecera X-ApiEmpresas-Delivery) para no procesar dos veces el mismo envío.
|
|
140
|
+
res.sendStatus(200);
|
|
141
|
+
} catch {
|
|
142
|
+
res.sendStatus(400);
|
|
143
|
+
}
|
|
144
|
+
});
|
|
145
|
+
```
|
|
146
|
+
|
|
147
|
+
Si tu servidor no responde 2xx, se reintenta a los 1 min, 5 min, 30 min, 2 h y 6 h.
|
|
148
|
+
|
|
149
|
+
## Entorno de Pruebas (Sandbox)
|
|
150
|
+
|
|
151
|
+
Para probar la integración sin consumir saldo, apunta a la URL del Sandbox con tu misma API Key. Devuelve datos simulados: `A15075062` (empresa encontrada) y `B00000000` (no encontrada).
|
|
152
|
+
|
|
153
|
+
```typescript
|
|
154
|
+
const api = new ApiEmpresas({
|
|
155
|
+
apiKey: 'TU_API_KEY',
|
|
156
|
+
baseURL: 'https://apiempresas.es/api/sandbox/v1'
|
|
157
|
+
});
|
|
158
|
+
```
|
|
159
|
+
|
|
160
|
+
## Consumo
|
|
161
|
+
|
|
162
|
+
```typescript
|
|
163
|
+
const u = await api.usage(); // no gasta consultas; no está en el Sandbox
|
|
164
|
+
console.log(u.stats.remaining_calls, u.stats.wallet_balance, u.stats.quota_resets_at);
|
|
165
|
+
```
|
|
166
|
+
|
|
167
|
+
## Valores de los filtros
|
|
168
|
+
|
|
169
|
+
```typescript
|
|
170
|
+
const cat = await api.catalog(); // no gasta consultas; también en el Sandbox
|
|
171
|
+
console.log(cat.province, cat.size_band, cat.radar.priority, cat.webhook_events);
|
|
172
|
+
```
|
|
173
|
+
|
|
174
|
+
## Manejo de Errores
|
|
175
|
+
|
|
176
|
+
El SDK arrojará un `ApiError` detallado si ocurre algún problema (ej. Plan Insuficiente, CIF inválido).
|
|
177
|
+
|
|
178
|
+
```typescript
|
|
179
|
+
import { ApiError } from 'apiempresas';
|
|
180
|
+
|
|
181
|
+
try {
|
|
182
|
+
await api.companies.score('B00000000');
|
|
183
|
+
} catch (error) {
|
|
184
|
+
if (error instanceof ApiError) {
|
|
185
|
+
console.error(`Status: ${error.status}`);
|
|
186
|
+
console.error(`Message: ${error.message}`);
|
|
187
|
+
console.error(`Code: ${error.code}`); // p. ej. QUOTA_EXCEEDED, TOO_MANY_REQUESTS, API_KEY_INVALID
|
|
188
|
+
console.error(`Request: ${error.requestId}`); // dáselo a soporte
|
|
189
|
+
console.error(`Retry after: ${error.retryAfter}`); // segundos, en los 429 por velocidad
|
|
190
|
+
console.error(`Plan: ${error.requiredPlan} ${error.checkoutUrl}`); // en los 403 de plan
|
|
191
|
+
}
|
|
192
|
+
}
|
|
193
|
+
```
|
|
194
|
+
|
|
195
|
+
Un `429` con `code: 'TOO_MANY_REQUESTS'` se resuelve esperando y reintentando; con `code: 'QUOTA_EXCEEDED'` no: hay que recargar saldo o cambiar de plan. `errorCode` sigue devolviendo el campo `error` de la respuesta, como en versiones anteriores.
|
|
196
|
+
|
|
197
|
+
## Licencia
|
|
198
|
+
MIT
|
package/dist/ApiEmpresas.d.ts
CHANGED
|
@@ -1,12 +1,32 @@
|
|
|
1
|
-
import { ApiEmpresasOptions } from './types';
|
|
1
|
+
import { ApiEmpresasOptions, UsageData, CatalogData } from './types';
|
|
2
2
|
import { Companies } from './resources/Companies';
|
|
3
|
+
import { Watchlist } from './resources/Watchlist';
|
|
4
|
+
import { Webhooks } from './resources/Webhooks';
|
|
5
|
+
import { verifyWebhookSignature, constructWebhookEvent } from './webhooks/signature';
|
|
3
6
|
/** Versión del SDK, enviada en el User-Agent. */
|
|
4
|
-
export declare const SDK_VERSION = "1.
|
|
7
|
+
export declare const SDK_VERSION = "1.3.0";
|
|
5
8
|
export declare class ApiEmpresas {
|
|
6
9
|
private apiKey;
|
|
7
10
|
private baseURL;
|
|
8
11
|
private timeout;
|
|
9
12
|
companies: Companies;
|
|
13
|
+
/** (Pro/Business) Vigilancia de empresas. */
|
|
14
|
+
watchlist: Watchlist;
|
|
15
|
+
/** (Business) Webhooks. */
|
|
16
|
+
webhooks: Webhooks;
|
|
17
|
+
/** Atajos: ApiEmpresas.verifyWebhookSignature(...) sin instanciar el cliente. */
|
|
18
|
+
static verifyWebhookSignature: typeof verifyWebhookSignature;
|
|
19
|
+
static constructWebhookEvent: typeof constructWebhookEvent;
|
|
10
20
|
constructor(options: ApiEmpresasOptions);
|
|
21
|
+
/**
|
|
22
|
+
* Consumo de tu API Key: consultas del periodo, cupo, saldo de créditos e historial
|
|
23
|
+
* de las últimas empresas consultadas. No gasta consultas. No está en el Sandbox.
|
|
24
|
+
*/
|
|
25
|
+
usage(): Promise<UsageData>;
|
|
26
|
+
/**
|
|
27
|
+
* Valores válidos de los filtros: provincias, tramos de tamaño, estados, opciones del radar,
|
|
28
|
+
* prioridades y eventos de webhook. No gasta consultas. También está en el Sandbox.
|
|
29
|
+
*/
|
|
30
|
+
catalog(): Promise<CatalogData>;
|
|
11
31
|
request<T>(endpoint: string, options?: RequestInit): Promise<T>;
|
|
12
32
|
}
|
package/dist/ApiEmpresas.js
CHANGED
|
@@ -3,8 +3,11 @@ Object.defineProperty(exports, "__esModule", { value: true });
|
|
|
3
3
|
exports.ApiEmpresas = exports.SDK_VERSION = void 0;
|
|
4
4
|
const ApiError_1 = require("./errors/ApiError");
|
|
5
5
|
const Companies_1 = require("./resources/Companies");
|
|
6
|
+
const Watchlist_1 = require("./resources/Watchlist");
|
|
7
|
+
const Webhooks_1 = require("./resources/Webhooks");
|
|
8
|
+
const signature_1 = require("./webhooks/signature");
|
|
6
9
|
/** Versión del SDK, enviada en el User-Agent. */
|
|
7
|
-
exports.SDK_VERSION = '1.
|
|
10
|
+
exports.SDK_VERSION = '1.3.0';
|
|
8
11
|
/**
|
|
9
12
|
* Mensaje legible del cuerpo de error. Según el error, la API lo pone en
|
|
10
13
|
* message, detail, error (texto) o messages (errores de validación).
|
|
@@ -30,6 +33,13 @@ class ApiEmpresas {
|
|
|
30
33
|
baseURL;
|
|
31
34
|
timeout;
|
|
32
35
|
companies;
|
|
36
|
+
/** (Pro/Business) Vigilancia de empresas. */
|
|
37
|
+
watchlist;
|
|
38
|
+
/** (Business) Webhooks. */
|
|
39
|
+
webhooks;
|
|
40
|
+
/** Atajos: ApiEmpresas.verifyWebhookSignature(...) sin instanciar el cliente. */
|
|
41
|
+
static verifyWebhookSignature = signature_1.verifyWebhookSignature;
|
|
42
|
+
static constructWebhookEvent = signature_1.constructWebhookEvent;
|
|
33
43
|
constructor(options) {
|
|
34
44
|
if (!options || !options.apiKey) {
|
|
35
45
|
throw new Error("La propiedad 'apiKey' es obligatoria para inicializar ApiEmpresas.");
|
|
@@ -38,6 +48,24 @@ class ApiEmpresas {
|
|
|
38
48
|
this.baseURL = (options.baseURL || 'https://apiempresas.es/api/v1').replace(/\/$/, '');
|
|
39
49
|
this.timeout = options.timeout || 30000;
|
|
40
50
|
this.companies = new Companies_1.Companies(this);
|
|
51
|
+
this.watchlist = new Watchlist_1.Watchlist(this);
|
|
52
|
+
this.webhooks = new Webhooks_1.Webhooks(this);
|
|
53
|
+
}
|
|
54
|
+
/**
|
|
55
|
+
* Consumo de tu API Key: consultas del periodo, cupo, saldo de créditos e historial
|
|
56
|
+
* de las últimas empresas consultadas. No gasta consultas. No está en el Sandbox.
|
|
57
|
+
*/
|
|
58
|
+
async usage() {
|
|
59
|
+
const res = await this.request('/usage');
|
|
60
|
+
return res.data;
|
|
61
|
+
}
|
|
62
|
+
/**
|
|
63
|
+
* Valores válidos de los filtros: provincias, tramos de tamaño, estados, opciones del radar,
|
|
64
|
+
* prioridades y eventos de webhook. No gasta consultas. También está en el Sandbox.
|
|
65
|
+
*/
|
|
66
|
+
async catalog() {
|
|
67
|
+
const res = await this.request('/catalog');
|
|
68
|
+
return res.data;
|
|
41
69
|
}
|
|
42
70
|
async request(endpoint, options = {}) {
|
|
43
71
|
const url = `${this.baseURL}${endpoint}`;
|
|
@@ -60,7 +88,7 @@ class ApiEmpresas {
|
|
|
60
88
|
const isJson = response.headers.get('content-type')?.includes('application/json');
|
|
61
89
|
const data = isJson ? await response.json() : await response.text();
|
|
62
90
|
if (!response.ok) {
|
|
63
|
-
throw new ApiError_1.ApiError(response.status, extractErrorMessage(data) || response.statusText || 'Error desconocido en la API', data?.error || undefined, data);
|
|
91
|
+
throw new ApiError_1.ApiError(response.status, extractErrorMessage(data) || response.statusText || 'Error desconocido en la API', data?.error || undefined, data, response.headers);
|
|
64
92
|
}
|
|
65
93
|
return data;
|
|
66
94
|
}
|
|
@@ -4,5 +4,13 @@ export declare class ApiError extends Error {
|
|
|
4
4
|
/** Identificador estable del error (QUOTA_EXCEEDED, TOO_MANY_REQUESTS, API_KEY_INVALID...). */
|
|
5
5
|
code?: string;
|
|
6
6
|
rawData?: any;
|
|
7
|
-
|
|
7
|
+
/** Identificador de la petición (cabecera X-Request-Id o campo instance). Dáselo a soporte. */
|
|
8
|
+
requestId?: string;
|
|
9
|
+
/** Segundos a esperar antes de reintentar (cabecera Retry-After). Solo en 429 que se arreglan esperando. */
|
|
10
|
+
retryAfter?: number;
|
|
11
|
+
/** Plan necesario para la ruta ('pro' o 'business'), en los 403 de plan. */
|
|
12
|
+
requiredPlan?: string;
|
|
13
|
+
/** Enlace para cambiar de plan o comprar créditos, si la API lo incluye. */
|
|
14
|
+
checkoutUrl?: string;
|
|
15
|
+
constructor(status: number, message: string, errorCode?: string, rawData?: any, headers?: Headers);
|
|
8
16
|
}
|
package/dist/errors/ApiError.js
CHANGED
|
@@ -7,13 +7,28 @@ class ApiError extends Error {
|
|
|
7
7
|
/** Identificador estable del error (QUOTA_EXCEEDED, TOO_MANY_REQUESTS, API_KEY_INVALID...). */
|
|
8
8
|
code;
|
|
9
9
|
rawData;
|
|
10
|
-
|
|
10
|
+
/** Identificador de la petición (cabecera X-Request-Id o campo instance). Dáselo a soporte. */
|
|
11
|
+
requestId;
|
|
12
|
+
/** Segundos a esperar antes de reintentar (cabecera Retry-After). Solo en 429 que se arreglan esperando. */
|
|
13
|
+
retryAfter;
|
|
14
|
+
/** Plan necesario para la ruta ('pro' o 'business'), en los 403 de plan. */
|
|
15
|
+
requiredPlan;
|
|
16
|
+
/** Enlace para cambiar de plan o comprar créditos, si la API lo incluye. */
|
|
17
|
+
checkoutUrl;
|
|
18
|
+
constructor(status, message, errorCode, rawData, headers) {
|
|
11
19
|
super(message);
|
|
12
20
|
this.name = 'ApiError';
|
|
13
21
|
this.status = status;
|
|
14
22
|
this.errorCode = errorCode;
|
|
15
23
|
this.rawData = rawData;
|
|
16
|
-
|
|
24
|
+
const d = rawData && typeof rawData === 'object' ? rawData : {};
|
|
25
|
+
this.code = typeof d.code === 'string' ? d.code : undefined;
|
|
26
|
+
this.requestId = headers?.get('x-request-id') || (typeof d.instance === 'string' ? d.instance : undefined);
|
|
27
|
+
const ra = headers?.get('retry-after');
|
|
28
|
+
this.retryAfter = ra && /^\d+$/.test(ra) ? parseInt(ra, 10) : undefined;
|
|
29
|
+
this.requiredPlan = typeof d.required_plan === 'string' ? d.required_plan : undefined;
|
|
30
|
+
const up = d.upsell_opportunities && typeof d.upsell_opportunities === 'object' ? d.upsell_opportunities : {};
|
|
31
|
+
this.checkoutUrl = [d.checkout_url, up.checkout_url, d.upgrade_url, up.upgrade_url].find((u) => typeof u === 'string' && u !== '');
|
|
17
32
|
// Fix prototype chain for built-in classes in TS
|
|
18
33
|
Object.setPrototypeOf(this, ApiError.prototype);
|
|
19
34
|
}
|
package/dist/index.d.ts
CHANGED
|
@@ -1,3 +1,7 @@
|
|
|
1
1
|
export { ApiEmpresas } from './ApiEmpresas';
|
|
2
2
|
export { ApiError } from './errors/ApiError';
|
|
3
3
|
export * from './types';
|
|
4
|
+
export { Companies } from './resources/Companies';
|
|
5
|
+
export { Watchlist } from './resources/Watchlist';
|
|
6
|
+
export { Webhooks } from './resources/Webhooks';
|
|
7
|
+
export { verifyWebhookSignature, constructWebhookEvent } from './webhooks/signature';
|
package/dist/index.js
CHANGED
|
@@ -14,9 +14,18 @@ var __exportStar = (this && this.__exportStar) || function(m, exports) {
|
|
|
14
14
|
for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
|
|
15
15
|
};
|
|
16
16
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
17
|
-
exports.ApiError = exports.ApiEmpresas = void 0;
|
|
17
|
+
exports.constructWebhookEvent = exports.verifyWebhookSignature = exports.Webhooks = exports.Watchlist = exports.Companies = exports.ApiError = exports.ApiEmpresas = void 0;
|
|
18
18
|
var ApiEmpresas_1 = require("./ApiEmpresas");
|
|
19
19
|
Object.defineProperty(exports, "ApiEmpresas", { enumerable: true, get: function () { return ApiEmpresas_1.ApiEmpresas; } });
|
|
20
20
|
var ApiError_1 = require("./errors/ApiError");
|
|
21
21
|
Object.defineProperty(exports, "ApiError", { enumerable: true, get: function () { return ApiError_1.ApiError; } });
|
|
22
22
|
__exportStar(require("./types"), exports);
|
|
23
|
+
var Companies_1 = require("./resources/Companies");
|
|
24
|
+
Object.defineProperty(exports, "Companies", { enumerable: true, get: function () { return Companies_1.Companies; } });
|
|
25
|
+
var Watchlist_1 = require("./resources/Watchlist");
|
|
26
|
+
Object.defineProperty(exports, "Watchlist", { enumerable: true, get: function () { return Watchlist_1.Watchlist; } });
|
|
27
|
+
var Webhooks_1 = require("./resources/Webhooks");
|
|
28
|
+
Object.defineProperty(exports, "Webhooks", { enumerable: true, get: function () { return Webhooks_1.Webhooks; } });
|
|
29
|
+
var signature_1 = require("./webhooks/signature");
|
|
30
|
+
Object.defineProperty(exports, "verifyWebhookSignature", { enumerable: true, get: function () { return signature_1.verifyWebhookSignature; } });
|
|
31
|
+
Object.defineProperty(exports, "constructWebhookEvent", { enumerable: true, get: function () { return signature_1.constructWebhookEvent; } });
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { ApiEmpresas } from '../ApiEmpresas';
|
|
2
|
-
import { Company, BatchRequest, BatchResponse, ScoreData, BormeData, SignalsData } from '../types';
|
|
2
|
+
import { Company, BatchRequest, BatchResponse, ScoreData, BormeData, SignalsData, VerifyOptions, VerifyResult, FilterOptions, SegmentRow, SegmentMeta, ReconcileItem, ReconcileResult, ReconcileMeta } from '../types';
|
|
3
3
|
/** Opciones de get(): admin=true añade administradores y cargos (Pro/Business). */
|
|
4
4
|
export interface GetOptions {
|
|
5
5
|
admin?: boolean;
|
|
@@ -15,6 +15,14 @@ export interface RadarOptions {
|
|
|
15
15
|
province?: string;
|
|
16
16
|
priority?: string;
|
|
17
17
|
range?: string;
|
|
18
|
+
/** Código CNAE (o su prefijo). */
|
|
19
|
+
cnae?: string;
|
|
20
|
+
/** Puntuación mínima (0-100). */
|
|
21
|
+
min_score?: number;
|
|
22
|
+
/** Tipo de acto principal (constitución, ampliación de capital...). */
|
|
23
|
+
main_act_type?: string;
|
|
24
|
+
/** true: solo empresas con teléfono. */
|
|
25
|
+
has_phone?: boolean;
|
|
18
26
|
}
|
|
19
27
|
export declare class Companies {
|
|
20
28
|
private client;
|
|
@@ -23,6 +31,31 @@ export declare class Companies {
|
|
|
23
31
|
* Obtiene los datos básicos de una empresa por su CIF.
|
|
24
32
|
*/
|
|
25
33
|
get(cif: string, options?: GetOptions): Promise<Company>;
|
|
34
|
+
/**
|
|
35
|
+
* (Pro) Verificación KYB en una llamada: estado, nombre, administrador, VIES y
|
|
36
|
+
* alertas, con decision_hint pass / review / fail. Coste: 2 consultas.
|
|
37
|
+
*/
|
|
38
|
+
verify(cif: string, options?: VerifyOptions): Promise<VerifyResult>;
|
|
39
|
+
/**
|
|
40
|
+
* (Pro) Nombre a CIF, hasta 100 por petición. 1 consulta por cada "match";
|
|
41
|
+
* ambiguous y no_match no se cobran.
|
|
42
|
+
*/
|
|
43
|
+
reconcile(items: Array<string | ReconcileItem>): Promise<{
|
|
44
|
+
data: ReconcileResult[];
|
|
45
|
+
meta: ReconcileMeta;
|
|
46
|
+
}>;
|
|
47
|
+
/**
|
|
48
|
+
* Cuántas empresas encajan con los filtros. Gratis en todos los planes.
|
|
49
|
+
*/
|
|
50
|
+
count(options: FilterOptions): Promise<number>;
|
|
51
|
+
/**
|
|
52
|
+
* (Business) Empresas de un segmento. 5 consultas por fila devuelta; para la página
|
|
53
|
+
* siguiente, pasa meta.next_cursor como cursor con los mismos filtros.
|
|
54
|
+
*/
|
|
55
|
+
filter(options: FilterOptions): Promise<{
|
|
56
|
+
data: SegmentRow[];
|
|
57
|
+
meta: SegmentMeta;
|
|
58
|
+
}>;
|
|
26
59
|
/**
|
|
27
60
|
* Busca empresas por nombre o razón social.
|
|
28
61
|
*/
|
|
@@ -55,15 +88,16 @@ export declare class Companies {
|
|
|
55
88
|
*/
|
|
56
89
|
signals(cif: string): Promise<SignalsData>;
|
|
57
90
|
/**
|
|
58
|
-
* (Business)
|
|
91
|
+
* (Business; en Pro, vista previa con profile y conversion_probability) Insights IA de una empresa.
|
|
59
92
|
*/
|
|
60
93
|
insights(cif: string): Promise<any>;
|
|
61
94
|
/**
|
|
62
|
-
* (
|
|
95
|
+
* (Business) Preparación del contacto comercial generada por IA.
|
|
63
96
|
*/
|
|
64
97
|
contactPrep(cif: string): Promise<any>;
|
|
65
98
|
/**
|
|
66
|
-
* (
|
|
99
|
+
* (Todos los planes: Free 10 resultados con nombre y CIF ocultos, Pro 100, Business 1.000)
|
|
100
|
+
* Empresas recién constituidas. Devuelve la lista (data); el resumen (meta) no se incluye.
|
|
67
101
|
*/
|
|
68
102
|
radar(cifOrOptions?: string | RadarOptions): Promise<any>;
|
|
69
103
|
/**
|
|
@@ -71,7 +105,7 @@ export declare class Companies {
|
|
|
71
105
|
*/
|
|
72
106
|
match(cif: string, sellerSector?: string): Promise<any>;
|
|
73
107
|
/**
|
|
74
|
-
* (Business)
|
|
108
|
+
* (Pro y Business) Red societaria de una empresa a través de sus administradores.
|
|
75
109
|
*/
|
|
76
110
|
network(cif: string): Promise<any>;
|
|
77
111
|
/**
|