@hirefinn/sdk 0.1.0 → 0.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.
Files changed (38) hide show
  1. package/README.md +79 -9
  2. package/dist/cjs/client.d.ts +13 -1
  3. package/dist/cjs/client.js +5 -0
  4. package/dist/cjs/core.d.ts +14 -2
  5. package/dist/cjs/core.js +41 -4
  6. package/dist/cjs/generated/openapi.d.ts +17426 -5875
  7. package/dist/cjs/generated/operations.d.ts +26 -0
  8. package/dist/cjs/generated/operations.js +165 -0
  9. package/dist/cjs/generated/resources.d.ts +887 -0
  10. package/dist/cjs/generated/resources.js +737 -0
  11. package/dist/cjs/index.d.ts +4 -2
  12. package/dist/cjs/index.js +12 -1
  13. package/dist/cjs/resource.d.ts +30 -0
  14. package/dist/cjs/resource.js +23 -0
  15. package/dist/cjs/resources.d.ts +52 -59
  16. package/dist/cjs/resources.js +27 -37
  17. package/dist/cjs/types.d.ts +17 -5
  18. package/dist/cjs/webhooks.d.ts +57 -0
  19. package/dist/cjs/webhooks.js +181 -0
  20. package/dist/esm/client.d.ts +13 -1
  21. package/dist/esm/client.js +6 -1
  22. package/dist/esm/core.d.ts +14 -2
  23. package/dist/esm/core.js +39 -3
  24. package/dist/esm/generated/openapi.d.ts +17426 -5875
  25. package/dist/esm/generated/operations.d.ts +26 -0
  26. package/dist/esm/generated/operations.js +162 -0
  27. package/dist/esm/generated/resources.d.ts +887 -0
  28. package/dist/esm/generated/resources.js +716 -0
  29. package/dist/esm/index.d.ts +4 -2
  30. package/dist/esm/index.js +2 -1
  31. package/dist/esm/resource.d.ts +30 -0
  32. package/dist/esm/resource.js +19 -0
  33. package/dist/esm/resources.d.ts +52 -59
  34. package/dist/esm/resources.js +20 -35
  35. package/dist/esm/types.d.ts +17 -5
  36. package/dist/esm/webhooks.d.ts +57 -0
  37. package/dist/esm/webhooks.js +140 -0
  38. package/package.json +4 -1
@@ -3,6 +3,7 @@
3
3
  * body and success response, so `finn.request('get', '/calls/{call_uuid}', ...)` is checked end to end.
4
4
  */
5
5
  import type { components, operations, paths } from './generated/openapi.js';
6
+ import type { SpecHoldableRoute } from './generated/operations.js';
6
7
  export type { components, operations, paths };
7
8
  /** Every schema in the spec, e.g. `Schemas['Call']`. */
8
9
  export type Schemas = components['schemas'];
@@ -101,9 +102,13 @@ export interface PendingApproval {
101
102
  /** The page in Finn where a person approves it. */
102
103
  approve_url: string;
103
104
  expires_at: string | null;
104
- action?: string;
105
- summary?: unknown;
105
+ /** What was held. */
106
+ action: HoldAction;
107
+ /** A short description of the held request, for showing to the person. */
108
+ summary: unknown;
106
109
  }
110
+ /** The actions the API can hold for approval. */
111
+ export type HoldAction = 'call.create' | 'phone_number.rent' | 'deployment.create' | 'case.start' | 'chat.start' | 'chat.send' | 'contact.stage_move' | 'contact.import' | 'contact.form_link' | 'contact.form_submit' | 'contact.upload_link' | (string & {});
107
112
  /** Status of a held API request as `GET /approvals/{id}` reports it. */
108
113
  export type HoldStatus = 'pending' | 'running' | 'succeeded' | 'failed' | 'declined' | 'expired';
109
114
  /** A held API request as `GET /approvals/{id}` returns it to the caller that made it. */
@@ -138,7 +143,14 @@ export interface FinnResponse<T> {
138
143
  /** True when the API replayed a saved answer for the same Idempotency-Key. */
139
144
  idempotentReplayed: boolean;
140
145
  }
