@microsoft/omnichannel-chat-widget 2.0.1-main.38e7390 → 2.0.1-main.41dd340

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.
Files changed (21) hide show
  1. package/README.md +57 -0
  2. package/lib/cjs/common/telemetry/TelemetryConstants.js +2 -0
  3. package/lib/cjs/components/livechatwidget/common/initWebChatComposer.js +31 -7
  4. package/lib/cjs/components/livechatwidget/common/reconnectChatHelper.js +29 -1
  5. package/lib/cjs/components/livechatwidget/common/startChat.js +15 -7
  6. package/lib/cjs/components/livechatwidget/common/updateSessionDataForTelemetry.js +34 -5
  7. package/lib/cjs/components/livechatwidget/livechatwidgetstateful/LiveChatWidgetStateful.js +5 -17
  8. package/lib/cjs/components/webchatcontainerstateful/webchatcontroller/middlewares/renderingmiddlewares/attachmentForScreenReaderMiddleware.js +159 -0
  9. package/lib/esm/common/telemetry/TelemetryConstants.js +2 -0
  10. package/lib/esm/components/livechatwidget/common/initWebChatComposer.js +28 -6
  11. package/lib/esm/components/livechatwidget/common/reconnectChatHelper.js +28 -1
  12. package/lib/esm/components/livechatwidget/common/startChat.js +15 -7
  13. package/lib/esm/components/livechatwidget/common/updateSessionDataForTelemetry.js +34 -5
  14. package/lib/esm/components/livechatwidget/livechatwidgetstateful/LiveChatWidgetStateful.js +6 -18
  15. package/lib/esm/components/webchatcontainerstateful/webchatcontroller/middlewares/renderingmiddlewares/attachmentForScreenReaderMiddleware.js +153 -0
  16. package/lib/types/common/telemetry/TelemetryConstants.d.ts +1 -0
  17. package/lib/types/components/livechatwidget/common/initWebChatComposer.d.ts +8 -0
  18. package/lib/types/components/livechatwidget/common/reconnectChatHelper.d.ts +6 -1
  19. package/lib/types/components/livechatwidget/common/startChat.d.ts +5 -1
  20. package/lib/types/components/webchatcontainerstateful/webchatcontroller/middlewares/renderingmiddlewares/attachmentForScreenReaderMiddleware.d.ts +11 -0
  21. package/package.json +5 -6
