@oryksa/sdk 0.1.4 → 0.1.5
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.es.md +133 -91
- package/README.fr.md +133 -91
- package/README.md +133 -91
- package/README.pt.md +133 -91
- package/package.json +19 -19
- package/src/index.d.ts +91 -2
- package/src/index.js +719 -328
package/src/index.js
CHANGED
|
@@ -1,328 +1,719 @@
|
|
|
1
|
-
/*!
|
|
2
|
-
* @oryksa/sdk - ORYKSA AI Employees SDK for JavaScript and TypeScript.
|
|
3
|
-
* Server client (secret API key), webhook verification, and an in-app chat
|
|
4
|
-
* client that only uses short-lived session tokens (never the secret key).
|
|
5
|
-
* Docs: https://developer.oryksa.com License: MIT
|
|
6
|
-
*/
|
|
7
|
-
|
|
8
|
-
const DEFAULT_BASE = "https://api.oryksa.com/v1";
|
|
9
|
-
export const VERSION = "0.1.
|
|
10
|
-
|
|
11
|
-
export class OryksaError extends Error {
|
|
12
|
-
constructor(status, code, message, extra = {}) {
|
|
13
|
-
super(message);
|
|
14
|
-
this.name = "OryksaError";
|
|
15
|
-
this.status = status;
|
|
16
|
-
this.code = code;
|
|
17
|
-
Object.assign(this, extra);
|
|
18
|
-
}
|
|
19
|
-
}
|
|
20
|
-
|
|
21
|
-
async function request(base, token, method, path, body, fetchImpl, timeoutMs) {
|
|
22
|
-
const f = fetchImpl || globalThis.fetch;
|
|
23
|
-
if (!f) throw new Error("fetch is not available: pass { fetch } in the options (Node < 18).");
|
|
24
|
-
const ctrl = typeof AbortController !== "undefined" ? new AbortController() : null;
|
|
25
|
-
const timer = ctrl ? setTimeout(() => ctrl.abort(), timeoutMs) : null;
|
|
26
|
-
let res;
|
|
27
|
-
try {
|
|
28
|
-
res = await f(base + path, {
|
|
29
|
-
method,
|
|
30
|
-
headers: {
|
|
31
|
-
Authorization: "Bearer " + token,
|
|
32
|
-
...(body !== undefined ? { "Content-Type": "application/json" } : {}),
|
|
33
|
-
"X-ORYKSA-SDK": "js/" + VERSION,
|
|
34
|
-
},
|
|
35
|
-
body: body !== undefined ? JSON.stringify(body) : undefined,
|
|
36
|
-
signal: ctrl ? ctrl.signal : undefined,
|
|
37
|
-
});
|
|
38
|
-
} finally {
|
|
39
|
-
if (timer) clearTimeout(timer);
|
|
40
|
-
}
|
|
41
|
-
let data = null;
|
|
42
|
-
try { data = await res.json(); } catch (_) { data = null; }
|
|
43
|
-
if (!res.ok && res.status !== 202) {
|
|
44
|
-
const e = (data && data.error) || {};
|
|
45
|
-
const { code, message, ...extra } = e;
|
|
46
|
-
throw new OryksaError(res.status, code || "http_" + res.status, message || "Request failed with HTTP " + res.status, extra);
|
|
47
|
-
}
|
|
48
|
-
return data;
|
|
49
|
-
}
|
|
50
|
-
|
|
51
|
-
/**
|
|
52
|
-
* Server-side client. Uses the SECRET API key (oryk_live_...). Never ship it in a browser or app bundle.
|
|
53
|
-
*/
|
|
54
|
-
export class Oryksa {
|
|
55
|
-
constructor(apiKey, opts = {}) {
|
|
56
|
-
if (!apiKey || !String(apiKey).startsWith("oryk_live_")) {
|
|
57
|
-
throw new Error("An ORYKSA API key (oryk_live_...) is required. Create one at developer.oryksa.com.");
|
|
58
|
-
}
|
|
59
|
-
if (typeof window !== "undefined" && typeof document !== "undefined" && !opts.dangerouslyAllowBrowser) {
|
|
60
|
-
throw new Error("The secret API key must stay on the server. In apps use OryksaClient with a session token.");
|
|
61
|
-
}
|
|
62
|
-
this._key = apiKey;
|
|
63
|
-
this._base = (opts.baseUrl || DEFAULT_BASE).replace(/\/$/, "");
|
|
64
|
-
this._fetch = opts.fetch;
|
|
65
|
-
this._timeout = opts.timeoutMs || 60000;
|
|
66
|
-
}
|
|
67
|
-
|
|
68
|
-
_req(method, path, body) {
|
|
69
|
-
return request(this._base, this._key, method, path, body, this._fetch, this._timeout);
|
|
70
|
-
}
|
|
71
|
-
|
|
72
|
-
account() { return this._req("GET", "/account"); }
|
|
73
|
-
|
|
74
|
-
/** Chat with the AI employee. Reuse conversationId to keep the context. */
|
|
75
|
-
chat({ message, conversationId, customerName } = {}) {
|
|
76
|
-
return this._req("POST", "/chat", { message, conversation_id: conversationId, customer_name: customerName });
|
|
77
|
-
}
|
|
78
|
-
|
|
79
|
-
conversations({ limit } = {}) { return this._req("GET", "/conversations" + (limit ? "?limit=" + Number(limit) : "")); }
|
|
80
|
-
conversation(id) { return this._req("GET", "/conversations/" + encodeURIComponent(id)); }
|
|
81
|
-
|
|
82
|
-
get agent() {
|
|
83
|
-
return {
|
|
84
|
-
update: (fields) => this._req("PATCH", "/agent", fields),
|
|
85
|
-
appearance: (fields) => this._req("PATCH", "/agent/appearance", fields),
|
|
86
|
-
};
|
|
87
|
-
}
|
|
88
|
-
|
|
89
|
-
get knowledge() {
|
|
90
|
-
return {
|
|
91
|
-
get: () => this._req("GET", "/knowledge"),
|
|
92
|
-
setPages: ({ pages, businessSummary, siteUrl }) =>
|
|
93
|
-
this._req("PUT", "/knowledge/pages", { pages, business_summary: businessSummary, site_url: siteUrl }),
|
|
94
|
-
crawl: ({ url, maxPages }) => this._req("POST", "/knowledge/crawl", { url, max_pages: maxPages }),
|
|
95
|
-
addFaq: (items) => this._req("POST", "/knowledge/faq", { items }),
|
|
96
|
-
};
|
|
97
|
-
}
|
|
98
|
-
|
|
99
|
-
get widget() {
|
|
100
|
-
return {
|
|
101
|
-
snippet: ({ framework = "html", lang = "", position = "" } = {}) =>
|
|
102
|
-
this._req("GET", `/widget?framework=${encodeURIComponent(framework)}&lang=${encodeURIComponent(lang)}&position=${encodeURIComponent(position)}`),
|
|
103
|
-
setDomains: (domains) => this._req("PUT", "/widget/domains", { domains }),
|
|
104
|
-
};
|
|
105
|
-
}
|
|
106
|
-
|
|
107
|
-
get webhooks() {
|
|
108
|
-
return {
|
|
109
|
-
list: () => this._req("GET", "/webhooks"),
|
|
110
|
-
create: ({ url, events = ["*"] }) => this._req("POST", "/webhooks", { url, events }),
|
|
111
|
-
delete: (id) => this._req("DELETE", "/webhooks/" + encodeURIComponent(id)),
|
|
112
|
-
test: (id) => this._req("POST", "/webhooks/" + encodeURIComponent(id) + "/test"),
|
|
113
|
-
};
|
|
114
|
-
}
|
|
115
|
-
|
|
116
|
-
/** Short-lived token for an app user. Send only this token to the app.
|
|
117
|
-
* For a user signed in to your app, pass customerEmail and/or customerPhone (with the country code):
|
|
118
|
-
* the AI then asks for no contact details and knows the customer is signed in. */
|
|
119
|
-
createSession({ conversationId, customerName, customerEmail, customerPhone, ttlMinutes = 60 } = {}) {
|
|
120
|
-
return this._req("POST", "/sessions", { conversation_id: conversationId, customer_name: customerName,
|
|
121
|
-
customer_email: customerEmail, customer_phone: customerPhone, ttl_minutes: ttlMinutes });
|
|
122
|
-
}
|
|
123
|
-
|
|
124
|
-
/**
|
|
125
|
-
* Teach the AI employee about an app: what it is, its screens/features and FAQs.
|
|
126
|
-
* The agent then answers users inside the app with that knowledge.
|
|
127
|
-
* @param {{name:string, description?:string, screens?:{title:string, content:string, url?:string}[], faq?:{question:string, answer:string}[], languages?:string[], agentName?:string, settings?:object}} app
|
|
128
|
-
*/
|
|
129
|
-
async learnApp(app) {
|
|
130
|
-
if (!app || !app.name) throw new Error("learnApp needs at least { name }.");
|
|
131
|
-
const out = {};
|
|
132
|
-
const profile = { business_name: app.name };
|
|
133
|
-
if (app.description) profile.business_description = app.description;
|
|
134
|
-
if (app.agentName) profile.agent_name = app.agentName;
|
|
135
|
-
if (Array.isArray(app.languages)) profile.languages = app.languages;
|
|
136
|
-
if (Array.isArray(app.services)) profile.services = app.services;
|
|
137
|
-
out.agent = await this.agent.update(profile);
|
|
138
|
-
const pages = [];
|
|
139
|
-
if (app.description) pages.push({ title: app.name + " - overview", content: app.description });
|
|
140
|
-
for (const s of app.screens || []) {
|
|
141
|
-
if (s && s.content) pages.push({ title: s.title || "Screen", url: s.url, content: String(s.content) });
|
|
142
|
-
}
|
|
143
|
-
if (app.settings && typeof app.settings === "object") {
|
|
144
|
-
const lines = Object.entries(app.settings).map(([k, v]) => `${k}: ${typeof v === "object" ? JSON.stringify(v) : v}`);
|
|
145
|
-
pages.push({ title: app.name + " - configuration", content: lines.join("\n") });
|
|
146
|
-
}
|
|
147
|
-
if (pages.length) out.pages = await this.knowledge.setPages({ pages, siteUrl: app.url });
|
|
148
|
-
if (Array.isArray(app.faq) && app.faq.length) out.faq = await this.knowledge.addFaq(app.faq);
|
|
149
|
-
return out;
|
|
150
|
-
}
|
|
151
|
-
}
|
|
152
|
-
|
|
153
|
-
/**
|
|
154
|
-
* Verify an ORYKSA webhook signature (Node.js). Pass the RAW request body.
|
|
155
|
-
* @returns {Promise<object>} the parsed event, or throws OryksaError(400).
|
|
156
|
-
*/
|
|
157
|
-
export async function verifyWebhook(rawBody, signatureHeader, secret, { toleranceSeconds = 300 } = {}) {
|
|
158
|
-
const parts = Object.fromEntries(String(signatureHeader || "").split(",").map((p) => p.split("=")));
|
|
159
|
-
const t = Number(parts.t || 0);
|
|
160
|
-
if (!t || Math.abs(Date.now() / 1000 - t) > toleranceSeconds) throw new OryksaError(400, "invalid_signature", "Webhook timestamp is missing or too old.");
|
|
161
|
-
const body = typeof rawBody === "string" ? rawBody : new TextDecoder().decode(rawBody);
|
|
162
|
-
let expected;
|
|
163
|
-
if (globalThis.crypto && globalThis.crypto.subtle) {
|
|
164
|
-
const key = await globalThis.crypto.subtle.importKey("raw", new TextEncoder().encode(secret), { name: "HMAC", hash: "SHA-256" }, false, ["sign"]);
|
|
165
|
-
const sig = await globalThis.crypto.subtle.sign("HMAC", key, new TextEncoder().encode(t + "." + body));
|
|
166
|
-
expected = [...new Uint8Array(sig)].map((b) => b.toString(16).padStart(2, "0")).join("");
|
|
167
|
-
} else {
|
|
168
|
-
const { createHmac } = await import("node:crypto");
|
|
169
|
-
expected = createHmac("sha256", secret).update(t + "." + body).digest("hex");
|
|
170
|
-
}
|
|
171
|
-
const got = String(parts.v1 || "");
|
|
172
|
-
let diff = expected.length ^ got.length;
|
|
173
|
-
for (let i = 0; i < Math.min(expected.length, got.length); i++) diff |= expected.charCodeAt(i) ^ got.charCodeAt(i);
|
|
174
|
-
if (diff !== 0) throw new OryksaError(400, "invalid_signature", "Webhook signature does not match.");
|
|
175
|
-
return JSON.parse(body);
|
|
176
|
-
}
|
|
177
|
-
|
|
178
|
-
/**
|
|
179
|
-
* In-app client (browser, React Native, Electron). Uses a short-lived session token
|
|
180
|
-
* created by YOUR server with Oryksa.createSession(). Pass getToken() to refresh it.
|
|
181
|
-
*/
|
|
182
|
-
export class OryksaClient {
|
|
183
|
-
constructor({ token, getToken, baseUrl, fetch, timeoutMs } = {}) {
|
|
184
|
-
if (!token && !getToken) throw new Error("OryksaClient needs { token } or { getToken }.");
|
|
185
|
-
if (token && String(token).startsWith("oryk_live_")) throw new Error("Never use the secret API key in an app. Use a session token (oryk_cs_...).");
|
|
186
|
-
this._token = token || null;
|
|
187
|
-
this._getToken = getToken || null;
|
|
188
|
-
this._base = (baseUrl || DEFAULT_BASE).replace(/\/$/, "");
|
|
189
|
-
this._fetch = fetch;
|
|
190
|
-
this._timeout = timeoutMs || 60000;
|
|
191
|
-
|
|
192
|
-
|
|
193
|
-
|
|
194
|
-
|
|
195
|
-
|
|
196
|
-
|
|
197
|
-
|
|
198
|
-
|
|
199
|
-
|
|
200
|
-
|
|
201
|
-
|
|
202
|
-
|
|
203
|
-
|
|
204
|
-
|
|
205
|
-
|
|
206
|
-
|
|
207
|
-
|
|
208
|
-
|
|
209
|
-
|
|
210
|
-
|
|
211
|
-
|
|
212
|
-
}
|
|
213
|
-
|
|
214
|
-
|
|
215
|
-
|
|
216
|
-
|
|
217
|
-
|
|
218
|
-
|
|
219
|
-
|
|
220
|
-
.
|
|
221
|
-
.
|
|
222
|
-
|
|
223
|
-
|
|
224
|
-
|
|
225
|
-
|
|
226
|
-
.
|
|
227
|
-
|
|
228
|
-
|
|
229
|
-
|
|
230
|
-
|
|
231
|
-
|
|
232
|
-
.
|
|
233
|
-
.
|
|
234
|
-
|
|
235
|
-
|
|
236
|
-
|
|
237
|
-
.
|
|
238
|
-
|
|
239
|
-
|
|
240
|
-
|
|
241
|
-
const
|
|
242
|
-
|
|
243
|
-
|
|
244
|
-
|
|
245
|
-
|
|
246
|
-
|
|
247
|
-
|
|
248
|
-
|
|
249
|
-
|
|
250
|
-
|
|
251
|
-
*/
|
|
252
|
-
export function
|
|
253
|
-
|
|
254
|
-
const
|
|
255
|
-
|
|
256
|
-
|
|
257
|
-
const
|
|
258
|
-
|
|
259
|
-
|
|
260
|
-
|
|
261
|
-
|
|
262
|
-
|
|
263
|
-
|
|
264
|
-
|
|
265
|
-
|
|
266
|
-
|
|
267
|
-
|
|
268
|
-
|
|
269
|
-
const
|
|
270
|
-
|
|
271
|
-
|
|
272
|
-
|
|
273
|
-
|
|
274
|
-
|
|
275
|
-
|
|
276
|
-
|
|
277
|
-
|
|
278
|
-
|
|
279
|
-
|
|
280
|
-
};
|
|
281
|
-
|
|
282
|
-
|
|
283
|
-
|
|
284
|
-
|
|
285
|
-
|
|
286
|
-
|
|
287
|
-
|
|
288
|
-
|
|
289
|
-
|
|
290
|
-
|
|
291
|
-
|
|
292
|
-
|
|
293
|
-
|
|
294
|
-
|
|
295
|
-
|
|
296
|
-
|
|
297
|
-
|
|
298
|
-
|
|
299
|
-
|
|
300
|
-
|
|
301
|
-
|
|
302
|
-
|
|
303
|
-
|
|
304
|
-
|
|
305
|
-
|
|
306
|
-
|
|
307
|
-
|
|
308
|
-
|
|
309
|
-
|
|
310
|
-
|
|
311
|
-
|
|
312
|
-
|
|
313
|
-
|
|
314
|
-
|
|
315
|
-
|
|
316
|
-
|
|
317
|
-
|
|
318
|
-
|
|
319
|
-
|
|
320
|
-
return {
|
|
321
|
-
|
|
322
|
-
|
|
323
|
-
|
|
324
|
-
|
|
325
|
-
|
|
326
|
-
|
|
327
|
-
|
|
328
|
-
|
|
1
|
+
/*!
|
|
2
|
+
* @oryksa/sdk - ORYKSA AI Employees SDK for JavaScript and TypeScript.
|
|
3
|
+
* Server client (secret API key), webhook verification, and an in-app chat
|
|
4
|
+
* client that only uses short-lived session tokens (never the secret key).
|
|
5
|
+
* Docs: https://developer.oryksa.com License: MIT
|
|
6
|
+
*/
|
|
7
|
+
|
|
8
|
+
const DEFAULT_BASE = "https://api.oryksa.com/v1";
|
|
9
|
+
export const VERSION = "0.1.5";
|
|
10
|
+
|
|
11
|
+
export class OryksaError extends Error {
|
|
12
|
+
constructor(status, code, message, extra = {}) {
|
|
13
|
+
super(message);
|
|
14
|
+
this.name = "OryksaError";
|
|
15
|
+
this.status = status;
|
|
16
|
+
this.code = code;
|
|
17
|
+
Object.assign(this, extra);
|
|
18
|
+
}
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
async function request(base, token, method, path, body, fetchImpl, timeoutMs) {
|
|
22
|
+
const f = fetchImpl || globalThis.fetch;
|
|
23
|
+
if (!f) throw new Error("fetch is not available: pass { fetch } in the options (Node < 18).");
|
|
24
|
+
const ctrl = typeof AbortController !== "undefined" ? new AbortController() : null;
|
|
25
|
+
const timer = ctrl ? setTimeout(() => ctrl.abort(), timeoutMs) : null;
|
|
26
|
+
let res;
|
|
27
|
+
try {
|
|
28
|
+
res = await f(base + path, {
|
|
29
|
+
method,
|
|
30
|
+
headers: {
|
|
31
|
+
Authorization: "Bearer " + token,
|
|
32
|
+
...(body !== undefined ? { "Content-Type": "application/json" } : {}),
|
|
33
|
+
"X-ORYKSA-SDK": "js/" + VERSION,
|
|
34
|
+
},
|
|
35
|
+
body: body !== undefined ? JSON.stringify(body) : undefined,
|
|
36
|
+
signal: ctrl ? ctrl.signal : undefined,
|
|
37
|
+
});
|
|
38
|
+
} finally {
|
|
39
|
+
if (timer) clearTimeout(timer);
|
|
40
|
+
}
|
|
41
|
+
let data = null;
|
|
42
|
+
try { data = await res.json(); } catch (_) { data = null; }
|
|
43
|
+
if (!res.ok && res.status !== 202) {
|
|
44
|
+
const e = (data && data.error) || {};
|
|
45
|
+
const { code, message, ...extra } = e;
|
|
46
|
+
throw new OryksaError(res.status, code || "http_" + res.status, message || "Request failed with HTTP " + res.status, extra);
|
|
47
|
+
}
|
|
48
|
+
return data;
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
/**
|
|
52
|
+
* Server-side client. Uses the SECRET API key (oryk_live_...). Never ship it in a browser or app bundle.
|
|
53
|
+
*/
|
|
54
|
+
export class Oryksa {
|
|
55
|
+
constructor(apiKey, opts = {}) {
|
|
56
|
+
if (!apiKey || !String(apiKey).startsWith("oryk_live_")) {
|
|
57
|
+
throw new Error("An ORYKSA API key (oryk_live_...) is required. Create one at developer.oryksa.com.");
|
|
58
|
+
}
|
|
59
|
+
if (typeof window !== "undefined" && typeof document !== "undefined" && !opts.dangerouslyAllowBrowser) {
|
|
60
|
+
throw new Error("The secret API key must stay on the server. In apps use OryksaClient with a session token.");
|
|
61
|
+
}
|
|
62
|
+
this._key = apiKey;
|
|
63
|
+
this._base = (opts.baseUrl || DEFAULT_BASE).replace(/\/$/, "");
|
|
64
|
+
this._fetch = opts.fetch;
|
|
65
|
+
this._timeout = opts.timeoutMs || 60000;
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
_req(method, path, body) {
|
|
69
|
+
return request(this._base, this._key, method, path, body, this._fetch, this._timeout);
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
account() { return this._req("GET", "/account"); }
|
|
73
|
+
|
|
74
|
+
/** Chat with the AI employee. Reuse conversationId to keep the context. */
|
|
75
|
+
chat({ message, conversationId, customerName } = {}) {
|
|
76
|
+
return this._req("POST", "/chat", { message, conversation_id: conversationId, customer_name: customerName });
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
conversations({ limit } = {}) { return this._req("GET", "/conversations" + (limit ? "?limit=" + Number(limit) : "")); }
|
|
80
|
+
conversation(id) { return this._req("GET", "/conversations/" + encodeURIComponent(id)); }
|
|
81
|
+
|
|
82
|
+
get agent() {
|
|
83
|
+
return {
|
|
84
|
+
update: (fields) => this._req("PATCH", "/agent", fields),
|
|
85
|
+
appearance: (fields) => this._req("PATCH", "/agent/appearance", fields),
|
|
86
|
+
};
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
get knowledge() {
|
|
90
|
+
return {
|
|
91
|
+
get: () => this._req("GET", "/knowledge"),
|
|
92
|
+
setPages: ({ pages, businessSummary, siteUrl }) =>
|
|
93
|
+
this._req("PUT", "/knowledge/pages", { pages, business_summary: businessSummary, site_url: siteUrl }),
|
|
94
|
+
crawl: ({ url, maxPages }) => this._req("POST", "/knowledge/crawl", { url, max_pages: maxPages }),
|
|
95
|
+
addFaq: (items) => this._req("POST", "/knowledge/faq", { items }),
|
|
96
|
+
};
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
get widget() {
|
|
100
|
+
return {
|
|
101
|
+
snippet: ({ framework = "html", lang = "", position = "" } = {}) =>
|
|
102
|
+
this._req("GET", `/widget?framework=${encodeURIComponent(framework)}&lang=${encodeURIComponent(lang)}&position=${encodeURIComponent(position)}`),
|
|
103
|
+
setDomains: (domains) => this._req("PUT", "/widget/domains", { domains }),
|
|
104
|
+
};
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
get webhooks() {
|
|
108
|
+
return {
|
|
109
|
+
list: () => this._req("GET", "/webhooks"),
|
|
110
|
+
create: ({ url, events = ["*"] }) => this._req("POST", "/webhooks", { url, events }),
|
|
111
|
+
delete: (id) => this._req("DELETE", "/webhooks/" + encodeURIComponent(id)),
|
|
112
|
+
test: (id) => this._req("POST", "/webhooks/" + encodeURIComponent(id) + "/test"),
|
|
113
|
+
};
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
/** Short-lived token for an app user. Send only this token to the app.
|
|
117
|
+
* For a user signed in to your app, pass customerEmail and/or customerPhone (with the country code):
|
|
118
|
+
* the AI then asks for no contact details and knows the customer is signed in. */
|
|
119
|
+
createSession({ conversationId, customerName, customerEmail, customerPhone, ttlMinutes = 60 } = {}) {
|
|
120
|
+
return this._req("POST", "/sessions", { conversation_id: conversationId, customer_name: customerName,
|
|
121
|
+
customer_email: customerEmail, customer_phone: customerPhone, ttl_minutes: ttlMinutes });
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
/**
|
|
125
|
+
* Teach the AI employee about an app: what it is, its screens/features and FAQs.
|
|
126
|
+
* The agent then answers users inside the app with that knowledge.
|
|
127
|
+
* @param {{name:string, description?:string, screens?:{title:string, content:string, url?:string}[], faq?:{question:string, answer:string}[], languages?:string[], agentName?:string, settings?:object}} app
|
|
128
|
+
*/
|
|
129
|
+
async learnApp(app) {
|
|
130
|
+
if (!app || !app.name) throw new Error("learnApp needs at least { name }.");
|
|
131
|
+
const out = {};
|
|
132
|
+
const profile = { business_name: app.name };
|
|
133
|
+
if (app.description) profile.business_description = app.description;
|
|
134
|
+
if (app.agentName) profile.agent_name = app.agentName;
|
|
135
|
+
if (Array.isArray(app.languages)) profile.languages = app.languages;
|
|
136
|
+
if (Array.isArray(app.services)) profile.services = app.services;
|
|
137
|
+
out.agent = await this.agent.update(profile);
|
|
138
|
+
const pages = [];
|
|
139
|
+
if (app.description) pages.push({ title: app.name + " - overview", content: app.description });
|
|
140
|
+
for (const s of app.screens || []) {
|
|
141
|
+
if (s && s.content) pages.push({ title: s.title || "Screen", url: s.url, content: String(s.content) });
|
|
142
|
+
}
|
|
143
|
+
if (app.settings && typeof app.settings === "object") {
|
|
144
|
+
const lines = Object.entries(app.settings).map(([k, v]) => `${k}: ${typeof v === "object" ? JSON.stringify(v) : v}`);
|
|
145
|
+
pages.push({ title: app.name + " - configuration", content: lines.join("\n") });
|
|
146
|
+
}
|
|
147
|
+
if (pages.length) out.pages = await this.knowledge.setPages({ pages, siteUrl: app.url });
|
|
148
|
+
if (Array.isArray(app.faq) && app.faq.length) out.faq = await this.knowledge.addFaq(app.faq);
|
|
149
|
+
return out;
|
|
150
|
+
}
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
/**
|
|
154
|
+
* Verify an ORYKSA webhook signature (Node.js). Pass the RAW request body.
|
|
155
|
+
* @returns {Promise<object>} the parsed event, or throws OryksaError(400).
|
|
156
|
+
*/
|
|
157
|
+
export async function verifyWebhook(rawBody, signatureHeader, secret, { toleranceSeconds = 300 } = {}) {
|
|
158
|
+
const parts = Object.fromEntries(String(signatureHeader || "").split(",").map((p) => p.split("=")));
|
|
159
|
+
const t = Number(parts.t || 0);
|
|
160
|
+
if (!t || Math.abs(Date.now() / 1000 - t) > toleranceSeconds) throw new OryksaError(400, "invalid_signature", "Webhook timestamp is missing or too old.");
|
|
161
|
+
const body = typeof rawBody === "string" ? rawBody : new TextDecoder().decode(rawBody);
|
|
162
|
+
let expected;
|
|
163
|
+
if (globalThis.crypto && globalThis.crypto.subtle) {
|
|
164
|
+
const key = await globalThis.crypto.subtle.importKey("raw", new TextEncoder().encode(secret), { name: "HMAC", hash: "SHA-256" }, false, ["sign"]);
|
|
165
|
+
const sig = await globalThis.crypto.subtle.sign("HMAC", key, new TextEncoder().encode(t + "." + body));
|
|
166
|
+
expected = [...new Uint8Array(sig)].map((b) => b.toString(16).padStart(2, "0")).join("");
|
|
167
|
+
} else {
|
|
168
|
+
const { createHmac } = await import("node:crypto");
|
|
169
|
+
expected = createHmac("sha256", secret).update(t + "." + body).digest("hex");
|
|
170
|
+
}
|
|
171
|
+
const got = String(parts.v1 || "");
|
|
172
|
+
let diff = expected.length ^ got.length;
|
|
173
|
+
for (let i = 0; i < Math.min(expected.length, got.length); i++) diff |= expected.charCodeAt(i) ^ got.charCodeAt(i);
|
|
174
|
+
if (diff !== 0) throw new OryksaError(400, "invalid_signature", "Webhook signature does not match.");
|
|
175
|
+
return JSON.parse(body);
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
/**
|
|
179
|
+
* In-app client (browser, React Native, Electron). Uses a short-lived session token
|
|
180
|
+
* created by YOUR server with Oryksa.createSession(). Pass getToken() to refresh it.
|
|
181
|
+
*/
|
|
182
|
+
export class OryksaClient {
|
|
183
|
+
constructor({ token, getToken, baseUrl, fetch, timeoutMs } = {}) {
|
|
184
|
+
if (!token && !getToken) throw new Error("OryksaClient needs { token } or { getToken }.");
|
|
185
|
+
if (token && String(token).startsWith("oryk_live_")) throw new Error("Never use the secret API key in an app. Use a session token (oryk_cs_...).");
|
|
186
|
+
this._token = token || null;
|
|
187
|
+
this._getToken = getToken || null;
|
|
188
|
+
this._base = (baseUrl || DEFAULT_BASE).replace(/\/$/, "");
|
|
189
|
+
this._fetch = fetch;
|
|
190
|
+
this._timeout = timeoutMs || 60000;
|
|
191
|
+
this._previews = new Map();
|
|
192
|
+
}
|
|
193
|
+
|
|
194
|
+
async _tok(force) {
|
|
195
|
+
if ((!this._token || force) && this._getToken) this._token = await this._getToken();
|
|
196
|
+
return this._token;
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
async _req(method, path, body) {
|
|
200
|
+
try {
|
|
201
|
+
return await request(this._base, await this._tok(false), method, path, body, this._fetch, this._timeout);
|
|
202
|
+
} catch (e) {
|
|
203
|
+
if (e instanceof OryksaError && (e.code === "session_expired" || e.status === 401) && this._getToken) {
|
|
204
|
+
return request(this._base, await this._tok(true), method, path, body, this._fetch, this._timeout);
|
|
205
|
+
}
|
|
206
|
+
throw e;
|
|
207
|
+
}
|
|
208
|
+
}
|
|
209
|
+
|
|
210
|
+
agent() { return this._req("GET", "/client/agent"); }
|
|
211
|
+
/**
|
|
212
|
+
* Sends a message. opts.image: a photo from the customer ({ base64, mime }, up to 2 MB), the AI looks at it.
|
|
213
|
+
* opts.file: a document ({ base64, name, mime }: PDF, Word, text, CSV, up to 8 MB), the AI reads it.
|
|
214
|
+
*/
|
|
215
|
+
send(message, opts) { return this._req("POST", "/client/chat", chatBody(message, opts)); }
|
|
216
|
+
messages() { return this._req("GET", "/client/messages"); }
|
|
217
|
+
|
|
218
|
+
/**
|
|
219
|
+
* An AI task of your own app, counted as ORYKSA interactions (1 per answer): read a photo, extract data,
|
|
220
|
+
* classify, translate, write. It never creates a conversation in the business's inbox and never acts on the
|
|
221
|
+
* account. Your prompt (instructions) and your JSON Schema (schema) live in your app.
|
|
222
|
+
* opts: { instructions?, input?, images?: [{ base64, mime? }] (up to 4, about 1.5 MB each), schema?, maxTokens?, temperature? }
|
|
223
|
+
* Resolves { text, json, interactionsSpent, interactionsRemaining }.
|
|
224
|
+
*/
|
|
225
|
+
async ai(opts) {
|
|
226
|
+
return aiResult(await this._req("POST", "/client/ai", aiBody(opts)));
|
|
227
|
+
}
|
|
228
|
+
|
|
229
|
+
/**
|
|
230
|
+
* Title and picture of a link the AI gave, for the card under her reply:
|
|
231
|
+
* { object: "link_preview", url, title, image, site, price }. Only the pages of the business's own
|
|
232
|
+
* site (its website chat domains) get a title and a picture. Resolves null when it cannot be read;
|
|
233
|
+
* never throws. Kept in memory for this client.
|
|
234
|
+
*/
|
|
235
|
+
async linkPreview(url) {
|
|
236
|
+
const key = String(url || "");
|
|
237
|
+
if (this._previews.has(key)) return this._previews.get(key);
|
|
238
|
+
try {
|
|
239
|
+
const d = (await this._req("GET", "/client/link-preview?url=" + encodeURIComponent(key))) || {};
|
|
240
|
+
const str = (v) => (v === null || v === undefined ? "" : String(v));
|
|
241
|
+
const p = { object: "link_preview", url: str(d.url), title: str(d.title), image: str(d.image), site: str(d.site), price: str(d.price) };
|
|
242
|
+
if (this._previews.size > 200) this._previews.clear();
|
|
243
|
+
this._previews.set(key, p);
|
|
244
|
+
return p;
|
|
245
|
+
} catch (_) {
|
|
246
|
+
return null;
|
|
247
|
+
}
|
|
248
|
+
}
|
|
249
|
+
}
|
|
250
|
+
|
|
251
|
+
/** The JSON of POST /v1/client/ai. */
|
|
252
|
+
export function aiBody(opts) {
|
|
253
|
+
const o = opts || {};
|
|
254
|
+
const images = Array.isArray(o.images) ? o.images : [];
|
|
255
|
+
if (!o.instructions && !o.input && !images.length) throw new Error("ai() needs instructions, input or an image.");
|
|
256
|
+
if (images.length > 4) throw new Error("ai() takes at most 4 images.");
|
|
257
|
+
const body = { platform: "web" };
|
|
258
|
+
if (o.instructions) body.instructions = String(o.instructions);
|
|
259
|
+
if (o.input) body.input = String(o.input);
|
|
260
|
+
if (images.length) body.images = images.map((i) => ({ base64: i.base64, mime: i.mime || "image/jpeg" }));
|
|
261
|
+
if (o.schema) body.schema = o.schema;
|
|
262
|
+
if (o.maxTokens != null) body.max_tokens = o.maxTokens;
|
|
263
|
+
if (o.temperature != null) body.temperature = o.temperature;
|
|
264
|
+
return body;
|
|
265
|
+
}
|
|
266
|
+
|
|
267
|
+
/** Reads an ai_result answer. */
|
|
268
|
+
export function aiResult(d) {
|
|
269
|
+
const use = (d && d.oryksa) || {};
|
|
270
|
+
return {
|
|
271
|
+
text: (d && d.text) || "",
|
|
272
|
+
json: d && d.json && typeof d.json === "object" ? d.json : null,
|
|
273
|
+
interactionsSpent: use.interactions_spent || 0,
|
|
274
|
+
interactionsRemaining: use.interactions_remaining == null ? null : use.interactions_remaining,
|
|
275
|
+
};
|
|
276
|
+
}
|
|
277
|
+
|
|
278
|
+
/** The JSON of POST /v1/client/chat. */
|
|
279
|
+
function chatBody(message, opts) {
|
|
280
|
+
const o = opts || {};
|
|
281
|
+
const body = { message };
|
|
282
|
+
if (o.image && o.image.base64) { body.image_base64 = o.image.base64; body.image_mime = o.image.mime || "image/jpeg"; }
|
|
283
|
+
if (o.file && typeof o.file.base64 === "string") {
|
|
284
|
+
body.file_base64 = o.file.base64; body.file_name = o.file.name || "file"; body.file_mime = o.file.mime || "application/octet-stream";
|
|
285
|
+
}
|
|
286
|
+
return body;
|
|
287
|
+
}
|
|
288
|
+
|
|
289
|
+
/* ------------------------------------------------------------------ Attachments */
|
|
290
|
+
/** The largest photo the chat sends (after it is made smaller): 2 MB. */
|
|
291
|
+
export const MAX_PHOTO_BYTES = 2 * 1024 * 1024;
|
|
292
|
+
/** The largest document the chat sends: 8 MB. */
|
|
293
|
+
export const MAX_FILE_BYTES = 8 * 1024 * 1024;
|
|
294
|
+
|
|
295
|
+
const DOC_MIME = {
|
|
296
|
+
pdf: "application/pdf",
|
|
297
|
+
doc: "application/msword",
|
|
298
|
+
docx: "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
|
|
299
|
+
txt: "text/plain",
|
|
300
|
+
csv: "text/csv",
|
|
301
|
+
jpg: "image/jpeg",
|
|
302
|
+
jpeg: "image/jpeg",
|
|
303
|
+
png: "image/png",
|
|
304
|
+
webp: "image/webp",
|
|
305
|
+
};
|
|
306
|
+
const extOf = (name) => { const m = /\.([^./\\]+)$/.exec(String(name || "")); return m ? m[1].toLowerCase() : ""; };
|
|
307
|
+
|
|
308
|
+
/** The type of a file from its name ("application/octet-stream" when it is not a known one). */
|
|
309
|
+
export function mimeOf(name) { return DOC_MIME[extOf(name)] || "application/octet-stream"; }
|
|
310
|
+
|
|
311
|
+
/** How many bytes a base64 text holds. */
|
|
312
|
+
export function base64Bytes(b64) {
|
|
313
|
+
const s = String(b64 || "").replace(/\s+/g, "");
|
|
314
|
+
const pad = s.endsWith("==") ? 2 : s.endsWith("=") ? 1 : 0;
|
|
315
|
+
return Math.max(0, Math.floor((s.length * 3) / 4) - pad);
|
|
316
|
+
}
|
|
317
|
+
|
|
318
|
+
/** The size of a photo of w x h pixels with its longest side at most maxSide (never larger). */
|
|
319
|
+
export function scaledSize(w, h, maxSide = 1600) {
|
|
320
|
+
if (!(w > 0 && h > 0)) return { width: 0, height: 0 };
|
|
321
|
+
const k = Math.min(1, maxSide / Math.max(w, h));
|
|
322
|
+
return { width: Math.max(1, Math.round(w * k)), height: Math.max(1, Math.round(h * k)) };
|
|
323
|
+
}
|
|
324
|
+
|
|
325
|
+
/** A photo ({ base64, mime }) as what the chat sends: { image } or { error: "big" | "failed" }. */
|
|
326
|
+
export function photoAttachment(p) {
|
|
327
|
+
if (!p || typeof p.base64 !== "string" || !p.base64) return { error: "failed" };
|
|
328
|
+
if (base64Bytes(p.base64) > MAX_PHOTO_BYTES) return { error: "big" };
|
|
329
|
+
return { image: { base64: p.base64, mime: p.mime || "image/jpeg" } };
|
|
330
|
+
}
|
|
331
|
+
|
|
332
|
+
/**
|
|
333
|
+
* A document ({ base64, name, mime } or { tooBig: true }) as what the chat sends: pictures up to 2 MB
|
|
334
|
+
* as { image } (the AI looks at it), the rest as { file } up to 8 MB, else { error: "big" | "failed" }.
|
|
335
|
+
*/
|
|
336
|
+
export function documentAttachment(d) {
|
|
337
|
+
if (!d) return { error: "failed" };
|
|
338
|
+
if (d.tooBig) return { error: "big" };
|
|
339
|
+
if (typeof d.base64 !== "string") return { error: "failed" };
|
|
340
|
+
const size = base64Bytes(d.base64);
|
|
341
|
+
if (size > MAX_FILE_BYTES) return { error: "big" };
|
|
342
|
+
const name = d.name || "file";
|
|
343
|
+
const mime = DOC_MIME[extOf(name)] || d.mime || "application/octet-stream";
|
|
344
|
+
if (mime.startsWith("image/") && size <= MAX_PHOTO_BYTES) return { image: { base64: d.base64, mime } };
|
|
345
|
+
return { file: { base64: d.base64, name, mime } };
|
|
346
|
+
}
|
|
347
|
+
|
|
348
|
+
const blobToBase64 = (blob) => new Promise((ok, fail) => {
|
|
349
|
+
const r = new FileReader();
|
|
350
|
+
r.onload = () => ok(String(r.result || "").replace(/^data:[^,]*,/, ""));
|
|
351
|
+
r.onerror = () => fail(r.error || new Error("read failed"));
|
|
352
|
+
r.readAsDataURL(blob);
|
|
353
|
+
});
|
|
354
|
+
|
|
355
|
+
/** A picture File as a JPEG of at most 1600 pixels on its longest side, at 80% (browser: canvas). */
|
|
356
|
+
export async function photoFromFile(file, maxSide = 1600, quality = 0.8) {
|
|
357
|
+
const url = URL.createObjectURL(file);
|
|
358
|
+
try {
|
|
359
|
+
const img = await new Promise((ok, fail) => { const i = new Image(); i.onload = () => ok(i); i.onerror = () => fail(new Error("not a picture")); i.src = url; });
|
|
360
|
+
const { width, height } = scaledSize(img.naturalWidth, img.naturalHeight, maxSide);
|
|
361
|
+
const c = document.createElement("canvas");
|
|
362
|
+
c.width = width; c.height = height;
|
|
363
|
+
const g = c.getContext("2d");
|
|
364
|
+
g.fillStyle = "#fff"; // JPEG has no transparency
|
|
365
|
+
g.fillRect(0, 0, width, height);
|
|
366
|
+
g.drawImage(img, 0, 0, width, height);
|
|
367
|
+
const blob = await new Promise((ok) => c.toBlob(ok, "image/jpeg", quality));
|
|
368
|
+
if (!blob) throw new Error("could not make the JPEG");
|
|
369
|
+
return { base64: await blobToBase64(blob), mime: "image/jpeg" };
|
|
370
|
+
} finally {
|
|
371
|
+
URL.revokeObjectURL(url);
|
|
372
|
+
}
|
|
373
|
+
}
|
|
374
|
+
|
|
375
|
+
/** A document File as { base64, name, mime } (or { tooBig: true } above 8 MB, without reading it). */
|
|
376
|
+
export async function documentFromFile(file) {
|
|
377
|
+
if (file.size > MAX_FILE_BYTES) return { tooBig: true, name: file.name };
|
|
378
|
+
return { base64: await blobToBase64(file), name: file.name, mime: file.type || mimeOf(file.name) };
|
|
379
|
+
}
|
|
380
|
+
|
|
381
|
+
/* ------------------------------------------------------------------ Links of the AI's replies */
|
|
382
|
+
const URL_RE = /https?:\/\/[^\s<>"'\)\]]+/gi;
|
|
383
|
+
const MAIL_RE = /[\w.+-]+@[\w-]+(\.[\w-]+)+/g;
|
|
384
|
+
|
|
385
|
+
/** Every match of re in s (a fresh copy of the regular expression, so no state is shared). */
|
|
386
|
+
function allMatches(re, s) {
|
|
387
|
+
const r = new RegExp(re.source, re.flags);
|
|
388
|
+
const out = [];
|
|
389
|
+
let m;
|
|
390
|
+
while ((m = r.exec(s)) !== null) {
|
|
391
|
+
out.push(m);
|
|
392
|
+
if (m[0] === "") r.lastIndex++;
|
|
393
|
+
}
|
|
394
|
+
return out;
|
|
395
|
+
}
|
|
396
|
+
|
|
397
|
+
const trimEnd = (u) => u.replace(/[.,;:!?…]+$/, "");
|
|
398
|
+
|
|
399
|
+
/** The distinct web links of text, in order, without the punctuation that ends the sentence (at most max). */
|
|
400
|
+
export function linksIn(text, max = 3) {
|
|
401
|
+
const out = [];
|
|
402
|
+
for (const m of allMatches(URL_RE, String(text || ""))) {
|
|
403
|
+
const u = trimEnd(m[0]);
|
|
404
|
+
if (!out.includes(u)) out.push(u);
|
|
405
|
+
if (out.length >= max) break;
|
|
406
|
+
}
|
|
407
|
+
return out;
|
|
408
|
+
}
|
|
409
|
+
|
|
410
|
+
/** text without its web links (what a voice screen shows: the link is on the button). */
|
|
411
|
+
export function withoutLinks(text) {
|
|
412
|
+
return String(text || "")
|
|
413
|
+
.replace(URL_RE, "")
|
|
414
|
+
.replace(/[ \t]+\n/g, "\n")
|
|
415
|
+
.replace(/\n{3,}/g, "\n\n")
|
|
416
|
+
.replace(/[ \t]{2,}/g, " ")
|
|
417
|
+
.replace(/\s+([.,;!?])/g, "$1")
|
|
418
|
+
.replace(/:\s*$/gm, "")
|
|
419
|
+
.trim();
|
|
420
|
+
}
|
|
421
|
+
|
|
422
|
+
/** text as parts { text, url }: url only on the links (web, and e-mail as mailto:). */
|
|
423
|
+
export function linkParts(text) {
|
|
424
|
+
const s = String(text || "");
|
|
425
|
+
const hits = [];
|
|
426
|
+
for (const m of allMatches(URL_RE, s)) {
|
|
427
|
+
const u = trimEnd(m[0]);
|
|
428
|
+
hits.push({ start: m.index, end: m.index + u.length, url: u });
|
|
429
|
+
}
|
|
430
|
+
for (const m of allMatches(MAIL_RE, s)) {
|
|
431
|
+
const start = m.index, end = m.index + m[0].length;
|
|
432
|
+
if (hits.some((x) => start < x.end && end > x.start)) continue;
|
|
433
|
+
hits.push({ start, end, url: "mailto:" + m[0] });
|
|
434
|
+
}
|
|
435
|
+
hits.sort((a, b) => a.start - b.start);
|
|
436
|
+
const out = [];
|
|
437
|
+
let at = 0;
|
|
438
|
+
for (const x of hits) {
|
|
439
|
+
if (x.start < at) continue;
|
|
440
|
+
if (x.start > at) out.push({ text: s.slice(at, x.start), url: null });
|
|
441
|
+
out.push({ text: s.slice(x.start, x.end), url: x.url });
|
|
442
|
+
at = x.end;
|
|
443
|
+
}
|
|
444
|
+
if (at < s.length) out.push({ text: s.slice(at), url: null });
|
|
445
|
+
return out;
|
|
446
|
+
}
|
|
447
|
+
|
|
448
|
+
/**
|
|
449
|
+
* Opens a link: your handler first (return true when your app opened it, for example its own product
|
|
450
|
+
* page), then a new tab (window.open with noopener).
|
|
451
|
+
*/
|
|
452
|
+
export function openLink(url, handler) {
|
|
453
|
+
if (handler && handler(url) === true) return;
|
|
454
|
+
if (typeof window !== "undefined" && window.open) window.open(url, "_blank", "noopener");
|
|
455
|
+
}
|
|
456
|
+
|
|
457
|
+
const hostOf = (url) => {
|
|
458
|
+
const m = /^[a-z][a-z0-9+.-]*:\/\/([^/?#:]+)/i.exec(String(url || ""));
|
|
459
|
+
return m ? m[1].replace(/^www\./i, "") : "";
|
|
460
|
+
};
|
|
461
|
+
|
|
462
|
+
/* ------------------------------------------------------------------ Browser chat UI */
|
|
463
|
+
const CSS = `
|
|
464
|
+
:host{all:initial}
|
|
465
|
+
*{box-sizing:border-box;font-family:Manrope,Inter,system-ui,-apple-system,Segoe UI,sans-serif}
|
|
466
|
+
.btn{position:fixed;bottom:22px;display:flex;align-items:center;gap:10px;background:var(--accent);color:#fff;border:0;border-radius:999px;padding:8px 18px 8px 8px;cursor:pointer;box-shadow:0 12px 30px rgba(22,27,61,.28);font-weight:800;font-size:13px;letter-spacing:.08em;text-transform:uppercase;z-index:2147483000}
|
|
467
|
+
.btn img{width:42px;height:42px;border-radius:50%;object-fit:cover;border:2px solid #fff}
|
|
468
|
+
.panel{position:fixed;bottom:92px;width:380px;max-width:calc(100vw - 24px);height:560px;max-height:calc(100vh - 120px);background:#fff;border-radius:20px;box-shadow:0 24px 60px rgba(22,27,61,.25);display:none;flex-direction:column;overflow:hidden;z-index:2147483000;color:var(--ink)}
|
|
469
|
+
.panel.open{display:flex}
|
|
470
|
+
.hd{display:flex;align-items:center;gap:12px;padding:14px 16px;border-bottom:1px solid #eceef6}
|
|
471
|
+
.hd img{width:46px;height:46px;border-radius:50%;object-fit:cover}
|
|
472
|
+
.hd b{display:block;font-size:14px;letter-spacing:.14em;text-transform:uppercase}
|
|
473
|
+
.hd small{color:#6b7280;font-size:12px}
|
|
474
|
+
.hd button{margin-left:auto;border:0;background:none;font-size:20px;cursor:pointer;color:#6b7280}
|
|
475
|
+
.msgs{flex:1;overflow:auto;padding:16px;display:flex;flex-direction:column;gap:10px;background:#fff}
|
|
476
|
+
.m{max-width:82%;padding:10px 14px;border-radius:16px;font-size:14px;line-height:1.5;white-space:pre-wrap;word-wrap:break-word}
|
|
477
|
+
.m.a{background:var(--soft);align-self:flex-start;border-bottom-left-radius:6px}
|
|
478
|
+
.m.u{background:var(--accent);color:#fff;align-self:flex-end;border-bottom-right-radius:6px}
|
|
479
|
+
.m.t{opacity:.6}
|
|
480
|
+
.sug{display:flex;flex-wrap:wrap;gap:8px;padding:0 16px 10px}
|
|
481
|
+
.sug button{border:1px solid #dcdcf5;background:#fff;color:var(--accent);border-radius:999px;padding:7px 12px;font-size:12.5px;cursor:pointer}
|
|
482
|
+
form{display:flex;border-top:1px solid #eceef6}
|
|
483
|
+
input{flex:1;border:0;padding:14px 16px;font-size:14px;outline:none;color:var(--ink)}
|
|
484
|
+
form button{border:0;background:var(--accent);color:#fff;font-weight:800;padding:0 18px;letter-spacing:.1em;cursor:pointer}
|
|
485
|
+
.pw{text-align:center;font-size:10.5px;letter-spacing:.12em;color:#9ca3af;padding:6px 0 8px;text-transform:uppercase}
|
|
486
|
+
.pw b{color:var(--accent)}
|
|
487
|
+
.m a{text-decoration:underline;cursor:pointer;word-break:break-all}
|
|
488
|
+
.m.a a{color:var(--accent)}
|
|
489
|
+
.m.u a{color:#fff}
|
|
490
|
+
.lk{align-self:flex-start;width:86%;display:flex;align-items:center;gap:10px;padding:8px;border:1px solid #e5e7eb;border-radius:14px;background:#fff;cursor:pointer;margin-top:-4px}
|
|
491
|
+
.lk .pic{flex:none;width:52px;height:52px;border-radius:10px;background:#e5e7eb;overflow:hidden;display:flex;align-items:center;justify-content:center;color:#6b7280}
|
|
492
|
+
.lk .pic img{width:100%;height:100%;object-fit:cover}
|
|
493
|
+
.lk .tx{flex:1;min-width:0}
|
|
494
|
+
.lk .tt{font-size:13.5px;line-height:1.3;font-weight:700;color:var(--ink);display:-webkit-box;-webkit-line-clamp:2;-webkit-box-orient:vertical;overflow:hidden;word-break:break-word}
|
|
495
|
+
.lk .sb{font-size:11.5px;color:#6b7280;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}
|
|
496
|
+
.lk button{flex:none;border:0;background:var(--accent);color:#fff;border-radius:999px;min-height:36px;padding:0 14px;font-size:13px;font-weight:700;cursor:pointer}
|
|
497
|
+
form button.clip{background:none;color:var(--accent);padding:0 10px;display:flex;align-items:center}
|
|
498
|
+
form button.clip:disabled{opacity:.5;cursor:default}
|
|
499
|
+
.menu{display:none;flex-direction:column;border-top:1px solid #eceef6;padding:4px 0}
|
|
500
|
+
.menu.open{display:flex}
|
|
501
|
+
.menu button{border:0;background:none;text-align:left;padding:11px 16px;font-size:14px;color:var(--ink);cursor:pointer}
|
|
502
|
+
.menu button:hover{background:#f5f5fb}
|
|
503
|
+
.note{display:none;align-self:center;margin:0 auto 8px;background:var(--ink);color:#fff;font-size:12.5px;padding:8px 12px;border-radius:999px}
|
|
504
|
+
.note.on{display:block}
|
|
505
|
+
.m .ph{display:block;width:200px;height:160px;object-fit:cover;border-radius:12px}
|
|
506
|
+
.m .fl{display:flex;align-items:center;gap:6px;font-size:13px;font-weight:600}
|
|
507
|
+
.m .fl svg{flex:none}
|
|
508
|
+
.m .ph + .fl{margin-top:8px}
|
|
509
|
+
.m .ph + span,.m .fl + span{display:block;margin-top:8px}
|
|
510
|
+
`;
|
|
511
|
+
|
|
512
|
+
const CLIP_ICON = '<svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="m21.44 11.05-9.19 9.19a6 6 0 0 1-8.49-8.49l8.57-8.57A4 4 0 1 1 18 8.84l-8.59 8.57a2 2 0 0 1-2.83-2.83l8.49-8.48"/></svg>';
|
|
513
|
+
const DOC_ICON = '<svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M15 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7Z"/><path d="M14 2v4a2 2 0 0 0 2 2h4"/><path d="M16 13H8"/><path d="M16 17H8"/></svg>';
|
|
514
|
+
|
|
515
|
+
const LINK_ICON = '<svg width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M10 13a5 5 0 0 0 7.54.54l3-3a5 5 0 0 0-7.07-7.07l-1.72 1.71"/><path d="M14 11a5 5 0 0 0-7.54-.54l-3 3a5 5 0 0 0 7.07 7.07l1.71-1.71"/></svg>';
|
|
516
|
+
|
|
517
|
+
const UI_TXT = {
|
|
518
|
+
en: { talk: "Talk to", ph: "Type your question", send: "Send", err: "Sorry, something went wrong. Try again.", open: "Open",
|
|
519
|
+
attach: "Attach", gallery: "Photo library", camera: "Camera", document: "Document", big: "The file is too large (max 8 MB).", attachErr: "Could not attach the file." },
|
|
520
|
+
pt: { talk: "Falar com", ph: "Escreve a tua pergunta", send: "Enviar", err: "Desculpa, algo correu mal. Tenta de novo.", open: "Abrir",
|
|
521
|
+
attach: "Anexar", gallery: "Foto da galeria", camera: "Câmara", document: "Documento", big: "O ficheiro é demasiado grande (máx. 8 MB).", attachErr: "Não foi possível anexar o ficheiro." },
|
|
522
|
+
br: { talk: "Falar com", ph: "Digite sua pergunta", send: "Enviar", err: "Desculpe, algo deu errado. Tente de novo.", open: "Abrir",
|
|
523
|
+
attach: "Anexar", gallery: "Foto da galeria", camera: "Câmera", document: "Documento", big: "O arquivo é grande demais (máx. 8 MB).", attachErr: "Não foi possível anexar o arquivo." },
|
|
524
|
+
es: { talk: "Hablar con", ph: "Escribe tu pregunta", send: "Enviar", err: "Lo siento, algo salió mal. Inténtalo de nuevo.", open: "Abrir",
|
|
525
|
+
attach: "Adjuntar", gallery: "Foto de la galería", camera: "Cámara", document: "Documento", big: "El archivo es demasiado grande (máx. 8 MB).", attachErr: "No se pudo adjuntar el archivo." },
|
|
526
|
+
};
|
|
527
|
+
|
|
528
|
+
/**
|
|
529
|
+
* Mount the ORYKSA chat inside a web app (same look as the website chat).
|
|
530
|
+
* onLink(url): what your app does with a link the AI gave; return true when your app opened it,
|
|
531
|
+
* otherwise it opens in a new tab. attachments (default true): the attach button (photo library,
|
|
532
|
+
* camera on phones, document).
|
|
533
|
+
* @param {{client: OryksaClient, lang?: 'en'|'pt'|'br'|'es', position?: 'left'|'right', accent?: string, ink?: string, soft?: string, open?: boolean, onLink?: (url: string) => boolean, attachments?: boolean}} opts
|
|
534
|
+
*/
|
|
535
|
+
export function mountChat(opts) {
|
|
536
|
+
if (typeof document === "undefined") throw new Error("mountChat runs in a browser. In React Native use @oryksa/react-native.");
|
|
537
|
+
const client = opts.client;
|
|
538
|
+
const lang = UI_TXT[opts.lang] ? opts.lang : "en";
|
|
539
|
+
const tx = UI_TXT[lang];
|
|
540
|
+
const host = document.createElement("div");
|
|
541
|
+
host.id = "oryksa-sdk-chat";
|
|
542
|
+
document.body.appendChild(host);
|
|
543
|
+
const root = host.attachShadow({ mode: "open" });
|
|
544
|
+
const side = opts.position === "left" ? "left:22px" : "right:22px";
|
|
545
|
+
root.innerHTML = `<style>${CSS}
|
|
546
|
+
:host{--accent:${opts.accent || "#5B57E0"};--ink:${opts.ink || "#161B3D"};--soft:${opts.soft || "#EEEBFB"}}
|
|
547
|
+
.btn,.panel{${side}}</style>
|
|
548
|
+
<button class="btn" part="button"><img alt=""><span></span></button>
|
|
549
|
+
<div class="panel" part="panel"><div class="hd"><img alt=""><div><b></b><small></small></div><button aria-label="close">×</button></div>
|
|
550
|
+
<div class="msgs"></div><div class="sug"></div><div class="note" role="status"></div><div class="menu"></div>
|
|
551
|
+
<form><input maxlength="2000"><button type="button" class="clip"></button><button type="submit"></button></form><div class="pw">Powered by <b>ORYKSA</b></div>
|
|
552
|
+
<input type="file" class="f-photo" accept="image/*" hidden><input type="file" class="f-cam" accept="image/*" capture="environment" hidden>
|
|
553
|
+
<input type="file" class="f-doc" accept="image/*,.pdf,.doc,.docx,.txt,.csv" hidden></div>`;
|
|
554
|
+
const $ = (s) => root.querySelector(s);
|
|
555
|
+
const panel = $(".panel"), msgs = $(".msgs"), sug = $(".sug"), input = $("form input");
|
|
556
|
+
input.placeholder = tx.ph;
|
|
557
|
+
$("form button[type=submit]").textContent = tx.send;
|
|
558
|
+
const onLink = opts.onLink;
|
|
559
|
+
// The links of a message can be tapped (web and e-mail): your onLink first, then the browser.
|
|
560
|
+
const fill = (d, text) => {
|
|
561
|
+
for (const p of linkParts(text)) {
|
|
562
|
+
if (!p.url) { d.appendChild(document.createTextNode(p.text)); continue; }
|
|
563
|
+
const a = document.createElement("a");
|
|
564
|
+
a.href = p.url;
|
|
565
|
+
a.target = "_blank";
|
|
566
|
+
a.rel = "noopener";
|
|
567
|
+
a.textContent = p.text;
|
|
568
|
+
a.addEventListener("click", (e) => { if (onLink && onLink(p.url) === true) e.preventDefault(); });
|
|
569
|
+
d.appendChild(a);
|
|
570
|
+
}
|
|
571
|
+
};
|
|
572
|
+
// The card under a reply for each web link: picture, title (from ORYKSA) and an Open button.
|
|
573
|
+
const card = (url) => {
|
|
574
|
+
const c = document.createElement("div");
|
|
575
|
+
c.className = "lk";
|
|
576
|
+
c.innerHTML = '<div class="pic">' + LINK_ICON + '</div><div class="tx"><div class="tt"></div><div class="sb"></div></div><button type="button"></button>';
|
|
577
|
+
const site = hostOf(url);
|
|
578
|
+
const tt = c.querySelector(".tt"), sb = c.querySelector(".sb"), btn = c.querySelector("button");
|
|
579
|
+
tt.textContent = site; sb.textContent = site; btn.textContent = tx.open;
|
|
580
|
+
btn.setAttribute("aria-label", tx.open + ": " + site);
|
|
581
|
+
const open = (e) => { e.stopPropagation(); openLink(url, onLink); };
|
|
582
|
+
c.addEventListener("click", open);
|
|
583
|
+
btn.addEventListener("click", open);
|
|
584
|
+
Promise.resolve(client.linkPreview ? client.linkPreview(url) : null).then((p) => {
|
|
585
|
+
if (!p) return;
|
|
586
|
+
const title = p.title || site;
|
|
587
|
+
tt.textContent = title;
|
|
588
|
+
sb.textContent = p.price ? p.price + " · " + p.site : (p.site || site);
|
|
589
|
+
btn.setAttribute("aria-label", tx.open + ": " + title);
|
|
590
|
+
if (/^https?:\/\//i.test(p.image || "")) {
|
|
591
|
+
const img = document.createElement("img");
|
|
592
|
+
img.alt = "";
|
|
593
|
+
img.src = p.image;
|
|
594
|
+
img.onload = () => { const pic = c.querySelector(".pic"); pic.textContent = ""; pic.appendChild(img); };
|
|
595
|
+
}
|
|
596
|
+
}).catch(() => {});
|
|
597
|
+
return c;
|
|
598
|
+
};
|
|
599
|
+
// att: { image } or { file } the customer attached (thumbnail, or the document icon and its name).
|
|
600
|
+
const add = (role, text, att) => {
|
|
601
|
+
const d = document.createElement("div");
|
|
602
|
+
d.className = "m " + (role === "user" ? "u" : role === "typing" ? "a t" : "a");
|
|
603
|
+
if (att && att.image) {
|
|
604
|
+
const img = document.createElement("img");
|
|
605
|
+
img.className = "ph";
|
|
606
|
+
img.alt = tx.gallery;
|
|
607
|
+
img.src = "data:" + (att.image.mime || "image/jpeg") + ";base64," + att.image.base64;
|
|
608
|
+
d.appendChild(img);
|
|
609
|
+
}
|
|
610
|
+
if (att && att.file) {
|
|
611
|
+
const f = document.createElement("div");
|
|
612
|
+
f.className = "fl";
|
|
613
|
+
f.innerHTML = DOC_ICON;
|
|
614
|
+
const n = document.createElement("span");
|
|
615
|
+
n.textContent = att.file.name;
|
|
616
|
+
f.appendChild(n);
|
|
617
|
+
d.appendChild(f);
|
|
618
|
+
}
|
|
619
|
+
if (role === "typing") d.textContent = text;
|
|
620
|
+
else if (text) { const t = document.createElement("span"); fill(t, text); d.appendChild(t); }
|
|
621
|
+
msgs.appendChild(d);
|
|
622
|
+
if (role !== "user" && role !== "typing") for (const u of linksIn(text)) msgs.appendChild(card(u));
|
|
623
|
+
msgs.scrollTop = msgs.scrollHeight;
|
|
624
|
+
return d;
|
|
625
|
+
};
|
|
626
|
+
let busy = false;
|
|
627
|
+
const clip = $("form button.clip");
|
|
628
|
+
const send = async (text, att) => {
|
|
629
|
+
text = String(text || "").trim();
|
|
630
|
+
const a = att || {};
|
|
631
|
+
if ((!text && !a.image && !a.file) || busy) return;
|
|
632
|
+
busy = true; clip.disabled = true; sug.innerHTML = ""; add("user", text, a); input.value = "";
|
|
633
|
+
const typing = add("typing", "...");
|
|
634
|
+
try {
|
|
635
|
+
let r = await client.send(text, a.image || a.file ? { image: a.image, file: a.file } : undefined);
|
|
636
|
+
if (r && r.status === "pending") {
|
|
637
|
+
for (let i = 0; i < 20 && r.status === "pending"; i++) {
|
|
638
|
+
await new Promise((ok) => setTimeout(ok, 1500));
|
|
639
|
+
const h = await client.messages();
|
|
640
|
+
const last = (h.messages || []).slice(-1)[0];
|
|
641
|
+
if (last && last.role === "assistant") r = { status: "replied", reply: last.content };
|
|
642
|
+
}
|
|
643
|
+
}
|
|
644
|
+
typing.remove();
|
|
645
|
+
add("assistant", (r && r.reply) || tx.err);
|
|
646
|
+
} catch (e) {
|
|
647
|
+
typing.remove();
|
|
648
|
+
add("assistant", tx.err);
|
|
649
|
+
} finally { busy = false; clip.disabled = false; }
|
|
650
|
+
};
|
|
651
|
+
|
|
652
|
+
// The attach button: photo library, camera (phones and tablets), document; a note when too large or unreadable.
|
|
653
|
+
const menu = $(".menu"), note = $(".note");
|
|
654
|
+
let noteTimer = null;
|
|
655
|
+
const showNote = (t) => {
|
|
656
|
+
note.textContent = t; note.classList.add("on");
|
|
657
|
+
clearTimeout(noteTimer); noteTimer = setTimeout(() => note.classList.remove("on"), 3500);
|
|
658
|
+
};
|
|
659
|
+
const touch = typeof window !== "undefined" && window.matchMedia && window.matchMedia("(pointer: coarse)").matches;
|
|
660
|
+
const attachIt = async (picked) => {
|
|
661
|
+
const r = picked;
|
|
662
|
+
if (r.error) { showNote(r.error === "big" ? tx.big : tx.attachErr); return; }
|
|
663
|
+
await send(input.value, r);
|
|
664
|
+
};
|
|
665
|
+
const onPick = (el, kind) => el.addEventListener("change", async () => {
|
|
666
|
+
const f = el.files && el.files[0];
|
|
667
|
+
el.value = "";
|
|
668
|
+
if (!f) return;
|
|
669
|
+
try {
|
|
670
|
+
if (kind === "doc") await attachIt(documentAttachment(await documentFromFile(f)));
|
|
671
|
+
else await attachIt(photoAttachment(await photoFromFile(f)));
|
|
672
|
+
} catch (_) {
|
|
673
|
+
showNote(tx.attachErr);
|
|
674
|
+
}
|
|
675
|
+
});
|
|
676
|
+
if (opts.attachments === false) {
|
|
677
|
+
clip.remove();
|
|
678
|
+
} else {
|
|
679
|
+
clip.innerHTML = CLIP_ICON;
|
|
680
|
+
clip.setAttribute("aria-label", tx.attach);
|
|
681
|
+
clip.title = tx.attach;
|
|
682
|
+
const choices = [["f-photo", tx.gallery]].concat(touch ? [["f-cam", tx.camera]] : [], [["f-doc", tx.document]]);
|
|
683
|
+
for (const [cls, label] of choices) {
|
|
684
|
+
const b = document.createElement("button");
|
|
685
|
+
b.type = "button";
|
|
686
|
+
b.textContent = label;
|
|
687
|
+
b.addEventListener("click", () => { menu.classList.remove("open"); $("." + cls).click(); });
|
|
688
|
+
menu.appendChild(b);
|
|
689
|
+
}
|
|
690
|
+
clip.addEventListener("click", () => { if (!busy) menu.classList.toggle("open"); });
|
|
691
|
+
onPick($(".f-photo"), "photo");
|
|
692
|
+
onPick($(".f-cam"), "photo");
|
|
693
|
+
onPick($(".f-doc"), "doc");
|
|
694
|
+
}
|
|
695
|
+
$("form").addEventListener("submit", (e) => { e.preventDefault(); send(input.value); });
|
|
696
|
+
$(".btn").addEventListener("click", () => { panel.classList.toggle("open"); if (panel.classList.contains("open")) input.focus(); });
|
|
697
|
+
$(".hd button").addEventListener("click", () => panel.classList.remove("open"));
|
|
698
|
+
client.agent().then(async (a) => {
|
|
699
|
+
const pick = (o) => (o && (o[lang] || (lang === "br" && o.pt) || o.en || Object.values(o)[0])) || "";
|
|
700
|
+
root.querySelectorAll("img").forEach((i) => (i.src = a.avatar));
|
|
701
|
+
$(".btn span").textContent = tx.talk + " " + a.name;
|
|
702
|
+
$(".hd b").textContent = a.name;
|
|
703
|
+
$(".hd small").textContent = pick(a.subtitle) || a.business || "";
|
|
704
|
+
const hist = await client.messages().catch(() => ({ messages: [] }));
|
|
705
|
+
if ((hist.messages || []).length) hist.messages.forEach((m) => add(m.role, m.content));
|
|
706
|
+
else if (pick(a.greeting)) add("assistant", pick(a.greeting));
|
|
707
|
+
const sg = (a.suggestions && (a.suggestions[lang] || (lang === "br" && a.suggestions.pt) || a.suggestions.en)) || [];
|
|
708
|
+
sg.slice(0, 4).forEach((s) => { const b = document.createElement("button"); b.textContent = s; b.onclick = () => send(s); sug.appendChild(b); });
|
|
709
|
+
}).catch(() => { $(".btn span").textContent = tx.talk + " ORYKSA"; });
|
|
710
|
+
if (opts.open) panel.classList.add("open");
|
|
711
|
+
return {
|
|
712
|
+
open: () => panel.classList.add("open"),
|
|
713
|
+
close: () => panel.classList.remove("open"),
|
|
714
|
+
send,
|
|
715
|
+
destroy: () => host.remove(),
|
|
716
|
+
};
|
|
717
|
+
}
|
|
718
|
+
|
|
719
|
+
export default Oryksa;
|