141
- /** Routes whose writes the API may hold for approval (HTTP 202 `pending_approval`). */
142
- export type HoldableRoute = 'post /calls' | 'post /deployments' | 'post /phone_numbers';
146
+ /**
147
+ * Routes whose writes the API may hold for approval (HTTP 202 `pending_approval`): the ones listed here plus the
148
+ * ones the spec marks (`x-finn-hold`, or a 202 answer that says `pending_approval`).
149
+ */
150
+ export type HoldableRoute = 'post /calls' | 'post /deployments' | 'post /phone_numbers' | 'post /agents/{id}/cases' | 'post /chat/conversations' | 'post /chat/conversations/{id}/messages' | SpecHoldableRoute;
151
+ /** The spec's own PendingApproval schema, replaced by the SDK's `PendingApproval` in results. */
152
+ type SpecPendingApproval = components['schemas'] extends {
153
+ PendingApproval: infer X;
154
+ } ? X : never;
143
155
  /** What `request()` resolves to: the spec's success body, or PendingApproval on holdable routes. */
144
- export type ResultOf<P extends string, M extends HttpMethod, O> = `${M} ${P}` extends HoldableRoute ? ResponseOf<O> | PendingApproval : ResponseOf<O>;
156
+ export type ResultOf<P extends string, M extends HttpMethod, O> = `${M} ${P}` extends HoldableRoute ? Exclude<ResponseOf<O>, SpecPendingApproval> | PendingApproval : ResponseOf<O>;
@@ -0,0 +1,57 @@
1
+ import { FinnSdkError } from './errors.js';
2
+ /**
3
+ * Webhook signature checks.
4
+ *
5
+ * Finn signs every delivery with `X-Finn-Signature: t=<unix seconds>,v1=<hex HMAC-SHA256(secret, "<t>.<raw body>")>`
6
+ * and names the event in `X-Finn-Event`. verifyWebhook() checks the signature in constant time and refuses
7
+ * deliveries whose timestamp is too far from now, so a captured request cannot be replayed later.
8
+ */
9
+ /** Header that carries the signature. */
10
+ export declare const WEBHOOK_SIGNATURE_HEADER = "X-Finn-Signature";
11
+ /** Header that carries the event name. */
12
+ export declare const WEBHOOK_EVENT_HEADER = "X-Finn-Event";
13
+ /** Default largest gap, in seconds, between the signed timestamp and now. */
14
+ export declare const DEFAULT_WEBHOOK_TOLERANCE_SECONDS = 300;
15
+ /** The body of every webhook delivery. */
16
+ export interface WebhookEvent<T = Record<string, unknown>> {
17
+ /** e.g. `call.completed`, `contact.created`, `case.completed`. */
18
+ event: string;
19
+ created_at: string;
20
+ data: T;
21
+ }
22
+ /** The delivery's signature is missing, malformed, wrong or too old. Answer the request with a 400. */
23
+ export declare class FinnWebhookVerificationError extends FinnSdkError {
24
+ constructor(message: string);
25
+ }
26
+ export interface VerifyWebhookOptions {
27
+ /** The raw request body, exactly as received (not re-serialised JSON). */
28
+ payload: string | Uint8Array;
29
+ /** The `X-Finn-Signature` value, or the request's headers to read it from. */
30
+ header?: string | null;
31
+ headers?: Headers | Record<string, string | string[] | undefined>;
32
+ /** The endpoint's signing secret (`whsec_...`). Pass several while you rotate secrets. */
33
+ secret: string | readonly string[];
34
+ /** Largest gap between the signed timestamp and now, in seconds. Default 300. */
35
+ toleranceSeconds?: number;
36
+ /** Current time in unix seconds (for tests). */
37
+ now?: number;
38
+ }
39
+ /** Splits `t=...,v1=...` into its timestamp and v1 signatures. */
40
+ export declare function parseSignatureHeader(header: string): {
41
+ timestamp: number;
42
+ signatures: string[];
43
+ };
44
+ /** Compares two byte arrays in time that depends only on their length. */
45
+ export declare function timingSafeEqual(a: Uint8Array, b: Uint8Array): boolean;
46
+ /** Hex HMAC-SHA256 of `<timestamp>.<payload>`, the way Finn signs deliveries. */
47
+ export declare function signWebhookPayload(secret: string, timestamp: number | string, payload: string | Uint8Array): Promise<string>;
48
+ /**
49
+ * Checks a webhook delivery and returns its parsed body. Throws FinnWebhookVerificationError when the signature is
50
+ * missing, malformed or wrong, or the timestamp is more than `toleranceSeconds` (default 300) away from now.
51
+ *
52
+ * app.post('/finn-webhook', express.raw({ type: 'application/json' }), async (req, res) => {
53
+ * const event = await verifyWebhook({ payload: req.body, headers: req.headers, secret: process.env.FINN_WEBHOOK_SECRET! });
54
+ * ...
55
+ * });
56
+ */
57
+ export declare function verifyWebhook<T = Record<string, unknown>>(options: VerifyWebhookOptions): Promise<WebhookEvent<T>>;
@@ -0,0 +1,181 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
15
+ }) : function(o, v) {
16
+ o["default"] = v;
17
+ });
18
+ var __importStar = (this && this.__importStar) || (function () {
19
+ var ownKeys = function(o) {
20
+ ownKeys = Object.getOwnPropertyNames || function (o) {
21
+ var ar = [];
22
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
23
+ return ar;
24
+ };
25
+ return ownKeys(o);
26
+ };
27
+ return function (mod) {
28
+ if (mod && mod.__esModule) return mod;
29
+ var result = {};
30
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
31
+ __setModuleDefault(result, mod);
32
+ return result;
33
+ };
34
+ })();
35
+ Object.defineProperty(exports, "__esModule", { value: true });
36
+ exports.FinnWebhookVerificationError = exports.DEFAULT_WEBHOOK_TOLERANCE_SECONDS = exports.WEBHOOK_EVENT_HEADER = exports.WEBHOOK_SIGNATURE_HEADER = void 0;
37
+ exports.parseSignatureHeader = parseSignatureHeader;
38
+ exports.timingSafeEqual = timingSafeEqual;
39
+ exports.signWebhookPayload = signWebhookPayload;
40
+ exports.verifyWebhook = verifyWebhook;
41
+ const errors_js_1 = require("./errors.js");
42
+ /**
43
+ * Webhook signature checks.
44
+ *
45
+ * Finn signs every delivery with `X-Finn-Signature: t=<unix seconds>,v1=<hex HMAC-SHA256(secret, "<t>.<raw body>")>`
46
+ * and names the event in `X-Finn-Event`. verifyWebhook() checks the signature in constant time and refuses
47
+ * deliveries whose timestamp is too far from now, so a captured request cannot be replayed later.
48
+ */
49
+ /** Header that carries the signature. */
50
+ exports.WEBHOOK_SIGNATURE_HEADER = 'X-Finn-Signature';
51
+ /** Header that carries the event name. */
52
+ exports.WEBHOOK_EVENT_HEADER = 'X-Finn-Event';
53
+ /** Default largest gap, in seconds, between the signed timestamp and now. */
54
+ exports.DEFAULT_WEBHOOK_TOLERANCE_SECONDS = 300;
55
+ /** The delivery's signature is missing, malformed, wrong or too old. Answer the request with a 400. */
56
+ class FinnWebhookVerificationError extends errors_js_1.FinnSdkError {
57
+ constructor(message) {
58
+ super(message);
59
+ this.name = 'FinnWebhookVerificationError';
60
+ }
61
+ }
62
+ exports.FinnWebhookVerificationError = FinnWebhookVerificationError;
63
+ /** Splits `t=...,v1=...` into its timestamp and v1 signatures. */
64
+ function parseSignatureHeader(header) {
65
+ let timestamp = NaN;
66
+ const signatures = [];
67
+ for (const part of header.split(',')) {
68
+ const i = part.indexOf('=');
69
+ if (i <= 0)
70
+ continue;
71
+ const k = part.slice(0, i).trim();
72
+ const v = part.slice(i + 1).trim();
73
+ if (k === 't' && /^\d+$/.test(v))
74
+ timestamp = Number(v);
75
+ else if (k === 'v1' && v)
76
+ signatures.push(v.toLowerCase());
77
+ }
78
+ return { timestamp, signatures };
79
+ }
80
+ function readHeader(headers) {
81
+ if (!headers)
82
+ return null;
83
+ if (typeof headers.get === 'function')
84
+ return headers.get(exports.WEBHOOK_SIGNATURE_HEADER);
85
+ const want = exports.WEBHOOK_SIGNATURE_HEADER.toLowerCase();
86
+ for (const [k, v] of Object.entries(headers)) {
87
+ if (k.toLowerCase() === want)
88
+ return Array.isArray(v) ? (v[0] ?? null) : (v ?? null);
89
+ }
90
+ return null;
91
+ }
92
+ async function subtleCrypto() {
93
+ const c = globalThis.crypto;
94
+ if (c?.subtle)
95
+ return c.subtle;
96
+ // Node 18 without the global: fall back to node:crypto. The specifier is a variable so bundlers leave it alone.
97
+ const name = 'node:crypto';
98
+ const mod = (await Promise.resolve(`${name}`).then(s => __importStar(require(s))));
99
+ return mod.webcrypto.subtle;
100
+ }
101
+ const encoder = new TextEncoder();
102
+ function hexToBytes(hex) {
103
+ if (hex.length === 0 || hex.length % 2 !== 0 || !/^[0-9a-f]+$/.test(hex))
104
+ return null;
105
+ const out = new Uint8Array(hex.length / 2);
106
+ for (let i = 0; i < out.length; i += 1)
107
+ out[i] = parseInt(hex.slice(i * 2, i * 2 + 2), 16);
108
+ return out;
109
+ }
110
+ /** Compares two byte arrays in time that depends only on their length. */
111
+ function timingSafeEqual(a, b) {
112
+ if (a.length !== b.length)
113
+ return false;
114
+ let diff = 0;
115
+ for (let i = 0; i < a.length; i += 1)
116
+ diff |= a[i] ^ b[i];
117
+ return diff === 0;
118
+ }
119
+ /** Hex HMAC-SHA256 of `<timestamp>.<payload>`, the way Finn signs deliveries. */
120
+ async function signWebhookPayload(secret, timestamp, payload) {
121
+ const mac = await hmac(secret, timestamp, payload);
122
+ return Array.from(mac, (b) => b.toString(16).padStart(2, '0')).join('');
123
+ }
124
+ async function hmac(secret, timestamp, payload) {
125
+ const subtle = await subtleCrypto();
126
+ const key = await subtle.importKey('raw', encoder.encode(secret), { name: 'HMAC', hash: 'SHA-256' }, false, ['sign']);
127
+ const body = typeof payload === 'string' ? encoder.encode(payload) : payload;
128
+ const prefix = encoder.encode(`${timestamp}.`);
129
+ const data = new Uint8Array(prefix.length + body.length);
130
+ data.set(prefix, 0);
131
+ data.set(body, prefix.length);
132
+ return new Uint8Array(await subtle.sign('HMAC', key, data));
133
+ }
134
+ /**
135
+ * Checks a webhook delivery and returns its parsed body. Throws FinnWebhookVerificationError when the signature is
136
+ * missing, malformed or wrong, or the timestamp is more than `toleranceSeconds` (default 300) away from now.
137
+ *
138
+ * app.post('/finn-webhook', express.raw({ type: 'application/json' }), async (req, res) => {
139
+ * const event = await verifyWebhook({ payload: req.body, headers: req.headers, secret: process.env.FINN_WEBHOOK_SECRET! });
140
+ * ...
141
+ * });
142
+ */
143
+ async function verifyWebhook(options) {
144
+ const { payload } = options;
145
+ if (typeof payload !== 'string' && !(payload instanceof Uint8Array)) {
146
+ throw new FinnWebhookVerificationError('payload must be the raw request body (a string or bytes), not parsed JSON: re-serialising changes the bytes that were signed.');
147
+ }
148
+ const secrets = (typeof options.secret === 'string' ? [options.secret] : [...options.secret]).filter((s) => !!s);
149
+ if (secrets.length === 0)
150
+ throw new FinnWebhookVerificationError('Missing webhook signing secret.');
151
+ const header = options.header ?? readHeader(options.headers);
152
+ if (!header)
153
+ throw new FinnWebhookVerificationError(`Missing ${exports.WEBHOOK_SIGNATURE_HEADER} header.`);
154
+ const { timestamp, signatures } = parseSignatureHeader(header);
155
+ if (!Number.isFinite(timestamp) || signatures.length === 0) {
156
+ throw new FinnWebhookVerificationError(`Malformed ${exports.WEBHOOK_SIGNATURE_HEADER} header: expected t=<unix>,v1=<hex>.`);
157
+ }
158
+ const tolerance = options.toleranceSeconds ?? exports.DEFAULT_WEBHOOK_TOLERANCE_SECONDS;
159
+ const now = options.now ?? Math.floor(Date.now() / 1000);
160
+ if (Math.abs(now - timestamp) > tolerance) {
161
+ throw new FinnWebhookVerificationError('Webhook timestamp is outside the tolerance window.');
162
+ }
163
+ const given = signatures.map(hexToBytes).filter((b) => b !== null);
164
+ let ok = false;
165
+ for (const secret of secrets) {
166
+ const expected = await hmac(secret, timestamp, payload);
167
+ // Check every pair, so the time taken does not reveal which one matched.
168
+ for (const sig of given)
169
+ if (timingSafeEqual(expected, sig))
170
+ ok = true;
171
+ }
172
+ if (!ok)
173
+ throw new FinnWebhookVerificationError('Webhook signature does not match.');
174
+ const text = typeof payload === 'string' ? payload : new TextDecoder().decode(payload);
175
+ try {
176
+ return JSON.parse(text);
177
+ }
178
+ catch {
179
+ throw new FinnWebhookVerificationError('Webhook body is not valid JSON.');
180
+ }
181
+ }
@@ -1,5 +1,5 @@
1
1
  import { FinnCore, type FinnOptions } from './core.js';
