@dinghy-chat/sdk 0.0.0-stage → 0.35.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/LICENSE +21 -0
- package/README.md +135 -2
- package/dist/events.d.ts +25 -0
- package/dist/identity.d.ts +11 -0
- package/dist/index.d.ts +52 -0
- package/dist/index.js +402 -0
- package/dist/openapi.d.ts +5946 -0
- package/dist/request.d.ts +95 -0
- package/dist/resources.d.ts +525 -0
- package/dist/webhooks.d.ts +52 -0
- package/package.json +32 -4
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Dinghy contributors
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1,3 +1,136 @@
|
|
|
1
|
-
#
|
|
1
|
+
# Dinghy SDK
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Call the [Dinghy](https://dinghy.chat) API from your server, a small live support chat you can host yourself. MIT licensed.
|
|
4
|
+
|
|
5
|
+
It has no dependencies. It uses `fetch` and WebCrypto, so it runs on Node 24, Bun, Deno and Cloudflare Workers. Its types come from Dinghy's OpenAPI file. It is for a server: never put an API key or a secret in a browser.
|
|
6
|
+
|
|
7
|
+
## Install
|
|
8
|
+
|
|
9
|
+
```sh
|
|
10
|
+
npm install @dinghy-chat/sdk
|
|
11
|
+
```
|
|
12
|
+
|
|
13
|
+
## Create a client
|
|
14
|
+
|
|
15
|
+
```ts
|
|
16
|
+
import { Dinghy } from "@dinghy-chat/sdk";
|
|
17
|
+
|
|
18
|
+
const dinghy = new Dinghy({
|
|
19
|
+
url: "https://chat.example.com",
|
|
20
|
+
apiKey: process.env.DINGHY_API_KEY,
|
|
21
|
+
signingSecret: process.env.DINGHY_SIGNING_SECRET,
|
|
22
|
+
publicKey: "YOUR_PUBLIC_KEY",
|
|
23
|
+
webhookSecret: process.env.DINGHY_WEBHOOK_SECRET,
|
|
24
|
+
});
|
|
25
|
+
```
|
|
26
|
+
|
|
27
|
+
| Option | What it is |
|
|
28
|
+
| --------------- | --------------------------------------------------------------------------------- |
|
|
29
|
+
| `url` | Your Dinghy server |
|
|
30
|
+
| `apiKey` | A workspace API key, `dk_...`, from Settings > API keys, or an OAuth access token |
|
|
31
|
+
| `signingSecret` | The workspace's signing secret, for `identity.sign` |
|
|
32
|
+
| `publicKey` | The workspace's public key, `wk_...`, for `identity.sign` |
|
|
33
|
+
| `webhookSecret` | The webhook's secret, for `webhooks.verify` |
|
|
34
|
+
| `fetch` | Optional. Replaces the global `fetch`, such as in a test |
|
|
35
|
+
|
|
36
|
+
The key names its workspace, so you never pass a workspace ID.
|
|
37
|
+
|
|
38
|
+
A method answers what the route answers, such as `{ outboundMessage }`. A refused request throws a `DinghyError` with the HTTP `status`, the API's `code` and a `message`. The client tries a request up to 3 times after a 429, a 503 or a dropped connection, and waits for `retry-after` when the server sends one. A send makes its own `clientId` when you pass none, and keeps it across these tries, so a retry never sends twice.
|
|
39
|
+
|
|
40
|
+
## Send a welcome that waits for the chat
|
|
41
|
+
|
|
42
|
+
Create a key with "Send directly" and "May send as a member" first. Then, in the signup handler:
|
|
43
|
+
|
|
44
|
+
```ts
|
|
45
|
+
await dinghy.outboundMessages.send({
|
|
46
|
+
visitor: { userId: user.id, name: user.name, email: user.email },
|
|
47
|
+
sender: { email: "julien@example.com" },
|
|
48
|
+
body: "Welcome! Any question about getting started? Ask me here.",
|
|
49
|
+
dedupeKey: "welcome",
|
|
50
|
+
});
|
|
51
|
+
```
|
|
52
|
+
|
|
53
|
+
The message waits until the user opens the chat. `dedupeKey` sends it one time per user, however often the handler runs.
|
|
54
|
+
|
|
55
|
+
## Send a message later, and cancel it
|
|
56
|
+
|
|
57
|
+
```ts
|
|
58
|
+
await dinghy.outboundMessages.send({
|
|
59
|
+
visitor: { userId: customer.id },
|
|
60
|
+
body: `Invoice ${invoice.number} is still open. Any question about it?`,
|
|
61
|
+
delay: "3d",
|
|
62
|
+
dedupeKey: `invoice-${invoice.id}-unpaid`,
|
|
63
|
+
metadata: { invoiceId: invoice.id },
|
|
64
|
+
});
|
|
65
|
+
|
|
66
|
+
// When the invoice is paid:
|
|
67
|
+
await dinghy.outboundMessages.cancel({
|
|
68
|
+
visitor: { userId: customer.id },
|
|
69
|
+
dedupeKey: `invoice-${invoice.id}-unpaid`,
|
|
70
|
+
});
|
|
71
|
+
```
|
|
72
|
+
|
|
73
|
+
The `dedupeKey` names the message, so the cancel needs no stored ID. `cancel` also takes `{ id }`. `get(id)` and `list({ visitorId, userId, dedupeKey, status })` read sent messages. `metadata` comes back on the message and its webhooks, and the visitor never sees it.
|
|
74
|
+
|
|
75
|
+
## Sign users in to the chat
|
|
76
|
+
|
|
77
|
+
`identity.sign` makes the token for `Dinghy.identify` on your page. It needs `signingSecret` and `publicKey`.
|
|
78
|
+
|
|
79
|
+
```ts
|
|
80
|
+
const token = await dinghy.identity.sign({
|
|
81
|
+
userId: user.id,
|
|
82
|
+
name: user.name,
|
|
83
|
+
email: user.email,
|
|
84
|
+
attributes: { plan: user.plan },
|
|
85
|
+
});
|
|
86
|
+
```
|
|
87
|
+
|
|
88
|
+
The token is valid for one hour. Set `expiresInSeconds` for up to 24 hours. Give it only to the user's own session.
|
|
89
|
+
|
|
90
|
+
## Check a webhook
|
|
91
|
+
|
|
92
|
+
`webhooks.verify` checks the `Dinghy-Signature` header with `webhookSecret`, and returns the body, typed by its `type`. It throws a `DinghyError` with the code `bad_signature` when the signature does not match or is more than 5 minutes old.
|
|
93
|
+
|
|
94
|
+
```ts
|
|
95
|
+
export async function POST(request: Request) {
|
|
96
|
+
const event = await dinghy.webhooks.verify(request);
|
|
97
|
+
if (event.type === "outbound_message.replied") {
|
|
98
|
+
console.log(event.data.outboundMessage.conversationId);
|
|
99
|
+
}
|
|
100
|
+
return new Response(null, { status: 204 });
|
|
101
|
+
}
|
|
102
|
+
```
|
|
103
|
+
|
|
104
|
+
It also takes `{ body, headers }`, with the raw body as a string or bytes. Read the body before any JSON parsing. A webhook may come more than once: use `Dinghy-Event-Id` to skip one you already handled.
|
|
105
|
+
|
|
106
|
+
## Read the events stream
|
|
107
|
+
|
|
108
|
+
`events.stream` reads the workspace's events with no public server, as a bot would. Each event has the same `type` and `data` as a webhook.
|
|
109
|
+
|
|
110
|
+
```ts
|
|
111
|
+
for await (const event of dinghy.events.stream({ types: ["message.created"] })) {
|
|
112
|
+
if (event.type === "message.created") console.log(event.data.message.body);
|
|
113
|
+
}
|
|
114
|
+
```
|
|
115
|
+
|
|
116
|
+
It reconnects when the server ends the stream or the connection drops, and resumes after the last event. Pass `after` with an event's `id` to resume after a restart. A `resync` event means the position was too old: read the open conversations again.
|
|
117
|
+
|
|
118
|
+
## Everything else
|
|
119
|
+
|
|
120
|
+
| Group | Methods |
|
|
121
|
+
| ------------------ | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
|
122
|
+
| `conversations` | `list`, `search`, `messages`, `reply`, `note`, `upload`, `receipt`, `close`, `reopen`, `snooze`, `assign`, `addLabel`, `removeLabel`, `handoff`, `typing` |
|
|
123
|
+
| `contacts` | `upsert` |
|
|
124
|
+
| `outboundMessages` | `send`, `get`, `list`, `cancel` |
|
|
125
|
+
| `labels` | `list` |
|
|
126
|
+
| `savedReplies` | `list` |
|
|
127
|
+
| `analytics` | `get` |
|
|
128
|
+
| `workspace` | `get` |
|
|
129
|
+
| `webhooks` | `list`, `create`, `update`, `delete`, `rotateSecret`, `test`, `deliveries`, `replay`, `verify` |
|
|
130
|
+
| `setup` | `snippet`, `checkInstall`, `identitySetup`, `sites`, `addSite`, `removeSite`, `widget`, `updateWidget`, `businessHours`, `updateBusinessHours`, `testVisitorMessage`, `clearTestVisitors` |
|
|
131
|
+
|
|
132
|
+
`webhooks` and `setup` need a key with Full access. `request` reaches any route a key may call, with the same types:
|
|
133
|
+
|
|
134
|
+
```ts
|
|
135
|
+
await dinghy.request("get", "/v1/operator/workspaces/{workspaceId}/labels");
|
|
136
|
+
```
|
package/dist/events.d.ts
ADDED
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
import { type Fetch } from "./request.ts";
|
|
2
|
+
import type { StreamEvent, WebhookType } from "./webhooks.ts";
|
|
3
|
+
/** An event, or `resync`: the cursor was too old, so read the open conversations again. */
|
|
4
|
+
export type StreamItem = StreamEvent | {
|
|
5
|
+
id: string;
|
|
6
|
+
type: "resync";
|
|
7
|
+
data: Record<string, never>;
|
|
8
|
+
};
|
|
9
|
+
export interface StreamOptions {
|
|
10
|
+
/** The types to receive. All by default. */
|
|
11
|
+
types?: WebhookType[];
|
|
12
|
+
/** The position to resume after, from an earlier event's `id`. With none, it starts now. */
|
|
13
|
+
after?: string;
|
|
14
|
+
}
|
|
15
|
+
interface Client {
|
|
16
|
+
baseUrl: string;
|
|
17
|
+
apiKey: string;
|
|
18
|
+
fetch: Fetch;
|
|
19
|
+
}
|
|
20
|
+
/**
|
|
21
|
+
* The workspace's events, for as long as the caller reads them. It reconnects after the server
|
|
22
|
+
* ends a stream or a connection drops, and resumes after the last event with `Last-Event-ID`.
|
|
23
|
+
*/
|
|
24
|
+
export declare function streamEvents(client: Client, options: StreamOptions): AsyncGenerator<StreamItem>;
|
|
25
|
+
export {};
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
/** The signed-in user that a host token names. */
|
|
2
|
+
export interface HostUser {
|
|
3
|
+
userId: string;
|
|
4
|
+
name?: string;
|
|
5
|
+
email?: string;
|
|
6
|
+
attributes?: Record<string, unknown>;
|
|
7
|
+
/** How long the token is valid. One hour by default, and at most 24 hours. */
|
|
8
|
+
expiresInSeconds?: number;
|
|
9
|
+
}
|
|
10
|
+
/** An HS256 JWT for `Dinghy.identify`, signed with the workspace's signing secret. */
|
|
11
|
+
export declare function signHostToken(user: HostUser, signingSecret: string, publicKey: string): Promise<string>;
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
import { type StreamItem, type StreamOptions } from "./events.ts";
|
|
2
|
+
import { type HostUser } from "./identity.ts";
|
|
3
|
+
import { type Answer, type Fetch, type MethodOf, type RequestArgs, type WorkspacePath } from "./request.ts";
|
|
4
|
+
import { analytics, contacts, conversations, labels, outboundMessages, savedReplies, setup, webhookRoutes, workspace } from "./resources.ts";
|
|
5
|
+
import { type Received, type WebhookEvent } from "./webhooks.ts";
|
|
6
|
+
export type { StreamItem, StreamOptions } from "./events.ts";
|
|
7
|
+
export type { HostUser } from "./identity.ts";
|
|
8
|
+
export type { components, paths } from "./openapi.ts";
|
|
9
|
+
export type { ErrorCode, Fetch } from "./request.ts";
|
|
10
|
+
export { DinghyError } from "./request.ts";
|
|
11
|
+
export type { Received, StreamEvent, WebhookEvent, WebhookType } from "./webhooks.ts";
|
|
12
|
+
export interface DinghyOptions {
|
|
13
|
+
/** The Dinghy server, such as https://chat.example.com. */
|
|
14
|
+
url: string;
|
|
15
|
+
/** A workspace API key, `dk_...`, or an OAuth access token, `dko_...`. */
|
|
16
|
+
apiKey: string;
|
|
17
|
+
/** The workspace's signing secret, for `identity.sign`. */
|
|
18
|
+
signingSecret?: string | undefined;
|
|
19
|
+
/** The workspace's public key, `wk_...`, for `identity.sign`. */
|
|
20
|
+
publicKey?: string | undefined;
|
|
21
|
+
/** A webhook's secret, for `webhooks.verify`. */
|
|
22
|
+
webhookSecret?: string | undefined;
|
|
23
|
+
/** Replaces the global `fetch`, such as in a test. */
|
|
24
|
+
fetch?: Fetch;
|
|
25
|
+
}
|
|
26
|
+
/** A client for the Dinghy API, for a server. It runs on Node, Bun, Deno and Workers. */
|
|
27
|
+
export declare class Dinghy {
|
|
28
|
+
#private;
|
|
29
|
+
readonly workspaceId: string;
|
|
30
|
+
readonly conversations: ReturnType<typeof conversations>;
|
|
31
|
+
readonly contacts: ReturnType<typeof contacts>;
|
|
32
|
+
readonly outboundMessages: ReturnType<typeof outboundMessages>;
|
|
33
|
+
readonly labels: ReturnType<typeof labels>;
|
|
34
|
+
readonly savedReplies: ReturnType<typeof savedReplies>;
|
|
35
|
+
readonly analytics: ReturnType<typeof analytics>;
|
|
36
|
+
readonly workspace: ReturnType<typeof workspace>;
|
|
37
|
+
/** The install, sites, widget, business hours and test visitors. They need a Full access key. */
|
|
38
|
+
readonly setup: ReturnType<typeof setup>;
|
|
39
|
+
/** The webhook routes need a Full access key. `verify` needs `webhookSecret`. */
|
|
40
|
+
readonly webhooks: ReturnType<typeof webhookRoutes> & {
|
|
41
|
+
verify: (received: Received) => Promise<WebhookEvent>;
|
|
42
|
+
};
|
|
43
|
+
readonly events: {
|
|
44
|
+
stream: (options?: StreamOptions) => AsyncGenerator<StreamItem>;
|
|
45
|
+
};
|
|
46
|
+
readonly identity: {
|
|
47
|
+
sign: (user: HostUser) => Promise<string>;
|
|
48
|
+
};
|
|
49
|
+
constructor(options: DinghyOptions);
|
|
50
|
+
/** Any workspace route, typed from the API: `request("get", "/v1/operator/workspaces/{workspaceId}/labels")`. */
|
|
51
|
+
request<P extends WorkspacePath, M extends MethodOf<P>>(method: M, path: P, ...[options]: RequestArgs<P, M>): Promise<Answer<P, M>>;
|
|
52
|
+
}
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,402 @@
|
|
|
1
|
+
// src/request.ts
|
|
2
|
+
var DinghyError = class extends Error {
|
|
3
|
+
status;
|
|
4
|
+
code;
|
|
5
|
+
constructor(status, code, message) {
|
|
6
|
+
super(message);
|
|
7
|
+
this.name = "DinghyError";
|
|
8
|
+
this.status = status;
|
|
9
|
+
this.code = code;
|
|
10
|
+
}
|
|
11
|
+
};
|
|
12
|
+
var MAX_TRIES = 3;
|
|
13
|
+
var BACKOFF_MS = 250;
|
|
14
|
+
var MAX_WAIT_MS = 3e4;
|
|
15
|
+
var RETRY_STATUSES = /* @__PURE__ */ new Set([429, 503]);
|
|
16
|
+
var wait = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
|
|
17
|
+
function retryDelayMs(response, tries) {
|
|
18
|
+
const seconds = Number(response?.headers.get("retry-after") ?? Number.NaN);
|
|
19
|
+
const ms = Number.isFinite(seconds) ? seconds * 1e3 : BACKOFF_MS * 2 ** (tries - 1);
|
|
20
|
+
return Math.min(Math.max(ms, 0), MAX_WAIT_MS);
|
|
21
|
+
}
|
|
22
|
+
async function errorOf(response) {
|
|
23
|
+
const body = await response.json().catch(() => null);
|
|
24
|
+
if (body?.error?.code === void 0) {
|
|
25
|
+
return new DinghyError(response.status, "unexpected_response", `HTTP ${response.status}`);
|
|
26
|
+
}
|
|
27
|
+
return new DinghyError(response.status, body.error.code, body.error.message);
|
|
28
|
+
}
|
|
29
|
+
async function withRetries(fetch, raw, isRepeatable) {
|
|
30
|
+
for (let tries = 1; ; tries++) {
|
|
31
|
+
const init = { method: raw.method.toUpperCase(), headers: raw.headers };
|
|
32
|
+
if (raw.body !== void 0) init.body = raw.body;
|
|
33
|
+
let response;
|
|
34
|
+
try {
|
|
35
|
+
response = await fetch(raw.url, init);
|
|
36
|
+
} catch (error) {
|
|
37
|
+
if (!isRepeatable || tries >= MAX_TRIES) throw error;
|
|
38
|
+
await wait(retryDelayMs(null, tries));
|
|
39
|
+
continue;
|
|
40
|
+
}
|
|
41
|
+
if (!RETRY_STATUSES.has(response.status) || tries >= MAX_TRIES) return response;
|
|
42
|
+
await response.body?.cancel();
|
|
43
|
+
await wait(retryDelayMs(response, tries));
|
|
44
|
+
}
|
|
45
|
+
}
|
|
46
|
+
function urlOf(target, template, path, query) {
|
|
47
|
+
const params = { ...path, workspaceId: target.workspaceId };
|
|
48
|
+
const filled = template.replace(
|
|
49
|
+
/\{(\w+)\}/g,
|
|
50
|
+
(_, name) => encodeURIComponent(String(params[name]))
|
|
51
|
+
);
|
|
52
|
+
const search = new URLSearchParams();
|
|
53
|
+
for (const [name, value] of Object.entries(query)) {
|
|
54
|
+
if (value !== void 0) search.set(name, String(value));
|
|
55
|
+
}
|
|
56
|
+
const text = search.toString();
|
|
57
|
+
return new URL(text === "" ? filled : `${filled}?${text}`, target.baseUrl).href;
|
|
58
|
+
}
|
|
59
|
+
async function call(client, method, template, options) {
|
|
60
|
+
const headers = {
|
|
61
|
+
authorization: `Bearer ${client.apiKey}`,
|
|
62
|
+
accept: "application/json"
|
|
63
|
+
};
|
|
64
|
+
if (options.body !== void 0) headers["content-type"] = "application/json";
|
|
65
|
+
if (options.bytes !== void 0) headers["content-type"] = "application/octet-stream";
|
|
66
|
+
const raw = {
|
|
67
|
+
method,
|
|
68
|
+
url: urlOf(client, template, options.path ?? {}, options.query ?? {}),
|
|
69
|
+
headers
|
|
70
|
+
};
|
|
71
|
+
const body = options.bytes ?? (options.body === void 0 ? void 0 : JSON.stringify(options.body));
|
|
72
|
+
if (body !== void 0) raw.body = body;
|
|
73
|
+
const hasClientId = "clientId" in (options.body ?? {}) || "clientId" in (options.query ?? {});
|
|
74
|
+
const response = await withRetries(client.fetch, raw, method !== "post" || hasClientId);
|
|
75
|
+
if (!response.ok) throw await errorOf(response);
|
|
76
|
+
return response.json();
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
// src/events.ts
|
|
80
|
+
var RECONNECT_DELAY_MS = 1e3;
|
|
81
|
+
function parseBlock(block) {
|
|
82
|
+
const message = { event: "message", id: null, data: "" };
|
|
83
|
+
for (const line of block.split("\n")) {
|
|
84
|
+
const colon = line.indexOf(":");
|
|
85
|
+
if (colon === 0) continue;
|
|
86
|
+
const field = colon === -1 ? line : line.slice(0, colon);
|
|
87
|
+
const value = colon === -1 ? "" : line.slice(colon + 1).replace(/^ /, "");
|
|
88
|
+
if (field === "event") message.event = value;
|
|
89
|
+
else if (field === "id") message.id = value;
|
|
90
|
+
else if (field === "data")
|
|
91
|
+
message.data = message.data === "" ? value : `${message.data}
|
|
92
|
+
${value}`;
|
|
93
|
+
}
|
|
94
|
+
return message;
|
|
95
|
+
}
|
|
96
|
+
async function* messages(body) {
|
|
97
|
+
const reader = body.getReader();
|
|
98
|
+
const decoder = new TextDecoder();
|
|
99
|
+
let buffered = "";
|
|
100
|
+
try {
|
|
101
|
+
for (; ; ) {
|
|
102
|
+
const { done, value } = await reader.read();
|
|
103
|
+
if (done) return;
|
|
104
|
+
buffered += decoder.decode(value, { stream: true }).replace(/\r\n?/g, "\n");
|
|
105
|
+
let end = buffered.indexOf("\n\n");
|
|
106
|
+
while (end !== -1) {
|
|
107
|
+
yield parseBlock(buffered.slice(0, end));
|
|
108
|
+
buffered = buffered.slice(end + 2);
|
|
109
|
+
end = buffered.indexOf("\n\n");
|
|
110
|
+
}
|
|
111
|
+
}
|
|
112
|
+
} finally {
|
|
113
|
+
await reader.cancel().catch(() => void 0);
|
|
114
|
+
}
|
|
115
|
+
}
|
|
116
|
+
async function connect(client, options, lastId) {
|
|
117
|
+
const url = new URL("/v1/events", client.baseUrl);
|
|
118
|
+
if (options.types !== void 0) url.searchParams.set("types", options.types.join(","));
|
|
119
|
+
if (options.after !== void 0) url.searchParams.set("after", options.after);
|
|
120
|
+
const headers = {
|
|
121
|
+
authorization: `Bearer ${client.apiKey}`,
|
|
122
|
+
accept: "text/event-stream"
|
|
123
|
+
};
|
|
124
|
+
if (lastId !== void 0) headers["last-event-id"] = lastId;
|
|
125
|
+
const response = await withRetries(client.fetch, { method: "get", url: url.href, headers }, true);
|
|
126
|
+
if (!response.ok || response.body === null) throw await errorOf(response);
|
|
127
|
+
return response.body;
|
|
128
|
+
}
|
|
129
|
+
function read(message) {
|
|
130
|
+
if (message.event === "close") {
|
|
131
|
+
const { reason } = JSON.parse(message.data);
|
|
132
|
+
if (reason === "unauthorized") {
|
|
133
|
+
throw new DinghyError(401, "unauthorized", "The API key is not valid or was revoked.");
|
|
134
|
+
}
|
|
135
|
+
return "reconnect";
|
|
136
|
+
}
|
|
137
|
+
if (message.event === "resync") {
|
|
138
|
+
const { cursor } = JSON.parse(message.data);
|
|
139
|
+
return { id: cursor, type: "resync", data: {} };
|
|
140
|
+
}
|
|
141
|
+
if (message.id === null) return "skip";
|
|
142
|
+
const { type, data } = JSON.parse(message.data);
|
|
143
|
+
return { id: message.id, type, data };
|
|
144
|
+
}
|
|
145
|
+
async function* streamEvents(client, options) {
|
|
146
|
+
let lastId;
|
|
147
|
+
for (; ; ) {
|
|
148
|
+
try {
|
|
149
|
+
for await (const message of messages(await connect(client, options, lastId))) {
|
|
150
|
+
const item = read(message);
|
|
151
|
+
if (item === "reconnect") break;
|
|
152
|
+
if (item === "skip") continue;
|
|
153
|
+
lastId = item.id;
|
|
154
|
+
yield item;
|
|
155
|
+
}
|
|
156
|
+
} catch (error) {
|
|
157
|
+
if (error instanceof DinghyError && !RETRY_STATUSES.has(error.status)) throw error;
|
|
158
|
+
}
|
|
159
|
+
await wait(RECONNECT_DELAY_MS);
|
|
160
|
+
}
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
// src/identity.ts
|
|
164
|
+
var DEFAULT_LIFETIME_SECONDS = 60 * 60;
|
|
165
|
+
var MAX_LIFETIME_SECONDS = 24 * 60 * 60;
|
|
166
|
+
var base64url = (bytes) => btoa(Array.from(bytes, (byte) => String.fromCharCode(byte)).join("")).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
|
|
167
|
+
var encodeJson = (value) => base64url(new TextEncoder().encode(JSON.stringify(value)));
|
|
168
|
+
async function signHostToken(user, signingSecret, publicKey) {
|
|
169
|
+
const lifetime = user.expiresInSeconds ?? DEFAULT_LIFETIME_SECONDS;
|
|
170
|
+
if (lifetime <= 0 || lifetime > MAX_LIFETIME_SECONDS) {
|
|
171
|
+
throw new RangeError("expiresInSeconds must be more than 0 and at most 86400 (24 hours).");
|
|
172
|
+
}
|
|
173
|
+
const iat = Math.floor(Date.now() / 1e3);
|
|
174
|
+
const claims = {
|
|
175
|
+
sub: user.userId,
|
|
176
|
+
aud: publicKey,
|
|
177
|
+
iat,
|
|
178
|
+
exp: iat + lifetime,
|
|
179
|
+
name: user.name,
|
|
180
|
+
email: user.email,
|
|
181
|
+
attributes: user.attributes
|
|
182
|
+
};
|
|
183
|
+
const unsigned = `${encodeJson({ alg: "HS256", typ: "JWT" })}.${encodeJson(claims)}`;
|
|
184
|
+
const key = await crypto.subtle.importKey(
|
|
185
|
+
"raw",
|
|
186
|
+
new TextEncoder().encode(signingSecret),
|
|
187
|
+
{ name: "HMAC", hash: "SHA-256" },
|
|
188
|
+
false,
|
|
189
|
+
["sign"]
|
|
190
|
+
);
|
|
191
|
+
const signature = await crypto.subtle.sign("HMAC", key, new TextEncoder().encode(unsigned));
|
|
192
|
+
return `${unsigned}.${base64url(new Uint8Array(signature))}`;
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
// src/resources.ts
|
|
196
|
+
var IN_WORKSPACE = "/v1/operator/workspaces/{workspaceId}";
|
|
197
|
+
var CONVERSATIONS = `${IN_WORKSPACE}/conversations`;
|
|
198
|
+
var CONVERSATION = `${CONVERSATIONS}/{conversationId}`;
|
|
199
|
+
var MESSAGES = `${CONVERSATION}/messages`;
|
|
200
|
+
var CONTACT_BY_USER = `${IN_WORKSPACE}/contacts/by-user/{userId}`;
|
|
201
|
+
var OUTBOUND = `${IN_WORKSPACE}/outbound-messages`;
|
|
202
|
+
var WEBHOOKS = `${IN_WORKSPACE}/webhooks`;
|
|
203
|
+
var WEBHOOK = `${WEBHOOKS}/{webhookId}`;
|
|
204
|
+
var withClientId = (input) => ({
|
|
205
|
+
...input,
|
|
206
|
+
clientId: input.clientId ?? crypto.randomUUID()
|
|
207
|
+
});
|
|
208
|
+
function conversations(request) {
|
|
209
|
+
const at = (conversationId) => ({ path: { conversationId } });
|
|
210
|
+
return {
|
|
211
|
+
list: (query = {}) => request("get", CONVERSATIONS, { query }),
|
|
212
|
+
search: (q) => request("get", `${CONVERSATIONS}/search`, { query: { q } }),
|
|
213
|
+
messages: (conversationId, query = {}) => request("get", MESSAGES, { ...at(conversationId), query }),
|
|
214
|
+
reply: (conversationId, input) => request("post", MESSAGES, { ...at(conversationId), body: withClientId(input) }),
|
|
215
|
+
note: (conversationId, input) => request("post", MESSAGES, {
|
|
216
|
+
...at(conversationId),
|
|
217
|
+
body: { ...withClientId(input), note: true }
|
|
218
|
+
}),
|
|
219
|
+
upload: (conversationId, { file, ...query }) => request("post", `${CONVERSATION}/uploads`, {
|
|
220
|
+
...at(conversationId),
|
|
221
|
+
query: withClientId(query),
|
|
222
|
+
bytes: file
|
|
223
|
+
}),
|
|
224
|
+
receipt: (conversationId, messageId) => request("get", `${MESSAGES}/{messageId}/receipt`, { path: { conversationId, messageId } }),
|
|
225
|
+
close: (conversationId) => request("patch", CONVERSATION, { ...at(conversationId), body: { status: "closed" } }),
|
|
226
|
+
reopen: (conversationId) => request("patch", CONVERSATION, { ...at(conversationId), body: { status: "open" } }),
|
|
227
|
+
snooze: (conversationId, snooze) => request("patch", CONVERSATION, { ...at(conversationId), body: { snooze } }),
|
|
228
|
+
/** Assigns a member by operator ID, or unassigns with null. */
|
|
229
|
+
assign: (conversationId, operatorId) => request("put", `${CONVERSATION}/assignee`, { ...at(conversationId), body: { operatorId } }),
|
|
230
|
+
addLabel: (conversationId, labelId) => request("put", `${CONVERSATION}/labels/{labelId}`, { path: { conversationId, labelId } }),
|
|
231
|
+
removeLabel: (conversationId, labelId) => request("delete", `${CONVERSATION}/labels/{labelId}`, { path: { conversationId, labelId } }),
|
|
232
|
+
handoff: (conversationId, input) => request("post", `${CONVERSATION}/handoff`, {
|
|
233
|
+
...at(conversationId),
|
|
234
|
+
body: withClientId(input)
|
|
235
|
+
}),
|
|
236
|
+
typing: (conversationId, typing = true) => request("post", `${CONVERSATION}/typing`, { ...at(conversationId), body: { typing } })
|
|
237
|
+
};
|
|
238
|
+
}
|
|
239
|
+
function contacts(request) {
|
|
240
|
+
return {
|
|
241
|
+
/** Creates or updates the contact with this user ID, as a host token would. */
|
|
242
|
+
upsert: ({ userId, ...body }) => request("put", CONTACT_BY_USER, { path: { userId }, body })
|
|
243
|
+
};
|
|
244
|
+
}
|
|
245
|
+
function outboundMessages(request) {
|
|
246
|
+
return {
|
|
247
|
+
send: (input) => request("post", OUTBOUND, { body: withClientId(input) }),
|
|
248
|
+
get: (id) => request("get", `${OUTBOUND}/{id}`, { path: { id } }),
|
|
249
|
+
list: (query = {}) => request("get", OUTBOUND, { query }),
|
|
250
|
+
/** Cancels by ID, or by the visitor and the `dedupeKey` it was sent with. */
|
|
251
|
+
cancel: (input) => "id" in input ? request("post", `${OUTBOUND}/{id}/cancel`, { path: { id: input.id } }) : request("post", `${OUTBOUND}/cancel`, { body: input })
|
|
252
|
+
};
|
|
253
|
+
}
|
|
254
|
+
function webhookRoutes(request) {
|
|
255
|
+
const at = (webhookId) => ({ path: { webhookId } });
|
|
256
|
+
return {
|
|
257
|
+
list: () => request("get", WEBHOOKS),
|
|
258
|
+
create: (body) => request("post", WEBHOOKS, { body }),
|
|
259
|
+
update: (webhookId, body) => request("patch", WEBHOOK, { ...at(webhookId), body }),
|
|
260
|
+
delete: (webhookId) => request("delete", WEBHOOK, at(webhookId)),
|
|
261
|
+
rotateSecret: (webhookId) => request("post", `${WEBHOOK}/rotate-secret`, at(webhookId)),
|
|
262
|
+
test: (webhookId) => request("post", `${WEBHOOK}/test`, at(webhookId)),
|
|
263
|
+
deliveries: (webhookId) => request("get", `${WEBHOOK}/deliveries`, at(webhookId)),
|
|
264
|
+
replay: (webhookId, deliveryId) => request("post", `${WEBHOOK}/deliveries/{deliveryId}/replay`, {
|
|
265
|
+
path: { webhookId, deliveryId }
|
|
266
|
+
})
|
|
267
|
+
};
|
|
268
|
+
}
|
|
269
|
+
function setup(request) {
|
|
270
|
+
return {
|
|
271
|
+
snippet: (query) => request("get", `${IN_WORKSPACE}/install/snippet`, { query }),
|
|
272
|
+
checkInstall: (query) => request("get", `${IN_WORKSPACE}/install/check`, { query }),
|
|
273
|
+
identitySetup: (query) => request("get", `${IN_WORKSPACE}/install/identity`, { query }),
|
|
274
|
+
sites: () => request("get", `${IN_WORKSPACE}/sites`),
|
|
275
|
+
addSite: (origin) => request("post", `${IN_WORKSPACE}/sites`, { body: { origin } }),
|
|
276
|
+
removeSite: (origin) => request("delete", `${IN_WORKSPACE}/sites`, { query: { origin } }),
|
|
277
|
+
widget: () => request("get", `${IN_WORKSPACE}/widget`),
|
|
278
|
+
updateWidget: (body) => request("put", `${IN_WORKSPACE}/widget`, { body }),
|
|
279
|
+
businessHours: () => request("get", `${IN_WORKSPACE}/business-hours`),
|
|
280
|
+
updateBusinessHours: (body) => request("put", `${IN_WORKSPACE}/business-hours`, { body }),
|
|
281
|
+
testVisitorMessage: (body) => request("post", `${IN_WORKSPACE}/test-visitors/messages`, { body }),
|
|
282
|
+
clearTestVisitors: () => request("delete", `${IN_WORKSPACE}/test-visitors`)
|
|
283
|
+
};
|
|
284
|
+
}
|
|
285
|
+
function workspace(request) {
|
|
286
|
+
return { get: () => request("get", IN_WORKSPACE) };
|
|
287
|
+
}
|
|
288
|
+
function labels(request) {
|
|
289
|
+
return { list: () => request("get", `${IN_WORKSPACE}/labels`) };
|
|
290
|
+
}
|
|
291
|
+
function savedReplies(request) {
|
|
292
|
+
return { list: () => request("get", `${IN_WORKSPACE}/saved-replies`) };
|
|
293
|
+
}
|
|
294
|
+
function analytics(request) {
|
|
295
|
+
return {
|
|
296
|
+
get: (query = {}) => request("get", `${IN_WORKSPACE}/analytics`, { query })
|
|
297
|
+
};
|
|
298
|
+
}
|
|
299
|
+
|
|
300
|
+
// src/webhooks.ts
|
|
301
|
+
var TOLERANCE_SECONDS = 300;
|
|
302
|
+
var SIGNATURE = /^t=(\d+),v1=([0-9a-f]{64})$/;
|
|
303
|
+
function header(headers, name) {
|
|
304
|
+
if (headers instanceof globalThis.Headers) return headers.get(name);
|
|
305
|
+
const found = Object.entries(headers).find(([key]) => key.toLowerCase() === name)?.[1];
|
|
306
|
+
return (Array.isArray(found) ? found[0] : found) ?? null;
|
|
307
|
+
}
|
|
308
|
+
var hexBytes = (hex) => Uint8Array.from(hex.match(/../g) ?? [], (pair) => Number.parseInt(pair, 16));
|
|
309
|
+
var refused = (message) => new DinghyError(400, "bad_signature", message);
|
|
310
|
+
async function verifyWebhook(received, secret) {
|
|
311
|
+
const bytes = received instanceof Request ? new Uint8Array(await received.arrayBuffer()) : typeof received.body === "string" ? new TextEncoder().encode(received.body) : received.body;
|
|
312
|
+
const match = SIGNATURE.exec(header(received.headers, "dinghy-signature") ?? "");
|
|
313
|
+
if (match === null) throw refused("The Dinghy-Signature header is missing or malformed.");
|
|
314
|
+
const [, timestamp = "", digest = ""] = match;
|
|
315
|
+
if (Math.abs(Date.now() / 1e3 - Number(timestamp)) > TOLERANCE_SECONDS) {
|
|
316
|
+
throw refused("The webhook's timestamp is more than 5 minutes away from now.");
|
|
317
|
+
}
|
|
318
|
+
const encoder = new TextEncoder();
|
|
319
|
+
const key = await crypto.subtle.importKey(
|
|
320
|
+
"raw",
|
|
321
|
+
encoder.encode(secret),
|
|
322
|
+
{ name: "HMAC", hash: "SHA-256" },
|
|
323
|
+
false,
|
|
324
|
+
["verify"]
|
|
325
|
+
);
|
|
326
|
+
const prefix = encoder.encode(`${timestamp}.`);
|
|
327
|
+
const signed = new Uint8Array(prefix.length + bytes.length);
|
|
328
|
+
signed.set(prefix);
|
|
329
|
+
signed.set(bytes, prefix.length);
|
|
330
|
+
if (!await crypto.subtle.verify("HMAC", key, hexBytes(digest), signed)) {
|
|
331
|
+
throw refused("The webhook's signature does not match its secret.");
|
|
332
|
+
}
|
|
333
|
+
return JSON.parse(new TextDecoder().decode(bytes));
|
|
334
|
+
}
|
|
335
|
+
|
|
336
|
+
// src/index.ts
|
|
337
|
+
var TOKEN = /^dko?_([0-9a-f-]{36})\./i;
|
|
338
|
+
function workspaceOf(apiKey) {
|
|
339
|
+
const workspaceId = TOKEN.exec(apiKey)?.[1];
|
|
340
|
+
if (workspaceId === void 0) {
|
|
341
|
+
throw new TypeError("apiKey must be a workspace API key, dk_..., or an access token, dko_...");
|
|
342
|
+
}
|
|
343
|
+
return workspaceId;
|
|
344
|
+
}
|
|
345
|
+
var needed = (value, name) => {
|
|
346
|
+
if (value === void 0) throw new TypeError(`Pass ${name} to new Dinghy() first.`);
|
|
347
|
+
return value;
|
|
348
|
+
};
|
|
349
|
+
var Dinghy = class {
|
|
350
|
+
workspaceId;
|
|
351
|
+
conversations;
|
|
352
|
+
contacts;
|
|
353
|
+
outboundMessages;
|
|
354
|
+
labels;
|
|
355
|
+
savedReplies;
|
|
356
|
+
analytics;
|
|
357
|
+
workspace;
|
|
358
|
+
/** The install, sites, widget, business hours and test visitors. They need a Full access key. */
|
|
359
|
+
setup;
|
|
360
|
+
/** The webhook routes need a Full access key. `verify` needs `webhookSecret`. */
|
|
361
|
+
webhooks;
|
|
362
|
+
events;
|
|
363
|
+
identity;
|
|
364
|
+
#options;
|
|
365
|
+
constructor(options) {
|
|
366
|
+
this.#options = options;
|
|
367
|
+
this.workspaceId = workspaceOf(options.apiKey);
|
|
368
|
+
const request = (method, path, ...args) => this.request(method, path, ...args);
|
|
369
|
+
this.conversations = conversations(request);
|
|
370
|
+
this.contacts = contacts(request);
|
|
371
|
+
this.outboundMessages = outboundMessages(request);
|
|
372
|
+
this.labels = labels(request);
|
|
373
|
+
this.savedReplies = savedReplies(request);
|
|
374
|
+
this.analytics = analytics(request);
|
|
375
|
+
this.workspace = workspace(request);
|
|
376
|
+
this.setup = setup(request);
|
|
377
|
+
this.webhooks = {
|
|
378
|
+
...webhookRoutes(request),
|
|
379
|
+
verify: async (received) => verifyWebhook(received, needed(options.webhookSecret, "webhookSecret"))
|
|
380
|
+
};
|
|
381
|
+
this.events = { stream: (stream = {}) => streamEvents(this.#client(), stream) };
|
|
382
|
+
this.identity = {
|
|
383
|
+
sign: async (user) => signHostToken(
|
|
384
|
+
user,
|
|
385
|
+
needed(options.signingSecret, "signingSecret"),
|
|
386
|
+
needed(options.publicKey, "publicKey")
|
|
387
|
+
)
|
|
388
|
+
};
|
|
389
|
+
}
|
|
390
|
+
#client() {
|
|
391
|
+
const { url, apiKey, fetch = globalThis.fetch } = this.#options;
|
|
392
|
+
return { baseUrl: url, apiKey, workspaceId: this.workspaceId, fetch };
|
|
393
|
+
}
|
|
394
|
+
/** Any workspace route, typed from the API: `request("get", "/v1/operator/workspaces/{workspaceId}/labels")`. */
|
|
395
|
+
request(method, path, ...[options]) {
|
|
396
|
+
return call(this.#client(), method, path, options ?? {});
|
|
397
|
+
}
|
|
398
|
+
};
|
|
399
|
+
export {
|
|
400
|
+
Dinghy,
|
|
401
|
+
DinghyError
|
|
402
|
+
};
|