From a2deae579318be0bedd4411948dc76efccd87221 Mon Sep 17 00:00:00 2001 From: JiayuanL Date: Wed, 6 Jan 2021 16:28:18 -0800 Subject: [PATCH] add outlook test app --- .../AgaveErrorUX/AgaveErrorUx.debug.js | 0 addins/outlook/AgaveErrorUX/AgaveErrorUx.js | 0 addins/outlook/AgaveErrorUX/index.html | 0 .../AgaveErrorUX/style/AgaveErrorUX.css | 0 addins/outlook/Home_olk.html | 31 + addins/outlook/app_olk.js | 49 + addins/outlook/en-us/outlook_strings.debug.js | 69 + addins/outlook/en-us/outlook_strings.js | 1 + addins/outlook/outlook.debug.js | 14622 ++++++++++++++++ addins/outlook/outlook.js | 19 + addins/outlook/telemetry/oteljs.js | 1283 ++ addins/outlook/telemetry/oteljs_agave.js | 3910 +++++ 12 files changed, 19984 insertions(+) create mode 100644 addins/outlook/AgaveErrorUX/AgaveErrorUx.debug.js create mode 100644 addins/outlook/AgaveErrorUX/AgaveErrorUx.js create mode 100644 addins/outlook/AgaveErrorUX/index.html create mode 100644 addins/outlook/AgaveErrorUX/style/AgaveErrorUX.css create mode 100644 addins/outlook/Home_olk.html create mode 100644 addins/outlook/app_olk.js create mode 100644 addins/outlook/en-us/outlook_strings.debug.js create mode 100644 addins/outlook/en-us/outlook_strings.js create mode 100644 addins/outlook/outlook.debug.js create mode 100644 addins/outlook/outlook.js create mode 100644 addins/outlook/telemetry/oteljs.js create mode 100644 addins/outlook/telemetry/oteljs_agave.js diff --git a/addins/outlook/AgaveErrorUX/AgaveErrorUx.debug.js b/addins/outlook/AgaveErrorUX/AgaveErrorUx.debug.js new file mode 100644 index 0000000..e69de29 diff --git a/addins/outlook/AgaveErrorUX/AgaveErrorUx.js b/addins/outlook/AgaveErrorUX/AgaveErrorUx.js new file mode 100644 index 0000000..e69de29 diff --git a/addins/outlook/AgaveErrorUX/index.html b/addins/outlook/AgaveErrorUX/index.html new file mode 100644 index 0000000..e69de29 diff --git a/addins/outlook/AgaveErrorUX/style/AgaveErrorUX.css b/addins/outlook/AgaveErrorUX/style/AgaveErrorUX.css new file mode 100644 index 0000000..e69de29 diff --git a/addins/outlook/Home_olk.html b/addins/outlook/Home_olk.html new file mode 100644 index 0000000..3b12c1b --- /dev/null +++ b/addins/outlook/Home_olk.html @@ -0,0 +1,31 @@ + + + + + + + + + + + + + + + + + +
+ + + + + + +
+ +
+ +
+ + diff --git a/addins/outlook/app_olk.js b/addins/outlook/app_olk.js new file mode 100644 index 0000000..c2b5b18 --- /dev/null +++ b/addins/outlook/app_olk.js @@ -0,0 +1,49 @@ +function getSubject() { + Office.context.mailbox.item.subject.getAsync(callback); + + function callback(asyncResult) { + var subject = asyncResult.value; + writeResult("GetSubject result is: "+ subject); + } +} + +function setSubject() { + Office.context.mailbox.item.subject.setAsync("New subject!", function (asyncResult) { + if (asyncResult.status === "failed") { + console.log("Action failed with error: " + asyncResult.error.message); + writeResult("Set subject Action failed with error: " + asyncResult.error.message); + } + else { + writeResult("SetSubject done."); + } + }); +} + +function getUserProfile() { + writeResult(Office.context.mailbox.userProfile.displayname); +} + +function getRestId() { + let itemId = Office.context.mailbox.item.itemId; + let restId = Office.context.mailbox.convertToRestId(itemId, Office.MailboxEnums.RestVersion.v2_0); + writeResult(restId); +} + +function getLanguage() { + writeResult(Office.context.displayLanguage); +} + +function closeContainer() { + Office.context.ui.closeContainer(); +} + +function clearResult() { + document.getElementById("result").value = ""; +} + +function writeResult(result) { + document.getElementById("result").value += ("\n" +result); +} + +Office.initialize = function (reason) {}; +Office.onReady(function(info) {}); \ No newline at end of file diff --git a/addins/outlook/en-us/outlook_strings.debug.js b/addins/outlook/en-us/outlook_strings.debug.js new file mode 100644 index 0000000..d8905d1 --- /dev/null +++ b/addins/outlook/en-us/outlook_strings.debug.js @@ -0,0 +1,69 @@ +_u = typeof _u === "object" ? _u : {}; +_u.ExtensibilityStrings = _u.ExtensibilityStrings || {}; + +_u.ExtensibilityStrings.l_APICallFailedDueToItemChange_Text='The selected item has been changed.'; +_u.ExtensibilityStrings.l_ActionsDefinitionMultipleActionsError_Text='Only a single action is currently supported.'; +_u.ExtensibilityStrings.l_ActionsDefinitionWrongNotificationMessageError_Text='Actions can\'t be defined for this notification message type.'; +_u.ExtensibilityStrings.l_AttachmentDeleteGeneralFailure_Text='The attachment cannot be deleted from the item.'; +_u.ExtensibilityStrings.l_AttachmentDeletedBeforeUploadCompletes_Text='The user removed the attachment before upload has completed.'; +_u.ExtensibilityStrings.l_AttachmentErrorName_Text='Attachment Error'; +_u.ExtensibilityStrings.l_AttachmentExceededSize_Text='The attachment cannot be added because it is too big.'; +_u.ExtensibilityStrings.l_AttachmentItemIdTooLong_Text='One or more of the attachment IDs is too long.'; +_u.ExtensibilityStrings.l_AttachmentNameTooLong_Text='One or more of the attachment names is too long.'; +_u.ExtensibilityStrings.l_AttachmentNotSupported_Text='The attachment type is not supported.'; +_u.ExtensibilityStrings.l_AttachmentUploadGeneralFailure_Text='The attachment cannot be added to the item.'; +_u.ExtensibilityStrings.l_AttachmentUrlTooLong_Text='One or more of the attachment URLs is too long.'; +_u.ExtensibilityStrings.l_CallSaveAsyncBeforeToken_Text='The token can\'t be retrieved until the item is saved.'; +_u.ExtensibilityStrings.l_CannotAddAttachmentBeforeUpgrade_Text='Attachments cannot be added while the full reply or forward is being retrieved from the server.'; +_u.ExtensibilityStrings.l_CannotPersistPropertyInUnsavedDraftError_Text='Notifications can\'t be persisted in unsaved drafts. Save the item before you call this API.'; +_u.ExtensibilityStrings.l_CursorPositionChanged_Text='The user changed the position of the cursor while the data was being inserted.'; +_u.ExtensibilityStrings.l_DataWriteErrorName_Text='Data Write Error'; +_u.ExtensibilityStrings.l_DeleteAttachmentDoesNotExist_Text='The attachment cannot be deleted because attachment with the attachment index cannot be found.'; +_u.ExtensibilityStrings.l_DisplayNameTooLong_Text='One or more of the display names provided is too long.'; +_u.ExtensibilityStrings.l_DisplayReplyFormHtmlBodyRequired_Text='The \'htmlBody\' is required.'; +_u.ExtensibilityStrings.l_DuplicateNotificationKey_Text='A notification with the provided key already exists.'; +_u.ExtensibilityStrings.l_Duplicate_Category_Error_Text='One of the categories provided is already in the master category list.'; +_u.ExtensibilityStrings.l_ElevatedPermissionNeededForMethod_Text='Elevated permission is required to call the method: \'{0}\'.'; +_u.ExtensibilityStrings.l_ElevatedPermissionNeeded_Text='Elevated permission is required to access protected members of the JavaScript API for Office.'; +_u.ExtensibilityStrings.l_EmailAddressTooLong_Text='One or more of the email addresses provided is too long.'; +_u.ExtensibilityStrings.l_EwsRequestOversized_Text='The request exceeds the 1 MB size limit. Please modify your EWS request.'; +_u.ExtensibilityStrings.l_ExceededMaxNumberOfAttachments_Text='Attachments cannot be added because the message already has the maximum number of attachments'; +_u.ExtensibilityStrings.l_HtmlSanitizationFailure_Text='The HTML santization has failed.'; +_u.ExtensibilityStrings.l_Insufficient_Item_Permissions_Text='The user doesn\'t have the permissions required to perform this operation.'; +_u.ExtensibilityStrings.l_InternalFormatError_Text='There was an internal format error.'; +_u.ExtensibilityStrings.l_InternalProtocolError_Text='Internal protocol error: \'{0}\'.'; +_u.ExtensibilityStrings.l_Internal_Server_Error_Text='The Exchange server returned an error. Please look at the diagnostics object for more information.'; +_u.ExtensibilityStrings.l_Internet_Not_Connected_Error_Text='The user is no longer connected to the network. Please check your network connection and try again.'; +_u.ExtensibilityStrings.l_InvalidActionType_Text='The value of the parameter \'actionType\' is invalid. The accepted value is \"showTaskPane\".'; +_u.ExtensibilityStrings.l_InvalidAttachmentId_Text='The attachment ID was invalid.'; +_u.ExtensibilityStrings.l_InvalidAttachmentPath_Text='The attachment path was invalid.'; +_u.ExtensibilityStrings.l_InvalidCommandIdError_Text='The value of the parameter \'commandId\' is invalid.'; +_u.ExtensibilityStrings.l_InvalidDate_Text='The input doesn\'t resolve to a valid date.'; +_u.ExtensibilityStrings.l_InvalidEndTime_Text='The end time cannot be before the start time.'; +_u.ExtensibilityStrings.l_InvalidEventDates_Text='The end date occurs before the start date.'; +_u.ExtensibilityStrings.l_InvalidParameterValueError_Text='The value of the \'{0}\' parameter is invalid.'; +_u.ExtensibilityStrings.l_InvalidSelection_Text='The selection is invalid.'; +_u.ExtensibilityStrings.l_InvalidTime_Text='The input doesn\'t resolve to a valid time.'; +_u.ExtensibilityStrings.l_Invalid_Category_Error_Text='Invalid categories were provided.'; +_u.ExtensibilityStrings.l_Item_Not_Saved_Error_Text='The id can\'t be retrieved until the item is saved.'; +_u.ExtensibilityStrings.l_MessageInDifferentStoreError_Text='The EWS ID can\'t be retrieved because the message is saved in a different store.'; +_u.ExtensibilityStrings.l_NoValidRecipientsProvided_Text='No valid recipients were provided.'; +_u.ExtensibilityStrings.l_NotificationKeyNotFound_Text='There are no notifications with the provided key.'; +_u.ExtensibilityStrings.l_NullOrEmptyParameterError_Text='The parameter \'{0}\' is mandatory and it can\'t be null or empty.'; +_u.ExtensibilityStrings.l_NumberOfNotificationsExceeded_Text='The notification couldn\'t be added because the notification limit has been reached.'; +_u.ExtensibilityStrings.l_NumberOfRecipientsExceeded_Text='The total number of recipients in the field can\'t exceed {0}.'; +_u.ExtensibilityStrings.l_OffsetNotfound_Text='An offset for this time stamp couldn\'t be found.'; +_u.ExtensibilityStrings.l_Olk_Http_Error_Text='The request has failed. Please look at the diagnostics object for the HTTP error code.'; +_u.ExtensibilityStrings.l_ParameterValueTooLongError_Text='The value of the \'{0}\' parameter is too long. The maximum number of characters is \'{1}\'.'; +_u.ExtensibilityStrings.l_ParametersNotAsExpected_Text='The given parameters do not match the expected format.'; +_u.ExtensibilityStrings.l_PersistedNotificationArrayReadError_Text='The API call you made failed because the persisted notifications couldn\'t be retrieved.'; +_u.ExtensibilityStrings.l_PersistedNotificationArraySaveError_Text='The API call you made failed because notifications couldn\'t be persisted.'; +_u.ExtensibilityStrings.l_RecurrenceErrorMaxOccurrences_Text='The recurring series exceeds the maximum limit of 999 occurrences.'; +_u.ExtensibilityStrings.l_RecurrenceErrorZeroOccurrences_Text='The recurring series has no occurrences in the specified date range.'; +_u.ExtensibilityStrings.l_RecurrenceInvalidTimeZone_Text='The specified time zone is not supported.'; +_u.ExtensibilityStrings.l_RecurrenceUnsupportedAlternateCalendar_Text='The recurrence pattern was set by the user using an alternate calendar that is not supported.'; +_u.ExtensibilityStrings.l_Recurrence_Error_Instance_SetAsync_Text='A recurrence pattern can\'t be set for a single occurrence in a series.'; +_u.ExtensibilityStrings.l_Recurrence_Error_Properties_Invalid_Text='The recurrence pattern isn\'t valid. Please check that the specified recurrence properties align with the recurrence type.'; +_u.ExtensibilityStrings.l_SaveError_Text='Connection error occurred while trying to save the item on the server.'; + + diff --git a/addins/outlook/en-us/outlook_strings.js b/addins/outlook/en-us/outlook_strings.js new file mode 100644 index 0000000..218bda5 --- /dev/null +++ b/addins/outlook/en-us/outlook_strings.js @@ -0,0 +1 @@ +_u = typeof _u === "object" ? _u : {};_u.ExtensibilityStrings = _u.ExtensibilityStrings || {};_u.ExtensibilityStrings=function(){};if (_u.ExtensibilityStrings.registerClass) _u.ExtensibilityStrings.registerClass("_u.ExtensibilityStrings");_u.ExtensibilityStrings.l_APICallFailedDueToItemChange_Text="The selected item has been changed.";_u.ExtensibilityStrings.l_ActionsDefinitionMultipleActionsError_Text="Only a single action is currently supported.";_u.ExtensibilityStrings.l_ActionsDefinitionWrongNotificationMessageError_Text="Actions can't be defined for this notification message type.";_u.ExtensibilityStrings.l_AttachmentDeleteGeneralFailure_Text="The attachment cannot be deleted from the item.";_u.ExtensibilityStrings.l_AttachmentDeletedBeforeUploadCompletes_Text="The user removed the attachment before upload has completed.";_u.ExtensibilityStrings.l_AttachmentErrorName_Text="Attachment Error";_u.ExtensibilityStrings.l_AttachmentExceededSize_Text="The attachment cannot be added because it is too big.";_u.ExtensibilityStrings.l_AttachmentItemIdTooLong_Text="One or more of the attachment IDs is too long.";_u.ExtensibilityStrings.l_AttachmentNameTooLong_Text="One or more of the attachment names is too long.";_u.ExtensibilityStrings.l_AttachmentNotSupported_Text="The attachment type is not supported.";_u.ExtensibilityStrings.l_AttachmentUploadGeneralFailure_Text="The attachment cannot be added to the item.";_u.ExtensibilityStrings.l_AttachmentUrlTooLong_Text="One or more of the attachment URLs is too long.";_u.ExtensibilityStrings.l_CallSaveAsyncBeforeToken_Text="The token can't be retrieved until the item is saved.";_u.ExtensibilityStrings.l_CannotAddAttachmentBeforeUpgrade_Text="Attachments cannot be added while the full reply or forward is being retrieved from the server.";_u.ExtensibilityStrings.l_CannotPersistPropertyInUnsavedDraftError_Text="Notifications can't be persisted in unsaved drafts. Save the item before you call this API.";_u.ExtensibilityStrings.l_CursorPositionChanged_Text="The user changed the position of the cursor while the data was being inserted.";_u.ExtensibilityStrings.l_DataWriteErrorName_Text="Data Write Error";_u.ExtensibilityStrings.l_DeleteAttachmentDoesNotExist_Text="The attachment cannot be deleted because attachment with the attachment index cannot be found.";_u.ExtensibilityStrings.l_DisplayNameTooLong_Text="One or more of the display names provided is too long.";_u.ExtensibilityStrings.l_DisplayReplyFormHtmlBodyRequired_Text="The 'htmlBody' is required.";_u.ExtensibilityStrings.l_DuplicateNotificationKey_Text="A notification with the provided key already exists.";_u.ExtensibilityStrings.l_Duplicate_Category_Error_Text="One of the categories provided is already in the master category list.";_u.ExtensibilityStrings.l_ElevatedPermissionNeededForMethod_Text="Elevated permission is required to call the method: '{0}'.";_u.ExtensibilityStrings.l_ElevatedPermissionNeeded_Text="Elevated permission is required to access protected members of the JavaScript API for Office.";_u.ExtensibilityStrings.l_EmailAddressTooLong_Text="One or more of the email addresses provided is too long.";_u.ExtensibilityStrings.l_EwsRequestOversized_Text="The request exceeds the 1 MB size limit. Please modify your EWS request.";_u.ExtensibilityStrings.l_ExceededMaxNumberOfAttachments_Text="Attachments cannot be added because the message already has the maximum number of attachments";_u.ExtensibilityStrings.l_HtmlSanitizationFailure_Text="The HTML santization has failed.";_u.ExtensibilityStrings.l_Insufficient_Item_Permissions_Text="The user doesn't have the permissions required to perform this operation.";_u.ExtensibilityStrings.l_InternalFormatError_Text="There was an internal format error.";_u.ExtensibilityStrings.l_InternalProtocolError_Text="Internal protocol error: '{0}'.";_u.ExtensibilityStrings.l_Internal_Server_Error_Text="The Exchange server returned an error. Please look at the diagnostics object for more information.";_u.ExtensibilityStrings.l_Internet_Not_Connected_Error_Text="The user is no longer connected to the network. Please check your network connection and try again.";_u.ExtensibilityStrings.l_InvalidActionType_Text="The value of the parameter 'actionType' is invalid. The accepted value is \"showTaskPane\".";_u.ExtensibilityStrings.l_InvalidAttachmentId_Text="The attachment ID was invalid.";_u.ExtensibilityStrings.l_InvalidAttachmentPath_Text="The attachment path was invalid.";_u.ExtensibilityStrings.l_InvalidCommandIdError_Text="The value of the parameter 'commandId' is invalid.";_u.ExtensibilityStrings.l_InvalidDate_Text="The input doesn't resolve to a valid date.";_u.ExtensibilityStrings.l_InvalidEndTime_Text="The end time cannot be before the start time.";_u.ExtensibilityStrings.l_InvalidEventDates_Text="The end date occurs before the start date.";_u.ExtensibilityStrings.l_InvalidParameterValueError_Text="The value of the '{0}' parameter is invalid.";_u.ExtensibilityStrings.l_InvalidSelection_Text="The selection is invalid.";_u.ExtensibilityStrings.l_InvalidTime_Text="The input doesn't resolve to a valid time.";_u.ExtensibilityStrings.l_Invalid_Category_Error_Text="Invalid categories were provided.";_u.ExtensibilityStrings.l_Item_Not_Saved_Error_Text="The id can't be retrieved until the item is saved.";_u.ExtensibilityStrings.l_MessageInDifferentStoreError_Text="The EWS ID can't be retrieved because the message is saved in a different store.";_u.ExtensibilityStrings.l_NoValidRecipientsProvided_Text="No valid recipients were provided.";_u.ExtensibilityStrings.l_NotificationKeyNotFound_Text="There are no notifications with the provided key.";_u.ExtensibilityStrings.l_NullOrEmptyParameterError_Text="The parameter '{0}' is mandatory and it can't be null or empty.";_u.ExtensibilityStrings.l_NumberOfNotificationsExceeded_Text="The notification couldn't be added because the notification limit has been reached.";_u.ExtensibilityStrings.l_NumberOfRecipientsExceeded_Text="The total number of recipients in the field can't exceed {0}.";_u.ExtensibilityStrings.l_OffsetNotfound_Text="An offset for this time stamp couldn't be found.";_u.ExtensibilityStrings.l_Olk_Http_Error_Text="The request has failed. Please look at the diagnostics object for the HTTP error code.";_u.ExtensibilityStrings.l_ParameterValueTooLongError_Text="The value of the '{0}' parameter is too long. The maximum number of characters is '{1}'.";_u.ExtensibilityStrings.l_ParametersNotAsExpected_Text="The given parameters do not match the expected format.";_u.ExtensibilityStrings.l_PersistedNotificationArrayReadError_Text="The API call you made failed because the persisted notifications couldn't be retrieved.";_u.ExtensibilityStrings.l_PersistedNotificationArraySaveError_Text="The API call you made failed because notifications couldn't be persisted.";_u.ExtensibilityStrings.l_RecurrenceErrorMaxOccurrences_Text="The recurring series exceeds the maximum limit of 999 occurrences.";_u.ExtensibilityStrings.l_RecurrenceErrorZeroOccurrences_Text="The recurring series has no occurrences in the specified date range.";_u.ExtensibilityStrings.l_RecurrenceInvalidTimeZone_Text="The specified time zone is not supported.";_u.ExtensibilityStrings.l_RecurrenceUnsupportedAlternateCalendar_Text="The recurrence pattern was set by the user using an alternate calendar that is not supported.";_u.ExtensibilityStrings.l_Recurrence_Error_Instance_SetAsync_Text="A recurrence pattern can't be set for a single occurrence in a series.";_u.ExtensibilityStrings.l_Recurrence_Error_Properties_Invalid_Text="The recurrence pattern isn't valid. Please check that the specified recurrence properties align with the recurrence type.";_u.ExtensibilityStrings.l_SaveError_Text="Connection error occurred while trying to save the item on the server." \ No newline at end of file diff --git a/addins/outlook/outlook.debug.js b/addins/outlook/outlook.debug.js new file mode 100644 index 0000000..3d55f8f --- /dev/null +++ b/addins/outlook/outlook.debug.js @@ -0,0 +1,14622 @@ +/* + * Office JavaScript API library + * + * Copyright (c) Microsoft Corporation. All rights reserved. + * + * Your use of this file is governed by the Microsoft Services Agreement http://go.microsoft.com/fwlink/?LinkId=266419. + * + * This file also contains the following Promise implementation (with a few small modifications): + * * @overview es6-promise - a tiny implementation of Promises/A+. + * * @copyright Copyright (c) 2014 Yehuda Katz, Tom Dale, Stefan Penner and contributors (Conversion to ES6 API by Jake Archibald) + * * @license Licensed under MIT license + * * See https://raw.githubusercontent.com/jakearchibald/es6-promise/master/LICENSE + * * @version 2.3.0 + */ +var OSFPerformance; +(function (OSFPerformance) { + function now() { + if (typeof (performance) !== 'undefined' && performance.now) { + return performance.now(); + } + else { + return 0; + } + } + OSFPerformance.now = now; + OSFPerformance.officeExecuteStartDate = Date.now(); + OSFPerformance.officeExecuteStart = 0; + OSFPerformance.officeExecuteEnd = 0; + OSFPerformance.hostInitializationStart = now(); + OSFPerformance.hostInitializationEnd = 0; + OSFPerformance.createOMEnd = 0; + OSFPerformance.hostSpecificFileName = ""; + OSFPerformance.getAppContextStart = 0; + OSFPerformance.getAppContextEnd = 0; + OSFPerformance.getAppContextXdmStart = 0; + OSFPerformance.getAppContextXdmEnd = 0; + OSFPerformance.officeOnReady = 0; +})(OSFPerformance || (OSFPerformance = {})); +var OSF; +(function (OSF) { + function definePropertyOnNamespace(o, name, getFunction) { + Object.defineProperty(o, name, { + get: function () { + return getFunction(); + }, + configurable: true, + enumerable: true + }); + } + OSF.definePropertyOnNamespace = definePropertyOnNamespace; +})(OSF || (OSF = {})); +var Office; +(function (Office) { + var actions; + (function (actions) { + var m_association; + function get_association() { + if (!m_association) { + m_association = new OSF.Association(); + } + return m_association; + } + function associate() { + get_association().associate.apply(get_association(), arguments); + } + actions.associate = associate; + ; + OSF.definePropertyOnNamespace(actions, '_association', get_association); + })(actions = Office.actions || (Office.actions = {})); +})(Office || (Office = {})); +var OSF; +(function (OSF) { + var AgaveHostAction; + (function (AgaveHostAction) { + AgaveHostAction[AgaveHostAction["Select"] = 0] = "Select"; + AgaveHostAction[AgaveHostAction["UnSelect"] = 1] = "UnSelect"; + AgaveHostAction[AgaveHostAction["CancelDialog"] = 2] = "CancelDialog"; + AgaveHostAction[AgaveHostAction["InsertAgave"] = 3] = "InsertAgave"; + AgaveHostAction[AgaveHostAction["CtrlF6In"] = 4] = "CtrlF6In"; + AgaveHostAction[AgaveHostAction["CtrlF6Exit"] = 5] = "CtrlF6Exit"; + AgaveHostAction[AgaveHostAction["CtrlF6ExitShift"] = 6] = "CtrlF6ExitShift"; + AgaveHostAction[AgaveHostAction["SelectWithError"] = 7] = "SelectWithError"; + AgaveHostAction[AgaveHostAction["NotifyHostError"] = 8] = "NotifyHostError"; + AgaveHostAction[AgaveHostAction["RefreshAddinCommands"] = 9] = "RefreshAddinCommands"; + AgaveHostAction[AgaveHostAction["PageIsReady"] = 10] = "PageIsReady"; + AgaveHostAction[AgaveHostAction["TabIn"] = 11] = "TabIn"; + AgaveHostAction[AgaveHostAction["TabInShift"] = 12] = "TabInShift"; + AgaveHostAction[AgaveHostAction["TabExit"] = 13] = "TabExit"; + AgaveHostAction[AgaveHostAction["TabExitShift"] = 14] = "TabExitShift"; + AgaveHostAction[AgaveHostAction["EscExit"] = 15] = "EscExit"; + AgaveHostAction[AgaveHostAction["F2Exit"] = 16] = "F2Exit"; + AgaveHostAction[AgaveHostAction["ExitNoFocusable"] = 17] = "ExitNoFocusable"; + AgaveHostAction[AgaveHostAction["ExitNoFocusableShift"] = 18] = "ExitNoFocusableShift"; + AgaveHostAction[AgaveHostAction["MouseEnter"] = 19] = "MouseEnter"; + AgaveHostAction[AgaveHostAction["MouseLeave"] = 20] = "MouseLeave"; + AgaveHostAction[AgaveHostAction["UpdateTargetUrl"] = 21] = "UpdateTargetUrl"; + AgaveHostAction[AgaveHostAction["InstallCustomFunctions"] = 22] = "InstallCustomFunctions"; + AgaveHostAction[AgaveHostAction["SendTelemetryEvent"] = 23] = "SendTelemetryEvent"; + AgaveHostAction[AgaveHostAction["UninstallCustomFunctions"] = 24] = "UninstallCustomFunctions"; + AgaveHostAction[AgaveHostAction["SendMessage"] = 25] = "SendMessage"; + AgaveHostAction[AgaveHostAction["LaunchExtensionComponent"] = 26] = "LaunchExtensionComponent"; + AgaveHostAction[AgaveHostAction["StopExtensionComponent"] = 27] = "StopExtensionComponent"; + AgaveHostAction[AgaveHostAction["RestartExtensionComponent"] = 28] = "RestartExtensionComponent"; + AgaveHostAction[AgaveHostAction["EnableTaskPaneHeaderButton"] = 29] = "EnableTaskPaneHeaderButton"; + AgaveHostAction[AgaveHostAction["DisableTaskPaneHeaderButton"] = 30] = "DisableTaskPaneHeaderButton"; + AgaveHostAction[AgaveHostAction["TaskPaneHeaderButtonClicked"] = 31] = "TaskPaneHeaderButtonClicked"; + AgaveHostAction[AgaveHostAction["RemoveAppCommandsAddin"] = 32] = "RemoveAppCommandsAddin"; + AgaveHostAction[AgaveHostAction["RefreshRibbonGallery"] = 33] = "RefreshRibbonGallery"; + AgaveHostAction[AgaveHostAction["GetOriginalControlId"] = 34] = "GetOriginalControlId"; + AgaveHostAction[AgaveHostAction["OfficeJsReady"] = 35] = "OfficeJsReady"; + })(AgaveHostAction = OSF.AgaveHostAction || (OSF.AgaveHostAction = {})); +})(OSF || (OSF = {})); +var OSF; +(function (OSF) { + var AppCommandManager = (function () { + function AppCommandManager() { + var _this = this; + this._processAppCommandInvocation = function (args) { + var verifyResult = _this._verifyManifestCallback(args.callbackName); + if (verifyResult.errorCode != 0) { + _this._invokeAppCommandCompletedMethod(args.appCommandId, verifyResult.errorCode, ""); + return; + } + var eventObj = _this._constructEventObjectForCallback(args); + if (eventObj) { + window.setTimeout(function () { verifyResult.callback(eventObj); }, 0); + } + else { + _this._invokeAppCommandCompletedMethod(args.appCommandId, 5001, ""); + } + }; + this._eventDispatch = new OSF.EventDispatch([ + { + type: OSF.EventType.AppCommandInvoked, + id: 39, + getTargetId: function () { return ''; }, + fromSafeArrayHost: function (payload) { + return { + type: OSF.EventType.AppCommandInvoked, + appCommandId: payload[0], + callbackName: payload[1], + eventObjStr: payload[2] + }; + }, + fromWebHost: function (payload) { + return { + type: OSF.EventType.AppCommandInvoked, + appCommandId: payload[0], + callbackName: payload[1], + eventObjStr: payload[2] + }; + } + } + ]); + } + AppCommandManager.prototype.initializeEventHandler = function (callback) { + var _this = this; + this.addHandlerAsync(OSF.EventType.AppCommandInvoked, function (args) { + _this._processAppCommandInvocation(args); + }, callback); + }; + AppCommandManager.prototype.appCommandInvocationCompletedAsync = function (id, status, completedData, callback) { + var asyncMethodExecutor = OSF._OfficeAppFactory.getAsyncMethodExecutor(); + asyncMethodExecutor.executeAsync(94, { + fromSafeArrayHost: function (payload) { + return payload; + }, + fromWebHost: function (payload) { + return payload; + }, + toSafeArrayHost: function () { + return [id, status, completedData]; + }, + toWebHost: function () { + var obj = {}; + obj[0] = id; + obj[1] = status; + obj[2] = completedData; + return obj; + } + }, callback); + }; + AppCommandManager.prototype.addHandlerAsync = function (eventType, handler, callback) { + OSF.EventHelper.addEventHandler(eventType, handler, callback, this._eventDispatch, false); + }; + AppCommandManager.prototype._verifyManifestCallback = function (callbackName) { + var defaultResult = { callback: null, errorCode: 11101 }; + callbackName = callbackName.trim(); + try { + var callbackFunc = this._getCallbackFunc(callbackName); + if (typeof callbackFunc != "function") { + return defaultResult; + } + } + catch (e) { + return defaultResult; + } + return { callback: callbackFunc, errorCode: 0 }; + }; + AppCommandManager.prototype._getCallbackFuncFromWindow = function (callbackName) { + var callList = callbackName.split("."); + var parentObject = window; + for (var i = 0; i < callList.length - 1; i++) { + if (parentObject[callList[i]] && (typeof parentObject[callList[i]] == "object" || typeof parentObject[callList[i]] == "function")) { + parentObject = parentObject[callList[i]]; + } + else { + return null; + } + } + var callbackFunc = parentObject[callList[callList.length - 1]]; + return callbackFunc; + }; + AppCommandManager.prototype._getCallbackFuncFromActionAssociateTable = function (callbackName) { + var nameUpperCase = callbackName.toUpperCase(); + return Office.actions._association.mappings[nameUpperCase]; + }; + AppCommandManager.prototype._getCallbackFunc = function (callbackName) { + var callbackFunc = this._getCallbackFuncFromWindow(callbackName); + if (!callbackFunc) { + callbackFunc = this._getCallbackFuncFromActionAssociateTable(callbackName); + } + return callbackFunc; + }; + AppCommandManager.prototype._invokeAppCommandCompletedMethod = function (appCommandId, resultCode, data) { + this.appCommandInvocationCompletedAsync(appCommandId, resultCode, data, function (result) { + if (result.status !== Office.AsyncResultStatus.succeeded) { + console.error("Failed to notify the host thta app command is completed"); + } + }); + }; + AppCommandManager.prototype._constructEventObjectForCallback = function (args) { + var _this = this; + var eventObj; + var eventObjCopy; + try { + eventObj = JSON.parse(args.eventObjStr); + eventObjCopy = JSON.parse(args.eventObjStr); + } + catch (ex) { + } + if (!eventObj) { + eventObj = {}; + } + if (!eventObjCopy) { + eventObjCopy = {}; + } + eventObj.completed = function (completedContext) { + eventObjCopy.completedContext = completedContext; + var jsonString = JSON.stringify(eventObjCopy); + _this._invokeAppCommandCompletedMethod(args.appCommandId, 0, jsonString); + }; + return eventObj; + }; + AppCommandManager.initialize = function () { + if (AppCommandManager._instance == null) { + AppCommandManager._instance = new AppCommandManager(); + AppCommandManager._instance.initializeEventHandler(function (result) { + if (result.status !== Office.AsyncResultStatus.succeeded) { + console.error('Cannot initialize app command: ' + JSON.stringify(result)); + } + }); + } + }; + AppCommandManager._instance = null; + return AppCommandManager; + }()); + OSF.AppCommandManager = AppCommandManager; +})(OSF || (OSF = {})); +var OSF; +(function (OSF) { + var AppName; + (function (AppName) { + AppName[AppName["Unsupported"] = 0] = "Unsupported"; + AppName[AppName["Excel"] = 1] = "Excel"; + AppName[AppName["Word"] = 2] = "Word"; + AppName[AppName["PowerPoint"] = 4] = "PowerPoint"; + AppName[AppName["Outlook"] = 8] = "Outlook"; + AppName[AppName["ExcelWebApp"] = 16] = "ExcelWebApp"; + AppName[AppName["WordWebApp"] = 32] = "WordWebApp"; + AppName[AppName["OutlookWebApp"] = 64] = "OutlookWebApp"; + AppName[AppName["Project"] = 128] = "Project"; + AppName[AppName["AccessWebApp"] = 256] = "AccessWebApp"; + AppName[AppName["PowerpointWebApp"] = 512] = "PowerpointWebApp"; + AppName[AppName["ExcelIOS"] = 1024] = "ExcelIOS"; + AppName[AppName["Sway"] = 2048] = "Sway"; + AppName[AppName["WordIOS"] = 4096] = "WordIOS"; + AppName[AppName["PowerPointIOS"] = 8192] = "PowerPointIOS"; + AppName[AppName["Access"] = 16384] = "Access"; + AppName[AppName["Lync"] = 32768] = "Lync"; + AppName[AppName["OutlookIOS"] = 65536] = "OutlookIOS"; + AppName[AppName["OneNoteWebApp"] = 131072] = "OneNoteWebApp"; + AppName[AppName["OneNote"] = 262144] = "OneNote"; + AppName[AppName["ExcelWinRT"] = 524288] = "ExcelWinRT"; + AppName[AppName["WordWinRT"] = 1048576] = "WordWinRT"; + AppName[AppName["PowerpointWinRT"] = 2097152] = "PowerpointWinRT"; + AppName[AppName["OutlookAndroid"] = 4194304] = "OutlookAndroid"; + AppName[AppName["OneNoteWinRT"] = 8388608] = "OneNoteWinRT"; + AppName[AppName["ExcelAndroid"] = 8388609] = "ExcelAndroid"; + AppName[AppName["VisioWebApp"] = 8388610] = "VisioWebApp"; + AppName[AppName["OneNoteIOS"] = 8388611] = "OneNoteIOS"; + AppName[AppName["WordAndroid"] = 8388613] = "WordAndroid"; + AppName[AppName["PowerpointAndroid"] = 8388614] = "PowerpointAndroid"; + AppName[AppName["Visio"] = 8388615] = "Visio"; + AppName[AppName["OneNoteAndroid"] = 4194305] = "OneNoteAndroid"; + })(AppName = OSF.AppName || (OSF.AppName = {})); +})(OSF || (OSF = {})); +var OSF; +(function (OSF) { + var Association = (function () { + function Association() { + this.m_mappings = {}; + this.m_onchangeHandlers = []; + } + Association.prototype.associate = function (arg1, arg2) { + function consoleWarn(message) { + if (typeof console !== 'undefined' && console.warn) { + console.warn(message); + } + } + if (arguments.length == 1 && typeof arguments[0] === 'object' && arguments[0]) { + var mappings = arguments[0]; + for (var key in mappings) { + this.associate(key, mappings[key]); + } + } + else if (arguments.length == 2) { + var name_1 = arguments[0]; + var func = arguments[1]; + if (typeof name_1 !== 'string') { + consoleWarn('[InvalidArg] Function=associate'); + return; + } + if (typeof func !== 'function') { + consoleWarn('[InvalidArg] Function=associate'); + return; + } + var nameUpperCase = name_1.toUpperCase(); + if (this.m_mappings[nameUpperCase]) { + consoleWarn('[DuplicatedName] Function=' + name_1); + } + this.m_mappings[nameUpperCase] = func; + for (var i = 0; i < this.m_onchangeHandlers.length; i++) { + this.m_onchangeHandlers[i](); + } + } + else { + consoleWarn('[InvalidArg] Function=associate'); + } + }; + Association.prototype.onchange = function (handler) { + if (handler) { + this.m_onchangeHandlers.push(handler); + } + }; + Object.defineProperty(Association.prototype, "mappings", { + get: function () { + return this.m_mappings; + }, + enumerable: true, + configurable: true + }); + return Association; + }()); + OSF.Association = Association; +})(OSF || (OSF = {})); +var OSF; +(function (OSF) { + var AsyncMethodExecutor = (function () { + function AsyncMethodExecutor() { + } + AsyncMethodExecutor.prototype.invokeCallback = function (dispId, callback, status, value) { + if (status == 0) { + var successResult = { + status: Office.AsyncResultStatus.succeeded, + value: value + }; + callback(successResult); + } + else { + var errorResult = { + status: Office.AsyncResultStatus.failed, + error: { + code: status + } + }; + callback(errorResult); + } + }; + return AsyncMethodExecutor; + }()); + OSF.AsyncMethodExecutor = AsyncMethodExecutor; +})(OSF || (OSF = {})); +var OSF; +(function (OSF) { + var DDA; + (function (DDA) { + var AsyncResultEnum; + (function (AsyncResultEnum) { + var Properties; + (function (Properties) { + Properties["Context"] = "Context"; + Properties["Value"] = "Value"; + Properties["Status"] = "Status"; + Properties["Error"] = "Error"; + })(Properties = AsyncResultEnum.Properties || (AsyncResultEnum.Properties = {})); + ; + var ErrorCode; + (function (ErrorCode) { + ErrorCode[ErrorCode["Success"] = 0] = "Success"; + ErrorCode[ErrorCode["Failed"] = 1] = "Failed"; + })(ErrorCode = AsyncResultEnum.ErrorCode || (AsyncResultEnum.ErrorCode = {})); + ; + var ErrorProperties; + (function (ErrorProperties) { + ErrorProperties["Name"] = "Name"; + ErrorProperties["Message"] = "Message"; + ErrorProperties["Code"] = "Code"; + })(ErrorProperties = AsyncResultEnum.ErrorProperties || (AsyncResultEnum.ErrorProperties = {})); + ; + var AsyncResultStatus; + (function (AsyncResultStatus) { + AsyncResultStatus["Succeeded"] = "succeeded"; + AsyncResultStatus["Failed"] = "failed"; + })(AsyncResultStatus = AsyncResultEnum.AsyncResultStatus || (AsyncResultEnum.AsyncResultStatus = {})); + ; + })(AsyncResultEnum = DDA.AsyncResultEnum || (DDA.AsyncResultEnum = {})); + var AsyncResult = (function () { + function AsyncResult(initArgs, errorArgs) { + this.value = initArgs[AsyncResultEnum.Properties.Value]; + this.status = (errorArgs ? AsyncResultEnum.AsyncResultStatus.Failed : AsyncResultEnum.AsyncResultStatus.Succeeded); + if (initArgs[AsyncResultEnum.Properties.Context]) { + this.asyncContext = initArgs[AsyncResultEnum.Properties.Context]; + } + if (errorArgs) { + this.error = new Error(errorArgs[AsyncResultEnum.ErrorProperties.Name], errorArgs[AsyncResultEnum.ErrorProperties.Message], errorArgs[AsyncResultEnum.ErrorProperties.Code]); + } + } + return AsyncResult; + }()); + DDA.AsyncResult = AsyncResult; + var Error = (function () { + function Error(name, message, code) { + this.name = name; + this.message = message; + this.code = code; + } + return Error; + }()); + DDA.Error = Error; + })(DDA = OSF.DDA || (OSF.DDA = {})); +})(OSF || (OSF = {})); +var OSF; +(function (OSF) { + var ConstantNames; + (function (ConstantNames) { + ConstantNames["DefaultLocale"] = "en-us"; + ConstantNames["OfficeJS"] = "office.js"; + ConstantNames["OfficeDebugJS"] = "office.debug.js"; + ConstantNames["OfficeStringsId"] = "OFFICESTRINGS"; + ConstantNames["OfficeJsId"] = "OFFICEJS"; + ConstantNames["HostFileId"] = "HOST"; + ConstantNames["OfficeStringJS"] = "office_strings.js"; + ConstantNames["OfficeStringDebugJS"] = "office_strings.debug.js"; + })(ConstantNames = OSF.ConstantNames || (OSF.ConstantNames = {})); +})(OSF || (OSF = {})); +var OSF; +(function (OSF) { + var Constants = (function () { + function Constants() { + } + Constants.NotificationConversationIdSuffix = '_ntf'; + return Constants; + }()); + OSF.Constants = Constants; +})(OSF || (OSF = {})); +var CustomFunctionMappings; +(function (CustomFunctionMappings) { +})(CustomFunctionMappings || (CustomFunctionMappings = {})); +var CustomFunctions; +(function (CustomFunctions) { + function delayInitialization() { + CustomFunctionMappings.__delay__ = true; + } + CustomFunctions.delayInitialization = delayInitialization; + ; + CustomFunctions._association = new OSF.Association(); + function associate() { + CustomFunctions._association.associate.apply(CustomFunctions._association, arguments); + delete CustomFunctionMappings.__delay__; + } + CustomFunctions.associate = associate; + ; +})(CustomFunctions || (CustomFunctions = {})); +var OSF; +(function (OSF) { + var ErrorCodeManager = (function () { + function ErrorCodeManager() { + } + ErrorCodeManager.getAsyncResult = function (code) { + if (code == 0) { + return { + status: Office.AsyncResultStatus.succeeded + }; + } + else { + return { + status: Office.AsyncResultStatus.failed, + error: { + code: code + } + }; + } + }; + return ErrorCodeManager; + }()); + OSF.ErrorCodeManager = ErrorCodeManager; +})(OSF || (OSF = {})); +var OSF; +(function (OSF) { + var EventDispatch = (function () { + function EventDispatch(eventInfos) { + this._eventInfos = {}; + this._queuedEventsArgs = {}; + this._eventHandlers = {}; + this._queuedEventsArgs = {}; + if (eventInfos != null) { + for (var i = 0; i < eventInfos.length; i++) { + var eventType = eventInfos[i].type; + this._eventInfos[eventType] = eventInfos[i]; + this._eventHandlers[eventType] = []; + this._queuedEventsArgs[eventType] = []; + } + } + } + EventDispatch.prototype.getSupportedEvents = function () { + var events = []; + for (var eventName in this._eventHandlers) + events.push(eventName); + return events; + }; + EventDispatch.prototype.supportsEvent = function (event) { + for (var eventName in this._eventHandlers) { + if (event == eventName) + return true; + } + return false; + }; + EventDispatch.prototype.hasEventHandler = function (eventType, handler) { + var handlers = this._eventHandlers[eventType]; + if (handlers && handlers.length > 0) { + for (var i = 0; i < handlers.length; i++) { + if (handlers[i] === handler) + return true; + } + } + return false; + }; + EventDispatch.prototype.addEventHandler = function (eventType, handler) { + if (typeof handler != "function") { + return false; + } + var handlers = this._eventHandlers[eventType]; + if (handlers && !this.hasEventHandler(eventType, handler)) { + handlers.push(handler); + return true; + } + else { + return false; + } + }; + EventDispatch.prototype.addEventHandlerAndFireQueuedEvent = function (eventType, handler) { + var handlers = this._eventHandlers[eventType]; + var isFirstHandler = (!handlers || handlers.length == 0); + var succeed = this.addEventHandler(eventType, handler); + if (isFirstHandler && succeed) { + this.fireQueuedEvent(eventType); + } + return succeed; + }; + EventDispatch.prototype.removeEventHandler = function (eventType, handler) { + var handlers = this._eventHandlers[eventType]; + if (handlers && handlers.length > 0) { + for (var index = 0; index < handlers.length; index++) { + if (handlers[index] === handler) { + handlers.splice(index, 1); + return true; + } + } + } + return false; + }; + EventDispatch.prototype.clearEventHandlers = function (eventType) { + if (typeof this._eventHandlers[eventType] != "undefined" && this._eventHandlers[eventType].length > 0) { + this._eventHandlers[eventType] = []; + return true; + } + return false; + }; + EventDispatch.prototype.getEventHandlerCount = function (eventType) { + return this._eventHandlers[eventType] != undefined ? this._eventHandlers[eventType].length : -1; + }; + EventDispatch.prototype.getEventInfo = function (eventType) { + return this._eventInfos[eventType]; + }; + EventDispatch.prototype.fireEvent = function (eventArgs) { + if (eventArgs.type == undefined) + return false; + var eventType = eventArgs.type; + if (eventType && this._eventHandlers[eventType]) { + var eventHandlers = this._eventHandlers[eventType]; + for (var i = 0; i < eventHandlers.length; i++) { + eventHandlers[i](eventArgs); + } + return true; + } + else { + return false; + } + }; + EventDispatch.prototype.fireQueuedEvent = function (eventType) { + if (eventType && this._eventHandlers[eventType]) { + var eventHandlers = this._eventHandlers[eventType]; + var queuedEvents = this._queuedEventsArgs[eventType]; + if (eventHandlers.length > 0) { + var eventHandler = eventHandlers[0]; + while (queuedEvents.length > 0) { + var eventArgs = queuedEvents.shift(); + eventHandler(eventArgs); + } + return true; + } + } + return false; + }; + EventDispatch.prototype.clearQueuedEvent = function (eventType) { + if (eventType && this._eventHandlers[eventType]) { + var queuedEvents = this._queuedEventsArgs[eventType]; + if (queuedEvents) { + this._queuedEventsArgs[eventType] = []; + } + } + }; + return EventDispatch; + }()); + OSF.EventDispatch = EventDispatch; +})(OSF || (OSF = {})); +var OSF; +(function (OSF) { + var EventHelper = (function () { + function EventHelper() { + } + EventHelper.addEventHandler = function (eventType, handler, callback, eventDispatch, isPopupWindow) { + var dispId = 0; + function onEnsureRegistration(status) { + if (status == 0) { + if (!eventDispatch.hasEventHandler(eventType, handler)) { + var added = eventDispatch.addEventHandler(eventType, handler); + if (!added) { + status = 5010; + } + } + } + var asyncMethodExecutor = OSF._OfficeAppFactory.getAsyncMethodExecutor(); + asyncMethodExecutor.invokeCallback(dispId, callback, status, null); + } + var eventInfo = eventDispatch.getEventInfo(eventType); + if (!eventInfo) { + onEnsureRegistration(5010); + return; + } + try { + if (isPopupWindow) { + onEnsureRegistration(0); + return; + } + dispId = eventInfo.id; + var targetId = eventInfo.getTargetId(); + var count = eventDispatch.getEventHandlerCount(eventType); + if (count == 0) { + var asyncMethodExecutor = OSF._OfficeAppFactory.getAsyncMethodExecutor(); + asyncMethodExecutor.registerEventAsync(dispId, eventInfo.type, targetId, function (eventArgs) { + eventDispatch.fireEvent(eventArgs); + }, eventInfo, function (result) { + onEnsureRegistration(OSF.Utility.getErrorCodeFromAsyncResult(result)); + }); + } + else { + onEnsureRegistration(0); + } + } + catch (ex) { + EventHelper.onException(dispId, ex, callback); + } + }; + EventHelper.removeEventHandler = function (eventType, handler, callback, eventDispatch, isPopupWindow) { + var dispId = 0; + function onEnsureRegistration(status) { + var asyncMethodExecutor = OSF._OfficeAppFactory.getAsyncMethodExecutor(); + asyncMethodExecutor.invokeCallback(dispId, callback, status, null); + } + var eventInfo = eventDispatch.getEventInfo(eventType); + if (!eventInfo) { + onEnsureRegistration(5010); + return; + } + try { + dispId = eventInfo.id; + var targetId = eventInfo.getTargetId(); + var status_1 = 0; + var removeSuccess = true; + if (handler === null) { + removeSuccess = eventDispatch.clearEventHandlers(eventType); + status_1 = 0; + } + else { + removeSuccess = eventDispatch.removeEventHandler(eventType, handler); + status_1 = removeSuccess ? 0 : 5003; + } + var count = eventDispatch.getEventHandlerCount(eventType); + if (removeSuccess && count == 0) { + var asyncMethodExecutor = OSF._OfficeAppFactory.getAsyncMethodExecutor(); + asyncMethodExecutor.unregisterEventAsync(dispId, eventInfo.type, targetId, function (result) { + onEnsureRegistration(OSF.Utility.getErrorCodeFromAsyncResult(result)); + }); + } + else { + onEnsureRegistration(status_1); + } + } + catch (ex) { + EventHelper.onException(dispId, ex, callback); + } + }; + EventHelper.onException = function (dispId, ex, callback) { + if (typeof ex == "number") { + var asyncMethodExecutor = OSF._OfficeAppFactory.getAsyncMethodExecutor(); + asyncMethodExecutor.invokeCallback(dispId, callback, ex, null); + } + else { + throw ex; + } + }; + return EventHelper; + }()); + OSF.EventHelper = EventHelper; +})(OSF || (OSF = {})); +var OSF; +(function (OSF) { + var EventType; + (function (EventType) { + EventType["AppCommandInvoked"] = "appCommandInvoked"; + EventType["RichApiMessage"] = "richApiMessage"; + EventType["BindingSelectionChanged"] = "bindingSelectionChanged"; + EventType["BindingDataChanged"] = "bindingDataChanged"; + EventType["DataNodeDeleted"] = "nodeDeleted"; + EventType["DataNodeInserted"] = "nodeInserted"; + EventType["DataNodeReplaced"] = "nodeReplaced"; + EventType["SettingsChanged"] = "settingsChanged"; + })(EventType = OSF.EventType || (OSF.EventType = {})); +})(OSF || (OSF = {})); +var OSF; +(function (OSF) { + var HostName; + (function (HostName) { + var Host = (function () { + function Host() { + this.platformRemappings = { + web: Office.PlatformType.OfficeOnline, + winrt: Office.PlatformType.Universal, + win32: Office.PlatformType.PC, + mac: Office.PlatformType.Mac, + ios: Office.PlatformType.iOS, + android: Office.PlatformType.Android + }; + this.camelCaseMappings = { + powerpoint: Office.HostType.PowerPoint, + onenote: Office.HostType.OneNote + }; + this.hostInfo = OSF._OfficeAppFactory.getHostInfo(); + } + Host.prototype.capitalizeFirstLetter = function (input) { + if (input) { + return (input[0].toUpperCase() + input.slice(1).toLowerCase()); + } + return input; + }; + Host.getInstance = function () { + if (Host.hostObj === undefined) { + Host.hostObj = new Host(); + } + return Host.hostObj; + }; + Host.prototype.getPlatform = function (appNumber) { + if (this.hostInfo.hostPlatform) { + var hostPlatform = this.hostInfo.hostPlatform.toLowerCase(); + if (this.platformRemappings[hostPlatform]) { + return this.platformRemappings[hostPlatform]; + } + } + return null; + }; + Host.prototype.getHost = function (appNumber) { + if (this.hostInfo.hostType) { + var hostType = this.hostInfo.hostType.toLowerCase(); + if (this.camelCaseMappings[hostType]) { + return this.camelCaseMappings[hostType]; + } + hostType = this.capitalizeFirstLetter(this.hostInfo.hostType); + if (Office.HostType[hostType]) { + return Office.HostType[hostType]; + } + } + return null; + }; + Host.prototype.getDefaultVersion = function () { + if (this.getHost()) { + return "16.0.0000.0000"; + } + return null; + }; + Host.prototype.getDiagnostics = function (version) { + var diagnostics = { + host: this.getHost(), + version: (version || this.getDefaultVersion()), + platform: this.getPlatform() + }; + return diagnostics; + }; + return Host; + }()); + HostName.Host = Host; + })(HostName = OSF.HostName || (OSF.HostName = {})); +})(OSF || (OSF = {})); +var OSF; +(function (OSF) { + var HostInfoHostType; + (function (HostInfoHostType) { + HostInfoHostType["excel"] = "excel"; + HostInfoHostType["word"] = "word"; + })(HostInfoHostType = OSF.HostInfoHostType || (OSF.HostInfoHostType = {})); +})(OSF || (OSF = {})); +var OSF; +(function (OSF) { + var HostInfoPlatform; + (function (HostInfoPlatform) { + HostInfoPlatform["web"] = "web"; + HostInfoPlatform["winrt"] = "winrt"; + HostInfoPlatform["win32"] = "win32"; + HostInfoPlatform["mac"] = "mac"; + HostInfoPlatform["ios"] = "ios"; + HostInfoPlatform["android"] = "android"; + })(HostInfoPlatform = OSF.HostInfoPlatform || (OSF.HostInfoPlatform = {})); +})(OSF || (OSF = {})); +var OSF; +(function (OSF) { + var InitializationHelper = (function () { + function InitializationHelper(hostInfo, webAppState, context, hostFacade) { + this._hostInfo = hostInfo; + this._webAppState = webAppState; + this._context = context; + this._hostFacade = hostFacade; + } + ; + InitializationHelper.prototype.saveAndSetDialogInfo = function (hostInfoValue) { + }; + InitializationHelper.prototype.setAgaveHostCommunication = function () { + }; + InitializationHelper.prototype.createClientHostController = function () { + return null; + }; + InitializationHelper.prototype.createAsyncMethodExecutor = function () { + return null; + }; + InitializationHelper.prototype.createClientSettingsManager = function () { + return null; + }; + InitializationHelper.prototype.createSettings = function (serializedSettings) { + var osfSessionStorage = OSF.OUtil.getSessionStorage(); + if (osfSessionStorage) { + var storageSettings = osfSessionStorage.getItem(OSF._OfficeAppFactory.getCachedSessionSettingsKey()); + if (storageSettings) { + serializedSettings = JSON.parse(storageSettings); + } + else { + storageSettings = JSON.stringify(serializedSettings); + osfSessionStorage.setItem(OSF._OfficeAppFactory.getCachedSessionSettingsKey(), storageSettings); + } + } + var deserializedSettings = OSF.OUtil.deserializeSettings(serializedSettings); + var clientSettingsManager = this.createClientSettingsManager(); + var settings = new Office.Settings(deserializedSettings, clientSettingsManager); + return settings; + }; + InitializationHelper.prototype.prepareApiSurface = function (officeAppContext) { + var featureGates = officeAppContext.get_featureGates(); + if (featureGates) { + Microsoft.Office.WebExtension.FeatureGates = featureGates; + } + OSF.AppCommandManager.initialize(); + OSFPerformance.createOMEnd = OSFPerformance.now(); + }; + InitializationHelper.prototype.loadAppSpecificScriptAndCreateOM = function (officeAppContext, callback) { + throw OSF.Utility.createNotImplementedException(); + }; + return InitializationHelper; + }()); + OSF.InitializationHelper = InitializationHelper; +})(OSF || (OSF = {})); +var OSF; +(function (OSF) { + var InitializationReason; + (function (InitializationReason) { + InitializationReason["Inserted"] = "inserted"; + InitializationReason["DocumentOpened"] = "documentOpened"; + })(InitializationReason = OSF.InitializationReason || (OSF.InitializationReason = {})); +})(OSF || (OSF = {})); +var OSF; +(function (OSF) { +})(OSF || (OSF = {})); +var OSF; +(function (OSF) { + var LoadScriptHelper; + (function (LoadScriptHelper) { + var _scriptInfo; + var _officeScriptBase = ['excel', 'word', 'powerpoint', 'outlook', 'office-common', 'office.common']; + var _officeScriptSuffix = ['.js', '.debug.js']; + function getHostBundleJsBasePath() { + ensureScriptInfo(); + return _scriptInfo.basePath; + } + LoadScriptHelper.getHostBundleJsBasePath = getHostBundleJsBasePath; + function getHostBundleJsName() { + ensureScriptInfo(); + return _scriptInfo.name; + } + LoadScriptHelper.getHostBundleJsName = getHostBundleJsName; + function getOfficeStringJsName() { + ensureScriptInfo(); + return _scriptInfo.isDebugJs ? OSF.ConstantNames.OfficeStringDebugJS : OSF.ConstantNames.OfficeStringJS; + } + LoadScriptHelper.getOfficeStringJsName = getOfficeStringJsName; + function ensureScriptInfo() { + if (_scriptInfo) { + return; + } + var getScriptBase = function (scriptSrc, scriptNameToCheck) { + var scriptSrcLowerCase = scriptSrc.toLowerCase(); + var indexOfJS = scriptSrcLowerCase.indexOf(scriptNameToCheck); + if (indexOfJS >= 0 && + (indexOfJS === 0 || scriptSrc.charAt(indexOfJS - 1) === '/' || scriptSrc.charAt(indexOfJS - 1) === '\\') && + (indexOfJS + scriptNameToCheck.length === scriptSrc.length || scriptSrc.charAt(indexOfJS + scriptNameToCheck.length) === '?')) { + var scriptBase = scriptSrc.substring(0, indexOfJS); + var isDebugJs = scriptSrcLowerCase.indexOf(".debug.js", indexOfJS) > 0; + return { basePath: scriptBase, name: scriptNameToCheck, isDebugJs: isDebugJs }; + } + return null; + }; + var scripts = document.getElementsByTagName("script"); + var scriptsCount = scripts.length; + for (var i = 0; i < scriptsCount; i++) { + if (scripts[i].src) { + for (var j = 0; j < _officeScriptBase.length; j++) { + for (var k = 0; k < _officeScriptSuffix.length; k++) { + _scriptInfo = getScriptBase(scripts[i].src, _officeScriptBase[j] + _officeScriptSuffix[k]); + if (_scriptInfo) { + return; + } + } + } + } + } + _scriptInfo = { + basePath: "", + name: "", + isDebugJs: false + }; + } + })(LoadScriptHelper = OSF.LoadScriptHelper || (OSF.LoadScriptHelper = {})); +})(OSF || (OSF = {})); +var Microsoft; +(function (Microsoft) { + var Office; + (function (Office) { + var WebExtension; + (function (WebExtension) { + WebExtension.FeatureGates = {}; + function sendTelemetryEvent(telemetryEvent) { + OTel.OTelLogger.sendTelemetryEvent(telemetryEvent); + } + WebExtension.sendTelemetryEvent = sendTelemetryEvent; + })(WebExtension = Office.WebExtension || (Office.WebExtension = {})); + })(Office = Microsoft.Office || (Microsoft.Office = {})); +})(Microsoft || (Microsoft = {})); +var OSF; +(function (OSF) { + var SupportedLocales = { + "ar-sa": true, + "bg-bg": true, + "bn-in": true, + "ca-es": true, + "cs-cz": true, + "da-dk": true, + "de-de": true, + "el-gr": true, + "en-us": true, + "es-es": true, + "et-ee": true, + "eu-es": true, + "fa-ir": true, + "fi-fi": true, + "fr-fr": true, + "gl-es": true, + "he-il": true, + "hi-in": true, + "hr-hr": true, + "hu-hu": true, + "id-id": true, + "it-it": true, + "ja-jp": true, + "kk-kz": true, + "ko-kr": true, + "lo-la": true, + "lt-lt": true, + "lv-lv": true, + "ms-my": true, + "nb-no": true, + "nl-nl": true, + "nn-no": true, + "pl-pl": true, + "pt-br": true, + "pt-pt": true, + "ro-ro": true, + "ru-ru": true, + "sk-sk": true, + "sl-si": true, + "sr-cyrl-cs": true, + "sr-cyrl-rs": true, + "sr-latn-cs": true, + "sr-latn-rs": true, + "sv-se": true, + "th-th": true, + "tr-tr": true, + "uk-ua": true, + "ur-pk": true, + "vi-vn": true, + "zh-cn": true, + "zh-tw": true + }; + var AssociatedLocales = { + ar: "ar-sa", + bg: "bg-bg", + bn: "bn-in", + ca: "ca-es", + cs: "cs-cz", + da: "da-dk", + de: "de-de", + el: "el-gr", + en: "en-us", + es: "es-es", + et: "et-ee", + eu: "eu-es", + fa: "fa-ir", + fi: "fi-fi", + fr: "fr-fr", + gl: "gl-es", + he: "he-il", + hi: "hi-in", + hr: "hr-hr", + hu: "hu-hu", + id: "id-id", + it: "it-it", + ja: "ja-jp", + kk: "kk-kz", + ko: "ko-kr", + lo: "lo-la", + lt: "lt-lt", + lv: "lv-lv", + ms: "ms-my", + nb: "nb-no", + nl: "nl-nl", + nn: "nn-no", + pl: "pl-pl", + pt: "pt-br", + ro: "ro-ro", + ru: "ru-ru", + sk: "sk-sk", + sl: "sl-si", + sr: "sr-cyrl-cs", + sv: "sv-se", + th: "th-th", + tr: "tr-tr", + uk: "uk-ua", + ur: "ur-pk", + vi: "vi-vn", + zh: "zh-cn" + }; + function getSupportedLocale(locale, defaultLocale) { + if (defaultLocale === void 0) { defaultLocale = "en-us"; } + if (!locale) { + return defaultLocale; + } + var supportedLocale; + locale = locale.toLowerCase(); + if (locale in SupportedLocales) { + supportedLocale = locale; + } + else { + var localeParts = locale.split('-', 1); + if (localeParts && localeParts.length > 0) { + supportedLocale = AssociatedLocales[localeParts[0]]; + } + } + if (!supportedLocale) { + supportedLocale = defaultLocale; + } + return supportedLocale; + } + OSF.getSupportedLocale = getSupportedLocale; +})(OSF || (OSF = {})); +var Strings; +(function (Strings) { + var OfficeOM; + (function (OfficeOM) { + })(OfficeOM = Strings.OfficeOM || (Strings.OfficeOM = {})); +})(Strings || (Strings = {})); +var OSF; +(function (OSF) { + var OUtil; + (function (OUtil) { + var officeStringsJsLoadPromise; + function ensureOfficeStringsJs() { + if (!officeStringsJsLoadPromise) { + officeStringsJsLoadPromise = new Office.Promise(function (resolve, reject) { + if (!OSF._OfficeAppFactory.getHostInfo().hostLocale) { + reject(new Error("No host locale")); + return; + } + var url = OSF.LoadScriptHelper.getHostBundleJsBasePath() + OSF._OfficeAppFactory.getHostInfo().hostLocale + "/" + OSF.LoadScriptHelper.getOfficeStringJsName(); + OSF.OUtil.loadScript(url, function (success) { + if (success) { + resolve(); + } + else { + var fallbackUrl = OSF.LoadScriptHelper.getHostBundleJsBasePath() + OSF.ConstantNames.DefaultLocale + "/" + OSF.LoadScriptHelper.getOfficeStringJsName(); + OUtil.loadScript(fallbackUrl, function (fallbackUrlSuccess) { + if (fallbackUrlSuccess) { + resolve(); + } + else { + reject(new Error("Cannot load " + OSF.ConstantNames.OfficeStringJS)); + } + }); + } + }); + }); + } + return officeStringsJsLoadPromise; + } + OUtil.ensureOfficeStringsJs = ensureOfficeStringsJs; + })(OUtil = OSF.OUtil || (OSF.OUtil = {})); +})(OSF || (OSF = {})); +var Office; +(function (Office) { + var context; + (function (context) { + var document; + (function (document) { + function get_url() { + return OSF._OfficeAppFactory.getOfficeAppContext().get_docUrl(); + } + OSF.definePropertyOnNamespace(document, 'url', get_url); + function get_mode() { + var clientMode = OSF._OfficeAppFactory.getOfficeAppContext().get_clientMode(); + if (clientMode == 0) { + return Office.DocumentMode.ReadOnly; + } + return Office.DocumentMode.ReadWrite; + } + OSF.definePropertyOnNamespace(document, 'mode', get_mode); + var _settings; + function get_settings() { + if (!_settings) { + var settingsFunc = OSF._OfficeAppFactory.getOfficeAppContext().get_settingsFunc(); + var serializedSettings = settingsFunc(); + _settings = OSF._OfficeAppFactory.getInitializationHelper().createSettings(serializedSettings); + } + return _settings; + } + OSF.definePropertyOnNamespace(document, 'settings', get_settings); + function goToByIdAsync(id, goToType, arg1, arg2) { + var goToTypeMap = {}; + goToTypeMap[Office.GoToType.Binding] = 0; + goToTypeMap[Office.GoToType.NamedItem] = 1; + goToTypeMap[Office.GoToType.Slide] = 2; + goToTypeMap[Office.GoToType.Index] = 3; + var selectionModeMap = {}; + selectionModeMap[Office.SelectionMode.Default] = 0; + selectionModeMap[Office.SelectionMode.Selected] = 1; + selectionModeMap[Office.SelectionMode.None] = 2; + var goToTypeHostValue = goToTypeMap[goToType]; + var selectionModeHostValue = 0; + var callback = arg2; + if (typeof arg1 === "function") { + callback = arg1; + } + else if (typeof arg1 !== "undefined") { + selectionModeHostValue = selectionModeMap[arg1]; + } + var asyncMethodExecutor = OSF._OfficeAppFactory.getAsyncMethodExecutor(); + var dataTransform = { + toSafeArrayHost: function () { + return [id, goToTypeHostValue, selectionModeHostValue]; + }, + fromSafeArrayHost: function (payload) { + return payload; + }, + toWebHost: function () { + var navigationRequestParam = { + Id: id, + GoToType: goToTypeHostValue, + SelectionMode: selectionModeHostValue + }; + var obj = { + DdaGoToByIdMethod: navigationRequestParam + }; + return obj; + }, + fromWebHost: function (payload) { + return payload; + } + }; + asyncMethodExecutor.executeAsync(82, dataTransform, callback); + } + document.goToByIdAsync = goToByIdAsync; + })(document = context.document || (context.document = {})); + })(context = Office.context || (Office.context = {})); +})(Office || (Office = {})); +var Office; +(function (Office) { + var context; + (function (context) { + var messaging; + (function (messaging) { + function sendMessage(message) { + var hostInfo = OSF._OfficeAppFactory.getHostInfo(); + if (hostInfo.hostPlatform == OSF.HostInfoPlatform.web) { + var webAppState = OSF._OfficeAppFactory.getWebAppState(); + webAppState.clientEndPoint.invoke("ContextActivationManager_notifyHost", null, [webAppState.id, OSF.AgaveHostAction.SendMessage, message]); + } + else { + throw OSF.Utility.createNotImplementedException(); + } + } + messaging.sendMessage = sendMessage; + })(messaging = context.messaging || (context.messaging = {})); + })(context = Office.context || (Office.context = {})); +})(Office || (Office = {})); +var Office; +(function (Office) { + var context; + (function (context) { + function get_contentLanguage() { + return OSF._OfficeAppFactory.getOfficeAppContext().get_dataLocale(); + } + OSF.definePropertyOnNamespace(context, 'contentLanguage', get_contentLanguage); + function get_displayLanguage() { + return OSF._OfficeAppFactory.getOfficeAppContext().get_appUILocale(); + } + OSF.definePropertyOnNamespace(context, 'displayLanguage', get_displayLanguage); + function get_isDialog() { + return OSF._OfficeAppFactory.getHostInfo().isDialog; + } + OSF.definePropertyOnNamespace(context, 'isDialog', get_isDialog); + function get_touchEnabled() { + return OSF._OfficeAppFactory.getOfficeAppContext().get_touchEnabled(); + } + OSF.definePropertyOnNamespace(context, 'touchEnabled', get_touchEnabled); + function get_commerceAllowed() { + return OSF._OfficeAppFactory.getOfficeAppContext().get_commerceAllowed(); + } + OSF.definePropertyOnNamespace(context, 'commerceAllowed', get_commerceAllowed); + function get_host() { + return OSF.HostName.Host.getInstance().getHost(); + } + OSF.definePropertyOnNamespace(context, 'host', get_host); + function get_platform() { + return OSF.HostName.Host.getInstance().getPlatform(); + } + OSF.definePropertyOnNamespace(context, 'platform', get_platform); + function get_diagnostics() { + return OSF.HostName.Host.getInstance().getDiagnostics(OSF._OfficeAppFactory.getOfficeAppContext().get_hostFullVersion()); + } + OSF.definePropertyOnNamespace(context, 'diagnostics', get_diagnostics); + var _requirements; + function get_requirements() { + if (!_requirements) { + var appContext = OSF._OfficeAppFactory.getOfficeAppContext(); + if (appContext) { + if (appContext.get_isDialog()) { + _requirements = OSF.Requirement.RequirementsMatrixFactory.getDefaultDialogRequirementMatrix(appContext); + } + else { + _requirements = OSF.Requirement.RequirementsMatrixFactory.getDefaultRequirementMatrix(appContext); + } + } + } + return _requirements; + } + OSF.definePropertyOnNamespace(context, 'requirements', get_requirements); + var _officeTheme; + function get_officeTheme() { + if (!_officeTheme) { + var func = OSF._OfficeAppFactory.getOfficeAppContext().get_officeThemeFunc(); + if (func) { + _officeTheme = func(); + } + else { + return undefined; + } + } + return _officeTheme; + } + OSF.definePropertyOnNamespace(context, 'officeTheme', get_officeTheme); + OSF.definePropertyOnNamespace(context, 'webAuth', function () { + if (OSF.DDA.WebAuth) { + return OSF.DDA.WebAuth; + } + return undefined; + }); + })(context = Office.context || (Office.context = {})); +})(Office || (Office = {})); +var Office; +(function (Office) { + var context; + (function (context) { + var ui; + (function (ui) { + var taskPaneAction; + (function (taskPaneAction) { + })(taskPaneAction = ui.taskPaneAction || (ui.taskPaneAction = {})); + })(ui = context.ui || (context.ui = {})); + })(context = Office.context || (Office.context = {})); +})(Office || (Office = {})); +var __assign = (this && this.__assign) || function () { + __assign = Object.assign || function(t) { + for (var s, i = 1, n = arguments.length; i < n; i++) { + s = arguments[i]; + for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) + t[p] = s[p]; + } + return t; + }; + return __assign.apply(this, arguments); +}; +var Office; +(function (Office) { + var _isOfficeOnReadyCalled = false; + var _officeOnReadyPromise = null; + var _officeOnReadyPromiseResolve = null; + var _officeOnReadyCallbacks = []; + var _officeOnReadyHostAndPlatformInfo; + var _officeOnReadyFired; + function ensureOfficeOnReadyPromise() { + if (!_officeOnReadyPromise) { + _officeOnReadyPromise = new Office.Promise(function (resolve, reject) { + _officeOnReadyPromiseResolve = resolve; + }); + } + } + function onReadyInternal(callback) { + ensureOfficeOnReadyPromise(); + if (callback) { + if (_officeOnReadyFired) { + callback(_officeOnReadyHostAndPlatformInfo); + } + else { + _officeOnReadyCallbacks.push(callback); + } + } + return _officeOnReadyPromise; + } + Office.onReadyInternal = onReadyInternal; + function onReady(callback) { + _isOfficeOnReadyCalled = true; + return onReadyInternal(callback); + } + Office.onReady = onReady; + function fireOnReady(hostAndPlatformInfo) { + ensureOfficeOnReadyPromise(); + _officeOnReadyHostAndPlatformInfo = __assign({}, hostAndPlatformInfo); + _officeOnReadyFired = true; + OSFPerformance.officeOnReady = OSFPerformance.now(); + while (_officeOnReadyCallbacks.length > 0) { + _officeOnReadyCallbacks.shift()(_officeOnReadyHostAndPlatformInfo); + } + _officeOnReadyPromiseResolve(_officeOnReadyHostAndPlatformInfo); + } + Office.fireOnReady = fireOnReady; + function sendTelemetryEvent(telemetryEvent) { + Microsoft.Office.WebExtension.sendTelemetryEvent(telemetryEvent); + } + Office.sendTelemetryEvent = sendTelemetryEvent; + Microsoft.Office.WebExtension.onReadyInternal = Office.onReadyInternal; +})(Office || (Office = {})); +var OSF; +(function (OSF) { + var OfficeAppContext = (function () { + function OfficeAppContext(id, appName, appVersion, appUILocale, dataLocale, docUrl, clientMode, settingsFunc, reason, osfControlType, eToken, correlationId, appInstanceId, touchEnabled, commerceAllowed, appMinorVersion, requirementMatrix, hostCustomMessage, hostFullVersion, clientWindowHeight, clientWindowWidth, addinName, appDomains, dialogRequirementMatrix, featureGates, officeThemeFunc, initialDisplayMode, isFromWacAutomation) { + this._isDialog = false; + this._id = id; + this._appName = appName; + this._appVersion = appVersion; + this._appUILocale = appUILocale; + this._dataLocale = dataLocale; + this._docUrl = docUrl; + this._clientMode = clientMode; + this._settingsFunc = settingsFunc; + this._reason = reason; + this._osfControlType = osfControlType; + this._eToken = eToken; + this._correlationId = correlationId; + this._appInstanceId = appInstanceId; + this._touchEnabled = touchEnabled; + this._commerceAllowed = commerceAllowed; + this._appMinorVersion = appMinorVersion; + this._requirementMatrix = requirementMatrix; + this._hostCustomMessage = hostCustomMessage; + this._hostFullVersion = hostFullVersion; + this._isDialog = false; + this._clientWindowHeight = clientWindowHeight; + this._clientWindowWidth = clientWindowWidth; + this._addinName = addinName; + this._appDomains = appDomains; + this._dialogRequirementMatrix = dialogRequirementMatrix; + this._featureGates = featureGates; + this._officeThemeFunc = officeThemeFunc; + this._initialDisplayMode = initialDisplayMode; + this._isFromWacAutomation = isFromWacAutomation; + } + OfficeAppContext.prototype.get_id = function () { + return this._id; + }; + OfficeAppContext.prototype.get_appName = function () { + return this._appName; + }; + OfficeAppContext.prototype.get_appVersion = function () { + return this._appVersion; + }; + OfficeAppContext.prototype.get_appUILocale = function () { + return this._appUILocale; + }; + OfficeAppContext.prototype.get_dataLocale = function () { return this._dataLocale; }; + OfficeAppContext.prototype.get_docUrl = function () { return this._docUrl; }; + OfficeAppContext.prototype.get_clientMode = function () { return this._clientMode; }; + OfficeAppContext.prototype.get_settingsFunc = function () { return this._settingsFunc; }; + OfficeAppContext.prototype.get_reason = function () { return this._reason; }; + OfficeAppContext.prototype.get_osfControlType = function () { return this._osfControlType; }; + OfficeAppContext.prototype.get_eToken = function () { return this._eToken; }; + OfficeAppContext.prototype.get_correlationId = function () { return this._correlationId; }; + OfficeAppContext.prototype.get_appInstanceId = function () { return this._appInstanceId; }; + OfficeAppContext.prototype.get_touchEnabled = function () { return this._touchEnabled; }; + OfficeAppContext.prototype.get_commerceAllowed = function () { return this._commerceAllowed; }; + OfficeAppContext.prototype.get_appMinorVersion = function () { return this._appMinorVersion; }; + OfficeAppContext.prototype.get_requirementMatrix = function () { return this._requirementMatrix; }; + OfficeAppContext.prototype.get_dialogRequirementMatrix = function () { return this._dialogRequirementMatrix; }; + OfficeAppContext.prototype.get_hostCustomMessage = function () { return this._hostCustomMessage; }; + OfficeAppContext.prototype.get_hostFullVersion = function () { return this._hostFullVersion; }; + OfficeAppContext.prototype.get_isDialog = function () { return this._isDialog; }; + OfficeAppContext.prototype.get_clientWindowHeight = function () { return this._clientWindowHeight; }; + OfficeAppContext.prototype.get_clientWindowWidth = function () { return this._clientWindowWidth; }; + OfficeAppContext.prototype.get_addinName = function () { return this._addinName; }; + OfficeAppContext.prototype.get_appDomains = function () { return this._appDomains; }; + OfficeAppContext.prototype.get_featureGates = function () { return this._featureGates; }; + OfficeAppContext.prototype.get_officeThemeFunc = function () { return this._officeThemeFunc; }; + OfficeAppContext.prototype.get_initialDisplayMode = function () { return this._initialDisplayMode ? this._initialDisplayMode : 0; }; + OfficeAppContext.prototype.get_isFromWacAutomation = function () { return this._isFromWacAutomation; }; + return OfficeAppContext; + }()); + OSF.OfficeAppContext = OfficeAppContext; +})(OSF || (OSF = {})); +var OSF; +(function (OSF) { + var _OfficeAppFactory; + (function (_OfficeAppFactory) { + var _windowLocationHash; + var _windowLocationSearch; + var _windowName; + if (typeof (window) !== 'undefined') { + if (window.location) { + _windowLocationHash = window.location.hash; + _windowLocationSearch = window.location.search; + } + _windowName = window.name; + } + var _hostInfo; + var _webAppState; + var _isLoggingAllowed; + var _initializationHelper; + var _asyncMethodExecutor; + var _officeAppContext; + var _initialDisplayModeMappings = { + 0: "Unknown", + 1: "Hidden", + 2: "Taskpane", + 3: "Dialog" + }; + function bootstrap(onSuccess, onError) { + _webAppState = { + id: null, + webAppUrl: null, + conversationID: null, + clientEndPoint: null, + wnd: window.parent, + focused: false, + serviceEndPoint: null, + serializerVersion: 1 + }; + retrieveHostInfo(); + retrieveLoggingAllowed(); + createInitializationHelper(); + if (!_initializationHelper) { + onError(new Error("Office.js cannot be initialized.")); + return; + } + if (_hostInfo.hostPlatform === OSF.HostInfoPlatform.web) { + _initializationHelper.saveAndSetDialogInfo(OSF.Utility.getQueryStringValue("_host_Info")); + } + _initializationHelper.setAgaveHostCommunication(); + OSFPerformance.getAppContextStart = OSFPerformance.now(); + var onGetAppContextSuccess = function (officeAppContext) { + OSFPerformance.getAppContextEnd = OSFPerformance.now(); + OSF.AppTelemetry.initialize(officeAppContext); + _officeAppContext = officeAppContext; + _initializationHelper.createClientHostController(); + _asyncMethodExecutor = _initializationHelper.createAsyncMethodExecutor(); + _initializationHelper.prepareApiSurface(officeAppContext); + var appNameNumber = officeAppContext.get_appName(); + var addinInfo = null; + if ((_hostInfo.flags & 1) !== 0) { + addinInfo = { + visibilityMode: _initialDisplayModeMappings[officeAppContext.get_initialDisplayMode()] + }; + } + Office.fireOnReady({ + host: OSF.HostName.Host.getInstance().getHost(appNameNumber), + platform: OSF.HostName.Host.getInstance().getPlatform(appNameNumber), + addin: addinInfo + }); + notifyHostOfficeReady(); + onSuccess(officeAppContext); + }; + var onGetAppContextError = function (e) { + onError(e); + }; + _initializationHelper.getAppContext(window, onGetAppContextSuccess, onGetAppContextError); + } + _OfficeAppFactory.bootstrap = bootstrap; + function retrieveHostInfo() { + _hostInfo = { + isO15: true, + isRichClient: true, + hostType: "", + hostPlatform: "", + hostSpecificFileVersion: "", + hostLocale: "", + osfControlAppCorrelationId: "", + isDialog: false, + disableLogging: false, + flags: 0 + }; + var hostInfoParaName = "_host_Info"; + var hostInfoValue = OSF.Utility.getQueryStringValue(hostInfoParaName); + if (!hostInfoValue) { + try { + var windowName = window.name; + if (windowName) { + var windowNameObj = JSON.parse(windowName); + hostInfoValue = windowNameObj ? windowNameObj["hostInfo"] : null; + } + } + catch (ex) { + OSF.Utility.log(JSON.stringify(ex)); + } + } + if (!hostInfoValue) { + try { + window.external = window.external || {}; + if (typeof agaveHost !== "undefined" && agaveHost.GetHostInfo) { + window.external.GetHostInfo = function () { + return agaveHost.GetHostInfo(); + }; + } + if (window.external.GetHostInfo) { + var fallbackHostInfo = window.external.GetHostInfo(); + if (fallbackHostInfo == "isDialog") { + _hostInfo.isO15 = true; + _hostInfo.isDialog = true; + } + else { + var hostInfoParts = fallbackHostInfo.split(hostInfoParaName + "="); + if (hostInfoParts.length > 1) { + hostInfoValue = hostInfoParts[1]; + } + else { + hostInfoValue = fallbackHostInfo; + } + } + } + } + catch (ex) { + OSF.Utility.log(JSON.stringify(ex)); + } + } + var osfSessionStorage = OSF.OUtil.getSessionStorage(); + if (!hostInfoValue && osfSessionStorage.getItem("hostInfoValue")) { + hostInfoValue = osfSessionStorage.getItem("hostInfoValue"); + } + if (hostInfoValue) { + hostInfoValue = decodeURIComponent(hostInfoValue); + _hostInfo.isO15 = false; + var items = hostInfoValue.split("$"); + if (typeof items[2] == "undefined") { + items = hostInfoValue.split("|"); + } + _hostInfo.hostType = (typeof items[0] == "undefined") ? "" : items[0].toLowerCase(); + _hostInfo.hostPlatform = (typeof items[1] == "undefined") ? "" : items[1].toLowerCase(); + ; + _hostInfo.hostSpecificFileVersion = (typeof items[2] == "undefined") ? "" : items[2].toLowerCase(); + _hostInfo.hostLocale = (typeof items[3] == "undefined") ? "" : items[3].toLowerCase(); + _hostInfo.osfControlAppCorrelationId = (typeof items[4] == "undefined") ? "" : items[4]; + if (_hostInfo.osfControlAppCorrelationId == "telemetry") { + _hostInfo.osfControlAppCorrelationId = ""; + } + _hostInfo.isDialog = (((typeof items[5]) != "undefined") && items[5] == "isDialog") ? true : false; + _hostInfo.disableLogging = (((typeof items[6]) != "undefined") && items[6] == "disableLogging") ? true : false; + _hostInfo.flags = (((typeof items[7]) === "string") && items[7].length > 0) ? parseInt(items[7]) : 0; + osfSessionStorage.setItem("hostInfoValue", hostInfoValue); + } + else { + _hostInfo.isO15 = true; + _hostInfo.hostLocale = OSF.Utility.getQueryStringValue("locale"); + } + } + function retrieveLoggingAllowed() { + _isLoggingAllowed = true; + try { + if (_hostInfo.disableLogging) { + _isLoggingAllowed = false; + return; + } + window.external = window.external || {}; + if (typeof window.external.GetLoggingAllowed === 'undefined') { + _isLoggingAllowed = true; + } + else { + _isLoggingAllowed = window.external.GetLoggingAllowed(); + } + } + catch (ex) { + } + } + function createInitializationHelper() { + if (_hostInfo.hostPlatform === OSF.HostInfoPlatform.web) { + _initializationHelper = new OSF.WebInitializationHelper(_hostInfo, _webAppState, null, null); + } + else if (_hostInfo.hostPlatform === OSF.HostInfoPlatform.win32) { + _initializationHelper = new OSF.RichClientInitializationHelper(_hostInfo, _webAppState, null, null); + } + else if (_hostInfo.hostPlatform === OSF.HostInfoPlatform.ios || _hostInfo.hostPlatform === OSF.HostInfoPlatform.mac) { + if (isWebkit2Sandbox()) { + _initializationHelper = new OSF.WebkitInitializationHelper(_hostInfo, _webAppState, null, null); + } + else { + throw OSF.Utility.createNotImplementedException(); + } + } + else { + console.warn("Office.js is loaded inside in unknown host or platform " + _hostInfo.hostPlatform); + } + } + function isWebkit2Sandbox() { + return window.webkit && window.webkit.messageHandlers && window.webkit.messageHandlers.Agave; + } + function notifyHostOfficeReady() { + if (_hostInfo.hostPlatform == OSF.HostInfoPlatform.web) { + if (_webAppState.clientEndPoint != null) { + _webAppState.clientEndPoint.invoke("ContextActivationManager_notifyHost", null, [_webAppState.id, OSF.AgaveHostAction.OfficeJsReady, Date.now()]); + } + } + } + function getWindowName() { + return _windowName; + } + _OfficeAppFactory.getWindowName = getWindowName; + function getWindowLocationHash() { + return _windowLocationHash; + } + _OfficeAppFactory.getWindowLocationHash = getWindowLocationHash; + function getWindowLocationSearch() { + return _windowLocationSearch; + } + _OfficeAppFactory.getWindowLocationSearch = getWindowLocationSearch; + function getAsyncMethodExecutor() { + return _asyncMethodExecutor; + } + _OfficeAppFactory.getAsyncMethodExecutor = getAsyncMethodExecutor; + function getOfficeAppContext() { + return _officeAppContext; + } + _OfficeAppFactory.getOfficeAppContext = getOfficeAppContext; + function getHostInfo() { + return _hostInfo; + } + _OfficeAppFactory.getHostInfo = getHostInfo; + function getCachedSessionSettingsKey() { + return (_webAppState.conversationID != null ? _webAppState.conversationID : _officeAppContext.get_appInstanceId()) + "CachedSessionSettings"; + } + _OfficeAppFactory.getCachedSessionSettingsKey = getCachedSessionSettingsKey; + function getWebAppState() { + return _webAppState; + } + _OfficeAppFactory.getWebAppState = getWebAppState; + function getId() { + return _webAppState.id; + } + _OfficeAppFactory.getId = getId; + function getInitializationHelper() { + return _initializationHelper; + } + _OfficeAppFactory.getInitializationHelper = getInitializationHelper; + })(_OfficeAppFactory = OSF._OfficeAppFactory || (OSF._OfficeAppFactory = {})); + function getClientEndPoint() { + return _OfficeAppFactory.getWebAppState().clientEndPoint; + } + OSF.getClientEndPoint = getClientEndPoint; +})(OSF || (OSF = {})); +var Office; +(function (Office) { + var VisibilityMode; + (function (VisibilityMode) { + VisibilityMode["hidden"] = "Hidden"; + VisibilityMode["taskpane"] = "Taskpane"; + })(VisibilityMode = Office.VisibilityMode || (Office.VisibilityMode = {})); + var AsyncResultStatus; + (function (AsyncResultStatus) { + AsyncResultStatus["succeeded"] = "succeeded"; + AsyncResultStatus["failed"] = "failed"; + })(AsyncResultStatus = Office.AsyncResultStatus || (Office.AsyncResultStatus = {})); + var DocumentMode; + (function (DocumentMode) { + DocumentMode["ReadOnly"] = "readOnly"; + DocumentMode["ReadWrite"] = "readWrite"; + })(DocumentMode = Office.DocumentMode || (Office.DocumentMode = {})); + var HostType; + (function (HostType) { + HostType["Word"] = "Word"; + HostType["Excel"] = "Excel"; + HostType["PowerPoint"] = "PowerPoint"; + HostType["Outlook"] = "Outlook"; + HostType["OneNote"] = "OneNote"; + HostType["Project"] = "Project"; + HostType["Access"] = "Access"; + HostType["Visio"] = "Visio"; + })(HostType = Office.HostType || (Office.HostType = {})); + var InitializationReason; + (function (InitializationReason) { + InitializationReason["Inserted"] = "inserted"; + InitializationReason["DocumentOpened"] = "documentOpened"; + })(InitializationReason = Office.InitializationReason || (Office.InitializationReason = {})); + var PlatformType; + (function (PlatformType) { + PlatformType["PC"] = "PC"; + PlatformType["OfficeOnline"] = "OfficeOnline"; + PlatformType["Mac"] = "Mac"; + PlatformType["iOS"] = "iOS"; + PlatformType["Android"] = "Android"; + PlatformType["Universal"] = "Universal"; + })(PlatformType = Office.PlatformType || (Office.PlatformType = {})); + var GoToType; + (function (GoToType) { + GoToType["Binding"] = "binding"; + GoToType["NamedItem"] = "namedItem"; + GoToType["Slide"] = "slide"; + GoToType["Index"] = "index"; + })(GoToType = Office.GoToType || (Office.GoToType = {})); + var SelectionMode; + (function (SelectionMode) { + SelectionMode["Default"] = "default"; + SelectionMode["Selected"] = "selected"; + SelectionMode["None"] = "none"; + })(SelectionMode = Office.SelectionMode || (Office.SelectionMode = {})); +})(Office || (Office = {})); +var __extends = (this && this.__extends) || (function () { + var extendStatics = function (d, b) { + extendStatics = Object.setPrototypeOf || + ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || + function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; + return extendStatics(d, b); + }; + return function (d, b) { + extendStatics(d, b); + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; +})(); +var OfficeExt; +(function (OfficeExt) { + function appSpecificCheckOriginFunction(allowed_domains, eventObj, origin, checkOriginFunction) { + return false; + } + ; + OfficeExt.appSpecificCheckOrigin = appSpecificCheckOriginFunction; +})(OfficeExt || (OfficeExt = {})); +var OSF; +(function (OSF) { + ; + var XdmMethodObject = (function () { + function XdmMethodObject(method, invokeType, blockingOthers) { + this._method = method; + this._invokeType = invokeType; + this._blockingOthers = blockingOthers; + } + XdmMethodObject.prototype.getMethod = function () { + return this._method; + }; + XdmMethodObject.prototype.getInvokeType = function () { + return this._invokeType; + }; + XdmMethodObject.prototype.getBlockingFlag = function () { + return this._blockingOthers; + }; + return XdmMethodObject; + }()); + OSF.XdmMethodObject = XdmMethodObject; + var XdmEventMethodObject = (function () { + function XdmEventMethodObject(registerMethodObject, unregisterMethodObject) { + this._registerMethodObject = registerMethodObject; + this._unregisterMethodObject = unregisterMethodObject; + } + XdmEventMethodObject.prototype.getRegisterMethodObject = function () { + return this._registerMethodObject; + }; + XdmEventMethodObject.prototype.getUnregisterMethodObject = function () { + return this._unregisterMethodObject; + }; + return XdmEventMethodObject; + }()); + OSF.XdmEventMethodObject = XdmEventMethodObject; + ; + var XdmServiceEndPoint = (function () { + function XdmServiceEndPoint(serviceEndPointId) { + this._methodObjectList = {}; + this._eventHandlerProxyList = {}; + this._conversations = {}; + this._policyManager = null; + this._appDomains = {}; + this._onHandleRequestError = null; + this._methodObjectList = {}; + this._eventHandlerProxyList = {}; + this._Id = serviceEndPointId; + this._conversations = {}; + this._policyManager = null; + this._appDomains = {}; + this._onHandleRequestError = null; + } + XdmServiceEndPoint.prototype.registerMethod = function (methodName, method, invokeType, blockingOthers) { + if (invokeType !== 0 + && invokeType !== 1) { + throw OSF.Utility.createArgumentException("invokeType"); + } + var methodObject = new XdmMethodObject(method, invokeType, blockingOthers); + this._methodObjectList[methodName] = methodObject; + }; + XdmServiceEndPoint.prototype.unregisterMethod = function (methodName) { + delete this._methodObjectList[methodName]; + }; + XdmServiceEndPoint.prototype.registerEvent = function (eventName, registerMethod, unregisterMethod) { + var methodObject = new XdmEventMethodObject(new XdmMethodObject(registerMethod, 4, false), new XdmMethodObject(unregisterMethod, 5, false)); + this._methodObjectList[eventName] = methodObject; + }; + XdmServiceEndPoint.prototype.registerEventEx = function (eventName, registerMethod, registerMethodInvokeType, unregisterMethod, unregisterMethodInvokeType) { + var methodObject = new XdmEventMethodObject(new XdmMethodObject(registerMethod, registerMethodInvokeType, false), new XdmMethodObject(unregisterMethod, unregisterMethodInvokeType, false)); + this._methodObjectList[eventName] = methodObject; + }; + XdmServiceEndPoint.prototype.unregisterEvent = function (eventName) { + this.unregisterMethod(eventName); + }; + XdmServiceEndPoint.prototype.registerConversation = function (conversationId, conversationUrl, appDomains, serializerVersion) { + OSF.Utility.xdmDebugLog("registerConversation: cId=" + conversationId + " Url=" + conversationUrl); + if (appDomains) { + if (!Array.isArray(appDomains)) { + throw OSF.Utility.createArgumentException("appDomains"); + } + this._appDomains[conversationId] = appDomains; + } + this._conversations[conversationId] = { url: conversationUrl, serializerVersion: serializerVersion }; + }; + XdmServiceEndPoint.prototype.unregisterConversation = function (conversationId) { + delete this._conversations[conversationId]; + }; + XdmServiceEndPoint.prototype.setPolicyManager = function (policyManager) { + if (!policyManager.checkPermission) { + throw OSF.Utility.createArgumentException("policyManager"); + } + this._policyManager = policyManager; + }; + XdmServiceEndPoint.prototype.getPolicyManager = function () { + return this._policyManager; + }; + XdmServiceEndPoint.prototype.dispose = function () { + this._methodObjectList = null; + this._eventHandlerProxyList = null; + this._Id = null; + this._conversations = null; + this._policyManager = null; + this._appDomains = null; + this._onHandleRequestError = null; + }; + return XdmServiceEndPoint; + }()); + OSF.XdmServiceEndPoint = XdmServiceEndPoint; + var XdmClientEndPoint = (function () { + function XdmClientEndPoint(conversationId, targetWindow, targetUrl, serializerVersion) { + this._callbackList = {}; + this._eventHandlerList = {}; + this._hostTrustCheckStatus = 0; + this._checkStatusLogged = false; + this._conversationId = conversationId; + this._targetWindow = targetWindow; + this._targetUrl = targetUrl; + this._callingIndex = 0; + this._callbackList = {}; + this._eventHandlerList = {}; + if (serializerVersion != null) { + this._serializerVersion = serializerVersion; + } + else { + this._serializerVersion = 1; + } + this._checkReceiverOriginAndRun = null; + ; + } + ; + Object.defineProperty(XdmClientEndPoint.prototype, "targetUrl", { + get: function () { + return this._targetUrl; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(XdmClientEndPoint.prototype, "hostTrustCheckStatus", { + get: function () { + return this._hostTrustCheckStatus; + }, + set: function (value) { + this._hostTrustCheckStatus = value; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(XdmClientEndPoint.prototype, "checkStatusLogged", { + get: function () { + return this._checkStatusLogged; + }, + set: function (value) { + this._checkStatusLogged = value; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(XdmClientEndPoint.prototype, "checkReceiverOriginAndRun", { + get: function () { + return this._checkReceiverOriginAndRun; + }, + set: function (value) { + this._checkReceiverOriginAndRun = value; + }, + enumerable: true, + configurable: true + }); + XdmClientEndPoint.prototype.invoke = function (targetMethodName, callback, param) { + var _this = this; + var funcToRun = function () { + var correlationId = _this._callingIndex++; + var now = new Date(); + var callbackEntry = { "callback": callback, "createdOn": now.getTime() }; + if (param && typeof param === "object" && typeof param.__timeout__ === "number") { + callbackEntry.timeout = param.__timeout__; + delete param.__timeout__; + } + _this._callbackList[correlationId] = callbackEntry; + try { + if (_this._hostTrustCheckStatus !== 3) { + if (targetMethodName !== "ContextActivationManager_getAppContextAsync") { + throw "Access Denied"; + } + } + var callRequest = new XdmRequest(targetMethodName, 0, _this._conversationId, correlationId, param); + var msg = XdmMessagePackager.envelope(callRequest, _this._serializerVersion); + _this._targetWindow.postMessage(msg, _this._targetUrl); + XdmCommunicationManager._startMethodTimeoutTimer(); + } + catch (ex) { + try { + if (callback !== null) + callback(-1, ex); + } + finally { + delete _this._callbackList[correlationId]; + } + } + }; + if (this._checkReceiverOriginAndRun) { + this._checkReceiverOriginAndRun(funcToRun); + } + else { + this._hostTrustCheckStatus = 3; + funcToRun(); + } + }; + XdmClientEndPoint.prototype.registerForEvent = function (targetEventName, eventHandler, callback, data) { + var correlationId = this._callingIndex++; + var now = new Date(); + this._callbackList[correlationId] = { "callback": callback, "createdOn": now.getTime() }; + try { + var callRequest = new XdmRequest(targetEventName, 1, this._conversationId, correlationId, data); + var msg = XdmMessagePackager.envelope(callRequest, this._serializerVersion); + this._targetWindow.postMessage(msg, this._targetUrl); + XdmCommunicationManager._startMethodTimeoutTimer(); + this._eventHandlerList[targetEventName] = eventHandler; + } + catch (ex) { + try { + if (callback !== null) { + callback(-1, ex); + } + } + finally { + delete this._callbackList[correlationId]; + } + } + }; + XdmClientEndPoint.prototype.unregisterForEvent = function (targetEventName, callback, data) { + var correlationId = this._callingIndex++; + var now = new Date(); + this._callbackList[correlationId] = { "callback": callback, "createdOn": now.getTime() }; + try { + var callRequest = new XdmRequest(targetEventName, 2, this._conversationId, correlationId, data); + var msg = XdmMessagePackager.envelope(callRequest, this._serializerVersion); + this._targetWindow.postMessage(msg, this._targetUrl); + XdmCommunicationManager._startMethodTimeoutTimer(); + } + catch (ex) { + try { + if (callback !== null) { + callback(-1, ex); + } + } + finally { + delete this._callbackList[correlationId]; + } + } + finally { + delete this._eventHandlerList[targetEventName]; + } + }; + return XdmClientEndPoint; + }()); + OSF.XdmClientEndPoint = XdmClientEndPoint; + ; + var XdmCommunicationManager; + (function (XdmCommunicationManager) { + var _invokerQueue = []; + var _lastMessageProcessTime = null; + var _messageProcessingTimer = null; + var _processInterval = 10; + var _blockingFlag = false; + var _methodTimeoutTimer = null; + var _methodTimeoutProcessInterval = 2000; + var _methodTimeoutDefault = 65000; + var _methodTimeout = _methodTimeoutDefault; + var _serviceEndPoints = {}; + var _clientEndPoints = {}; + var _initialized = false; + function _lookupServiceEndPoint(conversationId) { + for (var id in _serviceEndPoints) { + if (_serviceEndPoints[id]._conversations[conversationId]) { + return _serviceEndPoints[id]; + } + } + throw OSF.Utility.createArgumentException("conversationId"); + } + ; + function _lookupClientEndPoint(conversationId) { + var clientEndPoint = _clientEndPoints[conversationId]; + if (!clientEndPoint) { + OSF.Utility.xdmDebugLog("Unknown conversation Id."); + } + return clientEndPoint; + } + ; + function _lookupMethodObject(serviceEndPoint, messageObject) { + var methodOrEventMethodObject = serviceEndPoint._methodObjectList[messageObject._actionName]; + if (!methodOrEventMethodObject) { + OSF.Utility.xdmDebugLog("The specified method is not registered on service endpoint:" + messageObject._actionName); + throw OSF.Utility.createArgumentException("messageObject"); + } + var methodObject = null; + if (messageObject._actionType === 0) { + methodObject = methodOrEventMethodObject; + } + else if (messageObject._actionType === 1) { + methodObject = methodOrEventMethodObject.getRegisterMethodObject(); + } + else { + methodObject = methodOrEventMethodObject.getUnregisterMethodObject(); + } + return methodObject; + } + ; + function _enqueInvoker(invoker) { + _invokerQueue.push(invoker); + } + ; + function _dequeInvoker() { + if (_messageProcessingTimer !== null) { + if (!_blockingFlag) { + if (_invokerQueue.length > 0) { + var invoker = _invokerQueue.shift(); + _executeCommand(invoker); + } + else { + clearInterval(_messageProcessingTimer); + _messageProcessingTimer = null; + } + } + } + else { + OSF.Utility.xdmDebugLog("channel is not ready."); + } + } + ; + function _executeCommand(invoker) { + _blockingFlag = invoker.getInvokeBlockingFlag(); + invoker.invoke(); + _lastMessageProcessTime = (new Date()).getTime(); + } + ; + function _checkMethodTimeout() { + if (_methodTimeoutTimer) { + var clientEndPoint; + var methodCallsNotTimedout = 0; + var now = new Date(); + var timeoutValue; + for (var conversationId in _clientEndPoints) { + clientEndPoint = _clientEndPoints[conversationId]; + for (var correlationId in clientEndPoint._callbackList) { + var callbackEntry = clientEndPoint._callbackList[correlationId]; + timeoutValue = callbackEntry.timeout ? callbackEntry.timeout : _methodTimeout; + if (timeoutValue >= 0 && Math.abs(now.getTime() - callbackEntry.createdOn) >= timeoutValue) { + try { + if (callbackEntry.callback) { + callbackEntry.callback(-6, null); + } + } + finally { + delete clientEndPoint._callbackList[correlationId]; + } + } + else { + methodCallsNotTimedout++; + } + ; + } + } + if (methodCallsNotTimedout === 0) { + clearInterval(_methodTimeoutTimer); + _methodTimeoutTimer = null; + } + } + else { + OSF.Utility.xdmDebugLog("channel is not ready."); + } + } + ; + function _postCallbackHandler() { + _blockingFlag = false; + } + ; + function _registerListener(listener) { + if (window.addEventListener) { + window.addEventListener("message", listener, false); + } + else if ((navigator.userAgent.indexOf("MSIE") > -1) && window.attachEvent) { + window.attachEvent("onmessage", listener); + } + else { + OSF.Utility.xdmDebugLog("Browser doesn't support the required API."); + throw OSF.Utility.createArgumentException("Browser"); + } + } + ; + function _checkOrigin(url, origin) { + var res = false; + if (!url || !origin || url === "null" || origin === "null" || !url.length || !origin.length) { + return res; + } + var url_parser, org_parser; + url_parser = document.createElement('a'); + org_parser = document.createElement('a'); + url_parser.href = url; + org_parser.href = origin; + res = _urlCompare(url_parser, org_parser); + return res; + } + function _checkOriginWithAppDomains(allowed_domains, origin) { + var res = false; + if (!origin || origin === "null" || !origin.length || !(allowed_domains) || !(allowed_domains instanceof Array) || !allowed_domains.length) { + return res; + } + var org_parser = document.createElement('a'); + var app_domain_parser = document.createElement('a'); + org_parser.href = origin; + for (var i = 0; i < allowed_domains.length && !res; i++) { + if (allowed_domains[i].indexOf("://") !== -1) { + app_domain_parser.href = allowed_domains[i]; + res = _urlCompare(org_parser, app_domain_parser); + } + } + return res; + } + function _isHostNameValidWacDomain(hostName) { + if (!hostName || hostName === "null") { + return false; + } + var regexHostNameStringArray = new Array("^outlook\\.office\\.com$", "^outlook-sdf\\.office\\.com$", "^outlook\\.office\\.com$", "^outlook-sdf\\.office\\.com$", "^outlook\\.live\\.com$", "^outlook-sdf\\.live\\.com$", "^consumer\\.live-int\\.com$", "^outlook-tdf\\.live\\.com$", "^sdfpilot\\.live\\.com$", "^outlook\\.office\\.de$", "^outlook\\.office365\\.us$", "^outlook\\.office365\\.com$", "^partner\\.outlook\\.cn$", "^exchangelabs\\.live-int\\.com$", "^office-int\\.com$", "^officeapps\\.live-int\\.com$", "^.*\\.dod\\.online\\.office365\\.us$", "^.*\\.gov\\.online\\.office365\\.us$", "^.*\\.officeapps\\.live\\.com$", "^.*\\.officeapps\\.live-int\\.com$", "^.*\\.officeapps-df\\.live\\.com$", "^.*\\.online\\.office\\.de$", "^.*\\.partner\\.officewebapps\\.cn$", "^.*\\.office\\.net$", "^" + document.domain.replace(new RegExp("\\.", "g"), "\\.") + "$"); + var regexHostName = new RegExp(regexHostNameStringArray.join("|")); + return regexHostName.test(hostName); + } + function _isTargetSubdomainOfSourceLocation(sourceLocation, messageOrigin) { + if (!sourceLocation || !messageOrigin || sourceLocation === "null" || messageOrigin === "null") { + return false; + } + var sourceLocationParser = document.createElement('a'); + sourceLocationParser.href = sourceLocation; + var messageOriginParser = document.createElement('a'); + messageOriginParser.href = messageOrigin; + var isSameProtocol = sourceLocationParser.protocol === messageOriginParser.protocol; + var isSamePort = sourceLocationParser.port === messageOriginParser.port; + var originHostName = messageOriginParser.hostname; + var sourceLocationHostName = sourceLocationParser.hostname; + var isSameDomain = originHostName === sourceLocationHostName; + var isSubDomain = false; + if (!isSameDomain && originHostName.length > sourceLocationHostName.length + 1) { + isSubDomain = originHostName.slice(-(sourceLocationHostName.length + 1)) === '.' + sourceLocationHostName; + } + var isSameDomainOrSubdomain = isSameDomain || isSubDomain; + return isSamePort && isSameProtocol && isSameDomainOrSubdomain; + } + function _urlCompare(url_parser1, url_parser2) { + return ((url_parser1.hostname == url_parser2.hostname) && + (url_parser1.protocol == url_parser2.protocol) && + (url_parser1.port == url_parser2.port)); + } + function _receive(e) { + if (e.data != '') { + var messageObject; + var serializerVersion = 1; + var serializedMessage = e.data; + try { + messageObject = XdmMessagePackager.unenvelope(serializedMessage, 1); + serializerVersion = messageObject._serializerVersion != null ? messageObject._serializerVersion : serializerVersion; + } + catch (ex) { + return; + } + OSF.Utility.xdmDebugLog(serializedMessage); + if (messageObject._messageType === 0) { + var requesterUrl = (e.origin == null || e.origin === "null") ? messageObject._origin : e.origin; + try { + var serviceEndPoint = _lookupServiceEndPoint(messageObject._conversationId); + OSF.Utility.xdmDebugLog("_receive: request, origin=" + requesterUrl + " sourceURL:" + serviceEndPoint._conversations[messageObject._conversationId]); + var conversation = serviceEndPoint._conversations[messageObject._conversationId]; + serializerVersion = conversation.serializerVersion != null ? conversation.serializerVersion : serializerVersion; + OSF.Utility.xdmDebugLog("_receive: request, origin=" + requesterUrl + " sourceURL:" + conversation.url); + var allowedDomains = [conversation.url].concat(serviceEndPoint._appDomains[messageObject._conversationId]); + if (!_checkOriginWithAppDomains(allowedDomains, e.origin)) { + if (!OfficeExt.appSpecificCheckOrigin(allowedDomains, e, messageObject._origin, _checkOriginWithAppDomains)) { + var isOriginSubdomain = _isTargetSubdomainOfSourceLocation(conversation.url, e.origin); + if (!isOriginSubdomain) { + throw "Failed origin check"; + } + } + } + var policyManager = serviceEndPoint.getPolicyManager(); + if (policyManager && !policyManager.checkPermission(messageObject._conversationId, messageObject._actionName, messageObject._data)) { + throw "Access Denied"; + } + var methodObject = _lookupMethodObject(serviceEndPoint, messageObject); + var invokeCompleteCallback = new XdmInvokeCompleteCallback(e.source, requesterUrl, messageObject._actionName, messageObject._conversationId, messageObject._correlationId, _postCallbackHandler, serializerVersion); + var invoker = new XdmInvoker(methodObject, messageObject._data, invokeCompleteCallback, serviceEndPoint._eventHandlerProxyList, messageObject._conversationId, messageObject._actionName, serializerVersion); + var shouldEnque = true; + if (_messageProcessingTimer == null) { + if ((_lastMessageProcessTime == null || (new Date()).getTime() - _lastMessageProcessTime > _processInterval) && !_blockingFlag) { + _executeCommand(invoker); + shouldEnque = false; + } + else { + _messageProcessingTimer = setInterval(_dequeInvoker, _processInterval); + } + } + if (shouldEnque) { + _enqueInvoker(invoker); + } + } + catch (ex) { + if (serviceEndPoint && serviceEndPoint._onHandleRequestError) { + serviceEndPoint._onHandleRequestError(messageObject, ex); + } + var errorCode = -2; + if (ex == "Access Denied") { + errorCode = -5; + } + var callResponse = new XdmResponse(messageObject._actionName, messageObject._conversationId, messageObject._correlationId, errorCode, 0, ex); + var envelopedResult = XdmMessagePackager.envelope(callResponse, serializerVersion); + var canPostMessage = false; + try { + canPostMessage = !!(e.source && e.source.postMessage); + } + catch (ex) { + } + var isOriginValid = false; + if (window.location.href && e.origin && e.origin !== "null" && _isTargetSubdomainOfSourceLocation(window.location.href, e.origin)) { + isOriginValid = true; + } + else { + if (e.origin && e.origin !== "null") { + var parser = document.createElement("a"); + parser.href = e.origin; + isOriginValid = _isHostNameValidWacDomain(parser.hostname); + } + } + if (canPostMessage && isOriginValid) { + e.source.postMessage(envelopedResult, requesterUrl); + } + } + } + else if (messageObject._messageType === 1) { + var clientEndPoint = _lookupClientEndPoint(messageObject._conversationId); + if (!clientEndPoint) { + return; + } + clientEndPoint._serializerVersion = serializerVersion; + OSF.Utility.xdmDebugLog("_receive: response, origin=" + e.origin + " targetURL:" + clientEndPoint._targetUrl); + if (!_checkOrigin(clientEndPoint._targetUrl, e.origin)) { + throw "Failed orgin check"; + } + if (messageObject._responseType === 0) { + var callbackEntry = clientEndPoint._callbackList[messageObject._correlationId]; + if (callbackEntry) { + try { + if (callbackEntry.callback) + callbackEntry.callback(messageObject._errorCode, messageObject._data); + } + finally { + delete clientEndPoint._callbackList[messageObject._correlationId]; + } + } + } + else { + var eventhandler = clientEndPoint._eventHandlerList[messageObject._actionName]; + if (eventhandler !== undefined && eventhandler !== null) { + eventhandler(messageObject._data); + } + } + } + else { + return; + } + } + } + ; + function _initialize() { + if (!_initialized) { + _registerListener(_receive); + _initialized = true; + } + } + ; + function connect(conversationId, targetWindow, targetUrl, serializerVersion) { + var clientEndPoint = _clientEndPoints[conversationId]; + if (!clientEndPoint) { + _initialize(); + clientEndPoint = new XdmClientEndPoint(conversationId, targetWindow, targetUrl, serializerVersion); + _clientEndPoints[conversationId] = clientEndPoint; + } + return clientEndPoint; + } + XdmCommunicationManager.connect = connect; + function getClientEndPoint(conversationId) { + return _clientEndPoints[conversationId]; + } + XdmCommunicationManager.getClientEndPoint = getClientEndPoint; + function createServiceEndPoint(serviceEndPointId) { + _initialize(); + var serviceEndPoint = new XdmServiceEndPoint(serviceEndPointId); + _serviceEndPoints[serviceEndPointId] = serviceEndPoint; + return serviceEndPoint; + } + XdmCommunicationManager.createServiceEndPoint = createServiceEndPoint; + function getServiceEndPoint(serviceEndPointId) { + return _serviceEndPoints[serviceEndPointId]; + } + XdmCommunicationManager.getServiceEndPoint = getServiceEndPoint; + function deleteClientEndPoint(conversationId) { + delete _clientEndPoints[conversationId]; + } + XdmCommunicationManager.deleteClientEndPoint = deleteClientEndPoint; + function deleteServiceEndPoint(serviceEndPointId) { + delete _serviceEndPoints[serviceEndPointId]; + } + XdmCommunicationManager.deleteServiceEndPoint = deleteServiceEndPoint; + function checkUrlWithAppDomains(appDomains, origin) { + return _checkOriginWithAppDomains(appDomains, origin); + } + XdmCommunicationManager.checkUrlWithAppDomains = checkUrlWithAppDomains; + ; + function isTargetSubdomainOfSourceLocation(sourceLocation, messageOrigin) { + return _isTargetSubdomainOfSourceLocation(sourceLocation, messageOrigin); + } + XdmCommunicationManager.isTargetSubdomainOfSourceLocation = isTargetSubdomainOfSourceLocation; + function _setMethodTimeout(methodTimeout) { + _methodTimeout = (methodTimeout <= 0) ? _methodTimeoutDefault : methodTimeout; + } + XdmCommunicationManager._setMethodTimeout = _setMethodTimeout; + function _startMethodTimeoutTimer() { + } + XdmCommunicationManager._startMethodTimeoutTimer = _startMethodTimeoutTimer; + function isHostNameValidWacDomain(hostName) { + return _isHostNameValidWacDomain(hostName); + } + XdmCommunicationManager.isHostNameValidWacDomain = isHostNameValidWacDomain; + })(XdmCommunicationManager = OSF.XdmCommunicationManager || (OSF.XdmCommunicationManager = {})); + var XdmMessage = (function () { + function XdmMessage(messageType, actionName, conversationId, correlationId, data) { + this._messageType = messageType; + this._actionName = actionName; + this._conversationId = conversationId; + this._correlationId = correlationId; + this._origin = window.location.origin; + if (typeof data === "undefined") { + this._data = null; + } + else { + this._data = data; + } + } + XdmMessage.prototype.getActionName = function () { + return this._actionName; + }; + XdmMessage.prototype.getConversationId = function () { + return this._conversationId; + }; + XdmMessage.prototype.getCorrelationId = function () { + return this._correlationId; + }; + XdmMessage.prototype.getOrigin = function () { + return this._origin; + }; + XdmMessage.prototype.getData = function () { + return this._data; + }; + XdmMessage.prototype.getMessageType = function () { + return this._messageType; + }; + return XdmMessage; + }()); + var XdmRequest = (function (_super) { + __extends(XdmRequest, _super); + function XdmRequest(actionName, actionType, conversationId, correlationId, data) { + var _this = _super.call(this, 0, actionName, conversationId, correlationId, data) || this; + _this._actionType = actionType; + return _this; + } + ; + XdmRequest.prototype.getActionType = function () { + return this._actionType; + }; + return XdmRequest; + }(XdmMessage)); + var XdmResponse = (function (_super) { + __extends(XdmResponse, _super); + function XdmResponse(actionName, conversationId, correlationId, errorCode, responseType, data) { + var _this = _super.call(this, 1, actionName, conversationId, correlationId, data) || this; + _this._errorCode = errorCode; + _this._responseType = responseType; + return _this; + } + XdmResponse.prototype.getErrorCode = function () { + return this._errorCode; + }; + XdmResponse.prototype.getResponseType = function () { + return this._responseType; + }; + return XdmResponse; + }(XdmMessage)); + var XdmMessagePackager = (function () { + function XdmMessagePackager() { + } + XdmMessagePackager.envelope = function (messageObject, serializerVersion) { + if (typeof (messageObject) === "object") { + messageObject._serializerVersion = 1; + } + return JSON.stringify(messageObject); + }; + XdmMessagePackager.unenvelope = function (messageObject, serializerVersion) { + return JSON.parse(messageObject); + }; + return XdmMessagePackager; + }()); + var XdmResponseSender = (function () { + function XdmResponseSender(requesterWindow, requesterUrl, actionName, conversationId, correlationId, responseType, serializerVersion) { + var _this = this; + this._invokeResultCode = 0; + this._requesterWindow = requesterWindow; + this._requesterUrl = requesterUrl; + this._actionName = actionName; + this._conversationId = conversationId; + this._correlationId = correlationId; + this._invokeResultCode = 0; + this._responseType = responseType; + this._serializerVersion = serializerVersion; + this._send = function (result) { + try { + var response = new XdmResponse(_this._actionName, _this._conversationId, _this._correlationId, _this._invokeResultCode, _this._responseType, result); + var envelopedResult = XdmMessagePackager.envelope(response, _this._serializerVersion); + _this._requesterWindow.postMessage(envelopedResult, _this._requesterUrl); + OSF.Utility.xdmDebugLog("_send: requestUrl=" + _this._requesterUrl + " _actionName:" + _this._actionName); + } + catch (ex) { + OSF.Utility.xdmDebugLog("ResponseSender._send error:" + ex.message); + } + }; + } + XdmResponseSender.prototype.getRequesterWindow = function () { + return this._requesterWindow; + }; + XdmResponseSender.prototype.getRequesterUrl = function () { + return this._requesterUrl; + }; + XdmResponseSender.prototype.getActionName = function () { + return this._actionName; + }; + XdmResponseSender.prototype.getConversationId = function () { + return this._conversationId; + }; + XdmResponseSender.prototype.getCorrelationId = function () { + return this._correlationId; + }; + XdmResponseSender.prototype.getSend = function () { + return this._send; + }; + XdmResponseSender.prototype.setResultCode = function (resultCode) { + this._invokeResultCode = resultCode; + }; + return XdmResponseSender; + }()); + var XdmInvokeCompleteCallback = (function (_super) { + __extends(XdmInvokeCompleteCallback, _super); + function XdmInvokeCompleteCallback(requesterWindow, requesterUrl, actionName, conversationId, correlationId, postCallbackHandler, serializerVersion) { + var _this = _super.call(this, requesterWindow, requesterUrl, actionName, conversationId, correlationId, 0, serializerVersion) || this; + _this._postCallbackHandler = postCallbackHandler; + _this._send = function (result, responseCode) { + if (responseCode != undefined) { + _this._invokeResultCode = responseCode; + } + try { + var response = new XdmResponse(_this._actionName, _this._conversationId, _this._correlationId, _this._invokeResultCode, _this._responseType, result); + var envelopedResult = XdmMessagePackager.envelope(response, _this._serializerVersion); + _this._requesterWindow.postMessage(envelopedResult, _this._requesterUrl); + _this._postCallbackHandler(); + } + catch (ex) { + OSF.Utility.xdmDebugLog("InvokeCompleteCallback._send error:" + ex.message); + } + }; + return _this; + } + return XdmInvokeCompleteCallback; + }(XdmResponseSender)); + var XdmInvoker = (function () { + function XdmInvoker(methodObject, paramValue, invokeCompleteCallback, eventHandlerProxyList, conversationId, eventName, serializerVersion) { + this._callerId = ''; + this._methodObject = methodObject; + this._param = paramValue; + this._invokeCompleteCallback = invokeCompleteCallback; + this._eventHandlerProxyList = eventHandlerProxyList; + this._conversationId = conversationId; + this._eventName = eventName; + this._serializerVersion = serializerVersion; + } + XdmInvoker.prototype.invoke = function () { + try { + var result; + switch (this._methodObject.getInvokeType()) { + case 0: + this._methodObject.getMethod()(this._param, this._invokeCompleteCallback.getSend()); + break; + case 1: + result = this._methodObject.getMethod()(this._param); + this._invokeCompleteCallback.getSend()(result); + break; + case 4: + var eventHandlerProxy = this._createEventHandlerProxyObject(this._invokeCompleteCallback); + result = this._methodObject.getMethod()(eventHandlerProxy.getSend(), this._param); + this._eventHandlerProxyList[this._conversationId + this._eventName] = eventHandlerProxy.getSend(); + this._invokeCompleteCallback.getSend()(result); + break; + case 5: + var eventHandler = this._eventHandlerProxyList[this._conversationId + this._eventName]; + result = this._methodObject.getMethod()(eventHandler, this._param); + delete this._eventHandlerProxyList[this._conversationId + this._eventName]; + this._invokeCompleteCallback.getSend()(result); + break; + case 2: + var eventHandlerProxyAsync = this._createEventHandlerProxyObject(this._invokeCompleteCallback); + this._methodObject.getMethod()(eventHandlerProxyAsync.getSend(), this._invokeCompleteCallback.getSend(), this._param); + this._eventHandlerProxyList[this._callerId + this._eventName] = eventHandlerProxyAsync.getSend(); + break; + case 3: + var eventHandlerAsync = this._eventHandlerProxyList[this._callerId + this._eventName]; + this._methodObject.getMethod()(eventHandlerAsync, this._invokeCompleteCallback.getSend(), this._param); + delete this._eventHandlerProxyList[this._callerId + this._eventName]; + break; + default: + break; + } + } + catch (ex) { + this._invokeCompleteCallback.setResultCode(-3); + this._invokeCompleteCallback.getSend()(ex); + } + }; + XdmInvoker.prototype.getInvokeBlockingFlag = function () { + return this._methodObject.getBlockingFlag(); + }; + XdmInvoker.prototype._createEventHandlerProxyObject = function (invokeCompleteObject) { + return new XdmResponseSender(invokeCompleteObject.getRequesterWindow(), invokeCompleteObject.getRequesterUrl(), invokeCompleteObject.getActionName(), invokeCompleteObject.getConversationId(), invokeCompleteObject.getCorrelationId(), 1, this._serializerVersion); + }; + return XdmInvoker; + }()); +})(OSF || (OSF = {})); +var OSFPerfUtil; +(function (OSFPerfUtil) { + function prepareDataFieldsForOtel(resource, name) { + name = name + "_Resource"; + if (oteljs !== undefined) { + return [ + oteljs.makeStringDataField(name + "_name", resource.name), + oteljs.makeDoubleDataField(name + "_responseEnd", resource.responseEnd), + oteljs.makeDoubleDataField(name + "_responseStart", resource.responseStart), + oteljs.makeDoubleDataField(name + "_startTime", resource.startTime), + oteljs.makeDoubleDataField(name + "_transferSize", resource.transferSize) + ]; + } + return []; + } + function sendPerformanceTelemetry() { + if (OSF.AppTelemetry.enableTelemetry) { + var hostPerfResource_1; + var officePerfResource_1; + var hostSpecificFileName_1 = OSF.LoadScriptHelper.getHostBundleJsName(); + var resources = performance.getEntriesByType("resource"); + resources.forEach(function (resource) { + if (OSF.Utility.stringEndsWith(resource.name, hostSpecificFileName_1)) { + hostPerfResource_1 = resource; + } + else if (OSF.Utility.stringEndsWith(resource.name, OSF.ConstantNames.OfficeDebugJS) || + OSF.Utility.stringEndsWith(resource.name, OSF.ConstantNames.OfficeJS)) { + officePerfResource_1 = resource; + } + }); + OTel.OTelLogger.onTelemetryLoaded(function () { + var dataFields = []; + if (hostPerfResource_1) { + dataFields = dataFields.concat(prepareDataFieldsForOtel(hostPerfResource_1, "HostJs")); + } + if (officePerfResource_1) { + dataFields = dataFields.concat(prepareDataFieldsForOtel(officePerfResource_1, "OfficeJs")); + } + dataFields = dataFields.concat([ + oteljs.makeDoubleDataField("officeExecuteStartDate", OSFPerformance.officeExecuteStartDate), + oteljs.makeDoubleDataField("officeExecuteStart", OSFPerformance.officeExecuteStart), + oteljs.makeDoubleDataField("officeExecuteEnd", OSFPerformance.officeExecuteEnd), + oteljs.makeDoubleDataField("hostInitializationStart", OSFPerformance.hostInitializationStart), + oteljs.makeDoubleDataField("hostInitializationEnd", OSFPerformance.hostInitializationEnd), + oteljs.makeDoubleDataField("getAppContextStart", OSFPerformance.getAppContextStart), + oteljs.makeDoubleDataField("getAppContextEnd", OSFPerformance.getAppContextEnd), + oteljs.makeDoubleDataField("getAppContextXdmStart", OSFPerformance.getAppContextXdmStart), + oteljs.makeDoubleDataField("getAppContextXdmEnd", OSFPerformance.getAppContextXdmEnd), + oteljs.makeDoubleDataField("createOMEnd", OSFPerformance.createOMEnd), + oteljs.makeDoubleDataField("officeOnReady", OSFPerformance.officeOnReady) + ]); + Microsoft.Office.WebExtension.sendTelemetryEvent({ + eventName: "Office.Extensibility.OfficeJs.JSPerformanceTelemetryV06", + dataFields: dataFields, + eventFlags: { + dataCategories: oteljs.DataCategories.ProductServiceUsage, + diagnosticLevel: oteljs.DiagnosticLevel.NecessaryServiceDataEvent + } + }); + }); + } + } + OSFPerfUtil.sendPerformanceTelemetry = sendPerformanceTelemetry; +})(OSFPerfUtil || (OSFPerfUtil = {})); +var OSF; +(function (OSF) { + OSF.Flights = []; + var TestFlightStart = 1000; + var TestFlightEnd = 1009; + var OUtil; + (function (OUtil) { + var _uniqueId = -1; + var _xdmInfoKey = '&_xdm_Info='; + var _serializerVersionKey = '&_serializer_version='; + var _flightsKey = '&_flights='; + var _xdmSessionKeyPrefix = '_xdm_'; + var _serializerVersionKeyPrefix = '_serializer_version='; + var _flightsKeyPrefix = '_flights='; + var _fragmentSeparator = '#'; + var _fragmentInfoDelimiter = '&'; + var _loadedScripts = {}; + var _defaultScriptLoadingTimeout = 30000; + var _safeSessionStorage; + var _safeLocalStorage; + var Guid; + (function (Guid) { + var hexCode = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "a", "b", "c", "d", "e", "f"]; + function generateNewGuid() { + var result = ""; + var tick = (new Date()).getTime(); + var index = 0; + for (; index < 32 && tick > 0; index++) { + if (index == 8 || index == 12 || index == 16 || index == 20) { + result += "-"; + } + result += hexCode[tick % 16]; + tick = Math.floor(tick / 16); + } + for (; index < 32; index++) { + if (index == 8 || index == 12 || index == 16 || index == 20) { + result += "-"; + } + result += hexCode[Math.floor(Math.random() * 16)]; + } + return result; + } + Guid.generateNewGuid = generateNewGuid; + })(Guid = OUtil.Guid || (OUtil.Guid = {})); + function isArray(obj) { + return Object.prototype.toString.apply(obj) === "[object Array]"; + } + OUtil.isArray = isArray; + function isFunction(obj) { + return Object.prototype.toString.apply(obj) === "[object Function]"; + } + OUtil.isFunction = isFunction; + function isDate(obj) { + return Object.prototype.toString.apply(obj) === "[object Date]"; + } + OUtil.isDate = isDate; + function isEdge() { + return typeof (window) !== "undefined" && typeof (window.navigator) !== "undefined" && window.navigator.userAgent.indexOf("Edge") > 0; + } + function isIE() { + return typeof (window) !== "undefined" && typeof (window.navigator) !== "undefined" && window.navigator.userAgent.indexOf("Trident") > 0; + } + function startsWith(originalString, patternToCheck) { + return originalString.substr(0, patternToCheck.length) === patternToCheck; + } + function containsPort(url, protocol, hostname, portNumber) { + return startsWith(url, protocol + "//" + hostname + ":" + portNumber) || startsWith(url, hostname + ":" + portNumber); + } + function addEventListener(element, eventName, listener) { + if (element.addEventListener) { + element.addEventListener(eventName, listener, false); + } + else if (element.attachEvent) { + element.attachEvent("on" + eventName, listener); + } + else { + throw new Error("Cannot attach event"); + } + } + OUtil.addEventListener = addEventListener; + function removeEventListener(element, eventName, listener) { + if (element.removeEventListener) { + element.removeEventListener(eventName, listener, false); + } + else if (element.detachEvent) { + element.detachEvent("on" + eventName, listener); + } + else { + throw new Error("Cannot remove event"); + } + } + OUtil.removeEventListener = removeEventListener; + var DateJSONPrefix = "Date("; + var DataJSONSuffix = ")"; + function serializeSettings(settingsCollection) { + var ret = {}; + for (var key in settingsCollection) { + var value = settingsCollection[key]; + try { + value = JSON.stringify(value, function dateReplacer(k, v) { + return OSF.OUtil.isDate(this[k]) ? DateJSONPrefix + this[k].getTime() + DataJSONSuffix : v; + }); + ret[key] = value; + } + catch (ex) { + } + } + return ret; + } + OUtil.serializeSettings = serializeSettings; + function deserializeSettings(serializedSettings) { + var ret = {}; + serializedSettings = serializedSettings || {}; + for (var key in serializedSettings) { + var value = serializedSettings[key]; + try { + value = JSON.parse(value, function dateReviver(k, v) { + var d; + if (typeof v === 'string' && v && v.length > 6 && v.slice(0, 5) === DateJSONPrefix && v.slice(-1) === DataJSONSuffix) { + d = new Date(parseInt(v.slice(5, -1))); + if (d) { + return d; + } + } + return v; + }); + ret[key] = value; + } + catch (ex) { + } + } + return ret; + } + OUtil.deserializeSettings = deserializeSettings; + function loadScript(url, callback, timeoutInMs) { + if (url && callback) { + var doc = window.document; + var _loadedScriptEntry = _loadedScripts[url]; + if (!_loadedScriptEntry) { + var script = doc.createElement("script"); + script.type = "text/javascript"; + _loadedScriptEntry = { loaded: false, pendingCallbacks: [callback], timer: null }; + _loadedScripts[url] = _loadedScriptEntry; + var onLoadCallback = function OSF_OUtil_loadScript$onLoadCallback() { + if (_loadedScriptEntry.timer != null) { + clearTimeout(_loadedScriptEntry.timer); + delete _loadedScriptEntry.timer; + } + _loadedScriptEntry.loaded = true; + var pendingCallbackCount = _loadedScriptEntry.pendingCallbacks.length; + for (var i = 0; i < pendingCallbackCount; i++) { + var currentCallback = _loadedScriptEntry.pendingCallbacks.shift(); + currentCallback(true); + } + }; + var onLoadError = function OSF_OUtil_loadScript$onLoadError() { + delete _loadedScripts[url]; + if (_loadedScriptEntry.timer != null) { + clearTimeout(_loadedScriptEntry.timer); + delete _loadedScriptEntry.timer; + } + var pendingCallbackCount = _loadedScriptEntry.pendingCallbacks.length; + for (var i = 0; i < pendingCallbackCount; i++) { + var currentCallback = _loadedScriptEntry.pendingCallbacks.shift(); + currentCallback(false); + } + }; + if (script.readyState) { + script.onreadystatechange = function () { + if (script.readyState == "loaded" || script.readyState == "complete") { + script.onreadystatechange = null; + onLoadCallback(); + } + }; + } + else { + script.onload = onLoadCallback; + } + script.onerror = onLoadError; + timeoutInMs = timeoutInMs || _defaultScriptLoadingTimeout; + _loadedScriptEntry.timer = setTimeout(onLoadError, timeoutInMs); + script.setAttribute("crossOrigin", "anonymous"); + script.src = url; + doc.getElementsByTagName("head")[0].appendChild(script); + } + else if (_loadedScriptEntry.loaded) { + callback(true); + } + else { + _loadedScriptEntry.pendingCallbacks.push(callback); + } + } + } + OUtil.loadScript = loadScript; + function getSessionStorage() { + if (!_safeSessionStorage) { + try { + var sessionStorage = window.sessionStorage; + } + catch (ex) { + sessionStorage = null; + } + _safeSessionStorage = new OSF.SafeStorage(sessionStorage); + } + return _safeSessionStorage; + } + OUtil.getSessionStorage = getSessionStorage; + function getLocalStorage() { + if (!_safeLocalStorage) { + try { + var localStorage = window.localStorage; + } + catch (ex) { + localStorage = null; + } + _safeLocalStorage = new OSF.SafeStorage(localStorage); + } + return _safeLocalStorage; + } + OUtil.getLocalStorage = getLocalStorage; + function convertIntToCssHexColor(val) { + var hex = "#" + (Number(val) + 0x1000000).toString(16).slice(-6); + return hex; + } + OUtil.convertIntToCssHexColor = convertIntToCssHexColor; + function parseAppContextFromWindowName(skipSessionStorage, windowName) { + return OUtil.parseInfoFromWindowName(skipSessionStorage, windowName, "appContext"); + } + OUtil.parseAppContextFromWindowName = parseAppContextFromWindowName; + function parseHostInfoFromWindowName(skipSessionStorage, windowName) { + return OSF.OUtil.parseInfoFromWindowName(skipSessionStorage, windowName, "hostInfo"); + } + OUtil.parseHostInfoFromWindowName = parseHostInfoFromWindowName; + function parseXdmInfo(skipSessionStorage) { + var xdmInfoValue = OUtil.parseXdmInfoWithGivenFragment(skipSessionStorage, window.location.hash); + if (!xdmInfoValue) { + xdmInfoValue = OUtil.parseXdmInfoFromWindowName(skipSessionStorage, window.name); + } + return xdmInfoValue; + } + OUtil.parseXdmInfo = parseXdmInfo; + function parseXdmInfoFromWindowName(skipSessionStorage, windowName) { + return OSF.OUtil.parseInfoFromWindowName(skipSessionStorage, windowName, "xdmInfo"); + } + OUtil.parseXdmInfoFromWindowName = parseXdmInfoFromWindowName; + function parseXdmInfoWithGivenFragment(skipSessionStorage, fragment) { + return OSF.OUtil.parseInfoWithGivenFragment(_xdmInfoKey, _xdmSessionKeyPrefix, false, skipSessionStorage, fragment); + } + OUtil.parseXdmInfoWithGivenFragment = parseXdmInfoWithGivenFragment; + function parseSerializerVersion(skipSessionStorage) { + var serializerVersion = OSF.OUtil.parseSerializerVersionWithGivenFragment(skipSessionStorage, window.location.hash); + if (isNaN(serializerVersion)) { + serializerVersion = OSF.OUtil.parseSerializerVersionFromWindowName(skipSessionStorage, window.name); + } + return serializerVersion; + } + OUtil.parseSerializerVersion = parseSerializerVersion; + function parseSerializerVersionFromWindowName(skipSessionStorage, windowName) { + return parseInt(OSF.OUtil.parseInfoFromWindowName(skipSessionStorage, windowName, "serializerVersion")); + } + OUtil.parseSerializerVersionFromWindowName = parseSerializerVersionFromWindowName; + function parseSerializerVersionWithGivenFragment(skipSessionStorage, fragment) { + return parseInt(OSF.OUtil.parseInfoWithGivenFragment(_serializerVersionKey, _serializerVersionKeyPrefix, true, skipSessionStorage, fragment)); + } + OUtil.parseSerializerVersionWithGivenFragment = parseSerializerVersionWithGivenFragment; + function parseFlights(skipSessionStorage) { + var flights = parseFlightsWithGivenFragment(skipSessionStorage, window.location.hash); + if (flights.length == 0) { + flights = parseFlightsFromWindowName(skipSessionStorage, window.name); + } + return flights; + } + OUtil.parseFlights = parseFlights; + function checkFlight(flight) { + return OSF.Flights && OSF.Flights.indexOf(flight) >= 0; + } + OUtil.checkFlight = checkFlight; + function parseFlightsFromWindowName(skipSessionStorage, windowName) { + return parseArrayWithDefault(parseInfoFromWindowName(skipSessionStorage, windowName, "flights")); + } + function parseFlightsWithGivenFragment(skipSessionStorage, fragment) { + return parseArrayWithDefault(parseInfoWithGivenFragment(_flightsKey, _flightsKeyPrefix, true, skipSessionStorage, fragment)); + } + function parseArrayWithDefault(jsonString) { + var array = []; + try { + array = JSON.parse(jsonString); + } + catch (ex) { } + if (!Array.isArray(array)) { + array = []; + } + return array; + } + function parseInfoFromWindowName(skipSessionStorage, windowName, infoKey) { + try { + var windowNameObj = JSON.parse(windowName); + var infoValue = windowNameObj != null ? windowNameObj[infoKey] : null; + var osfSessionStorage = OUtil.getSessionStorage(); + if (!skipSessionStorage && osfSessionStorage && windowNameObj != null) { + var sessionKey = windowNameObj["baseFrameName"] + infoKey; + if (infoValue) { + osfSessionStorage.setItem(sessionKey, infoValue); + } + else { + infoValue = osfSessionStorage.getItem(sessionKey); + } + } + return infoValue; + } + catch (Exception) { + return null; + } + } + OUtil.parseInfoFromWindowName = parseInfoFromWindowName; + function parseInfoWithGivenFragment(infoKey, infoKeyPrefix, decodeInfo, skipSessionStorage, fragment) { + var fragmentParts = fragment.split(infoKey); + var infoValue = fragmentParts.length > 1 ? fragmentParts[fragmentParts.length - 1] : null; + if (decodeInfo && infoValue != null) { + if (infoValue.indexOf(_fragmentInfoDelimiter) >= 0) { + infoValue = infoValue.split(_fragmentInfoDelimiter)[0]; + } + infoValue = decodeURIComponent(infoValue); + } + var osfSessionStorage = OUtil.getSessionStorage(); + if (!skipSessionStorage && osfSessionStorage) { + var sessionKeyStart = window.name.indexOf(infoKeyPrefix); + if (sessionKeyStart > -1) { + var sessionKeyEnd = window.name.indexOf(";", sessionKeyStart); + if (sessionKeyEnd == -1) { + sessionKeyEnd = window.name.length; + } + var sessionKey = window.name.substring(sessionKeyStart, sessionKeyEnd); + if (infoValue) { + osfSessionStorage.setItem(sessionKey, infoValue); + } + else { + infoValue = osfSessionStorage.getItem(sessionKey); + } + } + } + return infoValue; + } + OUtil.parseInfoWithGivenFragment = parseInfoWithGivenFragment; + function getConversationId() { + var searchString = window.location.search; + var conversationId = null; + if (searchString) { + var index = searchString.indexOf("&"); + conversationId = index > 0 ? searchString.substring(1, index) : searchString.substr(1); + if (conversationId && conversationId.charAt(conversationId.length - 1) === '=') { + conversationId = conversationId.substring(0, conversationId.length - 1); + if (conversationId) { + conversationId = decodeURIComponent(conversationId); + } + } + } + return conversationId; + } + OUtil.getConversationId = getConversationId; + function getInfoItems(strInfo) { + var items = strInfo.split('$'); + if (typeof items[1] == "undefined") { + items = strInfo.split("|"); + } + if (typeof items[1] == "undefined") { + items = strInfo.split("%7C"); + } + return items; + } + OUtil.getInfoItems = getInfoItems; + function getXdmFieldValue(xdmFieldName, skipSessionStorage) { + var fieldValue = ''; + var xdmInfoValue = OSF.OUtil.parseXdmInfo(skipSessionStorage); + if (xdmInfoValue) { + var items = OSF.OUtil.getInfoItems(xdmInfoValue); + if (items != undefined && items.length >= 3) { + switch (xdmFieldName) { + case "ConversationUrl": + fieldValue = items[2]; + break; + case "AppId": + fieldValue = items[1]; + break; + } + } + } + return fieldValue; + } + OUtil.getXdmFieldValue = getXdmFieldValue; + function parseUrl(url, enforceHttps) { + if (enforceHttps === void 0) { enforceHttps = false; } + if (typeof url === "undefined" || !url) { + return undefined; + } + var notHttpsErrorMessage = "NotHttps"; + var invalidUrlErrorMessage = "InvalidUrl"; + var isIEBoolean = isIE(); + var isEdgeBoolean = isEdge(); + var parsedUrlObj = { + protocol: undefined, + hostname: undefined, + host: undefined, + port: undefined, + pathname: undefined, + search: undefined, + hash: undefined, + isPortPartOfUrl: undefined + }; + try { + if (isIEBoolean) { + var parser = document.createElement("a"); + parser.href = url; + if (!parser || !parser.protocol || !parser.host || !parser.hostname || !parser.href + || this.cleanUrl(parser.href) !== this.cleanUrl(url)) { + throw invalidUrlErrorMessage; + } + if (OSF.OUtil.checkFlight(2)) { + if (enforceHttps && parser.protocol != "https:") + throw new Error(notHttpsErrorMessage); + } + var redundandPortString = this.getRedundandPortString(url, parser); + parsedUrlObj.protocol = parser.protocol; + parsedUrlObj.hostname = parser.hostname; + parsedUrlObj.port = (redundandPortString == "") ? parser.port : ""; + parsedUrlObj.host = (redundandPortString != "") ? parser.hostname : parser.host; + parsedUrlObj.pathname = (isIEBoolean ? "/" : "") + parser.pathname; + parsedUrlObj.search = parser.search; + parsedUrlObj.hash = parser.hash; + parsedUrlObj.isPortPartOfUrl = this.containsPort(url, parser.protocol, parser.hostname, parser.port); + } + else { + var urlObj = new URL(url); + if (urlObj && urlObj.protocol && urlObj.host && urlObj.hostname) { + if (OSF.OUtil.checkFlight(2)) { + if (enforceHttps && urlObj.protocol != "https:") + throw new Error(notHttpsErrorMessage); + } + parsedUrlObj.protocol = urlObj.protocol; + parsedUrlObj.hostname = urlObj.hostname; + parsedUrlObj.port = urlObj.port; + parsedUrlObj.host = urlObj.host; + parsedUrlObj.pathname = urlObj.pathname; + parsedUrlObj.search = urlObj.search; + parsedUrlObj.hash = urlObj.hash; + parsedUrlObj.isPortPartOfUrl = urlObj.host.lastIndexOf(":" + urlObj.port) == (urlObj.host.length - urlObj.port.length - 1); + } + } + } + catch (err) { + if (err.message === notHttpsErrorMessage) + throw err; + } + return parsedUrlObj; + } + OUtil.parseUrl = parseUrl; + function _reOrderTabbableElements(elements) { + var bucket0 = []; + var bucketPositive = []; + var i; + var len = elements.length; + var ele; + for (i = 0; i < len; i++) { + ele = elements[i]; + if (ele.tabIndex) { + if (ele.tabIndex > 0) { + bucketPositive.push(ele); + } + else if (ele.tabIndex === 0) { + bucket0.push(ele); + } + } + else { + bucket0.push(ele); + } + } + bucketPositive = bucketPositive.sort(function (left, right) { + var diff = left.tabIndex - right.tabIndex; + if (diff === 0) { + diff = bucketPositive.indexOf(left) - bucketPositive.indexOf(right); + } + return diff; + }); + return [].concat(bucketPositive, bucket0); + } + ; + function focusToFirstTabbable(all, backward) { + var next; + var focused = false; + var candidate; + var setFlag = function (e) { + focused = true; + }; + var findNextPos = function (allLen, currPos, backward) { + if (currPos < 0 || currPos > allLen) { + return -1; + } + else if (currPos === 0 && backward) { + return -1; + } + else if (currPos === allLen - 1 && !backward) { + return -1; + } + if (backward) { + return currPos - 1; + } + else { + return currPos + 1; + } + }; + all = _reOrderTabbableElements(all); + next = backward ? all.length - 1 : 0; + if (all.length === 0) { + return null; + } + while (!focused && next >= 0 && next < all.length) { + candidate = all[next]; + window.focus(); + candidate.addEventListener('focus', setFlag); + candidate.focus(); + candidate.removeEventListener('focus', setFlag); + next = findNextPos(all.length, next, backward); + if (!focused && candidate === document.activeElement) { + focused = true; + } + } + if (focused) { + return candidate; + } + else { + return null; + } + } + OUtil.focusToFirstTabbable = focusToFirstTabbable; + function focusToNextTabbable(all, curr, shift) { + var currPos; + var next; + var focused = false; + var candidate; + var setFlag = function (e) { + focused = true; + }; + var findCurrPos = function (all, curr) { + var i = 0; + for (; i < all.length; i++) { + if (all[i] === curr) { + return i; + } + } + return -1; + }; + var findNextPos = function (allLen, currPos, shift) { + if (currPos < 0 || currPos > allLen) { + return -1; + } + else if (currPos === 0 && shift) { + return -1; + } + else if (currPos === allLen - 1 && !shift) { + return -1; + } + if (shift) { + return currPos - 1; + } + else { + return currPos + 1; + } + }; + all = _reOrderTabbableElements(all); + currPos = findCurrPos(all, curr); + next = findNextPos(all.length, currPos, shift); + if (next < 0) { + return null; + } + while (!focused && next >= 0 && next < all.length) { + candidate = all[next]; + candidate.addEventListener('focus', setFlag); + candidate.focus(); + candidate.removeEventListener('focus', setFlag); + next = findNextPos(all.length, next, shift); + if (!focused && candidate === document.activeElement) { + focused = true; + } + } + if (focused) { + return candidate; + } + else { + return null; + } + } + OUtil.focusToNextTabbable = focusToNextTabbable; + })(OUtil = OSF.OUtil || (OSF.OUtil = {})); +})(OSF || (OSF = {})); +var OSF; +(function (OSF) { + var ParameterNames; + (function (ParameterNames) { + ParameterNames["Callback"] = "callback"; + ParameterNames["AsyncContext"] = "asyncContext"; + ParameterNames["Data"] = "data"; + ParameterNames["MessageToParent"] = "messageToParent"; + ParameterNames["MessageContent"] = "messageContent"; + ParameterNames["AppCommandInvocationCompletedData"] = "appCommandInvocationCompletedData"; + })(ParameterNames = OSF.ParameterNames || (OSF.ParameterNames = {})); +})(OSF || (OSF = {})); +var OSF; +(function (OSF) { + var Requirement; + (function (Requirement) { + var RequirementVersion = (function () { + function RequirementVersion() { + } + return RequirementVersion; + }()); + Requirement.RequirementVersion = RequirementVersion; + var RequirementMatrix = (function () { + function RequirementMatrix(_setMap) { + this._setMap = _setMap; + } + RequirementMatrix.prototype.isSetSupported = function (name, minVersion) { + if (name == undefined) { + return false; + } + if (minVersion == undefined) { + minVersion = 0; + } + var setSupportArray = this._setMap; + var sets = setSupportArray._sets; + if (sets.hasOwnProperty(name.toLowerCase())) { + var setMaxVersion = sets[name.toLowerCase()]; + try { + var setMaxVersionNum = this._getVersion(setMaxVersion + ""); + minVersion = minVersion + ""; + var minVersionNum = this._getVersion(minVersion); + if (setMaxVersionNum.major > 0 && setMaxVersionNum.major > minVersionNum.major) { + return true; + } + if (setMaxVersionNum.major > 0 && + setMaxVersionNum.minor >= 0 && + setMaxVersionNum.major == minVersionNum.major && + setMaxVersionNum.minor >= minVersionNum.minor) { + return true; + } + } + catch (e) { + return false; + } + } + return false; + }; + RequirementMatrix.prototype._getVersion = function (version) { + version = version + ""; + var temp = version.split("."); + var major = 0; + var minor = 0; + if (temp.length < 2 && isNaN(Number(version))) { + throw "version format incorrect"; + } + else { + major = Number(temp[0]); + if (temp.length >= 2) { + minor = Number(temp[1]); + } + if (isNaN(major) || isNaN(minor)) { + throw "version format incorrect"; + } + } + var result = { "minor": minor, "major": major }; + return result; + }; + return RequirementMatrix; + }()); + Requirement.RequirementMatrix = RequirementMatrix; + var DefaultSetRequirement = (function () { + function DefaultSetRequirement(setMap) { + this._sets = setMap; + } + DefaultSetRequirement.prototype._addSetMap = function (addedSet) { + for (var name in addedSet) { + this._sets[name] = addedSet[name]; + } + }; + return DefaultSetRequirement; + }()); + Requirement.DefaultSetRequirement = DefaultSetRequirement; + var DefaultDialogSetRequirement = (function (_super) { + __extends(DefaultDialogSetRequirement, _super); + function DefaultDialogSetRequirement() { + return _super.call(this, { + "dialogapi": 1.1 + }) || this; + } + return DefaultDialogSetRequirement; + }(DefaultSetRequirement)); + Requirement.DefaultDialogSetRequirement = DefaultDialogSetRequirement; + var RequirementsMatrixFactory = (function () { + function RequirementsMatrixFactory() { + } + RequirementsMatrixFactory.getDefaultRequirementMatrix = function (appContext) { + var defaultRequirementMatrix = undefined; + var clientRequirement = appContext.get_requirementMatrix(); + if (clientRequirement != undefined && clientRequirement.length > 0) { + var matrixItem = JSON.parse(appContext.get_requirementMatrix().toLowerCase()); + defaultRequirementMatrix = new RequirementMatrix(new DefaultSetRequirement(matrixItem)); + } + else { + defaultRequirementMatrix = new RequirementMatrix(new DefaultSetRequirement({})); + } + return defaultRequirementMatrix; + }; + RequirementsMatrixFactory.getDefaultDialogRequirementMatrix = function (appContext) { + var defaultRequirementMatrix = undefined; + var clientRequirement = appContext.get_dialogRequirementMatrix(); + if (clientRequirement != undefined && clientRequirement.length > 0) { + var matrixItem = JSON.parse(appContext.get_requirementMatrix().toLowerCase()); + defaultRequirementMatrix = new RequirementMatrix(new DefaultSetRequirement(matrixItem)); + } + else { + defaultRequirementMatrix = new RequirementMatrix(new DefaultDialogSetRequirement()); + } + return defaultRequirementMatrix; + }; + return RequirementsMatrixFactory; + }()); + Requirement.RequirementsMatrixFactory = RequirementsMatrixFactory; + })(Requirement = OSF.Requirement || (OSF.Requirement = {})); +})(OSF || (OSF = {})); +var OSF; +(function (OSF) { + var DDA; + (function (DDA) { + var RichApi; + (function (RichApi) { + function executeRichApiRequestAsync(messageSafearray, callback) { + var asyncMethodExecutor = OSF._OfficeAppFactory.getAsyncMethodExecutor(); + var dataTransform = { + toSafeArrayHost: function () { + return [messageSafearray]; + }, + fromSafeArrayHost: function (payload) { + return { + data: payload + }; + }, + toWebHost: function () { + return { + ArrayData: messageSafearray + }; + }, + fromWebHost: function (payload) { + return { + data: payload.Data + }; + } + }; + asyncMethodExecutor.executeAsync(93, dataTransform, callback); + } + RichApi.executeRichApiRequestAsync = executeRichApiRequestAsync; + var _richApiMessageManager; + Object.defineProperty(RichApi, 'richApiMessageManager', { + get: function () { + if (!_richApiMessageManager) { + _richApiMessageManager = new OSF.RichApiMessageManager(); + } + return _richApiMessageManager; + } + }); + })(RichApi = DDA.RichApi || (DDA.RichApi = {})); + })(DDA = OSF.DDA || (OSF.DDA = {})); +})(OSF || (OSF = {})); +var OSF; +(function (OSF) { + var RichApiMessageManager = (function () { + function RichApiMessageManager() { + this._registerHandlers = []; + this._eventDispatch = new OSF.EventDispatch([ + { + type: OSF.EventType.RichApiMessage, + id: 33, + getTargetId: function () { return ''; }, + fromSafeArrayHost: function (payload) { + var entryArray = payload; + return RichApiMessageManager.transferEventArgument(entryArray); + }, + fromWebHost: function (payload) { + var entryArray = payload.ArrayData; + return RichApiMessageManager.transferEventArgument(entryArray); + } + } + ]); + } + RichApiMessageManager.transferEventArgument = function (entryArray) { + var entries = []; + if (entryArray) { + for (var i = 0; i < entryArray.length; i++) { + var elem = entryArray[i]; + if (elem.toArray) { + elem = elem.toArray(); + } + entries.push({ + messageCategory: elem[0], + messageType: elem[1], + targetId: elem[2], + message: elem[3], + id: elem[4], + isRemoteOverride: elem[5] + }); + } + } + return { + type: OSF.EventType.RichApiMessage, + entries: entries + }; + }; + RichApiMessageManager.prototype.addHandlerAsync = function (eventType, handler, callback) { + OSF.EventHelper.addEventHandler(eventType, handler, callback, this._eventDispatch); + }; + RichApiMessageManager.prototype.removeHandlerAsync = function (eventType, handler, callback) { + OSF.EventHelper.removeEventHandler(eventType, handler, callback, this._eventDispatch); + }; + RichApiMessageManager.prototype.register = function (handler) { + var _this = this; + if (!this._registerPromise) { + this._registerPromise = new Office.Promise(function (resolve, reject) { + _this.addHandlerAsync(OSF.EventType.RichApiMessage, function (args) { + _this._registerHandlers.forEach(function (value) { + if (value) { + value(args); + } + }); + }, function (asyncResult) { + if (asyncResult.status == 'failed') { + reject(asyncResult.error); + } + else { + resolve(); + } + }); + }); + } + return this._registerPromise.then(function () { + _this._registerHandlers.push(handler); + }); + }; + return RichApiMessageManager; + }()); + OSF.RichApiMessageManager = RichApiMessageManager; +})(OSF || (OSF = {})); +var OSF; +(function (OSF) { + var RichClientHostController = (function () { + function RichClientHostController() { + } + RichClientHostController.prototype.execute = function (id, params, callback) { + if (typeof OsfOMToken != 'undefined' && OsfOMToken) { + window.external.Execute(id, params, callback, OsfOMToken); + } + else { + window.external.Execute(id, params, callback); + } + }; + RichClientHostController.prototype.registerEvent = function (id, eventType, targetId, handler, callback) { + if (typeof OsfOMToken != 'undefined' && OsfOMToken) { + window.external.RegisterEvent(id, targetId, handler, callback, OsfOMToken); + } + else { + window.external.RegisterEvent(id, targetId, handler, callback); + } + }; + RichClientHostController.prototype.unregisterEvent = function (id, eventType, targetId, callback) { + if (typeof OsfOMToken != 'undefined' && OsfOMToken) { + window.external.UnregisterEvent(id, targetId, callback, OsfOMToken); + } + else { + window.external.UnregisterEvent(id, targetId, callback); + } + }; + return RichClientHostController; + }()); + OSF.RichClientHostController = RichClientHostController; +})(OSF || (OSF = {})); +var OSF; +(function (OSF) { + var RichClientInitializationHelper = (function (_super) { + __extends(RichClientInitializationHelper, _super); + function RichClientInitializationHelper() { + return _super !== null && _super.apply(this, arguments) || this; + } + RichClientInitializationHelper.prototype.getOsfControlContext = function () { + if (!this._osfControlContext) { + var warningText = "Warning: Office.js is loaded outside of Office client"; + try { + if (window.external) { + this._osfControlContext = window.external.GetContext(); + } + else { + console.error("There is no window.external."); + OSF.Utility.trace(warningText); + return null; + } + } + catch (e) { + console.error("Error when call window.external.GetContext() :" + JSON.stringify(e)); + OSF.Utility.trace(warningText); + return null; + } + } + return this._osfControlContext; + }; + RichClientInitializationHelper.prototype.getAppContext = function (wnd, onSuccess, onError) { + var _this = this; + var context = this.getOsfControlContext(); + if (!context) { + onError(new Error("The Office.js is loaded outside of Office client")); + return; + } + var appType; + var id; + var version; + var minorVersion; + var UILocale; + var dataLocale; + var docUrl; + var clientMode; + var activationMode; + var reason; + var osfControlType; + var eToken; + var correlationId; + var appInstanceId; + var touchEnabled; + var commerceAllowed; + var requirementMatrix; + var hostCustomMessage; + var hostFullVersion; + var dialogRequirementMatrix; + var sdxFeatureGates; + var initialDisplayMode = 0; + var settingsFunc; + var officeThemeFunc; + var fallback = false; + var externalNativeFunctionExists = OSF.Utility.externalNativeFunctionExists; + if (!externalNativeFunctionExists(typeof context.GetContextDataInJson)) { + fallback = true; + } + else { + var contextJsonString; + if (typeof OsfOMToken !== 'undefined' && OsfOMToken) { + contextJsonString = context.GetContextDataInJson(OsfOMToken); + var contextJson; + if (contextJsonString) { + contextJson = JSON.parse(contextJsonString); + } + if (!contextJson) { + fallback = true; + } + else { + appType = contextJson.appType; + id = contextJson.solutionRef; + version = contextJson.versionMajor; + minorVersion = contextJson.versionMinor; + UILocale = contextJson.uiLocale; + dataLocale = contextJson.dataLocale; + docUrl = contextJson.docUrl; + clientMode = contextJson.clientMode; + activationMode = contextJson.activationMode; + osfControlType = contextJson.controlType; + eToken = contextJson.eToken; + correlationId = contextJson.correlationId; + appInstanceId = contextJson.appInstanceId; + touchEnabled = contextJson.touchEnabled; + commerceAllowed = context.commerceAllowed; + requirementMatrix = contextJson.requirementMatrix; + hostFullVersion = contextJson.hostFullVersion; + dialogRequirementMatrix = contextJson.requirementMatrix; + var sdxFeatureGatesJson = contextJson.featureGates; + if (sdxFeatureGatesJson) { + sdxFeatureGates = JSON.parse(sdxFeatureGatesJson); + } + initialDisplayMode = contextJson.initialDisplayMode; + settingsFunc = function () { + var settingsString = contextJson.settings; + var settings; + if (settingsString) { + settings = JSON.parse(settingsString); + } + var serializedSettings = {}; + if (settings) { + var names = settings.names; + var values = settings.values; + for (var index = 0; index < names.length; index++) { + serializedSettings[names[index]] = values[index]; + } + } + return serializedSettings; + }; + officeThemeFunc = function () { + var osfOfficeThemeInfoString = contextJson.themeInfo; + return _this.getOfficeThemeFromInfoString(osfOfficeThemeInfoString); + }; + } + } + else { + fallback = true; + } + } + if (fallback) { + appType = context.GetAppType(); + id = context.GetSolutionRef(); + version = context.GetAppVersionMajor(); + minorVersion = context.GetAppVersionMinor(); + UILocale = context.GetAppUILocale(); + dataLocale = context.GetAppDataLocale(); + docUrl = context.GetDocUrl(); + clientMode = context.GetAppCapabilities(); + activationMode = context.GetActivationMode(); + osfControlType = context.GetControlIntegrationLevel(); + try { + eToken = context.GetSolutionToken(); + } + catch (ex) { + } + var externalNativeFunctionExists = OSF.Utility.externalNativeFunctionExists; + if (externalNativeFunctionExists(typeof context.GetCorrelationId)) { + correlationId = context.GetCorrelationId(); + } + if (externalNativeFunctionExists(typeof context.GetInstanceId)) { + appInstanceId = context.GetInstanceId(); + } + if (externalNativeFunctionExists(typeof context.GetTouchEnabled)) { + touchEnabled = context.GetTouchEnabled(); + } + if (externalNativeFunctionExists(typeof context.GetCommerceAllowed)) { + commerceAllowed = context.GetCommerceAllowed(); + } + if (externalNativeFunctionExists(typeof context.GetSupportedMatrix)) { + requirementMatrix = context.GetSupportedMatrix(); + } + if (externalNativeFunctionExists(typeof context.GetHostCustomMessage)) { + hostCustomMessage = context.GetHostCustomMessage(); + } + if (externalNativeFunctionExists(typeof context.GetHostFullVersion)) { + hostFullVersion = context.GetHostFullVersion(); + } + if (externalNativeFunctionExists(typeof context.GetDialogRequirementMatrix)) { + dialogRequirementMatrix = context.GetDialogRequirementMatrix(); + } + if (externalNativeFunctionExists(typeof context.GetFeaturesForSolution)) { + try { + var sdxFeatureGatesJson = context.GetFeaturesForSolution(); + if (sdxFeatureGatesJson) { + sdxFeatureGates = JSON.parse(sdxFeatureGatesJson); + } + } + catch (ex) { + OSF.Utility.trace("Exception while creating the SDX FeatureGates object. Details: " + ex); + } + } + if (externalNativeFunctionExists(typeof context.GetInitialDisplayMode)) { + initialDisplayMode = context.GetInitialDisplayMode(); + } + settingsFunc = function () { return _this.getSerializedSettings(); }; + officeThemeFunc = function () { return _this.getOfficeTheme(); }; + } + reason = (activationMode === 2) ? Office.InitializationReason.DocumentOpened : Office.InitializationReason.Inserted; + eToken = eToken ? eToken.toString() : ""; + var returnedContext = new OSF.OfficeAppContext(id, appType, version, UILocale, dataLocale, docUrl, clientMode, settingsFunc, reason, osfControlType, eToken, correlationId, appInstanceId, touchEnabled, commerceAllowed, minorVersion, requirementMatrix, hostCustomMessage, hostFullVersion, undefined, undefined, undefined, undefined, dialogRequirementMatrix, sdxFeatureGates, officeThemeFunc, initialDisplayMode, undefined); + onSuccess(returnedContext); + return; + }; + RichClientInitializationHelper.prototype.createClientHostController = function () { + if (!this._clientHostController) { + if (this._hostInfo.hostPlatform === OSF.HostInfoPlatform.win32) { + this._clientHostController = new OSF.Win32RichClientHostController(); + } + else { + throw OSF.Utility.createNotImplementedException(); + } + } + return this._clientHostController; + }; + RichClientInitializationHelper.prototype.createAsyncMethodExecutor = function () { + return new OSF.SafeArrayAsyncMethodExecutor(this._clientHostController); + }; + RichClientInitializationHelper.prototype.createClientSettingsManager = function () { + var manager = new OSF.RichClientSettingsManager(this.getOsfControlContext()); + return manager; + }; + RichClientInitializationHelper.prototype.getSerializedSettings = function () { + var osfControlContext = this.getOsfControlContext(); + var keys = []; + var values = []; + if (typeof OsfOMToken != 'undefined' && OsfOMToken) { + osfControlContext.GetSettings(OsfOMToken).Read(keys, values); + } + else { + osfControlContext.GetSettings().Read(keys, values); + } + var serializedSettings = {}; + for (var index = 0; index < keys.length; index++) { + serializedSettings[keys[index]] = values[index]; + } + return serializedSettings; + }; + RichClientInitializationHelper.prototype.initializeSettings = function () { + var osfControlContext = this.getOsfControlContext(); + var keys = []; + var values = []; + if (typeof OsfOMToken != 'undefined' && OsfOMToken) { + osfControlContext.GetSettings(OsfOMToken).Read(keys, values); + } + else { + osfControlContext.GetSettings().Read(keys, values); + } + var serializedSettings = {}; + for (var index = 0; index < keys.length; index++) { + serializedSettings[keys[index]] = values[index]; + } + return this.createSettings(serializedSettings); + }; + RichClientInitializationHelper.prototype.getOfficeTheme = function () { + var osfControlContext = this.getOsfControlContext(); + var osfOfficeThemeInfoString = osfControlContext.GetOfficeThemeInfo(); + return this.getOfficeThemeFromInfoString(osfOfficeThemeInfoString); + }; + RichClientInitializationHelper.prototype.getOfficeThemeFromInfoString = function (osfOfficeThemeInfoString) { + var osfOfficeTheme; + if (osfOfficeThemeInfoString) { + osfOfficeTheme = JSON.parse(osfOfficeThemeInfoString); + for (var color in osfOfficeTheme) { + osfOfficeTheme[color] = OSF.OUtil.convertIntToCssHexColor(osfOfficeTheme[color]); + } + } + return osfOfficeTheme; + }; + return RichClientInitializationHelper; + }(OSF.InitializationHelper)); + OSF.RichClientInitializationHelper = RichClientInitializationHelper; +})(OSF || (OSF = {})); +var OSF; +(function (OSF) { + var RichClientSettingsManager = (function () { + function RichClientSettingsManager(_osfClientContext) { + this._osfClientContext = _osfClientContext; + } + RichClientSettingsManager.prototype.read = function (onComplete) { + var keys = []; + var values = []; + var osfControlContext = this._osfClientContext; + if (typeof OsfOMToken != 'undefined' && OsfOMToken) { + osfControlContext.GetSettings(OsfOMToken).Read(keys, values); + } + else { + osfControlContext.GetSettings().Read(keys, values); + } + var serializedSettings = {}; + for (var index = 0; index < keys.length; index++) { + serializedSettings[keys[index]] = values[index]; + } + if (onComplete) { + onComplete(0, serializedSettings); + } + }; + RichClientSettingsManager.prototype.write = function (serializedSettings, onComplete) { + var keys = []; + var values = []; + for (var key in serializedSettings) { + keys.push(key); + values.push(serializedSettings[key]); + } + var osfControlContext = this._osfClientContext; + var settingObj; + if (typeof OsfOMToken != 'undefined' && OsfOMToken) { + settingObj = osfControlContext.GetSettings(OsfOMToken); + } + else { + settingObj = osfControlContext.GetSettings(); + } + if (typeof settingObj.WriteAsync != 'undefined') { + settingObj.WriteAsync(keys, values, onComplete); + } + else { + settingObj.Write(keys, values); + onComplete(0); + } + }; + return RichClientSettingsManager; + }()); + OSF.RichClientSettingsManager = RichClientSettingsManager; +})(OSF || (OSF = {})); +var OSF; +(function (OSF) { + var SafeArrayAsyncMethodExecutor = (function (_super) { + __extends(SafeArrayAsyncMethodExecutor, _super); + function SafeArrayAsyncMethodExecutor(_clientHostController) { + var _this = _super.call(this) || this; + _this._clientHostController = _clientHostController; + return _this; + } + SafeArrayAsyncMethodExecutor.prototype.executeAsync = function (id, dataTransform, callback) { + var _this = this; + try { + this._clientHostController.execute(id, dataTransform.toSafeArrayHost(), function (hostResponseArgsNative, resultCode) { + var hostResponseArgs = OSF.Utility.fromSafeArray(hostResponseArgsNative); + if (Office.context.host == Office.HostType.Outlook) { + if (callback) { + callback(resultCode, hostResponseArgs); + } + } + else { + _this.handleHostResponse(hostResponseArgs, callback, dataTransform, id); + } + return true; + }); + } + catch (ex) { + this.onException(ex, id, callback); + } + }; + SafeArrayAsyncMethodExecutor.prototype.registerEventAsync = function (id, eventType, targetId, handler, dataTransform, callback) { + var _this = this; + try { + this._clientHostController.registerEvent(id, eventType, targetId, function (eventDispId, payload) { + var eventPayload = OSF.Utility.fromSafeArray(payload); + var eventArgs = dataTransform.fromSafeArrayHost(eventPayload); + handler(eventArgs); + }, function (hostResponseArgsNative) { + var result; + var status; + var hostResponseArgs = OSF.Utility.fromSafeArray(hostResponseArgsNative); + if (typeof hostResponseArgs === "number") { + result = []; + status = hostResponseArgs; + } + else { + result = hostResponseArgs; + status = result[0]; + } + _this.invokeCallback(id, callback, status, null); + return true; + }); + } + catch (ex) { + this.onException(ex, id, callback); + } + }; + SafeArrayAsyncMethodExecutor.prototype.unregisterEventAsync = function (id, eventType, targetId, callback) { + var _this = this; + try { + this._clientHostController.unregisterEvent(id, eventType, targetId, function (hostResponseArgsNative, resultCode) { + var result; + var status; + var hostResponseArgs = OSF.Utility.fromSafeArray(hostResponseArgsNative); + if (typeof hostResponseArgs === "number") { + result = []; + status = hostResponseArgs; + } + else { + result = hostResponseArgs; + status = result[0]; + } + _this.invokeCallback(id, callback, status, null); + return true; + }); + } + catch (ex) { + this.onException(ex, id, callback); + } + }; + SafeArrayAsyncMethodExecutor.prototype.handleHostResponse = function (hostResponseArgsNative, callback, dataTransform, id) { + var chunkResultData; + var result; + var status; + var hostResponseArgs = OSF.Utility.fromSafeArray(hostResponseArgsNative); + if (typeof hostResponseArgs === "number") { + result = []; + status = hostResponseArgs; + } + else { + result = hostResponseArgs; + status = result[0]; + } + if (status == 1) { + var payload = result[1]; + if (payload != null) { + if (!chunkResultData) { + chunkResultData = new Array(); + } + chunkResultData[payload[0]] = payload[1]; + } + return false; + } + if (callback) { + var payload; + if (status == 0) { + if (result.length > 2) { + payload = []; + for (var i = 1; i < result.length; i++) + payload[i - 1] = result[i]; + } + else { + payload = result[1]; + } + if (chunkResultData) { + if (payload != null) { + var expectedChunkCount = payload[payload.length - 1]; + if (chunkResultData.length == expectedChunkCount) { + payload[payload.length - 1] = chunkResultData; + } + else { + status = 5001; + } + } + } + } + else { + payload = result[1]; + } + var value = null; + if (status == 0) { + value = dataTransform.fromSafeArrayHost(payload); + } + this.invokeCallback(id, callback, status, value); + } + }; + SafeArrayAsyncMethodExecutor.prototype.onException = function (ex, dispId, callback) { + var status; + var statusNumber = ex.number; + if (statusNumber) { + switch (statusNumber) { + case -2146828218: + status = 7000; + break; + case -2147467259: + if (dispId == 10) { + status = 12007; + } + else { + status = 5001; + } + break; + case -2146828283: + status = 5010; + break; + case -2147209089: + status = 5010; + break; + case -2147208704: + status = 5100; + break; + case -2146827850: + default: + status = 5001; + break; + } + } + if (callback) { + this.invokeCallback(dispId, callback, status || 5001, null); + } + }; + return SafeArrayAsyncMethodExecutor; + }(OSF.AsyncMethodExecutor)); + OSF.SafeArrayAsyncMethodExecutor = SafeArrayAsyncMethodExecutor; +})(OSF || (OSF = {})); +var OSF; +(function (OSF) { + var SafeStorage = (function () { + function SafeStorage(_internalStorage) { + this._internalStorage = _internalStorage; + } + SafeStorage.prototype.getItem = function (key) { + try { + return this._internalStorage && this._internalStorage.getItem(key); + } + catch (e) { + return null; + } + }; + SafeStorage.prototype.setItem = function (key, data) { + try { + this._internalStorage && this._internalStorage.setItem(key, data); + } + catch (e) { + } + }; + SafeStorage.prototype.clear = function () { + try { + this._internalStorage && this._internalStorage.clear(); + } + catch (e) { + } + }; + SafeStorage.prototype.removeItem = function (key) { + try { + this._internalStorage && this._internalStorage.removeItem(key); + } + catch (e) { + } + }; + SafeStorage.prototype.getKeysWithPrefix = function (keyPrefix) { + var keyList = []; + try { + var len = this._internalStorage && this._internalStorage.length || 0; + for (var i = 0; i < len; i++) { + var key = this._internalStorage.key(i); + if (key.indexOf(keyPrefix) === 0) { + keyList.push(key); + } + } + } + catch (e) { + } + return keyList; + }; + return SafeStorage; + }()); + OSF.SafeStorage = SafeStorage; +})(OSF || (OSF = {})); +var Office; +(function (Office) { + var Settings = (function () { + function Settings(settings, _clientSettingsManager) { + var _this = this; + this._clientSettingsManager = _clientSettingsManager; + settings = settings || {}; + this._settings = settings; + this._eventDispatch = new OSF.EventDispatch([ + { + id: 1, + type: OSF.EventType.SettingsChanged, + getTargetId: function () { return ''; }, + fromSafeArrayHost: function (payload) { + return { + type: OSF.EventType.SettingsChanged, + settings: _this + }; + }, + fromWebHost: function (payload) { + return { + type: OSF.EventType.SettingsChanged, + settings: _this + }; + } + } + ]); + } + Settings.prototype.cacheSessionSettings = function (settings) { + var osfSessionStorage = OSF.OUtil.getSessionStorage(); + if (osfSessionStorage) { + var serializedSettings = OSF.OUtil.serializeSettings(settings); + var storageSettings = JSON.stringify(serializedSettings); + osfSessionStorage.setItem(OSF._OfficeAppFactory.getCachedSessionSettingsKey(), storageSettings); + } + }; + Settings.prototype.get = function (name) { + var setting = this._settings[name]; + return typeof (setting) === 'undefined' ? null : setting; + }; + Settings.prototype.set = function (name, value) { + this._settings[name] = value; + this.cacheSessionSettings(this._settings); + }; + Settings.prototype.remove = function (name) { + delete this._settings[name]; + this.cacheSessionSettings(this._settings); + }; + Settings.prototype.saveAsync = function (callback) { + var settingsManager = this._clientSettingsManager; + var serializedSettings = OSF.OUtil.serializeSettings(this._settings); + settingsManager.write(serializedSettings, function (errorCode) { + var result = OSF.Utility.asyncResultFromErrorCode(errorCode); + if (callback) { + callback(result); + } + }); + }; + Settings.prototype.refreshAsync = function (callback) { + var _this = this; + var settingsManager = this._clientSettingsManager; + settingsManager.read(function (errorCode, serializedSettings) { + var result = OSF.Utility.asyncResultFromErrorCode(errorCode); + if (result.status === Office.AsyncResultStatus.succeeded) { + _this._settings = OSF.OUtil.deserializeSettings(serializedSettings); + result.value = _this; + } + if (callback) { + callback(result); + } + }); + }; + Settings.prototype.addHandlerAsync = function (eventType, handler, callback) { + OSF.EventHelper.addEventHandler(eventType, handler, callback, this._eventDispatch); + }; + Settings.prototype.removeHandlerAsync = function (eventType, handler, callback) { + OSF.EventHelper.removeEventHandler(eventType, handler, callback, this._eventDispatch); + }; + Settings.prototype.toJSON = function () { + return this._settings; + }; + return Settings; + }()); + Office.Settings = Settings; +})(Office || (Office = {})); +var OSF; +(function (OSF) { + var Utility; + (function (Utility) { + function createArgumentException(name) { + return new Error("Invalid argument " + name); + } + Utility.createArgumentException = createArgumentException; + function createNotImplementedException() { + return new Error("Not implemented yet"); + } + Utility.createNotImplementedException = createNotImplementedException; + function log(message) { + console.log(message); + } + Utility.log = log; + function trace(message) { + console.log(message); + } + Utility.trace = trace; + function debugLog(message) { + console.log(message); + } + Utility.debugLog = debugLog; + function xdmDebugLog(message) { + if (Utility._DebugXdm) { + console.log(message); + } + } + Utility.xdmDebugLog = xdmDebugLog; + function enableDebugXdm() { + Utility._DebugXdm = true; + } + Utility.enableDebugXdm = enableDebugXdm; + function createPromiseFromResult(result) { + return Promise.resolve(result); + } + Utility.createPromiseFromResult = createPromiseFromResult; + function createPromise(executor) { + var ret = new Promise(executor); + return ret; + } + Utility.createPromise = createPromise; + function compareVersions(version1, version2) { + var splitVersion1 = version1.split("."); + var splitVersion2 = version2.split("."); + var iter; + for (iter in splitVersion1) { + if (parseInt(splitVersion1[iter]) < parseInt(splitVersion2[iter])) { + return false; + } + else if (parseInt(splitVersion1[iter]) > parseInt(splitVersion2[iter])) { + return true; + } + } + return false; + } + Utility.compareVersions = compareVersions; + function getQueryStringValue(paramName) { + if (typeof (window) !== 'undefined' && window.location && window.location.search) { + var regex = new RegExp('[?&]' + paramName + '=([^&]*)'); + var match = regex.exec(window.location.search); + if (match) { + var ret = match[1]; + return ret; + } + } + return null; + } + Utility.getQueryStringValue = getQueryStringValue; + function getErrorCodeFromAsyncResult(asyncResult) { + if (asyncResult.status === Office.AsyncResultStatus.succeeded) { + return 0; + } + if (asyncResult.error && asyncResult.error.code) { + return asyncResult.error.code; + } + return 5001; + } + Utility.getErrorCodeFromAsyncResult = getErrorCodeFromAsyncResult; + function isNullOrUndefined(value) { + if (typeof (value) === "undefined") { + return true; + } + if (value === null) { + return true; + } + return false; + } + Utility.isNullOrUndefined = isNullOrUndefined; + function isNullOrEmpty(value) { + if (isNullOrUndefined(value)) { + return true; + } + return (value.length === 0); + } + Utility.isNullOrEmpty = isNullOrEmpty; + function externalNativeFunctionExists(type) { + return type === 'unknown' || type !== 'undefined'; + } + Utility.externalNativeFunctionExists = externalNativeFunctionExists; + function stringEndsWith(value, subString) { + if (isNullOrUndefined(value)) { + throw createArgumentException("value"); + } + if (isNullOrUndefined(subString)) { + throw createArgumentException("subString"); + } + if (subString.length > value.length) { + return false; + } + if (value.substr(value.length - subString.length) === subString) { + return true; + } + return false; + } + Utility.stringEndsWith = stringEndsWith; + function fromSafeArray(value) { + var ret = value; + if (value != null && value.toArray) { + var arrayResult = value.toArray(); + ret = new Array(arrayResult.length); + for (var i = 0; i < arrayResult.length; i++) { + ret[i] = fromSafeArray(arrayResult[i]); + } + } + return ret; + } + Utility.fromSafeArray = fromSafeArray; + function asyncResultFromErrorCode(errorCode) { + if (errorCode === 0) { + return { + status: Office.AsyncResultStatus.succeeded + }; + } + else { + return { + status: Office.AsyncResultStatus.failed, + error: { + code: errorCode + } + }; + } + } + Utility.asyncResultFromErrorCode = asyncResultFromErrorCode; + Utility._DebugXdm = false; + })(Utility = OSF.Utility || (OSF.Utility = {})); +})(OSF || (OSF = {})); +var OSF; +(function (OSF) { + var WebAsyncMethodExecutor = (function (_super) { + __extends(WebAsyncMethodExecutor, _super); + function WebAsyncMethodExecutor(_clientHostController) { + var _this = _super.call(this) || this; + _this._clientHostController = _clientHostController; + return _this; + } + WebAsyncMethodExecutor.prototype.executeAsync = function (id, dataTransform, callback) { + var _this = this; + this._clientHostController.execute(id, dataTransform.toWebHost(), function (resultCode, payload) { + if (callback) { + if (Office.context.host === Office.HostType.Outlook) { + callback(resultCode, payload); + } + else { + var value = null; + if (resultCode == 0) { + value = dataTransform.fromWebHost(payload); + } + _this.invokeCallback(id, callback, resultCode, value); + } + } + return true; + }); + }; + WebAsyncMethodExecutor.prototype.registerEventAsync = function (id, eventType, targetId, handler, dataTransform, callback) { + var _this = this; + this._clientHostController.registerEvent(id, eventType, targetId, function (payload) { + var eventPayload = payload; + var eventArgs = dataTransform.fromWebHost(eventPayload); + handler(eventArgs); + }, function (resultCode, payload) { + if (callback) { + _this.invokeCallback(id, callback, resultCode, null); + } + return true; + }); + }; + WebAsyncMethodExecutor.prototype.unregisterEventAsync = function (id, eventType, targetId, callback) { + var _this = this; + this._clientHostController.unregisterEvent(id, eventType, targetId, function (resultCode, payload) { + if (callback) { + _this.invokeCallback(id, callback, resultCode, null); + } + return true; + }); + }; + return WebAsyncMethodExecutor; + }(OSF.AsyncMethodExecutor)); + OSF.WebAsyncMethodExecutor = WebAsyncMethodExecutor; +})(OSF || (OSF = {})); +var OSF; +(function (OSF) { + var DDA; + (function (DDA) { + var WebAuth; + (function (WebAuth) { + function getAuthContextAsync(callback) { + var asyncMethodExecutor = OSF._OfficeAppFactory.getAsyncMethodExecutor(); + var dataTransform = { + toSafeArrayHost: function () { + return []; + }, + fromSafeArrayHost: function (payload) { + return null; + }, + toWebHost: function () { + return {}; + }, + fromWebHost: function (payload) { + return payload.authContext; + } + }; + asyncMethodExecutor.executeAsync(99, dataTransform, callback); + } + WebAuth.getAuthContextAsync = getAuthContextAsync; + })(WebAuth = DDA.WebAuth || (DDA.WebAuth = {})); + })(DDA = OSF.DDA || (OSF.DDA = {})); + var WebAuth; + (function (WebAuth) { + var CDN_PATH_WEBAUTHJS = 'webauth/webauth.implicit.js'; + WebAuth.config = null; + function load(callback) { + var loadResult; + OSF.OUtil.loadScript(OSF.LoadScriptHelper.getHostBundleJsBasePath() + CDN_PATH_WEBAUTHJS, function () { + if (WebAuth.config) { + loadResult = Implicit.Load(WebAuth.config, OSF._OfficeAppFactory.getHostInfo().osfControlAppCorrelationId); + WebAuth.loaded = true; + if (callback) { + callback(WebAuth.loaded); + } + } + else { + Implicit.GetAuthConfig().then(function (configParent) { + WebAuth.config = configParent; + loadResult = Implicit.Load(WebAuth.config, OSF._OfficeAppFactory.getHostInfo().osfControlAppCorrelationId); + WebAuth.loaded = true; + }, function () { + WebAuth.loaded = false; + }).then(function () { + if (callback) { + callback(WebAuth.loaded); + } + }); + } + }); + return loadResult; + } + WebAuth.load = load; + function getToken(target, applicationId, correlationId, popup) { + if (!WebAuth.loaded) + return null; + if (typeof popup === "boolean") { + return Implicit.GetToken(target, applicationId, correlationId, popup); + } + else { + return Implicit.GetToken(target, applicationId, correlationId); + } + } + WebAuth.getToken = getToken; + })(WebAuth = OSF.WebAuth || (OSF.WebAuth = {})); +})(OSF || (OSF = {})); +var OSF; +(function (OSF) { + var WebClientHostController = (function () { + function WebClientHostController(webAppState) { + this._delegateVersion = 1; + this._webAppState = webAppState; + } + WebClientHostController.prototype.execute = function (id, params, callback) { + var _this = this; + var hostCallArgs = params; + if (!hostCallArgs) { + hostCallArgs = {}; + } + hostCallArgs.DdaMethod = { + ControlId: this._webAppState.id, + DispatchId: id, + Version: this._delegateVersion + }; + hostCallArgs.__timeout__ = -1; + this._webAppState.clientEndPoint.invoke('executeMethod', function (xdmStatus, payload) { + var error = 0; + if (xdmStatus == 0) { + _this._delegateVersion = payload["Version"]; + error = payload["Error"]; + } + else { + switch (xdmStatus) { + case -5: + error = 7000; + break; + default: + error = 5001; + break; + } + } + if (callback) { + callback(error, payload); + } + }, hostCallArgs); + }; + WebClientHostController.prototype.registerEvent = function (id, eventType, targetId, handler, callback) { + this._webAppState.clientEndPoint.registerForEvent(this.getXdmEventName(targetId, eventType), function (payload) { + if (handler) { + handler(payload); + } + }, this._getOnAfterRegisterEvent(true, id, callback), { + controlId: this._webAppState.id, + eventDispId: id, + targetId: targetId, + __timeout__: -1 + }); + }; + WebClientHostController.prototype.unregisterEvent = function (id, eventType, targetId, callback) { + this._webAppState.clientEndPoint.unregisterForEvent(this.getXdmEventName(targetId, eventType), this._getOnAfterRegisterEvent(false, id, callback), { + controlId: this._webAppState.id, + eventDispId: id, + targetId: targetId, + __timeout__: -1 + }); + }; + WebClientHostController.prototype.messageParent = function (params) { + throw OSF.Utility.createNotImplementedException(); + }; + WebClientHostController.prototype.openDialog = function (id, eventType, targetId, handler, callback) { + throw OSF.Utility.createNotImplementedException(); + }; + WebClientHostController.prototype.closeDialog = function (id, eventType, targetId, callback) { + throw OSF.Utility.createNotImplementedException(); + }; + WebClientHostController.prototype.sendMessage = function (params) { + throw OSF.Utility.createNotImplementedException(); + }; + WebClientHostController.prototype.getXdmEventName = function (targetId, eventType) { + if (eventType == OSF.EventType.BindingSelectionChanged || + eventType == OSF.EventType.BindingDataChanged || + eventType == OSF.EventType.DataNodeDeleted || + eventType == OSF.EventType.DataNodeInserted || + eventType == OSF.EventType.DataNodeReplaced) { + return targetId + "_" + eventType; + } + else { + return eventType; + } + }; + WebClientHostController.prototype._getOnAfterRegisterEvent = function (register, id, callback) { + var startTime = (new Date()).getTime(); + return function (xdmStatus, payload) { + var status; + if (xdmStatus != 0) { + switch (xdmStatus) { + case -5: + status = 7000; + break; + default: + status = 5001; + break; + } + } + else { + if (payload) { + if (payload["Error"]) { + status = payload["Error"]; + } + else { + status = 0; + } + } + else { + status = 5001; + } + } + if (callback) { + callback(status); + } + if (OSF.AppTelemetry) { + OSF.AppTelemetry.onRegisterDone(register, id, Math.abs((new Date()).getTime() - startTime), status); + } + }; + }; + return WebClientHostController; + }()); + OSF.WebClientHostController = WebClientHostController; +})(OSF || (OSF = {})); +var OSF; +(function (OSF) { + var WebClientHostController_outlook = (function () { + function WebClientHostController_outlook(webAppState) { + this._delegateVersion = 1; + this._webAppState = webAppState; + } + WebClientHostController_outlook.prototype.execute = function (id, params, callback) { + var hostCallArgs; + if (id == 1) { + hostCallArgs = { + MethodData: { + ControlId: this._webAppState.id, + DispatchId: id + } + }; + } + else { + hostCallArgs = { + ApiParams: params, + MethodData: { + ControlId: this._webAppState.id, + DispatchId: id + } + }; + } + this._webAppState.clientEndPoint.invoke(id == 1 ? 'GetInitialData' : 'ExecuteMethod', function (xdmStatus, payload) { + var error = 0; + if (xdmStatus == 0) { + if (id != 1) { + error = payload["error"]; + } + } + else { + switch (xdmStatus) { + case -5: + error = 7000; + break; + default: + error = 5001; + break; + } + } + if (callback) { + callback(error, payload); + } + }, hostCallArgs); + }; + WebClientHostController_outlook.prototype.registerEvent = function (id, eventType, targetId, handler, callback) { + throw OSF.Utility.createNotImplementedException(); + }; + WebClientHostController_outlook.prototype.unregisterEvent = function (id, eventType, targetId, callback) { + throw OSF.Utility.createNotImplementedException(); + }; + WebClientHostController_outlook.prototype.messageParent = function (params) { + throw OSF.Utility.createNotImplementedException(); + }; + WebClientHostController_outlook.prototype.openDialog = function (id, eventType, targetId, handler, callback) { + throw OSF.Utility.createNotImplementedException(); + }; + WebClientHostController_outlook.prototype.closeDialog = function (id, eventType, targetId, callback) { + throw OSF.Utility.createNotImplementedException(); + }; + WebClientHostController_outlook.prototype.sendMessage = function (params) { + throw OSF.Utility.createNotImplementedException(); + }; + return WebClientHostController_outlook; + }()); + OSF.WebClientHostController_outlook = WebClientHostController_outlook; +})(OSF || (OSF = {})); +var OSF; +(function (OSF) { + var WebClientSettingsManager = (function () { + function WebClientSettingsManager() { + } + WebClientSettingsManager.prototype.read = function (onComplete) { + var asyncMethodExecutor = OSF._OfficeAppFactory.getAsyncMethodExecutor(); + var dataTransform = { + toSafeArrayHost: function () { + return []; + }, + fromSafeArrayHost: function (payload) { + return null; + }, + toWebHost: function () { + return {}; + }, + fromWebHost: function (payload) { + return payload.Properties.Settings; + } + }; + var callback = function (result) { + if (result.status === Office.AsyncResultStatus.succeeded) { + var serializedSettings = {}; + for (var i = 0; i < result.value.length; i++) { + var entry = result.value[i]; + if (Array.isArray(entry)) { + serializedSettings[entry[0]] = entry[1]; + } + else { + serializedSettings[entry.Name] = entry.Value; + } + } + onComplete(0, serializedSettings); + } + else { + var errorCode = result.error.code; + onComplete(errorCode, {}); + } + }; + asyncMethodExecutor.executeAsync(75, dataTransform, callback); + }; + WebClientSettingsManager.prototype.write = function (serializedSettings, onComplete) { + var asyncMethodExecutor = OSF._OfficeAppFactory.getAsyncMethodExecutor(); + var properties = []; + for (var key in serializedSettings) { + var entry = []; + entry.push(key); + entry.push(serializedSettings[key]); + properties.push(entry); + } + var dataTransform = { + toSafeArrayHost: function () { + return null; + }, + fromSafeArrayHost: function (payload) { + return null; + }, + toWebHost: function () { + return { + DdaSettingsMethod: { + OverwriteIfStale: true, + Properties: properties + } + }; + }, + fromWebHost: function (payload) { + return null; + } + }; + var callback = function (result) { + if (result.status === Office.AsyncResultStatus.succeeded) { + onComplete(0); + } + else { + var errorCode = result.error.code; + onComplete(errorCode); + } + }; + asyncMethodExecutor.executeAsync(76, dataTransform, callback); + }; + return WebClientSettingsManager; + }()); + OSF.WebClientSettingsManager = WebClientSettingsManager; +})(OSF || (OSF = {})); +var OSF; +(function (OSF) { + var WebInitializationHelper = (function (_super) { + __extends(WebInitializationHelper, _super); + function WebInitializationHelper(hostInfo, webAppState, context, hostFacade) { + var _this = _super.call(this, hostInfo, webAppState, context, hostFacade) || this; + _this._appContext = {}; + _this._tabbableElements = "a[href]:not([tabindex='-1'])," + + "area[href]:not([tabindex='-1'])," + + "button:not([disabled]):not([tabindex='-1'])," + + "input:not([disabled]):not([tabindex='-1'])," + + "select:not([disabled]):not([tabindex='-1'])," + + "textarea:not([disabled]):not([tabindex='-1'])," + + "*[tabindex]:not([tabindex='-1'])," + + "*[contenteditable]:not([disabled]):not([tabindex='-1'])"; + return _this; + } + Object.defineProperty(WebInitializationHelper.prototype, "isHostOriginTrusted", { + get: function () { + return this._isHostOriginTrustedFunc; + }, + set: function (value) { + this._isHostOriginTrustedFunc = value; + }, + enumerable: true, + configurable: true + }); + WebInitializationHelper.prototype.saveAndSetDialogInfo = function (hostInfoValue) { + function getAppIdFromWindowLocation() { + var xdmInfoValue = OSF.OUtil.parseXdmInfo(true); + if (xdmInfoValue) { + var items = xdmInfoValue.split("|"); + return items[1]; + } + return null; + } + ; + var osfSessionStorage = OSF.OUtil.getSessionStorage(); + if (osfSessionStorage) { + if (!hostInfoValue) { + hostInfoValue = OSF.OUtil.parseHostInfoFromWindowName(true, OSF._OfficeAppFactory.getWindowName()); + } + if (hostInfoValue && hostInfoValue.indexOf("isDialog") > -1) { + var appId = getAppIdFromWindowLocation(); + if (appId != null) { + osfSessionStorage.setItem(appId + "IsDialog", "true"); + } + this._hostInfo.isDialog = true; + return; + } + this._hostInfo.isDialog = osfSessionStorage.getItem(OSF.OUtil.getXdmFieldValue("AppId", false) + "IsDialog") != null ? true : false; + } + }; + WebInitializationHelper.prototype.checkReceiverOriginAndRun = function (funcToRun) { + var me = this; + var parsedHostname = OSF.OUtil.parseUrl(me._webAppState.clientEndPoint.targetUrl, false); + var isHttps = parsedHostname.protocol == "https:"; + var notHttpsErrorMessage = "NotHttps"; + if (me._webAppState.clientEndPoint.hostTrustCheckStatus === 0) { + if (!isHttps) + me._webAppState.clientEndPoint.hostTrustCheckStatus = 2; + if (me._webAppState.clientEndPoint.hostTrustCheckStatus != 2) { + var isOriginValid = OSF.XdmCommunicationManager.isHostNameValidWacDomain(parsedHostname.hostname); + if (me.isHostOriginTrusted) { + isOriginValid = isOriginValid || me.isHostOriginTrusted(parsedHostname.hostname); + } + if (isOriginValid) + me._webAppState.clientEndPoint.hostTrustCheckStatus = 3; + } + } + if (!me._webAppState.clientEndPoint.checkStatusLogged && me._hostInfo != null && me._hostInfo !== undefined) { + OSF.AppTelemetry.onCheckWACHost(me._webAppState.clientEndPoint.hostTrustCheckStatus, me._webAppState.id, me._hostInfo.hostType, me._hostInfo.hostPlatform, me._webAppState.clientEndPoint.targetUrl); + me._webAppState.clientEndPoint.checkStatusLogged = true; + } + if (me._webAppState.clientEndPoint.hostTrustCheckStatus != 3) { + var loadAgaveErrorUX = function () { + var officejsCDNHost = OSF.LoadScriptHelper.getHostBundleJsBasePath().match(/^https?:\/\/[^:/?#]*(?::([0-9]+))?/); + if (officejsCDNHost && officejsCDNHost[0]) { + var agaveErrorUXPath = OSF.LoadScriptHelper.getHostBundleJsBasePath() + 'AgaveErrorUX/index.html#'; + var hashObj = { + error: "NotTrustedWAC", + locale: OSF.getSupportedLocale(me._hostInfo.hostLocale, OSF.ConstantNames.DefaultLocale), + hostname: parsedHostname.hostname, + noHttps: !isHttps, + validate: false + }; + var hostUserTrustIframe = document.createElement("iframe"); + hostUserTrustIframe.style.visibility = "hidden"; + hostUserTrustIframe.style.height = "0"; + hostUserTrustIframe.style.width = "0"; + var hostUserTrustCallback = function (event) { + if ((event.source == hostUserTrustIframe.contentWindow) && + (event.origin == officejsCDNHost[0])) { + try { + var receivedObj = JSON.parse(event.data); + if (receivedObj.hostUserTrusted === true) { + me._webAppState.clientEndPoint.hostTrustCheckStatus = 3; + OSF.OUtil.removeEventListener(window, "message", hostUserTrustCallback); + document.body.removeChild(hostUserTrustIframe); + } + else { + hashObj.validate = false; + window.location.replace(agaveErrorUXPath + encodeURIComponent(JSON.stringify(hashObj))); + } + funcToRun(); + } + catch (e) { + OSF.OUtil.ensureOfficeStringsJs().then(function () { + document.body.innerHTML = Strings.OfficeOM.L_NotTrustedWAC; + }); + } + } + }; + OSF.OUtil.addEventListener(window, "message", hostUserTrustCallback); + hashObj.validate = true; + hostUserTrustIframe.setAttribute('src', agaveErrorUXPath + encodeURIComponent(JSON.stringify(hashObj))); + hostUserTrustIframe.onload = function () { + var postingObj = { + hostname: parsedHostname.hostname, + noHttps: !isHttps + }; + hostUserTrustIframe.contentWindow.postMessage(JSON.stringify(postingObj), officejsCDNHost[0]); + }; + document.body.appendChild(hostUserTrustIframe); + } + else { + OSF.OUtil.ensureOfficeStringsJs().then(function () { + document.body.innerHTML = Strings.OfficeOM.L_NotTrustedWAC; + }); + } + if (OSF.OUtil.checkFlight(2)) { + if (!isHttps) + throw new Error(notHttpsErrorMessage); + } + }; + if (document.body) { + loadAgaveErrorUX(); + } + else { + var checkDone = false; + document.addEventListener('DOMContentLoaded', function () { + if (!checkDone) { + checkDone = true; + loadAgaveErrorUX(); + } + }); + } + } + else { + funcToRun(); + } + }; + WebInitializationHelper.prototype.setAgaveHostCommunication = function () { + try { + var me = this; + var xdmInfoValue = OSF.OUtil.parseXdmInfoWithGivenFragment(false, OSF._OfficeAppFactory.getWindowLocationHash()); + if (!xdmInfoValue) { + xdmInfoValue = OSF.OUtil.parseXdmInfoFromWindowName(false, OSF._OfficeAppFactory.getWindowName()); + } + if (xdmInfoValue) { + var xdmItems = OSF.OUtil.getInfoItems(xdmInfoValue); + if (xdmItems != undefined && xdmItems.length >= 3) { + me._webAppState.conversationID = xdmItems[0]; + me._webAppState.id = xdmItems[1]; + me._webAppState.webAppUrl = xdmItems[2].indexOf(":") >= 0 ? xdmItems[2] : decodeURIComponent(xdmItems[2]); + } + } + me._webAppState.wnd = window.opener != null ? window.opener : window.parent; + var serializerVersion = OSF.OUtil.parseSerializerVersionWithGivenFragment(false, OSF._OfficeAppFactory.getWindowLocationHash()); + if (isNaN(serializerVersion)) { + serializerVersion = OSF.OUtil.parseSerializerVersionFromWindowName(false, OSF._OfficeAppFactory.getWindowName()); + } + me._webAppState.serializerVersion = serializerVersion; + if (this._hostInfo.isDialog && window.opener != null) { + return; + } + me._webAppState.clientEndPoint = OSF.XdmCommunicationManager.connect(me._webAppState.conversationID, me._webAppState.wnd, me._webAppState.webAppUrl, me._webAppState.serializerVersion); + me._webAppState.serviceEndPoint = OSF.XdmCommunicationManager.createServiceEndPoint(me._webAppState.id); + me._webAppState.clientEndPoint.checkReceiverOriginAndRun = function (funcToRun) { + me.checkReceiverOriginAndRun(funcToRun); + }; + var notificationConversationId = me._webAppState.conversationID + OSF.Constants.NotificationConversationIdSuffix; + me._webAppState.serviceEndPoint.registerConversation(notificationConversationId, me._webAppState.webAppUrl); + var notifyAgave = function (params) { + var actionId; + if (typeof params == "string") { + actionId = params; + } + else { + actionId = params[0]; + } + switch (actionId) { + case OSF.AgaveHostAction.Select: + me._webAppState.focused = true; + break; + case OSF.AgaveHostAction.UnSelect: + me._webAppState.focused = false; + break; + case OSF.AgaveHostAction.TabIn: + case OSF.AgaveHostAction.CtrlF6In: + window.focus(); + var list = document.querySelectorAll(me._tabbableElements); + var focused = OSF.OUtil.focusToFirstTabbable(list, false); + if (!focused) { + window.blur(); + me._webAppState.focused = false; + me._webAppState.clientEndPoint.invoke("ContextActivationManager_notifyHost", null, [me._webAppState.id, OSF.AgaveHostAction.ExitNoFocusable]); + } + break; + case OSF.AgaveHostAction.TabInShift: + window.focus(); + var list = document.querySelectorAll(me._tabbableElements); + var focused = OSF.OUtil.focusToFirstTabbable(list, true); + if (!focused) { + window.blur(); + me._webAppState.focused = false; + me._webAppState.clientEndPoint.invoke("ContextActivationManager_notifyHost", null, [me._webAppState.id, OSF.AgaveHostAction.ExitNoFocusableShift]); + } + break; + case OSF.AgaveHostAction.SendMessage: + if (Office.context.messaging.onMessage) { + var message = params[1]; + Office.context.messaging.onMessage(message); + } + break; + case OSF.AgaveHostAction.TaskPaneHeaderButtonClicked: + if (Office.context.ui.taskPaneAction.onHeaderButtonClick) { + Office.context.ui.taskPaneAction.onHeaderButtonClick(); + } + break; + default: + OSF.Utility.trace("actionId " + actionId + " notifyAgave is wrong."); + break; + } + }; + me._webAppState.serviceEndPoint.registerMethod("Office_notifyAgave", notifyAgave, 0, false); + me.addOrRemoveEventListenersForWindow(true); + } + catch (ex) { + if (OSF.AppTelemetry) { + OSF.AppTelemetry.logAppException("Exception thrown in setAgaveHostCommunication. Exception:[" + ex + "]"); + } + throw ex; + } + }; + WebInitializationHelper.prototype.getAppContext = function (wnd, onSuccess, onError) { + var _this = this; + var me = this; + var getInvocationCallbackWebApp = function (errorCode, appContext) { + OSFPerformance.getAppContextXdmEnd = OSFPerformance.now(); + if (appContext._appName === OSF.AppName.ExcelWebApp) { + var serializedSettingsFromHost = appContext._settings; + _this._serializedSettings = {}; + for (var index in serializedSettingsFromHost) { + var setting = serializedSettingsFromHost[index]; + _this._serializedSettings[setting[0]] = setting[1]; + } + } + else { + _this._serializedSettings = appContext._settings; + } + if (!me._hostInfo.isDialog || window.opener == null) { + var pageUrl = window.location.href; + me._webAppState.clientEndPoint.invoke("ContextActivationManager_notifyHost", null, [me._webAppState.id, OSF.AgaveHostAction.UpdateTargetUrl, pageUrl]); + } + if (errorCode === 0 && appContext._id != undefined && appContext._appName != undefined && appContext._appVersion != undefined && appContext._appUILocale != undefined && appContext._dataLocale != undefined && + appContext._docUrl != undefined && appContext._clientMode != undefined && appContext._settings != undefined && appContext._reason != undefined) { + me._appContext = appContext; + var appInstanceId = (appContext._appInstanceId ? appContext._appInstanceId : appContext._id); + var touchEnabled = false; + var commerceAllowed = true; + var minorVersion = 0; + if (appContext._appMinorVersion != undefined) { + minorVersion = appContext._appMinorVersion; + } + var requirementMatrix = undefined; + if (appContext._requirementMatrix != undefined) { + requirementMatrix = appContext._requirementMatrix; + } + appContext.eToken = appContext.eToken ? appContext.eToken : ""; + var settingsFunc = function () { + return _this._serializedSettings; + }; + var returnedContext = new OSF.OfficeAppContext(appContext._id, appContext._appName, appContext._appVersion, appContext._appUILocale, appContext._dataLocale, appContext._docUrl, appContext._clientMode, settingsFunc, appContext._reason, appContext._osfControlType, appContext._eToken, appContext._correlationId, appInstanceId, touchEnabled, commerceAllowed, minorVersion, requirementMatrix, appContext._hostCustomMessage, appContext._hostFullVersion, appContext._clientWindowHeight, appContext._clientWindowWidth, appContext._addinName, appContext._appDomains, appContext._dialogRequirementMatrix, appContext._featureGates, undefined, appContext._initialDisplayMode, appContext._isFromWacAutomation); + onSuccess(returnedContext); + } + else { + var errorMsg = "Function ContextActivationManager_getAppContextAsync call failed. ErrorCode is " + errorCode + ", exception: " + appContext; + if (OSF.AppTelemetry) { + OSF.AppTelemetry.logAppException(errorMsg); + } + onError(errorMsg); + } + }; + try { + var skipSessionStorage = true; + if (this._hostInfo.isDialog && window.opener != null) { + skipSessionStorage = false; + } + var appContext = OSF.OUtil.parseAppContextFromWindowName(skipSessionStorage, OSF._OfficeAppFactory.getWindowName()); + if (appContext) { + getInvocationCallbackWebApp(0, appContext); + } + else { + OSFPerformance.getAppContextXdmStart = OSFPerformance.now(); + this._webAppState.clientEndPoint.invoke("ContextActivationManager_getAppContextAsync", getInvocationCallbackWebApp, this._webAppState.id); + } + } + catch (ex) { + if (OSF.AppTelemetry) { + OSF.AppTelemetry.logAppException("Exception thrown when trying to invoke getAppContextAsync. Exception:[" + ex + "]"); + } + onError(ex); + } + }; + WebInitializationHelper.prototype.createClientHostController = function () { + if (!this._clientHostController) { + if (this._hostInfo.hostType.toLowerCase() === Office.HostType.Outlook.toLowerCase()) { + this._clientHostController = new OSF.WebClientHostController_outlook(this._webAppState); + } + else { + this._clientHostController = new OSF.WebClientHostController(this._webAppState); + } + } + return this._clientHostController; + }; + WebInitializationHelper.prototype.createAsyncMethodExecutor = function () { + return new OSF.WebAsyncMethodExecutor(this._clientHostController); + }; + WebInitializationHelper.prototype.createClientSettingsManager = function () { + return new OSF.WebClientSettingsManager(); + }; + WebInitializationHelper.prototype.addOrRemoveEventListenersForWindow = function (isAdd) { + var me = this; + var onWindowFocus = function () { + if (!me._webAppState.focused) { + me._webAppState.focused = true; + } + me._webAppState.clientEndPoint.invoke("ContextActivationManager_notifyHost", null, [me._webAppState.id, OSF.AgaveHostAction.Select]); + }; + var onWindowBlur = function () { + if (!OSF) { + return; + } + if (me._webAppState.focused) { + me._webAppState.focused = false; + } + me._webAppState.clientEndPoint.invoke("ContextActivationManager_notifyHost", null, [me._webAppState.id, OSF.AgaveHostAction.UnSelect]); + }; + var onWindowKeydown = function (e) { + e.preventDefault = e.preventDefault || function () { + e.returnValue = false; + }; + if (e.keyCode == 117 && (e.ctrlKey || e.metaKey)) { + e.preventDefault(); + var actionId = OSF.AgaveHostAction.CtrlF6Exit; + if (e.shiftKey) { + actionId = OSF.AgaveHostAction.CtrlF6ExitShift; + } + me._webAppState.clientEndPoint.invoke("ContextActivationManager_notifyHost", null, [me._webAppState.id, actionId]); + } + else if (e.keyCode == 9) { + e.preventDefault(); + var allTabbableElements = document.querySelectorAll(me._tabbableElements); + var focused = OSF.OUtil.focusToNextTabbable(allTabbableElements, e.target || e.srcElement, e.shiftKey); + if (!focused) { + if (me._hostInfo.isDialog) { + OSF.OUtil.focusToFirstTabbable(allTabbableElements, e.shiftKey); + } + else { + if (e.shiftKey) { + me._webAppState.clientEndPoint.invoke("ContextActivationManager_notifyHost", null, [me._webAppState.id, OSF.AgaveHostAction.TabExitShift]); + } + else { + me._webAppState.clientEndPoint.invoke("ContextActivationManager_notifyHost", null, [me._webAppState.id, OSF.AgaveHostAction.TabExit]); + } + } + } + } + else if (e.keyCode == 27) { + e.preventDefault(); + me._webAppState.clientEndPoint.invoke("ContextActivationManager_notifyHost", null, [me._webAppState.id, OSF.AgaveHostAction.EscExit]); + } + else if (e.keyCode == 113) { + e.preventDefault(); + me._webAppState.clientEndPoint.invoke("ContextActivationManager_notifyHost", null, [me._webAppState.id, OSF.AgaveHostAction.F2Exit]); + } + }; + var onWindowKeypress = function (e) { + if (e.keyCode == 117 && e.ctrlKey) { + if (e.preventDefault) { + e.preventDefault(); + } + else { + e.returnValue = false; + } + } + }; + if (!OSF.Utility._DebugXdm) { + if (isAdd) { + OSF.OUtil.addEventListener(window, "focus", onWindowFocus); + OSF.OUtil.addEventListener(window, "blur", onWindowBlur); + OSF.OUtil.addEventListener(window, "keydown", onWindowKeydown); + OSF.OUtil.addEventListener(window, "keypress", onWindowKeypress); + } + else { + OSF.OUtil.removeEventListener(window, "focus", onWindowFocus); + OSF.OUtil.removeEventListener(window, "blur", onWindowBlur); + OSF.OUtil.removeEventListener(window, "keydown", onWindowKeydown); + OSF.OUtil.removeEventListener(window, "keypress", onWindowKeypress); + } + } + }; + return WebInitializationHelper; + }(OSF.InitializationHelper)); + OSF.WebInitializationHelper = WebInitializationHelper; +})(OSF || (OSF = {})); +var OSF; +(function (OSF) { + var WebkitClientSettingsManager = (function () { + function WebkitClientSettingsManager(_initializationHelper, _scriptMessager) { + this._initializationHelper = _initializationHelper; + this._scriptMessager = _scriptMessager; + } + WebkitClientSettingsManager.prototype.read = function (onComplete) { + var keys = []; + var values = []; + var initializationHelper = this._initializationHelper; + var onGetAppContextSuccess = function (appContext) { + if (onComplete) { + var serializedSettings = appContext.get_settingsFunc()(); + onComplete(0, serializedSettings); + } + }; + var onGetAppContextError = function (e) { + if (onComplete) { + onComplete(5001, {}); + } + }; + initializationHelper.getAppContext(null, onGetAppContextSuccess, onGetAppContextError); + }; + WebkitClientSettingsManager.prototype.write = function (serializedSettings, onComplete) { + var hostParams = {}; + var keys = []; + var values = []; + for (var key in serializedSettings) { + keys.push(key); + values.push(serializedSettings[key]); + } + hostParams["keys"] = keys; + hostParams["values"] = values; + var onWriteCompleted = function onWriteCompleted(status) { + if (onComplete) { + onComplete(status[0]); + } + }; + this._scriptMessager.invokeMethod(OSF.Webkit.MessageHandlerName, OSF.Webkit.MethodId.WriteSettings, hostParams, onWriteCompleted); + }; + return WebkitClientSettingsManager; + }()); + OSF.WebkitClientSettingsManager = WebkitClientSettingsManager; +})(OSF || (OSF = {})); +var OSF; +(function (OSF) { + var Webkit; + (function (Webkit) { + Webkit.MessageHandlerName = "Agave"; + Webkit.PopupMessageHandlerName = "WefPopupHandler"; + var AppContextProperties; + (function (AppContextProperties) { + AppContextProperties[AppContextProperties["Settings"] = 0] = "Settings"; + AppContextProperties[AppContextProperties["SolutionReferenceId"] = 1] = "SolutionReferenceId"; + AppContextProperties[AppContextProperties["AppType"] = 2] = "AppType"; + AppContextProperties[AppContextProperties["MajorVersion"] = 3] = "MajorVersion"; + AppContextProperties[AppContextProperties["MinorVersion"] = 4] = "MinorVersion"; + AppContextProperties[AppContextProperties["RevisionVersion"] = 5] = "RevisionVersion"; + AppContextProperties[AppContextProperties["APIVersionSequence"] = 6] = "APIVersionSequence"; + AppContextProperties[AppContextProperties["AppCapabilities"] = 7] = "AppCapabilities"; + AppContextProperties[AppContextProperties["APPUILocale"] = 8] = "APPUILocale"; + AppContextProperties[AppContextProperties["AppDataLocale"] = 9] = "AppDataLocale"; + AppContextProperties[AppContextProperties["BindingCount"] = 10] = "BindingCount"; + AppContextProperties[AppContextProperties["DocumentUrl"] = 11] = "DocumentUrl"; + AppContextProperties[AppContextProperties["ActivationMode"] = 12] = "ActivationMode"; + AppContextProperties[AppContextProperties["ControlIntegrationLevel"] = 13] = "ControlIntegrationLevel"; + AppContextProperties[AppContextProperties["SolutionToken"] = 14] = "SolutionToken"; + AppContextProperties[AppContextProperties["APISetVersion"] = 15] = "APISetVersion"; + AppContextProperties[AppContextProperties["CorrelationId"] = 16] = "CorrelationId"; + AppContextProperties[AppContextProperties["InstanceId"] = 17] = "InstanceId"; + AppContextProperties[AppContextProperties["TouchEnabled"] = 18] = "TouchEnabled"; + AppContextProperties[AppContextProperties["CommerceAllowed"] = 19] = "CommerceAllowed"; + AppContextProperties[AppContextProperties["RequirementMatrix"] = 20] = "RequirementMatrix"; + AppContextProperties[AppContextProperties["HostCustomMessage"] = 21] = "HostCustomMessage"; + AppContextProperties[AppContextProperties["HostFullVersion"] = 22] = "HostFullVersion"; + AppContextProperties[AppContextProperties["InitialDisplayMode"] = 23] = "InitialDisplayMode"; + })(AppContextProperties = Webkit.AppContextProperties || (Webkit.AppContextProperties = {})); + var MethodId; + (function (MethodId) { + MethodId[MethodId["Execute"] = 1] = "Execute"; + MethodId[MethodId["RegisterEvent"] = 2] = "RegisterEvent"; + MethodId[MethodId["UnregisterEvent"] = 3] = "UnregisterEvent"; + MethodId[MethodId["WriteSettings"] = 4] = "WriteSettings"; + MethodId[MethodId["GetContext"] = 5] = "GetContext"; + MethodId[MethodId["SendMessage"] = 6] = "SendMessage"; + MethodId[MethodId["MessageParent"] = 7] = "MessageParent"; + })(MethodId = Webkit.MethodId || (Webkit.MethodId = {})); + var WebkitHostController = (function () { + function WebkitHostController(hostScriptProxy) { + this.hostScriptProxy = hostScriptProxy; + this.useFullDialogAPI = !!window._enableFullDialogAPI; + } + WebkitHostController.prototype.execute = function (id, params, callback) { + var hostParams = { + id: id, + apiArgs: params + }; + var agaveResponseCallback = function (payload) { + if (callback) { + var invokeArguments = []; + if (OSF.OUtil.isArray(payload)) { + for (var i = 0; i < payload.length; i++) { + var element = payload[i]; + if (OSF.OUtil.isArray(element)) { + element = new OSF.WebkitSafeArray(element); + } + invokeArguments.unshift(element); + } + } + return callback.apply(null, invokeArguments); + } + }; + this.hostScriptProxy.invokeMethod(OSF.Webkit.MessageHandlerName, OSF.Webkit.MethodId.Execute, hostParams, agaveResponseCallback); + }; + WebkitHostController.prototype.registerEvent = function (id, eventType, targetId, handler, callback) { + var agaveEventHandlerCallback = function (payload) { + var safeArraySource = payload; + var eventId = 0; + if (OSF.OUtil.isArray(payload) && payload.length >= 2) { + safeArraySource = payload[0]; + eventId = payload[1]; + } + if (handler) { + handler(eventId, new OSF.WebkitSafeArray(safeArraySource)); + } + }; + var agaveResponseCallback = function (payload) { + if (callback) { + return callback(new OSF.WebkitSafeArray(payload)); + } + }; + this.hostScriptProxy.registerEvent(OSF.Webkit.MessageHandlerName, OSF.Webkit.MethodId.RegisterEvent, id, targetId, agaveEventHandlerCallback, agaveResponseCallback); + }; + WebkitHostController.prototype.unregisterEvent = function (id, eventType, targetId, callback) { + var agaveResponseCallback = function (response) { + return callback(new OSF.WebkitSafeArray(response)); + }; + this.hostScriptProxy.unregisterEvent(OSF.Webkit.MessageHandlerName, OSF.Webkit.MethodId.UnregisterEvent, id, targetId, agaveResponseCallback); + }; + WebkitHostController.prototype.messageParent = function (params) { + var message = params[OSF.ParameterNames.MessageToParent]; + if (this.useFullDialogAPI) { + this.hostScriptProxy.invokeMethod(OSF.Webkit.MessageHandlerName, OSF.Webkit.MethodId.MessageParent, message, null); + } + else { + var messageObj = { dialogMessage: { messageType: 0, messageContent: message } }; + window.opener.postMessage(JSON.stringify(messageObj), window.location.origin); + } + }; + WebkitHostController.prototype.openDialog = function (id, eventType, targetId, handler, callback) { + if (this.useFullDialogAPI) { + this.registerEvent(id, eventType, targetId, handler, callback); + return; + } + if (WebkitHostController.popup && !WebkitHostController.popup.closed) { + callback(12007); + return; + } + var magicWord = "action=displayDialog"; + WebkitHostController.OpenDialogCallback = undefined; + var fragmentSeparator = '#'; + var callArgs = JSON.parse(targetId); + var callUrl = callArgs.url; + if (!callUrl) { + callback(12003); + return; + } + var urlParts = callUrl.split(fragmentSeparator); + var seperator = "?"; + if (urlParts[0].indexOf("?") > -1) { + seperator = "&"; + } + var width = screen.width * callArgs.width / 100; + var height = screen.height * callArgs.height / 100; + var params = "width=" + width + ", height=" + height; + urlParts[0] = urlParts[0].concat(seperator).concat(magicWord); + var openUrl = urlParts.join(fragmentSeparator); + WebkitHostController.popup = window.open(openUrl, "", params); + function receiveMessage(event) { + if (event.origin == window.location.origin) { + try { + var messageObj = JSON.parse(event.data); + if (messageObj.dialogMessage) { + handler(id, [0, messageObj.dialogMessage.messageContent]); + } + } + catch (e) { + OSF.Utility.trace("messages received cannot be handlered. Message:" + event.data); + } + } + } + WebkitHostController.DialogEventListener = receiveMessage; + function checkWindowClose() { + try { + if (WebkitHostController.popup == null || WebkitHostController.popup.closed) { + window.clearInterval(WebkitHostController.interval); + window.removeEventListener("message", WebkitHostController.DialogEventListener); + WebkitHostController.NotifyError = null; + WebkitHostController.popup = null; + handler(id, [12006]); + } + } + catch (e) { + OSF.Utility.trace("Error happened when popup window closed."); + } + } + WebkitHostController.OpenDialogCallback = function (code) { + if (code == 0) { + window.addEventListener("message", WebkitHostController.DialogEventListener); + WebkitHostController.interval = window.setInterval(checkWindowClose, 1000); + WebkitHostController.NotifyError = function (errorCode) { + handler(id, [errorCode]); + }; + } + callback(code); + }; + }; + WebkitHostController.prototype.closeDialog = function (id, eventType, targetId, callback) { + if (this.useFullDialogAPI) { + this.unregisterEvent(id, eventType, targetId, callback); + } + else { + if (WebkitHostController.popup) { + if (WebkitHostController.interval) { + window.clearInterval(WebkitHostController.interval); + } + WebkitHostController.popup.close(); + WebkitHostController.popup = null; + window.removeEventListener("message", WebkitHostController.DialogEventListener); + WebkitHostController.NotifyError = null; + callback(0); + } + else { + callback(5001); + } + } + }; + WebkitHostController.prototype.sendMessage = function (params) { + var message = params[OSF.ParameterNames.MessageContent]; + if (!isNaN(parseFloat(message)) && isFinite(message)) { + message = message.toString(); + } + this.hostScriptProxy.invokeMethod(OSF.Webkit.MessageHandlerName, OSF.Webkit.MethodId.SendMessage, message, null); + }; + return WebkitHostController; + }()); + Webkit.WebkitHostController = WebkitHostController; + })(Webkit = OSF.Webkit || (OSF.Webkit = {})); +})(OSF || (OSF = {})); +var OSF; +(function (OSF) { + var WebkitInitializationHelper = (function (_super) { + __extends(WebkitInitializationHelper, _super); + function WebkitInitializationHelper(hostInfo, webAppState, context, hostFacade) { + var _this = _super.call(this, hostInfo, webAppState, context, hostFacade) || this; + _this.initializeWebkitMessaging(); + return _this; + } + WebkitInitializationHelper.prototype.initializeWebkitMessaging = function () { + OSF.ScriptMessaging = OSFWebkit.ScriptMessaging; + }; + WebkitInitializationHelper.prototype.getAppContext = function (wnd, onSuccess, onError) { + var _this = this; + var getInvocationCallback = function (appContext) { + var returnedContext; + var appContextProperties = OSF.Webkit.AppContextProperties; + var appType = appContext[appContextProperties.AppType]; + var hostSettings = appContext[appContextProperties.Settings]; + _this._serializedSettings = {}; + var keys = hostSettings[0]; + var values = hostSettings[1]; + for (var index = 0; index < keys.length; index++) { + _this._serializedSettings[keys[index]] = values[index]; + } + var id = appContext[appContextProperties.SolutionReferenceId]; + var version = appContext[appContextProperties.MajorVersion]; + var minorVersion = appContext[appContextProperties.MinorVersion]; + var clientMode = appContext[appContextProperties.AppCapabilities]; + var UILocale = appContext[appContextProperties.APPUILocale]; + var dataLocale = appContext[appContextProperties.AppDataLocale]; + var docUrl = appContext[appContextProperties.DocumentUrl]; + var reason = appContext[appContextProperties.ActivationMode]; + var osfControlType = appContext[appContextProperties.ControlIntegrationLevel]; + var eToken = appContext[appContextProperties.SolutionToken]; + eToken = eToken ? eToken.toString() : ""; + var correlationId = appContext[appContextProperties.CorrelationId]; + var appInstanceId = appContext[appContextProperties.InstanceId]; + var touchEnabled = appContext[appContextProperties.TouchEnabled]; + var commerceAllowed = appContext[appContextProperties.CommerceAllowed]; + var requirementMatrix = appContext[appContextProperties.RequirementMatrix]; + var hostCustomMessage = appContext[appContextProperties.HostCustomMessage]; + var hostFullVersion = appContext[appContextProperties.HostFullVersion]; + var initialDisplayMode = appContext[appContextProperties.InitialDisplayMode]; + var settingsFunc = function () { + return _this._serializedSettings; + }; + returnedContext = new OSF.OfficeAppContext(id, appType, version, UILocale, dataLocale, docUrl, clientMode, settingsFunc, reason, osfControlType, eToken, correlationId, appInstanceId, touchEnabled, commerceAllowed, minorVersion, requirementMatrix, hostCustomMessage, hostFullVersion, undefined, undefined, undefined, undefined, undefined, undefined, undefined, initialDisplayMode, undefined); + onSuccess(returnedContext); + }; + var handler; + if (this._hostInfo.isDialog && window.webkit.messageHandlers[OSF.Webkit.PopupMessageHandlerName]) { + handler = OSF.Webkit.PopupMessageHandlerName; + } + else { + handler = OSF.Webkit.MessageHandlerName; + } + OSF.ScriptMessaging.GetScriptMessenger().invokeMethod(handler, OSF.Webkit.MethodId.GetContext, [], getInvocationCallback); + }; + WebkitInitializationHelper.prototype.createClientHostController = function () { + if (!this._clientHostController) { + this._clientHostController = new OSF.Webkit.WebkitHostController(OSF.ScriptMessaging.GetScriptMessenger()); + } + return this._clientHostController; + }; + WebkitInitializationHelper.prototype.createAsyncMethodExecutor = function () { + return new OSF.SafeArrayAsyncMethodExecutor(this.createClientHostController()); + }; + WebkitInitializationHelper.prototype.createClientSettingsManager = function () { + return new OSF.WebkitClientSettingsManager(this, OSF.ScriptMessaging.GetScriptMessenger()); + }; + return WebkitInitializationHelper; + }(OSF.InitializationHelper)); + OSF.WebkitInitializationHelper = WebkitInitializationHelper; +})(OSF || (OSF = {})); +var OSF; +(function (OSF) { + var WebkitSafeArray = (function () { + function WebkitSafeArray(data) { + this.data = data; + this.safeArrayFlag = this.isSafeArray(data); + } + WebkitSafeArray.prototype.dimensions = function () { + var dimensions = 0; + if (this.safeArrayFlag) { + dimensions = this.data[0][0]; + } + else if (this.isArray()) { + dimensions = 2; + } + return dimensions; + }; + WebkitSafeArray.prototype.getItem = function () { + var array = []; + var element = null; + if (this.safeArrayFlag) { + array = this.toArray(); + } + else { + array = this.data; + } + element = array; + for (var i = 0; i < arguments.length; i++) { + element = element[arguments[i]]; + } + return element; + }; + WebkitSafeArray.prototype.lbound = function (dimension) { + return 0; + }; + WebkitSafeArray.prototype.ubound = function (dimension) { + var ubound = 0; + if (this.safeArrayFlag) { + ubound = this.data[0][dimension]; + } + else if (this.isArray()) { + if (dimension == 1) { + return this.data.length; + } + else if (dimension == 2) { + if (OSF.OUtil.isArray(this.data[0])) { + return this.data[0].length; + } + else if (this.data[0] != null) { + return 1; + } + } + } + return ubound; + }; + WebkitSafeArray.prototype.toArray = function () { + if (this.isArray() == false) { + return this.data; + } + var arr = []; + var startingIndex = this.safeArrayFlag ? 1 : 0; + for (var i = startingIndex; i < this.data.length; i++) { + var element = this.data[i]; + if (this.isSafeArray(element)) { + arr.push(new WebkitSafeArray(element)); + } + else { + arr.push(element); + } + } + return arr; + }; + WebkitSafeArray.prototype.isArray = function () { + return OSF.OUtil.isArray(this.data); + }; + WebkitSafeArray.prototype.isSafeArray = function (obj) { + var isSafeArray = false; + if (OSF.OUtil.isArray(obj) && OSF.OUtil.isArray(obj[0])) { + var bounds = obj[0]; + var dimensions = bounds[0]; + if (bounds.length != dimensions + 1) { + return false; + } + var expectedArraySize = 1; + for (var i = 1; i < bounds.length; i++) { + var dimension = bounds[i]; + if (isFinite(dimension) == false) { + return false; + } + expectedArraySize = expectedArraySize * dimension; + } + expectedArraySize++; + isSafeArray = (expectedArraySize == obj.length); + } + return isSafeArray; + }; + return WebkitSafeArray; + }()); + OSF.WebkitSafeArray = WebkitSafeArray; +})(OSF || (OSF = {})); +var OSFWebkit; +(function (OSFWebkit) { + var ScriptMessaging; + (function (ScriptMessaging) { + var scriptMessenger = null; + function agaveHostCallback(callbackId, params) { + scriptMessenger.agaveHostCallback(callbackId, params); + } + ScriptMessaging.agaveHostCallback = agaveHostCallback; + function agaveHostEventCallback(callbackId, params) { + scriptMessenger.agaveHostEventCallback(callbackId, params); + } + ScriptMessaging.agaveHostEventCallback = agaveHostEventCallback; + function GetScriptMessenger() { + if (scriptMessenger == null) { + scriptMessenger = new WebkitScriptMessaging("OSF.ScriptMessaging.agaveHostCallback", "OSF.ScriptMessaging.agaveHostEventCallback"); + } + return scriptMessenger; + } + ScriptMessaging.GetScriptMessenger = GetScriptMessenger; + var EventHandlerCallback = (function () { + function EventHandlerCallback(id, targetId, handler) { + this.id = id; + this.targetId = targetId; + this.handler = handler; + } + return EventHandlerCallback; + }()); + var WebkitScriptMessaging = (function () { + function WebkitScriptMessaging(methodCallbackName, eventCallbackName) { + this.callingIndex = 0; + this.callbackList = {}; + this.eventHandlerList = {}; + this.asyncMethodCallbackFunctionName = methodCallbackName; + this.eventCallbackFunctionName = eventCallbackName; + this.conversationId = WebkitScriptMessaging.getCurrentTimeMS().toString(); + } + WebkitScriptMessaging.prototype.invokeMethod = function (handlerName, methodId, params, callback) { + var messagingArgs = {}; + this.postWebkitMessage(messagingArgs, handlerName, methodId, params, callback); + }; + WebkitScriptMessaging.prototype.registerEvent = function (handlerName, methodId, dispId, targetId, handler, callback) { + var messagingArgs = { + eventCallbackFunction: this.eventCallbackFunctionName + }; + var hostArgs = { + id: dispId, + targetId: targetId + }; + var correlationId = this.postWebkitMessage(messagingArgs, handlerName, methodId, hostArgs, callback); + this.eventHandlerList[correlationId] = new EventHandlerCallback(dispId, targetId, handler); + }; + WebkitScriptMessaging.prototype.unregisterEvent = function (handlerName, methodId, dispId, targetId, callback) { + var hostArgs = { + id: dispId, + targetId: targetId + }; + for (var key in this.eventHandlerList) { + if (this.eventHandlerList.hasOwnProperty(key)) { + var eventCallback = this.eventHandlerList[key]; + if (eventCallback.id == dispId && eventCallback.targetId == targetId) { + delete this.eventHandlerList[key]; + } + } + } + this.invokeMethod(handlerName, methodId, hostArgs, callback); + }; + WebkitScriptMessaging.prototype.agaveHostCallback = function (callbackId, params) { + var callbackFunction = this.callbackList[callbackId]; + if (callbackFunction) { + var callbacksDone = callbackFunction(params); + if (callbacksDone === undefined || callbacksDone === true) { + delete this.callbackList[callbackId]; + } + } + }; + WebkitScriptMessaging.prototype.agaveHostEventCallback = function (callbackId, params) { + var eventCallback = this.eventHandlerList[callbackId]; + if (eventCallback) { + eventCallback.handler(params); + } + }; + WebkitScriptMessaging.prototype.postWebkitMessage = function (messagingArgs, handlerName, methodId, params, callback) { + messagingArgs.methodId = methodId; + messagingArgs.params = params; + var correlationId = ""; + if (callback) { + correlationId = this.generateCorrelationId(); + this.callbackList[correlationId] = callback; + messagingArgs.callbackId = correlationId; + messagingArgs.callbackFunction = this.asyncMethodCallbackFunctionName; + } + var invokePostMessage = function () { + window.webkit.messageHandlers[handlerName].postMessage(JSON.stringify(messagingArgs)); + }; + var currentTimestamp = WebkitScriptMessaging.getCurrentTimeMS(); + if (this.lastMessageTimestamp == null || (currentTimestamp - this.lastMessageTimestamp >= WebkitScriptMessaging.MESSAGE_TIME_DELTA)) { + invokePostMessage(); + this.lastMessageTimestamp = currentTimestamp; + } + else { + this.lastMessageTimestamp += WebkitScriptMessaging.MESSAGE_TIME_DELTA; + setTimeout(function () { + invokePostMessage(); + }, this.lastMessageTimestamp - currentTimestamp); + } + return correlationId; + }; + WebkitScriptMessaging.prototype.generateCorrelationId = function () { + ++this.callingIndex; + return this.conversationId + this.callingIndex; + }; + WebkitScriptMessaging.getCurrentTimeMS = function () { + return (new Date).getTime(); + }; + WebkitScriptMessaging.MESSAGE_TIME_DELTA = 10; + return WebkitScriptMessaging; + }()); + })(ScriptMessaging = OSFWebkit.ScriptMessaging || (OSFWebkit.ScriptMessaging = {})); +})(OSFWebkit || (OSFWebkit = {})); +var OSF; +(function (OSF) { + var Win32RichClientHostController = (function (_super) { + __extends(Win32RichClientHostController, _super); + function Win32RichClientHostController() { + return _super !== null && _super.apply(this, arguments) || this; + } + Win32RichClientHostController.prototype.messageParent = function (params) { + var message = params[OSF.ParameterNames.MessageToParent]; + window.external.MessageParent(message); + }; + Win32RichClientHostController.prototype.openDialog = function (id, eventType, targetId, handler, callback) { + this.registerEvent(id, eventType, targetId, handler, callback); + }; + Win32RichClientHostController.prototype.closeDialog = function (id, eventType, targetId, callback) { + this.unregisterEvent(id, eventType, targetId, callback); + }; + Win32RichClientHostController.prototype.sendMessage = function (params) { + var message = params[OSF.ParameterNames.MessageContent]; + window.external.MessageChild(message); + }; + return Win32RichClientHostController; + }(OSF.RichClientHostController)); + OSF.Win32RichClientHostController = Win32RichClientHostController; +})(OSF || (OSF = {})); +var Office; +(function (Office) { + var _Internal; + (function (_Internal) { + var PromiseImpl; + (function (PromiseImpl) { + function Init() { + return (function () { + "use strict"; + function lib$es6$promise$utils$$objectOrFunction(x) { + return typeof x === 'function' || (typeof x === 'object' && x !== null); + } + function lib$es6$promise$utils$$isFunction(x) { + return typeof x === 'function'; + } + function lib$es6$promise$utils$$isMaybeThenable(x) { + return typeof x === 'object' && x !== null; + } + var lib$es6$promise$utils$$_isArray; + if (!Array.isArray) { + lib$es6$promise$utils$$_isArray = function (x) { + return Object.prototype.toString.call(x) === '[object Array]'; + }; + } + else { + lib$es6$promise$utils$$_isArray = Array.isArray; + } + var lib$es6$promise$utils$$isArray = lib$es6$promise$utils$$_isArray; + var lib$es6$promise$asap$$len = 0; + var lib$es6$promise$asap$$toString = {}.toString; + var lib$es6$promise$asap$$vertxNext; + var lib$es6$promise$asap$$customSchedulerFn; + var lib$es6$promise$asap$$asap = function asap(callback, arg) { + lib$es6$promise$asap$$queue[lib$es6$promise$asap$$len] = callback; + lib$es6$promise$asap$$queue[lib$es6$promise$asap$$len + 1] = arg; + lib$es6$promise$asap$$len += 2; + if (lib$es6$promise$asap$$len === 2) { + if (lib$es6$promise$asap$$customSchedulerFn) { + lib$es6$promise$asap$$customSchedulerFn(lib$es6$promise$asap$$flush); + } + else { + lib$es6$promise$asap$$scheduleFlush(); + } + } + }; + function lib$es6$promise$asap$$setScheduler(scheduleFn) { + lib$es6$promise$asap$$customSchedulerFn = scheduleFn; + } + function lib$es6$promise$asap$$setAsap(asapFn) { + lib$es6$promise$asap$$asap = asapFn; + } + var lib$es6$promise$asap$$browserWindow = (typeof window !== 'undefined') ? window : undefined; + var lib$es6$promise$asap$$browserGlobal = lib$es6$promise$asap$$browserWindow || {}; + var lib$es6$promise$asap$$BrowserMutationObserver = lib$es6$promise$asap$$browserGlobal.MutationObserver || lib$es6$promise$asap$$browserGlobal.WebKitMutationObserver; + var lib$es6$promise$asap$$isNode = typeof process !== 'undefined' && {}.toString.call(process) === '[object process]'; + var lib$es6$promise$asap$$isWorker = typeof Uint8ClampedArray !== 'undefined' && + typeof importScripts !== 'undefined' && + typeof MessageChannel !== 'undefined'; + function lib$es6$promise$asap$$useNextTick() { + var nextTick = process.nextTick; + var version = process.versions.node.match(/^(?:(\d+)\.)?(?:(\d+)\.)?(\*|\d+)$/); + if (Array.isArray(version) && version[1] === '0' && version[2] === '10') { + nextTick = setImmediate; + } + return function () { + nextTick(lib$es6$promise$asap$$flush); + }; + } + function lib$es6$promise$asap$$useVertxTimer() { + return function () { + lib$es6$promise$asap$$vertxNext(lib$es6$promise$asap$$flush); + }; + } + function lib$es6$promise$asap$$useMutationObserver() { + var iterations = 0; + var observer = new lib$es6$promise$asap$$BrowserMutationObserver(lib$es6$promise$asap$$flush); + var node = document.createTextNode(''); + observer.observe(node, { characterData: true }); + return function () { + node.data = (iterations = ++iterations % 2); + }; + } + function lib$es6$promise$asap$$useMessageChannel() { + var channel = new MessageChannel(); + channel.port1.onmessage = lib$es6$promise$asap$$flush; + return function () { + channel.port2.postMessage(0); + }; + } + function lib$es6$promise$asap$$useSetTimeout() { + return function () { + setTimeout(lib$es6$promise$asap$$flush, 1); + }; + } + var lib$es6$promise$asap$$queue = new Array(1000); + function lib$es6$promise$asap$$flush() { + for (var i = 0; i < lib$es6$promise$asap$$len; i += 2) { + var callback = lib$es6$promise$asap$$queue[i]; + var arg = lib$es6$promise$asap$$queue[i + 1]; + callback(arg); + lib$es6$promise$asap$$queue[i] = undefined; + lib$es6$promise$asap$$queue[i + 1] = undefined; + } + lib$es6$promise$asap$$len = 0; + } + var lib$es6$promise$asap$$scheduleFlush; + if (lib$es6$promise$asap$$isNode) { + lib$es6$promise$asap$$scheduleFlush = lib$es6$promise$asap$$useNextTick(); + } + else if (lib$es6$promise$asap$$isWorker) { + lib$es6$promise$asap$$scheduleFlush = lib$es6$promise$asap$$useMessageChannel(); + } + else { + lib$es6$promise$asap$$scheduleFlush = lib$es6$promise$asap$$useSetTimeout(); + } + function lib$es6$promise$$internal$$noop() { } + var lib$es6$promise$$internal$$PENDING = void 0; + var lib$es6$promise$$internal$$FULFILLED = 1; + var lib$es6$promise$$internal$$REJECTED = 2; + var lib$es6$promise$$internal$$GET_THEN_ERROR = new lib$es6$promise$$internal$$ErrorObject(); + function lib$es6$promise$$internal$$selfFullfillment() { + return new TypeError("You cannot resolve a promise with itself"); + } + function lib$es6$promise$$internal$$cannotReturnOwn() { + return new TypeError('A promises callback cannot return that same promise.'); + } + function lib$es6$promise$$internal$$getThen(promise) { + try { + return promise.then; + } + catch (error) { + lib$es6$promise$$internal$$GET_THEN_ERROR.error = error; + return lib$es6$promise$$internal$$GET_THEN_ERROR; + } + } + function lib$es6$promise$$internal$$tryThen(then, value, fulfillmentHandler, rejectionHandler) { + try { + then.call(value, fulfillmentHandler, rejectionHandler); + } + catch (e) { + return e; + } + } + function lib$es6$promise$$internal$$handleForeignThenable(promise, thenable, then) { + lib$es6$promise$asap$$asap(function (promise) { + var sealed = false; + var error = lib$es6$promise$$internal$$tryThen(then, thenable, function (value) { + if (sealed) { + return; + } + sealed = true; + if (thenable !== value) { + lib$es6$promise$$internal$$resolve(promise, value); + } + else { + lib$es6$promise$$internal$$fulfill(promise, value); + } + }, function (reason) { + if (sealed) { + return; + } + sealed = true; + lib$es6$promise$$internal$$reject(promise, reason); + }, 'Settle: ' + (promise._label || ' unknown promise')); + if (!sealed && error) { + sealed = true; + lib$es6$promise$$internal$$reject(promise, error); + } + }, promise); + } + function lib$es6$promise$$internal$$handleOwnThenable(promise, thenable) { + if (thenable._state === lib$es6$promise$$internal$$FULFILLED) { + lib$es6$promise$$internal$$fulfill(promise, thenable._result); + } + else if (thenable._state === lib$es6$promise$$internal$$REJECTED) { + lib$es6$promise$$internal$$reject(promise, thenable._result); + } + else { + lib$es6$promise$$internal$$subscribe(thenable, undefined, function (value) { + lib$es6$promise$$internal$$resolve(promise, value); + }, function (reason) { + lib$es6$promise$$internal$$reject(promise, reason); + }); + } + } + function lib$es6$promise$$internal$$handleMaybeThenable(promise, maybeThenable) { + if (maybeThenable.constructor === promise.constructor) { + lib$es6$promise$$internal$$handleOwnThenable(promise, maybeThenable); + } + else { + var then = lib$es6$promise$$internal$$getThen(maybeThenable); + if (then === lib$es6$promise$$internal$$GET_THEN_ERROR) { + lib$es6$promise$$internal$$reject(promise, lib$es6$promise$$internal$$GET_THEN_ERROR.error); + } + else if (then === undefined) { + lib$es6$promise$$internal$$fulfill(promise, maybeThenable); + } + else if (lib$es6$promise$utils$$isFunction(then)) { + lib$es6$promise$$internal$$handleForeignThenable(promise, maybeThenable, then); + } + else { + lib$es6$promise$$internal$$fulfill(promise, maybeThenable); + } + } + } + function lib$es6$promise$$internal$$resolve(promise, value) { + if (promise === value) { + lib$es6$promise$$internal$$reject(promise, lib$es6$promise$$internal$$selfFullfillment()); + } + else if (lib$es6$promise$utils$$objectOrFunction(value)) { + lib$es6$promise$$internal$$handleMaybeThenable(promise, value); + } + else { + lib$es6$promise$$internal$$fulfill(promise, value); + } + } + function lib$es6$promise$$internal$$publishRejection(promise) { + if (promise._onerror) { + promise._onerror(promise._result); + } + lib$es6$promise$$internal$$publish(promise); + } + function lib$es6$promise$$internal$$fulfill(promise, value) { + if (promise._state !== lib$es6$promise$$internal$$PENDING) { + return; + } + promise._result = value; + promise._state = lib$es6$promise$$internal$$FULFILLED; + if (promise._subscribers.length !== 0) { + lib$es6$promise$asap$$asap(lib$es6$promise$$internal$$publish, promise); + } + } + function lib$es6$promise$$internal$$reject(promise, reason) { + if (promise._state !== lib$es6$promise$$internal$$PENDING) { + return; + } + promise._state = lib$es6$promise$$internal$$REJECTED; + promise._result = reason; + lib$es6$promise$asap$$asap(lib$es6$promise$$internal$$publishRejection, promise); + } + function lib$es6$promise$$internal$$subscribe(parent, child, onFulfillment, onRejection) { + var subscribers = parent._subscribers; + var length = subscribers.length; + parent._onerror = null; + subscribers[length] = child; + subscribers[length + lib$es6$promise$$internal$$FULFILLED] = onFulfillment; + subscribers[length + lib$es6$promise$$internal$$REJECTED] = onRejection; + if (length === 0 && parent._state) { + lib$es6$promise$asap$$asap(lib$es6$promise$$internal$$publish, parent); + } + } + function lib$es6$promise$$internal$$publish(promise) { + var subscribers = promise._subscribers; + var settled = promise._state; + if (subscribers.length === 0) { + return; + } + var child, callback, detail = promise._result; + for (var i = 0; i < subscribers.length; i += 3) { + child = subscribers[i]; + callback = subscribers[i + settled]; + if (child) { + lib$es6$promise$$internal$$invokeCallback(settled, child, callback, detail); + } + else { + callback(detail); + } + } + promise._subscribers.length = 0; + } + function lib$es6$promise$$internal$$ErrorObject() { + this.error = null; + } + var lib$es6$promise$$internal$$TRY_CATCH_ERROR = new lib$es6$promise$$internal$$ErrorObject(); + function lib$es6$promise$$internal$$tryCatch(callback, detail) { + try { + return callback(detail); + } + catch (e) { + lib$es6$promise$$internal$$TRY_CATCH_ERROR.error = e; + return lib$es6$promise$$internal$$TRY_CATCH_ERROR; + } + } + function lib$es6$promise$$internal$$invokeCallback(settled, promise, callback, detail) { + var hasCallback = lib$es6$promise$utils$$isFunction(callback), value, error, succeeded, failed; + if (hasCallback) { + value = lib$es6$promise$$internal$$tryCatch(callback, detail); + if (value === lib$es6$promise$$internal$$TRY_CATCH_ERROR) { + failed = true; + error = value.error; + value = null; + } + else { + succeeded = true; + } + if (promise === value) { + lib$es6$promise$$internal$$reject(promise, lib$es6$promise$$internal$$cannotReturnOwn()); + return; + } + } + else { + value = detail; + succeeded = true; + } + if (promise._state !== lib$es6$promise$$internal$$PENDING) { + } + else if (hasCallback && succeeded) { + lib$es6$promise$$internal$$resolve(promise, value); + } + else if (failed) { + lib$es6$promise$$internal$$reject(promise, error); + } + else if (settled === lib$es6$promise$$internal$$FULFILLED) { + lib$es6$promise$$internal$$fulfill(promise, value); + } + else if (settled === lib$es6$promise$$internal$$REJECTED) { + lib$es6$promise$$internal$$reject(promise, value); + } + } + function lib$es6$promise$$internal$$initializePromise(promise, resolver) { + try { + resolver(function resolvePromise(value) { + lib$es6$promise$$internal$$resolve(promise, value); + }, function rejectPromise(reason) { + lib$es6$promise$$internal$$reject(promise, reason); + }); + } + catch (e) { + lib$es6$promise$$internal$$reject(promise, e); + } + } + function lib$es6$promise$enumerator$$Enumerator(Constructor, input) { + var enumerator = this; + enumerator._instanceConstructor = Constructor; + enumerator.promise = new Constructor(lib$es6$promise$$internal$$noop); + if (enumerator._validateInput(input)) { + enumerator._input = input; + enumerator.length = input.length; + enumerator._remaining = input.length; + enumerator._init(); + if (enumerator.length === 0) { + lib$es6$promise$$internal$$fulfill(enumerator.promise, enumerator._result); + } + else { + enumerator.length = enumerator.length || 0; + enumerator._enumerate(); + if (enumerator._remaining === 0) { + lib$es6$promise$$internal$$fulfill(enumerator.promise, enumerator._result); + } + } + } + else { + lib$es6$promise$$internal$$reject(enumerator.promise, enumerator._validationError()); + } + } + lib$es6$promise$enumerator$$Enumerator.prototype._validateInput = function (input) { + return lib$es6$promise$utils$$isArray(input); + }; + lib$es6$promise$enumerator$$Enumerator.prototype._validationError = function () { + return new Error('Array Methods must be provided an Array'); + }; + lib$es6$promise$enumerator$$Enumerator.prototype._init = function () { + this._result = new Array(this.length); + }; + var lib$es6$promise$enumerator$$default = lib$es6$promise$enumerator$$Enumerator; + lib$es6$promise$enumerator$$Enumerator.prototype._enumerate = function () { + var enumerator = this; + var length = enumerator.length; + var promise = enumerator.promise; + var input = enumerator._input; + for (var i = 0; promise._state === lib$es6$promise$$internal$$PENDING && i < length; i++) { + enumerator._eachEntry(input[i], i); + } + }; + lib$es6$promise$enumerator$$Enumerator.prototype._eachEntry = function (entry, i) { + var enumerator = this; + var c = enumerator._instanceConstructor; + if (lib$es6$promise$utils$$isMaybeThenable(entry)) { + if (entry.constructor === c && entry._state !== lib$es6$promise$$internal$$PENDING) { + entry._onerror = null; + enumerator._settledAt(entry._state, i, entry._result); + } + else { + enumerator._willSettleAt(c.resolve(entry), i); + } + } + else { + enumerator._remaining--; + enumerator._result[i] = entry; + } + }; + lib$es6$promise$enumerator$$Enumerator.prototype._settledAt = function (state, i, value) { + var enumerator = this; + var promise = enumerator.promise; + if (promise._state === lib$es6$promise$$internal$$PENDING) { + enumerator._remaining--; + if (state === lib$es6$promise$$internal$$REJECTED) { + lib$es6$promise$$internal$$reject(promise, value); + } + else { + enumerator._result[i] = value; + } + } + if (enumerator._remaining === 0) { + lib$es6$promise$$internal$$fulfill(promise, enumerator._result); + } + }; + lib$es6$promise$enumerator$$Enumerator.prototype._willSettleAt = function (promise, i) { + var enumerator = this; + lib$es6$promise$$internal$$subscribe(promise, undefined, function (value) { + enumerator._settledAt(lib$es6$promise$$internal$$FULFILLED, i, value); + }, function (reason) { + enumerator._settledAt(lib$es6$promise$$internal$$REJECTED, i, reason); + }); + }; + function lib$es6$promise$promise$all$$all(entries) { + return new lib$es6$promise$enumerator$$default(this, entries).promise; + } + var lib$es6$promise$promise$all$$default = lib$es6$promise$promise$all$$all; + function lib$es6$promise$promise$race$$race(entries) { + var Constructor = this; + var promise = new Constructor(lib$es6$promise$$internal$$noop); + if (!lib$es6$promise$utils$$isArray(entries)) { + lib$es6$promise$$internal$$reject(promise, new TypeError('You must pass an array to race.')); + return promise; + } + var length = entries.length; + function onFulfillment(value) { + lib$es6$promise$$internal$$resolve(promise, value); + } + function onRejection(reason) { + lib$es6$promise$$internal$$reject(promise, reason); + } + for (var i = 0; promise._state === lib$es6$promise$$internal$$PENDING && i < length; i++) { + lib$es6$promise$$internal$$subscribe(Constructor.resolve(entries[i]), undefined, onFulfillment, onRejection); + } + return promise; + } + var lib$es6$promise$promise$race$$default = lib$es6$promise$promise$race$$race; + function lib$es6$promise$promise$resolve$$resolve(object) { + var Constructor = this; + if (object && typeof object === 'object' && object.constructor === Constructor) { + return object; + } + var promise = new Constructor(lib$es6$promise$$internal$$noop); + lib$es6$promise$$internal$$resolve(promise, object); + return promise; + } + var lib$es6$promise$promise$resolve$$default = lib$es6$promise$promise$resolve$$resolve; + function lib$es6$promise$promise$reject$$reject(reason) { + var Constructor = this; + var promise = new Constructor(lib$es6$promise$$internal$$noop); + lib$es6$promise$$internal$$reject(promise, reason); + return promise; + } + var lib$es6$promise$promise$reject$$default = lib$es6$promise$promise$reject$$reject; + var lib$es6$promise$promise$$counter = 0; + function lib$es6$promise$promise$$needsResolver() { + throw new TypeError('You must pass a resolver function as the first argument to the promise constructor'); + } + function lib$es6$promise$promise$$needsNew() { + throw new TypeError("Failed to construct 'Promise': Please use the 'new' operator, this object constructor cannot be called as a function."); + } + var lib$es6$promise$promise$$default = lib$es6$promise$promise$$Promise; + function lib$es6$promise$promise$$Promise(resolver) { + this._id = lib$es6$promise$promise$$counter++; + this._state = undefined; + this._result = undefined; + this._subscribers = []; + if (lib$es6$promise$$internal$$noop !== resolver) { + if (!lib$es6$promise$utils$$isFunction(resolver)) { + lib$es6$promise$promise$$needsResolver(); + } + if (!(this instanceof lib$es6$promise$promise$$Promise)) { + lib$es6$promise$promise$$needsNew(); + } + lib$es6$promise$$internal$$initializePromise(this, resolver); + } + } + lib$es6$promise$promise$$Promise.all = lib$es6$promise$promise$all$$default; + lib$es6$promise$promise$$Promise.race = lib$es6$promise$promise$race$$default; + lib$es6$promise$promise$$Promise.resolve = lib$es6$promise$promise$resolve$$default; + lib$es6$promise$promise$$Promise.reject = lib$es6$promise$promise$reject$$default; + lib$es6$promise$promise$$Promise._setScheduler = lib$es6$promise$asap$$setScheduler; + lib$es6$promise$promise$$Promise._setAsap = lib$es6$promise$asap$$setAsap; + lib$es6$promise$promise$$Promise._asap = lib$es6$promise$asap$$asap; + lib$es6$promise$promise$$Promise.prototype = { + constructor: lib$es6$promise$promise$$Promise, + then: function (onFulfillment, onRejection) { + var parent = this; + var state = parent._state; + if (state === lib$es6$promise$$internal$$FULFILLED && !onFulfillment || state === lib$es6$promise$$internal$$REJECTED && !onRejection) { + return this; + } + var child = new this.constructor(lib$es6$promise$$internal$$noop); + var result = parent._result; + if (state) { + var callback = arguments[state - 1]; + lib$es6$promise$asap$$asap(function () { + lib$es6$promise$$internal$$invokeCallback(state, child, callback, result); + }); + } + else { + lib$es6$promise$$internal$$subscribe(parent, child, onFulfillment, onRejection); + } + return child; + }, + 'catch': function (onRejection) { + return this.then(null, onRejection); + } + }; + return lib$es6$promise$promise$$default; + }).call(this); + } + PromiseImpl.Init = Init; + })(PromiseImpl = _Internal.PromiseImpl || (_Internal.PromiseImpl = {})); + })(_Internal = Office._Internal || (Office._Internal = {})); + (function (_Internal) { + function isEdgeLessThan14() { + var userAgent = window.navigator.userAgent; + var versionIdx = userAgent.indexOf("Edge/"); + if (versionIdx >= 0) { + userAgent = userAgent.substring(versionIdx + 5, userAgent.length); + if (userAgent < "14.14393") + return true; + else + return false; + } + return false; + } + function determinePromise() { + if (typeof (window) === "undefined" && typeof (Promise) === "function") { + return Promise; + } + if (typeof (window) !== "undefined") { + if (window.Promise) { + return window.Promise; + } + else { + var ret = _Internal.PromiseImpl.Init(); + window.Promise = ret; + return ret; + } + } + } + _Internal.OfficePromise = determinePromise(); + })(_Internal = Office._Internal || (Office._Internal = {})); + Office.OfficePromise = _Internal.OfficePromise; + Office.Promise = Office.OfficePromise; +})(Office || (Office = {})); +var OSF; +(function (OSF) { + var AppTelemetry; + (function (AppTelemetry) { + var appInfo; + var sessionId = OSF.OUtil.Guid.generateNewGuid(); + var osfControlAppCorrelationId = ""; + var omexDomainRegex = new RegExp("^https?://store\\.office(ppe|-int)?\\.com/", "i"); + AppTelemetry.enableTelemetry = true; + var AppInfo = (function () { + function AppInfo() { + } + return AppInfo; + }()); + AppTelemetry.AppInfo = AppInfo; + var AppStorage = (function () { + function AppStorage() { + this.clientIDKey = "Office API client"; + this.logIdSetKey = "Office App Log Id Set"; + } + AppStorage.prototype.getClientId = function () { + var clientId = this.getValue(this.clientIDKey); + if (!clientId || clientId.length <= 0 || clientId.length > 40) { + clientId = OSF.OUtil.Guid.generateNewGuid(); + this.setValue(this.clientIDKey, clientId); + } + return clientId; + }; + AppStorage.prototype.getValue = function (key) { + var osfLocalStorage = OSF.OUtil.getLocalStorage(); + var value = ""; + if (osfLocalStorage) { + value = osfLocalStorage.getItem(key); + } + return value; + }; + AppStorage.prototype.setValue = function (key, value) { + var osfLocalStorage = OSF.OUtil.getLocalStorage(); + if (osfLocalStorage) { + osfLocalStorage.setItem(key, value); + } + }; + return AppStorage; + }()); + function trimStringToLowerCase(input) { + if (input) { + input = input.replace(/[{}]/g, "").toLowerCase(); + } + return (input || ""); + } + function initialize(context) { + if (!AppTelemetry.enableTelemetry) { + return; + } + if (appInfo) { + return; + } + appInfo = new AppInfo(); + if (context.get_hostFullVersion()) { + appInfo.hostVersion = context.get_hostFullVersion(); + } + else { + appInfo.hostVersion = context.get_appVersion(); + } + appInfo.appId = context.get_id(); + appInfo.host = "" + context.get_appName(); + appInfo.browser = window.navigator.userAgent; + appInfo.correlationId = trimStringToLowerCase(context.get_correlationId()); + appInfo.clientId = (new AppStorage()).getClientId(); + appInfo.appInstanceId = context.get_appInstanceId(); + if (appInfo.appInstanceId) { + appInfo.appInstanceId = appInfo.appInstanceId.replace(/[{}]/g, "").toLowerCase(); + } + appInfo.message = context.get_hostCustomMessage(); + appInfo.officeJSVersion = "16.0"; + appInfo.hostJSVersion = "16.0"; + if (context._wacHostEnvironment) { + appInfo.wacHostEnvironment = context._wacHostEnvironment; + } + var isFromWacAutomation = context.get_isFromWacAutomation(); + if (isFromWacAutomation !== undefined && isFromWacAutomation !== null) { + appInfo.isFromWacAutomation = isFromWacAutomation.toString().toLowerCase(); + } + var docUrl = context.get_docUrl(); + appInfo.docUrl = omexDomainRegex.test(docUrl) ? docUrl : ""; + var url = location.href; + if (url) { + url = url.split("?")[0].split("#")[0]; + } + appInfo.appURL = AppTelemetry.UrlFilter.filter(url); + (function getUserIdAndAssetIdFromToken(token, appInfo) { + appInfo.assetId = ""; + appInfo.userId = ""; + try { + if (!OSF.Utility.isNullOrEmpty(token)) { + var xmlContent = decodeURIComponent(token); + var parser = new DOMParser(); + var xmlDoc = parser.parseFromString(xmlContent, "text/xml"); + var cidNode = xmlDoc.getElementsByTagName("t")[0].attributes.getNamedItem("cid"); + var oidNode = xmlDoc.getElementsByTagName("t")[0].attributes.getNamedItem("oid"); + if (cidNode && cidNode.nodeValue) { + appInfo.userId = cidNode.nodeValue; + } + else if (oidNode && oidNode.nodeValue) { + appInfo.userId = oidNode.nodeValue; + } + appInfo.assetId = xmlDoc.getElementsByTagName("t")[0].attributes.getNamedItem("aid").nodeValue; + } + } + catch (e) { + } + })(context.get_eToken(), appInfo); + appInfo.sessionId = sessionId; + OTel.OTelLogger.initialize(appInfo); + AppTelemetry.onAppActivated(); + } + AppTelemetry.initialize = initialize; + function onAppActivated() { + if (!appInfo) { + return; + } + OTel.OTelLogger.onTelemetryLoaded(function () { + var dataFields = []; + dataFields = dataFields.concat([ + oteljs.makeStringDataField("Browser", appInfo.browser), + oteljs.makeStringDataField("AppURL", appInfo.appURL), + oteljs.makeInt64DataField("AppSizeWidth", window.innerWidth), + oteljs.makeInt64DataField("AppSizeHeight", window.innerHeight) + ]); + Microsoft.Office.WebExtension.sendTelemetryEvent({ + eventName: "Office.Extensibility.OfficeJs.AppActivatedX", + dataFields: dataFields, + eventFlags: { + dataCategories: oteljs.DataCategories.ProductServiceUsage, + diagnosticLevel: oteljs.DiagnosticLevel.NecessaryServiceDataEvent, + samplingPolicy: oteljs.SamplingPolicy.CriticalBusinessImpact + } + }); + }); + } + AppTelemetry.onAppActivated = onAppActivated; + function onScriptDone(scriptId, msStartTime, msResponseTime, appCorrelationId) { + } + AppTelemetry.onScriptDone = onScriptDone; + function onCallDone(apiType, id, parameters, msResponseTime, errorType) { + if (!appInfo) { + return; + } + } + AppTelemetry.onCallDone = onCallDone; + ; + function onMethodDone(id, args, msResponseTime, errorType) { + } + AppTelemetry.onMethodDone = onMethodDone; + function onPropertyDone(propertyName, msResponseTime) { + OSF.AppTelemetry.onCallDone("property", -1, propertyName, msResponseTime, 0); + } + AppTelemetry.onPropertyDone = onPropertyDone; + function onCheckWACHost(isWacKnownHost, instanceId, hostType, hostPlatform, wacDomain) { + } + AppTelemetry.onCheckWACHost = onCheckWACHost; + function onEventDone(id, errorType) { + OSF.AppTelemetry.onCallDone("event", id, null, 0, errorType); + } + AppTelemetry.onEventDone = onEventDone; + function onRegisterDone(register, id, msResponseTime, errorType) { + OSF.AppTelemetry.onCallDone(register ? "registerevent" : "unregisterevent", id, null, msResponseTime, errorType); + } + AppTelemetry.onRegisterDone = onRegisterDone; + function onAppClosed(openTime, focusTime) { + if (!appInfo) { + return; + } + } + AppTelemetry.onAppClosed = onAppClosed; + function setOsfControlAppCorrelationId(correlationId) { + osfControlAppCorrelationId = trimStringToLowerCase(correlationId); + } + AppTelemetry.setOsfControlAppCorrelationId = setOsfControlAppCorrelationId; + function doAppInitializationLogging(isException, message) { + } + AppTelemetry.doAppInitializationLogging = doAppInitializationLogging; + function logAppCommonMessage(message) { + doAppInitializationLogging(false, message); + } + AppTelemetry.logAppCommonMessage = logAppCommonMessage; + function logAppException(errorMessage) { + doAppInitializationLogging(true, errorMessage); + } + AppTelemetry.logAppException = logAppException; + })(AppTelemetry = OSF.AppTelemetry || (OSF.AppTelemetry = {})); +})(OSF || (OSF = {})); +var OTel; +(function (OTel) { + var OTelLogger = (function () { + function OTelLogger() { + } + OTelLogger.loaded = function () { + return !(OTelLogger.logger === undefined); + }; + OTelLogger.create = function (info) { + var contract = { + id: info.appId, + assetId: info.assetId, + officeJsVersion: info.officeJSVersion, + hostJsVersion: info.hostJSVersion, + browserToken: info.clientId, + instanceId: info.appInstanceId, + sessionId: info.sessionId + }; + var fields = oteljs.Contracts.Office.System.SDX.getFields("SDX", contract); + var flavor = OSF._OfficeAppFactory.getHostInfo().hostPlatform; + var sink; + if (flavor === "web") { + sink = new OTel.SdxWacSink(); + } + else if (Office.context.requirements.isSetSupported('Telemetry', '1.2')) { + sink = new OTel.RichApiSink(); + } + else { + console.error('Cannot create telemetry sink successfully'); + return null; + } + var namespace = "Office.Extensibility.OfficeJs"; + var ariaTenantToken = 'db334b301e7b474db5e0f02f07c51a47-a1b5bc36-1bbe-482f-a64a-c2d9cb606706-7439'; + var nexusTenantToken = 1755; + var logger = new oteljs.SimpleTelemetryLogger(undefined, fields); + logger.addSink(sink); + logger.setTenantToken(namespace, ariaTenantToken, nexusTenantToken); + oteljs.onNotification().addListener(function (notification) { + OSF.Utility.debugLog(notification.message()); + }); + return logger; + }; + OTelLogger.checkAndResolvePromises = function () { + if (OTelLogger.loaded()) { + OTelLogger.promises.forEach(function (resolve) { + resolve(); + }); + OTelLogger.promises = []; + } + }; + OTelLogger.initialize = function (info) { + if (!OTelLogger.Enabled) { + OTelLogger.promises = []; + return; + } + Office.onReadyInternal().then(function () { + if (!OTelLogger.loaded()) { + OSF.Utility.debugLog("Creating OTelLogger"); + OTelLogger.logger = OTelLogger.create(info); + OTelLogger.checkAndResolvePromises(); + } + }); + }; + OTelLogger.sendTelemetryEvent = function (telemetryEvent) { + OTelLogger.onTelemetryLoaded(function () { + try { + OTelLogger.logger.sendTelemetryEvent(telemetryEvent); + OSF.Utility.debugLog("Sent telemetry"); + } + catch (e) { + console.error("Cannot send telemetry event: " + JSON.stringify(e)); + } + }); + }; + OTelLogger.onTelemetryLoaded = function (resolve) { + if (!OTelLogger.Enabled) { + return; + } + if (OTelLogger.loaded()) { + resolve(); + } + else { + OTelLogger.promises.push(resolve); + } + }; + OTelLogger.promises = []; + OTelLogger.Enabled = true; + return OTelLogger; + }()); + OTel.OTelLogger = OTelLogger; +})(OTel || (OTel = {})); +var OTel; +(function (OTel) { + var DEFAULT_MINIMUM_MILLISECONDS_BETWEEN_CALLS = 1000; + var _minimumMillisecondsBeforeFirstCall = DEFAULT_MINIMUM_MILLISECONDS_BETWEEN_CALLS; + var _minimumMillisecondsBetweenCalls = DEFAULT_MINIMUM_MILLISECONDS_BETWEEN_CALLS; + var RichApiSink = (function () { + function RichApiSink() { + var _this = this; + this._requestIsPending = true; + this._telemetryQueue = []; + this.pause(_minimumMillisecondsBeforeFirstCall).then(function () { + var currentWork = _this._telemetryQueue; + _this._telemetryQueue = []; + _this._requestIsPending = false; + _this.processTelemetryEvents(currentWork); + }); + } + RichApiSink.prototype.sendTelemetryEvent = function (telemetryEvent) { + this._telemetryQueue.push(telemetryEvent); + if (this._requestIsPending) { + return; + } + this.processWorkBacklog(); + }; + RichApiSink.prototype.processWorkBacklog = function () { + var _this = this; + this._requestIsPending = true; + var currentWork = this._telemetryQueue; + this._telemetryQueue = []; + this.processTelemetryEvents(currentWork) + .then(this.waitAndProcessMore) + .catch(function (error) { + oteljs.logError(oteljs.Category.Sink, "RichApiSink Error", error); + _this.waitAndProcessMore(); + }); + }; + RichApiSink.prototype.waitAndProcessMore = function () { + var _this = this; + this.pause(_minimumMillisecondsBetweenCalls) + .then(function () { + if (_this._telemetryQueue.length > 0) { + setTimeout(function () { return _this.processWorkBacklog(); }, 0); + } + _this._requestIsPending = false; + }) + .catch(function () { }); + }; + RichApiSink.prototype.processTelemetryEvents = function (telemetryEvents) { + var _this = this; + var ctx = new OfficeCore.RequestContext(); + telemetryEvents.forEach(function (telemetryEvent) { + if (!telemetryEvent.telemetryProperties) { + return; + } + var dataFields = []; + _this.addDataFields(dataFields, telemetryEvent.dataFields); + var contractName = !!telemetryEvent.eventContract ? telemetryEvent.eventContract.name : ''; + if (!!telemetryEvent.eventContract) { + _this.addDataFields(dataFields, telemetryEvent.eventContract.dataFields); + } + ctx.telemetry.sendTelemetryEvent(telemetryEvent.telemetryProperties, telemetryEvent.eventName, contractName, oteljs.getEffectiveEventFlags(telemetryEvent), dataFields); + }); + return ctx.sync().catch(function () { + oteljs.logNotification(oteljs.LogLevel.Info, oteljs.Category.Sink, function () { return 'RichApi telemetry call failed.'; }); + }); + }; + RichApiSink.prototype.addDataFields = function (richApiDataFields, dataFields) { + if (dataFields) { + dataFields.forEach(function (dataField) { + richApiDataFields.push({ + name: dataField.name, + value: dataField.value, + classification: dataField.classification ? dataField.classification : oteljs.DataClassification.SystemMetadata, + type: dataField.dataType + }); + }); + } + }; + RichApiSink.prototype.pause = function (ms) { + return new Office.Promise(function (resolve) { return setTimeout(resolve, ms); }); + }; + return RichApiSink; + }()); + OTel.RichApiSink = RichApiSink; +})(OTel || (OTel = {})); +var OTel; +(function (OTel) { + var SdxWacSink = (function () { + function SdxWacSink() { + } + SdxWacSink.prototype.sendTelemetryEvent = function (event, _timestamp) { + try { + if (event.dataFields && + event.dataFields.filter(function (dataField) { + return dataField.classification && dataField.classification !== oteljs.DataClassification.SystemMetadata; + }).length > 0) { + return; + } + var id = OSF._OfficeAppFactory.getId(); + var SendTelemetryEventId = OSF.AgaveHostAction.SendTelemetryEvent; + OSF.getClientEndPoint().invoke('ContextActivationManager_notifyHost', null, [id, SendTelemetryEventId, event]); + } + catch (error) { + oteljs.logError(oteljs.Category.Sink, "AgaveWacSink", error); + } + }; + return SdxWacSink; + }()); + OTel.SdxWacSink = SdxWacSink; +})(OTel || (OTel = {})); +var OSF; +(function (OSF) { + var AppTelemetry; + (function (AppTelemetry) { + var UrlFilter = (function () { + function UrlFilter() { + } + UrlFilter.hashString = function (s) { + var hash = 0; + if (s.length === 0) { + return hash; + } + for (var i = 0; i < s.length; i++) { + var c = s.charCodeAt(i); + hash = ((hash << 5) - hash) + c; + hash |= 0; + } + return hash; + }; + ; + UrlFilter.stringToHash = function (s) { + var hash = UrlFilter.hashString(s); + var stringHash = hash.toString(); + if (hash < 0) { + stringHash = "1" + stringHash.substring(1); + } + else { + stringHash = "0" + stringHash; + } + return stringHash; + }; + UrlFilter.startsWith = function (s, prefix) { + return s.indexOf(prefix) == -0; + }; + UrlFilter.isFileUrl = function (url) { + return UrlFilter.startsWith(url.toLowerCase(), "file:"); + }; + UrlFilter.removeHttpPrefix = function (url) { + var prefix = ""; + if (UrlFilter.startsWith(url.toLowerCase(), UrlFilter.httpsPrefix)) { + prefix = UrlFilter.httpsPrefix; + } + else if (UrlFilter.startsWith(url.toLowerCase(), UrlFilter.httpPrefix)) { + prefix = UrlFilter.httpPrefix; + } + var clean = url.slice(prefix.length); + return clean; + }; + UrlFilter.getUrlDomain = function (url) { + var domain = UrlFilter.removeHttpPrefix(url); + domain = domain.split("/")[0]; + domain = domain.split(":")[0]; + return domain; + }; + UrlFilter.isIp4Address = function (domain) { + var ipv4Regex = /^(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/; + return ipv4Regex.test(domain); + }; + UrlFilter.filter = function (url) { + if (UrlFilter.isFileUrl(url)) { + var hash = UrlFilter.stringToHash(url); + return "file://" + hash; + } + var domain = UrlFilter.getUrlDomain(url); + if (UrlFilter.isIp4Address(domain)) { + var hash = UrlFilter.stringToHash(url); + if (UrlFilter.startsWith(domain, "10.")) { + return "IP10Range_" + hash; + } + else if (UrlFilter.startsWith(domain, "192.")) { + return "IP192Range_" + hash; + } + else if (UrlFilter.startsWith(domain, "127.")) { + return "IP127Range_" + hash; + } + return "IPOther_" + hash; + } + return domain; + }; + UrlFilter.httpPrefix = "http://"; + UrlFilter.httpsPrefix = "https://"; + return UrlFilter; + }()); + AppTelemetry.UrlFilter = UrlFilter; + })(AppTelemetry = OSF.AppTelemetry || (OSF.AppTelemetry = {})); +})(OSF || (OSF = {})); +var OSF; +(function (OSF) { + function isNodeJs() { + try { + return (typeof process === 'object' + && String(process) === '[object process]'); + } + catch (e) { + return false; + } + } + function isOfficeReactNative() { + try { + return (typeof OfficePlatformGlobal !== 'undefined' + && typeof OfficePlatformGlobal.ReactNativeReka !== 'undefined'); + } + catch (e) { + return false; + } + } + if (!isNodeJs() && !isOfficeReactNative()) { + try { + OSF.Flights = OSF.OUtil.parseFlights(true); + } + catch (ex) { } + OSF._OfficeAppFactory.bootstrap(function () { }, function (e) { + if (e instanceof Error) { + console.warn(e.message); + } + else { + console.warn(JSON.stringify(e)); + } + }); + window.addEventListener('DOMContentLoaded', function (event) { + OSFPerformance.hostSpecificFileName = OSF.LoadScriptHelper.getHostBundleJsName(); + Office.onReadyInternal(function () { + OSFPerfUtil.sendPerformanceTelemetry(); + }); + if (OSF._OfficeAppFactory.getHostInfo().hostLocale) { + setTimeout(function () { + OSF.OUtil.ensureOfficeStringsJs().then(function () { + if (OSF._OfficeAppFactory.getHostInfo().hostType === "outlook") { + OSF._OfficeAppFactory.getInitializationHelper().loadAppSpecificScriptAndCreateOM(OSF._OfficeAppFactory.getOfficeAppContext(), function () { console.log("callback called;"); }); + } + }).catch(function (ex) { + console.error(ex); + }); + }, 0); + } + }); + } +})(OSF || (OSF = {})); +var __assign = (this && this.__assign) || function () { + __assign = Object.assign || function(t) { + for (var s, i = 1, n = arguments.length; i < n; i++) { + s = arguments[i]; + for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) + t[p] = s[p]; + } + return t; + }; + return __assign.apply(this, arguments); +}; +var oteljs; +(function (oteljs) { + function addContractField(dataFields, instanceName, contractName) { + dataFields.push(oteljs.makeStringDataField("zC." + instanceName, contractName)); + } + oteljs.addContractField = addContractField; +})(oteljs || (oteljs = {})); +var oteljs; +(function (oteljs) { + var DataClassification; + (function (DataClassification) { + DataClassification[DataClassification["EssentialServiceMetadata"] = 1] = "EssentialServiceMetadata"; + DataClassification[DataClassification["AccountData"] = 2] = "AccountData"; + DataClassification[DataClassification["SystemMetadata"] = 4] = "SystemMetadata"; + DataClassification[DataClassification["OrganizationIdentifiableInformation"] = 8] = "OrganizationIdentifiableInformation"; + DataClassification[DataClassification["EndUserIdentifiableInformation"] = 16] = "EndUserIdentifiableInformation"; + DataClassification[DataClassification["CustomerContent"] = 32] = "CustomerContent"; + DataClassification[DataClassification["AccessControl"] = 64] = "AccessControl"; + })(DataClassification = oteljs.DataClassification || (oteljs.DataClassification = {})); +})(oteljs || (oteljs = {})); +var oteljs; +(function (oteljs) { + function makeBooleanDataField(name, value) { + return { + name: name, + dataType: oteljs.DataFieldType.Boolean, + value: value, + classification: oteljs.DataClassification.SystemMetadata + }; + } + oteljs.makeBooleanDataField = makeBooleanDataField; + function makeInt64DataField(name, value) { + return { + name: name, + dataType: oteljs.DataFieldType.Int64, + value: value, + classification: oteljs.DataClassification.SystemMetadata + }; + } + oteljs.makeInt64DataField = makeInt64DataField; + function makeDoubleDataField(name, value) { + return { + name: name, + dataType: oteljs.DataFieldType.Double, + value: value, + classification: oteljs.DataClassification.SystemMetadata + }; + } + oteljs.makeDoubleDataField = makeDoubleDataField; + function makeStringDataField(name, value) { + return { + name: name, + dataType: oteljs.DataFieldType.String, + value: value, + classification: oteljs.DataClassification.SystemMetadata + }; + } + oteljs.makeStringDataField = makeStringDataField; + function makeGuidDataField(name, value) { + return { + name: name, + dataType: oteljs.DataFieldType.Guid, + value: value, + classification: oteljs.DataClassification.SystemMetadata + }; + } + oteljs.makeGuidDataField = makeGuidDataField; +})(oteljs || (oteljs = {})); +var oteljs; +(function (oteljs) { + var DataFieldType; + (function (DataFieldType) { + DataFieldType[DataFieldType["String"] = 0] = "String"; + DataFieldType[DataFieldType["Boolean"] = 1] = "Boolean"; + DataFieldType[DataFieldType["Int64"] = 2] = "Int64"; + DataFieldType[DataFieldType["Double"] = 3] = "Double"; + DataFieldType[DataFieldType["Guid"] = 4] = "Guid"; + })(DataFieldType = oteljs.DataFieldType || (oteljs.DataFieldType = {})); +})(oteljs || (oteljs = {})); +var oteljs; +(function (oteljs) { + var Event = (function () { + function Event() { + this._listeners = []; + } + Event.prototype.fireEvent = function (args) { + this._listeners.forEach(function (listener) { return listener(args); }); + }; + Event.prototype.addListener = function (listener) { + if (listener) { + this._listeners.push(listener); + } + }; + Event.prototype.removeListener = function (listener) { + this._listeners = this._listeners.filter(function (h) { return h !== listener; }); + }; + Event.prototype.getListenerCount = function () { + return this._listeners.length; + }; + return Event; + }()); + oteljs.Event = Event; +})(oteljs || (oteljs = {})); +var oteljs; +(function (oteljs) { + function getEffectiveEventFlags(telemetryEvent) { + var eventFlags = { + costPriority: oteljs.CostPriority.Normal, + samplingPolicy: oteljs.SamplingPolicy.Measure, + persistencePriority: oteljs.PersistencePriority.Normal, + dataCategories: oteljs.DataCategories.NotSet, + diagnosticLevel: oteljs.DiagnosticLevel.FullEvent + }; + if (!telemetryEvent.eventFlags || !telemetryEvent.eventFlags.dataCategories) { + oteljs.logNotification(oteljs.LogLevel.Error, oteljs.Category.Core, function () { return 'Event is missing DataCategories event flag'; }); + } + if (!telemetryEvent.eventFlags) { + return eventFlags; + } + if (telemetryEvent.eventFlags.costPriority) { + eventFlags.costPriority = telemetryEvent.eventFlags.costPriority; + } + if (telemetryEvent.eventFlags.samplingPolicy) { + eventFlags.samplingPolicy = telemetryEvent.eventFlags.samplingPolicy; + } + if (telemetryEvent.eventFlags.persistencePriority) { + eventFlags.persistencePriority = telemetryEvent.eventFlags.persistencePriority; + } + if (telemetryEvent.eventFlags.dataCategories) { + eventFlags.dataCategories = telemetryEvent.eventFlags.dataCategories; + } + if (telemetryEvent.eventFlags.diagnosticLevel) { + eventFlags.diagnosticLevel = telemetryEvent.eventFlags.diagnosticLevel; + } + return eventFlags; + } + oteljs.getEffectiveEventFlags = getEffectiveEventFlags; +})(oteljs || (oteljs = {})); +var oteljs; +(function (oteljs) { + var SamplingPolicy; + (function (SamplingPolicy) { + SamplingPolicy[SamplingPolicy["NotSet"] = 0] = "NotSet"; + SamplingPolicy[SamplingPolicy["Measure"] = 1] = "Measure"; + SamplingPolicy[SamplingPolicy["Diagnostics"] = 2] = "Diagnostics"; + SamplingPolicy[SamplingPolicy["CriticalBusinessImpact"] = 191] = "CriticalBusinessImpact"; + SamplingPolicy[SamplingPolicy["CriticalCensus"] = 192] = "CriticalCensus"; + SamplingPolicy[SamplingPolicy["CriticalExperimentation"] = 193] = "CriticalExperimentation"; + SamplingPolicy[SamplingPolicy["CriticalUsage"] = 194] = "CriticalUsage"; + })(SamplingPolicy = oteljs.SamplingPolicy || (oteljs.SamplingPolicy = {})); + var PersistencePriority; + (function (PersistencePriority) { + PersistencePriority[PersistencePriority["NotSet"] = 0] = "NotSet"; + PersistencePriority[PersistencePriority["Normal"] = 1] = "Normal"; + PersistencePriority[PersistencePriority["High"] = 2] = "High"; + })(PersistencePriority = oteljs.PersistencePriority || (oteljs.PersistencePriority = {})); + var CostPriority; + (function (CostPriority) { + CostPriority[CostPriority["NotSet"] = 0] = "NotSet"; + CostPriority[CostPriority["Normal"] = 1] = "Normal"; + CostPriority[CostPriority["High"] = 2] = "High"; + })(CostPriority = oteljs.CostPriority || (oteljs.CostPriority = {})); + var DataCategories; + (function (DataCategories) { + DataCategories[DataCategories["NotSet"] = 0] = "NotSet"; + DataCategories[DataCategories["SoftwareSetup"] = 1] = "SoftwareSetup"; + DataCategories[DataCategories["ProductServiceUsage"] = 2] = "ProductServiceUsage"; + DataCategories[DataCategories["ProductServicePerformance"] = 4] = "ProductServicePerformance"; + DataCategories[DataCategories["DeviceConfiguration"] = 8] = "DeviceConfiguration"; + DataCategories[DataCategories["InkingTypingSpeech"] = 16] = "InkingTypingSpeech"; + })(DataCategories = oteljs.DataCategories || (oteljs.DataCategories = {})); + var DiagnosticLevel; + (function (DiagnosticLevel) { + DiagnosticLevel[DiagnosticLevel["ReservedDoNotUse"] = 0] = "ReservedDoNotUse"; + DiagnosticLevel[DiagnosticLevel["BasicEvent"] = 10] = "BasicEvent"; + DiagnosticLevel[DiagnosticLevel["FullEvent"] = 100] = "FullEvent"; + DiagnosticLevel[DiagnosticLevel["NecessaryServiceDataEvent"] = 110] = "NecessaryServiceDataEvent"; + DiagnosticLevel[DiagnosticLevel["AlwaysOnNecessaryServiceDataEvent"] = 120] = "AlwaysOnNecessaryServiceDataEvent"; + })(DiagnosticLevel = oteljs.DiagnosticLevel || (oteljs.DiagnosticLevel = {})); +})(oteljs || (oteljs = {})); +var oteljs; +(function (oteljs) { + var onNotificationEvent = new oteljs.Event(); + var LogLevel; + (function (LogLevel) { + LogLevel[LogLevel["Error"] = 0] = "Error"; + LogLevel[LogLevel["Warning"] = 1] = "Warning"; + LogLevel[LogLevel["Info"] = 2] = "Info"; + LogLevel[LogLevel["Verbose"] = 3] = "Verbose"; + })(LogLevel = oteljs.LogLevel || (oteljs.LogLevel = {})); + var Category; + (function (Category) { + Category[Category["Core"] = 0] = "Core"; + Category[Category["Sink"] = 1] = "Sink"; + Category[Category["Transport"] = 2] = "Transport"; + })(Category = oteljs.Category || (oteljs.Category = {})); + function onNotification() { + return onNotificationEvent; + } + oteljs.onNotification = onNotification; + function logNotification(level, category, message) { + onNotificationEvent.fireEvent({ level: level, category: category, message: message }); + } + oteljs.logNotification = logNotification; + function logError(category, message, error) { + logNotification(LogLevel.Error, category, function () { + var errorMessage = error instanceof Error ? error.message : ''; + return message + ": " + errorMessage; + }); + } + oteljs.logError = logError; +})(oteljs || (oteljs = {})); +var oteljs; +(function (oteljs) { + oteljs.SuppressNexus = -1; + var SimpleTelemetryLogger = (function () { + function SimpleTelemetryLogger(parent, persistentDataFields, config) { + var _a, _b; + this.onSendEvent = new oteljs.Event(); + this.persistentDataFields = []; + this.config = config || {}; + if (parent) { + this.onSendEvent = parent.onSendEvent; + (_a = this.persistentDataFields).push.apply(_a, parent.persistentDataFields); + this.config = __assign(__assign({}, parent.getConfig()), this.config); + } + else { + this.persistentDataFields.push(oteljs.makeStringDataField('OTelJS.Version', oteljs.oteljsVersion)); + } + if (persistentDataFields) { + (_b = this.persistentDataFields).push.apply(_b, persistentDataFields); + } + } + SimpleTelemetryLogger.prototype.sendTelemetryEvent = function (event) { + var localEvent; + try { + if (this.onSendEvent.getListenerCount() === 0) { + oteljs.logNotification(oteljs.LogLevel.Warning, oteljs.Category.Core, function () { return 'No telemetry sinks are attached.'; }); + return; + } + localEvent = this.cloneEvent(event); + this.processTelemetryEvent(localEvent); + } + catch (error) { + oteljs.logError(oteljs.Category.Core, 'SendTelemetryEvent', error); + return; + } + try { + this.onSendEvent.fireEvent(localEvent); + } + catch (_e) { + } + }; + SimpleTelemetryLogger.prototype.processTelemetryEvent = function (event) { + var _a; + if (!event.telemetryProperties) { + event.telemetryProperties = oteljs.TenantTokenManager.getTenantTokens(event.eventName); + } + if (event.dataFields && this.persistentDataFields) { + (_a = event.dataFields).unshift.apply(_a, this.persistentDataFields); + } + if (!this.config.disableValidation) { + oteljs.TelemetryEventValidator.validateTelemetryEvent(event); + } + }; + SimpleTelemetryLogger.prototype.addSink = function (sink) { + this.onSendEvent.addListener(function (event) { return sink.sendTelemetryEvent(event); }); + }; + SimpleTelemetryLogger.prototype.setTenantToken = function (namespace, ariaTenantToken, nexusTenantToken) { + oteljs.TenantTokenManager.setTenantToken(namespace, ariaTenantToken, nexusTenantToken); + }; + SimpleTelemetryLogger.prototype.setTenantTokens = function (tokenTree) { + oteljs.TenantTokenManager.setTenantTokens(tokenTree); + }; + SimpleTelemetryLogger.prototype.cloneEvent = function (event) { + return oteljs.cloneEvent(event); + }; + SimpleTelemetryLogger.prototype.getConfig = function () { + return this.config; + }; + return SimpleTelemetryLogger; + }()); + oteljs.SimpleTelemetryLogger = SimpleTelemetryLogger; +})(oteljs || (oteljs = {})); +var oteljs; +(function (oteljs) { + function cloneEvent(event) { + var localEvent = { eventName: event.eventName, eventFlags: event.eventFlags }; + if (!!event.telemetryProperties) { + localEvent.telemetryProperties = { + ariaTenantToken: event.telemetryProperties.ariaTenantToken, + nexusTenantToken: event.telemetryProperties.nexusTenantToken + }; + } + if (!!event.eventContract) { + localEvent.eventContract = { name: event.eventContract.name, dataFields: event.eventContract.dataFields.slice() }; + } + localEvent.dataFields = !!event.dataFields ? event.dataFields.slice() : []; + return localEvent; + } + oteljs.cloneEvent = cloneEvent; +})(oteljs || (oteljs = {})); +var oteljs; +(function (oteljs) { + var TelemetryEventValidator; + (function (TelemetryEventValidator) { + var INT64_MIN = -9007199254740991; + var INT64_MAX = 9007199254740991; + var StartsWithCapitalRegex = /^[A-Z][a-zA-Z0-9]*$/; + var AlphanumericRegex = /^[a-zA-Z0-9_\.]*$/; + function validateTelemetryEvent(event) { + if (!isEventNameValid(event.eventName)) { + throw new Error('Invalid eventName'); + } + if (event.eventContract && !isEventContractValid(event.eventContract)) { + throw new Error('Invalid eventContract'); + } + if (event.dataFields != null) { + for (var i = 0; i < event.dataFields.length; i++) { + validateDataField(event.dataFields[i]); + } + } + } + TelemetryEventValidator.validateTelemetryEvent = validateTelemetryEvent; + function isNamespaceValid(eventNamePieces) { + return !!eventNamePieces && eventNamePieces.length >= 3 && eventNamePieces[0] === 'Office'; + } + function isEventNodeValid(eventNode) { + return eventNode !== undefined && StartsWithCapitalRegex.test(eventNode); + } + function isEventNameValid(eventName) { + var maxEventNameLength = 98; + if (!eventName || eventName.length > maxEventNameLength) { + return false; + } + var eventNamePieces = eventName.split('.'); + var eventNodeName = eventNamePieces[eventNamePieces.length - 1]; + return isNamespaceValid(eventNamePieces) && isEventNodeValid(eventNodeName); + } + function isEventContractValid(eventContract) { + return isNameValid(eventContract.name); + } + function isDataFieldNameValid(dataFieldName) { + var maxDataFieldNameLength = 100; + var dataFieldPrefixLength = 5; + return !!dataFieldName && isNameValid(dataFieldName) && dataFieldName.length + dataFieldPrefixLength < maxDataFieldNameLength; + } + function isNameValid(name) { + return name !== undefined && AlphanumericRegex.test(name); + } + function validateDataField(dataField) { + if (!isDataFieldNameValid(dataField.name)) { + throw new Error('Invalid dataField name'); + } + if (dataField.dataType === oteljs.DataFieldType.Int64) { + validateInt(dataField.value); + } + } + function validateInt(value) { + if (typeof value !== 'number' || !isFinite(value) || Math.floor(value) !== value || value < INT64_MIN || value > INT64_MAX) { + throw new Error("Invalid integer " + JSON.stringify(value)); + } + } + TelemetryEventValidator.validateInt = validateInt; + })(TelemetryEventValidator = oteljs.TelemetryEventValidator || (oteljs.TelemetryEventValidator = {})); +})(oteljs || (oteljs = {})); +var oteljs; +(function (oteljs) { + var TokenType; + (function (TokenType) { + TokenType[TokenType["Aria"] = 0] = "Aria"; + TokenType[TokenType["Nexus"] = 1] = "Nexus"; + })(TokenType || (TokenType = {})); + var TenantTokenManager; + (function (TenantTokenManager) { + var ariaTokenMap = {}; + var nexusTokenMap = {}; + var tenantTokens = {}; + function setTenantToken(namespace, ariaTenantToken, nexusTenantToken) { + var parts = namespace.split('.'); + if (parts.length < 2 || parts[0] !== 'Office') { + oteljs.logNotification(oteljs.LogLevel.Error, oteljs.Category.Core, function () { + return "Invalid namespace: " + namespace; + }); + return; + } + var leaf = Object.create(Object.prototype); + if (ariaTenantToken) { + leaf['ariaTenantToken'] = ariaTenantToken; + } + if (nexusTenantToken) { + leaf['nexusTenantToken'] = nexusTenantToken; + } + var node = leaf; + var index; + for (index = parts.length - 1; index >= 0; --index) { + var parentNode = Object.create(Object.prototype); + parentNode[parts[index]] = node; + node = parentNode; + } + setTenantTokens(node); + } + TenantTokenManager.setTenantToken = setTenantToken; + function setTenantTokens(tokenTree) { + if (typeof tokenTree !== 'object') { + throw new Error('tokenTree must be an object'); + } + tenantTokens = mergeTenantTokens(tenantTokens, tokenTree); + } + TenantTokenManager.setTenantTokens = setTenantTokens; + function getTenantTokens(eventName) { + var ariaTenantToken = getAriaTenantToken(eventName); + var nexusTenantToken = getNexusTenantToken(eventName); + if (!nexusTenantToken || !ariaTenantToken) { + throw new Error('Could not find tenant token for ' + eventName); + } + return { + ariaTenantToken: ariaTenantToken, + nexusTenantToken: nexusTenantToken + }; + } + TenantTokenManager.getTenantTokens = getTenantTokens; + function getAriaTenantToken(eventName) { + if (ariaTokenMap[eventName]) { + return ariaTokenMap[eventName]; + } + var ariaToken = getTenantToken(eventName, TokenType.Aria); + if (typeof ariaToken === 'string') { + ariaTokenMap[eventName] = ariaToken; + return ariaToken; + } + return undefined; + } + TenantTokenManager.getAriaTenantToken = getAriaTenantToken; + function getNexusTenantToken(eventName) { + if (nexusTokenMap[eventName]) { + return nexusTokenMap[eventName]; + } + var nexusToken = getTenantToken(eventName, TokenType.Nexus); + if (typeof nexusToken === 'number') { + nexusTokenMap[eventName] = nexusToken; + return nexusToken; + } + return undefined; + } + TenantTokenManager.getNexusTenantToken = getNexusTenantToken; + function getTenantToken(eventName, tokenType) { + var pieces = eventName.split('.'); + var node = tenantTokens; + var token = undefined; + if (!node) { + return undefined; + } + for (var i = 0; i < pieces.length - 1; i++) { + if (node[pieces[i]]) { + node = node[pieces[i]]; + if (tokenType === TokenType.Aria && typeof node.ariaTenantToken === 'string') { + token = node.ariaTenantToken; + } + else if (tokenType === TokenType.Nexus && typeof node.nexusTenantToken === 'number') { + token = node.nexusTenantToken; + } + } + } + return token; + } + function mergeTenantTokens(existingTokenTree, newTokenTree) { + if (typeof newTokenTree !== 'object') { + return newTokenTree; + } + for (var _i = 0, _a = Object.keys(newTokenTree); _i < _a.length; _i++) { + var key = _a[_i]; + if (key in existingTokenTree && typeof (existingTokenTree[key] === 'object')) { + existingTokenTree[key] = mergeTenantTokens(existingTokenTree[key], newTokenTree[key]); + } + else { + existingTokenTree[key] = newTokenTree[key]; + } + } + return existingTokenTree; + } + function clear() { + ariaTokenMap = {}; + nexusTokenMap = {}; + tenantTokens = {}; + } + TenantTokenManager.clear = clear; + })(TenantTokenManager = oteljs.TenantTokenManager || (oteljs.TenantTokenManager = {})); +})(oteljs || (oteljs = {})); +var oteljs; +(function (oteljs) { + oteljs.oteljsVersion = '3.1.64'; +})(oteljs || (oteljs = {})); +var oteljs; +(function (oteljs) { + var Contracts; + (function (Contracts) { + var Office; + (function (Office) { + var System; + (function (System) { + var SDX; + (function (SDX) { + var contractName = 'Office.System.SDX'; + function getFields(instanceName, contract) { + var dataFields = []; + if (contract.id !== undefined) { + dataFields.push(oteljs.makeStringDataField(instanceName + ".Id", contract.id)); + } + if (contract.version !== undefined) { + dataFields.push(oteljs.makeStringDataField(instanceName + ".Version", contract.version)); + } + if (contract.instanceId !== undefined) { + dataFields.push(oteljs.makeStringDataField(instanceName + ".InstanceId", contract.instanceId)); + } + if (contract.name !== undefined) { + dataFields.push(oteljs.makeStringDataField(instanceName + ".Name", contract.name)); + } + if (contract.marketplaceType !== undefined) { + dataFields.push(oteljs.makeStringDataField(instanceName + ".MarketplaceType", contract.marketplaceType)); + } + if (contract.sessionId !== undefined) { + dataFields.push(oteljs.makeStringDataField(instanceName + ".SessionId", contract.sessionId)); + } + if (contract.browserToken !== undefined) { + dataFields.push(oteljs.makeStringDataField(instanceName + ".BrowserToken", contract.browserToken)); + } + if (contract.osfRuntimeVersion !== undefined) { + dataFields.push(oteljs.makeStringDataField(instanceName + ".OsfRuntimeVersion", contract.osfRuntimeVersion)); + } + if (contract.officeJsVersion !== undefined) { + dataFields.push(oteljs.makeStringDataField(instanceName + ".OfficeJsVersion", contract.officeJsVersion)); + } + if (contract.hostJsVersion !== undefined) { + dataFields.push(oteljs.makeStringDataField(instanceName + ".HostJsVersion", contract.hostJsVersion)); + } + if (contract.assetId !== undefined) { + dataFields.push(oteljs.makeStringDataField(instanceName + ".AssetId", contract.assetId)); + } + if (contract.providerName !== undefined) { + dataFields.push(oteljs.makeStringDataField(instanceName + ".ProviderName", contract.providerName)); + } + if (contract.type !== undefined) { + dataFields.push(oteljs.makeStringDataField(instanceName + ".Type", contract.type)); + } + oteljs.addContractField(dataFields, instanceName, contractName); + return dataFields; + } + SDX.getFields = getFields; + })(SDX = System.SDX || (System.SDX = {})); + })(System = Office.System || (Office.System = {})); + })(Office = Contracts.Office || (Contracts.Office = {})); + })(Contracts = oteljs.Contracts || (oteljs.Contracts = {})); +})(oteljs || (oteljs = {})); +OSF.InitializationHelper.prototype.prepareApiSurface = function OSF_InitializationHelper$prepareApiSurface(appContext) +{ + //var license = new OSF.DDA.License(appContext.get_eToken()); + // if ((appContext.get_appName() == OSF.AppName.OutlookWebApp)) { + // OSF.WebApp._UpdateLinksForHostAndXdmInfo(); + // this.initWebDialog(appContext); + // this.initWebAuth(appContext); + // OSF._OfficeAppFactory.setContext(new OSF.DDA.OutlookContext(appContext, this._settings, license, appContext.appOM)); + // OSF._OfficeAppFactory.setHostFacade(new OSF.DDA.DispIdHost.Facade(OSF.DDA.WAC.getDelegateMethods,OSF.DDA.WAC.Delegate.ParameterMap)); + // } + // else { + // OfficeJsClient_OutlookWin32.prepareApiSurface(appContext); + // OSF._OfficeAppFactory.setContext(new OSF.DDA.OutlookContext(appContext, this._settings, license, appContext.appOM, OSF.DDA.OfficeTheme ? OSF.DDA.OfficeTheme.getOfficeTheme : null, appContext.ui)); + // OSF._OfficeAppFactory.setHostFacade(new OSF.DDA.DispIdHost.Facade(OSF.DDA.DispIdHost.getClientDelegateMethods,OSF.DDA.SafeArray.Delegate.ParameterMap)); + // } +} +OSF.DDA.SettingsManager = { + SerializedSettings: "serializedSettings", + DateJSONPrefix: "Date(", + DataJSONSuffix: ")", + serializeSettings: function OSF_DDA_SettingsManager$serializeSettings(settingsCollection) { + var ret = {}; + for (var key in settingsCollection) { + var value = settingsCollection[key]; + try { + if (JSON) { + value = JSON.stringify(value, function dateReplacer(k, v) { + return OSF.OUtil.isDate(this[k]) ? OSF.DDA.SettingsManager.DateJSONPrefix + this[k].getTime() + OSF.DDA.SettingsManager.DataJSONSuffix : v; + }); + } else { + value = Sys.Serialization.JavaScriptSerializer.serialize(value); + } + ret[key] = value; + } catch (ex) { + } + } + return ret; + }, + deserializeSettings: function OSF_DDA_SettingsManager$deserializeSettings(serializedSettings) { + var ret = {}; + serializedSettings = serializedSettings || {}; + for (var key in serializedSettings) { + var value = serializedSettings[key]; + try { + if (JSON) { + value = JSON.parse(value, function dateReviver(k, v) { + var d; + if (typeof v === 'string' && v && v.length > 6 && v.slice(0, 5) === OSF.DDA.SettingsManager.DateJSONPrefix && v.slice(-1) === OSF.DDA.SettingsManager.DataJSONSuffix) { + d = new Date(parseInt(v.slice(5, -1))); + if (d) { + return d; + } + } + return v; + }); + } else { + value = Sys.Serialization.JavaScriptSerializer.deserialize(value, true); + } + ret[key] = value; + } catch (ex) { + } + } + return ret; + } +}; +OSF.InitializationHelper.prototype.loadAppSpecificScriptAndCreateOM = function OSF_InitializationHelper$loadAppSpecificScriptAndCreateOM(appContext, appReady) { + +var Outlook = typeof Outlook === "object" ? Outlook : {}; Outlook["OutlookAppOm"] = +/******/ (function(modules) { // webpackBootstrap +/******/ // The module cache +/******/ var installedModules = {}; +/******/ +/******/ // The require function +/******/ function __webpack_require__(moduleId) { +/******/ +/******/ // Check if module is in cache +/******/ if(installedModules[moduleId]) { +/******/ return installedModules[moduleId].exports; +/******/ } +/******/ // Create a new module (and put it into the cache) +/******/ var module = installedModules[moduleId] = { +/******/ i: moduleId, +/******/ l: false, +/******/ exports: {} +/******/ }; +/******/ +/******/ // Execute the module function +/******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__); +/******/ +/******/ // Flag the module as loaded +/******/ module.l = true; +/******/ +/******/ // Return the exports of the module +/******/ return module.exports; +/******/ } +/******/ +/******/ +/******/ // expose the modules object (__webpack_modules__) +/******/ __webpack_require__.m = modules; +/******/ +/******/ // expose the module cache +/******/ __webpack_require__.c = installedModules; +/******/ +/******/ // define getter function for harmony exports +/******/ __webpack_require__.d = function(exports, name, getter) { +/******/ if(!__webpack_require__.o(exports, name)) { +/******/ Object.defineProperty(exports, name, { enumerable: true, get: getter }); +/******/ } +/******/ }; +/******/ +/******/ // define __esModule on exports +/******/ __webpack_require__.r = function(exports) { +/******/ if(typeof Symbol !== 'undefined' && Symbol.toStringTag) { +/******/ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' }); +/******/ } +/******/ Object.defineProperty(exports, '__esModule', { value: true }); +/******/ }; +/******/ +/******/ // create a fake namespace object +/******/ // mode & 1: value is a module id, require it +/******/ // mode & 2: merge all properties of value into the ns +/******/ // mode & 4: return value when already ns object +/******/ // mode & 8|1: behave like require +/******/ __webpack_require__.t = function(value, mode) { +/******/ if(mode & 1) value = __webpack_require__(value); +/******/ if(mode & 8) return value; +/******/ if((mode & 4) && typeof value === 'object' && value && value.__esModule) return value; +/******/ var ns = Object.create(null); +/******/ __webpack_require__.r(ns); +/******/ Object.defineProperty(ns, 'default', { enumerable: true, value: value }); +/******/ if(mode & 2 && typeof value != 'string') for(var key in value) __webpack_require__.d(ns, key, function(key) { return value[key]; }.bind(null, key)); +/******/ return ns; +/******/ }; +/******/ +/******/ // getDefaultExport function for compatibility with non-harmony modules +/******/ __webpack_require__.n = function(module) { +/******/ var getter = module && module.__esModule ? +/******/ function getDefault() { return module['default']; } : +/******/ function getModuleExports() { return module; }; +/******/ __webpack_require__.d(getter, 'a', getter); +/******/ return getter; +/******/ }; +/******/ +/******/ // Object.prototype.hasOwnProperty.call +/******/ __webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); }; +/******/ +/******/ // __webpack_public_path__ +/******/ __webpack_require__.p = "/"; +/******/ +/******/ +/******/ // Load entry module and return exports +/******/ return __webpack_require__(__webpack_require__.s = 2); +/******/ }) +/************************************************************************/ +/******/ ([ +/* 0 */ +/***/ (function(module, exports) { + +module.exports = OSF; + +/***/ }), +/* 1 */ +/***/ (function(module, exports) { + +module.exports = Microsoft; + +/***/ }), +/* 2 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); + +// CONCATENATED MODULE: ./src/utils/isNullOrUndefined.ts +function isNullOrUndefined(value) { + return value === null || value === undefined; +} +// CONCATENATED MODULE: ./src/types/ExtensibilityStrings.ts + +var OfficeStringJS = "office_strings.js"; +var OfficeStringDebugJS = "office_strings.debug.js"; +var ExtensibilityStringJS = "outlook_strings.js"; +var tempWindow = window; +var ExtensibilityStrings; +function getString(string) { + return ExtensibilityStrings[string]; +} +var ExtensibilityStrings_url = ""; +var baseUrl = ""; +var scriptElement = null; +var stringLoadedCallback; +var stringsAreLoaded = false; + +function createScriptElement(url) { + var scriptElement = document.createElement("script"); + scriptElement.type = "text/javascript"; + scriptElement.src = url; + return scriptElement; +} + +function loadLocalizedScript(initializeAppCallback) { + stringLoadedCallback = initializeAppCallback; + var officeIndex; + var scripts = document.getElementsByTagName("script"); + + for (var i = 0; i < scripts.length; i++) { + var tag = scripts.item(i); + + if (tag && tag.src) { + var filename = tag.src || ""; + filename = filename.toLowerCase(); + officeIndex = filename.indexOf(OfficeStringJS); + + if (filename && officeIndex > 0) { + ExtensibilityStrings_url = filename.replace(OfficeStringJS, ExtensibilityStringJS); + baseUrl = saveBaseUrl(baseUrl, officeIndex, filename); + break; + } + + officeIndex = filename.indexOf(OfficeStringDebugJS); + + if (filename && officeIndex > 0) { + ExtensibilityStrings_url = filename.replace(OfficeStringDebugJS, ExtensibilityStringJS); + baseUrl = saveBaseUrl(baseUrl, officeIndex, filename); + break; + } + } + } + + if (ExtensibilityStrings_url) { + var head = document.getElementsByTagName("head")[0]; + scriptElement = createScriptElement(ExtensibilityStrings_url); + scriptElement.onload = scriptElementCallback; + scriptElement.onreadystatechange = scriptElementCallback; + window.setTimeout(failureCallback, 2000); + head.appendChild(scriptElement); + } +} + +function scriptElementCallback() { + stringsAreLoaded = true; + + if (!isNullOrUndefined(stringLoadedCallback) && (isNullOrUndefined(scriptElement.readyState) || !isNullOrUndefined(scriptElement.readyState) && (scriptElement.readyState === "loaded" || scriptElement.readyState === "complete"))) { + scriptElement.onload = null; + scriptElement.onreadystatechange = null; + + if (typeof tempWindow._u !== "undefined") { + ExtensibilityStrings = tempWindow._u.ExtensibilityStrings; + } + + stringLoadedCallback(); + } +} + +function failureCallback() { + if (!stringsAreLoaded) { + var head = document.getElementsByTagName("head")[0]; + var fallbackUrl = baseUrl + "en-us/" + ExtensibilityStringJS; + scriptElement.onload = null; + scriptElement.onreadystatechange = null; + scriptElement = createScriptElement(fallbackUrl); + scriptElement.onload = scriptElementCallback; + scriptElement.onreadystatechange = scriptElementCallback; + head.appendChild(scriptElement); + } +} + +function saveBaseUrl(baseUrl, officeIndex, filename) { + var languageUrl = filename.substring(0, officeIndex); + var lastIndexOfSlash = languageUrl.lastIndexOf("/", languageUrl.length - 2); + + if (lastIndexOfSlash === -1) { + lastIndexOfSlash = languageUrl.lastIndexOf("\\", languageUrl.length - 2); + } + + if (lastIndexOfSlash !== -1 && languageUrl.length > lastIndexOfSlash + 1) { + baseUrl = languageUrl.substring(0, lastIndexOfSlash + 1); + } + + return baseUrl; +} +// CONCATENATED MODULE: ./src/utils/getErrorForTelemetry.ts +var getErrorForTelemetry = function getErrorForTelemetry(resultCode, responseDictionary) { + return resultCode; +}; +// CONCATENATED MODULE: ./src/utils/isOwaOnly.ts +var isOwaOnly = function isOwaOnly(dispid) { + switch (dispid) { + case 402: + case 401: + case 400: + case 403: + return true; + + default: + return false; + } +}; +// CONCATENATED MODULE: ./src/utils/InvokeResultCode.ts +var InvokeResultCode; + +(function (InvokeResultCode) { + InvokeResultCode[InvokeResultCode["noError"] = 0] = "noError"; + InvokeResultCode[InvokeResultCode["errorInRequest"] = -1] = "errorInRequest"; + InvokeResultCode[InvokeResultCode["errorHandlingRequest"] = -2] = "errorHandlingRequest"; + InvokeResultCode[InvokeResultCode["errorInResponse"] = -3] = "errorInResponse"; + InvokeResultCode[InvokeResultCode["errorHandlingResponse"] = -4] = "errorHandlingResponse"; + InvokeResultCode[InvokeResultCode["errorHandlingRequestAccessDenied"] = -5] = "errorHandlingRequestAccessDenied"; + InvokeResultCode[InvokeResultCode["errorHandlingMethodCallTimedout"] = -6] = "errorHandlingMethodCallTimedout"; +})(InvokeResultCode || (InvokeResultCode = {})); +// CONCATENATED MODULE: ./src/utils/getErrorArgs.ts + + +var getErrorArgs_OSF = __webpack_require__(0); + +var isInitialized = false; +function getErrorArgs(detailedErrorCode) { + if (!isInitialized) { + initialize(); + } + + return getErrorArgs_OSF.DDA.ErrorCodeManager.getErrorArgs(detailedErrorCode); +} +var totalRecipientsLimit = 500; +var sessionDataLengthLimit = 50000; +function initialize() { + addErrorMessage(9000, "AttachmentSizeExceeded", getString("l_AttachmentExceededSize_Text")); + addErrorMessage(9001, "NumberOfAttachmentsExceeded", getString("l_ExceededMaxNumberOfAttachments_Text")); + addErrorMessage(9002, "InternalFormatError", getString("l_InternalFormatError_Text")); + addErrorMessage(9003, "InvalidAttachmentId", getString("l_InvalidAttachmentId_Text")); + addErrorMessage(9004, "InvalidAttachmentPath", getString("l_InvalidAttachmentPath_Text")); + addErrorMessage(9005, "CannotAddAttachmentBeforeUpgrade", getString("l_CannotAddAttachmentBeforeUpgrade_Text")); + addErrorMessage(9006, "AttachmentDeletedBeforeUploadCompletes", getString("l_AttachmentDeletedBeforeUploadCompletes_Text")); + addErrorMessage(9007, "AttachmentUploadGeneralFailure", getString("l_AttachmentUploadGeneralFailure_Text")); + addErrorMessage(9008, "AttachmentToDeleteDoesNotExist", getString("l_DeleteAttachmentDoesNotExist_Text")); + addErrorMessage(9009, "AttachmentDeleteGeneralFailure", getString("l_AttachmentDeleteGeneralFailure_Text")); + addErrorMessage(9010, "InvalidEndTime", getString("l_InvalidEndTime_Text")); + addErrorMessage(9011, "HtmlSanitizationFailure", getString("l_HtmlSanitizationFailure_Text")); + addErrorMessage(9012, "NumberOfRecipientsExceeded", getString("l_NumberOfRecipientsExceeded_Text").replace("{0}", totalRecipientsLimit)); + addErrorMessage(9013, "NoValidRecipientsProvided", getString("l_NoValidRecipientsProvided_Text")); + addErrorMessage(9014, "CursorPositionChanged", getString("l_CursorPositionChanged_Text")); + addErrorMessage(9016, "InvalidSelection", getString("l_InvalidSelection_Text")); + addErrorMessage(9017, "AccessRestricted", ""); + addErrorMessage(9018, "GenericTokenError", ""); + addErrorMessage(9019, "GenericSettingsError", ""); + addErrorMessage(9020, "GenericResponseError", ""); + addErrorMessage(9021, "SaveError", getString("l_SaveError_Text")); + addErrorMessage(9022, "MessageInDifferentStoreError", getString("l_MessageInDifferentStoreError_Text")); + addErrorMessage(9023, "DuplicateNotificationKey", getString("l_DuplicateNotificationKey_Text")); + addErrorMessage(9024, "NotificationKeyNotFound", getString("l_NotificationKeyNotFound_Text")); + addErrorMessage(9025, "NumberOfNotificationsExceeded", getString("l_NumberOfNotificationsExceeded_Text")); + addErrorMessage(9026, "PersistedNotificationArrayReadError", getString("l_PersistedNotificationArrayReadError_Text")); + addErrorMessage(9027, "PersistedNotificationArraySaveError", getString("l_PersistedNotificationArraySaveError_Text")); + addErrorMessage(9028, "CannotPersistPropertyInUnsavedDraftError", getString("l_CannotPersistPropertyInUnsavedDraftError_Text")); + addErrorMessage(9029, "CanOnlyGetTokenForSavedItem", getString("l_CallSaveAsyncBeforeToken_Text")); + addErrorMessage(9030, "APICallFailedDueToItemChange", getString("l_APICallFailedDueToItemChange_Text")); + addErrorMessage(9031, "InvalidParameterValueError", getString("l_InvalidParameterValueError_Text")); + addErrorMessage(9032, "ApiCallNotSupportedByExtensionPoint", getString("l_API_Not_Supported_By_ExtensionPoint_Error_Text")); + addErrorMessage(9033, "SetRecurrenceOnInstanceError", getString("l_Recurrence_Error_Instance_SetAsync_Text")); + addErrorMessage(9034, "InvalidRecurrenceError", getString("l_Recurrence_Error_Properties_Invalid_Text")); + addErrorMessage(9035, "RecurrenceZeroOccurrences", getString("l_RecurrenceErrorZeroOccurrences_Text")); + addErrorMessage(9036, "RecurrenceMaxOccurrences", getString("l_RecurrenceErrorMaxOccurrences_Text")); + addErrorMessage(9037, "RecurrenceInvalidTimeZone", getString("l_RecurrenceInvalidTimeZone_Text")); + addErrorMessage(9038, "InsufficientItemPermissionsError", getString("l_Insufficient_Item_Permissions_Text")); + addErrorMessage(9039, "RecurrenceUnsupportedAlternateCalendar", getString("l_RecurrenceUnsupportedAlternateCalendar_Text")); + addErrorMessage(9040, "HTTPRequestFailure", getString("l_Olk_Http_Error_Text")); + addErrorMessage(9041, "NetworkError", getString("l_Internet_Not_Connected_Error_Text")); + addErrorMessage(9042, "InternalServerError", getString("l_Internal_Server_Error_Text")); + addErrorMessage(9043, "AttachmentTypeNotSupported", getString("l_AttachmentNotSupported_Text")); + addErrorMessage(9044, "InvalidCategory", getString("l_Invalid_Category_Error_Text")); + addErrorMessage(9045, "DuplicateCategory", getString("l_Duplicate_Category_Error_Text")); + addErrorMessage(9046, "ItemNotSaved", getString("l_Item_Not_Saved_Error_Text")); + addErrorMessage(9047, "MissingExtendedPermissionsForAPIError", getString("l_Missing_Extended_Permissions_For_API")); + addErrorMessage(9048, "TokenAccessDenied", getString("l_TokenAccessDeniedWithoutItemContext_Text")); + addErrorMessage(9049, "ItemNotFound", getString("l_ItemNotFound_Text")); + addErrorMessage(9050, "KeyNotFound", getString("l_KeyNotFound_Text")); + addErrorMessage(9051, "SessionObjectMaxLengthExceeded", getString("l_SessionDataObjectMaxLengthExceeded_Text").replace("{0}", sessionDataLengthLimit)); + addErrorMessage(9052, "AttachmentResourceNotFound", getString("l_Attachment_Resource_Not_Found")); + addErrorMessage(9053, "AttachmentResourceUnAuthorizedAccess", getString("l_Attachment_Resource_UnAuthorizedAccess")); + addErrorMessage(9054, "AttachmentDownloadFailed", getString("l_Attachment_Download_Failed_Generic_Error")); + addErrorMessage(9055, "APINotSupportedForSharedFolders", getString("l_API_Not_Supported_For_Shared_Folders_Error")); + isInitialized = true; +} +function addErrorMessage(code, error, message) { + getErrorArgs_OSF.DDA.ErrorCodeManager.addErrorMessage(code, { + name: error, + message: message + }); +} +// CONCATENATED MODULE: ./src/utils/AdditionalGlobalParameters.ts +var additionalOutlookGlobalParameters; +var getAdditionalGlobalParametersSingleton = function getAdditionalGlobalParametersSingleton() { + return additionalOutlookGlobalParameters; +}; +var recreateAdditionalGlobalParametersSingleton = function recreateAdditionalGlobalParametersSingleton(parameterBlobSupported) { + additionalOutlookGlobalParameters = new AdditionalGlobalParameters(); + additionalOutlookGlobalParameters.parameterBlobSupported = true; + return additionalOutlookGlobalParameters; +}; + +var AdditionalGlobalParameters = function () { + function AdditionalGlobalParameters() { + this._parameterBlobSupported = true; + this._itemNumber = 0; + additionalOutlookGlobalParameters = this; + } + + Object.defineProperty(AdditionalGlobalParameters.prototype, "parameterBlobSupported", { + set: function set(supported) { + this._parameterBlobSupported = supported; + }, + enumerable: true, + configurable: true + }); + + AdditionalGlobalParameters.prototype.setActionsDefinition = function (actionsDefinitionIn) { + this._actionsDefinition = actionsDefinitionIn; + }; + + AdditionalGlobalParameters.prototype.setCurrentItemNumber = function (itemNumberIn) { + if (itemNumberIn > 0) { + this._itemNumber = itemNumberIn; + } + }; + + Object.defineProperty(AdditionalGlobalParameters.prototype, "itemNumber", { + get: function get() { + return this._itemNumber; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(AdditionalGlobalParameters.prototype, "actionsDefinition", { + get: function get() { + return this._actionsDefinition; + }, + enumerable: true, + configurable: true + }); + + AdditionalGlobalParameters.prototype.updateOutlookExecuteParameters = function (executeParameters, additionalApiParameters) { + var outParameters = executeParameters; + + if (this._parameterBlobSupported) { + if (this._itemNumber > 0) { + additionalApiParameters.itemNumber = this._itemNumber.toString(); + } + + if (this._actionsDefinition != null) { + additionalApiParameters.actions = this.actionsDefinition; + } + + if (Object.keys(additionalApiParameters).length === 0) { + return outParameters; + } + + if (outParameters == null) { + outParameters = []; + } + + outParameters.push(JSON.stringify(additionalApiParameters)); + } + + return outParameters; + }; + + return AdditionalGlobalParameters; +}(); + + +// CONCATENATED MODULE: ./src/utils/callOutlookNativeDispatcher.ts + + +var callOutlookNativeDispatcher_OSF = __webpack_require__(0); + +var callOutlookNativeDispatcher_callOutlookNativeDispatcher = function callOutlookNativeDispatcher(dispid, data, responseCallback) { + var executeParameters = callOutlookNativeDispatcher_convertToOutlookNativeParameters(dispid, data); + callOutlookNativeDispatcher_OSF.ClientHostController.execute(dispid, executeParameters, function (nativeData, resultCode) { + var deserializedData = null; + var responseData = nativeData.toArray(); + + if (responseData.length > 0) { + var itemNumberFromOutlookResponse = getItemNumberFromOutlookResponse(responseData); + var isValidItemNumberFromOutlookResponse = itemNumberFromOutlookResponse > 0; + var itemNumberInternal = 0; + + if (getAdditionalGlobalParametersSingleton()) { + itemNumberInternal = getAdditionalGlobalParametersSingleton().itemNumber; + } + + var isValidItemNumberInternal = itemNumberInternal > 0; + var itemChanged = isValidItemNumberFromOutlookResponse && isValidItemNumberInternal && itemNumberFromOutlookResponse > itemNumberInternal; + deserializedData = createDeserializedData(responseData, itemChanged); + } + + if (responseCallback != null) { + responseCallback(resultCode, deserializedData); + } + }); +}; +var callOutlookNativeDispatcher_convertToOutlookNativeParameters = function convertToOutlookNativeParameters(dispid, data) { + var executeParameters = null; + var optionalParameters = {}; + + switch (dispid) { + case 12: + optionalParameters.isRest = data.isRest; + break; + + case 4: + { + var jsonProperty = JSON.stringify(data.customProperties); + executeParameters = [jsonProperty]; + break; + } + + case 5: + executeParameters = new Array(data.body); + break; + + case 8: + case 9: + case 179: + case 180: + executeParameters = new Array(data.itemId); + break; + + case 7: + case 177: + executeParameters = new Array(convertRecipientArrayParameterForOutlookForDisplayApi(data.requiredAttendees), convertRecipientArrayParameterForOutlookForDisplayApi(data.optionalAttendees), data.start, data.end, data.location, convertRecipientArrayParameterForOutlookForDisplayApi(data.resources), data.subject, data.body); + break; + + case 44: + case 178: + executeParameters = [convertRecipientArrayParameterForOutlookForDisplayApi(data.toRecipients), convertRecipientArrayParameterForOutlookForDisplayApi(data.ccRecipients), convertRecipientArrayParameterForOutlookForDisplayApi(data.bccRecipients), data.subject, data.htmlBody, data.attachments]; + break; + + case 43: + executeParameters = [data.ewsIdOrEmail]; + break; + + case 45: + executeParameters = [data.module, data.queryString]; + break; + + case 40: + executeParameters = [data.extensionId, data.consentState]; + break; + + case 11: + case 10: + case 184: + case 183: + executeParameters = [data.htmlBody]; + break; + + case 31: + case 30: + case 182: + case 181: + executeParameters = [data.htmlBody, data.attachments]; + break; + + case 23: + case 13: + case 38: + case 29: + executeParameters = [data.data, data.coercionType]; + break; + + case 37: + case 28: + executeParameters = [data.coercionType]; + break; + + case 17: + executeParameters = [data.subject]; + break; + + case 15: + executeParameters = [data.recipientField]; + break; + + case 22: + case 21: + executeParameters = [data.recipientField, convertComposeEmailDictionaryParameterForSetApi(data.recipientArray)]; + break; + + case 19: + executeParameters = [data.itemId, data.name]; + break; + + case 16: + executeParameters = [data.uri, data.name, data.isInline]; + break; + + case 148: + executeParameters = [data.base64String, data.name, data.isInline]; + break; + + case 20: + executeParameters = [data.attachmentIndex]; + break; + + case 25: + executeParameters = [data.TimeProperty, data.time]; + break; + + case 24: + executeParameters = [data.TimeProperty]; + break; + + case 27: + executeParameters = [data.location]; + break; + + case 33: + case 35: + executeParameters = [data.key, data.type, data.persistent, data.message, data.icon]; + getAdditionalGlobalParametersSingleton().setActionsDefinition(data.actions); + break; + + case 36: + executeParameters = [data.key]; + break; + + default: + optionalParameters = data || {}; + break; + } + + if (dispid !== 1) { + executeParameters = getAdditionalGlobalParametersSingleton().updateOutlookExecuteParameters(executeParameters, optionalParameters); + } + + return executeParameters; +}; + +var convertRecipientArrayParameterForOutlookForDisplayApi = function convertRecipientArrayParameterForOutlookForDisplayApi(recipients) { + return recipients != null ? recipients.join(";") : ""; +}; + +var convertComposeEmailDictionaryParameterForSetApi = function convertComposeEmailDictionaryParameterForSetApi(recipients) { + var results = []; + + if (recipients == null) { + return results; + } + + for (var i = 0; i < recipients.length; i++) { + var newRecipient = [recipients[i].address, recipients[i].name]; + results.push(newRecipient); + } + + return results; +}; + +var getItemNumberFromOutlookResponse = function getItemNumberFromOutlookResponse(responseData) { + var itemNumber = 0; + + if (responseData.length > 2) { + var extraParameters = JSON.parse(responseData[2]); + + if (!!extraParameters && typeof extraParameters === "object") { + itemNumber = extraParameters.itemNumber; + } + } + + return itemNumber; +}; +var createDeserializedData = function createDeserializedData(responseData, itemChanged) { + var deserializedData = null; + var returnValues = JSON.parse(responseData[0]); + + if (typeof returnValues === "number") { + deserializedData = createDeserializedDataWithInt(responseData, itemChanged); + } else if (!!returnValues && typeof returnValues === "object") { + deserializedData = createDeserializedDataWithDictionary(responseData, itemChanged); + } else { + throw new Error("Return data type from host must be Object or Number"); + } + + return deserializedData; +}; + +var createDeserializedDataWithDictionary = function createDeserializedDataWithDictionary(responseData, itemChanged) { + var deserializedData = JSON.parse(responseData[0]); + + if (itemChanged) { + deserializedData.error = true; + deserializedData.errorCode = 9030; + } else if (responseData.length > 1 && responseData[1] !== 0) { + deserializedData.error = true; + deserializedData.errorCode = responseData[1]; + + if (responseData.length > 2) { + var diagnosticsData = JSON.parse(responseData[2]); + deserializedData.diagnostics = diagnosticsData["Diagnostics"]; + } + } else { + deserializedData.error = false; + } + + return deserializedData; +}; + +var createDeserializedDataWithInt = function createDeserializedDataWithInt(responseData, itemChanged) { + var deserializedData = {}; + deserializedData.error = true; + deserializedData.errorCode = responseData[0]; + return deserializedData; +}; +// CONCATENATED MODULE: ./src/api/standardInvokeHostMethod.ts + + + + + + + + +var standardInvokeHostMethod_OSF = __webpack_require__(0); + +function standardInvokeHostMethod(dispid, userContext, callback, data, format, customResponse) { + standardInvokeHostMethod_invokeHostMethod(dispid, data, function (resultCode, response) { + if (callback) { + var asyncResult = void 0; + var wasSuccessful = true; + + if (typeof response === "object" && response !== null) { + if (response.wasSuccessful !== undefined) { + wasSuccessful = response.wasSuccessful; + } + + if (response.error !== undefined || response.errorCode !== undefined || response.data !== undefined) { + if (!response.error) { + var formattedData = format ? format(response.data) : response.data; + asyncResult = createAsyncResult(formattedData, standardInvokeHostMethod_OSF.DDA.AsyncResultEnum.ErrorCode.Success, 0, userContext); + } else { + var errorCode = response.errorCode; + asyncResult = createAsyncResult(undefined, standardInvokeHostMethod_OSF.DDA.AsyncResultEnum.ErrorCode.Failed, errorCode, userContext); + } + } + + if (customResponse) { + asyncResult = customResponse(response, userContext, resultCode); + } + + if (!asyncResult && resultCode !== InvokeResultCode.noError) { + asyncResult = createAsyncResult(undefined, standardInvokeHostMethod_OSF.DDA.AsyncResultEnum.ErrorCode.Failed, 9002, userContext); + } + + if (!asyncResult && resultCode === InvokeResultCode.noError && wasSuccessful === false) { + asyncResult = createAsyncResult(undefined, standardInvokeHostMethod_OSF.DDA.AsyncResultEnum.ErrorCode.Failed, standardInvokeHostMethod_OSF.DDA.ErrorCodeManager.errorCodes.ooeOperationNotSupported, userContext); + } + + if (!asyncResult && !customResponse && !response.errorCode && wasSuccessful === true) { + var formattedData = format ? format(response.data) : response.data; + asyncResult = createAsyncResult(formattedData, standardInvokeHostMethod_OSF.DDA.AsyncResultEnum.ErrorCode.Success, 0, userContext); + } + + callback(asyncResult); + } + } + }); +} +function createAsyncResult(value, errorCode, detailedErrorCode, userContext, errorMessage) { + var initArgs = {}; + var errorArgs; + initArgs[standardInvokeHostMethod_OSF.DDA.AsyncResultEnum.Properties.Value] = value; + initArgs[standardInvokeHostMethod_OSF.DDA.AsyncResultEnum.Properties.Context] = userContext; + + if (standardInvokeHostMethod_OSF.DDA.AsyncResultEnum.ErrorCode.Success !== errorCode) { + errorArgs = {}; + var errorProperties = getErrorArgs(detailedErrorCode); + errorArgs[standardInvokeHostMethod_OSF.DDA.AsyncResultEnum.ErrorProperties.Name] = errorProperties.name; + errorArgs[standardInvokeHostMethod_OSF.DDA.AsyncResultEnum.ErrorProperties.Message] = !errorMessage ? errorProperties.message : errorMessage; + errorArgs[standardInvokeHostMethod_OSF.DDA.AsyncResultEnum.ErrorProperties.Code] = detailedErrorCode; + } + + return new standardInvokeHostMethod_OSF.DDA.AsyncResult(initArgs, errorArgs); +} +var standardInvokeHostMethod_invokeHostMethod = function invokeHostMethod(dispid, data, responseCallback) { + if (standardInvokeHostMethod_OSF.AppName.OutlookWebApp === getAppName() || !isOwaOnly(dispid)) { + var dataTransform = { + toSafeArrayHost: function toSafeArrayHost() { + return callOutlookNativeDispatcher_convertToOutlookNativeParameters(dispid, data); + }, + fromSafeArrayHost: function fromSafeArrayHost(payload) { + return payload; + }, + toWebHost: function toWebHost() { + return data; + }, + fromWebHost: function fromWebHost(payload) { + return payload; + } + }; + + standardInvokeHostMethod_OSF._OfficeAppFactory.getAsyncMethodExecutor().executeAsync(dispid, dataTransform, function (resultCode, response) { + var start = performance && performance.now(); + + if (standardInvokeHostMethod_OSF.AppTelemetry) { + var detailedErrorCode = getErrorForTelemetry(resultCode, response); + var end = performance && performance.now(); + standardInvokeHostMethod_OSF.AppTelemetry.onMethodDone(dispid, null, Math.round(end - start), detailedErrorCode); + } + + if (responseCallback) { + var deserializedData = response; + + if (standardInvokeHostMethod_OSF.AppName.OutlookWebApp !== getAppName() && !isOwaOnly(dispid)) { + if (response.length > 0) { + var itemNumberFromOutlookResponse = getItemNumberFromOutlookResponse(response); + var isValidItemNumberFromOutlookResponse = itemNumberFromOutlookResponse > 0; + var itemNumberInternal = 0; + + if (getAdditionalGlobalParametersSingleton()) { + itemNumberInternal = getAdditionalGlobalParametersSingleton().itemNumber; + } + + var isValidItemNumberInternal = itemNumberInternal > 0; + var itemChanged = isValidItemNumberFromOutlookResponse && isValidItemNumberInternal && itemNumberFromOutlookResponse > itemNumberInternal; + deserializedData = createDeserializedData(response, itemChanged); + } + } + + responseCallback(resultCode, deserializedData); + } + }); + } else { + responseCallback(InvokeResultCode.errorHandlingRequest, null); + } +}; +// CONCATENATED MODULE: ./src/utils/getPermissionLevel.ts + + +var getPermissionLevel_getPermissionLevel = function getPermissionLevel() { + var permissionLevel = getInitialDataProp("permissionLevel"); + + if (isNullOrUndefined(permissionLevel)) { + return -1; + } + + return permissionLevel; +}; +// CONCATENATED MODULE: ./src/utils/createError.ts +function createError(message, errorInfo) { + var err = new Error(message); + err.message = message || ""; + + if (errorInfo) { + for (var v in errorInfo) { + err[v] = errorInfo[v]; + } + } + + return err; +} +function createBetaError(featureName) { + var displayMessage = "The feature {0}, is only enabled on the beta api endpoint".replace("{0}", featureName); + var err = createError(displayMessage, { + name: "Sys.FeatureNotEnabled" + }); + return err; +} +function createParameterCountError(message) { + var displayMessage = "Sys.ParameterCountException: " + (message ? message : "Parameter count mismatch."); + var err = createError(displayMessage, { + name: "Sys.ParameterCountException" + }); + return err; +} +function createArgumentError(paramName, message) { + var displayMessage = "Sys.ArgumentException: " + (message ? message : "Value does not fall within the expected range."); + + if (paramName) { + displayMessage += "\n" + "Parameter name: {0}".replace("{0}", paramName); + } + + var err = createError(displayMessage, { + name: "Sys.ArgumentException", + paramName: paramName + }); + return err; +} +function createNullItemError(namespace) { + var displayMessage = "Invalid operation ({0}) when Office.context.mailbox.item is null.".replace("{0}", namespace); + var err = createError(displayMessage); + return err; +} +function createNullArgumentError(paramName, message) { + var displayMessage = "Sys.ArgumentNullException: " + (message ? message : "Value cannot be null."); + + if (paramName) { + displayMessage += "\n" + "Parameter name: {0}".replace("{0}", paramName); + } + + var err = createError(displayMessage, { + name: "Sys.ArgumentNullException", + paramName: paramName + }); + return err; +} +function createArgumentOutOfRange(paramName, actualValue, message) { + var displayMessage = "Sys.ArgumentOutOfRangeException: " + (message ? message : "Specified argument was out of the range of valid values."); + + if (paramName) { + displayMessage += "\n" + "Parameter name: {0}".replace("{0}", paramName); + } + + if (typeof actualValue !== "undefined" && actualValue !== null) { + displayMessage += "\n" + "Actual value was {0}.".replace("{0}", actualValue); + } + + var err = createError(displayMessage, { + name: "Sys.ArgumentOutOfRangeException", + paramName: paramName, + actualValue: actualValue + }); + return err; +} +function createArgumentTypeError(paramName, actualType, expectedType, message) { + var displayMessage = "Sys.ArgumentTypeException: "; + + if (message) { + displayMessage += message; + } else if (actualType && expectedType) { + displayMessage += "Object of type '{0}' cannot be converted to type '{1}'.".replace("{0}", actualType.getName ? actualType.getName() : actualType).replace("{1}", expectedType.getName ? expectedType.getName() : expectedType); + } else { + displayMessage += "Object cannot be converted to the required type."; + } + + if (paramName) { + displayMessage += "\n" + "Parameter name: {0}".replace("{0}", paramName); + } + + var err = createError(displayMessage, { + name: "Sys.ArgumentTypeException", + paramName: paramName, + actualType: actualType, + expectedType: expectedType + }); + return err; +} +// CONCATENATED MODULE: ./src/utils/checkPermissionsAndThrow.ts + + + +function checkPermissionsAndThrow(permissions, namespace) { + if (getPermissionLevel_getPermissionLevel() == -1) { + throw createNullItemError(namespace); + } + + if (getPermissionLevel_getPermissionLevel() < permissions) { + throw createError(getString("l_ElevatedPermissionNeededForMethod_Text").replace("{0}", namespace)); + } +} +// CONCATENATED MODULE: ./src/utils/parseCommonArgs.ts + + +function parseCommonArgs(args, isCallbackRequired, tryLegacy) { + var result = {}; + + if (tryLegacy) { + result = tryParseLegacy(args); + + if (result.callback) { + return result; + } + } + + if (args.length === 1) { + if (typeof args[0] === "function") { + result.callback = args[0]; + } else if (typeof args[0] === "object") { + result.options = args[0]; + } else { + throw createArgumentTypeError(); + } + } else if (args.length === 2) { + if (typeof args[0] !== "object") { + throw createArgumentError("options"); + } + + if (typeof args[1] !== "function") { + throw createArgumentError("callback"); + } + + result.callback = args[1]; + result.options = args[0]; + } else if (args.length !== 0) { + throw createParameterCountError(getString("l_ParametersNotAsExpected_Text")); + } + + if (isCallbackRequired && !result.callback) { + throw createNullArgumentError("callback"); + } + + if (result.options && result.options.asyncContext) { + result.asyncContext = result.options.asyncContext; + } + + return result; +} + +function tryParseLegacy(args) { + var result = {}; + + if (args.length === 1 || args.length === 2) { + if (typeof args[0] !== "function") { + return result; + } + + result.callback = args[0]; + + if (args.length === 2) { + result.asyncContext = args[1]; + } + + return result; + } + + return result; +} +// CONCATENATED MODULE: ./src/validation/recipientConstants.ts +var RecipientFields; + +(function (RecipientFields) { + RecipientFields[RecipientFields["to"] = 0] = "to"; + RecipientFields[RecipientFields["cc"] = 1] = "cc"; + RecipientFields[RecipientFields["bcc"] = 2] = "bcc"; + RecipientFields[RecipientFields["requiredAttendees"] = 0] = "requiredAttendees"; + RecipientFields[RecipientFields["optionalAttendees"] = 1] = "optionalAttendees"; +})(RecipientFields || (RecipientFields = {})); + +var displayNameLengthLimit = 255; +var recipientsLimit = 100; +var recipientConstants_totalRecipientsLimit = 500; +var maxSmtpLength = 571; +// CONCATENATED MODULE: ./src/validation/displayConstants.ts +var maxLocationLength = 255; +var maxBodyLength = 32 * 1024; +var maxSubjectLength = 255; +var maxRecipients = 100; +var MaxAttachmentNameLength = 255; +var MaxUrlLength = 2048; +var MaxItemIdLength = 200; +var MaxRemoveIdLength = 200; +// CONCATENATED MODULE: ./src/utils/throwOnOutOfRange.ts + +function throwOnOutOfRange(value, minValue, maxValue, argumentName) { + if (value < minValue || value > maxValue) { + throw createArgumentOutOfRange(String(argumentName)); + } +} +// CONCATENATED MODULE: ./src/utils/OutlookEnums.ts +var MailboxEnums = {}; +MailboxEnums.EntityType = { + MeetingSuggestion: "meetingSuggestion", + TaskSuggestion: "taskSuggestion", + Address: "address", + EmailAddress: "emailAddress", + Url: "url", + PhoneNumber: "phoneNumber", + Contact: "contact", + FlightReservations: "flightReservations", + ParcelDeliveries: "parcelDeliveries" +}; +MailboxEnums.ItemType = { + Message: "message", + Appointment: "appointment" +}; +MailboxEnums.ResponseType = { + None: "none", + Organizer: "organizer", + Tentative: "tentative", + Accepted: "accepted", + Declined: "declined" +}; +MailboxEnums.RecipientType = { + Other: "other", + DistributionList: "distributionList", + User: "user", + ExternalUser: "externalUser" +}; +MailboxEnums.AttachmentType = { + File: "file", + Item: "item", + Cloud: "cloud" +}; +MailboxEnums.AttachmentStatus = { + Added: "added", + Removed: "removed" +}; +MailboxEnums.AttachmentContentFormat = { + Base64: "base64", + Url: "url", + Eml: "eml", + ICalendar: "iCalendar" +}; +MailboxEnums.BodyType = { + Text: "text", + Html: "html" +}; +MailboxEnums.ItemNotificationMessageType = { + ProgressIndicator: "progressIndicator", + InformationalMessage: "informationalMessage", + ErrorMessage: "errorMessage", + InsightMessage: "insightMessage" +}; +MailboxEnums.Folder = { + Inbox: "inbox", + Junk: "junk", + DeletedItems: "deletedItems" +}; +MailboxEnums.ComposeType = { + Forward: "forward", + NewMail: "newMail", + Reply: "reply" +}; +var CoercionType = { + Text: "text", + Html: "html" +}; +MailboxEnums.UserProfileType = { + Office365: "office365", + OutlookCom: "outlookCom", + Enterprise: "enterprise" +}; +MailboxEnums.RestVersion = { + v1_0: "v1.0", + v2_0: "v2.0", + Beta: "beta" +}; +MailboxEnums.ModuleType = { + Addins: "addins" +}; +MailboxEnums.ActionType = { + ShowTaskPane: "showTaskPane" +}; +MailboxEnums.Days = { + Mon: "mon", + Tue: "tue", + Wed: "wed", + Thu: "thu", + Fri: "fri", + Sat: "sat", + Sun: "sun", + Weekday: "weekday", + WeekendDay: "weekendDay", + Day: "day" +}; +MailboxEnums.WeekNumber = { + First: "first", + Second: "second", + Third: "third", + Fourth: "fourth", + Last: "last" +}; +MailboxEnums.RecurrenceType = { + Daily: "daily", + Weekday: "weekday", + Weekly: "weekly", + Monthly: "monthly", + Yearly: "yearly" +}; +MailboxEnums.Month = { + Jan: "jan", + Feb: "feb", + Mar: "mar", + Apr: "apr", + May: "may", + Jun: "jun", + Jul: "jul", + Aug: "aug", + Sep: "sep", + Oct: "oct", + Nov: "nov", + Dec: "dec" +}; +MailboxEnums.DelegatePermissions = { + Read: 0x00000001, + Write: 0x00000002, + DeleteOwn: 0x00000004, + DeleteAll: 0x00000008, + EditOwn: 0x00000010, + EditAll: 0x00000020 +}; +MailboxEnums.TimeZone = { + AfghanistanStandardTime: "Afghanistan Standard Time", + AlaskanStandardTime: "Alaskan Standard Time", + AleutianStandardTime: "Aleutian Standard Time", + AltaiStandardTime: "Altai Standard Time", + ArabStandardTime: "Arab Standard Time", + ArabianStandardTime: "Arabian Standard Time", + ArabicStandardTime: "Arabic Standard Time", + ArgentinaStandardTime: "Argentina Standard Time", + AstrakhanStandardTime: "Astrakhan Standard Time", + AtlanticStandardTime: "Atlantic Standard Time", + AUSCentralStandardTime: "AUS Central Standard Time", + AusCentralWStandardTime: "Aus Central W. Standard Time", + AUSEasternStandardTime: "AUS Eastern Standard Time", + AzerbaijanStandardTime: "Azerbaijan Standard Time", + AzoresStandardTime: "Azores Standard Time", + BahiaStandardTime: "Bahia Standard Time", + BangladeshStandardTime: "Bangladesh Standard Time", + BelarusStandardTime: "Belarus Standard Time", + BougainvilleStandardTime: "Bougainville Standard Time", + CanadaCentralStandardTime: "Canada Central Standard Time", + CapeVerdeStandardTime: "Cape Verde Standard Time", + CaucasusStandardTime: "Caucasus Standard Time", + CenAustraliaStandardTime: "Cen. Australia Standard Time", + CentralAmericaStandardTime: "Central America Standard Time", + CentralAsiaStandardTime: "Central Asia Standard Time", + CentralBrazilianStandardTime: "Central Brazilian Standard Time", + CentralEuropeStandardTime: "Central Europe Standard Time", + CentralEuropeanStandardTime: "Central European Standard Time", + CentralPacificStandardTime: "Central Pacific Standard Time", + CentralStandardTime: "Central Standard Time", + CentralStandardTime_Mexico: "Central Standard Time (Mexico)", + ChathamIslandsStandardTime: "Chatham Islands Standard Time", + ChinaStandardTime: "China Standard Time", + CubaStandardTime: "Cuba Standard Time", + DatelineStandardTime: "Dateline Standard Time", + EAfricaStandardTime: "E. Africa Standard Time", + EAustraliaStandardTime: "E. Australia Standard Time", + EEuropeStandardTime: "E. Europe Standard Time", + ESouthAmericaStandardTime: "E. South America Standard Time", + EasterIslandStandardTime: "Easter Island Standard Time", + EasternStandardTime: "Eastern Standard Time", + EasternStandardTime_Mexico: "Eastern Standard Time (Mexico)", + EgyptStandardTime: "Egypt Standard Time", + EkaterinburgStandardTime: "Ekaterinburg Standard Time", + FijiStandardTime: "Fiji Standard Time", + FLEStandardTime: "FLE Standard Time", + GeorgianStandardTime: "Georgian Standard Time", + GMTStandardTime: "GMT Standard Time", + GreenlandStandardTime: "Greenland Standard Time", + GreenwichStandardTime: "Greenwich Standard Time", + GTBStandardTime: "GTB Standard Time", + HaitiStandardTime: "Haiti Standard Time", + HawaiianStandardTime: "Hawaiian Standard Time", + IndiaStandardTime: "India Standard Time", + IranStandardTime: "Iran Standard Time", + IsraelStandardTime: "Israel Standard Time", + JordanStandardTime: "Jordan Standard Time", + KaliningradStandardTime: "Kaliningrad Standard Time", + KamchatkaStandardTime: "Kamchatka Standard Time", + KoreaStandardTime: "Korea Standard Time", + LibyaStandardTime: "Libya Standard Time", + LineIslandsStandardTime: "Line Islands Standard Time", + LordHoweStandardTime: "Lord Howe Standard Time", + MagadanStandardTime: "Magadan Standard Time", + MagallanesStandardTime: "Magallanes Standard Time", + MarquesasStandardTime: "Marquesas Standard Time", + MauritiusStandardTime: "Mauritius Standard Time", + MidAtlanticStandardTime: "Mid-Atlantic Standard Time", + MiddleEastStandardTime: "Middle East Standard Time", + MontevideoStandardTime: "Montevideo Standard Time", + MoroccoStandardTime: "Morocco Standard Time", + MountainStandardTime: "Mountain Standard Time", + MountainStandardTime_Mexico: "Mountain Standard Time (Mexico)", + MyanmarStandardTime: "Myanmar Standard Time", + NCentralAsiaStandardTime: "N. Central Asia Standard Time", + NamibiaStandardTime: "Namibia Standard Time", + NepalStandardTime: "Nepal Standard Time", + NewZealandStandardTime: "New Zealand Standard Time", + NewfoundlandStandardTime: "Newfoundland Standard Time", + NorfolkStandardTime: "Norfolk Standard Time", + NorthAsiaEastStandardTime: "North Asia East Standard Time", + NorthAsiaStandardTime: "North Asia Standard Time", + NorthKoreaStandardTime: "North Korea Standard Time", + OmskStandardTime: "Omsk Standard Time", + PacificSAStandardTime: "Pacific SA Standard Time", + PacificStandardTime: "Pacific Standard Time", + PacificStandardTime_Mexico: "Pacific Standard Time (Mexico)", + PakistanStandardTime: "Pakistan Standard Time", + ParaguayStandardTime: "Paraguay Standard Time", + RomanceStandardTime: "Romance Standard Time", + RussiaTimeZone10: "Russia Time Zone 10", + RussiaTimeZone11: "Russia Time Zone 11", + RussiaTimeZone3: "Russia Time Zone 3", + RussianStandardTime: "Russian Standard Time", + SAEasternStandardTime: "SA Eastern Standard Time", + SAPacificStandardTime: "SA Pacific Standard Time", + SAWesternStandardTime: "SA Western Standard Time", + SaintPierreStandardTime: "Saint Pierre Standard Time", + SakhalinStandardTime: "Sakhalin Standard Time", + SamoaStandardTime: "Samoa Standard Time", + SaratovStandardTime: "Saratov Standard Time", + SEAsiaStandardTime: "SE Asia Standard Time", + SingaporeStandardTime: "Singapore Standard Time", + SouthAfricaStandardTime: "South Africa Standard Time", + SriLankaStandardTime: "Sri Lanka Standard Time", + SudanStandardTime: "Sudan Standard Time", + SyriaStandardTime: "Syria Standard Time", + TaipeiStandardTime: "Taipei Standard Time", + TasmaniaStandardTime: "Tasmania Standard Time", + TocantinsStandardTime: "Tocantins Standard Time", + TokyoStandardTime: "Tokyo Standard Time", + TomskStandardTime: "Tomsk Standard Time", + TongaStandardTime: "Tonga Standard Time", + TransbaikalStandardTime: "Transbaikal Standard Time", + TurkeyStandardTime: "Turkey Standard Time", + TurksAndCaicosStandardTime: "Turks And Caicos Standard Time", + UlaanbaatarStandardTime: "Ulaanbaatar Standard Time", + USEasternStandardTime: "US Eastern Standard Time", + USMountainStandardTime: "US Mountain Standard Time", + UTC: "UTC", + UTCPLUS12: "UTC+12", + UTCPLUS13: "UTC+13", + UTCMINUS02: "UTC-02", + UTCMINUS08: "UTC-08", + UTCMINUS09: "UTC-09", + UTCMINUS11: "UTC-11", + VenezuelaStandardTime: "Venezuela Standard Time", + VladivostokStandardTime: "Vladivostok Standard Time", + WAustraliaStandardTime: "W. Australia Standard Time", + WCentralAfricaStandardTime: "W. Central Africa Standard Time", + WEuropeStandardTime: "W. Europe Standard Time", + WMongoliaStandardTime: "W. Mongolia Standard Time", + WestAsiaStandardTime: "West Asia Standard Time", + WestBankStandardTime: "West Bank Standard Time", + WestPacificStandardTime: "West Pacific Standard Time", + YakutskStandardTime: "Yakutsk Standard Time" +}; +MailboxEnums.LocationType = { + Custom: "custom", + Room: "room" +}; +MailboxEnums.AppointmentSensitivityType = { + Normal: "normal", + Personal: "personal", + Private: "private", + Confidential: "confidential" +}; +MailboxEnums.CategoryColor = { + None: "None", + Preset0: "Preset0", + Preset1: "Preset1", + Preset2: "Preset2", + Preset3: "Preset3", + Preset4: "Preset4", + Preset5: "Preset5", + Preset6: "Preset6", + Preset7: "Preset7", + Preset8: "Preset8", + Preset9: "Preset9", + Preset10: "Preset10", + Preset11: "Preset11", + Preset12: "Preset12", + Preset13: "Preset13", + Preset14: "Preset14", + Preset15: "Preset15", + Preset16: "Preset16", + Preset17: "Preset17", + Preset18: "Preset18", + Preset19: "Preset19", + Preset20: "Preset20", + Preset21: "Preset21", + Preset22: "Preset22", + Preset23: "Preset23", + Preset24: "Preset24" +}; +// CONCATENATED MODULE: ./src/utils/throwOnInvalidRestVersion.ts + + +function throwOnInvalidRestVersion(restVersion) { + if (restVersion === null || restVersion === undefined) { + throw createNullArgumentError(restVersion); + } + + if (restVersion !== MailboxEnums.RestVersion.v1_0 && restVersion !== MailboxEnums.RestVersion.v2_0 && restVersion !== MailboxEnums.RestVersion.Beta) { + throw createArgumentError(restVersion); + } +} +// CONCATENATED MODULE: ./src/utils/convertToRestId.ts + + +function convertToRestId(itemId, restVersion) { + if (itemId === null || itemId === undefined) { + throw createNullArgumentError(itemId); + } + + throwOnInvalidRestVersion(restVersion); + return itemId.replace(new RegExp("[/]", "g"), "-").replace(new RegExp("[+]", "g"), "_"); +} +// CONCATENATED MODULE: ./src/utils/convertToEwsId.ts + + +function convertToEwsId(itemId, restVersion) { + if (itemId === null || itemId === undefined) { + throw createNullArgumentError(itemId); + } + + throwOnInvalidRestVersion(restVersion); + return itemId.replace(new RegExp("[-]", "g"), "/").replace(new RegExp("[_]", "g"), "+"); +} +// CONCATENATED MODULE: ./src/validation/validateDisplayForms.ts + + + + + + + + + +function validateRecipientEmails(emailset, name) { + if (!Array.isArray(emailset)) { + throw createArgumentTypeError("name"); + } + + throwOnOutOfRange(emailset.length, 0, maxRecipients, "{0}.length".replace("{0}", name)); +} +function normalizeRecipientEmails(emailset, name) { + var originalAttendees = emailset; + var updatedAttendees = []; + + for (var i = 0; i < originalAttendees.length; i++) { + if (typeof originalAttendees[i] === "object") { + throwOnInvalidEmailAddressDetails(originalAttendees[i]); + updatedAttendees[i] = originalAttendees[i].emailAddress; + + if (typeof updatedAttendees[i] !== "string") { + throw createArgumentError("{0}[{1}]".replace(name, String(i))); + } + } else { + if (!(typeof originalAttendees[i] === "string")) { + throw createArgumentError("{0}[{1}]".replace(name, String(i))); + } + + updatedAttendees[i] = originalAttendees[i]; + } + } + + return updatedAttendees; +} +function throwOnInvalidEmailAddressDetails(originalAttendee) { + if (!isNullOrUndefined(originalAttendee.displayName)) { + if (typeof originalAttendee.displayName === "string" && originalAttendee.displayName.length > displayNameLengthLimit) { + throw createArgumentOutOfRange("displayName"); + } + } + + if (!isNullOrUndefined(originalAttendee.emailAddress)) { + if (typeof originalAttendee.emailAddress === "string" && originalAttendee.emailAddress.length > maxSmtpLength) { + throw createArgumentOutOfRange("emailAddress"); + } + } + + if (!isNullOrUndefined(originalAttendee.appointmentResponse)) { + if (typeof originalAttendee.appointmentResponse !== "string") { + throw createArgumentOutOfRange("appointmentResponse"); + } + } + + if (!isNullOrUndefined(originalAttendee.recipientType)) { + if (typeof originalAttendee.recipientType !== "string") { + throw createArgumentOutOfRange("recipientType"); + } + } +} +function validateDisplayFormParameters(itemId) { + if (typeof itemId === "string") { + throwOnInvalidItemId(itemId); + } else { + throw createArgumentTypeError("itemId"); + } +} + +function throwOnInvalidItemId(itemId) { + if (isNullOrUndefined(itemId) || itemId === "") { + throw createNullArgumentError("itemId"); + } +} + +function getItemIdBasedOnHost(itemId) { + if (getInitialDataProp("isRestIdSupported")) { + return convertToRestId(itemId, MailboxEnums.RestVersion.v1_0); + } + + return convertToEwsId(itemId, MailboxEnums.RestVersion.v1_0); +} +// CONCATENATED MODULE: ./src/utils/RuntimeFlighting.ts + +var beta = 2; +var production = 1; +var currentLevel; +currentLevel = production; +var getCurrentLevel = function getCurrentLevel() { + return currentLevel; +}; +var Features = { + featureSampleProduction: production, + featureSampleBeta: beta, + displayXAsync: production, + propertyGetAll: production, + calendarItems: beta, + signature: beta, + replyCallback: beta, + sessionData: beta +}; +function isFeatureEnabled(feature) { + return feature <= getCurrentLevel(); +} +function checkFeatureEnabledAndThrow(feature, featureName) { + if (!isFeatureEnabled(feature)) { + throw createBetaError(featureName); + } +} +// CONCATENATED MODULE: ./src/methods/displayAppointmentForm.ts +var __spreadArrays = undefined && undefined.__spreadArrays || function () { + for (var s = 0, i = 0, il = arguments.length; i < il; i++) { + s += arguments[i].length; + } + + for (var r = Array(s), k = 0, i = 0; i < il; i++) { + for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++) { + r[k] = a[j]; + } + } + + return r; +}; + + + + + + +function displayAppointmentForm(itemId) { + var args = []; + + for (var _i = 1; _i < arguments.length; _i++) { + args[_i - 1] = arguments[_i]; + } + + displayAppointmentFormHelper.apply(void 0, __spreadArrays([9, itemId], args)); +} +function displayAppointmentFormAsync(itemId) { + var args = []; + + for (var _i = 1; _i < arguments.length; _i++) { + args[_i - 1] = arguments[_i]; + } + + checkFeatureEnabledAndThrow(Features.displayXAsync, "displayAppointmentFormAsync"); + displayAppointmentFormHelper.apply(void 0, __spreadArrays([180, itemId], args)); +} + +function displayAppointmentFormHelper(dispidToInvoke, itemId) { + var args = []; + + for (var _i = 2; _i < arguments.length; _i++) { + args[_i - 2] = arguments[_i]; + } + + checkPermissionsAndThrow(1, "mailbox.displayAppointmentForm"); + var commonParameters = parseCommonArgs(args, false, false); + var parameters = { + itemId: itemId + }; + validateParameters(parameters); + standardInvokeHostMethod(dispidToInvoke, commonParameters.asyncContext, commonParameters.callback, { + itemId: getItemIdBasedOnHost(parameters.itemId) + }, undefined); +} + +function validateParameters(parameters) { + validateDisplayFormParameters(parameters.itemId); +} +// CONCATENATED MODULE: ./src/methods/displayMessageForm.ts +var displayMessageForm_spreadArrays = undefined && undefined.__spreadArrays || function () { + for (var s = 0, i = 0, il = arguments.length; i < il; i++) { + s += arguments[i].length; + } + + for (var r = Array(s), k = 0, i = 0; i < il; i++) { + for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++) { + r[k] = a[j]; + } + } + + return r; +}; + + + + + + +function displayMessageForm(itemId) { + var args = []; + + for (var _i = 1; _i < arguments.length; _i++) { + args[_i - 1] = arguments[_i]; + } + + displayMessageFormHelper.apply(void 0, displayMessageForm_spreadArrays([8, itemId], args)); +} +function displayMessageFormAsync(itemId) { + var args = []; + + for (var _i = 1; _i < arguments.length; _i++) { + args[_i - 1] = arguments[_i]; + } + + checkFeatureEnabledAndThrow(Features.displayXAsync, "displayMessageFormAsync"); + displayMessageFormHelper.apply(void 0, displayMessageForm_spreadArrays([179, itemId], args)); +} + +function displayMessageFormHelper(dispidToInvoke, itemId) { + var args = []; + + for (var _i = 2; _i < arguments.length; _i++) { + args[_i - 2] = arguments[_i]; + } + + checkPermissionsAndThrow(1, "mailbox.displayMessageForm"); + var commonParameters = parseCommonArgs(args, false, false); + var parameters = { + itemId: itemId + }; + displayMessageForm_validateParameters(parameters); + standardInvokeHostMethod(dispidToInvoke, commonParameters.asyncContext, commonParameters.callback, { + itemId: getItemIdBasedOnHost(parameters.itemId) + }, undefined); +} + +function displayMessageForm_validateParameters(parameters) { + validateDisplayFormParameters(parameters.itemId); +} +// CONCATENATED MODULE: ./src/utils/validateOptionalStringParameter.ts + + +function validateOptionalStringParameter(value, minLength, maxlength, name) { + if (typeof value === "string") { + throwOnOutOfRange(value.length, minLength, maxlength, name); + } else { + throw createArgumentError(String(name)); + } +} +// CONCATENATED MODULE: ./src/utils/isDateObject.ts +var isDateObject = function isDateObject(objectIn) { + return objectIn instanceof Date || Object.prototype.toString.call(objectIn) == "[object Date]"; +}; +// CONCATENATED MODULE: ./src/methods/displayNewAppointmentForm.ts +var displayNewAppointmentForm_spreadArrays = undefined && undefined.__spreadArrays || function () { + for (var s = 0, i = 0, il = arguments.length; i < il; i++) { + s += arguments[i].length; + } + + for (var r = Array(s), k = 0, i = 0; i < il; i++) { + for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++) { + r[k] = a[j]; + } + } + + return r; +}; + + + + + + + + + + + + +function displayNewAppointmentForm(parameters) { + var args = []; + + for (var _i = 1; _i < arguments.length; _i++) { + args[_i - 1] = arguments[_i]; + } + + return displayNewAppointmentFormHelper.apply(void 0, displayNewAppointmentForm_spreadArrays([7, parameters], args)); +} +function displayNewAppointmentFormAsync(parameters) { + var args = []; + + for (var _i = 1; _i < arguments.length; _i++) { + args[_i - 1] = arguments[_i]; + } + + checkFeatureEnabledAndThrow(Features.displayXAsync, "displayNewAppointmentFormAsync"); + return displayNewAppointmentFormHelper.apply(void 0, displayNewAppointmentForm_spreadArrays([177, parameters], args)); +} + +function displayNewAppointmentFormHelper(dispidToInvoke, parameters) { + var args = []; + + for (var _i = 2; _i < arguments.length; _i++) { + args[_i - 2] = arguments[_i]; + } + + checkPermissionsAndThrow(1, "mailbox.displayNewAppointmentForm"); + var commonParameters = parseCommonArgs(args, false, false); + displayNewAppointmentForm_validateParameters(parameters); + var updatedParameters = normalizeParameters(parameters); + standardInvokeHostMethod(dispidToInvoke, commonParameters.asyncContext, commonParameters.callback, updatedParameters, undefined); +} + +function displayNewAppointmentForm_validateParameters(parameters) { + if (!isNullOrUndefined(parameters.requiredAttendees)) { + validateRecipientEmails(parameters.requiredAttendees, "requiredAttendees"); + } + + if (!isNullOrUndefined(parameters.optionalAttendees)) { + validateRecipientEmails(parameters.optionalAttendees, "optionalAttendees"); + } + + if (!isNullOrUndefined(parameters.location)) { + validateOptionalStringParameter(parameters.location, 0, maxLocationLength, "location"); + } + + if (!isNullOrUndefined(parameters.body)) { + validateOptionalStringParameter(parameters.body, 0, maxBodyLength, "body"); + } + + if (!isNullOrUndefined(parameters.subject)) { + validateOptionalStringParameter(parameters.subject, 0, maxSubjectLength, "subject"); + } + + if (!isNullOrUndefined(parameters.start)) { + if (!isDateObject(parameters.start)) { + throw createArgumentError("start"); + } + + if (!isNullOrUndefined(parameters.end)) { + if (!isDateObject(parameters.end)) { + throw createArgumentError("end"); + } + + if (parameters.end && parameters.start && parameters.end < parameters.start) { + throw createArgumentError("end", getString("l_InvalidEventDates_Text")); + } + } + } +} + +function normalizeParameters(parameters) { + var normalizedRequiredAttendees = null; + var normalizedOptionalAttendees = null; + + if (!isNullOrUndefined(parameters.requiredAttendees)) { + normalizedRequiredAttendees = normalizeRecipientEmails(parameters.requiredAttendees, "requiredAttendees"); + } + + if (!isNullOrUndefined(parameters.optionalAttendees)) { + normalizedOptionalAttendees = normalizeRecipientEmails(parameters.optionalAttendees, "optionalAttendees"); + } + + if (!isNullOrUndefined(parameters.start)) { + var startDate = parameters.start; + parameters.start = startDate.getTime(); + } + + if (!isNullOrUndefined(parameters.end)) { + var endDate = parameters.end; + parameters.end = endDate.getTime(); + } + + var updatedParameters = JSON.parse(JSON.stringify(parameters)); + + if (normalizedRequiredAttendees || normalizedOptionalAttendees) { + if (!isNullOrUndefined(parameters.requiredAttendees)) { + updatedParameters.requiredAttendees = normalizedRequiredAttendees; + } + + if (!isNullOrUndefined(parameters.optionalAttendees)) { + updatedParameters.optionalAttendees = normalizedOptionalAttendees; + } + } + + return updatedParameters; +} +// CONCATENATED MODULE: ./src/methods/displayNewMessageForm.ts +var displayNewMessageForm_spreadArrays = undefined && undefined.__spreadArrays || function () { + for (var s = 0, i = 0, il = arguments.length; i < il; i++) { + s += arguments[i].length; + } + + for (var r = Array(s), k = 0, i = 0; i < il; i++) { + for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++) { + r[k] = a[j]; + } + } + + return r; +}; + + + + + + + + + + + + +function displayNewMessageForm(parameters) { + var args = []; + + for (var _i = 1; _i < arguments.length; _i++) { + args[_i - 1] = arguments[_i]; + } + + return displayNewMessageFormHelper.apply(void 0, displayNewMessageForm_spreadArrays([44, parameters], args)); +} +function displayNewMessageFormAsync(parameters) { + var args = []; + + for (var _i = 1; _i < arguments.length; _i++) { + args[_i - 1] = arguments[_i]; + } + + checkFeatureEnabledAndThrow(Features.displayXAsync, "displayNewMessageFormAsync"); + return displayNewMessageFormHelper.apply(void 0, displayNewMessageForm_spreadArrays([178, parameters], args)); +} + +function displayNewMessageFormHelper(dispidToInvoke, parameters) { + var args = []; + + for (var _i = 2; _i < arguments.length; _i++) { + args[_i - 2] = arguments[_i]; + } + + checkPermissionsAndThrow(1, "mailbox.displayNewMessageForm"); + var commonParameters = parseCommonArgs(args, false, false); + displayNewMessageForm_validateParameters(parameters); + var updatedParameters = normailzeParameters(parameters); + standardInvokeHostMethod(dispidToInvoke, commonParameters.asyncContext, commonParameters.callback, updatedParameters === null || updatedParameters === undefined ? parameters : updatedParameters, undefined); +} + +function displayNewMessageForm_validateParameters(parameters) { + if (parameters !== null && parameters !== null) { + if (!isNullOrUndefined(parameters.toRecipients)) { + validateRecipientEmails(parameters.toRecipients, "toRecipients"); + } + + if (!isNullOrUndefined(parameters.ccRecipients)) { + validateRecipientEmails(parameters.ccRecipients, "ccRecipients"); + } + + if (!isNullOrUndefined(parameters.bccRecipients)) { + validateRecipientEmails(parameters.bccRecipients, "bccRecipients"); + } + + if (!isNullOrUndefined(parameters.htmlBody)) { + validateOptionalStringParameter(parameters.htmlBody, 0, maxBodyLength, "htmlBody"); + } + + if (!isNullOrUndefined(parameters.subject)) { + validateOptionalStringParameter(parameters.subject, 0, maxSubjectLength, "subject"); + } + } +} + +function normailzeParameters(parameters) { + var updatedParameters = JSON.parse(JSON.stringify(parameters)); + + if (!isNullOrUndefined(parameters)) { + if (parameters.toRecipients) { + updatedParameters.toRecipients = normalizeRecipientEmails(parameters.toRecipients, "toRecipients"); + } + + if (parameters.ccRecipients) { + updatedParameters.ccRecipients = normalizeRecipientEmails(parameters.ccRecipients, "ccRecipients"); + } + + if (parameters.bccRecipients) { + updatedParameters.bccRecipients = normalizeRecipientEmails(parameters.bccRecipients, "bccRecipients"); + } + + var attachments = getAttachments(parameters); + + if (parameters.attachments) { + updatedParameters.attachments = createAttachmentsDataForHost(attachments); + } + } + + return updatedParameters; +} +function getAttachments(data) { + var attachments = []; + + if (data.attachments) { + attachments = data.attachments; + throwOnInvalidAttachmentsArray(attachments); + } + + return attachments; +} +function throwOnInvalidAttachmentsArray(attachments) { + if (!isNullOrUndefined(attachments) && !Array.isArray(attachments)) { + throw createArgumentError("attachments"); + } +} +function createAttachmentsDataForHost(attachments) { + var attachmentsData = []; + + for (var i = 0; i < attachments.length; i++) { + if (typeof attachments[i] === "object") { + var attachment = attachments[i]; + throwOnInvalidAttachment(attachment); + attachmentsData.push(createAttachmentData(attachment)); + } else { + throw createArgumentError("attachments"); + } + } + + return attachmentsData; +} +function throwOnInvalidAttachment(attachment) { + if (typeof attachment !== "object") { + throw createArgumentError("attachments"); + } + + if (!attachment.type || !attachment.name) { + throw createArgumentError("attachments"); + } + + if (!attachment.url && !attachment.itemId) { + throw createArgumentError("attachments"); + } +} +function createAttachmentData(attachment) { + var attachmentData = null; + + if (attachment.type === MailboxEnums.AttachmentType.File) { + var url = attachment.url; + var name_1 = attachment.name; + var isInline = !!attachment.isInline; + throwOnInvalidAttachmentUrlOrName(url, name_1); + attachmentData = [MailboxEnums.AttachmentType.File, name_1, url, isInline]; + } else if (attachment.type === MailboxEnums.AttachmentType.Item) { + var itemId = getItemIdBasedOnHost(attachment.itemId); + var name_2 = attachment.name; + throwOnInvalidAttachmentItemIdOrName(itemId, name_2); + attachmentData = [MailboxEnums.AttachmentType.Item, name_2, itemId]; + } else { + throw createArgumentError("attachments"); + } + + return attachmentData; +} +function throwOnInvalidAttachmentUrlOrName(url, name) { + if (!(typeof url === "string") && !(typeof name === "string")) { + throw createArgumentError("attachments"); + } + + if (url.length > MaxUrlLength) { + throw createArgumentOutOfRange("attachments", url.length, getString("l_AttachmentUrlTooLong_Text")); + } + + throwOnInvalidAttachmentName(name); +} +function throwOnInvalidAttachmentName(name) { + if (name.length > MaxAttachmentNameLength) { + throw createArgumentOutOfRange("attachments", name.length, getString("l_AttachmentNameTooLong_Text")); + } +} +function throwOnInvalidAttachmentItemIdOrName(itemId, name) { + if (!(typeof itemId === "string") || !(typeof name === "string")) { + throw createArgumentError("attachments"); + } + + if (itemId.length > MaxItemIdLength) { + throw createArgumentOutOfRange("attachments", itemId.length, getString("l_AttachmentItemIdTooLong_Text")); + } + + throwOnInvalidAttachmentName(name); +} +// CONCATENATED MODULE: ./src/utils/handleTokenResponse.ts + + + + + +var handleTokenResponse_OSF = __webpack_require__(0); + +function handleTokenResponse(response, context, resultCode) { + var asyncResult = undefined; + + if (!!resultCode && resultCode !== InvokeResultCode.noError) { + asyncResult = createAsyncResult(undefined, handleTokenResponse_OSF.DDA.AsyncResultEnum.ErrorCode.Failed, 9017, context, getString("l_InternalProtocolError_Text").replace("{0}", resultCode)); + + if (!!asyncResult) { + asyncResult.diagnostics = { + InvokeCodeResult: resultCode + }; + } + } else { + if (getAppName() === handleTokenResponse_OSF.AppName.Outlook && response.error !== undefined && response.errorCode !== undefined && !!response.error && response.errorCode === 9030) { + asyncResult = createAsyncResult(undefined, handleTokenResponse_OSF.DDA.AsyncResultEnum.ErrorCode.Failed, response.errorCode, context, response.errorMessage); + } else if (!!response.wasSuccessful) { + asyncResult = createAsyncResult(response.token, handleTokenResponse_OSF.DDA.AsyncResultEnum.ErrorCode.Success, 0, context); + } else { + asyncResult = createAsyncResult(undefined, handleTokenResponse_OSF.DDA.AsyncResultEnum.ErrorCode.Failed, response.errorCode, context, response.errorMessage); + } + + if (response.diagnostics) { + asyncResult.diagnostics = response.diagnostics; + } + } + + return asyncResult; +} +// CONCATENATED MODULE: ./src/methods/getCallbackToken.ts + + + + + + + + +function getCallbackToken() { + var args = []; + + for (var _i = 0; _i < arguments.length; _i++) { + args[_i] = arguments[_i]; + } + + checkPermissionsAndThrow(1, "mailbox.getCallbackTokenAsync"); + var commonParameters = parseCommonArgs(args, true, true); + var isRest = false; + + if (commonParameters.options && !!commonParameters.options.isRest) { + isRest = true; + } + + if (getIsNoItemContextWebExt()) { + if (!isRest || getPermissionLevel_getPermissionLevel() < 3) { + throw createError(getString("l_TokenAccessDeniedWithoutItemContext_Text")); + } + } + + standardInvokeHostMethod(12, commonParameters.asyncContext, commonParameters.callback, { + isRest: isRest + }, undefined, handleTokenResponse); +} +// CONCATENATED MODULE: ./src/methods/getUserIdentityToken.ts + + + + +function getUserIdentityToken() { + var args = []; + + for (var _i = 0; _i < arguments.length; _i++) { + args[_i] = arguments[_i]; + } + + checkPermissionsAndThrow(1, "mailbox.getUserIdentityToken"); + var commonParameters = parseCommonArgs(args, true, true); + standardInvokeHostMethod(2, commonParameters.asyncContext, commonParameters.callback, undefined, undefined, handleTokenResponse); +} +// CONCATENATED MODULE: ./src/methods/makeEwsRequest.ts + + + + + + + +var makeEwsRequest_OSF = __webpack_require__(0); + +var maxEwsRequestSize = 1000000; +function makeEwsRequest(body) { + var args = []; + + for (var _i = 1; _i < arguments.length; _i++) { + args[_i - 1] = arguments[_i]; + } + + checkPermissionsAndThrow(3, "mailbox.makeEwsRequest"); + var commonParameters = parseCommonArgs(args, true, true); + + if (body === null || body === undefined) { + throw createNullArgumentError("data"); + } + + if (typeof body !== "string") { + throw createArgumentTypeError("data", typeof body, "string"); + } + + if (body.length > maxEwsRequestSize) { + throw createArgumentError("data", getString("l_EwsRequestOversized_Text")); + } + + standardInvokeHostMethod(5, commonParameters.asyncContext, commonParameters.callback, { + body: body + }, undefined, handleCustomResponse); +} + +function handleCustomResponse(data, context, responseCode) { + if (!!responseCode && responseCode !== InvokeResultCode.noError) { + return createAsyncResult(undefined, makeEwsRequest_OSF.DDA.AsyncResultEnum.ErrorCode.Failed, 9017, context, getString("l_InternalProtocolError_Text").replace("{0}", responseCode)); + } else if (data.wasProxySuccessful === false) { + return createAsyncResult(undefined, makeEwsRequest_OSF.DDA.AsyncResultEnum.ErrorCode.Failed, 9020, context, data.errorMessage); + } else { + return createAsyncResult(data.body, makeEwsRequest_OSF.DDA.AsyncResultEnum.ErrorCode.Success, 0, context); + } +} +// CONCATENATED MODULE: ./src/utils/objectDefine.ts +var objectDefine = function objectDefine(o, props) { + var keys = Object.keys(props); + var values = keys.map(function (prop) { + return { + value: props[prop], + writable: false + }; + }); + var properties = {}; + keys.forEach(function (key, index) { + properties[key] = values[index]; + }); + return Object.defineProperties(o, properties); +}; +// CONCATENATED MODULE: ./src/api/getDiagnostics.ts + + + +var getDiagnostics_OSF = __webpack_require__(0); + +var getDiagnostics_getHostName = function getHostName() { + var appName = getAppName(); + + switch (appName) { + case getDiagnostics_OSF.AppName.Outlook: + return "Outlook"; + + case getDiagnostics_OSF.AppName.OutlookWebApp: + return "OutlookWebApp"; + + case getDiagnostics_OSF.AppName.OutlookIOS: + return "OutlookIOS"; + + case getDiagnostics_OSF.AppName.OutlookAndroid: + return "OutlookAndroid"; + + default: + return undefined; + } +}; +function getDiagnosticsSurface() { + return objectDefine({}, { + hostName: getDiagnostics_getHostName(), + hostVersion: getInitialDataProp("hostVersion"), + OWAView: getInitialDataProp("owaView") + }); +} +// CONCATENATED MODULE: ./src/api/getUserProfile.ts + + +function getUserProfileSurface() { + return objectDefine({}, { + accountType: getInitialDataProp("userProfileType"), + displayName: getInitialDataProp("userDisplayName"), + emailAddress: getInitialDataProp("userEmailAddress"), + timeZone: getInitialDataProp("userTimeZone") + }); +} +// CONCATENATED MODULE: ./src/validation/categoryConstants.ts + +var CategoryColor = MailboxEnums.CategoryColor; +var categoriesCharacterLimit = 255; +var colorPresets = [CategoryColor.None, CategoryColor.Preset0, CategoryColor.Preset1, CategoryColor.Preset2, CategoryColor.Preset3, CategoryColor.Preset4, CategoryColor.Preset5, CategoryColor.Preset6, CategoryColor.Preset7, CategoryColor.Preset8, CategoryColor.Preset9, CategoryColor.Preset10, CategoryColor.Preset11, CategoryColor.Preset12, CategoryColor.Preset13, CategoryColor.Preset14, CategoryColor.Preset15, CategoryColor.Preset16, CategoryColor.Preset17, CategoryColor.Preset18, CategoryColor.Preset19, CategoryColor.Preset20, CategoryColor.Preset21, CategoryColor.Preset22, CategoryColor.Preset23, CategoryColor.Preset24]; +// CONCATENATED MODULE: ./src/validation/validateCategoryDetailsArray.ts + + +function validateCategoryDetailsArray(categoryDetails) { + if (!categoryDetails) { + throw createArgumentError("categoryDetails"); + } + + if (!Array.isArray(categoryDetails)) { + throw createArgumentTypeError("categoryDetails", typeof categoryDetails, typeof []); + } + + if (categoryDetails.length === 0) { + throw createArgumentError("categoryDetails"); + } + + categoryDetails.forEach(validateCategoryDetails); +} + +function validateCategoryDetails(categoryDetails) { + if (!categoryDetails) { + throw createArgumentError("categoryDetails"); + } + + if (!categoryDetails.color || !categoryDetails.displayName) { + throw createArgumentError("categoryDetails"); + } + + if (typeof categoryDetails.color !== "string") { + throw createArgumentTypeError("categoryDetails.color", typeof categoryDetails.color, "string"); + } + + if (typeof categoryDetails.displayName !== "string") { + throw createArgumentTypeError("categoryDetails.displayName", typeof categoryDetails.displayName, "string"); + } + + if (categoryDetails.displayName.length > categoriesCharacterLimit) { + throw createArgumentOutOfRange("categoryDetails.displayName", categoryDetails.displayName.length); + } + + if (colorPresets.indexOf(categoryDetails.color) === -1) { + throw createArgumentError("categoryDetails.color"); + } +} +// CONCATENATED MODULE: ./src/methods/addMasterCategories.ts + + + + +function addMasterCategories(categoryDetails) { + var args = []; + + for (var _i = 1; _i < arguments.length; _i++) { + args[_i - 1] = arguments[_i]; + } + + checkPermissionsAndThrow(3, "masterCategories.addAsync"); + var commonParameters = parseCommonArgs(args, false, false); + var parameters = { + categoryDetails: categoryDetails + }; + validateCategoryDetailsArray(categoryDetails); + standardInvokeHostMethod(161, commonParameters.asyncContext, commonParameters.callback, parameters, undefined); +} +// CONCATENATED MODULE: ./src/methods/getMasterCategories.ts + + + +function getMasterCategories() { + var args = []; + + for (var _i = 0; _i < arguments.length; _i++) { + args[_i] = arguments[_i]; + } + + checkPermissionsAndThrow(3, "masterCategories.getAsync"); + var commonParameters = parseCommonArgs(args, true, false); + standardInvokeHostMethod(160, commonParameters.asyncContext, commonParameters.callback, undefined, undefined); +} +// CONCATENATED MODULE: ./src/validation/validateCategoryArray.ts + + +function validateCategoryArray(categories) { + if (!categories) { + throw createArgumentError("categories"); + } + + if (!Array.isArray(categories)) { + throw createArgumentTypeError("categories", typeof categories, typeof Array); + } + + if (categories.length === 0) { + throw createArgumentError("categories"); + } + + categories.forEach(validateCategory); +} + +function validateCategory(category) { + if (!category) { + throw createArgumentError("categories"); + } + + if (typeof category !== "string") { + throw createArgumentTypeError("categories", typeof category, "string"); + } + + if (category.length > categoriesCharacterLimit) { + throw createArgumentOutOfRange("categories", category.length); + } +} +// CONCATENATED MODULE: ./src/methods/removeMasterCategories.ts + + + + +function removeMasterCategories(categories) { + var args = []; + + for (var _i = 1; _i < arguments.length; _i++) { + args[_i - 1] = arguments[_i]; + } + + checkPermissionsAndThrow(3, "masterCategories.removeAsync"); + var commonParameters = parseCommonArgs(args, false, false); + var parameters = { + categories: categories + }; + validateCategoryArray(categories); + standardInvokeHostMethod(162, commonParameters.asyncContext, commonParameters.callback, parameters, undefined); +} +// CONCATENATED MODULE: ./src/api/getMasterCategoriesSurface.ts + + + + +function getMasterCategoriesSurface() { + return objectDefine({}, { + addAsync: addMasterCategories, + getAsync: getMasterCategories, + removeAsync: removeMasterCategories + }); +} +// CONCATENATED MODULE: ./src/methods/closeApp.ts + +function closeApp() { + standardInvokeHostMethod(42, undefined, undefined, undefined, undefined); +} +// CONCATENATED MODULE: ./src/utils/getHostItemType.ts + +var getHostItemType_getHostItemType = function getHostItemType() { + return getInitialDataProp("itemType"); +}; +// CONCATENATED MODULE: ./src/utils/HostItemType.ts +var HostItemType; + +(function (HostItemType) { + HostItemType[HostItemType["Message"] = 1] = "Message"; + HostItemType[HostItemType["Appointment"] = 2] = "Appointment"; + HostItemType[HostItemType["MeetingRequest"] = 3] = "MeetingRequest"; + HostItemType[HostItemType["MessageCompose"] = 4] = "MessageCompose"; + HostItemType[HostItemType["AppointmentCompose"] = 5] = "AppointmentCompose"; + HostItemType[HostItemType["ItemLess"] = 6] = "ItemLess"; +})(HostItemType || (HostItemType = {})); +// CONCATENATED MODULE: ./src/methods/getInitializationContext.ts + + + +function getInitializationContext() { + var args = []; + + for (var _i = 0; _i < arguments.length; _i++) { + args[_i] = arguments[_i]; + } + + checkPermissionsAndThrow(1, "item.getInitializationContext"); + var commonParameters = parseCommonArgs(args, true, false); + standardInvokeHostMethod(99, commonParameters.asyncContext, commonParameters.callback, undefined, undefined); +} +// CONCATENATED MODULE: ./src/validation/customPropertiesConstants.ts +var DatePrefix = "Date("; +var DatePostfix = ")"; +var MaxCustomPropertiesLength = 2500; +var CustomPropertyType; + +(function (CustomPropertyType) { + CustomPropertyType[CustomPropertyType["NonTransmittable"] = 0] = "NonTransmittable"; +})(CustomPropertyType || (CustomPropertyType = {})); +// CONCATENATED MODULE: ./src/methods/saveCustomProperties.ts + + + + + +function saveCustomProperties(customProperties) { + var args = []; + + for (var _i = 1; _i < arguments.length; _i++) { + args[_i - 1] = arguments[_i]; + } + + checkPermissionsAndThrow(1, "item.saveCustomProperties"); + var commonParameters = parseCommonArgs(args, false, true); + saveCustomProperties_validateParameters(customProperties); + standardInvokeHostMethod(4, commonParameters.asyncContext, commonParameters.callback, { + customProperties: customProperties + }, undefined); +} + +function saveCustomProperties_validateParameters(customProperties) { + if (JSON.stringify(customProperties).length > MaxCustomPropertiesLength) { + throw createArgumentOutOfRange("customProperties"); + } +} +// CONCATENATED MODULE: ./src/api/CustomProperties.ts +var CustomProperties_spreadArrays = undefined && undefined.__spreadArrays || function () { + for (var s = 0, i = 0, il = arguments.length; i < il; i++) { + s += arguments[i].length; + } + + for (var r = Array(s), k = 0, i = 0; i < il; i++) { + for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++) { + r[k] = a[j]; + } + } + + return r; +}; + + + + + + + + +var CustomProperties_CustomProperties = function () { + function CustomProperties(deserializedData) { + if (isNullOrUndefined(deserializedData)) { + createNullArgumentError("data"); + } + + if (Array.isArray(deserializedData)) { + var customropertiesArray = deserializedData; + + if (customropertiesArray.length > CustomPropertyType.NonTransmittable) { + deserializedData = customropertiesArray[CustomPropertyType.NonTransmittable]; + } else { + throw createArgumentError("data"); + } + } else { + this.rawData = deserializedData; + } + } + + CustomProperties.prototype.get = function (key) { + var value = this.rawData[key]; + + if (typeof value === "string") { + var valueString = value; + + if (valueString.length > DatePrefix.length + DatePostfix.length && valueString.startsWith(DatePrefix) && valueString.endsWith(DatePostfix)) { + var ticksString = valueString.substring(DatePrefix.length, valueString.length - 1); + var ticks = parseInt(ticksString); + + if (!isNaN(ticks)) { + var dateTimeValue = new Date(ticks); + + if (!isNullOrUndefined(dateTimeValue)) { + value = dateTimeValue; + } + } + } + } + + return value; + }; + + CustomProperties.prototype.set = function (key, value) { + if (isDateObject(value)) { + value = DatePrefix + value.getTime() + DatePostfix; + } + + this.rawData[key] = value; + }; + + CustomProperties.prototype.remove = function (key) { + delete this.rawData[key]; + }; + + CustomProperties.prototype.saveAsync = function () { + var args = []; + + for (var _i = 0; _i < arguments.length; _i++) { + args[_i] = arguments[_i]; + } + + saveCustomProperties.apply(void 0, CustomProperties_spreadArrays([this.rawData], args)); + }; + + CustomProperties.prototype.getAll = function () { + var _this = this; + + checkFeatureEnabledAndThrow(Features.propertyGetAll, "getAll"); + var dictionary = {}; + var keys = Object.keys(this.rawData); + keys.forEach(function (key) { + dictionary[key] = _this.get(key); + }); + return dictionary; + }; + + return CustomProperties; +}(); + + +// CONCATENATED MODULE: ./src/methods/loadCustomProperties.ts + + + + + + +var loadCustomProperties_OSF = __webpack_require__(0); + +function loadCustomProperties() { + var args = []; + + for (var _i = 0; _i < arguments.length; _i++) { + args[_i] = arguments[_i]; + } + + var commonParameters = parseCommonArgs(args, true, true); + standardInvokeHostMethod(3, commonParameters.asyncContext, commonParameters.callback, undefined, undefined, loadCustomProperties_handleCustomResponse); +} + +function loadCustomProperties_handleCustomResponse(data, context, responseCode) { + if (typeof responseCode !== "undefined" && responseCode !== InvokeResultCode.noError) { + return createAsyncResult(undefined, loadCustomProperties_OSF.DDA.AsyncResultEnum.ErrorCode.Failed, 9017, context, getString("l_InternalProtocolError_Text").replace("{0}", responseCode)); + } else if (data.wasSuccessful) { + var props = JSON.parse(data.customProperties); + var value = new CustomProperties_CustomProperties(props); + return createAsyncResult(value, loadCustomProperties_OSF.DDA.AsyncResultEnum.ErrorCode.Success, 0, context); + } else { + return createAsyncResult(undefined, loadCustomProperties_OSF.DDA.AsyncResultEnum.ErrorCode.Failed, 9020, context, data.errorMessage); + } +} +// CONCATENATED MODULE: ./src/utils/bodyUtils.ts + + + +var bodyUtils_OSF = __webpack_require__(0); + +var HostCoercionType; + +(function (HostCoercionType) { + HostCoercionType[HostCoercionType["Text"] = 0] = "Text"; + HostCoercionType[HostCoercionType["Html"] = 3] = "Html"; +})(HostCoercionType || (HostCoercionType = {})); + +function addCoercionTypeParameter(parameters, args) { + if (!!args.options && typeof args.options.coercionType === "string") { + parameters.coercionType = getCoercionTypeFromString(args.options.coercionType); + } else { + parameters.coercionType = HostCoercionType.Text; + } +} +function getCoercionTypeFromString(coercionType) { + if (coercionType === CoercionType.Html) { + return HostCoercionType.Html; + } else if (coercionType === CoercionType.Text) { + return HostCoercionType.Text; + } else { + return undefined; + } +} +function invokeCallbackWithCoercionTypeError(args) { + args.callback && args.callback(createAsyncResult(undefined, bodyUtils_OSF.DDA.AsyncResultEnum.ErrorCode.Failed, 1000, args.asyncContext)); +} +// CONCATENATED MODULE: ./src/methods/getBody.ts + + + + + +function getBody(coercionType) { + var args = []; + + for (var _i = 1; _i < arguments.length; _i++) { + args[_i - 1] = arguments[_i]; + } + + checkPermissionsAndThrow(1, "body.getAsync"); + var commonParameters = parseCommonArgs(args, true, false); + var parameters = { + coercionType: getCoercionTypeFromString(coercionType) + }; + + if (parameters.coercionType === undefined) { + throw createArgumentError("coercionType"); + } + + standardInvokeHostMethod(37, commonParameters.asyncContext, commonParameters.callback, parameters, undefined); +} +// CONCATENATED MODULE: ./src/methods/getBodyType.ts + + + +function getBodyType() { + var args = []; + + for (var _i = 0; _i < arguments.length; _i++) { + args[_i] = arguments[_i]; + } + + checkPermissionsAndThrow(1, "body.getTypeAsync"); + var commonParameters = parseCommonArgs(args, true, false); + standardInvokeHostMethod(14, commonParameters.asyncContext, commonParameters.callback, undefined, undefined); +} +// CONCATENATED MODULE: ./src/validation/validateBodyParameters.ts + +var maxDataLengthForBodyApi = 1000000; +var maxAppendOnSendLength = 5000; +var maxDataLengthForSignatureBodyApi = 30000; +function validateAppendOnSendBodyParamters(parameters) { + if (typeof parameters.appendTxt !== "string") { + throw createArgumentTypeError("data", typeof parameters.appendTxt, "string"); + } + + if (parameters.appendTxt.length > maxAppendOnSendLength) { + throw createArgumentOutOfRange("data", parameters.appendTxt.length); + } +} +function validateBodyParameters(parameters) { + if (typeof parameters.data !== "string") { + throw createArgumentTypeError("data", typeof parameters.data, "string"); + } + + if (parameters.data.length > maxDataLengthForBodyApi) { + throw createArgumentOutOfRange("data", parameters.data.length); + } +} +function validateSignatureBodyParameters(parameters) { + if (typeof parameters.data !== "string") { + throw createArgumentTypeError("data", typeof parameters.data, "string"); + } + + if (parameters.data.length > maxDataLengthForSignatureBodyApi) { + throw createArgumentOutOfRange("data", parameters.data.length); + } +} +// CONCATENATED MODULE: ./src/methods/setBody.ts + + + + + +function setBody(data) { + var args = []; + + for (var _i = 1; _i < arguments.length; _i++) { + args[_i - 1] = arguments[_i]; + } + + checkPermissionsAndThrow(2, "body.setAsync"); + var commonParameters = parseCommonArgs(args, false, false); + var parameters = { + data: data + }; + validateBodyParameters(parameters); + addCoercionTypeParameter(parameters, commonParameters); + + if (parameters.coercionType === undefined) { + invokeCallbackWithCoercionTypeError(commonParameters); + return; + } + + standardInvokeHostMethod(38, commonParameters.asyncContext, commonParameters.callback, parameters, undefined); +} +// CONCATENATED MODULE: ./src/methods/bodyPrepend.ts + + + + + +function bodyPrepend(data) { + var args = []; + + for (var _i = 1; _i < arguments.length; _i++) { + args[_i - 1] = arguments[_i]; + } + + checkPermissionsAndThrow(2, "body.prependAsync"); + var commonParameters = parseCommonArgs(args, false, false); + var parameters = { + data: data + }; + validateBodyParameters(parameters); + addCoercionTypeParameter(parameters, commonParameters); + + if (parameters.coercionType === undefined) { + invokeCallbackWithCoercionTypeError(commonParameters); + return; + } + + standardInvokeHostMethod(23, commonParameters.asyncContext, commonParameters.callback, parameters, undefined); +} +// CONCATENATED MODULE: ./src/methods/appendOnSend.ts + + + + + + +function appendOnSend(data) { + var args = []; + + for (var _i = 1; _i < arguments.length; _i++) { + args[_i - 1] = arguments[_i]; + } + + checkPermissionsAndThrow(2, "body.appendOnSendAsync"); + var commonParameters = parseCommonArgs(args, false, false); + var parameters = { + appendTxt: data + }; + + if (isNullOrUndefined(parameters.appendTxt)) { + parameters.appendTxt = ""; + } else { + validateAppendOnSendBodyParamters(parameters); + } + + addCoercionTypeParameter(parameters, commonParameters); + + if (parameters.coercionType === undefined) { + invokeCallbackWithCoercionTypeError(commonParameters); + return; + } + + standardInvokeHostMethod(100, commonParameters.asyncContext, commonParameters.callback, parameters, undefined); +} +// CONCATENATED MODULE: ./src/methods/setSelectedData.ts + + + + + +function setSelectedData(dispid) { + return function (data) { + var args = []; + + for (var _i = 1; _i < arguments.length; _i++) { + args[_i - 1] = arguments[_i]; + } + + checkPermissionsAndThrow(2, "body.setSelectedDataAsync"); + var commonParameters = parseCommonArgs(args, false, false); + var parameters = { + data: data + }; + validateBodyParameters(parameters); + addCoercionTypeParameter(parameters, commonParameters); + + if (parameters.coercionType === undefined) { + invokeCallbackWithCoercionTypeError(commonParameters); + return; + } + + standardInvokeHostMethod(dispid, commonParameters.asyncContext, commonParameters.callback, parameters, undefined); + }; +} +// CONCATENATED MODULE: ./src/methods/setSignature.ts + + + + + + + +function setSignature(data) { + var args = []; + + for (var _i = 1; _i < arguments.length; _i++) { + args[_i - 1] = arguments[_i]; + } + + checkPermissionsAndThrow(2, "item.body.setSignatureAsync"); + var commonParameters = parseCommonArgs(args, false, false); + var parameters = { + data: data + }; + checkFeatureEnabledAndThrow(Features.signature, "setSignatureAsync"); + + if (isNullOrUndefined(parameters.data)) { + parameters.data = ""; + } else { + validateSignatureBodyParameters(parameters); + } + + addCoercionTypeParameter(parameters, commonParameters); + + if (parameters.coercionType === undefined) { + invokeCallbackWithCoercionTypeError(commonParameters); + return; + } + + standardInvokeHostMethod(173, commonParameters.asyncContext, commonParameters.callback, parameters, undefined); +} +// CONCATENATED MODULE: ./src/api/getBodySurface.ts + + + + + + + + +function getBodySurface(isCompose) { + var body = objectDefine({}, { + getAsync: getBody + }); + + if (isCompose) { + objectDefine(body, { + appendOnSendAsync: appendOnSend, + getTypeAsync: getBodyType, + prependAsync: bodyPrepend, + setAsync: setBody, + setSelectedDataAsync: setSelectedData(13), + setSignatureAsync: setSignature + }); + } + + return body; +} +// CONCATENATED MODULE: ./src/methods/getAllInternetHeaders.ts + + + +function getAllInternetHeaders() { + var args = []; + + for (var _i = 0; _i < arguments.length; _i++) { + args[_i] = arguments[_i]; + } + + checkPermissionsAndThrow(1, "item.getAllInternetHeadersAsync"); + var commonParameters = parseCommonArgs(args, true, false); + standardInvokeHostMethod(168, commonParameters.asyncContext, commonParameters.callback, undefined, undefined); +} +// CONCATENATED MODULE: ./src/types/ItemNotificationMessageType.ts +var ItemNotificationMessageType; + +(function (ItemNotificationMessageType) { + ItemNotificationMessageType[ItemNotificationMessageType["informationalMessage"] = 0] = "informationalMessage"; + ItemNotificationMessageType[ItemNotificationMessageType["progressIndicator"] = 1] = "progressIndicator"; + ItemNotificationMessageType[ItemNotificationMessageType["errorMessage"] = 2] = "errorMessage"; + ItemNotificationMessageType[ItemNotificationMessageType["insightMessage"] = 3] = "insightMessage"; +})(ItemNotificationMessageType || (ItemNotificationMessageType = {})); +// CONCATENATED MODULE: ./src/utils/validateString.ts + + +function validateStringParam(paramName, paramValue) { + if (isNullOrUndefined(paramValue) || paramValue === "") { + throw createNullArgumentError(paramName); + } + + if (!(typeof paramValue === "string")) { + throw createArgumentTypeError(paramName, typeof paramValue, "string"); + } +} +function validateStringParamWithEmptyAllowed(paramName, paramValue) { + if (isNullOrUndefined(paramValue)) { + throw createNullArgumentError(paramName); + } + + if (!(typeof paramValue === "string")) { + throw createArgumentTypeError(paramName, typeof paramValue, "string"); + } +} +// CONCATENATED MODULE: ./src/validation/notificationMessagesConstants.ts +var MaximumKeyLength = 32; +var MaximumIconLength = 32; +var MaximumMessageLength = 150; +var MaximumActionTextLength = 30; +var NotificationsKeyParameterName = "key"; +var NotificationsTypeParameterName = "type"; +var NotificationsIconParameterName = "icon"; +var NotificationsMessageParameterName = "message"; +var NotificationsPersistentParameterName = "persistent"; +var NotificationsActionsDefinitionParameterName = "actions"; +var NotificationsActionTypeParameterName = "actionType"; +var NotificationsActionTextParameterName = "actionText"; +var NotificationsActionCommandIdParameterName = "commandId"; +var NotificationsActionShowTaskPaneActionId = "showTaskPane"; +// CONCATENATED MODULE: ./src/validation/validateNotificationMessages.ts + + + + + + +function validateKey(key) { + validateStringParam(NotificationsKeyParameterName, key); + + if (key.length > MaximumKeyLength) { + throw createArgumentOutOfRange(NotificationsKeyParameterName, key.length); + } +} +function validateData(data) { + validateStringParam(NotificationsTypeParameterName, data.type); + + if (data.type === MailboxEnums.ItemNotificationMessageType.InformationalMessage) { + validateStringParam(NotificationsIconParameterName, data.icon); + + if (data.icon.length > MaximumIconLength) { + throw createArgumentOutOfRange(NotificationsIconParameterName, data.icon.length); + } + + if (isNullOrUndefined(data.persistent)) { + throw createNullArgumentError(NotificationsPersistentParameterName); + } + + if (typeof data.persistent !== "boolean") { + throw createArgumentTypeError(NotificationsPersistentParameterName, typeof data.persistent, "boolean"); + } + + if (!isNullOrUndefined(data.actions)) { + throw createArgumentError(NotificationsActionsDefinitionParameterName, getString("l_ActionsDefinitionWrongNotificationMessageError_Text")); + } + } else if (data.type === MailboxEnums.ItemNotificationMessageType.InsightMessage) { + validateInsightMessageParameters(data); + } else { + if (!isNullOrUndefined(data.icon)) { + throw createArgumentError(NotificationsIconParameterName); + } + + if (!isNullOrUndefined(data.persistent)) { + throw createArgumentError(NotificationsPersistentParameterName); + } + + if (!isNullOrUndefined(data.actions)) { + throw createArgumentError(NotificationsActionsDefinitionParameterName, getString("l_ActionsDefinitionWrongNotificationMessageError_Text")); + } + } + + validateStringParam(NotificationsMessageParameterName, data.message); + + if (data.message.length > MaximumMessageLength) { + throw createArgumentOutOfRange(NotificationsMessageParameterName, data.message.length); + } +} + +function validateInsightMessageParameters(data) { + validateStringParam(NotificationsIconParameterName, data.icon); + + if (data.icon.length > MaximumIconLength) { + throw createArgumentOutOfRange(NotificationsIconParameterName, data.icon.length); + } + + if (!isNullOrUndefined(data.persistent)) { + throw createArgumentError(NotificationsPersistentParameterName); + } + + if (isNullOrUndefined(data.actions)) { + throw createNullArgumentError(NotificationsActionsDefinitionParameterName); + } else { + validateActionsDefinitionBlob(data.actions); + } +} + +function validateActionsDefinitionBlob(actionsDefinitionBlob) { + var actionsDefinition = extractActionsDefinition(actionsDefinitionBlob); + + if (isNullOrUndefined(actionsDefinition)) { + return; + } + + validateActionsDefinitionActionsType(actionsDefinition); + validateActionsDefinitionActionsText(actionsDefinition); +} + +function extractActionsDefinition(actionsDefinitionBlob) { + var actionsDefinition = null; + + if (Array.isArray(actionsDefinitionBlob)) { + if (actionsDefinitionBlob.length === 1) { + actionsDefinition = actionsDefinitionBlob[0]; + } else if (actionsDefinitionBlob.length > 1) { + throw createArgumentError(NotificationsActionsDefinitionParameterName, getString("l_ActionsDefinitionMultipleActionsError_Text")); + } + } else { + throw createArgumentError(NotificationsActionsDefinitionParameterName); + } + + return actionsDefinition; +} + +function validateActionsDefinitionActionsType(actionsDefinition) { + if (isNullOrUndefined(actionsDefinition.actionType)) { + throw createNullArgumentError(NotificationsActionTypeParameterName); + } + + if (NotificationsActionShowTaskPaneActionId !== actionsDefinition.actionType) { + throw createArgumentError(NotificationsActionTypeParameterName, getString("l_InvalidActionType_Text")); + } else { + if (isNullOrUndefined(actionsDefinition.commandId) || typeof actionsDefinition.commandId !== "string" || actionsDefinition.commandId === "") { + throw createArgumentError(NotificationsActionCommandIdParameterName, getString("l_InvalidCommandIdError_Text")); + } + } +} + +function validateActionsDefinitionActionsText(actionsDefinition) { + if (isNullOrUndefined(actionsDefinition.actionText) || actionsDefinition.actionText === "" || typeof actionsDefinition.actionText !== "string") { + throw createNullArgumentError(NotificationsActionTextParameterName); + } + + if (actionsDefinition.actionText.length > MaximumActionTextLength) { + throw createArgumentOutOfRange(NotificationsActionTextParameterName, actionsDefinition.actionText.length); + } +} +// CONCATENATED MODULE: ./src/methods/addNotificationMessage.ts + + + + + + + +function addNotificationMessage(key, data) { + var args = []; + + for (var _i = 2; _i < arguments.length; _i++) { + args[_i - 2] = arguments[_i]; + } + + checkPermissionsAndThrow(1, "notificationMessages.addAsync"); + var commonParameters = parseCommonArgs(args, false, false); + validateKey(key); + validateData(data); + var type = ItemNotificationMessageType[data.type]; + + if (isNullOrUndefined(type)) { + throw createArgumentError("type"); + } + + var message = data.message; + var icon = data.icon; + var persistent = data.persistent; + var actions = data.actions; + var parameters = { + key: key, + message: message, + type: type, + icon: icon, + persistent: persistent, + actions: actions + }; + standardInvokeHostMethod(33, commonParameters.asyncContext, commonParameters.callback, parameters, undefined); +} +// CONCATENATED MODULE: ./src/methods/getAllNotificationMessages.ts + + + +function getAllNotificationMessages() { + var args = []; + + for (var _i = 0; _i < arguments.length; _i++) { + args[_i] = arguments[_i]; + } + + checkPermissionsAndThrow(1, "notificationMessages.getAsync"); + var commonParameters = parseCommonArgs(args, true, false); + standardInvokeHostMethod(34, commonParameters.asyncContext, commonParameters.callback, undefined, undefined); +} +// CONCATENATED MODULE: ./src/methods/removeNotificationMessage.ts + + + + +function removeNotificationMessage(key) { + var args = []; + + for (var _i = 1; _i < arguments.length; _i++) { + args[_i - 1] = arguments[_i]; + } + + checkPermissionsAndThrow(1, "notificationMessages.removeAsync"); + var commonParameters = parseCommonArgs(args, false, false); + validateKey(key); + var parameters = { + key: key + }; + standardInvokeHostMethod(36, commonParameters.asyncContext, commonParameters.callback, parameters, undefined); +} +// CONCATENATED MODULE: ./src/methods/replaceNotificationMessage.ts + + + + + + + +function replaceNotificationMessage(key, data) { + var args = []; + + for (var _i = 2; _i < arguments.length; _i++) { + args[_i - 2] = arguments[_i]; + } + + checkPermissionsAndThrow(1, "notificationMessages.replaceAsync"); + var commonParameters = parseCommonArgs(args, false, false); + validateKey(key); + validateData(data); + var type = ItemNotificationMessageType[data.type]; + + if (isNullOrUndefined(type)) { + throw createArgumentError("type"); + } + + var message = data.message; + var icon = data.icon; + var persistent = data.persistent; + var actions = data.actions; + var parameters = { + key: key, + message: message, + type: type, + icon: icon, + persistent: persistent, + actions: actions + }; + standardInvokeHostMethod(35, commonParameters.asyncContext, commonParameters.callback, parameters, undefined); +} +// CONCATENATED MODULE: ./src/api/getNotificationMessagesSurface.ts + + + + + +function getNotificationMessageSurface() { + return objectDefine({}, { + addAsync: addNotificationMessage, + getAllAsync: getAllNotificationMessages, + removeAsync: removeNotificationMessage, + replaceAsync: replaceNotificationMessage + }); +} +// CONCATENATED MODULE: ./src/validation/validateDisplayReplyForm.ts + + + + + +function validateStringParameters(formData) { + if (!isNullOrUndefined(formData)) { + throwOnOutOfRange(formData.length, 0, maxBodyLength, "htmlBody"); + } +} +function validateAndGetHtmlBody(data) { + var htmlBody = ""; + + if (data.htmlBody) { + throwOnInvalidHtmlBody(data.htmlBody); + htmlBody = data.htmlBody; + } + + return htmlBody; +} +function throwOnInvalidHtmlBody(htmlBody) { + if (!(typeof htmlBody === "string")) { + throw createArgumentTypeError("htmlBody", typeof htmlBody, "string"); + } + + if (isNullOrUndefined(htmlBody)) { + throw createNullArgumentError("htmlBody"); + } + + throwOnOutOfRange(htmlBody.length, 0, maxBodyLength, "htmlBody"); +} +function validateAndGetAttachments(data) { + var attachments = []; + + if (data.attachments) { + attachments = data.attachments; + throwOnInvalidAttachmentsArray(attachments); + } + + return attachments; +} +// CONCATENATED MODULE: ./src/utils/getOptionsAndCallback.ts + +function getOptionsAndCallback(data) { + var args = []; + + if (!isNullOrUndefined(data.options)) { + args[0] = data.options; + } + + if (!isNullOrUndefined(data.callback)) { + args[args.length] = data.callback; + } + + return args; +} +// CONCATENATED MODULE: ./src/methods/displayReplyForm.ts +var displayReplyForm_spreadArrays = undefined && undefined.__spreadArrays || function () { + for (var s = 0, i = 0, il = arguments.length; i < il; i++) { + s += arguments[i].length; + } + + for (var r = Array(s), k = 0, i = 0; i < il; i++) { + for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++) { + r[k] = a[j]; + } + } + + return r; +}; + + + + + + + + + + +function displayReplyForm(formData) { + var args = []; + + for (var _i = 1; _i < arguments.length; _i++) { + args[_i - 1] = arguments[_i]; + } + + return displayReplyFormHelper.apply(void 0, displayReplyForm_spreadArrays([false, false, formData], args)); +} +function displayReplyAllForm(formData) { + var args = []; + + for (var _i = 1; _i < arguments.length; _i++) { + args[_i - 1] = arguments[_i]; + } + + return displayReplyFormHelper.apply(void 0, displayReplyForm_spreadArrays([true, false, formData], args)); +} +function displayReplyFormAsync(formData) { + var args = []; + + for (var _i = 1; _i < arguments.length; _i++) { + args[_i - 1] = arguments[_i]; + } + + checkFeatureEnabledAndThrow(Features.displayXAsync, "displayReplyFormAsync"); + return displayReplyFormHelper.apply(void 0, displayReplyForm_spreadArrays([false, true, formData], args)); +} +function displayReplyAllFormAsync(formData) { + var args = []; + + for (var _i = 1; _i < arguments.length; _i++) { + args[_i - 1] = arguments[_i]; + } + + checkFeatureEnabledAndThrow(Features.displayXAsync, "displayReplyAllFormAsync"); + return displayReplyFormHelper.apply(void 0, displayReplyForm_spreadArrays([true, true, formData], args)); +} + +function displayReplyFormHelper(isReplyAll, isAsync, formData) { + var args = []; + + for (var _i = 3; _i < arguments.length; _i++) { + args[_i - 3] = arguments[_i]; + } + + var dispidToInvoke; + checkPermissionsAndThrow(1, "mailbox.displayReplyForm"); + var commonParameters = parseCommonArgs(getOptionsAndCallback(formData), false, false); + + if (isFeatureEnabled(Features.replyCallback)) { + if (isNullOrUndefined(commonParameters) || commonParameters.options === undefined && commonParameters.callback === undefined) { + commonParameters = parseCommonArgs(args, false, false); + } + } + + var parameters = { + formData: formData + }; + var updatedHtmlBody = null; + var updateAttachments = null; + + if (typeof parameters.formData === "string") { + if (isReplyAll) { + if (isAsync) { + dispidToInvoke = 184; + } else { + dispidToInvoke = 11; + } + } else { + if (isAsync) { + dispidToInvoke = 183; + } else { + dispidToInvoke = 10; + } + } + + validateStringParameters(parameters.formData); + standardInvokeHostMethod(dispidToInvoke, commonParameters.asyncContext, commonParameters.callback, { + htmlBody: parameters.formData + }, undefined); + } else if (typeof parameters.formData === "object") { + updatedHtmlBody = validateAndGetHtmlBody(parameters.formData); + updateAttachments = createAttachmentsDataForHost(validateAndGetAttachments(parameters.formData)); + + if (isReplyAll) { + if (isAsync) { + dispidToInvoke = 182; + } else { + dispidToInvoke = 31; + } + } else { + if (isAsync) { + dispidToInvoke = 181; + } else { + dispidToInvoke = 30; + } + } + + standardInvokeHostMethod(dispidToInvoke, commonParameters.asyncContext, commonParameters.callback, { + htmlBody: updatedHtmlBody, + attachments: updateAttachments + }, undefined); + } else { + throw createArgumentError(); + } +} +// CONCATENATED MODULE: ./src/methods/addCategories.ts + + + + +function addCategories(categories) { + var args = []; + + for (var _i = 1; _i < arguments.length; _i++) { + args[_i - 1] = arguments[_i]; + } + + checkPermissionsAndThrow(2, "categories.addAsync"); + var commonParameters = parseCommonArgs(args, false, false); + var parameters = { + categories: categories + }; + validateCategoryArray(categories); + standardInvokeHostMethod(158, commonParameters.asyncContext, commonParameters.callback, parameters, undefined); +} +// CONCATENATED MODULE: ./src/methods/getCategories.ts + + + +function getCategories() { + var args = []; + + for (var _i = 0; _i < arguments.length; _i++) { + args[_i] = arguments[_i]; + } + + checkPermissionsAndThrow(1, "categories.getAsync"); + var commonParameters = parseCommonArgs(args, true, false); + standardInvokeHostMethod(157, commonParameters.asyncContext, commonParameters.callback, undefined, undefined); +} +// CONCATENATED MODULE: ./src/methods/removeCategories.ts + + + + +function removeCategories(categories) { + var args = []; + + for (var _i = 1; _i < arguments.length; _i++) { + args[_i - 1] = arguments[_i]; + } + + checkPermissionsAndThrow(2, "categories.removeAsync"); + var commonParameters = parseCommonArgs(args, false, false); + var parameters = { + categories: categories + }; + validateCategoryArray(categories); + standardInvokeHostMethod(159, commonParameters.asyncContext, commonParameters.callback, parameters, undefined); +} +// CONCATENATED MODULE: ./src/api/getCategoriesSurface.ts + + + + +function getCategoriesSurface() { + return objectDefine({}, { + addAsync: addCategories, + getAsync: getCategories, + removeAsync: removeCategories + }); +} +// CONCATENATED MODULE: ./src/methods/getAttachmentContent.ts + + + + +function getAttachmentContent(id) { + var args = []; + + for (var _i = 1; _i < arguments.length; _i++) { + args[_i - 1] = arguments[_i]; + } + + checkPermissionsAndThrow(1, "item.getAttachmentContentAsync"); + var commonParameters = parseCommonArgs(args, true, false); + var parameters = { + id: id + }; + getAttachmentContent_validateParameters(parameters); + standardInvokeHostMethod(150, commonParameters.asyncContext, commonParameters.callback, parameters, undefined); +} + +function getAttachmentContent_validateParameters(parameters) { + validateStringParam("attachmentId", parameters.id); +} +// CONCATENATED MODULE: ./src/methods/moveToFolder.ts + + + + + +var Folder = MailboxEnums.Folder; +function moveToFolder(destinationFolder) { + var args = []; + + for (var _i = 1; _i < arguments.length; _i++) { + args[_i - 1] = arguments[_i]; + } + + checkPermissionsAndThrow(3, "item.move"); + var commonParameters = parseCommonArgs(args, false, false); + var parameters = { + destinationFolder: destinationFolder + }; + moveToFolder_validateParameters(destinationFolder); + standardInvokeHostMethod(101, commonParameters.asyncContext, commonParameters.callback, parameters, undefined); +} + +function moveToFolder_validateParameters(destinationFolder) { + if (destinationFolder !== Folder.Inbox && destinationFolder !== Folder.Junk && destinationFolder !== Folder.DeletedItems) { + throw createArgumentError("destinationFolder"); + } +} +// CONCATENATED MODULE: ./src/utils/createEmailAddressDetails.ts + +var ResponseType = MailboxEnums.ResponseType; +var RecipientType = MailboxEnums.RecipientType; +var responseTypeMap = [ResponseType.None, ResponseType.Organizer, ResponseType.Tentative, ResponseType.Accepted, ResponseType.Declined]; +var recipientTypeMap = [RecipientType.Other, RecipientType.DistributionList, RecipientType.User, RecipientType.ExternalUser]; +var createEmailAddressDetails = function createEmailAddressDetails(input) { + var response = input.appointmentResponse; + var type = input.recipientType; + var emailAddressDetails = { + emailAddress: input.address, + displayName: input.name + }; + + if (typeof input.appointmentResponse === "number") { + emailAddressDetails.appointmentResponse = response < responseTypeMap.length ? responseTypeMap[response] : ResponseType.None; + } + + if (typeof input.recipientType === "number") { + emailAddressDetails.recipientType = type < recipientTypeMap.length ? recipientTypeMap[type] : RecipientType.Other; + } + + return emailAddressDetails; +}; +function createEmailAddressDetailsForEntity(data) { + return createEmailAddressDetails({ + name: data.Name || "", + address: data.UserId || "" + }); +} +// CONCATENATED MODULE: ./src/methods/getDelayDelivery.ts + + + +function getDelayDelivery() { + var args = []; + + for (var _i = 0; _i < arguments.length; _i++) { + args[_i] = arguments[_i]; + } + + checkPermissionsAndThrow(1, "delayDeliveryTime.getAsync"); + var commonParameters = parseCommonArgs(args, true, false); + standardInvokeHostMethod(166, commonParameters.asyncContext, commonParameters.callback, undefined, undefined); +} +// CONCATENATED MODULE: ./src/methods/setDelayDelivery.ts + + + + + + + +function setDelayDelivery(dateTime) { + var args = []; + + for (var _i = 1; _i < arguments.length; _i++) { + args[_i - 1] = arguments[_i]; + } + + checkPermissionsAndThrow(2, "delayDeliveryTime.setAsync"); + var commonParameters = parseCommonArgs(args, false, false); + validateParamerters(dateTime); + standardInvokeHostMethod(167, commonParameters.asyncContext, commonParameters.callback, { + time: dateTime.getTime() + }, undefined); +} + +function validateParamerters(dateTime) { + if (isNullOrUndefined(dateTime)) { + throw createNullArgumentError("dateTime", "You cannot conduct to a null dateTime"); + } + + if (!isDateObject(dateTime)) { + throw createArgumentTypeError("dateTime", typeof dateTime, typeof Date); + } + + if (isNaN(dateTime.getTime())) { + throw createArgumentError("dateTime"); + } + + throwOnOutOfRange(dateTime.getTime(), -8640000000000000, 8640000000000000, "dateTime"); +} +// CONCATENATED MODULE: ./src/api/getDelayDeliverySurface.ts + + + +function getDelayDeliverySurface(isCompose) { + var delayDelivery = objectDefine({}, { + getAsync: getDelayDelivery + }); + + if (isCompose) { + objectDefine(delayDelivery, { + setAsync: setDelayDelivery + }); + } + + return delayDelivery; +} +// CONCATENATED MODULE: ./src/utils/removeDuplicates.ts +function removeDuplicates(array, comparator) { + for (var matchIndex1 = array.length - 1; matchIndex1 >= 0; matchIndex1--) { + var removeMatch = false; + + for (var matchIndex2 = matchIndex1 - 1; matchIndex2 >= 0; matchIndex2--) { + if (comparator(array[matchIndex1], array[matchIndex2])) { + removeMatch = true; + break; + } + } + + if (removeMatch) { + array.splice(matchIndex1, 1); + } + } + + return array; +} +var stringComparator = function stringComparator(a, b) { + return a === b; +}; +var meetingComparator = function meetingComparator(a, b) { + if (a === b) { + return true; + } else if (!a || !b) { + return false; + } else { + return a.meetingString === b.meetingString; + } +}; +var taskComparator = function taskComparator(a, b) { + if (a === b) { + return true; + } else if (!a || !b) { + return false; + } else { + return a.taskString === b.taskString; + } +}; +var contactComparator = function contactComparator(a, b) { + if (a === b) { + return true; + } else if (!a || !b) { + return false; + } else { + return a.contactString === b.contactString; + } +}; +// CONCATENATED MODULE: ./src/utils/isLegacyEntityExtraction.ts + +function isLegacyEntityExtraction() { + return !!getInitialDataProp("entities") && getInitialDataProp("entities").IsLegacyExtraction !== undefined && getInitialDataProp("entities").IsLegacyExtraction; +} +// CONCATENATED MODULE: ./src/utils/resolveDate.ts + + +var totalBits = 18; +var typeBits = 3; +var preciseDateTypeBits = 3; +var yearBits = 7; +var monthBits = 4; +var dayBits = 5; +var modifierBits = 2; +var unitBits = 3; +var offsetBits = 6; +var tagBits = 4; +var preciseDateType = 0; +var relativeDateType = 1; +var oneDayInMilliseconds = 86400000; +var baseDate = new Date("0001-01-01T00:00:00Z"); +function resolveDate(input, sentTime) { + if (!sentTime) { + return input; + } + + var date = null; + + try { + var sentDate = new Date(sentTime.getFullYear(), sentTime.getMonth(), sentTime.getDate(), 0, 0, 0, 0); + var extractedDate = decode(input); + + if (!extractedDate) { + return input; + } else { + var preciseDate = extractedDate; + + if (preciseDate.day && preciseDate.month && preciseDate.year !== undefined) { + date = resolvePreciseDate(sentDate, extractedDate); + } else { + var relativeDate = extractedDate; + + if (relativeDate.modifier !== undefined && relativeDate.offset !== undefined && relativeDate.tag !== undefined && relativeDate.unit !== undefined) { + date = resolveRelativeDate(sentDate, extractedDate); + } else { + date = sentDate; + } + } + } + + if (isNaN(date.getTime())) { + return sentTime; + } + + date.setMilliseconds(date.getMilliseconds() + (isLegacyEntityExtraction() ? getTimeOfDayInMillisecondsUTC(input) : getTimeOfDayInMilliseconds(input))); + return date; + } catch (e) { + return sentTime; + } +} + +function decode(input) { + var dateValueMask = (1 << totalBits - typeBits) - 1; + var time = 0; + + if (input == null) { + return undefined; + } + + if (isLegacyEntityExtraction()) { + time = getTimeOfDayInMillisecondsUTC(input); + } else { + time = getTimeOfDayInMilliseconds(input); + } + + var inDateAtMidnight = input.getTime() - time; + var value = (inDateAtMidnight - baseDate.getTime()) / oneDayInMilliseconds; + + if (value < 0) { + return undefined; + } else if (value >= 1 << totalBits) { + return undefined; + } else { + var type = value >> totalBits - typeBits; + value = value & dateValueMask; + + switch (type) { + case preciseDateType: + return decodePreciseDate(value); + + case relativeDateType: + return decodeRelativeDate(value); + + default: + return undefined; + } + } +} + +function decodePreciseDate(value) { + var cSubTypeMask = (1 << preciseDateTypeBits) - 1; + var cMonthMask = (1 << monthBits) - 1; + var cDayMask = (1 << dayBits) - 1; + var cYearMask = (1 << yearBits) - 1; + var year = 0; + var month = 0; + var day = 0; + var subType = value >> totalBits - typeBits - preciseDateTypeBits & cSubTypeMask; + + if ((subType & 4) == 4) { + year = value >> totalBits - typeBits - preciseDateTypeBits - yearBits & cYearMask; + + if ((subType & 2) == 2) { + if ((subType & 1) == 1) { + return undefined; + } + + month = value >> totalBits - typeBits - preciseDateTypeBits - yearBits - monthBits & cMonthMask; + } + } else { + if ((subType & 2) == 2) { + month = value >> totalBits - typeBits - preciseDateTypeBits - monthBits & cMonthMask; + } + + if ((subType & 1) == 1) { + day = value >> totalBits - typeBits - preciseDateTypeBits - monthBits - dayBits & cDayMask; + } + } + + return createPreciseDate(day, month, year); +} + +function resolvePreciseDate(sentDate, precise) { + var year = precise.year; + var month = precise.month == 0 ? sentDate.getMonth() : precise.month - 1; + var day = precise.day; + + if (day == 0) { + return sentDate; + } + + var candidate; + + if (isNullOrUndefined(year)) { + candidate = new Date(sentDate.getFullYear(), month, day); + + if (candidate.getTime() < sentDate.getTime()) { + candidate = new Date(sentDate.getFullYear() + 1, month, day); + } + } else { + candidate = new Date(year < 50 ? 2000 + year : 1900 + year, month, day); + } + + if (candidate.getMonth() != month) { + return sentDate; + } + + return candidate; +} + +function resolveRelativeDate(sentDate, relative) { + var date; + + switch (relative.unit) { + case 0: + date = new Date(sentDate.getFullYear(), sentDate.getMonth(), sentDate.getDate()); + date.setDate(date.getDate() + relative.offset); + return date; + + case 5: + return findBestDateForWeekDate(sentDate, relative.offset, relative.tag); + + case 2: + { + var days = 1; + + switch (relative.modifier) { + case 1: + break; + + case 2: + days = 16; + break; + + default: + if (relative.offset == 0) { + days = sentDate.getDate(); + } + + break; + } + + date = new Date(sentDate.getFullYear(), sentDate.getMonth(), days); + date.setMonth(date.getMonth() + relative.offset); + + if (date.getTime() < sentDate.getTime()) { + date.setDate(date.getDate() + sentDate.getDate() - 1); + } + + return date; + } + + case 1: + date = new Date(sentDate.getFullYear(), sentDate.getMonth(), sentDate.getDate()); + date.setDate(sentDate.getDate() + 7 * relative.offset); + + if (relative.modifier == 1 || relative.modifier == 0) { + date.setDate(date.getDate() + 1 - date.getDay()); + + if (date.getTime() < sentDate.getTime()) { + return sentDate; + } + + return date; + } else if (relative.modifier == 2) { + date.setDate(date.getDate() + 5 - date.getDay()); + return date; + } + + break; + + case 4: + return findBestDateForWeekOfMonthDate(sentDate, relative); + + case 3: + if (relative.offset > 0) { + return new Date(sentDate.getFullYear() + relative.offset, 0, 1); + } + + break; + + default: + break; + } + + return sentDate; +} + +function findBestDateForWeekDate(sentDate, offset, tag) { + if (offset > -5 && offset < 5) { + var dayOfWeek = (tag + 6) % 7 + 1; + var days = 7 * offset + (dayOfWeek - sentDate.getDay()); + sentDate.setDate(sentDate.getDate() + days); + return sentDate; + } else { + var days = (tag - sentDate.getDay()) % 7; + + if (days < 0) { + days += 7; + } + + sentDate.setDate(sentDate.getDate() + days); + return sentDate; + } +} + +function findBestDateForWeekOfMonthDate(sentDate, relative) { + var date; + var firstDay; + var newDate; + date = sentDate; + + if (relative.tag <= 0 || relative.tag > 12 || relative.offset <= 0 || relative.offset > 5) { + return sentDate; + } + + var monthOffset = (12 + relative.tag - date.getMonth() - 1) % 12; + firstDay = new Date(date.getFullYear(), date.getMonth() + monthOffset, 1); + + if (relative.modifier == 1) { + if (relative.offset == 1 && firstDay.getDay() != 6 && firstDay.getDay() != 0) { + return firstDay; + } else { + newDate = new Date(firstDay.getFullYear(), firstDay.getMonth(), firstDay.getDate()); + newDate.setDate(newDate.getDate() + (7 + (1 - firstDay.getDay())) % 7); + + if (firstDay.getDay() != 6 && firstDay.getDay() != 0 && firstDay.getDay() != 1) { + newDate.setDate(newDate.getDate() - 7); + } + + newDate.setDate(newDate.getDate() + 7 * (relative.offset - 1)); + + if (newDate.getMonth() + 1 != relative.tag) { + return sentDate; + } + + return newDate; + } + } else { + newDate = new Date(firstDay.getFullYear(), firstDay.getMonth(), daysInMonth(firstDay.getMonth(), firstDay.getFullYear())); + var offset = 1 - newDate.getDay(); + + if (offset > 0) { + offset = offset - 7; + } + + newDate.setDate(newDate.getDate() + offset); + newDate.setDate(newDate.getDate() + 7 * (1 - relative.offset)); + + if (newDate.getMonth() + 1 != relative.tag) { + if (firstDay.getDay() != 6 && firstDay.getDay() != 0) { + return firstDay; + } else { + return sentDate; + } + } else { + return newDate; + } + } +} + +function decodeRelativeDate(value) { + var tagMask = (1 << tagBits) - 1; + var offsetMask = (1 << offsetBits) - 1; + var unitMask = (1 << unitBits) - 1; + var modifierMask = (1 << modifierBits) - 1; + var tag = value & tagMask; + value >>= tagBits; + var offset = fromComplement(value & offsetMask, offsetBits); + value >>= offsetBits; + var unit = value & unitMask; + value >>= unitBits; + var modifier = value & modifierMask; + + try { + return createRelativeDate(modifier, offset, unit, tag); + } catch (_a) { + return undefined; + } +} + +function fromComplement(value, n) { + var signed = 1 << n - 1; + var mask = (1 << n) - 1; + + if ((value & signed) == signed) { + return -((value ^ mask) + 1); + } else { + return value; + } +} + +function daysInMonth(month, year) { + return 32 - new Date(year, month, 32).getDate(); +} + +function getTimeOfDayInMilliseconds(inputTime) { + var timeOfDay = 0; + timeOfDay += inputTime.getHours() * 3600; + timeOfDay += inputTime.getMinutes() * 60; + timeOfDay += inputTime.getSeconds(); + timeOfDay *= 1000; + timeOfDay += inputTime.getMilliseconds(); + return timeOfDay; +} + +function getTimeOfDayInMillisecondsUTC(inputTime) { + var timeOfDay = 0; + timeOfDay += inputTime.getUTCHours() * 3600; + timeOfDay += inputTime.getUTCMinutes() * 60; + timeOfDay += inputTime.getUTCSeconds(); + timeOfDay *= 1000; + timeOfDay += inputTime.getUTCMilliseconds(); + return timeOfDay; +} + +function createPreciseDate(day, month, year) { + return { + day: day, + month: month, + year: year % 100 + }; +} + +function createRelativeDate(modifier, offset, unit, tag) { + return { + modifier: modifier, + offset: offset, + unit: unit, + tag: tag + }; +} +// CONCATENATED MODULE: ./src/utils/findOffset.ts + + + +function findOffset(value) { + var ranges = getInitialDataProp("timeZoneOffsets"); + + for (var r = 0; r < ranges.length; r++) { + var range = ranges[r]; + var start = parseInt(range.start); + var end = parseInt(range.end); + + if (value.getTime() - start >= 0 && value.getTime() - end < 0) { + return parseInt(range.offset); + } + } + + throw createArgumentError("input", getString("l_InvalidDate_Text")); +} +// CONCATENATED MODULE: ./src/utils/convertToUtcClientTime.ts + + + + + +function convertToUtcClientTime(input) { + var retValue = localClientTimeToDate(input); + + if (!isNullOrUndefined(getInitialDataProp("timeZoneOffsets"))) { + var offset = findOffset(retValue); + retValue.setUTCMinutes(retValue.getUTCMinutes() - offset); + offset = !input["timezoneOffset"] ? retValue.getTimezoneOffset() * -1 : input["timezoneOffset"]; + retValue.setUTCMinutes(retValue.getUTCMinutes() + offset); + } + + return retValue; +} +function localClientTimeToDate(input) { + var retValue = new Date(input["year"], input["month"], input["date"], input["hours"], input["minutes"], input["seconds"], input["milliseconds"] === null ? 0 : input["milliseconds"]); + + if (isNaN(retValue.getTime())) { + throw createArgumentError("input", getString("l_InvalidDate_Text")); + } + + return retValue; +} +// CONCATENATED MODULE: ./src/utils/dateToDictionary.ts +function dateToDictionary(date) { + return { + month: date.getMonth(), + date: date.getDate(), + year: date.getFullYear(), + hours: date.getHours(), + minutes: date.getMinutes(), + seconds: date.getSeconds(), + milliseconds: date.getMilliseconds() + }; +} +// CONCATENATED MODULE: ./src/utils/createEntities.ts + + + + + + + + + +var EntityKeys; + +(function (EntityKeys) { + EntityKeys["meetingSuggestion"] = "MeetingSuggestions"; + EntityKeys["taskSuggestion"] = "TaskSuggestions"; + EntityKeys["address"] = "Addresses"; + EntityKeys["emailAddress"] = "EmailAddresses"; + EntityKeys["url"] = "Urls"; + EntityKeys["phoneNumber"] = "PhoneNumbers"; + EntityKeys["contact"] = "Contacts"; + EntityKeys["flightReservations"] = "FlightReservations"; + EntityKeys["parcelDeliveries"] = "ParcelDeliveries"; +})(EntityKeys || (EntityKeys = {})); + +function createEntities(data) { + if (isNullOrUndefined(data)) { + return { + addresses: [], + emailAddresses: [], + urls: [], + taskSuggestions: [], + meetingSuggestions: [], + phoneNumbers: [], + contacts: [], + flightReservations: [], + parcelDelivery: [] + }; + } else { + return { + addresses: createEntities_createAddresses(data[EntityKeys.address]), + emailAddresses: createEntities_createEmailAddresses(data[EntityKeys.emailAddress]), + urls: createUrls(data[EntityKeys.url]), + taskSuggestions: createEntities_createTaskSuggestions(data[EntityKeys.taskSuggestion]), + meetingSuggestions: createEntities_createMeetingSuggestions(data[EntityKeys.meetingSuggestion]), + phoneNumbers: createPhoneNumbers(data[EntityKeys.phoneNumber]), + contacts: createEntities_createContacts(data[EntityKeys.contact]), + flightReservations: createEntities_createReadItemArray(data[EntityKeys.flightReservations]), + parcelDelivery: createEntities_createReadItemArray(data[EntityKeys.parcelDeliveries]) + }; + } +} +function createFilteredEntities(data, name) { + checkPermissionsAndThrow(1, "item.getFilteredEntitiesByName"); + var results = Object.keys(data).map(function (entities) { + var results = data[entities][name]; + if (results) return { + entityType: entities, + name: name, + entities: data[entities][name] + };else return undefined; + }).filter(function (results) { + return results !== undefined; + }); + + if (results.length === 0) { + return null; + } + + var matchedRule = results[0]; + + switch (matchedRule.entityType) { + case EntityKeys.meetingSuggestion: + return createEntities_createMeetingSuggestions(matchedRule.entities); + + case EntityKeys.address: + return createEntities_createAddresses(matchedRule.entities); + + case EntityKeys.contact: + return createEntities_createContacts(matchedRule.entities); + + case EntityKeys.emailAddress: + return createEntities_createEmailAddresses(matchedRule.entities); + + case EntityKeys.phoneNumber: + return createPhoneNumbers(matchedRule.entities); + + case EntityKeys.taskSuggestion: + return createEntities_createTaskSuggestions(matchedRule.entities); + + case EntityKeys.url: + return createUrls(matchedRule.entities); + + default: + return createEntities_createReadItemArray(matchedRule.entities); + } +} +var createEntities_createAddresses = function createAddresses(data) { + var addresses = data || []; + return removeDuplicates(addresses, stringComparator); +}; +var createEntities_createEmailAddresses = function createEmailAddresses(data) { + if (getPermissionLevel_getPermissionLevel() === 0) { + return []; + } + + return data || []; +}; +var createUrls = function createUrls(data) { + return data || []; +}; +var createEntities_createTaskSuggestions = function createTaskSuggestions(data) { + if (getPermissionLevel_getPermissionLevel() === 0) { + return []; + } + + var tasks = data || []; + tasks = tasks.map(function (task) { + return { + assignees: (task.Assignees || []).map(createEmailAddressDetailsForEntity), + taskString: task.TaskString + }; + }); + return removeDuplicates(tasks, taskComparator); +}; +var createEntities_createMeetingSuggestions = function createMeetingSuggestions(data) { + if (getPermissionLevel_getPermissionLevel() === 0) { + return []; + } + + var meetings = data || []; + meetings = meetings.map(function (meeting) { + var start = meeting.StartTime !== "" ? getDate(meeting.StartTime) : undefined; + var end = meeting.EndTime !== "" ? getDate(meeting.EndTime) : undefined; + return { + meetingString: meeting.MeetingString, + attendees: (meeting.Attendees || []).map(createEmailAddressDetailsForEntity), + location: meeting.Location, + subject: meeting.Subject, + start: meeting.StartTime !== undefined ? start : undefined, + end: meeting.EndTime !== undefined ? end : undefined + }; + }); + return removeDuplicates(meetings, meetingComparator); +}; + +function getDate(date) { + var result = resolveDate(new Date(date), new Date(getInitialDataProp("dateTimeSent"))); + + if (result.getTime() !== new Date(date).getTime()) { + return convertToUtcClientTime(dateToDictionary(result)); + } + + return new Date(date); +} + +var createPhoneNumbers = function createPhoneNumbers(data) { + var phoneNumbers = data || []; + return phoneNumbers.map(function (number) { + return { + phoneString: number.PhoneString, + originalPhoneString: number.OriginalPhoneString, + type: number.Type + }; + }); +}; +var createEntities_createContacts = function createContacts(data) { + if (getPermissionLevel_getPermissionLevel() === 0) { + return []; + } + + var contacts = data || []; + contacts = contacts.map(function (contact) { + return { + personName: contact.PersonName, + businessName: contact.BusinessName, + phoneNumbers: createPhoneNumbers(contact.PhoneNumbers || []), + emailAddresses: contact.EmailAddresses || [], + urls: contact.Urls || [], + addresses: contact.Addresses || [], + contactString: contact.ContactString + }; + }); + return removeDuplicates(contacts, contactComparator); +}; +var createEntities_createReadItemArray = function createReadItemArray(data) { + if (getPermissionLevel_getPermissionLevel() === 0) { + return []; + } + + return data || []; +}; +// CONCATENATED MODULE: ./src/api/Entities.ts + + + +var entityPermissions = { + meetingSuggestion: 1, + taskSuggestion: 1, + address: 0, + emailAddress: 1, + url: 0, + phoneNumber: 0, + contact: 1, + flightReservations: 1, + parcelDeliveries: 1 +}; +var entityKeys = { + meetingSuggestion: "meetingSuggestions", + taskSuggestion: "taskSuggestions", + address: "addresses", + emailAddress: "emailAddresses", + url: "urls", + phoneNumber: "phoneNumbers", + contact: "contacts", + flightReservations: "flightReservations", + parcelDeliveries: "parcelDeliveries" +}; +var Entities_getEntities = function getEntities() { + return createEntities(getInitialDataProp("entities")); +}; +var Entities_getEntitiesByType = function getEntitiesByType(entityType) { + var entities = createEntities(getInitialDataProp("entities")); + checkPermissionsAndThrow(entityPermissions[entityType] !== undefined ? entityPermissions[entityType] : 1, entityType); + var entityProperty = entityKeys[entityType]; + + if (entityProperty === undefined) { + return null; + } + + return entities[entityProperty]; +}; +var Entities_getFilteredEntitiesByName = function getFilteredEntitiesByName(name) { + return createFilteredEntities(getInitialDataProp("filteredEntities"), name); +}; +var Entities_getRegExMatches = function getRegExMatches() { + return getInitialDataProp("regExMatches"); +}; +var Entities_getRegExMatchesByName = function getRegExMatchesByName(name) { + var regExMatches = getInitialDataProp("regExMatches") || {}; + return regExMatches[name]; +}; +var Entities_getSelectedEntities = function getSelectedEntities() { + return createEntities(getInitialDataProp("selectedEntities")); +}; +var Entities_getSelectedRegExMatches = function getSelectedRegExMatches() { + return getInitialDataProp("selectedRegExMatches"); +}; +// CONCATENATED MODULE: ./src/utils/CustomJsonAttachmentsResponse.ts + + +function CustomJsonAttachmentsResponse(arrayOfAttachmentJsonData) { + var customJsonResponse = []; + + if (getPermissionLevel_getPermissionLevel() === 0) { + return []; + } + + if (!!arrayOfAttachmentJsonData) { + for (var i = 0; i < arrayOfAttachmentJsonData.length; i++) { + if (!!arrayOfAttachmentJsonData[i]) { + var newAttachment = convertAttachmentType(arrayOfAttachmentJsonData[i]); + customJsonResponse.push(newAttachment); + } + } + } + + return customJsonResponse; +} +function convertAttachmentType(attachmentDetails) { + if (attachmentDetails.attachmentType !== null || attachmentDetails.attachmentType !== undefined) { + switch (attachmentDetails.attachmentType) { + case 0: + { + attachmentDetails.attachmentType = MailboxEnums.AttachmentType.File; + break; + } + + case 1: + { + attachmentDetails.attachmentType = MailboxEnums.AttachmentType.Item; + break; + } + + case 2: + { + attachmentDetails.attachmentType = MailboxEnums.AttachmentType.Cloud; + break; + } + } + } + + return attachmentDetails; +} +// CONCATENATED MODULE: ./src/methods/deepClone.ts +function deepClone(original) { + return JSON.parse(JSON.stringify(original)); +} +// CONCATENATED MODULE: ./src/validation/seriesTimeConstants.ts +var StartYearKey = "startYear"; +var StartMonthKey = "startMonth"; +var StartDayKey = "startDay"; +var EndYearKey = "endYear"; +var EndMonthKey = "endMonth"; +var EndDayKey = "endDay"; +var NoEndDateKey = "noEndDate"; +var StartTimeMinKey = "startTimeMin"; +var DurationMinKey = "durationMin"; +// CONCATENATED MODULE: ./src/validation/recurrenceConstants.ts +var StartDateKey = "startDate"; +var EndDateKey = "endDate"; +var StartTimeKey = "startTime"; +var EndTimeKey = "endTime"; +var RecurrenceTypeKey = "recurrenceType"; +var SeriesTimeKey = "seriesTime"; +var SeriesTimeJsonKey = "seriesTimeJson"; +var RecurrenceTimeZoneKey = "recurrenceTimeZone"; +var RecurrenceTimeZoneName = "name"; +var RecurrencePropertiesKey = "recurrenceProperties"; +var IntervalKey = "interval"; +var DaysKey = "days"; +var DayOfMonthKey = "dayOfMonth"; +var DayOfWeekKey = "dayOfWeek"; +var WeekNumberKey = "weekNumber"; +var MonthKey = "month"; +var FirstDayOfWeekKey = "firstDayOfWeek"; +// CONCATENATED MODULE: ./src/utils/seriesTimeUtils.ts + + + +function prependZeroToString(number) { + if (number < 0) { + number = 1; + } + + if (number < 10) { + return "0" + number.toString(); + } + + return number.toString(); +} +function throwOnInvalidDate(year, month, day) { + if (!isValidDate(year, month, day)) { + throw createArgumentError(SeriesTimeKey, getString("l_InvalidDate_Text")); + } +} +function isValidDate(year, month, day) { + if (year < 1601 || month < 1 || month > 12 || day < 1 || day > 31) { + return false; + } + + return true; +} +function throwOnInvalidDateString(dateString) { + var regEx = new RegExp("^\\d{4}-(?:[0]\\d|1[0-2])-(?:[0-2]\\d|3[01])$"); + + if (!regEx.test(dateString)) { + throw createArgumentError(SeriesTimeKey, getString("l_InvalidDate_Text")); + } +} +// CONCATENATED MODULE: ./src/api/SeriesTime.ts + + + + + + +var SeriesTime_SeriesTime = function () { + function SeriesTime() { + this.startYear = 0; + this.startMonth = 0; + this.startDay = 0; + this.endYear = 0; + this.endMonth = 0; + this.endDay = 0; + this.startTimeMinutes = 0; + this.durationMinutes = 0; + } + + SeriesTime.prototype.getDuration = function () { + return this.durationMinutes; + }; + + SeriesTime.prototype.getEndTime = function () { + var endTimeMinutes = this.startTimeMinutes + this.durationMinutes; + var minutes = endTimeMinutes % 60; + var hours = Math.floor(endTimeMinutes / 60) % 24; + return "T" + prependZeroToString(hours) + ":" + prependZeroToString(minutes) + ":00.000"; + }; + + SeriesTime.prototype.getEndDate = function () { + if (this.endYear === 0 && this.endMonth === 0 && this.endDay === 0) { + return null; + } + + return this.endYear.toString() + "-" + prependZeroToString(this.endMonth) + "-" + prependZeroToString(this.endDay); + }; + + SeriesTime.prototype.getStartDate = function () { + return this.startYear.toString() + "-" + prependZeroToString(this.startMonth) + "-" + prependZeroToString(this.startDay); + }; + + SeriesTime.prototype.getStartTime = function () { + var minutes = this.startTimeMinutes % 60; + var hours = Math.floor(this.startTimeMinutes / 60); + return "T" + prependZeroToString(hours) + ":" + prependZeroToString(minutes) + ":00.000"; + }; + + SeriesTime.prototype.setDuration = function (minutes) { + if (minutes >= 0) { + this.durationMinutes = minutes; + } else { + throw createArgumentError(undefined, getString("l_InvalidTime_Text")); + } + }; + + SeriesTime.prototype.setEndDate = function (yearOrDateString, month, day) { + if (yearOrDateString !== null && !isNullOrUndefined(month) && day !== null) { + this.setDateHelper(false, yearOrDateString, month, day); + } else if (yearOrDateString !== null) { + this.setDateHelper(false, yearOrDateString); + } else if (yearOrDateString == null) { + this.endYear = 0; + this.endMonth = 0; + this.endDay = 0; + } + }; + + SeriesTime.prototype.setStartDate = function (yearOrDateString, month, day) { + if (yearOrDateString !== null && !isNullOrUndefined(month) && day !== null) { + this.setDateHelper(true, yearOrDateString, month, day); + } else if (yearOrDateString !== null) { + this.setDateHelper(true, yearOrDateString); + } + }; + + SeriesTime.prototype.setStartTime = function (hoursOrTimeString, minutes) { + if (!isNullOrUndefined(hoursOrTimeString) && !isNullOrUndefined(minutes)) { + var totalMinutes = hoursOrTimeString * 60 + minutes; + + if (totalMinutes >= 0) { + this.startTimeMinutes = totalMinutes; + } else { + throw createArgumentError(undefined, getString("l_InvalidTime_Text")); + } + } else if (!isNullOrUndefined(hoursOrTimeString)) { + var timeString = hoursOrTimeString; + var newDateString = "2017-01-15" + timeString + "Z"; + var regEx = new RegExp("^T[0-2]\\d:[0-5]\\d:[0-5]\\d\\.\\d{3}$"); + + if (!regEx.test(timeString)) { + throw createArgumentError(undefined, getString("l_InvalidTime_Text")); + } + + var dateObject = new Date(newDateString); + + if (!isNullOrUndefined(dateObject) && !isNaN(dateObject.getUTCHours()) && !isNaN(dateObject.getUTCMinutes())) { + this.startTimeMinutes = dateObject.getUTCHours() * 60 + dateObject.getUTCMinutes(); + } else { + throw createArgumentError(undefined, getString("l_InvalidTime_Text")); + } + } + }; + + SeriesTime.prototype.isValid = function () { + if (!isValidDate(this.startYear, this.startMonth, this.startDay)) { + return false; + } + + if (this.endDay !== 0 && this.endMonth !== 0 && this.endYear !== 0) { + if (!isValidDate(this.endYear, this.endMonth, this.endDay)) { + return false; + } + } + + if (this.startTimeMinutes < 0 || this.durationMinutes <= 0) { + return false; + } + + return true; + }; + + SeriesTime.prototype.exportToSeriesTimeJson = function () { + var result = {}; + result[StartYearKey] = this.startYear; + result[StartMonthKey] = this.startMonth; + result[StartDayKey] = this.startDay; + + if (this.endYear === 0 && this.endMonth === 0 && this.endDay === 0) { + result[NoEndDateKey] = true; + } else { + result[EndYearKey] = this.endYear; + result[EndMonthKey] = this.endMonth; + result[EndDayKey] = this.endDay; + } + + result[StartTimeMinKey] = this.startTimeMinutes; + + if (this.durationMinutes > 0) { + result[DurationMinKey] = this.durationMinutes; + } + + return result; + }; + + SeriesTime.prototype.importFromSeriesTimeJsonObject = function (jsonObject) { + this.startYear = jsonObject[StartYearKey]; + this.startMonth = jsonObject[StartMonthKey]; + this.startDay = jsonObject[StartDayKey]; + + if (jsonObject[NoEndDateKey] != null && typeof jsonObject[NoEndDateKey] === "boolean") { + this.endYear = 0; + this.endMonth = 0; + this.endDay = 0; + } else { + this.endYear = jsonObject[EndYearKey]; + this.endMonth = jsonObject[EndMonthKey]; + this.endDay = jsonObject[EndDayKey]; + } + + this.startTimeMinutes = jsonObject[StartTimeMinKey]; + this.durationMinutes = jsonObject[DurationMinKey]; + }; + + SeriesTime.prototype.setDateHelper = function (isStart, yearOrDateString, month, day) { + var yearCalculated = 0; + var monthCalculated = 0; + var dayCalculated = 0; + + if (yearOrDateString !== null && !isNullOrUndefined(month) && day !== null) { + throwOnInvalidDate(yearOrDateString, month + 1, day); + yearCalculated = yearOrDateString; + monthCalculated = month + 1; + dayCalculated = day; + } else if (yearOrDateString !== null) { + var dateString = yearOrDateString; + throwOnInvalidDateString(dateString); + var dateObject = new Date(dateString); + + if (dateObject !== null && !isNaN(dateObject.getUTCFullYear()) && !isNaN(dateObject.getUTCMonth()) && !isNaN(dateObject.getUTCDate())) { + throwOnInvalidDate(dateObject.getUTCFullYear(), dateObject.getUTCMonth() + 1, dateObject.getUTCDate()); + yearCalculated = dateObject.getUTCFullYear(); + monthCalculated = dateObject.getUTCMonth() + 1; + dayCalculated = dateObject.getUTCDate(); + } + } + + if (yearCalculated !== 0 && monthCalculated !== 0 && dayCalculated !== 0) { + if (isStart) { + this.startYear = yearCalculated; + this.startMonth = monthCalculated; + this.startDay = dayCalculated; + } else { + this.endYear = yearCalculated; + this.endMonth = monthCalculated; + this.endDay = dayCalculated; + } + } + }; + + SeriesTime.prototype.isEndAfterStart = function () { + if (this.endYear === 0 && this.endMonth === 0 && this.endDay === 0) { + return true; + } + + var startDateTime = new Date(); + startDateTime.setFullYear(this.startYear); + startDateTime.setMonth(this.startMonth - 1); + startDateTime.setDate(this.startDay); + var endDateTime = new Date(); + endDateTime.setFullYear(this.endYear); + endDateTime.setMonth(this.endMonth - 1); + endDateTime.setDate(this.endDay); + return endDateTime >= startDateTime; + }; + + return SeriesTime; +}(); + + +// CONCATENATED MODULE: ./src/utils/recurrenceUtils.ts + + + +function copyRecurrenceObjectConvertSeriesTimeJson(recurrenceOriginal) { + if (isNullOrUndefined(recurrenceOriginal) || isNullOrUndefined(recurrenceOriginal.seriesTimeJson)) { + return recurrenceOriginal; + } + + var recurrenceCopy = { + recurrenceType: "", + recurrenceProperties: null, + recurrenceTimeZone: null + }; + var newSeriesTime = new SeriesTime_SeriesTime(); + + if (!isNullOrUndefined(recurrenceOriginal.recurrenceProperties)) { + recurrenceCopy.recurrenceProperties = deepClone(recurrenceOriginal.recurrenceProperties); + } + + recurrenceCopy.recurrenceType = recurrenceOriginal.recurrenceType; + + if (!isNullOrUndefined(recurrenceOriginal.recurrenceTimeZone)) { + recurrenceCopy.recurrenceTimeZone = deepClone(recurrenceOriginal.recurrenceTimeZone); + } + + newSeriesTime.importFromSeriesTimeJsonObject(recurrenceOriginal.seriesTimeJson); + recurrenceCopy.seriesTime = newSeriesTime; + return recurrenceCopy; +} +// CONCATENATED MODULE: ./src/api/getMessageRead.ts + + + + + + + + + + + + + + + + +function getMessageRead() { + var sender = getInitialDataProp("sender"); + var from = getInitialDataProp("from"); + var dateTimeCreated = getInitialDataProp("dateTimeCreated"); + var dateTimeModified = getInitialDataProp("dateTimeModified"); + var end = getInitialDataProp("end"); + var start = getInitialDataProp("start"); + var messageRead = objectDefine({}, { + attachments: CustomJsonAttachmentsResponse(getInitialDataProp("attachments")), + bcc: (getInitialDataProp("bcc") || []).map(createEmailAddressDetails), + body: getBodySurface(false), + categories: getCategoriesSurface(), + cc: (getInitialDataProp("cc") || []).map(createEmailAddressDetails), + conversationId: getInitialDataProp("conversationId"), + dateTimeCreated: dateTimeCreated ? new Date(dateTimeCreated) : undefined, + dateTimeModified: dateTimeModified ? new Date(dateTimeModified) : undefined, + end: end ? new Date(end) : undefined, + from: from ? createEmailAddressDetails(from) : undefined, + getAllInternetHeadersAsync: getAllInternetHeaders, + internetMessageId: getInitialDataProp("internetMessageId"), + itemClass: getInitialDataProp("itemClass"), + itemId: getInitialDataProp("id"), + itemType: "message", + location: getInitialDataProp("location"), + move: moveToFolder, + normalizedSubject: getInitialDataProp("normalizedSubject"), + notificationMessages: getNotificationMessageSurface(), + recurrence: copyRecurrenceObjectConvertSeriesTimeJson(getInitialDataProp("recurrence")), + seriesId: getInitialDataProp("seriesId"), + sender: sender ? createEmailAddressDetails(sender) : undefined, + start: start ? new Date(start) : undefined, + subject: getInitialDataProp("subject"), + to: (getInitialDataProp("to") || []).map(createEmailAddressDetails), + displayReplyForm: displayReplyForm, + displayReplyFormAsync: displayReplyFormAsync, + displayReplyAllForm: displayReplyAllForm, + displayReplyAllFormAsync: displayReplyAllFormAsync, + getAttachmentContentAsync: getAttachmentContent, + getEntities: Entities_getEntities, + getEntitiesByType: Entities_getEntitiesByType, + getFilteredEntitiesByName: Entities_getFilteredEntitiesByName, + getInitializationContextAsync: getInitializationContext, + getRegExMatches: Entities_getRegExMatches, + getRegExMatchesByName: Entities_getRegExMatchesByName, + getSelectedEntities: Entities_getSelectedEntities, + getSelectedRegExMatches: Entities_getSelectedRegExMatches, + loadCustomPropertiesAsync: loadCustomProperties, + delayDeliveryTime: getDelayDeliverySurface(false), + isAllDayEvent: getInitialDataProp("isAllDayEvent"), + sensitivity: getInitialDataProp("sensitivity") + }); + return messageRead; +} +// CONCATENATED MODULE: ./src/validation/validateAttachments.ts + + + + +function validateAddFileAttachmentApis(attachmentName) { + if (isNullOrUndefined(attachmentName) || attachmentName === "" || !(typeof attachmentName === "string")) { + throw createArgumentError("attachmentName"); + } + + throwOnOutOfRange(attachmentName.length, 0, MaxAttachmentNameLength, "attachmentName"); +} +// CONCATENATED MODULE: ./src/validation/attachmentsConstants.ts +var AddItemAttachmentClientEndPointTimeoutInMilliseconds = 600000; +// CONCATENATED MODULE: ./src/methods/addFileAttachment.ts + + + + + + + + +function addFileAttachment(uri, attachmentName) { + var args = []; + + for (var _i = 2; _i < arguments.length; _i++) { + args[_i - 2] = arguments[_i]; + } + + checkPermissionsAndThrow(2, "item.addFileAttachmentAsync"); + var commonParameters = parseCommonArgs(args, false, false); + var isInline = false; + + if (!!commonParameters.options) { + isInline = !!commonParameters.options.isInline; + } + + var name = attachmentName; + var parameters = { + uri: uri, + name: name, + isInline: isInline, + __timeout__: AddItemAttachmentClientEndPointTimeoutInMilliseconds + }; + addFileAttachment_validateParameters(parameters); + standardInvokeHostMethod(16, commonParameters.asyncContext, commonParameters.callback, parameters, undefined); +} + +function addFileAttachment_validateParameters(parameters) { + validateStringParam("uri", parameters.uri); + throwOnOutOfRange(parameters.uri.length, 0, MaxUrlLength, "uri"); + validateAddFileAttachmentApis(parameters.name); +} +// CONCATENATED MODULE: ./src/methods/addBase64FileAttachment.ts + + + + + + +function addBase64FileAttachment(base64String, name) { + var args = []; + + for (var _i = 2; _i < arguments.length; _i++) { + args[_i - 2] = arguments[_i]; + } + + checkPermissionsAndThrow(2, "item.addBase64FileAttachmentAsync"); + var commonParameters = parseCommonArgs(args, false, false); + var isInline = false; + + if (!!commonParameters.options) { + isInline = !!commonParameters.options.isInline; + } + + var parameters = { + base64String: base64String, + name: name, + isInline: isInline, + __timeout__: AddItemAttachmentClientEndPointTimeoutInMilliseconds + }; + addBase64FileAttachment_validateParameters(parameters); + standardInvokeHostMethod(148, commonParameters.asyncContext, commonParameters.callback, parameters, undefined); +} + +function addBase64FileAttachment_validateParameters(parameters) { + validateStringParam("base64Encoded", parameters.base64String); + validateAddFileAttachmentApis(parameters.name); +} +// CONCATENATED MODULE: ./src/methods/addItemAttachment.ts + + + + + + + + +function addItemAttachment(itemId, name) { + var args = []; + + for (var _i = 2; _i < arguments.length; _i++) { + args[_i - 2] = arguments[_i]; + } + + checkPermissionsAndThrow(2, "item.addItemAttachmentAsync"); + var commonParameters = parseCommonArgs(args, false, false); + var parameters = { + itemId: itemId, + name: name + }; + addItemAttachment_validateParameters(parameters); + standardInvokeHostMethod(19, commonParameters.asyncContext, commonParameters.callback, { + itemId: getItemIdBasedOnHost(parameters.itemId), + name: parameters.name, + __timeout__: AddItemAttachmentClientEndPointTimeoutInMilliseconds + }, undefined); +} + +function addItemAttachment_validateParameters(parameters) { + validateStringParam("itemId", parameters.itemId); + validateStringParam("attachmentName", parameters.name); + throwOnOutOfRange(parameters.itemId.length, 0, MaxItemIdLength, "itemId"); + throwOnOutOfRange(parameters.name.length, 0, MaxAttachmentNameLength, "attachmentName"); +} +// CONCATENATED MODULE: ./src/methods/close.ts + +function close_close() { + standardInvokeHostMethod(41, undefined, undefined, undefined, undefined); +} +// CONCATENATED MODULE: ./src/methods/getAttachments.ts + + + + +function getAttachments_getAttachments() { + var args = []; + + for (var _i = 0; _i < arguments.length; _i++) { + args[_i] = arguments[_i]; + } + + checkPermissionsAndThrow(1, "item.getAttachmentsAsync"); + var commonParameters = parseCommonArgs(args, true, false); + standardInvokeHostMethod(149, commonParameters.asyncContext, commonParameters.callback, undefined, CustomJsonAttachmentsResponse); +} +// CONCATENATED MODULE: ./src/methods/getSelectedData.ts + + + + + +function getSelectedData(coercionType) { + var args = []; + + for (var _i = 1; _i < arguments.length; _i++) { + args[_i - 1] = arguments[_i]; + } + + checkPermissionsAndThrow(2, "item.getSelectedDataAsync"); + var commonParameters = parseCommonArgs(args, true, false); + var parameters = { + coercionType: getCoercionTypeFromString(coercionType) + }; + + if (parameters.coercionType === undefined) { + throw createArgumentError("coercionType"); + } + + standardInvokeHostMethod(28, commonParameters.asyncContext, commonParameters.callback, parameters, undefined); +} +// CONCATENATED MODULE: ./src/methods/removeAttachment.ts + + + + + + +function removeAttachment(attachmentId) { + var args = []; + + for (var _i = 1; _i < arguments.length; _i++) { + args[_i - 1] = arguments[_i]; + } + + checkPermissionsAndThrow(2, "item.removeAttachmentAsync"); + var commonParameters = parseCommonArgs(args, false, false); + var parameters = { + attachmentIndex: attachmentId + }; + removeAttachment_validateParameters(parameters); + standardInvokeHostMethod(20, commonParameters.asyncContext, commonParameters.callback, parameters, undefined); +} + +function removeAttachment_validateParameters(parameters) { + validateStringParam("attachmentId", parameters.attachmentIndex); + throwOnOutOfRange(parameters.attachmentIndex.length, 0, MaxRemoveIdLength, "attachmentId"); +} +// CONCATENATED MODULE: ./src/methods/save.ts + + + +function save() { + var args = []; + + for (var _i = 0; _i < arguments.length; _i++) { + args[_i] = arguments[_i]; + } + + checkPermissionsAndThrow(2, "item.saveAsync"); + var commonParameters = parseCommonArgs(args, false, false); + standardInvokeHostMethod(32, commonParameters.asyncContext, commonParameters.callback, undefined, undefined); +} +// CONCATENATED MODULE: ./src/validation/validateRecipientParameters.ts + + + + +function validateRecipientParameters(parameters) { + if (Array.isArray(parameters.recipientArray)) { + if (parameters.recipientArray.length > recipientsLimit) { + throw createArgumentOutOfRange("recipients", parameters.recipientArray.length); + } + + var validatedRecipients = parameters.recipientArray.map(function (recipient) { + if (isNullOrUndefined(recipient)) { + throw createArgumentError("recipients"); + } + + if (typeof recipient === "string") { + throwOnInvalidDisplayNameOrEmail(recipient, recipient); + return createEmailAddressForHost(recipient, recipient); + } else if (typeof recipient === "object") { + throwOnInvalidDisplayNameOrEmail(recipient.displayName, recipient.emailAddress); + return createEmailAddressForHost(recipient.displayName, recipient.emailAddress); + } else { + throw createArgumentError("recipients"); + } + }); + parameters.recipientArray = validatedRecipients; + } else { + throw createArgumentError("recipients"); + } +} + +function throwOnInvalidDisplayNameOrEmail(displayName, email) { + if (!displayName && !email) { + throw createArgumentError("recipients"); + } else if (typeof displayName === "string" && displayName.length > displayNameLengthLimit) { + throw createArgumentOutOfRange("recipients", displayName.length, getString("l_DisplayNameTooLong_Text")); + } else if (typeof email === "string" && email.length > maxSmtpLength) { + throw createArgumentOutOfRange("recipients", email.length, getString("l_EmailAddressTooLong_Text")); + } else if (typeof displayName !== "string" && typeof email !== "string") { + throw createArgumentError("recipients"); + } +} + +function createEmailAddressForHost(displayName, email) { + return { + address: email, + name: displayName + }; +} +// CONCATENATED MODULE: ./src/methods/addRecipients.ts + + + + + +function addRecipients(namespace) { + return function (recipientArray) { + var args = []; + + for (var _i = 1; _i < arguments.length; _i++) { + args[_i - 1] = arguments[_i]; + } + + checkPermissionsAndThrow(2, namespace + ".addAsync"); + var commonParameters = parseCommonArgs(args, false, false); + var parameters = { + recipientField: RecipientFields[namespace], + recipientArray: recipientArray + }; + validateRecipientParameters(parameters); + standardInvokeHostMethod(22, commonParameters.asyncContext, commonParameters.callback, parameters, undefined); + }; +} +// CONCATENATED MODULE: ./src/methods/getRecipients.ts + + + + + +function getRecipients(namespace) { + return function () { + var args = []; + + for (var _i = 0; _i < arguments.length; _i++) { + args[_i] = arguments[_i]; + } + + checkPermissionsAndThrow(1, namespace + ".getAsync"); + var commonParameters = parseCommonArgs(args, true, false); + standardInvokeHostMethod(15, commonParameters.asyncContext, commonParameters.callback, { + recipientField: RecipientFields[namespace] + }, getRecipients_format); + }; +} + +function getRecipients_format(rawInput) { + if (rawInput === null || rawInput === undefined) { + return []; + } + + return rawInput.map(function (input) { + return createEmailAddressDetails(input); + }); +} +// CONCATENATED MODULE: ./src/methods/setRecipients.ts + + + + + +function setRecipients(namespace) { + return function (recipientArray) { + var args = []; + + for (var _i = 1; _i < arguments.length; _i++) { + args[_i - 1] = arguments[_i]; + } + + checkPermissionsAndThrow(2, namespace + ".setAsync"); + var commonParameters = parseCommonArgs(args, false, false); + var parameters = { + recipientField: RecipientFields[namespace], + recipientArray: recipientArray + }; + validateRecipientParameters(parameters); + standardInvokeHostMethod(21, commonParameters.asyncContext, commonParameters.callback, parameters, undefined); + }; +} +// CONCATENATED MODULE: ./src/api/getRecipientsSurface.ts + + + + +function getRecipientsSurface(namespace) { + return objectDefine({}, { + addAsync: addRecipients(namespace), + getAsync: getRecipients(namespace), + setAsync: setRecipients(namespace) + }); +} +// CONCATENATED MODULE: ./src/methods/getFrom.ts + + + + + +function getFrom(namespace) { + return function () { + var args = []; + + for (var _i = 0; _i < arguments.length; _i++) { + args[_i] = arguments[_i]; + } + + checkPermissionsAndThrow(1, namespace + ".getAsync"); + var commonParameters = parseCommonArgs(args, true, false); + standardInvokeHostMethod(107, commonParameters.asyncContext, commonParameters.callback, undefined, getFrom_format); + }; +} + +function getFrom_format(rawInput) { + return isNullOrUndefined(rawInput) ? null : createEmailAddressDetails(rawInput); +} +// CONCATENATED MODULE: ./src/api/getFromSurface.ts + + +function getFromSurface(namespace) { + return objectDefine({}, { + getAsync: getFrom(namespace) + }); +} +// CONCATENATED MODULE: ./src/validation/validateInternetHeaders.ts + + + +function validateInternetHeaderArray(internetHeaderArray) { + if (isNullOrUndefined(internetHeaderArray)) { + throw createArgumentError("internetHeaders"); + } + + if (!Array.isArray(internetHeaderArray)) { + throw createArgumentTypeError("internetHeaders", typeof internetHeaderArray, "Array"); + } + + if (internetHeaderArray.length === 0) { + throw createArgumentError("internetHeaders"); + } + + for (var _i = 0, internetHeaderArray_1 = internetHeaderArray; _i < internetHeaderArray_1.length; _i++) { + var internetHeader = internetHeaderArray_1[_i]; + validateStringParam("internetHeaders", internetHeader); + } +} +// CONCATENATED MODULE: ./src/methods/removeInternetHeaders.ts + + + + +function removeInternetHeaders(internetHeaderKeys) { + var args = []; + + for (var _i = 1; _i < arguments.length; _i++) { + args[_i - 1] = arguments[_i]; + } + + checkPermissionsAndThrow(2, "internetHeaders.removeAsync"); + var commonParameters = parseCommonArgs(args, false, false); + var parameters = { + internetHeaderKeys: internetHeaderKeys + }; + removeInternetHeaders_validateParameters(parameters); + standardInvokeHostMethod(153, commonParameters.asyncContext, commonParameters.callback, parameters, undefined); +} + +function removeInternetHeaders_validateParameters(parameters) { + validateInternetHeaderArray(parameters.internetHeaderKeys); +} +// CONCATENATED MODULE: ./src/methods/getInternetHeaders.ts + + + + +function getInternetHeaders(internetHeaderKeys) { + var args = []; + + for (var _i = 1; _i < arguments.length; _i++) { + args[_i - 1] = arguments[_i]; + } + + checkPermissionsAndThrow(1, "internetHeaders.getAsync"); + var commonParameters = parseCommonArgs(args, true, false); + var parameters = { + internetHeaderKeys: internetHeaderKeys + }; + getInternetHeaders_validateParameters(parameters); + standardInvokeHostMethod(151, commonParameters.asyncContext, commonParameters.callback, parameters, undefined); +} + +function getInternetHeaders_validateParameters(parameters) { + validateInternetHeaderArray(parameters.internetHeaderKeys); +} +// CONCATENATED MODULE: ./src/methods/setInternetHeaders.ts + + + + + + + +var InternetHeadersLimit = 998; +function setInternetHeaders(internetHeaderNameValuePairs) { + var args = []; + + for (var _i = 1; _i < arguments.length; _i++) { + args[_i - 1] = arguments[_i]; + } + + checkPermissionsAndThrow(2, "internetHeaders.setAsync"); + var commonParameters = parseCommonArgs(args, false, false); + var parameters = { + internetHeaderNameValuePairs: internetHeaderNameValuePairs + }; + setInternetHeaders_validateParameters(parameters); + standardInvokeHostMethod(152, commonParameters.asyncContext, commonParameters.callback, parameters, undefined); +} + +function setInternetHeaders_validateParameters(parameters) { + if (isNullOrUndefined(parameters.internetHeaderNameValuePairs)) { + throw createNullArgumentError("internetHeaders"); + } + + var keys = Object.keys(parameters.internetHeaderNameValuePairs); + + if (keys.length === 0) { + throw createArgumentError("internetHeaders"); + } + + for (var _i = 0, keys_1 = keys; _i < keys_1.length; _i++) { + var key = keys_1[_i]; + var value = parameters.internetHeaderNameValuePairs[key]; + validateStringParam("internetHeaders", key); + + if (!(typeof value === "string")) { + throw createArgumentTypeError("internetHeaders", typeof value, "string"); + } + + throwOnOutOfRange(key.length + value.length, 0, InternetHeadersLimit, key); + } +} +// CONCATENATED MODULE: ./src/api/getInternetHeadersSurface.ts + + + + +function getInternetHeadersSurface(isCompose) { + var internetHeaders = objectDefine({}, { + getAsync: getInternetHeaders + }); + + if (isCompose) { + objectDefine(internetHeaders, { + removeAsync: removeInternetHeaders, + setAsync: setInternetHeaders + }); + } + + return internetHeaders; +} +// CONCATENATED MODULE: ./src/methods/getSubject.ts + + + +function getSubject() { + var args = []; + + for (var _i = 0; _i < arguments.length; _i++) { + args[_i] = arguments[_i]; + } + + checkPermissionsAndThrow(1, "subject.getAsync"); + var commonParameters = parseCommonArgs(args, true, false); + standardInvokeHostMethod(18, commonParameters.asyncContext, commonParameters.callback, undefined, undefined); +} +// CONCATENATED MODULE: ./src/methods/setSubject.ts + + + + + +var MaximumSubjectLength = 255; +function setSubject(subject) { + var args = []; + + for (var _i = 1; _i < arguments.length; _i++) { + args[_i - 1] = arguments[_i]; + } + + checkPermissionsAndThrow(2, "subject.setAsync"); + var commonParameters = parseCommonArgs(args, false, false); + var parameters = { + subject: subject + }; + setSubject_validateParameters(parameters); + standardInvokeHostMethod(17, commonParameters.asyncContext, commonParameters.callback, parameters, undefined); +} + +function setSubject_validateParameters(parameters) { + if (!(typeof parameters.subject === "string")) { + throw createArgumentTypeError("subject", typeof parameters.subject, "string"); + } + + throwOnOutOfRange(parameters.subject.length, 0, MaximumSubjectLength, "subject"); +} +// CONCATENATED MODULE: ./src/api/getSubjectSurface.ts + + + +function getSubjectSurface() { + return objectDefine({}, { + getAsync: getSubject, + setAsync: setSubject + }); +} +// CONCATENATED MODULE: ./src/methods/getItemId.ts + + + +function getItemId() { + var args = []; + + for (var _i = 0; _i < arguments.length; _i++) { + args[_i] = arguments[_i]; + } + + checkPermissionsAndThrow(1, "item.getItemIdAsync"); + var commonParameters = parseCommonArgs(args, true, false); + standardInvokeHostMethod(164, commonParameters.asyncContext, commonParameters.callback, undefined, undefined); +} +// CONCATENATED MODULE: ./src/methods/getComposeType.ts + + + + +function getComposeType() { + var args = []; + + for (var _i = 0; _i < arguments.length; _i++) { + args[_i] = arguments[_i]; + } + + checkPermissionsAndThrow(1, "item.getComposeTypeAsync"); + var commonParameters = parseCommonArgs(args, true, false); + checkFeatureEnabledAndThrow(Features.signature, "getComposeTypeAsync"); + standardInvokeHostMethod(174, commonParameters.asyncContext, commonParameters.callback, undefined, undefined); +} +// CONCATENATED MODULE: ./src/methods/isClientSignatureEnabled.ts + + + + +function isClientSignatureEnabled() { + var args = []; + + for (var _i = 0; _i < arguments.length; _i++) { + args[_i] = arguments[_i]; + } + + checkPermissionsAndThrow(1, "isClientSignatureEnabledAsync"); + var commonParameters = parseCommonArgs(args, true, false); + checkFeatureEnabledAndThrow(Features.signature, "isClientSignatureEnabledAsync"); + standardInvokeHostMethod(175, commonParameters.asyncContext, commonParameters.callback, undefined, undefined); +} +// CONCATENATED MODULE: ./src/methods/disableClientSignature.ts + + + + +function disableClientSignature() { + var args = []; + + for (var _i = 0; _i < arguments.length; _i++) { + args[_i] = arguments[_i]; + } + + checkPermissionsAndThrow(2, "disableClientSignatureAsync"); + var commonParameters = parseCommonArgs(args, true, false); + checkFeatureEnabledAndThrow(Features.signature, "disableClientSignatureAsync"); + standardInvokeHostMethod(176, commonParameters.asyncContext, commonParameters.callback, undefined, undefined); +} +// CONCATENATED MODULE: ./src/methods/getSessionData.ts + + + + + +function getSessionData(name) { + var args = []; + + for (var _i = 1; _i < arguments.length; _i++) { + args[_i - 1] = arguments[_i]; + } + + checkPermissionsAndThrow(2, "sessionData.getAsync"); + var commonParameters = parseCommonArgs(args, true, false); + checkFeatureEnabledAndThrow(Features.sessionData, "sessionData.getAsync"); + var parameters = { + name: name + }; + getSessionData_validateParameters(parameters); + standardInvokeHostMethod(186, commonParameters.asyncContext, commonParameters.callback, parameters, undefined); +} + +function getSessionData_validateParameters(parameters) { + validateStringParam("name", parameters.name); +} +// CONCATENATED MODULE: ./src/methods/setSessionData.ts + + + + + +function setSessionData(name, value) { + var args = []; + + for (var _i = 2; _i < arguments.length; _i++) { + args[_i - 2] = arguments[_i]; + } + + checkPermissionsAndThrow(2, "sessionData.setAsync"); + var commonParameters = parseCommonArgs(args, false, false); + var parameters = { + name: name, + value: value + }; + checkFeatureEnabledAndThrow(Features.sessionData, "sessionData.setAsync"); + setSessionData_validateParameters(parameters); + standardInvokeHostMethod(185, commonParameters.asyncContext, commonParameters.callback, parameters, undefined); +} + +function setSessionData_validateParameters(parameters) { + validateStringParam("name", parameters.name); + validateStringParamWithEmptyAllowed("value", parameters.value); +} +// CONCATENATED MODULE: ./src/methods/getAllSessionData.ts + + + + +function getAllSessionData() { + var args = []; + + for (var _i = 0; _i < arguments.length; _i++) { + args[_i] = arguments[_i]; + } + + checkPermissionsAndThrow(2, "sessionData.getAllAsync"); + var commonParameters = parseCommonArgs(args, true, false); + checkFeatureEnabledAndThrow(Features.sessionData, "sessionData.getAllAsync"); + standardInvokeHostMethod(187, commonParameters.asyncContext, commonParameters.callback, undefined, undefined); +} +// CONCATENATED MODULE: ./src/methods/clearSessionData.ts + + + + +function clearSessionData() { + var args = []; + + for (var _i = 0; _i < arguments.length; _i++) { + args[_i] = arguments[_i]; + } + + checkPermissionsAndThrow(2, "sessionData.clearAsync"); + var commonParameters = parseCommonArgs(args, false, false); + checkFeatureEnabledAndThrow(Features.sessionData, "sessionData.clearAsync"); + standardInvokeHostMethod(188, commonParameters.asyncContext, commonParameters.callback, undefined, undefined); +} +// CONCATENATED MODULE: ./src/methods/removeSessionData.ts + + + + + +function removeSessionData(name) { + var args = []; + + for (var _i = 1; _i < arguments.length; _i++) { + args[_i - 1] = arguments[_i]; + } + + checkPermissionsAndThrow(2, "sessionData.removeAsync"); + var commonParameters = parseCommonArgs(args, false, false); + var parameters = { + name: name + }; + checkFeatureEnabledAndThrow(Features.sessionData, "sessionData.removeAsync"); + removeSessionData_validateParameters(parameters); + standardInvokeHostMethod(189, commonParameters.asyncContext, commonParameters.callback, parameters, undefined); +} + +function removeSessionData_validateParameters(parameters) { + validateStringParam("name", parameters.name); +} +// CONCATENATED MODULE: ./src/api/getSessionDataSurface.ts + + + + + + +function getSessionDataSurface() { + return objectDefine({}, { + getAsync: getSessionData, + setAsync: setSessionData, + getAllAsync: getAllSessionData, + clearAsync: clearSessionData, + removeAsync: removeSessionData + }); +} +// CONCATENATED MODULE: ./src/api/getMessageCompose.ts + + + + + + + + + + + + + + + + + + + + + + + + + + + +function getMessageCompose() { + var messageCompose = objectDefine({}, { + bcc: getRecipientsSurface("bcc"), + body: getBodySurface(true), + categories: getCategoriesSurface(), + cc: getRecipientsSurface("cc"), + conversationId: getInitialDataProp("conversationId"), + from: getFromSurface("from"), + internetHeaders: getInternetHeadersSurface(true), + itemType: "message", + notificationMessages: getNotificationMessageSurface(), + seriesId: getInitialDataProp("seriesId"), + subject: getSubjectSurface(), + to: getRecipientsSurface("to"), + addFileAttachmentAsync: addFileAttachment, + addFileAttachmentFromBase64Async: addBase64FileAttachment, + addItemAttachmentAsync: addItemAttachment, + close: close_close, + getAttachmentsAsync: getAttachments_getAttachments, + getAttachmentContentAsync: getAttachmentContent, + getInitializationContextAsync: getInitializationContext, + getItemIdAsync: getItemId, + getSelectedDataAsync: getSelectedData, + loadCustomPropertiesAsync: loadCustomProperties, + removeAttachmentAsync: removeAttachment, + saveAsync: save, + setSelectedDataAsync: setSelectedData(29), + delayDeliveryTime: getDelayDeliverySurface(true), + getComposeTypeAsync: getComposeType, + isClientSignatureEnabledAsync: isClientSignatureEnabled, + disableClientSignatureAsync: disableClientSignature, + sessionData: getSessionDataSurface() + }); + return messageCompose; +} +// CONCATENATED MODULE: ./src/validation/validateEnhancedLocation.ts + + + + +function validateLocationIdentifiers(locationIdentifiers) { + if (isNullOrUndefined(locationIdentifiers)) { + throw createNullArgumentError("locationIdentifier"); + } + + if (!Array.isArray(locationIdentifiers)) { + throw createArgumentTypeError("locationIdentifier", typeof locationIdentifiers, "Array"); + } + + if (locationIdentifiers.length === 0) { + throw createArgumentError("locationIdentifier"); + } + + for (var _i = 0, locationIdentifiers_1 = locationIdentifiers; _i < locationIdentifiers_1.length; _i++) { + var locationIdentifier = locationIdentifiers_1[_i]; + validateLocationIdentifier(locationIdentifier); + } +} + +function validateLocationIdentifier(locationIdentifier) { + if (isNullOrUndefined(locationIdentifier) || isNullOrUndefined(locationIdentifier.id) || isNullOrUndefined(locationIdentifier.type)) { + throw createNullArgumentError("locationIdentifier"); + } + + if (locationIdentifier.type === MailboxEnums.LocationType.Room || locationIdentifier.type === MailboxEnums.LocationType.Custom) { + validateIdParameter(locationIdentifier.id, locationIdentifier.type); + } else { + throw createArgumentError("type"); + } +} + +function validateIdParameter(id, type) { + if (id === "") { + throw createArgumentError("id"); + } + + if (type === MailboxEnums.LocationType.Room) { + if (id.length > maxSmtpLength) { + throw createArgumentError("id"); + } + } +} +// CONCATENATED MODULE: ./src/methods/addEnhancedLocations.ts + + + + +function addEnhancedLocations(enhancedLocations) { + var args = []; + + for (var _i = 1; _i < arguments.length; _i++) { + args[_i - 1] = arguments[_i]; + } + + checkPermissionsAndThrow(2, "enhancedLocations.addAsync"); + var commonParameters = parseCommonArgs(args, false, false); + var parameters = { + enhancedLocations: enhancedLocations + }; + addEnhancedLocations_validateParameters(parameters); + standardInvokeHostMethod(155, commonParameters.asyncContext, commonParameters.callback, parameters, undefined); +} + +function addEnhancedLocations_validateParameters(parameters) { + validateLocationIdentifiers(parameters.enhancedLocations); +} +// CONCATENATED MODULE: ./src/methods/getEnhancedLocations.ts + + + +function getEnhancedLocations() { + var args = []; + + for (var _i = 0; _i < arguments.length; _i++) { + args[_i] = arguments[_i]; + } + + checkPermissionsAndThrow(1, "enhancedLocations.getAsync"); + var commonParameters = parseCommonArgs(args, true, false); + standardInvokeHostMethod(154, commonParameters.asyncContext, commonParameters.callback, undefined, undefined); +} +// CONCATENATED MODULE: ./src/methods/removeEnhancedLocations.ts + + + + +function removeEnhancedLocations(enhancedLocations) { + var args = []; + + for (var _i = 1; _i < arguments.length; _i++) { + args[_i - 1] = arguments[_i]; + } + + checkPermissionsAndThrow(2, "enhancedLocations.removeAsync"); + var commonParameters = parseCommonArgs(args, false, false); + var parameters = { + enhancedLocations: enhancedLocations + }; + removeEnhancedLocations_validateParameters(parameters); + standardInvokeHostMethod(156, commonParameters.asyncContext, commonParameters.callback, parameters, undefined); +} + +function removeEnhancedLocations_validateParameters(parameters) { + validateLocationIdentifiers(parameters.enhancedLocations); +} +// CONCATENATED MODULE: ./src/api/getEnhancedLocationSurface.ts + + + + +function getEnhancedLocationsSurface(isCompose) { + var enhancedLocations = objectDefine({}, { + getAsync: getEnhancedLocations + }); + + if (isCompose) { + objectDefine(enhancedLocations, { + addAsync: addEnhancedLocations, + removeAsync: removeEnhancedLocations + }); + } + + return enhancedLocations; +} +// CONCATENATED MODULE: ./src/api/getAppointmentRead.ts + + + + + + + + + + + + + + +function getAppointmentRead() { + var organizer = getInitialDataProp("organizer"); + var dateTimeCreated = getInitialDataProp("dateTimeCreated"); + var dateTimeModified = getInitialDataProp("dateTimeModified"); + var end = getInitialDataProp("end"); + var start = getInitialDataProp("start"); + var appointmentRead = objectDefine({}, { + attachments: CustomJsonAttachmentsResponse(getInitialDataProp("attachments")), + body: getBodySurface(false), + categories: getCategoriesSurface(), + dateTimeCreated: dateTimeCreated ? new Date(dateTimeCreated) : undefined, + dateTimeModified: dateTimeModified ? new Date(dateTimeModified) : undefined, + end: end ? new Date(end) : undefined, + enhancedLocation: getEnhancedLocationsSurface(false), + itemClass: getInitialDataProp("itemClass"), + itemId: getInitialDataProp("id"), + itemType: "appointment", + location: getInitialDataProp("location"), + normalizedSubject: getInitialDataProp("normalizedSubject"), + notificationMessages: getNotificationMessageSurface(), + optionalAttendees: (getInitialDataProp("cc") || []).map(createEmailAddressDetails), + organizer: organizer ? createEmailAddressDetails(organizer) : undefined, + recurrence: copyRecurrenceObjectConvertSeriesTimeJson(getInitialDataProp("recurrence")), + requiredAttendees: (getInitialDataProp("to") || []).map(createEmailAddressDetails), + start: start ? new Date(start) : undefined, + seriesId: getInitialDataProp("seriesId"), + subject: getInitialDataProp("subject"), + displayReplyForm: displayReplyForm, + displayReplyFormAsync: displayReplyFormAsync, + displayReplyAllForm: displayReplyAllForm, + displayReplyAllFormAsync: displayReplyAllFormAsync, + getAttachmentContentAsync: getAttachmentContent, + getEntities: Entities_getEntities, + getEntitiesByType: Entities_getEntitiesByType, + getFilteredEntitiesByName: Entities_getFilteredEntitiesByName, + getInitializationContextAsync: getInitializationContext, + getRegExMatches: Entities_getRegExMatches, + getRegExMatchesByName: Entities_getRegExMatchesByName, + getSelectedEntities: Entities_getSelectedEntities, + getSelectedRegExMatches: Entities_getSelectedRegExMatches, + loadCustomPropertiesAsync: loadCustomProperties, + isAllDayEvent: getInitialDataProp("isAllDayEvent"), + sensitivity: getInitialDataProp("sensitivity") + }); + return appointmentRead; +} +// CONCATENATED MODULE: ./src/validation/timeConstants.ts +var TimeType; + +(function (TimeType) { + TimeType[TimeType["start"] = 1] = "start"; + TimeType[TimeType["end"] = 2] = "end"; +})(TimeType || (TimeType = {})); +// CONCATENATED MODULE: ./src/methods/getTime.ts + + + + +function getTime(namespace) { + return function () { + var args = []; + + for (var _i = 0; _i < arguments.length; _i++) { + args[_i] = arguments[_i]; + } + + checkPermissionsAndThrow(1, namespace + ".getAsync"); + var commonParameters = parseCommonArgs(args, true, false); + standardInvokeHostMethod(24, commonParameters.asyncContext, commonParameters.callback, { + TimeProperty: TimeType[namespace] + }, getTime_format); + }; +} + +function getTime_format(rawInput) { + var ticks = rawInput; + return new Date(ticks); +} +// CONCATENATED MODULE: ./src/methods/setTime.ts + + + + + + +var maxTime = 8640000000000000; +var minTime = -8640000000000000; +function setTime(namespace) { + return function (date) { + var args = []; + + for (var _i = 1; _i < arguments.length; _i++) { + args[_i - 1] = arguments[_i]; + } + + checkPermissionsAndThrow(2, namespace + ".setAsync"); + var commonParameters = parseCommonArgs(args, false, false); + var parameters = { + date: date + }; + setTime_validateParameters(parameters); + standardInvokeHostMethod(25, commonParameters.asyncContext, commonParameters.callback, { + TimeProperty: TimeType[namespace], + time: parameters.date.getTime() + }, undefined); + }; +} + +function setTime_validateParameters(parameters) { + if (!isDateObject(parameters.date)) { + throw createArgumentTypeError("dateTime", typeof parameters.date, typeof Date); + } + + if (isNaN(parameters.date.getTime())) { + throw createArgumentError("dateTime"); + } + + if (parameters.date.getTime() < minTime || parameters.date.getTime() > maxTime) { + throw createArgumentOutOfRange("dateTime"); + } +} +// CONCATENATED MODULE: ./src/api/getTimeSurface.ts + + + +function getTimeSurface(namespace) { + return objectDefine({}, { + getAsync: getTime(namespace), + setAsync: setTime(namespace) + }); +} +// CONCATENATED MODULE: ./src/methods/getLocation.ts + + + +function getLocation() { + var args = []; + + for (var _i = 0; _i < arguments.length; _i++) { + args[_i] = arguments[_i]; + } + + checkPermissionsAndThrow(1, "location.getAsync"); + var commonParameters = parseCommonArgs(args, true, false); + standardInvokeHostMethod(26, commonParameters.asyncContext, commonParameters.callback, undefined, undefined); +} +// CONCATENATED MODULE: ./src/methods/setLocation.ts + + + + + + +var MaximumLocationLength = 255; +function setLocation(location) { + var args = []; + + for (var _i = 1; _i < arguments.length; _i++) { + args[_i - 1] = arguments[_i]; + } + + checkPermissionsAndThrow(2, "location.setAsync"); + var commonParameters = parseCommonArgs(args, false, false); + var parameters = { + location: location + }; + setLocation_validateParameters(parameters); + standardInvokeHostMethod(27, commonParameters.asyncContext, commonParameters.callback, parameters, undefined); +} + +function setLocation_validateParameters(parameters) { + if (!isNullOrUndefined(parameters.location)) { + if (!(typeof parameters.location === "string")) { + throw createArgumentTypeError("location", typeof parameters.location, "string"); + } + + throwOnOutOfRange(parameters.location.length, 0, MaximumLocationLength, "location"); + } else { + throw createNullArgumentError("location"); + } +} +// CONCATENATED MODULE: ./src/api/getLocationSurface.ts + + + +function getLocationSurface() { + return objectDefine({}, { + getAsync: getLocation, + setAsync: setLocation + }); +} +// CONCATENATED MODULE: ./src/methods/getRecurrence.ts + + + + +function getRecurrence() { + var args = []; + + for (var _i = 0; _i < arguments.length; _i++) { + args[_i] = arguments[_i]; + } + + checkPermissionsAndThrow(1, "recurrenceProperties.getAsync"); + var commonParameters = parseCommonArgs(args, true, false); + standardInvokeHostMethod(103, commonParameters.asyncContext, commonParameters.callback, undefined, seriesTimeJsonConverter); +} +function seriesTimeJsonConverter(rawInput) { + if (rawInput !== null) { + if (rawInput.seriesTimeJson !== null) { + var seriesTime = new SeriesTime_SeriesTime(); + seriesTime.importFromSeriesTimeJsonObject(rawInput.seriesTimeJson); + delete rawInput.seriesTimeJson; + rawInput.seriesTime = seriesTime; + } + } + + return rawInput; +} +// CONCATENATED MODULE: ./src/validation/validateRecurrenceObject.ts + + + + + + +function validateRecurrenceObject(recurrenceObject) { + if (isNullOrUndefined(recurrenceObject)) { + return; + } + + recurrenceObject = recurrenceObject; + + if (isNullOrUndefined(recurrenceObject.recurrenceType)) { + throw createNullArgumentError(RecurrenceTypeKey); + } + + if (isNullOrUndefined(recurrenceObject.seriesTime)) { + throw createNullArgumentError(SeriesTimeKey); + } + + if (!(recurrenceObject.seriesTime instanceof SeriesTime_SeriesTime) || !recurrenceObject.seriesTime.isValid()) { + throw createArgumentError(SeriesTimeKey); + } + + if (!recurrenceObject.seriesTime.isEndAfterStart()) { + throw createArgumentError(SeriesTimeKey, getString("l_InvalidEventDates_Text")); + } + + throwOnInvalidRecurrenceType(recurrenceObject.recurrenceType); + + if (recurrenceObject.recurrenceType !== MailboxEnums.RecurrenceType.Weekday) { + if (isNullOrUndefined(recurrenceObject.recurrenceProperties)) { + throw createNullArgumentError(RecurrenceTypeKey); + } + } + + if (!isNullOrUndefined(recurrenceObject.recurrenceTimeZone)) { + if (isNullOrUndefined(recurrenceObject.recurrenceTimeZone.name)) { + throw createNullArgumentError(RecurrenceTimeZoneName); + } + + if (typeof recurrenceObject.recurrenceTimeZone.name !== "string") { + throw createArgumentTypeError(RecurrenceTimeZoneName, typeof recurrenceObject.recurrenceTimeZone.name, "string"); + } + } + + if (recurrenceObject.recurrenceType === MailboxEnums.RecurrenceType.Daily) { + throwOnInvalidDailyRecurrence(recurrenceObject.recurrenceProperties); + } else if (recurrenceObject.recurrenceType === MailboxEnums.RecurrenceType.Weekly) { + throwOnInvalidWeeklyRecurrence(recurrenceObject.recurrenceProperties); + } else if (recurrenceObject.recurrenceType === MailboxEnums.RecurrenceType.Monthly) { + throwOnInvalidMonthlyRecurrence(recurrenceObject.recurrenceProperties); + } else if (recurrenceObject.recurrenceType === MailboxEnums.RecurrenceType.Yearly) { + throwOnInvalidYearlyRecurrence(recurrenceObject.recurrenceProperties); + } +} + +function throwOnInvalidRecurrenceType(recurrenceType) { + if (recurrenceType !== MailboxEnums.RecurrenceType.Daily && recurrenceType !== MailboxEnums.RecurrenceType.Weekly && recurrenceType !== MailboxEnums.RecurrenceType.Weekday && recurrenceType !== MailboxEnums.RecurrenceType.Yearly && recurrenceType !== MailboxEnums.RecurrenceType.Monthly) { + throw createArgumentError(RecurrenceTypeKey); + } +} + +function throwOnInvalidRecurrenceInterval(recurrenceProperties) { + if (isNullOrUndefined(recurrenceProperties.interval)) { + throw createNullArgumentError(IntervalKey); + } + + if (typeof recurrenceProperties.interval !== "number") { + throw createArgumentTypeError(IntervalKey, typeof recurrenceProperties.interval, "number"); + } + + if (recurrenceProperties.interval <= 0) { + throw createArgumentError(IntervalKey); + } +} + +function throwOnInvalidDailyRecurrence(recurrenceProperties) { + throwOnInvalidRecurrenceInterval(recurrenceProperties); +} + +function throwOnInvalidWeeklyRecurrence(recurrenceProperties) { + throwOnInvalidRecurrenceInterval(recurrenceProperties); + + if (isNullOrUndefined(recurrenceProperties.days)) { + throw createArgumentTypeError(DaysKey); + } + + if (!Array.isArray(recurrenceProperties.days)) { + throw createArgumentTypeError(DaysKey); + } + + throwOnInvalidDaysArray(recurrenceProperties.days); + + if (!isNullOrUndefined(recurrenceProperties.firstDayOfWeek)) { + if (typeof recurrenceProperties.firstDayOfWeek !== "string") { + throw createArgumentTypeError(FirstDayOfWeekKey); + } + + if (!verifyDays(recurrenceProperties.firstDayOfWeek, false)) { + throw createArgumentError(FirstDayOfWeekKey); + } + } +} + +function throwOnInvalidDaysArray(daysArray) { + for (var i = 0; i < daysArray.length; i++) { + if (!verifyDays(daysArray[i], false)) { + throw createArgumentError(DaysKey); + } + } +} + +function verifyDays(dayEnum, checkGroupedDays) { + var fRegularDay = dayEnum === MailboxEnums.Days.Mon || dayEnum === MailboxEnums.Days.Tue || dayEnum === MailboxEnums.Days.Wed || dayEnum === MailboxEnums.Days.Thu || dayEnum === MailboxEnums.Days.Fri || dayEnum === MailboxEnums.Days.Sat || dayEnum === MailboxEnums.Days.Sun; + + if (checkGroupedDays) { + var fGroupedDay = dayEnum === MailboxEnums.Days.WeekendDay || dayEnum === MailboxEnums.Days.Weekday || dayEnum === MailboxEnums.Days.Day; + return fGroupedDay || fRegularDay; + } else { + return fRegularDay; + } +} + +function throwOnInvalidMonthlyRecurrence(recurrenceProperties) { + if (isNullOrUndefined(recurrenceProperties.interval)) { + throw createNullArgumentError(IntervalKey); + } + + if (typeof recurrenceProperties.interval !== "number") { + throw createArgumentTypeError(IntervalKey, typeof recurrenceProperties.interval, "number"); + } + + if (!isNullOrUndefined(recurrenceProperties.dayOfMonth)) { + if (typeof recurrenceProperties.dayOfMonth !== "number") { + throw createArgumentTypeError(DayOfMonthKey, typeof recurrenceProperties.dayOfMonth, "number"); + } + + throwOnInvalidDayOfMonth(recurrenceProperties.dayOfMonth); + } else if (!isNullOrUndefined(recurrenceProperties.dayOfWeek) && !isNullOrUndefined(recurrenceProperties.weekNumber)) { + if (typeof recurrenceProperties.dayOfWeek !== "string") { + throw createArgumentTypeError(DayOfWeekKey, typeof recurrenceProperties.dayOfWeek, "string"); + } + + if (!verifyDays(recurrenceProperties.dayOfWeek, true)) { + throw createArgumentError(DayOfWeekKey); + } + + if (typeof recurrenceProperties.weekNumber !== "string") { + throw createArgumentTypeError(WeekNumberKey, typeof recurrenceProperties.weekNumber, "string"); + } + + throwOnInvalidWeekNumber(recurrenceProperties.weekNumber); + } else { + throw createArgumentError(undefined, getString("l_Recurrence_Error_Properties_Invalid_Text")); + } +} + +function throwOnInvalidWeekNumber(weekNumber) { + if (weekNumber !== MailboxEnums.WeekNumber.First && weekNumber !== MailboxEnums.WeekNumber.Second && weekNumber !== MailboxEnums.WeekNumber.Third && weekNumber !== MailboxEnums.WeekNumber.Fourth && weekNumber !== MailboxEnums.WeekNumber.Last) { + throw createArgumentError(WeekNumberKey); + } +} + +function throwOnInvalidDayOfMonth(iDayOfMonth) { + if (iDayOfMonth < 1 || iDayOfMonth > 31) { + throw createArgumentError(DayOfMonthKey); + } +} + +function throwOnInvalidYearlyRecurrence(recurrenceProperties) { + if (isNullOrUndefined(recurrenceProperties.interval)) { + throw createNullArgumentError(IntervalKey); + } + + if (typeof recurrenceProperties.interval !== "number") { + throw createArgumentTypeError(IntervalKey, typeof recurrenceProperties.interval, "number"); + } + + if (isNullOrUndefined(recurrenceProperties.month)) { + throw createNullArgumentError(MonthKey); + } + + if (typeof recurrenceProperties.month !== "string") { + throw createArgumentTypeError(MonthKey, typeof recurrenceProperties.month, "string"); + } + + throwOnInvalidMonth(recurrenceProperties.month); + + if (!isNullOrUndefined(recurrenceProperties.dayOfMonth)) { + if (typeof recurrenceProperties.dayOfMonth !== "number") { + throw createArgumentTypeError(DayOfMonthKey, typeof recurrenceProperties.dayOfMonth, "number"); + } + + throwOnInvalidDayOfMonth(recurrenceProperties.dayOfMonth); + } else if (!isNullOrUndefined(recurrenceProperties.weekNumber) && !isNullOrUndefined(recurrenceProperties.dayOfWeek)) { + if (typeof recurrenceProperties.dayOfWeek !== "string") { + throw createArgumentTypeError(DayOfWeekKey, typeof recurrenceProperties.dayOfWeek, "string"); + } + + if (!verifyDays(recurrenceProperties.dayOfWeek, true)) { + throw createArgumentError(DayOfWeekKey); + } + + if (typeof recurrenceProperties.weekNumber !== "string") { + throw createArgumentTypeError(WeekNumberKey, typeof recurrenceProperties.weekNumber, "string"); + } + + throwOnInvalidWeekNumber(recurrenceProperties.weekNumber); + } else { + throw createArgumentError(undefined, getString("l_Recurrence_Error_Properties_Invalid_Text")); + } +} + +function throwOnInvalidMonth(month) { + if (month !== MailboxEnums.Month.Jan && month !== MailboxEnums.Month.Feb && month !== MailboxEnums.Month.Mar && month !== MailboxEnums.Month.Apr && month !== MailboxEnums.Month.May && month !== MailboxEnums.Month.Jun && month !== MailboxEnums.Month.Jul && month !== MailboxEnums.Month.Aug && month !== MailboxEnums.Month.Sep && month !== MailboxEnums.Month.Oct && month !== MailboxEnums.Month.Nov && month !== MailboxEnums.Month.Dec) { + throw createArgumentError(MonthKey); + } +} +// CONCATENATED MODULE: ./src/methods/setRecurrence.ts + + + + + + + + + +function setRecurrence(recurrencePattern) { + var args = []; + + for (var _i = 1; _i < arguments.length; _i++) { + args[_i - 1] = arguments[_i]; + } + + checkPermissionsAndThrow(2, "recurrenceProperties.setAsync"); + var seriesId = getAppointmentCompose().seriesId; + + if (!isNullOrUndefined(seriesId) && seriesId.length > 0) { + throw createArgumentError(undefined, getString("l_Recurrence_Error_Instance_SetAsync_Text")); + } + + validateRecurrenceObject(recurrencePattern); + var commonParameters = parseCommonArgs(args, false, false); + var recurrenceData = convertSeriesTime(recurrencePattern); + var parameters = { + recurrenceData: recurrenceData + }; + standardInvokeHostMethod(104, commonParameters.asyncContext, commonParameters.callback, parameters, undefined); +} + +function convertSeriesTime(recurrencePattern) { + if (recurrencePattern !== null && recurrencePattern.seriesTime !== null) { + if (recurrencePattern.seriesTime instanceof SeriesTime_SeriesTime) { + var recurrencePatternCopy = { + recurrenceProperties: recurrencePattern.recurrenceProperties, + recurrenceTimeZone: recurrencePattern.recurrenceTimeZone, + recurrenceType: recurrencePattern.recurrenceType, + seriesTimeJson: recurrencePattern.seriesTime.exportToSeriesTimeJson() + }; + return recurrencePatternCopy; + } + } + + return recurrencePattern; +} +// CONCATENATED MODULE: ./src/api/getRecurrenceSurface.ts + + + +function getRecurrenceSurface(isCompose) { + var recurrence = objectDefine({}, { + getAsync: getRecurrence + }); + + if (isCompose) { + objectDefine(recurrence, { + setAsync: setRecurrence + }); + } + + return recurrence; +} +// CONCATENATED MODULE: ./src/methods/getAllDayEvent.ts + + + + +function getAllDayEvent() { + var args = []; + + for (var _i = 0; _i < arguments.length; _i++) { + args[_i] = arguments[_i]; + } + + checkPermissionsAndThrow(1, "isAllDayEvent.getAsync"); + var commonParameters = parseCommonArgs(args, true, false); + checkFeatureEnabledAndThrow(Features.calendarItems, "isAllDayEvent.getAsync"); + standardInvokeHostMethod(169, commonParameters.asyncContext, commonParameters.callback, undefined, undefined); +} +// CONCATENATED MODULE: ./src/methods/setAllDayEvent.ts + + + + + + +function setAllDayEvent(isAllDayEvent) { + var args = []; + + for (var _i = 1; _i < arguments.length; _i++) { + args[_i - 1] = arguments[_i]; + } + + checkPermissionsAndThrow(2, "isAllDayEvent.setAsync"); + var commonParameters = parseCommonArgs(args, true, false); + var parameters = { + isAllDayEvent: isAllDayEvent + }; + checkFeatureEnabledAndThrow(Features.calendarItems, "isAllDayEvent.setAsync"); + setAllDayEvent_validateParameters(parameters); + standardInvokeHostMethod(170, commonParameters.asyncContext, commonParameters.callback, parameters, undefined); +} + +function setAllDayEvent_validateParameters(parameters) { + if (isNullOrUndefined(parameters.isAllDayEvent)) { + throw createNullArgumentError("isAllDayEvent"); + } + + if (typeof parameters.isAllDayEvent !== "boolean") { + throw createArgumentTypeError("isAllDayEvent", typeof parameters.isAllDayEvent, "boolean"); + } +} +// CONCATENATED MODULE: ./src/api/getAllDayEventSurface.ts + + + +function getAllDayEventSurface() { + return objectDefine({}, { + getAsync: getAllDayEvent, + setAsync: setAllDayEvent + }); +} +// CONCATENATED MODULE: ./src/methods/setSensitivity.ts + + + + + + + +function setSensitivity(sensitivity) { + var args = []; + + for (var _i = 1; _i < arguments.length; _i++) { + args[_i - 1] = arguments[_i]; + } + + checkPermissionsAndThrow(2, "sensitivity.setAsync"); + var commonParameters = parseCommonArgs(args, true, false); + var parameters = { + sensitivity: sensitivity + }; + checkFeatureEnabledAndThrow(Features.calendarItems, "sensitivity.setAsync"); + setSensitivity_validateParameters(parameters); + standardInvokeHostMethod(172, commonParameters.asyncContext, commonParameters.callback, parameters, undefined); +} + +function setSensitivity_validateParameters(parameters) { + validateStringParam("sensitivity", parameters.sensitivity); + throwOnInvalidSensitivityType(parameters.sensitivity); +} + +function throwOnInvalidSensitivityType(sensitivity) { + if (sensitivity !== MailboxEnums.AppointmentSensitivityType.Normal && sensitivity !== MailboxEnums.AppointmentSensitivityType.Personal && sensitivity !== MailboxEnums.AppointmentSensitivityType.Private && sensitivity !== MailboxEnums.AppointmentSensitivityType.Confidential) { + throw createArgumentError("sensitivity"); + } +} +// CONCATENATED MODULE: ./src/methods/getSensitivity.ts + + + + +function getSensitivity() { + var args = []; + + for (var _i = 0; _i < arguments.length; _i++) { + args[_i] = arguments[_i]; + } + + checkPermissionsAndThrow(1, "sensitivity.getAsync"); + var commonParameters = parseCommonArgs(args, true, false); + checkFeatureEnabledAndThrow(Features.calendarItems, "sensitivity.getAsync"); + standardInvokeHostMethod(171, commonParameters.asyncContext, commonParameters.callback, undefined, undefined); +} +// CONCATENATED MODULE: ./src/api/getSensitivitySurface.ts + + + +function getSensitivitySurface() { + return objectDefine({}, { + getAsync: getSensitivity, + setAsync: setSensitivity + }); +} +// CONCATENATED MODULE: ./src/api/getAppointmentCompose.ts + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +function getAppointmentCompose() { + var appointmentCompose = objectDefine({}, { + body: getBodySurface(true), + categories: getCategoriesSurface(), + end: getTimeSurface("end"), + enhancedLocation: getEnhancedLocationsSurface(true), + itemType: "appointment", + location: getLocationSurface(), + notificationMessages: getNotificationMessageSurface(), + optionalAttendees: getRecipientsSurface("optionalAttendees"), + organizer: getFromSurface("organizer"), + recurrence: getRecurrenceSurface(true), + requiredAttendees: getRecipientsSurface("requiredAttendees"), + seriesId: getInitialDataProp("seriesId"), + start: getTimeSurface("start"), + subject: getSubjectSurface(), + addFileAttachmentAsync: addFileAttachment, + addFileAttachmentFromBase64Async: addBase64FileAttachment, + addItemAttachmentAsync: addItemAttachment, + close: close_close, + getAttachmentsAsync: getAttachments_getAttachments, + getAttachmentContentAsync: getAttachmentContent, + getInitializationContextAsync: getInitializationContext, + getItemIdAsync: getItemId, + getSelectedDataAsync: getSelectedData, + loadCustomPropertiesAsync: loadCustomProperties, + removeAttachmentAsync: removeAttachment, + saveAsync: save, + setSelectedDataAsync: setSelectedData(29), + isAllDayEvent: getAllDayEventSurface(), + sensitivity: getSensitivitySurface(), + isClientSignatureEnabledAsync: isClientSignatureEnabled, + disableClientSignatureAsync: disableClientSignature, + sessionData: getSessionDataSurface() + }); + return appointmentCompose; +} +// CONCATENATED MODULE: ./src/utils/addEventSupport.ts +var addEventSupport_OSF = __webpack_require__(0); + +var addEventSupport_Microsoft = __webpack_require__(1); + +var addEventSupport = function addEventSupport(target) {}; +// CONCATENATED MODULE: ./src/methods/registerConsent.ts + + + +var ConsentStateType; + +(function (ConsentStateType) { + ConsentStateType[ConsentStateType["NotResponded"] = 0] = "NotResponded"; + ConsentStateType[ConsentStateType["NotConsented"] = 1] = "NotConsented"; + ConsentStateType[ConsentStateType["Consented"] = 2] = "Consented"; +})(ConsentStateType || (ConsentStateType = {})); + +function registerConsent(consentState) { + var parameters = { + consentState: consentState, + extensionId: getInitialDataProp("extensionId") + }; + registerConsent_validateParameters(consentState); + standardInvokeHostMethod(40, undefined, undefined, parameters, undefined); +} + +function registerConsent_validateParameters(consentState) { + if (consentState !== ConsentStateType.Consented && consentState !== ConsentStateType.NotConsented && consentState !== ConsentStateType.NotResponded) { + throw createArgumentOutOfRange("consentState"); + } +} +// CONCATENATED MODULE: ./src/methods/navigateToModule.ts + + + + + +function navigateToModule(moduleName) { + var args = []; + + for (var _i = 1; _i < arguments.length; _i++) { + args[_i - 1] = arguments[_i]; + } + + var commonParameters = parseCommonArgs(args, false, false); + var parameters = { + module: moduleName + }; + navigateToModule_validateParameters(moduleName); + + if (moduleName === MailboxEnums.ModuleType.Addins) { + if (!!commonParameters.options && !!commonParameters.options.queryString) { + parameters.queryString = commonParameters.options.queryString; + } else { + parameters.queryString = ""; + } + } + + standardInvokeHostMethod(45, commonParameters.asyncContext, commonParameters.callback, parameters, undefined); +} + +function navigateToModule_validateParameters(moduleName) { + if (isNullOrUndefined(moduleName)) { + throw createNullArgumentError("module"); + } + + if (moduleName === "") { + throw createArgumentError("module"); + } + + if (moduleName !== MailboxEnums.ModuleType.Addins) { + throw createArgumentError("module"); + } +} +// CONCATENATED MODULE: ./src/methods/recordDataPoint.ts + + + +function recordDataPoint(data) { + if (isNullOrUndefined(data)) { + throw createNullArgumentError("data"); + } + + standardInvokeHostMethod(402, undefined, undefined, data, undefined); +} +// CONCATENATED MODULE: ./src/methods/recordTrace.ts + + + +function recordTrace(data) { + if (isNullOrUndefined(data)) { + throw createNullArgumentError("data"); + } + + standardInvokeHostMethod(401, undefined, undefined, data, undefined); +} +// CONCATENATED MODULE: ./src/methods/trackCtq.ts + + + +function trackCtq(data) { + if (isNullOrUndefined(data)) { + throw createNullArgumentError("data"); + } + + standardInvokeHostMethod(400, undefined, undefined, data, undefined); +} +// CONCATENATED MODULE: ./src/methods/windowOpenOverrideHandler.ts + +function windowOpenOverrideHandler(url, target, features, replace) { + standardInvokeHostMethod(403, undefined, undefined, { + launchUrl: url + }, undefined); + return window; +} +// CONCATENATED MODULE: ./src/methods/logTelemetry.ts + + + +function logTelemetry(data) { + if (isNullOrUndefined(data)) { + throw createNullArgumentError("data"); + } + + standardInvokeHostMethod(163, undefined, undefined, { + telemetryData: data + }, undefined); +} +// CONCATENATED MODULE: ./src/utils/convertToLocalClientTime.ts +var __assign = undefined && undefined.__assign || function () { + __assign = Object.assign || function (t) { + for (var s, i = 1, n = arguments.length; i < n; i++) { + s = arguments[i]; + + for (var p in s) { + if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p]; + } + } + + return t; + }; + + return __assign.apply(this, arguments); +}; + + + + + + + +function convertToLocalClientTime(timeValue) { + if (!isDateObject(timeValue)) { + throw createArgumentError("timeValue"); + } + + var date = new Date(timeValue.getTime()); + var offset = date.getTimezoneOffset() * -1; + + if (!isNullOrUndefined(getInitialDataProp("timeZoneOffsets"))) { + date.setUTCMinutes(date.getUTCMinutes() - offset); + offset = findOffset(date); + date.setUTCMinutes(date.getUTCMinutes() + offset); + } + + var retValue = __assign({ + timezoneOffset: offset + }, dateToDictionary(date)); + + return retValue; +} +// CONCATENATED MODULE: ./src/methods/displayPersonaCardAsync.ts + + + + +function displayPersonaCardAsync(ewsIdOrEmail) { + var args = []; + + for (var _i = 1; _i < arguments.length; _i++) { + args[_i - 1] = arguments[_i]; + } + + var commonParameters = parseCommonArgs(args, false, false); + var parameters = { + ewsIdOrEmail: ewsIdOrEmail + }; + displayPersonaCardAsync_validateParameters(parameters); + standardInvokeHostMethod(43, commonParameters.asyncContext, commonParameters.callback, { + ewsIdOrEmail: ewsIdOrEmail.trim() + }, undefined); +} + +function displayPersonaCardAsync_validateParameters(parameters) { + if (!isNullOrUndefined(parameters.ewsIdOrEmail)) { + displayPersonaCardAsync_throwOnInvalidItemId(parameters.ewsIdOrEmail); + + if (parameters.ewsIdOrEmail === "") { + throw createArgumentError("ewsIdOrEmail", "ewsIdOrEmail cannot be empty."); + } + } else { + throw createNullArgumentError("ewsIdOrEmail"); + } +} + +function displayPersonaCardAsync_throwOnInvalidItemId(ewsIdOrEmail) { + if (!(typeof ewsIdOrEmail === "string")) { + throw createArgumentError("ewsIdOrEmail"); + } +} +// CONCATENATED MODULE: ./src/methods/getSharedProperties.ts + + + +function getSharedProperties() { + var args = []; + + for (var _i = 0; _i < arguments.length; _i++) { + args[_i] = arguments[_i]; + } + + checkPermissionsAndThrow(1, "item.getSharedPropertiesAsync"); + var commonParameters = parseCommonArgs(args, true, false); + standardInvokeHostMethod(108, commonParameters.asyncContext, commonParameters.callback, undefined, undefined); +} +// CONCATENATED MODULE: ./src/utils/addSharedPropertiesSupport.ts + + + + + +var addSharedPropertiesSupport_addSharedPropertiesSupport = function addSharedPropertiesSupport(target) { + if (target && getInitialDataProp("isFromSharedFolder") && getHostItemType_getHostItemType() !== HostItemType.ItemLess) { + objectDefine(target, { + getSharedPropertiesAsync: getSharedProperties + }); + } +}; +// CONCATENATED MODULE: ./src/api/prepareApiSurface.ts + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +var prepareApiSurface_OSF = __webpack_require__(0); + +var prepareApiSurface_createMailboxSurface = function createMailboxSurface(target) { + objectDefine(target, { + ewsUrl: getInitialDataProp("ewsUrl"), + restUrl: getInitialDataProp("restUrl"), + displayAppointmentForm: displayAppointmentForm, + displayAppointmentFormAsync: displayAppointmentFormAsync, + displayMessageForm: displayMessageForm, + displayMessageFormAsync: displayMessageFormAsync, + displayPersonaCardAsync: displayPersonaCardAsync, + getCallbackTokenAsync: getCallbackToken, + getUserIdentityTokenAsync: getUserIdentityToken, + logTelemetry: logTelemetry, + makeEwsRequestAsync: makeEwsRequest, + masterCategories: getMasterCategoriesSurface(), + navigateToModuleAsync: navigateToModule, + diagnostics: getDiagnosticsSurface(), + userProfile: getUserProfileSurface(), + convertToEwsId: convertToEwsId, + convertToLocalClientTime: convertToLocalClientTime, + convertToRestId: convertToRestId, + convertToUtcClientTime: convertToUtcClientTime, + RegisterConsentAsync: registerConsent, + GetIsRead: function GetIsRead() { + return getInitialDataProp("isRead"); + }, + GetEndPointUrl: function GetEndPointUrl() { + return getInitialDataProp("endNodeUrl"); + }, + GetConsentMetaData: function GetConsentMetaData() { + return getInitialDataProp("consentMetadata"); + }, + GetMarketplaceContentMarket: function GetMarketplaceContentMarket() { + return getInitialDataProp("marketplaceContentMarket"); + }, + GetMarketplaceAssetId: function GetMarketplaceAssetId() { + return getInitialDataProp("marketplaceAssetId"); + }, + GetExtensionId: function GetExtensionId() { + return getInitialDataProp("extensionId"); + }, + CloseApp: closeApp, + recordDataPoint: recordDataPoint, + recordTrace: recordTrace, + trackCtq: trackCtq + }); + + if (getHostItemType_getHostItemType() !== HostItemType.MessageCompose && getHostItemType_getHostItemType() !== HostItemType.AppointmentCompose) { + objectDefine(target, { + displayNewAppointmentForm: displayNewAppointmentForm, + displayNewMessageForm: displayNewMessageForm, + displayNewAppointmentFormAsync: displayNewAppointmentFormAsync, + displayNewMessageFormAsync: displayNewMessageFormAsync + }); + } + + if (getAppName() === prepareApiSurface_OSF.AppName.OutlookWebApp && getInitialDataProp("openWindowOpen")) { + window.open = windowOpenOverrideHandler; + } + + return target; +}; +var prepareApiSurface_getItem = function getItem() { + var item = undefined; + + switch (getHostItemType_getHostItemType()) { + case HostItemType.Message: + item = getMessageRead(); + break; + + case HostItemType.MessageCompose: + item = getMessageCompose(); + break; + + case HostItemType.Appointment: + item = getAppointmentRead(); + break; + + case HostItemType.AppointmentCompose: + item = getAppointmentCompose(); + break; + + case HostItemType.MeetingRequest: + item = getMessageRead(); + break; + + default: + return undefined; + } + + addEventSupport(item); + addSharedPropertiesSupport_addSharedPropertiesSupport(item); + return item; +}; +// CONCATENATED MODULE: ./src/utils/isOutlook16.ts + +var isOutlook16_isOutlook16OrGreater = function isOutlook16OrGreater(hostVersion) { + var endIndex = 0; + var majorVersionNumber = 0; + + if (!isNullOrUndefined(hostVersion)) { + endIndex = hostVersion.indexOf("."); + majorVersionNumber = parseInt(hostVersion.substring(0, endIndex)); + } + + return majorVersionNumber >= 16; +}; +// CONCATENATED MODULE: ./src/utils/isApiVersionSupported.ts +var isApiVersionSupported = function isApiVersionSupported(requirementSet, officeAppContext) { + var apiSupported = false; + + try { + var requirementDict = JSON.parse(officeAppContext.get_requirementMatrix()); + var hostApiVersion = requirementDict["Mailbox"]; + var hostApiVersionParts = hostApiVersion.split("."); + var requirementSetParts = requirementSet.split("."); + + if (parseInt(hostApiVersionParts[0]) > parseInt(requirementSetParts[0]) || parseInt(hostApiVersionParts[0]) === parseInt(requirementSetParts[0]) && parseInt(hostApiVersionParts[1]) >= parseInt(requirementSetParts[1])) { + apiSupported = true; + } + } catch (_a) {} + + return apiSupported; +}; +// CONCATENATED MODULE: ./src/api/OutlookAppOm.ts + + + + + + + + +var OutlookAppOm_OSF = __webpack_require__(0); + +var appInstance; +var whenStringsFinish; +var getInitialDataProp = function getInitialDataProp(key) { + return appInstance && appInstance.getInitialDataProp(key); +}; +var getIsNoItemContextWebExt = function getIsNoItemContextWebExt() { + return !appInstance || !appInstance.item; +}; +var getAppName = function getAppName() { + return appInstance && appInstance.getAppName(); +}; + +var OutlookAppOm_OutlookAppOm = function () { + function OutlookAppOm(appContext, targetWindow, appReadyCallback) { + var _this = this; + + this.displayName = "mailbox"; + + this.stringLoadedCallback = function () { + if (!!_this.appReadyCallback) { + if (!_this.officeAppContext.get_isDialog()) { + standardInvokeHostMethod_invokeHostMethod(1, undefined, _this.onInitialDataResponse); + } else { + setTimeout(function () { + return _this.appReadyCallback(); + }, 0); + } + } + }; + + this.initialize = function (data) { + if (data === null || data === undefined) { + recreateAdditionalGlobalParametersSingleton(true); + _this.initialData = null; + _this.item = null; + } else { + _this.initialData = data; + _this.initialData.permissionLevel = calculatePermissionLevel(); + _this.item = prepareApiSurface_getItem(); + var supportsAdditionalParameters = false; + supportsAdditionalParameters = getAppName() !== OutlookAppOm_OSF.AppName.Outlook || isOutlook16_isOutlook16OrGreater(getInitialDataProp("hostVersion")) || isApiVersionSupported("1.5", _this.officeAppContext); + recreateAdditionalGlobalParametersSingleton(supportsAdditionalParameters); + + if (typeof data.itemNumber !== "undefined") { + getAdditionalGlobalParametersSingleton().setCurrentItemNumber(data.itemNumber); + } + } + }; + + this.onInitialDataResponse = function (resultCode, data) { + if (!!resultCode && resultCode !== InvokeResultCode.noError) { + return; + } + + _this.initialize(data); + + prepareApiSurface_createMailboxSurface(_this); + setTimeout(function () { + return _this.appReadyCallback(); + }, 0); + }; + + this.officeAppContext = appContext; + this.targetWindow = window; + this.appReadyCallback = appReadyCallback; + appInstance = this; + loadLocalizedScript(this.stringLoadedCallback); + } + + OutlookAppOm.prototype.getAppName = function () { + var retVal = -1; + retVal = this.officeAppContext.get_appName(); + return retVal; + }; + + OutlookAppOm.prototype.getInitialDataProp = function (key) { + return this.initialData && this.initialData[key]; + }; + + OutlookAppOm.prototype.setCurrentItemNumber = function (newItemNumber) { + getAdditionalGlobalParametersSingleton().setCurrentItemNumber(newItemNumber); + }; + + OutlookAppOm.addAdditionalArgs = function (dispid, hostCallingArgs) { + return hostCallingArgs; + }; + + OutlookAppOm.shouldRunInitialDataResponse = function () { + return true; + }; + + return OutlookAppOm; +}(); + + + +var calculatePermissionLevel = function calculatePermissionLevel() { + var HostReadItem = 1; + var HostReadWriteMailbox = 2; + var HostReadWriteItem = 3; + var permissionLevelFromHost = getInitialDataProp("permissionLevel"); + + if (permissionLevelFromHost === undefined) { + return 0; + } + + switch (permissionLevelFromHost) { + case HostReadItem: + return 1; + + case HostReadWriteItem: + return 2; + + case HostReadWriteMailbox: + return 3; + + default: + return 0; + } +}; +// CONCATENATED MODULE: ./src/methods/saveSettingsRequest.ts + + + + + +var saveSettingsRequest_OSF = __webpack_require__(0); + +var settingsMaxNumberOfCharacters = 32 * 1024; +function saveSettingsRequest(data) { + var args = []; + + for (var _i = 1; _i < arguments.length; _i++) { + args[_i - 1] = arguments[_i]; + } + + var commonParameters = parseCommonArgs(args, false, false); + var serializedSettings = saveSettingsRequest_OSF.DDA.SettingsManager.serializeSettings(data); + + if (JSON.stringify(serializedSettings).length > settingsMaxNumberOfCharacters) { + var asyncResult_1 = createAsyncResult(undefined, saveSettingsRequest_OSF.DDA.AsyncResultEnum.ErrorCode.Failed, 9019, commonParameters.asyncContext, ""); + + if (!!commonParameters.callback) { + setTimeout(function () { + if (!!commonParameters.callback) commonParameters.callback(asyncResult_1); + }, 0); + } + + return; + } + + if (saveSettingsRequest_OSF.AppName.OutlookWebApp === getAppName()) { + saveSettingsForOwa(commonParameters, serializedSettings); + } else { + saveSettingsForOutlookDesktop(commonParameters, serializedSettings); + } +} + +function saveSettingsForOwa(commonParameters, serializedSettings) { + standardInvokeHostMethod(404, commonParameters.asyncContext, commonParameters.callback, [serializedSettings], undefined); +} + +function saveSettingsForOutlookDesktop(commonParameters, serializedSettings) { + var detailedErrorCode = -1; + var storedException = null; + + try { + var jsonSettings = JSON.stringify(serializedSettings); + var settingsObjectToSave = {}; + settingsObjectToSave.SettingsKey = jsonSettings; + saveSettingsRequest_OSF.DDA.ClientSettingsManager.write(settingsObjectToSave); + } catch (ex) { + storedException = ex; + } + + var asyncResult = undefined; + + if (storedException != null) { + detailedErrorCode = 9019; + asyncResult = createAsyncResult(undefined, saveSettingsRequest_OSF.DDA.AsyncResultEnum.ErrorCode.Failed, detailedErrorCode, commonParameters.asyncContext, storedException.Message); + } else { + detailedErrorCode = 0; + asyncResult = createAsyncResult(undefined, saveSettingsRequest_OSF.DDA.AsyncResultEnum.ErrorCode.Success, detailedErrorCode, commonParameters.asyncContext); + } + + if (!!commonParameters.callback) { + commonParameters.callback(asyncResult); + } +} +// CONCATENATED MODULE: ./src/api/Settings.ts +var Settings_spreadArrays = undefined && undefined.__spreadArrays || function () { + for (var s = 0, i = 0, il = arguments.length; i < il; i++) { + s += arguments[i].length; + } + + for (var r = Array(s), k = 0, i = 0; i < il; i++) { + for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++) { + r[k] = a[j]; + } + } + + return r; +}; + + + + +var Settings_OSF = __webpack_require__(0); + +var Settings_Settings = function () { + function Settings(deserializedData) { + this.rawData = deserializedData; + this.settingsData = null; + } + + Settings.prototype.getSettingsData = function () { + if (this.settingsData == null) { + this.settingsData = this.convertFromRawSettings(this.rawData); + this.rawData = null; + } + + return this.settingsData; + }; + + Settings.prototype.get = function (key) { + return this.getSettingsData()[key]; + }; + + Settings.prototype.set = function (key, value) { + this.getSettingsData()[key] = value; + }; + + Settings.prototype.remove = function (key) { + delete this.getSettingsData()[key]; + }; + + Settings.prototype.saveAsync = function () { + var args = []; + + for (var _i = 0; _i < arguments.length; _i++) { + args[_i] = arguments[_i]; + } + + saveSettingsRequest.apply(void 0, Settings_spreadArrays([this.getSettingsData()], args)); + }; + + Settings.prototype.convertFromRawSettings = function (rawSettings) { + if (rawSettings == null) { + return {}; + } + + if (getAppName() !== Settings_OSF.AppName.OutlookWebApp) { + var outlookSettings = rawSettings.SettingsKey; + + if (!!outlookSettings) { + return Settings_OSF.DDA.SettingsManager.deserializeSettings(outlookSettings); + } + } + + return rawSettings; + }; + + return Settings; +}(); + + +// CONCATENATED MODULE: ./src/api/Intellisense.ts + + + +var Intellisense = { + toItemRead: function toItemRead(item) { + var hostItemtype = getHostItemType_getHostItemType(); + + if (hostItemtype === HostItemType.Message || hostItemtype === HostItemType.Appointment || hostItemtype === HostItemType.MeetingRequest) { + return item; + } + + throw createArgumentTypeError(); + }, + toItemCompose: function toItemCompose(item) { + var hostItemtype = getHostItemType_getHostItemType(); + + if (hostItemtype === HostItemType.MessageCompose || hostItemtype === HostItemType.AppointmentCompose) { + return item; + } + + throw createArgumentTypeError(); + }, + toMessage: function toMessage(item) { + return Intellisense.toMessageRead(item); + }, + toMessageRead: function toMessageRead(item) { + if (getHostItemType_getHostItemType() === HostItemType.Message || getHostItemType_getHostItemType() === HostItemType.MeetingRequest) { + return item; + } + + throw createArgumentTypeError(); + }, + toMessageCompose: function toMessageCompose(item) { + if (getHostItemType_getHostItemType() === HostItemType.MessageCompose) { + return item; + } + + throw createArgumentTypeError(); + }, + toMeetingRequest: function toMeetingRequest(item) { + if (getHostItemType_getHostItemType() === HostItemType.MeetingRequest) { + return item; + } + + throw createArgumentTypeError(); + }, + toAppointment: function toAppointment(item) { + if (getHostItemType_getHostItemType() === HostItemType.Appointment) { + return item; + } + + throw createArgumentTypeError(); + }, + toAppointmentRead: function toAppointmentRead(item) { + if (getHostItemType_getHostItemType() === HostItemType.Appointment) { + return item; + } + + throw createArgumentTypeError(); + }, + toAppointmentCompose: function toAppointmentCompose(item) { + if (getHostItemType_getHostItemType() === HostItemType.AppointmentCompose) { + return item; + } + + throw createArgumentTypeError(); + } +}; +// CONCATENATED MODULE: ./src/api/OutlookBase.ts + + +var OutlookBase = { + SeriesTimeJsonConverter: function SeriesTimeJsonConverter(rawInput) { + if (rawInput !== null && typeof rawInput === "object") { + if (rawInput.seriesTimeJson !== null) { + var seriesTime = new SeriesTime_SeriesTime(); + seriesTime.importFromSeriesTimeJsonObject(rawInput.seriesTimeJson); + delete rawInput["seriesTimeJson"]; + rawInput.seriesTime = seriesTime; + } + } + + return rawInput; + }, + CreateAttachmentDetails: function CreateAttachmentDetails(data) { + convertAttachmentType(data); + return data; + } +}; +// CONCATENATED MODULE: ./src/index.tsx + + + + + + +OSF = typeof OSF === "object" ? OSF : {}; +OSF.DDA = OSF.DDA || {}; +OSF.DDA.Settings = Settings_Settings; +OSF = typeof OSF === "object" ? OSF : {}; +OSF.DDA = OSF.DDA || {}; +OSF.DDA.OutlookAppOm = OutlookAppOm_OutlookAppOm; +Office = typeof Office === "object" ? Office : {}; +Office.cast = Office.cast || {}; +Office.cast.item = Intellisense; +Microsoft.Office.WebExtension.MailboxEnums = MailboxEnums; +Microsoft.Office.WebExtension.CoercionType = CoercionType; +Microsoft.Office.WebExtension.SeriesTime = SeriesTime_SeriesTime; +Microsoft.Office.WebExtension.OutlookBase = OutlookBase; +/* harmony default export */ var src = __webpack_exports__["default"] = (OutlookAppOm_OutlookAppOm); +var hWindow = window; +hWindow.$h = typeof $h === "object" ? $h : {}; +hWindow.$h.Message = $h.Message || {}; +hWindow.$h.Appointment = $h.Appointment || {}; + +hWindow.$h.Message.isInstanceOfType = function (item) { + return item && item.itemType === "message"; +}; + +hWindow.$h.Appointment.isInstanceOfType = function (item) { + return item && item.itemType === "appointment"; +}; + +/***/ }) +/******/ ])["default"]; +//# sourceMappingURL=outlook.web.js.map + //OSF.DDA.ErrorCodeManager.initializeErrorMessages(Strings.OfficeOM); + // if (appContext.get_appName() == OSF.AppName.Outlook && OSF.DDA.RichApi && OSF.DDA.AsyncMethodNames.ExecuteRichApiRequestAsync) + // { + // OSF.DDA.DispIdHost.addAsyncMethods(OSF.DDA.RichApi, [OSF.DDA.AsyncMethodNames.ExecuteRichApiRequestAsync]); + // OSF.DDA.RichApi.richApiMessageManager = new OfficeExt.RichApiMessageManager(); + // } + // if (appContext.get_appName() == OSF.AppName.OutlookWebApp || appContext.get_appName() == OSF.AppName.OutlookIOS || appContext.get_appName() == OSF.AppName.OutlookAndroid) + // { + // this._settings = this._initializeSettings(appContext, false); + // } + // else if (OSF._OfficeAppFactory.getHostInfo()["hostPlatform"] == "mac" && appContext.get_appName() == OSF.AppName.Outlook) + // { + // this._settings = this.initializeMacSettings(appContext, false); + // } + // else + // { + // this._settings = this._initializeSettings(false); + // } + + + Office.context.mailbox = new OSF.DDA.OutlookAppOm(appContext, this._webAppState.wnd, appReady); + + // if (appContext.get_appName() == OSF.AppName.Outlook || appContext.get_appName() == OSF.AppName.OutlookWebApp || appContext.get_appName() == OSF.AppName.OutlookIOS || appContext.get_appName() == OSF.AppName.OutlookAndroid) + // { + // // Add OSF's eventing mechanism. + // OSF.DDA.DispIdHost.addEventSupport( + // appContext.appOM, + // new OSF.EventDispatch( + // [ + // Microsoft.Office.WebExtension.EventType.ItemChanged, + // Microsoft.Office.WebExtension.EventType.OfficeThemeChanged + // ] + // ) + // ); + // } +};OSFPerformance.hostInitializationEnd = OSFPerformance.now(); + diff --git a/addins/outlook/outlook.js b/addins/outlook/outlook.js new file mode 100644 index 0000000..1beff29 --- /dev/null +++ b/addins/outlook/outlook.js @@ -0,0 +1,19 @@ +/* + * Office JavaScript API library + * + * Copyright (c) Microsoft Corporation. All rights reserved. + * + * Your use of this file is governed by the Microsoft Services Agreement http://go.microsoft.com/fwlink/?LinkId=266419. + * + * This file also contains the following Promise implementation (with a few small modifications): + * * @overview es6-promise - a tiny implementation of Promises/A+. + * * @copyright Copyright (c) 2014 Yehuda Katz, Tom Dale, Stefan Penner and contributors (Conversion to ES6 API by Jake Archibald) + * * @license Licensed under MIT license + * * See https://raw.githubusercontent.com/jakearchibald/es6-promise/master/LICENSE + * * @version 2.3.0 + */ +var OSFPerformance,CustomFunctionMappings,CustomFunctions,Microsoft,Strings;!function(e){function t(){return"undefined"!=typeof performance&&performance.now?performance.now():0}e.now=t,e.officeExecuteStartDate=Date.now(),e.officeExecuteStart=0,e.officeExecuteEnd=0,e.hostInitializationStart=t(),e.hostInitializationEnd=0,e.createOMEnd=0,e.hostSpecificFileName="",e.getAppContextStart=0,e.getAppContextEnd=0,e.getAppContextXdmStart=0,e.getAppContextXdmEnd=0,e.officeOnReady=0}(OSFPerformance||(OSFPerformance={})),function(e){e.definePropertyOnNamespace=function(e,t,n){Object.defineProperty(e,t,{get:function(){return n()},configurable:!0,enumerable:!0})}}(OSF||(OSF={})),function(e){!function(e){var t;function n(){return t||(t=new OSF.Association),t}e.associate=function(){n().associate.apply(n(),arguments)},OSF.definePropertyOnNamespace(e,"_association",n)}(e.actions||(e.actions={}))}(Office||(Office={})),function(e){!function(e){e[e.Select=0]="Select",e[e.UnSelect=1]="UnSelect",e[e.CancelDialog=2]="CancelDialog",e[e.InsertAgave=3]="InsertAgave",e[e.CtrlF6In=4]="CtrlF6In",e[e.CtrlF6Exit=5]="CtrlF6Exit",e[e.CtrlF6ExitShift=6]="CtrlF6ExitShift",e[e.SelectWithError=7]="SelectWithError",e[e.NotifyHostError=8]="NotifyHostError",e[e.RefreshAddinCommands=9]="RefreshAddinCommands",e[e.PageIsReady=10]="PageIsReady",e[e.TabIn=11]="TabIn",e[e.TabInShift=12]="TabInShift",e[e.TabExit=13]="TabExit",e[e.TabExitShift=14]="TabExitShift",e[e.EscExit=15]="EscExit",e[e.F2Exit=16]="F2Exit",e[e.ExitNoFocusable=17]="ExitNoFocusable",e[e.ExitNoFocusableShift=18]="ExitNoFocusableShift",e[e.MouseEnter=19]="MouseEnter",e[e.MouseLeave=20]="MouseLeave",e[e.UpdateTargetUrl=21]="UpdateTargetUrl",e[e.InstallCustomFunctions=22]="InstallCustomFunctions",e[e.SendTelemetryEvent=23]="SendTelemetryEvent",e[e.UninstallCustomFunctions=24]="UninstallCustomFunctions",e[e.SendMessage=25]="SendMessage",e[e.LaunchExtensionComponent=26]="LaunchExtensionComponent",e[e.StopExtensionComponent=27]="StopExtensionComponent",e[e.RestartExtensionComponent=28]="RestartExtensionComponent",e[e.EnableTaskPaneHeaderButton=29]="EnableTaskPaneHeaderButton",e[e.DisableTaskPaneHeaderButton=30]="DisableTaskPaneHeaderButton",e[e.TaskPaneHeaderButtonClicked=31]="TaskPaneHeaderButtonClicked",e[e.RemoveAppCommandsAddin=32]="RemoveAppCommandsAddin",e[e.RefreshRibbonGallery=33]="RefreshRibbonGallery",e[e.GetOriginalControlId=34]="GetOriginalControlId",e[e.OfficeJsReady=35]="OfficeJsReady"}(e.AgaveHostAction||(e.AgaveHostAction={}))}(OSF||(OSF={})),function(e){var t=function(){function t(){var t=this;this._processAppCommandInvocation=function(e){var n=t._verifyManifestCallback(e.callbackName);if(0==n.errorCode){var i=t._constructEventObjectForCallback(e);i?window.setTimeout((function(){n.callback(i)}),0):t._invokeAppCommandCompletedMethod(e.appCommandId,5001,"")}else t._invokeAppCommandCompletedMethod(e.appCommandId,n.errorCode,"")},this._eventDispatch=new e.EventDispatch([{type:e.EventType.AppCommandInvoked,id:39,getTargetId:function(){return""},fromSafeArrayHost:function(t){return{type:e.EventType.AppCommandInvoked,appCommandId:t[0],callbackName:t[1],eventObjStr:t[2]}},fromWebHost:function(t){return{type:e.EventType.AppCommandInvoked,appCommandId:t[0],callbackName:t[1],eventObjStr:t[2]}}}])}return t.prototype.initializeEventHandler=function(t){var n=this;this.addHandlerAsync(e.EventType.AppCommandInvoked,(function(e){n._processAppCommandInvocation(e)}),t)},t.prototype.appCommandInvocationCompletedAsync=function(t,n,i,r){e._OfficeAppFactory.getAsyncMethodExecutor().executeAsync(94,{fromSafeArrayHost:function(e){return e},fromWebHost:function(e){return e},toSafeArrayHost:function(){return[t,n,i]},toWebHost:function(){var e={};return e[0]=t,e[1]=n,e[2]=i,e}},r)},t.prototype.addHandlerAsync=function(t,n,i){e.EventHelper.addEventHandler(t,n,i,this._eventDispatch,!1)},t.prototype._verifyManifestCallback=function(e){var t={callback:null,errorCode:11101};e=e.trim();try{var n=this._getCallbackFunc(e);if("function"!=typeof n)return t}catch(e){return t}return{callback:n,errorCode:0}},t.prototype._getCallbackFuncFromWindow=function(e){for(var t=e.split("."),n=window,i=0;i0)for(var i=0;i0)for(var i=0;i0&&(this._eventHandlers[e]=[],!0)},e.prototype.getEventHandlerCount=function(e){return null!=this._eventHandlers[e]?this._eventHandlers[e].length:-1},e.prototype.getEventInfo=function(e){return this._eventInfos[e]},e.prototype.fireEvent=function(e){if(null==e.type)return!1;var t=e.type;if(t&&this._eventHandlers[t]){for(var n=this._eventHandlers[t],i=0;i0){for(var i=t[0];n.length>0;){i(n.shift())}return!0}}return!1},e.prototype.clearQueuedEvent=function(e){e&&this._eventHandlers[e]&&(this._queuedEventsArgs[e]&&(this._queuedEventsArgs[e]=[]))},e}();e.EventDispatch=t}(OSF||(OSF={})),function(e){var t=function(){function t(){}return t.addEventHandler=function(n,i,r,o,a){var s=0;function c(t){0==t&&(o.hasEventHandler(n,i)||o.addEventHandler(n,i)||(t=5010));e._OfficeAppFactory.getAsyncMethodExecutor().invokeCallback(s,r,t,null)}var l=o.getEventInfo(n);if(l)try{if(a)return void c(0);s=l.id;var u=l.getTargetId();if(0==o.getEventHandlerCount(n))e._OfficeAppFactory.getAsyncMethodExecutor().registerEventAsync(s,l.type,u,(function(e){o.fireEvent(e)}),l,(function(t){c(e.Utility.getErrorCodeFromAsyncResult(t))}));else c(0)}catch(e){t.onException(s,e,r)}else c(5010)},t.removeEventHandler=function(n,i,r,o,a){var s=0;function c(t){e._OfficeAppFactory.getAsyncMethodExecutor().invokeCallback(s,r,t,null)}var l=o.getEventInfo(n);if(l)try{s=l.id;var u=l.getTargetId(),d=0,f=!0;null===i?(f=o.clearEventHandlers(n),d=0):d=(f=o.removeEventHandler(n,i))?0:5003;var p=o.getEventHandlerCount(n);if(f&&0==p)e._OfficeAppFactory.getAsyncMethodExecutor().unregisterEventAsync(s,l.type,u,(function(t){c(e.Utility.getErrorCodeFromAsyncResult(t))}));else c(d)}catch(e){t.onException(s,e,r)}else c(5010)},t.onException=function(t,n,i){if("number"!=typeof n)throw n;e._OfficeAppFactory.getAsyncMethodExecutor().invokeCallback(t,i,n,null)},t}();e.EventHelper=t}(OSF||(OSF={})),function(e){!function(e){e.AppCommandInvoked="appCommandInvoked",e.RichApiMessage="richApiMessage",e.BindingSelectionChanged="bindingSelectionChanged",e.BindingDataChanged="bindingDataChanged",e.DataNodeDeleted="nodeDeleted",e.DataNodeInserted="nodeInserted",e.DataNodeReplaced="nodeReplaced",e.SettingsChanged="settingsChanged"}(e.EventType||(e.EventType={}))}(OSF||(OSF={})),function(e){!function(t){var n=function(){function t(){this.platformRemappings={web:Office.PlatformType.OfficeOnline,winrt:Office.PlatformType.Universal,win32:Office.PlatformType.PC,mac:Office.PlatformType.Mac,ios:Office.PlatformType.iOS,android:Office.PlatformType.Android},this.camelCaseMappings={powerpoint:Office.HostType.PowerPoint,onenote:Office.HostType.OneNote},this.hostInfo=e._OfficeAppFactory.getHostInfo()}return t.prototype.capitalizeFirstLetter=function(e){return e?e[0].toUpperCase()+e.slice(1).toLowerCase():e},t.getInstance=function(){return void 0===t.hostObj&&(t.hostObj=new t),t.hostObj},t.prototype.getPlatform=function(e){if(this.hostInfo.hostPlatform){var t=this.hostInfo.hostPlatform.toLowerCase();if(this.platformRemappings[t])return this.platformRemappings[t]}return null},t.prototype.getHost=function(e){if(this.hostInfo.hostType){var t=this.hostInfo.hostType.toLowerCase();if(this.camelCaseMappings[t])return this.camelCaseMappings[t];if(t=this.capitalizeFirstLetter(this.hostInfo.hostType),Office.HostType[t])return Office.HostType[t]}return null},t.prototype.getDefaultVersion=function(){return this.getHost()?"16.0.0000.0000":null},t.prototype.getDiagnostics=function(e){return{host:this.getHost(),version:e||this.getDefaultVersion(),platform:this.getPlatform()}},t}();t.Host=n}(e.HostName||(e.HostName={}))}(OSF||(OSF={})),function(e){!function(e){e.excel="excel",e.word="word"}(e.HostInfoHostType||(e.HostInfoHostType={}))}(OSF||(OSF={})),function(e){!function(e){e.web="web",e.winrt="winrt",e.win32="win32",e.mac="mac",e.ios="ios",e.android="android"}(e.HostInfoPlatform||(e.HostInfoPlatform={}))}(OSF||(OSF={})),function(e){var t=function(){function t(e,t,n,i){this._hostInfo=e,this._webAppState=t,this._context=n,this._hostFacade=i}return t.prototype.saveAndSetDialogInfo=function(e){},t.prototype.setAgaveHostCommunication=function(){},t.prototype.createClientHostController=function(){return null},t.prototype.createAsyncMethodExecutor=function(){return null},t.prototype.createClientSettingsManager=function(){return null},t.prototype.createSettings=function(t){var n=e.OUtil.getSessionStorage();if(n){var i=n.getItem(e._OfficeAppFactory.getCachedSessionSettingsKey());i?t=JSON.parse(i):(i=JSON.stringify(t),n.setItem(e._OfficeAppFactory.getCachedSessionSettingsKey(),i))}var r=e.OUtil.deserializeSettings(t),o=this.createClientSettingsManager();return new Office.Settings(r,o)},t.prototype.prepareApiSurface=function(t){var n=t.get_featureGates();n&&(Microsoft.Office.WebExtension.FeatureGates=n),e.AppCommandManager.initialize(),OSFPerformance.createOMEnd=OSFPerformance.now()},t.prototype.loadAppSpecificScriptAndCreateOM=function(t,n){throw e.Utility.createNotImplementedException()},t}();e.InitializationHelper=t}(OSF||(OSF={})),function(e){!function(e){e.Inserted="inserted",e.DocumentOpened="documentOpened"}(e.InitializationReason||(e.InitializationReason={}))}(OSF||(OSF={})),OSF||(OSF={}),function(e){!function(t){var n,i=["excel","word","powerpoint","outlook","office-common","office.common"],r=[".js",".debug.js"];function o(){if(!n){for(var e,t,o,a,s=document.getElementsByTagName("script"),c=s.length,l=0;l=0)||0!==a&&"/"!==e.charAt(a-1)&&"\\"!==e.charAt(a-1)||a+t.length!==e.length&&"?"!==e.charAt(a+t.length)?null:{basePath:e.substring(0,a),name:t,isDebugJs:o.indexOf(".debug.js",a)>0})return;n={basePath:"",name:"",isDebugJs:!1}}}t.getHostBundleJsBasePath=function(){return o(),n.basePath},t.getHostBundleJsName=function(){return o(),n.name},t.getOfficeStringJsName=function(){return o(),n.isDebugJs?e.ConstantNames.OfficeStringDebugJS:e.ConstantNames.OfficeStringJS}}(e.LoadScriptHelper||(e.LoadScriptHelper={}))}(OSF||(OSF={})),function(e){!function(e){!function(e){e.FeatureGates={},e.sendTelemetryEvent=function(e){OTel.OTelLogger.sendTelemetryEvent(e)}}(e.WebExtension||(e.WebExtension={}))}(e.Office||(e.Office={}))}(Microsoft||(Microsoft={})),function(e){var t={"ar-sa":!0,"bg-bg":!0,"bn-in":!0,"ca-es":!0,"cs-cz":!0,"da-dk":!0,"de-de":!0,"el-gr":!0,"en-us":!0,"es-es":!0,"et-ee":!0,"eu-es":!0,"fa-ir":!0,"fi-fi":!0,"fr-fr":!0,"gl-es":!0,"he-il":!0,"hi-in":!0,"hr-hr":!0,"hu-hu":!0,"id-id":!0,"it-it":!0,"ja-jp":!0,"kk-kz":!0,"ko-kr":!0,"lo-la":!0,"lt-lt":!0,"lv-lv":!0,"ms-my":!0,"nb-no":!0,"nl-nl":!0,"nn-no":!0,"pl-pl":!0,"pt-br":!0,"pt-pt":!0,"ro-ro":!0,"ru-ru":!0,"sk-sk":!0,"sl-si":!0,"sr-cyrl-cs":!0,"sr-cyrl-rs":!0,"sr-latn-cs":!0,"sr-latn-rs":!0,"sv-se":!0,"th-th":!0,"tr-tr":!0,"uk-ua":!0,"ur-pk":!0,"vi-vn":!0,"zh-cn":!0,"zh-tw":!0},n={ar:"ar-sa",bg:"bg-bg",bn:"bn-in",ca:"ca-es",cs:"cs-cz",da:"da-dk",de:"de-de",el:"el-gr",en:"en-us",es:"es-es",et:"et-ee",eu:"eu-es",fa:"fa-ir",fi:"fi-fi",fr:"fr-fr",gl:"gl-es",he:"he-il",hi:"hi-in",hr:"hr-hr",hu:"hu-hu",id:"id-id",it:"it-it",ja:"ja-jp",kk:"kk-kz",ko:"ko-kr",lo:"lo-la",lt:"lt-lt",lv:"lv-lv",ms:"ms-my",nb:"nb-no",nl:"nl-nl",nn:"nn-no",pl:"pl-pl",pt:"pt-br",ro:"ro-ro",ru:"ru-ru",sk:"sk-sk",sl:"sl-si",sr:"sr-cyrl-cs",sv:"sv-se",th:"th-th",tr:"tr-tr",uk:"uk-ua",ur:"ur-pk",vi:"vi-vn",zh:"zh-cn"};e.getSupportedLocale=function(e,i){if(void 0===i&&(i="en-us"),!e)return i;var r;if((e=e.toLowerCase())in t)r=e;else{var o=e.split("-",1);o&&o.length>0&&(r=n[o[0]])}return r||(r=i),r}}(OSF||(OSF={})),function(e){e.OfficeOM||(e.OfficeOM={})}(Strings||(Strings={})),function(e){!function(t){var n;t.ensureOfficeStringsJs=function(){return n||(n=new Office.Promise((function(n,i){if(e._OfficeAppFactory.getHostInfo().hostLocale){var r=e.LoadScriptHelper.getHostBundleJsBasePath()+e._OfficeAppFactory.getHostInfo().hostLocale+"/"+e.LoadScriptHelper.getOfficeStringJsName();e.OUtil.loadScript(r,(function(r){if(r)n();else{var o=e.LoadScriptHelper.getHostBundleJsBasePath()+e.ConstantNames.DefaultLocale+"/"+e.LoadScriptHelper.getOfficeStringJsName();t.loadScript(o,(function(t){t?n():i(new Error("Cannot load "+e.ConstantNames.OfficeStringJS))}))}}))}else i(new Error("No host locale"))}))),n}}(e.OUtil||(e.OUtil={}))}(OSF||(OSF={})),function(e){!function(t){!function(t){var n;OSF.definePropertyOnNamespace(t,"url",(function(){return OSF._OfficeAppFactory.getOfficeAppContext().get_docUrl()})),OSF.definePropertyOnNamespace(t,"mode",(function(){return 0==OSF._OfficeAppFactory.getOfficeAppContext().get_clientMode()?e.DocumentMode.ReadOnly:e.DocumentMode.ReadWrite})),OSF.definePropertyOnNamespace(t,"settings",(function(){if(!n){var e=OSF._OfficeAppFactory.getOfficeAppContext().get_settingsFunc()();n=OSF._OfficeAppFactory.getInitializationHelper().createSettings(e)}return n})),t.goToByIdAsync=function(t,n,i,r){var o={};o[e.GoToType.Binding]=0,o[e.GoToType.NamedItem]=1,o[e.GoToType.Slide]=2,o[e.GoToType.Index]=3;var a={};a[e.SelectionMode.Default]=0,a[e.SelectionMode.Selected]=1,a[e.SelectionMode.None]=2;var s=o[n],c=0,l=r;"function"==typeof i?l=i:void 0!==i&&(c=a[i]);var u={toSafeArrayHost:function(){return[t,s,c]},fromSafeArrayHost:function(e){return e},toWebHost:function(){return{DdaGoToByIdMethod:{Id:t,GoToType:s,SelectionMode:c}}},fromWebHost:function(e){return e}};OSF._OfficeAppFactory.getAsyncMethodExecutor().executeAsync(82,u,l)}}(t.document||(t.document={}))}(e.context||(e.context={}))}(Office||(Office={})),function(e){!function(e){!function(e){e.sendMessage=function(e){if(OSF._OfficeAppFactory.getHostInfo().hostPlatform!=OSF.HostInfoPlatform.web)throw OSF.Utility.createNotImplementedException();var t=OSF._OfficeAppFactory.getWebAppState();t.clientEndPoint.invoke("ContextActivationManager_notifyHost",null,[t.id,OSF.AgaveHostAction.SendMessage,e])}}(e.messaging||(e.messaging={}))}(e.context||(e.context={}))}(Office||(Office={})),function(e){!function(e){var t,n;OSF.definePropertyOnNamespace(e,"contentLanguage",(function(){return OSF._OfficeAppFactory.getOfficeAppContext().get_dataLocale()})),OSF.definePropertyOnNamespace(e,"displayLanguage",(function(){return OSF._OfficeAppFactory.getOfficeAppContext().get_appUILocale()})),OSF.definePropertyOnNamespace(e,"isDialog",(function(){return OSF._OfficeAppFactory.getHostInfo().isDialog})),OSF.definePropertyOnNamespace(e,"touchEnabled",(function(){return OSF._OfficeAppFactory.getOfficeAppContext().get_touchEnabled()})),OSF.definePropertyOnNamespace(e,"commerceAllowed",(function(){return OSF._OfficeAppFactory.getOfficeAppContext().get_commerceAllowed()})),OSF.definePropertyOnNamespace(e,"host",(function(){return OSF.HostName.Host.getInstance().getHost()})),OSF.definePropertyOnNamespace(e,"platform",(function(){return OSF.HostName.Host.getInstance().getPlatform()})),OSF.definePropertyOnNamespace(e,"diagnostics",(function(){return OSF.HostName.Host.getInstance().getDiagnostics(OSF._OfficeAppFactory.getOfficeAppContext().get_hostFullVersion())})),OSF.definePropertyOnNamespace(e,"requirements",(function(){if(!t){var e=OSF._OfficeAppFactory.getOfficeAppContext();e&&(t=e.get_isDialog()?OSF.Requirement.RequirementsMatrixFactory.getDefaultDialogRequirementMatrix(e):OSF.Requirement.RequirementsMatrixFactory.getDefaultRequirementMatrix(e))}return t})),OSF.definePropertyOnNamespace(e,"officeTheme",(function(){if(!n){var e=OSF._OfficeAppFactory.getOfficeAppContext().get_officeThemeFunc();if(!e)return;n=e()}return n})),OSF.definePropertyOnNamespace(e,"webAuth",(function(){if(OSF.DDA.WebAuth)return OSF.DDA.WebAuth}))}(e.context||(e.context={}))}(Office||(Office={})),function(e){!function(e){!function(e){e.taskPaneAction||(e.taskPaneAction={})}(e.ui||(e.ui={}))}(e.context||(e.context={}))}(Office||(Office={}));var __assign=this&&this.__assign||function(){return(__assign=Object.assign||function(e){for(var t,n=1,i=arguments.length;n0;)o.shift()(t);r(t)},e.sendTelemetryEvent=function(e){Microsoft.Office.WebExtension.sendTelemetryEvent(e)},Microsoft.Office.WebExtension.onReadyInternal=e.onReadyInternal}(Office||(Office={})),function(e){var t=function(){function e(e,t,n,i,r,o,a,s,c,l,u,d,f,p,g,m,h,y,v,S,A,_,T,b,w,O,C,E){this._isDialog=!1,this._id=e,this._appName=t,this._appVersion=n,this._appUILocale=i,this._dataLocale=r,this._docUrl=o,this._clientMode=a,this._settingsFunc=s,this._reason=c,this._osfControlType=l,this._eToken=u,this._correlationId=d,this._appInstanceId=f,this._touchEnabled=p,this._commerceAllowed=g,this._appMinorVersion=m,this._requirementMatrix=h,this._hostCustomMessage=y,this._hostFullVersion=v,this._isDialog=!1,this._clientWindowHeight=S,this._clientWindowWidth=A,this._addinName=_,this._appDomains=T,this._dialogRequirementMatrix=b,this._featureGates=w,this._officeThemeFunc=O,this._initialDisplayMode=C,this._isFromWacAutomation=E}return e.prototype.get_id=function(){return this._id},e.prototype.get_appName=function(){return this._appName},e.prototype.get_appVersion=function(){return this._appVersion},e.prototype.get_appUILocale=function(){return this._appUILocale},e.prototype.get_dataLocale=function(){return this._dataLocale},e.prototype.get_docUrl=function(){return this._docUrl},e.prototype.get_clientMode=function(){return this._clientMode},e.prototype.get_settingsFunc=function(){return this._settingsFunc},e.prototype.get_reason=function(){return this._reason},e.prototype.get_osfControlType=function(){return this._osfControlType},e.prototype.get_eToken=function(){return this._eToken},e.prototype.get_correlationId=function(){return this._correlationId},e.prototype.get_appInstanceId=function(){return this._appInstanceId},e.prototype.get_touchEnabled=function(){return this._touchEnabled},e.prototype.get_commerceAllowed=function(){return this._commerceAllowed},e.prototype.get_appMinorVersion=function(){return this._appMinorVersion},e.prototype.get_requirementMatrix=function(){return this._requirementMatrix},e.prototype.get_dialogRequirementMatrix=function(){return this._dialogRequirementMatrix},e.prototype.get_hostCustomMessage=function(){return this._hostCustomMessage},e.prototype.get_hostFullVersion=function(){return this._hostFullVersion},e.prototype.get_isDialog=function(){return this._isDialog},e.prototype.get_clientWindowHeight=function(){return this._clientWindowHeight},e.prototype.get_clientWindowWidth=function(){return this._clientWindowWidth},e.prototype.get_addinName=function(){return this._addinName},e.prototype.get_appDomains=function(){return this._appDomains},e.prototype.get_featureGates=function(){return this._featureGates},e.prototype.get_officeThemeFunc=function(){return this._officeThemeFunc},e.prototype.get_initialDisplayMode=function(){return this._initialDisplayMode?this._initialDisplayMode:0},e.prototype.get_isFromWacAutomation=function(){return this._isFromWacAutomation},e}();e.OfficeAppContext=t}(OSF||(OSF={})),function(e){var t;!function(t){var n,i,r,o,a,s,c,l;"undefined"!=typeof window&&(window.location&&(n=window.location.hash,i=window.location.search),r=window.name);var u={0:"Unknown",1:"Hidden",2:"Taskpane",3:"Dialog"};t.bootstrap=function(t,n){if(a={id:null,webAppUrl:null,conversationID:null,clientEndPoint:null,wnd:window.parent,focused:!1,serviceEndPoint:null,serializerVersion:1},function(){o={isO15:!0,isRichClient:!0,hostType:"",hostPlatform:"",hostSpecificFileVersion:"",hostLocale:"",osfControlAppCorrelationId:"",isDialog:!1,disableLogging:!1,flags:0};var t="_host_Info",n=e.Utility.getQueryStringValue(t);if(!n)try{var i=window.name;if(i){var r=JSON.parse(i);n=r?r.hostInfo:null}}catch(t){e.Utility.log(JSON.stringify(t))}if(!n)try{if(window.external=window.external||{},"undefined"!=typeof agaveHost&&agaveHost.GetHostInfo&&(window.external.GetHostInfo=function(){return agaveHost.GetHostInfo()}),window.external.GetHostInfo){var a=window.external.GetHostInfo();if("isDialog"==a)o.isO15=!0,o.isDialog=!0;else{var s=a.split(t+"=");n=s.length>1?s[1]:a}}}catch(t){e.Utility.log(JSON.stringify(t))}var c=e.OUtil.getSessionStorage();!n&&c.getItem("hostInfoValue")&&(n=c.getItem("hostInfoValue"));if(n){n=decodeURIComponent(n),o.isO15=!1;var l=n.split("$");void 0===l[2]&&(l=n.split("|")),o.hostType=void 0===l[0]?"":l[0].toLowerCase(),o.hostPlatform=void 0===l[1]?"":l[1].toLowerCase(),o.hostSpecificFileVersion=void 0===l[2]?"":l[2].toLowerCase(),o.hostLocale=void 0===l[3]?"":l[3].toLowerCase(),o.osfControlAppCorrelationId=void 0===l[4]?"":l[4],"telemetry"==o.osfControlAppCorrelationId&&(o.osfControlAppCorrelationId=""),o.isDialog=void 0!==l[5]&&"isDialog"==l[5],o.disableLogging=void 0!==l[6]&&"disableLogging"==l[6],o.flags="string"==typeof l[7]&&l[7].length>0?parseInt(l[7]):0,c.setItem("hostInfoValue",n)}else o.isO15=!0,o.hostLocale=e.Utility.getQueryStringValue("locale")}(),function(){!0;try{if(o.disableLogging)return void!1;window.external=window.external||{},void 0===window.external.GetLoggingAllowed||window.external.GetLoggingAllowed()}catch(e){}}(),function(){if(o.hostPlatform===e.HostInfoPlatform.web)s=new e.WebInitializationHelper(o,a,null,null);else if(o.hostPlatform===e.HostInfoPlatform.win32)s=new e.RichClientInitializationHelper(o,a,null,null);else if(o.hostPlatform===e.HostInfoPlatform.ios||o.hostPlatform===e.HostInfoPlatform.mac){if(!(window.webkit&&window.webkit.messageHandlers&&window.webkit.messageHandlers.Agave))throw e.Utility.createNotImplementedException();s=new e.WebkitInitializationHelper(o,a,null,null)}else console.warn("Office.js is loaded inside in unknown host or platform "+o.hostPlatform)}(),s){o.hostPlatform===e.HostInfoPlatform.web&&s.saveAndSetDialogInfo(e.Utility.getQueryStringValue("_host_Info")),s.setAgaveHostCommunication(),OSFPerformance.getAppContextStart=OSFPerformance.now();s.getAppContext(window,(function(n){OSFPerformance.getAppContextEnd=OSFPerformance.now(),e.AppTelemetry.initialize(n),l=n,s.createClientHostController(),c=s.createAsyncMethodExecutor(),s.prepareApiSurface(n);var i=n.get_appName(),r=null;0!=(1&o.flags)&&(r={visibilityMode:u[n.get_initialDisplayMode()]}),Office.fireOnReady({host:e.HostName.Host.getInstance().getHost(i),platform:e.HostName.Host.getInstance().getPlatform(i),addin:r}),o.hostPlatform==e.HostInfoPlatform.web&&null!=a.clientEndPoint&&a.clientEndPoint.invoke("ContextActivationManager_notifyHost",null,[a.id,e.AgaveHostAction.OfficeJsReady,Date.now()]),t(n)}),(function(e){n(e)}))}else n(new Error("Office.js cannot be initialized."))},t.getWindowName=function(){return r},t.getWindowLocationHash=function(){return n},t.getWindowLocationSearch=function(){return i},t.getAsyncMethodExecutor=function(){return c},t.getOfficeAppContext=function(){return l},t.getHostInfo=function(){return o},t.getCachedSessionSettingsKey=function(){return(null!=a.conversationID?a.conversationID:l.get_appInstanceId())+"CachedSessionSettings"},t.getWebAppState=function(){return a},t.getId=function(){return a.id},t.getInitializationHelper=function(){return s}}(t=e._OfficeAppFactory||(e._OfficeAppFactory={})),e.getClientEndPoint=function(){return t.getWebAppState().clientEndPoint}}(OSF||(OSF={})),function(e){!function(e){e.hidden="Hidden",e.taskpane="Taskpane"}(e.VisibilityMode||(e.VisibilityMode={})),function(e){e.succeeded="succeeded",e.failed="failed"}(e.AsyncResultStatus||(e.AsyncResultStatus={})),function(e){e.ReadOnly="readOnly",e.ReadWrite="readWrite"}(e.DocumentMode||(e.DocumentMode={})),function(e){e.Word="Word",e.Excel="Excel",e.PowerPoint="PowerPoint",e.Outlook="Outlook",e.OneNote="OneNote",e.Project="Project",e.Access="Access",e.Visio="Visio"}(e.HostType||(e.HostType={})),function(e){e.Inserted="inserted",e.DocumentOpened="documentOpened"}(e.InitializationReason||(e.InitializationReason={})),function(e){e.PC="PC",e.OfficeOnline="OfficeOnline",e.Mac="Mac",e.iOS="iOS",e.Android="Android",e.Universal="Universal"}(e.PlatformType||(e.PlatformType={})),function(e){e.Binding="binding",e.NamedItem="namedItem",e.Slide="slide",e.Index="index"}(e.GoToType||(e.GoToType={})),function(e){e.Default="default",e.Selected="selected",e.None="none"}(e.SelectionMode||(e.SelectionMode={}))}(Office||(Office={}));var OfficeExt,OSFPerfUtil,OSFWebkit,Office,OTel,OSF,__extends=this&&this.__extends||function(){var e=function(t,n){return(e=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var n in t)t.hasOwnProperty(n)&&(e[n]=t[n])})(t,n)};return function(t,n){function i(){this.constructor=t}e(t,n),t.prototype=null===n?Object.create(n):(i.prototype=n.prototype,new i)}}();!function(e){e.appSpecificCheckOrigin=function(e,t,n,i){return!1}}(OfficeExt||(OfficeExt={})),function(e){var t=function(){function e(e,t,n){this._method=e,this._invokeType=t,this._blockingOthers=n}return e.prototype.getMethod=function(){return this._method},e.prototype.getInvokeType=function(){return this._invokeType},e.prototype.getBlockingFlag=function(){return this._blockingOthers},e}();e.XdmMethodObject=t;var n=function(){function e(e,t){this._registerMethodObject=e,this._unregisterMethodObject=t}return e.prototype.getRegisterMethodObject=function(){return this._registerMethodObject},e.prototype.getUnregisterMethodObject=function(){return this._unregisterMethodObject},e}();e.XdmEventMethodObject=n;var i=function(){function i(e){this._methodObjectList={},this._eventHandlerProxyList={},this._conversations={},this._policyManager=null,this._appDomains={},this._onHandleRequestError=null,this._methodObjectList={},this._eventHandlerProxyList={},this._Id=e,this._conversations={},this._policyManager=null,this._appDomains={},this._onHandleRequestError=null}return i.prototype.registerMethod=function(n,i,r,o){if(0!==r&&1!==r)throw e.Utility.createArgumentException("invokeType");var a=new t(i,r,o);this._methodObjectList[n]=a},i.prototype.unregisterMethod=function(e){delete this._methodObjectList[e]},i.prototype.registerEvent=function(e,i,r){var o=new n(new t(i,4,!1),new t(r,5,!1));this._methodObjectList[e]=o},i.prototype.registerEventEx=function(e,i,r,o,a){var s=new n(new t(i,r,!1),new t(o,a,!1));this._methodObjectList[e]=s},i.prototype.unregisterEvent=function(e){this.unregisterMethod(e)},i.prototype.registerConversation=function(t,n,i,r){if(e.Utility.xdmDebugLog("registerConversation: cId="+t+" Url="+n),i){if(!Array.isArray(i))throw e.Utility.createArgumentException("appDomains");this._appDomains[t]=i}this._conversations[t]={url:n,serializerVersion:r}},i.prototype.unregisterConversation=function(e){delete this._conversations[e]},i.prototype.setPolicyManager=function(t){if(!t.checkPermission)throw e.Utility.createArgumentException("policyManager");this._policyManager=t},i.prototype.getPolicyManager=function(){return this._policyManager},i.prototype.dispose=function(){this._methodObjectList=null,this._eventHandlerProxyList=null,this._Id=null,this._conversations=null,this._policyManager=null,this._appDomains=null,this._onHandleRequestError=null},i}();e.XdmServiceEndPoint=i;var r,o=function(){function e(e,t,n,i){this._callbackList={},this._eventHandlerList={},this._hostTrustCheckStatus=0,this._checkStatusLogged=!1,this._conversationId=e,this._targetWindow=t,this._targetUrl=n,this._callingIndex=0,this._callbackList={},this._eventHandlerList={},this._serializerVersion=null!=i?i:1,this._checkReceiverOriginAndRun=null}return Object.defineProperty(e.prototype,"targetUrl",{get:function(){return this._targetUrl},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"hostTrustCheckStatus",{get:function(){return this._hostTrustCheckStatus},set:function(e){this._hostTrustCheckStatus=e},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"checkStatusLogged",{get:function(){return this._checkStatusLogged},set:function(e){this._checkStatusLogged=e},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"checkReceiverOriginAndRun",{get:function(){return this._checkReceiverOriginAndRun},set:function(e){this._checkReceiverOriginAndRun=e},enumerable:!0,configurable:!0}),e.prototype.invoke=function(e,t,n){var i=this,o=function(){var o=i._callingIndex++,a=new Date,c={callback:t,createdOn:a.getTime()};n&&"object"==typeof n&&"number"==typeof n.__timeout__&&(c.timeout=n.__timeout__,delete n.__timeout__),i._callbackList[o]=c;try{if(3!==i._hostTrustCheckStatus&&"ContextActivationManager_getAppContextAsync"!==e)throw"Access Denied";var u=new s(e,0,i._conversationId,o,n),d=l.envelope(u,i._serializerVersion);i._targetWindow.postMessage(d,i._targetUrl),r._startMethodTimeoutTimer()}catch(e){try{null!==t&&t(-1,e)}finally{delete i._callbackList[o]}}};this._checkReceiverOriginAndRun?this._checkReceiverOriginAndRun(o):(this._hostTrustCheckStatus=3,o())},e.prototype.registerForEvent=function(e,t,n,i){var o=this._callingIndex++,a=new Date;this._callbackList[o]={callback:n,createdOn:a.getTime()};try{var c=new s(e,1,this._conversationId,o,i),u=l.envelope(c,this._serializerVersion);this._targetWindow.postMessage(u,this._targetUrl),r._startMethodTimeoutTimer(),this._eventHandlerList[e]=t}catch(e){try{null!==n&&n(-1,e)}finally{delete this._callbackList[o]}}},e.prototype.unregisterForEvent=function(e,t,n){var i=this._callingIndex++,o=new Date;this._callbackList[i]={callback:t,createdOn:o.getTime()};try{var a=new s(e,2,this._conversationId,i,n),c=l.envelope(a,this._serializerVersion);this._targetWindow.postMessage(c,this._targetUrl),r._startMethodTimeoutTimer()}catch(e){try{null!==t&&t(-1,e)}finally{delete this._callbackList[i]}}finally{delete this._eventHandlerList[e]}},e}();e.XdmClientEndPoint=o,function(t){var n=[],r=null,a=null,s=!1,u={},p={},g=!1;function m(){null!==a?s||(n.length>0?h(n.shift()):(clearInterval(a),a=null)):e.Utility.xdmDebugLog("channel is not ready.")}function h(e){s=e.getInvokeBlockingFlag(),e.invoke(),r=(new Date).getTime()}function y(){s=!1}function v(e,t){var n=!1;if(!(t&&"null"!==t&&t.length&&e&&e instanceof Array&&e.length))return n;var i=document.createElement("a"),r=document.createElement("a");i.href=t;for(var o=0;os.length+1&&(l=a.slice(-(s.length+1))==="."+s),o&&r&&(c||l)}function _(e,t){return e.hostname==t.hostname&&e.protocol==t.protocol&&e.port==t.port}function T(t){if(""!=t.data){var i,o=1,g=t.data;try{o=null!=(i=l.unenvelope(g,1))._serializerVersion?i._serializerVersion:o}catch(e){return}if(e.Utility.xdmDebugLog(g),0===i._messageType){var T=null==t.origin||"null"===t.origin?i._origin:t.origin;try{var b=function(t){for(var n in u)if(u[n]._conversations[t])return u[n];throw e.Utility.createArgumentException("conversationId")}(i._conversationId);e.Utility.xdmDebugLog("_receive: request, origin="+T+" sourceURL:"+b._conversations[i._conversationId]);var w=b._conversations[i._conversationId];o=null!=w.serializerVersion?w.serializerVersion:o,e.Utility.xdmDebugLog("_receive: request, origin="+T+" sourceURL:"+w.url);var O=[w.url].concat(b._appDomains[i._conversationId]);if(!v(O,t.origin))if(!OfficeExt.appSpecificCheckOrigin(O,t,i._origin,v))if(!A(w.url,t.origin))throw"Failed origin check";var C=b.getPolicyManager();if(C&&!C.checkPermission(i._conversationId,i._actionName,i._data))throw"Access Denied";var E=function(t,n){var i=t._methodObjectList[n._actionName];if(!i)throw e.Utility.xdmDebugLog("The specified method is not registered on service endpoint:"+n._actionName),e.Utility.createArgumentException("messageObject");return 0===n._actionType?i:1===n._actionType?i.getRegisterMethodObject():i.getUnregisterMethodObject()}(b,i),I=new d(t.source,T,i._actionName,i._conversationId,i._correlationId,y,o),k=new f(E,i._data,I,b._eventHandlerProxyList,i._conversationId,i._actionName,o),D=!0;null==a&&((null==r||(new Date).getTime()-r>10)&&!s?(h(k),D=!1):a=setInterval(m,10)),D&&function(e){n.push(e)}(k)}catch(e){b&&b._onHandleRequestError&&b._onHandleRequestError(i,e);var x=-2;"Access Denied"==e&&(x=-5);var M=new c(i._actionName,i._conversationId,i._correlationId,x,0,e),F=l.envelope(M,o),P=!1;try{P=!(!t.source||!t.source.postMessage)}catch(e){}var N=!1;if(window.location.href&&t.origin&&"null"!==t.origin&&A(window.location.href,t.origin))N=!0;else if(t.origin&&"null"!==t.origin){var H=document.createElement("a");H.href=t.origin,N=S(H.hostname)}P&&N&&t.source.postMessage(F,T)}}else{if(1!==i._messageType)return;var R=function(t){var n=p[t];return n||e.Utility.xdmDebugLog("Unknown conversation Id."),n}(i._conversationId);if(!R)return;if(R._serializerVersion=o,e.Utility.xdmDebugLog("_receive: response, origin="+t.origin+" targetURL:"+R._targetUrl),W=R._targetUrl,j=t.origin,J=!1,!(W&&j&&"null"!==W&&"null"!==j&&W.length&&j.length?(V=document.createElement("a"),z=document.createElement("a"),V.href=W,z.href=j,J=_(V,z)):J))throw"Failed orgin check";if(0===i._responseType){var U=R._callbackList[i._correlationId];if(U)try{U.callback&&U.callback(i._errorCode,i._data)}finally{delete R._callbackList[i._correlationId]}}else{var L=R._eventHandlerList[i._actionName];null!=L&&L(i._data)}}}var W,j,V,z,J}function b(){g||(!function(t){if(window.addEventListener)window.addEventListener("message",t,!1);else{if(!(navigator.userAgent.indexOf("MSIE")>-1&&window.attachEvent))throw e.Utility.xdmDebugLog("Browser doesn't support the required API."),e.Utility.createArgumentException("Browser");window.attachEvent("onmessage",t)}}(T),g=!0)}t.connect=function(e,t,n,i){var r=p[e];return r||(b(),r=new o(e,t,n,i),p[e]=r),r},t.getClientEndPoint=function(e){return p[e]},t.createServiceEndPoint=function(e){b();var t=new i(e);return u[e]=t,t},t.getServiceEndPoint=function(e){return u[e]},t.deleteClientEndPoint=function(e){delete p[e]},t.deleteServiceEndPoint=function(e){delete u[e]},t.checkUrlWithAppDomains=function(e,t){return v(e,t)},t.isTargetSubdomainOfSourceLocation=function(e,t){return A(e,t)},t._setMethodTimeout=function(e){e<=0?65e3:e},t._startMethodTimeoutTimer=function(){},t.isHostNameValidWacDomain=function(e){return S(e)}}(r=e.XdmCommunicationManager||(e.XdmCommunicationManager={}));var a=function(){function e(e,t,n,i,r){this._messageType=e,this._actionName=t,this._conversationId=n,this._correlationId=i,this._origin=window.location.origin,this._data=void 0===r?null:r}return e.prototype.getActionName=function(){return this._actionName},e.prototype.getConversationId=function(){return this._conversationId},e.prototype.getCorrelationId=function(){return this._correlationId},e.prototype.getOrigin=function(){return this._origin},e.prototype.getData=function(){return this._data},e.prototype.getMessageType=function(){return this._messageType},e}(),s=function(e){function t(t,n,i,r,o){var a=e.call(this,0,t,i,r,o)||this;return a._actionType=n,a}return __extends(t,e),t.prototype.getActionType=function(){return this._actionType},t}(a),c=function(e){function t(t,n,i,r,o,a){var s=e.call(this,1,t,n,i,a)||this;return s._errorCode=r,s._responseType=o,s}return __extends(t,e),t.prototype.getErrorCode=function(){return this._errorCode},t.prototype.getResponseType=function(){return this._responseType},t}(a),l=function(){function e(){}return e.envelope=function(e,t){return"object"==typeof e&&(e._serializerVersion=1),JSON.stringify(e)},e.unenvelope=function(e,t){return JSON.parse(e)},e}(),u=function(){function t(t,n,i,r,o,a,s){var u=this;this._invokeResultCode=0,this._requesterWindow=t,this._requesterUrl=n,this._actionName=i,this._conversationId=r,this._correlationId=o,this._invokeResultCode=0,this._responseType=a,this._serializerVersion=s,this._send=function(t){try{var n=new c(u._actionName,u._conversationId,u._correlationId,u._invokeResultCode,u._responseType,t),i=l.envelope(n,u._serializerVersion);u._requesterWindow.postMessage(i,u._requesterUrl),e.Utility.xdmDebugLog("_send: requestUrl="+u._requesterUrl+" _actionName:"+u._actionName)}catch(t){e.Utility.xdmDebugLog("ResponseSender._send error:"+t.message)}}}return t.prototype.getRequesterWindow=function(){return this._requesterWindow},t.prototype.getRequesterUrl=function(){return this._requesterUrl},t.prototype.getActionName=function(){return this._actionName},t.prototype.getConversationId=function(){return this._conversationId},t.prototype.getCorrelationId=function(){return this._correlationId},t.prototype.getSend=function(){return this._send},t.prototype.setResultCode=function(e){this._invokeResultCode=e},t}(),d=function(t){function n(n,i,r,o,a,s,u){var d=t.call(this,n,i,r,o,a,0,u)||this;return d._postCallbackHandler=s,d._send=function(t,n){null!=n&&(d._invokeResultCode=n);try{var i=new c(d._actionName,d._conversationId,d._correlationId,d._invokeResultCode,d._responseType,t),r=l.envelope(i,d._serializerVersion);d._requesterWindow.postMessage(r,d._requesterUrl),d._postCallbackHandler()}catch(t){e.Utility.xdmDebugLog("InvokeCompleteCallback._send error:"+t.message)}},d}return __extends(n,t),n}(u),f=function(){function e(e,t,n,i,r,o,a){this._callerId="",this._methodObject=e,this._param=t,this._invokeCompleteCallback=n,this._eventHandlerProxyList=i,this._conversationId=r,this._eventName=o,this._serializerVersion=a}return e.prototype.invoke=function(){try{var e;switch(this._methodObject.getInvokeType()){case 0:this._methodObject.getMethod()(this._param,this._invokeCompleteCallback.getSend());break;case 1:e=this._methodObject.getMethod()(this._param),this._invokeCompleteCallback.getSend()(e);break;case 4:var t=this._createEventHandlerProxyObject(this._invokeCompleteCallback);e=this._methodObject.getMethod()(t.getSend(),this._param),this._eventHandlerProxyList[this._conversationId+this._eventName]=t.getSend(),this._invokeCompleteCallback.getSend()(e);break;case 5:var n=this._eventHandlerProxyList[this._conversationId+this._eventName];e=this._methodObject.getMethod()(n,this._param),delete this._eventHandlerProxyList[this._conversationId+this._eventName],this._invokeCompleteCallback.getSend()(e);break;case 2:var i=this._createEventHandlerProxyObject(this._invokeCompleteCallback);this._methodObject.getMethod()(i.getSend(),this._invokeCompleteCallback.getSend(),this._param),this._eventHandlerProxyList[this._callerId+this._eventName]=i.getSend();break;case 3:var r=this._eventHandlerProxyList[this._callerId+this._eventName];this._methodObject.getMethod()(r,this._invokeCompleteCallback.getSend(),this._param),delete this._eventHandlerProxyList[this._callerId+this._eventName]}}catch(e){this._invokeCompleteCallback.setResultCode(-3),this._invokeCompleteCallback.getSend()(e)}},e.prototype.getInvokeBlockingFlag=function(){return this._methodObject.getBlockingFlag()},e.prototype._createEventHandlerProxyObject=function(e){return new u(e.getRequesterWindow(),e.getRequesterUrl(),e.getActionName(),e.getConversationId(),e.getCorrelationId(),1,this._serializerVersion)},e}()}(OSF||(OSF={})),function(e){function t(e,t){return t+="_Resource",void 0!==oteljs?[oteljs.makeStringDataField(t+"_name",e.name),oteljs.makeDoubleDataField(t+"_responseEnd",e.responseEnd),oteljs.makeDoubleDataField(t+"_responseStart",e.responseStart),oteljs.makeDoubleDataField(t+"_startTime",e.startTime),oteljs.makeDoubleDataField(t+"_transferSize",e.transferSize)]:[]}e.sendPerformanceTelemetry=function(){if(OSF.AppTelemetry.enableTelemetry){var e,n,i=OSF.LoadScriptHelper.getHostBundleJsName();performance.getEntriesByType("resource").forEach((function(t){OSF.Utility.stringEndsWith(t.name,i)?e=t:(OSF.Utility.stringEndsWith(t.name,OSF.ConstantNames.OfficeDebugJS)||OSF.Utility.stringEndsWith(t.name,OSF.ConstantNames.OfficeJS))&&(n=t)})),OTel.OTelLogger.onTelemetryLoaded((function(){var i=[];e&&(i=i.concat(t(e,"HostJs"))),n&&(i=i.concat(t(n,"OfficeJs"))),i=i.concat([oteljs.makeDoubleDataField("officeExecuteStartDate",OSFPerformance.officeExecuteStartDate),oteljs.makeDoubleDataField("officeExecuteStart",OSFPerformance.officeExecuteStart),oteljs.makeDoubleDataField("officeExecuteEnd",OSFPerformance.officeExecuteEnd),oteljs.makeDoubleDataField("hostInitializationStart",OSFPerformance.hostInitializationStart),oteljs.makeDoubleDataField("hostInitializationEnd",OSFPerformance.hostInitializationEnd),oteljs.makeDoubleDataField("getAppContextStart",OSFPerformance.getAppContextStart),oteljs.makeDoubleDataField("getAppContextEnd",OSFPerformance.getAppContextEnd),oteljs.makeDoubleDataField("getAppContextXdmStart",OSFPerformance.getAppContextXdmStart),oteljs.makeDoubleDataField("getAppContextXdmEnd",OSFPerformance.getAppContextXdmEnd),oteljs.makeDoubleDataField("createOMEnd",OSFPerformance.createOMEnd),oteljs.makeDoubleDataField("officeOnReady",OSFPerformance.officeOnReady)]),Microsoft.Office.WebExtension.sendTelemetryEvent({eventName:"Office.Extensibility.OfficeJs.JSPerformanceTelemetryV06",dataFields:i,eventFlags:{dataCategories:oteljs.DataCategories.ProductServiceUsage,diagnosticLevel:oteljs.DiagnosticLevel.NecessaryServiceDataEvent}})}))}}}(OSFPerfUtil||(OSFPerfUtil={})),function(e){e.Flights=[];!function(t){var n,i,r="&_flights=",o="_flights=",a={};!function(e){var t=["0","1","2","3","4","5","6","7","8","9","a","b","c","d","e","f"];e.generateNewGuid=function(){for(var e="",n=(new Date).getTime(),i=0;i<32&&n>0;i++)8!=i&&12!=i&&16!=i&&20!=i||(e+="-"),e+=t[n%16],n=Math.floor(n/16);for(;i<32;i++)8!=i&&12!=i&&16!=i&&20!=i||(e+="-"),e+=t[Math.floor(16*Math.random())];return e}}(t.Guid||(t.Guid={})),t.isArray=function(e){return"[object Array]"===Object.prototype.toString.apply(e)},t.isFunction=function(e){return"[object Function]"===Object.prototype.toString.apply(e)},t.isDate=function(e){return"[object Date]"===Object.prototype.toString.apply(e)},t.addEventListener=function(e,t,n){if(e.addEventListener)e.addEventListener(t,n,!1);else{if(!e.attachEvent)throw new Error("Cannot attach event");e.attachEvent("on"+t,n)}},t.removeEventListener=function(e,t,n){if(e.removeEventListener)e.removeEventListener(t,n,!1);else{if(!e.detachEvent)throw new Error("Cannot remove event");e.detachEvent("on"+t,n)}};var s="Date(";function c(e){var t=[];try{t=JSON.parse(e)}catch(e){}return Array.isArray(t)||(t=[]),t}function l(e,n,i){try{var r=JSON.parse(n),o=null!=r?r[i]:null,a=t.getSessionStorage();if(!e&&a&&null!=r){var s=r.baseFrameName+i;o?a.setItem(s,o):o=a.getItem(s)}return o}catch(e){return null}}function u(e,n,i,r,o){var a=o.split(e),s=a.length>1?a[a.length-1]:null;i&&null!=s&&(s.indexOf("&")>=0&&(s=s.split("&")[0]),s=decodeURIComponent(s));var c=t.getSessionStorage();if(!r&&c){var l=window.name.indexOf(n);if(l>-1){var u=window.name.indexOf(";",l);-1==u&&(u=window.name.length);var d=window.name.substring(l,u);s?c.setItem(d,s):s=c.getItem(d)}}return s}function d(e){var t,n,i=[],r=[],o=e.length;for(t=0;t0?r.push(n):0===n.tabIndex&&i.push(n):i.push(n);return r=r.sort((function(e,t){var n=e.tabIndex-t.tabIndex;return 0===n&&(n=r.indexOf(e)-r.indexOf(t)),n})),[].concat(r,i)}t.serializeSettings=function(t){var n={};for(var i in t){var r=t[i];try{r=JSON.stringify(r,(function(t,n){return e.OUtil.isDate(this[t])?s+this[t].getTime()+")":n})),n[i]=r}catch(e){}}return n},t.deserializeSettings=function(e){var t={};for(var n in e=e||{}){var i=e[n];try{i=JSON.parse(i,(function(e,t){var n;return"string"==typeof t&&t&&t.length>6&&t.slice(0,5)===s&&")"===t.slice(-1)&&(n=new Date(parseInt(t.slice(5,-1))))?n:t})),t[n]=i}catch(e){}}return t},t.loadScript=function(e,t,n){if(e&&t){var i=window.document,r=a[e];if(r)r.loaded?t(!0):r.pendingCallbacks.push(t);else{var o=i.createElement("script");o.type="text/javascript",r={loaded:!1,pendingCallbacks:[t],timer:null},a[e]=r;var s=function(){null!=r.timer&&(clearTimeout(r.timer),delete r.timer),r.loaded=!0;for(var e=r.pendingCallbacks.length,t=0;t=0},t.parseInfoFromWindowName=l,t.parseInfoWithGivenFragment=u,t.getConversationId=function(){var e=window.location.search,t=null;if(e){var n=e.indexOf("&");(t=n>0?e.substring(1,n):e.substr(1))&&"="===t.charAt(t.length-1)&&(t=t.substring(0,t.length-1))&&(t=decodeURIComponent(t))}return t},t.getInfoItems=function(e){var t=e.split("$");return void 0===t[1]&&(t=e.split("|")),void 0===t[1]&&(t=e.split("%7C")),t},t.getXdmFieldValue=function(t,n){var i="",r=e.OUtil.parseXdmInfo(n);if(r){var o=e.OUtil.getInfoItems(r);if(null!=o&&o.length>=3)switch(t){case"ConversationUrl":i=o[2];break;case"AppId":i=o[1]}}return i},t.parseUrl=function(t,n){if(void 0===n&&(n=!1),void 0!==t&&t){var i="NotHttps",r="undefined"!=typeof window&&void 0!==window.navigator&&window.navigator.userAgent.indexOf("Trident")>0,o=("undefined"!=typeof window&&void 0!==window.navigator&&window.navigator.userAgent.indexOf("Edge"),{protocol:void 0,hostname:void 0,host:void 0,port:void 0,pathname:void 0,search:void 0,hash:void 0,isPortPartOfUrl:void 0});try{if(r){var a=document.createElement("a");if(a.href=t,!(a&&a.protocol&&a.host&&a.hostname&&a.href&&this.cleanUrl(a.href)===this.cleanUrl(t)))throw"InvalidUrl";if(e.OUtil.checkFlight(2)&&n&&"https:"!=a.protocol)throw new Error(i);var s=this.getRedundandPortString(t,a);o.protocol=a.protocol,o.hostname=a.hostname,o.port=""==s?a.port:"",o.host=""!=s?a.hostname:a.host,o.pathname=(r?"/":"")+a.pathname,o.search=a.search,o.hash=a.hash,o.isPortPartOfUrl=this.containsPort(t,a.protocol,a.hostname,a.port)}else{var c=new URL(t);if(c&&c.protocol&&c.host&&c.hostname){if(e.OUtil.checkFlight(2)&&n&&"https:"!=c.protocol)throw new Error(i);o.protocol=c.protocol,o.hostname=c.hostname,o.port=c.port,o.host=c.host,o.pathname=c.pathname,o.search=c.search,o.hash=c.hash,o.isPortPartOfUrl=c.host.lastIndexOf(":"+c.port)==c.host.length-c.port.length-1}}}catch(e){if(e.message===i)throw e}return o}},t.focusToFirstTabbable=function(e,t){var n,i,r=!1,o=function(e){r=!0},a=function(e,t,n){return t<0||t>e||0===t&&n?-1:t!==e-1||n?n?t-1:t+1:-1};if(e=d(e),n=t?e.length-1:0,0===e.length)return null;for(;!r&&n>=0&&ne||0===t&&n?-1:t!==e-1||n?n?t-1:t+1:-1};if(i=function(e,t){for(var n=0;n=0&&r0&&r.major>o.major)return!0;if(r.major>0&&r.minor>=0&&r.major==o.major&&r.minor>=o.minor)return!0}catch(e){return!1}}return!1},e.prototype._getVersion=function(e){var t=(e+="").split("."),n=0,i=0;if(t.length<2&&isNaN(Number(e)))throw"version format incorrect";if(n=Number(t[0]),t.length>=2&&(i=Number(t[1])),isNaN(n)||isNaN(i))throw"version format incorrect";return{minor:i,major:n}},e}();e.RequirementMatrix=n;var i=function(){function e(e){this._sets=e}return e.prototype._addSetMap=function(e){for(var t in e)this._sets[t]=e[t]},e}();e.DefaultSetRequirement=i;var r=function(e){function t(){return e.call(this,{dialogapi:1.1})||this}return __extends(t,e),t}(i);e.DefaultDialogSetRequirement=r;var o=function(){function e(){}return e.getDefaultRequirementMatrix=function(e){var t=void 0,r=e.get_requirementMatrix();if(null!=r&&r.length>0){var o=JSON.parse(e.get_requirementMatrix().toLowerCase());t=new n(new i(o))}else t=new n(new i({}));return t},e.getDefaultDialogRequirementMatrix=function(e){var t=void 0,o=e.get_dialogRequirementMatrix();if(null!=o&&o.length>0){var a=JSON.parse(e.get_requirementMatrix().toLowerCase());t=new n(new i(a))}else t=new n(new r);return t},e}();e.RequirementsMatrixFactory=o}(e.Requirement||(e.Requirement={}))}(OSF||(OSF={})),function(e){!function(t){!function(t){var n;t.executeRichApiRequestAsync=function(t,n){var i={toSafeArrayHost:function(){return[t]},fromSafeArrayHost:function(e){return{data:e}},toWebHost:function(){return{ArrayData:t}},fromWebHost:function(e){return{data:e.Data}}};e._OfficeAppFactory.getAsyncMethodExecutor().executeAsync(93,i,n)},Object.defineProperty(t,"richApiMessageManager",{get:function(){return n||(n=new e.RichApiMessageManager),n}})}(t.RichApi||(t.RichApi={}))}(e.DDA||(e.DDA={}))}(OSF||(OSF={})),function(e){var t=function(){function t(){this._registerHandlers=[],this._eventDispatch=new e.EventDispatch([{type:e.EventType.RichApiMessage,id:33,getTargetId:function(){return""},fromSafeArrayHost:function(e){var n=e;return t.transferEventArgument(n)},fromWebHost:function(e){var n=e.ArrayData;return t.transferEventArgument(n)}}])}return t.transferEventArgument=function(t){var n=[];if(t)for(var i=0;i2){l=[];for(var u=1;uparseInt(r[n]))return!0}return!1},e.getQueryStringValue=function(e){if("undefined"!=typeof window&&window.location&&window.location.search){var t=new RegExp("[?&]"+e+"=([^&]*)").exec(window.location.search);if(t)return t[1]}return null},e.getErrorCodeFromAsyncResult=function(e){return e.status===Office.AsyncResultStatus.succeeded?0:e.error&&e.error.code?e.error.code:5001},e.isNullOrUndefined=n,e.isNullOrEmpty=function(e){return!!n(e)||0===e.length},e.externalNativeFunctionExists=function(e){return"unknown"===e||"undefined"!==e},e.stringEndsWith=function(e,i){if(n(e))throw t("value");if(n(i))throw t("subString");return!(i.length>e.length)&&e.substr(e.length-i.length)===i},e.fromSafeArray=function e(t){var n=t;if(null!=t&&t.toArray){var i=t.toArray();n=new Array(i.length);for(var r=0;r-1){var r=(n=e.OUtil.parseXdmInfo(!0))?n.split("|")[1]:null;return null!=r&&i.setItem(r+"IsDialog","true"),void(this._hostInfo.isDialog=!0)}this._hostInfo.isDialog=null!=i.getItem(e.OUtil.getXdmFieldValue("AppId",!1)+"IsDialog")}},n.prototype.checkReceiverOriginAndRun=function(t){var n=this,i=e.OUtil.parseUrl(n._webAppState.clientEndPoint.targetUrl,!1),r="https:"==i.protocol;if(0===n._webAppState.clientEndPoint.hostTrustCheckStatus&&(r||(n._webAppState.clientEndPoint.hostTrustCheckStatus=2),2!=n._webAppState.clientEndPoint.hostTrustCheckStatus)){var o=e.XdmCommunicationManager.isHostNameValidWacDomain(i.hostname);n.isHostOriginTrusted&&(o=o||n.isHostOriginTrusted(i.hostname)),o&&(n._webAppState.clientEndPoint.hostTrustCheckStatus=3)}if(n._webAppState.clientEndPoint.checkStatusLogged||null==n._hostInfo||void 0===n._hostInfo||(e.AppTelemetry.onCheckWACHost(n._webAppState.clientEndPoint.hostTrustCheckStatus,n._webAppState.id,n._hostInfo.hostType,n._hostInfo.hostPlatform,n._webAppState.clientEndPoint.targetUrl),n._webAppState.clientEndPoint.checkStatusLogged=!0),3!=n._webAppState.clientEndPoint.hostTrustCheckStatus){var a=function(){var o=e.LoadScriptHelper.getHostBundleJsBasePath().match(/^https?:\/\/[^:/?#]*(?::([0-9]+))?/);if(o&&o[0]){var a=e.LoadScriptHelper.getHostBundleJsBasePath()+"AgaveErrorUX/index.html#",s={error:"NotTrustedWAC",locale:e.getSupportedLocale(n._hostInfo.hostLocale,e.ConstantNames.DefaultLocale),hostname:i.hostname,noHttps:!r,validate:!1},c=document.createElement("iframe");c.style.visibility="hidden",c.style.height="0",c.style.width="0";var l=function(i){if(i.source==c.contentWindow&&i.origin==o[0])try{!0===JSON.parse(i.data).hostUserTrusted?(n._webAppState.clientEndPoint.hostTrustCheckStatus=3,e.OUtil.removeEventListener(window,"message",l),document.body.removeChild(c)):(s.validate=!1,window.location.replace(a+encodeURIComponent(JSON.stringify(s)))),t()}catch(t){e.OUtil.ensureOfficeStringsJs().then((function(){document.body.innerHTML=Strings.OfficeOM.L_NotTrustedWAC}))}};e.OUtil.addEventListener(window,"message",l),s.validate=!0,c.setAttribute("src",a+encodeURIComponent(JSON.stringify(s))),c.onload=function(){var e={hostname:i.hostname,noHttps:!r};c.contentWindow.postMessage(JSON.stringify(e),o[0])},document.body.appendChild(c)}else e.OUtil.ensureOfficeStringsJs().then((function(){document.body.innerHTML=Strings.OfficeOM.L_NotTrustedWAC}));if(e.OUtil.checkFlight(2)&&!r)throw new Error("NotHttps")};if(document.body)a();else{var s=!1;document.addEventListener("DOMContentLoaded",(function(){s||(s=!0,a())}))}}else t()},n.prototype.setAgaveHostCommunication=function(){try{var t=this,n=e.OUtil.parseXdmInfoWithGivenFragment(!1,e._OfficeAppFactory.getWindowLocationHash());if(n||(n=e.OUtil.parseXdmInfoFromWindowName(!1,e._OfficeAppFactory.getWindowName())),n){var i=e.OUtil.getInfoItems(n);null!=i&&i.length>=3&&(t._webAppState.conversationID=i[0],t._webAppState.id=i[1],t._webAppState.webAppUrl=i[2].indexOf(":")>=0?i[2]:decodeURIComponent(i[2]))}t._webAppState.wnd=null!=window.opener?window.opener:window.parent;var r=e.OUtil.parseSerializerVersionWithGivenFragment(!1,e._OfficeAppFactory.getWindowLocationHash());if(isNaN(r)&&(r=e.OUtil.parseSerializerVersionFromWindowName(!1,e._OfficeAppFactory.getWindowName())),t._webAppState.serializerVersion=r,this._hostInfo.isDialog&&null!=window.opener)return;t._webAppState.clientEndPoint=e.XdmCommunicationManager.connect(t._webAppState.conversationID,t._webAppState.wnd,t._webAppState.webAppUrl,t._webAppState.serializerVersion),t._webAppState.serviceEndPoint=e.XdmCommunicationManager.createServiceEndPoint(t._webAppState.id),t._webAppState.clientEndPoint.checkReceiverOriginAndRun=function(e){t.checkReceiverOriginAndRun(e)};var o=t._webAppState.conversationID+e.Constants.NotificationConversationIdSuffix;t._webAppState.serviceEndPoint.registerConversation(o,t._webAppState.webAppUrl);t._webAppState.serviceEndPoint.registerMethod("Office_notifyAgave",(function(n){var i;switch(i="string"==typeof n?n:n[0]){case e.AgaveHostAction.Select:t._webAppState.focused=!0;break;case e.AgaveHostAction.UnSelect:t._webAppState.focused=!1;break;case e.AgaveHostAction.TabIn:case e.AgaveHostAction.CtrlF6In:window.focus();var r=document.querySelectorAll(t._tabbableElements);e.OUtil.focusToFirstTabbable(r,!1)||(window.blur(),t._webAppState.focused=!1,t._webAppState.clientEndPoint.invoke("ContextActivationManager_notifyHost",null,[t._webAppState.id,e.AgaveHostAction.ExitNoFocusable]));break;case e.AgaveHostAction.TabInShift:window.focus();r=document.querySelectorAll(t._tabbableElements);e.OUtil.focusToFirstTabbable(r,!0)||(window.blur(),t._webAppState.focused=!1,t._webAppState.clientEndPoint.invoke("ContextActivationManager_notifyHost",null,[t._webAppState.id,e.AgaveHostAction.ExitNoFocusableShift]));break;case e.AgaveHostAction.SendMessage:if(Office.context.messaging.onMessage){var o=n[1];Office.context.messaging.onMessage(o)}break;case e.AgaveHostAction.TaskPaneHeaderButtonClicked:Office.context.ui.taskPaneAction.onHeaderButtonClick&&Office.context.ui.taskPaneAction.onHeaderButtonClick();break;default:e.Utility.trace("actionId "+i+" notifyAgave is wrong.")}}),0,!1),t.addOrRemoveEventListenersForWindow(!0)}catch(t){throw e.AppTelemetry&&e.AppTelemetry.logAppException("Exception thrown in setAgaveHostCommunication. Exception:["+t+"]"),t}},n.prototype.getAppContext=function(t,n,i){var r=this,o=this,a=function(t,a){if(OSFPerformance.getAppContextXdmEnd=OSFPerformance.now(),a._appName===e.AppName.ExcelWebApp){var s=a._settings;for(var c in r._serializedSettings={},s){var l=s[c];r._serializedSettings[l[0]]=l[1]}}else r._serializedSettings=a._settings;if(!o._hostInfo.isDialog||null==window.opener){var u=window.location.href;o._webAppState.clientEndPoint.invoke("ContextActivationManager_notifyHost",null,[o._webAppState.id,e.AgaveHostAction.UpdateTargetUrl,u])}if(0===t&&null!=a._id&&null!=a._appName&&null!=a._appVersion&&null!=a._appUILocale&&null!=a._dataLocale&&null!=a._docUrl&&null!=a._clientMode&&null!=a._settings&&null!=a._reason){o._appContext=a;var d=a._appInstanceId?a._appInstanceId:a._id,f=0;null!=a._appMinorVersion&&(f=a._appMinorVersion);var p=void 0;null!=a._requirementMatrix&&(p=a._requirementMatrix),a.eToken=a.eToken?a.eToken:"";var g=new e.OfficeAppContext(a._id,a._appName,a._appVersion,a._appUILocale,a._dataLocale,a._docUrl,a._clientMode,(function(){return r._serializedSettings}),a._reason,a._osfControlType,a._eToken,a._correlationId,d,!1,!0,f,p,a._hostCustomMessage,a._hostFullVersion,a._clientWindowHeight,a._clientWindowWidth,a._addinName,a._appDomains,a._dialogRequirementMatrix,a._featureGates,void 0,a._initialDisplayMode,a._isFromWacAutomation);n(g)}else{var m="Function ContextActivationManager_getAppContextAsync call failed. ErrorCode is "+t+", exception: "+a;e.AppTelemetry&&e.AppTelemetry.logAppException(m),i(m)}};try{var s=!0;this._hostInfo.isDialog&&null!=window.opener&&(s=!1);var c=e.OUtil.parseAppContextFromWindowName(s,e._OfficeAppFactory.getWindowName());c?a(0,c):(OSFPerformance.getAppContextXdmStart=OSFPerformance.now(),this._webAppState.clientEndPoint.invoke("ContextActivationManager_getAppContextAsync",a,this._webAppState.id))}catch(t){e.AppTelemetry&&e.AppTelemetry.logAppException("Exception thrown when trying to invoke getAppContextAsync. Exception:["+t+"]"),i(t)}},n.prototype.createClientHostController=function(){return this._clientHostController||(this._hostInfo.hostType.toLowerCase()===Office.HostType.Outlook.toLowerCase()?this._clientHostController=new e.WebClientHostController_outlook(this._webAppState):this._clientHostController=new e.WebClientHostController(this._webAppState)),this._clientHostController},n.prototype.createAsyncMethodExecutor=function(){return new e.WebAsyncMethodExecutor(this._clientHostController)},n.prototype.createClientSettingsManager=function(){return new e.WebClientSettingsManager},n.prototype.addOrRemoveEventListenersForWindow=function(t){var n=this,i=function(){n._webAppState.focused||(n._webAppState.focused=!0),n._webAppState.clientEndPoint.invoke("ContextActivationManager_notifyHost",null,[n._webAppState.id,e.AgaveHostAction.Select])},r=function(){e&&(n._webAppState.focused&&(n._webAppState.focused=!1),n._webAppState.clientEndPoint.invoke("ContextActivationManager_notifyHost",null,[n._webAppState.id,e.AgaveHostAction.UnSelect]))},o=function(t){if(t.preventDefault=t.preventDefault||function(){t.returnValue=!1},117==t.keyCode&&(t.ctrlKey||t.metaKey)){t.preventDefault();var i=e.AgaveHostAction.CtrlF6Exit;t.shiftKey&&(i=e.AgaveHostAction.CtrlF6ExitShift),n._webAppState.clientEndPoint.invoke("ContextActivationManager_notifyHost",null,[n._webAppState.id,i])}else if(9==t.keyCode){t.preventDefault();var r=document.querySelectorAll(n._tabbableElements);e.OUtil.focusToNextTabbable(r,t.target||t.srcElement,t.shiftKey)||(n._hostInfo.isDialog?e.OUtil.focusToFirstTabbable(r,t.shiftKey):t.shiftKey?n._webAppState.clientEndPoint.invoke("ContextActivationManager_notifyHost",null,[n._webAppState.id,e.AgaveHostAction.TabExitShift]):n._webAppState.clientEndPoint.invoke("ContextActivationManager_notifyHost",null,[n._webAppState.id,e.AgaveHostAction.TabExit]))}else 27==t.keyCode?(t.preventDefault(),n._webAppState.clientEndPoint.invoke("ContextActivationManager_notifyHost",null,[n._webAppState.id,e.AgaveHostAction.EscExit])):113==t.keyCode&&(t.preventDefault(),n._webAppState.clientEndPoint.invoke("ContextActivationManager_notifyHost",null,[n._webAppState.id,e.AgaveHostAction.F2Exit]))},a=function(e){117==e.keyCode&&e.ctrlKey&&(e.preventDefault?e.preventDefault():e.returnValue=!1)};e.Utility._DebugXdm||(t?(e.OUtil.addEventListener(window,"focus",i),e.OUtil.addEventListener(window,"blur",r),e.OUtil.addEventListener(window,"keydown",o),e.OUtil.addEventListener(window,"keypress",a)):(e.OUtil.removeEventListener(window,"focus",i),e.OUtil.removeEventListener(window,"blur",r),e.OUtil.removeEventListener(window,"keydown",o),e.OUtil.removeEventListener(window,"keypress",a)))},n}(e.InitializationHelper);e.WebInitializationHelper=t}(OSF||(OSF={})),function(e){var t=function(){function t(e,t){this._initializationHelper=e,this._scriptMessager=t}return t.prototype.read=function(e){this._initializationHelper.getAppContext(null,(function(t){if(e){var n=t.get_settingsFunc()();e(0,n)}}),(function(t){e&&e(5001,{})}))},t.prototype.write=function(t,n){var i={},r=[],o=[];for(var a in t)r.push(a),o.push(t[a]);i.keys=r,i.values=o;this._scriptMessager.invokeMethod(e.Webkit.MessageHandlerName,e.Webkit.MethodId.WriteSettings,i,(function(e){n&&n(e[0])}))},t}();e.WebkitClientSettingsManager=t}(OSF||(OSF={})),function(e){!function(t){t.MessageHandlerName="Agave",t.PopupMessageHandlerName="WefPopupHandler",function(e){e[e.Settings=0]="Settings",e[e.SolutionReferenceId=1]="SolutionReferenceId",e[e.AppType=2]="AppType",e[e.MajorVersion=3]="MajorVersion",e[e.MinorVersion=4]="MinorVersion",e[e.RevisionVersion=5]="RevisionVersion",e[e.APIVersionSequence=6]="APIVersionSequence",e[e.AppCapabilities=7]="AppCapabilities",e[e.APPUILocale=8]="APPUILocale",e[e.AppDataLocale=9]="AppDataLocale",e[e.BindingCount=10]="BindingCount",e[e.DocumentUrl=11]="DocumentUrl",e[e.ActivationMode=12]="ActivationMode",e[e.ControlIntegrationLevel=13]="ControlIntegrationLevel",e[e.SolutionToken=14]="SolutionToken",e[e.APISetVersion=15]="APISetVersion",e[e.CorrelationId=16]="CorrelationId",e[e.InstanceId=17]="InstanceId",e[e.TouchEnabled=18]="TouchEnabled",e[e.CommerceAllowed=19]="CommerceAllowed",e[e.RequirementMatrix=20]="RequirementMatrix",e[e.HostCustomMessage=21]="HostCustomMessage",e[e.HostFullVersion=22]="HostFullVersion",e[e.InitialDisplayMode=23]="InitialDisplayMode"}(t.AppContextProperties||(t.AppContextProperties={})),function(e){e[e.Execute=1]="Execute",e[e.RegisterEvent=2]="RegisterEvent",e[e.UnregisterEvent=3]="UnregisterEvent",e[e.WriteSettings=4]="WriteSettings",e[e.GetContext=5]="GetContext",e[e.SendMessage=6]="SendMessage",e[e.MessageParent=7]="MessageParent"}(t.MethodId||(t.MethodId={}));var n=function(){function t(e){this.hostScriptProxy=e,this.useFullDialogAPI=!!window._enableFullDialogAPI}return t.prototype.execute=function(t,n,i){var r={id:t,apiArgs:n};this.hostScriptProxy.invokeMethod(e.Webkit.MessageHandlerName,e.Webkit.MethodId.Execute,r,(function(t){if(i){var n=[];if(e.OUtil.isArray(t))for(var r=0;r=2&&(n=t[0],i=t[1]),r&&r(i,new e.WebkitSafeArray(n))}),(function(t){if(o)return o(new e.WebkitSafeArray(t))}))},t.prototype.unregisterEvent=function(t,n,i,r){this.hostScriptProxy.unregisterEvent(e.Webkit.MessageHandlerName,e.Webkit.MethodId.UnregisterEvent,t,i,(function(t){return r(new e.WebkitSafeArray(t))}))},t.prototype.messageParent=function(t){var n=t[e.ParameterNames.MessageToParent];if(this.useFullDialogAPI)this.hostScriptProxy.invokeMethod(e.Webkit.MessageHandlerName,e.Webkit.MethodId.MessageParent,n,null);else{var i={dialogMessage:{messageType:0,messageContent:n}};window.opener.postMessage(JSON.stringify(i),window.location.origin)}},t.prototype.openDialog=function(n,i,r,o,a){if(this.useFullDialogAPI)this.registerEvent(n,i,r,o,a);else if(!t.popup||t.popup.closed){t.OpenDialogCallback=void 0;var s=JSON.parse(r),c=s.url;if(c){var l=c.split("#"),u="?";l[0].indexOf("?")>-1&&(u="&");var d="width="+screen.width*s.width/100+", height="+screen.height*s.height/100;l[0]=l[0].concat(u).concat("action=displayDialog");var f=l.join("#");t.popup=window.open(f,"",d),t.DialogEventListener=function(t){if(t.origin==window.location.origin)try{var i=JSON.parse(t.data);i.dialogMessage&&o(n,[0,i.dialogMessage.messageContent])}catch(n){e.Utility.trace("messages received cannot be handlered. Message:"+t.data)}},t.OpenDialogCallback=function(e){0==e&&(window.addEventListener("message",t.DialogEventListener),t.interval=window.setInterval(p,1e3),t.NotifyError=function(e){o(n,[e])}),a(e)}}else a(12003)}else a(12007);function p(){try{(null==t.popup||t.popup.closed)&&(window.clearInterval(t.interval),window.removeEventListener("message",t.DialogEventListener),t.NotifyError=null,t.popup=null,o(n,[12006]))}catch(t){e.Utility.trace("Error happened when popup window closed.")}}},t.prototype.closeDialog=function(e,n,i,r){this.useFullDialogAPI?this.unregisterEvent(e,n,i,r):t.popup?(t.interval&&window.clearInterval(t.interval),t.popup.close(),t.popup=null,window.removeEventListener("message",t.DialogEventListener),t.NotifyError=null,r(0)):r(5001)},t.prototype.sendMessage=function(t){var n=t[e.ParameterNames.MessageContent];!isNaN(parseFloat(n))&&isFinite(n)&&(n=n.toString()),this.hostScriptProxy.invokeMethod(e.Webkit.MessageHandlerName,e.Webkit.MethodId.SendMessage,n,null)},t}();t.WebkitHostController=n}(e.Webkit||(e.Webkit={}))}(OSF||(OSF={})),function(e){var t=function(t){function n(e,n,i,r){var o=t.call(this,e,n,i,r)||this;return o.initializeWebkitMessaging(),o}return __extends(n,t),n.prototype.initializeWebkitMessaging=function(){e.ScriptMessaging=OSFWebkit.ScriptMessaging},n.prototype.getAppContext=function(t,n,i){var r,o=this;r=this._hostInfo.isDialog&&window.webkit.messageHandlers[e.Webkit.PopupMessageHandlerName]?e.Webkit.PopupMessageHandlerName:e.Webkit.MessageHandlerName,e.ScriptMessaging.GetScriptMessenger().invokeMethod(r,e.Webkit.MethodId.GetContext,[],(function(t){var i,r=e.Webkit.AppContextProperties,a=t[r.AppType],s=t[r.Settings];o._serializedSettings={};for(var c=s[0],l=s[1],u=0;u=e.MESSAGE_TIME_DELTA?(s(),this.lastMessageTimestamp=c):(this.lastMessageTimestamp+=e.MESSAGE_TIME_DELTA,setTimeout((function(){s()}),this.lastMessageTimestamp-c)),a},e.prototype.generateCorrelationId=function(){return++this.callingIndex,this.conversationId+this.callingIndex},e.getCurrentTimeMS=function(){return(new Date).getTime()},e.MESSAGE_TIME_DELTA=10,e}()}(e.ScriptMessaging||(e.ScriptMessaging={}))}(OSFWebkit||(OSFWebkit={})),function(e){var t=function(t){function n(){return null!==t&&t.apply(this,arguments)||this}return __extends(n,t),n.prototype.messageParent=function(t){var n=t[e.ParameterNames.MessageToParent];window.external.MessageParent(n)},n.prototype.openDialog=function(e,t,n,i,r){this.registerEvent(e,t,n,i,r)},n.prototype.closeDialog=function(e,t,n,i){this.unregisterEvent(e,t,n,i)},n.prototype.sendMessage=function(t){var n=t[e.ParameterNames.MessageContent];window.external.MessageChild(n)},n}(e.RichClientHostController);e.Win32RichClientHostController=t}(OSF||(OSF={})),function(e){var t;!function(e){!function(e){e.Init=function(){return function(){"use strict";function e(e){return"function"==typeof e}var t,n=Array.isArray?Array.isArray:function(e){return"[object Array]"===Object.prototype.toString.call(e)},i=0,r=function(e,n){f[i]=e,f[i+1]=n,2===(i+=2)&&(t?t(p):c())};var o=("undefined"!=typeof window?window:void 0)||{},a=(o.MutationObserver||o.WebKitMutationObserver,"undefined"!=typeof process&&"[object process]"==={}.toString.call(process)),s="undefined"!=typeof Uint8ClampedArray&&"undefined"!=typeof importScripts&&"undefined"!=typeof MessageChannel;var c,l,u,d,f=new Array(1e3);function p(){for(var e=0;e40)&&(t=e.OUtil.Guid.generateNewGuid(),this.setValue(this.clientIDKey,t)),t},t.prototype.getValue=function(t){var n=e.OUtil.getLocalStorage(),i="";return n&&(i=n.getItem(t)),i},t.prototype.setValue=function(t,n){var i=e.OUtil.getLocalStorage();i&&i.setItem(t,n)},t}();function s(e){return e&&(e=e.replace(/[{}]/g,"").toLowerCase()),e||""}function c(e,t){}t.initialize=function(c){if(t.enableTelemetry&&!n){n=new o,c.get_hostFullVersion()?n.hostVersion=c.get_hostFullVersion():n.hostVersion=c.get_appVersion(),n.appId=c.get_id(),n.host=""+c.get_appName(),n.browser=window.navigator.userAgent,n.correlationId=s(c.get_correlationId()),n.clientId=(new a).getClientId(),n.appInstanceId=c.get_appInstanceId(),n.appInstanceId&&(n.appInstanceId=n.appInstanceId.replace(/[{}]/g,"").toLowerCase()),n.message=c.get_hostCustomMessage(),n.officeJSVersion="16.0",n.hostJSVersion="16.0",c._wacHostEnvironment&&(n.wacHostEnvironment=c._wacHostEnvironment);var l=c.get_isFromWacAutomation();null!=l&&(n.isFromWacAutomation=l.toString().toLowerCase());var u=c.get_docUrl();n.docUrl=r.test(u)?u:"";var d=location.href;d&&(d=d.split("?")[0].split("#")[0]),n.appURL=t.UrlFilter.filter(d),function(t,n){n.assetId="",n.userId="";try{if(!e.Utility.isNullOrEmpty(t)){var i=decodeURIComponent(t),r=(new DOMParser).parseFromString(i,"text/xml"),o=r.getElementsByTagName("t")[0].attributes.getNamedItem("cid"),a=r.getElementsByTagName("t")[0].attributes.getNamedItem("oid");o&&o.nodeValue?n.userId=o.nodeValue:a&&a.nodeValue&&(n.userId=a.nodeValue),n.assetId=r.getElementsByTagName("t")[0].attributes.getNamedItem("aid").nodeValue}}catch(e){}}(c.get_eToken(),n),n.sessionId=i,OTel.OTelLogger.initialize(n),t.onAppActivated()}},t.onAppActivated=function(){n&&OTel.OTelLogger.onTelemetryLoaded((function(){var e=[];e=e.concat([oteljs.makeStringDataField("Browser",n.browser),oteljs.makeStringDataField("AppURL",n.appURL),oteljs.makeInt64DataField("AppSizeWidth",window.innerWidth),oteljs.makeInt64DataField("AppSizeHeight",window.innerHeight)]),Microsoft.Office.WebExtension.sendTelemetryEvent({eventName:"Office.Extensibility.OfficeJs.AppActivatedX",dataFields:e,eventFlags:{dataCategories:oteljs.DataCategories.ProductServiceUsage,diagnosticLevel:oteljs.DiagnosticLevel.NecessaryServiceDataEvent,samplingPolicy:oteljs.SamplingPolicy.CriticalBusinessImpact}})}))},t.onScriptDone=function(e,t,n,i){},t.onCallDone=function(e,t,n,i,r){},t.onMethodDone=function(e,t,n,i){},t.onPropertyDone=function(t,n){e.AppTelemetry.onCallDone("property",-1,t,n,0)},t.onCheckWACHost=function(e,t,n,i,r){},t.onEventDone=function(t,n){e.AppTelemetry.onCallDone("event",t,null,0,n)},t.onRegisterDone=function(t,n,i,r){e.AppTelemetry.onCallDone(t?"registerevent":"unregisterevent",n,null,i,r)},t.onAppClosed=function(e,t){},t.setOsfControlAppCorrelationId=function(e){s(e)},t.doAppInitializationLogging=c,t.logAppCommonMessage=function(e){},t.logAppException=function(e){}}(e.AppTelemetry||(e.AppTelemetry={}))}(OSF||(OSF={})),function(e){var t=function(){function t(){}return t.loaded=function(){return!(void 0===t.logger)},t.create=function(t){var n,i={id:t.appId,assetId:t.assetId,officeJsVersion:t.officeJSVersion,hostJsVersion:t.hostJSVersion,browserToken:t.clientId,instanceId:t.appInstanceId,sessionId:t.sessionId},r=oteljs.Contracts.Office.System.SDX.getFields("SDX",i);if("web"===OSF._OfficeAppFactory.getHostInfo().hostPlatform)n=new e.SdxWacSink;else{if(!Office.context.requirements.isSetSupported("Telemetry","1.2"))return console.error("Cannot create telemetry sink successfully"),null;n=new e.RichApiSink}var o=new oteljs.SimpleTelemetryLogger(void 0,r);return o.addSink(n),o.setTenantToken("Office.Extensibility.OfficeJs","db334b301e7b474db5e0f02f07c51a47-a1b5bc36-1bbe-482f-a64a-c2d9cb606706-7439",1755),oteljs.onNotification().addListener((function(e){OSF.Utility.debugLog(e.message())})),o},t.checkAndResolvePromises=function(){t.loaded()&&(t.promises.forEach((function(e){e()})),t.promises=[])},t.initialize=function(e){t.Enabled?Office.onReadyInternal().then((function(){t.loaded()||(OSF.Utility.debugLog("Creating OTelLogger"),t.logger=t.create(e),t.checkAndResolvePromises())})):t.promises=[]},t.sendTelemetryEvent=function(e){t.onTelemetryLoaded((function(){try{t.logger.sendTelemetryEvent(e),OSF.Utility.debugLog("Sent telemetry")}catch(e){console.error("Cannot send telemetry event: "+JSON.stringify(e))}}))},t.onTelemetryLoaded=function(e){t.Enabled&&(t.loaded()?e():t.promises.push(e))},t.promises=[],t.Enabled=!0,t}();e.OTelLogger=t}(OTel||(OTel={})),function(e){var t=function(){function e(){var e=this;this._requestIsPending=!0,this._telemetryQueue=[],this.pause(1e3).then((function(){var t=e._telemetryQueue;e._telemetryQueue=[],e._requestIsPending=!1,e.processTelemetryEvents(t)}))}return e.prototype.sendTelemetryEvent=function(e){this._telemetryQueue.push(e),this._requestIsPending||this.processWorkBacklog()},e.prototype.processWorkBacklog=function(){var e=this;this._requestIsPending=!0;var t=this._telemetryQueue;this._telemetryQueue=[],this.processTelemetryEvents(t).then(this.waitAndProcessMore).catch((function(t){oteljs.logError(oteljs.Category.Sink,"RichApiSink Error",t),e.waitAndProcessMore()}))},e.prototype.waitAndProcessMore=function(){var e=this;this.pause(1e3).then((function(){e._telemetryQueue.length>0&&setTimeout((function(){return e.processWorkBacklog()}),0),e._requestIsPending=!1})).catch((function(){}))},e.prototype.processTelemetryEvents=function(e){var t=this,n=new OfficeCore.RequestContext;return e.forEach((function(e){if(e.telemetryProperties){var i=[];t.addDataFields(i,e.dataFields);var r=e.eventContract?e.eventContract.name:"";e.eventContract&&t.addDataFields(i,e.eventContract.dataFields),n.telemetry.sendTelemetryEvent(e.telemetryProperties,e.eventName,r,oteljs.getEffectiveEventFlags(e),i)}})),n.sync().catch((function(){oteljs.logNotification(oteljs.LogLevel.Info,oteljs.Category.Sink,(function(){return"RichApi telemetry call failed."}))}))},e.prototype.addDataFields=function(e,t){t&&t.forEach((function(t){e.push({name:t.name,value:t.value,classification:t.classification?t.classification:oteljs.DataClassification.SystemMetadata,type:t.dataType})}))},e.prototype.pause=function(e){return new Office.Promise((function(t){return setTimeout(t,e)}))},e}();e.RichApiSink=t}(OTel||(OTel={})),function(e){var t=function(){function e(){}return e.prototype.sendTelemetryEvent=function(e,t){try{if(e.dataFields&&e.dataFields.filter((function(e){return e.classification&&e.classification!==oteljs.DataClassification.SystemMetadata})).length>0)return;var n=OSF._OfficeAppFactory.getId(),i=OSF.AgaveHostAction.SendTelemetryEvent;OSF.getClientEndPoint().invoke("ContextActivationManager_notifyHost",null,[n,i,e])}catch(e){oteljs.logError(oteljs.Category.Sink,"AgaveWacSink",e)}},e}();e.SdxWacSink=t}(OTel||(OTel={})),function(e){!function(e){var t=function(){function e(){}return e.hashString=function(e){var t=0;if(0===e.length)return t;for(var n=0;n9007199254740991)throw new Error("Invalid integer "+JSON.stringify(e))}t.validateTelemetryEvent=function(e){if(!function(e){var t=98;if(!e||e.length>t)return!1;var i=e.split("."),r=i[i.length-1];return function(e){return!!e&&e.length>=3&&"Office"===e[0]}(i)&&(o=r,void 0!==o&&n.test(o));var o}(e.eventName))throw new Error("Invalid eventName");if(e.eventContract&&!r(e.eventContract.name))throw new Error("Invalid eventContract");if(null!=e.dataFields)for(var t=0;t=0;--s){var l=Object.create(Object.prototype);l[r[s]]=c,c=l}a(c)}},n.setTenantTokens=a,n.getTenantTokens=function(e){var t=s(e),n=c(e);if(!n||!t)throw new Error("Could not find tenant token for "+e);return{ariaTenantToken:t,nexusTenantToken:n}},n.getAriaTenantToken=s,n.getNexusTenantToken=c,n.clear=function(){i={},r={},o={}}}(e.TenantTokenManager||(e.TenantTokenManager={}))}(oteljs||(oteljs={})),function(e){e.oteljsVersion="3.1.64"}(oteljs||(oteljs={})),function(e){!function(t){!function(t){!function(t){!function(t){t.getFields=function(t,n){var i=[];return void 0!==n.id&&i.push(e.makeStringDataField(t+".Id",n.id)),void 0!==n.version&&i.push(e.makeStringDataField(t+".Version",n.version)),void 0!==n.instanceId&&i.push(e.makeStringDataField(t+".InstanceId",n.instanceId)),void 0!==n.name&&i.push(e.makeStringDataField(t+".Name",n.name)),void 0!==n.marketplaceType&&i.push(e.makeStringDataField(t+".MarketplaceType",n.marketplaceType)),void 0!==n.sessionId&&i.push(e.makeStringDataField(t+".SessionId",n.sessionId)),void 0!==n.browserToken&&i.push(e.makeStringDataField(t+".BrowserToken",n.browserToken)),void 0!==n.osfRuntimeVersion&&i.push(e.makeStringDataField(t+".OsfRuntimeVersion",n.osfRuntimeVersion)),void 0!==n.officeJsVersion&&i.push(e.makeStringDataField(t+".OfficeJsVersion",n.officeJsVersion)),void 0!==n.hostJsVersion&&i.push(e.makeStringDataField(t+".HostJsVersion",n.hostJsVersion)),void 0!==n.assetId&&i.push(e.makeStringDataField(t+".AssetId",n.assetId)),void 0!==n.providerName&&i.push(e.makeStringDataField(t+".ProviderName",n.providerName)),void 0!==n.type&&i.push(e.makeStringDataField(t+".Type",n.type)),e.addContractField(i,t,"Office.System.SDX"),i}}(t.SDX||(t.SDX={}))}(t.System||(t.System={}))}(t.Office||(t.Office={}))}(e.Contracts||(e.Contracts={}))}(oteljs||(oteljs={})),OSF.InitializationHelper.prototype.prepareApiSurface=function(e){ +//var license = new OSF.DDA.License(appContext.get_eToken()); +// OSF._OfficeAppFactory.setContext(new OSF.DDA.OutlookContext(appContext, this._settings, license, appContext.appOM)); +// OSF._OfficeAppFactory.setContext(new OSF.DDA.OutlookContext(appContext, this._settings, license, appContext.appOM, OSF.DDA.OfficeTheme ? OSF.DDA.OfficeTheme.getOfficeTheme : null, appContext.ui)); +},OSF.DDA.SettingsManager={SerializedSettings:"serializedSettings",DateJSONPrefix:"Date(",DataJSONSuffix:")",serializeSettings:function(e){var t={};for(var n in e){var i=e[n];try{i=JSON?JSON.stringify(i,(function(e,t){return OSF.OUtil.isDate(this[e])?OSF.DDA.SettingsManager.DateJSONPrefix+this[e].getTime()+OSF.DDA.SettingsManager.DataJSONSuffix:t})):Sys.Serialization.JavaScriptSerializer.serialize(i),t[n]=i}catch(e){}}return t},deserializeSettings:function(e){var t={};for(var n in e=e||{}){var i=e[n];try{i=JSON?JSON.parse(i,(function(e,t){var n;return"string"==typeof t&&t&&t.length>6&&t.slice(0,5)===OSF.DDA.SettingsManager.DateJSONPrefix&&t.slice(-1)===OSF.DDA.SettingsManager.DataJSONSuffix&&(n=new Date(parseInt(t.slice(5,-1))))?n:t})):Sys.Serialization.JavaScriptSerializer.deserialize(i,!0),t[n]=i}catch(e){}}return t}},OSF.InitializationHelper.prototype.loadAppSpecificScriptAndCreateOM=function(e,t){var n="object"==typeof n?n:{};n.OutlookAppOm=function(e){var t={};function n(i){if(t[i])return t[i].exports;var r=t[i]={i:i,l:!1,exports:{}};return e[i].call(r.exports,r,r.exports,n),r.l=!0,r.exports}return n.m=e,n.c=t,n.d=function(e,t,i){n.o(e,t)||Object.defineProperty(e,t,{enumerable:!0,get:i})},n.r=function(e){"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})},n.t=function(e,t){if(1&t&&(e=n(e)),8&t)return e;if(4&t&&"object"==typeof e&&e&&e.__esModule)return e;var i=Object.create(null);if(n.r(i),Object.defineProperty(i,"default",{enumerable:!0,value:e}),2&t&&"string"!=typeof e)for(var r in e)n.d(i,r,function(t){return e[t]}.bind(null,r));return i},n.n=function(e){var t=e&&e.__esModule?function(){return e.default}:function(){return e};return n.d(t,"a",t),t},n.o=function(e,t){return Object.prototype.hasOwnProperty.call(e,t)},n.p="/",n(n.s=2)}([function(e,t){e.exports=OSF},function(e,t){e.exports=Microsoft},function(e,t,n){"use strict";function i(e){return null==e}n.r(t);var r,o="office_strings.js",a="office_strings.debug.js",s="outlook_strings.js",c=window;function l(e){return r[e]}var u,d="",f="",p=null,g=!1;function m(e){var t=document.createElement("script");return t.type="text/javascript",t.src=e,t}function h(){g=!0,i(u)||!i(p.readyState)&&(i(p.readyState)||"loaded"!==p.readyState&&"complete"!==p.readyState)||(p.onload=null,p.onreadystatechange=null,void 0!==c._u&&(r=c._u.ExtensibilityStrings),u())}function y(){if(!g){var e=document.getElementsByTagName("head")[0],t=f+"en-us/"+s;p.onload=null,p.onreadystatechange=null,(p=m(t)).onload=h,p.onreadystatechange=h,e.appendChild(p)}}function v(e,t,n){var i=n.substring(0,t),r=i.lastIndexOf("/",i.length-2);return-1===r&&(r=i.lastIndexOf("\\",i.length-2)),-1!==r&&i.length>r+1&&(e=i.substring(0,r+1)),e}var S,A=function(e){switch(e){case 402:case 401:case 400:case 403:return!0;default:return!1}};!function(e){e[e.noError=0]="noError",e[e.errorInRequest=-1]="errorInRequest",e[e.errorHandlingRequest=-2]="errorHandlingRequest",e[e.errorInResponse=-3]="errorInResponse",e[e.errorHandlingResponse=-4]="errorHandlingResponse",e[e.errorHandlingRequestAccessDenied=-5]="errorHandlingRequestAccessDenied",e[e.errorHandlingMethodCallTimedout=-6]="errorHandlingMethodCallTimedout"}(S||(S={}));var _=n(0),T=!1;function b(e){return T||(O(9e3,"AttachmentSizeExceeded",l("l_AttachmentExceededSize_Text")),O(9001,"NumberOfAttachmentsExceeded",l("l_ExceededMaxNumberOfAttachments_Text")),O(9002,"InternalFormatError",l("l_InternalFormatError_Text")),O(9003,"InvalidAttachmentId",l("l_InvalidAttachmentId_Text")),O(9004,"InvalidAttachmentPath",l("l_InvalidAttachmentPath_Text")),O(9005,"CannotAddAttachmentBeforeUpgrade",l("l_CannotAddAttachmentBeforeUpgrade_Text")),O(9006,"AttachmentDeletedBeforeUploadCompletes",l("l_AttachmentDeletedBeforeUploadCompletes_Text")),O(9007,"AttachmentUploadGeneralFailure",l("l_AttachmentUploadGeneralFailure_Text")),O(9008,"AttachmentToDeleteDoesNotExist",l("l_DeleteAttachmentDoesNotExist_Text")),O(9009,"AttachmentDeleteGeneralFailure",l("l_AttachmentDeleteGeneralFailure_Text")),O(9010,"InvalidEndTime",l("l_InvalidEndTime_Text")),O(9011,"HtmlSanitizationFailure",l("l_HtmlSanitizationFailure_Text")),O(9012,"NumberOfRecipientsExceeded",l("l_NumberOfRecipientsExceeded_Text").replace("{0}",500)),O(9013,"NoValidRecipientsProvided",l("l_NoValidRecipientsProvided_Text")),O(9014,"CursorPositionChanged",l("l_CursorPositionChanged_Text")),O(9016,"InvalidSelection",l("l_InvalidSelection_Text")),O(9017,"AccessRestricted",""),O(9018,"GenericTokenError",""),O(9019,"GenericSettingsError",""),O(9020,"GenericResponseError",""),O(9021,"SaveError",l("l_SaveError_Text")),O(9022,"MessageInDifferentStoreError",l("l_MessageInDifferentStoreError_Text")),O(9023,"DuplicateNotificationKey",l("l_DuplicateNotificationKey_Text")),O(9024,"NotificationKeyNotFound",l("l_NotificationKeyNotFound_Text")),O(9025,"NumberOfNotificationsExceeded",l("l_NumberOfNotificationsExceeded_Text")),O(9026,"PersistedNotificationArrayReadError",l("l_PersistedNotificationArrayReadError_Text")),O(9027,"PersistedNotificationArraySaveError",l("l_PersistedNotificationArraySaveError_Text")),O(9028,"CannotPersistPropertyInUnsavedDraftError",l("l_CannotPersistPropertyInUnsavedDraftError_Text")),O(9029,"CanOnlyGetTokenForSavedItem",l("l_CallSaveAsyncBeforeToken_Text")),O(9030,"APICallFailedDueToItemChange",l("l_APICallFailedDueToItemChange_Text")),O(9031,"InvalidParameterValueError",l("l_InvalidParameterValueError_Text")),O(9032,"ApiCallNotSupportedByExtensionPoint",l("l_API_Not_Supported_By_ExtensionPoint_Error_Text")),O(9033,"SetRecurrenceOnInstanceError",l("l_Recurrence_Error_Instance_SetAsync_Text")),O(9034,"InvalidRecurrenceError",l("l_Recurrence_Error_Properties_Invalid_Text")),O(9035,"RecurrenceZeroOccurrences",l("l_RecurrenceErrorZeroOccurrences_Text")),O(9036,"RecurrenceMaxOccurrences",l("l_RecurrenceErrorMaxOccurrences_Text")),O(9037,"RecurrenceInvalidTimeZone",l("l_RecurrenceInvalidTimeZone_Text")),O(9038,"InsufficientItemPermissionsError",l("l_Insufficient_Item_Permissions_Text")),O(9039,"RecurrenceUnsupportedAlternateCalendar",l("l_RecurrenceUnsupportedAlternateCalendar_Text")),O(9040,"HTTPRequestFailure",l("l_Olk_Http_Error_Text")),O(9041,"NetworkError",l("l_Internet_Not_Connected_Error_Text")),O(9042,"InternalServerError",l("l_Internal_Server_Error_Text")),O(9043,"AttachmentTypeNotSupported",l("l_AttachmentNotSupported_Text")),O(9044,"InvalidCategory",l("l_Invalid_Category_Error_Text")),O(9045,"DuplicateCategory",l("l_Duplicate_Category_Error_Text")),O(9046,"ItemNotSaved",l("l_Item_Not_Saved_Error_Text")),O(9047,"MissingExtendedPermissionsForAPIError",l("l_Missing_Extended_Permissions_For_API")),O(9048,"TokenAccessDenied",l("l_TokenAccessDeniedWithoutItemContext_Text")),O(9049,"ItemNotFound",l("l_ItemNotFound_Text")),O(9050,"KeyNotFound",l("l_KeyNotFound_Text")),O(9051,"SessionObjectMaxLengthExceeded",l("l_SessionDataObjectMaxLengthExceeded_Text").replace("{0}",5e4)),O(9052,"AttachmentResourceNotFound",l("l_Attachment_Resource_Not_Found")),O(9053,"AttachmentResourceUnAuthorizedAccess",l("l_Attachment_Resource_UnAuthorizedAccess")),O(9054,"AttachmentDownloadFailed",l("l_Attachment_Download_Failed_Generic_Error")),O(9055,"APINotSupportedForSharedFolders",l("l_API_Not_Supported_For_Shared_Folders_Error")),T=!0),_.DDA.ErrorCodeManager.getErrorArgs(e)}var w;function O(e,t,n){_.DDA.ErrorCodeManager.addErrorMessage(e,{name:t,message:n})}var C=function(){return w},E=function(e){return(w=new I).parameterBlobSupported=!0,w},I=function(){function e(){this._parameterBlobSupported=!0,this._itemNumber=0,w=this}return Object.defineProperty(e.prototype,"parameterBlobSupported",{set:function(e){this._parameterBlobSupported=e},enumerable:!0,configurable:!0}),e.prototype.setActionsDefinition=function(e){this._actionsDefinition=e},e.prototype.setCurrentItemNumber=function(e){e>0&&(this._itemNumber=e)},Object.defineProperty(e.prototype,"itemNumber",{get:function(){return this._itemNumber},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"actionsDefinition",{get:function(){return this._actionsDefinition},enumerable:!0,configurable:!0}),e.prototype.updateOutlookExecuteParameters=function(e,t){var n=e;if(this._parameterBlobSupported){if(this._itemNumber>0&&(t.itemNumber=this._itemNumber.toString()),null!=this._actionsDefinition&&(t.actions=this.actionsDefinition),0===Object.keys(t).length)return n;null==n&&(n=[]),n.push(JSON.stringify(t))}return n},e}(),k=(n(0),function(e,t){var n=null,i={};switch(e){case 12:i.isRest=t.isRest;break;case 4:n=[JSON.stringify(t.customProperties)];break;case 5:n=new Array(t.body);break;case 8:case 9:case 179:case 180:n=new Array(t.itemId);break;case 7:case 177:n=new Array(D(t.requiredAttendees),D(t.optionalAttendees),t.start,t.end,t.location,D(t.resources),t.subject,t.body);break;case 44:case 178:n=[D(t.toRecipients),D(t.ccRecipients),D(t.bccRecipients),t.subject,t.htmlBody,t.attachments];break;case 43:n=[t.ewsIdOrEmail];break;case 45:n=[t.module,t.queryString];break;case 40:n=[t.extensionId,t.consentState];break;case 11:case 10:case 184:case 183:n=[t.htmlBody];break;case 31:case 30:case 182:case 181:n=[t.htmlBody,t.attachments];break;case 23:case 13:case 38:case 29:n=[t.data,t.coercionType];break;case 37:case 28:n=[t.coercionType];break;case 17:n=[t.subject];break;case 15:n=[t.recipientField];break;case 22:case 21:n=[t.recipientField,x(t.recipientArray)];break;case 19:n=[t.itemId,t.name];break;case 16:n=[t.uri,t.name,t.isInline];break;case 148:n=[t.base64String,t.name,t.isInline];break;case 20:n=[t.attachmentIndex];break;case 25:n=[t.TimeProperty,t.time];break;case 24:n=[t.TimeProperty];break;case 27:n=[t.location];break;case 33:case 35:n=[t.key,t.type,t.persistent,t.message,t.icon],C().setActionsDefinition(t.actions);break;case 36:n=[t.key];break;default:i=t||{}}return 1!==e&&(n=C().updateOutlookExecuteParameters(n,i)),n}),D=function(e){return null!=e?e.join(";"):""},x=function(e){var t=[];if(null==e)return t;for(var n=0;n2){var n=JSON.parse(e[2]);n&&"object"==typeof n&&(t=n.itemNumber)}return t},F=function(e,t){var n=null,i=JSON.parse(e[0]);if("number"==typeof i)n=N(e,t);else{if(!i||"object"!=typeof i)throw new Error("Return data type from host must be Object or Number");n=P(e,t)}return n},P=function(e,t){var n=JSON.parse(e[0]);if(t)n.error=!0,n.errorCode=9030;else if(e.length>1&&0!==e[1]){if(n.error=!0,n.errorCode=e[1],e.length>2){var i=JSON.parse(e[2]);n.diagnostics=i.Diagnostics}}else n.error=!1;return n},N=function(e,t){var n={error:!0};return n.errorCode=e[0],n},H=n(0);function R(e,t,n,i,r,o){W(e,i,(function(e,i){if(n){var a=void 0,s=!0;if("object"==typeof i&&null!==i){if(void 0!==i.wasSuccessful&&(s=i.wasSuccessful),void 0!==i.error||void 0!==i.errorCode||void 0!==i.data)if(i.error){var c=i.errorCode;a=U(void 0,H.DDA.AsyncResultEnum.ErrorCode.Failed,c,t)}else{a=U(r?r(i.data):i.data,H.DDA.AsyncResultEnum.ErrorCode.Success,0,t)}if(o&&(a=o(i,t,e)),a||e===S.noError||(a=U(void 0,H.DDA.AsyncResultEnum.ErrorCode.Failed,9002,t)),a||e!==S.noError||!1!==s||(a=U(void 0,H.DDA.AsyncResultEnum.ErrorCode.Failed,H.DDA.ErrorCodeManager.errorCodes.ooeOperationNotSupported,t)),!a&&!o&&!i.errorCode&&!0===s)a=U(r?r(i.data):i.data,H.DDA.AsyncResultEnum.ErrorCode.Success,0,t);n(a)}}}))}function U(e,t,n,i,r){var o,a={};if(a[H.DDA.AsyncResultEnum.Properties.Value]=e,a[H.DDA.AsyncResultEnum.Properties.Context]=i,H.DDA.AsyncResultEnum.ErrorCode.Success!==t){o={};var s=b(n);o[H.DDA.AsyncResultEnum.ErrorProperties.Name]=s.name,o[H.DDA.AsyncResultEnum.ErrorProperties.Message]=r||s.message,o[H.DDA.AsyncResultEnum.ErrorProperties.Code]=n}return new H.DDA.AsyncResult(a,o)}var L,W=function(e,t,n){if(H.AppName.OutlookWebApp!==ko()&&A(e))n(S.errorHandlingRequest,null);else{var i={toSafeArrayHost:function(){return k(e,t)},fromSafeArrayHost:function(e){return e},toWebHost:function(){return t},fromWebHost:function(e){return e}};H._OfficeAppFactory.getAsyncMethodExecutor().executeAsync(e,i,(function(t,i){var r=performance&&performance.now();if(H.AppTelemetry){var o=function(e,t){return e}(t),a=performance&&performance.now();H.AppTelemetry.onMethodDone(e,null,Math.round(a-r),o)}if(n){var s=i;if(H.AppName.OutlookWebApp!==ko()&&!A(e)&&i.length>0){var c=M(i),l=c>0,u=0;C()&&(u=C().itemNumber),s=F(i,l&&u>0&&c>u)}n(t,s)}}))}},j=function(){var e=Eo("permissionLevel");return i(e)?-1:e};function V(e,t){var n=new Error(e);if(n.message=e||"",t)for(var i in t)n[i]=t[i];return n}function z(e,t){var n="Sys.ArgumentException: "+(t||"Value does not fall within the expected range.");return e&&(n+="\n"+"Parameter name: {0}".replace("{0}",e)),V(n,{name:"Sys.ArgumentException",paramName:e})}function J(e,t){var n="Sys.ArgumentNullException: "+(t||"Value cannot be null.");return e&&(n+="\n"+"Parameter name: {0}".replace("{0}",e)),V(n,{name:"Sys.ArgumentNullException",paramName:e})}function G(e,t,n){var i="Sys.ArgumentOutOfRangeException: "+(n||"Specified argument was out of the range of valid values.");return e&&(i+="\n"+"Parameter name: {0}".replace("{0}",e)),null!=t&&(i+="\n"+"Actual value was {0}.".replace("{0}",t)),V(i,{name:"Sys.ArgumentOutOfRangeException",paramName:e,actualValue:t})}function B(e,t,n,i){var r="Sys.ArgumentTypeException: ";return r+=i||(t&&n?"Object of type '{0}' cannot be converted to type '{1}'.".replace("{0}",t.getName?t.getName():t).replace("{1}",n.getName?n.getName():n):"Object cannot be converted to the required type."),e&&(r+="\n"+"Parameter name: {0}".replace("{0}",e)),V(r,{name:"Sys.ArgumentTypeException",paramName:e,actualType:t,expectedType:n})}function q(e,t){if(-1==j())throw function(e){return V("Invalid operation ({0}) when Office.context.mailbox.item is null.".replace("{0}",e))}(t);if(j()n)throw G(String(i))}var Q={EntityType:{MeetingSuggestion:"meetingSuggestion",TaskSuggestion:"taskSuggestion",Address:"address",EmailAddress:"emailAddress",Url:"url",PhoneNumber:"phoneNumber",Contact:"contact",FlightReservations:"flightReservations",ParcelDeliveries:"parcelDeliveries"},ItemType:{Message:"message",Appointment:"appointment"},ResponseType:{None:"none",Organizer:"organizer",Tentative:"tentative",Accepted:"accepted",Declined:"declined"},RecipientType:{Other:"other",DistributionList:"distributionList",User:"user",ExternalUser:"externalUser"},AttachmentType:{File:"file",Item:"item",Cloud:"cloud"},AttachmentStatus:{Added:"added",Removed:"removed"},AttachmentContentFormat:{Base64:"base64",Url:"url",Eml:"eml",ICalendar:"iCalendar"},BodyType:{Text:"text",Html:"html"},ItemNotificationMessageType:{ProgressIndicator:"progressIndicator",InformationalMessage:"informationalMessage",ErrorMessage:"errorMessage",InsightMessage:"insightMessage"},Folder:{Inbox:"inbox",Junk:"junk",DeletedItems:"deletedItems"},ComposeType:{Forward:"forward",NewMail:"newMail",Reply:"reply"}},ee={Text:"text",Html:"html"};function te(e){if(null==e)throw J(e);if(e!==Q.RestVersion.v1_0&&e!==Q.RestVersion.v2_0&&e!==Q.RestVersion.Beta)throw z(e)}function ne(e,t){if(null==e)throw J(e);return te(t),e.replace(new RegExp("[/]","g"),"-").replace(new RegExp("[+]","g"),"_")}function ie(e,t){if(null==e)throw J(e);return te(t),e.replace(new RegExp("[-]","g"),"/").replace(new RegExp("[_]","g"),"+")}function re(e,t){if(!Array.isArray(e))throw B("name");Z(e.length,0,100,"{0}.length".replace("{0}",t))}function oe(e,t){for(var n=e,i=[],r=0;r255)throw G("displayName");if(!i(e.emailAddress)&&"string"==typeof e.emailAddress&&e.emailAddress.length>571)throw G("emailAddress");if(!i(e.appointmentResponse)&&"string"!=typeof e.appointmentResponse)throw G("appointmentResponse");if(!i(e.recipientType)&&"string"!=typeof e.recipientType)throw G("recipientType")}function se(e){if("string"!=typeof e)throw B("itemId");!function(e){if(i(e)||""===e)throw J("itemId")}(e)}function ce(e){return Eo("isRestIdSupported")?ne(e,Q.RestVersion.v1_0):ie(e,Q.RestVersion.v1_0)}Q.UserProfileType={Office365:"office365",OutlookCom:"outlookCom",Enterprise:"enterprise"},Q.RestVersion={v1_0:"v1.0",v2_0:"v2.0",Beta:"beta"},Q.ModuleType={Addins:"addins"},Q.ActionType={ShowTaskPane:"showTaskPane"},Q.Days={Mon:"mon",Tue:"tue",Wed:"wed",Thu:"thu",Fri:"fri",Sat:"sat",Sun:"sun",Weekday:"weekday",WeekendDay:"weekendDay",Day:"day"},Q.WeekNumber={First:"first",Second:"second",Third:"third",Fourth:"fourth",Last:"last"},Q.RecurrenceType={Daily:"daily",Weekday:"weekday",Weekly:"weekly",Monthly:"monthly",Yearly:"yearly"},Q.Month={Jan:"jan",Feb:"feb",Mar:"mar",Apr:"apr",May:"may",Jun:"jun",Jul:"jul",Aug:"aug",Sep:"sep",Oct:"oct",Nov:"nov",Dec:"dec"},Q.DelegatePermissions={Read:1,Write:2,DeleteOwn:4,DeleteAll:8,EditOwn:16,EditAll:32},Q.TimeZone={AfghanistanStandardTime:"Afghanistan Standard Time",AlaskanStandardTime:"Alaskan Standard Time",AleutianStandardTime:"Aleutian Standard Time",AltaiStandardTime:"Altai Standard Time",ArabStandardTime:"Arab Standard Time",ArabianStandardTime:"Arabian Standard Time",ArabicStandardTime:"Arabic Standard Time",ArgentinaStandardTime:"Argentina Standard Time",AstrakhanStandardTime:"Astrakhan Standard Time",AtlanticStandardTime:"Atlantic Standard Time",AUSCentralStandardTime:"AUS Central Standard Time",AusCentralWStandardTime:"Aus Central W. Standard Time",AUSEasternStandardTime:"AUS Eastern Standard Time",AzerbaijanStandardTime:"Azerbaijan Standard Time",AzoresStandardTime:"Azores Standard Time",BahiaStandardTime:"Bahia Standard Time",BangladeshStandardTime:"Bangladesh Standard Time",BelarusStandardTime:"Belarus Standard Time",BougainvilleStandardTime:"Bougainville Standard Time",CanadaCentralStandardTime:"Canada Central Standard Time",CapeVerdeStandardTime:"Cape Verde Standard Time",CaucasusStandardTime:"Caucasus Standard Time",CenAustraliaStandardTime:"Cen. Australia Standard Time",CentralAmericaStandardTime:"Central America Standard Time",CentralAsiaStandardTime:"Central Asia Standard Time",CentralBrazilianStandardTime:"Central Brazilian Standard Time",CentralEuropeStandardTime:"Central Europe Standard Time",CentralEuropeanStandardTime:"Central European Standard Time",CentralPacificStandardTime:"Central Pacific Standard Time",CentralStandardTime:"Central Standard Time",CentralStandardTime_Mexico:"Central Standard Time (Mexico)",ChathamIslandsStandardTime:"Chatham Islands Standard Time",ChinaStandardTime:"China Standard Time",CubaStandardTime:"Cuba Standard Time",DatelineStandardTime:"Dateline Standard Time",EAfricaStandardTime:"E. Africa Standard Time",EAustraliaStandardTime:"E. Australia Standard Time",EEuropeStandardTime:"E. Europe Standard Time",ESouthAmericaStandardTime:"E. South America Standard Time",EasterIslandStandardTime:"Easter Island Standard Time",EasternStandardTime:"Eastern Standard Time",EasternStandardTime_Mexico:"Eastern Standard Time (Mexico)",EgyptStandardTime:"Egypt Standard Time",EkaterinburgStandardTime:"Ekaterinburg Standard Time",FijiStandardTime:"Fiji Standard Time",FLEStandardTime:"FLE Standard Time",GeorgianStandardTime:"Georgian Standard Time",GMTStandardTime:"GMT Standard Time",GreenlandStandardTime:"Greenland Standard Time",GreenwichStandardTime:"Greenwich Standard Time",GTBStandardTime:"GTB Standard Time",HaitiStandardTime:"Haiti Standard Time",HawaiianStandardTime:"Hawaiian Standard Time",IndiaStandardTime:"India Standard Time",IranStandardTime:"Iran Standard Time",IsraelStandardTime:"Israel Standard Time",JordanStandardTime:"Jordan Standard Time",KaliningradStandardTime:"Kaliningrad Standard Time",KamchatkaStandardTime:"Kamchatka Standard Time",KoreaStandardTime:"Korea Standard Time",LibyaStandardTime:"Libya Standard Time",LineIslandsStandardTime:"Line Islands Standard Time",LordHoweStandardTime:"Lord Howe Standard Time",MagadanStandardTime:"Magadan Standard Time",MagallanesStandardTime:"Magallanes Standard Time",MarquesasStandardTime:"Marquesas Standard Time",MauritiusStandardTime:"Mauritius Standard Time",MidAtlanticStandardTime:"Mid-Atlantic Standard Time",MiddleEastStandardTime:"Middle East Standard Time",MontevideoStandardTime:"Montevideo Standard Time",MoroccoStandardTime:"Morocco Standard Time",MountainStandardTime:"Mountain Standard Time",MountainStandardTime_Mexico:"Mountain Standard Time (Mexico)",MyanmarStandardTime:"Myanmar Standard Time",NCentralAsiaStandardTime:"N. Central Asia Standard Time",NamibiaStandardTime:"Namibia Standard Time",NepalStandardTime:"Nepal Standard Time",NewZealandStandardTime:"New Zealand Standard Time",NewfoundlandStandardTime:"Newfoundland Standard Time",NorfolkStandardTime:"Norfolk Standard Time",NorthAsiaEastStandardTime:"North Asia East Standard Time",NorthAsiaStandardTime:"North Asia Standard Time",NorthKoreaStandardTime:"North Korea Standard Time",OmskStandardTime:"Omsk Standard Time",PacificSAStandardTime:"Pacific SA Standard Time",PacificStandardTime:"Pacific Standard Time",PacificStandardTime_Mexico:"Pacific Standard Time (Mexico)",PakistanStandardTime:"Pakistan Standard Time",ParaguayStandardTime:"Paraguay Standard Time",RomanceStandardTime:"Romance Standard Time",RussiaTimeZone10:"Russia Time Zone 10",RussiaTimeZone11:"Russia Time Zone 11",RussiaTimeZone3:"Russia Time Zone 3",RussianStandardTime:"Russian Standard Time",SAEasternStandardTime:"SA Eastern Standard Time",SAPacificStandardTime:"SA Pacific Standard Time",SAWesternStandardTime:"SA Western Standard Time",SaintPierreStandardTime:"Saint Pierre Standard Time",SakhalinStandardTime:"Sakhalin Standard Time",SamoaStandardTime:"Samoa Standard Time",SaratovStandardTime:"Saratov Standard Time",SEAsiaStandardTime:"SE Asia Standard Time",SingaporeStandardTime:"Singapore Standard Time",SouthAfricaStandardTime:"South Africa Standard Time",SriLankaStandardTime:"Sri Lanka Standard Time",SudanStandardTime:"Sudan Standard Time",SyriaStandardTime:"Syria Standard Time",TaipeiStandardTime:"Taipei Standard Time",TasmaniaStandardTime:"Tasmania Standard Time",TocantinsStandardTime:"Tocantins Standard Time",TokyoStandardTime:"Tokyo Standard Time",TomskStandardTime:"Tomsk Standard Time",TongaStandardTime:"Tonga Standard Time",TransbaikalStandardTime:"Transbaikal Standard Time",TurkeyStandardTime:"Turkey Standard Time",TurksAndCaicosStandardTime:"Turks And Caicos Standard Time",UlaanbaatarStandardTime:"Ulaanbaatar Standard Time",USEasternStandardTime:"US Eastern Standard Time",USMountainStandardTime:"US Mountain Standard Time",UTC:"UTC",UTCPLUS12:"UTC+12",UTCPLUS13:"UTC+13",UTCMINUS02:"UTC-02",UTCMINUS08:"UTC-08",UTCMINUS09:"UTC-09",UTCMINUS11:"UTC-11",VenezuelaStandardTime:"Venezuela Standard Time",VladivostokStandardTime:"Vladivostok Standard Time",WAustraliaStandardTime:"W. Australia Standard Time",WCentralAfricaStandardTime:"W. Central Africa Standard Time",WEuropeStandardTime:"W. Europe Standard Time",WMongoliaStandardTime:"W. Mongolia Standard Time",WestAsiaStandardTime:"West Asia Standard Time",WestBankStandardTime:"West Bank Standard Time",WestPacificStandardTime:"West Pacific Standard Time",YakutskStandardTime:"Yakutsk Standard Time"},Q.LocationType={Custom:"custom",Room:"room"},Q.AppointmentSensitivityType={Normal:"normal",Personal:"personal",Private:"private",Confidential:"confidential"},Q.CategoryColor={None:"None",Preset0:"Preset0",Preset1:"Preset1",Preset2:"Preset2",Preset3:"Preset3",Preset4:"Preset4",Preset5:"Preset5",Preset6:"Preset6",Preset7:"Preset7",Preset8:"Preset8",Preset9:"Preset9",Preset10:"Preset10",Preset11:"Preset11",Preset12:"Preset12",Preset13:"Preset13",Preset14:"Preset14",Preset15:"Preset15",Preset16:"Preset16",Preset17:"Preset17",Preset18:"Preset18",Preset19:"Preset19",Preset20:"Preset20",Preset21:"Preset21",Preset22:"Preset22",Preset23:"Preset23",Preset24:"Preset24"};var le=1,ue=1,de=2,fe=2,pe=2,ge=2;function me(e){return e<=1}function he(e,t){if(!me(e))throw function(e){return V("The feature {0}, is only enabled on the beta api endpoint".replace("{0}",e),{name:"Sys.FeatureNotEnabled"})}(t)}var ye=function(){for(var e=0,t=0,n=arguments.length;tK)throw G("attachments",e.length,l("l_AttachmentUrlTooLong_Text"));Ge(t)}(n,i),t=[Q.AttachmentType.File,i,n,r]}else{if(e.type!==Q.AttachmentType.Item)throw z("attachments");var o=ce(e.itemId),a=e.name;!function(e,t){if("string"!=typeof e||"string"!=typeof t)throw z("attachments");if(e.length>200)throw G("attachments",e.length,l("l_AttachmentItemIdTooLong_Text"));Ge(t)}(o,a),t=[Q.AttachmentType.Item,a,o]}return t}function Ge(e){if(e.length>255)throw G("attachments",e.length,l("l_AttachmentNameTooLong_Text"))}var Be=n(0);function qe(e,t,n){var i=void 0;return n&&n!==S.noError?(i=U(void 0,Be.DDA.AsyncResultEnum.ErrorCode.Failed,9017,t,l("l_InternalProtocolError_Text").replace("{0}",n)))&&(i.diagnostics={InvokeCodeResult:n}):(i=ko()===Be.AppName.Outlook&&void 0!==e.error&&void 0!==e.errorCode&&e.error&&9030===e.errorCode?U(void 0,Be.DDA.AsyncResultEnum.ErrorCode.Failed,e.errorCode,t,e.errorMessage):e.wasSuccessful?U(e.token,Be.DDA.AsyncResultEnum.ErrorCode.Success,0,t):U(void 0,Be.DDA.AsyncResultEnum.ErrorCode.Failed,e.errorCode,t,e.errorMessage),e.diagnostics&&(i.diagnostics=e.diagnostics)),i}function Ye(){for(var e=[],t=0;tKe)throw z("data",l("l_EwsRequestOversized_Text"));R(5,i.asyncContext,i.callback,{body:e},void 0,Qe)}function Qe(e,t,n){return n&&n!==S.noError?U(void 0,$e.DDA.AsyncResultEnum.ErrorCode.Failed,9017,t,l("l_InternalProtocolError_Text").replace("{0}",n)):!1===e.wasProxySuccessful?U(void 0,$e.DDA.AsyncResultEnum.ErrorCode.Failed,9020,t,e.errorMessage):U(e.body,$e.DDA.AsyncResultEnum.ErrorCode.Success,0,t)}var et=function(e,t){var n=Object.keys(t),i=n.map((function(e){return{value:t[e],writable:!1}})),r={};return n.forEach((function(e,t){r[e]=i[t]})),Object.defineProperties(e,r)},tt=n(0),nt=function(){switch(ko()){case tt.AppName.Outlook:return"Outlook";case tt.AppName.OutlookWebApp:return"OutlookWebApp";case tt.AppName.OutlookIOS:return"OutlookIOS";case tt.AppName.OutlookAndroid:return"OutlookAndroid";default:return}};var it=Q.CategoryColor,rt=[it.None,it.Preset0,it.Preset1,it.Preset2,it.Preset3,it.Preset4,it.Preset5,it.Preset6,it.Preset7,it.Preset8,it.Preset9,it.Preset10,it.Preset11,it.Preset12,it.Preset13,it.Preset14,it.Preset15,it.Preset16,it.Preset17,it.Preset18,it.Preset19,it.Preset20,it.Preset21,it.Preset22,it.Preset23,it.Preset24];function ot(e){if(!e)throw z("categoryDetails");if(!Array.isArray(e))throw B("categoryDetails",typeof e,typeof[]);if(0===e.length)throw z("categoryDetails");e.forEach(at)}function at(e){if(!e)throw z("categoryDetails");if(!e.color||!e.displayName)throw z("categoryDetails");if("string"!=typeof e.color)throw B("categoryDetails.color",typeof e.color,"string");if("string"!=typeof e.displayName)throw B("categoryDetails.displayName",typeof e.displayName,"string");if(e.displayName.length>255)throw G("categoryDetails.displayName",e.displayName.length);if(-1===rt.indexOf(e.color))throw z("categoryDetails.color")}function st(e){for(var t=[],n=1;n255)throw G("categories",e.length)}function dt(e){for(var t=[],n=1;n2500)throw G("customProperties")}!function(e){e[e.NonTransmittable=0]="NonTransmittable"}(ht||(ht={}));var At=function(){for(var e=0,t=0,n=arguments.length;tht.NonTransmittable))throw z("data");e=t[ht.NonTransmittable]}else this.rawData=e}return e.prototype.get=function(e){var t=this.rawData[e];if("string"==typeof t){var n=t;if(n.length>yt.length+")".length&&n.startsWith(yt)&&n.endsWith(")")){var r=n.substring(yt.length,n.length-1),o=parseInt(r);if(!isNaN(o)){var a=new Date(o);i(a)||(t=a)}}}return t},e.prototype.set=function(e,t){Ie(t)&&(t=yt+t.getTime()+")"),this.rawData[e]=t},e.prototype.remove=function(e){delete this.rawData[e]},e.prototype.saveAsync=function(){for(var e=[],t=0;t5e3)throw G("data",e.appendTxt.length)}function Pt(e){if("string"!=typeof e.data)throw B("data",typeof e.data,"string");if(e.data.length>1e6)throw G("data",e.data.length)}function Nt(e){if("string"!=typeof e.data)throw B("data",typeof e.data,"string");if(e.data.length>3e4)throw G("data",e.data.length)}function Ht(e){for(var t=[],n=1;n32)throw G("key",e.length)}function Qt(e){if(zt("type",e.type),e.type===Q.ItemNotificationMessageType.InformationalMessage){if(zt(Jt,e.icon),e.icon.length>32)throw G(Jt,e.icon.length);if(i(e.persistent))throw J(Bt);if("boolean"!=typeof e.persistent)throw B(Bt,typeof e.persistent,"boolean");if(!i(e.actions))throw z(qt,l("l_ActionsDefinitionWrongNotificationMessageError_Text"))}else if(e.type===Q.ItemNotificationMessageType.InsightMessage)!function(e){if(zt(Jt,e.icon),e.icon.length>32)throw G(Jt,e.icon.length);if(!i(e.persistent))throw z(Bt);if(i(e.actions))throw J(qt);!function(e){var t=function(e){var t=null;if(!Array.isArray(e))throw z(qt);if(1===e.length)t=e[0];else if(e.length>1)throw z(qt,l("l_ActionsDefinitionMultipleActionsError_Text"));return t}(e);if(i(t))return;(function(e){if(i(e.actionType))throw J(Yt);if(Kt!==e.actionType)throw z(Yt,l("l_InvalidActionType_Text"));if(i(e.commandId)||"string"!=typeof e.commandId||""===e.commandId)throw z($t,l("l_InvalidCommandIdError_Text"))})(t),function(e){if(i(e.actionText)||""===e.actionText||"string"!=typeof e.actionText)throw J(Xt);if(e.actionText.length>30)throw G(Xt,e.actionText.length)}(t)}(e.actions)}(e);else{if(!i(e.icon))throw z(Jt);if(!i(e.persistent))throw z(Bt);if(!i(e.actions))throw z(qt,l("l_ActionsDefinitionWrongNotificationMessageError_Text"))}if(zt(Gt,e.message),e.message.length>150)throw G(Gt,e.message.length)}function en(e,t){for(var n=[],r=2;r=0;n--){for(var i=!1,r=n-1;r>=0;r--)if(t(e[n],e[r])){i=!0;break}i&&e.splice(n,1)}return e}var Hn=function(e,t){return e===t},Rn=function(e,t){return e===t||!(!e||!t)&&e.meetingString===t.meetingString},Un=function(e,t){return e===t||!(!e||!t)&&e.taskString===t.taskString},Ln=function(e,t){return e===t||!(!e||!t)&&e.contactString===t.contactString};function Wn(){return!!Eo("entities")&&void 0!==Eo("entities").IsLegacyExtraction&&Eo("entities").IsLegacyExtraction}var jn,Vn=864e5,zn=new Date("0001-01-01T00:00:00Z");function Jn(e,t){if(!t)return e;var n=null;try{var r=new Date(t.getFullYear(),t.getMonth(),t.getDate(),0,0,0,0),o=function(e){var t=32767,n=0;if(null==e)return;n=Wn()?Bn(e):Gn(e);var i=(e.getTime()-n-zn.getTime())/Vn;if(i<0)return;if(i>=262144)return;var r=i>>15;switch(i&=t,r){case 0:return function(e){var t=15,n=31,i=127,r=0,o=0,a=0,s=e>>12&7;if(4==(4&s)){if(r=e>>5&i,2==(2&s)){if(1==(1&s))return;o=e>>1&t}}else 2==(2&s)&&(o=e>>8&t),1==(1&s)&&(a=e>>3&n);return function(e,t,n){return{day:e,month:t,year:n%100}}(a,o,r)}(i);case 1:return function(e){var t=7,n=3,i=15&e,r=function(e,t){var n=1<>=4),6),o=(e>>=6)&t,a=(e>>=3)&n;try{return function(e,t,n,i){return{modifier:e,offset:t,unit:n,tag:i}}(a,r,o,i)}catch(e){return}}(i);default:return}}(e);if(!o)return e;var a=o;if(a.day&&a.month&&void 0!==a.year)n=function(e,t){var n,r=t.year,o=0==t.month?e.getMonth():t.month-1,a=t.day;if(0==a)return e;i(r)?(n=new Date(e.getFullYear(),o,a)).getTime()-5&&t<5){var i=7*t+((n+6)%7+1-e.getDay());return e.setDate(e.getDate()+i),e}return(i=(n-e.getDay())%7)<0&&(i+=7),e.setDate(e.getDate()+i),e}(e,t.offset,t.tag);case 2:var i=1;switch(t.modifier){case 1:break;case 2:i=16;break;default:0==t.offset&&(i=e.getDate())}return(n=new Date(e.getFullYear(),e.getMonth(),i)).setMonth(n.getMonth()+t.offset),n.getTime()12||t.offset<=0||t.offset>5)return e;var o=(12+t.tag-n.getMonth()-1)%12;if(i=new Date(n.getFullYear(),n.getMonth()+o,1),1==t.modifier)return 1==t.offset&&6!=i.getDay()&&0!=i.getDay()?i:((r=new Date(i.getFullYear(),i.getMonth(),i.getDate())).setDate(r.getDate()+(1-i.getDay()+7)%7),6!=i.getDay()&&0!=i.getDay()&&1!=i.getDay()&&r.setDate(r.getDate()-7),r.setDate(r.getDate()+7*(t.offset-1)),r.getMonth()+1!=t.tag?e:r);var a=1-(r=new Date(i.getFullYear(),i.getMonth(),(s=i.getMonth(),c=i.getFullYear(),32-new Date(c,s,32).getDate()))).getDay();return a>0&&(a-=7),r.setDate(r.getDate()+a),r.setDate(r.getDate()+7*(1-t.offset)),r.getMonth()+1!=t.tag?6!=i.getDay()&&0!=i.getDay()?i:e:r;var s,c}(e,t);case 3:if(t.offset>0)return new Date(e.getFullYear()+t.offset,0,1)}return e}(r,o):r}return isNaN(n.getTime())?t:(n.setMilliseconds(n.getMilliseconds()+(Wn()?Bn(e):Gn(e))),n)}catch(e){return t}}function Gn(e){var t=0;return t+=3600*e.getHours(),t+=60*e.getMinutes(),t+=e.getSeconds(),t*=1e3,t+=e.getMilliseconds()}function Bn(e){var t=0;return t+=3600*e.getUTCHours(),t+=60*e.getUTCMinutes(),t+=e.getUTCSeconds(),t*=1e3,t+=e.getUTCMilliseconds()}function qn(e){for(var t=Eo("timeZoneOffsets"),n=0;n=0&&e.getTime()-o<0)return parseInt(i.offset)}throw z("input",l("l_InvalidDate_Text"))}function Yn(e){var t=function(e){var t=new Date(e.year,e.month,e.date,e.hours,e.minutes,e.seconds,null===e.milliseconds?0:e.milliseconds);if(isNaN(t.getTime()))throw z("input",l("l_InvalidDate_Text"));return t}(e);if(!i(Eo("timeZoneOffsets"))){var n=qn(t);t.setUTCMinutes(t.getUTCMinutes()-n),n=e.timezoneOffset?e.timezoneOffset:-1*t.getTimezoneOffset(),t.setUTCMinutes(t.getUTCMinutes()+n)}return t}function Xn(e){return{month:e.getMonth(),date:e.getDate(),year:e.getFullYear(),hours:e.getHours(),minutes:e.getMinutes(),seconds:e.getSeconds(),milliseconds:e.getMilliseconds()}}function $n(e){return i(e)?{addresses:[],emailAddresses:[],urls:[],taskSuggestions:[],meetingSuggestions:[],phoneNumbers:[],contacts:[],flightReservations:[],parcelDelivery:[]}:{addresses:Kn(e[jn.address]),emailAddresses:Zn(e[jn.emailAddress]),urls:Qn(e[jn.url]),taskSuggestions:ei(e[jn.taskSuggestion]),meetingSuggestions:ti(e[jn.meetingSuggestion]),phoneNumbers:ii(e[jn.phoneNumber]),contacts:ri(e[jn.contact]),flightReservations:oi(e[jn.flightReservations]),parcelDelivery:oi(e[jn.parcelDeliveries])}}!function(e){e.meetingSuggestion="MeetingSuggestions",e.taskSuggestion="TaskSuggestions",e.address="Addresses",e.emailAddress="EmailAddresses",e.url="Urls",e.phoneNumber="PhoneNumbers",e.contact="Contacts",e.flightReservations="FlightReservations",e.parcelDeliveries="ParcelDeliveries"}(jn||(jn={}));var Kn=function(e){return Nn(e||[],Hn)},Zn=function(e){return 0===j()?[]:e||[]},Qn=function(e){return e||[]},ei=function(e){if(0===j())return[];var t=e||[];return Nn(t=t.map((function(e){return{assignees:(e.Assignees||[]).map(Dn),taskString:e.TaskString}})),Un)},ti=function(e){if(0===j())return[];var t=e||[];return Nn(t=t.map((function(e){var t=""!==e.StartTime?ni(e.StartTime):void 0,n=""!==e.EndTime?ni(e.EndTime):void 0;return{meetingString:e.MeetingString,attendees:(e.Attendees||[]).map(Dn),location:e.Location,subject:e.Subject,start:void 0!==e.StartTime?t:void 0,end:void 0!==e.EndTime?n:void 0}})),Rn)};function ni(e){var t=Jn(new Date(e),new Date(Eo("dateTimeSent")));return t.getTime()!==new Date(e).getTime()?Yn(Xn(t)):new Date(e)}var ii=function(e){return(e||[]).map((function(e){return{phoneString:e.PhoneString,originalPhoneString:e.OriginalPhoneString,type:e.Type}}))},ri=function(e){if(0===j())return[];var t=e||[];return Nn(t=t.map((function(e){return{personName:e.PersonName,businessName:e.BusinessName,phoneNumbers:ii(e.PhoneNumbers||[]),emailAddresses:e.EmailAddresses||[],urls:e.Urls||[],addresses:e.Addresses||[],contactString:e.ContactString}})),Ln)},oi=function(e){return 0===j()?[]:e||[]},ai={meetingSuggestion:1,taskSuggestion:1,address:0,emailAddress:1,url:0,phoneNumber:0,contact:1,flightReservations:1,parcelDeliveries:1},si={meetingSuggestion:"meetingSuggestions",taskSuggestion:"taskSuggestions",address:"addresses",emailAddress:"emailAddresses",url:"urls",phoneNumber:"phoneNumbers",contact:"contacts",flightReservations:"flightReservations",parcelDeliveries:"parcelDeliveries"},ci=function(){return $n(Eo("entities"))},li=function(e){var t=$n(Eo("entities"));q(void 0!==ai[e]?ai[e]:1,e);var n=si[e];return void 0===n?null:t[n]},ui=function(e){return function(e,t){q(1,"item.getFilteredEntitiesByName");var n=Object.keys(e).map((function(n){return e[n][t]?{entityType:n,name:t,entities:e[n][t]}:void 0})).filter((function(e){return void 0!==e}));if(0===n.length)return null;var i=n[0];switch(i.entityType){case jn.meetingSuggestion:return ti(i.entities);case jn.address:return Kn(i.entities);case jn.contact:return ri(i.entities);case jn.emailAddress:return Zn(i.entities);case jn.phoneNumber:return ii(i.entities);case jn.taskSuggestion:return ei(i.entities);case jn.url:return Qn(i.entities);default:return oi(i.entities)}}(Eo("filteredEntities"),e)},di=function(){return Eo("regExMatches")},fi=function(e){return(Eo("regExMatches")||{})[e]},pi=function(){return $n(Eo("selectedEntities"))},gi=function(){return Eo("selectedRegExMatches")};function mi(e){var t=[];if(0===j())return[];if(e)for(var n=0;n12||n<1||n>31)}var xi=function(){function e(){this.startYear=0,this.startMonth=0,this.startDay=0,this.endYear=0,this.endMonth=0,this.endDay=0,this.startTimeMinutes=0,this.durationMinutes=0}return e.prototype.getDuration=function(){return this.durationMinutes},e.prototype.getEndTime=function(){var e=this.startTimeMinutes+this.durationMinutes,t=e%60;return"T"+Ii(Math.floor(e/60)%24)+":"+Ii(t)+":00.000"},e.prototype.getEndDate=function(){return 0===this.endYear&&0===this.endMonth&&0===this.endDay?null:this.endYear.toString()+"-"+Ii(this.endMonth)+"-"+Ii(this.endDay)},e.prototype.getStartDate=function(){return this.startYear.toString()+"-"+Ii(this.startMonth)+"-"+Ii(this.startDay)},e.prototype.getStartTime=function(){var e=this.startTimeMinutes%60;return"T"+Ii(Math.floor(this.startTimeMinutes/60))+":"+Ii(e)+":00.000"},e.prototype.setDuration=function(e){if(!(e>=0))throw z(void 0,l("l_InvalidTime_Text"));this.durationMinutes=e},e.prototype.setEndDate=function(e,t,n){null===e||i(t)||null===n?null!==e?this.setDateHelper(!1,e):null==e&&(this.endYear=0,this.endMonth=0,this.endDay=0):this.setDateHelper(!1,e,t,n)},e.prototype.setStartDate=function(e,t,n){null===e||i(t)||null===n?null!==e&&this.setDateHelper(!0,e):this.setDateHelper(!0,e,t,n)},e.prototype.setStartTime=function(e,t){if(i(e)||i(t)){if(!i(e)){var n=e,r="2017-01-15"+n+"Z";if(!new RegExp("^T[0-2]\\d:[0-5]\\d:[0-5]\\d\\.\\d{3}$").test(n))throw z(void 0,l("l_InvalidTime_Text"));var o=new Date(r);if(i(o)||isNaN(o.getUTCHours())||isNaN(o.getUTCMinutes()))throw z(void 0,l("l_InvalidTime_Text"));this.startTimeMinutes=60*o.getUTCHours()+o.getUTCMinutes()}}else{var a=60*e+t;if(!(a>=0))throw z(void 0,l("l_InvalidTime_Text"));this.startTimeMinutes=a}},e.prototype.isValid=function(){return!!Di(this.startYear,this.startMonth,this.startDay)&&(!(0!==this.endDay&&0!==this.endMonth&&0!==this.endYear&&!Di(this.endYear,this.endMonth,this.endDay))&&!(this.startTimeMinutes<0||this.durationMinutes<=0))},e.prototype.exportToSeriesTimeJson=function(){var e={};return e.startYear=this.startYear,e.startMonth=this.startMonth,e.startDay=this.startDay,0===this.endYear&&0===this.endMonth&&0===this.endDay?e.noEndDate=!0:(e.endYear=this.endYear,e.endMonth=this.endMonth,e.endDay=this.endDay),e.startTimeMin=this.startTimeMinutes,this.durationMinutes>0&&(e.durationMin=this.durationMinutes),e},e.prototype.importFromSeriesTimeJsonObject=function(e){this.startYear=e.startYear,this.startMonth=e.startMonth,this.startDay=e.startDay,null!=e.noEndDate&&"boolean"==typeof e.noEndDate?(this.endYear=0,this.endMonth=0,this.endDay=0):(this.endYear=e.endYear,this.endMonth=e.endMonth,this.endDay=e.endDay),this.startTimeMinutes=e.startTimeMin,this.durationMinutes=e.durationMin},e.prototype.setDateHelper=function(e,t,n,r){var o=0,a=0,s=0;if(null===t||i(n)||null===r){if(null!==t){var c=t;!function(e){if(!new RegExp("^\\d{4}-(?:[0]\\d|1[0-2])-(?:[0-2]\\d|3[01])$").test(e))throw z(Si,l("l_InvalidDate_Text"))}(c);var u=new Date(c);null===u||isNaN(u.getUTCFullYear())||isNaN(u.getUTCMonth())||isNaN(u.getUTCDate())||(ki(u.getUTCFullYear(),u.getUTCMonth()+1,u.getUTCDate()),o=u.getUTCFullYear(),a=u.getUTCMonth()+1,s=u.getUTCDate())}}else ki(t,n+1,r),o=t,a=n+1,s=r;0!==o&&0!==a&&0!==s&&(e?(this.startYear=o,this.startMonth=a,this.startDay=s):(this.endYear=o,this.endMonth=a,this.endDay=s))},e.prototype.isEndAfterStart=function(){if(0===this.endYear&&0===this.endMonth&&0===this.endDay)return!0;var e=new Date;e.setFullYear(this.startYear),e.setMonth(this.startMonth-1),e.setDate(this.startDay);var t=new Date;return t.setFullYear(this.endYear),t.setMonth(this.endMonth-1),t.setDate(this.endDay),t>=e},e}();function Mi(e){if(i(e)||i(e.seriesTimeJson))return e;var t={recurrenceType:"",recurrenceProperties:null,recurrenceTimeZone:null},n=new xi;return i(e.recurrenceProperties)||(t.recurrenceProperties=yi(e.recurrenceProperties)),t.recurrenceType=e.recurrenceType,i(e.recurrenceTimeZone)||(t.recurrenceTimeZone=yi(e.recurrenceTimeZone)),n.importFromSeriesTimeJsonObject(e.seriesTimeJson),t.seriesTime=n,t}function Fi(){var e=Eo("sender"),t=Eo("from"),n=Eo("dateTimeCreated"),i=Eo("dateTimeModified"),r=Eo("end"),o=Eo("start");return et({},{attachments:mi(Eo("attachments")),bcc:(Eo("bcc")||[]).map(kn),body:jt(!1),categories:Sn(),cc:(Eo("cc")||[]).map(kn),conversationId:Eo("conversationId"),dateTimeCreated:n?new Date(n):void 0,dateTimeModified:i?new Date(i):void 0,end:r?new Date(r):void 0,from:t?kn(t):void 0,getAllInternetHeadersAsync:Vt,internetMessageId:Eo("internetMessageId"),itemClass:Eo("itemClass"),itemId:Eo("id"),itemType:"message",location:Eo("location"),move:bn,normalizedSubject:Eo("normalizedSubject"),notificationMessages:on(),recurrence:Mi(Eo("recurrence")),seriesId:Eo("seriesId"),sender:e?kn(e):void 0,start:o?new Date(o):void 0,subject:Eo("subject"),to:(Eo("to")||[]).map(kn),displayReplyForm:dn,displayReplyFormAsync:pn,displayReplyAllForm:fn,displayReplyAllFormAsync:gn,getAttachmentContentAsync:An,getEntities:ci,getEntitiesByType:li,getFilteredEntitiesByName:ui,getInitializationContextAsync:mt,getRegExMatches:di,getRegExMatchesByName:fi,getSelectedEntities:pi,getSelectedRegExMatches:gi,loadCustomPropertiesAsync:bt,delayDeliveryTime:Pn(!1),isAllDayEvent:Eo("isAllDayEvent"),sensitivity:Eo("sensitivity")})}function Pi(e){if(i(e)||""===e||"string"!=typeof e)throw z("attachmentName");Z(e.length,0,255,"attachmentName")}var Ni=6e5;function Hi(e,t){for(var n=[],i=2;i100)throw G("recipients",e.recipientArray.length);var t=e.recipientArray.map((function(e){if(i(e))throw z("recipients");if("string"==typeof e)return Xi(e,e),$i(e,e);if("object"==typeof e)return Xi(e.displayName,e.emailAddress),$i(e.displayName,e.emailAddress);throw z("recipients")}));e.recipientArray=t}function Xi(e,t){if(!e&&!t)throw z("recipients");if("string"==typeof e&&e.length>255)throw G("recipients",e.length,l("l_DisplayNameTooLong_Text"));if("string"==typeof t&&t.length>571)throw G("recipients",t.length,l("l_EmailAddressTooLong_Text"));if("string"!=typeof e&&"string"!=typeof t)throw z("recipients")}function $i(e,t){return{address:t,name:e}}function Ki(e){return function(t){for(var n=[],i=1;iX)throw z("id")}(e.id,e.type)}function Mr(e){for(var t=[],n=1;n864e13)throw G("dateTime")}function Vr(e){return et({},{getAsync:Ur(e),setAsync:Wr(e)})}function zr(){for(var e=[],t=0;t31)throw z(bi)}function Qr(e){for(var t=[],n=1;n0)throw z(void 0,l("l_Recurrence_Error_Instance_SetAsync_Text"));Yr(e);var o=Y(t,!1,!1),a=eo(e),s={recurrenceData:a};R(104,o.asyncContext,o.callback,s,void 0)}function eo(e){if(null!==e&&null!==e.seriesTime&&e.seriesTime instanceof xi)return{recurrenceProperties:e.recurrenceProperties,recurrenceTimeZone:e.recurrenceTimeZone,recurrenceType:e.recurrenceType,seriesTimeJson:e.seriesTime.exportToSeriesTimeJson()};return e}function to(){for(var e=[],t=0;t=16)||function(e,t){var n=!1;try{var i=JSON.parse(t.get_requirementMatrix()).Mailbox.split("."),r=e.split(".");(parseInt(i[0])>parseInt(r[0])||parseInt(i[0])===parseInt(r[0])&&parseInt(i[1])>=parseInt(r[1]))&&(n=!0)}catch(e){}return n}("1.5",r.officeAppContext),E(),void 0!==e.itemNumber&&C().setCurrentItemNumber(e.itemNumber)}var t,n,o},this.onInitialDataResponse=function(e,t){var n;e&&e!==S.noError||(r.initialize(t),et(n=r,{ewsUrl:Eo("ewsUrl"),restUrl:Eo("restUrl"),displayAppointmentForm:ve,displayAppointmentFormAsync:Se,displayMessageForm:be,displayMessageFormAsync:we,displayPersonaCardAsync:Ao,getCallbackTokenAsync:Ye,getUserIdentityTokenAsync:Xe,logTelemetry:yo,makeEwsRequestAsync:Ze,masterCategories:et({},{addAsync:st,getAsync:ct,removeAsync:dt}),navigateToModuleAsync:uo,diagnostics:et({},{hostName:nt(),hostVersion:Eo("hostVersion"),OWAView:Eo("owaView")}),userProfile:et({},{accountType:Eo("userProfileType"),displayName:Eo("userDisplayName"),emailAddress:Eo("userEmailAddress"),timeZone:Eo("userTimeZone")}),convertToEwsId:ie,convertToLocalClientTime:So,convertToRestId:ne,convertToUtcClientTime:Yn,RegisterConsentAsync:lo,GetIsRead:function(){return Eo("isRead")},GetEndPointUrl:function(){return Eo("endNodeUrl")},GetConsentMetaData:function(){return Eo("consentMetadata")},GetMarketplaceContentMarket:function(){return Eo("marketplaceContentMarket")},GetMarketplaceAssetId:function(){return Eo("marketplaceAssetId")},GetExtensionId:function(){return Eo("extensionId")},CloseApp:ft,recordDataPoint:po,recordTrace:go,trackCtq:mo}),gt()!==pt.MessageCompose&>()!==pt.AppointmentCompose&&et(n,{displayNewAppointmentForm:De,displayNewMessageForm:He,displayNewAppointmentFormAsync:xe,displayNewMessageFormAsync:Re}),ko()===wo.AppName.OutlookWebApp&&Eo("openWindowOpen")&&(window.open=ho),setTimeout((function(){return r.appReadyCallback()}),0))},this.officeAppContext=e,this.targetWindow=window,this.appReadyCallback=n,bo=this,function(e){var t;u=e;for(var n=document.getElementsByTagName("script"),i=0;i0){d=c.replace(o,s),f=v(f,t,c);break}if(t=c.indexOf(a),c&&t>0){d=c.replace(a,s),f=v(f,t,c);break}}}if(d){var l=document.getElementsByTagName("head")[0];(p=m(d)).onload=h,p.onreadystatechange=h,window.setTimeout(y,2e3),l.appendChild(p)}}(this.stringLoadedCallback)}return e.prototype.getAppName=function(){return this.officeAppContext.get_appName()},e.prototype.getInitialDataProp=function(e){return this.initialData&&this.initialData[e]},e.prototype.setCurrentItemNumber=function(e){C().setCurrentItemNumber(e)},e.addAdditionalArgs=function(e,t){return t},e.shouldRunInitialDataResponse=function(){return!0},e}(),xo=function(){var e=Eo("permissionLevel");if(void 0===e)return 0;switch(e){case 1:return 1;case 3:return 2;case 2:return 3;default:return 0}},Mo=n(0);function Fo(e){for(var t=[],n=1;n32768){var o=U(void 0,Mo.DDA.AsyncResultEnum.ErrorCode.Failed,9019,i.asyncContext,"");i.callback&&setTimeout((function(){i.callback&&i.callback(o)}),0)}else Mo.AppName.OutlookWebApp===ko()?Po(i,r):No(i,r)}function Po(e,t){R(404,e.asyncContext,e.callback,[t],void 0)}function No(e,t){var n=-1,i=null;try{var r=JSON.stringify(t),o={};o.SettingsKey=r,Mo.DDA.ClientSettingsManager.write(o)}catch(e){i=e}var a=void 0;null!=i?(n=9019,a=U(void 0,Mo.DDA.AsyncResultEnum.ErrorCode.Failed,n,e.asyncContext,i.Message)):(n=0,a=U(void 0,Mo.DDA.AsyncResultEnum.ErrorCode.Success,n,e.asyncContext)),e.callback&&e.callback(a)}var Ho=function(){for(var e=0,t=0,n=arguments.length;t 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { + _ = 0; + continue; + } + if (op[0] === 3 && (!t || op[1] > t[0] && op[1] < t[3])) { + _.label = op[1]; + break; + } + if (op[0] === 6 && _.label < t[1]) { + _.label = t[1]; + t = op; + break; + } + if (t && _.label < t[2]) { + _.label = t[2]; + _.ops.push(op); + break; + } + if (t[2]) _.ops.pop(); + _.trys.pop(); + continue; + } + op = body.call(thisArg, _); + } catch (e) { + op = [ 6, e ]; + y = 0; + } finally { + f = t = 0; + } + if (op[0] & 5) throw op[1]; + return { + value: op[0] ? op[1] : void 0, + done: true + }; + } + }; + var ACTIVITY_COUNT = 1; + var ACTIVITY_AGGMODE = 0; + var getCurrentMicroseconds = function() { + return Date.now() * 1e3; + }; + if (typeof window.performance === "object" && "now" in window.performance) { + getCurrentMicroseconds = function() { + return Math.floor(window.performance.now()) * 1e3; + }; + } + var Activity_ActivityScope = function() { + function ActivityScope(telemetryLogger, activityName, parent) { + this._optionalEventFlags = {}; + this._ended = false; + this._telemetryLogger = telemetryLogger; + this._activityName = activityName; + if (parent) { + this._cv = CorrelationVector.getNextChild(parent._cv); + } else { + this._cv = CorrelationVector.getNext(); + } + this._dataFields = []; + this._success = undefined; + this._startTime = getCurrentMicroseconds(); + } + ActivityScope.createNew = function(telemetryLogger, activityName) { + return new ActivityScope(telemetryLogger, activityName); + }; + ActivityScope.prototype.createChildActivity = function(activityName) { + var childActivity = new ActivityScope(this._telemetryLogger, activityName, this); + return childActivity; + }; + ActivityScope.prototype.setEventFlags = function(eventFlags) { + this._optionalEventFlags = eventFlags; + }; + ActivityScope.prototype.addDataField = function(dataField) { + this._dataFields.push(dataField); + }; + ActivityScope.prototype.addDataFields = function(dataFields) { + var _a; + (_a = this._dataFields).push.apply(_a, dataFields); + }; + ActivityScope.prototype.setSuccess = function(success) { + this._success = success; + }; + ActivityScope.prototype.setResult = function(code, type, tag) { + this._result = { + code: code, + type: type, + tag: tag + }; + }; + ActivityScope.prototype.endNow = function() { + if (this._ended) { + logNotification(LogLevel.Error, Category.Core, function() { + return "Activity has already ended"; + }); + return; + } + if (this._success === undefined && this._result === undefined) { + logNotification(LogLevel.Warning, Category.Core, function() { + return "Activity does not have success or result set"; + }); + } + var endTime = getCurrentMicroseconds(); + var duration = endTime - this._startTime; + this._ended = true; + var activity = { + duration: duration, + count: ACTIVITY_COUNT, + aggMode: ACTIVITY_AGGMODE, + cV: this._cv.getString(), + success: this._success, + result: this._result + }; + return this._telemetryLogger.sendActivity(this._activityName, activity, this._dataFields, this._optionalEventFlags); + }; + ActivityScope.prototype.executeAsync = function(activityBody) { + return __awaiter(this, void 0, void 0, function() { + var _this = this; + return __generator(this, function(_a) { + return [ 2, activityBody(this).then(function(result) { + _this.endNow(); + return result; + }).catch(function(e) { + _this.endNow(); + throw e; + }) ]; + }); + }); + }; + ActivityScope.prototype.executeSync = function(activityBody) { + try { + var ret = activityBody(this); + this.endNow(); + return ret; + } catch (e) { + this.endNow(); + throw e; + } + }; + ActivityScope.prototype.executeChildActivityAsync = function(activityName, activityBody) { + return __awaiter(this, void 0, void 0, function() { + return __generator(this, function(_a) { + return [ 2, this.createChildActivity(activityName).executeAsync(activityBody) ]; + }); + }); + }; + ActivityScope.prototype.executeChildActivitySync = function(activityName, activityBody) { + return this.createChildActivity(activityName).executeSync(activityBody); + }; + return ActivityScope; + }(); + var DataClassification; + (function(DataClassification) { + DataClassification[DataClassification["EssentialServiceMetadata"] = 1] = "EssentialServiceMetadata"; + DataClassification[DataClassification["AccountData"] = 2] = "AccountData"; + DataClassification[DataClassification["SystemMetadata"] = 4] = "SystemMetadata"; + DataClassification[DataClassification["OrganizationIdentifiableInformation"] = 8] = "OrganizationIdentifiableInformation"; + DataClassification[DataClassification["EndUserIdentifiableInformation"] = 16] = "EndUserIdentifiableInformation"; + DataClassification[DataClassification["CustomerContent"] = 32] = "CustomerContent"; + DataClassification[DataClassification["AccessControl"] = 64] = "AccessControl"; + })(DataClassification || (DataClassification = {})); + var SamplingPolicy; + (function(SamplingPolicy) { + SamplingPolicy[SamplingPolicy["NotSet"] = 0] = "NotSet"; + SamplingPolicy[SamplingPolicy["Measure"] = 1] = "Measure"; + SamplingPolicy[SamplingPolicy["Diagnostics"] = 2] = "Diagnostics"; + SamplingPolicy[SamplingPolicy["CriticalBusinessImpact"] = 191] = "CriticalBusinessImpact"; + SamplingPolicy[SamplingPolicy["CriticalCensus"] = 192] = "CriticalCensus"; + SamplingPolicy[SamplingPolicy["CriticalExperimentation"] = 193] = "CriticalExperimentation"; + SamplingPolicy[SamplingPolicy["CriticalUsage"] = 194] = "CriticalUsage"; + })(SamplingPolicy || (SamplingPolicy = {})); + var PersistencePriority; + (function(PersistencePriority) { + PersistencePriority[PersistencePriority["NotSet"] = 0] = "NotSet"; + PersistencePriority[PersistencePriority["Normal"] = 1] = "Normal"; + PersistencePriority[PersistencePriority["High"] = 2] = "High"; + })(PersistencePriority || (PersistencePriority = {})); + var CostPriority; + (function(CostPriority) { + CostPriority[CostPriority["NotSet"] = 0] = "NotSet"; + CostPriority[CostPriority["Normal"] = 1] = "Normal"; + CostPriority[CostPriority["High"] = 2] = "High"; + })(CostPriority || (CostPriority = {})); + var DataCategories; + (function(DataCategories) { + DataCategories[DataCategories["NotSet"] = 0] = "NotSet"; + DataCategories[DataCategories["SoftwareSetup"] = 1] = "SoftwareSetup"; + DataCategories[DataCategories["ProductServiceUsage"] = 2] = "ProductServiceUsage"; + DataCategories[DataCategories["ProductServicePerformance"] = 4] = "ProductServicePerformance"; + DataCategories[DataCategories["DeviceConfiguration"] = 8] = "DeviceConfiguration"; + DataCategories[DataCategories["InkingTypingSpeech"] = 16] = "InkingTypingSpeech"; + })(DataCategories || (DataCategories = {})); + var DiagnosticLevel; + (function(DiagnosticLevel) { + DiagnosticLevel[DiagnosticLevel["ReservedDoNotUse"] = 0] = "ReservedDoNotUse"; + DiagnosticLevel[DiagnosticLevel["BasicEvent"] = 10] = "BasicEvent"; + DiagnosticLevel[DiagnosticLevel["FullEvent"] = 100] = "FullEvent"; + DiagnosticLevel[DiagnosticLevel["NecessaryServiceDataEvent"] = 110] = "NecessaryServiceDataEvent"; + DiagnosticLevel[DiagnosticLevel["AlwaysOnNecessaryServiceDataEvent"] = 120] = "AlwaysOnNecessaryServiceDataEvent"; + })(DiagnosticLevel || (DiagnosticLevel = {})); + function getEffectiveEventFlags(telemetryEvent) { + var eventFlags = { + costPriority: CostPriority.Normal, + samplingPolicy: SamplingPolicy.Measure, + persistencePriority: PersistencePriority.Normal, + dataCategories: DataCategories.NotSet, + diagnosticLevel: DiagnosticLevel.FullEvent + }; + if (!telemetryEvent.eventFlags || !telemetryEvent.eventFlags.dataCategories) { + logNotification(LogLevel.Error, Category.Core, function() { + return "Event is missing DataCategories event flag"; + }); + } + if (!telemetryEvent.eventFlags) { + return eventFlags; + } + if (telemetryEvent.eventFlags.costPriority) { + eventFlags.costPriority = telemetryEvent.eventFlags.costPriority; + } + if (telemetryEvent.eventFlags.samplingPolicy) { + eventFlags.samplingPolicy = telemetryEvent.eventFlags.samplingPolicy; + } + if (telemetryEvent.eventFlags.persistencePriority) { + eventFlags.persistencePriority = telemetryEvent.eventFlags.persistencePriority; + } + if (telemetryEvent.eventFlags.dataCategories) { + eventFlags.dataCategories = telemetryEvent.eventFlags.dataCategories; + } + if (telemetryEvent.eventFlags.diagnosticLevel) { + eventFlags.diagnosticLevel = telemetryEvent.eventFlags.diagnosticLevel; + } + return eventFlags; + } + var TokenType; + (function(TokenType) { + TokenType[TokenType["Aria"] = 0] = "Aria"; + TokenType[TokenType["Nexus"] = 1] = "Nexus"; + })(TokenType || (TokenType = {})); + var TenantTokenManager_TenantTokenManager; + (function(TenantTokenManager) { + var ariaTokenMap = {}; + var nexusTokenMap = {}; + var tenantTokens = {}; + function setTenantToken(namespace, ariaTenantToken, nexusTenantToken) { + var parts = namespace.split("."); + if (parts.length < 2 || parts[0] !== "Office") { + logNotification(LogLevel.Error, Category.Core, function() { + return "Invalid namespace: " + namespace; + }); + return; + } + var leaf = Object.create(Object.prototype); + if (ariaTenantToken) { + leaf["ariaTenantToken"] = ariaTenantToken; + } + if (nexusTenantToken) { + leaf["nexusTenantToken"] = nexusTenantToken; + } + var node = leaf; + var index; + for (index = parts.length - 1; index >= 0; --index) { + var parentNode = Object.create(Object.prototype); + parentNode[parts[index]] = node; + node = parentNode; + } + setTenantTokens(node); + } + TenantTokenManager.setTenantToken = setTenantToken; + function setTenantTokens(tokenTree) { + if (typeof tokenTree !== "object") { + throw new Error("tokenTree must be an object"); + } + tenantTokens = mergeTenantTokens(tenantTokens, tokenTree); + } + TenantTokenManager.setTenantTokens = setTenantTokens; + function getTenantTokens(eventName) { + var ariaTenantToken = getAriaTenantToken(eventName); + var nexusTenantToken = getNexusTenantToken(eventName); + if (!nexusTenantToken || !ariaTenantToken) { + throw new Error("Could not find tenant token for " + eventName); + } + return { + ariaTenantToken: ariaTenantToken, + nexusTenantToken: nexusTenantToken + }; + } + TenantTokenManager.getTenantTokens = getTenantTokens; + function getAriaTenantToken(eventName) { + if (ariaTokenMap[eventName]) { + return ariaTokenMap[eventName]; + } + var ariaToken = getTenantToken(eventName, TokenType.Aria); + if (typeof ariaToken === "string") { + ariaTokenMap[eventName] = ariaToken; + return ariaToken; + } + return undefined; + } + TenantTokenManager.getAriaTenantToken = getAriaTenantToken; + function getNexusTenantToken(eventName) { + if (nexusTokenMap[eventName]) { + return nexusTokenMap[eventName]; + } + var nexusToken = getTenantToken(eventName, TokenType.Nexus); + if (typeof nexusToken === "number") { + nexusTokenMap[eventName] = nexusToken; + return nexusToken; + } + return undefined; + } + TenantTokenManager.getNexusTenantToken = getNexusTenantToken; + function getTenantToken(eventName, tokenType) { + var pieces = eventName.split("."); + var node = tenantTokens; + var token = undefined; + if (!node) { + return undefined; + } + for (var i = 0; i < pieces.length - 1; i++) { + if (node[pieces[i]]) { + node = node[pieces[i]]; + if (tokenType === TokenType.Aria && typeof node.ariaTenantToken === "string") { + token = node.ariaTenantToken; + } else if (tokenType === TokenType.Nexus && typeof node.nexusTenantToken === "number") { + token = node.nexusTenantToken; + } + } + } + return token; + } + function mergeTenantTokens(existingTokenTree, newTokenTree) { + if (typeof newTokenTree !== "object") { + return newTokenTree; + } + for (var _i = 0, _a = Object.keys(newTokenTree); _i < _a.length; _i++) { + var key = _a[_i]; + if (key in existingTokenTree && typeof (existingTokenTree[key] === "object")) { + existingTokenTree[key] = mergeTenantTokens(existingTokenTree[key], newTokenTree[key]); + } else { + existingTokenTree[key] = newTokenTree[key]; + } + } + return existingTokenTree; + } + function clear() { + ariaTokenMap = {}; + nexusTokenMap = {}; + tenantTokens = {}; + } + TenantTokenManager.clear = clear; + })(TenantTokenManager_TenantTokenManager || (TenantTokenManager_TenantTokenManager = {})); + var TelemetryEventValidator_TelemetryEventValidator; + (function(TelemetryEventValidator) { + var INT64_MIN = -9007199254740991; + var INT64_MAX = 9007199254740991; + var StartsWithCapitalRegex = /^[A-Z][a-zA-Z0-9]*$/; + var AlphanumericRegex = /^[a-zA-Z0-9_\.]*$/; + function validateTelemetryEvent(event) { + if (!isEventNameValid(event.eventName)) { + throw new Error("Invalid eventName"); + } + if (event.eventContract && !isEventContractValid(event.eventContract)) { + throw new Error("Invalid eventContract"); + } + if (event.dataFields != null) { + for (var i = 0; i < event.dataFields.length; i++) { + validateDataField(event.dataFields[i]); + } + } + } + TelemetryEventValidator.validateTelemetryEvent = validateTelemetryEvent; + function isNamespaceValid(eventNamePieces) { + return !!eventNamePieces && eventNamePieces.length >= 3 && eventNamePieces[0] === "Office"; + } + function isEventNodeValid(eventNode) { + return eventNode !== undefined && StartsWithCapitalRegex.test(eventNode); + } + function isEventNameValid(eventName) { + var maxEventNameLength = 98; + if (!eventName || eventName.length > maxEventNameLength) { + return false; + } + var eventNamePieces = eventName.split("."); + var eventNodeName = eventNamePieces[eventNamePieces.length - 1]; + return isNamespaceValid(eventNamePieces) && isEventNodeValid(eventNodeName); + } + function isEventContractValid(eventContract) { + return isNameValid(eventContract.name); + } + function isDataFieldNameValid(dataFieldName) { + var maxDataFieldNameLength = 100; + var dataFieldPrefixLength = 5; + return !!dataFieldName && isNameValid(dataFieldName) && dataFieldName.length + dataFieldPrefixLength < maxDataFieldNameLength; + } + function isNameValid(name) { + return name !== undefined && AlphanumericRegex.test(name); + } + function validateDataField(dataField) { + if (!isDataFieldNameValid(dataField.name)) { + throw new Error("Invalid dataField name"); + } + if (dataField.dataType === DataFieldType.Int64) { + validateInt(dataField.value); + } + } + function validateInt(value) { + if (typeof value !== "number" || !isFinite(value) || Math.floor(value) !== value || value < INT64_MIN || value > INT64_MAX) { + throw new Error("Invalid integer " + JSON.stringify(value)); + } + } + TelemetryEventValidator.validateInt = validateInt; + })(TelemetryEventValidator_TelemetryEventValidator || (TelemetryEventValidator_TelemetryEventValidator = {})); + var oteljsVersion = "3.1.33"; + var __assign = undefined && undefined.__assign || function() { + __assign = Object.assign || function(t) { + for (var s, i = 1, n = arguments.length; i < n; i++) { + s = arguments[i]; + for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p]; + } + return t; + }; + return __assign.apply(this, arguments); + }; + var SuppressNexus = -1; + var SimpleTelemetryLogger_SimpleTelemetryLogger = function() { + function SimpleTelemetryLogger(parent, persistentDataFields, config) { + var _a, _b; + this.onSendEvent = new Event(); + this.persistentDataFields = []; + this.config = config || {}; + if (parent) { + this.onSendEvent = parent.onSendEvent; + (_a = this.persistentDataFields).push.apply(_a, parent.persistentDataFields); + this.config = __assign(__assign({}, parent.getConfig()), this.config); + } else { + this.persistentDataFields.push(makeStringDataField("OTelJS.Version", oteljsVersion)); + } + if (persistentDataFields) { + (_b = this.persistentDataFields).push.apply(_b, persistentDataFields); + } + } + SimpleTelemetryLogger.prototype.sendTelemetryEvent = function(event) { + var localEvent; + try { + if (this.onSendEvent.getListenerCount() === 0) { + logNotification(LogLevel.Warning, Category.Core, function() { + return "No telemetry sinks are attached."; + }); + return; + } + localEvent = this.cloneEvent(event); + this.processTelemetryEvent(localEvent); + } catch (error) { + logError(Category.Core, "SendTelemetryEvent", error); + return; + } + try { + this.onSendEvent.fireEvent(localEvent); + } catch (_e) {} + }; + SimpleTelemetryLogger.prototype.processTelemetryEvent = function(event) { + var _a; + if (!event.telemetryProperties) { + event.telemetryProperties = TenantTokenManager_TenantTokenManager.getTenantTokens(event.eventName); + } + (_a = event.dataFields).push.apply(_a, this.persistentDataFields); + if (!this.config.disableValidation) { + TelemetryEventValidator_TelemetryEventValidator.validateTelemetryEvent(event); + } + }; + SimpleTelemetryLogger.prototype.addSink = function(sink) { + this.onSendEvent.addListener(function(event) { + return sink.sendTelemetryEvent(event); + }); + }; + SimpleTelemetryLogger.prototype.setTenantToken = function(namespace, ariaTenantToken, nexusTenantToken) { + TenantTokenManager_TenantTokenManager.setTenantToken(namespace, ariaTenantToken, nexusTenantToken); + }; + SimpleTelemetryLogger.prototype.setTenantTokens = function(tokenTree) { + TenantTokenManager_TenantTokenManager.setTenantTokens(tokenTree); + }; + SimpleTelemetryLogger.prototype.cloneEvent = function(event) { + var localEvent = { + eventName: event.eventName, + eventFlags: event.eventFlags + }; + if (!!event.telemetryProperties) { + localEvent.telemetryProperties = { + ariaTenantToken: event.telemetryProperties.ariaTenantToken, + nexusTenantToken: event.telemetryProperties.nexusTenantToken + }; + } + if (!!event.eventContract) { + localEvent.eventContract = { + name: event.eventContract.name, + dataFields: event.eventContract.dataFields.slice() + }; + } + localEvent.dataFields = !!event.dataFields ? event.dataFields.slice() : []; + return localEvent; + }; + SimpleTelemetryLogger.prototype.getConfig = function() { + return this.config; + }; + return SimpleTelemetryLogger; + }(); + var __extends = undefined && undefined.__extends || function() { + var extendStatics = function(d, b) { + extendStatics = Object.setPrototypeOf || { + __proto__: [] + } instanceof Array && function(d, b) { + d.__proto__ = b; + } || function(d, b) { + for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; + }; + return extendStatics(d, b); + }; + return function(d, b) { + extendStatics(d, b); + function __() { + this.constructor = d; + } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; + }(); + var TelemetryLogger_awaiter = undefined && undefined.__awaiter || function(thisArg, _arguments, P, generator) { + function adopt(value) { + return value instanceof P ? value : new P(function(resolve) { + resolve(value); + }); + } + return new (P || (P = Promise))(function(resolve, reject) { + function fulfilled(value) { + try { + step(generator.next(value)); + } catch (e) { + reject(e); + } + } + function rejected(value) { + try { + step(generator["throw"](value)); + } catch (e) { + reject(e); + } + } + function step(result) { + result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); + } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); + }; + var TelemetryLogger_generator = undefined && undefined.__generator || function(thisArg, body) { + var _ = { + label: 0, + sent: function() { + if (t[0] & 1) throw t[1]; + return t[1]; + }, + trys: [], + ops: [] + }, f, y, t, g; + return g = { + next: verb(0), + throw: verb(1), + return: verb(2) + }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { + return this; + }), g; + function verb(n) { + return function(v) { + return step([ n, v ]); + }; + } + function step(op) { + if (f) throw new TypeError("Generator is already executing."); + while (_) try { + if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), + 0) : y.next) && !(t = t.call(y, op[1])).done) return t; + if (y = 0, t) op = [ op[0] & 2, t.value ]; + switch (op[0]) { + case 0: + case 1: + t = op; + break; + + case 4: + _.label++; + return { + value: op[1], + done: false + }; + + case 5: + _.label++; + y = op[1]; + op = [ 0 ]; + continue; + + case 7: + op = _.ops.pop(); + _.trys.pop(); + continue; + + default: + if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { + _ = 0; + continue; + } + if (op[0] === 3 && (!t || op[1] > t[0] && op[1] < t[3])) { + _.label = op[1]; + break; + } + if (op[0] === 6 && _.label < t[1]) { + _.label = t[1]; + t = op; + break; + } + if (t && _.label < t[2]) { + _.label = t[2]; + _.ops.push(op); + break; + } + if (t[2]) _.ops.pop(); + _.trys.pop(); + continue; + } + op = body.call(thisArg, _); + } catch (e) { + op = [ 6, e ]; + y = 0; + } finally { + f = t = 0; + } + if (op[0] & 5) throw op[1]; + return { + value: op[0] ? op[1] : void 0, + done: true + }; + } + }; + var TelemetryLogger_TelemetryLogger = function(_super) { + __extends(TelemetryLogger, _super); + function TelemetryLogger() { + return _super !== null && _super.apply(this, arguments) || this; + } + TelemetryLogger.prototype.executeActivityAsync = function(activityName, activityBody) { + return TelemetryLogger_awaiter(this, void 0, void 0, function() { + return TelemetryLogger_generator(this, function(_a) { + return [ 2, this.createNewActivity(activityName).executeAsync(activityBody) ]; + }); + }); + }; + TelemetryLogger.prototype.executeActivitySync = function(activityName, activityBody) { + return this.createNewActivity(activityName).executeSync(activityBody); + }; + TelemetryLogger.prototype.createNewActivity = function(activityName) { + return Activity_ActivityScope.createNew(this, activityName); + }; + TelemetryLogger.prototype.sendActivity = function(activityName, activity, dataFields, optionalEventFlags) { + return this.sendTelemetryEvent({ + eventName: activityName, + eventContract: { + name: Contracts.Office.System.Activity.contractName, + dataFields: Contracts.Office.System.Activity.getFields(activity) + }, + dataFields: dataFields, + eventFlags: optionalEventFlags + }); + }; + TelemetryLogger.prototype.sendError = function(error) { + var dataFields = Office_System_Error_Error.getFields("Error", error.error); + if (error.dataFields != null) { + dataFields.push.apply(dataFields, error.dataFields); + } + return this.sendTelemetryEvent({ + eventName: error.eventName, + dataFields: dataFields, + eventFlags: error.eventFlags + }); + }; + return TelemetryLogger; + }(SimpleTelemetryLogger_SimpleTelemetryLogger); + __webpack_require__.d(__webpack_exports__, "Contracts", function() { + return Contracts; + }); + __webpack_require__.d(__webpack_exports__, "ActivityScope", function() { + return Activity_ActivityScope; + }); + __webpack_require__.d(__webpack_exports__, "getFieldsForContract", function() { + return getFieldsForContract; + }); + __webpack_require__.d(__webpack_exports__, "addContractField", function() { + return addContractField; + }); + __webpack_require__.d(__webpack_exports__, "DataClassification", function() { + return DataClassification; + }); + __webpack_require__.d(__webpack_exports__, "makeBooleanDataField", function() { + return makeBooleanDataField; + }); + __webpack_require__.d(__webpack_exports__, "makeInt64DataField", function() { + return makeInt64DataField; + }); + __webpack_require__.d(__webpack_exports__, "makeDoubleDataField", function() { + return makeDoubleDataField; + }); + __webpack_require__.d(__webpack_exports__, "makeStringDataField", function() { + return makeStringDataField; + }); + __webpack_require__.d(__webpack_exports__, "makeGuidDataField", function() { + return makeGuidDataField; + }); + __webpack_require__.d(__webpack_exports__, "DataFieldType", function() { + return DataFieldType; + }); + __webpack_require__.d(__webpack_exports__, "getEffectiveEventFlags", function() { + return getEffectiveEventFlags; + }); + __webpack_require__.d(__webpack_exports__, "SamplingPolicy", function() { + return SamplingPolicy; + }); + __webpack_require__.d(__webpack_exports__, "PersistencePriority", function() { + return PersistencePriority; + }); + __webpack_require__.d(__webpack_exports__, "CostPriority", function() { + return CostPriority; + }); + __webpack_require__.d(__webpack_exports__, "DataCategories", function() { + return DataCategories; + }); + __webpack_require__.d(__webpack_exports__, "DiagnosticLevel", function() { + return DiagnosticLevel; + }); + __webpack_require__.d(__webpack_exports__, "LogLevel", function() { + return LogLevel; + }); + __webpack_require__.d(__webpack_exports__, "Category", function() { + return Category; + }); + __webpack_require__.d(__webpack_exports__, "onNotification", function() { + return onNotification; + }); + __webpack_require__.d(__webpack_exports__, "logNotification", function() { + return logNotification; + }); + __webpack_require__.d(__webpack_exports__, "logError", function() { + return logError; + }); + __webpack_require__.d(__webpack_exports__, "SuppressNexus", function() { + return SuppressNexus; + }); + __webpack_require__.d(__webpack_exports__, "SimpleTelemetryLogger", function() { + return SimpleTelemetryLogger_SimpleTelemetryLogger; + }); + __webpack_require__.d(__webpack_exports__, "TelemetryLogger", function() { + return TelemetryLogger_TelemetryLogger; + }); +} ]); \ No newline at end of file diff --git a/addins/outlook/telemetry/oteljs_agave.js b/addins/outlook/telemetry/oteljs_agave.js new file mode 100644 index 0000000..ce2f676 --- /dev/null +++ b/addins/outlook/telemetry/oteljs_agave.js @@ -0,0 +1,3910 @@ +var oteljs_agave = function(modules) { + var installedModules = {}; + function __webpack_require__(moduleId) { + if (installedModules[moduleId]) { + return installedModules[moduleId].exports; + } + var module = installedModules[moduleId] = { + i: moduleId, + l: false, + exports: {} + }; + modules[moduleId].call(module.exports, module, module.exports, __webpack_require__); + module.l = true; + return module.exports; + } + __webpack_require__.m = modules; + __webpack_require__.c = installedModules; + __webpack_require__.d = function(exports, name, getter) { + if (!__webpack_require__.o(exports, name)) { + Object.defineProperty(exports, name, { + enumerable: true, + get: getter + }); + } + }; + __webpack_require__.r = function(exports) { + if (typeof Symbol !== "undefined" && Symbol.toStringTag) { + Object.defineProperty(exports, Symbol.toStringTag, { + value: "Module" + }); + } + Object.defineProperty(exports, "__esModule", { + value: true + }); + }; + __webpack_require__.t = function(value, mode) { + if (mode & 1) value = __webpack_require__(value); + if (mode & 8) return value; + if (mode & 4 && typeof value === "object" && value && value.__esModule) return value; + var ns = Object.create(null); + __webpack_require__.r(ns); + Object.defineProperty(ns, "default", { + enumerable: true, + value: value + }); + if (mode & 2 && typeof value != "string") for (var key in value) __webpack_require__.d(ns, key, function(key) { + return value[key]; + }.bind(null, key)); + return ns; + }; + __webpack_require__.n = function(module) { + var getter = module && module.__esModule ? function getDefault() { + return module["default"]; + } : function getModuleExports() { + return module; + }; + __webpack_require__.d(getter, "a", getter); + return getter; + }; + __webpack_require__.o = function(object, property) { + return Object.prototype.hasOwnProperty.call(object, property); + }; + __webpack_require__.p = ""; + return __webpack_require__(__webpack_require__.s = 22); +}([ function(module, exports, __webpack_require__) { + "use strict"; + Object.defineProperty(exports, "__esModule", { + value: true + }); + var AWTPropertyType; + (function(AWTPropertyType) { + AWTPropertyType[AWTPropertyType["Unspecified"] = 0] = "Unspecified"; + AWTPropertyType[AWTPropertyType["String"] = 1] = "String"; + AWTPropertyType[AWTPropertyType["Int64"] = 2] = "Int64"; + AWTPropertyType[AWTPropertyType["Double"] = 3] = "Double"; + AWTPropertyType[AWTPropertyType["Boolean"] = 4] = "Boolean"; + AWTPropertyType[AWTPropertyType["Date"] = 5] = "Date"; + })(AWTPropertyType = exports.AWTPropertyType || (exports.AWTPropertyType = {})); + var AWTPiiKind; + (function(AWTPiiKind) { + AWTPiiKind[AWTPiiKind["NotSet"] = 0] = "NotSet"; + AWTPiiKind[AWTPiiKind["DistinguishedName"] = 1] = "DistinguishedName"; + AWTPiiKind[AWTPiiKind["GenericData"] = 2] = "GenericData"; + AWTPiiKind[AWTPiiKind["IPV4Address"] = 3] = "IPV4Address"; + AWTPiiKind[AWTPiiKind["IPv6Address"] = 4] = "IPv6Address"; + AWTPiiKind[AWTPiiKind["MailSubject"] = 5] = "MailSubject"; + AWTPiiKind[AWTPiiKind["PhoneNumber"] = 6] = "PhoneNumber"; + AWTPiiKind[AWTPiiKind["QueryString"] = 7] = "QueryString"; + AWTPiiKind[AWTPiiKind["SipAddress"] = 8] = "SipAddress"; + AWTPiiKind[AWTPiiKind["SmtpAddress"] = 9] = "SmtpAddress"; + AWTPiiKind[AWTPiiKind["Identity"] = 10] = "Identity"; + AWTPiiKind[AWTPiiKind["Uri"] = 11] = "Uri"; + AWTPiiKind[AWTPiiKind["Fqdn"] = 12] = "Fqdn"; + AWTPiiKind[AWTPiiKind["IPV4AddressLegacy"] = 13] = "IPV4AddressLegacy"; + })(AWTPiiKind = exports.AWTPiiKind || (exports.AWTPiiKind = {})); + var AWTCustomerContentKind; + (function(AWTCustomerContentKind) { + AWTCustomerContentKind[AWTCustomerContentKind["NotSet"] = 0] = "NotSet"; + AWTCustomerContentKind[AWTCustomerContentKind["GenericContent"] = 1] = "GenericContent"; + })(AWTCustomerContentKind = exports.AWTCustomerContentKind || (exports.AWTCustomerContentKind = {})); + var AWTEventPriority; + (function(AWTEventPriority) { + AWTEventPriority[AWTEventPriority["Low"] = 1] = "Low"; + AWTEventPriority[AWTEventPriority["Normal"] = 2] = "Normal"; + AWTEventPriority[AWTEventPriority["High"] = 3] = "High"; + AWTEventPriority[AWTEventPriority["Immediate_sync"] = 5] = "Immediate_sync"; + })(AWTEventPriority = exports.AWTEventPriority || (exports.AWTEventPriority = {})); + var AWTEventsDroppedReason; + (function(AWTEventsDroppedReason) { + AWTEventsDroppedReason[AWTEventsDroppedReason["NonRetryableStatus"] = 1] = "NonRetryableStatus"; + AWTEventsDroppedReason[AWTEventsDroppedReason["QueueFull"] = 3] = "QueueFull"; + AWTEventsDroppedReason[AWTEventsDroppedReason["MaxRetryLimit"] = 4] = "MaxRetryLimit"; + })(AWTEventsDroppedReason = exports.AWTEventsDroppedReason || (exports.AWTEventsDroppedReason = {})); + var AWTEventsRejectedReason; + (function(AWTEventsRejectedReason) { + AWTEventsRejectedReason[AWTEventsRejectedReason["InvalidEvent"] = 1] = "InvalidEvent"; + AWTEventsRejectedReason[AWTEventsRejectedReason["SizeLimitExceeded"] = 2] = "SizeLimitExceeded"; + AWTEventsRejectedReason[AWTEventsRejectedReason["KillSwitch"] = 3] = "KillSwitch"; + })(AWTEventsRejectedReason = exports.AWTEventsRejectedReason || (exports.AWTEventsRejectedReason = {})); +}, , function(module, exports, __webpack_require__) { + "use strict"; + Object.defineProperty(exports, "__esModule", { + value: true + }); + var microsoft_bond_primitives_1 = __webpack_require__(8); + var Enums_1 = __webpack_require__(0); + var GuidRegex = /[xy]/g; + var MSTillUnixEpoch = 621355968e5; + var MSToTicksMultiplier = 1e4; + var NullValue = null; + exports.EventNameAndTypeRegex = /^[a-zA-Z]([a-zA-Z0-9]|_){2,98}[a-zA-Z0-9]$/; + exports.EventNameDotRegex = /\./g; + exports.PropertyNameRegex = /^[a-zA-Z](([a-zA-Z0-9|_|\.]){0,98}[a-zA-Z0-9])?$/; + exports.StatsApiKey = "a387cfcf60114a43a7699f9fbb49289e-9bceb9fe-1c06-460f-96c5-6a0b247358bc-7238"; + var beaconsSupported = NullValue; + var uInt8ArraySupported = NullValue; + var useXDR = NullValue; + function numberToBondInt64(value) { + var bond_value = new microsoft_bond_primitives_1.Int64("0"); + bond_value.low = value & 4294967295; + bond_value.high = Math.floor(value / 4294967296); + return bond_value; + } + exports.numberToBondInt64 = numberToBondInt64; + function newGuid() { + return "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(GuidRegex, function(c) { + var r = Math.random() * 16 | 0, v = c === "x" ? r : r & 3 | 8; + return v.toString(16); + }); + } + exports.newGuid = newGuid; + function isString(value) { + return typeof value === "string"; + } + exports.isString = isString; + function isNumber(value) { + return typeof value === "number"; + } + exports.isNumber = isNumber; + function isBoolean(value) { + return typeof value === "boolean"; + } + exports.isBoolean = isBoolean; + function isDate(value) { + return value instanceof Date; + } + exports.isDate = isDate; + function msToTicks(timeInMs) { + return (timeInMs + MSTillUnixEpoch) * MSToTicksMultiplier; + } + exports.msToTicks = msToTicks; + function getTenantId(apiKey) { + var indexTenantId = apiKey.indexOf("-"); + if (indexTenantId > -1) { + return apiKey.substring(0, indexTenantId); + } + return ""; + } + exports.getTenantId = getTenantId; + function isBeaconsSupported() { + if (beaconsSupported === NullValue) { + beaconsSupported = typeof navigator !== "undefined" && Boolean(navigator.sendBeacon); + } + return beaconsSupported; + } + exports.isBeaconsSupported = isBeaconsSupported; + function isUint8ArrayAvailable() { + if (uInt8ArraySupported === NullValue) { + uInt8ArraySupported = typeof Uint8Array !== "undefined" && !isSafariOrFirefox() && !isReactNative(); + } + return uInt8ArraySupported; + } + exports.isUint8ArrayAvailable = isUint8ArrayAvailable; + function isPriority(value) { + if (isNumber(value) && (value >= 1 && value <= 3 || value === 5)) { + return true; + } + return false; + } + exports.isPriority = isPriority; + function sanitizeProperty(name, property) { + if (!exports.PropertyNameRegex.test(name) || isNotDefined(property)) { + return NullValue; + } + if (isNotDefined(property.value)) { + property = { + value: property, + type: Enums_1.AWTPropertyType.Unspecified + }; + } + property.type = sanitizePropertyType(property.value, property.type); + if (!property.type) { + return NullValue; + } + if (isDate(property.value)) { + property.value = msToTicks(property.value.getTime()); + } + if (property.pii > 0 && property.cc > 0) { + return NullValue; + } + if (property.pii) { + return isPii(property.pii) ? property : NullValue; + } + if (property.cc) { + return isCustomerContent(property.cc) ? property : NullValue; + } + return property; + } + exports.sanitizeProperty = sanitizeProperty; + function getISOString(date) { + return date.getUTCFullYear() + "-" + twoDigit(date.getUTCMonth() + 1) + "-" + twoDigit(date.getUTCDate()) + "T" + twoDigit(date.getUTCHours()) + ":" + twoDigit(date.getUTCMinutes()) + ":" + twoDigit(date.getUTCSeconds()) + "." + threeDigit(date.getUTCMilliseconds()) + "Z"; + } + exports.getISOString = getISOString; + function useXDomainRequest() { + if (useXDR === NullValue) { + var conn = new XMLHttpRequest(); + if (typeof conn.withCredentials === "undefined" && typeof XDomainRequest !== "undefined") { + useXDR = true; + } else { + useXDR = false; + } + } + return useXDR; + } + exports.useXDomainRequest = useXDomainRequest; + function useFetchRequest() { + return isReactNative() || isServiceWorkerGlobalScope(); + } + exports.useFetchRequest = useFetchRequest; + function isReactNative() { + if (typeof navigator !== "undefined" && navigator.product) { + return navigator.product === "ReactNative"; + } + return false; + } + exports.isReactNative = isReactNative; + function isServiceWorkerGlobalScope() { + if (typeof self === "object") { + return self.constructor.name === "ServiceWorkerGlobalScope"; + } + return false; + } + exports.isServiceWorkerGlobalScope = isServiceWorkerGlobalScope; + function twoDigit(n) { + return n < 10 ? "0" + n : n.toString(); + } + function threeDigit(n) { + if (n < 10) { + return "00" + n; + } else if (n < 100) { + return "0" + n; + } + return n.toString(); + } + function sanitizePropertyType(value, type) { + type = !isPropertyType(type) ? Enums_1.AWTPropertyType.Unspecified : type; + switch (type) { + case Enums_1.AWTPropertyType.Unspecified: + return getCorrectType(value); + + case Enums_1.AWTPropertyType.String: + return isString(value) ? type : NullValue; + + case Enums_1.AWTPropertyType.Boolean: + return isBoolean(value) ? type : NullValue; + + case Enums_1.AWTPropertyType.Date: + return isDate(value) && value.getTime() !== NaN ? type : NullValue; + + case Enums_1.AWTPropertyType.Int64: + return isNumber(value) && value % 1 === 0 ? type : NullValue; + + case Enums_1.AWTPropertyType.Double: + return isNumber(value) ? type : NullValue; + } + return NullValue; + } + function getCorrectType(value) { + switch (typeof value) { + case "string": + return Enums_1.AWTPropertyType.String; + + case "boolean": + return Enums_1.AWTPropertyType.Boolean; + + case "number": + return Enums_1.AWTPropertyType.Double; + + case "object": + return isDate(value) ? Enums_1.AWTPropertyType.Date : NullValue; + } + return NullValue; + } + function isPii(value) { + if (isNumber(value) && value >= 0 && value <= 13) { + return true; + } + return false; + } + function isCustomerContent(value) { + if (isNumber(value) && value >= 0 && value <= 1) { + return true; + } + return false; + } + function isPropertyType(value) { + if (isNumber(value) && value >= 0 && value <= 4) { + return true; + } + return false; + } + function isSafariOrFirefox() { + if (typeof navigator !== "undefined" && navigator.userAgent) { + var ua = navigator.userAgent.toLowerCase(); + if ((ua.indexOf("safari") >= 0 || ua.indexOf("firefox") >= 0) && ua.indexOf("chrome") < 0) { + return true; + } + } + return false; + } + function isNotDefined(value) { + return value === undefined || value === NullValue || value === ""; + } +}, function(module, exports, __webpack_require__) { + "use strict"; + Object.defineProperty(exports, "__esModule", { + value: true + }); + var DataModels_1 = __webpack_require__(12); + var Enums_1 = __webpack_require__(0); + var AWTQueueManager_1 = __webpack_require__(11); + var AWTStatsManager_1 = __webpack_require__(14); + var AWTEventProperties_1 = __webpack_require__(7); + var AWTLogManager_1 = __webpack_require__(17); + var Utils = __webpack_require__(2); + var MaxBackoffCount = 4; + var MinDurationBetweenUploadNow = 3e4; + var StatName = "awt_stats"; + var AWTTransmissionManagerCore = function() { + function AWTTransmissionManagerCore() {} + AWTTransmissionManagerCore.setEventsHandler = function(eventsHandler) { + this._eventHandler = eventsHandler; + }; + AWTTransmissionManagerCore.getEventsHandler = function() { + return this._eventHandler; + }; + AWTTransmissionManagerCore.scheduleTimer = function() { + var _this = this; + var timer = this._profiles[this._currentProfile][2]; + if (this._timeout < 0 && timer >= 0 && !this._paused) { + if (this._eventHandler.hasEvents()) { + if (timer === 0 && this._currentBackoffCount > 0) { + timer = 1; + } + this._timeout = setTimeout(function() { + return _this._batchAndSendEvents(); + }, timer * (1 << this._currentBackoffCount) * 1e3); + } else { + this._timerCount = 0; + } + } + }; + AWTTransmissionManagerCore.initialize = function(config) { + var _this = this; + this._newEventsAllowed = true; + this._config = config; + this._eventHandler = new AWTQueueManager_1.default(config.collectorUri, config.cacheMemorySizeLimitInNumberOfEvents, config.httpXHROverride, config.clockSkewRefreshDurationInMins); + this._initializeProfiles(); + AWTStatsManager_1.default.initialize(function(stats, tenantId) { + if (_this._config.canSendStatEvent(StatName)) { + var event_1 = new AWTEventProperties_1.default(StatName); + event_1.setEventPriority(Enums_1.AWTEventPriority.High); + event_1.setProperty("TenantId", tenantId); + for (var statKey in stats) { + if (stats.hasOwnProperty(statKey)) { + event_1.setProperty(statKey, stats[statKey].toString()); + } + } + AWTLogManager_1.default.getLogger(Utils.StatsApiKey).logEvent(event_1); + } + }); + }; + AWTTransmissionManagerCore.setTransmitProfile = function(profileName) { + if (this._currentProfile !== profileName && this._profiles[profileName] !== undefined) { + this.clearTimeout(); + this._currentProfile = profileName; + this.scheduleTimer(); + } + }; + AWTTransmissionManagerCore.loadTransmitProfiles = function(profiles) { + this._resetTransmitProfiles(); + for (var profileName in profiles) { + if (profiles.hasOwnProperty(profileName)) { + if (profiles[profileName].length !== 3) { + continue; + } + for (var i = 2; i >= 0; --i) { + if (profiles[profileName][i] < 0) { + for (var j = i; j >= 0; --j) { + profiles[profileName][j] = -1; + } + break; + } + } + for (var i = 2; i > 0; --i) { + if (profiles[profileName][i] > 0 && profiles[profileName][i - 1] > 0) { + var timerMultiplier = profiles[profileName][i - 1] / profiles[profileName][i]; + profiles[profileName][i - 1] = Math.ceil(timerMultiplier) * profiles[profileName][i]; + } + } + this._profiles[profileName] = profiles[profileName]; + } + } + }; + AWTTransmissionManagerCore.sendEvent = function(event) { + if (this._newEventsAllowed) { + if (this._currentBackoffCount > 0 && event.priority === Enums_1.AWTEventPriority.Immediate_sync) { + event.priority = Enums_1.AWTEventPriority.High; + } + this._eventHandler.addEvent(event); + this.scheduleTimer(); + } + }; + AWTTransmissionManagerCore.flush = function(callback) { + var currentTime = new Date().getTime(); + if (!this._paused && this._lastUploadNowCall + MinDurationBetweenUploadNow < currentTime) { + this._lastUploadNowCall = currentTime; + if (this._timeout > -1) { + clearTimeout(this._timeout); + this._timeout = -1; + } + this._eventHandler.uploadNow(callback); + } + }; + AWTTransmissionManagerCore.pauseTransmission = function() { + if (!this._paused) { + this.clearTimeout(); + this._eventHandler.pauseTransmission(); + this._paused = true; + } + }; + AWTTransmissionManagerCore.resumeTransmision = function() { + if (this._paused) { + this._paused = false; + this._eventHandler.resumeTransmission(); + this.scheduleTimer(); + } + }; + AWTTransmissionManagerCore.flushAndTeardown = function() { + AWTStatsManager_1.default.teardown(); + this._newEventsAllowed = false; + this.clearTimeout(); + this._eventHandler.teardown(); + }; + AWTTransmissionManagerCore.backOffTransmission = function() { + if (this._currentBackoffCount < MaxBackoffCount) { + this._currentBackoffCount++; + this.clearTimeout(); + this.scheduleTimer(); + } + }; + AWTTransmissionManagerCore.clearBackOff = function() { + if (this._currentBackoffCount > 0) { + this._currentBackoffCount = 0; + this.clearTimeout(); + this.scheduleTimer(); + } + }; + AWTTransmissionManagerCore._resetTransmitProfiles = function() { + this.clearTimeout(); + this._initializeProfiles(); + this._currentProfile = DataModels_1.AWT_REAL_TIME; + this.scheduleTimer(); + }; + AWTTransmissionManagerCore.clearTimeout = function() { + if (this._timeout > 0) { + clearTimeout(this._timeout); + this._timeout = -1; + this._timerCount = 0; + } + }; + AWTTransmissionManagerCore._batchAndSendEvents = function() { + var priority = Enums_1.AWTEventPriority.High; + this._timerCount++; + if (this._timerCount * this._profiles[this._currentProfile][2] === this._profiles[this._currentProfile][0]) { + priority = Enums_1.AWTEventPriority.Low; + this._timerCount = 0; + } else if (this._timerCount * this._profiles[this._currentProfile][2] === this._profiles[this._currentProfile][1]) { + priority = Enums_1.AWTEventPriority.Normal; + } + this._eventHandler.sendEventsForPriorityAndAbove(priority); + this._timeout = -1; + this.scheduleTimer(); + }; + AWTTransmissionManagerCore._initializeProfiles = function() { + this._profiles = {}; + this._profiles[DataModels_1.AWT_REAL_TIME] = [ 4, 2, 1 ]; + this._profiles[DataModels_1.AWT_NEAR_REAL_TIME] = [ 12, 6, 3 ]; + this._profiles[DataModels_1.AWT_BEST_EFFORT] = [ 36, 18, 9 ]; + }; + AWTTransmissionManagerCore._newEventsAllowed = false; + AWTTransmissionManagerCore._currentProfile = DataModels_1.AWT_REAL_TIME; + AWTTransmissionManagerCore._timeout = -1; + AWTTransmissionManagerCore._currentBackoffCount = 0; + AWTTransmissionManagerCore._paused = false; + AWTTransmissionManagerCore._timerCount = 0; + AWTTransmissionManagerCore._lastUploadNowCall = 0; + return AWTTransmissionManagerCore; + }(); + exports.default = AWTTransmissionManagerCore; +}, function(module, exports, __webpack_require__) { + "use strict"; + Object.defineProperty(exports, "__esModule", { + value: true + }); + var AWTNotificationManager = function() { + function AWTNotificationManager() {} + AWTNotificationManager.addNotificationListener = function(listener) { + this.listeners.push(listener); + }; + AWTNotificationManager.removeNotificationListener = function(listener) { + var index = this.listeners.indexOf(listener); + while (index > -1) { + this.listeners.splice(index, 1); + index = this.listeners.indexOf(listener); + } + }; + AWTNotificationManager.eventsSent = function(events) { + var _this = this; + var _loop_1 = function(i) { + if (this_1.listeners[i].eventsSent) { + setTimeout(function() { + return _this.listeners[i].eventsSent(events); + }, 0); + } + }; + var this_1 = this; + for (var i = 0; i < this.listeners.length; ++i) { + _loop_1(i); + } + }; + AWTNotificationManager.eventsDropped = function(events, reason) { + var _this = this; + var _loop_2 = function(i) { + if (this_2.listeners[i].eventsDropped) { + setTimeout(function() { + return _this.listeners[i].eventsDropped(events, reason); + }, 0); + } + }; + var this_2 = this; + for (var i = 0; i < this.listeners.length; ++i) { + _loop_2(i); + } + }; + AWTNotificationManager.eventsRetrying = function(events) { + var _this = this; + var _loop_3 = function(i) { + if (this_3.listeners[i].eventsRetrying) { + setTimeout(function() { + return _this.listeners[i].eventsRetrying(events); + }, 0); + } + }; + var this_3 = this; + for (var i = 0; i < this.listeners.length; ++i) { + _loop_3(i); + } + }; + AWTNotificationManager.eventsRejected = function(events, reason) { + var _this = this; + var _loop_4 = function(i) { + if (this_4.listeners[i].eventsRejected) { + setTimeout(function() { + return _this.listeners[i].eventsRejected(events, reason); + }, 0); + } + }; + var this_4 = this; + for (var i = 0; i < this.listeners.length; ++i) { + _loop_4(i); + } + }; + AWTNotificationManager.listeners = []; + return AWTNotificationManager; + }(); + exports.default = AWTNotificationManager; +}, function(module, exports, __webpack_require__) { + "use strict"; + Object.defineProperty(exports, "__esModule", { + value: true + }); + var Enums_1 = __webpack_require__(0); + exports.AWTPropertyType = Enums_1.AWTPropertyType; + exports.AWTPiiKind = Enums_1.AWTPiiKind; + exports.AWTEventPriority = Enums_1.AWTEventPriority; + exports.AWTEventsDroppedReason = Enums_1.AWTEventsDroppedReason; + exports.AWTEventsRejectedReason = Enums_1.AWTEventsRejectedReason; + exports.AWTCustomerContentKind = Enums_1.AWTCustomerContentKind; + var Enums_2 = __webpack_require__(6); + exports.AWTUserIdType = Enums_2.AWTUserIdType; + exports.AWTSessionState = Enums_2.AWTSessionState; + var DataModels_1 = __webpack_require__(12); + exports.AWT_BEST_EFFORT = DataModels_1.AWT_BEST_EFFORT; + exports.AWT_NEAR_REAL_TIME = DataModels_1.AWT_NEAR_REAL_TIME; + exports.AWT_REAL_TIME = DataModels_1.AWT_REAL_TIME; + var AWTEventProperties_1 = __webpack_require__(7); + exports.AWTEventProperties = AWTEventProperties_1.default; + var AWTLogger_1 = __webpack_require__(13); + exports.AWTLogger = AWTLogger_1.default; + var AWTLogManager_1 = __webpack_require__(17); + exports.AWTLogManager = AWTLogManager_1.default; + var AWTTransmissionManager_1 = __webpack_require__(36); + exports.AWTTransmissionManager = AWTTransmissionManager_1.default; + var AWTSerializer_1 = __webpack_require__(15); + exports.AWTSerializer = AWTSerializer_1.default; + var AWTSemanticContext_1 = __webpack_require__(9); + exports.AWTSemanticContext = AWTSemanticContext_1.default; + exports.AWT_COLLECTOR_URL_UNITED_STATES = "https://us.pipe.aria.microsoft.com/Collector/3.0/"; + exports.AWT_COLLECTOR_URL_GERMANY = "https://de.pipe.aria.microsoft.com/Collector/3.0/"; + exports.AWT_COLLECTOR_URL_JAPAN = "https://jp.pipe.aria.microsoft.com/Collector/3.0/"; + exports.AWT_COLLECTOR_URL_AUSTRALIA = "https://au.pipe.aria.microsoft.com/Collector/3.0/"; + exports.AWT_COLLECTOR_URL_EUROPE = "https://eu.pipe.aria.microsoft.com/Collector/3.0/"; + exports.AWT_COLLECTOR_URL_USGOV_DOD = "https://pf.pipe.aria.microsoft.com/Collector/3.0"; + exports.AWT_COLLECTOR_URL_USGOV_DOJ = "https://tb.pipe.aria.microsoft.com/Collector/3.0"; +}, function(module, exports, __webpack_require__) { + "use strict"; + Object.defineProperty(exports, "__esModule", { + value: true + }); + var AWTUserIdType; + (function(AWTUserIdType) { + AWTUserIdType[AWTUserIdType["Unknown"] = 0] = "Unknown"; + AWTUserIdType[AWTUserIdType["MSACID"] = 1] = "MSACID"; + AWTUserIdType[AWTUserIdType["MSAPUID"] = 2] = "MSAPUID"; + AWTUserIdType[AWTUserIdType["ANID"] = 3] = "ANID"; + AWTUserIdType[AWTUserIdType["OrgIdCID"] = 4] = "OrgIdCID"; + AWTUserIdType[AWTUserIdType["OrgIdPUID"] = 5] = "OrgIdPUID"; + AWTUserIdType[AWTUserIdType["UserObjectId"] = 6] = "UserObjectId"; + AWTUserIdType[AWTUserIdType["Skype"] = 7] = "Skype"; + AWTUserIdType[AWTUserIdType["Yammer"] = 8] = "Yammer"; + AWTUserIdType[AWTUserIdType["EmailAddress"] = 9] = "EmailAddress"; + AWTUserIdType[AWTUserIdType["PhoneNumber"] = 10] = "PhoneNumber"; + AWTUserIdType[AWTUserIdType["SipAddress"] = 11] = "SipAddress"; + AWTUserIdType[AWTUserIdType["MUID"] = 12] = "MUID"; + })(AWTUserIdType = exports.AWTUserIdType || (exports.AWTUserIdType = {})); + var AWTSessionState; + (function(AWTSessionState) { + AWTSessionState[AWTSessionState["Started"] = 0] = "Started"; + AWTSessionState[AWTSessionState["Ended"] = 1] = "Ended"; + })(AWTSessionState = exports.AWTSessionState || (exports.AWTSessionState = {})); +}, function(module, exports, __webpack_require__) { + "use strict"; + Object.defineProperty(exports, "__esModule", { + value: true + }); + var Utils = __webpack_require__(2); + var Enums_1 = __webpack_require__(0); + var AWTEventProperties = function() { + function AWTEventProperties(name) { + this._event = { + name: "", + properties: {} + }; + if (name) { + this.setName(name); + } + } + AWTEventProperties.prototype.setName = function(name) { + this._event.name = name; + }; + AWTEventProperties.prototype.getName = function() { + return this._event.name; + }; + AWTEventProperties.prototype.setType = function(type) { + this._event.type = type; + }; + AWTEventProperties.prototype.getType = function() { + return this._event.type; + }; + AWTEventProperties.prototype.setTimestamp = function(timestampInEpochMillis) { + this._event.timestamp = timestampInEpochMillis; + }; + AWTEventProperties.prototype.getTimestamp = function() { + return this._event.timestamp; + }; + AWTEventProperties.prototype.setEventPriority = function(priority) { + this._event.priority = priority; + }; + AWTEventProperties.prototype.getEventPriority = function() { + return this._event.priority; + }; + AWTEventProperties.prototype.setProperty = function(name, value, type) { + if (type === void 0) { + type = Enums_1.AWTPropertyType.Unspecified; + } + var property = { + value: value, + type: type, + pii: Enums_1.AWTPiiKind.NotSet, + cc: Enums_1.AWTCustomerContentKind.NotSet + }; + property = Utils.sanitizeProperty(name, property); + if (property === null) { + delete this._event.properties[name]; + return; + } + this._event.properties[name] = property; + }; + AWTEventProperties.prototype.setPropertyWithPii = function(name, value, pii, type) { + if (type === void 0) { + type = Enums_1.AWTPropertyType.Unspecified; + } + var property = { + value: value, + type: type, + pii: pii, + cc: Enums_1.AWTCustomerContentKind.NotSet + }; + property = Utils.sanitizeProperty(name, property); + if (property === null) { + delete this._event.properties[name]; + return; + } + this._event.properties[name] = property; + }; + AWTEventProperties.prototype.setPropertyWithCustomerContent = function(name, value, customerContent, type) { + if (type === void 0) { + type = Enums_1.AWTPropertyType.Unspecified; + } + var property = { + value: value, + type: type, + pii: Enums_1.AWTPiiKind.NotSet, + cc: customerContent + }; + property = Utils.sanitizeProperty(name, property); + if (property === null) { + delete this._event.properties[name]; + return; + } + this._event.properties[name] = property; + }; + AWTEventProperties.prototype.getPropertyMap = function() { + return this._event.properties; + }; + AWTEventProperties.prototype.getEvent = function() { + return this._event; + }; + return AWTEventProperties; + }(); + exports.default = AWTEventProperties; +}, function(module, exports, __webpack_require__) { + "use strict"; + Object.defineProperty(exports, "__esModule", { + value: true + }); + var Int64 = function() { + function Int64(numberStr) { + this.low = 0; + this.high = 0; + this.low = parseInt(numberStr, 10); + if (this.low < 0) { + this.high = -1; + } + } + Int64.prototype._Equals = function(numberStr) { + var tmp = new Int64(numberStr); + return this.low === tmp.low && this.high === tmp.high; + }; + return Int64; + }(); + exports.Int64 = Int64; + var UInt64 = function() { + function UInt64(numberStr) { + this.low = 0; + this.high = 0; + this.low = parseInt(numberStr, 10); + } + UInt64.prototype._Equals = function(numberStr) { + var tmp = new UInt64(numberStr); + return this.low === tmp.low && this.high === tmp.high; + }; + return UInt64; + }(); + exports.UInt64 = UInt64; + var Number = function() { + function Number() {} + Number._ToByte = function(value) { + return this._ToUInt8(value); + }; + Number._ToUInt8 = function(value) { + return value & 255; + }; + Number._ToInt32 = function(value) { + var signMask = value & 2147483648; + return value & 2147483647 | signMask; + }; + Number._ToUInt32 = function(value) { + return value & 4294967295; + }; + return Number; + }(); + exports.Number = Number; +}, function(module, exports, __webpack_require__) { + "use strict"; + Object.defineProperty(exports, "__esModule", { + value: true + }); + var AWTAutoCollection_1 = __webpack_require__(10); + var Enums_1 = __webpack_require__(0); + var Enums_2 = __webpack_require__(6); + var UI_IDTYPE = "UserInfo.IdType"; + var AWTSemanticContext = function() { + function AWTSemanticContext(_allowDeviceFields, _properties) { + this._allowDeviceFields = _allowDeviceFields; + this._properties = _properties; + } + AWTSemanticContext.prototype.setAppId = function(appId) { + this._addContext("AppInfo.Id", appId); + }; + AWTSemanticContext.prototype.setAppVersion = function(appVersion) { + this._addContext("AppInfo.Version", appVersion); + }; + AWTSemanticContext.prototype.setAppLanguage = function(appLanguage) { + this._addContext("AppInfo.Language", appLanguage); + }; + AWTSemanticContext.prototype.setDeviceId = function(deviceId) { + if (this._allowDeviceFields) { + AWTAutoCollection_1.default.checkAndSaveDeviceId(deviceId); + this._addContext("DeviceInfo.Id", deviceId); + } + }; + AWTSemanticContext.prototype.setDeviceOsName = function(deviceOsName) { + if (this._allowDeviceFields) { + this._addContext("DeviceInfo.OsName", deviceOsName); + } + }; + AWTSemanticContext.prototype.setDeviceOsVersion = function(deviceOsVersion) { + if (this._allowDeviceFields) { + this._addContext("DeviceInfo.OsVersion", deviceOsVersion); + } + }; + AWTSemanticContext.prototype.setDeviceBrowserName = function(deviceBrowserName) { + if (this._allowDeviceFields) { + this._addContext("DeviceInfo.BrowserName", deviceBrowserName); + } + }; + AWTSemanticContext.prototype.setDeviceBrowserVersion = function(deviceBrowserVersion) { + if (this._allowDeviceFields) { + this._addContext("DeviceInfo.BrowserVersion", deviceBrowserVersion); + } + }; + AWTSemanticContext.prototype.setDeviceMake = function(deviceMake) { + if (this._allowDeviceFields) { + this._addContext("DeviceInfo.Make", deviceMake); + } + }; + AWTSemanticContext.prototype.setDeviceModel = function(deviceModel) { + if (this._allowDeviceFields) { + this._addContext("DeviceInfo.Model", deviceModel); + } + }; + AWTSemanticContext.prototype.setUserId = function(userId, pii, userIdType) { + if (!isNaN(userIdType) && userIdType !== null && userIdType >= 0 && userIdType <= 12) { + this._addContext(UI_IDTYPE, userIdType.toString()); + } else { + var inferredUserIdType = void 0; + switch (pii) { + case Enums_1.AWTPiiKind.SipAddress: + inferredUserIdType = Enums_2.AWTUserIdType.SipAddress; + break; + + case Enums_1.AWTPiiKind.PhoneNumber: + inferredUserIdType = Enums_2.AWTUserIdType.PhoneNumber; + break; + + case Enums_1.AWTPiiKind.SmtpAddress: + inferredUserIdType = Enums_2.AWTUserIdType.EmailAddress; + break; + + default: + inferredUserIdType = Enums_2.AWTUserIdType.Unknown; + break; + } + this._addContext(UI_IDTYPE, inferredUserIdType.toString()); + } + if (isNaN(pii) || pii === null || pii === Enums_1.AWTPiiKind.NotSet || pii > 13) { + switch (userIdType) { + case Enums_2.AWTUserIdType.Skype: + pii = Enums_1.AWTPiiKind.Identity; + break; + + case Enums_2.AWTUserIdType.EmailAddress: + pii = Enums_1.AWTPiiKind.SmtpAddress; + break; + + case Enums_2.AWTUserIdType.PhoneNumber: + pii = Enums_1.AWTPiiKind.PhoneNumber; + break; + + case Enums_2.AWTUserIdType.SipAddress: + pii = Enums_1.AWTPiiKind.SipAddress; + break; + + default: + pii = Enums_1.AWTPiiKind.NotSet; + break; + } + } + this._addContextWithPii("UserInfo.Id", userId, pii); + }; + AWTSemanticContext.prototype.setUserAdvertisingId = function(userAdvertisingId) { + this._addContext("UserInfo.AdvertisingId", userAdvertisingId); + }; + AWTSemanticContext.prototype.setUserTimeZone = function(userTimeZone) { + this._addContext("UserInfo.TimeZone", userTimeZone); + }; + AWTSemanticContext.prototype.setUserLanguage = function(userLanguage) { + this._addContext("UserInfo.Language", userLanguage); + }; + AWTSemanticContext.prototype._addContext = function(key, value) { + if (typeof value === "string") { + this._properties.setProperty(key, value); + } + }; + AWTSemanticContext.prototype._addContextWithPii = function(key, value, pii) { + if (typeof value === "string") { + this._properties.setPropertyWithPii(key, value, pii); + } + }; + return AWTSemanticContext; + }(); + exports.default = AWTSemanticContext; +}, function(module, exports, __webpack_require__) { + "use strict"; + Object.defineProperty(exports, "__esModule", { + value: true + }); + var Utils = __webpack_require__(2); + var DEVICE_ID_COOKIE = "MicrosoftApplicationsTelemetryDeviceId"; + var FIRSTLAUNCHTIME_COOKIE = "MicrosoftApplicationsTelemetryFirstLaunchTime"; + var BROWSERS = { + MSIE: "MSIE", + CHROME: "Chrome", + FIREFOX: "Firefox", + SAFARI: "Safari", + EDGE: "Edge", + ELECTRON: "Electron", + SKYPE_SHELL: "SkypeShell", + PHANTOMJS: "PhantomJS", + OPERA: "Opera" + }; + var OPERATING_SYSTEMS = { + WINDOWS: "Windows", + MACOSX: "Mac OS X", + WINDOWS_PHONE: "Windows Phone", + WINDOWS_RT: "Windows RT", + IOS: "iOS", + ANDROID: "Android", + LINUX: "Linux", + CROS: "Chrome OS", + UNKNOWN: "Unknown" + }; + var OSNAMEREGEX = { + WIN: /(windows|win32)/i, + WINRT: / arm;/i, + WINPHONE: /windows\sphone\s\d+\.\d+/i, + OSX: /(macintosh|mac os x)/i, + IOS: /(iPad|iPhone|iPod)(?=.*like Mac OS X)/i, + LINUX: /(linux|joli|[kxln]?ubuntu|debian|[open]*suse|gentoo|arch|slackware|fedora|mandriva|centos|pclinuxos|redhat|zenwalk)/i, + ANDROID: /android/i, + CROS: /CrOS/i + }; + var VERSION_MAPPINGS = { + 5.1: "XP", + "6.0": "Vista", + 6.1: "7", + 6.2: "8", + 6.3: "8.1", + "10.0": "10" + }; + var REGEX_VERSION = "([\\d,.]+)"; + var REGEX_VERSION_MAC = "([\\d,_,.]+)"; + var UNKNOWN = "Unknown"; + var UNDEFINED = "undefined"; + var AWTAutoCollection = function() { + function AWTAutoCollection() {} + AWTAutoCollection.addPropertyStorageOverride = function(propertyStorage) { + if (propertyStorage) { + this._propertyStorage = propertyStorage; + return true; + } + return false; + }; + AWTAutoCollection.autoCollect = function(semanticContext, disableCookies, userAgent) { + this._semanticContext = semanticContext; + this._disableCookies = disableCookies; + this._autoCollect(); + if (!userAgent && typeof navigator !== UNDEFINED) { + userAgent = navigator.userAgent || ""; + } + this._autoCollectFromUserAgent(userAgent); + if (this._disableCookies && !this._propertyStorage) { + this._deleteCookie(DEVICE_ID_COOKIE); + this._deleteCookie(FIRSTLAUNCHTIME_COOKIE); + return; + } + if (this._propertyStorage || this._areCookiesAvailable && !this._disableCookies) { + this._autoCollectDeviceId(); + } + }; + AWTAutoCollection.checkAndSaveDeviceId = function(deviceId) { + if (deviceId) { + var oldDeviceId = this._getData(DEVICE_ID_COOKIE); + var flt = this._getData(FIRSTLAUNCHTIME_COOKIE); + if (oldDeviceId !== deviceId) { + flt = Utils.getISOString(new Date()); + } + this._saveData(DEVICE_ID_COOKIE, deviceId); + this._saveData(FIRSTLAUNCHTIME_COOKIE, flt); + this._setFirstLaunchTime(flt); + } + }; + AWTAutoCollection._autoCollectDeviceId = function() { + var deviceId = this._getData(DEVICE_ID_COOKIE); + if (!deviceId) { + deviceId = Utils.newGuid(); + } + this._semanticContext.setDeviceId(deviceId); + }; + AWTAutoCollection._autoCollect = function() { + if (typeof document !== UNDEFINED && document.documentElement) { + this._semanticContext.setAppLanguage(document.documentElement.lang); + } + if (typeof navigator !== UNDEFINED) { + this._semanticContext.setUserLanguage(navigator.userLanguage || navigator.language); + } + var timeZone = new Date().getTimezoneOffset(); + var minutes = timeZone % 60; + var hours = (timeZone - minutes) / 60; + var timeZonePrefix = "+"; + if (hours > 0) { + timeZonePrefix = "-"; + } + hours = Math.abs(hours); + minutes = Math.abs(minutes); + this._semanticContext.setUserTimeZone(timeZonePrefix + (hours < 10 ? "0" + hours : hours.toString()) + ":" + (minutes < 10 ? "0" + minutes : minutes.toString())); + }; + AWTAutoCollection._autoCollectFromUserAgent = function(userAgent) { + if (userAgent) { + var browserName = this._getBrowserName(userAgent); + this._semanticContext.setDeviceBrowserName(browserName); + this._semanticContext.setDeviceBrowserVersion(this._getBrowserVersion(userAgent, browserName)); + var osName = this._getOsName(userAgent); + this._semanticContext.setDeviceOsName(osName); + this._semanticContext.setDeviceOsVersion(this._getOsVersion(userAgent, osName)); + } + }; + AWTAutoCollection._getBrowserName = function(userAgent) { + if (this._userAgentContainsString("OPR/", userAgent)) { + return BROWSERS.OPERA; + } + if (this._userAgentContainsString(BROWSERS.PHANTOMJS, userAgent)) { + return BROWSERS.PHANTOMJS; + } + if (this._userAgentContainsString(BROWSERS.EDGE, userAgent) || this._userAgentContainsString("Edg", userAgent)) { + return BROWSERS.EDGE; + } + if (this._userAgentContainsString(BROWSERS.ELECTRON, userAgent)) { + return BROWSERS.ELECTRON; + } + if (this._userAgentContainsString(BROWSERS.CHROME, userAgent)) { + return BROWSERS.CHROME; + } + if (this._userAgentContainsString("Trident", userAgent)) { + return BROWSERS.MSIE; + } + if (this._userAgentContainsString(BROWSERS.FIREFOX, userAgent)) { + return BROWSERS.FIREFOX; + } + if (this._userAgentContainsString(BROWSERS.SAFARI, userAgent)) { + return BROWSERS.SAFARI; + } + if (this._userAgentContainsString(BROWSERS.SKYPE_SHELL, userAgent)) { + return BROWSERS.SKYPE_SHELL; + } + return UNKNOWN; + }; + AWTAutoCollection._setFirstLaunchTime = function(flt) { + if (!isNaN(flt)) { + var fltDate = new Date(); + fltDate.setTime(parseInt(flt, 10)); + flt = Utils.getISOString(fltDate); + } + this.firstLaunchTime = flt; + }; + AWTAutoCollection._userAgentContainsString = function(searchString, userAgent) { + return userAgent.indexOf(searchString) > -1; + }; + AWTAutoCollection._getBrowserVersion = function(userAgent, browserName) { + if (browserName === BROWSERS.MSIE) { + return this._getIeVersion(userAgent); + } else { + return this._getOtherVersion(browserName, userAgent); + } + }; + AWTAutoCollection._getIeVersion = function(userAgent) { + var classicIeVersionMatches = userAgent.match(new RegExp(BROWSERS.MSIE + " " + REGEX_VERSION)); + if (classicIeVersionMatches) { + return classicIeVersionMatches[1]; + } else { + var ieVersionMatches = userAgent.match(new RegExp("rv:" + REGEX_VERSION)); + if (ieVersionMatches) { + return ieVersionMatches[1]; + } + } + }; + AWTAutoCollection._getOtherVersion = function(browserString, userAgent) { + if (browserString === BROWSERS.SAFARI) { + browserString = "Version"; + } + var matches = userAgent.match(new RegExp(browserString + "/" + REGEX_VERSION)); + if (matches) { + return matches[1]; + } + return UNKNOWN; + }; + AWTAutoCollection._getOsName = function(userAgent) { + if (userAgent.match(OSNAMEREGEX.WINPHONE)) { + return OPERATING_SYSTEMS.WINDOWS_PHONE; + } + if (userAgent.match(OSNAMEREGEX.WINRT)) { + return OPERATING_SYSTEMS.WINDOWS_RT; + } + if (userAgent.match(OSNAMEREGEX.IOS)) { + return OPERATING_SYSTEMS.IOS; + } + if (userAgent.match(OSNAMEREGEX.ANDROID)) { + return OPERATING_SYSTEMS.ANDROID; + } + if (userAgent.match(OSNAMEREGEX.LINUX)) { + return OPERATING_SYSTEMS.LINUX; + } + if (userAgent.match(OSNAMEREGEX.OSX)) { + return OPERATING_SYSTEMS.MACOSX; + } + if (userAgent.match(OSNAMEREGEX.WIN)) { + return OPERATING_SYSTEMS.WINDOWS; + } + if (userAgent.match(OSNAMEREGEX.CROS)) { + return OPERATING_SYSTEMS.CROS; + } + return UNKNOWN; + }; + AWTAutoCollection._getOsVersion = function(userAgent, osName) { + if (osName === OPERATING_SYSTEMS.WINDOWS) { + return this._getGenericOsVersion(userAgent, "Windows NT"); + } + if (osName === OPERATING_SYSTEMS.ANDROID) { + return this._getGenericOsVersion(userAgent, osName); + } + if (osName === OPERATING_SYSTEMS.MACOSX) { + return this._getMacOsxVersion(userAgent); + } + return UNKNOWN; + }; + AWTAutoCollection._getGenericOsVersion = function(userAgent, osName) { + var ntVersionMatches = userAgent.match(new RegExp(osName + " " + REGEX_VERSION)); + if (ntVersionMatches) { + if (VERSION_MAPPINGS[ntVersionMatches[1]]) { + return VERSION_MAPPINGS[ntVersionMatches[1]]; + } + return ntVersionMatches[1]; + } + return UNKNOWN; + }; + AWTAutoCollection._getMacOsxVersion = function(userAgent) { + var macOsxVersionInUserAgentMatches = userAgent.match(new RegExp(OPERATING_SYSTEMS.MACOSX + " " + REGEX_VERSION_MAC)); + if (macOsxVersionInUserAgentMatches) { + var versionString = macOsxVersionInUserAgentMatches[1].replace(/_/g, "."); + if (versionString) { + var delimiter = this._getDelimiter(versionString); + if (delimiter) { + var components = versionString.split(delimiter); + return components[0]; + } else { + return versionString; + } + } + } + return UNKNOWN; + }; + AWTAutoCollection._getDelimiter = function(versionString) { + if (versionString.indexOf(".") > -1) { + return "."; + } + if (versionString.indexOf("_") > -1) { + return "_"; + } + return null; + }; + AWTAutoCollection._saveData = function(name, value) { + if (this._propertyStorage) { + this._propertyStorage.setProperty(name, value); + } else if (this._areCookiesAvailable) { + var date = new Date(); + date.setTime(date.getTime() + 31536e6); + var expires = "expires=" + date.toUTCString(); + document.cookie = name + "=" + value + "; " + expires; + } + }; + AWTAutoCollection._getData = function(name) { + if (this._propertyStorage) { + return this._propertyStorage.getProperty(name) || ""; + } else if (this._areCookiesAvailable) { + name = name + "="; + var ca = document.cookie.split(";"); + for (var i = 0; i < ca.length; i++) { + var c = ca[i]; + var j = 0; + while (c.charAt(j) === " ") { + j++; + } + c = c.substring(j); + if (c.indexOf(name) === 0) { + return c.substring(name.length, c.length); + } + } + } + return ""; + }; + AWTAutoCollection._deleteCookie = function(name) { + if (this._areCookiesAvailable) { + document.cookie = name + "=;expires=Thu, 01 Jan 1970 00:00:01 GMT;"; + } + }; + AWTAutoCollection._disableCookies = false; + AWTAutoCollection._areCookiesAvailable = typeof document !== UNDEFINED && typeof document.cookie !== UNDEFINED; + return AWTAutoCollection; + }(); + exports.default = AWTAutoCollection; +}, function(module, exports, __webpack_require__) { + "use strict"; + Object.defineProperty(exports, "__esModule", { + value: true + }); + var Enums_1 = __webpack_require__(0); + var AWTHttpManager_1 = __webpack_require__(25); + var AWTTransmissionManagerCore_1 = __webpack_require__(3); + var AWTRecordBatcher_1 = __webpack_require__(35); + var AWTNotificationManager_1 = __webpack_require__(4); + var Utils = __webpack_require__(2); + var UploadNowCheckTimer = 250; + var MaxNumberEventPerBatch = 500; + var MaxSendAttempts = 6; + var AWTQueueManager = function() { + function AWTQueueManager(collectorUrl, _queueSizeLimit, xhrOverride, clockSkewRefreshDurationInMins) { + this._queueSizeLimit = _queueSizeLimit; + this._isCurrentlyUploadingNow = false; + this._uploadNowQueue = []; + this._shouldDropEventsOnPause = false; + this._paused = false; + this._queueSize = 0; + this._outboundQueue = []; + this._inboundQueues = {}; + this._inboundQueues[Enums_1.AWTEventPriority.High] = []; + this._inboundQueues[Enums_1.AWTEventPriority.Normal] = []; + this._inboundQueues[Enums_1.AWTEventPriority.Low] = []; + this._addEmptyQueues(); + this._batcher = new AWTRecordBatcher_1.default(this._outboundQueue, MaxNumberEventPerBatch); + this._httpManager = new AWTHttpManager_1.default(this._outboundQueue, collectorUrl, this, xhrOverride, clockSkewRefreshDurationInMins); + } + AWTQueueManager.prototype.addEvent = function(event) { + if (!Utils.isPriority(event.priority)) { + event.priority = Enums_1.AWTEventPriority.Normal; + } + if (event.priority === Enums_1.AWTEventPriority.Immediate_sync) { + this._httpManager.sendSynchronousRequest(this._batcher.addEventToBatch(event), event.apiKey); + } else if (this._queueSize < this._queueSizeLimit) { + this._addEventToProperQueue(event); + } else { + if (this._dropEventWithPriorityOrLess(event.priority)) { + this._addEventToProperQueue(event); + } else { + AWTNotificationManager_1.default.eventsDropped([ event ], Enums_1.AWTEventsDroppedReason.QueueFull); + } + } + }; + AWTQueueManager.prototype.sendEventsForPriorityAndAbove = function(priority) { + this._batchEvents(priority); + this._httpManager.sendQueuedRequests(); + }; + AWTQueueManager.prototype.hasEvents = function() { + return (this._inboundQueues[Enums_1.AWTEventPriority.High][0].length > 0 || this._inboundQueues[Enums_1.AWTEventPriority.Normal][0].length > 0 || this._inboundQueues[Enums_1.AWTEventPriority.Low][0].length > 0 || this._batcher.hasBatch()) && this._httpManager.hasIdleConnection(); + }; + AWTQueueManager.prototype.addBackRequest = function(request) { + if (!this._paused || !this._shouldDropEventsOnPause) { + for (var token in request) { + if (request.hasOwnProperty(token)) { + for (var i = 0; i < request[token].length; ++i) { + if (request[token][i].sendAttempt < MaxSendAttempts) { + this.addEvent(request[token][i]); + } else { + AWTNotificationManager_1.default.eventsDropped([ request[token][i] ], Enums_1.AWTEventsDroppedReason.MaxRetryLimit); + } + } + } + } + AWTTransmissionManagerCore_1.default.scheduleTimer(); + } + }; + AWTQueueManager.prototype.teardown = function() { + if (!this._paused) { + this._batchEvents(Enums_1.AWTEventPriority.Low); + this._httpManager.teardown(); + } + }; + AWTQueueManager.prototype.uploadNow = function(callback) { + var _this = this; + this._addEmptyQueues(); + if (!this._isCurrentlyUploadingNow) { + this._isCurrentlyUploadingNow = true; + setTimeout(function() { + return _this._uploadNow(callback); + }, 0); + } else { + this._uploadNowQueue.push(callback); + } + }; + AWTQueueManager.prototype.pauseTransmission = function() { + this._paused = true; + this._httpManager.pause(); + if (this.shouldDropEventsOnPause) { + this._queueSize -= this._inboundQueues[Enums_1.AWTEventPriority.High][0].length + this._inboundQueues[Enums_1.AWTEventPriority.Normal][0].length + this._inboundQueues[Enums_1.AWTEventPriority.Low][0].length; + this._inboundQueues[Enums_1.AWTEventPriority.High][0] = []; + this._inboundQueues[Enums_1.AWTEventPriority.Normal][0] = []; + this._inboundQueues[Enums_1.AWTEventPriority.Low][0] = []; + this._httpManager.removeQueuedRequests(); + } + }; + AWTQueueManager.prototype.resumeTransmission = function() { + this._paused = false; + this._httpManager.resume(); + }; + AWTQueueManager.prototype.shouldDropEventsOnPause = function(shouldDropEventsOnPause) { + this._shouldDropEventsOnPause = shouldDropEventsOnPause; + }; + AWTQueueManager.prototype._removeFirstQueues = function() { + this._inboundQueues[Enums_1.AWTEventPriority.High].shift(); + this._inboundQueues[Enums_1.AWTEventPriority.Normal].shift(); + this._inboundQueues[Enums_1.AWTEventPriority.Low].shift(); + }; + AWTQueueManager.prototype._addEmptyQueues = function() { + this._inboundQueues[Enums_1.AWTEventPriority.High].push([]); + this._inboundQueues[Enums_1.AWTEventPriority.Normal].push([]); + this._inboundQueues[Enums_1.AWTEventPriority.Low].push([]); + }; + AWTQueueManager.prototype._addEventToProperQueue = function(event) { + if (!this._paused || !this._shouldDropEventsOnPause) { + this._queueSize++; + this._inboundQueues[event.priority][this._inboundQueues[event.priority].length - 1].push(event); + } + }; + AWTQueueManager.prototype._dropEventWithPriorityOrLess = function(priority) { + var currentPriority = Enums_1.AWTEventPriority.Low; + while (currentPriority <= priority) { + if (this._inboundQueues[currentPriority][this._inboundQueues[currentPriority].length - 1].length > 0) { + AWTNotificationManager_1.default.eventsDropped([ this._inboundQueues[currentPriority][this._inboundQueues[currentPriority].length - 1].shift() ], Enums_1.AWTEventsDroppedReason.QueueFull); + return true; + } + currentPriority++; + } + return false; + }; + AWTQueueManager.prototype._batchEvents = function(priority) { + var priorityToProcess = Enums_1.AWTEventPriority.High; + while (priorityToProcess >= priority) { + while (this._inboundQueues[priorityToProcess][0].length > 0) { + var event_1 = this._inboundQueues[priorityToProcess][0].pop(); + this._queueSize--; + this._batcher.addEventToBatch(event_1); + } + priorityToProcess--; + } + this._batcher.flushBatch(); + }; + AWTQueueManager.prototype._uploadNow = function(callback) { + var _this = this; + if (this.hasEvents()) { + this.sendEventsForPriorityAndAbove(Enums_1.AWTEventPriority.Low); + } + this._checkOutboundQueueEmptyAndSent(function() { + _this._removeFirstQueues(); + if (callback !== null && callback !== undefined) { + callback(); + } + if (_this._uploadNowQueue.length > 0) { + setTimeout(function() { + return _this._uploadNow(_this._uploadNowQueue.shift()); + }, 0); + } else { + _this._isCurrentlyUploadingNow = false; + if (_this.hasEvents()) { + AWTTransmissionManagerCore_1.default.scheduleTimer(); + } + } + }); + }; + AWTQueueManager.prototype._checkOutboundQueueEmptyAndSent = function(callback) { + var _this = this; + if (this._httpManager.isCompletelyIdle()) { + callback(); + } else { + setTimeout(function() { + return _this._checkOutboundQueueEmptyAndSent(callback); + }, UploadNowCheckTimer); + } + }; + return AWTQueueManager; + }(); + exports.default = AWTQueueManager; +}, function(module, exports, __webpack_require__) { + "use strict"; + Object.defineProperty(exports, "__esModule", { + value: true + }); + exports.AWT_REAL_TIME = "REAL_TIME"; + exports.AWT_NEAR_REAL_TIME = "NEAR_REAL_TIME"; + exports.AWT_BEST_EFFORT = "BEST_EFFORT"; +}, function(module, exports, __webpack_require__) { + "use strict"; + Object.defineProperty(exports, "__esModule", { + value: true + }); + var Enums_1 = __webpack_require__(0); + var Enums_2 = __webpack_require__(6); + var AWTEventProperties_1 = __webpack_require__(7); + var Utils = __webpack_require__(2); + var AWTStatsManager_1 = __webpack_require__(14); + var AWTNotificationManager_1 = __webpack_require__(4); + var AWTTransmissionManagerCore_1 = __webpack_require__(3); + var AWTLogManagerSettings_1 = __webpack_require__(18); + var Version = __webpack_require__(16); + var AWTSemanticContext_1 = __webpack_require__(9); + var AWTAutoCollection_1 = __webpack_require__(10); + var AWTLogger = function() { + function AWTLogger(_apiKey) { + this._apiKey = _apiKey; + this._contextProperties = new AWTEventProperties_1.default(); + this._semanticContext = new AWTSemanticContext_1.default(false, this._contextProperties); + this._sessionStartTime = 0; + this._createInitId(); + } + AWTLogger.prototype.setContext = function(name, value, type) { + if (type === void 0) { + type = Enums_1.AWTPropertyType.Unspecified; + } + this._contextProperties.setProperty(name, value, type); + }; + AWTLogger.prototype.setContextWithPii = function(name, value, pii, type) { + if (type === void 0) { + type = Enums_1.AWTPropertyType.Unspecified; + } + this._contextProperties.setPropertyWithPii(name, value, pii, type); + }; + AWTLogger.prototype.setContextWithCustomerContent = function(name, value, customerContent, type) { + if (type === void 0) { + type = Enums_1.AWTPropertyType.Unspecified; + } + this._contextProperties.setPropertyWithCustomerContent(name, value, customerContent, type); + }; + AWTLogger.prototype.getSemanticContext = function() { + return this._semanticContext; + }; + AWTLogger.prototype.logEvent = function(event) { + if (AWTLogManagerSettings_1.default.loggingEnabled) { + if (!this._apiKey) { + this._apiKey = AWTLogManagerSettings_1.default.defaultTenantToken; + this._createInitId(); + } + var sanitizeProperties = true; + if (Utils.isString(event)) { + event = { + name: event + }; + } else if (event instanceof AWTEventProperties_1.default) { + event = event.getEvent(); + sanitizeProperties = false; + } + AWTStatsManager_1.default.eventReceived(this._apiKey); + AWTLogger._logEvent(AWTLogger._getInternalEvent(event, this._apiKey, sanitizeProperties), this._contextProperties); + } + }; + AWTLogger.prototype.logSession = function(state, properties) { + if (AWTLogManagerSettings_1.default.sessionEnabled) { + var sessionEvent = { + name: "session", + type: "session", + properties: {} + }; + AWTLogger._addPropertiesToEvent(sessionEvent, properties); + sessionEvent.priority = Enums_1.AWTEventPriority.High; + if (state === Enums_2.AWTSessionState.Started) { + if (this._sessionStartTime > 0) { + return; + } + this._sessionStartTime = new Date().getTime(); + this._sessionId = Utils.newGuid(); + this.setContext("Session.Id", this._sessionId); + sessionEvent.properties["Session.State"] = "Started"; + } else if (state === Enums_2.AWTSessionState.Ended) { + if (this._sessionStartTime === 0) { + return; + } + var sessionDurationSec = Math.floor((new Date().getTime() - this._sessionStartTime) / 1e3); + sessionEvent.properties["Session.Id"] = this._sessionId; + sessionEvent.properties["Session.State"] = "Ended"; + sessionEvent.properties["Session.Duration"] = sessionDurationSec.toString(); + sessionEvent.properties["Session.DurationBucket"] = AWTLogger._getSessionDurationFromTime(sessionDurationSec); + this._sessionStartTime = 0; + this.setContext("Session.Id", null); + this._sessionId = undefined; + } else { + return; + } + sessionEvent.properties["Session.FirstLaunchTime"] = AWTAutoCollection_1.default.firstLaunchTime; + this.logEvent(sessionEvent); + } + }; + AWTLogger.prototype.getSessionId = function() { + return this._sessionId; + }; + AWTLogger.prototype.logFailure = function(signature, detail, category, id, properties) { + if (!signature || !detail) { + return; + } + var failureEvent = { + name: "failure", + type: "failure", + properties: {} + }; + AWTLogger._addPropertiesToEvent(failureEvent, properties); + failureEvent.properties["Failure.Signature"] = signature; + failureEvent.properties["Failure.Detail"] = detail; + if (category) { + failureEvent.properties["Failure.Category"] = category; + } + if (id) { + failureEvent.properties["Failure.Id"] = id; + } + failureEvent.priority = Enums_1.AWTEventPriority.High; + this.logEvent(failureEvent); + }; + AWTLogger.prototype.logPageView = function(id, pageName, category, uri, referrerUri, properties) { + if (!id || !pageName) { + return; + } + var pageViewEvent = { + name: "pageview", + type: "pageview", + properties: {} + }; + AWTLogger._addPropertiesToEvent(pageViewEvent, properties); + pageViewEvent.properties["PageView.Id"] = id; + pageViewEvent.properties["PageView.Name"] = pageName; + if (category) { + pageViewEvent.properties["PageView.Category"] = category; + } + if (uri) { + pageViewEvent.properties["PageView.Uri"] = uri; + } + if (referrerUri) { + pageViewEvent.properties["PageView.ReferrerUri"] = referrerUri; + } + this.logEvent(pageViewEvent); + }; + AWTLogger.prototype._createInitId = function() { + if (!AWTLogger._initIdMap[this._apiKey] && this._apiKey) { + AWTLogger._initIdMap[this._apiKey] = Utils.newGuid(); + } + }; + AWTLogger._addPropertiesToEvent = function(event, propertiesEvent) { + if (propertiesEvent) { + if (propertiesEvent instanceof AWTEventProperties_1.default) { + propertiesEvent = propertiesEvent.getEvent(); + } + if (propertiesEvent.name) { + event.name = propertiesEvent.name; + } + if (propertiesEvent.priority) { + event.priority = propertiesEvent.priority; + } + for (var name_1 in propertiesEvent.properties) { + if (propertiesEvent.properties.hasOwnProperty(name_1)) { + event.properties[name_1] = propertiesEvent.properties[name_1]; + } + } + } + }; + AWTLogger._getSessionDurationFromTime = function(timeInSec) { + if (timeInSec < 0) { + return "Undefined"; + } else if (timeInSec <= 3) { + return "UpTo3Sec"; + } else if (timeInSec <= 10) { + return "UpTo10Sec"; + } else if (timeInSec <= 30) { + return "UpTo30Sec"; + } else if (timeInSec <= 60) { + return "UpTo60Sec"; + } else if (timeInSec <= 180) { + return "UpTo3Min"; + } else if (timeInSec <= 600) { + return "UpTo10Min"; + } else if (timeInSec <= 1800) { + return "UpTo30Min"; + } + return "Above30Min"; + }; + AWTLogger._logEvent = function(eventWithMetaData, contextProperties) { + if (!eventWithMetaData.name || !Utils.isString(eventWithMetaData.name)) { + AWTNotificationManager_1.default.eventsRejected([ eventWithMetaData ], Enums_1.AWTEventsRejectedReason.InvalidEvent); + return; + } + eventWithMetaData.name = eventWithMetaData.name.toLowerCase(); + eventWithMetaData.name = eventWithMetaData.name.replace(Utils.EventNameDotRegex, "_"); + if (!eventWithMetaData.type || !Utils.isString(eventWithMetaData.type)) { + eventWithMetaData.type = "custom"; + } else { + eventWithMetaData.type = eventWithMetaData.type.toLowerCase(); + } + if (!Utils.EventNameAndTypeRegex.test(eventWithMetaData.name) || !Utils.EventNameAndTypeRegex.test(eventWithMetaData.type)) { + AWTNotificationManager_1.default.eventsRejected([ eventWithMetaData ], Enums_1.AWTEventsRejectedReason.InvalidEvent); + return; + } + if (!Utils.isNumber(eventWithMetaData.timestamp) || eventWithMetaData.timestamp < 0) { + eventWithMetaData.timestamp = new Date().getTime(); + } + if (!eventWithMetaData.properties) { + eventWithMetaData.properties = {}; + } + this._addContextIfAbsent(eventWithMetaData, contextProperties.getPropertyMap()); + this._addContextIfAbsent(eventWithMetaData, AWTLogManagerSettings_1.default.logManagerContext.getPropertyMap()); + this._setDefaultProperty(eventWithMetaData, "EventInfo.InitId", this._getInitId(eventWithMetaData.apiKey)); + this._setDefaultProperty(eventWithMetaData, "EventInfo.Sequence", this._getSequenceId(eventWithMetaData.apiKey)); + this._setDefaultProperty(eventWithMetaData, "EventInfo.SdkVersion", Version.FullVersionString); + this._setDefaultProperty(eventWithMetaData, "EventInfo.Name", eventWithMetaData.name); + this._setDefaultProperty(eventWithMetaData, "EventInfo.Time", new Date(eventWithMetaData.timestamp).toISOString()); + if (!Utils.isPriority(eventWithMetaData.priority)) { + eventWithMetaData.priority = Enums_1.AWTEventPriority.Normal; + } + this._sendEvent(eventWithMetaData); + }; + AWTLogger._addContextIfAbsent = function(event, contextProperties) { + if (contextProperties) { + for (var name_2 in contextProperties) { + if (contextProperties.hasOwnProperty(name_2)) { + if (!event.properties[name_2]) { + event.properties[name_2] = contextProperties[name_2]; + } + } + } + } + }; + AWTLogger._setDefaultProperty = function(event, name, value) { + event.properties[name] = { + value: value, + pii: Enums_1.AWTPiiKind.NotSet, + type: Enums_1.AWTPropertyType.String + }; + }; + AWTLogger._sendEvent = function(event) { + AWTTransmissionManagerCore_1.default.sendEvent(event); + }; + AWTLogger._getInternalEvent = function(event, apiKey, sanitizeProperties) { + event.properties = event.properties || {}; + if (sanitizeProperties) { + for (var name_3 in event.properties) { + if (event.properties.hasOwnProperty(name_3)) { + event.properties[name_3] = Utils.sanitizeProperty(name_3, event.properties[name_3]); + if (event.properties[name_3] === null) { + delete event.properties[name_3]; + } + } + } + } + var internalEvent = event; + internalEvent.id = Utils.newGuid(); + internalEvent.apiKey = apiKey; + return internalEvent; + }; + AWTLogger._getInitId = function(apiKey) { + return AWTLogger._initIdMap[apiKey]; + }; + AWTLogger._getSequenceId = function(apiKey) { + if (AWTLogger._sequenceIdMap[apiKey] === undefined) { + AWTLogger._sequenceIdMap[apiKey] = 0; + } + return (++AWTLogger._sequenceIdMap[apiKey]).toString(); + }; + AWTLogger._sequenceIdMap = {}; + AWTLogger._initIdMap = {}; + return AWTLogger; + }(); + exports.default = AWTLogger; +}, function(module, exports, __webpack_require__) { + "use strict"; + Object.defineProperty(exports, "__esModule", { + value: true + }); + var Utils = __webpack_require__(2); + var AWTNotificationManager_1 = __webpack_require__(4); + var Enums_1 = __webpack_require__(0); + var StatsTimer = 6e4; + var AWTStatsManager = function() { + function AWTStatsManager() {} + AWTStatsManager.initialize = function(sendStats) { + var _this = this; + this._sendStats = sendStats; + this._isInitalized = true; + AWTNotificationManager_1.default.addNotificationListener({ + eventsSent: function(events) { + _this._addStat("records_sent_count", events.length, events[0].apiKey); + }, + eventsDropped: function(events, reason) { + switch (reason) { + case Enums_1.AWTEventsDroppedReason.NonRetryableStatus: + _this._addStat("d_send_fail", events.length, events[0].apiKey); + _this._addStat("records_dropped_count", events.length, events[0].apiKey); + break; + + case Enums_1.AWTEventsDroppedReason.MaxRetryLimit: + _this._addStat("d_retry_limit", events.length, events[0].apiKey); + _this._addStat("records_dropped_count", events.length, events[0].apiKey); + break; + + case Enums_1.AWTEventsDroppedReason.QueueFull: + _this._addStat("d_queue_full", events.length, events[0].apiKey); + break; + } + }, + eventsRejected: function(events, reason) { + switch (reason) { + case Enums_1.AWTEventsRejectedReason.InvalidEvent: + _this._addStat("r_inv", events.length, events[0].apiKey); + break; + + case Enums_1.AWTEventsRejectedReason.KillSwitch: + _this._addStat("r_kl", events.length, events[0].apiKey); + break; + + case Enums_1.AWTEventsRejectedReason.SizeLimitExceeded: + _this._addStat("r_size", events.length, events[0].apiKey); + break; + } + _this._addStat("r_count", events.length, events[0].apiKey); + }, + eventsRetrying: null + }); + setTimeout(function() { + return _this.flush(); + }, StatsTimer); + }; + AWTStatsManager.teardown = function() { + if (this._isInitalized) { + this.flush(); + this._isInitalized = false; + } + }; + AWTStatsManager.eventReceived = function(apiKey) { + AWTStatsManager._addStat("records_received_count", 1, apiKey); + }; + AWTStatsManager.flush = function() { + var _this = this; + if (this._isInitalized) { + for (var tenantId in this._stats) { + if (this._stats.hasOwnProperty(tenantId)) { + this._sendStats(this._stats[tenantId], tenantId); + } + } + this._stats = {}; + setTimeout(function() { + return _this.flush(); + }, StatsTimer); + } + }; + AWTStatsManager._addStat = function(statName, value, apiKey) { + if (this._isInitalized && apiKey !== Utils.StatsApiKey) { + var tenantId = Utils.getTenantId(apiKey); + if (!this._stats[tenantId]) { + this._stats[tenantId] = {}; + } + if (!this._stats[tenantId][statName]) { + this._stats[tenantId][statName] = value; + } else { + this._stats[tenantId][statName] = this._stats[tenantId][statName] + value; + } + } + }; + AWTStatsManager._isInitalized = false; + AWTStatsManager._stats = {}; + return AWTStatsManager; + }(); + exports.default = AWTStatsManager; +}, function(module, exports, __webpack_require__) { + "use strict"; + Object.defineProperty(exports, "__esModule", { + value: true + }); + var Bond = __webpack_require__(26); + var Enums_1 = __webpack_require__(0); + var AWTNotificationManager_1 = __webpack_require__(4); + var Utils = __webpack_require__(2); + var RequestSizeLimitBytes = 2936012; + var AWTSerializer = function() { + function AWTSerializer() {} + AWTSerializer.getPayloadBlob = function(requestDictionary, tokenCount) { + var requestFull = false; + var remainingRequest; + var stream = new Bond.IO.MemoryStream(); + var writer = new Bond.CompactBinaryProtocolWriter(stream); + writer._WriteFieldBegin(Bond._BondDataType._BT_MAP, 3, null); + writer._WriteMapContainerBegin(tokenCount, Bond._BondDataType._BT_STRING, Bond._BondDataType._BT_LIST); + for (var token in requestDictionary) { + if (!requestFull) { + if (requestDictionary.hasOwnProperty(token)) { + writer._WriteString(token); + var dataPackage = requestDictionary[token]; + writer._WriteContainerBegin(1, Bond._BondDataType._BT_STRUCT); + writer._WriteFieldBegin(Bond._BondDataType._BT_STRING, 2, null); + writer._WriteString("act_default_source"); + writer._WriteFieldBegin(Bond._BondDataType._BT_STRING, 5, null); + writer._WriteString(Utils.newGuid()); + writer._WriteFieldBegin(Bond._BondDataType._BT_INT64, 6, null); + writer._WriteInt64(Utils.numberToBondInt64(Date.now())); + writer._WriteFieldBegin(Bond._BondDataType._BT_LIST, 8, null); + var dpSizePos = stream._GetBuffer().length + 1; + writer._WriteContainerBegin(requestDictionary[token].length, Bond._BondDataType._BT_STRUCT); + var dpSizeSerialized = stream._GetBuffer().length - dpSizePos; + for (var i = 0; i < dataPackage.length; ++i) { + var currentStreamPos = stream._GetBuffer().length; + this.writeEvent(dataPackage[i], writer); + if (stream._GetBuffer().length - currentStreamPos > RequestSizeLimitBytes) { + AWTNotificationManager_1.default.eventsRejected([ dataPackage[i] ], Enums_1.AWTEventsRejectedReason.SizeLimitExceeded); + dataPackage.splice(i--, 1); + stream._GetBuffer().splice(currentStreamPos); + this._addNewDataPackageSize(dataPackage.length, stream, dpSizeSerialized, dpSizePos); + continue; + } + if (stream._GetBuffer().length > RequestSizeLimitBytes) { + stream._GetBuffer().splice(currentStreamPos); + if (!remainingRequest) { + remainingRequest = {}; + } + requestDictionary[token] = dataPackage.splice(0, i); + remainingRequest[token] = dataPackage; + this._addNewDataPackageSize(requestDictionary[token].length, stream, dpSizeSerialized, dpSizePos); + requestFull = true; + break; + } + } + writer._WriteStructEnd(false); + } + } else { + if (!remainingRequest) { + remainingRequest = {}; + } + remainingRequest[token] = requestDictionary[token]; + delete requestDictionary[token]; + } + } + writer._WriteStructEnd(false); + return { + payloadBlob: stream._GetBuffer(), + remainingRequest: remainingRequest + }; + }; + AWTSerializer._addNewDataPackageSize = function(size, stream, oldDpSize, streamPos) { + var newRecordCountSerialized = Bond._Encoding._Varint_GetBytes(Bond.Number._ToUInt32(size)); + for (var j = 0; j < oldDpSize; ++j) { + if (j < newRecordCountSerialized.length) { + stream._GetBuffer()[streamPos + j] = newRecordCountSerialized[j]; + } else { + stream._GetBuffer().slice(streamPos + j, oldDpSize - j); + break; + } + } + }; + AWTSerializer.writeEvent = function(eventData, writer) { + writer._WriteFieldBegin(Bond._BondDataType._BT_STRING, 1, null); + writer._WriteString(eventData.id); + writer._WriteFieldBegin(Bond._BondDataType._BT_INT64, 3, null); + writer._WriteInt64(Utils.numberToBondInt64(eventData.timestamp)); + writer._WriteFieldBegin(Bond._BondDataType._BT_STRING, 5, null); + writer._WriteString(eventData.type); + writer._WriteFieldBegin(Bond._BondDataType._BT_STRING, 6, null); + writer._WriteString(eventData.name); + var propsString = {}; + var propStringCount = 0; + var propsInt64 = {}; + var propInt64Count = 0; + var propsDouble = {}; + var propDoubleCount = 0; + var propsBool = {}; + var propBoolCount = 0; + var propsDate = {}; + var propDateCount = 0; + var piiProps = {}; + var piiPropCount = 0; + var ccProps = {}; + var ccPropCount = 0; + for (var key in eventData.properties) { + if (eventData.properties.hasOwnProperty(key)) { + var property = eventData.properties[key]; + if (property.cc > 0) { + ccProps[key] = property; + ccPropCount++; + } else if (property.pii > 0) { + piiProps[key] = property; + piiPropCount++; + } else { + switch (property.type) { + case Enums_1.AWTPropertyType.String: + propsString[key] = property.value; + propStringCount++; + break; + + case Enums_1.AWTPropertyType.Int64: + propsInt64[key] = property.value; + propInt64Count++; + break; + + case Enums_1.AWTPropertyType.Double: + propsDouble[key] = property.value; + propDoubleCount++; + break; + + case Enums_1.AWTPropertyType.Boolean: + propsBool[key] = property.value; + propBoolCount++; + break; + + case Enums_1.AWTPropertyType.Date: + propsDate[key] = property.value; + propDateCount++; + break; + } + } + } + } + if (propStringCount) { + writer._WriteFieldBegin(Bond._BondDataType._BT_MAP, 13, null); + writer._WriteMapContainerBegin(propStringCount, Bond._BondDataType._BT_STRING, Bond._BondDataType._BT_STRING); + for (var key in propsString) { + if (propsString.hasOwnProperty(key)) { + var value = propsString[key]; + writer._WriteString(key); + writer._WriteString(value.toString()); + } + } + } + if (piiPropCount) { + writer._WriteFieldBegin(Bond._BondDataType._BT_MAP, 30, null); + writer._WriteMapContainerBegin(piiPropCount, Bond._BondDataType._BT_STRING, Bond._BondDataType._BT_STRUCT); + for (var key in piiProps) { + if (piiProps.hasOwnProperty(key)) { + var property = piiProps[key]; + writer._WriteString(key); + writer._WriteFieldBegin(Bond._BondDataType._BT_INT32, 1, null); + writer._WriteInt32(1); + writer._WriteFieldBegin(Bond._BondDataType._BT_INT32, 2, null); + writer._WriteInt32(property.pii); + writer._WriteFieldBegin(Bond._BondDataType._BT_STRING, 3, null); + writer._WriteString(property.value.toString()); + writer._WriteStructEnd(false); + } + } + } + if (propBoolCount) { + writer._WriteFieldBegin(Bond._BondDataType._BT_MAP, 31, null); + writer._WriteMapContainerBegin(propBoolCount, Bond._BondDataType._BT_STRING, Bond._BondDataType._BT_BOOL); + for (var key in propsBool) { + if (propsBool.hasOwnProperty(key)) { + var value = propsBool[key]; + writer._WriteString(key); + writer._WriteBool(value); + } + } + } + if (propDateCount) { + writer._WriteFieldBegin(Bond._BondDataType._BT_MAP, 32, null); + writer._WriteMapContainerBegin(propDateCount, Bond._BondDataType._BT_STRING, Bond._BondDataType._BT_INT64); + for (var key in propsDate) { + if (propsDate.hasOwnProperty(key)) { + var value = propsDate[key]; + writer._WriteString(key); + writer._WriteInt64(Utils.numberToBondInt64(value)); + } + } + } + if (propInt64Count) { + writer._WriteFieldBegin(Bond._BondDataType._BT_MAP, 33, null); + writer._WriteMapContainerBegin(propInt64Count, Bond._BondDataType._BT_STRING, Bond._BondDataType._BT_INT64); + for (var key in propsInt64) { + if (propsInt64.hasOwnProperty(key)) { + var value = propsInt64[key]; + writer._WriteString(key); + writer._WriteInt64(Utils.numberToBondInt64(value)); + } + } + } + if (propDoubleCount) { + writer._WriteFieldBegin(Bond._BondDataType._BT_MAP, 34, null); + writer._WriteMapContainerBegin(propDoubleCount, Bond._BondDataType._BT_STRING, Bond._BondDataType._BT_DOUBLE); + for (var key in propsDouble) { + if (propsDouble.hasOwnProperty(key)) { + var value = propsDouble[key]; + writer._WriteString(key); + writer._WriteDouble(value); + } + } + } + if (ccPropCount) { + writer._WriteFieldBegin(Bond._BondDataType._BT_MAP, 36, null); + writer._WriteMapContainerBegin(ccPropCount, Bond._BondDataType._BT_STRING, Bond._BondDataType._BT_STRUCT); + for (var key in ccProps) { + if (ccProps.hasOwnProperty(key)) { + var property = ccProps[key]; + writer._WriteString(key); + writer._WriteFieldBegin(Bond._BondDataType._BT_INT32, 1, null); + writer._WriteInt32(property.cc); + writer._WriteFieldBegin(Bond._BondDataType._BT_STRING, 2, null); + writer._WriteString(property.value.toString()); + writer._WriteStructEnd(false); + } + } + } + writer._WriteStructEnd(false); + }; + AWTSerializer.base64Encode = function(data) { + return Bond._Encoding._Base64_GetString(data); + }; + return AWTSerializer; + }(); + exports.default = AWTSerializer; +}, function(module, exports, __webpack_require__) { + "use strict"; + Object.defineProperty(exports, "__esModule", { + value: true + }); + exports.Version = "1.8.5"; + exports.FullVersionString = "AWT-Web-JS-" + exports.Version; +}, function(module, exports, __webpack_require__) { + "use strict"; + Object.defineProperty(exports, "__esModule", { + value: true + }); + var Enums_1 = __webpack_require__(0); + var Enums_2 = __webpack_require__(6); + var AWTLogManagerSettings_1 = __webpack_require__(18); + var AWTLogger_1 = __webpack_require__(13); + var AWTTransmissionManagerCore_1 = __webpack_require__(3); + var AWTNotificationManager_1 = __webpack_require__(4); + var AWTAutoCollection_1 = __webpack_require__(10); + var AWTLogManager = function() { + function AWTLogManager() {} + AWTLogManager.initialize = function(tenantToken, configuration) { + if (configuration === void 0) { + configuration = {}; + } + if (this._isInitialized) { + return; + } + this._isInitialized = true; + AWTLogManagerSettings_1.default.defaultTenantToken = tenantToken; + this._overrideValuesFromConfig(configuration); + if (this._config.disableCookiesUsage && !this._config.propertyStorageOverride) { + AWTLogManagerSettings_1.default.sessionEnabled = false; + } + AWTAutoCollection_1.default.addPropertyStorageOverride(this._config.propertyStorageOverride); + AWTAutoCollection_1.default.autoCollect(AWTLogManagerSettings_1.default.semanticContext, this._config.disableCookiesUsage, this._config.userAgent); + AWTTransmissionManagerCore_1.default.initialize(this._config); + AWTLogManagerSettings_1.default.loggingEnabled = true; + if (this._config.enableAutoUserSession) { + this.getLogger().logSession(Enums_2.AWTSessionState.Started); + window.addEventListener("beforeunload", this.flushAndTeardown); + } + return this.getLogger(); + }; + AWTLogManager.getSemanticContext = function() { + return AWTLogManagerSettings_1.default.semanticContext; + }; + AWTLogManager.flush = function(callback) { + if (this._isInitialized && !this._isDestroyed) { + AWTTransmissionManagerCore_1.default.flush(callback); + } + }; + AWTLogManager.flushAndTeardown = function() { + if (this._isInitialized && !this._isDestroyed) { + if (this._config.enableAutoUserSession) { + this.getLogger().logSession(Enums_2.AWTSessionState.Ended); + } + AWTTransmissionManagerCore_1.default.flushAndTeardown(); + AWTLogManagerSettings_1.default.loggingEnabled = false; + this._isDestroyed = true; + } + }; + AWTLogManager.pauseTransmission = function() { + if (this._isInitialized && !this._isDestroyed) { + AWTTransmissionManagerCore_1.default.pauseTransmission(); + } + }; + AWTLogManager.resumeTransmision = function() { + if (this._isInitialized && !this._isDestroyed) { + AWTTransmissionManagerCore_1.default.resumeTransmision(); + } + }; + AWTLogManager.setTransmitProfile = function(profileName) { + if (this._isInitialized && !this._isDestroyed) { + AWTTransmissionManagerCore_1.default.setTransmitProfile(profileName); + } + }; + AWTLogManager.loadTransmitProfiles = function(profiles) { + if (this._isInitialized && !this._isDestroyed) { + AWTTransmissionManagerCore_1.default.loadTransmitProfiles(profiles); + } + }; + AWTLogManager.setContext = function(name, value, type) { + if (type === void 0) { + type = Enums_1.AWTPropertyType.Unspecified; + } + AWTLogManagerSettings_1.default.logManagerContext.setProperty(name, value, type); + }; + AWTLogManager.setContextWithPii = function(name, value, pii, type) { + if (type === void 0) { + type = Enums_1.AWTPropertyType.Unspecified; + } + AWTLogManagerSettings_1.default.logManagerContext.setPropertyWithPii(name, value, pii, type); + }; + AWTLogManager.setContextWithCustomerContent = function(name, value, customerContent, type) { + if (type === void 0) { + type = Enums_1.AWTPropertyType.Unspecified; + } + AWTLogManagerSettings_1.default.logManagerContext.setPropertyWithCustomerContent(name, value, customerContent, type); + }; + AWTLogManager.getLogger = function(tenantToken) { + var key = tenantToken; + if (!key || key === AWTLogManagerSettings_1.default.defaultTenantToken) { + key = ""; + } + if (!this._loggers[key]) { + this._loggers[key] = new AWTLogger_1.default(key); + } + return this._loggers[key]; + }; + AWTLogManager.addNotificationListener = function(listener) { + AWTNotificationManager_1.default.addNotificationListener(listener); + }; + AWTLogManager.removeNotificationListener = function(listener) { + AWTNotificationManager_1.default.removeNotificationListener(listener); + }; + AWTLogManager._overrideValuesFromConfig = function(config) { + if (config.collectorUri) { + this._config.collectorUri = config.collectorUri; + } + if (config.cacheMemorySizeLimitInNumberOfEvents > 0) { + this._config.cacheMemorySizeLimitInNumberOfEvents = config.cacheMemorySizeLimitInNumberOfEvents; + } + if (config.httpXHROverride && config.httpXHROverride.sendPOST) { + this._config.httpXHROverride = config.httpXHROverride; + } + if (config.propertyStorageOverride && config.propertyStorageOverride.getProperty && config.propertyStorageOverride.setProperty) { + this._config.propertyStorageOverride = config.propertyStorageOverride; + } + if (config.userAgent) { + this._config.userAgent = config.userAgent; + } + if (config.disableCookiesUsage) { + this._config.disableCookiesUsage = config.disableCookiesUsage; + } + if (config.canSendStatEvent) { + this._config.canSendStatEvent = config.canSendStatEvent; + } + if (config.enableAutoUserSession && typeof window !== "undefined" && window.addEventListener) { + this._config.enableAutoUserSession = config.enableAutoUserSession; + } + if (config.clockSkewRefreshDurationInMins > 0) { + this._config.clockSkewRefreshDurationInMins = config.clockSkewRefreshDurationInMins; + } + }; + AWTLogManager._loggers = {}; + AWTLogManager._isInitialized = false; + AWTLogManager._isDestroyed = false; + AWTLogManager._config = { + collectorUri: "https://browser.pipe.aria.microsoft.com/Collector/3.0/", + cacheMemorySizeLimitInNumberOfEvents: 1e4, + disableCookiesUsage: false, + canSendStatEvent: function(eventName) { + return true; + }, + clockSkewRefreshDurationInMins: 0 + }; + return AWTLogManager; + }(); + exports.default = AWTLogManager; +}, function(module, exports, __webpack_require__) { + "use strict"; + Object.defineProperty(exports, "__esModule", { + value: true + }); + var AWTEventProperties_1 = __webpack_require__(7); + var AWTSemanticContext_1 = __webpack_require__(9); + var AWTLogManagerSettings = function() { + function AWTLogManagerSettings() {} + AWTLogManagerSettings.logManagerContext = new AWTEventProperties_1.default(); + AWTLogManagerSettings.sessionEnabled = true; + AWTLogManagerSettings.loggingEnabled = false; + AWTLogManagerSettings.defaultTenantToken = ""; + AWTLogManagerSettings.semanticContext = new AWTSemanticContext_1.default(true, AWTLogManagerSettings.logManagerContext); + return AWTLogManagerSettings; + }(); + exports.default = AWTLogManagerSettings; +}, function(module, exports, __webpack_require__) { + var rng = __webpack_require__(23); + var bytesToUuid = __webpack_require__(24); + function v4(options, buf, offset) { + var i = buf && offset || 0; + if (typeof options == "string") { + buf = options === "binary" ? new Array(16) : null; + options = null; + } + options = options || {}; + var rnds = options.random || (options.rng || rng)(); + rnds[6] = rnds[6] & 15 | 64; + rnds[8] = rnds[8] & 63 | 128; + if (buf) { + for (var ii = 0; ii < 16; ++ii) { + buf[i + ii] = rnds[ii]; + } + } + return buf || bytesToUuid(rnds); + } + module.exports = v4; +}, , , function(module, exports, __webpack_require__) { + module.exports = __webpack_require__(37); +}, function(module, exports) { + var getRandomValues = typeof crypto != "undefined" && crypto.getRandomValues && crypto.getRandomValues.bind(crypto) || typeof msCrypto != "undefined" && typeof window.msCrypto.getRandomValues == "function" && msCrypto.getRandomValues.bind(msCrypto); + if (getRandomValues) { + var rnds8 = new Uint8Array(16); + module.exports = function whatwgRNG() { + getRandomValues(rnds8); + return rnds8; + }; + } else { + var rnds = new Array(16); + module.exports = function mathRNG() { + for (var i = 0, r; i < 16; i++) { + if ((i & 3) === 0) r = Math.random() * 4294967296; + rnds[i] = r >>> ((i & 3) << 3) & 255; + } + return rnds; + }; + } +}, function(module, exports) { + var byteToHex = []; + for (var i = 0; i < 256; ++i) { + byteToHex[i] = (i + 256).toString(16).substr(1); + } + function bytesToUuid(buf, offset) { + var i = offset || 0; + var bth = byteToHex; + return [ bth[buf[i++]], bth[buf[i++]], bth[buf[i++]], bth[buf[i++]], "-", bth[buf[i++]], bth[buf[i++]], "-", bth[buf[i++]], bth[buf[i++]], "-", bth[buf[i++]], bth[buf[i++]], "-", bth[buf[i++]], bth[buf[i++]], bth[buf[i++]], bth[buf[i++]], bth[buf[i++]], bth[buf[i++]] ].join(""); + } + module.exports = bytesToUuid; +}, function(module, exports, __webpack_require__) { + "use strict"; + Object.defineProperty(exports, "__esModule", { + value: true + }); + var Enums_1 = __webpack_require__(0); + var AWTSerializer_1 = __webpack_require__(15); + var AWTRetryPolicy_1 = __webpack_require__(32); + var AWTKillSwitch_1 = __webpack_require__(33); + var AWTClockSkewManager_1 = __webpack_require__(34); + var Version = __webpack_require__(16); + var Utils = __webpack_require__(2); + var AWTNotificationManager_1 = __webpack_require__(4); + var AWTTransmissionManagerCore_1 = __webpack_require__(3); + var MaxConnections = 2; + var MaxRetries = 1; + var Method = "POST"; + var AWTHttpManager = function() { + function AWTHttpManager(_requestQueue, collectorUrl, _queueManager, _httpInterface, clockSkewRefreshDurationInMins) { + var _this = this; + this._requestQueue = _requestQueue; + this._queueManager = _queueManager; + this._httpInterface = _httpInterface; + this._urlString = "?qsp=true&content-type=application%2Fbond-compact-binary&client-id=NO_AUTH&sdk-version=" + Version.FullVersionString; + this._killSwitch = new AWTKillSwitch_1.default(); + this._paused = false; + this._useBeacons = false; + this._activeConnections = 0; + this._clockSkewManager = new AWTClockSkewManager_1.default(clockSkewRefreshDurationInMins); + if (!Utils.isUint8ArrayAvailable()) { + this._urlString += "&content-encoding=base64"; + } + this._urlString = collectorUrl + this._urlString; + if (!this._httpInterface) { + this._useBeacons = !Utils.isReactNative(); + this._httpInterface = { + sendPOST: function(urlString, data, ontimeout, onerror, onload, sync) { + try { + if (Utils.useFetchRequest()) { + fetch(urlString, { + body: data, + method: Method + }).then(function(response) { + var headerMap = {}; + if (response.headers) { + response.headers.forEach(function(value, name) { + headerMap[name] = value; + }); + } + onload(response.status, headerMap); + }).catch(function(error) { + onerror(0, {}); + }); + } else if (Utils.useXDomainRequest()) { + var xdr = new XDomainRequest(); + xdr.open(Method, urlString); + xdr.onload = function() { + onload(200, null); + }; + xdr.onerror = function() { + onerror(400, null); + }; + xdr.ontimeout = function() { + ontimeout(500, null); + }; + xdr.send(data); + } else { + var xhr_1 = new XMLHttpRequest(); + xhr_1.open(Method, urlString, !sync); + xhr_1.onload = function() { + onload(xhr_1.status, _this._convertAllHeadersToMap(xhr_1.getAllResponseHeaders())); + }; + xhr_1.onerror = function() { + onerror(xhr_1.status, _this._convertAllHeadersToMap(xhr_1.getAllResponseHeaders())); + }; + xhr_1.ontimeout = function() { + ontimeout(xhr_1.status, _this._convertAllHeadersToMap(xhr_1.getAllResponseHeaders())); + }; + xhr_1.send(data); + } + } catch (e) { + onerror(400, null); + } + } + }; + } + } + AWTHttpManager.prototype.hasIdleConnection = function() { + return this._activeConnections < MaxConnections; + }; + AWTHttpManager.prototype.sendQueuedRequests = function() { + while (this.hasIdleConnection() && !this._paused && this._requestQueue.length > 0 && this._clockSkewManager.allowRequestSending()) { + this._activeConnections++; + this._sendRequest(this._requestQueue.shift(), 0, false); + } + if (this.hasIdleConnection()) { + AWTTransmissionManagerCore_1.default.scheduleTimer(); + } + }; + AWTHttpManager.prototype.isCompletelyIdle = function() { + return this._activeConnections === 0; + }; + AWTHttpManager.prototype.teardown = function() { + while (this._requestQueue.length > 0) { + this._sendRequest(this._requestQueue.shift(), 0, true); + } + }; + AWTHttpManager.prototype.pause = function() { + this._paused = true; + }; + AWTHttpManager.prototype.resume = function() { + this._paused = false; + this.sendQueuedRequests(); + }; + AWTHttpManager.prototype.removeQueuedRequests = function() { + this._requestQueue.length = 0; + }; + AWTHttpManager.prototype.sendSynchronousRequest = function(request, token) { + if (this._paused) { + request[token][0].priority = Enums_1.AWTEventPriority.High; + } + this._activeConnections++; + this._sendRequest(request, 0, false, true); + }; + AWTHttpManager.prototype._sendRequest = function(request, retryCount, isTeardown, isSynchronous) { + var _this = this; + if (isSynchronous === void 0) { + isSynchronous = false; + } + try { + if (this._paused) { + this._activeConnections--; + this._queueManager.addBackRequest(request); + return; + } + var tokenCount_1 = 0; + var apikey_1 = ""; + for (var token in request) { + if (request.hasOwnProperty(token)) { + if (!this._killSwitch.isTenantKilled(token)) { + if (apikey_1.length > 0) { + apikey_1 += ","; + } + apikey_1 += token; + tokenCount_1++; + } else { + AWTNotificationManager_1.default.eventsRejected(request[token], Enums_1.AWTEventsRejectedReason.KillSwitch); + delete request[token]; + } + } + } + if (tokenCount_1 > 0) { + var payloadResult = AWTSerializer_1.default.getPayloadBlob(request, tokenCount_1); + if (payloadResult.remainingRequest) { + this._requestQueue.push(payloadResult.remainingRequest); + } + var urlString = this._urlString + "&x-apikey=" + apikey_1 + "&client-time-epoch-millis=" + Date.now().toString(); + if (this._clockSkewManager.shouldAddClockSkewHeaders()) { + urlString = urlString + "&time-delta-to-apply-millis=" + this._clockSkewManager.getClockSkewHeaderValue(); + } + var data = void 0; + if (!Utils.isUint8ArrayAvailable()) { + data = AWTSerializer_1.default.base64Encode(payloadResult.payloadBlob); + } else { + data = new Uint8Array(payloadResult.payloadBlob); + } + for (var token in request) { + if (request.hasOwnProperty(token)) { + for (var i = 0; i < request[token].length; ++i) { + request[token][i].sendAttempt > 0 ? request[token][i].sendAttempt++ : request[token][i].sendAttempt = 1; + } + } + } + if (this._useBeacons && isTeardown && Utils.isBeaconsSupported()) { + if (navigator.sendBeacon(urlString, data)) { + return; + } + } + this._httpInterface.sendPOST(urlString, data, function(status, headers) { + _this._retryRequestIfNeeded(status, headers, request, tokenCount_1, apikey_1, retryCount, isTeardown, isSynchronous); + }, function(status, headers) { + _this._retryRequestIfNeeded(status, headers, request, tokenCount_1, apikey_1, retryCount, isTeardown, isSynchronous); + }, function(status, headers) { + _this._retryRequestIfNeeded(status, headers, request, tokenCount_1, apikey_1, retryCount, isTeardown, isSynchronous); + }, isTeardown || isSynchronous); + } else if (!isTeardown) { + this._handleRequestFinished(false, {}, isTeardown, isSynchronous); + } + } catch (e) { + this._handleRequestFinished(false, {}, isTeardown, isSynchronous); + } + }; + AWTHttpManager.prototype._retryRequestIfNeeded = function(status, headers, request, tokenCount, apikey, retryCount, isTeardown, isSynchronous) { + var _this = this; + var shouldRetry = true; + if (typeof status !== "undefined") { + if (headers) { + var killedTokens = this._killSwitch.setKillSwitchTenants(headers["kill-tokens"], headers["kill-duration-seconds"]); + this._clockSkewManager.setClockSkew(headers["time-delta-millis"]); + for (var i = 0; i < killedTokens.length; ++i) { + AWTNotificationManager_1.default.eventsRejected(request[killedTokens[i]], Enums_1.AWTEventsRejectedReason.KillSwitch); + delete request[killedTokens[i]]; + tokenCount--; + } + } else { + this._clockSkewManager.setClockSkew(null); + } + if (status === 200) { + this._handleRequestFinished(true, request, isTeardown, isSynchronous); + return; + } + if (!AWTRetryPolicy_1.default.shouldRetryForStatus(status) || tokenCount <= 0) { + shouldRetry = false; + } + } + if (shouldRetry) { + if (isSynchronous) { + this._activeConnections--; + request[apikey][0].priority = Enums_1.AWTEventPriority.High; + this._queueManager.addBackRequest(request); + } else if (retryCount < MaxRetries) { + for (var token in request) { + if (request.hasOwnProperty(token)) { + AWTNotificationManager_1.default.eventsRetrying(request[token]); + } + } + setTimeout(function() { + return _this._sendRequest(request, retryCount + 1, false); + }, AWTRetryPolicy_1.default.getMillisToBackoffForRetry(retryCount)); + } else { + this._activeConnections--; + AWTTransmissionManagerCore_1.default.backOffTransmission(); + this._queueManager.addBackRequest(request); + } + } else { + this._handleRequestFinished(false, request, isTeardown, isSynchronous); + } + }; + AWTHttpManager.prototype._handleRequestFinished = function(success, request, isTeardown, isSynchronous) { + if (success) { + AWTTransmissionManagerCore_1.default.clearBackOff(); + } + for (var token in request) { + if (request.hasOwnProperty(token)) { + if (success) { + AWTNotificationManager_1.default.eventsSent(request[token]); + } else { + AWTNotificationManager_1.default.eventsDropped(request[token], Enums_1.AWTEventsDroppedReason.NonRetryableStatus); + } + } + } + this._activeConnections--; + if (!isSynchronous && !isTeardown) { + this.sendQueuedRequests(); + } + }; + AWTHttpManager.prototype._convertAllHeadersToMap = function(headersString) { + var headers = {}; + if (headersString) { + var headersArray = headersString.split("\n"); + for (var i = 0; i < headersArray.length; ++i) { + var header = headersArray[i].split(": "); + headers[header[0]] = header[1]; + } + } + return headers; + }; + return AWTHttpManager; + }(); + exports.default = AWTHttpManager; +}, function(module, exports, __webpack_require__) { + "use strict"; + Object.defineProperty(exports, "__esModule", { + value: true + }); + var bond_const_1 = __webpack_require__(27); + exports._BondDataType = bond_const_1._BondDataType; + var _Encoding = __webpack_require__(28); + exports._Encoding = _Encoding; + var IO = __webpack_require__(31); + exports.IO = IO; + var microsoft_bond_primitives_1 = __webpack_require__(8); + exports.Int64 = microsoft_bond_primitives_1.Int64; + exports.UInt64 = microsoft_bond_primitives_1.UInt64; + exports.Number = microsoft_bond_primitives_1.Number; + var CompactBinaryProtocolWriter = function() { + function CompactBinaryProtocolWriter(stream) { + this._stream = stream; + } + CompactBinaryProtocolWriter.prototype._WriteBlob = function(blob) { + this._stream._Write(blob, 0, blob.length); + }; + CompactBinaryProtocolWriter.prototype._WriteBool = function(value) { + this._stream._WriteByte(value ? 1 : 0); + }; + CompactBinaryProtocolWriter.prototype._WriteContainerBegin = function(size, elementType) { + this._WriteUInt8(elementType); + this._WriteUInt32(size); + }; + CompactBinaryProtocolWriter.prototype._WriteMapContainerBegin = function(size, keyType, valueType) { + this._WriteUInt8(keyType); + this._WriteUInt8(valueType); + this._WriteUInt32(size); + }; + CompactBinaryProtocolWriter.prototype._WriteDouble = function(value) { + var array = _Encoding._Double_GetBytes(value); + this._stream._Write(array, 0, array.length); + }; + CompactBinaryProtocolWriter.prototype._WriteFieldBegin = function(type, id, metadata) { + if (id <= 5) { + this._stream._WriteByte(type | id << 5); + } else if (id <= 255) { + this._stream._WriteByte(type | 6 << 5); + this._stream._WriteByte(id); + } else { + this._stream._WriteByte(type | 7 << 5); + this._stream._WriteByte(id); + this._stream._WriteByte(id >> 8); + } + }; + CompactBinaryProtocolWriter.prototype._WriteInt32 = function(value) { + value = _Encoding._Zigzag_EncodeZigzag32(value); + this._WriteUInt32(value); + }; + CompactBinaryProtocolWriter.prototype._WriteInt64 = function(value) { + this._WriteUInt64(_Encoding._Zigzag_EncodeZigzag64(value)); + }; + CompactBinaryProtocolWriter.prototype._WriteString = function(value) { + if (value === "") { + this._WriteUInt32(0); + } else { + var array = _Encoding._Utf8_GetBytes(value); + this._WriteUInt32(array.length); + this._stream._Write(array, 0, array.length); + } + }; + CompactBinaryProtocolWriter.prototype._WriteStructEnd = function(isBase) { + this._WriteUInt8(isBase ? bond_const_1._BondDataType._BT_STOP_BASE : bond_const_1._BondDataType._BT_STOP); + }; + CompactBinaryProtocolWriter.prototype._WriteUInt32 = function(value) { + var array = _Encoding._Varint_GetBytes(microsoft_bond_primitives_1.Number._ToUInt32(value)); + this._stream._Write(array, 0, array.length); + }; + CompactBinaryProtocolWriter.prototype._WriteUInt64 = function(value) { + var array = _Encoding._Varint64_GetBytes(value); + this._stream._Write(array, 0, array.length); + }; + CompactBinaryProtocolWriter.prototype._WriteUInt8 = function(value) { + this._stream._WriteByte(microsoft_bond_primitives_1.Number._ToUInt8(value)); + }; + return CompactBinaryProtocolWriter; + }(); + exports.CompactBinaryProtocolWriter = CompactBinaryProtocolWriter; +}, function(module, exports, __webpack_require__) { + "use strict"; + Object.defineProperty(exports, "__esModule", { + value: true + }); + var _BondDataType; + (function(_BondDataType) { + _BondDataType[_BondDataType["_BT_STOP"] = 0] = "_BT_STOP"; + _BondDataType[_BondDataType["_BT_STOP_BASE"] = 1] = "_BT_STOP_BASE"; + _BondDataType[_BondDataType["_BT_BOOL"] = 2] = "_BT_BOOL"; + _BondDataType[_BondDataType["_BT_DOUBLE"] = 8] = "_BT_DOUBLE"; + _BondDataType[_BondDataType["_BT_STRING"] = 9] = "_BT_STRING"; + _BondDataType[_BondDataType["_BT_STRUCT"] = 10] = "_BT_STRUCT"; + _BondDataType[_BondDataType["_BT_LIST"] = 11] = "_BT_LIST"; + _BondDataType[_BondDataType["_BT_MAP"] = 13] = "_BT_MAP"; + _BondDataType[_BondDataType["_BT_INT32"] = 16] = "_BT_INT32"; + _BondDataType[_BondDataType["_BT_INT64"] = 17] = "_BT_INT64"; + })(_BondDataType = exports._BondDataType || (exports._BondDataType = {})); +}, function(module, exports, __webpack_require__) { + "use strict"; + Object.defineProperty(exports, "__esModule", { + value: true + }); + var microsoft_bond_primitives_1 = __webpack_require__(8); + var microsoft_bond_floatutils_1 = __webpack_require__(29); + var microsoft_bond_utils_1 = __webpack_require__(30); + function _Utf8_GetBytes(value) { + var array = []; + for (var i = 0; i < value.length; ++i) { + var char = value.charCodeAt(i); + if (char < 128) { + array.push(char); + } else if (char < 2048) { + array.push(192 | char >> 6, 128 | char & 63); + } else if (char < 55296 || char >= 57344) { + array.push(224 | char >> 12, 128 | char >> 6 & 63, 128 | char & 63); + } else { + char = 65536 + ((char & 1023) << 10 | value.charCodeAt(++i) & 1023); + array.push(240 | char >> 18, 128 | char >> 12 & 63, 128 | char >> 6 & 63, 128 | char & 63); + } + } + return array; + } + exports._Utf8_GetBytes = _Utf8_GetBytes; + function _Base64_GetString(inArray) { + var lookup = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; + var output = []; + var paddingBytes = inArray.length % 3; + var toBase64 = function(num) { + return [ lookup.charAt(num >> 18 & 63), lookup.charAt(num >> 12 & 63), lookup.charAt(num >> 6 & 63), lookup.charAt(num & 63) ].join(""); + }; + for (var i = 0, length_1 = inArray.length - paddingBytes; i < length_1; i += 3) { + var temp = (inArray[i] << 16) + (inArray[i + 1] << 8) + inArray[i + 2]; + output.push(toBase64(temp)); + } + switch (paddingBytes) { + case 1: + var temp = inArray[inArray.length - 1]; + output.push(lookup.charAt(temp >> 2)); + output.push(lookup.charAt(temp << 4 & 63)); + output.push("=="); + break; + + case 2: + var temp2 = (inArray[inArray.length - 2] << 8) + inArray[inArray.length - 1]; + output.push(lookup.charAt(temp2 >> 10)); + output.push(lookup.charAt(temp2 >> 4 & 63)); + output.push(lookup.charAt(temp2 << 2 & 63)); + output.push("="); + break; + } + return output.join(""); + } + exports._Base64_GetString = _Base64_GetString; + function _Varint_GetBytes(value) { + var array = []; + while (value & 4294967168) { + array.push(value & 127 | 128); + value >>>= 7; + } + array.push(value & 127); + return array; + } + exports._Varint_GetBytes = _Varint_GetBytes; + function _Varint64_GetBytes(value) { + var low = value.low; + var high = value.high; + var array = []; + while (high || 4294967168 & low) { + array.push(low & 127 | 128); + low = (high & 127) << 25 | low >>> 7; + high >>>= 7; + } + array.push(low & 127); + return array; + } + exports._Varint64_GetBytes = _Varint64_GetBytes; + function _Double_GetBytes(value) { + if (microsoft_bond_utils_1.BrowserChecker._IsDataViewSupport()) { + var view = new DataView(new ArrayBuffer(8)); + view.setFloat64(0, value, true); + var array = []; + for (var i = 0; i < 8; ++i) { + array.push(view.getUint8(i)); + } + return array; + } else { + return microsoft_bond_floatutils_1.FloatUtils._ConvertNumberToArray(value, true); + } + } + exports._Double_GetBytes = _Double_GetBytes; + function _Zigzag_EncodeZigzag32(value) { + value = microsoft_bond_primitives_1.Number._ToInt32(value); + return value << 1 ^ value >> 4 * 8 - 1; + } + exports._Zigzag_EncodeZigzag32 = _Zigzag_EncodeZigzag32; + function _Zigzag_EncodeZigzag64(value) { + var low = value.low; + var high = value.high; + var tmpH = high << 1 | low >>> 31; + var tmpL = low << 1; + if (high & 2147483648) { + tmpH = ~tmpH; + tmpL = ~tmpL; + } + var res = new microsoft_bond_primitives_1.UInt64("0"); + res.low = tmpL; + res.high = tmpH; + return res; + } + exports._Zigzag_EncodeZigzag64 = _Zigzag_EncodeZigzag64; +}, function(module, exports, __webpack_require__) { + "use strict"; + Object.defineProperty(exports, "__esModule", { + value: true + }); + var FloatUtils = function() { + function FloatUtils() {} + FloatUtils._ConvertNumberToArray = function(num, isDouble) { + if (!num) { + return isDouble ? this._doubleZero : this._floatZero; + } + var exponentBits = isDouble ? 11 : 8; + var precisionBits = isDouble ? 52 : 23; + var bias = (1 << exponentBits - 1) - 1; + var minExponent = 1 - bias; + var maxExponent = bias; + var sign = num < 0 ? 1 : 0; + num = Math.abs(num); + var intPart = Math.floor(num); + var floatPart = num - intPart; + var len = 2 * (bias + 2) + precisionBits; + var buffer = new Array(len); + var i = 0; + while (i < len) { + buffer[i++] = 0; + } + i = bias + 2; + while (i && intPart) { + buffer[--i] = intPart % 2; + intPart = Math.floor(intPart / 2); + } + i = bias + 1; + while (i < len - 1 && floatPart > 0) { + floatPart *= 2; + if (floatPart >= 1) { + buffer[++i] = 1; + --floatPart; + } else { + buffer[++i] = 0; + } + } + var firstBit = 0; + while (firstBit < len && !buffer[firstBit]) { + firstBit++; + } + var exponent = bias + 1 - firstBit; + var lastBit = firstBit + precisionBits; + if (buffer[lastBit + 1]) { + for (i = lastBit; i > firstBit; --i) { + buffer[i] = 1 - buffer[i]; + if (buffer) { + break; + } + } + if (i === firstBit) { + ++exponent; + } + } + if (exponent > maxExponent || intPart) { + if (sign) { + return isDouble ? this._doubleNegInifinity : this._floatNegInifinity; + } else { + return isDouble ? this._doubleInifinity : this._floatInifinity; + } + } else if (exponent < minExponent) { + return isDouble ? this._doubleZero : this._floatZero; + } + if (isDouble) { + var high = 0; + for (i = 0; i < 20; ++i) { + high = high << 1 | buffer[++firstBit]; + } + var low = 0; + for (;i < 52; ++i) { + low = low << 1 | buffer[++firstBit]; + } + high |= exponent + bias << 20; + high = sign << 31 | high & 2147483647; + var resArray = [ low & 255, low >> 8 & 255, low >> 16 & 255, low >>> 24, high & 255, high >> 8 & 255, high >> 16 & 255, high >>> 24 ]; + return resArray; + } else { + var result = 0; + for (i = 0; i < 23; ++i) { + result = result << 1 | buffer[++firstBit]; + } + result |= exponent + bias << 23; + result = sign << 31 | result & 2147483647; + var resArray = [ result & 255, result >> 8 & 255, result >> 16 & 255, result >>> 24 ]; + return resArray; + } + }; + FloatUtils._floatZero = [ 0, 0, 0, 0 ]; + FloatUtils._doubleZero = [ 0, 0, 0, 0, 0, 0, 0, 0 ]; + FloatUtils._floatInifinity = [ 0, 0, 128, 127 ]; + FloatUtils._floatNegInifinity = [ 0, 0, 128, 255 ]; + FloatUtils._doubleInifinity = [ 0, 0, 0, 0, 0, 0, 240, 127 ]; + FloatUtils._doubleNegInifinity = [ 0, 0, 0, 0, 0, 0, 240, 255 ]; + return FloatUtils; + }(); + exports.FloatUtils = FloatUtils; +}, function(module, exports, __webpack_require__) { + "use strict"; + Object.defineProperty(exports, "__esModule", { + value: true + }); + var BrowserChecker = function() { + function BrowserChecker() {} + BrowserChecker._IsDataViewSupport = function() { + return typeof ArrayBuffer !== "undefined" && typeof DataView !== "undefined"; + }; + return BrowserChecker; + }(); + exports.BrowserChecker = BrowserChecker; +}, function(module, exports, __webpack_require__) { + "use strict"; + Object.defineProperty(exports, "__esModule", { + value: true + }); + var microsoft_bond_primitives_1 = __webpack_require__(8); + var MemoryStream = function() { + function MemoryStream() { + this._buffer = []; + } + MemoryStream.prototype._WriteByte = function(byte) { + this._buffer.push(microsoft_bond_primitives_1.Number._ToByte(byte)); + }; + MemoryStream.prototype._Write = function(buffer, offset, count) { + while (count--) { + this._WriteByte(buffer[offset++]); + } + }; + MemoryStream.prototype._GetBuffer = function() { + return this._buffer; + }; + return MemoryStream; + }(); + exports.MemoryStream = MemoryStream; +}, function(module, exports, __webpack_require__) { + "use strict"; + Object.defineProperty(exports, "__esModule", { + value: true + }); + var RandomizationLowerThreshold = .8; + var RandomizationUpperThreshold = 1.2; + var BaseBackoff = 3e3; + var MaxBackoff = 12e4; + var AWTRetryPolicy = function() { + function AWTRetryPolicy() {} + AWTRetryPolicy.shouldRetryForStatus = function(httpStatusCode) { + return !(httpStatusCode >= 300 && httpStatusCode < 500 && httpStatusCode !== 408 || httpStatusCode === 501 || httpStatusCode === 505); + }; + AWTRetryPolicy.getMillisToBackoffForRetry = function(retriesSoFar) { + var waitDuration = 0; + var minBackoff = BaseBackoff * RandomizationLowerThreshold; + var maxBackoff = BaseBackoff * RandomizationUpperThreshold; + var randomBackoff = Math.floor(Math.random() * (maxBackoff - minBackoff)) + minBackoff; + waitDuration = Math.pow(4, retriesSoFar) * randomBackoff; + return Math.min(waitDuration, MaxBackoff); + }; + return AWTRetryPolicy; + }(); + exports.default = AWTRetryPolicy; +}, function(module, exports, __webpack_require__) { + "use strict"; + Object.defineProperty(exports, "__esModule", { + value: true + }); + var SecToMsMultiplier = 1e3; + var AWTKillSwitch = function() { + function AWTKillSwitch() { + this._killedTokenDictionary = {}; + } + AWTKillSwitch.prototype.setKillSwitchTenants = function(killTokens, killDuration) { + if (killTokens && killDuration) { + try { + var killedTokens = killTokens.split(","); + if (killDuration === "this-request-only") { + return killedTokens; + } + var durationMs = parseInt(killDuration, 10) * SecToMsMultiplier; + for (var i = 0; i < killedTokens.length; ++i) { + this._killedTokenDictionary[killedTokens[i]] = Date.now() + durationMs; + } + } catch (ex) { + return []; + } + } + return []; + }; + AWTKillSwitch.prototype.isTenantKilled = function(tenantToken) { + if (this._killedTokenDictionary[tenantToken] !== undefined && this._killedTokenDictionary[tenantToken] > Date.now()) { + return true; + } + delete this._killedTokenDictionary[tenantToken]; + return false; + }; + return AWTKillSwitch; + }(); + exports.default = AWTKillSwitch; +}, function(module, exports, __webpack_require__) { + "use strict"; + Object.defineProperty(exports, "__esModule", { + value: true + }); + var AWTClockSkewManager = function() { + function AWTClockSkewManager(clockSkewRefreshDurationInMins) { + this.clockSkewRefreshDurationInMins = clockSkewRefreshDurationInMins; + this._reset(); + } + AWTClockSkewManager.prototype.allowRequestSending = function() { + if (this._isFirstRequest && !this._clockSkewSet) { + this._isFirstRequest = false; + this._allowRequestSending = false; + return true; + } + return this._allowRequestSending; + }; + AWTClockSkewManager.prototype.shouldAddClockSkewHeaders = function() { + return this._shouldAddClockSkewHeaders; + }; + AWTClockSkewManager.prototype.getClockSkewHeaderValue = function() { + return this._clockSkewHeaderValue; + }; + AWTClockSkewManager.prototype.setClockSkew = function(timeDeltaInMillis) { + if (!this._clockSkewSet) { + if (timeDeltaInMillis) { + this._clockSkewHeaderValue = timeDeltaInMillis; + } else { + this._shouldAddClockSkewHeaders = false; + } + this._clockSkewSet = true; + this._allowRequestSending = true; + } + }; + AWTClockSkewManager.prototype._reset = function() { + var _this = this; + this._isFirstRequest = true; + this._clockSkewSet = false; + this._allowRequestSending = true; + this._shouldAddClockSkewHeaders = true; + this._clockSkewHeaderValue = "use-collector-delta"; + if (this.clockSkewRefreshDurationInMins > 0) { + setTimeout(function() { + return _this._reset(); + }, this.clockSkewRefreshDurationInMins * 6e4); + } + }; + return AWTClockSkewManager; + }(); + exports.default = AWTClockSkewManager; +}, function(module, exports, __webpack_require__) { + "use strict"; + Object.defineProperty(exports, "__esModule", { + value: true + }); + var Enums_1 = __webpack_require__(0); + var AWTRecordBatcher = function() { + function AWTRecordBatcher(_outboundQueue, _maxNumberOfEvents) { + this._outboundQueue = _outboundQueue; + this._maxNumberOfEvents = _maxNumberOfEvents; + this._currentBatch = {}; + this._currentNumEventsInBatch = 0; + } + AWTRecordBatcher.prototype.addEventToBatch = function(event) { + if (event.priority === Enums_1.AWTEventPriority.Immediate_sync) { + var immediateBatch = {}; + immediateBatch[event.apiKey] = [ event ]; + return immediateBatch; + } else { + if (this._currentNumEventsInBatch >= this._maxNumberOfEvents) { + this.flushBatch(); + } + if (this._currentBatch[event.apiKey] === undefined) { + this._currentBatch[event.apiKey] = []; + } + this._currentBatch[event.apiKey].push(event); + this._currentNumEventsInBatch++; + } + return null; + }; + AWTRecordBatcher.prototype.flushBatch = function() { + if (this._currentNumEventsInBatch > 0) { + this._outboundQueue.push(this._currentBatch); + this._currentBatch = {}; + this._currentNumEventsInBatch = 0; + } + }; + AWTRecordBatcher.prototype.hasBatch = function() { + return this._currentNumEventsInBatch > 0; + }; + return AWTRecordBatcher; + }(); + exports.default = AWTRecordBatcher; +}, function(module, exports, __webpack_require__) { + "use strict"; + Object.defineProperty(exports, "__esModule", { + value: true + }); + var AWTTransmissionManagerCore_1 = __webpack_require__(3); + var AWTTransmissionManager = function() { + function AWTTransmissionManager() {} + AWTTransmissionManager.setEventsHandler = function(eventsHandler) { + AWTTransmissionManagerCore_1.default.setEventsHandler(eventsHandler); + }; + AWTTransmissionManager.getEventsHandler = function() { + return AWTTransmissionManagerCore_1.default.getEventsHandler(); + }; + AWTTransmissionManager.scheduleTimer = function() { + AWTTransmissionManagerCore_1.default.scheduleTimer(); + }; + return AWTTransmissionManager; + }(); + exports.default = AWTTransmissionManager; +}, function(module, __webpack_exports__, __webpack_require__) { + "use strict"; + __webpack_require__.r(__webpack_exports__); + var Event = function() { + function Event() { + this._listeners = []; + } + Event.prototype.fireEvent = function(args) { + this._listeners.forEach(function(listener) { + return listener(args); + }); + }; + Event.prototype.addListener = function(listener) { + if (listener) { + this._listeners.push(listener); + } + }; + Event.prototype.removeListener = function(listener) { + this._listeners = this._listeners.filter(function(h) { + return h !== listener; + }); + }; + Event.prototype.getListenerCount = function() { + return this._listeners.length; + }; + return Event; + }(); + var onNotificationEvent = new Event(); + var LogLevel; + (function(LogLevel) { + LogLevel[LogLevel["Error"] = 0] = "Error"; + LogLevel[LogLevel["Warning"] = 1] = "Warning"; + LogLevel[LogLevel["Info"] = 2] = "Info"; + LogLevel[LogLevel["Verbose"] = 3] = "Verbose"; + })(LogLevel || (LogLevel = {})); + var Category; + (function(Category) { + Category[Category["Core"] = 0] = "Core"; + Category[Category["Sink"] = 1] = "Sink"; + Category[Category["Transport"] = 2] = "Transport"; + })(Category || (Category = {})); + function onNotification() { + return onNotificationEvent; + } + function logNotification(level, category, message) { + onNotificationEvent.fireEvent({ + level: level, + category: category, + message: message + }); + } + function logError(category, message, error) { + logNotification(LogLevel.Error, category, function() { + var errorMessage = error instanceof Error ? error.message : ""; + return message + ": " + errorMessage; + }); + } + var SamplingPolicy; + (function(SamplingPolicy) { + SamplingPolicy[SamplingPolicy["NotSet"] = 0] = "NotSet"; + SamplingPolicy[SamplingPolicy["Measure"] = 1] = "Measure"; + SamplingPolicy[SamplingPolicy["Diagnostics"] = 2] = "Diagnostics"; + SamplingPolicy[SamplingPolicy["CriticalBusinessImpact"] = 191] = "CriticalBusinessImpact"; + SamplingPolicy[SamplingPolicy["CriticalCensus"] = 192] = "CriticalCensus"; + SamplingPolicy[SamplingPolicy["CriticalExperimentation"] = 193] = "CriticalExperimentation"; + SamplingPolicy[SamplingPolicy["CriticalUsage"] = 194] = "CriticalUsage"; + })(SamplingPolicy || (SamplingPolicy = {})); + var PersistencePriority; + (function(PersistencePriority) { + PersistencePriority[PersistencePriority["NotSet"] = 0] = "NotSet"; + PersistencePriority[PersistencePriority["Normal"] = 1] = "Normal"; + PersistencePriority[PersistencePriority["High"] = 2] = "High"; + })(PersistencePriority || (PersistencePriority = {})); + var CostPriority; + (function(CostPriority) { + CostPriority[CostPriority["NotSet"] = 0] = "NotSet"; + CostPriority[CostPriority["Normal"] = 1] = "Normal"; + CostPriority[CostPriority["High"] = 2] = "High"; + })(CostPriority || (CostPriority = {})); + var DataCategories; + (function(DataCategories) { + DataCategories[DataCategories["NotSet"] = 0] = "NotSet"; + DataCategories[DataCategories["SoftwareSetup"] = 1] = "SoftwareSetup"; + DataCategories[DataCategories["ProductServiceUsage"] = 2] = "ProductServiceUsage"; + DataCategories[DataCategories["ProductServicePerformance"] = 4] = "ProductServicePerformance"; + DataCategories[DataCategories["DeviceConfiguration"] = 8] = "DeviceConfiguration"; + DataCategories[DataCategories["InkingTypingSpeech"] = 16] = "InkingTypingSpeech"; + })(DataCategories || (DataCategories = {})); + var DiagnosticLevel; + (function(DiagnosticLevel) { + DiagnosticLevel[DiagnosticLevel["ReservedDoNotUse"] = 0] = "ReservedDoNotUse"; + DiagnosticLevel[DiagnosticLevel["BasicEvent"] = 10] = "BasicEvent"; + DiagnosticLevel[DiagnosticLevel["FullEvent"] = 100] = "FullEvent"; + DiagnosticLevel[DiagnosticLevel["NecessaryServiceDataEvent"] = 110] = "NecessaryServiceDataEvent"; + DiagnosticLevel[DiagnosticLevel["AlwaysOnNecessaryServiceDataEvent"] = 120] = "AlwaysOnNecessaryServiceDataEvent"; + })(DiagnosticLevel || (DiagnosticLevel = {})); + function isWacAgave() { + if (typeof Office !== "undefined" && typeof Office.context !== "undefined" && typeof Office.context.platform !== "undefined") { + return Office.context.platform === Office.PlatformType.OfficeOnline; + } + return typeof OfficeExt !== "undefined" && typeof OfficeExt.HostName !== "undefined" && typeof OfficeExt.HostName.Host !== "undefined" && typeof OfficeExt.HostName.Host.getInstance === "function" && typeof OfficeExt.HostName.Host.getInstance().getPlatform === "function" && OfficeExt.HostName.Host.getInstance().getPlatform() === Office.PlatformType.OfficeOnline; + } + function getEffectiveEventFlags(telemetryEvent) { + var eventFlags = { + costPriority: CostPriority.Normal, + samplingPolicy: SamplingPolicy.Measure, + persistencePriority: PersistencePriority.Normal, + dataCategories: DataCategories.NotSet, + diagnosticLevel: DiagnosticLevel.FullEvent + }; + if (!telemetryEvent.eventFlags || !telemetryEvent.eventFlags.dataCategories) { + logNotification(LogLevel.Error, Category.Core, function() { + return "Event is missing DataCategories event flag"; + }); + } + if (!telemetryEvent.eventFlags) { + return eventFlags; + } + if (telemetryEvent.eventFlags.costPriority) { + eventFlags.costPriority = telemetryEvent.eventFlags.costPriority; + } + if (telemetryEvent.eventFlags.samplingPolicy) { + eventFlags.samplingPolicy = telemetryEvent.eventFlags.samplingPolicy; + } + if (telemetryEvent.eventFlags.persistencePriority) { + eventFlags.persistencePriority = telemetryEvent.eventFlags.persistencePriority; + } + if (telemetryEvent.eventFlags.dataCategories) { + eventFlags.dataCategories = telemetryEvent.eventFlags.dataCategories; + } + if (telemetryEvent.eventFlags.diagnosticLevel) { + eventFlags.diagnosticLevel = telemetryEvent.eventFlags.diagnosticLevel; + } + return eventFlags; + } + var DataClassification; + (function(DataClassification) { + DataClassification[DataClassification["EssentialServiceMetadata"] = 1] = "EssentialServiceMetadata"; + DataClassification[DataClassification["AccountData"] = 2] = "AccountData"; + DataClassification[DataClassification["SystemMetadata"] = 4] = "SystemMetadata"; + DataClassification[DataClassification["OrganizationIdentifiableInformation"] = 8] = "OrganizationIdentifiableInformation"; + DataClassification[DataClassification["EndUserIdentifiableInformation"] = 16] = "EndUserIdentifiableInformation"; + DataClassification[DataClassification["CustomerContent"] = 32] = "CustomerContent"; + DataClassification[DataClassification["AccessControl"] = 64] = "AccessControl"; + })(DataClassification || (DataClassification = {})); + var DEFAULT_MINIMUM_MILLISECONDS_BETWEEN_CALLS = 1e3; + var _minimumMillisecondsBeforeFirstCall = DEFAULT_MINIMUM_MILLISECONDS_BETWEEN_CALLS; + var _minimumMillisecondsBetweenCalls = DEFAULT_MINIMUM_MILLISECONDS_BETWEEN_CALLS; + var RichApiSink_RichApiSink = function() { + function RichApiSink(onSendFirstEvent) { + this._requestIsPending = false; + this._items = []; + this._sentFirstEvent = false; + this._onSendFirstEvent = onSendFirstEvent; + } + RichApiSink.prototype.sendTelemetryEvent = function(telemetryEvent) { + this._items.push(telemetryEvent); + if (this._requestIsPending) { + return; + } + this.processWorkBacklog(); + }; + RichApiSink.prototype.processWorkBacklog = function() { + var _this = this; + this._requestIsPending = true; + var currentWork = this._items; + this._items = []; + this.pauseIfNecessary().then(function() { + _this.processTelemetryEvents(currentWork); + _this.waitAndProcessMore(); + }).catch(function(error) { + logError(Category.Sink, "RichAPI Error", error); + _this.waitAndProcessMore(); + }); + }; + RichApiSink.prototype.waitAndProcessMore = function() { + var _this = this; + pause(_minimumMillisecondsBetweenCalls).then(function() { + if (_this._items.length > 0) { + setTimeout(function() { + return _this.processWorkBacklog(); + }, 0); + } + _this._requestIsPending = false; + }); + }; + RichApiSink.prototype.processTelemetryEvents = function(telemetryEvents) { + var _this = this; + var ctx = new OfficeCore.RequestContext(); + telemetryEvents.forEach(function(telemetryEvent) { + if (!telemetryEvent.telemetryProperties) { + return; + } + var dataFields = []; + _this.addDataFields(dataFields, telemetryEvent.dataFields); + var contractName = !!telemetryEvent.eventContract ? telemetryEvent.eventContract.name : ""; + if (!!telemetryEvent.eventContract) { + _this.addDataFields(dataFields, telemetryEvent.eventContract.dataFields); + } + ctx.telemetry.sendTelemetryEvent(telemetryEvent.telemetryProperties, telemetryEvent.eventName, contractName, getEffectiveEventFlags(telemetryEvent), dataFields); + }); + ctx.sync().then(function() { + if (!_this._sentFirstEvent) { + _this._sentFirstEvent = true; + if (_this._onSendFirstEvent) { + _this._onSendFirstEvent(true); + } + } + }).catch(function(e) { + if (!_this._sentFirstEvent) { + _this._sentFirstEvent = true; + if (_this._onSendFirstEvent) { + _this._onSendFirstEvent(false); + } + } + logError(Category.Sink, "RichApiError", e); + }); + }; + RichApiSink.prototype.addDataFields = function(richApiDataFields, dataFields) { + if (dataFields) { + dataFields.forEach(function(dataField) { + richApiDataFields.push({ + name: dataField.name, + value: dataField.value, + classification: dataField.classification ? dataField.classification : DataClassification.SystemMetadata, + type: dataField.dataType + }); + }); + } + }; + RichApiSink.prototype.pauseIfNecessary = function() { + if (!this._sentFirstEvent) { + return pause(_minimumMillisecondsBeforeFirstCall); + } + return OfficeExtension.Promise.resolve(undefined); + }; + return RichApiSink; + }(); + function pause(ms) { + return new OfficeExtension.Promise(function(resolve) { + return setTimeout(resolve, ms); + }); + } + var _queriedForIsSupported = false; + var _richApiSink; + var IsSupportedState; + (function(IsSupportedState) { + IsSupportedState[IsSupportedState["Unsupported"] = 0] = "Unsupported"; + IsSupportedState[IsSupportedState["Supported"] = 1] = "Supported"; + IsSupportedState[IsSupportedState["NotDetermined"] = 2] = "NotDetermined"; + })(IsSupportedState || (IsSupportedState = {})); + function getRichApiSink(forceNew, onGetRichApiSink) { + if (_queriedForIsSupported && !forceNew) { + return onGetRichApiSink(_richApiSink); + } + _richApiSink = undefined; + var isSupported = isSupportedSync(); + if (isSupported === IsSupportedState.NotDetermined) { + return isSupportedAsync(onGetRichApiSink); + } + _queriedForIsSupported = true; + if (isSupported === IsSupportedState.Supported) { + _richApiSink = new RichApiSink_RichApiSink(); + } + onGetRichApiSink(_richApiSink); + } + function isSupportedSync() { + if (isWacAgave()) { + logNotification(LogLevel.Info, Category.Sink, function() { + return "RichApi telemetry is not supported on Office Online"; + }); + return IsSupportedState.Unsupported; + } + if (typeof OfficeCore === "undefined") { + logNotification(LogLevel.Info, Category.Sink, function() { + return "Can't get OfficeCore"; + }); + return IsSupportedState.Unsupported; + } + if (isTelemetryApiSetSupported()) { + return IsSupportedState.Supported; + } + return IsSupportedState.NotDetermined; + } + function isTelemetryApiSetSupported() { + return Office.context.requirements.isSetSupported("Telemetry", 1.2); + } + function isSupportedAsync(onGetRichApiSink) { + var testEvent = { + telemetryProperties: { + nexusTenantToken: 1723, + ariaTenantToken: "f998cc5ba4d448d6a1e8e913ff18be94-dd122e0a-fcf8-4dc5-9dbb-6afac5325183-7405" + }, + eventName: "Office.Telemetry.RichApi.TestForSupport", + eventFlags: { + dataCategories: DataCategories.ProductServiceUsage, + diagnosticLevel: DiagnosticLevel.FullEvent + } + }; + function onSendFirstEvent(succeeded) { + if (!succeeded) { + _richApiSink = undefined; + logNotification(LogLevel.Info, Category.Sink, function() { + return "RichAPI SendTelemetryEvent is not supported on the host"; + }); + } + onGetRichApiSink(_richApiSink); + } + _richApiSink = new RichApiSink_RichApiSink(onSendFirstEvent); + _richApiSink.sendTelemetryEvent(testEvent); + } + var SdxWacSink_SdxWacSink = function() { + function SdxWacSink() {} + SdxWacSink.isSupported = function() { + return isWacAgave() && typeof OSF === "object" && typeof OSF.getClientEndPoint === "function" && typeof OSF._OfficeAppFactory === "object" && typeof OSF._OfficeAppFactory.getId === "function" && typeof OSF.AgaveHostAction === "object" && typeof OSF.AgaveHostAction.SendTelemetryEvent === "number"; + }; + SdxWacSink.prototype.sendTelemetryEvent = function(event, _timestamp) { + try { + if (event.dataFields && event.dataFields.filter(function(dataField) { + return dataField.classification && dataField.classification !== DataClassification.SystemMetadata; + }).length > 0) { + return; + } + var id = OSF._OfficeAppFactory.getId(); + var SendTelemetryEventId = OSF.AgaveHostAction.SendTelemetryEvent; + OSF.getClientEndPoint().invoke("ContextActivationManager_notifyHost", null, [ id, SendTelemetryEventId, event ]); + } catch (error) { + logError(Category.Sink, "AgaveWacSink", error); + } + }; + return SdxWacSink; + }(); + var AriaSDK = __webpack_require__(5); + var AWTTransmissionManagerCore = __webpack_require__(3); + var AWTTransmissionManagerCore_default = __webpack_require__.n(AWTTransmissionManagerCore); + var AWTQueueManager = __webpack_require__(11); + var AWTQueueManager_default = __webpack_require__.n(AWTQueueManager); + var Enums = __webpack_require__(0); + var DataFieldType; + (function(DataFieldType) { + DataFieldType[DataFieldType["String"] = 0] = "String"; + DataFieldType[DataFieldType["Boolean"] = 1] = "Boolean"; + DataFieldType[DataFieldType["Int64"] = 2] = "Int64"; + DataFieldType[DataFieldType["Double"] = 3] = "Double"; + DataFieldType[DataFieldType["Guid"] = 4] = "Guid"; + })(DataFieldType || (DataFieldType = {})); + var EVENT_NAME_DOT_REPLACE_REGEX = /\./g; + var SEPARATOR_TOKEN = "."; + var DATA_TOKEN = "Data"; + var CONTRACT_TOKEN = "zC"; + var eventSequence = 0; + function getAriaEvent(telemetryEvent, additionalDataFields, timestamp) { + var ariaEvent = { + name: getAriaEventName(telemetryEvent.eventName), + properties: {} + }; + ariaEvent.properties["Event.Sequence"] = { + value: ++eventSequence, + type: Enums["AWTPropertyType"].Int64 + }; + ariaEvent.properties["Event.Name"] = telemetryEvent.eventName; + ariaEvent.properties["Event.Source"] = "OTelJS"; + var timestampLocal; + if (timestamp) { + timestampLocal = new Date(timestamp); + } else { + timestampLocal = new Date(); + } + ariaEvent.properties["Event.Time"] = { + value: timestampLocal, + type: Enums["AWTPropertyType"].Date + }; + if (telemetryEvent.eventContract) { + ariaEvent.properties["Event.Contract"] = telemetryEvent.eventContract.name; + addDataFields(ariaEvent, telemetryEvent.eventContract.dataFields, false); + } + addDataFields(ariaEvent, additionalDataFields, false); + addDataFields(ariaEvent, telemetryEvent.dataFields, true); + return ariaEvent; + } + function addDataFields(ariaEvent, fields, prependDataToken) { + if (fields) { + fields.forEach(function(field) { + if (field.classification && !(field.classification === DataClassification.SystemMetadata || field.classification === DataClassification.EssentialServiceMetadata)) { + return; + } + var _a = [ "", "", field.name ], metadataPrefix = _a[0], dataToken = _a[1], fieldName = _a[2]; + var firstSeparator = field.name.indexOf(SEPARATOR_TOKEN); + if (firstSeparator > 0 && isMetadataPrefix(field.name.substr(0, firstSeparator))) { + metadataPrefix = field.name.substring(0, firstSeparator + 1); + fieldName = field.name.substring(firstSeparator + 1); + } + if (prependDataToken) { + dataToken = DATA_TOKEN + SEPARATOR_TOKEN; + } + var ariaFieldName = metadataPrefix + dataToken + fieldName; + ariaEvent.properties[ariaFieldName] = { + value: field.value, + type: mapDataFieldTypeToAWTPropertyType(field.dataType) + }; + }); + } + } + function mapDataFieldTypeToAWTPropertyType(otelType) { + switch (otelType) { + case DataFieldType.String: + case DataFieldType.Guid: + return Enums["AWTPropertyType"].String; + + case DataFieldType.Boolean: + return Enums["AWTPropertyType"].Boolean; + + case DataFieldType.Int64: + return Enums["AWTPropertyType"].Int64; + + case DataFieldType.Double: + return Enums["AWTPropertyType"].Double; + + default: + var _exhaustiveCheck = otelType; + throw new Error(_exhaustiveCheck); + } + } + function getAriaEventName(eventName) { + return eventName.toLowerCase().replace(EVENT_NAME_DOT_REPLACE_REGEX, "_"); + } + function isMetadataPrefix(prefix) { + return prefix === CONTRACT_TOKEN; + } + var ARIA_INIT_TOKEN = "cd836626611c4caaa8fc5b2e728ee81d-3b6d6c45-6377-4bf5-9792-dbf8e1881088-7521"; + var otelEventsProcessed = 0; + var ariaEventsSent = 0; + var ariaEventsDropped = 0; + var ariaEventsRejected = 0; + var ariaEventsRetrying = 0; + var awtInitialized = false; + function sendEvent(telemetryEvent, additionalDataFields, timestamp) { + otelEventsProcessed++; + initialize(); + var ariaEvent; + if (!telemetryEvent.telemetryProperties || !telemetryEvent.telemetryProperties.ariaTenantToken) { + throw new Error("Missing Aria Tenant Token"); + } + ariaEvent = getAriaEvent(telemetryEvent, additionalDataFields, timestamp); + var logger = AriaSDK["AWTLogManager"].getLogger(telemetryEvent.telemetryProperties.ariaTenantToken); + logger.logEvent(ariaEvent); + } + function initialize(configuration) { + if (!awtInitialized) { + hookUpAriaNotifications(); + AriaSDK["AWTLogManager"].initialize(ARIA_INIT_TOKEN, configuration); + awtInitialized = true; + } + } + function hookUpAriaNotifications() { + AriaSDK["AWTLogManager"].addNotificationListener({ + eventsSent: function(events) { + logNotification(LogLevel.Info, Category.Transport, function() { + return "Successfully sent " + events.length + " event(s)"; + }); + logNotification(LogLevel.Verbose, Category.Transport, function() { + return "Sent event(s) details : " + JSON.stringify(events, null, 2); + }); + ariaEventsSent += events.length; + }, + eventsDropped: function(events, reason) { + logNotification(LogLevel.Error, Category.Transport, function() { + return "Dropped " + events.length + " event(s) because " + reason; + }); + logNotification(LogLevel.Verbose, Category.Transport, function() { + return "Dropped event(s) details : " + JSON.stringify(events, null, 2); + }); + ariaEventsDropped += events.length; + }, + eventsRejected: function(events, reason) { + logNotification(LogLevel.Error, Category.Transport, function() { + return "Rejected " + events.length + " event(s) because " + reason; + }); + logNotification(LogLevel.Verbose, Category.Transport, function() { + return "Rejected event(s) details : " + JSON.stringify(events, null, 2); + }); + ariaEventsRejected += events.length; + }, + eventsRetrying: function(events) { + logNotification(LogLevel.Warning, Category.Transport, function() { + return "Retrying " + events.length + " event(s)"; + }); + logNotification(LogLevel.Verbose, Category.Transport, function() { + return "Retrying event(s) details : " + JSON.stringify(events, null, 2); + }); + ariaEventsRetrying += events.length; + } + }); + } + function disableBeaconsApiAvailabilityForAriaSdk() { + var ariaEventHander = AWTTransmissionManagerCore_default.a.getEventsHandler(); + if (ariaEventHander instanceof AWTQueueManager_default.a) { + var ariaHttpManager = ariaEventHander._httpManager; + if (ariaHttpManager && ariaHttpManager.hasOwnProperty("_useBeacons")) { + ariaHttpManager._useBeacons = false; + return true; + } + } + return false; + } + function shutdown() { + AriaSDK["AWTLogManager"].flushAndTeardown(); + } + var FullEventProcessor_FullEventProcessor = function() { + function FullEventProcessor() { + this._fullEventsEnabled = false; + } + FullEventProcessor.prototype.processEvent = function(event) { + return this._fullEventsEnabled || !!event.eventFlags && (event.eventFlags.diagnosticLevel === DiagnosticLevel.BasicEvent || event.eventFlags.diagnosticLevel === DiagnosticLevel.NecessaryServiceDataEvent || event.eventFlags.diagnosticLevel === DiagnosticLevel.AlwaysOnNecessaryServiceDataEvent); + }; + FullEventProcessor.prototype.setFullEventsEnabled = function(enabled) { + this._fullEventsEnabled = enabled; + }; + return FullEventProcessor; + }(); + var AriaSinkType; + (function(AriaSinkType) { + AriaSinkType[AriaSinkType["Aria"] = 0] = "Aria"; + AriaSinkType[AriaSinkType["AriaSE"] = 1] = "AriaSE"; + })(AriaSinkType || (AriaSinkType = {})); + var AriaSink_AriaSink = function() { + function AriaSink(additionalDataFields, cacheMemorySizeLimitInNumberOfEvents, ariaSinkProperties) { + if (additionalDataFields === void 0) { + additionalDataFields = []; + } + this._preprocessors = []; + this.additionalDataFields = additionalDataFields; + this._fullEventProcessor = new FullEventProcessor_FullEventProcessor(); + this.addPreprocessor(this._fullEventProcessor); + if (AriaSink.ariaSinkType === undefined) { + AriaSink.ariaSinkType = this.getSinkType(); + } else if (AriaSink.ariaSinkType !== this.getSinkType()) { + throw new Error("Multiple Aria Configurations are not allowed"); + } + initialize(this.getAWTLogConfiguration(cacheMemorySizeLimitInNumberOfEvents, ariaSinkProperties)); + } + AriaSink.prototype.getSinkType = function() { + return AriaSinkType.Aria; + }; + AriaSink.prototype.getAWTLogConfiguration = function(cacheMemorySizeLimitInNumberOfEvents, ariaSinkProperties) { + var awtLogConfiguration = { + cacheMemorySizeLimitInNumberOfEvents: cacheMemorySizeLimitInNumberOfEvents, + disableCookiesUsage: true + }; + if (ariaSinkProperties !== undefined) { + awtLogConfiguration.collectorUri = ariaSinkProperties.endpointUrl; + } + return awtLogConfiguration; + }; + AriaSink.prototype.sendTelemetryEvent = function(event, timestamp) { + try { + for (var i = 0; i < this._preprocessors.length; i++) { + if (!this._preprocessors[i].processEvent(event)) { + return; + } + } + sendEvent(event, this.additionalDataFields, timestamp); + } catch (error) { + logError(Category.Sink, "AriaSink", error); + } + }; + AriaSink.prototype.getAdditionalDataFields = function() { + return this.additionalDataFields; + }; + AriaSink.prototype.addPreprocessor = function(preprocessor) { + this._preprocessors.push(preprocessor); + }; + AriaSink.prototype.setFullEventsEnabled = function(enabled) { + this._fullEventProcessor.setFullEventsEnabled(enabled); + }; + AriaSink.prototype.disableBeaconsApiAvailabilityForAriaSdk = function() { + return disableBeaconsApiAvailabilityForAriaSdk(); + }; + AriaSink.prototype.shutdown = function() { + shutdown(); + }; + return AriaSink; + }(); + function getDataFieldsFromContext(context) { + var additionalDataFields = []; + Object.keys(context).forEach(function(key) { + additionalDataFields.push({ + name: key, + value: context[key], + dataType: DataFieldType.String + }); + }); + return additionalDataFields; + } + var OutlookSink_OutlookSink = function() { + function OutlookSink(context) { + this._supportsAllEvents = false; + this._contextDataFields = []; + this._supportsAllEvents = Office.context.requirements.isSetSupported("OutlookTelemetry", 1.1); + if (context["App.Platform"] === "iOS" || context["App.Platform"] === "Android") { + this._contextDataFields = getDataFieldsFromContext(context); + } + } + OutlookSink.isSupported = function() { + try { + return Office.context.requirements.isSetSupported("OutlookTelemetry"); + } catch (_a) { + return false; + } + }; + OutlookSink.prototype.sendTelemetryEvent = function(event) { + if (!this._supportsAllEvents && !event.eventName.match(/^Office\.Extensibility\.OfficeJs\.[a-zA-Z]*$/)) { + logNotification(LogLevel.Info, Category.Sink, function() { + return "This version of Outlook only accepts OfficeJS telemetry events"; + }); + return; + } + this.addAdditionalDataFields(event); + Office.context.mailbox.logTelemetry(JSON.stringify(event)); + }; + OutlookSink.prototype.addAdditionalDataFields = function(event) { + var _a; + event.dataFields = event.dataFields || []; + (_a = event.dataFields).push.apply(_a, this._contextDataFields); + }; + return OutlookSink; + }(); + var v4 = __webpack_require__(19); + var Utils_Utils; + (function(Utils) { + function newGuid() { + return v4(); + } + Utils.newGuid = newGuid; + })(Utils_Utils || (Utils_Utils = {})); + var BASE10 = 10; + var MAX_SUPPORTED_WIN32_VERSION = [ 16, 0, 11599 ]; + var MAX_SUPPORTED_MAC_VERSION = [ 16, 26 ]; + var MAX_SUPPORTED_IOS_WXP_VERSION = [ 2, 29 ]; + var MAX_SUPPORTED_WEB_OUTLOOK_VERSION = [ 16, 0, 99999 ]; + var _additionalContext; + var _sendEventEnabled; + function AriaHelper_initialize(additionalContext, sendEventEnabled) { + _additionalContext = additionalContext; + _sendEventEnabled = sendEventEnabled; + } + function getAdditionalDataFields() { + if (!_additionalContext["Session.Id"]) { + _additionalContext["Session.Id"] = getSessionId(); + } + return getDataFieldsFromContext(_additionalContext); + } + function canSendToAria() { + if (!_sendEventEnabled) { + return false; + } + var platform = _additionalContext["App.Platform"]; + var version = _additionalContext["App.Version"]; + var appName = _additionalContext["App.Name"]; + return isSupportedVersion(version, platform, appName); + } + function isSupportedVersion(version, platform, appName) { + if (!version) { + return true; + } + var versionArray = String(version).split("."); + var maxVersion; + if (platform === "Win32") { + maxVersion = MAX_SUPPORTED_WIN32_VERSION; + } else if (platform === "Mac") { + maxVersion = MAX_SUPPORTED_MAC_VERSION; + } else if (platform === "iOS") { + if (appName === "Outlook") { + return true; + } + maxVersion = MAX_SUPPORTED_IOS_WXP_VERSION; + } else if (platform === "Web" && appName === "Outlook") { + maxVersion = MAX_SUPPORTED_WEB_OUTLOOK_VERSION; + } else { + return false; + } + for (var i = 0; i < maxVersion.length && i < versionArray.length; i++) { + var versionToken = parseInt(versionArray[i], BASE10); + if (isNaN(versionToken)) { + return false; + } + if (versionToken < maxVersion[i]) { + return true; + } + if (versionToken > maxVersion[i]) { + return false; + } + } + return true; + } + function getSessionId() { + return Utils_Utils.newGuid(); + } + var E_TELEMETRY_DISABLED = "AppTelemetry is disabled for this platform."; + var AgaveSink_AgaveSink = function() { + function AgaveSink(ariaAdditionalContext, ariaSendEventEnabled) { + this._isUsable = true; + this._awaitingInitialization = false; + this._eventQueue = []; + this._ariaAdditionalContext = ariaAdditionalContext; + AriaHelper_initialize(this._ariaAdditionalContext, ariaSendEventEnabled); + this.initialize(); + } + AgaveSink.createInstance = function(ariaAdditionalContext, ariaSendEventEnabled) { + if (ariaAdditionalContext === void 0) { + ariaAdditionalContext = {}; + } + if (ariaSendEventEnabled === void 0) { + ariaSendEventEnabled = true; + } + var agaveSink = new AgaveSink(ariaAdditionalContext, ariaSendEventEnabled); + if (!agaveSink._isUsable) { + return undefined; + } + return agaveSink; + }; + AgaveSink.prototype.initialize = function() { + if (!this.isTelemetryEnabled()) { + this.failToInitialize(E_TELEMETRY_DISABLED); + } + if (OutlookSink_OutlookSink.isSupported()) { + this.connectOutlookSink(); + } else if (SdxWacSink_SdxWacSink.isSupported()) { + this.connectSdxWacSink(); + } else if (isWacAgave() || typeof OfficeExtension === "undefined") { + if (canSendToAria()) { + this.connectAriaSink(); + } else { + this.failToInitialize(); + } + } else { + this._awaitingInitialization = true; + getRichApiSink(false, this.onGetRichApi.bind(this)); + } + }; + AgaveSink.prototype.onGetRichApi = function(richApiSink) { + var _this = this; + if (richApiSink) { + this.connectRichApiSink(richApiSink); + } else if (canSendToAria()) { + this.connectAriaSink(); + } else { + this.failToInitialize(); + } + this._awaitingInitialization = false; + this._eventQueue.forEach(function(event) { + _this.sendTelemetryEvent(event); + }); + }; + AgaveSink.prototype.failToInitialize = function(reason) { + this._isUsable = false; + this._awaitingInitialization = false; + var errorMessage = reason ? reason : "AgaveSink could not find a suitable sink to use"; + logNotification(LogLevel.Error, Category.Sink, function() { + return errorMessage; + }); + }; + AgaveSink.prototype.sendTelemetryEvent = function(event) { + if (this._awaitingInitialization && this._isUsable) { + this._eventQueue.push(event); + } else if (this._sink) { + try { + this._sink.sendTelemetryEvent(event); + } catch (error) { + logError(Category.Sink, "AgaveSink", error); + } + } else { + logNotification(LogLevel.Error, Category.Sink, function() { + return "AgaveSink does not have an underlying sink"; + }); + } + }; + AgaveSink.prototype.connectOutlookSink = function() { + this._sink = new OutlookSink_OutlookSink(this._ariaAdditionalContext); + logNotification(LogLevel.Info, Category.Sink, function() { + return "AgaveSink is using OutlookSink"; + }); + }; + AgaveSink.prototype.connectRichApiSink = function(sink) { + this._sink = sink; + logNotification(LogLevel.Info, Category.Sink, function() { + return "AgaveSink is using RichApiSink"; + }); + }; + AgaveSink.prototype.connectAriaSink = function() { + this._sink = new AriaSink_AriaSink(getAdditionalDataFields()); + logNotification(LogLevel.Info, Category.Sink, function() { + return "AgaveSink is using AriaSink"; + }); + }; + AgaveSink.prototype.connectSdxWacSink = function() { + this._sink = new SdxWacSink_SdxWacSink(); + logNotification(LogLevel.Info, Category.Sink, function() { + return "AgaveSink is using SdxWacSink"; + }); + }; + AgaveSink.prototype.isTelemetryEnabled = function() { + if (typeof OSF !== "undefined") { + if (typeof OSF.AppTelemetry === "undefined" || typeof OSF.AppTelemetry.enableTelemetry === "undefined" || OSF.AppTelemetry.enableTelemetry === false) { + logNotification(LogLevel.Warning, Category.Core, function() { + return E_TELEMETRY_DISABLED; + }); + return false; + } + } + return true; + }; + return AgaveSink; + }(); + __webpack_require__.d(__webpack_exports__, "AgaveSink", function() { + return AgaveSink_AgaveSink; + }); +} ]); \ No newline at end of file