2
- import { Agents, Approvals, Audiences, Calls, Cases, Chat, Contacts, Deployments, DoNotCall, Finns, PhoneNumbers, Voices, Wallet, type WaitForApprovalOptions } from './resources.js';
2
+ import { Agents, Approvals, Audiences, Calls, Cases, Chat, Contacts, Crm, Deployments, Dialer, DoNotCall, Finns, Organization, PhoneNumbers, Sales, Voices, Wallet, Webhooks, type WaitForApprovalOptions } from './resources.js';
3
3
  import type { ApprovalHold, Schemas } from './types.js';
4
4
  /**
5
5
  * The Finn API client.
@@ -24,6 +24,18 @@ export declare class Finn extends FinnCore {
24
24
  readonly approvals: Approvals;
25
25
  readonly agents: Agents;
26
26
  readonly chat: Chat;
27
+ /** CRM: records, stages, forms, documents, follow-ups, views and imports (`/crm`). */
28
+ readonly crm: Crm;
29
+ readonly dialer: Dialer;
30
+ /** Webhook endpoints, deliveries and event types. */
31
+ readonly webhooks: Webhooks;
32
+ /** The organization, its members, integrations and API keys. */
33
+ readonly organization: Organization;
34
+ /**
35
+ * Sales plays, prospects, drafts and threads.
36
+ * @experimental The Sales API is switched off for every organization; calls answer an error until it is on for yours.
37
+ */
38
+ readonly sales: Sales;
27
39
  constructor(options?: FinnOptions);
