reponly 0.0.0-stage → 0.1.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 ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Reponly
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,137 @@
1
- # Temporary Holding Version
1
+ # reponly
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ The JavaScript SDK for [Reponly](https://reponly.com) customer chat. Use it to build your own in-app support chat instead of the hosted widget. It handles sessions, token storage, retries and real-time messages for you.
4
+
5
+ - No dependencies. It ships its own small real-time client.
6
+ - Works in any browser framework, or with none.
7
+ - TypeScript types included.
8
+
9
+ The hosted Reponly widget runs on this same SDK.
10
+
11
+ ## Before you start
12
+
13
+ - A custom UI needs the **Pro** plan.
14
+ - Add your site's origin to **Allowed domains** in the product's settings. Otherwise browser calls fail with `403 origin_not_allowed`.
15
+ - Copy your **project key** (`pk_...`) and the **base URL** from the product's **Custom UI** tab.
16
+
17
+ ## Install
18
+
19
+ ```sh
20
+ npm install reponly
21
+ ```
22
+
23
+ ## Quick start
24
+
25
+ ```ts
26
+ import { ReponlyClient, ReponlyError } from "reponly";
27
+
28
+ const chat = new ReponlyClient({
29
+ projectKey: "pk_...",
30
+ baseUrl: "https://reponly.com",
31
+ });
32
+
33
+ // Anonymous visitor. The customer token is kept in localStorage, so a returning
34
+ // visitor gets the same chat.
35
+ await chat.connect();
36
+
37
+ const config = await chat.getConfig(); // welcome text, availability, askForEmail, attachments
38
+
39
+ const off = chat.subscribe((event) => {
40
+ if (event.type === "message.created") render(event.message);
41
+ if (event.type === "connection" && event.state === "open") resync(); // after every reconnect
42
+ });
43
+
44
+ try {
45
+ await chat.sendMessage("Hello!"); // sends the current page, language and time zone with it
46
+ } catch (error) {
47
+ if (error instanceof ReponlyError && (error.isRateLimited || error.isRestricted)) {
48
+ showNotice(error.message, error.retryAt);
49
+ }
50
+ }
51
+ ```
52
+
53
+ ## Signed-in users
54
+
55
+ To give a signed-in user the same chat on every device, your backend asks Reponly for an identity token (`POST /api/v1/identify` with your secret key). The **Identify users** tab in Reponly has the exact steps. Pass the token to the SDK:
56
+
57
+ ```ts
58
+ await chat.identify(identityToken);
59
+
60
+ // When your user signs out:
61
+ chat.logout();
62
+ ```
63
+
64
+ ## History
65
+
66
+ ```ts
67
+ const conversations = await chat.listConversations();
68
+ const messages = await chat.getMessages(conversations[0].id);
69
+
70
+ // After a reconnect, fetch only what you missed:
71
+ const newer = await chat.getMessages(conversationId, lastSeenSeq);
72
+ ```
73
+
74
+ Messages are ordered by `seq`.
75
+
76
+ ## Files
77
+
78
+ Upload first, then send the ids. A message can contain only files.
79
+
80
+ ```ts
81
+ if (config.attachments) {
82
+ const file = await chat.uploadAttachment(input.files[0]); // up to 10 MB
83
+ await chat.sendMessage("", { attachmentIds: [file.id] }); // up to 5 per message
84
+ }
85
+ ```
86
+
87
+ Show image attachments (`kind: "image"`) inline and other files as download links.
88
+
89
+ ## Email fallback and read receipts
90
+
91
+ ```ts
92
+ // Guests: after their first message, offer to email them the answer.
93
+ await chat.setContactEmail("maya@example.com");
94
+
95
+ // While your chat is visible, report what was read. Replies the customer
96
+ // already saw aren't emailed.
97
+ await chat.markRead(conversationId, lastSeq);
98
+ ```
99
+
100
+ Check `config.askForEmail`:
101
+
102
+ - `"after_first_message"`: ask after the first message.
103
+ - `"before_first_message"`: ask first, and pass the address as `contactEmail` to `sendMessage`. Do the same when `config.paused` is true.
104
+ - `"never"`: don't ask.
105
+
106
+ ## Errors
107
+
108
+ Every failed call throws a `ReponlyError` with `code`, `message`, `status` and `retryAt`. `message` is written to be shown to the user.
109
+
110
+ | Check | When |
111
+ | --- | --- |
112
+ | `isRateLimited` | Too many messages. `retryAt` says when the customer can send again. |
113
+ | `isRestricted` | The customer is blocked, either temporarily (`retryAt`) or permanently. |
114
+ | `isEmailRequired` | The product needs the customer's email first. |
115
+ | `isNetworkError` | The request didn't reach the server. Retry with the same `clientMessageId`. |
116
+
117
+ `sendMessage` creates a `clientMessageId` for you. Generate one yourself with `createClientMessageId()` and pass it in when you retry, so a retry never sends the same message twice.
118
+
119
+ ## API
120
+
121
+ | Method | Description |
122
+ | --- | --- |
123
+ | `new ReponlyClient({ projectKey, baseUrl?, storage? })` | `baseUrl` defaults to the current origin. `storage` defaults to localStorage, with an in-memory fallback. |
124
+ | `getConfig()` | The product's public settings (cached). |
125
+ | `connect(identityToken?)` | Starts or resumes the session. |
126
+ | `identify(identityToken)` / `logout()` | Sign a user in or out. |
127
+ | `getStatus()` | Any restriction or cooldown on this customer. |
128
+ | `listConversations()` / `getMessages(id, afterSeq?)` | History. |
129
+ | `sendMessage(content, options?)` | Options: `conversationId`, `clientMessageId`, `attachmentIds`, `contactEmail`, `context`. |
130
+ | `uploadAttachment(file, name?)` | Upload one file and get back an `AttachmentView`. |
131
+ | `setContactEmail(email)` | The address replies are emailed to. |
132
+ | `markRead(conversationId, seq)` | Read receipt. |
133
+ | `subscribe(handler)` | Real-time events. Returns an unsubscribe function. |
134
+
135
+ ## License
136
+
137
+ MIT
@@ -0,0 +1,147 @@
1
+ /**
2
+ * Reponly customer SDK — build a custom chat UI or power the hosted widget.
3
+ *
4
+ * const chat = new ReponlyClient({ projectKey: "pk_...", baseUrl: "https://reponly.com" });
5
+ * await chat.connect(); // anonymous visitor (durable id)
6
+ * await chat.identify(identityTokenFromYourServer); // optional: logged-in customer
7
+ * const off = chat.subscribe((event) => ...);
8
+ * await chat.sendMessage("Hi!"); // sends the current page + locale with it
9
+ * const file = await chat.uploadAttachment(fileInput.files[0]);
10
+ * await chat.sendMessage("Screenshot", { attachmentIds: [file.id] });
11
+ * await chat.setContactEmail("me@example.com"); // replies reach them by email after they leave
12
+ * await chat.markRead(conversationId, lastSeq); // while your chat UI is visible
13
+ */
14
+ import type { AttachmentView, CustomerConversationView, CustomerRealtimeEvent, CustomerSessionView, CustomerStatusView, MessageView, PublicProjectConfig } from "./types.js";
15
+ export type * from "./types.js";
16
+ export { customerChannelName } from "./types.js";
17
+ export type TokenStorage = {
18
+ get(key: string): string | null;
19
+ set(key: string, value: string): void;
20
+ remove(key: string): void;
21
+ };
22
+ export type ConnectionEvent = {
23
+ type: "connection";
24
+ state: "open" | "reconnecting";
25
+ };
26
+ export type ReponlyEvent = CustomerRealtimeEvent | ConnectionEvent;
27
+ export type ReponlyClientOptions = {
28
+ projectKey: string;
29
+ /** Origin of the Reponly app. Defaults to the current origin. */
30
+ baseUrl?: string;
31
+ /** Where the customer token is persisted. Defaults to localStorage when available. */
32
+ storage?: TokenStorage | null;
33
+ /**
34
+ * The widget loader's key for this browser on the site (live visitors). Links the visitor's
35
+ * live presence to their chat, and hands them a conversation an agent started with them.
36
+ */
37
+ visitorKey?: string | null;
38
+ };
39
+ /** Page and locale sent with each message, so agents know where the customer was. */
40
+ export type MessageContext = {
41
+ pageUrl?: string;
42
+ pageTitle?: string;
43
+ /** BCP 47, e.g. "en-GB". */
44
+ language?: string;
45
+ /** Every language the browser prefers, in order. */
46
+ languages?: string[];
47
+ /** IANA, e.g. "Europe/Berlin". */
48
+ timezone?: string;
49
+ /** "1440x900" */
50
+ screen?: string;
51
+ };
52
+ /** What the browser can tell about the current page and locale. Empty outside a browser. */
53
+ export declare function currentPageContext(): MessageContext;
54
+ export type SendMessageOptions = {
55
+ conversationId?: string;
56
+ /** Idempotency key. Reuse it when retrying the same message. */
57
+ clientMessageId?: string;
58
+ /**
59
+ * Lets the team answer by email. Required when the project's config says `paused: true`
60
+ * and the customer has no email yet (the API answers `email_required`).
61
+ */
62
+ contactEmail?: string;
63
+ /** Ids from uploadAttachment(); a message may be only attachments (empty text). */
64
+ attachmentIds?: string[];
65
+ /**
66
+ * Page and locale to store with the message. Defaults to the current page
67
+ * (currentPageContext()); pass `null` to send none.
68
+ */
69
+ context?: MessageContext | null;
70
+ /**
71
+ * Hosted widget: the automatic message the visitor answered, saved as the chat's greeting.
72
+ * Custom UIs can leave it out.
73
+ */
74
+ triggerId?: string;
75
+ };
76
+ /** Structured API error. `retryAt` is set for rate limits and temporary restrictions. */
77
+ export declare class ReponlyError extends Error {
78
+ readonly code: string;
79
+ readonly status: number;
80
+ readonly retryAt: Date | null;
81
+ constructor(code: string, message: string, status: number, retryAt: Date | null);
82
+ get isRateLimited(): boolean;
83
+ get isRestricted(): boolean;
84
+ /** The project is paused and needs the customer's email before accepting messages. */
85
+ get isEmailRequired(): boolean;
86
+ /** Network failure: safe to retry with the same clientMessageId. */
87
+ get isNetworkError(): boolean;
88
+ }
89
+ export declare function createClientMessageId(): string;
90
+ export declare class ReponlyClient {
91
+ private readonly projectKey;
92
+ private readonly baseUrl;
93
+ private readonly storage;
94
+ private token;
95
+ private customerId;
96
+ private readonly visitorKey;
97
+ private readonly tokenListeners;
98
+ constructor({ projectKey, baseUrl, storage, visitorKey }: ReponlyClientOptions);
99
+ private get tokenKey();
100
+ /** Storage is the source of truth so several tabs/instances converge on one identity. */
101
+ private currentToken;
102
+ private setToken;
103
+ private request;
104
+ /** Calls an authenticated endpoint, transparently re-establishing an expired session once. */
105
+ private authed;
106
+ private configPromise;
107
+ /** Project appearance + realtime settings (cached; retried after a failure). */
108
+ getConfig(): Promise<PublicProjectConfig>;
109
+ /** Creates or resumes the visitor session. Optionally identifies a logged-in customer. */
110
+ connect(identityToken?: string, resumeToken?: string): Promise<CustomerSessionView["customer"]>;
111
+ /** Links the current visitor to a customer from a token signed by your backend. */
112
+ identify(identityToken: string): Promise<CustomerSessionView["customer"]>;
113
+ /** Forget the stored identity (call when your user logs out). */
114
+ logout(): void;
115
+ getStatus(): Promise<CustomerStatusView>;
116
+ listConversations(): Promise<CustomerConversationView[]>;
117
+ getMessages(conversationId: string, afterSeq?: number): Promise<MessageView[]>;
118
+ sendMessage(content: string, options?: SendMessageOptions): Promise<{
119
+ message: MessageView;
120
+ conversationId: string;
121
+ }>;
122
+ /**
123
+ * Uploads one file (up to 10 MB: images, PDFs, text, Office files, zips, short videos) for the
124
+ * next message. Send its `id` in `attachmentIds`. Needs the server to have file storage set up
125
+ * (the project config's `attachments` is true).
126
+ */
127
+ uploadAttachment(file: Blob, name?: string): Promise<AttachmentView>;
128
+ /** Saves the address replies are emailed to when the customer isn't in the chat. */
129
+ setContactEmail(email: string): Promise<{
130
+ hasEmail: true;
131
+ }>;
132
+ /**
133
+ * Tells Reponly the customer has seen messages up to `seq`. Call it while your chat UI is
134
+ * visible: agents see "Seen", and replies already seen aren't emailed.
135
+ */
136
+ markRead(conversationId: string, seq: number): Promise<{
137
+ customerLastReadSeq: number;
138
+ }>;
139
+ /**
140
+ * Real-time events over the Pusher protocol (Soketi). Emits `{type:"connection", state:"open"}`
141
+ * after every (re)subscribe — refetch messages then, so nothing sent while offline is missed.
142
+ * Follows identity changes (identify/logout) automatically.
143
+ */
144
+ subscribe(handler: (event: ReponlyEvent) => void): () => void;
145
+ private authorizeChannel;
146
+ }
147
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;GAYG;AACH,OAAO,KAAK,EAEV,cAAc,EACd,wBAAwB,EACxB,qBAAqB,EACrB,mBAAmB,EACnB,kBAAkB,EAClB,WAAW,EACX,mBAAmB,EACpB,MAAM,YAAY,CAAC;AAIpB,mBAAmB,YAAY,CAAC;AAChC,OAAO,EAAE,mBAAmB,EAAE,MAAM,YAAY,CAAC;AAEjD,MAAM,MAAM,YAAY,GAAG;IACzB,GAAG,CAAC,GAAG,EAAE,MAAM,GAAG,MAAM,GAAG,IAAI,CAAC;IAChC,GAAG,CAAC,GAAG,EAAE,MAAM,EAAE,KAAK,EAAE,MAAM,GAAG,IAAI,CAAC;IACtC,MAAM,CAAC,GAAG,EAAE,MAAM,GAAG,IAAI,CAAC;CAC3B,CAAC;AAEF,MAAM,MAAM,eAAe,GAAG;IAAE,IAAI,EAAE,YAAY,CAAC;IAAC,KAAK,EAAE,MAAM,GAAG,cAAc,CAAA;CAAE,CAAC;AACrF,MAAM,MAAM,YAAY,GAAG,qBAAqB,GAAG,eAAe,CAAC;AAEnE,MAAM,MAAM,oBAAoB,GAAG;IACjC,UAAU,EAAE,MAAM,CAAC;IACnB,iEAAiE;IACjE,OAAO,CAAC,EAAE,MAAM,CAAC;IACjB,sFAAsF;IACtF,OAAO,CAAC,EAAE,YAAY,GAAG,IAAI,CAAC;IAC9B;;;OAGG;IACH,UAAU,CAAC,EAAE,MAAM,GAAG,IAAI,CAAC;CAC5B,CAAC;AAEF,qFAAqF;AACrF,MAAM,MAAM,cAAc,GAAG;IAC3B,OAAO,CAAC,EAAE,MAAM,CAAC;IACjB,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB,4BAA4B;IAC5B,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB,oDAAoD;IACp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,KAAK,EAAE,MAAM,GAAG,OAAO,CAAC;QAAE,QAAQ,EAAE,IAAI,CAAA;KAAE,CAAC;IAI3D;;;OAGG;IACH,QAAQ,CAAC,cAAc,EAAE,MAAM,EAAE,GAAG,EAAE,MAAM,GAAG,OAAO,CAAC;QAAE,mBAAmB,EAAE,MAAM,CAAA;KAAE,CAAC;IAOvF;;;;OAIG;IACH,SAAS,CAAC,OAAO,EAAE,CAAC,KAAK,EAAE,YAAY,KAAK,IAAI,GAAG,MAAM,IAAI;YAkD/C,gBAAgB;CAyB/B"}
package/dist/index.js ADDED
@@ -0,0 +1,311 @@
1
+ import { customerChannelName } from "./types.js";
2
+ import { PusherLite } from "./pusherLite.js";
3
+ export { customerChannelName } from "./types.js";
4
+ /** What the browser can tell about the current page and locale. Empty outside a browser. */
5
+ export function currentPageContext() {
6
+ var _a;
7
+ if (typeof window === "undefined")
8
+ return {};
9
+ const context = {
10
+ pageUrl: window.location.href,
11
+ pageTitle: document.title || undefined,
12
+ language: navigator.language || undefined,
13
+ languages: ((_a = navigator.languages) === null || _a === void 0 ? void 0 : _a.length) ? navigator.languages.slice(0, 5) : undefined,
14
+ screen: window.screen ? `${window.screen.width}x${window.screen.height}` : undefined,
15
+ };
16
+ try {
17
+ context.timezone = Intl.DateTimeFormat().resolvedOptions().timeZone;
18
+ }
19
+ catch {
20
+ // Old browsers without Intl time zones: leave it out.
21
+ }
22
+ return context;
23
+ }
24
+ /** Structured API error. `retryAt` is set for rate limits and temporary restrictions. */
25
+ export class ReponlyError extends Error {
26
+ constructor(code, message, status, retryAt) {
27
+ super(message);
28
+ this.name = "ReponlyError";
29
+ this.code = code;
30
+ this.status = status;
31
+ this.retryAt = retryAt;
32
+ }
33
+ get isRateLimited() {
34
+ return this.code === "rate_limited";
35
+ }
36
+ get isRestricted() {
37
+ return this.code === "customer_restricted";
38
+ }
39
+ /** The project is paused and needs the customer's email before accepting messages. */
40
+ get isEmailRequired() {
41
+ return this.code === "email_required";
42
+ }
43
+ /** Network failure: safe to retry with the same clientMessageId. */
44
+ get isNetworkError() {
45
+ return this.code === "network";
46
+ }
47
+ }
48
+ const memoryStorage = () => {
49
+ const map = new Map();
50
+ return {
51
+ get: (k) => { var _a; return (_a = map.get(k)) !== null && _a !== void 0 ? _a : null; },
52
+ set: (k, v) => void map.set(k, v),
53
+ remove: (k) => void map.delete(k),
54
+ };
55
+ };
56
+ function defaultStorage() {
57
+ try {
58
+ const probe = "__reponly_probe__";
59
+ window.localStorage.setItem(probe, "1");
60
+ window.localStorage.removeItem(probe);
61
+ return {
62
+ get: (k) => window.localStorage.getItem(k),
63
+ set: (k, v) => window.localStorage.setItem(k, v),
64
+ remove: (k) => window.localStorage.removeItem(k),
65
+ };
66
+ }
67
+ catch {
68
+ return memoryStorage();
69
+ }
70
+ }
71
+ export function createClientMessageId() {
72
+ const random = typeof crypto !== "undefined" && "randomUUID" in crypto
73
+ ? crypto.randomUUID().replace(/-/g, "")
74
+ : `${Date.now().toString(36)}${Math.random().toString(36).slice(2, 12)}`;
75
+ return `cm_${random}`;
76
+ }
77
+ /** Session requests in flight, shared by every client instance for the same project. */
78
+ const inflightSessions = new Map();
79
+ export class ReponlyClient {
80
+ constructor({ projectKey, baseUrl, storage, visitorKey }) {
81
+ this.customerId = null;
82
+ this.tokenListeners = new Set();
83
+ this.configPromise = null;
84
+ this.projectKey = projectKey;
85
+ this.visitorKey = visitorKey !== null && visitorKey !== void 0 ? visitorKey : null;
86
+ this.baseUrl = (baseUrl !== null && baseUrl !== void 0 ? baseUrl : (typeof window !== "undefined" ? window.location.origin : "")).replace(/\/$/, "");
87
+ this.storage = storage !== null && storage !== void 0 ? storage : (typeof window !== "undefined" ? defaultStorage() : memoryStorage());
88
+ this.token = this.storage.get(this.tokenKey);
89
+ }
90
+ get tokenKey() {
91
+ return `reponly:${this.projectKey}:token`;
92
+ }
93
+ /** Storage is the source of truth so several tabs/instances converge on one identity. */
94
+ currentToken() {
95
+ var _a;
96
+ this.token = (_a = this.storage.get(this.tokenKey)) !== null && _a !== void 0 ? _a : this.token;
97
+ return this.token;
98
+ }
99
+ setToken(token) {
100
+ const changed = token !== this.token;
101
+ this.token = token;
102
+ if (token)
103
+ this.storage.set(this.tokenKey, token);
104
+ else
105
+ this.storage.remove(this.tokenKey);
106
+ if (changed)
107
+ for (const listener of this.tokenListeners)
108
+ listener();
109
+ }
110
+ async request(path, init = {}, authenticated = true) {
111
+ const headers = new Headers(init.headers);
112
+ if (typeof init.body === "string")
113
+ headers.set("Content-Type", "application/json");
114
+ const token = authenticated ? this.currentToken() : null;
115
+ if (token)
116
+ headers.set("Authorization", `Bearer ${token}`);
117
+ let response;
118
+ try {
119
+ response = await fetch(`${this.baseUrl}${path}`, { ...init, headers });
120
+ }
121
+ catch {
122
+ throw new ReponlyError("network", "Connection lost. Check your network and try again.", 0, null);
123
+ }
124
+ const payload = (await response.json().catch(() => null));
125
+ if (!payload)
126
+ throw new ReponlyError("internal", "Unexpected server response", response.status, null);
127
+ if (!payload.success) {
128
+ const { code, message, retryAt } = payload.error;
129
+ throw new ReponlyError(code, message, response.status, retryAt ? new Date(retryAt) : null);
130
+ }
131
+ return payload.data;
132
+ }
133
+ /** Calls an authenticated endpoint, transparently re-establishing an expired session once. */
134
+ async authed(path, init = {}) {
135
+ if (!this.currentToken())
136
+ await this.connect();
137
+ try {
138
+ return await this.request(path, init);
139
+ }
140
+ catch (error) {
141
+ if (!(error instanceof ReponlyError) || error.code !== "unauthorized")
142
+ throw error;
143
+ this.setToken(null);
144
+ await this.connect();
145
+ return this.request(path, init);
146
+ }
147
+ }
148
+ /** Project appearance + realtime settings (cached; retried after a failure). */
149
+ getConfig() {
150
+ var _a;
151
+ (_a = this.configPromise) !== null && _a !== void 0 ? _a : (this.configPromise = this.request(`/api/v1/projects/${encodeURIComponent(this.projectKey)}/config`, {}, false).catch((error) => {
152
+ this.configPromise = null;
153
+ throw error;
154
+ }));
155
+ return this.configPromise;
156
+ }
157
+ /** Creates or resumes the visitor session. Optionally identifies a logged-in customer. */
158
+ async connect(identityToken, resumeToken) {
159
+ const key = `${this.baseUrl}|${this.tokenKey}|${identityToken !== null && identityToken !== void 0 ? identityToken : ""}|${resumeToken !== null && resumeToken !== void 0 ? resumeToken : ""}`;
160
+ let pending = inflightSessions.get(key);
161
+ if (!pending) {
162
+ pending = this.request("/api/v1/sessions", {
163
+ method: "POST",
164
+ body: JSON.stringify({
165
+ projectKey: this.projectKey,
166
+ customerToken: this.currentToken(),
167
+ identityToken: identityToken !== null && identityToken !== void 0 ? identityToken : null,
168
+ resumeToken: resumeToken !== null && resumeToken !== void 0 ? resumeToken : null,
169
+ visitorKey: this.visitorKey,
170
+ }),
171
+ }, false).finally(() => inflightSessions.delete(key));
172
+ inflightSessions.set(key, pending);
173
+ }
174
+ const session = await pending;
175
+ this.customerId = session.customer.id;
176
+ this.setToken(session.customerToken);
177
+ return session.customer;
178
+ }
179
+ /** Links the current visitor to a customer from a token signed by your backend. */
180
+ identify(identityToken) {
181
+ return this.connect(identityToken);
182
+ }
183
+ /** Forget the stored identity (call when your user logs out). */
184
+ logout() {
185
+ this.customerId = null;
186
+ this.setToken(null);
187
+ }
188
+ getStatus() {
189
+ return this.authed("/api/v1/status");
190
+ }
191
+ listConversations() {
192
+ return this.authed("/api/v1/conversations");
193
+ }
194
+ getMessages(conversationId, afterSeq = 0) {
195
+ return this.authed(`/api/v1/conversations/${encodeURIComponent(conversationId)}/messages?after=${afterSeq}`);
196
+ }
197
+ sendMessage(content, options = {}) {
198
+ var _a, _b;
199
+ const body = JSON.stringify({
200
+ content,
201
+ clientMessageId: (_a = options.clientMessageId) !== null && _a !== void 0 ? _a : createClientMessageId(),
202
+ contactEmail: options.contactEmail,
203
+ attachmentIds: options.attachmentIds,
204
+ triggerId: options.triggerId,
205
+ context: options.context === undefined ? currentPageContext() : ((_b = options.context) !== null && _b !== void 0 ? _b : undefined),
206
+ });
207
+ const path = options.conversationId
208
+ ? `/api/v1/conversations/${encodeURIComponent(options.conversationId)}/messages`
209
+ : "/api/v1/messages";
210
+ return this.authed(path, { method: "POST", body });
211
+ }
212
+ /**
213
+ * Uploads one file (up to 10 MB: images, PDFs, text, Office files, zips, short videos) for the
214
+ * next message. Send its `id` in `attachmentIds`. Needs the server to have file storage set up
215
+ * (the project config's `attachments` is true).
216
+ */
217
+ async uploadAttachment(file, name) {
218
+ const form = new FormData();
219
+ form.append("file", file, name !== null && name !== void 0 ? name : (file instanceof File ? file.name : "file"));
220
+ return this.authed("/api/v1/attachments", { method: "POST", body: form });
221
+ }
222
+ /** Saves the address replies are emailed to when the customer isn't in the chat. */
223
+ setContactEmail(email) {
224
+ return this.authed("/api/v1/contact", { method: "POST", body: JSON.stringify({ email }) });
225
+ }
226
+ /**
227
+ * Tells Reponly the customer has seen messages up to `seq`. Call it while your chat UI is
228
+ * visible: agents see "Seen", and replies already seen aren't emailed.
229
+ */
230
+ markRead(conversationId, seq) {
231
+ return this.authed(`/api/v1/conversations/${encodeURIComponent(conversationId)}/read`, {
232
+ method: "POST",
233
+ body: JSON.stringify({ seq }),
234
+ });
235
+ }
236
+ /**
237
+ * Real-time events over the Pusher protocol (Soketi). Emits `{type:"connection", state:"open"}`
238
+ * after every (re)subscribe — refetch messages then, so nothing sent while offline is missed.
239
+ * Follows identity changes (identify/logout) automatically.
240
+ */
241
+ subscribe(handler) {
242
+ let stopped = false;
243
+ let socket = null;
244
+ let leaveChannel = () => undefined;
245
+ let joinedCustomerId = null;
246
+ const join = (prefix) => {
247
+ if (!socket || stopped || joinedCustomerId === this.customerId)
248
+ return;
249
+ leaveChannel();
250
+ leaveChannel = () => undefined;
251
+ joinedCustomerId = this.customerId;
252
+ if (!joinedCustomerId)
253
+ return;
254
+ leaveChannel = socket.subscribe(customerChannelName(prefix, joinedCustomerId), {
255
+ onEvent: (_event, data) => handler(data),
256
+ onSubscribed: () => handler({ type: "connection", state: "open" }),
257
+ });
258
+ };
259
+ let onIdentityChange = () => undefined;
260
+ const start = async () => {
261
+ const [config] = await Promise.all([this.getConfig(), this.connect()]);
262
+ if (stopped)
263
+ return;
264
+ socket = new PusherLite({
265
+ ...config.realtime,
266
+ authorize: (socketId, channel) => this.authorizeChannel(socketId, channel),
267
+ onStateChange: (state) => state === "disconnected" && handler({ type: "connection", state: "reconnecting" }),
268
+ });
269
+ onIdentityChange = () => join(config.realtime.channelPrefix);
270
+ this.tokenListeners.add(onIdentityChange);
271
+ join(config.realtime.channelPrefix);
272
+ socket.connect();
273
+ };
274
+ const boot = () => start().catch(() => {
275
+ if (stopped)
276
+ return;
277
+ handler({ type: "connection", state: "reconnecting" });
278
+ setTimeout(boot, 5000);
279
+ });
280
+ void boot();
281
+ return () => {
282
+ stopped = true;
283
+ this.tokenListeners.delete(onIdentityChange);
284
+ leaveChannel();
285
+ socket === null || socket === void 0 ? void 0 : socket.disconnect();
286
+ };
287
+ }
288
+ async authorizeChannel(socketId, channel) {
289
+ const attempt = () => {
290
+ var _a;
291
+ return fetch(`${this.baseUrl}/api/v1/realtime/auth`, {
292
+ method: "POST",
293
+ headers: {
294
+ "Content-Type": "application/json",
295
+ Authorization: `Bearer ${(_a = this.currentToken()) !== null && _a !== void 0 ? _a : ""}`,
296
+ },
297
+ body: JSON.stringify({ socket_id: socketId, channel_name: channel }),
298
+ });
299
+ };
300
+ let response = await attempt();
301
+ if (response.status === 401) {
302
+ this.setToken(null);
303
+ await this.connect();
304
+ response = await attempt();
305
+ }
306
+ if (!response.ok)
307
+ throw new ReponlyError("unauthorized", "Realtime authorization failed", response.status, null);
308
+ return (await response.json()).auth;
309
+ }
310
+ }
311
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAuBA,OAAO,EAAE,mBAAmB,EAAE,MAAM,YAAY,CAAC;AACjD,OAAO,EAAE,UAAU,EAAE,MAAM,iBAAiB,CAAC;AAG7C,OAAO,EAAE,mBAAmB,EAAE,MAAM,YAAY,CAAC;AAsCjD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AC,gBAAgB,CAAC,CAAC;YAC7C,YAAY,EAAE,CAAC;YACf,MAAM,aAAN,MAAM,uBAAN,MAAM,CAAE,UAAU,EAAE,CAAC;QACvB,CAAC,CAAC;IACJ,CAAC;IAEO,KAAK,CAAC,gBAAgB,CAAC,QAAgB,EAAE,OAAe;QAC9D,MAAM,OAAO,GAAG,GAAG,EAAE;;YACnB,OAAA,KAAK,CAAC,GAAG,IAAI,CAAC,OAAO,uBAAuB,EAAE;gBAC5C,MAAM,EAAE,MAAM;gBACd,OAAO,EAAE;oBACP,cAAc,EAAE,kBAAkB;oBAClC,aAAa,EAAE,UAAU,MAAA,IAAI,CAAC,YAAY,EAAE,mCAAI,EAAE,EAAE;iBACrD;gBACD,IAAI,EAAE,IAAI,CAAC,SAAS,CAAC,EAAE,SAAS,EAAE,QAAQ,EAAE,YAAY,EAAE,OAAO,EAAE,CAAC;aACrE,CAAC,CAAA;SAAA,CAAC;QACL,IAAI,QAAQ,GAAG,MAAM,OAAO,EAAE,CAAC;QAC/B,IAAI,QAAQ,CAAC,MAAM,KAAK,GAAG,EAAE,CAAC;YAC5B,IAAI,CAAC,QAAQ,CAAC,IAAI,CAAC,CAAC;YACpB,MAAM,IAAI,CAAC,OAAO,EAAE,CAAC;YACrB,QAAQ,GAAG,MAAM,OAAO,EAAE,CAAC;QAC7B,CAAC;QACD,IAAI,CAAC,QAAQ,CAAC,EAAE;YACd,MAAM,IAAI,YAAY,CACpB,cAAc,EACd,+BAA+B,EAC/B,QAAQ,CAAC,MAAM,EACf,IAAI,CACL,CAAC;QACJ,OAAQ,CAAC,MAAM,QAAQ,CAAC,IAAI,EAAE,CAAsB,CAAC,IAAI,CAAC;IAC5D,CAAC;CACF","sourcesContent":["/**\n * Reponly customer SDK — build a custom chat UI or power the hosted widget.\n *\n * const chat = new ReponlyClient({ projectKey: \"pk_...\", baseUrl: \"https://reponly.com\" });\n * await chat.connect(); // anonymous visitor (durable id)\n * await chat.identify(identityTokenFromYourServer); // optional: logged-in customer\n * const off = chat.subscribe((event) => ...);\n * await chat.sendMessage(\"Hi!\"); // sends the current page + locale with it\n * const file = await chat.uploadAttachment(fileInput.files[0]);\n * await chat.sendMessage(\"Screenshot\", { attachmentIds: [file.id] });\n * await chat.setContactEmail(\"me@example.com\"); // replies reach them by email after they leave\n * await chat.markRead(conversationId, lastSeq); // while your chat UI is visible\n */\nimport type {\n ApiResponse,\n AttachmentView,\n CustomerConversationView,\n CustomerRealtimeEvent,\n CustomerSessionView,\n CustomerStatusView,\n MessageView,\n PublicProjectConfig,\n} from \"./types.js\";\nimport { customerChannelName } from \"./types.js\";\nimport { PusherLite } from \"./pusherLite.js\";\n\nexport type * from \"./types.js\";\nexport { customerChannelName } from \"./types.js\";\n\nexport type TokenStorage = {\n get(key: string): string | null;\n set(key: string, value: string): void;\n remove(key: string): void;\n};\n\nexport type ConnectionEvent = { type: \"connection\"; state: \"open\" | \"reconnecting\" };\nexport type ReponlyEvent = CustomerRealtimeEvent | ConnectionEvent;\n\nexport type ReponlyClientOptions = {\n projectKey: string;\n /** Origin of the Reponly app. Defaults to the current origin. */\n baseUrl?: string;\n /** Where the customer token is persisted. Defaults to localStorage when available. */\n storage?: TokenStorage | null;\n /**\n * The widget loader's key for this browser on the site (live visitors). Links the visitor's\n * live presence to their chat, and hands them a conversation an agent started with them.\n */\n visitorKey?: string | null;\n};\n\n/** Page and locale sent with each message, so agents know where the customer was. */\nexport type MessageContext = {\n pageUrl?: string;\n pageTitle?: string;\n /** BCP 47, e.g. \"en-GB\". */\n language?: string;\n /** Every language the browser prefers, in order. */\n languages?: string[];\n /** IANA, e.g. \"Europe/Berlin\". */\n timezone?: string;\n /** \"1440x900\" */\n screen?: string;\n};\n\n/** What the browser can tell about the current page and locale. Empty outside a browser. */\nexport function currentPageContext(): MessageContext {\n if (typeof window === \"undefined\") return {};\n const context: MessageContext = {\n pageUrl: window.location.href,\n pageTitle: document.title || undefined,\n language: navigator.language || undefined,\n languages: navigator.languages?.length ? navigator.languages.slice(0, 5) : undefined,\n screen: window.screen ? `${window.screen.width}x${window.screen.height}` : undefined,\n };\n try {\n context.timezone = Intl.DateTimeFormat().resolvedOptions().timeZone;\n } catch {\n // Old browsers without Intl time zones: leave it out.\n }\n return context;\n}\n\nexport type SendMessageOptions = {\n conversationId?: string;\n /** Idempotency key. Reuse it when retrying the same message. */\n clientMessageId?: string;\n /**\n * Lets the team answer by email. Required when the project's config says `paused: true`\n * and the customer has no email yet (the API answers `email_required`).\n */\n contactEmail?: string;\n /** Ids from uploadAttachment(); a message may be only attachments (empty text). */\n attachmentIds?: string[];\n /**\n * Page and locale to store with the message. Defaults to the current page\n * (currentPageContext()); pass `null` to send none.\n */\n context?: MessageContext | null;\n /**\n * Hosted widget: the automatic message the visitor answered, saved as the chat's greeting.\n * Custom UIs can leave it out.\n */\n triggerId?: string;\n};\n\n/** Structured API error. `retryAt` is set for rate limits and temporary restrictions. */\nexport class ReponlyError extends Error {\n readonly code: string;\n readonly status: number;\n readonly retryAt: Date | null;\n\n constructor(code: string, message: string, status: number, retryAt: Date | null) {\n super(message);\n this.name = \"ReponlyError\";\n this.code = code;\n this.status = status;\n this.retryAt = retryAt;\n }\n\n get isRateLimited(): boolean {\n return this.code === \"rate_limited\";\n }\n\n get isRestricted(): boolean {\n return this.code === \"customer_restricted\";\n }\n\n /** The project is paused and needs the customer's email before accepting messages. */\n get isEmailRequired(): boolean {\n return this.code === \"email_required\";\n }\n\n /** Network failure: safe to retry with the same clientMessageId. */\n get isNetworkError(): boolean {\n return this.code === \"network\";\n }\n}\n\nconst memoryStorage = (): TokenStorage => {\n const map = new Map<string, string>();\n return {\n get: (k) => map.get(k) ?? null,\n set: (k, v) => void map.set(k, v),\n remove: (k) => void map.delete(k),\n };\n};\n\nfunction defaultStorage(): TokenStorage {\n try {\n const probe = \"__reponly_probe__\";\n window.localStorage.setItem(probe, \"1\");\n window.localStorage.removeItem(probe);\n return {\n get: (k) => window.localStorage.getItem(k),\n set: (k, v) => window.localStorage.setItem(k, v),\n remove: (k) => window.localStorage.removeItem(k),\n };\n } catch {\n return memoryStorage();\n }\n}\n\nexport function createClientMessageId(): string {\n const random =\n typeof crypto !== \"undefined\" && \"randomUUID\" in crypto\n ? crypto.randomUUID().replace(/-/g, \"\")\n : `${Date.now().toString(36)}${Math.random().toString(36).slice(2, 12)}`;\n return `cm_${random}`;\n}\n\n/** Session requests in flight, shared by every client instance for the same project. */\nconst inflightSessions = new Map<string, Promise<CustomerSessionView>>();\n\nexport class ReponlyClient {\n private readonly projectKey: string;\n private readonly baseUrl: string;\n private readonly storage: TokenStorage;\n private token: string | null;\n private customerId: string | null = null;\n private readonly visitorKey: string | null;\n private readonly tokenListeners = new Set<() => void>();\n\n constructor({ projectKey, baseUrl, storage, visitorKey }: ReponlyClientOptions) {\n this.projectKey = projectKey;\n this.visitorKey = visitorKey ?? null;\n this.baseUrl = (\n baseUrl ?? (typeof window !== \"undefined\" ? window.location.origin : \"\")\n ).replace(/\\/$/, \"\");\n this.storage = storage ?? (typeof window !== \"undefined\" ? defaultStorage() : memoryStorage());\n this.token = this.storage.get(this.tokenKey);\n }\n\n private get tokenKey(): string {\n return `reponly:${this.projectKey}:token`;\n }\n\n /** Storage is the source of truth so several tabs/instances converge on one identity. */\n private currentToken(): string | null {\n this.token = this.storage.get(this.tokenKey) ?? this.token;\n return this.token;\n }\n\n private setToken(token: string | null): void {\n const changed = token !== this.token;\n this.token = token;\n if (token) this.storage.set(this.tokenKey, token);\n else this.storage.remove(this.tokenKey);\n if (changed) for (const listener of this.tokenListeners) listener();\n }\n\n private async request<T>(path: string, init: RequestInit = {}, authenticated = true): Promise<T> {\n const headers = new Headers(init.headers);\n if (typeof init.body === \"string\") headers.set(\"Content-Type\", \"application/json\");\n const token = authenticated ? this.currentToken() : null;\n if (token) headers.set(\"Authorization\", `Bearer ${token}`);\n let response: Response;\n try {\n response = await fetch(`${this.baseUrl}${path}`, { ...init, headers });\n } catch {\n throw new ReponlyError(\n \"network\",\n \"Connection lost. Check your network and try again.\",\n 0,\n null,\n );\n }\n const payload = (await response.json().catch(() => null)) as ApiResponse<T> | null;\n if (!payload)\n throw new ReponlyError(\"internal\", \"Unexpected server response\", response.status, null);\n if (!payload.success) {\n const { code, message, retryAt } = payload.error;\n throw new ReponlyError(code, message, response.status, retryAt ? new Date(retryAt) : null);\n }\n return payload.data;\n }\n\n /** Calls an authenticated endpoint, transparently re-establishing an expired session once. */\n private async authed<T>(path: string, init: RequestInit = {}): Promise<T> {\n if (!this.currentToken()) await this.connect();\n try {\n return await this.request<T>(path, init);\n } catch (error) {\n if (!(error instanceof ReponlyError) || error.code !== \"unauthorized\") throw error;\n this.setToken(null);\n await this.connect();\n return this.request<T>(path, init);\n }\n }\n\n private configPromise: Promise<PublicProjectConfig> | null = null;\n\n /** Project appearance + realtime settings (cached; retried after a failure). */\n getConfig(): Promise<PublicProjectConfig> {\n this.configPromise ??= this.request<PublicProjectConfig>(\n `/api/v1/projects/${encodeURIComponent(this.projectKey)}/config`,\n {},\n false,\n ).catch((error: unknown) => {\n this.configPromise = null;\n throw error;\n });\n return this.configPromise;\n }\n\n /** Creates or resumes the visitor session. Optionally identifies a logged-in customer. */\n async connect(\n identityToken?: string,\n resumeToken?: string,\n ): Promise<CustomerSessionView[\"customer\"]> {\n const key = `${this.baseUrl}|${this.tokenKey}|${identityToken ?? \"\"}|${resumeToken ?? \"\"}`;\n let pending = inflightSessions.get(key);\n if (!pending) {\n pending = this.request<CustomerSessionView>(\n \"/api/v1/sessions\",\n {\n method: \"POST\",\n body: JSON.stringify({\n projectKey: this.projectKey,\n customerToken: this.currentToken(),\n identityToken: identityToken ?? null,\n resumeToken: resumeToken ?? null,\n visitorKey: this.visitorKey,\n }),\n },\n false,\n ).finally(() => inflightSessions.delete(key));\n inflightSessions.set(key, pending);\n }\n const session = await pending;\n this.customerId = session.customer.id;\n this.setToken(session.customerToken);\n return session.customer;\n }\n\n /** Links the current visitor to a customer from a token signed by your backend. */\n identify(identityToken: string): Promise<CustomerSessionView[\"customer\"]> {\n return this.connect(identityToken);\n }\n\n /** Forget the stored identity (call when your user logs out). */\n logout(): void {\n this.customerId = null;\n this.setToken(null);\n }\n\n getStatus(): Promise<CustomerStatusView> {\n return this.authed(\"/api/v1/status\");\n }\n\n listConversations(): Promise<CustomerConversationView[]> {\n return this.authed(\"/api/v1/conversations\");\n }\n\n getMessages(conversationId: string, afterSeq = 0): Promise<MessageView[]> {\n return this.authed(\n `/api/v1/conversations/${encodeURIComponent(conversationId)}/messages?after=${afterSeq}`,\n );\n }\n\n sendMessage(\n content: string,\n options: SendMessageOptions = {},\n ): Promise<{ message: MessageView; conversationId: string }> {\n const body = JSON.stringify({\n content,\n clientMessageId: options.clientMessageId ?? createClientMessageId(),\n contactEmail: options.contactEmail,\n attachmentIds: options.attachmentIds,\n triggerId: options.triggerId,\n context:\n options.context === undefined ? currentPageContext() : (options.context ?? undefined),\n });\n const path = options.conversationId\n ? `/api/v1/conversations/${encodeURIComponent(options.conversationId)}/messages`\n : \"/api/v1/messages\";\n return this.authed(path, { method: \"POST\", body });\n }\n\n /**\n * Uploads one file (up to 10 MB: images, PDFs, text, Office files, zips, short videos) for the\n * next message. Send its `id` in `attachmentIds`. Needs the server to have file storage set up\n * (the project config's `attachments` is true).\n */\n async uploadAttachment(file: Blob, name?: string): Promise<AttachmentView> {\n const form = new FormData();\n form.append(\"file\", file, name ?? (file instanceof File ? file.name : \"file\"));\n return this.authed(\"/api/v1/attachments\", { method: \"POST\", body: form });\n }\n\n /** Saves the address replies are emailed to when the customer isn't in the chat. */\n setContactEmail(email: string): Promise<{ hasEmail: true }> {\n return this.authed(\"/api/v1/contact\", { method: \"POST\", body: JSON.stringify({ email }) });\n }\n\n /**\n * Tells Reponly the customer has seen messages up to `seq`. Call it while your chat UI is\n * visible: agents see \"Seen\", and replies already seen aren't emailed.\n */\n markRead(conversationId: string, seq: number): Promise<{ customerLastReadSeq: number }> {\n return this.authed(`/api/v1/conversations/${encodeURIComponent(conversationId)}/read`, {\n method: \"POST\",\n body: JSON.stringify({ seq }),\n });\n }\n\n /**\n * Real-time events over the Pusher protocol (Soketi). Emits `{type:\"connection\", state:\"open\"}`\n * after every (re)subscribe — refetch messages then, so nothing sent while offline is missed.\n * Follows identity changes (identify/logout) automatically.\n */\n subscribe(handler: (event: ReponlyEvent) => void): () => void {\n let stopped = false;\n let socket: PusherLite | null = null;\n let leaveChannel: () => void = () => undefined;\n let joinedCustomerId: string | null = null;\n\n const join = (prefix: string) => {\n if (!socket || stopped || joinedCustomerId === this.customerId) return;\n leaveChannel();\n leaveChannel = () => undefined;\n joinedCustomerId = this.customerId;\n if (!joinedCustomerId) return;\n leaveChannel = socket.subscribe(customerChannelName(prefix, joinedCustomerId), {\n onEvent: (_event, data) => handler(data as CustomerRealtimeEvent),\n onSubscribed: () => handler({ type: \"connection\", state: \"open\" }),\n });\n };\n\n let onIdentityChange: () => void = () => undefined;\n const start = async () => {\n const [config] = await Promise.all([this.getConfig(), this.connect()]);\n if (stopped) return;\n socket = new PusherLite({\n ...config.realtime,\n authorize: (socketId, channel) => this.authorizeChannel(socketId, channel),\n onStateChange: (state) =>\n state === \"disconnected\" && handler({ type: \"connection\", state: \"reconnecting\" }),\n });\n onIdentityChange = () => join(config.realtime.channelPrefix);\n this.tokenListeners.add(onIdentityChange);\n join(config.realtime.channelPrefix);\n socket.connect();\n };\n\n const boot = () =>\n start().catch(() => {\n if (stopped) return;\n handler({ type: \"connection\", state: \"reconnecting\" });\n setTimeout(boot, 5_000);\n });\n void boot();\n\n return () => {\n stopped = true;\n this.tokenListeners.delete(onIdentityChange);\n leaveChannel();\n socket?.disconnect();\n };\n }\n\n private async authorizeChannel(socketId: string, channel: string): Promise<string> {\n const attempt = () =>\n fetch(`${this.baseUrl}/api/v1/realtime/auth`, {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n Authorization: `Bearer ${this.currentToken() ?? \"\"}`,\n },\n body: JSON.stringify({ socket_id: socketId, channel_name: channel }),\n });\n let response = await attempt();\n if (response.status === 401) {\n this.setToken(null);\n await this.connect();\n response = await attempt();\n }\n if (!response.ok)\n throw new ReponlyError(\n \"unauthorized\",\n \"Realtime authorization failed\",\n response.status,\n null,\n );\n return ((await response.json()) as { auth: string }).auth;\n }\n}\n"]}
@@ -0,0 +1,48 @@
1
+ /**
2
+ * Minimal Pusher-protocol (v7) client for Soketi — a few KB instead of pusher-js, so the widget
3
+ * stays light. Supports private channels, ping/pong, activity timeout and reconnect with backoff.
4
+ */
5
+ import type { RealtimeClientConfig } from "./types.js";
6
+ export type ConnectionState = "connecting" | "connected" | "disconnected";
7
+ type ChannelHandlers = {
8
+ onEvent: (event: string, data: unknown) => void;
9
+ onSubscribed?: () => void;
10
+ };
11
+ type Options = RealtimeClientConfig & {
12
+ /** Returns the `auth` signature for a private channel. */
13
+ authorize: (socketId: string, channel: string) => Promise<string>;
14
+ onStateChange?: (state: ConnectionState) => void;
15
+ /** Injectable for tests. */
16
+ WebSocketImpl?: typeof WebSocket;
17
+ };
18
+ export declare class PusherLite {
19
+ private readonly options;
20
+ private socket;
21
+ private socketId;
22
+ private readonly channels;
23
+ private activityTimeoutMs;
24
+ private activityTimer;
25
+ private pongTimer;
26
+ private reconnectTimer;
27
+ private attempt;
28
+ private stopped;
29
+ constructor(options: Options);
30
+ private get url();
31
+ connect(): void;
32
+ disconnect(): void;
33
+ subscribe(channel: string, handlers: ChannelHandlers): () => void;
34
+ private open;
35
+ private handleFrame;
36
+ /** 4000–4099: fatal (bad app key / origin), so stop. Anything else reconnects. */
37
+ private handleError;
38
+ private sendSubscribe;
39
+ private retrySubscribe;
40
+ private send;
41
+ private handleClose;
42
+ /** Server expects traffic within activity_timeout; ping when idle, reconnect if no pong. */
43
+ private resetActivityTimer;
44
+ private clearPongTimer;
45
+ private clearTimers;
46
+ }
47
+ export {};
48
+ //# sourceMappingURL=pusherLite.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"pusherLite.d.ts","sourceRoot":"","sources":["../src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AClF,OAAO,CAAC,WAAW;YAIL,aAAa;IAa3B,OAAO,CAAC,cAAc;IAMtB,OAAO,CAAC,IAAI;IAIZ,OAAO,CAAC,WAAW;IAYnB,4FAA4F;IAC5F,OAAO,CAAC,kBAAkB;IAQ1B,OAAO,CAAC,cAAc;IAKtB,OAAO,CAAC,WAAW;CAIpB"}
@@ -0,0 +1,161 @@
1
+ const PROTOCOL_VERSION = 7;
2
+ const PONG_TIMEOUT_MS = 30000;
3
+ const MAX_BACKOFF_MS = 30000;
4
+ const parseData = (data) => {
5
+ if (typeof data !== "string")
6
+ return data;
7
+ try {
8
+ return JSON.parse(data);
9
+ }
10
+ catch {
11
+ return data;
12
+ }
13
+ };
14
+ export class PusherLite {
15
+ constructor(options) {
16
+ this.options = options;
17
+ this.socket = null;
18
+ this.socketId = null;
19
+ this.channels = new Map();
20
+ this.activityTimeoutMs = 120000;
21
+ this.activityTimer = null;
22
+ this.pongTimer = null;
23
+ this.reconnectTimer = null;
24
+ this.attempt = 0;
25
+ this.stopped = true;
26
+ }
27
+ get url() {
28
+ const { forceTLS, wsHost, wsPort, key } = this.options;
29
+ return `${forceTLS ? "wss" : "ws"}://${wsHost}:${wsPort}/app/${encodeURIComponent(key)}?protocol=${PROTOCOL_VERSION}&client=reponly-js&version=1.0.0&flash=false`;
30
+ }
31
+ connect() {
32
+ if (!this.stopped)
33
+ return;
34
+ this.stopped = false;
35
+ this.open();
36
+ }
37
+ disconnect() {
38
+ var _a;
39
+ this.stopped = true;
40
+ this.clearTimers();
41
+ (_a = this.socket) === null || _a === void 0 ? void 0 : _a.close();
42
+ this.socket = null;
43
+ this.socketId = null;
44
+ }
45
+ subscribe(channel, handlers) {
46
+ this.channels.set(channel, handlers);
47
+ if (this.socketId)
48
+ void this.sendSubscribe(channel);
49
+ return () => {
50
+ this.channels.delete(channel);
51
+ this.send({ event: "pusher:unsubscribe", data: { channel } });
52
+ };
53
+ }
54
+ open() {
55
+ var _a, _b, _c;
56
+ (_b = (_a = this.options).onStateChange) === null || _b === void 0 ? void 0 : _b.call(_a, "connecting");
57
+ const Impl = (_c = this.options.WebSocketImpl) !== null && _c !== void 0 ? _c : WebSocket;
58
+ const socket = new Impl(this.url);
59
+ this.socket = socket;
60
+ socket.onmessage = (message) => this.handleFrame(JSON.parse(String(message.data)));
61
+ socket.onclose = () => this.handleClose(socket);
62
+ socket.onerror = () => socket.close();
63
+ }
64
+ handleFrame(frame) {
65
+ var _a, _b, _c, _d;
66
+ this.resetActivityTimer();
67
+ const data = parseData(frame.data);
68
+ if (frame.event === "pusher:connection_established") {
69
+ const established = data;
70
+ this.socketId = established.socket_id;
71
+ this.activityTimeoutMs = Math.min(((_a = established.activity_timeout) !== null && _a !== void 0 ? _a : 120) * 1000, 120000);
72
+ this.attempt = 0;
73
+ (_c = (_b = this.options).onStateChange) === null || _c === void 0 ? void 0 : _c.call(_b, "connected");
74
+ for (const channel of this.channels.keys())
75
+ void this.sendSubscribe(channel);
76
+ return;
77
+ }
78
+ if (frame.event === "pusher:ping")
79
+ return this.send({ event: "pusher:pong", data: {} });
80
+ if (frame.event === "pusher:pong")
81
+ return this.clearPongTimer();
82
+ if (frame.event === "pusher:error")
83
+ return this.handleError(data);
84
+ if (!frame.channel)
85
+ return;
86
+ const handlers = this.channels.get(frame.channel);
87
+ if (!handlers)
88
+ return;
89
+ if (frame.event === "pusher_internal:subscription_succeeded")
90
+ (_d = handlers.onSubscribed) === null || _d === void 0 ? void 0 : _d.call(handlers);
91
+ else if (frame.event === "pusher:subscription_error")
92
+ this.retrySubscribe(frame.channel);
93
+ else if (!frame.event.startsWith("pusher"))
94
+ handlers.onEvent(frame.event, data);
95
+ }
96
+ /** 4000–4099: fatal (bad app key / origin), so stop. Anything else reconnects. */
97
+ handleError({ code }) {
98
+ if (code && code >= 4000 && code < 4100)
99
+ this.disconnect();
100
+ }
101
+ async sendSubscribe(channel) {
102
+ const socketId = this.socketId;
103
+ if (!socketId)
104
+ return;
105
+ try {
106
+ const auth = await this.options.authorize(socketId, channel);
107
+ if (this.socketId === socketId && this.channels.has(channel)) {
108
+ this.send({ event: "pusher:subscribe", data: { channel, auth } });
109
+ }
110
+ }
111
+ catch {
112
+ this.retrySubscribe(channel);
113
+ }
114
+ }
115
+ retrySubscribe(channel) {
116
+ setTimeout(() => {
117
+ if (this.channels.has(channel))
118
+ void this.sendSubscribe(channel);
119
+ }, 5000);
120
+ }
121
+ send(frame) {
122
+ var _a;
123
+ if (((_a = this.socket) === null || _a === void 0 ? void 0 : _a.readyState) === 1)
124
+ this.socket.send(JSON.stringify(frame));
125
+ }
126
+ handleClose(socket) {
127
+ var _a, _b;
128
+ if (socket !== this.socket)
129
+ return;
130
+ this.clearTimers();
131
+ this.socket = null;
132
+ this.socketId = null;
133
+ (_b = (_a = this.options).onStateChange) === null || _b === void 0 ? void 0 : _b.call(_a, "disconnected");
134
+ if (this.stopped)
135
+ return;
136
+ this.attempt += 1;
137
+ const delay = Math.min(MAX_BACKOFF_MS, 1000 * 2 ** Math.min(this.attempt, 5)) * (0.75 + Math.random() * 0.5);
138
+ this.reconnectTimer = setTimeout(() => this.open(), delay);
139
+ }
140
+ /** Server expects traffic within activity_timeout; ping when idle, reconnect if no pong. */
141
+ resetActivityTimer() {
142
+ if (this.activityTimer)
143
+ clearTimeout(this.activityTimer);
144
+ this.activityTimer = setTimeout(() => {
145
+ this.send({ event: "pusher:ping", data: {} });
146
+ this.pongTimer = setTimeout(() => { var _a; return (_a = this.socket) === null || _a === void 0 ? void 0 : _a.close(); }, PONG_TIMEOUT_MS);
147
+ }, this.activityTimeoutMs);
148
+ }
149
+ clearPongTimer() {
150
+ if (this.pongTimer)
151
+ clearTimeout(this.pongTimer);
152
+ this.pongTimer = null;
153
+ }
154
+ clearTimers() {
155
+ for (const timer of [this.activityTimer, this.pongTimer, this.reconnectTimer])
156
+ if (timer)
157
+ clearTimeout(timer);
158
+ this.activityTimer = this.pongTimer = this.reconnectTimer = null;
159
+ }
160
+ }
161
+ //# sourceMappingURL=p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C,GAAG,EAAE;YACnC,IAAI,CAAC,IAAI,CAAC,EAAE,KAAK,EAAE,aAAa,EAAE,IAAI,EAAE,EAAE,EAAE,CAAC,CAAC;YAC9C,IAAI,CAAC,SAAS,GAAG,UAAU,CAAC,GAAG,EAAE,WAAC,OAAA,MAAA,IAAI,CAAC,MAAM,0CAAE,KAAK,EAAE,CAAA,EAAA,EAAE,eAAe,CAAC,CAAC;QAC3E,CAAC,EAAE,IAAI,CAAC,iBAAiB,CAAC,CAAC;IAC7B,CAAC;IAEO,cAAc;QACpB,IAAI,IAAI,CAAC,SAAS;YAAE,YAAY,CAAC,IAAI,CAAC,SAAS,CAAC,CAAC;QACjD,IAAI,CAAC,SAAS,GAAG,IAAI,CAAC;IACxB,CAAC;IAEO,WAAW;QACjB,KAAK,MAAM,KAAK,IAAI,CAAC,IAAI,CAAC,aAAa,EAAE,IAAI,CAAC,SAAS,EAAE,IAAI,CAAC,cAAc,CAAC;YAAE,IAAI,KAAK;gBAAE,YAAY,CAAC,KAAK,CAAC,CAAC;QAC9G,IAAI,CAAC,aAAa,GAAG,IAAI,CAAC,SAAS,GAAG,IAAI,CAAC,cAAc,GAAG,IAAI,CAAC;IACnE,CAAC;CACF","sourcesContent":["/**\n * Minimal Pusher-protocol (v7) client for Soketi — a few KB instead of pusher-js, so the widget\n * stays light. Supports private channels, ping/pong, activity timeout and reconnect with backoff.\n */\nimport type { RealtimeClientConfig } from \"./types.js\";\n\nexport type ConnectionState = \"connecting\" | \"connected\" | \"disconnected\";\n\ntype ChannelHandlers = {\n onEvent: (event: string, data: unknown) => void;\n onSubscribed?: () => void;\n};\n\ntype Options = RealtimeClientConfig & {\n /** Returns the `auth` signature for a private channel. */\n authorize: (socketId: string, channel: string) => Promise<string>;\n onStateChange?: (state: ConnectionState) => void;\n /** Injectable for tests. */\n WebSocketImpl?: typeof WebSocket;\n};\n\ntype Frame = { event: string; channel?: string; data?: unknown };\n\nconst PROTOCOL_VERSION = 7;\nconst PONG_TIMEOUT_MS = 30_000;\nconst MAX_BACKOFF_MS = 30_000;\n\nconst parseData = (data: unknown): unknown => {\n if (typeof data !== \"string\") return data;\n try {\n return JSON.parse(data);\n } catch {\n return data;\n }\n};\n\nexport class PusherLite {\n private socket: WebSocket | null = null;\n private socketId: string | null = null;\n private readonly channels = new Map<string, ChannelHandlers>();\n private activityTimeoutMs = 120_000;\n private activityTimer: ReturnType<typeof setTimeout> | null = null;\n private pongTimer: ReturnType<typeof setTimeout> | null = null;\n private reconnectTimer: ReturnType<typeof setTimeout> | null = null;\n private attempt = 0;\n private stopped = true;\n\n constructor(private readonly options: Options) {}\n\n private get url(): string {\n const { forceTLS, wsHost, wsPort, key } = this.options;\n return `${forceTLS ? \"wss\" : \"ws\"}://${wsHost}:${wsPort}/app/${encodeURIComponent(key)}?protocol=${PROTOCOL_VERSION}&client=reponly-js&version=1.0.0&flash=false`;\n }\n\n connect(): void {\n if (!this.stopped) return;\n this.stopped = false;\n this.open();\n }\n\n disconnect(): void {\n this.stopped = true;\n this.clearTimers();\n this.socket?.close();\n this.socket = null;\n this.socketId = null;\n }\n\n subscribe(channel: string, handlers: ChannelHandlers): () => void {\n this.channels.set(channel, handlers);\n if (this.socketId) void this.sendSubscribe(channel);\n return () => {\n this.channels.delete(channel);\n this.send({ event: \"pusher:unsubscribe\", data: { channel } });\n };\n }\n\n private open(): void {\n this.options.onStateChange?.(\"connecting\");\n const Impl = this.options.WebSocketImpl ?? WebSocket;\n const socket = new Impl(this.url);\n this.socket = socket;\n socket.onmessage = (message) => this.handleFrame(JSON.parse(String(message.data)) as Frame);\n socket.onclose = () => this.handleClose(socket);\n socket.onerror = () => socket.close();\n }\n\n private handleFrame(frame: Frame): void {\n this.resetActivityTimer();\n const data = parseData(frame.data);\n if (frame.event === \"pusher:connection_established\") {\n const established = data as { socket_id: string; activity_timeout?: number };\n this.socketId = established.socket_id;\n this.activityTimeoutMs = Math.min((established.activity_timeout ?? 120) * 1000, 120_000);\n this.attempt = 0;\n this.options.onStateChange?.(\"connected\");\n for (const channel of this.channels.keys()) void this.sendSubscribe(channel);\n return;\n }\n if (frame.event === \"pusher:ping\") return this.send({ event: \"pusher:pong\", data: {} });\n if (frame.event === \"pusher:pong\") return this.clearPongTimer();\n if (frame.event === \"pusher:error\") return this.handleError(data as { code?: number });\n if (!frame.channel) return;\n const handlers = this.channels.get(frame.channel);\n if (!handlers) return;\n if (frame.event === \"pusher_internal:subscription_succeeded\") handlers.onSubscribed?.();\n else if (frame.event === \"pusher:subscription_error\") this.retrySubscribe(frame.channel);\n else if (!frame.event.startsWith(\"pusher\")) handlers.onEvent(frame.event, data);\n }\n\n /** 4000–4099: fatal (bad app key / origin), so stop. Anything else reconnects. */\n private handleError({ code }: { code?: number }): void {\n if (code && code >= 4000 && code < 4100) this.disconnect();\n }\n\n private async sendSubscribe(channel: string): Promise<void> {\n const socketId = this.socketId;\n if (!socketId) return;\n try {\n const auth = await this.options.authorize(socketId, channel);\n if (this.socketId === socketId && this.channels.has(channel)) {\n this.send({ event: \"pusher:subscribe\", data: { channel, auth } });\n }\n } catch {\n this.retrySubscribe(channel);\n }\n }\n\n private retrySubscribe(channel: string): void {\n setTimeout(() => {\n if (this.channels.has(channel)) void this.sendSubscribe(channel);\n }, 5_000);\n }\n\n private send(frame: Frame): void {\n if (this.socket?.readyState === 1) this.socket.send(JSON.stringify(frame));\n }\n\n private handleClose(socket: WebSocket): void {\n if (socket !== this.socket) return;\n this.clearTimers();\n this.socket = null;\n this.socketId = null;\n this.options.onStateChange?.(\"disconnected\");\n if (this.stopped) return;\n this.attempt += 1;\n const delay = Math.min(MAX_BACKOFF_MS, 1000 * 2 ** Math.min(this.attempt, 5)) * (0.75 + Math.random() * 0.5);\n this.reconnectTimer = setTimeout(() => this.open(), delay);\n }\n\n /** Server expects traffic within activity_timeout; ping when idle, reconnect if no pong. */\n private resetActivityTimer(): void {\n if (this.activityTimer) clearTimeout(this.activityTimer);\n this.activityTimer = setTimeout(() => {\n this.send({ event: \"pusher:ping\", data: {} });\n this.pongTimer = setTimeout(() => this.socket?.close(), PONG_TIMEOUT_MS);\n }, this.activityTimeoutMs);\n }\n\n private clearPongTimer(): void {\n if (this.pongTimer) clearTimeout(this.pongTimer);\n this.pongTimer = null;\n }\n\n private clearTimers(): void {\n for (const timer of [this.activityTimer, this.pongTimer, this.reconnectTimer]) if (timer) clearTimeout(timer);\n this.activityTimer = this.pongTimer = this.reconnectTimer = null;\n }\n}\n"]}
@@ -0,0 +1,160 @@
1
+ /**
2
+ * Wire types of the Reponly customer API (`/api/v1/*`). They mirror the server's types; the
3
+ * Reponly app type-checks itself against them, so a change on either side fails its build.
4
+ */
5
+ /** Pusher-protocol (Soketi) connection settings from the project config. */
6
+ export type RealtimeClientConfig = {
7
+ key: string;
8
+ wsHost: string;
9
+ wsPort: number;
10
+ forceTLS: boolean;
11
+ channelPrefix: string;
12
+ };
13
+ export type ApiError = {
14
+ code: string;
15
+ message: string;
16
+ /** ISO timestamp after which a temporarily blocked operation can be retried. */
17
+ retryAt: string | null;
18
+ fields?: Record<string, string[]>;
19
+ };
20
+ export type ApiResponse<T> = {
21
+ success: true;
22
+ data: T;
23
+ error: null;
24
+ } | {
25
+ success: false;
26
+ data: null;
27
+ error: ApiError;
28
+ };
29
+ export type SenderType = "customer" | "agent" | "system";
30
+ /** When to ask a guest for an email, so replies can reach them after they leave. */
31
+ export type AskForEmail = "after_first_message" | "before_first_message" | "never";
32
+ /** A file sent in chat. Images are shown inline; everything else downloads. */
33
+ export type AttachmentView = {
34
+ id: string;
35
+ url: string;
36
+ name: string;
37
+ contentType: string;
38
+ /** Bytes. */
39
+ size: number;
40
+ kind: "image" | "file";
41
+ };
42
+ /**
43
+ * Where a customer was and what they used when they wrote. Reported by the browser, so it can be
44
+ * wrong or missing; never use it to make access decisions.
45
+ */
46
+ export type VisitorContextView = {
47
+ pageUrl: string | null;
48
+ pageTitle: string | null;
49
+ userAgent: string | null;
50
+ /** "Chrome 131" */
51
+ browser: string | null;
52
+ /** "macOS", "iOS 18" */
53
+ os: string | null;
54
+ deviceType: "desktop" | "mobile" | "tablet" | null;
55
+ /** BCP 47, e.g. "en-GB". */
56
+ language: string | null;
57
+ /** Every language the browser prefers, first one first: ["en-GB", "ru", "hy"]. */
58
+ languages: string[] | null;
59
+ /** IANA, e.g. "Europe/Berlin". */
60
+ timezone: string | null;
61
+ /** "1440x900" */
62
+ screen: string | null;
63
+ /** ISO 3166-1 alpha-2 ("DE"). */
64
+ country: string | null;
65
+ };
66
+ export type ProjectAppearance = {
67
+ /** Brand colour in light mode (and in dark mode when primaryColorDark is null). */
68
+ primaryColor: string;
69
+ primaryColorDark: string | null;
70
+ /** Chat background in light mode; null = the default (white). */
71
+ backgroundColor: string | null;
72
+ /** Chat background in dark mode; null = the default (neutral near-black). */
73
+ backgroundColorDark: string | null;
74
+ logoUrl: string | null;
75
+ welcomeText: string;
76
+ onlineText: string;
77
+ offlineText: string;
78
+ };
79
+ export type TriggerAudience = "everyone" | "new" | "returning";
80
+ /** An automatic message the hosted widget shows on its own: on matching pages, after a delay. */
81
+ export type TriggerView = {
82
+ id: string;
83
+ enabled: boolean;
84
+ message: string;
85
+ /** Shown on pages whose path contains this ("/pricing"); null = every page. */
86
+ pathContains: string | null;
87
+ /** Seconds on the page before it shows. */
88
+ delaySeconds: number;
89
+ audience: TriggerAudience;
90
+ };
91
+ export type MessageView = {
92
+ id: string;
93
+ conversationId: string;
94
+ seq: number;
95
+ senderType: SenderType;
96
+ /** Agent messages: the agent's current name (customers: their name, if known). */
97
+ senderName: string | null;
98
+ /** Agent messages: the agent's profile photo, or null to show initials. */
99
+ senderAvatarUrl: string | null;
100
+ /** May be empty when the message only carries attachments. */
101
+ content: string;
102
+ attachments: AttachmentView[];
103
+ /** Customer messages: the page and device they were sent from. */
104
+ context: VisitorContextView | null;
105
+ clientMessageId: string | null;
106
+ createdAt: string;
107
+ };
108
+ export type CustomerRealtimeEvent = {
109
+ type: "message.created";
110
+ message: MessageView;
111
+ } | {
112
+ type: "restriction.updated";
113
+ };
114
+ export type PublicProjectConfig = {
115
+ projectKey: string;
116
+ name: string;
117
+ appearance: ProjectAppearance;
118
+ supportOnline: boolean;
119
+ showBranding: boolean;
120
+ /** Live chat is off for this product: collect an email and a message instead. */
121
+ paused: boolean;
122
+ /** When to ask guests for an email (identified customers with an email are never asked). */
123
+ askForEmail: AskForEmail;
124
+ /** File uploads are set up on this server, so the chat can offer attachments. */
125
+ attachments: boolean;
126
+ realtime: RealtimeClientConfig;
127
+ /** Enabled automatic messages (Pro only; empty otherwise). */
128
+ triggers: TriggerView[];
129
+ };
130
+ export type CustomerSessionView = {
131
+ customerToken: string;
132
+ customer: {
133
+ id: string;
134
+ kind: "anonymous" | "identified";
135
+ name: string | null;
136
+ /** Whether we already have an address to answer this customer by email. */
137
+ hasEmail: boolean;
138
+ };
139
+ };
140
+ export type CustomerStatusView = {
141
+ restriction: {
142
+ active: true;
143
+ permanent: boolean;
144
+ retryAt: string | null;
145
+ message: string;
146
+ } | null;
147
+ rateLimit: {
148
+ retryAt: string;
149
+ message: string;
150
+ } | null;
151
+ };
152
+ export type CustomerConversationView = {
153
+ id: string;
154
+ lastMessageAt: string | null;
155
+ lastMessagePreview: string;
156
+ messageSeq: number;
157
+ };
158
+ /** Private channel of one customer: `private-{prefix}customer.{customerId}`. */
159
+ export declare const customerChannelName: (prefix: string, customerId: string) => string;
160
+ //# sourceMappingURL=types.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../src/types.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAEH,4EAA4E;AAC5E,MAAM,MAAM,oBAAoB,GAAG;IACjC,GAAG,EAAE,MAAM,CAAC;IACZ,MAAM,EAAE,MAAM,CAAC;IACf,MAAM,EAAE,MAAM,CAAC;IACf,QAAQ,EAAE,OAAO,CAAC;IAClB,aAAa,EAAE,MAAM,CAAC;CACvB,CAAC;AAEF,MAAM,MAAM,QAAQ,GAAG;IACrB,IAAI,EA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O,EAAE,MAAM,GAAG,IAAI,CAAC;QAAC,OAAO,EAAE,MAAM,CAAA;KAAE,GAAG,IAAI,CAAC;IAClG,SAAS,EAAE;QAAE,OAAO,EAAE,MAAM,CAAC;QAAC,OAAO,EAAE,MAAM,CAAA;KAAE,GAAG,IAAI,CAAC;CACxD,CAAC;AAEF,MAAM,MAAM,wBAAwB,GAAG;IACrC,EAAE,EAAE,MAAM,CAAC;IACX,aAAa,EAAE,MAAM,GAAG,IAAI,CAAC;IAC7B,kBAAkB,EAAE,MAAM,CAAC;IAC3B,UAAU,EAAE,MAAM,CAAC;CACpB,CAAC;AAEF,gFAAgF;AAChF,eAAO,MAAM,mBAAmB,GAAI,QAAQ,MAAM,EAAE,YAAY,MAAM,KAAG,MAC9B,CAAC"}
package/dist/types.js ADDED
@@ -0,0 +1,7 @@
1
+ /**
2
+ * Wire types of the Reponly customer API (`/api/v1/*`). They mirror the server's types; the
3
+ * Reponly app type-checks itself against them, so a change on either side fails its build.
4
+ */
5
+ /** Private channel of one customer: `private-{prefix}customer.{customerId}`. */
6
+ export const customerChannelName = (prefix, customerId) => `private-${prefix}customer.${customerId}`;
7
+ //# sourceMappingURL=types.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"types.js","sourceRoot":"","sources":["../src/types.ts"],"names":[],"mappings":"AAAA;;;GAGG;AA0JH,gFAAgF;AAChF,MAAM,CAAC,MAAM,mBAAmB,GAAG,CAAC,MAAc,EAAE,UAAkB,EAAU,EAAE,CAChF,WAAW,MAAM,YAAY,UAAU,EAAE,CAAC","sourcesContent":["/**\n * Wire types of the Reponly customer API (`/api/v1/*`). They mirror the server's types; the\n * Reponly app type-checks itself against them, so a change on either side fails its build.\n */\n\n/** Pusher-protocol (Soketi) connection settings from the project config. */\nexport type RealtimeClientConfig = {\n key: string;\n wsHost: string;\n wsPort: number;\n forceTLS: boolean;\n channelPrefix: string;\n};\n\nexport type ApiError = {\n code: string;\n message: string;\n /** ISO timestamp after which a temporarily blocked operation can be retried. */\n retryAt: string | null;\n fields?: Record<string, string[]>;\n};\n\nexport type ApiResponse<T> =\n | { success: true; data: T; error: null }\n | { success: false; data: null; error: ApiError };\n\nexport type SenderType = \"customer\" | \"agent\" | \"system\";\n\n/** When to ask a guest for an email, so replies can reach them after they leave. */\nexport type AskForEmail = \"after_first_message\" | \"before_first_message\" | \"never\";\n\n/** A file sent in chat. Images are shown inline; everything else downloads. */\nexport type AttachmentView = {\n id: string;\n url: string;\n name: string;\n contentType: string;\n /** Bytes. */\n size: number;\n kind: \"image\" | \"file\";\n};\n\n/**\n * Where a customer was and what they used when they wrote. Reported by the browser, so it can be\n * wrong or missing; never use it to make access decisions.\n */\nexport type VisitorContextView = {\n pageUrl: string | null;\n pageTitle: string | null;\n userAgent: string | null;\n /** \"Chrome 131\" */\n browser: string | null;\n /** \"macOS\", \"iOS 18\" */\n os: string | null;\n deviceType: \"desktop\" | \"mobile\" | \"tablet\" | null;\n /** BCP 47, e.g. \"en-GB\". */\n language: string | null;\n /** Every language the browser prefers, first one first: [\"en-GB\", \"ru\", \"hy\"]. */\n languages: string[] | null;\n /** IANA, e.g. \"Europe/Berlin\". */\n timezone: string | null;\n /** \"1440x900\" */\n screen: string | null;\n /** ISO 3166-1 alpha-2 (\"DE\"). */\n country: string | null;\n};\n\nexport type ProjectAppearance = {\n /** Brand colour in light mode (and in dark mode when primaryColorDark is null). */\n primaryColor: string;\n primaryColorDark: string | null;\n /** Chat background in light mode; null = the default (white). */\n backgroundColor: string | null;\n /** Chat background in dark mode; null = the default (neutral near-black). */\n backgroundColorDark: string | null;\n logoUrl: string | null;\n welcomeText: string;\n onlineText: string;\n offlineText: string;\n};\n\nexport type TriggerAudience = \"everyone\" | \"new\" | \"returning\";\n\n/** An automatic message the hosted widget shows on its own: on matching pages, after a delay. */\nexport type TriggerView = {\n id: string;\n enabled: boolean;\n message: string;\n /** Shown on pages whose path contains this (\"/pricing\"); null = every page. */\n pathContains: string | null;\n /** Seconds on the page before it shows. */\n delaySeconds: number;\n audience: TriggerAudience;\n};\n\nexport type MessageView = {\n id: string;\n conversationId: string;\n seq: number;\n senderType: SenderType;\n /** Agent messages: the agent's current name (customers: their name, if known). */\n senderName: string | null;\n /** Agent messages: the agent's profile photo, or null to show initials. */\n senderAvatarUrl: string | null;\n /** May be empty when the message only carries attachments. */\n content: string;\n attachments: AttachmentView[];\n /** Customer messages: the page and device they were sent from. */\n context: VisitorContextView | null;\n clientMessageId: string | null;\n createdAt: string;\n};\n\nexport type CustomerRealtimeEvent =\n | { type: \"message.created\"; message: MessageView }\n | { type: \"restriction.updated\" };\n\nexport type PublicProjectConfig = {\n projectKey: string;\n name: string;\n appearance: ProjectAppearance;\n supportOnline: boolean;\n showBranding: boolean;\n /** Live chat is off for this product: collect an email and a message instead. */\n paused: boolean;\n /** When to ask guests for an email (identified customers with an email are never asked). */\n askForEmail: AskForEmail;\n /** File uploads are set up on this server, so the chat can offer attachments. */\n attachments: boolean;\n realtime: RealtimeClientConfig;\n /** Enabled automatic messages (Pro only; empty otherwise). */\n triggers: TriggerView[];\n};\n\nexport type CustomerSessionView = {\n customerToken: string;\n customer: {\n id: string;\n kind: \"anonymous\" | \"identified\";\n name: string | null;\n /** Whether we already have an address to answer this customer by email. */\n hasEmail: boolean;\n };\n};\n\nexport type CustomerStatusView = {\n restriction: { active: true; permanent: boolean; retryAt: string | null; message: string } | null;\n rateLimit: { retryAt: string; message: string } | null;\n};\n\nexport type CustomerConversationView = {\n id: string;\n lastMessageAt: string | null;\n lastMessagePreview: string;\n messageSeq: number;\n};\n\n/** Private channel of one customer: `private-{prefix}customer.{customerId}`. */\nexport const customerChannelName = (prefix: string, customerId: string): string =>\n `private-${prefix}customer.${customerId}`;\n"]}
package/package.json CHANGED
@@ -1,6 +1,51 @@
1
1
  {
2
2
  "name": "reponly",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.0",
4
+ "description": "Reponly customer SDK: build your own in-app support chat on the Reponly customer API.",
5
+ "license": "MIT",
6
+ "type": "module",
7
+ "sideEffects": false,
8
+ "main": "./dist/index.js",
9
+ "types": "./dist/index.d.ts",
10
+ "exports": {
11
+ ".": {
12
+ "types": "./dist/index.d.ts",
13
+ "import": "./dist/index.js"
14
+ },
15
+ "./package.json": "./package.json"
16
+ },
17
+ "files": [
18
+ "dist",
19
+ "README.md",
20
+ "LICENSE"
21
+ ],
22
+ "keywords": [
23
+ "reponly",
24
+ "support",
25
+ "chat",
26
+ "live-chat",
27
+ "customer-support",
28
+ "sdk"
29
+ ],
30
+ "homepage": "https://reponly.com",
31
+ "repository": {
32
+ "type": "git",
33
+ "url": "git+https://github.com/reponly-com/reponly-js.git"
34
+ },
35
+ "bugs": {
36
+ "url": "https://github.com/reponly-com/reponly-js/issues"
37
+ },
38
+ "engines": {
39
+ "node": ">=18"
40
+ },
41
+ "scripts": {
42
+ "build": "rm -rf dist && tsc -p tsconfig.build.json",
43
+ "typecheck": "tsc --noEmit",
44
+ "test": "vitest run",
45
+ "prepublishOnly": "npm run typecheck && npm test && npm run build"
46
+ },
47
+ "devDependencies": {
48
+ "typescript": "^5.9.3",
49
+ "vitest": "^5.1.0"
50
+ }
51
+ }