bitsnap-react 1.18.0 → 1.19.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/AGENTS.md +106 -0
- package/README.md +98 -0
- package/dist/BitsnapCart-E72W5RRZ.mjs +2 -0
- package/dist/BitsnapCart-LHJ6KOTV.css +2 -0
- package/dist/BitsnapCart-LHJ6KOTV.css.map +1 -0
- package/dist/BitsnapCart-Q2HER6GU.js +2 -0
- package/dist/BitsnapCart-Q2HER6GU.js.map +1 -0
- package/dist/CartProvider-677CE2FI.js +2 -0
- package/dist/CartProvider-677CE2FI.js.map +1 -0
- package/dist/CartProvider-YPDOFSYC.mjs +2 -0
- package/dist/{PanelModelFiles-JZFSF7BF.mjs → PanelModelFiles-4B2HYGIE.mjs} +2 -2
- package/dist/{PanelModelFiles-7HPXWONN.js → PanelModelFiles-EKQRLF46.js} +2 -2
- package/dist/PanelModelFiles-EKQRLF46.js.map +1 -0
- package/dist/analytics.js +1 -1
- package/dist/analytics.js.map +1 -1
- package/dist/analytics.mjs +1 -1
- package/dist/catalog.js +1 -1
- package/dist/catalog.js.map +1 -1
- package/dist/catalog.mjs +1 -1
- package/dist/chat.css +2 -0
- package/dist/chat.css.map +1 -0
- package/dist/chat.d.mts +172 -0
- package/dist/chat.d.ts +172 -0
- package/dist/chat.js +2 -0
- package/dist/chat.js.map +1 -0
- package/dist/chat.mjs +2 -0
- package/dist/chat.mjs.map +1 -0
- package/dist/chunk-2FD2QP4Y.js +2 -0
- package/dist/chunk-2FD2QP4Y.js.map +1 -0
- package/dist/chunk-5JRUPLXY.mjs +2 -0
- package/dist/chunk-5JRUPLXY.mjs.map +1 -0
- package/dist/chunk-5M6M7FAR.mjs +2 -0
- package/dist/chunk-5M6M7FAR.mjs.map +1 -0
- package/dist/chunk-6Q3VGPSF.js.map +1 -1
- package/dist/chunk-AAC576BC.mjs +5 -0
- package/dist/chunk-AAC576BC.mjs.map +1 -0
- package/dist/{chunk-4OVOKGGS.mjs → chunk-AB37DWOK.mjs} +2 -2
- package/dist/{chunk-ZATPBYOA.js → chunk-BUYTK7KM.js} +2 -2
- package/dist/chunk-BUYTK7KM.js.map +1 -0
- package/dist/{chunk-DP2NOHCI.js → chunk-D2ASWUXM.js} +2 -2
- package/dist/chunk-D2ASWUXM.js.map +1 -0
- package/dist/chunk-DDIEFKNP.mjs +2 -0
- package/dist/{chunk-ZHTMK5TA.mjs.map → chunk-DDIEFKNP.mjs.map} +1 -1
- package/dist/{chunk-4HGZZJEL.js → chunk-DOJICJCQ.js} +2 -2
- package/dist/chunk-DOJICJCQ.js.map +1 -0
- package/dist/chunk-EMR4YXNY.mjs +2 -0
- package/dist/chunk-EMR4YXNY.mjs.map +1 -0
- package/dist/{chunk-JA62KNAQ.js → chunk-GJOGATP6.js} +2 -2
- package/dist/chunk-GJOGATP6.js.map +1 -0
- package/dist/chunk-GQ5OKU74.js +2 -0
- package/dist/chunk-GQ5OKU74.js.map +1 -0
- package/dist/chunk-JSDGZ4NY.js.map +1 -1
- package/dist/chunk-KHQEDQYF.js +5 -0
- package/dist/chunk-KHQEDQYF.js.map +1 -0
- package/dist/chunk-KOYBZORL.js.map +1 -1
- package/dist/chunk-LGPNJ5XE.js +2 -0
- package/dist/chunk-LGPNJ5XE.js.map +1 -0
- package/dist/chunk-MDAFPGPA.js +2 -0
- package/dist/chunk-MDAFPGPA.js.map +1 -0
- package/dist/{chunk-JHJ3ZZF4.mjs → chunk-MMLBQHBM.mjs} +2 -2
- package/dist/chunk-MWWEPEU2.js +2 -0
- package/dist/chunk-MWWEPEU2.js.map +1 -0
- package/dist/{chunk-GEBRXFT3.mjs → chunk-N523LFAM.mjs} +2 -2
- package/dist/chunk-NWXZ45TV.js +2 -0
- package/dist/chunk-NWXZ45TV.js.map +1 -0
- package/dist/chunk-OFPRIENJ.mjs +2 -0
- package/dist/chunk-OFPRIENJ.mjs.map +1 -0
- package/dist/chunk-OR566YJI.mjs +2 -0
- package/dist/chunk-OR566YJI.mjs.map +1 -0
- package/dist/chunk-Q337IQNA.js +2 -0
- package/dist/chunk-Q337IQNA.js.map +1 -0
- package/dist/chunk-SCEWYZUZ.mjs +2 -0
- package/dist/chunk-SCEWYZUZ.mjs.map +1 -0
- package/dist/{chunk-CF45RDMD.mjs → chunk-SSSF64M7.mjs} +2 -2
- package/dist/{chunk-CF45RDMD.mjs.map → chunk-SSSF64M7.mjs.map} +1 -1
- package/dist/chunk-W3RGQYPD.js.map +1 -1
- package/dist/chunk-WG54EHST.mjs +2 -0
- package/dist/chunk-WG54EHST.mjs.map +1 -0
- package/dist/chunk-XEXPQFKN.mjs +2 -0
- package/dist/chunk-XEXPQFKN.mjs.map +1 -0
- package/dist/chunk-YV2C276H.js +2 -0
- package/dist/chunk-YV2C276H.js.map +1 -0
- package/dist/consent.js.map +1 -1
- package/dist/course.d.mts +2 -14
- package/dist/course.d.ts +2 -14
- package/dist/course.js +1 -1
- package/dist/course.js.map +1 -1
- package/dist/course.mjs +1 -1
- package/dist/course.mjs.map +1 -1
- package/dist/embed/analytics.js +1 -1
- package/dist/errors.js.map +1 -1
- package/dist/index.css +1 -1
- package/dist/index.css.map +1 -1
- package/dist/index.d.mts +288 -4
- package/dist/index.d.ts +288 -4
- package/dist/index.js +1 -1
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +1 -1
- package/dist/index.mjs.map +1 -1
- package/dist/internal.js.map +1 -1
- package/dist/methods-64D5DD6K.js +2 -0
- package/dist/methods-64D5DD6K.js.map +1 -0
- package/dist/methods-NQA3DFLE.mjs +2 -0
- package/dist/methods-NQA3DFLE.mjs.map +1 -0
- package/dist/model-files-client-P4PORZJ6.js.map +1 -1
- package/dist/models.js.map +1 -1
- package/dist/returns.js +1 -1
- package/dist/returns.js.map +1 -1
- package/dist/returns.mjs +1 -1
- package/dist/texts-9kfgClsA.d.mts +14 -0
- package/dist/texts-9kfgClsA.d.ts +14 -0
- package/dist/{types-D6LsoycW.d.mts → types-B-sjyZQs.d.mts} +7 -1
- package/dist/{types-ClFCVzk_.d.ts → types-iRe6ix2y.d.ts} +7 -1
- package/dist/viewer3d.js.map +1 -1
- package/dist/viewer3d.mjs +1 -1
- package/dist/viewer3d.mjs.map +1 -1
- package/dist/widgets-BT2LN2Nq.d.mts +547 -0
- package/dist/widgets-BVOSj9fU.d.ts +547 -0
- package/package.json +18 -3
- package/dist/CartProvider-OEI526IN.js +0 -2
- package/dist/CartProvider-OEI526IN.js.map +0 -1
- package/dist/CartProvider-RYAA3JDA.mjs +0 -2
- package/dist/PanelModelFiles-7HPXWONN.js.map +0 -1
- package/dist/chunk-4HGZZJEL.js.map +0 -1
- package/dist/chunk-5X7TP3TQ.mjs +0 -2
- package/dist/chunk-5X7TP3TQ.mjs.map +0 -1
- package/dist/chunk-7RXW6XFY.js +0 -2
- package/dist/chunk-7RXW6XFY.js.map +0 -1
- package/dist/chunk-DP2NOHCI.js.map +0 -1
- package/dist/chunk-EVIDNS22.mjs +0 -2
- package/dist/chunk-EVIDNS22.mjs.map +0 -1
- package/dist/chunk-G4V2KWTV.js +0 -2
- package/dist/chunk-G4V2KWTV.js.map +0 -1
- package/dist/chunk-GWF3MRUP.js +0 -2
- package/dist/chunk-GWF3MRUP.js.map +0 -1
- package/dist/chunk-JA62KNAQ.js.map +0 -1
- package/dist/chunk-UPAOIY4R.mjs +0 -2
- package/dist/chunk-UPAOIY4R.mjs.map +0 -1
- package/dist/chunk-V5ECGBFW.js +0 -5
- package/dist/chunk-V5ECGBFW.js.map +0 -1
- package/dist/chunk-VNV5BD4X.js +0 -2
- package/dist/chunk-VNV5BD4X.js.map +0 -1
- package/dist/chunk-VNYHJT6V.mjs +0 -2
- package/dist/chunk-VNYHJT6V.mjs.map +0 -1
- package/dist/chunk-WJO5GSY3.mjs +0 -5
- package/dist/chunk-WJO5GSY3.mjs.map +0 -1
- package/dist/chunk-ZATPBYOA.js.map +0 -1
- package/dist/chunk-ZHTMK5TA.mjs +0 -2
- package/dist/methods-AULQDKVS.mjs +0 -2
- package/dist/methods-PMH5VQ25.js +0 -2
- package/dist/methods-PMH5VQ25.js.map +0 -1
- /package/dist/{CartProvider-RYAA3JDA.mjs.map → BitsnapCart-E72W5RRZ.mjs.map} +0 -0
- /package/dist/{methods-AULQDKVS.mjs.map → CartProvider-YPDOFSYC.mjs.map} +0 -0
- /package/dist/{PanelModelFiles-JZFSF7BF.mjs.map → PanelModelFiles-4B2HYGIE.mjs.map} +0 -0
- /package/dist/{chunk-4OVOKGGS.mjs.map → chunk-AB37DWOK.mjs.map} +0 -0
- /package/dist/{chunk-JHJ3ZZF4.mjs.map → chunk-MMLBQHBM.mjs.map} +0 -0
- /package/dist/{chunk-GEBRXFT3.mjs.map → chunk-N523LFAM.mjs.map} +0 -0
package/dist/chat.d.mts
ADDED
|
@@ -0,0 +1,172 @@
|
|
|
1
|
+
import { C as ChatTexts } from './widgets-BT2LN2Nq.mjs';
|
|
2
|
+
export { n as CHAT_TEXT_TABLES, a as Channel, c as ChannelProps, d as ChatBuyRequest, r as ChatChannelEntitlement, t as ChatChannelSummary, i as ChatClient, j as ChatClientOptions, g as ChatError, v as ChatLiveMode, w as ChatMe, x as ChatMessage, y as ChatMessagePage, z as ChatPack, A as ChatPackEntitlement, B as ChatRealtimeEvent, E as ChatRealtimeToken, F as ChatReportReason, G as ChatSendResult, b as ChatThread, e as ChatThreadProps, H as ChatThreadState, I as ChatThreadSummary, f as ChatWidgetBaseProps, k as ConversationLock, l as ConversationMessage, m as ConversationTarget, D as DEFAULT_CHAT_API_URL, q as DEFAULT_CHAT_REALTIME_URL, L as LiveOptions, U as UseConversationOptions, h as createChatClient, o as getChatTexts, p as parseRealtimeEvent, s as startLive, u as useConversation } from './widgets-BT2LN2Nq.mjs';
|
|
3
|
+
import * as react_jsx_runtime from 'react/jsx-runtime';
|
|
4
|
+
import { Message } from '@bufbuild/protobuf';
|
|
5
|
+
import './texts-9kfgClsA.mjs';
|
|
6
|
+
|
|
7
|
+
/**
|
|
8
|
+
* @generated from message public_api.v1.UserProduct
|
|
9
|
+
*/
|
|
10
|
+
type UserProduct = Message<"public_api.v1.UserProduct"> & {
|
|
11
|
+
/**
|
|
12
|
+
* @generated from field: string project_id = 1;
|
|
13
|
+
*/
|
|
14
|
+
projectId: string;
|
|
15
|
+
/**
|
|
16
|
+
* @generated from field: string project_name = 2;
|
|
17
|
+
*/
|
|
18
|
+
projectName: string;
|
|
19
|
+
/**
|
|
20
|
+
* @generated from field: string product_id = 3;
|
|
21
|
+
*/
|
|
22
|
+
productId: string;
|
|
23
|
+
/**
|
|
24
|
+
* @generated from field: string product_name = 4;
|
|
25
|
+
*/
|
|
26
|
+
productName: string;
|
|
27
|
+
/**
|
|
28
|
+
* @generated from field: string product_description = 5;
|
|
29
|
+
*/
|
|
30
|
+
productDescription: string;
|
|
31
|
+
/**
|
|
32
|
+
* @generated from field: string product_image_url = 6;
|
|
33
|
+
*/
|
|
34
|
+
productImageUrl: string;
|
|
35
|
+
/**
|
|
36
|
+
* @generated from field: public_api.v1.UserProductType product_type = 7;
|
|
37
|
+
*/
|
|
38
|
+
productType: UserProductType;
|
|
39
|
+
/**
|
|
40
|
+
* @generated from field: string access_id = 8;
|
|
41
|
+
*/
|
|
42
|
+
accessId: string;
|
|
43
|
+
/**
|
|
44
|
+
* @generated from field: optional public_api.v1.ProjectTheme project_theme = 9;
|
|
45
|
+
*/
|
|
46
|
+
projectTheme?: ProjectTheme | undefined;
|
|
47
|
+
/**
|
|
48
|
+
* @generated from field: optional string project_description = 10;
|
|
49
|
+
*/
|
|
50
|
+
projectDescription?: string | undefined;
|
|
51
|
+
/**
|
|
52
|
+
* Paid chat: the numeric project id as a decimal string ("18"), which the
|
|
53
|
+
* chat service expects in X-Bitsnap-Project. Set only on CHAT and COMMUNITY
|
|
54
|
+
* products; project_id stays the public hashed id (cart, checkout).
|
|
55
|
+
*
|
|
56
|
+
* @generated from field: optional string chat_project_id = 11;
|
|
57
|
+
*/
|
|
58
|
+
chatProjectId?: string | undefined;
|
|
59
|
+
};
|
|
60
|
+
/**
|
|
61
|
+
* @generated from message public_api.v1.ProjectTheme
|
|
62
|
+
*/
|
|
63
|
+
type ProjectTheme = Message<"public_api.v1.ProjectTheme"> & {
|
|
64
|
+
/**
|
|
65
|
+
* @generated from field: optional string image_url = 1;
|
|
66
|
+
*/
|
|
67
|
+
imageUrl?: string | undefined;
|
|
68
|
+
/**
|
|
69
|
+
* @generated from field: optional string image_dark_url = 2;
|
|
70
|
+
*/
|
|
71
|
+
imageDarkUrl?: string | undefined;
|
|
72
|
+
/**
|
|
73
|
+
* @generated from field: optional string brand_color = 3;
|
|
74
|
+
*/
|
|
75
|
+
brandColor?: string | undefined;
|
|
76
|
+
/**
|
|
77
|
+
* @generated from field: optional string brand_color_dark = 4;
|
|
78
|
+
*/
|
|
79
|
+
brandColorDark?: string | undefined;
|
|
80
|
+
};
|
|
81
|
+
/**
|
|
82
|
+
* @generated from enum public_api.v1.UserProductType
|
|
83
|
+
*/
|
|
84
|
+
declare enum UserProductType {
|
|
85
|
+
/**
|
|
86
|
+
* @generated from enum value: USER_PRODUCT_TYPE_UNKNOWN = 0;
|
|
87
|
+
*/
|
|
88
|
+
UNKNOWN = 0,
|
|
89
|
+
/**
|
|
90
|
+
* @generated from enum value: USER_PRODUCT_TYPE_AUDIO = 1;
|
|
91
|
+
*/
|
|
92
|
+
AUDIO = 1,
|
|
93
|
+
/**
|
|
94
|
+
* @generated from enum value: USER_PRODUCT_TYPE_FILE = 2;
|
|
95
|
+
*/
|
|
96
|
+
FILE = 2,
|
|
97
|
+
/**
|
|
98
|
+
* @generated from enum value: USER_PRODUCT_TYPE_TICKET = 3;
|
|
99
|
+
*/
|
|
100
|
+
TICKET = 3,
|
|
101
|
+
/**
|
|
102
|
+
* @generated from enum value: USER_PRODUCT_TYPE_COURSE = 4;
|
|
103
|
+
*/
|
|
104
|
+
COURSE = 4,
|
|
105
|
+
/**
|
|
106
|
+
* Paid chat (CHAT_ENABLED only): a service whose paid order holds a reply pack.
|
|
107
|
+
* product_id is the service product; access_id is not used.
|
|
108
|
+
*
|
|
109
|
+
* @generated from enum value: USER_PRODUCT_TYPE_CHAT = 5;
|
|
110
|
+
*/
|
|
111
|
+
CHAT = 5,
|
|
112
|
+
/**
|
|
113
|
+
* Paid chat (CHAT_ENABLED only): a community product, whose channel the buyer may open.
|
|
114
|
+
*
|
|
115
|
+
* @generated from enum value: USER_PRODUCT_TYPE_COMMUNITY = 6;
|
|
116
|
+
*/
|
|
117
|
+
COMMUNITY = 6
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
/** Which conversation the panel shows (kept in the URL). */
|
|
121
|
+
type PanelMessagesSelection = {
|
|
122
|
+
/** Chat project of the conversation. */
|
|
123
|
+
chatProject?: string;
|
|
124
|
+
thread?: string;
|
|
125
|
+
channel?: string;
|
|
126
|
+
};
|
|
127
|
+
type PanelMessagesProps = {
|
|
128
|
+
accessToken: string;
|
|
129
|
+
/** Panel products: CHAT and COMMUNITY items name the conversations. */
|
|
130
|
+
products: UserProduct[];
|
|
131
|
+
/** `chat_api_url` of the products answer. */
|
|
132
|
+
chatApiUrl?: string;
|
|
133
|
+
/** Project of the panel, used when no chat product names one. */
|
|
134
|
+
projectID?: string;
|
|
135
|
+
host?: string;
|
|
136
|
+
selection: PanelMessagesSelection;
|
|
137
|
+
onSelect: (selection: PanelMessagesSelection) => void;
|
|
138
|
+
locale?: string;
|
|
139
|
+
texts?: Partial<ChatTexts>;
|
|
140
|
+
};
|
|
141
|
+
/**
|
|
142
|
+
* The projects whose chat the buyer may have: those of the CHAT and
|
|
143
|
+
* COMMUNITY products, else the panel's project.
|
|
144
|
+
*
|
|
145
|
+
* `UserProduct.projectId` is the public (hashed) id the cart uses; the chat
|
|
146
|
+
* service wants the numeric one (`X-Bitsnap-Project`), which Instapay sends as
|
|
147
|
+
* `chatProjectId` on CHAT and COMMUNITY products (see `chatProjectIds`).
|
|
148
|
+
*/
|
|
149
|
+
declare function chatProjects(products: UserProduct[], fallback?: string): string[];
|
|
150
|
+
/** The "Wiadomości" screen of the customer panel. */
|
|
151
|
+
declare function PanelMessages({ accessToken, products, chatApiUrl, projectID, host, selection, onSelect, locale, texts: overrides, }: PanelMessagesProps): react_jsx_runtime.JSX.Element;
|
|
152
|
+
|
|
153
|
+
type BuyPackInput = {
|
|
154
|
+
/** Public project id of the shop (the cart's project). */
|
|
155
|
+
projectID: string;
|
|
156
|
+
/** The product (or variant) to add: the pack's service or community product. */
|
|
157
|
+
productId: string;
|
|
158
|
+
name?: string;
|
|
159
|
+
priceCents?: number;
|
|
160
|
+
/** Backend origin of the cart, when not the default. */
|
|
161
|
+
host?: string;
|
|
162
|
+
};
|
|
163
|
+
/**
|
|
164
|
+
* Default "Kup pakiet" / "Kup dostęp" action: adds the product to the page
|
|
165
|
+
* cart (`Bitsnap.addProductToCart`) and opens the cart drawer. The page needs
|
|
166
|
+
* a mounted `BitsnapCheckout`. When the page cart belongs to another project
|
|
167
|
+
* or host nothing changes and the promise rejects; pass `onBuy` to the widget
|
|
168
|
+
* to use your own checkout instead.
|
|
169
|
+
*/
|
|
170
|
+
declare function addPackToCart(input: BuyPackInput): Promise<void>;
|
|
171
|
+
|
|
172
|
+
export { type BuyPackInput, ChatTexts, PanelMessages, type PanelMessagesProps, type PanelMessagesSelection, addPackToCart, chatProjects };
|
package/dist/chat.d.ts
ADDED
|
@@ -0,0 +1,172 @@
|
|
|
1
|
+
import { C as ChatTexts } from './widgets-BVOSj9fU.js';
|
|
2
|
+
export { n as CHAT_TEXT_TABLES, a as Channel, c as ChannelProps, d as ChatBuyRequest, r as ChatChannelEntitlement, t as ChatChannelSummary, i as ChatClient, j as ChatClientOptions, g as ChatError, v as ChatLiveMode, w as ChatMe, x as ChatMessage, y as ChatMessagePage, z as ChatPack, A as ChatPackEntitlement, B as ChatRealtimeEvent, E as ChatRealtimeToken, F as ChatReportReason, G as ChatSendResult, b as ChatThread, e as ChatThreadProps, H as ChatThreadState, I as ChatThreadSummary, f as ChatWidgetBaseProps, k as ConversationLock, l as ConversationMessage, m as ConversationTarget, D as DEFAULT_CHAT_API_URL, q as DEFAULT_CHAT_REALTIME_URL, L as LiveOptions, U as UseConversationOptions, h as createChatClient, o as getChatTexts, p as parseRealtimeEvent, s as startLive, u as useConversation } from './widgets-BVOSj9fU.js';
|
|
3
|
+
import * as react_jsx_runtime from 'react/jsx-runtime';
|
|
4
|
+
import { Message } from '@bufbuild/protobuf';
|
|
5
|
+
import './texts-9kfgClsA.js';
|
|
6
|
+
|
|
7
|
+
/**
|
|
8
|
+
* @generated from message public_api.v1.UserProduct
|
|
9
|
+
*/
|
|
10
|
+
type UserProduct = Message<"public_api.v1.UserProduct"> & {
|
|
11
|
+
/**
|
|
12
|
+
* @generated from field: string project_id = 1;
|
|
13
|
+
*/
|
|
14
|
+
projectId: string;
|
|
15
|
+
/**
|
|
16
|
+
* @generated from field: string project_name = 2;
|
|
17
|
+
*/
|
|
18
|
+
projectName: string;
|
|
19
|
+
/**
|
|
20
|
+
* @generated from field: string product_id = 3;
|
|
21
|
+
*/
|
|
22
|
+
productId: string;
|
|
23
|
+
/**
|
|
24
|
+
* @generated from field: string product_name = 4;
|
|
25
|
+
*/
|
|
26
|
+
productName: string;
|
|
27
|
+
/**
|
|
28
|
+
* @generated from field: string product_description = 5;
|
|
29
|
+
*/
|
|
30
|
+
productDescription: string;
|
|
31
|
+
/**
|
|
32
|
+
* @generated from field: string product_image_url = 6;
|
|
33
|
+
*/
|
|
34
|
+
productImageUrl: string;
|
|
35
|
+
/**
|
|
36
|
+
* @generated from field: public_api.v1.UserProductType product_type = 7;
|
|
37
|
+
*/
|
|
38
|
+
productType: UserProductType;
|
|
39
|
+
/**
|
|
40
|
+
* @generated from field: string access_id = 8;
|
|
41
|
+
*/
|
|
42
|
+
accessId: string;
|
|
43
|
+
/**
|
|
44
|
+
* @generated from field: optional public_api.v1.ProjectTheme project_theme = 9;
|
|
45
|
+
*/
|
|
46
|
+
projectTheme?: ProjectTheme | undefined;
|
|
47
|
+
/**
|
|
48
|
+
* @generated from field: optional string project_description = 10;
|
|
49
|
+
*/
|
|
50
|
+
projectDescription?: string | undefined;
|
|
51
|
+
/**
|
|
52
|
+
* Paid chat: the numeric project id as a decimal string ("18"), which the
|
|
53
|
+
* chat service expects in X-Bitsnap-Project. Set only on CHAT and COMMUNITY
|
|
54
|
+
* products; project_id stays the public hashed id (cart, checkout).
|
|
55
|
+
*
|
|
56
|
+
* @generated from field: optional string chat_project_id = 11;
|
|
57
|
+
*/
|
|
58
|
+
chatProjectId?: string | undefined;
|
|
59
|
+
};
|
|
60
|
+
/**
|
|
61
|
+
* @generated from message public_api.v1.ProjectTheme
|
|
62
|
+
*/
|
|
63
|
+
type ProjectTheme = Message<"public_api.v1.ProjectTheme"> & {
|
|
64
|
+
/**
|
|
65
|
+
* @generated from field: optional string image_url = 1;
|
|
66
|
+
*/
|
|
67
|
+
imageUrl?: string | undefined;
|
|
68
|
+
/**
|
|
69
|
+
* @generated from field: optional string image_dark_url = 2;
|
|
70
|
+
*/
|
|
71
|
+
imageDarkUrl?: string | undefined;
|
|
72
|
+
/**
|
|
73
|
+
* @generated from field: optional string brand_color = 3;
|
|
74
|
+
*/
|
|
75
|
+
brandColor?: string | undefined;
|
|
76
|
+
/**
|
|
77
|
+
* @generated from field: optional string brand_color_dark = 4;
|
|
78
|
+
*/
|
|
79
|
+
brandColorDark?: string | undefined;
|
|
80
|
+
};
|
|
81
|
+
/**
|
|
82
|
+
* @generated from enum public_api.v1.UserProductType
|
|
83
|
+
*/
|
|
84
|
+
declare enum UserProductType {
|
|
85
|
+
/**
|
|
86
|
+
* @generated from enum value: USER_PRODUCT_TYPE_UNKNOWN = 0;
|
|
87
|
+
*/
|
|
88
|
+
UNKNOWN = 0,
|
|
89
|
+
/**
|
|
90
|
+
* @generated from enum value: USER_PRODUCT_TYPE_AUDIO = 1;
|
|
91
|
+
*/
|
|
92
|
+
AUDIO = 1,
|
|
93
|
+
/**
|
|
94
|
+
* @generated from enum value: USER_PRODUCT_TYPE_FILE = 2;
|
|
95
|
+
*/
|
|
96
|
+
FILE = 2,
|
|
97
|
+
/**
|
|
98
|
+
* @generated from enum value: USER_PRODUCT_TYPE_TICKET = 3;
|
|
99
|
+
*/
|
|
100
|
+
TICKET = 3,
|
|
101
|
+
/**
|
|
102
|
+
* @generated from enum value: USER_PRODUCT_TYPE_COURSE = 4;
|
|
103
|
+
*/
|
|
104
|
+
COURSE = 4,
|
|
105
|
+
/**
|
|
106
|
+
* Paid chat (CHAT_ENABLED only): a service whose paid order holds a reply pack.
|
|
107
|
+
* product_id is the service product; access_id is not used.
|
|
108
|
+
*
|
|
109
|
+
* @generated from enum value: USER_PRODUCT_TYPE_CHAT = 5;
|
|
110
|
+
*/
|
|
111
|
+
CHAT = 5,
|
|
112
|
+
/**
|
|
113
|
+
* Paid chat (CHAT_ENABLED only): a community product, whose channel the buyer may open.
|
|
114
|
+
*
|
|
115
|
+
* @generated from enum value: USER_PRODUCT_TYPE_COMMUNITY = 6;
|
|
116
|
+
*/
|
|
117
|
+
COMMUNITY = 6
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
/** Which conversation the panel shows (kept in the URL). */
|
|
121
|
+
type PanelMessagesSelection = {
|
|
122
|
+
/** Chat project of the conversation. */
|
|
123
|
+
chatProject?: string;
|
|
124
|
+
thread?: string;
|
|
125
|
+
channel?: string;
|
|
126
|
+
};
|
|
127
|
+
type PanelMessagesProps = {
|
|
128
|
+
accessToken: string;
|
|
129
|
+
/** Panel products: CHAT and COMMUNITY items name the conversations. */
|
|
130
|
+
products: UserProduct[];
|
|
131
|
+
/** `chat_api_url` of the products answer. */
|
|
132
|
+
chatApiUrl?: string;
|
|
133
|
+
/** Project of the panel, used when no chat product names one. */
|
|
134
|
+
projectID?: string;
|
|
135
|
+
host?: string;
|
|
136
|
+
selection: PanelMessagesSelection;
|
|
137
|
+
onSelect: (selection: PanelMessagesSelection) => void;
|
|
138
|
+
locale?: string;
|
|
139
|
+
texts?: Partial<ChatTexts>;
|
|
140
|
+
};
|
|
141
|
+
/**
|
|
142
|
+
* The projects whose chat the buyer may have: those of the CHAT and
|
|
143
|
+
* COMMUNITY products, else the panel's project.
|
|
144
|
+
*
|
|
145
|
+
* `UserProduct.projectId` is the public (hashed) id the cart uses; the chat
|
|
146
|
+
* service wants the numeric one (`X-Bitsnap-Project`), which Instapay sends as
|
|
147
|
+
* `chatProjectId` on CHAT and COMMUNITY products (see `chatProjectIds`).
|
|
148
|
+
*/
|
|
149
|
+
declare function chatProjects(products: UserProduct[], fallback?: string): string[];
|
|
150
|
+
/** The "Wiadomości" screen of the customer panel. */
|
|
151
|
+
declare function PanelMessages({ accessToken, products, chatApiUrl, projectID, host, selection, onSelect, locale, texts: overrides, }: PanelMessagesProps): react_jsx_runtime.JSX.Element;
|
|
152
|
+
|
|
153
|
+
type BuyPackInput = {
|
|
154
|
+
/** Public project id of the shop (the cart's project). */
|
|
155
|
+
projectID: string;
|
|
156
|
+
/** The product (or variant) to add: the pack's service or community product. */
|
|
157
|
+
productId: string;
|
|
158
|
+
name?: string;
|
|
159
|
+
priceCents?: number;
|
|
160
|
+
/** Backend origin of the cart, when not the default. */
|
|
161
|
+
host?: string;
|
|
162
|
+
};
|
|
163
|
+
/**
|
|
164
|
+
* Default "Kup pakiet" / "Kup dostęp" action: adds the product to the page
|
|
165
|
+
* cart (`Bitsnap.addProductToCart`) and opens the cart drawer. The page needs
|
|
166
|
+
* a mounted `BitsnapCheckout`. When the page cart belongs to another project
|
|
167
|
+
* or host nothing changes and the promise rejects; pass `onBuy` to the widget
|
|
168
|
+
* to use your own checkout instead.
|
|
169
|
+
*/
|
|
170
|
+
declare function addPackToCart(input: BuyPackInput): Promise<void>;
|
|
171
|
+
|
|
172
|
+
export { type BuyPackInput, ChatTexts, PanelMessages, type PanelMessagesProps, type PanelMessagesSelection, addPackToCart, chatProjects };
|
package/dist/chat.js
ADDED
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
"use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { newObj[key] = obj[key]; } } } newObj.default = obj; return newObj; } } function _nullishCoalesce(lhs, rhsFn) { if (lhs != null) { return lhs; } else { return rhsFn(); } } function _optionalChain(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = fn(value); } else if (op === 'call' || op === 'optionalCall') { value = fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; }var _chunkMWWEPEU2js = require('./chunk-MWWEPEU2.js');var _chunkMDAFPGPAjs = require('./chunk-MDAFPGPA.js');require('./chunk-LGPNJ5XE.js');var _chunkDOJICJCQjs = require('./chunk-DOJICJCQ.js');require('./chunk-D2ASWUXM.js');require('./chunk-W3RGQYPD.js');var _chunkQ337IQNAjs = require('./chunk-Q337IQNA.js');require('./chunk-JSDGZ4NY.js');var _react = require('react');async function ee(e){await _chunkMWWEPEU2js.e.call(void 0, {id:e.productId,name:_nullishCoalesce(e.name, () => ("")),price:_nullishCoalesce(e.priceCents, () => (0)),currency:""},{projectID:e.projectID,host:e.host,showCart:!0})}var ge="https://chat.bitsnap.pl",fe= exports.DEFAULT_CHAT_REALTIME_URL ="wss://bitsnap-nats-queue-production.up.railway.app";var U=class extends Error{constructor(t,r,n={}){super(`chat: ${t} (${r})`),this.name="ChatError",this.code=t,this.status=r,this.data=n;let a=Number(n.retry_after);Number.isFinite(a)&&a>0&&(this.retryAfter=a)}};function te(e){let t=(e.baseUrl||ge).replace(/\/+$/,""),r=_nullishCoalesce(e.fetch, () => (((...u)=>fetch(...u))));async function n(u,c,h){let g;try{g=await r(t+c,{method:u,headers:{Authorization:`Bearer ${e.token}`,"X-Bitsnap-Project":e.projectId,...h===void 0?{}:{"Content-Type":"application/json"}},body:h===void 0?void 0:JSON.stringify(h)})}catch (e2){throw new U("network",0)}let l=null;try{let b=await g.text();l=b?JSON.parse(b):null}catch (e3){l=null}if(!g.ok){let b=D(l)?l:{},w=typeof b.error=="string"?b.error:"internal_error";throw new U(w,g.status,b)}return{status:g.status,json:l}}let a=encodeURIComponent,d;return{baseUrl:t,projectId:e.projectId,async me(){let{json:u}=await n("GET","/v1/me");return Xe(u)},async openThread(u){let{json:c}=await n("POST","/v1/threads",{product_id:u});return Se(c)},async messages(u,c={}){let h=new URLSearchParams;c.before&&h.set("before",c.before),c.limit&&h.set("limit",String(c.limit));let g=h.toString(),l=g?`?${g}`:"",{json:b}=await n("GET",`/v1/threads/${a(u)}/messages${l}`),w=D(b)?b:{};return{messages:V(w.messages).map(ie),hasMore:w.has_more===!0}},async send(u,c){let{json:h}=await n("POST",`/v1/threads/${a(u)}/messages`,{body:c.body,...c.clientId?{client_id:c.clientId}:{}}),g=D(h)?h:{};return{message:ie(g.message),thread:Le(g.thread)}},async deleteMessage(u,c){await n("DELETE",`/v1/threads/${a(u)}/messages/${a(c)}`)},async mute(u,c){await n("POST",`/v1/threads/${a(u)}/mute`,{muted:c})},async report(u){await n("POST","/v1/reports",{thread_id:u.threadId,...u.messageId?{message_id:u.messageId}:{},reason:u.reason,...u.note?{note:u.note}:{}})},async markRead(u,c){await n("POST",`/v1/threads/${a(u)}/receipts`,{state:"read",message_id:c})},async realtimeToken(u={}){if(!u.fresh&&d&&Date.parse(d.expiresAt)-Date.now()>9e4)return d;let{json:c}=await n("POST","/v1/realtime/token"),h=D(c)?c:{};return d={jwt:M(h.jwt),expiresAt:M(h.expires_at),servers:V(h.servers).filter(g=>typeof g=="string"),subjects:V(h.subjects).filter(g=>typeof g=="string"),truncated:h.truncated===!0}}}}function ye(e){if(!D(e)||typeof e.type!="string")return null;let t=M(e.id);switch(e.type){case"message.created":return{type:"message.created",message:ie(e)};case"message.rejected":return{type:"message.rejected",id:t,reason:M(e.reason)};case"message.deleted":case"message.pinned":case"message.unpinned":return{type:e.type,id:t};default:return null}}function D(e){return typeof e=="object"&&e!=null&&!Array.isArray(e)}function V(e){return Array.isArray(e)?e:[]}function M(e){return typeof e=="string"?e:e==null?"":String(e)}function W(e){let t=Number(e);return Number.isFinite(t)?t:0}function X(e){return typeof e=="string"&&e!==""?e:void 0}function be(e){return typeof e=="string"&&e!==""?e:null}function ie(e){let t=D(e)?e:{};return{id:M(t.id),threadId:M(t.thread_id),authorEmail:M(t.author_email),body:M(t.body),attachmentKey:X(t.attachment_key),attachmentKind:X(t.attachment_kind),createdAt:M(t.created_at),pinned:t.pinned===!0,deleted:t.deleted===!0,system:t.system===!0,...t.status==="pending"?{status:"pending"}:{}}}function Ve(e){let t=D(e)?e:{};return{orderId:M(t.order_id),productId:X(t.product_id),replies:W(t.replies),used:W(t.used),left:W(t.left),expiresAt:be(t.expires_at),expired:t.expired===!0}}function Le(e){let t=D(e)?e:{};return{id:M(t.id),kind:t.kind==="channel"?"channel":"pack",repliesTotal:W(t.replies_total),repliesUsed:W(t.replies_used),repliesLeft:W(t.replies_left),expiresAt:be(t.expires_at),composerLocked:t.composer_locked===!0,responseHours:W(t.response_hours)}}function Se(e){let t=D(e)?e:{};return{...Le(t),channelId:X(t.channel_id),title:M(t.title),lastMessage:D(t.last_message)?ie(t.last_message):void 0,unread:W(t.unread),productId:X(t.product_id),packs:V(t.packs).map(Ve),muted:t.muted===!0}}function Je(e){let t=D(e)?e:{};return{id:M(t.id),name:M(t.name),topic:M(t.topic),welcome:M(t.welcome),whoCanPost:t.who_can_post==="members"?"members":"creator",productId:M(t.product_id),role:M(t.role),memberCount:W(t.member_count),createdAt:M(t.created_at),blockLinks:t.block_links===!0,blockMedia:t.block_media===!0,cooldownSeconds:W(t.cooldown_seconds)}}function Xe(e){let t=D(e)?e:{},r=D(t.entitlements)?t.entitlements:{};return{email:M(t.email),threads:V(t.threads).map(Se),entitlements:{packs:V(r.packs).map(n=>{let a=D(n)?n:{};return{productId:M(a.product_id),name:M(a.name),repliesLeftHint:W(a.replies_left_hint),expiresAt:be(a.expires_at)}}),channels:V(r.channels).map(n=>{let a=D(n)?n:{};return{productId:M(a.product_id),channelId:X(a.channel_id)}})},channels:V(t.channels).map(Je)}}var _lucidereact = require('lucide-react');var Ee={pl:{inboxHeading:"Wiadomo\u015Bci",inboxIntro:"Rozmowy z tw\xF3rcami i kana\u0142y, do kt\xF3rych nale\u017Cysz.",inboxEmpty:"Nie masz jeszcze rozm\xF3w. Po zakupie pakietu konsultacji lub dost\u0119pu do spo\u0142eczno\u015Bci rozmowa pojawi si\u0119 tutaj.",inboxError:"Nie uda\u0142o si\u0119 wczyta\u0107 wiadomo\u015Bci.",loading:"Wczytywanie\u2026",retry:"Spr\xF3buj ponownie",back:"Wr\xF3\u0107",selectConversation:"Wybierz rozmow\u0119 z listy.",kindChat:"Czat",kindChannel:"Kana\u0142",startSection:"Do rozpocz\u0119cia",startChat:"Rozpocznij rozmow\u0119",openChannel:"Otw\xF3rz kana\u0142",channelNotReady:"Tw\xF3rca jeszcze nie otworzy\u0142 tego kana\u0142u.",chatFallbackTitle:"Czat z tw\xF3rc\u0105",channelFallbackTitle:"Kana\u0142",repliesLeftOne:"Zosta\u0142a {count} odpowied\u017A",repliesLeftFew:"Zosta\u0142y {count} odpowiedzi",repliesLeftMany:"Zosta\u0142o {count} odpowiedzi",noRepliesLeft:"Brak odpowiedzi w pakiecie",expiresOn:"Wa\u017Cny do {date}",expiredOn:"Wygas\u0142 {date}",responseHours:"Odpowied\u017A w ci\u0105gu {hours} h",unread:"Nieprzeczytane: {count}",members:"Cz\u0142onkowie: {count}",mutedBadge:"Wyciszony",noMessagesYet:"Brak wiadomo\u015Bci",emptyThread:"Napisz pierwsz\u0105 wiadomo\u015B\u0107. Tw\xF3rca odpowie w ramach Twojego pakietu.",emptyChannel:"W kanale nie ma jeszcze wiadomo\u015Bci.",privacyNote:"Wiadomo\u015Bci czyta druga strona rozmowy. Bitsnap przechowuje je przez 90 dni.",loadOlder:"Wcze\u015Bniejsze wiadomo\u015Bci",you:"Ty",creator:"Tw\xF3rca",systemLabel:"Wiadomo\u015B\u0107 automatyczna",pinned:"Przypi\u0119ta",deletedPlaceholder:"Wiadomo\u015B\u0107 zosta\u0142a usuni\u0119ta",attachment:"Za\u0142\u0105cznik",composerLabel:"Wiadomo\u015B\u0107",composerPlaceholder:"Napisz wiadomo\u015B\u0107\u2026",send:"Wy\u015Blij",composerExpired:"Pakiet wygas\u0142, wi\u0119c nie mo\u017Cesz ju\u017C pisa\u0107 w tej rozmowie.",composerCreatorOnly:"W tym kanale pisze tylko tw\xF3rca.",composerMuted:"Masz wyciszone pisanie w tym kanale.",composerReadOnly:"Ten dost\u0119p pozwala tylko czyta\u0107.",lockRepliesTitle:"Odpowiedzi w pakiecie si\u0119 sko\u0144czy\u0142y",lockRepliesBody:"Mo\u017Cesz dalej pisa\u0107, ale tw\xF3rca odpowie dopiero po zakupie kolejnego pakietu.",lockExpiredTitle:"Pakiet wygas\u0142",lockExpiredBody:"Rozmowa zostaje do wgl\u0105du. Kup nowy pakiet, aby j\u0105 kontynuowa\u0107.",lockThreadTitle:"Nie masz pakietu odpowiedzi",lockThreadBody:"Kup pakiet, aby napisa\u0107 do tw\xF3rcy.",lockChannelTitle:"Kana\u0142 dla cz\u0142onk\xF3w",lockChannelBody:"Kup dost\u0119p, aby czyta\u0107 i pisa\u0107 w tym kanale.",buyPack:"Kup pakiet",buyAccess:"Kup dost\u0119p",buying:"Dodawanie do koszyka\u2026",buyError:"Nie uda\u0142o si\u0119 doda\u0107 do koszyka. Spr\xF3buj ponownie.",pending:"Wysy\u0142anie\u2026",notConfirmed:"Czekamy na potwierdzenie wys\u0142ania",rejectedLink:"Linki s\u0105 w tym kanale zablokowane. Usu\u0144 link i wy\u015Blij ponownie.",rejectedBannedWord:"Wiadomo\u015B\u0107 zawiera s\u0142owo zablokowane w tym kanale. Popraw j\u0105 i wy\u015Blij ponownie.",rejectedMedia:"Za\u0142\u0105czniki s\u0105 w tym kanale zablokowane.",rejectedCooldown:"Piszesz za szybko. Spr\xF3buj ponownie za {seconds} s.",rejectedBlocked:"Tw\xF3rca zablokowa\u0142 Ci mo\u017Cliwo\u015B\u0107 pisania w tym sklepie.",rejectedMuted:"Masz wyciszone pisanie w tym kanale.",rejectedReadOnly:"Ten dost\u0119p pozwala tylko czyta\u0107.",rejectedPackEmpty:"Pakiet nie ma ju\u017C odpowiedzi.",rejectedForbidden:"Nie mo\u017Cesz pisa\u0107 w tej rozmowie.",rejectedGeneric:"Nie uda\u0142o si\u0119 wys\u0142a\u0107 wiadomo\u015Bci.",failedNetwork:"Brak po\u0142\u0105czenia. Wiadomo\u015B\u0107 nie zosta\u0142a wys\u0142ana.",editMessage:"Popraw",retrySend:"Wy\u015Blij ponownie",dismiss:"Odrzu\u0107",messageActions:"Opcje wiadomo\u015Bci",deleteMessage:"Usu\u0144 wiadomo\u015B\u0107",deleteConfirm:"Na pewno usun\u0105\u0107?",reportMessage:"Zg\u0142o\u015B wiadomo\u015B\u0107",conversationActions:"Opcje rozmowy",muteThread:"Wycisz powiadomienia",unmuteThread:"W\u0142\u0105cz powiadomienia",muteError:"Nie uda\u0142o si\u0119 zmieni\u0107 powiadomie\u0144.",reportConversation:"Zg\u0142o\u015B rozmow\u0119",reportTitle:"Zg\u0142o\u015B wiadomo\u015B\u0107",reportConversationTitle:"Zg\u0142o\u015B rozmow\u0119",reportReason:"Pow\xF3d zg\u0142oszenia",reasonSpam:"Spam",reasonAbuse:"N\u0119kanie lub obra\u017Aliwe tre\u015Bci",reasonIllegal:"Tre\u015Bci niezgodne z prawem",reasonOther:"Inny pow\xF3d",reportNote:"Opis (opcjonalnie)",reportSend:"Wy\u015Blij zg\u0142oszenie",reportCancel:"Anuluj",reportSent:"Dzi\u0119kujemy. Zg\u0142oszenie trafi\u0142o do moderacji.",reportError:"Nie uda\u0142o si\u0119 wys\u0142a\u0107 zg\u0142oszenia. Spr\xF3buj ponownie.",liveLabel:"Nowe wiadomo\u015Bci pojawiaj\u0105 si\u0119 na bie\u017C\u0105co",pollingLabel:"Nowe wiadomo\u015Bci od\u015Bwie\u017Caj\u0105 si\u0119 co kilka sekund",errorNoToken:"Zaloguj si\u0119 w panelu klienta, aby zobaczy\u0107 rozmow\u0119.",errorUnauthorized:"Sesja wygas\u0142a. Zaloguj si\u0119 ponownie.",errorPlan:"Czat nie jest dost\u0119pny w tym sklepie.",errorNotFound:"Nie znaleziono tej rozmowy.",errorUnavailable:"Czat jest chwilowo niedost\u0119pny. Spr\xF3buj za chwil\u0119.",errorGeneric:"Nie uda\u0142o si\u0119 wczyta\u0107 rozmowy."},en:{inboxHeading:"Messages",inboxIntro:"Your conversations with creators and the channels you belong to.",inboxEmpty:"No conversations yet. When you buy a consultation pack or community access, it shows up here.",inboxError:"Your messages could not be loaded.",loading:"Loading\u2026",retry:"Try again",back:"Back",selectConversation:"Pick a conversation from the list.",kindChat:"Chat",kindChannel:"Channel",startSection:"Ready to start",startChat:"Start the conversation",openChannel:"Open the channel",channelNotReady:"The creator has not opened this channel yet.",chatFallbackTitle:"Chat with the creator",channelFallbackTitle:"Channel",repliesLeftOne:"{count} reply left",repliesLeftFew:"{count} replies left",repliesLeftMany:"{count} replies left",noRepliesLeft:"No replies left in your pack",expiresOn:"Valid until {date}",expiredOn:"Expired on {date}",responseHours:"Replies within {hours} h",unread:"Unread: {count}",members:"Members: {count}",mutedBadge:"Muted",noMessagesYet:"No messages yet",emptyThread:"Write the first message. The creator replies within your pack.",emptyChannel:"There are no messages in this channel yet.",privacyNote:"The other side of the conversation reads your messages. Bitsnap keeps them for 90 days.",loadOlder:"Earlier messages",you:"You",creator:"Creator",systemLabel:"Automatic message",pinned:"Pinned",deletedPlaceholder:"This message was deleted",attachment:"Attachment",composerLabel:"Message",composerPlaceholder:"Write a message\u2026",send:"Send",composerExpired:"Your pack has expired, so you can no longer write here.",composerCreatorOnly:"Only the creator posts in this channel.",composerMuted:"You are muted in this channel.",composerReadOnly:"This access is read only.",lockRepliesTitle:"Your pack has no replies left",lockRepliesBody:"You can keep writing, but the creator can reply only after you buy another pack.",lockExpiredTitle:"Your pack has expired",lockExpiredBody:"You can still read the conversation. Buy a new pack to continue it.",lockThreadTitle:"You have no reply pack",lockThreadBody:"Buy a pack to write to the creator.",lockChannelTitle:"Members-only channel",lockChannelBody:"Buy access to read and post in this channel.",buyPack:"Buy a pack",buyAccess:"Buy access",buying:"Adding to cart\u2026",buyError:"Could not add it to the cart. Try again.",pending:"Sending\u2026",notConfirmed:"Waiting for the send to be confirmed",rejectedLink:"Links are blocked in this channel. Remove the link and send again.",rejectedBannedWord:"Your message contains a word blocked in this channel. Edit it and send again.",rejectedMedia:"Attachments are blocked in this channel.",rejectedCooldown:"You are posting too fast. Try again in {seconds} s.",rejectedBlocked:"The creator has blocked you from posting in this shop.",rejectedMuted:"You are muted in this channel.",rejectedReadOnly:"This access is read only.",rejectedPackEmpty:"The pack has no replies left.",rejectedForbidden:"You cannot post in this conversation.",rejectedGeneric:"Your message could not be sent.",failedNetwork:"No connection. Your message was not sent.",editMessage:"Edit",retrySend:"Send again",dismiss:"Discard",messageActions:"Message options",deleteMessage:"Delete message",deleteConfirm:"Delete for sure?",reportMessage:"Report message",conversationActions:"Conversation options",muteThread:"Mute notifications",unmuteThread:"Unmute notifications",muteError:"Notifications could not be changed.",reportConversation:"Report conversation",reportTitle:"Report message",reportConversationTitle:"Report conversation",reportReason:"Reason",reasonSpam:"Spam",reasonAbuse:"Harassment or abusive content",reasonIllegal:"Illegal content",reasonOther:"Something else",reportNote:"Details (optional)",reportSend:"Send report",reportCancel:"Cancel",reportSent:"Thank you. Your report went to moderation.",reportError:"Your report could not be sent. Try again.",liveLabel:"New messages appear live",pollingLabel:"New messages refresh every few seconds",errorNoToken:"Log in to the customer panel to see this conversation.",errorUnauthorized:"Your session has expired. Log in again.",errorPlan:"Chat is not available in this shop.",errorNotFound:"This conversation was not found.",errorUnavailable:"Chat is unavailable right now. Try again in a moment.",errorGeneric:"The conversation could not be loaded."}};function Q(e,t=_chunkQ337IQNAjs.f.call(void 0, )){return _chunkQ337IQNAjs.b.call(void 0, Ee,t,e)}function $(e,t){return e.replace(/\{(\w+)\}/g,(r,n)=>n in t?String(t[n]):r)}function ne(e,t,r=_chunkQ337IQNAjs.f.call(void 0, )){if(t<=0)return e.noRepliesLeft;let n="other";try{n=new Intl.PluralRules(r).select(t)}catch (e4){}let a=n==="one"?e.repliesLeftOne:n==="few"?e.repliesLeftFew:e.repliesLeftMany;return $(a,{count:t})}function re(e,t=_chunkQ337IQNAjs.f.call(void 0, )){let r=new Date(e);return Number.isNaN(r.getTime())?"":new Intl.DateTimeFormat(t,{day:"numeric",month:"numeric",year:"numeric"}).format(r)}function le(e,t=_chunkQ337IQNAjs.f.call(void 0, ),r=new Date){let n=new Date(e);if(Number.isNaN(n.getTime()))return"";let a=n.toDateString()===r.toDateString();return new Intl.DateTimeFormat(t,a?{hour:"2-digit",minute:"2-digit"}:{day:"numeric",month:"short",hour:"2-digit",minute:"2-digit"}).format(n)}function Ae(e,t,r){switch(t){case"moderation_link":return e.rejectedLink;case"moderation_banned_word":return e.rejectedBannedWord;case"moderation_media":return e.rejectedMedia;case"cooldown":return $(e.rejectedCooldown,{seconds:_nullishCoalesce(r, () => (30))});case"blocked":return e.rejectedBlocked;case"muted":return e.rejectedMuted;case"read_only":return e.rejectedReadOnly;case"pack_empty":case"replies_exhausted":return e.rejectedPackEmpty;case"forbidden":case"locked":return e.rejectedForbidden;case"network":case"unavailable":return e.failedNetwork;default:return e.rejectedGeneric}}var _jsxruntime = require('react/jsx-runtime');var xe="focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-neutral-500",H=_chunkDOJICJCQjs.g.call(void 0, "inline-flex min-h-11 items-center gap-2 rounded-md px-3 text-sm text-neutral-700 hover:bg-neutral-100 dark:text-neutral-300 dark:hover:bg-neutral-800",xe),de=_chunkDOJICJCQjs.g.call(void 0, "inline-flex min-h-11 items-center justify-center gap-2 rounded-md bg-neutral-900 px-4 text-sm font-medium text-white hover:bg-neutral-800 disabled:cursor-not-allowed disabled:opacity-50 dark:bg-white dark:text-neutral-900 dark:hover:bg-neutral-200",xe);function Ce({conversation:e,texts:t,locale:r,kind:n,title:a,onBack:d,onBuy:u,className:c}){let[h,g]=_react.useState.call(void 0, !1),[l,b]=_react.useState.call(void 0, null),[w,P]=_react.useState.call(void 0, ),[x,T]=_react.useState.call(void 0, ""),[N,j]=_react.useState.call(void 0, !1);_react.useEffect.call(void 0, ()=>{if(!N)return;let I=setTimeout(()=>j(!1),6e3);return()=>clearTimeout(I)},[N]);let y=a||_optionalChain([e, 'access', _2 => _2.channel, 'optionalAccess', _3 => _3.name])||(n==="channel"?t.channelFallbackTitle:t.chatFallbackTitle),S=it(e,t,r);return _jsxruntime.jsxs.call(void 0, "section",{"data-bitsnap-chat":n,"aria-label":y,className:_chunkDOJICJCQjs.g.call(void 0, "flex h-full min-h-[28rem] w-full min-w-0 flex-col overflow-hidden rounded-xl border border-neutral-200 bg-white text-neutral-900 dark:border-neutral-800 dark:bg-neutral-900 dark:text-neutral-50",c),children:[_jsxruntime.jsxs.call(void 0, "header",{className:"flex items-start gap-2 border-b border-neutral-200 px-3 py-2 dark:border-neutral-800",children:[d&&_jsxruntime.jsx.call(void 0, "button",{type:"button",onClick:d,"aria-label":t.back,className:_chunkDOJICJCQjs.g.call(void 0, H,"w-11 justify-center px-0"),children:_jsxruntime.jsx.call(void 0, _lucidereact.ArrowLeft,{className:"size-5","aria-hidden":"true"})}),_jsxruntime.jsxs.call(void 0, "div",{className:"min-w-0 flex-1 py-1.5",children:[_jsxruntime.jsxs.call(void 0, "h2",{className:"flex items-center gap-2 text-base font-semibold",children:[_jsxruntime.jsx.call(void 0, "span",{className:"truncate",children:y}),_jsxruntime.jsx.call(void 0, lt,{live:e.live,texts:t})]}),S.length>0&&_jsxruntime.jsx.call(void 0, "p",{className:"mt-0.5 flex flex-wrap gap-x-3 gap-y-0.5 text-xs text-neutral-600 dark:text-neutral-400",children:S.map(I=>_jsxruntime.jsx.call(void 0, "span",{children:I},I))})]}),e.status==="ready"&&_jsxruntime.jsx.call(void 0, "button",{type:"button","aria-label":t.conversationActions,"aria-expanded":h,onClick:()=>g(I=>!I),className:_chunkDOJICJCQjs.g.call(void 0, H,"w-11 justify-center px-0"),children:_jsxruntime.jsx.call(void 0, _lucidereact.MoreHorizontal,{className:"size-5","aria-hidden":"true"})})]}),h&&e.status==="ready"&&_jsxruntime.jsxs.call(void 0, "div",{className:"flex flex-wrap gap-1 border-b border-neutral-200 bg-neutral-50 px-3 py-1 dark:border-neutral-800 dark:bg-neutral-950",children:[n==="thread"&&e.thread&&_jsxruntime.jsx.call(void 0, "button",{type:"button",className:H,onClick:async()=>{g(!1);try{await e.setMuted(!e.thread.muted),P(void 0)}catch (e5){P(t.muteError)}},children:e.thread.muted?t.unmuteThread:t.muteThread}),_jsxruntime.jsx.call(void 0, "button",{type:"button",className:H,onClick:()=>{g(!1),b({})},children:t.reportConversation})]}),e.status==="loading"&&_jsxruntime.jsx.call(void 0, dt,{texts:t}),e.status==="error"&&_jsxruntime.jsx.call(void 0, ut,{conversation:e,texts:t}),e.status==="locked"&&e.lock&&_jsxruntime.jsx.call(void 0, "div",{className:"flex flex-1 flex-col justify-center overflow-y-auto p-4",children:_jsxruntime.jsx.call(void 0, _e,{lock:e.lock,kind:n,texts:t,onBuy:u,prominent:!0})}),e.status==="ready"&&_jsxruntime.jsxs.call(void 0, _jsxruntime.Fragment,{children:[_jsxruntime.jsx.call(void 0, mt,{conversation:e,texts:t,locale:r,kind:n,onReport:I=>b({messageId:I}),onEdit:I=>{T(I.body),e.discard(I.id)}}),w&&_jsxruntime.jsx.call(void 0, "p",{role:"status",className:"px-4 pb-2 text-xs text-red-700 dark:text-red-400",children:w}),e.lock&&_jsxruntime.jsx.call(void 0, "div",{className:"border-t border-neutral-200 p-3 dark:border-neutral-800",children:_jsxruntime.jsx.call(void 0, _e,{lock:e.lock,kind:n,texts:t,onBuy:u})}),l?_jsxruntime.jsx.call(void 0, bt,{texts:t,messageId:l.messageId,onCancel:()=>b(null),onSubmit:async(I,A)=>{await e.report({messageId:l.messageId,reason:I,note:A}),b(null),P(void 0),j(!0)}}):_jsxruntime.jsx.call(void 0, ft,{conversation:e,texts:t,kind:n,draft:x,setDraft:T})]}),N&&_jsxruntime.jsx.call(void 0, "p",{role:"status",className:"border-t border-neutral-200 px-4 py-2 text-xs text-neutral-700 dark:border-neutral-800 dark:text-neutral-300",children:t.reportSent})]})}function it(e,t,r){let n=[];if(e.thread&&e.thread.kind==="pack"){if(n.push(ne(t,e.thread.repliesLeft,r)),e.thread.expiresAt){let a=re(e.thread.expiresAt,r);n.push($(e.thread.composerLocked?t.expiredOn:t.expiresOn,{date:a}))}e.thread.responseHours>0&&n.push($(t.responseHours,{hours:e.thread.responseHours})),e.thread.muted&&n.push(t.mutedBadge)}return e.channel&&(e.channel.topic&&n.push(e.channel.topic),e.channel.memberCount>0&&n.push($(t.members,{count:e.channel.memberCount}))),n}function lt({live:e,texts:t}){if(e!=="live"&&e!=="polling")return null;let r=e==="live"?t.liveLabel:t.pollingLabel;return _jsxruntime.jsx.call(void 0, "span",{title:r,"data-live":e,className:_chunkDOJICJCQjs.g.call(void 0, "inline-block size-2 shrink-0 rounded-full",e==="live"?"bg-emerald-500":"bg-neutral-400 dark:bg-neutral-500"),children:_jsxruntime.jsx.call(void 0, "span",{className:"sr-only",children:r})})}function dt({texts:e}){return _jsxruntime.jsx.call(void 0, "div",{role:"status","aria-busy":"true","aria-label":e.loading,className:"flex flex-1 flex-col gap-3 p-4",children:[60,40,70].map((t,r)=>_jsxruntime.jsx.call(void 0, "div",{"aria-hidden":"true",style:{width:`${t}%`},className:_chunkDOJICJCQjs.g.call(void 0, "h-10 rounded-2xl bg-neutral-100 motion-safe:animate-pulse dark:bg-neutral-800",r===1&&"self-end")},r))})}function ct(e,t){switch(e){case"no_token":return t.errorNoToken;case"unauthorized":return t.errorUnauthorized;case"plan_required":return t.errorPlan;case"not_found":return t.errorNotFound;case"unavailable":case"network":return t.errorUnavailable;default:return t.errorGeneric}}function ut({conversation:e,texts:t}){let r=_nullishCoalesce(_optionalChain([e, 'access', _4 => _4.error, 'optionalAccess', _5 => _5.code]), () => ("")),n=r!=="no_token"&&r!=="plan_required"&&r!=="unauthorized";return _jsxruntime.jsxs.call(void 0, "div",{role:"alert",className:"flex flex-1 flex-col items-start justify-center gap-3 p-4",children:[_jsxruntime.jsx.call(void 0, "p",{className:"text-sm text-neutral-700 dark:text-neutral-300",children:ct(r,t)}),n&&_jsxruntime.jsx.call(void 0, "button",{type:"button",className:de,onClick:e.reload,children:t.retry})]})}function _e({lock:e,kind:t,texts:r,onBuy:n,prominent:a}){let[d,u]=_react.useState.call(void 0, !1),[c,h]=_react.useState.call(void 0, !1),[g,l]=e.reason==="replies"?[r.lockRepliesTitle,r.lockRepliesBody]:e.reason==="expired"?[r.lockExpiredTitle,r.lockExpiredBody]:t==="channel"?[r.lockChannelTitle,r.lockChannelBody]:[r.lockThreadTitle,r.lockThreadBody],b=t==="channel"?r.buyAccess:r.buyPack,w=n!=null&&e.productId!=null;return _jsxruntime.jsxs.call(void 0, "div",{"data-testid":"chat-lock","data-lock":e.reason,className:_chunkDOJICJCQjs.g.call(void 0, "flex gap-3 rounded-xl bg-neutral-100 p-3 dark:bg-neutral-800",a?"flex-col items-start p-5":"flex-col sm:flex-row sm:items-center"),children:[_jsxruntime.jsx.call(void 0, _lucidereact.Lock,{className:_chunkDOJICJCQjs.g.call(void 0, "shrink-0 text-neutral-500 dark:text-neutral-400",a?"size-6":"hidden size-5 sm:block"),"aria-hidden":"true"}),_jsxruntime.jsxs.call(void 0, "div",{className:"min-w-0 flex-1",children:[_jsxruntime.jsx.call(void 0, "p",{className:_chunkDOJICJCQjs.g.call(void 0, "font-semibold",a?"text-lg":"text-sm"),children:g}),_jsxruntime.jsx.call(void 0, "p",{className:"mt-0.5 text-sm text-neutral-600 dark:text-neutral-300",children:l}),e.welcome&&_jsxruntime.jsx.call(void 0, "p",{className:"mt-3 whitespace-pre-wrap text-sm",children:e.welcome}),c&&_jsxruntime.jsx.call(void 0, "p",{role:"alert",className:"mt-2 text-sm text-red-700 dark:text-red-400",children:r.buyError})]}),w&&_jsxruntime.jsx.call(void 0, "button",{type:"button",className:_chunkDOJICJCQjs.g.call(void 0, de,"shrink-0"),disabled:d,"aria-busy":d||void 0,onClick:async()=>{u(!0),h(!1);try{await n(e)}catch (e6){h(!0)}finally{u(!1)}},children:d?r.buying:b})]})}function pt(e,t,r,n){return t?n.you:r==="thread"?n.creator:e.authorEmail.split("@")[0]||n.creator}function mt({conversation:e,texts:t,locale:r,kind:n,onReport:a,onEdit:d}){let u=_react.useRef.call(void 0, null),c=_react.useRef.call(void 0, !0),h=e.messages.length,g=_optionalChain([e, 'access', _6 => _6.messages, 'access', _7 => _7[h-1], 'optionalAccess', _8 => _8.id]);return _react.useLayoutEffect.call(void 0, ()=>{let l=u.current;l&&c.current&&(l.scrollTop=l.scrollHeight)},[h,g]),_jsxruntime.jsxs.call(void 0, "div",{ref:u,role:"log","aria-live":"polite","aria-relevant":"additions",onScroll:l=>{let b=l.currentTarget;c.current=b.scrollHeight-b.scrollTop-b.clientHeight<80},className:"flex flex-1 flex-col gap-3 overflow-y-auto overscroll-contain px-3 py-4 sm:px-4",children:[e.hasMore&&_jsxruntime.jsx.call(void 0, "button",{type:"button",onClick:()=>{c.current=!1,e.loadOlder()},disabled:e.loadingOlder,className:_chunkDOJICJCQjs.g.call(void 0, H,"self-center text-xs"),children:e.loadingOlder?t.loading:t.loadOlder}),h===0&&_jsxruntime.jsxs.call(void 0, "div",{className:"m-auto max-w-sm text-center","data-testid":"chat-empty",children:[_jsxruntime.jsx.call(void 0, "p",{className:"text-sm font-medium",children:t.noMessagesYet}),_jsxruntime.jsx.call(void 0, "p",{className:"mt-1 text-sm text-neutral-600 dark:text-neutral-400",children:n==="channel"?t.emptyChannel:t.emptyThread}),_optionalChain([e, 'access', _9 => _9.channel, 'optionalAccess', _10 => _10.welcome])&&_jsxruntime.jsx.call(void 0, "p",{className:"mt-3 whitespace-pre-wrap text-sm",children:e.channel.welcome})]}),e.messages.map(l=>_jsxruntime.jsx.call(void 0, ht,{message:l,mine:l.authorEmail.toLowerCase()===e.me,kind:n,texts:t,locale:r,onDelete:()=>e.deleteMessage(l.id),onReport:()=>a(l.id),onRetry:()=>void e.retry(l.id),onDiscard:()=>e.discard(l.id),onEdit:()=>d(l)},l.id))]})}function ht({message:e,mine:t,kind:r,texts:n,locale:a,onDelete:d,onReport:u,onRetry:c,onDiscard:h,onEdit:g}){let[l,b]=_react.useState.call(void 0, !1),[w,P]=_react.useState.call(void 0, !1),x=e.local;if(e.system)return _jsxruntime.jsxs.call(void 0, "div",{"data-message-id":e.id,className:"mx-auto max-w-md text-center text-xs text-neutral-600 dark:text-neutral-400",children:[_jsxruntime.jsx.call(void 0, "span",{className:"font-medium",children:n.systemLabel}),e.body&&_jsxruntime.jsx.call(void 0, "p",{className:"mt-0.5 whitespace-pre-wrap",children:e.body})]});let T=_optionalChain([x, 'optionalAccess', _11 => _11.state])==="rejected"||_optionalChain([x, 'optionalAccess', _12 => _12.state])==="failed",N=_optionalChain([x, 'optionalAccess', _13 => _13.state])==="pending"||_optionalChain([x, 'optionalAccess', _14 => _14.state])==="unconfirmed",j=!x&&!e.deleted;return _jsxruntime.jsxs.call(void 0, "div",{"data-message-id":e.id,"data-state":_nullishCoalesce(_optionalChain([x, 'optionalAccess', _15 => _15.state]), () => ((e.deleted?"deleted":"stored"))),className:_chunkDOJICJCQjs.g.call(void 0, "group flex max-w-[85%] flex-col gap-1 sm:max-w-[75%]",t?"items-end self-end":"items-start self-start"),children:[_jsxruntime.jsxs.call(void 0, "div",{className:_chunkDOJICJCQjs.g.call(void 0, "flex items-end gap-1",t&&"flex-row-reverse"),children:[_jsxruntime.jsx.call(void 0, "div",{className:_chunkDOJICJCQjs.g.call(void 0, "min-w-0 rounded-2xl px-3.5 py-2 text-sm leading-relaxed",e.deleted?"border border-dashed border-neutral-300 bg-transparent italic text-neutral-500 dark:border-neutral-700 dark:text-neutral-400":t?"bg-neutral-900 text-white dark:bg-neutral-100 dark:text-neutral-900":"bg-neutral-100 text-neutral-900 dark:bg-neutral-800 dark:text-neutral-50",N&&"opacity-70",T&&"border border-red-600 dark:border-red-400"),children:e.deleted?n.deletedPlaceholder:_jsxruntime.jsxs.call(void 0, _jsxruntime.Fragment,{children:[_jsxruntime.jsx.call(void 0, "p",{className:"whitespace-pre-wrap break-words",children:e.body}),e.attachmentKey&&_jsxruntime.jsxs.call(void 0, "span",{className:"mt-1 inline-flex items-center gap-1 text-xs opacity-80",children:[_jsxruntime.jsx.call(void 0, _lucidereact.Paperclip,{className:"size-3.5","aria-hidden":"true"}),n.attachment]})]})}),j&&_jsxruntime.jsx.call(void 0, "button",{type:"button","aria-label":n.messageActions,"aria-expanded":l,onClick:()=>{b(y=>!y),P(!1)},className:_chunkDOJICJCQjs.g.call(void 0, "inline-flex size-11 shrink-0 items-center justify-center rounded-md text-neutral-500 opacity-100 hover:bg-neutral-100 sm:opacity-0 sm:group-hover:opacity-100 sm:focus-visible:opacity-100 dark:text-neutral-400 dark:hover:bg-neutral-800",l&&"sm:opacity-100",xe),children:_jsxruntime.jsx.call(void 0, _lucidereact.MoreHorizontal,{className:"size-4","aria-hidden":"true"})})]}),_jsxruntime.jsxs.call(void 0, "p",{className:"flex items-center gap-1.5 px-1 text-[11px] text-neutral-500 dark:text-neutral-400",children:[e.pinned&&_jsxruntime.jsxs.call(void 0, "span",{className:"inline-flex items-center gap-0.5",children:[_jsxruntime.jsx.call(void 0, _lucidereact.Pin,{className:"size-3","aria-hidden":"true"}),n.pinned]}),_jsxruntime.jsx.call(void 0, "span",{children:pt(e,t,r,n)}),_jsxruntime.jsx.call(void 0, "span",{"aria-hidden":"true",children:"\xB7"}),N?_jsxruntime.jsxs.call(void 0, "span",{className:"inline-flex items-center gap-1",children:[_jsxruntime.jsx.call(void 0, _lucidereact.Clock,{className:"size-3","aria-hidden":"true"}),_optionalChain([x, 'optionalAccess', _16 => _16.state])==="pending"?n.pending:n.notConfirmed]}):_jsxruntime.jsx.call(void 0, "time",{dateTime:e.createdAt,children:le(e.createdAt,a)})]}),T&&_jsxruntime.jsxs.call(void 0, "div",{role:"alert",className:_chunkDOJICJCQjs.g.call(void 0, "flex flex-col gap-1",t?"items-end":"items-start"),children:[_jsxruntime.jsxs.call(void 0, "p",{className:"flex items-start gap-1 text-xs text-red-700 dark:text-red-400",children:[_jsxruntime.jsx.call(void 0, _lucidereact.AlertCircle,{className:"mt-px size-3.5 shrink-0","aria-hidden":"true"}),Ae(n,_nullishCoalesce(_optionalChain([x, 'optionalAccess', _17 => _17.reason]), () => ("")),_optionalChain([x, 'optionalAccess', _18 => _18.retryAfter]))]}),_jsxruntime.jsxs.call(void 0, "div",{className:"flex flex-wrap gap-1",children:[_optionalChain([x, 'optionalAccess', _19 => _19.state])==="failed"||_optionalChain([x, 'optionalAccess', _20 => _20.reason])==="cooldown"?_jsxruntime.jsx.call(void 0, "button",{type:"button",className:_chunkDOJICJCQjs.g.call(void 0, H,"text-xs"),onClick:c,children:n.retrySend}):_jsxruntime.jsx.call(void 0, "button",{type:"button",className:_chunkDOJICJCQjs.g.call(void 0, H,"text-xs"),onClick:g,children:n.editMessage}),_jsxruntime.jsx.call(void 0, "button",{type:"button",className:_chunkDOJICJCQjs.g.call(void 0, H,"text-xs"),onClick:h,children:n.dismiss})]})]}),l&&j&&_jsxruntime.jsx.call(void 0, "div",{className:"flex flex-wrap gap-1",children:t?_jsxruntime.jsx.call(void 0, "button",{type:"button",className:_chunkDOJICJCQjs.g.call(void 0, H,"text-xs text-red-700 dark:text-red-400"),onClick:async()=>{if(!w){P(!0);return}b(!1),await d().catch(()=>{})},children:w?n.deleteConfirm:n.deleteMessage}):_jsxruntime.jsx.call(void 0, "button",{type:"button",className:_chunkDOJICJCQjs.g.call(void 0, H,"text-xs"),onClick:()=>{b(!1),u()},children:n.reportMessage})})]})}function gt(e,t,r){if(t==="thread"&&_optionalChain([e, 'access', _21 => _21.thread, 'optionalAccess', _22 => _22.composerLocked]))return r.composerExpired;if(t==="channel"&&e.channel){if(e.channel.role==="muted")return r.composerMuted;if(e.channel.whoCanPost==="creator"&&e.channel.role!=="creator")return r.composerCreatorOnly}}function ft({conversation:e,texts:t,kind:r,draft:n,setDraft:a}){let d=_react.useId.call(void 0, ),u=_react.useRef.call(void 0, null),c=gt(e,r,t);if(_react.useLayoutEffect.call(void 0, ()=>{let l=u.current;l&&(l.style.height="auto",l.style.height=`${Math.min(l.scrollHeight,160)}px`)},[n]),c)return _jsxruntime.jsx.call(void 0, "p",{"data-testid":"chat-composer-blocked",className:"border-t border-neutral-200 px-4 py-3 text-sm text-neutral-600 dark:border-neutral-800 dark:text-neutral-400",children:c});let h=l=>{_optionalChain([l, 'optionalAccess', _23 => _23.preventDefault, 'call', _24 => _24()]);let b=n.trim();b&&(a(""),e.send(b))},g=l=>{l.key==="Enter"&&!l.shiftKey&&!l.nativeEvent.isComposing&&(l.preventDefault(),h())};return _jsxruntime.jsxs.call(void 0, "form",{onSubmit:h,className:"border-t border-neutral-200 px-3 pb-3 pt-2 dark:border-neutral-800",children:[e.messages.length===0&&_jsxruntime.jsx.call(void 0, "p",{className:"pb-2 text-xs text-neutral-500 dark:text-neutral-400",children:t.privacyNote}),_jsxruntime.jsxs.call(void 0, "div",{className:"flex items-end gap-2",children:[_jsxruntime.jsx.call(void 0, "label",{htmlFor:d,className:"sr-only",children:t.composerLabel}),_jsxruntime.jsx.call(void 0, "textarea",{id:d,ref:u,rows:1,value:n,onChange:l=>a(l.target.value),onKeyDown:g,placeholder:t.composerPlaceholder,className:"max-h-40 min-h-11 flex-1 resize-none rounded-xl border border-neutral-300 bg-white px-3 py-2.5 text-sm text-neutral-900 placeholder:text-neutral-500 focus-visible:border-neutral-500 focus-visible:outline-none dark:border-neutral-700 dark:bg-neutral-950 dark:text-neutral-50 dark:placeholder:text-neutral-400"}),_jsxruntime.jsx.call(void 0, "button",{type:"submit","aria-label":t.send,disabled:n.trim().length===0,className:_chunkDOJICJCQjs.g.call(void 0, de,"w-11 px-0"),children:_jsxruntime.jsx.call(void 0, _lucidereact.SendHorizontal,{className:"size-5","aria-hidden":"true"})})]})]})}var yt=["spam","abuse","illegal","other"];function bt({texts:e,messageId:t,onCancel:r,onSubmit:n}){let[a,d]=_react.useState.call(void 0, "spam"),[u,c]=_react.useState.call(void 0, ""),[h,g]=_react.useState.call(void 0, !1),[l,b]=_react.useState.call(void 0, !1),w=_react.useId.call(void 0, ),P={spam:e.reasonSpam,abuse:e.reasonAbuse,illegal:e.reasonIllegal,other:e.reasonOther};return _jsxruntime.jsxs.call(void 0, "form",{"data-testid":"chat-report",className:"flex flex-col gap-3 border-t border-neutral-200 p-4 dark:border-neutral-800",onSubmit:async x=>{x.preventDefault(),g(!0),b(!1);try{await n(a,u.trim())}catch (e7){b(!0)}finally{g(!1)}},children:[_jsxruntime.jsx.call(void 0, "p",{className:"text-sm font-semibold",children:t?e.reportTitle:e.reportConversationTitle}),_jsxruntime.jsxs.call(void 0, "fieldset",{className:"flex flex-col gap-1",children:[_jsxruntime.jsx.call(void 0, "legend",{className:"mb-1 text-xs text-neutral-600 dark:text-neutral-400",children:e.reportReason}),yt.map(x=>_jsxruntime.jsxs.call(void 0, "label",{className:"flex min-h-9 items-center gap-2 text-sm",children:[_jsxruntime.jsx.call(void 0, "input",{type:"radio",name:"chat-report-reason",value:x,checked:a===x,onChange:()=>d(x),className:"size-4 accent-neutral-900 dark:accent-white"}),P[x]]},x))]}),_jsxruntime.jsxs.call(void 0, "div",{className:"flex flex-col gap-1",children:[_jsxruntime.jsx.call(void 0, "label",{htmlFor:w,className:"text-xs text-neutral-600 dark:text-neutral-400",children:e.reportNote}),_jsxruntime.jsx.call(void 0, "textarea",{id:w,rows:2,maxLength:1e3,value:u,onChange:x=>c(x.target.value),className:"resize-none rounded-xl border border-neutral-300 bg-white px-3 py-2 text-sm focus-visible:border-neutral-500 focus-visible:outline-none dark:border-neutral-700 dark:bg-neutral-950"})]}),l&&_jsxruntime.jsx.call(void 0, "p",{role:"alert",className:"text-sm text-red-700 dark:text-red-400",children:e.reportError}),_jsxruntime.jsxs.call(void 0, "div",{className:"flex flex-wrap justify-end gap-2",children:[_jsxruntime.jsx.call(void 0, "button",{type:"button",className:H,onClick:r,children:e.reportCancel}),_jsxruntime.jsx.call(void 0, "button",{type:"submit",className:de,disabled:h,"aria-busy":h||void 0,children:e.reportSend})]})]})}var kt=()=>Promise.resolve().then(() => _interopRequireWildcard(require("@nats-io/nats-core")));function we(e){let t=_nullishCoalesce(e.pollIntervalMs, () => (8e3)),r=_nullishCoalesce(e.retryMs, () => (6e4)),n=_nullishCoalesce(e.loadNats, () => (kt)),a=`.${e.kind}.${e.id}`,d=!1,u,c="",h,g,l,b=()=>{h!=null&&clearInterval(h),h=void 0},w=()=>{d||(e.onMode("polling"),h==null&&(h=setInterval(()=>{e.poll().catch(()=>{})},t)),g==null&&(g=setTimeout(()=>{g=void 0,x()},r)))},P=T=>{l!=null&&clearTimeout(l);let N=Date.parse(T);if(!Number.isFinite(N))return;let j=Math.max(5e3,N-Date.now()-6e4);l=setTimeout(async()=>{if(!d)try{let y=await e.client.realtimeToken({fresh:!0});c=y.jwt,P(y.expiresAt)}catch (e8){}},j)};async function x(){if(!d){if(typeof WebSocket>"u"){w();return}e.onMode("connecting");try{let T=await e.client.realtimeToken(),N=T.subjects.find(A=>A.endsWith(a));if(N||(T=await e.client.realtimeToken({fresh:!0}),N=T.subjects.find(A=>A.endsWith(a))),!N||!T.jwt)throw new Error("subject not granted");c=T.jwt;let j=await n();if(d)return;let y=e.realtimeUrl?[e.realtimeUrl]:T.servers.length>0?T.servers:[fe],S=await j.wsconnect({servers:y,authenticator:j.jwtAuthenticator(()=>c),name:"bitsnap-react/chat",reconnect:!0,maxReconnectAttempts:5});if(d){S.close().catch(()=>{});return}u=S;let I=new TextDecoder;S.subscribe(N,{callback:(A,K)=>{if(!A)try{let p=ye(JSON.parse(I.decode(K.data)));p&&e.onEvent(p)}catch (e9){}}}),S.closed().then(()=>{u===S&&(u=void 0,w())}),P(T.expiresAt),b(),e.onMode("live"),e.poll().catch(()=>{})}catch (e10){w()}}}return x(),()=>{d=!0,b(),g!=null&&clearTimeout(g),l!=null&&clearTimeout(l);let T=u;u=void 0,T&&T.close().catch(()=>{})}}var ve=50,J={status:"loading",messages:[],hasMore:!1,loadingOlder:!1,live:"off"};function xt(){let e=globalThis.crypto;if(e&&typeof e.randomUUID=="function")return e.randomUUID();let t=new Uint8Array(16);if(e&&typeof e.getRandomValues=="function")e.getRandomValues(t);else for(let n=0;n<16;n++)t[n]=Math.floor(Math.random()*256);t[6]=t[6]&15|64,t[8]=t[8]&63|128;let r=Array.from(t,n=>n.toString(16).padStart(2,"0")).join("");return`${r.slice(0,8)}-${r.slice(8,12)}-${r.slice(12,16)}-${r.slice(16,20)}-${r.slice(20)}`}function ae(e,t){let r=new Map(e.map(n=>[n.id,n]));for(let n of t){let a=r.get(n.id);if(n.status==="pending"){if(a&&!a.local)continue;r.set(n.id,{...n,local:_nullishCoalesce(_optionalChain([a, 'optionalAccess', _25 => _25.local]), () => ({state:"pending"}))});continue}_optionalChain([a, 'optionalAccess', _26 => _26.local])&&a.local.state!=="pending"&&a.local.state!=="unconfirmed"||r.set(n.id,{...n,local:void 0})}return[...r.values()].sort((n,a)=>{let d=Date.parse(n.createdAt)||0,u=Date.parse(a.createdAt)||0;return d-u})}function Te(e){if(e.kind==="pack"){if(e.composerLocked)return{reason:"expired",productId:e.productId};if(e.repliesLeft<=0)return{reason:"replies",productId:e.productId}}}function $e(e,t,r){let n=Number(e.data.price_cents);return{reason:t,productId:typeof e.data.product_id=="string"&&e.data.product_id?e.data.product_id:r,priceCents:Number.isFinite(n)&&n>0?n:void 0,welcome:typeof e.data.welcome=="string"?e.data.welcome:void 0}}function pe(e){return e instanceof U?e:new U("internal_error",0)}function me(e){let{client:t,target:r}=e,[n,a]=_react.useState.call(void 0, J),[d,u]=_react.useState.call(void 0, 0),c=_react.useRef.call(void 0, n);c.current=n;let h=_react.useRef.call(void 0, new Set),g=_react.useRef.call(void 0, void 0),l=_react.useRef.call(void 0, void 0),b=r.kind==="thread"?`t:${_nullishCoalesce(r.threadId, () => (""))}:${_nullishCoalesce(r.productId, () => (""))}`:`c:${r.channelId}:${_nullishCoalesce(r.productId, () => (""))}`;_react.useEffect.call(void 0, ()=>{let o=!1;if(l.current=void 0,a(J),t!==null){if(!t){a({...J,status:"error",error:new U("no_token",401)});return}return(async()=>{try{let s=await t.me(),m=s.email.toLowerCase(),f,z,R;if(r.kind==="thread"){if(f=r.threadId?s.threads.find(E=>E.id===r.threadId):s.threads.find(E=>E.productId===r.productId),!f&&r.productId)try{f=await t.openThread(r.productId)}catch(E){let _=pe(E);if(_.code==="locked"||_.status===404){o||a({...J,status:"locked",me:m,lock:$e(_,"no-pack",r.productId)});return}throw _}if(!f)throw new U("not_found",404);R=f.id}else z=s.channels.find(E=>E.id===r.channelId),R=r.channelId;let Z;try{Z=await t.messages(R,{limit:ve})}catch(E){let _=pe(E);if(_.code==="locked"){o||a({...J,status:"locked",me:m,thread:f,channel:z,threadId:R,lock:$e(_,r.kind==="channel"?"no-access":"no-pack",_nullishCoalesce(_nullishCoalesce(r.productId, () => (_optionalChain([z, 'optionalAccess', _27 => _27.productId]))), () => (_optionalChain([f, 'optionalAccess', _28 => _28.productId]))))});return}throw _}if(o)return;a({...J,status:"ready",me:m,thread:f,channel:z,threadId:R,lock:f?Te(f):void 0,messages:ae([],Z.messages),hasMore:Z.hasMore})}catch(s){o||a({...J,status:"error",error:pe(s)})}})(),()=>{o=!0}}},[t,b,d]);let w=_react.useCallback.call(void 0, ()=>{t&&(g.current&&clearTimeout(g.current),g.current=setTimeout(async()=>{try{let o=await t.me();a(s=>{if(s.status!=="ready")return s;let m=s.thread&&o.threads.find(z=>z.id===s.thread.id),f=s.channel&&o.channels.find(z=>z.id===s.channel.id);return{...s,thread:_nullishCoalesce(m, () => (s.thread)),channel:_nullishCoalesce(f, () => (s.channel)),lock:m?Te(m):s.lock}})}catch (e11){}},1500))},[t]),P=_react.useCallback.call(void 0, async()=>{let{threadId:o}=c.current;if(!t||!o)return;let s=await t.messages(o,{limit:ve});a(m=>m.threadId===o?{...m,messages:ae(m.messages,s.messages)}:m)},[t]),x=_react.useCallback.call(void 0, o=>{a(s=>{switch(o.type){case"message.created":return{...s,messages:ae(s.messages,[o.message])};case"message.rejected":return{...s,messages:s.messages.map(m=>m.id===o.id?{...m,local:{state:"rejected",reason:o.reason||"rejected"}}:m)};case"message.deleted":return{...s,messages:s.messages.map(m=>m.id===o.id?{...m,deleted:!0,body:"",attachmentKey:void 0}:m)};case"message.pinned":case"message.unpinned":return{...s,messages:s.messages.map(m=>m.id===o.id?{...m,pinned:o.type==="message.pinned"}:m)}}}),o.type==="message.created"&&!o.message.system&&o.message.authorEmail.toLowerCase()!==c.current.me&&w()},[w]),N=n.status==="ready"?n.threadId:void 0;_react.useEffect.call(void 0, ()=>{if(!t||!N)return;let o=we({client:t,kind:r.kind,id:N,onEvent:x,onMode:s=>a(m=>({...m,live:s})),poll:P,pollIntervalMs:e.pollIntervalMs,realtimeUrl:e.realtimeUrl,loadNats:e.loadNats});return()=>{o(),a(s=>({...s,live:"off"}))}},[t,N,x,P]),_react.useEffect.call(void 0, ()=>{if(!t||!n.threadId||n.status!=="ready")return;let o=[...n.messages].reverse().find(s=>!s.local&&s.authorEmail.toLowerCase()!==n.me);!o||l.current===o.id||(l.current=o.id,t.markRead(n.threadId,o.id).catch(()=>{}))},[t,n.threadId,n.status,n.messages,n.me]),_react.useEffect.call(void 0, ()=>()=>{for(let o of h.current)clearTimeout(o);g.current&&clearTimeout(g.current)},[]);let j=(o,s)=>a(m=>({...m,messages:m.messages.map(f=>f.id===o?s(f):f)})),y=_react.useCallback.call(void 0, async(o,s)=>{let m=o.trim(),{threadId:f,me:z}=c.current;if(!t||!f||!m)return;let R=_nullishCoalesce(s, () => (xt())),Z={id:R,threadId:f,authorEmail:_nullishCoalesce(z, () => ("")),body:m,createdAt:new Date().toISOString(),pinned:!1,deleted:!1,system:!1,status:"pending",local:{state:"pending"}};a(E=>({...E,messages:[...E.messages,Z]}));try{let E=await t.send(f,{body:m,clientId:R});a(B=>({...B,messages:ae(B.messages,[{...E.message,id:R}]),thread:B.thread?{...B.thread,...E.thread,id:B.thread.id}:B.thread,lock:B.thread?Te({...B.thread,...E.thread,id:B.thread.id}):B.lock}));let _=setTimeout(()=>{h.current.delete(_),j(R,B=>_optionalChain([B, 'access', _29 => _29.local, 'optionalAccess', _30 => _30.state])==="pending"?{...B,local:{state:"unconfirmed"}}:B)},_nullishCoalesce(e.confirmTimeoutMs, () => (45e3)));h.current.add(_)}catch(E){let _=pe(E),B=_.code==="network"||_.code==="unavailable"||_.status>=500;j(R,Ze=>({...Ze,local:{state:B?"failed":"rejected",reason:_.code,retryAfter:_.retryAfter,keepId:B||s!=null}}))}},[t,e.confirmTimeoutMs]),S=_react.useCallback.call(void 0, o=>{a(s=>({...s,messages:s.messages.filter(m=>m.id!==o)}))},[]),I=_react.useCallback.call(void 0, async o=>{let s=c.current.messages.find(f=>f.id===o);if(!s)return;let m=_optionalChain([s, 'access', _31 => _31.local, 'optionalAccess', _32 => _32.state])!=="rejected"||s.local.keepId===!0;S(o),await y(s.body,m?o:void 0)},[S,y]),A=_react.useCallback.call(void 0, async o=>{let{threadId:s}=c.current,m=c.current.messages.find(f=>f.id===o);if(!(!t||!s||!m)){j(o,f=>({...f,deleted:!0,body:"",attachmentKey:void 0}));try{await t.deleteMessage(s,o)}catch(f){throw j(o,()=>m),f}}},[t]),K=_react.useCallback.call(void 0, async o=>{let{threadId:s}=c.current;!t||!s||await t.report({threadId:s,...o})},[t]),p=_react.useCallback.call(void 0, async o=>{let{threadId:s}=c.current;!t||!s||(await t.mute(s,o),a(m=>m.thread?{...m,thread:{...m.thread,muted:o}}:m))},[t]),L=_react.useCallback.call(void 0, async()=>{let{threadId:o,messages:s,hasMore:m,loadingOlder:f}=c.current,z=s.find(R=>!R.local);if(!(!t||!o||!m||f||!z)){a(R=>({...R,loadingOlder:!0}));try{let R=await t.messages(o,{before:z.id,limit:ve});a(Z=>({...Z,loadingOlder:!1,hasMore:R.hasMore,messages:ae(Z.messages,R.messages)}))}catch (e12){a(R=>({...R,loadingOlder:!1}))}}},[t]),G=_react.useCallback.call(void 0, ()=>u(o=>o+1),[]);return{...n,send:y,retry:I,discard:S,deleteMessage:A,report:K,setMuted:p,loadOlder:L,reload:G}}function We(e){let[t,r]=_react.useState.call(void 0, null),n=_nullishCoalesce(e.host, () => (_chunkMDAFPGPAjs.b.call(void 0, ).host));_react.useEffect.call(void 0, ()=>{e.client||e.token||r(_chunkMDAFPGPAjs.i.call(void 0, e.projectID,n))},[e.client,e.token,e.projectID,n]);let a=_nullishCoalesce(e.token, () => (t)),d=_nullishCoalesce(e.chatProjectID, () => (e.projectID));return _react.useMemo.call(void 0, ()=>{if(e.client)return e.client;if(a===null)return null;if(a)return te({projectId:d,token:a,baseUrl:e.apiUrl})},[e.client,a,d,e.apiUrl])}function He(e){return async t=>{let r=_nullishCoalesce(e.buyProductId, () => (t.productId));if(!r)return;let n={productId:r,reason:t.reason,priceCents:t.priceCents};if(e.onBuy){await e.onBuy(n);return}await ee({projectID:e.projectID,productId:r,name:e.title,priceCents:t.priceCents,host:e.host})}}function Ie(e){let t=We(e),r=_nullishCoalesce(e.locale, () => (_chunkQ337IQNAjs.f.call(void 0, ))),n=_react.useMemo.call(void 0, ()=>Q(e.texts,r),[e.texts,r]),a=me({client:t,target:{kind:"thread",threadId:e.threadId,productId:e.productId},pollIntervalMs:e.pollIntervalMs,realtimeUrl:e.realtimeUrl,loadNats:e.loadNats}),d=He(e);return _jsxruntime.jsx.call(void 0, "div",{className:"bitsnap-react h-full",children:_jsxruntime.jsx.call(void 0, Ce,{conversation:a,texts:n,locale:r,kind:"thread",title:e.title,onBack:e.onBack,onBuy:d,className:e.className})})}function je(e){let t=We(e),r=_nullishCoalesce(e.locale, () => (_chunkQ337IQNAjs.f.call(void 0, ))),n=_react.useMemo.call(void 0, ()=>Q(e.texts,r),[e.texts,r]),a=me({client:t,target:{kind:"channel",channelId:e.channelId,productId:e.productId},pollIntervalMs:e.pollIntervalMs,realtimeUrl:e.realtimeUrl,loadNats:e.loadNats}),d=He(e);return _jsxruntime.jsx.call(void 0, "div",{className:"bitsnap-react h-full",children:_jsxruntime.jsx.call(void 0, Ce,{conversation:a,texts:n,locale:r,kind:"channel",title:e.title,onBack:e.onBack,onBuy:d,className:e.className})})}var Mt=_react.lazy.call(void 0, ()=>Promise.resolve().then(() => _interopRequireWildcard(require("./BitsnapCart-Q2HER6GU.js")))),Ke=e=>e.productType===5||e.productType===6;function Ge(e,t){let r=[...new Set(e.filter(Ke).map(n=>n.projectId).filter(Boolean))];return r.length>0?r:t?[t]:[]}function Pt(e){let t=new Map;for(let r of e)Ke(r)&&r.projectId&&r.chatProjectId&&t.set(r.projectId,r.chatProjectId);return t}function qe({accessToken:e,products:t,chatApiUrl:r,projectID:n,host:a,selection:d,onSelect:u,locale:c=_chunkQ337IQNAjs.f.call(void 0, ),texts:h}){let g=_react.useMemo.call(void 0, ()=>Q(h,c),[h,c]),l=_react.useMemo.call(void 0, ()=>Ge(t,n),[t,n]),b=_react.useMemo.call(void 0, ()=>Pt(t),[t]),w=_react.useMemo.call(void 0, ()=>{let o=new Map;for(let s of l)o.set(s,te({projectId:_nullishCoalesce(b.get(s), () => (s)),token:e,baseUrl:r}));return o},[l,b,e,r]),[P,x]=_react.useState.call(void 0, {}),[T,N]=_react.useState.call(void 0, 0),j=`${_nullishCoalesce(d.chatProject, () => (""))}:${_nullishCoalesce(d.thread, () => (""))}:${_nullishCoalesce(d.channel, () => (""))}`;_react.useEffect.call(void 0, ()=>{let o=!1;for(let[s,m]of w)x(f=>_optionalChain([f, 'access', _33 => _33[s], 'optionalAccess', _34 => _34.status])==="ready"?f:{...f,[s]:{status:"loading"}}),m.me().then(f=>!o&&x(z=>({...z,[s]:{status:"ready",me:f}})),f=>!o&&x(z=>({...z,[s]:{status:"error",error:f instanceof U?f:new U("internal_error",0)}})));return()=>{o=!0}},[w,T,j]);let y=_react.useMemo.call(void 0, ()=>{let o=new Map;for(let s of t)o.set(s.productId,s);return o},[t]),[S,I]=_react.useState.call(void 0, ),A=o=>async s=>{I(o),await ee({projectID:o,productId:s.productId,name:_optionalChain([y, 'access', _35 => _35.get, 'call', _36 => _36(s.productId), 'optionalAccess', _37 => _37.productName]),priceCents:s.priceCents,host:a})},K=d.chatProject?w.get(d.chatProject):void 0,p=!!(K&&(d.thread||d.channel)),L=()=>u({}),G=null;if(p&&K&&d.chatProject){let o=d.chatProject,s=P[o],m=_optionalChain([s, 'optionalAccess', _38 => _38.status])==="ready"?s.me:void 0;if(d.thread){let f=_optionalChain([m, 'optionalAccess', _39 => _39.threads, 'access', _40 => _40.find, 'call', _41 => _41(z=>z.id===d.thread)]);G=_jsxruntime.jsx.call(void 0, Ie,{projectID:o,client:K,threadId:d.thread,title:_optionalChain([f, 'optionalAccess', _42 => _42.productId])&&_optionalChain([y, 'access', _43 => _43.get, 'call', _44 => _44(f.productId), 'optionalAccess', _45 => _45.productName])||void 0,locale:c,texts:h,onBack:L,onBuy:A(o)},`t:${o}:${d.thread}`)}else if(d.channel){let f=_optionalChain([m, 'optionalAccess', _46 => _46.entitlements, 'access', _47 => _47.channels, 'access', _48 => _48.find, 'call', _49 => _49(z=>z.channelId===d.channel)]);G=_jsxruntime.jsx.call(void 0, je,{projectID:o,client:K,channelId:d.channel,productId:_optionalChain([f, 'optionalAccess', _50 => _50.productId]),locale:c,texts:h,onBack:L,onBuy:A(o)},`c:${o}:${d.channel}`)}}return _jsxruntime.jsxs.call(void 0, "div",{className:"flex min-h-0 flex-1 flex-col",children:[_jsxruntime.jsxs.call(void 0, "div",{className:_chunkDOJICJCQjs.g.call(void 0, p&&"hidden md:block"),children:[_jsxruntime.jsx.call(void 0, "h3",{className:"text-2xl",children:g.inboxHeading}),_jsxruntime.jsx.call(void 0, "p",{className:"text-sm text-neutral-500 dark:text-neutral-400",children:g.inboxIntro})]}),_jsxruntime.jsxs.call(void 0, "div",{className:"mt-6 grid min-h-0 flex-1 gap-4 md:grid-cols-[minmax(16rem,22rem)_1fr]",children:[_jsxruntime.jsx.call(void 0, "div",{className:_chunkDOJICJCQjs.g.call(void 0, "min-w-0",p&&"hidden md:block"),children:_jsxruntime.jsx.call(void 0, zt,{projects:l,loads:P,clients:w,products:t,texts:g,locale:c,selection:d,onSelect:u,onRetry:()=>N(o=>o+1)})}),_jsxruntime.jsx.call(void 0, "div",{className:_chunkDOJICJCQjs.g.call(void 0, "min-h-[32rem] min-w-0 md:h-[calc(100dvh-10rem)]",!p&&"hidden md:flex"),children:_nullishCoalesce(G, () => (_jsxruntime.jsx.call(void 0, "div",{className:"flex h-full w-full items-center justify-center rounded-xl border border-dashed border-neutral-300 p-6 text-sm text-neutral-600 dark:border-neutral-700 dark:text-neutral-400",children:g.selectConversation})))})]}),S&&_jsxruntime.jsx.call(void 0, _react.Suspense,{fallback:null,children:_jsxruntime.jsx.call(void 0, Mt,{projectID:S,locale:c})})]})}var Ye="flex min-h-11 w-full min-w-0 items-start gap-3 rounded-xl p-3 text-left transition-colors focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-neutral-500";function zt({projects:e,loads:t,clients:r,products:n,texts:a,locale:d,selection:u,onSelect:c,onRetry:h}){let[g,l]=_react.useState.call(void 0, ),[b,w]=_react.useState.call(void 0, ),P=new Map(n.map(y=>[y.productId,y])),x=e.length>1,T=e.map(y=>_nullishCoalesce(t[y], () => ({status:"loading"})));if(T.length>0&&T.every(y=>y.status==="loading"))return _jsxruntime.jsx.call(void 0, "div",{role:"status","aria-busy":"true","aria-label":a.loading,className:"flex flex-col gap-2",children:[0,1,2].map(y=>_jsxruntime.jsx.call(void 0, "div",{"aria-hidden":"true",className:"h-20 rounded-xl bg-white motion-safe:animate-pulse dark:bg-neutral-800"},y))});if(T.length===0||T.every(y=>y.status==="error"))return _jsxruntime.jsxs.call(void 0, "div",{role:"alert",className:"flex flex-col items-start gap-3","data-testid":"chat-inbox-error",children:[_jsxruntime.jsx.call(void 0, "p",{className:"text-sm text-neutral-700 dark:text-neutral-300",children:a.inboxError}),_jsxruntime.jsx.call(void 0, "button",{type:"button",onClick:h,className:"inline-flex min-h-11 items-center rounded-md bg-neutral-900 px-4 text-sm font-medium text-white hover:bg-neutral-800 focus-visible:outline-2 focus-visible:outline-current dark:bg-white dark:text-neutral-900",children:a.retry})]});let N=[],j=[];for(let y of e){let S=t[y];if(_optionalChain([S, 'optionalAccess', _51 => _51.status])!=="ready")continue;let{me:I}=S,A=x?_optionalChain([n, 'access', _52 => _52.find, 'call', _53 => _53(p=>p.projectId===y), 'optionalAccess', _54 => _54.projectName]):void 0;for(let p of I.threads){let L=p.productId?P.get(p.productId):void 0,G=u.chatProject===y&&u.thread===p.id,o=[ne(a,p.repliesLeft,d)];p.expiresAt&&o.push($(p.composerLocked?a.expiredOn:a.expiresOn,{date:re(p.expiresAt,d)})),p.responseHours>0&&o.push($(a.responseHours,{hours:p.responseHours}));let s=p.lastMessage;N.push(_jsxruntime.jsx.call(void 0, "li",{children:_jsxruntime.jsxs.call(void 0, "button",{type:"button","data-thread-id":p.id,"aria-current":G?"true":void 0,onClick:()=>c({chatProject:y,thread:p.id}),className:_chunkDOJICJCQjs.g.call(void 0, Ye,G?"bg-neutral-200 dark:bg-neutral-800":"bg-white hover:bg-neutral-50 dark:bg-neutral-900 dark:hover:bg-neutral-800"),children:[_jsxruntime.jsx.call(void 0, _lucidereact.MessageCircle,{className:"mt-0.5 size-5 shrink-0 text-neutral-500 dark:text-neutral-400","aria-hidden":"true"}),_jsxruntime.jsxs.call(void 0, "span",{className:"flex min-w-0 flex-1 flex-col gap-0.5",children:[_jsxruntime.jsxs.call(void 0, "span",{className:"flex items-baseline gap-2",children:[_jsxruntime.jsx.call(void 0, "span",{className:_chunkDOJICJCQjs.g.call(void 0, "truncate",p.unread>0?"font-semibold":"font-medium"),children:_optionalChain([L, 'optionalAccess', _55 => _55.productName])||a.chatFallbackTitle}),s&&_jsxruntime.jsx.call(void 0, "time",{dateTime:s.createdAt,className:"ml-auto shrink-0 text-xs text-neutral-500 dark:text-neutral-400",children:le(s.createdAt,d)})]}),A&&_jsxruntime.jsx.call(void 0, "span",{className:"truncate text-xs text-neutral-500 dark:text-neutral-400",children:A}),_jsxruntime.jsxs.call(void 0, "span",{className:"flex items-center gap-2",children:[_jsxruntime.jsx.call(void 0, "span",{className:"line-clamp-1 flex-1 text-sm text-neutral-600 dark:text-neutral-300",children:s?s.deleted?a.deletedPlaceholder:s.body:a.noMessagesYet}),p.unread>0&&_jsxruntime.jsx.call(void 0, "span",{"aria-label":$(a.unread,{count:p.unread}),className:"inline-flex min-w-5 shrink-0 items-center justify-center rounded-full bg-neutral-900 px-1.5 text-xs font-semibold text-white tabular-nums dark:bg-white dark:text-neutral-900",children:p.unread})]}),_jsxruntime.jsxs.call(void 0, "span",{className:_chunkDOJICJCQjs.g.call(void 0, "text-xs",p.repliesLeft<=0||p.composerLocked?"text-amber-800 dark:text-amber-300":"text-neutral-500 dark:text-neutral-400"),children:[o.join(" \xB7 "),p.muted&&` \xB7 ${a.mutedBadge}`]})]})]})},`t:${y}:${p.id}`))}for(let p of I.channels){let L=u.chatProject===y&&u.channel===p.id;N.push(_jsxruntime.jsx.call(void 0, "li",{children:_jsxruntime.jsxs.call(void 0, "button",{type:"button","data-channel-id":p.id,"aria-current":L?"true":void 0,onClick:()=>c({chatProject:y,channel:p.id}),className:_chunkDOJICJCQjs.g.call(void 0, Ye,L?"bg-neutral-200 dark:bg-neutral-800":"bg-white hover:bg-neutral-50 dark:bg-neutral-900 dark:hover:bg-neutral-800"),children:[_jsxruntime.jsx.call(void 0, _lucidereact.Hash,{className:"mt-0.5 size-5 shrink-0 text-neutral-500 dark:text-neutral-400","aria-hidden":"true"}),_jsxruntime.jsxs.call(void 0, "span",{className:"flex min-w-0 flex-1 flex-col gap-0.5",children:[_jsxruntime.jsx.call(void 0, "span",{className:"truncate font-medium",children:p.name||a.channelFallbackTitle}),A&&_jsxruntime.jsx.call(void 0, "span",{className:"truncate text-xs text-neutral-500 dark:text-neutral-400",children:A}),_jsxruntime.jsx.call(void 0, "span",{className:"line-clamp-1 text-sm text-neutral-600 dark:text-neutral-300",children:p.topic||a.kindChannel}),p.memberCount>0&&_jsxruntime.jsx.call(void 0, "span",{className:"text-xs text-neutral-500 dark:text-neutral-400",children:$(a.members,{count:p.memberCount})})]})]})},`c:${y}:${p.id}`))}for(let p of I.entitlements.packs){let L=`${y}:${p.productId}`,G=_optionalChain([P, 'access', _56 => _56.get, 'call', _57 => _57(p.productId), 'optionalAccess', _58 => _58.productName])||p.name||a.chatFallbackTitle;j.push(_jsxruntime.jsxs.call(void 0, "li",{className:"flex flex-col gap-2 rounded-xl bg-white p-3 dark:bg-neutral-900 sm:flex-row sm:items-center",children:[_jsxruntime.jsxs.call(void 0, "span",{className:"flex min-w-0 flex-1 flex-col gap-0.5",children:[_jsxruntime.jsx.call(void 0, "span",{className:"truncate font-medium",children:G}),_jsxruntime.jsx.call(void 0, "span",{className:"text-xs text-neutral-500 dark:text-neutral-400",children:[ne(a,p.repliesLeftHint,d),p.expiresAt?$(a.expiresOn,{date:re(p.expiresAt,d)}):""].filter(Boolean).join(" \xB7 ")})]}),_jsxruntime.jsx.call(void 0, "button",{type:"button",disabled:g===L,"aria-busy":g===L||void 0,onClick:async()=>{let o=r.get(y);if(o){l(L),w(void 0);try{let s=await o.openThread(p.productId);c({chatProject:y,thread:s.id})}catch (e13){w(L)}finally{l(void 0)}}},className:"inline-flex min-h-11 shrink-0 items-center justify-center rounded-md bg-neutral-900 px-4 text-sm font-medium text-white hover:bg-neutral-800 disabled:opacity-50 focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-neutral-500 dark:bg-white dark:text-neutral-900 dark:hover:bg-neutral-200",children:g===L?a.loading:a.startChat}),b===L&&_jsxruntime.jsx.call(void 0, "p",{role:"alert",className:"text-xs text-red-700 dark:text-red-400 sm:basis-full",children:a.errorGeneric})]},`p:${L}`))}let K=new Set(I.channels.map(p=>p.id));for(let p of I.entitlements.channels){if(p.channelId&&K.has(p.channelId))continue;let L=_optionalChain([P, 'access', _59 => _59.get, 'call', _60 => _60(p.productId), 'optionalAccess', _61 => _61.productName])||a.channelFallbackTitle;j.push(_jsxruntime.jsxs.call(void 0, "li",{className:"flex flex-col gap-2 rounded-xl bg-white p-3 dark:bg-neutral-900 sm:flex-row sm:items-center",children:[_jsxruntime.jsxs.call(void 0, "span",{className:"flex min-w-0 flex-1 flex-col gap-0.5",children:[_jsxruntime.jsx.call(void 0, "span",{className:"truncate font-medium",children:L}),!p.channelId&&_jsxruntime.jsx.call(void 0, "span",{className:"text-xs text-neutral-500 dark:text-neutral-400",children:a.channelNotReady})]}),p.channelId&&_jsxruntime.jsx.call(void 0, "button",{type:"button",onClick:()=>c({chatProject:y,channel:p.channelId}),className:"inline-flex min-h-11 shrink-0 items-center justify-center rounded-md border border-neutral-300 px-4 text-sm font-medium hover:bg-neutral-50 focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-neutral-500 dark:border-neutral-700 dark:hover:bg-neutral-800",children:a.openChannel})]},`e:${y}:${p.productId}`))}}return N.length===0&&j.length===0?_jsxruntime.jsx.call(void 0, "p",{"data-testid":"chat-inbox-empty",className:"text-sm text-neutral-600 dark:text-neutral-400",children:a.inboxEmpty}):_jsxruntime.jsxs.call(void 0, "div",{className:"flex flex-col gap-6","data-testid":"chat-inbox",children:[N.length>0&&_jsxruntime.jsx.call(void 0, "ul",{className:"flex flex-col gap-2",children:N}),j.length>0&&_jsxruntime.jsxs.call(void 0, "section",{className:"flex flex-col gap-2",children:[_jsxruntime.jsx.call(void 0, "h4",{className:"text-sm font-semibold text-neutral-700 dark:text-neutral-300",children:a.startSection}),_jsxruntime.jsx.call(void 0, "ul",{className:"flex flex-col gap-2",children:j})]})]})}exports.CHAT_TEXT_TABLES = Ee; exports.Channel = je; exports.ChatError = U; exports.ChatThread = Ie; exports.DEFAULT_CHAT_API_URL = ge; exports.DEFAULT_CHAT_REALTIME_URL = fe; exports.PanelMessages = qe; exports.addPackToCart = ee; exports.chatProjects = Ge; exports.createChatClient = te; exports.getChatTexts = Q; exports.parseRealtimeEvent = ye; exports.startLive = we; exports.useConversation = me;
|
|
2
|
+
//# sourceMappingURL=chat.js.map
|
package/dist/chat.js.map
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["/home/emems/.t3/worktrees/bitsnap-react/emems-chat-v1/dist/chat.js","../src/chat/widgets.tsx","../src/chat/buy.ts","../src/chat/types.ts","../src/chat/client.ts"],"names":["addPackToCart","input","addProductToCart","DEFAULT_CHAT_API_URL","DEFAULT_CHAT_REALTIME_URL","ChatError","code","status","data","retry","createChatClient","options","baseUrl","doFetch","args","call","method","path","body","response"],"mappings":"AAAA,y/BAAwC,sDAAiD,+BAA4B,sDAAwC,+BAA4B,+BAA4B,sDAAgD,+BAA4B,8BCApP,MCoB7C,SAAsBA,EAAAA,CAAcC,CAAAA,CAAoC,CACtE,MAAMC,gCAAAA,CAEF,EAAA,CAAID,CAAAA,CAAM,SAAA,CACV,IAAA,kBAAMA,CAAAA,CAAM,IAAA,SAAQ,IAAA,CACpB,KAAA,kBAAOA,CAAAA,CAAM,UAAA,SAAc,GAAA,CAC3B,QAAA,CAAU,EACZ,CAAA,CACA,CAAE,SAAA,CAAWA,CAAAA,CAAM,SAAA,CAAW,IAAA,CAAMA,CAAAA,CAAM,IAAA,CAAM,QAAA,CAAU,CAAA,CAAK,CACjE,CACF,CCvBO,IAAME,EAAAA,CAAuB,yBAAA,CAGvBC,EAAAA,qCACX,oDAAA,CCcK,IAAMC,CAAAA,CAAN,MAAA,QAAwB,KAAM,CAC1B,WAOT,CACEC,CAAAA,CACAC,CAAAA,CACAC,CAAAA,CAAgC,CAAC,CAAA,CACjC,CACA,KAAA,CAAM,CAAA,MAAA,EAASF,CAAI,CAAA,EAAA,EAAKC,CAAM,CAAA,CAAA,CAAG,CAAA,CACjC,IAAA,CAAK,IAAA,CAAO,WAAA,CACZ,IAAA,CAAK,IAAA,CAAOD,CAAAA,CACZ,IAAA,CAAK,MAAA,CAASC,CAAAA,CACd,IAAA,CAAK,IAAA,CAAOC,CAAAA,CACZ,IAAMC,CAAAA,CAAQ,MAAA,CAAOD,CAAAA,CAAK,WAAW,CAAA,CACjC,MAAA,CAAO,QAAA,CAASC,CAAK,CAAA,EAAKA,CAAAA,CAAQ,CAAA,EAAA,CAAG,IAAA,CAAK,UAAA,CAAaA,CAAAA,CAC7D,CACF,CAAA,CA+CO,SAASC,EAAAA,CAAiBC,CAAAA,CAAwC,CACvE,IAAMC,CAAAA,CAAAA,CAAWD,CAAAA,CAAQ,OAAA,EAAWR,EAAAA,CAAAA,CAAsB,OAAA,CAAQ,MAAA,CAAQ,EAAE,CAAA,CACtEU,CAAAA,kBAAUF,CAAAA,CAAQ,KAAA,SAAA,CAAU,CAAA,GAAIG,CAAAA,CAAAA,EAAS,KAAA,CAAM,GAAGA,CAAI,CAAA,GAAA,CAE5D,MAAA,SAAeC,CAAAA,CACbC,CAAAA,CACAC,CAAAA,CACAC,CAAAA,CAC4C,CAC5C,IAAIC,CAAAA,CACJ,GAAI,CACFA,CAAAA,CAAW,MAAMN,CAAAA,CAAQD,CAAAA,CAAUK,CAAAA,CAAM,CACvC,MAAA,CAAAD,CAAAA,CACA,OAAA,CAAS,CACP,aAAA,CAAe,CAAA,OAAA,EAAUL,CAAAA,CAAQ,KAAK,CAAA,CAAA","file":"/home/emems/.t3/worktrees/bitsnap-react/emems-chat-v1/dist/chat.js","sourcesContent":[null,"import { useEffect, useMemo, useState } from \"react\";\nimport { getLocale } from \"../components/checkout/locale\";\nimport { getPanelConfig } from \"../panel/config\";\nimport { getPanelSession } from \"../panel/session-storage\";\nimport { addPackToCart } from \"./buy\";\nimport { createChatClient, type ChatClient } from \"./client\";\nimport { ConversationView } from \"./Conversation\";\nimport type { NatsModule } from \"./realtime\";\nimport { getChatTexts, type ChatTexts } from \"./texts\";\nimport { useConversation, type ConversationLock } from \"./useConversation\";\n\n/** What the lock's buy action gets. */\nexport type ChatBuyRequest = {\n /** The product (or variant) to sell: `buyProductId`, else the locked product. */\n productId: string;\n /** `replies`, `expired`, `no-pack` or `no-access`. */\n reason: ConversationLock[\"reason\"];\n /** Known for a locked channel (from the chat service). */\n priceCents?: number;\n};\n\n/** Props shared by `ChatThread` and `Channel`. */\nexport type ChatWidgetBaseProps = {\n /**\n * Public Bitsnap project id of the shop. The cart uses it, the panel\n * session is looked up with it, and it is the `X-Bitsnap-Project` of the\n * chat service unless `chatProjectID` is given.\n */\n projectID: string;\n /** Project id for the chat service, when it differs from `projectID`. */\n chatProjectID?: string;\n /**\n * Bearer for the chat service: a `bcht_` buyer token from your server\n * (`POST /api/v1/chat/buyer-token`). Defaults to the customer panel session\n * of this browser (after `PanelLogin`).\n */\n token?: string;\n /** Chat service base URL. Defaults to `https://chat.bitsnap.pl`. */\n apiUrl?: string;\n /** NATS WebSocket URL overriding the one of the realtime token. */\n realtimeUrl?: string;\n /** Bitsnap host of the panel session (`setHost`), when not the default. */\n host?: string;\n /** Polling interval in ms while the live connection is down. Default 8000. */\n pollIntervalMs?: number;\n /** Language of the default texts; defaults to the library locale. */\n locale?: string;\n /** Text overrides, whatever the locale. */\n texts?: Partial<ChatTexts>;\n /** Heading of the conversation. */\n title?: string;\n /** Shows a back button in the header. */\n onBack?: () => void;\n /**\n * The lock's \"Kup pakiet\" / \"Kup dostęp\". Default: add the product to the\n * page cart and open it (mount `BitsnapCheckout` on the page). Throw to\n * show the error line.\n */\n onBuy?: (request: ChatBuyRequest) => Promise<void> | void;\n /** The product or variant the buy action sells (e.g. the pack variant). */\n buyProductId?: string;\n className?: string;\n /** A ready client (tests, custom transport). Replaces token and URLs. */\n client?: ChatClient;\n /** @internal Replaces the NATS loader (tests). */\n loadNats?: () => Promise<NatsModule>;\n};\n\nexport type ChatThreadProps = ChatWidgetBaseProps & {\n /** The service product of the pack: opens its thread, creating it if needed. */\n productId?: string;\n /** An existing thread. Give this or `productId`. */\n threadId?: string;\n};\n\nexport type ChannelProps = ChatWidgetBaseProps & {\n /** The channel (its id is also the id of its conversation). */\n channelId: string;\n /** The community product sold by the lock; defaults to the channel's own. */\n productId?: string;\n};\n\n/**\n * The chat client of a widget. The panel session lives in localStorage, so\n * it is read after mounting (`null` until then: the widget stays loading and\n * the server HTML has no session-dependent content).\n */\nfunction useWidgetClient(props: ChatWidgetBaseProps): ChatClient | null | undefined {\n const [stored, setStored] = useState<string | undefined | null>(null);\n const host = props.host ?? getPanelConfig().host;\n useEffect(() => {\n if (props.client || props.token) return;\n setStored(getPanelSession(props.projectID, host));\n }, [props.client, props.token, props.projectID, host]);\n const token = props.token ?? stored;\n const projectId = props.chatProjectID ?? props.projectID;\n return useMemo(() => {\n if (props.client) return props.client;\n if (token === null) return null;\n if (!token) return undefined;\n return createChatClient({ projectId, token, baseUrl: props.apiUrl });\n }, [props.client, token, projectId, props.apiUrl]);\n}\n\nfunction useBuy(props: ChatWidgetBaseProps) {\n return async (lock: ConversationLock) => {\n const productId = props.buyProductId ?? lock.productId;\n if (!productId) return;\n const request: ChatBuyRequest = { productId, reason: lock.reason, priceCents: lock.priceCents };\n if (props.onBuy) {\n await props.onBuy(request);\n return;\n }\n await addPackToCart({\n projectID: props.projectID,\n productId,\n name: props.title,\n priceCents: lock.priceCents,\n host: props.host,\n });\n };\n}\n\n/**\n * A buyer's pack thread for one service product: history, live updates,\n * sending with pending and refused states, report and mute, and the lock\n * with \"Kup pakiet\" when the replies are used up or the pack expired.\n * Load `bitsnap-react/dist/index.css` once.\n */\nexport function ChatThread(props: ChatThreadProps) {\n const client = useWidgetClient(props);\n const locale = props.locale ?? getLocale();\n const texts = useMemo(() => getChatTexts(props.texts, locale), [props.texts, locale]);\n const conversation = useConversation({\n client,\n target: { kind: \"thread\", threadId: props.threadId, productId: props.productId },\n pollIntervalMs: props.pollIntervalMs,\n realtimeUrl: props.realtimeUrl,\n loadNats: props.loadNats,\n });\n const buy = useBuy(props);\n return (\n <div className=\"bitsnap-react h-full\">\n <ConversationView\n conversation={conversation}\n texts={texts}\n locale={locale}\n kind=\"thread\"\n title={props.title}\n onBack={props.onBack}\n onBuy={buy}\n className={props.className}\n />\n </div>\n );\n}\n\n/**\n * A community channel: messages, live updates, posting when the channel\n * allows it (with the channel's moderation refusals shown on the message),\n * report, and the lock with \"Kup dostęp\" for a buyer without a grant.\n * Load `bitsnap-react/dist/index.css` once.\n */\nexport function Channel(props: ChannelProps) {\n const client = useWidgetClient(props);\n const locale = props.locale ?? getLocale();\n const texts = useMemo(() => getChatTexts(props.texts, locale), [props.texts, locale]);\n const conversation = useConversation({\n client,\n target: { kind: \"channel\", channelId: props.channelId, productId: props.productId },\n pollIntervalMs: props.pollIntervalMs,\n realtimeUrl: props.realtimeUrl,\n loadNats: props.loadNats,\n });\n const buy = useBuy(props);\n return (\n <div className=\"bitsnap-react h-full\">\n <ConversationView\n conversation={conversation}\n texts={texts}\n locale={locale}\n kind=\"channel\"\n title={props.title}\n onBack={props.onBack}\n onBuy={buy}\n className={props.className}\n />\n </div>\n );\n}\n","import { addProductToCart } from \"../components/products/add-to-cart\";\n\nexport type BuyPackInput = {\n /** Public project id of the shop (the cart's project). */\n projectID: string;\n /** The product (or variant) to add: the pack's service or community product. */\n productId: string;\n name?: string;\n priceCents?: number;\n /** Backend origin of the cart, when not the default. */\n host?: string;\n};\n\n/**\n * Default \"Kup pakiet\" / \"Kup dostęp\" action: adds the product to the page\n * cart (`Bitsnap.addProductToCart`) and opens the cart drawer. The page needs\n * a mounted `BitsnapCheckout`. When the page cart belongs to another project\n * or host nothing changes and the promise rejects; pass `onBuy` to the widget\n * to use your own checkout instead.\n */\nexport async function addPackToCart(input: BuyPackInput): Promise<void> {\n await addProductToCart(\n {\n id: input.productId,\n name: input.name ?? \"\",\n price: input.priceCents ?? 0,\n currency: \"\",\n },\n { projectID: input.projectID, host: input.host, showCart: true },\n );\n}\n","/**\n * Buyer side of the Bitsnap chat service (`bitsnap-messaging`): the shapes\n * the library works with. The wire is snake_case JSON; `client.ts` maps it to\n * these camelCase types. Times are ISO 8601 strings, `null` when absent.\n */\n\n/** Default base URL of the chat service. */\nexport const DEFAULT_CHAT_API_URL = \"https://chat.bitsnap.pl\";\n\n/** Default NATS WebSocket URL, used when the realtime token lists no server. */\nexport const DEFAULT_CHAT_REALTIME_URL =\n \"wss://bitsnap-nats-queue-production.up.railway.app\";\n\n/** One paid order that gives a pack thread creator replies. */\nexport type ChatPack = {\n orderId: string;\n productId?: string;\n replies: number;\n used: number;\n left: number;\n expiresAt: string | null;\n expired: boolean;\n};\n\n/** A stored message, or the pending answer of a send. */\nexport type ChatMessage = {\n id: string;\n threadId: string;\n authorEmail: string;\n body: string;\n attachmentKey?: string;\n attachmentKind?: string;\n createdAt: string;\n pinned: boolean;\n /** Soft deleted: the body is empty. */\n deleted: boolean;\n /** A message of the service, such as the creator's away notice. */\n system: boolean;\n /** `\"pending\"` in the answer of a send: queued, not stored yet. */\n status?: \"pending\";\n};\n\n/** The state of a conversation for the caller (`ThreadView` on the wire). */\nexport type ChatThreadSummary = {\n id: string;\n kind: \"pack\" | \"channel\";\n channelId?: string;\n /** For a buyer, the creator's e-mail (pack) or the channel name. */\n title: string;\n lastMessage?: ChatMessage;\n unread: number;\n repliesTotal: number;\n repliesUsed: number;\n repliesLeft: number;\n expiresAt: string | null;\n /** The caller cannot write: every pack has expired. */\n composerLocked: boolean;\n productId?: string;\n /** The creator's promise in hours (\"odpowiedź w ciągu 48 h\"), 0 for none. */\n responseHours: number;\n packs: ChatPack[];\n muted: boolean;\n};\n\n/** A channel the caller may read. */\nexport type ChatChannelSummary = {\n id: string;\n name: string;\n topic: string;\n welcome: string;\n whoCanPost: \"creator\" | \"members\";\n productId: string;\n /** `creator`, `member` or `muted`. */\n role: string;\n memberCount: number;\n createdAt: string;\n blockLinks: boolean;\n blockMedia: boolean;\n cooldownSeconds: number;\n};\n\n/** A pack the buyer holds and has not opened a thread for yet. */\nexport type ChatPackEntitlement = {\n productId: string;\n name: string;\n repliesLeftHint: number;\n expiresAt: string | null;\n};\n\n/** A community product the buyer holds; `channelId` once a channel is bound. */\nexport type ChatChannelEntitlement = {\n productId: string;\n channelId?: string;\n};\n\n/** `GET /v1/me`: the buyer's chat in one project. */\nexport type ChatMe = {\n email: string;\n threads: ChatThreadSummary[];\n entitlements: {\n packs: ChatPackEntitlement[];\n channels: ChatChannelEntitlement[];\n };\n channels: ChatChannelSummary[];\n};\n\n/** One page of history, newest first as the service answers it. */\nexport type ChatMessagePage = {\n messages: ChatMessage[];\n hasMore: boolean;\n};\n\n/** The thread part of a send answer. */\nexport type ChatThreadState = Pick<\n ChatThreadSummary,\n | \"id\"\n | \"kind\"\n | \"repliesTotal\"\n | \"repliesUsed\"\n | \"repliesLeft\"\n | \"expiresAt\"\n | \"composerLocked\"\n | \"responseHours\"\n>;\n\n/** `POST /v1/threads/{id}/messages` answers 202 with the queued message. */\nexport type ChatSendResult = {\n message: ChatMessage;\n thread: ChatThreadState;\n};\n\nexport type ChatReportReason = \"spam\" | \"abuse\" | \"illegal\" | \"other\";\n\n/** `POST /v1/realtime/token`. */\nexport type ChatRealtimeToken = {\n jwt: string;\n expiresAt: string;\n servers: string[];\n subjects: string[];\n truncated: boolean;\n};\n\n/** Live events on the thread or channel subject. */\nexport type ChatRealtimeEvent =\n | { type: \"message.created\"; message: ChatMessage }\n | { type: \"message.rejected\"; id: string; reason: string }\n | { type: \"message.deleted\"; id: string }\n | { type: \"message.pinned\"; id: string }\n | { type: \"message.unpinned\"; id: string };\n\n/** How a conversation hears about new messages. */\nexport type ChatLiveMode = \"connecting\" | \"live\" | \"polling\" | \"off\";\n","import {\n DEFAULT_CHAT_API_URL,\n type ChatChannelSummary,\n type ChatMe,\n type ChatMessage,\n type ChatMessagePage,\n type ChatPack,\n type ChatRealtimeEvent,\n type ChatRealtimeToken,\n type ChatReportReason,\n type ChatSendResult,\n type ChatThreadState,\n type ChatThreadSummary,\n} from \"./types\";\n\n/**\n * An error answer of the chat service (`{\"error\":\"<code>\"}`), or `network`\n * (status 0) when the request did not get an answer.\n *\n * Codes the buyer UI handles: `unauthorized` (401), `plan_required`,\n * `locked`, `muted`, `blocked`, `forbidden`, `read_only` (403), `not_found`\n * (404), `moderation_link`, `moderation_banned_word`, `moderation_media`\n * (422), `cooldown` (429, with `retryAfter`), `unavailable` (503),\n * `invalid_project` (400).\n */\nexport class ChatError extends Error {\n readonly code: string;\n readonly status: number;\n /** `cooldown`: seconds to wait before the next post. */\n readonly retryAfter?: number;\n /** Extra fields of the answer (`locked`: `product_id`, `price_cents`, `welcome`). */\n readonly data: Record<string, unknown>;\n\n constructor(\n code: string,\n status: number,\n data: Record<string, unknown> = {},\n ) {\n super(`chat: ${code} (${status})`);\n this.name = \"ChatError\";\n this.code = code;\n this.status = status;\n this.data = data;\n const retry = Number(data.retry_after);\n if (Number.isFinite(retry) && retry > 0) this.retryAfter = retry;\n }\n}\n\nexport type ChatClientOptions = {\n /** Project id sent as `X-Bitsnap-Project`. */\n projectId: string;\n /** Bearer credential: the panel session token or a `bcht_` buyer token. */\n token: string;\n /** Base URL of the chat service. Defaults to `https://chat.bitsnap.pl`. */\n baseUrl?: string;\n /** Replaces `fetch` (tests, server rendering). */\n fetch?: typeof fetch;\n};\n\n/** The buyer calls of the chat service HTTP API. */\nexport type ChatClient = {\n readonly baseUrl: string;\n readonly projectId: string;\n me(): Promise<ChatMe>;\n /** Opens or returns the pack thread of a service product. */\n openThread(productId: string): Promise<ChatThreadSummary>;\n /** Newest first; `before` is a message id. */\n messages(\n threadId: string,\n options?: { before?: string; limit?: number },\n ): Promise<ChatMessagePage>;\n /** Queues a message. The service answers 202 with `status: \"pending\"`. */\n send(\n threadId: string,\n input: { body: string; clientId?: string },\n ): Promise<ChatSendResult>;\n deleteMessage(threadId: string, messageId: string): Promise<void>;\n mute(threadId: string, muted: boolean): Promise<void>;\n report(input: {\n threadId: string;\n messageId?: string;\n reason: ChatReportReason;\n note?: string;\n }): Promise<void>;\n markRead(threadId: string, messageId: string): Promise<void>;\n /**\n * A NATS token for every conversation the caller may read. The answer is\n * kept until a minute and a half before it expires (the service mints one\n * per caller every 10 s); `fresh` asks for a new one.\n */\n realtimeToken(options?: { fresh?: boolean }): Promise<ChatRealtimeToken>;\n};\n\nexport function createChatClient(options: ChatClientOptions): ChatClient {\n const baseUrl = (options.baseUrl || DEFAULT_CHAT_API_URL).replace(/\\/+$/, \"\");\n const doFetch = options.fetch ?? ((...args) => fetch(...args));\n\n async function call(\n method: string,\n path: string,\n body?: unknown,\n ): Promise<{ status: number; json: unknown }> {\n let response: Response;\n try {\n response = await doFetch(baseUrl + path, {\n method,\n headers: {\n Authorization: `Bearer ${options.token}`,\n \"X-Bitsnap-Project\": options.projectId,\n ...(body === undefined ? {} : { \"Content-Type\": \"application/json\" }),\n },\n body: body === undefined ? undefined : JSON.stringify(body),\n });\n } catch {\n throw new ChatError(\"network\", 0);\n }\n let json: unknown = null;\n try {\n const text = await response.text();\n json = text ? JSON.parse(text) : null;\n } catch {\n json = null;\n }\n if (!response.ok) {\n const data = isRecord(json) ? json : {};\n const code = typeof data.error === \"string\" ? data.error : \"internal_error\";\n throw new ChatError(code, response.status, data);\n }\n return { status: response.status, json };\n }\n\n const id = encodeURIComponent;\n let cachedToken: ChatRealtimeToken | undefined;\n\n return {\n baseUrl,\n projectId: options.projectId,\n async me() {\n const { json } = await call(\"GET\", \"/v1/me\");\n return mapMe(json);\n },\n async openThread(productId) {\n const { json } = await call(\"POST\", \"/v1/threads\", {\n product_id: productId,\n });\n return mapThread(json);\n },\n async messages(threadId, opts = {}) {\n const query = new URLSearchParams();\n if (opts.before) query.set(\"before\", opts.before);\n if (opts.limit) query.set(\"limit\", String(opts.limit));\n const qs = query.toString();\n const suffix = qs ? `?${qs}` : \"\";\n const { json } = await call(\n \"GET\",\n `/v1/threads/${id(threadId)}/messages${suffix}`,\n );\n const page = isRecord(json) ? json : {};\n return {\n messages: arr(page.messages).map(mapMessage),\n hasMore: page.has_more === true,\n };\n },\n async send(threadId, input) {\n const { json } = await call(\n \"POST\",\n `/v1/threads/${id(threadId)}/messages`,\n {\n body: input.body,\n ...(input.clientId ? { client_id: input.clientId } : {}),\n },\n );\n const res = isRecord(json) ? json : {};\n return {\n message: mapMessage(res.message),\n thread: mapThreadState(res.thread),\n };\n },\n async deleteMessage(threadId, messageId) {\n await call(\n \"DELETE\",\n `/v1/threads/${id(threadId)}/messages/${id(messageId)}`,\n );\n },\n async mute(threadId, muted) {\n await call(\"POST\", `/v1/threads/${id(threadId)}/mute`, { muted });\n },\n async report(input) {\n await call(\"POST\", \"/v1/reports\", {\n thread_id: input.threadId,\n ...(input.messageId ? { message_id: input.messageId } : {}),\n reason: input.reason,\n ...(input.note ? { note: input.note } : {}),\n });\n },\n async markRead(threadId, messageId) {\n await call(\"POST\", `/v1/threads/${id(threadId)}/receipts`, {\n state: \"read\",\n message_id: messageId,\n });\n },\n async realtimeToken(opts = {}) {\n if (\n !opts.fresh &&\n cachedToken &&\n Date.parse(cachedToken.expiresAt) - Date.now() > 90_000\n ) {\n return cachedToken;\n }\n const { json } = await call(\"POST\", \"/v1/realtime/token\");\n const res = isRecord(json) ? json : {};\n return (cachedToken = {\n jwt: str(res.jwt),\n expiresAt: str(res.expires_at),\n servers: arr(res.servers).filter((s): s is string => typeof s === \"string\"),\n subjects: arr(res.subjects).filter((s): s is string => typeof s === \"string\"),\n truncated: res.truncated === true,\n });\n },\n };\n}\n\n/** Parses one live event of the thread or channel subject. */\nexport function parseRealtimeEvent(raw: unknown): ChatRealtimeEvent | null {\n if (!isRecord(raw) || typeof raw.type !== \"string\") return null;\n const eventId = str(raw.id);\n switch (raw.type) {\n case \"message.created\":\n return { type: \"message.created\", message: mapMessage(raw) };\n case \"message.rejected\":\n return { type: \"message.rejected\", id: eventId, reason: str(raw.reason) };\n case \"message.deleted\":\n case \"message.pinned\":\n case \"message.unpinned\":\n return { type: raw.type, id: eventId };\n default:\n return null;\n }\n}\n\n// --- wire mapping -------------------------------------------------------\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === \"object\" && value != null && !Array.isArray(value);\n}\n\nfunction arr(value: unknown): unknown[] {\n return Array.isArray(value) ? value : [];\n}\n\nfunction str(value: unknown): string {\n return typeof value === \"string\" ? value : value == null ? \"\" : String(value);\n}\n\nfunction num(value: unknown): number {\n const n = Number(value);\n return Number.isFinite(n) ? n : 0;\n}\n\nfunction optStr(value: unknown): string | undefined {\n return typeof value === \"string\" && value !== \"\" ? value : undefined;\n}\n\nfunction time(value: unknown): string | null {\n return typeof value === \"string\" && value !== \"\" ? value : null;\n}\n\nexport function mapMessage(raw: unknown): ChatMessage {\n const m = isRecord(raw) ? raw : {};\n return {\n id: str(m.id),\n threadId: str(m.thread_id),\n authorEmail: str(m.author_email),\n body: str(m.body),\n attachmentKey: optStr(m.attachment_key),\n attachmentKind: optStr(m.attachment_kind),\n createdAt: str(m.created_at),\n pinned: m.pinned === true,\n deleted: m.deleted === true,\n system: m.system === true,\n ...(m.status === \"pending\" ? { status: \"pending\" as const } : {}),\n };\n}\n\nfunction mapPack(raw: unknown): ChatPack {\n const p = isRecord(raw) ? raw : {};\n return {\n orderId: str(p.order_id),\n productId: optStr(p.product_id),\n replies: num(p.replies),\n used: num(p.used),\n left: num(p.left),\n expiresAt: time(p.expires_at),\n expired: p.expired === true,\n };\n}\n\nfunction mapThreadState(raw: unknown): ChatThreadState {\n const t = isRecord(raw) ? raw : {};\n return {\n id: str(t.id),\n kind: t.kind === \"channel\" ? \"channel\" : \"pack\",\n repliesTotal: num(t.replies_total),\n repliesUsed: num(t.replies_used),\n repliesLeft: num(t.replies_left),\n expiresAt: time(t.expires_at),\n composerLocked: t.composer_locked === true,\n responseHours: num(t.response_hours),\n };\n}\n\nexport function mapThread(raw: unknown): ChatThreadSummary {\n const t = isRecord(raw) ? raw : {};\n return {\n ...mapThreadState(t),\n channelId: optStr(t.channel_id),\n title: str(t.title),\n lastMessage: isRecord(t.last_message) ? mapMessage(t.last_message) : undefined,\n unread: num(t.unread),\n productId: optStr(t.product_id),\n packs: arr(t.packs).map(mapPack),\n muted: t.muted === true,\n };\n}\n\nfunction mapChannel(raw: unknown): ChatChannelSummary {\n const c = isRecord(raw) ? raw : {};\n return {\n id: str(c.id),\n name: str(c.name),\n topic: str(c.topic),\n welcome: str(c.welcome),\n whoCanPost: c.who_can_post === \"members\" ? \"members\" : \"creator\",\n productId: str(c.product_id),\n role: str(c.role),\n memberCount: num(c.member_count),\n createdAt: str(c.created_at),\n blockLinks: c.block_links === true,\n blockMedia: c.block_media === true,\n cooldownSeconds: num(c.cooldown_seconds),\n };\n}\n\nfunction mapMe(raw: unknown): ChatMe {\n const m = isRecord(raw) ? raw : {};\n const ent = isRecord(m.entitlements) ? m.entitlements : {};\n return {\n email: str(m.email),\n threads: arr(m.threads).map(mapThread),\n entitlements: {\n packs: arr(ent.packs).map((raw) => {\n const p = isRecord(raw) ? raw : {};\n return {\n productId: str(p.product_id),\n name: str(p.name),\n repliesLeftHint: num(p.replies_left_hint),\n expiresAt: time(p.expires_at),\n };\n }),\n channels: arr(ent.channels).map((raw) => {\n const c = isRecord(raw) ? raw : {};\n return { productId: str(c.product_id), channelId: optStr(c.channel_id) };\n }),\n },\n channels: arr(m.channels).map(mapChannel),\n };\n}\n"]}
|