28
40
  /** Polls an approval until it is decided (see approvals.wait). */
29
41
  waitForApproval(id: string, options?: WaitForApprovalOptions): Promise<ApprovalHold | Schemas['Approval']>;
@@ -1,5 +1,5 @@
1
1
  import { FinnCore } from './core.js';
2
- import { Agents, Approvals, Audiences, Calls, Cases, Chat, Contacts, Deployments, DoNotCall, Finns, PhoneNumbers, Voices, Wallet, } from './resources.js';
2
+ import { Agents, Approvals, Audiences, Calls, Cases, Chat, Contacts, Crm, Deployments, Dialer, DoNotCall, Finns, Organization, PhoneNumbers, Sales, Voices, Wallet, Webhooks, } from './resources.js';
3
3
  /**
4
4
  * The Finn API client.
5
5
  *
@@ -23,6 +23,11 @@ export class Finn extends FinnCore {
23
23
  this.approvals = new Approvals(this);
24
24
  this.agents = new Agents(this);
25
25
  this.chat = new Chat(this);
26
+ this.crm = new Crm(this);
27
+ this.dialer = new Dialer(this);
28
+ this.webhooks = new Webhooks(this);
29
+ this.organization = new Organization(this);
30
+ this.sales = new Sales(this);
26
31
  }
27
32
  /** Polls an approval until it is decided (see approvals.wait). */
