@intelligence-cloud/sdk 0.1.1 → 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.
- package/CHANGELOG.md +88 -0
- package/README.md +388 -88
- package/dist/index.cjs +3519 -1130
- package/dist/index.d.cts +1036 -5035
- package/dist/index.d.ts +1036 -5035
- package/dist/index.js +3495 -1116
- package/dist/testing.cjs +1271 -0
- package/dist/testing.d.cts +209 -0
- package/dist/testing.d.ts +209 -0
- package/dist/testing.js +1263 -0
- package/package.json +19 -2
package/README.md
CHANGED
|
@@ -1,13 +1,13 @@
|
|
|
1
1
|
# Intelligence Cloud SDK for TypeScript
|
|
2
2
|
|
|
3
|
-
`@intelligence-cloud/sdk` 0.
|
|
3
|
+
`@intelligence-cloud/sdk` 0.3.0 (changes: `CHANGELOG.md`). The partner API for Node.js 20+ and Next.js server code (route handlers, server actions).
|
|
4
4
|
|
|
5
|
-
- **
|
|
6
|
-
- **
|
|
5
|
+
- **Customers** (administrator login): the account layer, `client.accounts`, creates and maintains a customer on Base User and Base Manager licenses, beside one method per API operation (companies, locations, users, products, connectors, First Alert rules, Insights Hub).
|
|
6
|
+
- **Conversations** (a user's own login): the conversation layer, `client.conversations`, gives a signed-in person their own calls, tasks and alerts; `client.intelligence` reads calls, transcripts, recording links, alerts, tasks and insights; and the After Call and First Alert webhooks.
|
|
7
7
|
|
|
8
8
|
Zero runtime dependencies (uses the global `fetch`). ESM and CommonJS builds with full types.
|
|
9
9
|
|
|
10
|
-
|
|
10
|
+
SDK documentation: overview https://docs.intelligence.cloud/sdk/, quick start https://docs.intelligence.cloud/sdk/quick-start, every helper https://docs.intelligence.cloud/sdk/reference, events https://docs.intelligence.cloud/sdk/events, client options and errors https://docs.intelligence.cloud/sdk/configuration, downloads and versions https://docs.intelligence.cloud/sdk/downloads, testing https://docs.intelligence.cloud/sdk/testing. The API itself: the guide https://docs.intelligence.cloud/api and the API reference https://docs.intelligence.cloud/reference, built from https://docs.intelligence.cloud/openapi.yaml.
|
|
11
11
|
|
|
12
12
|
## Install
|
|
13
13
|
|
|
@@ -17,11 +17,11 @@ npm install @intelligence-cloud/sdk
|
|
|
17
17
|
|
|
18
18
|
The package holds only the compiled SDK and pulls in no dependencies.
|
|
19
19
|
|
|
20
|
-
Alternative, from the source download: it includes a packed build, `intelligence-cloud-sdk-0.
|
|
20
|
+
Alternative, from the source download: it includes a packed build, `intelligence-cloud-sdk-0.3.0.tgz`.
|
|
21
21
|
|
|
22
22
|
```bash
|
|
23
23
|
unzip typescript.zip -d vendor-src # creates vendor-src/typescript
|
|
24
|
-
npm install ./vendor-src/typescript/intelligence-cloud-sdk-0.
|
|
24
|
+
npm install ./vendor-src/typescript/intelligence-cloud-sdk-0.3.0.tgz # from your project
|
|
25
25
|
```
|
|
26
26
|
|
|
27
27
|
```ts
|
|
@@ -29,6 +29,8 @@ import { Client } from "@intelligence-cloud/sdk"; // ESM
|
|
|
29
29
|
const { Client } = require("@intelligence-cloud/sdk"); // CommonJS
|
|
30
30
|
```
|
|
31
31
|
|
|
32
|
+
The fake API for your tests is a separate entry, `@intelligence-cloud/sdk/testing` (ESM and CommonJS, with types); the main entry does not contain it. See "Testing your code".
|
|
33
|
+
|
|
32
34
|
To rebuild from source: `npm install && npm run build && npm pack` in the SDK folder (the dev tools stay in that folder). `npm run generate` regenerates the types and operation table from `openapi.yaml` (download it from https://docs.intelligence.cloud/openapi.yaml and pass its path: `node scripts/generate.mjs openapi.yaml`).
|
|
33
35
|
|
|
34
36
|
## Credentials
|
|
@@ -39,34 +41,41 @@ Use one client per credential:
|
|
|
39
41
|
|
|
40
42
|
| Client | Login | For |
|
|
41
43
|
|---|---|---|
|
|
42
|
-
| Admin (`IC_ADMIN_EMAIL`, `IC_ADMIN_PASSWORD` in the examples) | a reseller admin
|
|
43
|
-
| Data (`
|
|
44
|
+
| Admin (`IC_ADMIN_EMAIL`, `IC_ADMIN_PASSWORD` in the examples) | a reseller admin login (`reseller_admin`) | `client.accounts`, `client.companies`, `client.users`, … |
|
|
45
|
+
| Data (`IC_USER_EMAIL`, `IC_USER_PASSWORD` in the examples) | a frontline login (`frontline_user`), a person's own or an integration user mapped to the lines you need | `client.conversations` and `client.intelligence` (calls, alerts, tasks, insights) |
|
|
44
46
|
|
|
45
|
-
Admin logins get empty lists from the conversation-data endpoints by design. The intelligence helpers check the role once and throw `FrontlineRequiredError` instead of returning nothing.
|
|
47
|
+
Admin logins get empty lists from the conversation-data endpoints by design. The intelligence helpers check the role once and throw `FrontlineRequiredError` instead of returning nothing; `client.conversations` throws `WrongLoginError`, and `client.accounts` throws it for a user login.
|
|
46
48
|
|
|
47
49
|
```ts
|
|
48
50
|
const ic = new Client({
|
|
49
|
-
email: process.env.
|
|
50
|
-
password: process.env.
|
|
51
|
+
email: process.env.IC_USER_EMAIL!,
|
|
52
|
+
password: process.env.IC_USER_PASSWORD!,
|
|
51
53
|
// baseUrl: "https://app.intelligence.cloud/api/v1", (default; https only, plain http for localhost only)
|
|
52
54
|
// timeout: 30, (seconds)
|
|
53
55
|
// tokenStore: new FileTokenStore("/var/lib/my-app/ic-tokens.json"), (default: memory)
|
|
54
56
|
// loginRateLimitWait: 60, (seconds to wait once on a sign-in 429; 0 throws at once)
|
|
55
57
|
// keepUnknownFields: false, (true keeps fields the reference doesn't list yet)
|
|
58
|
+
// deadline: 120, (seconds one API request may take in all: sign-in, renewal, retries and waits included; see "Retries")
|
|
59
|
+
// maxRetries: 3,
|
|
60
|
+
// sleep, clock: test hooks (see below)
|
|
61
|
+
// maskNumbers: true, (client.conversations shows caller numbers as their last four digits; false shows them in full)
|
|
62
|
+
// appUrl: "https://app.intelligence.cloud", (links on call and alert briefs; https only)
|
|
56
63
|
// userAgent: "riverbend-bi-sync/1.0",
|
|
57
64
|
});
|
|
58
65
|
```
|
|
59
66
|
|
|
60
67
|
If you pass your own `fetch`, keep certificate verification on.
|
|
61
68
|
|
|
69
|
+
Two options are **test hooks**: `sleep` (default a `setTimeout` wait, in milliseconds) is called for every wait (retries, Retry-After, connector checks), and `clock` (default `performance.now`, milliseconds) is read for the deadline. Pass your own to run waits instantly or drive time in a test (`@intelligence-cloud/sdk/testing` passes a no-op `sleep`). `timeout` is the per-attempt HTTP timeout; it is not the connector settle timeout, which `ConnectorSpec.timeout` sets (default 600 seconds).
|
|
70
|
+
|
|
62
71
|
`keepUnknownFields: true` passes on response fields the reference doesn't list yet, so you can use a new field before you update the SDK. It applies to the customer-lifecycle (admin) reads: `/me`, sign-in and every conversation-data read (calls, transcripts, alerts, tasks, insights) always keep only the documented fields, and the one-time sign-in link is never passed on.
|
|
63
72
|
|
|
64
73
|
### How the client signs in
|
|
65
74
|
|
|
66
75
|
- It signs in on the first call and keeps the access and refresh tokens in its token store.
|
|
67
76
|
- It renews the access token before it expires and once after a 401. Refresh tokens are **single use**: the SDK marks the old one spent before sending it and stores the new pair before using it. Renewals are serialised, so concurrent calls share one refresh.
|
|
68
|
-
- Sign-in is rate limited. On a 429 at sign-in the client waits `loginRateLimitWait`
|
|
69
|
-
- A
|
|
77
|
+
- Sign-in is rate limited (5 a minute). On a 429 at sign-in the client waits `Retry-After` once, but only when it fits in `loginRateLimitWait` (60 seconds): a longer one throws `RateLimitError` at once with `retryAfter`. Set `loginRateLimitWait` to 0 inside a web request to fail at once. Sign-in is also retried after a failure that never left or a 5xx, but not after a timeout or reset once the request was sent (see "Retries").
|
|
78
|
+
- A refresh token is sent again **only** after a 429 or a failure where the request provably never left this machine. After a 5xx, a failure after the request left, or an unreadable answer the client signs in instead: sending a used refresh token ends every session of the login. See "Retries" for which failures count as "never left".
|
|
70
79
|
- An integration user with MFA on gets `MfaRequiredError`: "Integration users need MFA off for their company. API keys arrive in December 2026."
|
|
71
80
|
- A sign-in with an expired password throws `PasswordExpiredError`: a person must set a new password for the integration user in the app; then update your secret store.
|
|
72
81
|
|
|
@@ -88,10 +97,23 @@ The client signs in and renews inside `withLock`, and re-reads the store first,
|
|
|
88
97
|
|
|
89
98
|
## Quick start: conversation intelligence
|
|
90
99
|
|
|
100
|
+
The samples in this README use top-level `await`. That needs an ES module project (`"type": "module"` in `package.json`, or a `.mjs` file); otherwise wrap them in an async function. In a CommonJS project:
|
|
101
|
+
|
|
102
|
+
```js
|
|
103
|
+
const { Client } = require("@intelligence-cloud/sdk");
|
|
104
|
+
|
|
105
|
+
async function main() {
|
|
106
|
+
const ic = new Client({ email: process.env.IC_USER_EMAIL, password: process.env.IC_USER_PASSWORD });
|
|
107
|
+
await ic.requireFrontline();
|
|
108
|
+
// ... the rest of the sample
|
|
109
|
+
}
|
|
110
|
+
main().catch((e) => { console.error(e); process.exit(1); });
|
|
111
|
+
```
|
|
112
|
+
|
|
91
113
|
```ts
|
|
92
114
|
import { Client } from "@intelligence-cloud/sdk";
|
|
93
115
|
|
|
94
|
-
const ic = new Client({ email: process.env.
|
|
116
|
+
const ic = new Client({ email: process.env.IC_USER_EMAIL!, password: process.env.IC_USER_PASSWORD! });
|
|
95
117
|
await ic.requireFrontline();
|
|
96
118
|
|
|
97
119
|
const since = new Date(Date.now() - 24 * 3600 * 1000);
|
|
@@ -183,35 +205,50 @@ Each processed call at the location is POSTed to the URL (`type: "end_of_call_su
|
|
|
183
205
|
- Answer 2xx within 2 seconds and do the work after responding. Redirects count as failures.
|
|
184
206
|
- Answer 2xx to event types you don't handle (`isUnknownEvent`) and ignore them. Answer 400 only for a body that isn't JSON, 413 for a body over 256 KB, 404 for a wrong token.
|
|
185
207
|
- Treat the event as a notification: read the call with `getCall(event.call.id)` before you write anything from it into another system. A 404 means drop it.
|
|
186
|
-
- Three attempts in all, then the delivery is dropped.
|
|
208
|
+
- Three attempts in all, then the delivery is dropped.
|
|
209
|
+
- **Store by call id and upsert.** The same call can arrive again (retries, calls with several legs), and **a later delivery can carry newer data**: it replaces the earlier one. Store each delivery durably under `upsertKey(event)` (the call id) before acknowledging. Never drop a delivery because its call id was seen before.
|
|
210
|
+
- **Check, compare, store, remember.** `Deduplicator.seen(event)` only checks whether this exact delivery was remembered; `remember(event)` records it and is called **after** your durable write. In order: parse, then if `seen(event)` answer 2xx, then load what is stored under `upsertKey(event)`, then if `isOlder(event, stored)` call `remember(event)` and answer 2xx without storing, else upsert, then `remember(event)`, then answer 2xx. If the write fails, answer 5xx and do not remember: the sender's retry is then processed. `isOlder(event, stored)` compares the events' own `timestamp` fields (`stored` is the stored event, its body or its timestamp; false when either has none). **Ordering relies on the event's timestamp; when two deliveries carry the same timestamp, the later arrival wins.** Without the comparison, a v1 that failed to store and is retried after v2 was stored would overwrite newer data with older. An exact re-delivery is the same event type, location and call id with the same content (a SHA-256 of the canonical JSON body, because the payload carries no version marker); a later delivery with newer data is not seen. **Limits of the check.** Two identical deliveries that arrive at the same moment can both be "not seen" (neither is remembered yet): that is harmless because storing is an upsert. A delivery that differs from an earlier one only in a field the published event does not list is treated as a duplicate, because unlisted fields are dropped before the key is made. `seen` and `remember` take an event, a parsed body or the raw request body (which must be I-JSON: valid UTF-8, no lone surrogates, no repeated key in one object, only finite numbers; the parsers refuse anything else); a plain id is refused (`InvalidRequestError`), because an id alone cannot tell newer data apart.
|
|
211
|
+
- The default store is **in memory and per process**: with more than one worker or process it misses deliveries the others remembered. Pass a shared store with `has(key)` and `add(key)` (both may be async), for example over a key-value store your workers share: `new Deduplicator({ store: { has: async (k) => (await kv.exists("ic:" + k)) === 1, add: async (k) => void (await kv.set("ic:" + k, "1", { expiresIn: 86400 })) } })`, where `kv` is your own client.
|
|
187
212
|
|
|
188
213
|
```ts
|
|
189
|
-
import { Deduplicator, isUnknownEvent, parseAfterCallEvent } from "@intelligence-cloud/sdk";
|
|
214
|
+
import { Deduplicator, isOlder, isUnknownEvent, parseAfterCallEvent, upsertKey } from "@intelligence-cloud/sdk";
|
|
190
215
|
|
|
191
216
|
const dedup = new Deduplicator(); // in-memory LRU; pass { store } for a shared store (a database or cache)
|
|
192
217
|
|
|
193
218
|
const event = parseAfterCallEvent(rawBody); // WebhookPayloadError (400) / PayloadTooLargeError (413)
|
|
194
219
|
if (isUnknownEvent(event)) return; // a type you don't handle: answer 2xx
|
|
195
|
-
if (
|
|
196
|
-
|
|
220
|
+
if (event.is_test || (await dedup.seen(event))) return; // an exact re-delivery you already stored: answer 2xx
|
|
221
|
+
try {
|
|
222
|
+
const stored = await db.get(upsertKey(event)); // what you stored for this call, or null
|
|
223
|
+
if (stored && isOlder(event, stored.timestamp)) {
|
|
224
|
+
await dedup.remember(event); // an older delivery arriving late: keep the newer data
|
|
225
|
+
return; // answer 2xx
|
|
226
|
+
}
|
|
227
|
+
await db.upsert(upsertKey(event), event); // durable, keyed on the call id: newer data replaces older
|
|
228
|
+
} catch {
|
|
229
|
+
return new Response(null, { status: 503 }); // not remembered: the sender's retry is processed
|
|
197
230
|
}
|
|
231
|
+
await dedup.remember(event); // only after the write
|
|
232
|
+
// answer 2xx; read the call later with getCall(event.call.id)
|
|
198
233
|
```
|
|
199
234
|
|
|
200
|
-
`parseAfterCallEvent(body, { maxBytes })` refuses bodies over `MAX_EVENT_BYTES` (262144).
|
|
235
|
+
`parseAfterCallEvent(body, { maxBytes })` refuses bodies over `MAX_EVENT_BYTES` (262144). The in-memory store keeps the last 10,000 delivery keys. The key is a SHA-256 of the RFC 8785 (JSON Canonicalization Scheme) text of the event as projected onto the published fields: numbers are IEEE-754 doubles written as in JavaScript, so integers beyond 2^53 collapse to the nearest double by rule, in every SDK language; the key is the same text in the Python and PHP SDKs for the same event (shared test vectors pin it). `examples/after-call-sample.json` is a sample event: post it to your receiver locally, e.g. `curl -X POST http://localhost:3000/api/ic-webhook/$IC_WEBHOOK_TOKEN -H 'Content-Type: application/json' -d @examples/after-call-sample.json`.
|
|
201
236
|
|
|
202
|
-
The Next.js route handler in `examples/nextjs/app/api/ic-webhook/[token]/route.ts` shows the whole receiver: path token, size cap, parse,
|
|
237
|
+
The Next.js route handler in `examples/nextjs/app/api/ic-webhook/[token]/route.ts` shows the whole receiver: path token, size cap, parse, check, compare with what is stored, upsert, remember, respond, then read the call with `after()`.
|
|
203
238
|
|
|
204
239
|
## Receiving the First Alert webhook
|
|
205
240
|
|
|
206
241
|
Webhooks are how your integration hears about new calls and alerts: the After Call webhook for every call, the First Alert webhook for each alert as it fires. Subscribe to them; don't poll the API for new data.
|
|
207
242
|
|
|
208
|
-
The First Alert webhook posts the alert that fired: the alert id, the rule, the location, the call and the time.
|
|
243
|
+
The First Alert webhook posts the alert that fired: the alert id, the rule, the location, the call and the time. **The First Alert payload is not final yet.** `parseFirstAlertEvent` returns a `FirstAlertEvent`: `alertId` (letters, digits, `-` and `_`, at most 128 characters, kept as sent, under `alert_id`, else `alert.id`, else `id`; the first present decides, and anything else is refused), and `rule`, `locationId`, `callId` and `timestamp` when the delivery carries them in the shapes known today; `raw` holds the whole payload. Take the alert id, answer 2xx at once, then fetch the alert and its call with a login that is in every alert group:
|
|
209
244
|
|
|
210
245
|
```ts
|
|
211
|
-
const
|
|
212
|
-
if (
|
|
246
|
+
const event = parseFirstAlertEvent(await request.text()); // WebhookPayloadError (400): no valid alert id
|
|
247
|
+
if (!(await alertDedup.seen(event))) { // a second Deduplicator
|
|
248
|
+
await alertQueue.put(event.alertId); // durable; answer 5xx if this fails
|
|
249
|
+
await alertDedup.remember(event); // after the write
|
|
213
250
|
after(async () => {
|
|
214
|
-
const alert = await ic.getAlert(alertId, { withCall: true }); // null when this login can't see it
|
|
251
|
+
const alert = await ic.getAlert(event.alertId, { withCall: true }); // null when this login can't see it
|
|
215
252
|
if (alert?.id && alert.call_id) await pageOnCallManager(alert.id, alert.call_id); // ids only
|
|
216
253
|
});
|
|
217
254
|
}
|
|
@@ -221,63 +258,133 @@ If your receiver was unavailable, read the window you missed once and skip alert
|
|
|
221
258
|
|
|
222
259
|
```ts
|
|
223
260
|
for await (const a of ic.iterAlerts({ dateFrom: new Date(wentDown.getTime() - 30 * 60_000), dateTo: cameBack })) {
|
|
224
|
-
if (a.id && !
|
|
261
|
+
if (a.id && !handled.has(a.id)) { // your own store of handled alert ids
|
|
262
|
+
handled.add(a.id);
|
|
263
|
+
await handleAlert(a.id);
|
|
264
|
+
}
|
|
225
265
|
}
|
|
226
266
|
```
|
|
227
267
|
|
|
228
|
-
##
|
|
268
|
+
## Account layer: `client.accounts` (admin)
|
|
269
|
+
|
|
270
|
+
A customer is one company with one or more **teams** (each a location in the API) and a **Management** location named `<Company> - Management`.
|
|
271
|
+
|
|
272
|
+
- Each team has a connector to the phone system, five groups (Customer Threats, Upset Customers, Low Sentiment Calls, Insights Hub Access, Insights Hub Weekly Reports) and three alerts, each routed to its group: Customer Threat (priority high, sentiment below -20 and its phrases), Upset Customer (medium, below -20 and its phrases) and Low Sentiment (low, below -40).
|
|
273
|
+
- Management has its own connector, which captures the managers' own lines, and the Insights Hub Weekly Reports group for the company-wide reports. It has no alerts.
|
|
274
|
+
- A **Base User** has After Call on their own line at one team. A **Base Manager** has all three products, their own line at Management, every Base User line of the teams they run, and those teams' groups.
|
|
229
275
|
|
|
230
276
|
```ts
|
|
231
|
-
|
|
277
|
+
import { Client, ConnectorSpec } from "@intelligence-cloud/sdk";
|
|
232
278
|
|
|
233
|
-
const
|
|
234
|
-
|
|
235
|
-
|
|
236
|
-
|
|
237
|
-
|
|
238
|
-
|
|
239
|
-
|
|
240
|
-
|
|
241
|
-
|
|
279
|
+
const admin = new Client({ email: process.env.IC_ADMIN_EMAIL!, password: process.env.IC_ADMIN_PASSWORD! });
|
|
280
|
+
const phoneSystem = ConnectorSpec.netsapiens("https://pbx.example.com/ns-api/v2", "riverbend.example.com", phoneSystemKey);
|
|
281
|
+
|
|
282
|
+
const customer = await admin.accounts.createCustomer({
|
|
283
|
+
companyId: savedCompanyId, // null the first time; store customer.companyId and pass it on re-runs
|
|
284
|
+
companyName: "Riverbend Auto Group",
|
|
285
|
+
admin: { email: "pat.lee@example.com", firstName: "Pat", lastName: "Lee", phoneNumber: "+15555550100" },
|
|
286
|
+
team: { name: "Riverbend - Main", street: "1 River Rd", city: "Springfield", state: "IL", country: "US", zipcode: "62701", vertical: "<vertical id or key>" },
|
|
287
|
+
connector: phoneSystem, // used for the team and for Management
|
|
288
|
+
alerts: { customerThreat: { phrases: threatPhrases }, upsetCustomer: { phrases: upsetPhrases } },
|
|
289
|
+
mfaOff: true, // the company has an integration user
|
|
242
290
|
});
|
|
291
|
+
const team = customer.teams[0]!;
|
|
292
|
+
|
|
293
|
+
await admin.accounts.addBaseUser(customer, { email: "sam.ortiz@example.com", firstName: "Sam", lastName: "Ortiz" }, { team, line: "2101" });
|
|
294
|
+
await admin.accounts.addBaseManager(customer, { email: "dana.cho@example.com", firstName: "Dana", lastName: "Cho" }, { teams: [team], line: "2001" });
|
|
295
|
+
await admin.accounts.activateAlerts(customer); // every team; a team with no manager is listed in the result
|
|
296
|
+
```
|
|
297
|
+
|
|
298
|
+
Optional settings go in one options object as the last argument; names are the camelCase form of the field names in the other SDKs.
|
|
299
|
+
|
|
300
|
+
- **Phrase lists come from you.** The SDK holds none; ask your Tresic contact for them. A customer can be created without them: Low Sentiment and every group are created, `customer.pending` lists `"customerThreat"` and `"upsetCustomer"`, and `setAlerts` creates those alerts when the lists arrive. `AlertSetting` sets `phrases` and `sentimentBelow` (a whole number from -100 to -1); leaving one out keeps what is there.
|
|
301
|
+
- **Safe to re-run.** Every helper finds what exists before it writes; a second run with the same input writes nothing. A company is never adopted by its name alone: pass `companyId` from the first run. Without it, a same-named company is used only when its primary contact email is `admin.email`; otherwise `ConflictError` (`code: "company_name_conflict"`) is thrown before anything is written.
|
|
302
|
+
- **Stops are reported.** A helper that fails part-way throws `AccountError` with `.step`, `.result` (so far) and `.cause`. Run it again with the same input to continue; `changeLicense` and `moveUser` also recognise a person they left part-way. A connector that does not become active stops `createCustomer`, `addTeam` and `setConnector` at the end, once everything else is built: `.step` is `"connectors"` and `.cause` is `ConnectorTimeoutError` or `ConnectorError` (with `stateReason`).
|
|
303
|
+
- **Existing people keep their license.** `addBaseUser`, `addBaseManager` and `addIntegrationUser` refuse (`InvalidRequestError`, before any write) a person already set up with another license; use `changeLicense`.
|
|
304
|
+
- **Alerts start switched off.** `activateAlerts` switches them on for every team. A team does not need a manager: its alerts then show in the app only, and it is listed under `noManager` with the alert groups that have none.
|
|
305
|
+
- **One at a time.** The helpers for one customer run one at a time within a client (each waits for the one before it). Do not run them at the same time from several clients or processes: lists are read, merged and written back, and two writers lose each other's lines.
|
|
306
|
+
- **Alert email is off** for every person the helpers create, managers included. People switch it on in their own settings.
|
|
307
|
+
- **Insights Hub "monitor all numbers" stays off.** The helpers never switch it on and switch it off where they find it on.
|
|
308
|
+
- **Nothing is deleted.** Companies, locations and people are deactivated; connectors are stopped.
|
|
309
|
+
- **Invitations go last.** People are created without one; it is emailed once their products, groups and lines are in place (`invite: false` holds it back; `sendInvitations` sends it later).
|
|
310
|
+
- **Connectors.** `new ConnectorSpec(type, config, { name, timeout })` takes the phone platform as the API names it and that platform's own settings; `ConnectorSpec.netsapiens(apiUrl, domain, apiKey)` is the shortcut for the documented one. Give the key in full each time: it is sent when a connector is created or repaired and is never kept or logged. Any setting whose name contains key, secret, token, password, passwd, pwd, credential or auth is hidden at any depth from `JSON.stringify`, `console.log` / `util.inspect` and `String()`; `spec.config` is for sending: copying it out (spread, `Object.entries`) exposes its values. Setting names `__proto__`, `constructor` and `prototype` are refused. A new connector is checked every 10 seconds until it settles (`active` or `connected`); its status is recorded on the team (`connectorStatus`, `connectorStateReason`). A re-run with a corrected key repairs a connector in `error`; it never creates a second one.
|
|
311
|
+
|
|
312
|
+
| Helper | Does | Returns |
|
|
313
|
+
|---|---|---|
|
|
314
|
+
| `createCustomer(spec)` | Company with all three products, SSO domain claim (optional), first team and Management, connector on each (if given), groups, alerts (switched off), Insights Hub | `Customer` |
|
|
315
|
+
| `getCustomer(companyId)` | Reads the layout back; a layout it does not recognise is listed in `pending` | `Customer` |
|
|
316
|
+
| `addTeam(customer, team, connector, { alerts?, reactivate? })` | A further team with its connector, groups, alerts (copying the first team's phrases and levels unless `alerts` sets them) and Insights Hub | `Team` |
|
|
317
|
+
| `setAlerts(customer, alerts, { team? })` | Phrases and sentiment levels on one team or all; alerts keep their on or off state | rule ids changed |
|
|
318
|
+
| `setConnector(customer, connector, { team? })` | Attaches a phone system to the named team, or the first team and Management; refuses where an active one exists | `Team[]` |
|
|
319
|
+
| `addBaseUser(customer, person, { team, line, invite? })` | After Call, their line on the team's connector, First Alert and Insights Hub lists and the team's managers | `Member` |
|
|
320
|
+
| `addBaseManager(customer, person, { teams, line?, companyReports?, invite? })` | All three products on each team and Management, own line at Management, the teams' lines and groups; `companyReports: true` adds the company-wide reports group | `Member` |
|
|
321
|
+
| `addIntegrationUser(customer, person, { invite? })` | A data-reading user across every team: password sign-in, tagged `department: "integration"`, every line | `Member` |
|
|
322
|
+
| `changeLicense(customer, userId, to, { teams?, line? })` | `"base_manager"` or `"base_user"`, moving their own line between the team and Management | `Member` |
|
|
323
|
+
| `moveUser(customer, userId, { fromTeam, toTeam })` | Moves a Base User's membership and line, or swaps one of a manager's teams; call history stays with the old team | `Member` |
|
|
324
|
+
| `changeLine(customer, userId, old, new)` | A Base User's line: their mapping and the team's lists (a line another Base User still holds stays listed). A manager's own line at Management only | `Member` |
|
|
325
|
+
| `removeUser(customer, userId, { keepLines? })` | Clears groups and lines, then deactivates; `notes` names teams left with no manager in an alert group (alerts are not changed) | `RemovalSummary` (`userId`, `license`, `releasedLines`, `deactivated`, `notes`) |
|
|
326
|
+
| `activateAlerts(customer, { team? })` | Switches alerts on for every team | `AlertActivation` (`switchedOn`, `noManager`: `NoManagerTeam[]`, the teams whose alert groups have no manager, with those groups) |
|
|
327
|
+
| `sendInvitations(customer, { userIds? })` | Sends invitations not yet sent or expired; re-sends to `userIds` | user ids |
|
|
328
|
+
| `listMembers(customer, { license?, team? })` | Everyone, with license (`base_user`, `base_manager`, `integration`, `other`), teams and lines | `Member[]` |
|
|
329
|
+
| `licenseReport(customer)` | People by license and the number of teams (Management not counted) | `LicenseReport` (`baseUser`, `baseManager`, `integration`, `other`, `teams`, `members`) |
|
|
330
|
+
| `syncLines(customer, { dryRun? })` | Makes every line list match the people. Someone with After Call and one line who reads back as `other` keeps their line and is listed under `other` | `LineSyncReport` (`teams`: `TeamLines` by location id, `applied`) |
|
|
331
|
+
| `offboardCustomer(customer, { deactivateCompany? })` | Pauses webhooks, stops every connector, deactivates integration users and the company | `OffboardSummary` |
|
|
332
|
+
|
|
333
|
+
The results have the same field names in every SDK (camelCase here). A `Member` lists **every** team the person is on after the call, not only the teams named in it. A line (extension or number) must be the whole value `+?[0-9*#]{1,32}`: `"21 10"` or `"21-10"` throws `InvalidRequestError` before any request.
|
|
334
|
+
|
|
335
|
+
Every helper that takes `customer` also takes a company id. `team` is a `Team`, its location id or its name. Lines need a **running** connector: a refused mapping throws `AccountError` whose `.cause` is `ExtensionMappingError`, and no invitation is sent. An extension belongs to one location only. A line another location already holds reaches you as **`AccountError` → `ExtensionMappingError` → `ConflictError`** (message "Extension is already monitored at another location.", the clashing numbers on `.extensions`). Use `AccountError.find` instead of walking the chain:
|
|
243
336
|
|
|
244
|
-
|
|
245
|
-
|
|
246
|
-
|
|
247
|
-
|
|
337
|
+
```ts
|
|
338
|
+
try {
|
|
339
|
+
await admin.accounts.addBaseUser(customer, person, { team, line: "2101" });
|
|
340
|
+
} catch (err) {
|
|
341
|
+
if (!(err instanceof AccountError)) throw err;
|
|
342
|
+
const clash = err.find(ConflictError); // undefined when the stop had another cause
|
|
343
|
+
if (clash) console.log("already captured at another location:", clash.extensions);
|
|
344
|
+
}
|
|
248
345
|
```
|
|
249
346
|
|
|
250
|
-
|
|
251
|
-
- **Store the returned `companyId` and pass it on every re-run.** Without it, an existing company is reused only when both its name and its primary contact email match. A same-named company with another contact throws `ConflictError` (`code: "company_name_conflict"`) before anything is written: company names are not unique, and a new customer's users must never land in another customer's company.
|
|
252
|
-
- Users are created **without** an invitation. The workflow maps their lines and sets their products and groups, and only then emails the invitation. If a mapping is refused, `ExtensionMappingError` is thrown and no invitation has been sent. Pass `sendInvitation: false` to invite later with `admin.users.resendInvitation(companyId, userId)`.
|
|
347
|
+
A customer built with 0.1.x is not converted: `getCustomer` lists what its layout is missing in `pending`.
|
|
253
348
|
|
|
254
|
-
|
|
349
|
+
## Conversation layer: `client.conversations` (user login)
|
|
255
350
|
|
|
256
|
-
|
|
257
|
-
|
|
258
|
-
|
|
259
|
-
|
|
260
|
-
|
|
261
|
-
|
|
262
|
-
|
|
263
|
-
|
|
264
|
-
|
|
265
|
-
|
|
266
|
-
|
|
267
|
-
|
|
268
|
-
|
|
269
|
-
|
|
270
|
-
|
|
271
|
-
|
|
272
|
-
|
|
273
|
-
|
|
274
|
-
|
|
275
|
-
|
|
276
|
-
|
|
277
|
-
|
|
278
|
-
|
|
279
|
-
|
|
280
|
-
|
|
351
|
+
Sign in as the person. The platform decides what each call returns: a Base User gets their own calls, a Base Manager their teams'.
|
|
352
|
+
|
|
353
|
+
```ts
|
|
354
|
+
const me = new Client({ email: process.env.IC_USER_EMAIL!, password: process.env.IC_USER_PASSWORD! });
|
|
355
|
+
|
|
356
|
+
for (const brief of await me.conversations.calls()) { // today, newest first
|
|
357
|
+
console.log(String(brief)); // CallBrief(id='…', when='…'): no content
|
|
358
|
+
}
|
|
359
|
+
const history = await me.conversations.callerHistory("5555550142", { limit: 5 });
|
|
360
|
+
const detail = await me.conversations.brief(callId); // summary, key points, tasks, sentiment, topics, alerts
|
|
361
|
+
const tasks = await me.conversations.openTasks();
|
|
362
|
+
const myTeam = (await me.conversations.teams()).find((t) => t.kind === "team")!; // teams first, Management last
|
|
363
|
+
const board = await me.conversations.teamView(myTeam); // for a manager: counts, alerts, open tasks, briefs
|
|
364
|
+
```
|
|
365
|
+
|
|
366
|
+
| Helper | Returns | Limits |
|
|
367
|
+
|---|---|---|
|
|
368
|
+
| `me()`, `teams()` | Who is signed in and the teams they can see: `kind === "team"` first in name order, Management last. `me().lines` is `null`: the API gives a user login no way to read its own lines | |
|
|
369
|
+
| `calls({ day?, since?, until?, team?, number?, search?, limit? = 50 })` | `CallBrief[]`, newest first; default today | window at most 31 days, `limit` at most 200 |
|
|
370
|
+
| `brief(callId)` | One `CallBrief` with key points, tasks, topics and the alerts it raised (read from one page of that day's alerts, so a day with more than 100 alerts can miss some) | no transcript, no recording |
|
|
371
|
+
| `transcript(callId)` | The transcript of one call | one call per request |
|
|
372
|
+
| `recordingLink(callId)` | A `RecordingLink` that expires (`null` without a recording); the SDK never downloads the audio | |
|
|
373
|
+
| `callerHistory(number, { limit? = 10 })` | Recent briefs for one caller (last 31 days) | `limit` at most 50 |
|
|
374
|
+
| `openTasks({ due?, team? })` | Open tasks with the id of the call each came from | up to 200 |
|
|
375
|
+
| `alerts({ since?, until?, team?, limit? = 50 })` | `AlertBrief[]` on this person's teams. `status` throws `InvalidRequestError` and `holder` is `null`: the API has no alert status or holder yet | as `calls` |
|
|
376
|
+
| `alert(alertId)` | One alert with its call brief (`null` when this login cannot see it) | |
|
|
377
|
+
| `teamView(team, { day?, since?, until? })` | Counts, alerts, open tasks and briefs for one team | as `calls` |
|
|
378
|
+
| `topics({ since?, until?, team? })` | Topic volumes and rising topics (default last 7 days) | needs Insights Hub access |
|
|
379
|
+
| `reference(callOrAlert)` | The id and its page in the app, to pass to another system in place of content | |
|
|
380
|
+
| `parseFirstAlertEvent(payload)` | A `FirstAlertEvent` | |
|
|
381
|
+
|
|
382
|
+
- **Caller numbers are masked** to their last four digits (`***0142`) unless the client was created with `maskNumbers: false`, also where a digit run of five or more appears in a name. Extensions are shown as they are.
|
|
383
|
+
- **Links**: `CallBrief.link`, `AlertBrief.link` and `reference()` give the page in the app, `<app>/after-call-copilot/calls/<id>` or `<app>/first-alert-copilot/alerts/<id>`; they carry only the id. `<app>` is `https://app.intelligence.cloud` unless you pass your own address: `new Client({ …, appUrl: "https://…" })` (https only).
|
|
384
|
+
- **Limits are checked before any request**: a longer window, a larger limit, `number` with `search`, or a date without a time zone offset throws `InvalidRequestError`. Dates are a `Date` or an RFC 3339 string with an offset; `day` is a `Date` (its local calendar day) or `"YYYY-MM-DD"`. "Today" and `day` are midnight to midnight in this machine's time zone, worked out for that date, daylight saving included.
|
|
385
|
+
- `JSON.stringify` of a brief returns all its fields, so do not hand briefs to a JSON logger.
|
|
386
|
+
- **Nothing is logged.** Printing a brief (`String()`, `console.log`) shows its id and time only. Keep summaries, names and numbers out of your own logs too.
|
|
387
|
+
- An administrator login throws `WrongLoginError`. There is no helper that walks every call; for a bounded daily job use `client.intelligence.iterCalls`.
|
|
281
388
|
|
|
282
389
|
## Low-level methods
|
|
283
390
|
|
|
@@ -318,40 +425,68 @@ What the SDK does for you on these:
|
|
|
318
425
|
- **Full-replacement writes** (`enabled_products`, `member_ids`, `group_ids`, rule triggers and groups, First Alert numbers and webhook URL, Insights Hub numbers and groups, user number mappings, user locations) have `add*` / `remove*` / `set*` helpers that read, merge, then write.
|
|
319
426
|
- `users.createCompanyUser` always sends an `Idempotency-Key` (a new UUID per call unless you pass `{ idempotencyKey }`) and reuses it on retries. After a 422 it looks the user up by email and fixes the half-created user with PATCH.
|
|
320
427
|
- Webhook test results and connector dry runs never carry the server's error text.
|
|
321
|
-
- `connectors.createConnector`, `reactivateConnector` and `updateConnector` (when it reconnects) wait until the connector is `active
|
|
428
|
+
- `connectors.createConnector`, `reactivateConnector` and `updateConnector` (when it reconnects) wait until the connector is running (`active` or `connected`), and throw `ConnectorError` with `stateReason` (for example `invalid_permissions` for a key without the permissions the connector needs) when it lands in `error`. If it has not settled in time they throw `ConnectorTimeoutError`. `deactivateConnector` waits for `inactive`. They check the status every 10 seconds for up to 10 minutes. Pass `{ wait: false }` to return at once, or `{ timeout, checkInterval }` in seconds.
|
|
322
429
|
- The connector dry run and the webhook tests return only `success` and the HTTP status.
|
|
323
|
-
- `client.intelligence`
|
|
430
|
+
- `client.intelligence` holds the read helpers; the same methods are also on the client itself. `client.accounts` and `client.conversations` are the two layers above.
|
|
431
|
+
|
|
432
|
+
## Retries
|
|
433
|
+
|
|
434
|
+
One policy, the same in every SDK:
|
|
435
|
+
|
|
436
|
+
| Situation | What the client does |
|
|
437
|
+
|---|---|
|
|
438
|
+
| Network failure (no connection, timeout) or 5xx on a read, update, delete, or user create (which carries an idempotency key, reused on every try) | Retries up to `maxRetries` (3) times with exponential backoff and jitter: about 0.5, 1 and 2 seconds plus up to half again |
|
|
439
|
+
| Sign-in | Retried after a failure that provably never left, after a 5xx, and after a 429 whose `Retry-After` is within the wait limit (it waits once). A timeout, a reset or any failure **after** the request was sent is **not** retried: the error is thrown |
|
|
440
|
+
| Token renewal | The refresh token is sent again **only** after a 429 (the server did not use it) or after a failure where the request provably never left this machine (see below). Any other outcome (a 5xx, a failure after the request left, an unreadable answer) may have used it: it is never resent, and the client signs in instead |
|
|
441
|
+
| Network failure or 5xx on any other create | Not retried: the error is thrown, so nothing is created twice |
|
|
442
|
+
| 429 with `Retry-After` within the limit (60 s; for sign-in, `loginRateLimitWait`, default 60 s) | Waits `Retry-After` (backoff when absent or not plain seconds), then retries; sign-in waits once |
|
|
443
|
+
| 429 with `Retry-After` above the limit | Throws `RateLimitError` at once with `retryAfter` set; it never waits first and then fails |
|
|
444
|
+
| 401 on a request | Renews the token once and retries |
|
|
445
|
+
|
|
446
|
+
**Which fetch failures "never left".** Node's `fetch` reports a failure as a `TypeError("fetch failed")` whose `cause` carries a code. The SDK treats a failure as *never left this machine* only when every code found says so. An errno-style code (`ENOTFOUND`, `EAI_AGAIN`, `EAI_FAIL`, `ECONNREFUSED`, `ENETUNREACH`, `EHOSTUNREACH`, `ETIMEDOUT`) counts only when its `syscall` is `connect` or `getaddrinfo`, because the same codes also come from an established socket after the request was written (`syscall` `read` or `write`). Always counted: `UND_ERR_CONNECT_TIMEOUT` (no connection made in time), `ERR_INVALID_URL` and the TLS certificate refusals (`CERT_HAS_EXPIRED`, `DEPTH_ZERO_SELF_SIGNED_CERT`, `SELF_SIGNED_CERT_IN_CHAIN`, `UNABLE_TO_VERIFY_LEAF_SIGNATURE`, `UNABLE_TO_GET_ISSUER_CERT_LOCALLY`, `ERR_TLS_CERT_ALTNAME_INVALID`), all of which stop before the request is written. Everything else *may have left*: an errno-style code without that syscall, a reset or closed socket (`ECONNRESET`, `EPIPE`, `UND_ERR_SOCKET`), a timeout after the connection was made (`UND_ERR_HEADERS_TIMEOUT`, `UND_ERR_BODY_TIMEOUT`, `ETIMEDOUT`, and the SDK's own per-attempt timeout), a body that cannot be read, a failure with no code, or a mix of codes. When in doubt it is "may have left". `NetworkError.requestSent` is `false` only in the first case.
|
|
447
|
+
|
|
448
|
+
**Bounds.** One API request, including the sign-in or token renewal it needs and every retry and wait, never runs past **`deadline`** (default **120 seconds**). When the time left cannot cover the next wait, the client stops at once: `RateLimitError` (with `retryAfter`) after a 429, `NetworkError` with `kind` `"timeout"` after network failures, or the last 5xx as an `ApiError`. Each attempt is aborted after `timeout` (30 s) or the time left, whichever is less. Helpers that make many requests (`createCustomer`) apply the deadline to each request. Connector settle waits are not counted: they have their own `timeout` (600 s). Inside a web request, pass a smaller `deadline` (for example 10), `loginRateLimitWait: 0` and `maxRetries: 1`.
|
|
449
|
+
|
|
450
|
+
**Retry-After** counts only as plain decimal seconds, `[0-9]{1,9}` with an optional fraction (`5`, `1.5`); a date, a sign, an exponent, a space or a number of ten digits is treated as absent. `RateLimitError.retryAfter` is a number of seconds.
|
|
451
|
+
|
|
452
|
+
**Checks first.** Every helper of both layers checks its arguments, types included, before it signs in or sends anything, and before it joins the write queue (the generated methods check the JSON type of every top-level body field against the spec the same way), so a bad argument is refused at once rather than after earlier helpers finish. Bad input throws `InvalidRequestError` with no request made, so it costs no sign-in. An id that goes into a URL (a company, user, call, alert or location id) must be a non-empty string of at most 128 characters (counted as code points) that is not `.` or `..` and has no `/`, `\`, `?`, `#`, `%`, whitespace (nothing is trimmed: a leading or trailing space or newline is refused) or control character (including U+0080 to U+009F and U+FEFF); free text and numbers must be real strings of at most 200 characters. Lists passed as `teams`, `userIds` or `phrases` may be any iterable and are read once.
|
|
324
453
|
|
|
325
454
|
## Filters and validation
|
|
326
455
|
|
|
327
456
|
The API ignores parameters it doesn't know and returns unfiltered data. The SDK accepts only the documented filters and checks them **before** sending:
|
|
328
457
|
|
|
329
|
-
- An unknown filter throws `FilterError
|
|
458
|
+
- An unknown filter throws `InvalidRequestError` (`FilterError` is kept as an alias).
|
|
330
459
|
- Dates: a `Date` or a full RFC 3339 timestamp, always sent as UTC. `2026-11-01` alone is refused; use `2026-11-01T00:00:00Z`. A `Date` passed as `dueOn` is sent as its local calendar date.
|
|
331
460
|
- `numbers`: at most 25, stripped to digits; a North American number with its leading 1 is sent as the last 10 digits (`+1 555-555-0142` → `5555550142`), because some numbers are stored without the 1. `locationIds`: at most 50 (longer query strings are refused before they reach the API).
|
|
332
461
|
- Enum values, UUIDs, page sizes (1–100) and required filters are checked.
|
|
333
462
|
|
|
334
463
|
## Errors
|
|
335
464
|
|
|
465
|
+
The error tree is the same in every SDK language:
|
|
466
|
+
|
|
336
467
|
```
|
|
337
468
|
IntelligenceCloudError
|
|
338
|
-
|
|
339
|
-
│
|
|
340
|
-
│
|
|
341
|
-
│
|
|
342
|
-
│
|
|
343
|
-
│
|
|
344
|
-
|
|
345
|
-
|
|
346
|
-
|
|
347
|
-
|
|
348
|
-
|
|
349
|
-
|
|
350
|
-
|
|
469
|
+
├─ ApiError (status, code, serverMessage, requestId, operationId)
|
|
470
|
+
│ ├─ AuthError (401: sign-in failed, or the token could not be renewed)
|
|
471
|
+
│ │ ├─ MfaRequiredError (the integration user's company has MFA on)
|
|
472
|
+
│ │ └─ PasswordExpiredError
|
|
473
|
+
│ ├─ NotFoundError (404: not found, or outside what this login can see)
|
|
474
|
+
│ ├─ ConflictError (409: duplicate, already active or inactive, extension held elsewhere; .extensions)
|
|
475
|
+
│ ├─ ValidationError (400, 422)
|
|
476
|
+
│ ├─ RateLimitError (429; .retryAfter)
|
|
477
|
+
│ └─ NetworkError (status 0; .kind transport | timeout | decoding; .requestSent; the underlying error is not attached)
|
|
478
|
+
├─ InvalidRequestError (bad input, refused before sending; FilterError is an alias)
|
|
479
|
+
├─ WrongLoginError (the other kind of login is needed; the message says which)
|
|
480
|
+
│ └─ FrontlineRequiredError (client.intelligence asked for conversation data with an admin login)
|
|
481
|
+
├─ ConnectorError (a connector ended in error; .stateReason)
|
|
482
|
+
│ └─ ConnectorTimeoutError (a new connector did not settle in time)
|
|
483
|
+
├─ ExtensionMappingError (numbers not mapped; .userId, .cause)
|
|
484
|
+
├─ AccountError (an account helper stopped part-way; .step, .result, .cause, .find(ErrorClass))
|
|
485
|
+
└─ WebhookPayloadError (a webhook body is not JSON or is malformed: answer 400)
|
|
486
|
+
└─ PayloadTooLargeError (over 256 KB: answer 413)
|
|
351
487
|
```
|
|
352
488
|
|
|
353
|
-
-
|
|
354
|
-
- The API's different error shapes are normalised into `status`, `code` and `requestId`. The exception text (`message`) never carries the server's error text, which can echo phone numbers or names: it reads e.g. `HTTP 422 VALIDATION_ERROR (request_id …)`. The server's text is on `serverMessage`.
|
|
489
|
+
- The API's different error shapes are normalised into `status`, `code` and `requestId`. The exception text (`message`) never carries the server's error text, which can echo phone numbers or names: it reads e.g. `HTTP 422 VALIDATION_ERROR (request_id …)`. The server's text is on `serverMessage`; keep it out of logs.
|
|
355
490
|
- Log `status`, `code` and `requestId`, not exception text or response bodies.
|
|
356
491
|
- The text of a 409 on number mappings is replaced with "Extension is already monitored at another location." and `extensions` lists the requested extensions that were refused.
|
|
357
492
|
- Show your own messages to end users.
|
|
@@ -368,9 +503,174 @@ try {
|
|
|
368
503
|
}
|
|
369
504
|
```
|
|
370
505
|
|
|
506
|
+
## Testing your code
|
|
507
|
+
|
|
508
|
+
The samples here use top-level `await` too: use an ES module project (`"type": "module"`) or wrap them in an async function, as shown under Quick start.
|
|
509
|
+
|
|
510
|
+
`@intelligence-cloud/sdk/testing` is a supported fake API: run your code and CI with no account and no network. `api.client({ role: "admin" | "user", ...options })` returns a real `Client` wired to it.
|
|
511
|
+
|
|
512
|
+
```js
|
|
513
|
+
import assert from "node:assert/strict";
|
|
514
|
+
import { AccountError, ValidationError } from "@intelligence-cloud/sdk";
|
|
515
|
+
import { FakeAPI } from "@intelligence-cloud/sdk/testing";
|
|
516
|
+
|
|
517
|
+
const person = { email: "sam.ortiz@example.com", firstName: "Sam", lastName: "Ortiz" };
|
|
518
|
+
|
|
519
|
+
export async function testAddsABaseUser() {
|
|
520
|
+
const api = new FakeAPI();
|
|
521
|
+
const seeded = await api.seedCustomer(); // "Riverbend Auto Group": fictional data
|
|
522
|
+
const admin = api.client({ role: "admin" });
|
|
523
|
+
const team = seeded.customer.teams[0];
|
|
524
|
+
const member = await admin.accounts.addBaseUser(seeded.customer, person, { team, line: "2109" });
|
|
525
|
+
assert.equal(member.license, "base_user");
|
|
526
|
+
assert.ok(api.writes.some(([method, path]) => method === "POST" && path === `/companies/${seeded.companyId}/users`));
|
|
527
|
+
assert.equal(api.faNumbers(team.locationId).at(-1), "2109");
|
|
528
|
+
const start = api.requests.length;
|
|
529
|
+
await admin.accounts.addBaseUser(seeded.customer, person, { team, line: "2109" });
|
|
530
|
+
assert.deepEqual(api.writesSince(start), []); // safe to re-run
|
|
531
|
+
}
|
|
532
|
+
|
|
533
|
+
export async function testReadsTodaysCalls() {
|
|
534
|
+
const api = new FakeAPI();
|
|
535
|
+
const ids = api.seedCalls(3);
|
|
536
|
+
const briefs = await api.client({ role: "user" }).conversations.calls();
|
|
537
|
+
assert.deepEqual(briefs.map((b) => b.id), ids);
|
|
538
|
+
assert.ok(briefs[0].callerNumber.startsWith("***"));
|
|
539
|
+
}
|
|
540
|
+
|
|
541
|
+
export async function testResumesAfterAStop() {
|
|
542
|
+
const api = new FakeAPI();
|
|
543
|
+
const seeded = await api.seedCustomer();
|
|
544
|
+
const admin = api.client({ role: "admin" });
|
|
545
|
+
const team = seeded.customer.teams[0];
|
|
546
|
+
api.failWrite(2); // the second write of the next call fails
|
|
547
|
+
const err = await admin.accounts.addBaseUser(seeded.customer, person, { team, line: "2109" }).catch((e) => e);
|
|
548
|
+
assert.ok(err instanceof AccountError && err.find(ValidationError));
|
|
549
|
+
const again = await admin.accounts.addBaseUser(seeded.customer, person, { team, line: "2109" });
|
|
550
|
+
assert.equal(again.userId, err.result.userId); // running it again continues
|
|
551
|
+
}
|
|
552
|
+
```
|
|
553
|
+
|
|
554
|
+
| `FakeAPI` | Does |
|
|
555
|
+
|---|---|
|
|
556
|
+
| `new FakeAPI({ connectorOutcome = "active", role = "admin", strict = true })` | A new, empty fake |
|
|
557
|
+
| `client({ role?, asUser?, ...clientOptions })` | A real `Client` (role "admin" or "user"); waits do not sleep unless you pass `sleep`. `fetch` is refused. `asUser` (role "user"): the id or email of a seeded person, so their calls, alerts, tasks and Insights Hub access follow their license and teams; clients for the same person share that login's sessions |
|
|
558
|
+
| `await seedCustomer({ teams = 1, people = true })` | Riverbend Auto Group through the account layer: teams, Management, two Base Users per team, one manager. Returns `SeededCustomer` (`customer`, `companyId`, `baseUsers`, `managers`, `people`: `SeededPerson` with `userId`, `email`, `license`, `teams`, `lines`) |
|
|
559
|
+
| `seedCalls(n = 3, { locationId, day, alerts = true, tasks = true, recording = false, topics = false })` | Fictional calls with details, tasks and alerts (555-01xx numbers), each reaching a seeded Base User's line in turn. `recording: true` adds a recording link (example.com, expires in two hours); `topics: true` fills topic volumes and rising topics. Returns the call ids, newest first |
|
|
560
|
+
| `connectorOutcome` | `"active"`, `"connected"`, `"error"` or `"stuck"` (never settles) for connection attempts made after it is set (a connector created or restarted later); it does not change connectors already waiting |
|
|
561
|
+
| `settleConnector(connectorIdOrLocation, outcome = "active")` | Settle connectors that are waiting: the one with this id, or every waiting one at this location ("active", "connected" or "error") |
|
|
562
|
+
| `failNext({ status, network, signIn, method, path, retryAfter, afterProcessing })` | The next matching request fails once: the next sign-in answers `signIn: "mfa_required"`, `"password_expired"` or `"invalid_credentials"`; or an HTTP status, or `network: "connect"` (never left), `"read_timeout"`, `"write_timeout"` or `"reset"` (the request may have left) or `"undecodable"` (an answer that cannot be read). Each raises the error Node's fetch gives for that failure; `requestSent` is false only for "connect". A status answers **before** the platform acts (a renewal's refresh token is not used); with `afterProcessing: true` the platform acts first (the token is rotated), as a gateway error after processing would. A network failure other than "connect" on a renewal has used its token |
|
|
563
|
+
| `failWrite(nth = 1, status = 400)`, `networkDown(down = true)`, `rateLimit(count = 1, retryAfter = 1)`, `expireAccessTokens()` | Simpler knobs: the nth write fails; no network; 429s; every access token expires (the next call renews) |
|
|
564
|
+
| `requests`, `writes`, `writesSince(start)`, `count(method, pathRegex)`, `resetLog()`, `authLog` | The request log: **every** request the fake received, including those a knob answered, each with `answer` (the HTTP status, or `"network:connect"` and the like), so retries can be counted. Sign-in and renewal attempts are in `authLog` ("login", "refresh", and "refresh_reused" when a used refresh token was sent again, which ends every session of that login, as on the platform) |
|
|
565
|
+
| `products(uid, lid)`, `numbers(uid, connectorId?)`, `faNumbers(lid)`, `ihNumbers(lid)`, `groupMembers(lid, name)` | State to assert on |
|
|
566
|
+
|
|
567
|
+
That table is the whole supported surface; anything else on `FakeAPI` starts with an underscore (or is the client's wiring) and may change.
|
|
568
|
+
|
|
569
|
+
**Strict mode** (`strict: true`) answers with the API's error shape when a request is not what the published spec defines: an unknown path or method (404); an unknown query parameter, or a query value of the wrong type (whole number, true/false), outside its enum or range, or not in its format (uuid, date-time) (400); a body missing a required top-level field, carrying a top-level field the spec does not define, or with a top-level value of the wrong JSON type, outside its enum or not in its format, including each item of a top-level list (422). Formats are the ones the spec names: a whole number is `-?(0|[1-9][0-9]*)`, a date is `YYYY-MM-DD` and a real calendar day, a date-time has seconds, a `T` and `Z` or `±HH:MM` and a real calendar time, a uuid is all lower case or all upper case with hyphens. The spec lists only `netsapiens` as a connector type, so strict mode refuses any other (`strict: false` lets one through). It does **not** check nested objects, rules that join several fields, or how the platform searches and sorts, and it can only refuse what the spec states. Code that passes against it still needs one run against a test company before release.
|
|
570
|
+
|
|
571
|
+
## Upgrading from 0.2
|
|
572
|
+
|
|
573
|
+
- **Connectors in account helpers:** a connector that does not settle, or ends in error, arrives as `AccountError` (step `"connectors"`) whose cause is `ConnectorTimeoutError` or `ConnectorError`, once everything else is built. A 0.2-style `catch (e instanceof ConnectorTimeoutError)` around `addTeam` no longer catches it:
|
|
574
|
+
|
|
575
|
+
```ts
|
|
576
|
+
try {
|
|
577
|
+
await admin.accounts.addTeam(customer, team, connector);
|
|
578
|
+
} catch (err) {
|
|
579
|
+
if (!(err instanceof AccountError)) throw err;
|
|
580
|
+
if (err.find(ConnectorTimeoutError)) { // still settling: run addTeam again later
|
|
581
|
+
// ...
|
|
582
|
+
} else if (err.find(ConnectorError)) { // ended in error: check stateReason, fix the key, run again
|
|
583
|
+
// ...
|
|
584
|
+
} else throw err;
|
|
585
|
+
}
|
|
586
|
+
```
|
|
587
|
+
|
|
588
|
+
The settle timeout is `ConnectorSpec.timeout` (600 s). The client's `timeout` and the `{ timeout }` option of the low-level `connectors.createConnector`, `reactivateConnector` and `deactivateConnector` methods apply only to those methods and HTTP attempts.
|
|
589
|
+
- `Deduplicator.isDuplicate` is gone: `seen(event)` checks, `remember(event)` records after your write (see "Receiving the After Call webhook").
|
|
590
|
+
- A line with a space or a dash is refused before sending; `conversations.teams()` lists Management last.
|
|
591
|
+
- See `CHANGELOG.md` for every breaking change.
|
|
592
|
+
|
|
593
|
+
## Running helpers from more than one process
|
|
594
|
+
|
|
595
|
+
Within one client, the helpers that write run one at a time (each waits for the one before). Across clients and processes nothing serialises them: account helpers read, merge and write whole lists, so two of them changing the same customer at once can each read the old list and write back their own version, and one change is lost; two runs of `createCustomer` for a new customer can create it twice. Run at most one account helper per customer at a time. On one machine, a lock file is enough:
|
|
596
|
+
|
|
597
|
+
```js
|
|
598
|
+
import { open, unlink } from "node:fs/promises";
|
|
599
|
+
|
|
600
|
+
export async function withCustomerLock(companyId, fn) {
|
|
601
|
+
const path = `/tmp/ic-customer-${companyId}.lock`;
|
|
602
|
+
for (;;) {
|
|
603
|
+
try {
|
|
604
|
+
const handle = await open(path, "wx"); // fails while another process holds the lock
|
|
605
|
+
await handle.close();
|
|
606
|
+
break;
|
|
607
|
+
} catch (err) {
|
|
608
|
+
if (err.code !== "EEXIST") throw err;
|
|
609
|
+
await new Promise((r) => setTimeout(r, 200)); // wait for the other process
|
|
610
|
+
}
|
|
611
|
+
}
|
|
612
|
+
try {
|
|
613
|
+
return await fn();
|
|
614
|
+
} finally {
|
|
615
|
+
await unlink(path);
|
|
616
|
+
}
|
|
617
|
+
}
|
|
618
|
+
|
|
619
|
+
await withCustomerLock(companyId, () => admin.accounts.addBaseUser(companyId, person, { team, line: "2101" }));
|
|
620
|
+
```
|
|
621
|
+
|
|
622
|
+
A process that dies while holding the file leaves it behind: delete a lock file older than your longest helper run. Across several machines, use your own database with a lock table keyed by company id: insert the row if it is missing, then lock that row inside a transaction that wraps the helper call. The statements are ordinary SQL (`INSERT ... ON CONFLICT DO NOTHING` or your database's insert-if-missing, then `SELECT ... FOR UPDATE`); `db.transaction` stands for your client's transaction wrapper:
|
|
623
|
+
|
|
624
|
+
```js
|
|
625
|
+
// create table customer_locks (company_id text primary key)
|
|
626
|
+
export async function withCustomerLock(db, companyId, fn) {
|
|
627
|
+
return db.transaction(async (tx) => {
|
|
628
|
+
await tx.run("INSERT INTO customer_locks (company_id) VALUES (?) ON CONFLICT (company_id) DO NOTHING", [companyId]); // insert if missing
|
|
629
|
+
await tx.run("SELECT company_id FROM customer_locks WHERE company_id = ? FOR UPDATE", [companyId]); // waits for any other holder
|
|
630
|
+
return fn(); // the row stays locked until the transaction ends
|
|
631
|
+
});
|
|
632
|
+
}
|
|
633
|
+
```
|
|
634
|
+
|
|
635
|
+
Keep the helper call short enough for your transaction timeout. For a new customer, lock on a key you already have (your own account id) until `createCustomer` returns and you have stored `companyId`.
|
|
636
|
+
|
|
637
|
+
## How many requests
|
|
638
|
+
|
|
639
|
+
Measured against `@intelligence-cloud/sdk/testing` with a fresh client (one `GET /me` included, sign-in not counted); a test pins these numbers. The published limits are **5 requests a second per user, bursts of 20, and 50,000 a day per company**.
|
|
640
|
+
|
|
641
|
+
| Helper | 1-team customer | 10-team customer |
|
|
642
|
+
|---|---|---|
|
|
643
|
+
| `createCustomer` (first run, one team) | 34 | 34 |
|
|
644
|
+
| `addTeam` (the 2nd team; the 10th team) | n/a | 23; 23 (241 for all ten teams) |
|
|
645
|
+
| `createCustomer`, re-run | 18 | 18 |
|
|
646
|
+
| `addBaseUser` (customer passed as a company id) | 36 | 90 |
|
|
647
|
+
| `addBaseManager` (on every team, Customer object) | 32 | 158 |
|
|
648
|
+
| `activateAlerts` (Customer object; company id), rules off before the call | 15; 21 | 105; 120 |
|
|
649
|
+
| `setAlerts` (both phrase alerts, Customer object) | 8 | 62 |
|
|
650
|
+
| `syncLines` (Customer object; company id) | 11; 19 | 65; 100 |
|
|
651
|
+
| `licenseReport` (Customer object; company id) | 8; 16 | 35; 70 |
|
|
652
|
+
| `calls` (one page) | 2 | 2 |
|
|
653
|
+
| `brief` | 3 | 3 |
|
|
654
|
+
|
|
655
|
+
A helper given a company id reads the whole layout first (for a 1-team customer 9 requests: the company, its locations, and each location's groups, rules and connectors, plus the domains); given a `Customer` object it reads only the location list it checks the object against (1 request), plus the groups and rules of each team whose ids it uses (2 per team), so a stale object cannot send a write to the wrong group or rule (a helper that needs a group the team no longer has stops with `InvalidRequestError` before its first write), and passing the object saves 8 requests on a 1-team customer and 35 on a 10-team one for `syncLines` and `licenseReport`. **Worked total:** setting up a ten-team customer end to end with a `Customer` object (create, nine `addTeam`, both phrase alerts, one manager per team, three Base Users per team, activate) takes **2,497 requests**, about **8.3 minutes** at 5 requests a second (a test pins it). If a team was added or stopped elsewhere the object is refreshed in place (`refreshedAt` says when it was last checked). The counts assume a freshly seeded customer with two Base Users per team and one manager, alert rules off before `activateAlerts`, a connector that settles at its first check, and the customer passed as an object to `addTeam`. **Each further 10 seconds a new connector takes to settle adds one request per connector** (one status check). At 5 a second a 10-team `addBaseManager` takes about 30 seconds; the client's retries absorb short 429 bursts.
|
|
656
|
+
|
|
657
|
+
## Examples
|
|
658
|
+
|
|
659
|
+
The examples are in the source download and the source repository, not in the npm package. Each uses the fictional customer Riverbend Auto Group.
|
|
660
|
+
|
|
661
|
+
| File | Shows | Sign-in |
|
|
662
|
+
|---|---|---|
|
|
663
|
+
| `examples/node/basic.mjs` | Sign in, count calls, read one | user |
|
|
664
|
+
| `examples/node/create-customer.mjs` | Create a customer, add a Base User and a Base Manager, switch the alerts on (dry run unless `--apply`; phrase lists from the files in `IC_THREAT_PHRASES_FILE` and `IC_UPSET_PHRASES_FILE`, optional) | administrator |
|
|
665
|
+
| `examples/node/my-day.mjs` | A person's day: today's call briefs, open tasks and alerts, with masked numbers and no content in logs | user (the person's own login) |
|
|
666
|
+
| `examples/nextjs` | An After Call and a First Alert receiver (parse, check, upsert, remember, respond) and a calls page | user (worker) |
|
|
667
|
+
| `examples/after-call-sample.json` | A sample After Call event for local tests | none |
|
|
668
|
+
|
|
669
|
+
Administrator examples read `IC_ADMIN_EMAIL` and `IC_ADMIN_PASSWORD`; the others read `IC_USER_EMAIL` and `IC_USER_PASSWORD`.
|
|
670
|
+
|
|
371
671
|
## Secrets
|
|
372
672
|
|
|
373
|
-
Never log access or refresh tokens, passwords, phone-system keys, webhook URLs or recording links. The SDK logs nothing and never returns the one-time sign-in link the API can include when a user is created.
|
|
673
|
+
Never log access or refresh tokens, passwords, phone-system keys, webhook URLs or recording links. The SDK logs nothing and never returns the one-time sign-in link the API can include when a user is created. A connector's key is sent once and never kept: it is hidden from `JSON.stringify`, `console.log` and `String()` on `ConnectorSpec`, and it is not in any error message. A `RecordingLink` hides its URL the same way.
|
|
374
674
|
|
|
375
675
|
## Build from source
|
|
376
676
|
|