@omniscore/chat-sdk 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,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright 2026 Omniscore
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
package/README.md CHANGED
@@ -1,3 +1,105 @@
1
- # Temporary Holding Version
1
+ # @omniscore/chat-sdk
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 client of the Omniscore website chat, for a site that draws its own chat interface. It keeps the
4
+ visitor's token, sends their messages, reads the answers and gives your page the chat as a state. It draws nothing.
5
+
6
+ No dependencies; about 2 KB minified and gzipped.
7
+
8
+ If you only want a chat on your site, you do not need this: paste the widget's line from the chat's page in Omniscore.
9
+
10
+ ## Before you start
11
+
12
+ - Create a website chat in Omniscore and copy its key.
13
+ - Add your site's address to the chat's list of sites. A page on any other address is refused by the browser.
14
+
15
+ ## Install
16
+
17
+ ```sh
18
+ npm install @omniscore/chat-sdk
19
+ ```
20
+
21
+ ```js
22
+ import { createChat } from "@omniscore/chat-sdk";
23
+
24
+ const chat = createChat({ key: "<the chat's key>", url: "https://<your Omniscore address>" });
25
+
26
+ chat.subscribe((state) => {
27
+ // draw state.messages, state.outgoing and state.answering
28
+ });
29
+ chat.open();
30
+ ```
31
+
32
+ Or without a bundler, from your Omniscore address; `url` is then taken from where the script came from:
33
+
34
+ ```html
35
+ <script src="https://<your Omniscore address>/web_chat/sdk.js"></script>
36
+ <script>
37
+ const chat = OmniChat.createChat({ key: "<the chat's key>" });
38
+ </script>
39
+ ```
40
+
41
+ ## Options
42
+
43
+ | Option | What |
44
+ | --- | --- |
45
+ | `key` | The chat's key. Required |
46
+ | `url` | Your Omniscore address. Required from npm; optional in the script build |
47
+ | `visible` | Whether the chat is on screen from the start. Default `true` |
48
+ | `page` | The address sent with a message, a string or a function. By default the page's address without its query |
49
+ | `storage` | Where the token and the last seen message are kept: `{ read(), write(patch) }`. By default `localStorage` under `omni-chat:<key>`, the entry the widget uses too, so a site that moves from the widget keeps its visitors |
50
+ | `fetch` | Your own `fetch` |
51
+
52
+ ## The chat
53
+
54
+ | Member | What |
55
+ | --- | --- |
56
+ | `getState()` | The state. A new object on every change |
57
+ | `subscribe(listener)` | Calls `listener(state)` on every change. Returns the function that ends it |
58
+ | `open()` | Takes the visitor's token (a new one for a new visitor), reads the chat so far and keeps reading. A promise of the state. Call it when the visitor opens the chat: nothing is asked of the server before that |
59
+ | `send(text)` | Writes the visitor's message and returns its client id, or `null` for empty text. Opens the chat if it was not |
60
+ | `retry(clientId)` | Sends a failed message once more. It is never doubled |
61
+ | `read()` | The visitor has seen everything so far: `unread` becomes 0 |
62
+ | `setVisible(bool)` | Tell it when the chat goes on and off screen: it reads every 3 seconds on screen and every 20 off it |
63
+ | `destroy()` | Stops reading and drops the listeners |
64
+
65
+ ## The state
66
+
67
+ | Field | What |
68
+ | --- | --- |
69
+ | `status` | `idle`, `opening`, `open`, `closed` (the chat was switched off or does not exist), `destroyed` |
70
+ | `messages` | Oldest first. Each has `id`, `from` (`visitor` or `team`), `text`, `at`, `clientId` |
71
+ | `outgoing` | What this page wrote and the server has not stored yet. Each has `clientId`, `text`, `status` (`sending` or `failed`) and `error` |
72
+ | `answering` | An answer is being written: show your typing sign |
73
+ | `unread` | The team's messages the visitor has not seen |
74
+ | `error` | `null`, `{ code: "offline" }` after repeated failed readings, or `{ code: "not_found" }` |
75
+
76
+ A failed message's `error` is `busy` (the chat takes no new visitors today), `rate_limited` (too many messages; wait
77
+ a little), `invalid_message` (empty or longer than 2 000 characters) or `failed`.
78
+
79
+ Draw `messages` and then `outgoing`. A message leaves `outgoing` and appears in `messages` once it is stored.
80
+
81
+ ## What it does not do
82
+
83
+ - Answers arrive whole, not streamed.
84
+ - Text only: no files, no formatting.
85
+ - One chat per visitor and browser. The visitor is anonymous; there is no sign-in.
86
+ - The chat's name, greeting and colours set in Omniscore belong to the widget. Your interface has its own.
87
+
88
+ ## Development
89
+
90
+ ```sh
91
+ npm install
92
+ npm run check # types, tests, build
93
+ ```
94
+
95
+ `dist/omni-chat.js` is the script build that Omniscore serves at `/web_chat/sdk.js`.
96
+
97
+ ## Releasing
98
+
99
+ Set `version` in `package.json`, finish the release, and push its tag (`0.2.0` or `v0.2.0`). The `Release` workflow
100
+ checks that the tag is the package's version, runs the checks and publishes to npm through trusted publishing, so no
101
+ token is stored.
102
+
103
+ ## Licence
104
+
105
+ Apache-2.0
@@ -0,0 +1,4 @@
1
+ import type { Chat, ChatOptions } from "./index.js";
2
+ export declare function createChat(options: Omit<ChatOptions, "url"> & {
3
+ url?: string;
4
+ }): Chat;
@@ -0,0 +1,74 @@
1
+ export type ChatStatus = "idle" | "opening" | "open" | "closed" | "destroyed";
2
+ export interface ChatMessage {
3
+ id: number;
4
+ from: "visitor" | "team";
5
+ text: string;
6
+ /** When it was written, ISO 8601. */
7
+ at: string;
8
+ /** The id `send` returned, on the visitor's own message. */
9
+ clientId: string | null;
10
+ }
11
+ export type OutgoingError = "busy" | "rate_limited" | "invalid_message" | "failed";
12
+ /** A message this page wrote that the server has not stored yet. */
13
+ export interface OutgoingMessage {
14
+ clientId: string;
15
+ text: string;
16
+ status: "sending" | "failed";
17
+ error: OutgoingError | null;
18
+ }
19
+ export interface ChatState {
20
+ status: ChatStatus;
21
+ /** What the visitor and the team wrote, oldest first. */
22
+ messages: ChatMessage[];
23
+ outgoing: OutgoingMessage[];
24
+ /** An answer is being written. */
25
+ answering: boolean;
26
+ /** The team's messages the visitor has not seen. */
27
+ unread: number;
28
+ /** `offline` after repeated failed readings, `not_found` once the chat is gone. */
29
+ error: {
30
+ code: "offline" | "not_found";
31
+ } | null;
32
+ }
33
+ /** Where the visitor's token and the last message they saw are kept between pages. */
34
+ export interface ChatStorage {
35
+ read(): {
36
+ token?: string | null;
37
+ seen?: number | null;
38
+ } | null | undefined;
39
+ write(patch: {
40
+ token?: string;
41
+ seen?: number;
42
+ }): void;
43
+ }
44
+ export interface ChatOptions {
45
+ /** The chat's key, from its page in Omniscore. */
46
+ key: string;
47
+ /** Omniscore's address, e.g. `https://app.example`. Empty for the page's own origin. */
48
+ url: string;
49
+ /** Whether the chat is on screen from the start (default true). */
50
+ visible?: boolean;
51
+ /** The address sent with a message; by default the page's address without its query. */
52
+ page?: string | null | (() => string | null);
53
+ /** By default the page's `localStorage`, under `omni-chat:<key>`. */
54
+ storage?: ChatStorage;
55
+ fetch?: typeof fetch;
56
+ }
57
+ export interface Chat {
58
+ getState(): ChatState;
59
+ /** Calls `listener` on every change; returns the function that ends it. */
60
+ subscribe(listener: (state: ChatState) => void): () => void;
61
+ /** Takes the visitor's token (a new one for a new visitor), reads the chat so far and keeps reading. */
62
+ open(): Promise<ChatState>;
63
+ /** Writes the visitor's message. Returns its client id, or null for empty text or a chat that is over. */
64
+ send(text: string): string | null;
65
+ /** A failed message once more, under the same client id. */
66
+ retry(clientId: string): void;
67
+ /** The visitor has seen everything so far. */
68
+ read(): void;
69
+ /** Whether the chat is on screen: read every few seconds then, three times a minute otherwise. */
70
+ setVisible(visible: boolean): void;
71
+ /** Stops reading and drops the listeners. */
72
+ destroy(): void;
73
+ }
74
+ export declare function createChat(options: ChatOptions): Chat;
package/dist/index.js ADDED
@@ -0,0 +1,234 @@
1
+ // src/index.ts
2
+ function localStore(key) {
3
+ const name = "omni-chat:" + key;
4
+ const read = () => {
5
+ try {
6
+ return JSON.parse(globalThis.localStorage.getItem(name) || "{}") || {};
7
+ } catch {
8
+ return {};
9
+ }
10
+ };
11
+ return {
12
+ read,
13
+ write(patch) {
14
+ try {
15
+ globalThis.localStorage.setItem(name, JSON.stringify({ ...read(), ...patch }));
16
+ } catch {
17
+ }
18
+ }
19
+ };
20
+ }
21
+ function createChat(options) {
22
+ const key = options && options.key;
23
+ if (typeof key !== "string" || !/^[A-Za-z0-9_-]+$/.test(key)) throw new Error("OmniChat: `key` is the chat's key");
24
+ const base = String(options.url == null ? "" : options.url).replace(/\/+$/, "") + "/web_chat/" + key;
25
+ const storage = options.storage || localStore(key);
26
+ const doFetch = options.fetch || ((input, init) => globalThis.fetch(input, init));
27
+ let state = { status: "idle", messages: [], outgoing: [], answering: false, unread: 0, error: null };
28
+ let listeners = [];
29
+ let token = null;
30
+ let seen = 0;
31
+ let last = 0;
32
+ const known = /* @__PURE__ */ new Set();
33
+ let loaded = false;
34
+ let started = false;
35
+ let visible = options.visible !== false;
36
+ let opening = null;
37
+ let timer;
38
+ let fails = 0;
39
+ let hiddenAt = 0;
40
+ const set = (patch) => {
41
+ state = { ...state, ...patch };
42
+ listeners.slice().forEach((listener) => listener(state));
43
+ };
44
+ const over = () => state.status === "closed" || state.status === "destroyed";
45
+ const destroyed = () => state.status === "destroyed";
46
+ const load = () => {
47
+ if (loaded) return;
48
+ loaded = true;
49
+ const saved = storage.read() || {};
50
+ token = typeof saved.token === "string" ? saved.token : null;
51
+ seen = Number(saved.seen) || 0;
52
+ };
53
+ const unread = (messages) => messages.filter((message) => message.from === "team" && message.id > seen).length;
54
+ const add = (rows) => {
55
+ const fresh = (rows || []).filter((row) => row && !known.has(row.id));
56
+ if (!fresh.length) return;
57
+ const settled = /* @__PURE__ */ new Set();
58
+ fresh.forEach((row) => {
59
+ known.add(row.id);
60
+ if (row.id > last) last = row.id;
61
+ if (row.client_id) settled.add(row.client_id);
62
+ });
63
+ const messages = state.messages.concat(fresh.map((row) => ({ id: row.id, from: row.from, text: row.text, at: row.at, clientId: row.client_id || null }))).sort((a, b) => a.id - b.id);
64
+ set({
65
+ messages,
66
+ outgoing: state.outgoing.filter((item) => !settled.has(item.clientId)),
67
+ unread: unread(messages),
68
+ answering: fresh.some((row) => row.from === "team") ? false : state.answering
69
+ });
70
+ };
71
+ const request = (method, path, body) => {
72
+ const headers = { Accept: "application/json" };
73
+ if (token) headers["Authorization"] = "Bearer " + token;
74
+ if (body) headers["Content-Type"] = "application/json";
75
+ return doFetch(base + path, { method, headers, body: body ? JSON.stringify(body) : void 0, credentials: "omit", cache: "no-store" }).then(
76
+ (response) => response.json().catch(() => ({})).then((data) => ({ status: response.status, data: data || {} }))
77
+ );
78
+ };
79
+ const close = () => {
80
+ clearTimeout(timer);
81
+ set({ status: "closed", answering: false, error: { code: "not_found" } });
82
+ };
83
+ const session = () => {
84
+ if (opening) return opening;
85
+ if (state.status === "idle") set({ status: "opening" });
86
+ const asked = request("POST", "/session").then((result) => {
87
+ if (destroyed()) return;
88
+ if (result.status === 404) close();
89
+ if (!result.data.token) throw new Error(result.status === 429 ? "slow" : "refused");
90
+ if (result.data.token !== token) {
91
+ token = result.data.token;
92
+ storage.write({ token });
93
+ }
94
+ fails = 0;
95
+ set({ status: "open", error: null });
96
+ add(result.data.messages);
97
+ });
98
+ opening = asked;
99
+ const done = () => {
100
+ opening = null;
101
+ };
102
+ asked.then(done, done);
103
+ return asked;
104
+ };
105
+ const failed = (error) => {
106
+ if (over()) return;
107
+ fails += error instanceof Error && error.message === "slow" ? 3 : 1;
108
+ if (fails > 2) set({ error: { code: "offline" } });
109
+ };
110
+ const hidden = () => typeof document !== "undefined" && document.hidden;
111
+ const schedule = () => {
112
+ clearTimeout(timer);
113
+ if (over() || !started) return;
114
+ const wait = visible ? state.answering ? 1500 : 3e3 : 2e4;
115
+ timer = setTimeout(poll, Math.min(wait * Math.pow(2, Math.min(fails, 4)), 6e4));
116
+ };
117
+ const poll = () => {
118
+ if (over() || !started) return;
119
+ if (hidden()) return schedule();
120
+ const asked = token ? request("GET", "/messages?after=" + last).then((result) => {
121
+ if (result.status === 401) {
122
+ token = null;
123
+ return session();
124
+ }
125
+ if (result.status === 404) return close();
126
+ if (result.status !== 200) throw new Error(result.status === 429 ? "slow" : "refused");
127
+ fails = 0;
128
+ add(result.data.messages);
129
+ const answering = result.data.typing === true;
130
+ if (answering !== state.answering || state.error) set({ answering, error: null });
131
+ }) : session();
132
+ asked.catch(failed).then(schedule);
133
+ };
134
+ const clientId = () => {
135
+ const bytes = new Uint8Array(12);
136
+ globalThis.crypto.getRandomValues(bytes);
137
+ return Array.from(bytes, (byte) => ("0" + byte.toString(16)).slice(-2)).join("");
138
+ };
139
+ const page = () => {
140
+ let value = typeof options.page === "function" ? options.page() : options.page;
141
+ if (value == null && typeof location !== "undefined") value = location.origin + location.pathname;
142
+ return typeof value === "string" ? value.slice(0, 500) : null;
143
+ };
144
+ const mark = (id, patch) => {
145
+ set({ outgoing: state.outgoing.map((item) => item.clientId === id ? { ...item, ...patch } : item) });
146
+ };
147
+ const deliver = (id, text) => {
148
+ (token ? Promise.resolve() : session()).then(() => {
149
+ if (destroyed()) throw new Error("destroyed");
150
+ return request("POST", "/messages", { text, client_id: id, page: page() });
151
+ }).then((result) => {
152
+ if (result.status === 201 && result.data.message) {
153
+ add([result.data.message]);
154
+ return poll();
155
+ }
156
+ if (result.status === 404) close();
157
+ throw new Error(result.status === 503 ? "busy" : result.status === 429 ? "rate_limited" : result.status === 422 ? "invalid_message" : "failed");
158
+ }).catch((error) => {
159
+ if (!state.outgoing.some((item) => item.clientId === id)) return;
160
+ const code = error instanceof Error && /^(busy|rate_limited|invalid_message)$/.test(error.message) ? error.message : "failed";
161
+ mark(id, { status: "failed", error: code });
162
+ });
163
+ };
164
+ const onVisibility = () => {
165
+ if (!started || over()) return;
166
+ if (document.hidden) {
167
+ hiddenAt = Date.now();
168
+ return;
169
+ }
170
+ if (token && Date.now() - hiddenAt > 9e4) session().catch(failed).then(schedule);
171
+ else poll();
172
+ };
173
+ if (typeof document !== "undefined") document.addEventListener("visibilitychange", onVisibility);
174
+ return {
175
+ getState: () => state,
176
+ subscribe(listener) {
177
+ listeners.push(listener);
178
+ return () => {
179
+ listeners = listeners.filter((other) => other !== listener);
180
+ };
181
+ },
182
+ open() {
183
+ if (over()) return Promise.resolve(state);
184
+ load();
185
+ started = true;
186
+ const ready = state.status === "open" ? Promise.resolve() : session().catch((error) => {
187
+ if (!over()) set({ error: { code: "offline" } });
188
+ failed(error);
189
+ });
190
+ return ready.then(() => {
191
+ schedule();
192
+ return state;
193
+ });
194
+ },
195
+ send(text) {
196
+ const body = String(text == null ? "" : text).trim();
197
+ if (!body || over()) return null;
198
+ load();
199
+ started = true;
200
+ const id = clientId();
201
+ set({ outgoing: state.outgoing.concat([{ clientId: id, text: body, status: "sending", error: null }]) });
202
+ deliver(id, body);
203
+ schedule();
204
+ return id;
205
+ },
206
+ retry(id) {
207
+ const item = state.outgoing.find((other) => other.clientId === id && other.status === "failed");
208
+ if (!item || over()) return;
209
+ mark(id, { status: "sending", error: null });
210
+ deliver(id, item.text);
211
+ },
212
+ read() {
213
+ if (last > seen) {
214
+ seen = last;
215
+ storage.write({ seen });
216
+ }
217
+ if (state.unread) set({ unread: 0 });
218
+ },
219
+ setVisible(value) {
220
+ visible = !!value;
221
+ schedule();
222
+ },
223
+ destroy() {
224
+ clearTimeout(timer);
225
+ if (typeof document !== "undefined") document.removeEventListener("visibilitychange", onVisibility);
226
+ set({ status: "destroyed", answering: false });
227
+ listeners = [];
228
+ }
229
+ };
230
+ }
231
+ export {
232
+ createChat
233
+ };
234
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1,7 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../src/index.ts"],
4
+ "sourcesContent": ["// Omniscore website chat's client: the visitor's token, sending, reading, and the chat as a state a page draws.\n// It draws nothing itself.\n\nexport type ChatStatus = \"idle\" | \"opening\" | \"open\" | \"closed\" | \"destroyed\";\n\nexport interface ChatMessage {\n id: number;\n from: \"visitor\" | \"team\";\n text: string;\n /** When it was written, ISO 8601. */\n at: string;\n /** The id `send` returned, on the visitor's own message. */\n clientId: string | null;\n}\n\nexport type OutgoingError = \"busy\" | \"rate_limited\" | \"invalid_message\" | \"failed\";\n\n/** A message this page wrote that the server has not stored yet. */\nexport interface OutgoingMessage {\n clientId: string;\n text: string;\n status: \"sending\" | \"failed\";\n error: OutgoingError | null;\n}\n\nexport interface ChatState {\n status: ChatStatus;\n /** What the visitor and the team wrote, oldest first. */\n messages: ChatMessage[];\n outgoing: OutgoingMessage[];\n /** An answer is being written. */\n answering: boolean;\n /** The team's messages the visitor has not seen. */\n unread: number;\n /** `offline` after repeated failed readings, `not_found` once the chat is gone. */\n error: { code: \"offline\" | \"not_found\" } | null;\n}\n\n/** Where the visitor's token and the last message they saw are kept between pages. */\nexport interface ChatStorage {\n read(): { token?: string | null; seen?: number | null } | null | undefined;\n write(patch: { token?: string; seen?: number }): void;\n}\n\nexport interface ChatOptions {\n /** The chat's key, from its page in Omniscore. */\n key: string;\n /** Omniscore's address, e.g. `https://app.example`. Empty for the page's own origin. */\n url: string;\n /** Whether the chat is on screen from the start (default true). */\n visible?: boolean;\n /** The address sent with a message; by default the page's address without its query. */\n page?: string | null | (() => string | null);\n /** By default the page's `localStorage`, under `omni-chat:<key>`. */\n storage?: ChatStorage;\n fetch?: typeof fetch;\n}\n\nexport interface Chat {\n getState(): ChatState;\n /** Calls `listener` on every change; returns the function that ends it. */\n subscribe(listener: (state: ChatState) => void): () => void;\n /** Takes the visitor's token (a new one for a new visitor), reads the chat so far and keeps reading. */\n open(): Promise<ChatState>;\n /** Writes the visitor's message. Returns its client id, or null for empty text or a chat that is over. */\n send(text: string): string | null;\n /** A failed message once more, under the same client id. */\n retry(clientId: string): void;\n /** The visitor has seen everything so far. */\n read(): void;\n /** Whether the chat is on screen: read every few seconds then, three times a minute otherwise. */\n setVisible(visible: boolean): void;\n /** Stops reading and drops the listeners. */\n destroy(): void;\n}\n\ninterface Row {\n id: number;\n from: \"visitor\" | \"team\";\n text: string;\n at: string;\n client_id?: string;\n}\n\ninterface Answer {\n status: number;\n data: { token?: string; messages?: Row[]; message?: Row; typing?: boolean };\n}\n\nfunction localStore(key: string): ChatStorage {\n const name = \"omni-chat:\" + key;\n const read = () => {\n try {\n return JSON.parse(globalThis.localStorage.getItem(name) || \"{}\") || {};\n } catch {\n return {};\n }\n };\n return {\n read,\n write(patch) {\n try {\n globalThis.localStorage.setItem(name, JSON.stringify({ ...read(), ...patch }));\n } catch {\n // A browser without storage keeps the chat for this page only.\n }\n },\n };\n}\n\nexport function createChat(options: ChatOptions): Chat {\n const key = options && options.key;\n if (typeof key !== \"string\" || !/^[A-Za-z0-9_-]+$/.test(key)) throw new Error(\"OmniChat: `key` is the chat's key\");\n const base = String(options.url == null ? \"\" : options.url).replace(/\\/+$/, \"\") + \"/web_chat/\" + key;\n const storage = options.storage || localStore(key);\n const doFetch: typeof fetch = options.fetch || ((input, init) => globalThis.fetch(input, init));\n\n let state: ChatState = { status: \"idle\", messages: [], outgoing: [], answering: false, unread: 0, error: null };\n let listeners: Array<(state: ChatState) => void> = [];\n let token: string | null = null;\n let seen = 0; // the last message id the visitor has had on screen\n let last = 0; // the last message id we hold\n const known = new Set<number>();\n let loaded = false;\n let started = false;\n let visible = options.visible !== false;\n let opening: Promise<void> | null = null; // the one request for a token in flight\n let timer: ReturnType<typeof setTimeout> | undefined;\n let fails = 0;\n let hiddenAt = 0;\n\n const set = (patch: Partial<ChatState>) => {\n state = { ...state, ...patch };\n listeners.slice().forEach((listener) => listener(state));\n };\n\n const over = () => state.status === \"closed\" || state.status === \"destroyed\";\n const destroyed = () => state.status === \"destroyed\";\n\n const load = () => {\n if (loaded) return;\n loaded = true;\n const saved = storage.read() || {};\n token = typeof saved.token === \"string\" ? saved.token : null;\n seen = Number(saved.seen) || 0;\n };\n\n const unread = (messages: ChatMessage[]) => messages.filter((message) => message.from === \"team\" && message.id > seen).length;\n\n const add = (rows: Row[] | undefined) => {\n const fresh = (rows || []).filter((row) => row && !known.has(row.id));\n if (!fresh.length) return;\n const settled = new Set<string>();\n fresh.forEach((row) => {\n known.add(row.id);\n if (row.id > last) last = row.id;\n if (row.client_id) settled.add(row.client_id);\n });\n const messages = state.messages\n .concat(fresh.map((row) => ({ id: row.id, from: row.from, text: row.text, at: row.at, clientId: row.client_id || null })))\n .sort((a, b) => a.id - b.id);\n set({\n messages,\n outgoing: state.outgoing.filter((item) => !settled.has(item.clientId)),\n unread: unread(messages),\n answering: fresh.some((row) => row.from === \"team\") ? false : state.answering,\n });\n };\n\n const request = (method: string, path: string, body?: unknown): Promise<Answer> => {\n const headers: Record<string, string> = { Accept: \"application/json\" };\n if (token) headers[\"Authorization\"] = \"Bearer \" + token;\n if (body) headers[\"Content-Type\"] = \"application/json\";\n return doFetch(base + path, { method, headers, body: body ? JSON.stringify(body) : undefined, credentials: \"omit\", cache: \"no-store\" }).then(\n (response) =>\n response\n .json()\n .catch(() => ({}))\n .then((data) => ({ status: response.status, data: data || {} })),\n );\n };\n\n const close = () => {\n clearTimeout(timer);\n set({ status: \"closed\", answering: false, error: { code: \"not_found\" } });\n };\n\n // One request at a time: two answers in the wrong order would leave the page on a token it did not write with.\n const session = (): Promise<void> => {\n if (opening) return opening;\n if (state.status === \"idle\") set({ status: \"opening\" });\n const asked = request(\"POST\", \"/session\").then((result) => {\n if (destroyed()) return;\n if (result.status === 404) close();\n if (!result.data.token) throw new Error(result.status === 429 ? \"slow\" : \"refused\");\n if (result.data.token !== token) {\n token = result.data.token;\n storage.write({ token });\n }\n fails = 0;\n set({ status: \"open\", error: null });\n add(result.data.messages);\n });\n opening = asked;\n const done = () => {\n opening = null;\n };\n asked.then(done, done);\n return asked;\n };\n\n const failed = (error: unknown) => {\n if (over()) return;\n fails += error instanceof Error && error.message === \"slow\" ? 3 : 1;\n if (fails > 2) set({ error: { code: \"offline\" } });\n };\n\n const hidden = () => typeof document !== \"undefined\" && document.hidden;\n\n const schedule = () => {\n clearTimeout(timer);\n if (over() || !started) return;\n const wait = visible ? (state.answering ? 1500 : 3000) : 20000;\n timer = setTimeout(poll, Math.min(wait * Math.pow(2, Math.min(fails, 4)), 60000));\n };\n\n const poll = (): void => {\n if (over() || !started) return;\n if (hidden()) return schedule();\n const asked: Promise<void> = token\n ? request(\"GET\", \"/messages?after=\" + last).then((result) => {\n if (result.status === 401) {\n token = null;\n return session();\n }\n if (result.status === 404) return close();\n if (result.status !== 200) throw new Error(result.status === 429 ? \"slow\" : \"refused\");\n fails = 0;\n add(result.data.messages);\n const answering = result.data.typing === true;\n if (answering !== state.answering || state.error) set({ answering, error: null });\n })\n : session();\n asked.catch(failed).then(schedule);\n };\n\n const clientId = () => {\n const bytes = new Uint8Array(12);\n globalThis.crypto.getRandomValues(bytes);\n return Array.from(bytes, (byte) => (\"0\" + byte.toString(16)).slice(-2)).join(\"\");\n };\n\n const page = () => {\n let value = typeof options.page === \"function\" ? options.page() : options.page;\n if (value == null && typeof location !== \"undefined\") value = location.origin + location.pathname;\n return typeof value === \"string\" ? value.slice(0, 500) : null;\n };\n\n const mark = (id: string, patch: Partial<OutgoingMessage>) => {\n set({ outgoing: state.outgoing.map((item) => (item.clientId === id ? { ...item, ...patch } : item)) });\n };\n\n const deliver = (id: string, text: string) => {\n (token ? Promise.resolve() : session())\n .then(() => {\n if (destroyed()) throw new Error(\"destroyed\");\n return request(\"POST\", \"/messages\", { text, client_id: id, page: page() });\n })\n .then((result) => {\n if (result.status === 201 && result.data.message) {\n add([result.data.message]);\n return poll();\n }\n if (result.status === 404) close();\n throw new Error(result.status === 503 ? \"busy\" : result.status === 429 ? \"rate_limited\" : result.status === 422 ? \"invalid_message\" : \"failed\");\n })\n .catch((error: unknown) => {\n // A reading may have brought the message meanwhile: then it went, whatever this request's answer was.\n if (!state.outgoing.some((item) => item.clientId === id)) return;\n const code = error instanceof Error && /^(busy|rate_limited|invalid_message)$/.test(error.message) ? (error.message as OutgoingError) : \"failed\";\n mark(id, { status: \"failed\", error: code });\n });\n };\n\n const onVisibility = () => {\n if (!started || over()) return;\n if (document.hidden) {\n hiddenAt = Date.now();\n return;\n }\n // The `after` reading covers answers sent in the last two minutes; a page that slept longer reads the whole chat.\n if (token && Date.now() - hiddenAt > 90000) session().catch(failed).then(schedule);\n else poll();\n };\n if (typeof document !== \"undefined\") document.addEventListener(\"visibilitychange\", onVisibility);\n\n return {\n getState: () => state,\n\n subscribe(listener) {\n listeners.push(listener);\n return () => {\n listeners = listeners.filter((other) => other !== listener);\n };\n },\n\n open() {\n if (over()) return Promise.resolve(state);\n load();\n started = true;\n const ready =\n state.status === \"open\"\n ? Promise.resolve()\n : session().catch((error: unknown) => {\n if (!over()) set({ error: { code: \"offline\" } });\n failed(error);\n });\n return ready.then(() => {\n schedule();\n return state;\n });\n },\n\n send(text) {\n const body = String(text == null ? \"\" : text).trim();\n if (!body || over()) return null;\n load();\n started = true;\n const id = clientId();\n set({ outgoing: state.outgoing.concat([{ clientId: id, text: body, status: \"sending\", error: null }]) });\n deliver(id, body);\n schedule();\n return id;\n },\n\n retry(id) {\n const item = state.outgoing.find((other) => other.clientId === id && other.status === \"failed\");\n if (!item || over()) return;\n mark(id, { status: \"sending\", error: null });\n deliver(id, item.text);\n },\n\n read() {\n if (last > seen) {\n seen = last;\n storage.write({ seen });\n }\n if (state.unread) set({ unread: 0 });\n },\n\n setVisible(value) {\n visible = !!value;\n schedule();\n },\n\n destroy() {\n clearTimeout(timer);\n if (typeof document !== \"undefined\") document.removeEventListener(\"visibilitychange\", onVisibility);\n set({ status: \"destroyed\", answering: false });\n listeners = [];\n },\n };\n}\n"],
5
+ "mappings": ";AAyFA,SAAS,WAAW,KAA0B;AAC5C,QAAM,OAAO,eAAe;AAC5B,QAAM,OAAO,MAAM;AACjB,QAAI;AACF,aAAO,KAAK,MAAM,WAAW,aAAa,QAAQ,IAAI,KAAK,IAAI,KAAK,CAAC;AAAA,IACvE,QAAQ;AACN,aAAO,CAAC;AAAA,IACV;AAAA,EACF;AACA,SAAO;AAAA,IACL;AAAA,IACA,MAAM,OAAO;AACX,UAAI;AACF,mBAAW,aAAa,QAAQ,MAAM,KAAK,UAAU,EAAE,GAAG,KAAK,GAAG,GAAG,MAAM,CAAC,CAAC;AAAA,MAC/E,QAAQ;AAAA,MAER;AAAA,IACF;AAAA,EACF;AACF;AAEO,SAAS,WAAW,SAA4B;AACrD,QAAM,MAAM,WAAW,QAAQ;AAC/B,MAAI,OAAO,QAAQ,YAAY,CAAC,mBA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xB;AACA,UAAI,MAAM,OAAQ,KAAI,EAAE,QAAQ,EAAE,CAAC;AAAA,IACrC;AAAA,IAEA,WAAW,OAAO;AAChB,gBAAU,CAAC,CAAC;AACZ,eAAS;AAAA,IACX;AAAA,IAEA,UAAU;AACR,mBAAa,KAAK;AAClB,UAAI,OAAO,aAAa,YAAa,UAAS,oBAAoB,oBAAoB,YAAY;AAClG,UAAI,EAAE,QAAQ,aAAa,WAAW,MAAM,CAAC;AAC7C,kBAAY,CAAC;AAAA,IACf;AAAA,EACF;AACF;",
6
+ "names": []
7
+ }
@@ -0,0 +1 @@
1
+ "use strict";var OmniChat=(()=>{var I=Object.defineProperty;var F=Object.getOwnPropertyDescriptor;var G=Object.getOwnPropertyNames;var H=Object.prototype.hasOwnProperty;var Z=(s,a)=>{for(var d in a)I(s,d,{get:a[d],enumerable:!0})},K=(s,a,d,u)=>{if(a&&typeof a=="object"||typeof a=="function")for(let f of G(a))!H.call(s,f)&&f!==d&&I(s,f,{get:()=>a[f],enumerable:!(u=F(a,f))||u.enumerable});return s};var Q=s=>K(I({},"__esModule",{value:!0}),s);var ee={};Z(ee,{createChat:()=>Y});function W(s){let a="omni-chat:"+s,d=()=>{try{return JSON.parse(globalThis.localStorage.getItem(a)||"{}")||{}}catch{return{}}};return{read:d,write(u){try{globalThis.localStorage.setItem(a,JSON.stringify({...d(),...u}))}catch{}}}}function z(s){let a=s&&s.key;if(typeof a!="string"||!/^[A-Za-z0-9_-]+$/.test(a))throw new Error("OmniChat: `key` is the chat's key");let d=String(s.url==null?"":s.url).replace(/\/+$/,"")+"/web_chat/"+a,u=s.storage||W(a),f=s.fetch||((e,t)=>globalThis.fetch(e,t)),i={status:"idle",messages:[],outgoing:[],answering:!1,unread:0,error:null},m=[],l=null,p=0,y=0,M=new Set,A=!1,w=!1,R=s.visible!==!1,S=null,C,b=0,j=0,o=e=>{i={...i,...e},m.slice().forEach(t=>t(i))},c=()=>i.status==="closed"||i.status==="destroyed",L=()=>i.status==="destroyed",N=()=>{if(A)return;A=!0;let e=u.read()||{};l=typeof e.token=="string"?e.token:null,p=Number(e.seen)||0},D=e=>e.filter(t=>t.from==="team"&&t.id>p).length,k=e=>{let t=(e||[]).filter(r=>r&&!M.has(r.id));if(!t.length)return;let n=new Set;t.forEach(r=>{M.add(r.id),r.id>y&&(y=r.id),r.client_id&&n.add(r.client_id)});let g=i.messages.concat(t.map(r=>({id:r.id,from:r.from,text:r.text,at:r.at,clientId:r.client_id||null}))).sort((r,_)=>r.id-_.id);o({messages:g,outgoing:i.outgoing.filter(r=>!n.has(r.clientId)),unread:D(g),answering:t.some(r=>r.from==="team")?!1:i.answering})},x=(e,t,n)=>{let g={Accept:"application/json"};return l&&(g.Authorization="Bearer "+l),n&&(g["Content-Type"]="application/json"),f(d+t,{method:e,headers:g,body:n?JSON.stringify(n):void 0,credentials:"omit",cache:"no-store"}).then(r=>r.json().catch(()=>({})).then(_=>({status:r.status,data:_||{}})))},O=()=>{clearTimeout(C),o({status:"closed",answering:!1,error:{code:"not_found"}})},v=()=>{if(S)return S;i.status==="idle"&&o({status:"opening"});let e=x("POST","/session").then(n=>{if(!L()){if(n.status===404&&O(),!n.data.token)throw new Error(n.status===429?"slow":"refused");n.data.token!==l&&(l=n.data.token,u.write({token:l})),b=0,o({status:"open",error:null}),k(n.data.messages)}});S=e;let t=()=>{S=null};return e.then(t,t),e},E=e=>{c()||(b+=e instanceof Error&&e.message==="slow"?3:1,b>2&&o({error:{code:"offline"}}))},U=()=>typeof document!="undefined"&&document.hidden,h=()=>{if(clearTimeout(C),c()||!w)return;let e=R?i.answering?1500:3e3:2e4;C=setTimeout(T,Math.min(e*Math.pow(2,Math.min(b,4)),6e4))},T=()=>{if(c()||!w)return;if(U())return h();(l?x("GET","/messages?after="+y).then(t=>{if(t.status===401)return l=null,v();if(t.status===404)return O();if(t.status!==200)throw new Error(t.status===429?"slow":"refused");b=0,k(t.data.messages);let n=t.data.typing===!0;(n!==i.answering||i.error)&&o({answering:n,error:null})}):v()).catch(E).then(h)},q=()=>{let e=new Uint8Array(12);return globalThis.crypto.getRandomValues(e),Array.from(e,t=>("0"+t.toString(16)).slice(-2)).join("")},B=()=>{let e=typeof s.page=="function"?s.page():s.page;return e==null&&typeof location!="undefined"&&(e=location.origin+location.pathname),typeof e=="string"?e.slice(0,500):null},V=(e,t)=>{o({outgoing:i.outgoing.map(n=>n.clientId===e?{...n,...t}:n)})},J=(e,t)=>{(l?Promise.resolve():v()).then(()=>{if(L())throw new Error("destroyed");return x("POST","/messages",{text:t,client_id:e,page:B()})}).then(n=>{if(n.status===201&&n.data.message)return k([n.data.message]),T();throw n.status===404&&O(),new Error(n.status===503?"busy":n.status===429?"rate_limited":n.status===422?"invalid_message":"failed")}).catch(n=>{if(!i.outgoing.some(r=>r.clientId===e))return;let g=n instanceof Error&&/^(busy|rate_limited|invalid_message)$/.test(n.message)?n.message:"failed";V(e,{status:"failed",error:g})})},$=()=>{if(!(!w||c())){if(document.hidden){j=Date.now();return}l&&Date.now()-j>9e4?v().catch(E).then(h):T()}};return typeof document!="undefined"&&document.addEventListener("visibilitychange",$),{getState:()=>i,subscribe(e){return m.push(e),()=>{m=m.filter(t=>t!==e)}},open(){return c()?Promise.resolve(i):(N(),w=!0,(i.status==="open"?Promise.resolve():v().catch(t=>{c()||o({error:{code:"offline"}}),E(t)})).then(()=>(h(),i)))},send(e){let t=String(e==null?"":e).trim();if(!t||c())return null;N(),w=!0;let n=q();return o({outgoing:i.outgoing.concat([{clientId:n,text:t,status:"sending",error:null}])}),J(n,t),h(),n},retry(e){let t=i.outgoing.find(n=>n.clientId===e&&n.status==="failed");!t||c()||(V(e,{status:"sending",error:null}),J(e,t.text))},read(){y>p&&(p=y,u.write({seen:p})),i.unread&&o({unread:0})},setVisible(e){R=!!e,h()},destroy(){clearTimeout(C),typeof document!="undefined"&&document.removeEventListener("visibilitychange",$),o({status:"destroyed",answering:!1}),m=[]}}}var P=typeof document!="undefined"?document.currentScript:null,X=P&&P.src?new URL(P.src).origin:"";function Y(s){return z({...s,url:s&&s.url!=null?s.url:X})}return Q(ee);})();
package/package.json CHANGED
@@ -1,6 +1,49 @@
1
1
  {
2
2
  "name": "@omniscore/chat-sdk",
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": "Omniscore website chat's JavaScript client: the visitor's token, their messages and the answers, as a state your page draws.",
5
+ "license": "Apache-2.0",
6
+ "repository": {
7
+ "type": "git",
8
+ "url": "git+https://github.com/42-production/omni-chat-sdk.git"
9
+ },
10
+ "keywords": [
11
+ "omniscore",
12
+ "chat",
13
+ "widget"
14
+ ],
15
+ "type": "module",
16
+ "exports": {
17
+ ".": {
18
+ "types": "./dist/index.d.ts",
19
+ "default": "./dist/index.js"
20
+ },
21
+ "./package.json": "./package.json"
22
+ },
23
+ "module": "./dist/index.js",
24
+ "types": "./dist/index.d.ts",
25
+ "unpkg": "./dist/omni-chat.js",
26
+ "jsdelivr": "./dist/omni-chat.js",
27
+ "files": [
28
+ "dist"
29
+ ],
30
+ "sideEffects": [
31
+ "./dist/omni-chat.js"
32
+ ],
33
+ "scripts": {
34
+ "build": "node build.mjs",
35
+ "typecheck": "tsc --noEmit && tsc -p tsconfig.test.json",
36
+ "test": "vitest run",
37
+ "check": "npm run typecheck && npm test && npm run build",
38
+ "prepack": "npm run check"
39
+ },
40
+ "publishConfig": {
41
+ "access": "public"
42
+ },
43
+ "devDependencies": {
44
+ "@types/node": "26.6.6",
45
+ "esbuild": "0.28.2",
46
+ "typescript": "7.0.2",
47
+ "vitest": "5.1.0"
48
+ }
49
+ }