@medalsocial/sdk 1.5.0 → 1.6.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,6 +1,6 @@
1
1
  # Medal Social SDK
2
2
 
3
- TypeScript SDK for the [Medal Social](https://medalsocial.com) API. Manage posts, emails, contacts, deals, helpdesk conversations, webhooks, and GDPR compliance programmatically.
3
+ TypeScript SDK for the [Medal Social](https://medalsocial.com) API. Manage posts, emails, contacts, deals, helpdesk conversations, webhooks, company/site scans, and GDPR compliance programmatically.
4
4
 
5
5
  ## Install
6
6
 
@@ -236,6 +236,22 @@ await medal.gdpr.cookieConsent({
236
236
  });
237
237
  ```
238
238
 
239
+ ### Scan
240
+
241
+ ```ts
242
+ // Find the company in the Norwegian registry (typeahead)
243
+ const { data: hits } = await medal.scan.companies('Eksempel Bygg');
244
+
245
+ // Queue a scan — exactly one of url / orgnr / name
246
+ const { data: job } = await medal.scan.create({ orgnr: hits[0].orgnr });
247
+
248
+ // Poll until it settles (~30 s; done or failed)
249
+ const finished = await medal.scan.waitForResult(job.id);
250
+ if (finished.status === 'done' && finished.result) {
251
+ console.log(finished.result.nettskaar, finished.result.subScores);
252
+ }
253
+ ```
254
+
239
255
  ### Helpdesk
240
256
 
241
257
  ```ts
@@ -269,6 +285,19 @@ const { data: reply } = await medal.helpdesk.replies.create(
269
285
  );
270
286
  ```
271
287
 
288
+ **A `201` from `replies.create` means accepted, not delivered.** The channel hand-off happens asynchronously afterwards. Each message carries `delivery_status` (`pending` | `sent` | `delivered` | `failed`) and `delivery_error`, both `null` for inbound messages and internal notes (neither is ever sent to a channel):
289
+
290
+ ```ts
291
+ const { data: messages } = await medal.helpdesk.conversations.messages('conv_id');
292
+ for (const message of messages) {
293
+ if (message.delivery_status === 'failed') {
294
+ console.error(message.id, message.delivery_error);
295
+ }
296
+ }
297
+ ```
298
+
299
+ Subscribe to `helpdesk.message_delivery_updated` for the same values pushed instead of polled.
300
+
272
301
  ### Webhooks
273
302
 
274
303
  ```ts
@@ -298,6 +327,8 @@ await medal.webhooks.test(endpoint.id); // queues a 'test.ping' delivery
298
327
 
299
328
  Failed deliveries retry with exponential backoff (up to 6 attempts) before being dead-lettered.
300
329
 
330
+ `deliveries()` returns the most recent attempts only — it takes a `limit` and is **not** cursor-paginated. A delivery's `id` is the same value sent as the `X-Medal-Delivery-Id` and `Idempotency-Key` headers on the outbound request, so you can join your own receiving log to this listing exactly. Deliveries **never carry payload bodies** (payloads can contain customer PII); instead each one exposes correlation fields — `resource_id`, `conversation_id`, `message_id`, `connection_ref`, `channel`, `channel_connection_id` — that let you look the subject up through the regular API. All six are nullable and **fail closed to `null`** when no canonical event exists for the delivery (e.g. `test.ping` deliveries, or events that have aged out of retention), so always null-check them.
331
+
301
332
  ### Channels (partner connect)
302
333
 
303
334
  Mint hosted connect links that let an external person — e.g. a partner's operator, with no Medal account — attach a channel account (today `telegram_inbox`) to the workspace's helpdesk, then track and disconnect the resulting connections. Requires the `channel.connect.manage` scope; OAuth callers additionally need the workspace `admin` role for the writes.
@@ -324,10 +355,123 @@ await medal.channels.connectLinks.revoke(link.id);
324
355
  const { data: connections } = await medal.channels.connections.list();
325
356
  // state: 'connecting' | 'active' | 'disconnected' | 'disabled'
326
357
  await medal.channels.connections.disconnect(connections[0].id);
358
+
359
+ // Both listings are cursor-paginated (limit defaults to 50, capped at 100)
360
+ let cursor: string | undefined;
361
+ do {
362
+ const page = await medal.channels.connections.list({ limit: 100, cursor });
363
+ for (const connection of page.data) console.log(connection.id, connection.state);
364
+ cursor = page.pagination.has_more ? page.pagination.next_cursor ?? undefined : undefined;
365
+ } while (cursor);
327
366
  ```
328
367
 
368
+ Filters (`channel_type`, `status`) are applied **within** each page, so a page may hold fewer than `limit` items while `pagination.has_more` is still `true` — drive the loop off `has_more`, never off the item count.
369
+
329
370
  When the person completes the hosted sign-in, the link flips to `consumed` and your webhook endpoint receives `helpdesk.channel_connected` (subscribe via the Webhooks resource above); disconnects emit `helpdesk.channel_disconnected` with a `reason`. Inbound messages on the connected account then flow into the helpdesk — consume them via `helpdesk.message_received` and reply with `medal.helpdesk.replies.create`.
330
371
 
372
+ ### Capability confirmations
373
+
374
+ Medal's confirmable write routes require **both** an `Idempotency-Key` and an `X-Capability-Confirmation` token whenever the calling credential holds the capability scope *directly* — which is the case for every correctly-scoped partner key and OAuth grant. (API keys carrying only legacy scopes are exempt.) Affected routes and their capability ids:
375
+
376
+ | Capability id | Route |
377
+ |---|---|
378
+ | `channel.connect_link.create.execute` | `POST /api/v1/channels/connect-links` |
379
+ | `channel.connect_link.revoke.execute` | `DELETE /api/v1/channels/connect-links/{id}` |
380
+ | `channel.connection.disconnect.execute` | `DELETE /api/v1/channels/connections/{id}` |
381
+ | `helpdesk.conversation.reply.execute` | `POST /api/v1/helpdesk/replies` |
382
+ | `helpdesk.conversation.update.execute` | `PATCH /api/v1/helpdesk/conversations/{id}` |
383
+ | `helpdesk.webhook.create.execute` | `POST /api/v1/webhooks` |
384
+ | `helpdesk.webhook.update.execute` | `PATCH /api/v1/webhooks/{id}` |
385
+ | `helpdesk.webhook.delete.execute` | `DELETE /api/v1/webhooks/{id}` |
386
+
387
+ These are exported as `CAPABILITY_IDS` (a typed union via `CapabilityId`) and `CAPABILITY_ROUTES`.
388
+
389
+ #### Explicit flow
390
+
391
+ ```ts
392
+ const idempotencyKey = crypto.randomUUID();
393
+
394
+ const { data: confirmation } = await medal.capabilityConfirmations.create({
395
+ capability_id: 'channel.connect_link.create.execute',
396
+ idempotency_key: idempotencyKey, // the token is bound to this exact key
397
+ preview_summary: 'Mint a Telegram connect link for Acme Support',
398
+ user_approved: true, // a human on your side approved this action
399
+ });
400
+
401
+ const { data: link } = await medal.channels.connectLinks.create(
402
+ { channel_type: 'telegram_inbox', label: 'Acme Support' },
403
+ { idempotencyKey, capabilityConfirmation: confirmation.confirmation_token },
404
+ );
405
+ ```
406
+
407
+ For an id-bound route, pass `path_params` so the token binds to the concrete path:
408
+
409
+ ```ts
410
+ const { data: confirmation } = await medal.capabilityConfirmations.create({
411
+ capability_id: 'channel.connection.disconnect.execute',
412
+ path_params: { id: connectionId },
413
+ idempotency_key: idempotencyKey,
414
+ preview_summary: `Disconnect ${connectionId} — approved by ${operator.email}`,
415
+ user_approved: true,
416
+ });
417
+
418
+ await medal.channels.connections.disconnect(connectionId, {
419
+ idempotencyKey,
420
+ capabilityConfirmation: confirmation.confirmation_token,
421
+ });
422
+ ```
423
+
424
+ Tokens expire within 15 minutes and are single-purpose: bound to the workspace, the auth subject, the method + path, the capability's required scopes, and the idempotency key.
425
+
426
+ #### Auto-confirm (opt-in, off by default)
427
+
428
+ If your integration already gates these writes behind a real human approval, let the SDK mint both halves for you:
429
+
430
+ ```ts
431
+ const medal = new Medal(process.env.MEDAL_API_KEY, {
432
+ autoConfirmCapabilities: {
433
+ previewSummary: (ctx) => {
434
+ // `ctx` is a discriminated union on `capabilityId` — narrowing gives you
435
+ // the exact request payload type, so the summary can describe the
436
+ // specific action rather than just the route.
437
+ switch (ctx.capabilityId) {
438
+ case 'channel.connect_link.create.execute':
439
+ return `${operator.email} approved a ${ctx.body.channel_type} connect link for "${ctx.body.label}"`;
440
+ case 'helpdesk.conversation.reply.execute':
441
+ return `${operator.email} approved replying to ${ctx.body.conversation_id}: "${ctx.body.body}"`;
442
+ default:
443
+ // DELETE routes have no body; identify them by path instead.
444
+ return `${operator.email} approved ${ctx.method} ${ctx.path}`;
445
+ }
446
+ },
447
+ },
448
+ });
449
+
450
+ // Both headers are minted and attached automatically.
451
+ const { data: link } = await medal.channels.connectLinks.create({
452
+ channel_type: 'telegram_inbox',
453
+ label: 'Acme Support',
454
+ });
455
+ ```
456
+
457
+ The callback receives `{ capabilityId, method, path, pathParams, idempotencyKey, body }`. `body` is the exact object you passed to the SDK method, by reference and unmodified — treat it as read-only, since mutating it would change what is actually sent. Prefer a payload-aware summary: `"Reply to conv_1: 'Refund issued'"` is an audit record, `"POST /api/v1/helpdesk/replies"` is not. The server caps `preview_summary` at 4000 characters, so summarise the payload rather than serialising it wholesale.
458
+
459
+ > **Read before enabling.** Every minted token carries `user_approved: true`, which asserts to Medal that *a human on your side approved that specific action*, and the `previewSummary` you return is retained as the audit record of what they approved. Enable it only on code paths where that is genuinely true — never to rubber-stamp unattended writes. Returning a blank summary throws rather than asserting an approval with no description.
460
+
461
+ Per-call control:
462
+
463
+ ```ts
464
+ // Opt in for one call only (client default stays off)
465
+ await medal.webhooks.delete(endpointId, {
466
+ autoConfirm: { previewSummary: () => `${operator.email} approved removing ${endpointId}` },
467
+ });
468
+
469
+ // Opt out of a client-level default for one call
470
+ await medal.webhooks.delete(endpointId, { autoConfirm: false });
471
+ ```
472
+
473
+ Auto-confirm never overrides what you supply: if a call already carries both `idempotencyKey` and `capabilityConfirmation`, nothing is minted. If it carries only `idempotencyKey`, that key is reused when binding the token.
474
+
331
475
  ### Workspaces
332
476
 
333
477
  ```ts