package/README.md CHANGED
@@ -13,6 +13,7 @@
13
13
  1. [Installation](#installation)
14
14
  1. [WebChat dependency constraint](#webchat-dependency-constraint)
15
15
  1. [Example Usage](#example-usage)
16
+ 1. [Bot authentication and the sign-in card](#bot-authentication-and-the-sign-in-card)
16
17
  1. [Components](#components)
17
18
  1. [See Also](#see-also)
18
19
 
@@ -81,6 +82,8 @@ This hotfix still declares these vulnerable transitive versions:
81
82
  | `swiper` | `8.4.7` |
82
83
  | `valibot` | `1.1.0` |
83
84
  | `uuid` | `3.4.0`, `8.3.2`, and `9.0.1` |
85
+ | `deepmerge` (via `sanitize-html@2.14.0`) | `4.3.1` |
86
+ | `minimatch` (via the Speech SDK's `rimraf@3` → `glob@7`) | `3.1.5` |
84
87
 
85
88
  The consumer audit permits only the reviewed advisories from this hotfix. It rejects each new advisory.
86
89
 
@@ -142,6 +145,60 @@ A typescript sample widget can be found [here](https://github.com/microsoft/omni
142
145
 
143
146
  ```react-scripts``` has deprecated to build the sample project, please refer to vite building instructions: [BuildingUsingVite.md](https://github.com/microsoft/omnichannel-chat-widget/blob/main/docs/BuildingUsingVite.md)
144
147
 
148
+ ## Bot authentication and the sign-in card
149
+
150
+ A bot that uses single sign-on (SSO) can send a sign-in (OAuth) card. The host page decides whether the widget shows the card. It passes a callback to the Omnichannel SDK method [`setBotAuthTokenProvider`](https://learn.microsoft.com/dynamics365/customer-service/develop/reference/methods/setbotauthtokenprovider), and the callback calls `callback({show: false})` for a customer who is already signed in.
151
+
152
+ When a sign-in card arrives, the widget asks the host for this result. It tries `fetchBotAuthConfigRetries` times (default `3`), `fetchBotAuthConfigRetryInterval` milliseconds apart (default `1000`), so it waits about 2 seconds by default. If the host doesn't answer in that time, `fallbackShowSignInCard` decides what happens:
153
+
154
+ | `fallbackShowSignInCard` | Card when the host doesn't answer in time | Telemetry |
155
+ | --- | --- | --- |
156
+ | Not set (default) | Shown | `SetBotAuthProviderNotFound` (with the error) |
157
+ | `false` | Hidden | `SetBotAuthProviderNotFound` (with the fallback value), then `SetBotAuthProviderHideCard` |
158
+ | `true` | Shown | `SetBotAuthProviderNotFound` (with the fallback value), then `SetBotAuthProviderDisplayCard` |
159
+
160
+ Which value to use:
161
+
162
+ | Your setup | `fallbackShowSignInCard` |
163
+ | --- | --- |
164
+ | Your page signs the customer in, and your `setBotAuthTokenProvider` callback passes the token to the bot (bot SSO) | `false` |
165
+ | You want the card to show whenever the callback is late, and you want this logged as a decision | `true` |
166
+ | Customers sign in through the sign-in card itself | Leave it unset |
167
+
168
+ ```js
169
+ const liveChatWidgetProps = {
170
+ chatSDK: chatSDK, // mandatory
171
+ chatConfig: chatConfig, // mandatory
172
+ webChatContainerProps: {
173
+ botAuthConfig: {
174
+ fallbackShowSignInCard: false // hide the card if the host doesn't answer in time
175
+ }
176
+ }
177
+ };
178
+ ```
179
+
180
+ If you use the live chat widget 2.0 script instead of this package, the function that the script's `data-customization-callback` attribute references must return a root props object that contains the setting, for example `{ webChatContainerProps: { botAuthConfig: { fallbackShowSignInCard: false } } }`. See [Develop a custom live chat widget](https://learn.microsoft.com/dynamics365/customer-service/develop/develop-live-chat-widget).
181
+
182
+ What the customer sees:
183
+
184
+ | Situation | Card |
185
+ | --- | --- |
186
+ | The host answers `callback({show: false})` in time | Hidden (`SetBotAuthProviderHideCard`) |
187
+ | The host answers `callback({show: true})` in time | Shown (`SetBotAuthProviderDisplayCard`) |
188
+ | The host doesn't answer in time (slow request, error, or no `callback(...)` call) | Depends on `fallbackShowSignInCard` (see the previous table) |
189
+ | The widget can't extract a sign-in ID from the card, or can't get a token exchange URL (from the card or from the Bot Framework token service) | Shown. The widget doesn't ask the host. |
190
+
191
+ `fallbackShowSignInCard` changes only what happens when the host doesn't answer in time. It isn't a substitute for a working `setBotAuthTokenProvider` callback. If you set it to `false` and the callback fails for a customer who isn't signed in, that customer doesn't see the card and can't sign in.
192
+
193
+ **Troubleshooting: a signed-in customer sometimes sees the sign-in card.** The `setBotAuthTokenProvider` callback probably didn't answer in time. Look for `SetBotAuthProviderNotFound` in the widget telemetry. To fix it:
194
+
195
+ 1. Call `callback(...)` on every code path of the function, including error paths. If the function throws before it calls `callback(...)`, the widget gets no answer.
196
+ 1. Make the whole function finish quickly. With the live chat widget 2.0 script, the widget gets the `callback(...)` value only after the function finishes, so slow work after `callback(...)` still delays the answer. For a sign-in card that your page already completed, call `callback({show: false})` and return at once. Otherwise, complete the token exchange, then call `callback(...)` with its result.
197
+ 1. If the function is correct but can't finish in about 2 seconds, increase `fetchBotAuthConfigRetries` or `fetchBotAuthConfigRetryInterval`.
198
+ 1. If your function passes a token to the bot for every customer before the chat needs it (bot SSO works), set `fallbackShowSignInCard: false`. Signing the customer in to your page, or using authenticated chat, doesn't by itself sign the customer in to the bot.
199
+
200
+ For the host-side callback, see [Pass authentication token to bot during single sign-on in live chat](https://learn.microsoft.com/dynamics365/customer-service/develop/pass-auth-token-sso-live-chat).
201
+
145
202
  ## Components
146
203
 
147
204
  For a detailed guide on how to customize each component with sample usages, please see our new [Developer Guide](https://github.com/microsoft/omnichannel-chat-widget/blob/main/docs/customizations/getstarted.md).
@@ -114,6 +114,7 @@ let TelemetryEvent = exports.TelemetryEvent = /*#__PURE__*/function (TelemetryEv
114
114
  TelemetryEvent["RecoveryEligibilityEvaluated"] = "RecoveryEligibilityEvaluated";
115
115
  TelemetryEvent["GetConversationDetailsCallStarted"] = "GetConversationDetailsCallStarted";
116
116
  TelemetryEvent["GetConversationDetailsCallFailed"] = "GetConversationDetailsCallFailed";
117
+ TelemetryEvent["UpdateTelemetryDataFailed"] = "UpdateTelemetryDataFailed";
117
118
  TelemetryEvent["EndChatSDKCallFailed"] = "EndChatSDKCallFailed";
118
119
  TelemetryEvent["DisconnectEndChatSDKCallFailed"] = "DisconnectEndChatSDKCallFailed";
119
120
  TelemetryEvent["GetChatReconnectContextSDKCallStarted"] = "GetChatReconnectContextSDKCallStarted";
@@ -430,6 +431,7 @@ let TelemetryConstants = exports.TelemetryConstants = /*#__PURE__*/function () {
430
431
  case TelemetryEvent.OnNewMessageFailed:
431
432
  case TelemetryEvent.OnNewMessageAudioNotificationFailed:
432
433
  case TelemetryEvent.GetConversationDetailsCallFailed:
434
+ case TelemetryEvent.UpdateTelemetryDataFailed:
433
435
  case TelemetryEvent.EndChatSDKCall:
434
436
  case TelemetryEvent.EndChatEventReceived:
435
437
  case TelemetryEvent.EndChatSDKCallFailed:
@@ -3,7 +3,7 @@
3
3
  Object.defineProperty(exports, "__esModule", {
4
4
  value: true
5
5
  });
6
- exports.initWebChatComposer = void 0;
6
+ exports.initWebChatComposer = exports.createScreenReaderMarkdownRenderer = void 0;
7
7
  var _Constants = require("../../../common/Constants");
8
8
  var _TelemetryConstants = require("../../../common/telemetry/TelemetryConstants");
9
9
  var _utils = require("../../../common/utils");
@@ -20,6 +20,7 @@ var _attachmentSentAnnouncementMiddleware = _interopRequireDefault(require("../.
20
20
  var _channelDataMiddleware = _interopRequireDefault(require("../../webchatcontainerstateful/webchatcontroller/middlewares/storemiddlewares/channelDataMiddleware"));
21
21
  var _activityMiddleware = require("../../webchatcontainerstateful/webchatcontroller/middlewares/renderingmiddlewares/activityMiddleware");
22
22
  var _activityStatusMiddleware = require("../../webchatcontainerstateful/webchatcontroller/middlewares/renderingmiddlewares/activityStatusMiddleware");
23
+ var _attachmentForScreenReaderMiddleware = require("../../webchatcontainerstateful/webchatcontroller/middlewares/renderingmiddlewares/attachmentForScreenReaderMiddleware");
23
24
  var _attachmentMiddleware = require("../../webchatcontainerstateful/webchatcontroller/middlewares/renderingmiddlewares/attachmentMiddleware");
24
25
  var _attachmentUploadValidatorMiddleware = _interopRequireDefault(require("../../webchatcontainerstateful/webchatcontroller/middlewares/storemiddlewares/attachmentUploadValidatorMiddleware"));
25
26
  var _avatarMiddleware = require("../../webchatcontainerstateful/webchatcontroller/middlewares/renderingmiddlewares/avatarMiddleware");
@@ -48,7 +49,34 @@ var _htmlTextMiddleware = _interopRequireDefault(require("../../webchatcontainer
48
49
  var _preProcessingMiddleware = _interopRequireDefault(require("../../webchatcontainerstateful/webchatcontroller/middlewares/storemiddlewares/preProcessingMiddleware"));
49
50
  var _sanitizationMiddleware = _interopRequireDefault(require("../../webchatcontainerstateful/webchatcontroller/middlewares/storemiddlewares/sanitizationMiddleware"));
50
51
  function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; }
52
+ const markdownSanitizeConfig = {
53
+ FORBID_TAGS: ["form", "button", "script", "div", "input"],
54
+ FORBID_ATTR: ["action"],
55
+ ADD_ATTR: ["target"]
56
+ };
57
+
58
+ /**
59
+ * Renders Markdown for the screen reader text of Adaptive Cards, from the same pieces as the visible card:
60
+ * the host renderMarkdown when set, the hyperlink text override, and the same sanitization.
61
+ * Markdown is always formatted, also when the widget shows Markdown unformatted, so that screen readers do not read the syntax.
62
+ * Styles are removed with their content because the card does not show them.
63
+ */
64
+ const createScreenReaderMarkdownRenderer = webChatContainerProps => {
65
+ var _webChatContainerProp;
66
+ const hostRenderMarkdown = webChatContainerProps === null || webChatContainerProps === void 0 || (_webChatContainerProp = webChatContainerProps.webChatProps) === null || _webChatContainerProp === void 0 ? void 0 : _webChatContainerProp.renderMarkdown;
67
+ const markdown = (0, _createMarkdown.createMarkdown)(false, (webChatContainerProps === null || webChatContainerProps === void 0 ? void 0 : webChatContainerProps.disableNewLineMarkdownSupport) ?? _defaultWebChatContainerStatefulProps.defaultWebChatContainerStatefulProps.disableNewLineMarkdownSupport, webChatContainerProps === null || webChatContainerProps === void 0 ? void 0 : webChatContainerProps.opensMarkdownLinksInSameTab);
68
+ const hyperlinkTextOverrideRenderer = new _HyperlinkTextOverrideRenderer.default((webChatContainerProps === null || webChatContainerProps === void 0 ? void 0 : webChatContainerProps.hyperlinkTextOverride) ?? _defaultWebChatContainerStatefulProps.defaultWebChatContainerStatefulProps.hyperlinkTextOverride);
69
+ return text => {
70
+ const html = hostRenderMarkdown ? hostRenderMarkdown(text) : markdown.render(text);
71
+ return _dompurify.default.sanitize(hyperlinkTextOverrideRenderer.render(html), {
72
+ ...markdownSanitizeConfig,
73
+ FORBID_TAGS: [...markdownSanitizeConfig.FORBID_TAGS, "style"]
74
+ });
75
+ };
76
+ };
77
+
51
78
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
79
+ exports.createScreenReaderMarkdownRenderer = createScreenReaderMarkdownRenderer;
52
80
  const initWebChatComposer = (props, state, dispatch, facadeChatSDK, endChat) => {
53
81
  var _props$webChatContain, _props$webChatContain2, _props$webChatContain3, _props$webChatContain4, _props$webChatContain5, _props$webChatContain6, _state$domainStates$l4, _props$webChatContain0, _state$domainStates$r, _state$domainStates$r2, _props$webChatContain1, _state$domainStates$r3, _props$webChatContain10, _state$domainStates$l5, _props$webChatContain11, _props$webChatContain12, _state$domainStates$r4, _state$domainStates$r5, _props$webChatContain13, _defaultWebChatContai, _props$webChatContain14, _defaultWebChatContai2, _props$webChatContain15, _props$webChatContain16, _props$webChatContain17;
54
82
  // Add a hook to make all links open a new window
@@ -154,12 +182,7 @@ const initWebChatComposer = (props, state, dispatch, facadeChatSDK, endChat) =>
154
182
  });
155
183
 
156
184
  // EXISTING sanitization (continues to work as before)
157
- const config = {
158
- FORBID_TAGS: ["form", "button", "script", "div", "input"],
159
- FORBID_ATTR: ["action"],
160
- ADD_ATTR: ["target"]
161
- };
162
- text = _dompurify.default.sanitize(text, config);
185
+ text = _dompurify.default.sanitize(text, markdownSanitizeConfig);
163
186
 
164
187
  // MONITOR-ONLY: Test what the stricter allowlist would remove (Phase 1)
165
188
  // This does NOT modify the text, only logs telemetry
@@ -363,6 +386,7 @@ const initWebChatComposer = (props, state, dispatch, facadeChatSDK, endChat) =>
363
386
  store: webChatStore,
364
387
  activityMiddleware: (_props$webChatContain0 = props.webChatContainerProps) !== null && _props$webChatContain0 !== void 0 && (_props$webChatContain0 = _props$webChatContain0.renderingMiddlewareProps) !== null && _props$webChatContain0 !== void 0 && _props$webChatContain0.disableActivityMiddleware ? undefined : (0, _activityMiddleware.createActivityMiddleware)(renderMarkdown, (_state$domainStates$r = state.domainStates.renderingMiddlewareProps) === null || _state$domainStates$r === void 0 ? void 0 : _state$domainStates$r.systemMessageStyleProps, (_state$domainStates$r2 = state.domainStates.renderingMiddlewareProps) === null || _state$domainStates$r2 === void 0 ? void 0 : _state$domainStates$r2.userMessageStyleProps, localizedTexts),
365
388
  attachmentMiddleware: (_props$webChatContain1 = props.webChatContainerProps) !== null && _props$webChatContain1 !== void 0 && (_props$webChatContain1 = _props$webChatContain1.renderingMiddlewareProps) !== null && _props$webChatContain1 !== void 0 && _props$webChatContain1.disableAttachmentMiddleware ? undefined : (0, _attachmentMiddleware.createAttachmentMiddleware)(((_state$domainStates$r3 = state.domainStates.renderingMiddlewareProps) === null || _state$domainStates$r3 === void 0 || (_state$domainStates$r3 = _state$domainStates$r3.attachmentProps) === null || _state$domainStates$r3 === void 0 ? void 0 : _state$domainStates$r3.enableInlinePlaying) ?? _defaultAttachmentProps.defaultAttachmentProps.enableInlinePlaying),
389
+ attachmentForScreenReaderMiddleware: (0, _attachmentForScreenReaderMiddleware.createAttachmentForScreenReaderMiddleware)(createScreenReaderMarkdownRenderer(props.webChatContainerProps)),
366
390
  activityStatusMiddleware: (_props$webChatContain10 = props.webChatContainerProps) !== null && _props$webChatContain10 !== void 0 && (_props$webChatContain10 = _props$webChatContain10.renderingMiddlewareProps) !== null && _props$webChatContain10 !== void 0 && _props$webChatContain10.disableActivityStatusMiddleware ? undefined : (0, _activityStatusMiddleware.createActivityStatusMiddleware)((0, _omnichannelChatSdk.getLocaleStringFromId)((_state$domainStates$l5 = state.domainStates.liveChatConfig) === null || _state$domainStates$l5 === void 0 || (_state$domainStates$l5 = _state$domainStates$l5.ChatWidgetLanguage) === null || _state$domainStates$l5 === void 0 ? void 0 : _state$domainStates$l5.msdyn_localeid)),
367
391
  toastMiddleware: (_props$webChatContain11 = props.webChatContainerProps) !== null && _props$webChatContain11 !== void 0 && (_props$webChatContain11 = _props$webChatContain11.renderingMiddlewareProps) !== null && _props$webChatContain11 !== void 0 && _props$webChatContain11.disableToastMiddleware ? undefined : (0, _toastMiddleware.createToastMiddleware)(props.notificationPaneProps, endChat),
368
392
  renderMarkdown,
@@ -3,7 +3,7 @@
3
3
  Object.defineProperty(exports, "__esModule", {
4
4
  value: true
5
5
  });
6
- exports.isReconnectEnabled = exports.isPersistentEnabled = exports.handleChatReconnect = exports.getChatReconnectContext = void 0;
6
+ exports.isReconnectTriggered = exports.isReconnectEnabled = exports.isPersistentEnabled = exports.handleChatReconnect = exports.getChatReconnectContext = void 0;
7
7
  require("regenerator-runtime/runtime");
8
8
  var _TelemetryConstants = require("../../../common/telemetry/TelemetryConstants");
9
9
  var _Constants = require("../../../common/Constants");
@@ -13,6 +13,7 @@ var _omnichannelChatComponents = require("@microsoft/omnichannel-chat-components
13
13
  var _ConversationState = require("../../../contexts/common/ConversationState");
14
14
  var _LiveChatWidgetActionType = require("../../../contexts/common/LiveChatWidgetActionType");
15
15
  var _TelemetryHelper = require("../../../common/telemetry/TelemetryHelper");
16
+ var _createReducer = require("../../../contexts/createReducer");
16
17
  var _startChatErrorHandler = require("./startChatErrorHandler");
17
18
  // Return value: should start normal chat flow when reconnect is enabled
18
19
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
@@ -55,8 +56,35 @@ const handleChatReconnect = async (facadeChatSDK, props, dispatch, setAdapter, i
55
56
  return true;
56
57
  };
57
58
 
59
+ /**
60
+ * Returns true when chat reconnect took over the start: it started the chat itself or showed the reconnect pane.
61
+ * In that case the caller must not start another chat.
62
+ */
58
63
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
59
64
  exports.handleChatReconnect = handleChatReconnect;
65
+ const isReconnectTriggered = async (facadeChatSDK, props, dispatch, setAdapter, initStartChat, state) => {
66
+ if (isReconnectEnabled(props.chatConfig) === true && !isPersistentEnabled(props.chatConfig)) {
67
+ let reconnectChatStarted = false;
68
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
69
+ const initStartChatAndTrack = async function () {
70
+ reconnectChatStarted = await initStartChat(...arguments);
71
+ };
72
+ const noValidReconnectId = await handleChatReconnect(facadeChatSDK, props, dispatch, setAdapter, initStartChatAndTrack, state);
73
+ // initStartChat resolves before React renders Active, so the in-memory state can still read Loading here.
74
+ // Its result tells whether reconnect started the chat; the in-memory state covers the reconnect pane.
75
+ const inMemoryState = (0, _createReducer.executeReducer)(state, {
76
+ type: _LiveChatWidgetActionType.LiveChatWidgetActionType.GET_IN_MEMORY_STATE,
77
+ payload: null
78
+ });
79
+ if (!noValidReconnectId && (reconnectChatStarted || inMemoryState.appStates.conversationState === _ConversationState.ConversationState.Active || inMemoryState.appStates.conversationState === _ConversationState.ConversationState.ReconnectChat)) {
80
+ return true;
81
+ }
82
+ }
83
+ return false;
84
+ };
85
+
86
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
87
+ exports.isReconnectTriggered = isReconnectTriggered;
60
88
  const getChatReconnectContext = async (facadeChatSDK, chatConfig, props, isAuthenticatedChat, dispatch) => {
61
89
  try {
62
90
  var _props$reconnectChatP4;
@@ -68,7 +68,7 @@ const getGuard = (guards, facadeChatSDK) => {
68
68
  * Runs `operation` only if no other invocation for the same widget instance is already in
69
69
  * flight. Concurrent invocations are dropped (and reported through telemetry) rather than
70
70
  * awaiting the in-flight promise, so a future re-entrant call can never deadlock on itself.
71
- * No caller acts on the resolved value, so dropping is safe.
71
+ * A dropped invocation resolves to `undefined`.
72
72
  *
73
73
  * `blockedBy` lets an operation also yield to a different, already running operation for the
74
74
  * same widget instance without claiming that operation's lock.
@@ -84,14 +84,14 @@ const runExclusively = async (guards, facadeChatSDK, description, operation, pro
84
84
  WidgetCacheId: props ? (0, _utils.getWidgetCacheIdfromProps)(props) : undefined
85
85
  }
86
86
  });
87
- return;
87
+ return undefined;
88
88
  }
89
89
 
90
90
  // Claim the lock before invoking the operation, so a re-entrant call made from the
91
91
  // operation's synchronous preamble (before its first await) cannot slip past the check above.
92
92
  guard.inFlight = true;
93
93
  try {
94
- await operation();
94
+ return await operation();
95
95
  } finally {
96
96
  guard.inFlight = false;
97
97
  }
@@ -228,10 +228,15 @@ const setPreChatAndInitiateChat = async (facadeChatSDK, dispatch, setAdapter, is
228
228
  await initStartChat(facadeChatSDK, dispatch, setAdapter, state, props, optionalParams);
229
229
  };
230
230
 
231
+ /**
232
+ * Resolves to `true` when the chat reached Active, and `false` when it failed or the call was dropped.
233
+ * It resolves before React renders Active, so callers must use this value rather than reading the conversation state.
234
+ */
231
235
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
232
236
  exports.setPreChatAndInitiateChat = setPreChatAndInitiateChat;
233
237
  const initStartChat = async (facadeChatSDK, dispatch, setAdapter, state, props, params, persistedState) => {
234
- return runExclusively(initStartChatGuards, facadeChatSDK, "Concurrent initStartChat call ignored, a start chat operation is already in progress for this widget instance.", () => initStartChatInternal(facadeChatSDK, dispatch, setAdapter, state, props, params, persistedState), props);
238
+ const chatStarted = await runExclusively(initStartChatGuards, facadeChatSDK, "Concurrent initStartChat call ignored, a start chat operation is already in progress for this widget instance.", () => initStartChatInternal(facadeChatSDK, dispatch, setAdapter, state, props, params, persistedState), props);
239
+ return chatStarted === true;
235
240
  };
236
241
 
237
242
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
@@ -346,7 +351,7 @@ const initStartChatInternal = async (facadeChatSDK, dispatch, setAdapter, state,
346
351
  (0, _startChatErrorHandler.logWidgetLoadComplete)(_Constants.WidgetLoadTelemetryMessage.PersistedStateRetrievedMessage);
347
352
  // Set post chat context in state, load in background to do not block the load
348
353
  (0, _setPostChatContextAndLoadSurvey.setPostChatContextAndLoadSurvey)(facadeChatSDK, dispatch, true);
349
- return;
354
+ return true;
350
355
  }
351
356
 
352
357
  // Persistent Chat relies on the `reconnectId` retrieved from reconnectablechats API to reconnect upon start chat and not `liveChatContext`
@@ -362,10 +367,13 @@ const initStartChatInternal = async (facadeChatSDK, dispatch, setAdapter, state,
362
367
  (0, _startChatErrorHandler.logWidgetLoadComplete)();
363
368
  // Set post chat context in state, load in background to do not block the load
364
369
  (0, _setPostChatContextAndLoadSurvey.setPostChatContextAndLoadSurvey)(facadeChatSDK, dispatch);
365
- // Updating chat session detail for telemetry
366
- await (0, _updateSessionDataForTelemetry.updateTelemetryData)(facadeChatSDK, dispatch);
370
+ // Updating chat session detail for telemetry, in background: getConversationDetails retries until the
371
+ // live work item exists (several seconds), and awaiting it would hold the start chat locks and drop the next start chat
372
+ (0, _updateSessionDataForTelemetry.updateTelemetryData)(facadeChatSDK, dispatch);
373
+ return true;
367
374
  } catch (ex) {
368
375
  (0, _startChatErrorHandler.handleStartChatError)(dispatch, facadeChatSDK, props, ex, isStartChatSuccessful);
376
+ return false;
369
377
  }
370
378
  };
371
379
 
@@ -12,16 +12,42 @@ var _TelemetryManager = require("../../../common/telemetry/TelemetryManager");
12
12
  var _utils = require("../../../common/utils");
13
13
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
14
14
  const updateTelemetryData = async (facadeChatSDK, dispatch) => {
15
- // load it concurrently, this will reduce the load time
16
- await Promise.all([updateSessionDataForTelemetry(facadeChatSDK, dispatch), updateConversationDataForTelemetry(facadeChatSDK, dispatch)]);
15
+ var _facadeChatSDK$getCha;
16
+ // startChat no longer waits for this, so the next chat can start (chatSDKStateCleanUp assigns a new requestId)
17
+ // before these calls resolve. Results for an earlier chat must not overwrite the current chat's data.
18
+ // endChat also assigns a new requestId, so the chat that just ended still applies its own results.
19
+ const requestId = facadeChatSDK === null || facadeChatSDK === void 0 || (_facadeChatSDK$getCha = facadeChatSDK.getChatSDK()) === null || _facadeChatSDK$getCha === void 0 ? void 0 : _facadeChatSDK$getCha.requestId;
20
+ try {
21
+ // load it concurrently, this will reduce the load time
22
+ await Promise.all([updateSessionDataForTelemetry(facadeChatSDK, dispatch, requestId), updateConversationDataForTelemetry(facadeChatSDK, dispatch, requestId)]);
23
+ } catch (error) {
24
+ _TelemetryHelper.TelemetryHelper.logSDKEvent(_TelemetryConstants.LogLevel.ERROR, {
25
+ Event: _TelemetryConstants.TelemetryEvent.UpdateTelemetryDataFailed,
26
+ ExceptionDetails: {
27
+ exception: `Update telemetry data failed: ${error}`
28
+ }
29
+ });
30
+ }
17
31
  };
18
32
 
19
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
33
+ // The requestId alone isn't enough: endChat also replaces it. Only the next chat's startChat gets a new chat token
34
+ // (endChat and chatSDKStateCleanUp clear it), so drop the result only when the SDK holds that next chat.
20
35
  exports.updateTelemetryData = updateTelemetryData;
21
- const updateSessionDataForTelemetry = async (facadeChatSDK, dispatch) => {
36
+ const isFromEarlierChat = (facadeChatSDK, requestId) => {
37
+ var _chatSDK$chatToken;
38
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
39
+ const chatSDK = facadeChatSDK.getChatSDK();
40
+ return (chatSDK === null || chatSDK === void 0 ? void 0 : chatSDK.requestId) !== requestId && !!(chatSDK !== null && chatSDK !== void 0 && (_chatSDK$chatToken = chatSDK.chatToken) !== null && _chatSDK$chatToken !== void 0 && _chatSDK$chatToken.chatId);
41
+ };
42
+
43
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
44
+ const updateSessionDataForTelemetry = async (facadeChatSDK, dispatch, requestId) => {
22
45
  if (facadeChatSDK && facadeChatSDK.getChatSDK()) {
23
46
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
24
47
  const chatSession = await facadeChatSDK.getCurrentLiveChatContext();
48
+ if (isFromEarlierChat(facadeChatSDK, requestId)) {
49
+ return;
50
+ }
25
51
  const telemetryData = _TelemetryHelper.TelemetryHelper.addSessionDataToTelemetry(chatSession, _TelemetryManager.TelemetryManager.InternalTelemetryData);
26
52
  dispatch({
27
53
  type: _LiveChatWidgetActionType.LiveChatWidgetActionType.SET_TELEMETRY_DATA,
@@ -37,10 +63,13 @@ const updateSessionDataForTelemetry = async (facadeChatSDK, dispatch) => {
37
63
  };
38
64
 
39
65
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
40
- const updateConversationDataForTelemetry = async (facadeChatSDK, dispatch) => {
66
+ const updateConversationDataForTelemetry = async (facadeChatSDK, dispatch, requestId) => {
41
67
  if (facadeChatSDK && facadeChatSDK.getChatSDK()) {
42
68
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
43
69
  const liveWorkItem = await (0, _utils.getConversationDetailsCall)(facadeChatSDK);
70
+ if (isFromEarlierChat(facadeChatSDK, requestId)) {
71
+ return;
72
+ }
44
73
  const telemetryData = _TelemetryHelper.TelemetryHelper.addConversationDataToTelemetry(liveWorkItem, _TelemetryManager.TelemetryManager.InternalTelemetryData);
45
74
  dispatch({
46
75
  type: _LiveChatWidgetActionType.LiveChatWidgetActionType.SET_TELEMETRY_DATA,
@@ -163,20 +163,6 @@ const LiveChatWidgetStateful = props => {
163
163
 
164
164
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
165
165
  const startChat = async (props, localState) => {
166
- const isReconnectTriggered = async () => {
167
- if ((0, _reconnectChatHelper.isReconnectEnabled)(props.chatConfig) === true && !(0, _reconnectChatHelper.isPersistentEnabled)(props.chatConfig)) {
168
- const noValidReconnectId = await (0, _reconnectChatHelper.handleChatReconnect)(facadeChatSDK, props, dispatch, setAdapter, _startChat.initStartChat, state);
169
- const inMemoryState = (0, _createReducer.executeReducer)(state, {
170
- type: _LiveChatWidgetActionType.LiveChatWidgetActionType.GET_IN_MEMORY_STATE,
171
- payload: null
172
- });
173
- // If chat reconnect has kicked in chat state will become Active or Reconnect. So just exit, else go next
174
- if (!noValidReconnectId && (inMemoryState.appStates.conversationState === _ConversationState.ConversationState.Active || inMemoryState.appStates.conversationState === _ConversationState.ConversationState.ReconnectChat)) {
175
- return true;
176
- }
177
- }
178
- return false;
179
- };
180
166
  let isChatValid = false;
181
167
  //Start a chat from cache/reconnectid
182
168
  if (activeCachedChatExist === true) {
@@ -188,7 +174,7 @@ const LiveChatWidgetStateful = props => {
188
174
  //Check if conversation state is not in wrapup or closed state
189
175
  isChatValid = await (0, _startChat.checkIfConversationStillValid)(facadeChatSDK, dispatch, state);
190
176
  if (isChatValid === true) {
191
- const reconnectTriggered = await isReconnectTriggered();
177
+ const reconnectTriggered = await (0, _reconnectChatHelper.isReconnectTriggered)(facadeChatSDK, props, dispatch, setAdapter, _startChat.initStartChat, state);
192
178
  if (!reconnectTriggered) {
193
179
  await (0, _startChat.initStartChat)(facadeChatSDK, dispatch, setAdapter, state, props, optionalParams);
194
180
  }
@@ -204,7 +190,7 @@ const LiveChatWidgetStateful = props => {
204
190
  if (isChatValid === false) {
205
191
  if (localState) {
206
192
  // adding the reconnect logic for the case when customer tries to reconnect from a new browser or InPrivate browser
207
- const reconnectTriggered = await isReconnectTriggered();
193
+ const reconnectTriggered = await (0, _reconnectChatHelper.isReconnectTriggered)(facadeChatSDK, props, dispatch, setAdapter, _startChat.initStartChat, state);
208
194
  if (!reconnectTriggered) {
209
195
  const inMemoryState = (0, _createReducer.executeReducer)(state, {
210
196
  type: _LiveChatWidgetActionType.LiveChatWidgetActionType.GET_IN_MEMORY_STATE,
@@ -1000,7 +986,9 @@ const LiveChatWidgetStateful = props => {
1000
986
  const endChatRelay = (adapter, skipEndChatSDK, skipCloseChat, postMessageToOtherTab) => (0, _endChat.endChat)(props, facadeChatSDK, state, dispatch, setAdapter, setWebChatStyles, adapter, skipEndChatSDK, skipCloseChat, postMessageToOtherTab);
1001
987
  const prepareStartChatRelay = () => (0, _startChat.prepareStartChat)(props, facadeChatSDK, state, dispatch, setAdapter);
1002
988
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
1003
- const initStartChatRelay = (optionalParams, persistedState) => (0, _startChat.initStartChat)(facadeChatSDK, dispatch, setAdapter, state, props, optionalParams, persistedState);
989
+ const initStartChatRelay = async (optionalParams, persistedState) => {
990
+ await (0, _startChat.initStartChat)(facadeChatSDK, dispatch, setAdapter, state, props, optionalParams, persistedState);
991
+ };
1004
992
  const confirmationPaneProps = (0, _initConfirmationPropsComposer.initConfirmationPropsComposer)(props);
1005
993
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
1006
994
  const prepareEndChatRelay = () => (0, _endChat.prepareEndChat)(props, facadeChatSDK, state, dispatch, setAdapter, setWebChatStyles, adapter);
@@ -0,0 +1,159 @@
1
+ "use strict";
2
+
3
+ Object.defineProperty(exports, "__esModule", {
4
+ value: true
5
+ });
6
+ exports.getAdaptiveCardSpeak = exports.createAttachmentForScreenReaderMiddleware = void 0;
7
+ var _react = _interopRequireWildcard(require("react"));
8
+ var _Constants = require("../../../../../common/Constants");
9
+ var _botframeworkWebchat = require("botframework-webchat");
10
+ function _interopRequireWildcard(e, t) { if ("function" == typeof WeakMap) var r = new WeakMap(), n = new WeakMap(); return (_interopRequireWildcard = function (e, t) { if (!t && e && e.__esModule) return e; var o, i, f = { __proto__: null, default: e }; if (null === e || "object" != typeof e && "function" != typeof e) return f; if (o = t ? n : r) { if (o.has(e)) return o.get(e); o.set(e, f); } for (const t in e) "default" !== t && {}.hasOwnProperty.call(e, t) && ((i = (o = Object.defineProperty) && Object.getOwnPropertyDescriptor(e, t)) && (i.get || i.set) ? o(f, t, i) : f[t] = e[t]); return f; })(e, t); }
11
+ function _slicedToArray(r, e) { return _arrayWithHoles(r) || _iterableToArrayLimit(r, e) || _unsupportedIterableToArray(r, e) || _nonIterableRest(); }
12
+ function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); }
13
+ function _unsupportedIterableToArray(r, a) { if (r) { if ("string" == typeof r) return _arrayLikeToArray(r, a); var t = {}.toString.call(r).slice(8, -1); return "Object" === t && r.constructor && (t = r.constructor.name), "Map" === t || "Set" === t ? Array.from(r) : "Arguments" === t || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t) ? _arrayLikeToArray(r, a) : void 0; } }
14
+ function _arrayLikeToArray(r, a) { (null == a || a > r.length) && (a = r.length); for (var e = 0, n = Array(a); e < a; e++) n[e] = r[e]; return n; }
15
+ function _iterableToArrayLimit(r, l) { var t = null == r ? null : "undefined" != typeof Symbol && r[Symbol.iterator] || r["@@iterator"]; if (null != t) { var e, n, i, u, a = [], f = !0, o = !1; try { if (i = (t = t.call(r)).next, 0 === l) { if (Object(t) !== t) return; f = !1; } else for (; !(f = (e = i.call(t)).done) && (a.push(e.value), a.length !== l); f = !0); } catch (r) { o = !0, n = r; } finally { try { if (!f && null != t.return && (u = t.return(), Object(u) !== u)) return; } finally { if (o) throw n; } } return a; } }
16
+ function _arrayWithHoles(r) { if (Array.isArray(r)) return r; } /* eslint-disable @typescript-eslint/no-explicit-any */ /******
17
+ * AttachmentForScreenReaderMiddleware
18
+ *
19
+ * Web Chat reads an Adaptive Card to screen readers only from the card's `speak` property.
20
+ * A card without `speak` is announced as "A card" with no content.
21
+ * This middleware sets `speak` from the visible text of the card, then lets Web Chat render it as usual.
22
+ ******/
23
+ const useAdaptiveCardsPackage = _botframeworkWebchat.hooks.useAdaptiveCardsPackage,
24
+ useStyleOptions = _botframeworkWebchat.hooks.useStyleOptions;
25
+ const ADAPTIVE_CARD_CONTENT_TYPE = "application/vnd.microsoft.card.adaptive";
26
+ const HTML_BLOCK_END = /<\/(p|li|h[1-6]|div|tr|td|th|blockquote|pre)>|<br\s*\/?>/gi;
27
+ // The "opens in a new window" icon of each link is left out: it describes the link target, not the content of the message.
28
+ const htmlToText = html => {
29
+ const body = new DOMParser().parseFromString(html.replace(HTML_BLOCK_END, "$& "), "text/html").body;
30
+ body.querySelectorAll(`script, style, template, img.${_Constants.Constants.OpenLinkIconCssClass}`).forEach(element => element.remove());
31
+ body.querySelectorAll("img").forEach(image => image.replaceWith(` ${image.getAttribute("alt") ?? ""} `));
32
+ return (body.textContent ?? "").replace(/\s+/g, " ").trim();
33
+ };
34
+
35
+ // Renders the element as the visible card does: Adaptive Cards formats {{DATE()}} and {{TIME()}}, then the Markdown is rendered.
36
+ // Web Chat sets the static Markdown handler before each visible render, and this restores the previous handler after rendering.
37
+ const getRenderedText = (element, AdaptiveCard, renderMarkdownAsHTML) => {
38
+ const previousOnProcessMarkdown = AdaptiveCard.onProcessMarkdown;
39
+ try {
40
+ AdaptiveCard.onProcessMarkdown = (text, result) => {
41
+ result.outputHtml = renderMarkdownAsHTML(text);
42
+ result.didProcess = true;
43
+ };
44
+ const renderedElement = element.render();
45
+ return renderedElement ? htmlToText(renderedElement.outerHTML) : "";
46
+ } catch {
47
+ var _element$asString;
48
+ return ((_element$asString = element.asString) === null || _element$asString === void 0 ? void 0 : _element$asString.call(element)) ?? "";
49
+ } finally {
50
+ AdaptiveCard.onProcessMarkdown = previousOnProcessMarkdown;
51
+ }
52
+ };
53
+
54
+ // Collects the visible text of the card in document order, after the parser has applied element fallbacks.
55
+ // Inputs and actions are not collected because Web Chat already lists them after the card text.
56
+ const getAdaptiveCardSpeak = (content, adaptiveCardsPackage, renderMarkdownAsHTML, adaptiveCardsParserMaxVersion) => {
57
+ const AdaptiveCard = adaptiveCardsPackage.AdaptiveCard,
58
+ FactSet = adaptiveCardsPackage.FactSet,
59
+ Image = adaptiveCardsPackage.Image,
60
+ RichTextBlock = adaptiveCardsPackage.RichTextBlock,
61
+ SerializationContext = adaptiveCardsPackage.SerializationContext,
62
+ TextBlock = adaptiveCardsPackage.TextBlock,
63
+ Version = adaptiveCardsPackage.Version;
64
+ const maxVersion = adaptiveCardsParserMaxVersion ? Version.parse(adaptiveCardsParserMaxVersion, new SerializationContext()) : undefined;
65
+ const card = new AdaptiveCard();
66
+ const texts = [];
67
+ card.parse(content, new SerializationContext(maxVersion !== null && maxVersion !== void 0 && maxVersion.isValid ? maxVersion : undefined));
68
+ const getFactText = (factSet, text) => {
69
+ const textBlock = new TextBlock(text);
70
+ textBlock.setParent(factSet);
71
+ return getRenderedText(textBlock, AdaptiveCard, renderMarkdownAsHTML);
72
+ };
73
+ const walk = element => {
74
+ if (!(element !== null && element !== void 0 && element.isVisible)) {
75
+ return;
76
+ }
77
+ if (element instanceof TextBlock || element instanceof RichTextBlock) {
78
+ texts.push(getRenderedText(element, AdaptiveCard, renderMarkdownAsHTML));
79
+ } else if (element instanceof FactSet) {
80
+ element.facts.forEach(_ref => {
81
+ let name = _ref.name,
82
+ value = _ref.value;
83
+ texts.push([name, value].map(text => text ? getFactText(element, text) : "").filter(Boolean).join(": "));
84
+ });
85
+ } else if (element instanceof Image) {
86
+ texts.push(element.altText);
87
+ }
88
+ if (element.getItemAt && element.getItemCount) {
89
+ for (let index = 0, count = element.getItemCount(); index < count; index++) {
90
+ walk(element.getItemAt(index));
91
+ }
92
+ }
93
+ };
94
+ walk(card);
95
+ return texts.filter(text => typeof text === "string" && text).join(" ").replace(/\s+/g, " ").trim();
96
+ };
97
+ exports.getAdaptiveCardSpeak = getAdaptiveCardSpeak;
98
+ const AdaptiveCardForScreenReader = _ref2 => {
99
+ let args = _ref2.args,
100
+ next = _ref2.next,
101
+ renderMarkdownAsHTML = _ref2.renderMarkdownAsHTML;
102
+ const _useAdaptiveCardsPack = useAdaptiveCardsPackage(),
103
+ _useAdaptiveCardsPack2 = _slicedToArray(_useAdaptiveCardsPack, 1),
104
+ adaptiveCardsPackage = _useAdaptiveCardsPack2[0];
105
+ const _useStyleOptions = useStyleOptions(),
106
+ _useStyleOptions2 = _slicedToArray(_useStyleOptions, 1),
107
+ adaptiveCardsParserMaxVersion = _useStyleOptions2[0].adaptiveCardsParserMaxVersion;
108
+ const _args = _slicedToArray(args, 1),
109
+ options = _args[0];
110
+ const attachment = options.attachment;
111
+
112
+ // The widget creates a new Markdown renderer on each render with the same settings, so the text is computed once for each attachment.
113
+ const contentWithSpeak = (0, _react.useMemo)(() => {
114
+ try {
115
+ const content = typeof attachment.content === "string" ? JSON.parse(attachment.content) : attachment.content;
116
+ if (!content || typeof content !== "object" || content.speak) {
117
+ return undefined;
118
+ }
119
+ const speak = getAdaptiveCardSpeak(content, adaptiveCardsPackage, renderMarkdownAsHTML, adaptiveCardsParserMaxVersion);
120
+ return speak ? {
121
+ ...content,
122
+ speak
123
+ } : undefined;
124
+ } catch {
125
+ return undefined;
126
+ }
127
+ }, [adaptiveCardsPackage, adaptiveCardsParserMaxVersion, attachment]);
128
+ const render = contentWithSpeak ? next({
129
+ ...options,
130
+ attachment: {
131
+ ...attachment,
132
+ content: contentWithSpeak
133
+ }
134
+ }, ...args.slice(1)) : next(...args);
135
+ return typeof render === "function" ? render() : null;
136
+ };
137
+ const createAttachmentForScreenReaderMiddleware = renderMarkdownAsHTML => {
138
+ const attachmentForScreenReaderMiddleware = () => next => function () {
139
+ var _args$;
140
+ for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
141
+ args[_key] = arguments[_key];
142
+ }
143
+ const attachment = (_args$ = args[0]) === null || _args$ === void 0 ? void 0 : _args$.attachment;
144
+
145
+ // Web Chat renders nothing for a card without content, so it is left to Web Chat.
146
+ if ((attachment === null || attachment === void 0 ? void 0 : attachment.contentType) !== ADAPTIVE_CARD_CONTENT_TYPE || !attachment.content) {
147
+ return next(...args);
148
+ }
149
+
150
+ // eslint-disable-next-line react/display-name
151
+ return () => /*#__PURE__*/_react.default.createElement(AdaptiveCardForScreenReader, {
152
+ args: args,
153
+ next: next,
154
+ renderMarkdownAsHTML: renderMarkdownAsHTML
155
+ });
156
+ };
157
+ return attachmentForScreenReaderMiddleware;
158
+ };
159
+ exports.createAttachmentForScreenReaderMiddleware = createAttachmentForScreenReaderMiddleware;
@@ -112,6 +112,7 @@ export let TelemetryEvent = /*#__PURE__*/function (TelemetryEvent) {
112
112
  TelemetryEvent["RecoveryEligibilityEvaluated"] = "RecoveryEligibilityEvaluated";
113
113
  TelemetryEvent["GetConversationDetailsCallStarted"] = "GetConversationDetailsCallStarted";
114
114
  TelemetryEvent["GetConversationDetailsCallFailed"] = "GetConversationDetailsCallFailed";
115
+ TelemetryEvent["UpdateTelemetryDataFailed"] = "UpdateTelemetryDataFailed";
115
116
  TelemetryEvent["EndChatSDKCallFailed"] = "EndChatSDKCallFailed";
116
117
  TelemetryEvent["DisconnectEndChatSDKCallFailed"] = "DisconnectEndChatSDKCallFailed";
117
118
  TelemetryEvent["GetChatReconnectContextSDKCallStarted"] = "GetChatReconnectContextSDKCallStarted";
@@ -428,6 +429,7 @@ export let TelemetryConstants = /*#__PURE__*/function () {
428
429
  case TelemetryEvent.OnNewMessageFailed:
429
430
  case TelemetryEvent.OnNewMessageAudioNotificationFailed:
430
431
  case TelemetryEvent.GetConversationDetailsCallFailed:
432
+ case TelemetryEvent.UpdateTelemetryDataFailed:
431
433
  case TelemetryEvent.EndChatSDKCall:
432
434
  case TelemetryEvent.EndChatEventReceived:
433
435
  case TelemetryEvent.EndChatSDKCallFailed:
@@ -15,6 +15,7 @@ import createAttachmentSentAnnouncementMiddleware from "../../webchatcontainerst
15
15
  import channelDataMiddleware from "../../webchatcontainerstateful/webchatcontroller/middlewares/storemiddlewares/channelDataMiddleware";
16
16
  import { createActivityMiddleware } from "../../webchatcontainerstateful/webchatcontroller/middlewares/renderingmiddlewares/activityMiddleware";
17
17
  import { createActivityStatusMiddleware } from "../../webchatcontainerstateful/webchatcontroller/middlewares/renderingmiddlewares/activityStatusMiddleware";
18
+ import { createAttachmentForScreenReaderMiddleware } from "../../webchatcontainerstateful/webchatcontroller/middlewares/renderingmiddlewares/attachmentForScreenReaderMiddleware";
18
19
  import { createAttachmentMiddleware } from "../../webchatcontainerstateful/webchatcontroller/middlewares/renderingmiddlewares/attachmentMiddleware";
19
20
  import createAttachmentUploadValidatorMiddleware from "../../webchatcontainerstateful/webchatcontroller/middlewares/storemiddlewares/attachmentUploadValidatorMiddleware";
20
21
  import { createAvatarMiddleware } from "../../webchatcontainerstateful/webchatcontroller/middlewares/renderingmiddlewares/avatarMiddleware";
@@ -42,6 +43,31 @@ import htmlPlayerMiddleware from "../../webchatcontainerstateful/webchatcontroll
42
43
  import htmlTextMiddleware from "../../webchatcontainerstateful/webchatcontroller/middlewares/storemiddlewares/htmlTextMiddleware";
43
44
  import preProcessingMiddleware from "../../webchatcontainerstateful/webchatcontroller/middlewares/storemiddlewares/preProcessingMiddleware";
44
45
  import sanitizationMiddleware from "../../webchatcontainerstateful/webchatcontroller/middlewares/storemiddlewares/sanitizationMiddleware";
46
+ const markdownSanitizeConfig = {
47
+ FORBID_TAGS: ["form", "button", "script", "div", "input"],
48
+ FORBID_ATTR: ["action"],
49
+ ADD_ATTR: ["target"]
50
+ };
51
+
52
+ /**
53
+ * Renders Markdown for the screen reader text of Adaptive Cards, from the same pieces as the visible card:
54
+ * the host renderMarkdown when set, the hyperlink text override, and the same sanitization.
55
+ * Markdown is always formatted, also when the widget shows Markdown unformatted, so that screen readers do not read the syntax.
56
+ * Styles are removed with their content because the card does not show them.
57
+ */
58
+ export const createScreenReaderMarkdownRenderer = webChatContainerProps => {
59
+ var _webChatContainerProp;
60
+ const hostRenderMarkdown = webChatContainerProps === null || webChatContainerProps === void 0 || (_webChatContainerProp = webChatContainerProps.webChatProps) === null || _webChatContainerProp === void 0 ? void 0 : _webChatContainerProp.renderMarkdown;
61
+ const markdown = createMarkdown(false, (webChatContainerProps === null || webChatContainerProps === void 0 ? void 0 : webChatContainerProps.disableNewLineMarkdownSupport) ?? defaultWebChatContainerStatefulProps.disableNewLineMarkdownSupport, webChatContainerProps === null || webChatContainerProps === void 0 ? void 0 : webChatContainerProps.opensMarkdownLinksInSameTab);
62
+ const hyperlinkTextOverrideRenderer = new HyperlinkTextOverrideRenderer((webChatContainerProps === null || webChatContainerProps === void 0 ? void 0 : webChatContainerProps.hyperlinkTextOverride) ?? defaultWebChatContainerStatefulProps.hyperlinkTextOverride);
63
+ return text => {
64
+ const html = hostRenderMarkdown ? hostRenderMarkdown(text) : markdown.render(text);
65
+ return DOMPurify.sanitize(hyperlinkTextOverrideRenderer.render(html), {
66
+ ...markdownSanitizeConfig,
67
+ FORBID_TAGS: [...markdownSanitizeConfig.FORBID_TAGS, "style"]
68
+ });
69
+ };
70
+ };
45
71
 
46
72
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
47
73
  export const initWebChatComposer = (props, state, dispatch, facadeChatSDK, endChat) => {
@@ -149,12 +175,7 @@ export const initWebChatComposer = (props, state, dispatch, facadeChatSDK, endCh
149
175
  });
150
176
 
151
177
  // EXISTING sanitization (continues to work as before)
152
- const config = {
153
- FORBID_TAGS: ["form", "button", "script", "div", "input"],
154
- FORBID_ATTR: ["action"],
155
- ADD_ATTR: ["target"]
156
- };
157
- text = DOMPurify.sanitize(text, config);
178
+ text = DOMPurify.sanitize(text, markdownSanitizeConfig);
158
179
 
159
180
  // MONITOR-ONLY: Test what the stricter allowlist would remove (Phase 1)
160
181
  // This does NOT modify the text, only logs telemetry
@@ -358,6 +379,7 @@ export const initWebChatComposer = (props, state, dispatch, facadeChatSDK, endCh
358
379
  store: webChatStore,
359
380
  activityMiddleware: (_props$webChatContain0 = props.webChatContainerProps) !== null && _props$webChatContain0 !== void 0 && (_props$webChatContain0 = _props$webChatContain0.renderingMiddlewareProps) !== null && _props$webChatContain0 !== void 0 && _props$webChatContain0.disableActivityMiddleware ? undefined : createActivityMiddleware(renderMarkdown, (_state$domainStates$r = state.domainStates.renderingMiddlewareProps) === null || _state$domainStates$r === void 0 ? void 0 : _state$domainStates$r.systemMessageStyleProps, (_state$domainStates$r2 = state.domainStates.renderingMiddlewareProps) === null || _state$domainStates$r2 === void 0 ? void 0 : _state$domainStates$r2.userMessageStyleProps, localizedTexts),
360
381
  attachmentMiddleware: (_props$webChatContain1 = props.webChatContainerProps) !== null && _props$webChatContain1 !== void 0 && (_props$webChatContain1 = _props$webChatContain1.renderingMiddlewareProps) !== null && _props$webChatContain1 !== void 0 && _props$webChatContain1.disableAttachmentMiddleware ? undefined : createAttachmentMiddleware(((_state$domainStates$r3 = state.domainStates.renderingMiddlewareProps) === null || _state$domainStates$r3 === void 0 || (_state$domainStates$r3 = _state$domainStates$r3.attachmentProps) === null || _state$domainStates$r3 === void 0 ? void 0 : _state$domainStates$r3.enableInlinePlaying) ?? defaultAttachmentProps.enableInlinePlaying),
382
+ attachmentForScreenReaderMiddleware: createAttachmentForScreenReaderMiddleware(createScreenReaderMarkdownRenderer(props.webChatContainerProps)),
361
383
  activityStatusMiddleware: (_props$webChatContain10 = props.webChatContainerProps) !== null && _props$webChatContain10 !== void 0 && (_props$webChatContain10 = _props$webChatContain10.renderingMiddlewareProps) !== null && _props$webChatContain10 !== void 0 && _props$webChatContain10.disableActivityStatusMiddleware ? undefined : createActivityStatusMiddleware(getLocaleStringFromId((_state$domainStates$l5 = state.domainStates.liveChatConfig) === null || _state$domainStates$l5 === void 0 || (_state$domainStates$l5 = _state$domainStates$l5.ChatWidgetLanguage) === null || _state$domainStates$l5 === void 0 ? void 0 : _state$domainStates$l5.msdyn_localeid)),
362
384
  toastMiddleware: (_props$webChatContain11 = props.webChatContainerProps) !== null && _props$webChatContain11 !== void 0 && (_props$webChatContain11 = _props$webChatContain11.renderingMiddlewareProps) !== null && _props$webChatContain11 !== void 0 && _props$webChatContain11.disableToastMiddleware ? undefined : createToastMiddleware(props.notificationPaneProps, endChat),
363
385
  renderMarkdown,
@@ -7,6 +7,7 @@ import { BroadcastService } from "@microsoft/omnichannel-chat-components";
7
7
  import { ConversationState } from "../../../contexts/common/ConversationState";
8
8
  import { LiveChatWidgetActionType } from "../../../contexts/common/LiveChatWidgetActionType";
9
9
  import { TelemetryHelper } from "../../../common/telemetry/TelemetryHelper";
10
+ import { executeReducer } from "../../../contexts/createReducer";
10
11
  import { handleStartChatError } from "./startChatErrorHandler";
11
12
 
12
13
  // Return value: should start normal chat flow when reconnect is enabled
@@ -50,6 +51,32 @@ const handleChatReconnect = async (facadeChatSDK, props, dispatch, setAdapter, i
50
51
  return true;
51
52
  };
52
53
 
54
+ /**
55
+ * Returns true when chat reconnect took over the start: it started the chat itself or showed the reconnect pane.
56
+ * In that case the caller must not start another chat.
57
+ */
58
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
59
+ const isReconnectTriggered = async (facadeChatSDK, props, dispatch, setAdapter, initStartChat, state) => {
60
+ if (isReconnectEnabled(props.chatConfig) === true && !isPersistentEnabled(props.chatConfig)) {
61
+ let reconnectChatStarted = false;
62
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
63
+ const initStartChatAndTrack = async function () {
64
+ reconnectChatStarted = await initStartChat(...arguments);
65
+ };
66
+ const noValidReconnectId = await handleChatReconnect(facadeChatSDK, props, dispatch, setAdapter, initStartChatAndTrack, state);
67
+ // initStartChat resolves before React renders Active, so the in-memory state can still read Loading here.
68
+ // Its result tells whether reconnect started the chat; the in-memory state covers the reconnect pane.
69
+ const inMemoryState = executeReducer(state, {
70
+ type: LiveChatWidgetActionType.GET_IN_MEMORY_STATE,
71
+ payload: null
72
+ });
73
+ if (!noValidReconnectId && (reconnectChatStarted || inMemoryState.appStates.conversationState === ConversationState.Active || inMemoryState.appStates.conversationState === ConversationState.ReconnectChat)) {
74
+ return true;
75
+ }
76
+ }
77
+ return false;
78
+ };
79
+
53
80
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
54
81
  const getChatReconnectContext = async (facadeChatSDK, chatConfig, props, isAuthenticatedChat, dispatch) => {
55
82
  try {
@@ -143,4 +170,4 @@ const isPersistentEnabled = chatConfig => {
143
170
  const hasReconnectId = reconnectAvailabilityResponse => {
144
171
  return reconnectAvailabilityResponse && !isNullOrUndefined(reconnectAvailabilityResponse.reconnectId);
145
172
  };
146
- export { handleChatReconnect, isReconnectEnabled, isPersistentEnabled, getChatReconnectContext };
173
+ export { handleChatReconnect, isReconnectTriggered, isReconnectEnabled, isPersistentEnabled, getChatReconnectContext };
@@ -62,7 +62,7 @@ const getGuard = (guards, facadeChatSDK) => {
62
62
  * Runs `operation` only if no other invocation for the same widget instance is already in
63
63
  * flight. Concurrent invocations are dropped (and reported through telemetry) rather than
64
64
  * awaiting the in-flight promise, so a future re-entrant call can never deadlock on itself.
65
- * No caller acts on the resolved value, so dropping is safe.
65
+ * A dropped invocation resolves to `undefined`.
66
66
  *
67
67
  * `blockedBy` lets an operation also yield to a different, already running operation for the
68
68
  * same widget instance without claiming that operation's lock.
@@ -78,14 +78,14 @@ const runExclusively = async (guards, facadeChatSDK, description, operation, pro
78
78
  WidgetCacheId: props ? getWidgetCacheIdfromProps(props) : undefined
79
79
  }
80
80
  });
81
- return;
81
+ return undefined;
82
82
  }
83
83
 
84
84
  // Claim the lock before invoking the operation, so a re-entrant call made from the
85
85
  // operation's synchronous preamble (before its first await) cannot slip past the check above.
86
86
  guard.inFlight = true;
87
87
  try {
88
- await operation();
88
+ return await operation();
89
89
  } finally {
90
90
  guard.inFlight = false;
91
91
  }
@@ -221,9 +221,14 @@ const setPreChatAndInitiateChat = async (facadeChatSDK, dispatch, setAdapter, is
221
221
  await initStartChat(facadeChatSDK, dispatch, setAdapter, state, props, optionalParams);
222
222
  };
223
223
 
224
+ /**
225
+ * Resolves to `true` when the chat reached Active, and `false` when it failed or the call was dropped.
226
+ * It resolves before React renders Active, so callers must use this value rather than reading the conversation state.
227
+ */
224
228
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
225
229
  const initStartChat = async (facadeChatSDK, dispatch, setAdapter, state, props, params, persistedState) => {
226
- return runExclusively(initStartChatGuards, facadeChatSDK, "Concurrent initStartChat call ignored, a start chat operation is already in progress for this widget instance.", () => initStartChatInternal(facadeChatSDK, dispatch, setAdapter, state, props, params, persistedState), props);
230
+ const chatStarted = await runExclusively(initStartChatGuards, facadeChatSDK, "Concurrent initStartChat call ignored, a start chat operation is already in progress for this widget instance.", () => initStartChatInternal(facadeChatSDK, dispatch, setAdapter, state, props, params, persistedState), props);
231
+ return chatStarted === true;
227
232
  };
228
233
 
229
234
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
@@ -337,7 +342,7 @@ const initStartChatInternal = async (facadeChatSDK, dispatch, setAdapter, state,
337
342
  logWidgetLoadComplete(WidgetLoadTelemetryMessage.PersistedStateRetrievedMessage);
338
343
  // Set post chat context in state, load in background to do not block the load
339
344
  setPostChatContextAndLoadSurvey(facadeChatSDK, dispatch, true);
340
- return;
345
+ return true;
341
346
  }
342
347
 
343
348
  // Persistent Chat relies on the `reconnectId` retrieved from reconnectablechats API to reconnect upon start chat and not `liveChatContext`
@@ -353,10 +358,13 @@ const initStartChatInternal = async (facadeChatSDK, dispatch, setAdapter, state,
353
358
  logWidgetLoadComplete();
354
359
  // Set post chat context in state, load in background to do not block the load
355
360
  setPostChatContextAndLoadSurvey(facadeChatSDK, dispatch);
356
- // Updating chat session detail for telemetry
357
- await updateTelemetryData(facadeChatSDK, dispatch);
361
+ // Updating chat session detail for telemetry, in background: getConversationDetails retries until the
362
+ // live work item exists (several seconds), and awaiting it would hold the start chat locks and drop the next start chat
363
+ updateTelemetryData(facadeChatSDK, dispatch);
364
+ return true;
358
365
  } catch (ex) {
359
366
  handleStartChatError(dispatch, facadeChatSDK, props, ex, isStartChatSuccessful);
367
+ return false;
360
368
  }
361
369
  };
362
370
 
@@ -1,4 +1,4 @@
1
- import { BroadcastEvent } from "../../../common/telemetry/TelemetryConstants";
1
+ import { BroadcastEvent, LogLevel, TelemetryEvent } from "../../../common/telemetry/TelemetryConstants";
2
2
  import { BroadcastService } from "@microsoft/omnichannel-chat-components";
3
3
  import { LiveChatWidgetActionType } from "../../../contexts/common/LiveChatWidgetActionType";
4
4
  import { TelemetryHelper } from "../../../common/telemetry/TelemetryHelper";
@@ -7,15 +7,41 @@ import { getConversationDetailsCall } from "../../../common/utils";
7
7
 
8
8
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
9
9
  export const updateTelemetryData = async (facadeChatSDK, dispatch) => {
10
- // load it concurrently, this will reduce the load time
11
- await Promise.all([updateSessionDataForTelemetry(facadeChatSDK, dispatch), updateConversationDataForTelemetry(facadeChatSDK, dispatch)]);
10
+ var _facadeChatSDK$getCha;
11
+ // startChat no longer waits for this, so the next chat can start (chatSDKStateCleanUp assigns a new requestId)
12
+ // before these calls resolve. Results for an earlier chat must not overwrite the current chat's data.
13
+ // endChat also assigns a new requestId, so the chat that just ended still applies its own results.
14
+ const requestId = facadeChatSDK === null || facadeChatSDK === void 0 || (_facadeChatSDK$getCha = facadeChatSDK.getChatSDK()) === null || _facadeChatSDK$getCha === void 0 ? void 0 : _facadeChatSDK$getCha.requestId;
15
+ try {
16
+ // load it concurrently, this will reduce the load time
17
+ await Promise.all([updateSessionDataForTelemetry(facadeChatSDK, dispatch, requestId), updateConversationDataForTelemetry(facadeChatSDK, dispatch, requestId)]);
18
+ } catch (error) {
19
+ TelemetryHelper.logSDKEvent(LogLevel.ERROR, {
20
+ Event: TelemetryEvent.UpdateTelemetryDataFailed,
21
+ ExceptionDetails: {
22
+ exception: `Update telemetry data failed: ${error}`
23
+ }
24
+ });
25
+ }
26
+ };
27
+
28
+ // The requestId alone isn't enough: endChat also replaces it. Only the next chat's startChat gets a new chat token
29
+ // (endChat and chatSDKStateCleanUp clear it), so drop the result only when the SDK holds that next chat.
30
+ const isFromEarlierChat = (facadeChatSDK, requestId) => {
31
+ var _chatSDK$chatToken;
32
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
33
+ const chatSDK = facadeChatSDK.getChatSDK();
34
+ return (chatSDK === null || chatSDK === void 0 ? void 0 : chatSDK.requestId) !== requestId && !!(chatSDK !== null && chatSDK !== void 0 && (_chatSDK$chatToken = chatSDK.chatToken) !== null && _chatSDK$chatToken !== void 0 && _chatSDK$chatToken.chatId);
12
35
  };
13
36
 
14
37
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
15
- const updateSessionDataForTelemetry = async (facadeChatSDK, dispatch) => {
38
+ const updateSessionDataForTelemetry = async (facadeChatSDK, dispatch, requestId) => {
16
39
  if (facadeChatSDK && facadeChatSDK.getChatSDK()) {
17
40
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
18
41
  const chatSession = await facadeChatSDK.getCurrentLiveChatContext();
42
+ if (isFromEarlierChat(facadeChatSDK, requestId)) {
43
+ return;
44
+ }
19
45
  const telemetryData = TelemetryHelper.addSessionDataToTelemetry(chatSession, TelemetryManager.InternalTelemetryData);
20
46
  dispatch({
21
47
  type: LiveChatWidgetActionType.SET_TELEMETRY_DATA,
@@ -31,10 +57,13 @@ const updateSessionDataForTelemetry = async (facadeChatSDK, dispatch) => {
31
57
  };
32
58
 
33
59
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
34
- const updateConversationDataForTelemetry = async (facadeChatSDK, dispatch) => {
60
+ const updateConversationDataForTelemetry = async (facadeChatSDK, dispatch, requestId) => {
35
61
  if (facadeChatSDK && facadeChatSDK.getChatSDK()) {
36
62
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
37
63
  const liveWorkItem = await getConversationDetailsCall(facadeChatSDK);
64
+ if (isFromEarlierChat(facadeChatSDK, requestId)) {
65
+ return;
66
+ }
38
67
  const telemetryData = TelemetryHelper.addConversationDataToTelemetry(liveWorkItem, TelemetryManager.InternalTelemetryData);
39
68
  dispatch({
40
69
  type: LiveChatWidgetActionType.SET_TELEMETRY_DATA,
@@ -17,7 +17,7 @@ import { checkIfConversationStillValid, initStartChat, prepareStartChat, setPreC
17
17
  import { createTimer, getBroadcastChannelName, getConversationDetailsCall, getLocaleDirection, getStateFromCache, getWidgetCacheIdfromProps, getWidgetEndChatEventName, isNullOrEmptyString, isNullOrUndefined, isThisSessionPopout, isUndefinedOrEmpty, setAriaHiddenForSiblings, setOcUserAgent } from "../../../common/utils";
18
18
  import { customEventCallback, subscribeToSendCustomEvent } from "../common/customEventHandler";
19
19
  import { defaultClientDataStoreProvider, isCookieAllowed } from "../../../common/storage/default/defaultClientDataStoreProvider";
20
- import { handleChatReconnect, isPersistentEnabled, isReconnectEnabled } from "../common/reconnectChatHelper";
20
+ import { isPersistentEnabled, isReconnectTriggered } from "../common/reconnectChatHelper";
21
21
  import { shouldShowCallingContainer, shouldShowChatButton, shouldShowConfirmationPane, shouldShowEmailTranscriptPane, shouldShowHeader, shouldShowLoadingPane, shouldShowOutOfOfficeHoursPane, shouldShowPostChatLoadingPane, shouldShowPostChatSurveyPane, shouldShowPreChatSurveyPane, shouldShowProactiveChatPane, shouldShowReconnectChatPane, shouldShowStartChatErrorPane, shouldShowWebChatContainer } from "../../../controller/componentController";
22
22
  import { ActivityStreamHandler } from "../common/ActivityStreamHandler";
23
23
  import CallingContainerStateful from "../../callingcontainerstateful/CallingContainerStateful";
@@ -156,20 +156,6 @@ export const LiveChatWidgetStateful = props => {
156
156
 
157
157
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
158
158
  const startChat = async (props, localState) => {
159
- const isReconnectTriggered = async () => {
160
- if (isReconnectEnabled(props.chatConfig) === true && !isPersistentEnabled(props.chatConfig)) {
161
- const noValidReconnectId = await handleChatReconnect(facadeChatSDK, props, dispatch, setAdapter, initStartChat, state);
162
- const inMemoryState = executeReducer(state, {
163
- type: LiveChatWidgetActionType.GET_IN_MEMORY_STATE,
164
- payload: null
165
- });
166
- // If chat reconnect has kicked in chat state will become Active or Reconnect. So just exit, else go next
167
- if (!noValidReconnectId && (inMemoryState.appStates.conversationState === ConversationState.Active || inMemoryState.appStates.conversationState === ConversationState.ReconnectChat)) {
168
- return true;
169
- }
170
- }
171
- return false;
172
- };
173
159
  let isChatValid = false;
174
160
  //Start a chat from cache/reconnectid
175
161
  if (activeCachedChatExist === true) {
@@ -181,7 +167,7 @@ export const LiveChatWidgetStateful = props => {
181
167
  //Check if conversation state is not in wrapup or closed state
182
168
  isChatValid = await checkIfConversationStillValid(facadeChatSDK, dispatch, state);
183
169
  if (isChatValid === true) {
184
- const reconnectTriggered = await isReconnectTriggered();
170
+ const reconnectTriggered = await isReconnectTriggered(facadeChatSDK, props, dispatch, setAdapter, initStartChat, state);
185
171
  if (!reconnectTriggered) {
186
172
  await initStartChat(facadeChatSDK, dispatch, setAdapter, state, props, optionalParams);
187
173
  }
@@ -197,7 +183,7 @@ export const LiveChatWidgetStateful = props => {
197
183
  if (isChatValid === false) {
198
184
  if (localState) {
199
185
  // adding the reconnect logic for the case when customer tries to reconnect from a new browser or InPrivate browser
200
- const reconnectTriggered = await isReconnectTriggered();
186
+ const reconnectTriggered = await isReconnectTriggered(facadeChatSDK, props, dispatch, setAdapter, initStartChat, state);
201
187
  if (!reconnectTriggered) {
202
188
  const inMemoryState = executeReducer(state, {
203
189
  type: LiveChatWidgetActionType.GET_IN_MEMORY_STATE,
@@ -993,7 +979,9 @@ export const LiveChatWidgetStateful = props => {
993
979
  const endChatRelay = (adapter, skipEndChatSDK, skipCloseChat, postMessageToOtherTab) => endChat(props, facadeChatSDK, state, dispatch, setAdapter, setWebChatStyles, adapter, skipEndChatSDK, skipCloseChat, postMessageToOtherTab);
994
980
  const prepareStartChatRelay = () => prepareStartChat(props, facadeChatSDK, state, dispatch, setAdapter);
995
981
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
996
- const initStartChatRelay = (optionalParams, persistedState) => initStartChat(facadeChatSDK, dispatch, setAdapter, state, props, optionalParams, persistedState);
982
+ const initStartChatRelay = async (optionalParams, persistedState) => {
983
+ await initStartChat(facadeChatSDK, dispatch, setAdapter, state, props, optionalParams, persistedState);
984
+ };
997
985
  const confirmationPaneProps = initConfirmationPropsComposer(props);
998
986
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
999
987
  const prepareEndChatRelay = () => prepareEndChat(props, facadeChatSDK, state, dispatch, setAdapter, setWebChatStyles, adapter);
@@ -0,0 +1,153 @@
1
+ function _slicedToArray(r, e) { return _arrayWithHoles(r) || _iterableToArrayLimit(r, e) || _unsupportedIterableToArray(r, e) || _nonIterableRest(); }
2
+ function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); }
3
+ function _unsupportedIterableToArray(r, a) { if (r) { if ("string" == typeof r) return _arrayLikeToArray(r, a); var t = {}.toString.call(r).slice(8, -1); return "Object" === t && r.constructor && (t = r.constructor.name), "Map" === t || "Set" === t ? Array.from(r) : "Arguments" === t || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t) ? _arrayLikeToArray(r, a) : void 0; } }
4
+ function _arrayLikeToArray(r, a) { (null == a || a > r.length) && (a = r.length); for (var e = 0, n = Array(a); e < a; e++) n[e] = r[e]; return n; }
5
+ function _iterableToArrayLimit(r, l) { var t = null == r ? null : "undefined" != typeof Symbol && r[Symbol.iterator] || r["@@iterator"]; if (null != t) { var e, n, i, u, a = [], f = !0, o = !1; try { if (i = (t = t.call(r)).next, 0 === l) { if (Object(t) !== t) return; f = !1; } else for (; !(f = (e = i.call(t)).done) && (a.push(e.value), a.length !== l); f = !0); } catch (r) { o = !0, n = r; } finally { try { if (!f && null != t.return && (u = t.return(), Object(u) !== u)) return; } finally { if (o) throw n; } } return a; } }
6
+ function _arrayWithHoles(r) { if (Array.isArray(r)) return r; }
7
+ /* eslint-disable @typescript-eslint/no-explicit-any */
8
+ /******
9
+ * AttachmentForScreenReaderMiddleware
10
+ *
11
+ * Web Chat reads an Adaptive Card to screen readers only from the card's `speak` property.
12
+ * A card without `speak` is announced as "A card" with no content.
13
+ * This middleware sets `speak` from the visible text of the card, then lets Web Chat render it as usual.
14
+ ******/
15
+
16
+ import React, { useMemo } from "react";
17
+ import { Constants } from "../../../../../common/Constants";
18
+ import { hooks } from "botframework-webchat";
19
+ const useAdaptiveCardsPackage = hooks.useAdaptiveCardsPackage,
20
+ useStyleOptions = hooks.useStyleOptions;
21
+ const ADAPTIVE_CARD_CONTENT_TYPE = "application/vnd.microsoft.card.adaptive";
22
+ const HTML_BLOCK_END = /<\/(p|li|h[1-6]|div|tr|td|th|blockquote|pre)>|<br\s*\/?>/gi;
23
+ // The "opens in a new window" icon of each link is left out: it describes the link target, not the content of the message.
24
+ const htmlToText = html => {
25
+ const body = new DOMParser().parseFromString(html.replace(HTML_BLOCK_END, "$& "), "text/html").body;
26
+ body.querySelectorAll(`script, style, template, img.${Constants.OpenLinkIconCssClass}`).forEach(element => element.remove());
27
+ body.querySelectorAll("img").forEach(image => image.replaceWith(` ${image.getAttribute("alt") ?? ""} `));
28
+ return (body.textContent ?? "").replace(/\s+/g, " ").trim();
29
+ };
30
+
31
+ // Renders the element as the visible card does: Adaptive Cards formats {{DATE()}} and {{TIME()}}, then the Markdown is rendered.
32
+ // Web Chat sets the static Markdown handler before each visible render, and this restores the previous handler after rendering.
33
+ const getRenderedText = (element, AdaptiveCard, renderMarkdownAsHTML) => {
34
+ const previousOnProcessMarkdown = AdaptiveCard.onProcessMarkdown;
35
+ try {
36
+ AdaptiveCard.onProcessMarkdown = (text, result) => {
37
+ result.outputHtml = renderMarkdownAsHTML(text);
38
+ result.didProcess = true;
39
+ };
40
+ const renderedElement = element.render();
41
+ return renderedElement ? htmlToText(renderedElement.outerHTML) : "";
42
+ } catch {
43
+ var _element$asString;
44
+ return ((_element$asString = element.asString) === null || _element$asString === void 0 ? void 0 : _element$asString.call(element)) ?? "";
45
+ } finally {
46
+ AdaptiveCard.onProcessMarkdown = previousOnProcessMarkdown;
47
+ }
48
+ };
49
+
50
+ // Collects the visible text of the card in document order, after the parser has applied element fallbacks.
51
+ // Inputs and actions are not collected because Web Chat already lists them after the card text.
52
+ export const getAdaptiveCardSpeak = (content, adaptiveCardsPackage, renderMarkdownAsHTML, adaptiveCardsParserMaxVersion) => {
53
+ const AdaptiveCard = adaptiveCardsPackage.AdaptiveCard,
54
+ FactSet = adaptiveCardsPackage.FactSet,
55
+ Image = adaptiveCardsPackage.Image,
56
+ RichTextBlock = adaptiveCardsPackage.RichTextBlock,
57
+ SerializationContext = adaptiveCardsPackage.SerializationContext,
58
+ TextBlock = adaptiveCardsPackage.TextBlock,
59
+ Version = adaptiveCardsPackage.Version;
60
+ const maxVersion = adaptiveCardsParserMaxVersion ? Version.parse(adaptiveCardsParserMaxVersion, new SerializationContext()) : undefined;
61
+ const card = new AdaptiveCard();
62
+ const texts = [];
63
+ card.parse(content, new SerializationContext(maxVersion !== null && maxVersion !== void 0 && maxVersion.isValid ? maxVersion : undefined));
64
+ const getFactText = (factSet, text) => {
65
+ const textBlock = new TextBlock(text);
66
+ textBlock.setParent(factSet);
67
+ return getRenderedText(textBlock, AdaptiveCard, renderMarkdownAsHTML);
68
+ };
69
+ const walk = element => {
70
+ if (!(element !== null && element !== void 0 && element.isVisible)) {
71
+ return;
72
+ }
73
+ if (element instanceof TextBlock || element instanceof RichTextBlock) {
74
+ texts.push(getRenderedText(element, AdaptiveCard, renderMarkdownAsHTML));
75
+ } else if (element instanceof FactSet) {
76
+ element.facts.forEach(_ref => {
77
+ let name = _ref.name,
78
+ value = _ref.value;
79
+ texts.push([name, value].map(text => text ? getFactText(element, text) : "").filter(Boolean).join(": "));
80
+ });
81
+ } else if (element instanceof Image) {
82
+ texts.push(element.altText);
83
+ }
84
+ if (element.getItemAt && element.getItemCount) {
85
+ for (let index = 0, count = element.getItemCount(); index < count; index++) {
86
+ walk(element.getItemAt(index));
87
+ }
88
+ }
89
+ };
90
+ walk(card);
91
+ return texts.filter(text => typeof text === "string" && text).join(" ").replace(/\s+/g, " ").trim();
92
+ };
93
+ const AdaptiveCardForScreenReader = _ref2 => {
94
+ let args = _ref2.args,
95
+ next = _ref2.next,
96
+ renderMarkdownAsHTML = _ref2.renderMarkdownAsHTML;
97
+ const _useAdaptiveCardsPack = useAdaptiveCardsPackage(),
98
+ _useAdaptiveCardsPack2 = _slicedToArray(_useAdaptiveCardsPack, 1),
99
+ adaptiveCardsPackage = _useAdaptiveCardsPack2[0];
100
+ const _useStyleOptions = useStyleOptions(),
101
+ _useStyleOptions2 = _slicedToArray(_useStyleOptions, 1),
102
+ adaptiveCardsParserMaxVersion = _useStyleOptions2[0].adaptiveCardsParserMaxVersion;
103
+ const _args = _slicedToArray(args, 1),
104
+ options = _args[0];
105
+ const attachment = options.attachment;
106
+
107
+ // The widget creates a new Markdown renderer on each render with the same settings, so the text is computed once for each attachment.
108
+ const contentWithSpeak = useMemo(() => {
109
+ try {
110
+ const content = typeof attachment.content === "string" ? JSON.parse(attachment.content) : attachment.content;
111
+ if (!content || typeof content !== "object" || content.speak) {
112
+ return undefined;
113
+ }
114
+ const speak = getAdaptiveCardSpeak(content, adaptiveCardsPackage, renderMarkdownAsHTML, adaptiveCardsParserMaxVersion);
115
+ return speak ? {
116
+ ...content,
117
+ speak
118
+ } : undefined;
119
+ } catch {
120
+ return undefined;
121
+ }
122
+ }, [adaptiveCardsPackage, adaptiveCardsParserMaxVersion, attachment]);
123
+ const render = contentWithSpeak ? next({
124
+ ...options,
125
+ attachment: {
126
+ ...attachment,
127
+ content: contentWithSpeak
128
+ }
129
+ }, ...args.slice(1)) : next(...args);
130
+ return typeof render === "function" ? render() : null;
131
+ };
132
+ export const createAttachmentForScreenReaderMiddleware = renderMarkdownAsHTML => {
133
+ const attachmentForScreenReaderMiddleware = () => next => function () {
134
+ var _args$;
135
+ for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
136
+ args[_key] = arguments[_key];
137
+ }
138
+ const attachment = (_args$ = args[0]) === null || _args$ === void 0 ? void 0 : _args$.attachment;
139
+
140
+ // Web Chat renders nothing for a card without content, so it is left to Web Chat.
141
+ if ((attachment === null || attachment === void 0 ? void 0 : attachment.contentType) !== ADAPTIVE_CARD_CONTENT_TYPE || !attachment.content) {
142
+ return next(...args);
143
+ }
144
+
145
+ // eslint-disable-next-line react/display-name
146
+ return () => /*#__PURE__*/React.createElement(AdaptiveCardForScreenReader, {
147
+ args: args,
148
+ next: next,
149
+ renderMarkdownAsHTML: renderMarkdownAsHTML
150
+ });
151
+ };
152
+ return attachmentForScreenReaderMiddleware;
153
+ };
@@ -98,6 +98,7 @@ export declare enum TelemetryEvent {
98
98
  RecoveryEligibilityEvaluated = "RecoveryEligibilityEvaluated",
99
99
  GetConversationDetailsCallStarted = "GetConversationDetailsCallStarted",
100
100
  GetConversationDetailsCallFailed = "GetConversationDetailsCallFailed",
101
+ UpdateTelemetryDataFailed = "UpdateTelemetryDataFailed",
101
102
  EndChatSDKCallFailed = "EndChatSDKCallFailed",
102
103
  DisconnectEndChatSDKCallFailed = "DisconnectEndChatSDKCallFailed",
103
104
  GetChatReconnectContextSDKCallStarted = "GetChatReconnectContextSDKCallStarted",
@@ -4,4 +4,12 @@ import { ILiveChatWidgetAction } from "../../../contexts/common/ILiveChatWidgetA
4
4
  import { ILiveChatWidgetContext } from "../../../contexts/common/ILiveChatWidgetContext";
5
5
  import { ILiveChatWidgetProps } from "../interfaces/ILiveChatWidgetProps";
6
6
  import { IWebChatProps } from "../../webchatcontainerstateful/interfaces/IWebChatProps";
7
+ import { IWebChatContainerStatefulProps } from "../../webchatcontainerstateful/interfaces/IWebChatContainerStatefulProps";
8
+ /**
9
+ * Renders Markdown for the screen reader text of Adaptive Cards, from the same pieces as the visible card:
10
+ * the host renderMarkdown when set, the hyperlink text override, and the same sanitization.
11
+ * Markdown is always formatted, also when the widget shows Markdown unformatted, so that screen readers do not read the syntax.
12
+ * Styles are removed with their content because the card does not show them.
13
+ */
14
+ export declare const createScreenReaderMarkdownRenderer: (webChatContainerProps?: IWebChatContainerStatefulProps) => (text: string) => string;
7
15
  export declare const initWebChatComposer: (props: ILiveChatWidgetProps, state: ILiveChatWidgetContext, dispatch: Dispatch<ILiveChatWidgetAction>, facadeChatSDK: FacadeChatSDK, endChat: any) => IWebChatProps;
@@ -6,7 +6,12 @@ import { ILiveChatWidgetAction } from "../../../contexts/common/ILiveChatWidgetA
6
6
  import { ILiveChatWidgetContext } from "../../../contexts/common/ILiveChatWidgetContext";
7
7
  import { ILiveChatWidgetProps } from "../interfaces/ILiveChatWidgetProps";
8
8
  declare const handleChatReconnect: (facadeChatSDK: FacadeChatSDK, props: ILiveChatWidgetProps, dispatch: Dispatch<ILiveChatWidgetAction>, setAdapter: any, initStartChat: any, state: ILiveChatWidgetContext) => Promise<boolean>;
9
+ /**
10
+ * Returns true when chat reconnect took over the start: it started the chat itself or showed the reconnect pane.
11
+ * In that case the caller must not start another chat.
12
+ */
13
+ declare const isReconnectTriggered: (facadeChatSDK: FacadeChatSDK, props: ILiveChatWidgetProps, dispatch: Dispatch<ILiveChatWidgetAction>, setAdapter: any, initStartChat: any, state: ILiveChatWidgetContext) => Promise<boolean>;
9
14
  declare const getChatReconnectContext: (facadeChatSDK: FacadeChatSDK, chatConfig: ChatConfig, props: any, isAuthenticatedChat: boolean, dispatch: Dispatch<ILiveChatWidgetAction>) => Promise<import("@microsoft/omnichannel-chat-sdk/lib/core/ChatReconnectContext").default | undefined>;
10
15
  declare const isReconnectEnabled: (chatConfig?: ChatConfig) => boolean;
11
16
  declare const isPersistentEnabled: (chatConfig?: ChatConfig) => boolean;
12
- export { handleChatReconnect, isReconnectEnabled, isPersistentEnabled, getChatReconnectContext };
17
+ export { handleChatReconnect, isReconnectTriggered, isReconnectEnabled, isPersistentEnabled, getChatReconnectContext };
@@ -6,6 +6,10 @@ import { ILiveChatWidgetProps } from "../interfaces/ILiveChatWidgetProps";
6
6
  import StartChatOptionalParams from "@microsoft/omnichannel-chat-sdk/lib/core/StartChatOptionalParams";
7
7
  declare const prepareStartChat: (props: ILiveChatWidgetProps, facadeChatSDK: FacadeChatSDK, state: ILiveChatWidgetContext, dispatch: Dispatch<ILiveChatWidgetAction>, setAdapter: any) => Promise<void>;
8
8
  declare const setPreChatAndInitiateChat: (facadeChatSDK: FacadeChatSDK, dispatch: Dispatch<ILiveChatWidgetAction>, setAdapter: any, isProactiveChat?: boolean | false, proactiveChatEnablePrechatState?: boolean | false, state?: ILiveChatWidgetContext, props?: ILiveChatWidgetProps) => Promise<void>;
9
- declare const initStartChat: (facadeChatSDK: FacadeChatSDK, dispatch: Dispatch<ILiveChatWidgetAction>, setAdapter: any, state: ILiveChatWidgetContext | undefined, props?: ILiveChatWidgetProps, params?: StartChatOptionalParams, persistedState?: any) => Promise<void>;
9
+ /**
10
+ * Resolves to `true` when the chat reached Active, and `false` when it failed or the call was dropped.
11
+ * It resolves before React renders Active, so callers must use this value rather than reading the conversation state.
12
+ */
13
+ declare const initStartChat: (facadeChatSDK: FacadeChatSDK, dispatch: Dispatch<ILiveChatWidgetAction>, setAdapter: any, state: ILiveChatWidgetContext | undefined, props?: ILiveChatWidgetProps, params?: StartChatOptionalParams, persistedState?: any) => Promise<boolean>;
10
14
  declare const checkIfConversationStillValid: (facadeChatSDK: FacadeChatSDK, dispatch: Dispatch<ILiveChatWidgetAction>, state: ILiveChatWidgetContext) => Promise<boolean>;
11
15
  export { prepareStartChat, initStartChat, setPreChatAndInitiateChat, checkIfConversationStillValid };
@@ -0,0 +1,11 @@
1
+ /******
2
+ * AttachmentForScreenReaderMiddleware
3
+ *
4
+ * Web Chat reads an Adaptive Card to screen readers only from the card's `speak` property.
5
+ * A card without `speak` is announced as "A card" with no content.
6
+ * This middleware sets `speak` from the visible text of the card, then lets Web Chat render it as usual.
7
+ ******/
8
+ type RenderMarkdownAsHTML = (markdown: string) => string;
9
+ export declare const getAdaptiveCardSpeak: (content: any, adaptiveCardsPackage: any, renderMarkdownAsHTML: RenderMarkdownAsHTML, adaptiveCardsParserMaxVersion?: string) => string;
10
+ export declare const createAttachmentForScreenReaderMiddleware: (renderMarkdownAsHTML: RenderMarkdownAsHTML) => () => (next: any) => (...args: any[]) => any;
11
+ export {};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@microsoft/omnichannel-chat-widget",
3
- "version": "2.0.1-main.38e7390",
3
+ "version": "2.0.1-main.41dd340",
4
4
  "description": "Microsoft Omnichannel Chat Widget",
5
5
  "main": "lib/cjs/index.js",
6
6
  "types": "lib/types/index.d.ts",
@@ -93,18 +93,17 @@
93
93
  "@azure/core-tracing": "^1.2.0",
94
94
  "@microsoft/applicationinsights-web": "^3.3.6",
95
95
  "@microsoft/omnichannel-chat-components": "1.2.0",
96
- "@microsoft/omnichannel-chat-sdk": "2.0.1",
96
+ "@microsoft/omnichannel-chat-sdk": "2.0.2-main.07ad838",
97
97
  "@opentelemetry/api": "^1.9.0",
98
98
  "abort-controller": "^3",
99
99
  "botframework-webchat": "4.18.1-hotfix.20260308.b15b405",
100
100
  "core-js-pure": "^3.42.0",
101
- "dompurify": "3.4.16",
102
- "markdown-it": "^14.3.0",
101
+ "dompurify": "3.4.17",
102
+ "markdown-it": "^14.3.3",
103
103
  "markdown-it-attrs": "^4.1.6",
104
104
  "markdown-it-for-inline": "^0.1.1",
105
105
  "md5-typescript": "^1.0.5",
106
106
  "rxjs": "5.5.12",
107
- "sanitize-html": "2.17.7",
108
107
  "simple-update-in": "2.2.0",
109
108
  "slack-markdown-it": "^1.0.5"
110
109
  },
@@ -164,7 +163,7 @@
164
163
  "**/@types/trusted-types": "2.0.7",
165
164
  "**/join-images": "1.1.5",
166
165
  "**/valibot": "1.4.2",
167
- "**/nanoid": "3.3.18"
166
+ "**/nanoid": "^3.3.20"
168
167
  },
169
168
  "jest": {
170
169
  "verbose": true,