apiempresas 1.1.0 → 1.4.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 CHANGED
@@ -1,110 +1,223 @@
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: 'semana' });
74
- ```
75
-
76
- Requiere Node.js 18 o superior (usa `fetch` nativo).
77
-
78
- ## Entorno de Pruebas (Sandbox)
79
-
80
- 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).
81
-
82
- ```typescript
83
- const api = new ApiEmpresas({
84
- apiKey: 'TU_API_KEY',
85
- baseURL: 'https://apiempresas.es/api/sandbox/v1'
86
- });
87
- ```
88
-
89
- ## Manejo de Errores
90
-
91
- El SDK arrojará un `ApiError` detallado si ocurre algún problema (ej. Plan Insuficiente, CIF inválido).
92
-
93
- ```typescript
94
- import { ApiError } from 'apiempresas';
95
-
96
- try {
97
- await api.companies.score('B00000000');
98
- } catch (error) {
99
- if (error instanceof ApiError) {
100
- console.error(`Status: ${error.status}`);
101
- console.error(`Message: ${error.message}`);
102
- console.error(`Code: ${error.code}`); // p. ej. QUOTA_EXCEEDED, TOO_MANY_REQUESTS, API_KEY_INVALID
103
- }
104
- }
105
- ```
106
-
107
- 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.
108
-
109
- ## Licencia
110
- MIT
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
+ ### 8. Licitaciones públicas abiertas (Business) — 1 consulta
150
+
151
+ ```typescript
152
+ // Concursos en plazo: Plataforma de Contratación del Sector Público y plataformas autonómicas
153
+ const { tenders, pagination } = await api.tenders.list({ q: 'limpieza', province: 'Madrid', type: 'services' });
154
+ console.log(pagination.total, tenders[0].title, tenders[0].deadline, tenders[0].url);
155
+
156
+ // Las parecidas a los contratos que una empresa ya ha ganado (ordenadas por match_score)
157
+ const forCompany = await api.tenders.forCompany('A82018474');
158
+ ```
159
+
160
+ ### 9. Listas de sanciones (Business) — 1 consulta
161
+
162
+ ```typescript
163
+ // Una empresa y sus administradores vigentes, en las listas de la UE, la ONU y OFAC
164
+ const r = await api.sanctions.screen({ cif: 'A46103834' });
165
+ console.log(r.summary.result); // 'clear' | 'possible_match' | 'match'
166
+
167
+ // Un nombre suelto
168
+ const p = await api.sanctions.screen({ name: 'Vladimir Putin', type: 'person' });
169
+ // Cada coincidencia trae level (strong | possible), list, programs, countries y birth_dates para confirmarla
170
+ ```
171
+
172
+ En `companies.verify()` con Business, el resultado incluye `checks.sanctions`.
173
+
174
+ ## Entorno de Pruebas (Sandbox)
175
+
176
+ 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).
177
+
178
+ ```typescript
179
+ const api = new ApiEmpresas({
180
+ apiKey: 'TU_API_KEY',
181
+ baseURL: 'https://apiempresas.es/api/sandbox/v1'
182
+ });
183
+ ```
184
+
185
+ ## Consumo
186
+
187
+ ```typescript
188
+ const u = await api.usage(); // no gasta consultas; no está en el Sandbox
189
+ console.log(u.stats.remaining_calls, u.stats.wallet_balance, u.stats.quota_resets_at);
190
+ ```
191
+
192
+ ## Valores de los filtros
193
+
194
+ ```typescript
195
+ const cat = await api.catalog(); // no gasta consultas; también en el Sandbox
196
+ console.log(cat.province, cat.size_band, cat.radar.priority, cat.webhook_events);
197
+ ```
198
+
199
+ ## Manejo de Errores
200
+
201
+ El SDK arrojará un `ApiError` detallado si ocurre algún problema (ej. Plan Insuficiente, CIF inválido).
202
+
203
+ ```typescript
204
+ import { ApiError } from 'apiempresas';
205
+
206
+ try {
207
+ await api.companies.score('B00000000');
208
+ } catch (error) {
209
+ if (error instanceof ApiError) {
210
+ console.error(`Status: ${error.status}`);
211
+ console.error(`Message: ${error.message}`);
212
+ console.error(`Code: ${error.code}`); // p. ej. QUOTA_EXCEEDED, TOO_MANY_REQUESTS, API_KEY_INVALID
213
+ console.error(`Request: ${error.requestId}`); // dáselo a soporte
214
+ console.error(`Retry after: ${error.retryAfter}`); // segundos, en los 429 por velocidad
215
+ console.error(`Plan: ${error.requiredPlan} ${error.checkoutUrl}`); // en los 403 de plan
216
+ }
217
+ }
218
+ ```
219
+
220
+ 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.
221
+
222
+ ## Licencia
223
+ MIT
@@ -1,12 +1,38 @@
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 { Tenders } from './resources/Tenders';
6
+ import { Sanctions } from './resources/Sanctions';
7
+ import { verifyWebhookSignature, constructWebhookEvent } from './webhooks/signature';
3
8
  /** Versión del SDK, enviada en el User-Agent. */
4
- export declare const SDK_VERSION = "1.1.0";
9
+ export declare const SDK_VERSION = "1.4.0";
5
10
  export declare class ApiEmpresas {
6
11
  private apiKey;
7
12
  private baseURL;
8
13
  private timeout;
9
14
  companies: Companies;
15
+ /** (Pro/Business) Vigilancia de empresas. */
16
+ watchlist: Watchlist;
17
+ /** (Business) Webhooks. */
18
+ webhooks: Webhooks;
19
+ /** (Business) Licitaciones públicas abiertas. */
20
+ tenders: Tenders;
21
+ /** (Business) Listas de sanciones (UE, ONU, OFAC). */
22
+ sanctions: Sanctions;
23
+ /** Atajos: ApiEmpresas.verifyWebhookSignature(...) sin instanciar el cliente. */
24
+ static verifyWebhookSignature: typeof verifyWebhookSignature;
25
+ static constructWebhookEvent: typeof constructWebhookEvent;
10
26
  constructor(options: ApiEmpresasOptions);
27
+ /**
28
+ * Consumo de tu API Key: consultas del periodo, cupo, saldo de créditos e historial
29
+ * de las últimas empresas consultadas. No gasta consultas. No está en el Sandbox.
30
+ */
31
+ usage(): Promise<UsageData>;
32
+ /**
33
+ * Valores válidos de los filtros: provincias, tramos de tamaño, estados, opciones del radar,
34
+ * prioridades y eventos de webhook. No gasta consultas. También está en el Sandbox.
35
+ */
36
+ catalog(): Promise<CatalogData>;
11
37
  request<T>(endpoint: string, options?: RequestInit): Promise<T>;
12
38
  }
@@ -3,8 +3,13 @@ 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 Tenders_1 = require("./resources/Tenders");
9
+ const Sanctions_1 = require("./resources/Sanctions");
10
+ const signature_1 = require("./webhooks/signature");
6
11
  /** Versión del SDK, enviada en el User-Agent. */
7
- exports.SDK_VERSION = '1.1.0';
12
+ exports.SDK_VERSION = '1.4.0';
8
13
  /**
9
14
  * Mensaje legible del cuerpo de error. Según el error, la API lo pone en
10
15
  * message, detail, error (texto) o messages (errores de validación).
@@ -30,6 +35,17 @@ class ApiEmpresas {
30
35
  baseURL;
31
36
  timeout;
32
37
  companies;
38
+ /** (Pro/Business) Vigilancia de empresas. */
39
+ watchlist;
40
+ /** (Business) Webhooks. */
41
+ webhooks;
42
+ /** (Business) Licitaciones públicas abiertas. */
43
+ tenders;
44
+ /** (Business) Listas de sanciones (UE, ONU, OFAC). */
45
+ sanctions;
46
+ /** Atajos: ApiEmpresas.verifyWebhookSignature(...) sin instanciar el cliente. */
47
+ static verifyWebhookSignature = signature_1.verifyWebhookSignature;
48
+ static constructWebhookEvent = signature_1.constructWebhookEvent;
33
49
  constructor(options) {
34
50
  if (!options || !options.apiKey) {
35
51
  throw new Error("La propiedad 'apiKey' es obligatoria para inicializar ApiEmpresas.");
@@ -38,6 +54,26 @@ class ApiEmpresas {
38
54
  this.baseURL = (options.baseURL || 'https://apiempresas.es/api/v1').replace(/\/$/, '');
39
55
  this.timeout = options.timeout || 30000;
40
56
  this.companies = new Companies_1.Companies(this);
57
+ this.watchlist = new Watchlist_1.Watchlist(this);
58
+ this.webhooks = new Webhooks_1.Webhooks(this);
59
+ this.tenders = new Tenders_1.Tenders(this);
60
+ this.sanctions = new Sanctions_1.Sanctions(this);
61
+ }
62
+ /**
63
+ * Consumo de tu API Key: consultas del periodo, cupo, saldo de créditos e historial
64
+ * de las últimas empresas consultadas. No gasta consultas. No está en el Sandbox.
65
+ */
66
+ async usage() {
67
+ const res = await this.request('/usage');
68
+ return res.data;
69
+ }
70
+ /**
71
+ * Valores válidos de los filtros: provincias, tramos de tamaño, estados, opciones del radar,
72
+ * prioridades y eventos de webhook. No gasta consultas. También está en el Sandbox.
73
+ */
74
+ async catalog() {
75
+ const res = await this.request('/catalog');
76
+ return res.data;
41
77
  }
42
78
  async request(endpoint, options = {}) {
43
79
  const url = `${this.baseURL}${endpoint}`;
@@ -60,7 +96,7 @@ class ApiEmpresas {
60
96
  const isJson = response.headers.get('content-type')?.includes('application/json');
61
97
  const data = isJson ? await response.json() : await response.text();
62
98
  if (!response.ok) {
63
- throw new ApiError_1.ApiError(response.status, extractErrorMessage(data) || response.statusText || 'Error desconocido en la API', data?.error || undefined, data);
99
+ throw new ApiError_1.ApiError(response.status, extractErrorMessage(data) || response.statusText || 'Error desconocido en la API', data?.error || undefined, data, response.headers);
64
100
  }
65
101
  return data;
66
102
  }
@@ -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
- constructor(status: number, message: string, errorCode?: string, rawData?: any);
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
  }
@@ -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
- constructor(status, message, errorCode, rawData) {
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
- this.code = rawData && typeof rawData.code === 'string' ? rawData.code : undefined;
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,9 @@
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 { Tenders } from './resources/Tenders';
8
+ export { Sanctions } from './resources/Sanctions';
9
+ export { verifyWebhookSignature, constructWebhookEvent } from './webhooks/signature';
package/dist/index.js CHANGED
@@ -14,9 +14,22 @@ 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.Sanctions = exports.Tenders = 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 Tenders_1 = require("./resources/Tenders");
30
+ Object.defineProperty(exports, "Tenders", { enumerable: true, get: function () { return Tenders_1.Tenders; } });
31
+ var Sanctions_1 = require("./resources/Sanctions");
32
+ Object.defineProperty(exports, "Sanctions", { enumerable: true, get: function () { return Sanctions_1.Sanctions; } });
33
+ var signature_1 = require("./webhooks/signature");
34
+ Object.defineProperty(exports, "verifyWebhookSignature", { enumerable: true, get: function () { return signature_1.verifyWebhookSignature; } });
35
+ 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) Obtiene Insights IA de una empresa.
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
- * (Pro) Obtiene datos de contacto y preparación de la empresa.
95
+ * (Business) Preparación del contacto comercial generada por IA.
63
96
  */
64
97
  contactPrep(cif: string): Promise<any>;
65
98
  /**
66
- * (Business) Obtiene la información del Radar de empresas.
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) Obtiene la red o entramado societario (Network) de una empresa.
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
  /**