28
33
  waitForApproval(id, options) {
@@ -1,6 +1,6 @@
1
1
  import type { FinnResponse, HttpMethod, Operation, PathsFor, RequestArgs, RequestOptions, ResultOf } from './types.js';
2
2
  export declare const DEFAULT_BASE_URL = "https://api.hirefinn.ai/v1";
3
- export declare const SDK_VERSION = "0.1.0";
3
+ export declare const SDK_VERSION = "0.3.0";
4
4
  export interface FinnOptions {
5
5
  /** `finn_live_...` org key, `finn_test_...` test key, or an OAuth `finn_oat_...` token. Defaults to env FINN_API_KEY. */
6
6
  apiKey?: string;
@@ -10,7 +10,11 @@ export interface FinnOptions {
10
10
  org?: string;
11
11
  /** Pins the API version (Finn-Version header), a date such as `2026-11-01`. */
12
12
  version?: string;
13
- /** Retries after the first attempt, on network errors, 408, 429 and 5xx. Default 2. */
13
+ /**
14
+ * Retries after the first attempt, on network errors, 408, 429, 502, 503 and 504. Only GET/HEAD/OPTIONS/PUT/DELETE
15
+ * are retried freely; a POST or PATCH is retried only when it carries an Idempotency-Key and its route dedupes by
16
+ * that key (IDEMPOTENT_WRITE_ROUTES). Default 2.
17
+ */
14
18
  maxRetries?: number;
15
19
  /** Timeout per attempt in milliseconds. Default 60000. */
16
20
  timeoutMs?: number;
@@ -31,6 +35,14 @@ export interface FinnOptions {
31
35
  }
32
36
  /** Writes that get an automatic Idempotency-Key (when autoIdempotency is on). */
33
37
  export declare const AUTO_IDEMPOTENCY_ROUTES: ReadonlySet<string>;
38
+ /**
39
+ * POST/PATCH routes where the API dedupes by Idempotency-Key (a retry with the same key and body replays the first
40
+ * answer). Only these writes are retried, and only when they carry a key: other routes ignore the header, so a retry
41
+ * after a timeout could create a second resource. `*` matches the rest of the path.
42
+ */
43
+ export declare const IDEMPOTENT_WRITE_ROUTES: readonly string[];
44
+ /** True when the API dedupes this write by Idempotency-Key. `path` may be a template or a filled-in path. */
45
+ export declare function honoursIdempotencyKey(method: string, path: string): boolean;
34
46
  /** A new random Idempotency-Key (a UUID v4). */
35
47
  export declare function idempotencyKey(): string;
36
48
  /** Untyped request input, for paths the spec does not have yet. */
package/dist/esm/core.js CHANGED
@@ -12,7 +12,7 @@ var __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (
12
12
  var _FinnCore_apiKey, _FinnCore_fetch, _FinnCore_defaultHeaders, _FinnCore_sleep;
13
13
  import { FinnConnectionError, FinnError, FinnSdkError, FinnTimeoutError } from './errors.js';
14
14
  export const DEFAULT_BASE_URL = 'https://api.hirefinn.ai/v1';
15
- export const SDK_VERSION = '0.1.0';
15
+ export const SDK_VERSION = '0.3.0';
16
16
  /** Writes that get an automatic Idempotency-Key (when autoIdempotency is on). */
17
17
  export const AUTO_IDEMPOTENCY_ROUTES = new Set([
18
18
  'post /calls',
@@ -23,7 +23,42 @@ export const AUTO_IDEMPOTENCY_ROUTES = new Set([
23
23
  'post /chat/conversations/{id}/messages',
24
24
  'post /agents',
25
25
  'post /agents/{id}/cases',
26
+ 'post /webhook_endpoints',
26
27
  ]);
28
+ /**
29
+ * POST/PATCH routes where the API dedupes by Idempotency-Key (a retry with the same key and body replays the first
30
+ * answer). Only these writes are retried, and only when they carry a key: other routes ignore the header, so a retry
31
+ * after a timeout could create a second resource. `*` matches the rest of the path.
32
+ */
33
+ export const IDEMPOTENT_WRITE_ROUTES = [
34
+ 'post /calls',
35
+ 'post /phone_numbers',
36
+ 'post /deployments',
37
+ 'post /deployments/inbound',
38
+ 'post /chat/conversations',
39
+ 'post /chat/conversations/{id}/messages',
40
+ 'post /agents',
41
+ 'post /agents/{id}/cases',
42
+ 'post /crm/*',
43
+ 'patch /crm/*',
44
+ 'post /sales/plays/{slug}/run',
45
+ 'post /sales/drafts/{id}/skip',
46
+ 'post /webhook_endpoints',
47
+ ];
48
+ const IDEMPOTENT_WRITE_MATCHERS = IDEMPOTENT_WRITE_ROUTES.map((route) => {
49
+ const [method, path] = route.split(' ');
50
+ const body = path
51
+ .split('/')
52
+ .map((seg) => (seg === '*' ? '.+' : /^\{[^}]+\}$/.test(seg) ? '[^/]+' : seg.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')))
53
+ .join('/');
54
+ return { method: method.toUpperCase(), re: new RegExp(`^${body}/?$`) };
55
+ });
56
+ /** True when the API dedupes this write by Idempotency-Key. `path` may be a template or a filled-in path. */
57
+ export function honoursIdempotencyKey(method, path) {
58
+ const m = method.toUpperCase();
59
+ const p = path.split('?')[0];
60
+ return IDEMPOTENT_WRITE_MATCHERS.some((x) => x.method === m && x.re.test(p));
61
+ }
27
62
  const SAFE_TO_RETRY_METHODS = new Set(['GET', 'HEAD', 'OPTIONS', 'PUT', 'DELETE']);
28
63
  const RETRY_BASE_DELAY_MS = 500;
29
64
  const RETRY_MAX_DELAY_MS = 8000;
@@ -137,7 +172,8 @@ export class FinnCore {
137
172
  for (const [k, v] of Object.entries(options.headers ?? {}))
138
173
  headers.set(k, v);
139
174
  headers.set('Authorization', `Bearer ${__classPrivateFieldGet(this, _FinnCore_apiKey, "f")}`);
140
- const canRetry = SAFE_TO_RETRY_METHODS.has(method) || headers.has('Idempotency-Key');
175
+ // Idempotent methods always; a POST/PATCH only with a key on a route that dedupes by it.
176
+ const canRetry = SAFE_TO_RETRY_METHODS.has(method) || (headers.has('Idempotency-Key') && honoursIdempotencyKey(method, req.path));
141
177
  const maxRetries = canRetry ? Math.max(0, options.maxRetries ?? this.maxRetries) : 0;
142
178
  const timeoutMs = options.timeoutMs ?? this.timeoutMs;
143
179
  for (let attempt = 0;; attempt += 1) {
@@ -235,7 +271,7 @@ function isRetryable(error) {
235
271
  return true;
236
272
  if (error.status === 409)
237
273
  return error.code === 'idempotency_in_progress';
238
- return error.status === 500 || error.status === 502 || error.status === 503 || error.status === 504;
274
+ return error.status === 502 || error.status === 503 || error.status === 504;
239
275
  }
240
276
  function backoffMs(attempt) {
241
277
  const base = Math.min(RETRY_MAX_DELAY_MS, RETRY_BASE_DELAY_MS * 2 ** attempt);