From 5c14f332f0173807d863f177591a4508d3fa17e3 Mon Sep 17 00:00:00 2001 From: Serhii Mamontov Date: Wed, 15 May 2024 17:22:17 +0300 Subject: [PATCH 1/3] feat(shared-worker): migrate to shared worker Use `SharedWorker` instead of `Service Worker` for better PubNub client instances feedback. feat(shared-worker): add worker log verbosity flag Add configuration option to enable debug log output from the subscription `SharedWorker`. refactor: add declarations generation Create types declaration files. --- .prettierrc | 1 + dist/web/pubnub.js | 1608 ++++++++++------- dist/web/pubnub.min.js | 4 +- dist/web/pubnub.worker.js | 452 +++-- dist/web/pubnub.worker.min.js | 4 +- lib/core/utils.js | 6 +- lib/event-engine/index.js | 4 +- lib/node/index.js | 93 +- lib/types/cbor/common.d.ts | 1 + lib/types/core/components/abort_signal.d.ts | 4 + lib/types/core/components/base64_codec.d.ts | 1 + lib/types/core/components/configuration.d.ts | 1 + .../components/cryptography/hmac-sha256.d.ts | 3 + .../core/components/cryptography/index.d.ts | 30 + .../core/components/deduping_manager.d.ts | 11 + lib/types/core/components/eventEmitter.d.ts | 1 + .../core/components/listener_manager.d.ts | 14 + lib/types/core/components/push_payload.d.ts | 156 ++ .../core/components/reconnection_manager.d.ts | 1 + lib/types/core/components/request.d.ts | 1 + .../components/stringify_buffer_keys.d.ts | 1 + lib/types/core/components/subject.d.ts | 1 + .../core/components/subscription-manager.d.ts | 1 + lib/types/core/components/token_manager.d.ts | 1 + lib/types/core/components/uuid.d.ts | 4 + lib/types/core/constants/categories.d.ts | 19 + lib/types/core/constants/operations.d.ts | 55 + .../core/endpoints/access_manager/audit.d.ts | 1 + .../core/endpoints/access_manager/grant.d.ts | 1 + .../endpoints/access_manager/grant_token.d.ts | 1 + .../access_manager/revoke_token.d.ts | 1 + .../endpoints/actions/add_message_action.d.ts | 1 + .../actions/get_message_actions.d.ts | 1 + .../actions/remove_message_action.d.ts | 1 + .../channel_groups/add_channels.d.ts | 1 + .../channel_groups/delete_group.d.ts | 1 + .../channel_groups/list_channels.d.ts | 1 + .../endpoints/channel_groups/list_groups.d.ts | 1 + .../channel_groups/remove_channels.d.ts | 1 + lib/types/core/endpoints/fetch_messages.d.ts | 1 + .../endpoints/file_upload/delete_file.d.ts | 1 + .../endpoints/file_upload/download_file.d.ts | 1 + .../file_upload/generate_upload_url.d.ts | 1 + .../endpoints/file_upload/get_file_url.d.ts | 1 + .../endpoints/file_upload/list_files.d.ts | 1 + .../endpoints/file_upload/publish_file.d.ts | 1 + .../core/endpoints/file_upload/send_file.d.ts | 1 + .../endpoints/file_upload/upload-file.d.ts | 1 + .../endpoints/history/delete_messages.d.ts | 1 + .../core/endpoints/history/get_history.d.ts | 1 + .../endpoints/history/message_counts.d.ts | 1 + .../core/endpoints/objects/channel/get.d.ts | 1 + .../endpoints/objects/channel/get_all.d.ts | 1 + .../endpoints/objects/channel/remove.d.ts | 1 + .../core/endpoints/objects/channel/set.d.ts | 1 + .../core/endpoints/objects/member/get.d.ts | 1 + .../core/endpoints/objects/member/set.d.ts | 1 + .../endpoints/objects/membership/get.d.ts | 1 + .../endpoints/objects/membership/set.d.ts | 1 + .../core/endpoints/objects/uuid/get.d.ts | 1 + .../core/endpoints/objects/uuid/get_all.d.ts | 1 + .../core/endpoints/objects/uuid/remove.d.ts | 1 + .../core/endpoints/objects/uuid/set.d.ts | 1 + .../core/endpoints/presence/get_state.d.ts | 1 + .../core/endpoints/presence/heartbeat.d.ts | 1 + .../core/endpoints/presence/here_now.d.ts | 1 + lib/types/core/endpoints/presence/leave.d.ts | 1 + .../core/endpoints/presence/set_state.d.ts | 1 + .../core/endpoints/presence/where_now.d.ts | 1 + lib/types/core/endpoints/publish.d.ts | 15 + .../endpoints/push/add_push_channels.d.ts | 1 + .../endpoints/push/list_push_channels.d.ts | 1 + lib/types/core/endpoints/push/push.d.ts | 1 + .../core/endpoints/push/remove_device.d.ts | 1 + .../endpoints/push/remove_push_channels.d.ts | 1 + lib/types/core/endpoints/signal.d.ts | 8 + lib/types/core/endpoints/subscribe.d.ts | 1 + .../subscriptionUtils/handshake.d.ts | 1 + .../subscriptionUtils/receiveMessages.d.ts | 1 + lib/types/core/endpoints/time.d.ts | 3 + lib/types/core/interfaces/configuration.d.ts | 74 + lib/types/core/interfaces/crypto-module.d.ts | 33 + lib/types/core/interfaces/cryptography.d.ts | 7 + lib/types/core/interfaces/request.d.ts | 1 + lib/types/core/interfaces/transport.d.ts | 12 + lib/types/core/pubnub-channel-groups.d.ts | 17 + lib/types/core/pubnub-common.d.ts | 230 +++ lib/types/core/pubnub-objects.d.ts | 52 + lib/types/core/pubnub-push.d.ts | 15 + lib/types/core/types/api/access-panager.d.ts | 124 ++ lib/types/core/types/api/app-context.d.ts | 207 +++ lib/types/core/types/api/channel-groups.d.ts | 18 + lib/types/core/types/api/file-sharing.d.ts | 85 + lib/types/core/types/api/history.d.ts | 105 ++ lib/types/core/types/api/index.d.ts | 33 + lib/types/core/types/api/message-action.d.ts | 44 + lib/types/core/types/api/presence.d.ts | 61 + .../core/types/api/push-notifications.d.ts | 14 + lib/types/core/types/api/push.d.ts | 32 + lib/types/core/types/api/subscription.d.ts | 96 + lib/types/core/types/file.d.ts | 24 + lib/types/core/types/transport-request.d.ts | 24 + lib/types/core/types/transport-response.d.ts | 6 + lib/types/core/utils.d.ts | 6 + lib/types/crypto/index.d.ts | 0 .../modules/NodeCryptoModule/ICryptor.d.ts | 18 + .../NodeCryptoModule/ILegacyCryptor.d.ts | 11 + .../NodeCryptoModule/aesCbcCryptor.d.ts | 25 + .../NodeCryptoModule/legacyCryptor.d.ts | 18 + .../NodeCryptoModule/nodeCryptoModule.d.ts | 26 + lib/types/crypto/modules/node.d.ts | 23 + lib/types/entities/Channel.d.ts | 11 + lib/types/entities/ChannelGroup.d.ts | 11 + lib/types/entities/ChannelMetadata.d.ts | 11 + lib/types/entities/SubscribeCapable.d.ts | 25 + lib/types/entities/Subscription.d.ts | 22 + lib/types/entities/SubscriptionSet.d.ts | 27 + lib/types/entities/UserMetadata.d.ts | 11 + lib/types/entities/commonTypes.d.ts | 7 + lib/types/errors/pubnub-api-error.d.ts | 16 + lib/types/errors/pubnub-error.d.ts | 6 + lib/types/event-engine/core/change.d.ts | 24 + lib/types/event-engine/core/dispatcher.d.ts | 13 + lib/types/event-engine/core/engine.d.ts | 11 + lib/types/event-engine/core/handler.d.ts | 18 + lib/types/event-engine/core/index.d.ts | 4 + lib/types/event-engine/core/retryPolicy.d.ts | 26 + lib/types/event-engine/core/state.d.ts | 21 + lib/types/event-engine/core/types.d.ts | 45 + lib/types/event-engine/dispatcher.d.ts | 27 + lib/types/event-engine/effects.d.ts | 77 + lib/types/event-engine/events.d.ts | 159 ++ lib/types/event-engine/index.d.ts | 33 + .../event-engine/presence/dispatcher.d.ts | 18 + lib/types/event-engine/presence/effects.d.ts | 31 + lib/types/event-engine/presence/events.d.ts | 47 + lib/types/event-engine/presence/presence.d.ts | 24 + .../presence/states/heartbeat_cooldown.d.ts | 8 + .../presence/states/heartbeat_failed.d.ts | 8 + .../presence/states/heartbeat_inactive.d.ts | 4 + .../states/heartbeat_reconnecting.d.ts | 11 + .../presence/states/heartbeat_stopped.d.ts | 8 + .../presence/states/heartbeating.d.ts | 8 + .../event-engine/states/handshake_failed.d.ts | 12 + .../states/handshake_reconnecting.d.ts | 13 + .../states/handshake_stopped.d.ts | 11 + .../event-engine/states/handshaking.d.ts | 10 + .../event-engine/states/receive_failed.d.ts | 12 + .../states/receive_reconnecting.d.ts | 13 + .../event-engine/states/receive_stopped.d.ts | 11 + lib/types/event-engine/states/receiving.d.ts | 10 + .../event-engine/states/unsubscribed.d.ts | 4 + lib/types/file/modules/node.d.ts | 35 + lib/types/file/modules/react-native.d.ts | 40 + lib/types/models/Cursor.d.ts | 4 + lib/types/node/configuration.d.ts | 13 + lib/types/node/index.d.ts | 18 + lib/types/react_native/configuration.d.ts | 3 + lib/types/react_native/index.d.ts | 7 + lib/types/transport/middleware.d.ts | 30 + lib/types/transport/node-transport.d.ts | 22 + .../transport/web-react-native-transport.d.ts | 13 + package-lock.json | 4 +- package.json | 1 + rollup.config.js | 12 +- src/cbor/common.ts | 2 + src/core/components/abort_signal.ts | 5 + src/core/components/base64_codec.ts | 10 + src/core/components/configuration.ts | 6 + src/core/components/deduping_manager.js | 5 + src/core/components/eventEmitter.ts | 8 + src/core/components/listener_manager.ts | 2 + src/core/components/reconnection_manager.ts | 7 + src/core/components/request.ts | 2 + src/core/components/stringify_buffer_keys.ts | 9 + src/core/components/subject.ts | 3 + src/core/components/subscription-manager.ts | 2 + src/core/components/token_manager.ts | 2 + src/core/endpoints/access_manager/audit.ts | 2 + src/core/endpoints/access_manager/grant.ts | 2 + .../endpoints/access_manager/grant_token.ts | 2 + .../endpoints/access_manager/revoke_token.ts | 2 + .../endpoints/actions/add_message_action.ts | 2 + .../endpoints/actions/get_message_actions.ts | 2 + .../actions/remove_message_action.ts | 2 + .../endpoints/channel_groups/add_channels.ts | 2 + .../endpoints/channel_groups/delete_group.ts | 2 + .../endpoints/channel_groups/list_channels.ts | 2 + .../endpoints/channel_groups/list_groups.ts | 2 + .../channel_groups/remove_channels.ts | 2 + src/core/endpoints/fetch_messages.ts | 2 + src/core/endpoints/file_upload/delete_file.ts | 2 + .../endpoints/file_upload/download_file.ts | 2 + .../file_upload/generate_upload_url.ts | 2 + .../endpoints/file_upload/get_file_url.ts | 2 + src/core/endpoints/file_upload/list_files.ts | 2 + .../endpoints/file_upload/publish_file.ts | 5 + src/core/endpoints/file_upload/send_file.ts | 2 + src/core/endpoints/file_upload/upload-file.ts | 2 + src/core/endpoints/history/delete_messages.ts | 2 + src/core/endpoints/history/get_history.ts | 2 + src/core/endpoints/history/message_counts.ts | 5 + src/core/endpoints/objects/channel/get.ts | 2 + src/core/endpoints/objects/channel/get_all.ts | 2 + src/core/endpoints/objects/channel/remove.ts | 2 + src/core/endpoints/objects/channel/set.ts | 2 + src/core/endpoints/objects/member/get.ts | 2 + src/core/endpoints/objects/member/set.ts | 2 + src/core/endpoints/objects/membership/get.ts | 2 + src/core/endpoints/objects/membership/set.ts | 2 + src/core/endpoints/objects/uuid/get.ts | 2 + src/core/endpoints/objects/uuid/get_all.ts | 5 + src/core/endpoints/objects/uuid/remove.ts | 2 + src/core/endpoints/objects/uuid/set.ts | 2 + src/core/endpoints/presence/get_state.ts | 2 + src/core/endpoints/presence/heartbeat.ts | 5 + src/core/endpoints/presence/here_now.ts | 5 + src/core/endpoints/presence/leave.ts | 5 + src/core/endpoints/presence/set_state.ts | 2 + src/core/endpoints/presence/where_now.ts | 5 + src/core/endpoints/publish.ts | 2 + src/core/endpoints/push/add_push_channels.ts | 2 + src/core/endpoints/push/list_push_channels.ts | 2 + src/core/endpoints/push/push.ts | 2 + src/core/endpoints/push/remove_device.ts | 2 + .../endpoints/push/remove_push_channels.ts | 2 + src/core/endpoints/signal.ts | 5 + src/core/endpoints/subscribe.ts | 22 + .../endpoints/subscriptionUtils/handshake.ts | 2 + .../subscriptionUtils/receiveMessages.ts | 2 + src/core/endpoints/time.ts | 5 + src/core/interfaces/configuration.ts | 2 + src/core/interfaces/request.ts | 2 + src/core/pubnub-common.ts | 31 +- src/core/utils.ts | 2 +- src/event-engine/index.ts | 4 +- src/node/configuration.ts | 2 +- src/node/index.ts | 6 +- .../subscription-worker-middleware.ts} | 203 ++- .../subscription-worker.ts} | 597 ++++-- src/web/components/configuration.ts | 53 +- src/web/index.ts | 13 +- tsconfig.json | 7 +- 243 files changed, 5035 insertions(+), 1168 deletions(-) create mode 100644 lib/types/cbor/common.d.ts create mode 100644 lib/types/core/components/abort_signal.d.ts create mode 100644 lib/types/core/components/base64_codec.d.ts create mode 100644 lib/types/core/components/configuration.d.ts create mode 100644 lib/types/core/components/cryptography/hmac-sha256.d.ts create mode 100644 lib/types/core/components/cryptography/index.d.ts create mode 100644 lib/types/core/components/deduping_manager.d.ts create mode 100644 lib/types/core/components/eventEmitter.d.ts create mode 100644 lib/types/core/components/listener_manager.d.ts create mode 100644 lib/types/core/components/push_payload.d.ts create mode 100644 lib/types/core/components/reconnection_manager.d.ts create mode 100644 lib/types/core/components/request.d.ts create mode 100644 lib/types/core/components/stringify_buffer_keys.d.ts create mode 100644 lib/types/core/components/subject.d.ts create mode 100644 lib/types/core/components/subscription-manager.d.ts create mode 100644 lib/types/core/components/token_manager.d.ts create mode 100644 lib/types/core/components/uuid.d.ts create mode 100644 lib/types/core/constants/categories.d.ts create mode 100644 lib/types/core/constants/operations.d.ts create mode 100644 lib/types/core/endpoints/access_manager/audit.d.ts create mode 100644 lib/types/core/endpoints/access_manager/grant.d.ts create mode 100644 lib/types/core/endpoints/access_manager/grant_token.d.ts create mode 100644 lib/types/core/endpoints/access_manager/revoke_token.d.ts create mode 100644 lib/types/core/endpoints/actions/add_message_action.d.ts create mode 100644 lib/types/core/endpoints/actions/get_message_actions.d.ts create mode 100644 lib/types/core/endpoints/actions/remove_message_action.d.ts create mode 100644 lib/types/core/endpoints/channel_groups/add_channels.d.ts create mode 100644 lib/types/core/endpoints/channel_groups/delete_group.d.ts create mode 100644 lib/types/core/endpoints/channel_groups/list_channels.d.ts create mode 100644 lib/types/core/endpoints/channel_groups/list_groups.d.ts create mode 100644 lib/types/core/endpoints/channel_groups/remove_channels.d.ts create mode 100644 lib/types/core/endpoints/fetch_messages.d.ts create mode 100644 lib/types/core/endpoints/file_upload/delete_file.d.ts create mode 100644 lib/types/core/endpoints/file_upload/download_file.d.ts create mode 100644 lib/types/core/endpoints/file_upload/generate_upload_url.d.ts create mode 100644 lib/types/core/endpoints/file_upload/get_file_url.d.ts create mode 100644 lib/types/core/endpoints/file_upload/list_files.d.ts create mode 100644 lib/types/core/endpoints/file_upload/publish_file.d.ts create mode 100644 lib/types/core/endpoints/file_upload/send_file.d.ts create mode 100644 lib/types/core/endpoints/file_upload/upload-file.d.ts create mode 100644 lib/types/core/endpoints/history/delete_messages.d.ts create mode 100644 lib/types/core/endpoints/history/get_history.d.ts create mode 100644 lib/types/core/endpoints/history/message_counts.d.ts create mode 100644 lib/types/core/endpoints/objects/channel/get.d.ts create mode 100644 lib/types/core/endpoints/objects/channel/get_all.d.ts create mode 100644 lib/types/core/endpoints/objects/channel/remove.d.ts create mode 100644 lib/types/core/endpoints/objects/channel/set.d.ts create mode 100644 lib/types/core/endpoints/objects/member/get.d.ts create mode 100644 lib/types/core/endpoints/objects/member/set.d.ts create mode 100644 lib/types/core/endpoints/objects/membership/get.d.ts create mode 100644 lib/types/core/endpoints/objects/membership/set.d.ts create mode 100644 lib/types/core/endpoints/objects/uuid/get.d.ts create mode 100644 lib/types/core/endpoints/objects/uuid/get_all.d.ts create mode 100644 lib/types/core/endpoints/objects/uuid/remove.d.ts create mode 100644 lib/types/core/endpoints/objects/uuid/set.d.ts create mode 100644 lib/types/core/endpoints/presence/get_state.d.ts create mode 100644 lib/types/core/endpoints/presence/heartbeat.d.ts create mode 100644 lib/types/core/endpoints/presence/here_now.d.ts create mode 100644 lib/types/core/endpoints/presence/leave.d.ts create mode 100644 lib/types/core/endpoints/presence/set_state.d.ts create mode 100644 lib/types/core/endpoints/presence/where_now.d.ts create mode 100644 lib/types/core/endpoints/publish.d.ts create mode 100644 lib/types/core/endpoints/push/add_push_channels.d.ts create mode 100644 lib/types/core/endpoints/push/list_push_channels.d.ts create mode 100644 lib/types/core/endpoints/push/push.d.ts create mode 100644 lib/types/core/endpoints/push/remove_device.d.ts create mode 100644 lib/types/core/endpoints/push/remove_push_channels.d.ts create mode 100644 lib/types/core/endpoints/signal.d.ts create mode 100644 lib/types/core/endpoints/subscribe.d.ts create mode 100644 lib/types/core/endpoints/subscriptionUtils/handshake.d.ts create mode 100644 lib/types/core/endpoints/subscriptionUtils/receiveMessages.d.ts create mode 100644 lib/types/core/endpoints/time.d.ts create mode 100644 lib/types/core/interfaces/configuration.d.ts create mode 100644 lib/types/core/interfaces/crypto-module.d.ts create mode 100644 lib/types/core/interfaces/cryptography.d.ts create mode 100644 lib/types/core/interfaces/request.d.ts create mode 100644 lib/types/core/interfaces/transport.d.ts create mode 100644 lib/types/core/pubnub-channel-groups.d.ts create mode 100644 lib/types/core/pubnub-common.d.ts create mode 100644 lib/types/core/pubnub-objects.d.ts create mode 100644 lib/types/core/pubnub-push.d.ts create mode 100644 lib/types/core/types/api/access-panager.d.ts create mode 100644 lib/types/core/types/api/app-context.d.ts create mode 100644 lib/types/core/types/api/channel-groups.d.ts create mode 100644 lib/types/core/types/api/file-sharing.d.ts create mode 100644 lib/types/core/types/api/history.d.ts create mode 100644 lib/types/core/types/api/index.d.ts create mode 100644 lib/types/core/types/api/message-action.d.ts create mode 100644 lib/types/core/types/api/presence.d.ts create mode 100644 lib/types/core/types/api/push-notifications.d.ts create mode 100644 lib/types/core/types/api/push.d.ts create mode 100644 lib/types/core/types/api/subscription.d.ts create mode 100644 lib/types/core/types/file.d.ts create mode 100644 lib/types/core/types/transport-request.d.ts create mode 100644 lib/types/core/types/transport-response.d.ts create mode 100644 lib/types/core/utils.d.ts create mode 100644 lib/types/crypto/index.d.ts create mode 100644 lib/types/crypto/modules/NodeCryptoModule/ICryptor.d.ts create mode 100644 lib/types/crypto/modules/NodeCryptoModule/ILegacyCryptor.d.ts create mode 100644 lib/types/crypto/modules/NodeCryptoModule/aesCbcCryptor.d.ts create mode 100644 lib/types/crypto/modules/NodeCryptoModule/legacyCryptor.d.ts create mode 100644 lib/types/crypto/modules/NodeCryptoModule/nodeCryptoModule.d.ts create mode 100644 lib/types/crypto/modules/node.d.ts create mode 100644 lib/types/entities/Channel.d.ts create mode 100644 lib/types/entities/ChannelGroup.d.ts create mode 100644 lib/types/entities/ChannelMetadata.d.ts create mode 100644 lib/types/entities/SubscribeCapable.d.ts create mode 100644 lib/types/entities/Subscription.d.ts create mode 100644 lib/types/entities/SubscriptionSet.d.ts create mode 100644 lib/types/entities/UserMetadata.d.ts create mode 100644 lib/types/entities/commonTypes.d.ts create mode 100644 lib/types/errors/pubnub-api-error.d.ts create mode 100644 lib/types/errors/pubnub-error.d.ts create mode 100644 lib/types/event-engine/core/change.d.ts create mode 100644 lib/types/event-engine/core/dispatcher.d.ts create mode 100644 lib/types/event-engine/core/engine.d.ts create mode 100644 lib/types/event-engine/core/handler.d.ts create mode 100644 lib/types/event-engine/core/index.d.ts create mode 100644 lib/types/event-engine/core/retryPolicy.d.ts create mode 100644 lib/types/event-engine/core/state.d.ts create mode 100644 lib/types/event-engine/core/types.d.ts create mode 100644 lib/types/event-engine/dispatcher.d.ts create mode 100644 lib/types/event-engine/effects.d.ts create mode 100644 lib/types/event-engine/events.d.ts create mode 100644 lib/types/event-engine/index.d.ts create mode 100644 lib/types/event-engine/presence/dispatcher.d.ts create mode 100644 lib/types/event-engine/presence/effects.d.ts create mode 100644 lib/types/event-engine/presence/events.d.ts create mode 100644 lib/types/event-engine/presence/presence.d.ts create mode 100644 lib/types/event-engine/presence/states/heartbeat_cooldown.d.ts create mode 100644 lib/types/event-engine/presence/states/heartbeat_failed.d.ts create mode 100644 lib/types/event-engine/presence/states/heartbeat_inactive.d.ts create mode 100644 lib/types/event-engine/presence/states/heartbeat_reconnecting.d.ts create mode 100644 lib/types/event-engine/presence/states/heartbeat_stopped.d.ts create mode 100644 lib/types/event-engine/presence/states/heartbeating.d.ts create mode 100644 lib/types/event-engine/states/handshake_failed.d.ts create mode 100644 lib/types/event-engine/states/handshake_reconnecting.d.ts create mode 100644 lib/types/event-engine/states/handshake_stopped.d.ts create mode 100644 lib/types/event-engine/states/handshaking.d.ts create mode 100644 lib/types/event-engine/states/receive_failed.d.ts create mode 100644 lib/types/event-engine/states/receive_reconnecting.d.ts create mode 100644 lib/types/event-engine/states/receive_stopped.d.ts create mode 100644 lib/types/event-engine/states/receiving.d.ts create mode 100644 lib/types/event-engine/states/unsubscribed.d.ts create mode 100644 lib/types/file/modules/node.d.ts create mode 100644 lib/types/file/modules/react-native.d.ts create mode 100644 lib/types/models/Cursor.d.ts create mode 100644 lib/types/node/configuration.d.ts create mode 100644 lib/types/node/index.d.ts create mode 100644 lib/types/react_native/configuration.d.ts create mode 100644 lib/types/react_native/index.d.ts create mode 100644 lib/types/transport/middleware.d.ts create mode 100644 lib/types/transport/node-transport.d.ts create mode 100644 lib/types/transport/web-react-native-transport.d.ts rename src/transport/{service-worker/subscription-service-worker-middleware.ts => subscription-worker/subscription-worker-middleware.ts} (54%) rename src/transport/{service-worker/subscription-service-worker.ts => subscription-worker/subscription-worker.ts} (71%) diff --git a/.prettierrc b/.prettierrc index cb71e61f6..2eccbc62e 100644 --- a/.prettierrc +++ b/.prettierrc @@ -1,4 +1,5 @@ { + "parser" : "typescript", "semi": true, "printWidth": 120, "singleQuote": true, diff --git a/dist/web/pubnub.js b/dist/web/pubnub.js index 7ba541855..5ee09af9b 100644 --- a/dist/web/pubnub.js +++ b/dist/web/pubnub.js @@ -423,522 +423,6 @@ var cborExports = cbor.exports; var CborReader = /*@__PURE__*/getDefaultExportFromCjs(cborExports); - /** - * Request processing status categories. - */ - var StatusCategory; - (function (StatusCategory) { - /** - * Call failed when network was unable to complete the call. - */ - StatusCategory["PNNetworkIssuesCategory"] = "PNNetworkIssuesCategory"; - /** - * Network call timed out. - */ - StatusCategory["PNTimeoutCategory"] = "PNTimeoutCategory"; - /** - * Request has been cancelled. - */ - StatusCategory["PNCancelledCategory"] = "PNCancelledCategory"; - /** - * Server responded with bad response. - */ - StatusCategory["PNBadRequestCategory"] = "PNBadRequestCategory"; - /** - * Server responded with access denied. - */ - StatusCategory["PNAccessDeniedCategory"] = "PNAccessDeniedCategory"; - /** - * Incomplete parameters provided for used endpoint. - */ - StatusCategory["PNValidationErrorCategory"] = "PNValidationErrorCategory"; - /** - * PubNub request acknowledgment status. - * - * Some API endpoints respond with request processing status w/o useful data. - */ - StatusCategory["PNAcknowledgmentCategory"] = "PNAcknowledgmentCategory"; - /** - * Something strange happened; please check the logs. - */ - StatusCategory["PNUnknownCategory"] = "PNUnknownCategory"; - // -------------------------------------------------------- - // --------------------- Network status ------------------- - // -------------------------------------------------------- - /** - * SDK will announce when the network appears to be connected again. - */ - StatusCategory["PNNetworkUpCategory"] = "PNNetworkUpCategory"; - /** - * SDK will announce when the network appears to down. - */ - StatusCategory["PNNetworkDownCategory"] = "PNNetworkDownCategory"; - // -------------------------------------------------------- - // -------------------- Real-time events ------------------ - // -------------------------------------------------------- - /** - * PubNub client reconnected to the real-time updates stream. - */ - StatusCategory["PNReconnectedCategory"] = "PNReconnectedCategory"; - /** - * PubNub client connected to the real-time updates stream. - */ - StatusCategory["PNConnectedCategory"] = "PNConnectedCategory"; - /** - * Received real-time updates exceed specified threshold. - * - * After temporary disconnection and catchup, this category means that potentially some - * real-time updates have been pushed into `storage` and need to be requested separately. - */ - StatusCategory["PNRequestMessageCountExceededCategory"] = "PNRequestMessageCountExceededCategory"; - /** - * PubNub client disconnected from the real-time updates streams. - */ - StatusCategory["PNDisconnectedCategory"] = "PNDisconnectedCategory"; - /** - * PubNub client wasn't able to connect to the real-time updates streams. - */ - StatusCategory["PNConnectionErrorCategory"] = "PNConnectionErrorCategory"; - /** - * PubNub client unexpectedly disconnected from the real-time updates streams. - */ - StatusCategory["PNDisconnectedUnexpectedlyCategory"] = "PNDisconnectedUnexpectedlyCategory"; - })(StatusCategory || (StatusCategory = {})); - var StatusCategory$1 = StatusCategory; - - class PubNubError extends Error { - constructor(message, status) { - super(message); - this.status = status; - this.name = 'PubNubError'; - this.message = message; - Object.setPrototypeOf(this, new.target.prototype); - } - } - function createError(errorPayload) { - var _a; - (_a = errorPayload.statusCode) !== null && _a !== void 0 ? _a : (errorPayload.statusCode = 0); - return Object.assign(Object.assign({}, errorPayload), { statusCode: errorPayload.statusCode, category: StatusCategory$1.PNValidationErrorCategory, error: true }); - } - function createValidationError(message, statusCode) { - return createError(Object.assign({ message }, (statusCode !== undefined ? { statusCode } : {}))); - } - - /** - * REST API endpoint use error module. - */ - /** - * PubNub REST API call error. - */ - class PubNubAPIError extends Error { - /** - * Construct API from known error object or {@link PubNub} service error response. - * - * @param errorOrResponse - `Error` or service error response object from which error information - * should be extracted. - * @param data - Preprocessed service error response. - * - * @returns `PubNubAPIError` object with known error category and additional information (if - * available). - */ - static create(errorOrResponse, data) { - if (errorOrResponse instanceof Error) - return PubNubAPIError.createFromError(errorOrResponse); - else - return PubNubAPIError.createFromServiceResponse(errorOrResponse, data); - } - /** - * Create API error instance from other error object. - * - * @param error - `Error` object provided by network provider (mostly) or other {@link PubNub} client components. - * - * @returns `PubNubAPIError` object with known error category and additional information (if - * available). - */ - static createFromError(error) { - let category = StatusCategory$1.PNUnknownCategory; - let message = 'Unknown error'; - let errorName = 'Error'; - if (!error) - return new PubNubAPIError(message, category, 0); - else if (error instanceof PubNubAPIError) - return error; - if (error instanceof Error) { - message = error.message; - errorName = error.name; - } - if (errorName === 'AbortError' || message.indexOf('Aborted') !== -1) { - category = StatusCategory$1.PNCancelledCategory; - message = 'Request cancelled'; - } - else if (message.indexOf('timeout') !== -1) { - category = StatusCategory$1.PNTimeoutCategory; - message = 'Request timeout'; - } - else if (message.indexOf('network') !== -1) { - category = StatusCategory$1.PNNetworkIssuesCategory; - message = 'Network issues'; - } - else if (errorName === 'TypeError') { - category = StatusCategory$1.PNBadRequestCategory; - } - else if (errorName === 'FetchError') { - const errorCode = error.code; - if (['ECONNREFUSED', 'ENETUNREACH', 'ENOTFOUND', 'ECONNRESET', 'EAI_AGAIN'].includes(errorCode)) - category = StatusCategory$1.PNNetworkIssuesCategory; - if (errorCode === 'ECONNREFUSED') - message = 'Connection refused'; - else if (errorCode === 'ENETUNREACH') - message = 'Network not reachable'; - else if (errorCode === 'ENOTFOUND') - message = 'Server not found'; - else if (errorCode === 'ECONNRESET') - message = 'Connection reset by peer'; - else if (errorCode === 'EAI_AGAIN') - message = 'Name resolution error'; - else if (errorCode === 'ETIMEDOUT') { - category = StatusCategory$1.PNTimeoutCategory; - message = 'Request timeout'; - } - else - message = `Unknown system error: ${error}`; - } - else if (message === 'Request timeout') - category = StatusCategory$1.PNTimeoutCategory; - return new PubNubAPIError(message, category, 0, error); - } - /** - * Construct API from known {@link PubNub} service error response. - * - * @param response - Service error response object from which error information should be - * extracted. - * @param data - Preprocessed service error response. - * - * @returns `PubNubAPIError` object with known error category and additional information (if - * available). - */ - static createFromServiceResponse(response, data) { - let category = StatusCategory$1.PNUnknownCategory; - let errorData; - let message = 'Unknown error'; - let { status } = response; - data !== null && data !== void 0 ? data : (data = response.body); - if (status === 402) - message = 'Not available for used key set. Contact support@pubnub.com'; - else if (status === 400) { - category = StatusCategory$1.PNBadRequestCategory; - message = 'Bad request'; - } - else if (status === 403) { - category = StatusCategory$1.PNAccessDeniedCategory; - message = 'Access denied'; - } - // Try to get more information about error from service response. - if (data && data.byteLength > 0) { - const decoded = new TextDecoder().decode(data); - if (response.headers['content-type'].indexOf('text/javascript') !== -1 || - response.headers['content-type'].indexOf('application/json') !== -1) { - try { - const errorResponse = JSON.parse(decoded); - if (typeof errorResponse === 'object' && !Array.isArray(errorResponse)) { - if ('error' in errorResponse && - (errorResponse.error === 1 || errorResponse.error === true) && - 'status' in errorResponse && - typeof errorResponse.status === 'number' && - 'message' in errorResponse && - 'service' in errorResponse) { - errorData = errorResponse; - status = errorResponse.status; - } - else - errorData = errorResponse; - if ('error' in errorResponse && errorResponse.error instanceof Error) - errorData = errorResponse.error; - } - } - catch (_) { - errorData = decoded; - } - } - else if (response.headers['content-type'].indexOf('xml') !== -1) { - const reason = /(.*)<\/Message>/gi.exec(decoded); - message = reason ? `Upload to bucket failed: ${reason[1]}` : 'Upload to bucket failed.'; - } - else { - errorData = decoded; - } - } - return new PubNubAPIError(message, category, status, errorData); - } - /** - * Construct PubNub endpoint error. - * - * @param message - Short API call error description. - * @param category - Error category. - * @param statusCode - Response HTTP status code. - * @param errorData - Error information. - */ - constructor(message, category, statusCode, errorData) { - super(message); - this.category = category; - this.statusCode = statusCode; - this.errorData = errorData; - this.name = 'PubNubAPIError'; - } - /** - * Convert API error object to API callback status object. - * - * @param operation - Request operation during which error happened. - * - * @returns Pre-formatted API callback status object. - */ - toStatus(operation) { - return { - error: true, - category: this.category, - operation, - statusCode: this.statusCode, - errorData: this.errorData, - }; - } - /** - * Convert API error object to PubNub client error object. - * - * @param operation - Request operation during which error happened. - * @param message - Custom error message. - * - * @returns Client-facing pre-formatted endpoint call error. - */ - toPubNubError(operation, message) { - return new PubNubError(message !== null && message !== void 0 ? message : this.message, this.toStatus(operation)); - } - } - - /** - * Subscription Service Worker transport middleware module. - * - * Middleware optimize subscription feature requests utilizing `Subscription Service Worker` if available and not - * disabled by user. - */ - // endregion - /** - * Subscription Service Worker transport middleware. - */ - class SubscriptionServiceWorkerMiddleware { - constructor(configuration) { - this.configuration = configuration; - this.serviceWorkerEventsQueue = []; - this.callbacks = new Map(); - this.setupServiceWorker(); - } - makeSendable(req) { - // Use default request flow for non-subscribe / presence leave requests. - if (!req.path.startsWith('/v2/subscribe') && !req.path.endsWith('/leave')) - return this.configuration.transport.makeSendable(req); - let controller; - const sendRequestEvent = { - type: 'send-request', - clientIdentifier: this.configuration.clientIdentifier, - subscriptionKey: this.configuration.subscriptionKey, - logVerbosity: this.configuration.logVerbosity, - request: req, - }; - if (req.cancellable) { - controller = { - abort: () => { - const cancelRequest = { - type: 'cancel-request', - clientIdentifier: this.configuration.clientIdentifier, - subscriptionKey: this.configuration.subscriptionKey, - logVerbosity: this.configuration.logVerbosity, - identifier: req.identifier, - }; - // Cancel active request with specified identifier. - this.scheduleEventPost(cancelRequest); - }, - }; - } - return [ - new Promise((resolve, reject) => { - // Associate Promise resolution / reject with request identifier for future usage in - // `onmessage` handler block to return results. - this.callbacks.set(req.identifier, { resolve, reject }); - // Trigger request processing by Service Worker. - this.scheduleEventPost(sendRequestEvent); - }), - controller, - ]; - } - request(req) { - return req; - } - /** - * Schedule {@link event} publish to the service worker. - * - * Service worker may not be ready for events processing and this method build queue for the time when worker will be - * ready. - * - * @param event - Event payload for service worker. - * @param outOfOrder - Whether event should be processed first then enqueued queue. - */ - scheduleEventPost(event, outOfOrder = false) { - // Trigger request processing by Web Worker. - const serviceWorker = this.serviceWorker; - if (serviceWorker) - serviceWorker.postMessage(event); - else { - if (outOfOrder) - this.serviceWorkerEventsQueue.splice(0, 0, event); - else - this.serviceWorkerEventsQueue.push(event); - } - } - /** - * Dequeue and post events from the queue to the service worker. - */ - flushScheduledEvents() { - // Trigger request processing by Web Worker. - const serviceWorker = this.serviceWorker; - if (!serviceWorker || this.serviceWorkerEventsQueue.length === 0) - return; - // Clean up from cancelled events. - const outdatedEvents = []; - for (let i = 0; i < this.serviceWorkerEventsQueue.length; i++) { - const event = this.serviceWorkerEventsQueue[i]; - // Check whether found request cancel event to search for request send event it cancels. - if (event.type !== 'cancel-request' || i === 0) - continue; - for (let j = 0; j < i; j++) { - const otherEvent = this.serviceWorkerEventsQueue[j]; - if (otherEvent.type !== 'send-request') - continue; - // Collect outdated events if identifiers match. - if (otherEvent.request.identifier === event.identifier) { - outdatedEvents.push(event, otherEvent); - break; - } - } - } - // Actualizing events queue. - this.serviceWorkerEventsQueue = this.serviceWorkerEventsQueue.filter((event) => !outdatedEvents.includes(event)); - this.serviceWorkerEventsQueue.forEach((event) => serviceWorker.postMessage(event)); - this.serviceWorkerEventsQueue = []; - } - /** - * Subscription service worker. - * - * @returns Service worker which has been registered by the PubNub SDK. - */ - get serviceWorker() { - return this.serviceWorkerRegistration ? this.serviceWorkerRegistration.active : null; - } - setupServiceWorker() { - if (!('serviceWorker' in navigator)) - return; - const serviceWorkerContainer = navigator.serviceWorker; - serviceWorkerContainer - .register(this.configuration.serviceWorkerUrl, { - scope: `/pubnub-${this.configuration.sdkVersion}`, - }) - .then((registration) => { - this.serviceWorkerRegistration = registration; - // Flush any pending service worker events. - if (registration.active) - this.flushScheduledEvents(); - /** - * Listening for service worker code update. - * - * It is possible that one of the tabs will open with newer SDK version and Subscription Service Worker - * will be re-installed - in this case we need to "rehydrate" it. - * - * After re-installation of new service worker it will lose all accumulated state and client need to - * re-introduce itself and its state. - */ - this.serviceWorkerRegistration.addEventListener('updatefound', () => { - if (!this.serviceWorkerRegistration) - return; - // New service installing right now. - const serviceWorker = this.serviceWorkerRegistration.installing; - const stateChangeListener = () => { - // Flush any pending service worker events. - if (serviceWorker.state === 'activated') { - // Flush any pending service worker events. - this.flushScheduledEvents(); - } - else if (serviceWorker.state === 'redundant') { - // Clean up listener from deprecated service worker version. - serviceWorker.removeEventListener('statechange', stateChangeListener); - } - }; - serviceWorker.addEventListener('statechange', stateChangeListener); - }); - }); - serviceWorkerContainer.addEventListener('message', (event) => this.handleServiceWorkerEvent(event)); - } - handleServiceWorkerEvent(event) { - const { data } = event; - // Ignoring updates not related to this instance. - if (data.clientIdentifier !== this.configuration.clientIdentifier) - return; - if (data.type === 'request-progress-start' || data.type === 'request-progress-end') { - this.logRequestProgress(data); - } - else if (data.type === 'request-process-success' || data.type === 'request-process-error') { - const { resolve, reject } = this.callbacks.get(data.identifier); - if (data.type === 'request-process-success') { - resolve({ - status: data.response.status, - url: data.url, - headers: data.response.headers, - body: data.response.body, - }); - } - else { - let category = StatusCategory$1.PNUnknownCategory; - let message = 'Unknown error'; - // Handle client-side issues (if any). - if (data.error) { - if (data.error.type === 'NETWORK_ISSUE') - category = StatusCategory$1.PNNetworkIssuesCategory; - else if (data.error.type === 'TIMEOUT') - category = StatusCategory$1.PNTimeoutCategory; - else if (data.error.type === 'ABORTED') - category = StatusCategory$1.PNCancelledCategory; - message = `${data.error.message} (${data.identifier})`; - } - // Handle service error response. - else if (data.response) { - return reject(PubNubAPIError.create({ - url: data.url, - headers: data.response.headers, - body: data.response.body, - status: data.response.status, - }, data.response.body)); - } - reject(new PubNubAPIError(message, category, 0, new Error(message))); - } - } - } - /** - * Print request progress information. - * - * @param information - Request progress information from Web Worker. - */ - logRequestProgress(information) { - var _a, _b; - if (information.type === 'request-progress-start') { - console.log('<<<<<'); - console.log(`[${information.timestamp}] ${information.url}\n${JSON.stringify((_a = information.query) !== null && _a !== void 0 ? _a : {})}`); - console.log('-----'); - } - else { - console.log('>>>>>>'); - console.log(`[${information.timestamp} / ${information.duration}] ${information.url}\n${JSON.stringify((_b = information.query) !== null && _b !== void 0 ? _b : {})}\n${information.response}`); - console.log('-----'); - } - } - } - /****************************************************************************** Copyright (c) Microsoft Corporation. @@ -1217,6 +701,8 @@ * * @param paddedInput Base64 string with padding * @returns ArrayBuffer with decoded data + * + * @internal */ function decode(paddedInput) { // Remove up to last two equal signs. @@ -1255,46 +741,155 @@ if (sx4 != 64) view[i + 2] = oc3; } - return data; + return data; + } + /** + * Encode `ArrayBuffer` as a Base64 encoded string. + * + * @param input ArrayBuffer with source data. + * @returns Base64 string with padding. + * + * @internal + */ + function encode(input) { + let base64 = ''; + const encodings = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'; + const bytes = new Uint8Array(input); + const byteLength = bytes.byteLength; + const byteRemainder = byteLength % 3; + const mainLength = byteLength - byteRemainder; + let a, b, c, d; + let chunk; + // Main loop deals with bytes in chunks of 3 + for (let i = 0; i < mainLength; i = i + 3) { + // Combine the three bytes into a single integer + chunk = (bytes[i] << 16) | (bytes[i + 1] << 8) | bytes[i + 2]; + // Use bitmasks to extract 6-bit segments from the triplet + a = (chunk & 16515072) >> 18; // 16515072 = (2^6 - 1) << 18 + b = (chunk & 258048) >> 12; // 258048 = (2^6 - 1) << 12 + c = (chunk & 4032) >> 6; // 4032 = (2^6 - 1) << 6 + d = chunk & 63; // 63 = 2^6 - 1 + // Convert the raw binary segments to the appropriate ASCII encoding + base64 += encodings[a] + encodings[b] + encodings[c] + encodings[d]; + } + // Deal with the remaining bytes and padding + if (byteRemainder == 1) { + chunk = bytes[mainLength]; + a = (chunk & 252) >> 2; // 252 = (2^6 - 1) << 2 + // Set the 4 least significant bits to zero + b = (chunk & 3) << 4; // 3 = 2^2 - 1 + base64 += encodings[a] + encodings[b] + '=='; + } + else if (byteRemainder == 2) { + chunk = (bytes[mainLength] << 8) | bytes[mainLength + 1]; + a = (chunk & 64512) >> 10; // 64512 = (2^6 - 1) << 10 + b = (chunk & 1008) >> 4; // 1008 = (2^6 - 1) << 4 + // Set the 2 least significant bits to zero + c = (chunk & 15) << 2; // 15 = 2^4 - 1 + base64 += encodings[a] + encodings[b] + encodings[c] + '='; + } + return base64; + } + + /** + * Request processing status categories. + */ + var StatusCategory; + (function (StatusCategory) { + /** + * Call failed when network was unable to complete the call. + */ + StatusCategory["PNNetworkIssuesCategory"] = "PNNetworkIssuesCategory"; + /** + * Network call timed out. + */ + StatusCategory["PNTimeoutCategory"] = "PNTimeoutCategory"; + /** + * Request has been cancelled. + */ + StatusCategory["PNCancelledCategory"] = "PNCancelledCategory"; + /** + * Server responded with bad response. + */ + StatusCategory["PNBadRequestCategory"] = "PNBadRequestCategory"; + /** + * Server responded with access denied. + */ + StatusCategory["PNAccessDeniedCategory"] = "PNAccessDeniedCategory"; + /** + * Incomplete parameters provided for used endpoint. + */ + StatusCategory["PNValidationErrorCategory"] = "PNValidationErrorCategory"; + /** + * PubNub request acknowledgment status. + * + * Some API endpoints respond with request processing status w/o useful data. + */ + StatusCategory["PNAcknowledgmentCategory"] = "PNAcknowledgmentCategory"; + /** + * Something strange happened; please check the logs. + */ + StatusCategory["PNUnknownCategory"] = "PNUnknownCategory"; + // -------------------------------------------------------- + // --------------------- Network status ------------------- + // -------------------------------------------------------- + /** + * SDK will announce when the network appears to be connected again. + */ + StatusCategory["PNNetworkUpCategory"] = "PNNetworkUpCategory"; + /** + * SDK will announce when the network appears to down. + */ + StatusCategory["PNNetworkDownCategory"] = "PNNetworkDownCategory"; + // -------------------------------------------------------- + // -------------------- Real-time events ------------------ + // -------------------------------------------------------- + /** + * PubNub client reconnected to the real-time updates stream. + */ + StatusCategory["PNReconnectedCategory"] = "PNReconnectedCategory"; + /** + * PubNub client connected to the real-time updates stream. + */ + StatusCategory["PNConnectedCategory"] = "PNConnectedCategory"; + /** + * Received real-time updates exceed specified threshold. + * + * After temporary disconnection and catchup, this category means that potentially some + * real-time updates have been pushed into `storage` and need to be requested separately. + */ + StatusCategory["PNRequestMessageCountExceededCategory"] = "PNRequestMessageCountExceededCategory"; + /** + * PubNub client disconnected from the real-time updates streams. + */ + StatusCategory["PNDisconnectedCategory"] = "PNDisconnectedCategory"; + /** + * PubNub client wasn't able to connect to the real-time updates streams. + */ + StatusCategory["PNConnectionErrorCategory"] = "PNConnectionErrorCategory"; + /** + * PubNub client unexpectedly disconnected from the real-time updates streams. + */ + StatusCategory["PNDisconnectedUnexpectedlyCategory"] = "PNDisconnectedUnexpectedlyCategory"; + })(StatusCategory || (StatusCategory = {})); + var StatusCategory$1 = StatusCategory; + + class PubNubError extends Error { + constructor(message, status) { + super(message); + this.status = status; + this.name = 'PubNubError'; + this.message = message; + Object.setPrototypeOf(this, new.target.prototype); + } } - function encode(input) { - let base64 = ''; - const encodings = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'; - const bytes = new Uint8Array(input); - const byteLength = bytes.byteLength; - const byteRemainder = byteLength % 3; - const mainLength = byteLength - byteRemainder; - let a, b, c, d; - let chunk; - // Main loop deals with bytes in chunks of 3 - for (let i = 0; i < mainLength; i = i + 3) { - // Combine the three bytes into a single integer - chunk = (bytes[i] << 16) | (bytes[i + 1] << 8) | bytes[i + 2]; - // Use bitmasks to extract 6-bit segments from the triplet - a = (chunk & 16515072) >> 18; // 16515072 = (2^6 - 1) << 18 - b = (chunk & 258048) >> 12; // 258048 = (2^6 - 1) << 12 - c = (chunk & 4032) >> 6; // 4032 = (2^6 - 1) << 6 - d = chunk & 63; // 63 = 2^6 - 1 - // Convert the raw binary segments to the appropriate ASCII encoding - base64 += encodings[a] + encodings[b] + encodings[c] + encodings[d]; - } - // Deal with the remaining bytes and padding - if (byteRemainder == 1) { - chunk = bytes[mainLength]; - a = (chunk & 252) >> 2; // 252 = (2^6 - 1) << 2 - // Set the 4 least significant bits to zero - b = (chunk & 3) << 4; // 3 = 2^2 - 1 - base64 += encodings[a] + encodings[b] + '=='; - } - else if (byteRemainder == 2) { - chunk = (bytes[mainLength] << 8) | bytes[mainLength + 1]; - a = (chunk & 64512) >> 10; // 64512 = (2^6 - 1) << 10 - b = (chunk & 1008) >> 4; // 1008 = (2^6 - 1) << 4 - // Set the 2 least significant bits to zero - c = (chunk & 15) << 2; // 15 = 2^4 - 1 - base64 += encodings[a] + encodings[b] + encodings[c] + '='; - } - return base64; + function createError(errorPayload) { + var _a; + (_a = errorPayload.statusCode) !== null && _a !== void 0 ? _a : (errorPayload.statusCode = 0); + return Object.assign(Object.assign({}, errorPayload), { statusCode: errorPayload.statusCode, category: StatusCategory$1.PNValidationErrorCategory, error: true }); + } + function createValidationError(message, statusCode) { + return createError(Object.assign({ message }, (statusCode !== undefined ? { statusCode } : {}))); } /*eslint-disable */ @@ -3020,173 +2615,590 @@ throw Error('Unknown cryptor error'); } /** - * Retrieve cryptor by its identifier. + * Retrieve cryptor by its identifier. + * + * @param header - Header with cryptor-defined data or raw cryptor identifier. + * + * @returns Cryptor which correspond to provided {@link header}. + */ + getCryptor(header) { + if (typeof header === 'string') { + const cryptor = this.getAllCryptors().find((cryptor) => cryptor.identifier === header); + if (cryptor) + return cryptor; + throw new Error('Unknown cryptor error'); + } + else if (header instanceof CryptorHeaderV1) { + return this.getCryptorFromId(header.identifier); + } + } + /** + * Create cryptor header data. + * + * @param encrypted - Encryption data object as source for header data. + * + * @returns Binary representation of the cryptor header data. + */ + getHeaderData(encrypted) { + if (!encrypted.metadata) + return; + const header = CryptorHeader.from(this.defaultCryptor.identifier, encrypted.metadata); + const headerData = new Uint8Array(header.length); + let pos = 0; + headerData.set(header.data, pos); + pos += header.length - encrypted.metadata.byteLength; + headerData.set(new Uint8Array(encrypted.metadata), pos); + return headerData.buffer; + } + /** + * Merge two {@link ArrayBuffer} instances. + * + * @param ab1 - First {@link ArrayBuffer}. + * @param ab2 - Second {@link ArrayBuffer}. + * + * @returns Merged data as {@link ArrayBuffer}. + */ + concatArrayBuffer(ab1, ab2) { + const tmp = new Uint8Array(ab1.byteLength + ab2.byteLength); + tmp.set(new Uint8Array(ab1), 0); + tmp.set(new Uint8Array(ab2), ab1.byteLength); + return tmp.buffer; + } + /** + * Retrieve file content. + * + * @param file - Content of the {@link PubNub} File object. + * + * @returns Normalized file {@link data} as {@link ArrayBuffer}; + */ + getFileData(file) { + return __awaiter(this, void 0, void 0, function* () { + if (file instanceof ArrayBuffer) + return file; + else if (file instanceof PubNubFile) + return file.toArrayBuffer(); + throw new Error('Cannot decrypt/encrypt file. In browsers file encrypt/decrypt supported for string, ArrayBuffer or Blob'); + }); + } + } + /** + * {@link LegacyCryptor|Legacy} cryptor identifier. + */ + WebCryptoModule.LEGACY_IDENTIFIER = ''; + /** + * CryptorHeader Utility + */ + class CryptorHeader { + static from(id, metadata) { + if (id === CryptorHeader.LEGACY_IDENTIFIER) + return; + return new CryptorHeaderV1(id, metadata.byteLength); + } + static tryParse(data) { + const encryptedData = new Uint8Array(data); + let sentinel; + let version = null; + if (encryptedData.byteLength >= 4) { + sentinel = encryptedData.slice(0, 4); + if (this.decoder.decode(sentinel) !== CryptorHeader.SENTINEL) + return WebCryptoModule.LEGACY_IDENTIFIER; + } + if (encryptedData.byteLength >= 5) + version = encryptedData[4]; + else + throw new Error('Decryption error: invalid header version'); + if (version > CryptorHeader.MAX_VERSION) + throw new Error('Decryption error: Unknown cryptor error'); + let identifier; + let pos = 5 + CryptorHeader.IDENTIFIER_LENGTH; + if (encryptedData.byteLength >= pos) + identifier = encryptedData.slice(5, pos); + else + throw new Error('Decryption error: invalid crypto identifier'); + let metadataLength = null; + if (encryptedData.byteLength >= pos + 1) + metadataLength = encryptedData[pos]; + else + throw new Error('Decryption error: invalid metadata length'); + pos += 1; + if (metadataLength === 255 && encryptedData.byteLength >= pos + 2) { + metadataLength = new Uint16Array(encryptedData.slice(pos, pos + 2)).reduce((acc, val) => (acc << 8) + val, 0); + } + return new CryptorHeaderV1(this.decoder.decode(identifier), metadataLength); + } + } + CryptorHeader.SENTINEL = 'PNED'; + CryptorHeader.LEGACY_IDENTIFIER = ''; + CryptorHeader.IDENTIFIER_LENGTH = 4; + CryptorHeader.VERSION = 1; + CryptorHeader.MAX_VERSION = 1; + CryptorHeader.decoder = new TextDecoder(); + // v1 CryptorHeader + class CryptorHeaderV1 { + constructor(id, metadataLength) { + this._identifier = id; + this._metadataLength = metadataLength; + } + get identifier() { + return this._identifier; + } + set identifier(value) { + this._identifier = value; + } + get metadataLength() { + return this._metadataLength; + } + set metadataLength(value) { + this._metadataLength = value; + } + get version() { + return CryptorHeader.VERSION; + } + get length() { + return (CryptorHeader.SENTINEL.length + + 1 + + CryptorHeader.IDENTIFIER_LENGTH + + (this.metadataLength < 255 ? 1 : 3) + + this.metadataLength); + } + get data() { + let pos = 0; + const header = new Uint8Array(this.length); + const encoder = new TextEncoder(); + header.set(encoder.encode(CryptorHeader.SENTINEL)); + pos += CryptorHeader.SENTINEL.length; + header[pos] = this.version; + pos++; + if (this.identifier) + header.set(encoder.encode(this.identifier), pos); + const metadataLength = this.metadataLength; + pos += CryptorHeader.IDENTIFIER_LENGTH; + if (metadataLength < 255) + header[pos] = metadataLength; + else + header.set([255, metadataLength >> 8, metadataLength & 0xff], pos); + return header; + } + } + CryptorHeaderV1.IDENTIFIER_LENGTH = 4; + CryptorHeaderV1.SENTINEL = 'PNED'; + + /** + * REST API endpoint use error module. + */ + /** + * PubNub REST API call error. + */ + class PubNubAPIError extends Error { + /** + * Construct API from known error object or {@link PubNub} service error response. + * + * @param errorOrResponse - `Error` or service error response object from which error information + * should be extracted. + * @param data - Preprocessed service error response. + * + * @returns `PubNubAPIError` object with known error category and additional information (if + * available). + */ + static create(errorOrResponse, data) { + if (errorOrResponse instanceof Error) + return PubNubAPIError.createFromError(errorOrResponse); + else + return PubNubAPIError.createFromServiceResponse(errorOrResponse, data); + } + /** + * Create API error instance from other error object. + * + * @param error - `Error` object provided by network provider (mostly) or other {@link PubNub} client components. + * + * @returns `PubNubAPIError` object with known error category and additional information (if + * available). + */ + static createFromError(error) { + let category = StatusCategory$1.PNUnknownCategory; + let message = 'Unknown error'; + let errorName = 'Error'; + if (!error) + return new PubNubAPIError(message, category, 0); + else if (error instanceof PubNubAPIError) + return error; + if (error instanceof Error) { + message = error.message; + errorName = error.name; + } + if (errorName === 'AbortError' || message.indexOf('Aborted') !== -1) { + category = StatusCategory$1.PNCancelledCategory; + message = 'Request cancelled'; + } + else if (message.indexOf('timeout') !== -1) { + category = StatusCategory$1.PNTimeoutCategory; + message = 'Request timeout'; + } + else if (message.indexOf('network') !== -1) { + category = StatusCategory$1.PNNetworkIssuesCategory; + message = 'Network issues'; + } + else if (errorName === 'TypeError') { + category = StatusCategory$1.PNBadRequestCategory; + } + else if (errorName === 'FetchError') { + const errorCode = error.code; + if (['ECONNREFUSED', 'ENETUNREACH', 'ENOTFOUND', 'ECONNRESET', 'EAI_AGAIN'].includes(errorCode)) + category = StatusCategory$1.PNNetworkIssuesCategory; + if (errorCode === 'ECONNREFUSED') + message = 'Connection refused'; + else if (errorCode === 'ENETUNREACH') + message = 'Network not reachable'; + else if (errorCode === 'ENOTFOUND') + message = 'Server not found'; + else if (errorCode === 'ECONNRESET') + message = 'Connection reset by peer'; + else if (errorCode === 'EAI_AGAIN') + message = 'Name resolution error'; + else if (errorCode === 'ETIMEDOUT') { + category = StatusCategory$1.PNTimeoutCategory; + message = 'Request timeout'; + } + else + message = `Unknown system error: ${error}`; + } + else if (message === 'Request timeout') + category = StatusCategory$1.PNTimeoutCategory; + return new PubNubAPIError(message, category, 0, error); + } + /** + * Construct API from known {@link PubNub} service error response. * - * @param header - Header with cryptor-defined data or raw cryptor identifier. + * @param response - Service error response object from which error information should be + * extracted. + * @param data - Preprocessed service error response. * - * @returns Cryptor which correspond to provided {@link header}. + * @returns `PubNubAPIError` object with known error category and additional information (if + * available). */ - getCryptor(header) { - if (typeof header === 'string') { - const cryptor = this.getAllCryptors().find((cryptor) => cryptor.identifier === header); - if (cryptor) - return cryptor; - throw new Error('Unknown cryptor error'); + static createFromServiceResponse(response, data) { + let category = StatusCategory$1.PNUnknownCategory; + let errorData; + let message = 'Unknown error'; + let { status } = response; + data !== null && data !== void 0 ? data : (data = response.body); + if (status === 402) + message = 'Not available for used key set. Contact support@pubnub.com'; + else if (status === 400) { + category = StatusCategory$1.PNBadRequestCategory; + message = 'Bad request'; } - else if (header instanceof CryptorHeaderV1) { - return this.getCryptorFromId(header.identifier); + else if (status === 403) { + category = StatusCategory$1.PNAccessDeniedCategory; + message = 'Access denied'; + } + // Try to get more information about error from service response. + if (data && data.byteLength > 0) { + const decoded = new TextDecoder().decode(data); + if (response.headers['content-type'].indexOf('text/javascript') !== -1 || + response.headers['content-type'].indexOf('application/json') !== -1) { + try { + const errorResponse = JSON.parse(decoded); + if (typeof errorResponse === 'object' && !Array.isArray(errorResponse)) { + if ('error' in errorResponse && + (errorResponse.error === 1 || errorResponse.error === true) && + 'status' in errorResponse && + typeof errorResponse.status === 'number' && + 'message' in errorResponse && + 'service' in errorResponse) { + errorData = errorResponse; + status = errorResponse.status; + } + else + errorData = errorResponse; + if ('error' in errorResponse && errorResponse.error instanceof Error) + errorData = errorResponse.error; + } + } + catch (_) { + errorData = decoded; + } + } + else if (response.headers['content-type'].indexOf('xml') !== -1) { + const reason = /(.*)<\/Message>/gi.exec(decoded); + message = reason ? `Upload to bucket failed: ${reason[1]}` : 'Upload to bucket failed.'; + } + else { + errorData = decoded; + } } + return new PubNubAPIError(message, category, status, errorData); } /** - * Create cryptor header data. - * - * @param encrypted - Encryption data object as source for header data. + * Construct PubNub endpoint error. * - * @returns Binary representation of the cryptor header data. + * @param message - Short API call error description. + * @param category - Error category. + * @param statusCode - Response HTTP status code. + * @param errorData - Error information. */ - getHeaderData(encrypted) { - if (!encrypted.metadata) - return; - const header = CryptorHeader.from(this.defaultCryptor.identifier, encrypted.metadata); - const headerData = new Uint8Array(header.length); - let pos = 0; - headerData.set(header.data, pos); - pos += header.length - encrypted.metadata.byteLength; - headerData.set(new Uint8Array(encrypted.metadata), pos); - return headerData.buffer; + constructor(message, category, statusCode, errorData) { + super(message); + this.category = category; + this.statusCode = statusCode; + this.errorData = errorData; + this.name = 'PubNubAPIError'; } /** - * Merge two {@link ArrayBuffer} instances. + * Convert API error object to API callback status object. * - * @param ab1 - First {@link ArrayBuffer}. - * @param ab2 - Second {@link ArrayBuffer}. + * @param operation - Request operation during which error happened. * - * @returns Merged data as {@link ArrayBuffer}. + * @returns Pre-formatted API callback status object. */ - concatArrayBuffer(ab1, ab2) { - const tmp = new Uint8Array(ab1.byteLength + ab2.byteLength); - tmp.set(new Uint8Array(ab1), 0); - tmp.set(new Uint8Array(ab2), ab1.byteLength); - return tmp.buffer; + toStatus(operation) { + return { + error: true, + category: this.category, + operation, + statusCode: this.statusCode, + errorData: this.errorData, + }; } /** - * Retrieve file content. + * Convert API error object to PubNub client error object. * - * @param file - Content of the {@link PubNub} File object. + * @param operation - Request operation during which error happened. + * @param message - Custom error message. * - * @returns Normalized file {@link data} as {@link ArrayBuffer}; + * @returns Client-facing pre-formatted endpoint call error. */ - getFileData(file) { - return __awaiter(this, void 0, void 0, function* () { - if (file instanceof ArrayBuffer) - return file; - else if (file instanceof PubNubFile) - return file.toArrayBuffer(); - throw new Error('Cannot decrypt/encrypt file. In browsers file encrypt/decrypt supported for string, ArrayBuffer or Blob'); - }); + toPubNubError(operation, message) { + return new PubNubError(message !== null && message !== void 0 ? message : this.message, this.toStatus(operation)); } } + /** - * {@link LegacyCryptor|Legacy} cryptor identifier. + * Subscription Worker transport middleware module. + * + * Middleware optimize subscription feature requests utilizing `Subscription Worker` if available and not disabled + * by user. */ - WebCryptoModule.LEGACY_IDENTIFIER = ''; + // endregion /** - * CryptorHeader Utility + * Subscription Worker transport middleware. */ - class CryptorHeader { - static from(id, metadata) { - if (id === CryptorHeader.LEGACY_IDENTIFIER) - return; - return new CryptorHeaderV1(id, metadata.byteLength); - } - static tryParse(data) { - const encryptedData = new Uint8Array(data); - let sentinel; - let version = null; - if (encryptedData.byteLength >= 4) { - sentinel = encryptedData.slice(0, 4); - if (this.decoder.decode(sentinel) !== CryptorHeader.SENTINEL) - return WebCryptoModule.LEGACY_IDENTIFIER; - } - if (encryptedData.byteLength >= 5) - version = encryptedData[4]; - else - throw new Error('Decryption error: invalid header version'); - if (version > CryptorHeader.MAX_VERSION) - throw new Error('Decryption error: Unknown cryptor error'); - let identifier; - let pos = 5 + CryptorHeader.IDENTIFIER_LENGTH; - if (encryptedData.byteLength >= pos) - identifier = encryptedData.slice(5, pos); - else - throw new Error('Decryption error: invalid crypto identifier'); - let metadataLength = null; - if (encryptedData.byteLength >= pos + 1) - metadataLength = encryptedData[pos]; - else - throw new Error('Decryption error: invalid metadata length'); - pos += 1; - if (metadataLength === 255 && encryptedData.byteLength >= pos + 2) { - metadataLength = new Uint16Array(encryptedData.slice(pos, pos + 2)).reduce((acc, val) => (acc << 8) + val, 0); - } - return new CryptorHeaderV1(this.decoder.decode(identifier), metadataLength); + class SubscriptionWorkerMiddleware { + constructor(configuration) { + this.configuration = configuration; + /** + * Whether subscription worker has been initialized and ready to handle events. + */ + this.subscriptionWorkerReady = false; + this.workerEventsQueue = []; + this.callbacks = new Map(); + this.setupSubscriptionWorker(); } - } - CryptorHeader.SENTINEL = 'PNED'; - CryptorHeader.LEGACY_IDENTIFIER = ''; - CryptorHeader.IDENTIFIER_LENGTH = 4; - CryptorHeader.VERSION = 1; - CryptorHeader.MAX_VERSION = 1; - CryptorHeader.decoder = new TextDecoder(); - // v1 CryptorHeader - class CryptorHeaderV1 { - constructor(id, metadataLength) { - this._identifier = id; - this._metadataLength = metadataLength; + makeSendable(req) { + // Use default request flow for non-subscribe / presence leave requests. + if (!req.path.startsWith('/v2/subscribe') && !req.path.endsWith('/leave')) + return this.configuration.transport.makeSendable(req); + let controller; + const sendRequestEvent = { + type: 'send-request', + clientIdentifier: this.configuration.clientIdentifier, + subscriptionKey: this.configuration.subscriptionKey, + logVerbosity: this.configuration.logVerbosity, + request: req, + }; + if (req.cancellable) { + controller = { + abort: () => { + const cancelRequest = { + type: 'cancel-request', + clientIdentifier: this.configuration.clientIdentifier, + subscriptionKey: this.configuration.subscriptionKey, + logVerbosity: this.configuration.logVerbosity, + identifier: req.identifier, + }; + // Cancel active request with specified identifier. + this.scheduleEventPost(cancelRequest); + }, + }; + } + return [ + new Promise((resolve, reject) => { + // Associate Promise resolution / reject with request identifier for future usage in + // `onmessage` handler block to return results. + this.callbacks.set(req.identifier, { resolve, reject }); + // Trigger request processing by Service Worker. + this.scheduleEventPost(sendRequestEvent); + }), + controller, + ]; } - get identifier() { - return this._identifier; + request(req) { + return req; } - set identifier(value) { - this._identifier = value; + /** + * Schedule {@link event} publish to the subscription worker. + * + * Subscription worker may not be ready for events processing and this method build queue for the time when worker + * will be ready. + * + * @param event - Event payload for the subscription worker. + * @param outOfOrder - Whether event should be processed first then enqueued queue. + */ + scheduleEventPost(event, outOfOrder = false) { + // Trigger request processing by subscription worker. + const subscriptionWorker = this.sharedSubscriptionWorker; + if (subscriptionWorker) + subscriptionWorker.port.postMessage(event); + else { + if (outOfOrder) + this.workerEventsQueue.splice(0, 0, event); + else + this.workerEventsQueue.push(event); + } } - get metadataLength() { - return this._metadataLength; + /** + * Dequeue and post events from the queue to the subscription worker. + */ + flushScheduledEvents() { + // Trigger request processing by subscription worker. + const subscriptionWorker = this.sharedSubscriptionWorker; + if (!subscriptionWorker || this.workerEventsQueue.length === 0) + return; + // Clean up from cancelled events. + const outdatedEvents = []; + for (let i = 0; i < this.workerEventsQueue.length; i++) { + const event = this.workerEventsQueue[i]; + // Check whether found request cancel event to search for request send event it cancels. + if (event.type !== 'cancel-request' || i === 0) + continue; + for (let j = 0; j < i; j++) { + const otherEvent = this.workerEventsQueue[j]; + if (otherEvent.type !== 'send-request') + continue; + // Collect outdated events if identifiers match. + if (otherEvent.request.identifier === event.identifier) { + outdatedEvents.push(event, otherEvent); + break; + } + } + } + // Actualizing events queue. + this.workerEventsQueue = this.workerEventsQueue.filter((event) => !outdatedEvents.includes(event)); + this.workerEventsQueue.forEach((event) => subscriptionWorker.port.postMessage(event)); + this.workerEventsQueue = []; } - set metadataLength(value) { - this._metadataLength = value; + /** + * Subscription worker. + * + * @returns Worker which has been registered by the PubNub SDK. + */ + get sharedSubscriptionWorker() { + return this.subscriptionWorkerReady ? this.subscriptionWorker : null; } - get version() { - return CryptorHeader.VERSION; + setupSubscriptionWorker() { + if (typeof SharedWorker === 'undefined') + return; + this.subscriptionWorker = new SharedWorker(this.configuration.workerUrl, `/pubnub-${this.configuration.sdkVersion}`); + this.subscriptionWorker.port.start(); + // Register PubNub client within subscription worker. + this.scheduleEventPost({ + type: 'client-register', + clientIdentifier: this.configuration.clientIdentifier, + subscriptionKey: this.configuration.subscriptionKey, + userId: this.configuration.userId, + logVerbosity: this.configuration.logVerbosity, + workerLogVerbosity: this.configuration.workerLogVerbosity, + }, true); + this.subscriptionWorker.port.onmessage = (event) => this.handleWorkerEvent(event); } - get length() { - return (CryptorHeader.SENTINEL.length + - 1 + - CryptorHeader.IDENTIFIER_LENGTH + - (this.metadataLength < 255 ? 1 : 3) + - this.metadataLength); + handleWorkerEvent(event) { + const { data } = event; + // Ignoring updates not related to this instance. + if (data.type !== 'shared-worker-ping' && + data.type !== 'shared-worker-connected' && + data.type !== 'shared-worker-console-log' && + data.type !== 'shared-worker-console-dir' && + data.clientIdentifier !== this.configuration.clientIdentifier) + return; + if (data.type === 'shared-worker-connected') { + this.subscriptionWorkerReady = true; + this.flushScheduledEvents(); + } + else if (data.type === 'shared-worker-console-log') { + console.log(`[SharedWorker] ${data.message}`); + } + else if (data.type === 'shared-worker-console-dir') { + if (data.message) + console.log(`[SharedWorker] ${data.message}`); + console.dir(data.data); + } + else if (data.type === 'shared-worker-ping') { + const { logVerbosity, subscriptionKey, clientIdentifier } = this.configuration; + this.scheduleEventPost({ + type: 'client-pong', + subscriptionKey, + clientIdentifier, + logVerbosity, + }); + } + else if (data.type === 'request-progress-start' || data.type === 'request-progress-end') { + this.logRequestProgress(data); + } + else if (data.type === 'request-process-success' || data.type === 'request-process-error') { + const { resolve, reject } = this.callbacks.get(data.identifier); + if (data.type === 'request-process-success') { + resolve({ + status: data.response.status, + url: data.url, + headers: data.response.headers, + body: data.response.body, + }); + } + else { + let category = StatusCategory$1.PNUnknownCategory; + let message = 'Unknown error'; + // Handle client-side issues (if any). + if (data.error) { + if (data.error.type === 'NETWORK_ISSUE') + category = StatusCategory$1.PNNetworkIssuesCategory; + else if (data.error.type === 'TIMEOUT') + category = StatusCategory$1.PNTimeoutCategory; + else if (data.error.type === 'ABORTED') + category = StatusCategory$1.PNCancelledCategory; + message = `${data.error.message} (${data.identifier})`; + } + // Handle service error response. + else if (data.response) { + return reject(PubNubAPIError.create({ + url: data.url, + headers: data.response.headers, + body: data.response.body, + status: data.response.status, + }, data.response.body)); + } + reject(new PubNubAPIError(message, category, 0, new Error(message))); + } + } } - get data() { - let pos = 0; - const header = new Uint8Array(this.length); - const encoder = new TextEncoder(); - header.set(encoder.encode(CryptorHeader.SENTINEL)); - pos += CryptorHeader.SENTINEL.length; - header[pos] = this.version; - pos++; - if (this.identifier) - header.set(encoder.encode(this.identifier), pos); - const metadataLength = this.metadataLength; - pos += CryptorHeader.IDENTIFIER_LENGTH; - if (metadataLength < 255) - header[pos] = metadataLength; - else - header.set([255, metadataLength >> 8, metadataLength & 0xff], pos); - return header; + /** + * Print request progress information. + * + * @param information - Request progress information from worker. + */ + logRequestProgress(information) { + var _a, _b; + if (information.type === 'request-progress-start') { + console.log('<<<<<'); + console.log(`[${information.timestamp}] ${information.url}\n${JSON.stringify((_a = information.query) !== null && _a !== void 0 ? _a : {})}`); + console.log('-----'); + } + else { + console.log('>>>>>>'); + console.log(`[${information.timestamp} / ${information.duration}] ${information.url}\n${JSON.stringify((_b = information.query) !== null && _b !== void 0 ? _b : {})}\n${information.response}`); + console.log('-----'); + } } } - CryptorHeaderV1.IDENTIFIER_LENGTH = 4; - CryptorHeaderV1.SENTINEL = 'PNED'; /** * Percent-encode input string. @@ -3213,7 +3225,7 @@ const encodedNames = names.map((name) => encodeString(name)); return encodedNames.length ? encodedNames.join(',') : defaultString !== null && defaultString !== void 0 ? defaultString : ''; }; - const removeSingleOccurance = (source, elementsToRemove) => { + const removeSingleOccurrence = (source, elementsToRemove) => { const removed = Object.fromEntries(elementsToRemove.map((prop) => [prop, false])); return source.filter((e) => { if (elementsToRemove.includes(e) && !removed[e]) { @@ -3387,6 +3399,15 @@ */ WebReactNativeTransport.decoder = new TextDecoder(); + /** + * Re-map CBOR object keys from potentially C buffer strings to actual strings. + * + * @param obj CBOR which should be remapped to stringified keys. + * + * @returns Dictionary with stringified keys. + * + * @internal + */ function stringifyBufferKeys(obj) { const isObject = (value) => typeof value === 'object' && value !== null && value.constructor === Object; const isString = (value) => typeof value === 'string' || value instanceof String; @@ -3599,6 +3620,10 @@ * reconnection issues, set the flag to `false`. This allows the SDK reconnection logic to take over. */ const LISTEN_TO_BROWSER_NETWORK_EVENTS = true; + /** + * Whether verbose logging should be enabled for `Subscription` worker to print debug messages or not. + */ + const SUBSCRIPTION_WORKER_LOG_VERBOSITY = false; /** * Whether PubNub client should try to utilize existing TCP connection for new requests or not. */ @@ -3607,15 +3632,17 @@ * Apply configuration default values. * * @param configuration - User-provided configuration. + * + * @internal */ const setDefaults = (configuration) => { - var _a, _b; + var _a, _b, _c; // Force disable service workers if environment doesn't support them. - if (configuration.serviceWorkerUrl && !('serviceWorker' in navigator)) - configuration.serviceWorkerUrl = null; + if (configuration.subscriptionWorkerUrl && typeof SharedWorker === 'undefined') + configuration.subscriptionWorkerUrl = null; return Object.assign(Object.assign({}, setDefaults$1(configuration)), { // Set platform-specific options. - listenToBrowserNetworkEvents: (_a = configuration.listenToBrowserNetworkEvents) !== null && _a !== void 0 ? _a : LISTEN_TO_BROWSER_NETWORK_EVENTS, serviceWorkerUrl: configuration.serviceWorkerUrl, keepAlive: (_b = configuration.keepAlive) !== null && _b !== void 0 ? _b : KEEP_ALIVE }); + listenToBrowserNetworkEvents: (_a = configuration.listenToBrowserNetworkEvents) !== null && _a !== void 0 ? _a : LISTEN_TO_BROWSER_NETWORK_EVENTS, subscriptionWorkerUrl: configuration.subscriptionWorkerUrl, subscriptionWorkerLogVerbosity: (_b = configuration.subscriptionWorkerLogVerbosity) !== null && _b !== void 0 ? _b : SUBSCRIPTION_WORKER_LOG_VERBOSITY, keepAlive: (_c = configuration.keepAlive) !== null && _c !== void 0 ? _c : KEEP_ALIVE }); }; var uuid = {exports: {}}; @@ -3685,6 +3712,8 @@ // region Defaults /** * Whether encryption (if set) should use random initialization vector or not. + * + * @internal */ const USE_RANDOM_INITIALIZATION_VECTOR = true; /** @@ -3694,6 +3723,8 @@ * @param setupCryptoModule - Platform-provided {@link CryptoModule} configuration block. * * @returns `PubNub` client private configuration. + * + * @internal */ const makeConfiguration = (base, setupCryptoModule) => { var _a, _b, _c; @@ -3835,6 +3866,8 @@ * REST API access token manager. * * Manager maintains active access token and let parse it to get information about permissions. + * + * @internal */ class TokenManager { constructor(cbor) { @@ -4127,6 +4160,8 @@ */ /** * Real-time listeners' manager. + * + * @internal */ class ListenerManager { constructor() { @@ -4311,6 +4346,13 @@ * * **Note:** Reconnection manger rely on legacy time-based availability check. */ + /** + * Network "discovery" manager. + * + * Manager perform periodic `time` API calls to identify network availability. + * + * @internal + */ class ReconnectionManager { constructor(time) { this.time = time; @@ -4361,6 +4403,11 @@ return hash; }; + /** + * Real-time events deduplication manager. + * + * @internal + */ class DedupingManager { _config; @@ -4399,6 +4446,8 @@ */ /** * Subscription loop manager. + * + * @internal */ class SubscriptionManager { constructor(configuration, listenerManager, eventEmitter, subscribeCall, heartbeatCall, leaveCall, time) { @@ -5309,6 +5358,8 @@ /** * Base REST API request class. + * + * @internal */ class AbstractRequest { /** @@ -5725,6 +5776,8 @@ // region Types /** * PubNub-defined event types by payload. + * + * @internal */ var PubNubEventType; (function (PubNubEventType) { @@ -5762,6 +5815,8 @@ * Subscription request used in small variations in two cases: * - subscription manager * - event engine + * + * @internal */ class BaseSubscribeRequest extends AbstractRequest { constructor(parameters) { @@ -6000,6 +6055,8 @@ } /** * Subscribe request. + * + * @internal */ class SubscribeRequest extends BaseSubscribeRequest { get path() { @@ -6030,6 +6087,14 @@ } } + /** + * Real-time events' emitter. + * + * Emitter responsible for forwarding received real-time events to the closures which has been + * registered for specific events handling. + * + * @internal + */ class EventEmitter { constructor(listenerManager) { this.listenerManager = listenerManager; @@ -6190,6 +6255,9 @@ } } + /** + * @internal + */ class Subject { constructor(sync = false) { this.sync = sync; @@ -6379,6 +6447,11 @@ Object.setPrototypeOf(this, new.target.prototype); } } + /** + * Event Engine stored effect processing cancellation signal. + * + * @internal + */ class AbortSignal extends Subject { constructor() { super(...arguments); @@ -7234,11 +7307,11 @@ } } unsubscribe({ channels = [], channelGroups = [] }) { - const filteredChannels = removeSingleOccurance(this.channels, [ + const filteredChannels = removeSingleOccurrence(this.channels, [ ...channels, ...channels.map((c) => `${c}-pnpres`), ]); - const filteredGroups = removeSingleOccurance(this.groups, [ + const filteredGroups = removeSingleOccurrence(this.groups, [ ...channelGroups, ...channelGroups.map((c) => `${c}-pnpres`), ]); @@ -7313,6 +7386,8 @@ * * Request will normalize and encrypt (if required) provided data and push it to the specified * channel. + * + * @internal */ class PublishRequest extends AbstractRequest { /** @@ -7396,6 +7471,11 @@ * Signal REST API module. */ // endregion + /** + * Signal data (size-limited) publish request. + * + * @internal + */ class SignalRequest extends AbstractRequest { constructor(parameters) { super(); @@ -7433,6 +7513,8 @@ */ /** * Receive messages subscribe request. + * + * @internal */ class ReceiveMessagesSubscribeRequest extends BaseSubscribeRequest { operation() { @@ -7477,6 +7559,8 @@ * Handshake subscribe request. * * Separate subscribe request required by Event Engine. + * + * @internal */ class HandshakeSubscribeRequest extends BaseSubscribeRequest { operation() { @@ -7505,6 +7589,8 @@ // endregion /** * Get `uuid` presence state request. + * + * @internal */ class GetPresenceStateRequest extends AbstractRequest { constructor(parameters) { @@ -7559,6 +7645,8 @@ // endregion /** * Set `uuid` presence state request. + * + * @internal */ class SetPresenceStateRequest extends AbstractRequest { constructor(parameters) { @@ -7605,6 +7693,11 @@ * Announce heartbeat REST API module. */ // endregion + /** + * Announce `uuid` presence request. + * + * @internal + */ class HeartbeatRequest extends AbstractRequest { constructor(parameters) { super(); @@ -7650,6 +7743,11 @@ * Announce leave REST API module. */ // endregion + /** + * Announce user leave request. + * + * @internal + */ class PresenceLeaveRequest extends AbstractRequest { constructor(parameters) { super(); @@ -7697,6 +7795,11 @@ * `uuid` presence REST API module. */ // endregion + /** + * Get `uuid` presence request. + * + * @internal + */ class WhereNowRequest extends AbstractRequest { constructor(parameters) { super(); @@ -7744,6 +7847,11 @@ */ const INCLUDE_STATE = false; // endregion + /** + * Channel presence request. + * + * @internal + */ class HereNowRequest extends AbstractRequest { constructor(parameters) { var _a, _b, _c; @@ -7826,6 +7934,8 @@ // endregion /** * Delete messages from channel history. + * + * @internal */ class DeleteMessageRequest extends AbstractRequest { constructor(parameters) { @@ -7866,6 +7976,11 @@ * Messages count REST API module. */ // endregion + /** + * Count messages request. + * + * @internal + */ class MessageCountRequest extends AbstractRequest { constructor(parameters) { super(); @@ -7935,6 +8050,8 @@ // endregion /** * Get single channel messages request. + * + * @internal */ class GetHistoryRequest extends AbstractRequest { constructor(parameters) { @@ -8080,6 +8197,8 @@ // endregion /** * Fetch messages from channels request. + * + * @internal */ class FetchMessagesRequest extends AbstractRequest { constructor(parameters) { @@ -8230,6 +8349,8 @@ // endregion /** * Fetch channel message actions request. + * + * @internal */ class GetMessageActionsRequest extends AbstractRequest { constructor(parameters) { @@ -8283,6 +8404,8 @@ // endregion /** * Add Message Reaction request. + * + * @internal */ class AddMessageActionRequest extends AbstractRequest { constructor(parameters) { @@ -8338,6 +8461,8 @@ // endregion /** * Remove specific message action request. + * + * @internal */ class RemoveMessageAction extends AbstractRequest { constructor(parameters) { @@ -8387,6 +8512,11 @@ */ const STORE_IN_HISTORY = true; // endregion + /** + * Publish shared file information request. + * + * @internal + */ class PublishFileMessageRequest extends AbstractRequest { constructor(parameters) { var _a; @@ -8456,6 +8586,8 @@ * File download Url generation request. * * Local request which generates Url to download shared file from the specific channel. + * + * @internal */ class GetFileDownloadUrlRequest extends AbstractRequest { /** @@ -8496,6 +8628,8 @@ // endregion /** * Delete File request. + * + * @internal */ class DeleteFileRequest extends AbstractRequest { constructor(parameters) { @@ -8545,6 +8679,8 @@ // endregion /** * Files List request. + * + * @internal */ class FilesListRequest extends AbstractRequest { constructor(parameters) { @@ -8589,6 +8725,8 @@ // endregion /** * Generate File Upload Url request. + * + * @internal */ class GenerateFileUploadUrlRequest extends AbstractRequest { constructor(parameters) { @@ -8634,6 +8772,8 @@ */ /** * File Upload request. + * + * @internal */ class UploadFileRequest extends AbstractRequest { constructor(parameters) { @@ -8689,6 +8829,8 @@ // endregion /** * Send file composed request. + * + * @internal */ class SendFileRequest { constructor(parameters) { @@ -8813,6 +8955,8 @@ * Access token revoke request. * * Invalidate token and permissions which has been granted for it. + * + * @internal */ class RevokeTokenRequest extends AbstractRequest { constructor(parameters) { @@ -8851,6 +8995,8 @@ // endregion /** * Grant token permissions request. + * + * @internal */ class GrantTokenRequest extends AbstractRequest { constructor(parameters) { @@ -9049,6 +9195,8 @@ // endregion /** * Grant permissions request. + * + * @internal */ class GrantRequest extends AbstractRequest { constructor(parameters) { @@ -9118,6 +9266,8 @@ // endregion /** * Permissions audit request. + * + * @internal */ class AuditRequest extends AbstractRequest { constructor(parameters) { @@ -9355,6 +9505,8 @@ // endregion /** * Remove channel group channels request. + * + * @internal */ // prettier-ignore class RemoveChannelGroupChannelsRequest extends AbstractRequest { @@ -9400,6 +9552,8 @@ // endregion /** * Add channel group channels request. + * + * @internal */ class AddChannelGroupChannelsRequest extends AbstractRequest { constructor(parameters) { @@ -9444,6 +9598,8 @@ // endregion /** * List Channel Group Channels request. + * + * @internal */ class ListChannelGroupChannels extends AbstractRequest { constructor(parameters) { @@ -9482,6 +9638,8 @@ // endregion /** * Channel group delete request. + * + * @internal */ class DeleteChannelGroupRequest extends AbstractRequest { constructor(parameters) { @@ -9520,6 +9678,8 @@ // endregion /** * List all channel groups request. + * + * @internal */ class ListChannelGroupsRequest extends AbstractRequest { constructor(parameters) { @@ -9663,6 +9823,8 @@ // endregion /** * Base push notification request. + * + * @internal */ class BasePushNotificationChannelsRequest extends AbstractRequest { constructor(parameters) { @@ -9726,6 +9888,8 @@ // endregion /** * Unregister channels from device push request. + * + * @internal */ // prettier-ignore class RemoveDevicePushNotificationChannelsRequest extends BasePushNotificationChannelsRequest { @@ -9751,6 +9915,8 @@ // endregion /** * List device push enabled channels request. + * + * @internal */ // prettier-ignore class ListDevicePushNotificationChannelsRequest extends BasePushNotificationChannelsRequest { @@ -9776,6 +9942,8 @@ // endregion /** * Register channels with device push request. + * + * @internal */ // prettier-ignore class AddDevicePushNotificationChannelsRequest extends BasePushNotificationChannelsRequest { @@ -9801,6 +9969,8 @@ // endregion /** * Unregister device push notifications request. + * + * @internal */ // prettier-ignore class RemoveDevicePushNotificationRequest extends BasePushNotificationChannelsRequest { @@ -9912,6 +10082,8 @@ // endregion /** * Get All Channels Metadata request. + * + * @internal */ class GetAllChannelsMetadataRequest extends AbstractRequest { constructor(parameters) { @@ -9955,6 +10127,8 @@ // endregion /** * Remove Channel Metadata request. + * + * @internal */ class RemoveChannelMetadataRequest extends AbstractRequest { constructor(parameters) { @@ -10027,6 +10201,8 @@ // endregion /** * Get UUID Memberships request. + * + * @internal */ class GetUUIDMembershipsRequest extends AbstractRequest { constructor(parameters) { @@ -10120,6 +10296,8 @@ // endregion /** * Set UUID Memberships request. + * + * @internal */ class SetUUIDMembershipsRequest extends AbstractRequest { constructor(parameters) { @@ -10206,6 +10384,11 @@ */ const LIMIT$2 = 100; // endregion + /** + * Get All UUIDs Metadata request. + * + * @internal + */ class GetAllUUIDMetadataRequest extends AbstractRequest { constructor(parameters) { var _a, _b, _c; @@ -10255,6 +10438,8 @@ // endregion /** * Get Channel Metadata request. + * + * @internal */ class GetChannelMetadataRequest extends AbstractRequest { constructor(parameters) { @@ -10309,6 +10494,8 @@ // endregion /** * Set Channel Metadata request. + * + * @internal */ class SetChannelMetadataRequest extends AbstractRequest { constructor(parameters) { @@ -10360,6 +10547,8 @@ // endregion /** * Remove UUID Metadata request. + * + * @internal */ class RemoveUUIDMetadataRequest extends AbstractRequest { constructor(parameters) { @@ -10435,6 +10624,8 @@ // endregion /** * Get Channel Members request. + * + * @internal */ class GetChannelMembersRequest extends AbstractRequest { constructor(parameters) { @@ -10525,6 +10716,8 @@ // endregion /** * Set Channel Members request. + * + * @internal */ class SetChannelMembersRequest extends AbstractRequest { constructor(parameters) { @@ -10606,6 +10799,8 @@ // endregion /** * Get UUID Metadata request. + * + * @internal */ class GetUUIDMetadataRequest extends AbstractRequest { constructor(parameters) { @@ -10662,6 +10857,8 @@ // endregion /** * Set UUID Metadata request. + * + * @internal */ class SetUUIDMetadataRequest extends AbstractRequest { constructor(parameters) { @@ -11233,6 +11430,11 @@ * Time REST API module. */ // endregion + /** + * Get current PubNub high-precision time request. + * + * @internal + */ class TimeRequest extends AbstractRequest { constructor() { super(); @@ -11259,6 +11461,8 @@ // endregion /** * Download File request. + * + * @internal */ class DownloadFileRequest extends AbstractRequest { constructor(parameters) { @@ -12937,7 +13141,9 @@ } } /** - * {@link ArrayBuffer} to {@link string} decoder. + * {@link ArrayBuffer} to {@link string} decoder. + * + * @internal */ PubNubCore.decoder = new TextDecoder(); // -------------------------------------------------------- @@ -12966,6 +13172,8 @@ */ /** * CBOR data decoder. + * + * @internal */ class Cbor { constructor(decode, base64ToBinary) { @@ -13025,14 +13233,16 @@ } // Setup transport provider. let transport = new WebReactNativeTransport(clientConfiguration.keepAlive, clientConfiguration.logVerbosity); - if (configurationCopy.serviceWorkerUrl) { - // Inject subscription service worker into transport provider stack. - transport = new SubscriptionServiceWorkerMiddleware({ + if (configurationCopy.subscriptionWorkerUrl) { + // Inject subscription worker into transport provider stack. + transport = new SubscriptionWorkerMiddleware({ clientIdentifier: clientConfiguration._instanceId, subscriptionKey: clientConfiguration.subscribeKey, - serviceWorkerUrl: configurationCopy.serviceWorkerUrl, + userId: clientConfiguration.getUserId(), + workerUrl: configurationCopy.subscriptionWorkerUrl, sdkVersion: clientConfiguration.getVersion(), logVerbosity: clientConfiguration.logVerbosity, + workerLogVerbosity: platformConfiguration.subscriptionWorkerLogVerbosity, transport, }); } diff --git a/dist/web/pubnub.min.js b/dist/web/pubnub.min.js index 435b2833f..006cf471a 100644 --- a/dist/web/pubnub.min.js +++ b/dist/web/pubnub.min.js @@ -1,2 +1,2 @@ -!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?module.exports=t():"function"==typeof define&&define.amd?define(t):(e="undefined"!=typeof globalThis?globalThis:e||self).PubNub=t()}(this,(function(){"use strict";var e="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{};function t(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var s={exports:{}};!function(t){!function(e,s){var n=Math.pow(2,-24),r=Math.pow(2,32),i=Math.pow(2,53);var o={encode:function(e){var t,n=new ArrayBuffer(256),o=new DataView(n),a=0;function c(e){for(var s=n.byteLength,r=a+e;s>2,u=0;u>6),r.push(128|63&o)):o<55296?(r.push(224|o>>12),r.push(128|o>>6&63),r.push(128|63&o)):(o=(1023&o)<<10,o|=1023&t.charCodeAt(++n),o+=65536,r.push(240|o>>18),r.push(128|o>>12&63),r.push(128|o>>6&63),r.push(128|63&o))}return d(3,r.length),h(r);default:var p;if(Array.isArray(t))for(d(4,p=t.length),n=0;n>5!==e)throw"Invalid indefinite length element";return s}function f(e,t){for(var s=0;s>10),e.push(56320|1023&n))}}"function"!=typeof t&&(t=function(e){return e}),"function"!=typeof i&&(i=function(){return s});var m=function e(){var r,d,m=l(),b=m>>5,v=31&m;if(7===b)switch(v){case 25:return function(){var e=new ArrayBuffer(4),t=new DataView(e),s=h(),r=32768&s,i=31744&s,o=1023&s;if(31744===i)i=261120;else if(0!==i)i+=114688;else if(0!==o)return o*n;return t.setUint32(0,r<<16|i<<13|o<<13),t.getFloat32(0)}();case 26:return c(o.getFloat32(a),4);case 27:return c(o.getFloat64(a),8)}if((d=g(v))<0&&(b<2||6=0;)S+=d,w.push(u(d));var k=new Uint8Array(S),E=0;for(r=0;r=0;)f(O,d);else f(O,d);return String.fromCharCode.apply(null,O);case 4:var C;if(d<0)for(C=[];!p();)C.push(e());else for(C=new Array(d),r=0;r0){const n=(new TextDecoder).decode(t);if(-1!==e.headers["content-type"].indexOf("text/javascript")||-1!==e.headers["content-type"].indexOf("application/json"))try{const e=JSON.parse(n);"object"!=typeof e||Array.isArray(e)||("error"in e&&(1===e.error||!0===e.error)&&"status"in e&&"number"==typeof e.status&&"message"in e&&"service"in e?(s=e,o=e.status):s=e,"error"in e&&e.error instanceof Error&&(s=e.error))}catch(e){s=n}else if(-1!==e.headers["content-type"].indexOf("xml")){const e=/(.*)<\/Message>/gi.exec(n);r=e?`Upload to bucket failed: ${e[1]}`:"Upload to bucket failed."}else s=n}return new c(r,n,o,s)}constructor(e,t,s,n){super(e),this.category=t,this.statusCode=s,this.errorData=n,this.name="PubNubAPIError"}toStatus(e){return{error:!0,category:this.category,operation:e,statusCode:this.statusCode,errorData:this.errorData}}toPubNubError(e,t){return new o(null!=t?t:this.message,this.toStatus(e))}}class u{constructor(e){this.configuration=e,this.serviceWorkerEventsQueue=[],this.callbacks=new Map,this.setupServiceWorker()}makeSendable(e){if(!e.path.startsWith("/v2/subscribe")&&!e.path.endsWith("/leave"))return this.configuration.transport.makeSendable(e);let t;const s={type:"send-request",clientIdentifier:this.configuration.clientIdentifier,subscriptionKey:this.configuration.subscriptionKey,logVerbosity:this.configuration.logVerbosity,request:e};return e.cancellable&&(t={abort:()=>{const t={type:"cancel-request",clientIdentifier:this.configuration.clientIdentifier,subscriptionKey:this.configuration.subscriptionKey,logVerbosity:this.configuration.logVerbosity,identifier:e.identifier};this.scheduleEventPost(t)}}),[new Promise(((t,n)=>{this.callbacks.set(e.identifier,{resolve:t,reject:n}),this.scheduleEventPost(s)})),t]}request(e){return e}scheduleEventPost(e,t=!1){const s=this.serviceWorker;s?s.postMessage(e):t?this.serviceWorkerEventsQueue.splice(0,0,e):this.serviceWorkerEventsQueue.push(e)}flushScheduledEvents(){const e=this.serviceWorker;if(!e||0===this.serviceWorkerEventsQueue.length)return;const t=[];for(let e=0;e!t.includes(e))),this.serviceWorkerEventsQueue.forEach((t=>e.postMessage(t))),this.serviceWorkerEventsQueue=[]}get serviceWorker(){return this.serviceWorkerRegistration?this.serviceWorkerRegistration.active:null}setupServiceWorker(){if(!("serviceWorker"in navigator))return;const e=navigator.serviceWorker;e.register(this.configuration.serviceWorkerUrl,{scope:`/pubnub-${this.configuration.sdkVersion}`}).then((e=>{this.serviceWorkerRegistration=e,e.active&&this.flushScheduledEvents(),this.serviceWorkerRegistration.addEventListener("updatefound",(()=>{if(!this.serviceWorkerRegistration)return;const e=this.serviceWorkerRegistration.installing,t=()=>{"activated"===e.state?this.flushScheduledEvents():"redundant"===e.state&&e.removeEventListener("statechange",t)};e.addEventListener("statechange",t)}))})),e.addEventListener("message",(e=>this.handleServiceWorkerEvent(e)))}handleServiceWorkerEvent(e){const{data:t}=e;if(t.clientIdentifier===this.configuration.clientIdentifier)if("request-progress-start"===t.type||"request-progress-end"===t.type)this.logRequestProgress(t);else if("request-process-success"===t.type||"request-process-error"===t.type){const{resolve:e,reject:s}=this.callbacks.get(t.identifier);if("request-process-success"===t.type)e({status:t.response.status,url:t.url,headers:t.response.headers,body:t.response.body});else{let e=i.PNUnknownCategory,n="Unknown error";if(t.error)"NETWORK_ISSUE"===t.error.type?e=i.PNNetworkIssuesCategory:"TIMEOUT"===t.error.type?e=i.PNTimeoutCategory:"ABORTED"===t.error.type&&(e=i.PNCancelledCategory),n=`${t.error.message} (${t.identifier})`;else if(t.response)return s(c.create({url:t.url,headers:t.response.headers,body:t.response.body,status:t.response.status},t.response.body));s(new c(n,e,0,new Error(n)))}}}logRequestProgress(e){var t,s;"request-progress-start"===e.type?(console.log("<<<<<"),console.log(`[${e.timestamp}] ${e.url}\n${JSON.stringify(null!==(t=e.query)&&void 0!==t?t:{})}`),console.log("-----")):(console.log(">>>>>>"),console.log(`[${e.timestamp} / ${e.duration}] ${e.url}\n${JSON.stringify(null!==(s=e.query)&&void 0!==s?s:{})}\n${e.response}`),console.log("-----"))}}function l(e,t){var s={};for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&t.indexOf(n)<0&&(s[n]=e[n]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(n=Object.getOwnPropertySymbols(e);r{const s=new FileReader;s.addEventListener("load",(()=>{if(s.result instanceof ArrayBuffer)return e(s.result)})),s.addEventListener("error",(()=>t(s.error))),s.readAsArrayBuffer(this.data)}))}))}toString(){return h(this,void 0,void 0,(function*(){return new Promise(((e,t)=>{const s=new FileReader;s.addEventListener("load",(()=>{if("string"==typeof s.result)return e(s.result)})),s.addEventListener("error",(()=>{t(s.error)})),s.readAsBinaryString(this.data)}))}))}toStream(){return h(this,void 0,void 0,(function*(){throw new Error("This feature is only supported in Node.js environments.")}))}toFile(){return h(this,void 0,void 0,(function*(){return this.data}))}toFileUri(){return h(this,void 0,void 0,(function*(){throw new Error("This feature is only supported in React Native environments.")}))}toBlob(){return h(this,void 0,void 0,(function*(){return this.data}))}}p.supportsBlob="undefined"!=typeof Blob,p.supportsFile="undefined"!=typeof File,p.supportsBuffer=!1,p.supportsStream=!1,p.supportsString=!0,p.supportsArrayBuffer=!0,p.supportsEncryptFile=!0,p.supportsFileUri=!1;function g(e){const t=e.replace(/==?$/,""),s=Math.floor(t.length/4*3),n=new ArrayBuffer(s),r=new Uint8Array(n);let i=0;function o(){const e=t.charAt(i++),s="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=".indexOf(e);if(-1===s)throw new Error(`Illegal character at ${i}: ${t.charAt(i-1)}`);return s}for(let e=0;e>4,c=(15&s)<<4|n>>2,u=(3&n)<<6|i;r[e]=a,64!=n&&(r[e+1]=c),64!=i&&(r[e+2]=u)}return n}function y(e){let t="";const s="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",n=new Uint8Array(e),r=n.byteLength,i=r%3,o=r-i;let a,c,u,l,h;for(let e=0;e>18,c=(258048&h)>>12,u=(4032&h)>>6,l=63&h,t+=s[a]+s[c]+s[u]+s[l];return 1==i?(h=n[o],a=(252&h)>>2,c=(3&h)<<4,t+=s[a]+s[c]+"=="):2==i&&(h=n[o]<<8|n[o+1],a=(64512&h)>>10,c=(1008&h)>>4,u=(15&h)<<2,t+=s[a]+s[c]+s[u]+"="),t}var f,m,b,v,w,S=S||function(e,t){var s={},n=s.lib={},r=function(){},i=n.Base={extend:function(e){r.prototype=this;var t=new r;return e&&t.mixIn(e),t.hasOwnProperty("init")||(t.init=function(){t.$super.init.apply(this,arguments)}),t.init.prototype=t,t.$super=this,t},create:function(){var e=this.extend();return e.init.apply(e,arguments),e},init:function(){},mixIn:function(e){for(var t in e)e.hasOwnProperty(t)&&(this[t]=e[t]);e.hasOwnProperty("toString")&&(this.toString=e.toString)},clone:function(){return this.init.prototype.extend(this)}},o=n.WordArray=i.extend({init:function(e,t){e=this.words=e||[],this.sigBytes=null!=t?t:4*e.length},toString:function(e){return(e||c).stringify(this)},concat:function(e){var t=this.words,s=e.words,n=this.sigBytes;if(e=e.sigBytes,this.clamp(),n%4)for(var r=0;r>>2]|=(s[r>>>2]>>>24-r%4*8&255)<<24-(n+r)%4*8;else if(65535>>2]=s[r>>>2];else t.push.apply(t,s);return this.sigBytes+=e,this},clamp:function(){var t=this.words,s=this.sigBytes;t[s>>>2]&=4294967295<<32-s%4*8,t.length=e.ceil(s/4)},clone:function(){var e=i.clone.call(this);return e.words=this.words.slice(0),e},random:function(t){for(var s=[],n=0;n>>2]>>>24-n%4*8&255;s.push((r>>>4).toString(16)),s.push((15&r).toString(16))}return s.join("")},parse:function(e){for(var t=e.length,s=[],n=0;n>>3]|=parseInt(e.substr(n,2),16)<<24-n%8*4;return new o.init(s,t/2)}},u=a.Latin1={stringify:function(e){var t=e.words;e=e.sigBytes;for(var s=[],n=0;n>>2]>>>24-n%4*8&255));return s.join("")},parse:function(e){for(var t=e.length,s=[],n=0;n>>2]|=(255&e.charCodeAt(n))<<24-n%4*8;return new o.init(s,t)}},l=a.Utf8={stringify:function(e){try{return decodeURIComponent(escape(u.stringify(e)))}catch(e){throw Error("Malformed UTF-8 data")}},parse:function(e){return u.parse(unescape(encodeURIComponent(e)))}},h=n.BufferedBlockAlgorithm=i.extend({reset:function(){this._data=new o.init,this._nDataBytes=0},_append:function(e){"string"==typeof e&&(e=l.parse(e)),this._data.concat(e),this._nDataBytes+=e.sigBytes},_process:function(t){var s=this._data,n=s.words,r=s.sigBytes,i=this.blockSize,a=r/(4*i);if(t=(a=t?e.ceil(a):e.max((0|a)-this._minBufferSize,0))*i,r=e.min(4*t,r),t){for(var c=0;cu;){var l;e:{l=c;for(var h=e.sqrt(l),d=2;d<=h;d++)if(!(l%d)){l=!1;break e}l=!0}l&&(8>u&&(i[u]=a(e.pow(c,.5))),o[u]=a(e.pow(c,1/3)),u++),c++}var p=[];r=r.SHA256=n.extend({_doReset:function(){this._hash=new s.init(i.slice(0))},_doProcessBlock:function(e,t){for(var s=this._hash.words,n=s[0],r=s[1],i=s[2],a=s[3],c=s[4],u=s[5],l=s[6],h=s[7],d=0;64>d;d++){if(16>d)p[d]=0|e[t+d];else{var g=p[d-15],y=p[d-2];p[d]=((g<<25|g>>>7)^(g<<14|g>>>18)^g>>>3)+p[d-7]+((y<<15|y>>>17)^(y<<13|y>>>19)^y>>>10)+p[d-16]}g=h+((c<<26|c>>>6)^(c<<21|c>>>11)^(c<<7|c>>>25))+(c&u^~c&l)+o[d]+p[d],y=((n<<30|n>>>2)^(n<<19|n>>>13)^(n<<10|n>>>22))+(n&r^n&i^r&i),h=l,l=u,u=c,c=a+g|0,a=i,i=r,r=n,n=g+y|0}s[0]=s[0]+n|0,s[1]=s[1]+r|0,s[2]=s[2]+i|0,s[3]=s[3]+a|0,s[4]=s[4]+c|0,s[5]=s[5]+u|0,s[6]=s[6]+l|0,s[7]=s[7]+h|0},_doFinalize:function(){var t=this._data,s=t.words,n=8*this._nDataBytes,r=8*t.sigBytes;return s[r>>>5]|=128<<24-r%32,s[14+(r+64>>>9<<4)]=e.floor(n/4294967296),s[15+(r+64>>>9<<4)]=n,t.sigBytes=4*s.length,this._process(),this._hash},clone:function(){var e=n.clone.call(this);return e._hash=this._hash.clone(),e}});t.SHA256=n._createHelper(r),t.HmacSHA256=n._createHmacHelper(r)}(Math),m=(f=S).enc.Utf8,f.algo.HMAC=f.lib.Base.extend({init:function(e,t){e=this._hasher=new e.init,"string"==typeof t&&(t=m.parse(t));var s=e.blockSize,n=4*s;t.sigBytes>n&&(t=e.finalize(t)),t.clamp();for(var r=this._oKey=t.clone(),i=this._iKey=t.clone(),o=r.words,a=i.words,c=0;c>>2]>>>24-r%4*8&255)<<16|(t[r+1>>>2]>>>24-(r+1)%4*8&255)<<8|t[r+2>>>2]>>>24-(r+2)%4*8&255,o=0;4>o&&r+.75*o>>6*(3-o)&63));if(t=n.charAt(64))for(;e.length%4;)e.push(t);return e.join("")},parse:function(e){var t=e.length,s=this._map;(n=s.charAt(64))&&-1!=(n=e.indexOf(n))&&(t=n);for(var n=[],r=0,i=0;i>>6-i%4*2;n[r>>>2]|=(o|a)<<24-r%4*8,r++}return v.create(n,r)},_map:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/="},function(e){function t(e,t,s,n,r,i,o){return((e=e+(t&s|~t&n)+r+o)<>>32-i)+t}function s(e,t,s,n,r,i,o){return((e=e+(t&n|s&~n)+r+o)<>>32-i)+t}function n(e,t,s,n,r,i,o){return((e=e+(t^s^n)+r+o)<>>32-i)+t}function r(e,t,s,n,r,i,o){return((e=e+(s^(t|~n))+r+o)<>>32-i)+t}for(var i=S,o=(c=i.lib).WordArray,a=c.Hasher,c=i.algo,u=[],l=0;64>l;l++)u[l]=4294967296*e.abs(e.sin(l+1))|0;c=c.MD5=a.extend({_doReset:function(){this._hash=new o.init([1732584193,4023233417,2562383102,271733878])},_doProcessBlock:function(e,i){for(var o=0;16>o;o++){var a=e[c=i+o];e[c]=16711935&(a<<8|a>>>24)|4278255360&(a<<24|a>>>8)}o=this._hash.words;var c=e[i+0],l=(a=e[i+1],e[i+2]),h=e[i+3],d=e[i+4],p=e[i+5],g=e[i+6],y=e[i+7],f=e[i+8],m=e[i+9],b=e[i+10],v=e[i+11],w=e[i+12],S=e[i+13],k=e[i+14],E=e[i+15],O=t(O=o[0],P=o[1],N=o[2],C=o[3],c,7,u[0]),C=t(C,O,P,N,a,12,u[1]),N=t(N,C,O,P,l,17,u[2]),P=t(P,N,C,O,h,22,u[3]);O=t(O,P,N,C,d,7,u[4]),C=t(C,O,P,N,p,12,u[5]),N=t(N,C,O,P,g,17,u[6]),P=t(P,N,C,O,y,22,u[7]),O=t(O,P,N,C,f,7,u[8]),C=t(C,O,P,N,m,12,u[9]),N=t(N,C,O,P,b,17,u[10]),P=t(P,N,C,O,v,22,u[11]),O=t(O,P,N,C,w,7,u[12]),C=t(C,O,P,N,S,12,u[13]),N=t(N,C,O,P,k,17,u[14]),O=s(O,P=t(P,N,C,O,E,22,u[15]),N,C,a,5,u[16]),C=s(C,O,P,N,g,9,u[17]),N=s(N,C,O,P,v,14,u[18]),P=s(P,N,C,O,c,20,u[19]),O=s(O,P,N,C,p,5,u[20]),C=s(C,O,P,N,b,9,u[21]),N=s(N,C,O,P,E,14,u[22]),P=s(P,N,C,O,d,20,u[23]),O=s(O,P,N,C,m,5,u[24]),C=s(C,O,P,N,k,9,u[25]),N=s(N,C,O,P,h,14,u[26]),P=s(P,N,C,O,f,20,u[27]),O=s(O,P,N,C,S,5,u[28]),C=s(C,O,P,N,l,9,u[29]),N=s(N,C,O,P,y,14,u[30]),O=n(O,P=s(P,N,C,O,w,20,u[31]),N,C,p,4,u[32]),C=n(C,O,P,N,f,11,u[33]),N=n(N,C,O,P,v,16,u[34]),P=n(P,N,C,O,k,23,u[35]),O=n(O,P,N,C,a,4,u[36]),C=n(C,O,P,N,d,11,u[37]),N=n(N,C,O,P,y,16,u[38]),P=n(P,N,C,O,b,23,u[39]),O=n(O,P,N,C,S,4,u[40]),C=n(C,O,P,N,c,11,u[41]),N=n(N,C,O,P,h,16,u[42]),P=n(P,N,C,O,g,23,u[43]),O=n(O,P,N,C,m,4,u[44]),C=n(C,O,P,N,w,11,u[45]),N=n(N,C,O,P,E,16,u[46]),O=r(O,P=n(P,N,C,O,l,23,u[47]),N,C,c,6,u[48]),C=r(C,O,P,N,y,10,u[49]),N=r(N,C,O,P,k,15,u[50]),P=r(P,N,C,O,p,21,u[51]),O=r(O,P,N,C,w,6,u[52]),C=r(C,O,P,N,h,10,u[53]),N=r(N,C,O,P,b,15,u[54]),P=r(P,N,C,O,a,21,u[55]),O=r(O,P,N,C,f,6,u[56]),C=r(C,O,P,N,E,10,u[57]),N=r(N,C,O,P,g,15,u[58]),P=r(P,N,C,O,S,21,u[59]),O=r(O,P,N,C,d,6,u[60]),C=r(C,O,P,N,v,10,u[61]),N=r(N,C,O,P,l,15,u[62]),P=r(P,N,C,O,m,21,u[63]);o[0]=o[0]+O|0,o[1]=o[1]+P|0,o[2]=o[2]+N|0,o[3]=o[3]+C|0},_doFinalize:function(){var t=this._data,s=t.words,n=8*this._nDataBytes,r=8*t.sigBytes;s[r>>>5]|=128<<24-r%32;var i=e.floor(n/4294967296);for(s[15+(r+64>>>9<<4)]=16711935&(i<<8|i>>>24)|4278255360&(i<<24|i>>>8),s[14+(r+64>>>9<<4)]=16711935&(n<<8|n>>>24)|4278255360&(n<<24|n>>>8),t.sigBytes=4*(s.length+1),this._process(),s=(t=this._hash).words,n=0;4>n;n++)r=s[n],s[n]=16711935&(r<<8|r>>>24)|4278255360&(r<<24|r>>>8);return t},clone:function(){var e=a.clone.call(this);return e._hash=this._hash.clone(),e}}),i.MD5=a._createHelper(c),i.HmacMD5=a._createHmacHelper(c)}(Math),function(){var e,t=S,s=(e=t.lib).Base,n=e.WordArray,r=(e=t.algo).EvpKDF=s.extend({cfg:s.extend({keySize:4,hasher:e.MD5,iterations:1}),init:function(e){this.cfg=this.cfg.extend(e)},compute:function(e,t){for(var s=(a=this.cfg).hasher.create(),r=n.create(),i=r.words,o=a.keySize,a=a.iterations;i.length>>2]}},t.BlockCipher=a.extend({cfg:a.cfg.extend({mode:c,padding:l}),reset:function(){a.reset.call(this);var e=(t=this.cfg).iv,t=t.mode;if(this._xformMode==this._ENC_XFORM_MODE)var s=t.createEncryptor;else s=t.createDecryptor,this._minBufferSize=1;this._mode=s.call(t,this,e&&e.words)},_doProcessBlock:function(e,t){this._mode.processBlock(e,t)},_doFinalize:function(){var e=this.cfg.padding;if(this._xformMode==this._ENC_XFORM_MODE){e.pad(this._data,this.blockSize);var t=this._process(!0)}else t=this._process(!0),e.unpad(t);return t},blockSize:4});var h=t.CipherParams=s.extend({init:function(e){this.mixIn(e)},toString:function(e){return(e||this.formatter).stringify(this)}}),d=(c=(p.format={}).OpenSSL={stringify:function(e){var t=e.ciphertext;return((e=e.salt)?n.create([1398893684,1701076831]).concat(e).concat(t):t).toString(i)},parse:function(e){var t=(e=i.parse(e)).words;if(1398893684==t[0]&&1701076831==t[1]){var s=n.create(t.slice(2,4));t.splice(0,4),e.sigBytes-=16}return h.create({ciphertext:e,salt:s})}},t.SerializableCipher=s.extend({cfg:s.extend({format:c}),encrypt:function(e,t,s,n){n=this.cfg.extend(n);var r=e.createEncryptor(s,n);return t=r.finalize(t),r=r.cfg,h.create({ciphertext:t,key:s,iv:r.iv,algorithm:e,mode:r.mode,padding:r.padding,blockSize:e.blockSize,formatter:n.format})},decrypt:function(e,t,s,n){return n=this.cfg.extend(n),t=this._parse(t,n.format),e.createDecryptor(s,n).finalize(t.ciphertext)},_parse:function(e,t){return"string"==typeof e?t.parse(e,this):e}})),p=(p.kdf={}).OpenSSL={execute:function(e,t,s,r){return r||(r=n.random(8)),e=o.create({keySize:t+s}).compute(e,r),s=n.create(e.words.slice(t),4*s),e.sigBytes=4*t,h.create({key:e,iv:s,salt:r})}},g=t.PasswordBasedCipher=d.extend({cfg:d.cfg.extend({kdf:p}),encrypt:function(e,t,s,n){return s=(n=this.cfg.extend(n)).kdf.execute(s,e.keySize,e.ivSize),n.iv=s.iv,(e=d.encrypt.call(this,e,t,s.key,n)).mixIn(s),e},decrypt:function(e,t,s,n){return n=this.cfg.extend(n),t=this._parse(t,n.format),s=n.kdf.execute(s,e.keySize,e.ivSize,t.salt),n.iv=s.iv,d.decrypt.call(this,e,t,s.key,n)}})}(),function(){for(var e=S,t=e.lib.BlockCipher,s=e.algo,n=[],r=[],i=[],o=[],a=[],c=[],u=[],l=[],h=[],d=[],p=[],g=0;256>g;g++)p[g]=128>g?g<<1:g<<1^283;var y=0,f=0;for(g=0;256>g;g++){var m=(m=f^f<<1^f<<2^f<<3^f<<4)>>>8^255&m^99;n[y]=m,r[m]=y;var b=p[y],v=p[b],w=p[v],k=257*p[m]^16843008*m;i[y]=k<<24|k>>>8,o[y]=k<<16|k>>>16,a[y]=k<<8|k>>>24,c[y]=k,k=16843009*w^65537*v^257*b^16843008*y,u[m]=k<<24|k>>>8,l[m]=k<<16|k>>>16,h[m]=k<<8|k>>>24,d[m]=k,y?(y=b^p[p[p[w^b]]],f^=p[p[f]]):y=f=1}var E=[0,1,2,4,8,16,32,64,128,27,54];s=s.AES=t.extend({_doReset:function(){for(var e=(s=this._key).words,t=s.sigBytes/4,s=4*((this._nRounds=t+6)+1),r=this._keySchedule=[],i=0;i>>24]<<24|n[o>>>16&255]<<16|n[o>>>8&255]<<8|n[255&o]):(o=n[(o=o<<8|o>>>24)>>>24]<<24|n[o>>>16&255]<<16|n[o>>>8&255]<<8|n[255&o],o^=E[i/t|0]<<24),r[i]=r[i-t]^o}for(e=this._invKeySchedule=[],t=0;tt||4>=i?o:u[n[o>>>24]]^l[n[o>>>16&255]]^h[n[o>>>8&255]]^d[n[255&o]]},encryptBlock:function(e,t){this._doCryptBlock(e,t,this._keySchedule,i,o,a,c,n)},decryptBlock:function(e,t){var s=e[t+1];e[t+1]=e[t+3],e[t+3]=s,this._doCryptBlock(e,t,this._invKeySchedule,u,l,h,d,r),s=e[t+1],e[t+1]=e[t+3],e[t+3]=s},_doCryptBlock:function(e,t,s,n,r,i,o,a){for(var c=this._nRounds,u=e[t]^s[0],l=e[t+1]^s[1],h=e[t+2]^s[2],d=e[t+3]^s[3],p=4,g=1;g>>24]^r[l>>>16&255]^i[h>>>8&255]^o[255&d]^s[p++],f=n[l>>>24]^r[h>>>16&255]^i[d>>>8&255]^o[255&u]^s[p++],m=n[h>>>24]^r[d>>>16&255]^i[u>>>8&255]^o[255&l]^s[p++];d=n[d>>>24]^r[u>>>16&255]^i[l>>>8&255]^o[255&h]^s[p++],u=y,l=f,h=m}y=(a[u>>>24]<<24|a[l>>>16&255]<<16|a[h>>>8&255]<<8|a[255&d])^s[p++],f=(a[l>>>24]<<24|a[h>>>16&255]<<16|a[d>>>8&255]<<8|a[255&u])^s[p++],m=(a[h>>>24]<<24|a[d>>>16&255]<<16|a[u>>>8&255]<<8|a[255&l])^s[p++],d=(a[d>>>24]<<24|a[u>>>16&255]<<16|a[l>>>8&255]<<8|a[255&h])^s[p++],e[t]=y,e[t+1]=f,e[t+2]=m,e[t+3]=d},keySize:8});e.AES=t._createHelper(s)}(),S.mode.ECB=((w=S.lib.BlockCipherMode.extend()).Encryptor=w.extend({processBlock:function(e,t){this._cipher.encryptBlock(e,t)}}),w.Decryptor=w.extend({processBlock:function(e,t){this._cipher.decryptBlock(e,t)}}),w);var k=t(S);class E{constructor({cipherKey:e}){this.cipherKey=e,this.CryptoJS=k,this.encryptedKey=this.CryptoJS.SHA256(e)}encrypt(e){if(0===("string"==typeof e?e:E.decoder.decode(e)).length)throw new Error("encryption error. empty content");const t=this.getIv();return{metadata:t,data:g(this.CryptoJS.AES.encrypt(e,this.encryptedKey,{iv:this.bufferToWordArray(t),mode:this.CryptoJS.mode.CBC}).ciphertext.toString(this.CryptoJS.enc.Base64))}}encryptFileData(e){return h(this,void 0,void 0,(function*(){const t=yield this.getKey(),s=this.getIv();return{data:yield crypto.subtle.encrypt({name:this.algo,iv:s},t,e),metadata:s}}))}decrypt(e){if("string"==typeof e.data)throw new Error("Decryption error: data for decryption should be ArrayBuffed.");const t=this.bufferToWordArray(new Uint8ClampedArray(e.metadata)),s=this.bufferToWordArray(new Uint8ClampedArray(e.data));return E.encoder.encode(this.CryptoJS.AES.decrypt({ciphertext:s},this.encryptedKey,{iv:t,mode:this.CryptoJS.mode.CBC}).toString(this.CryptoJS.enc.Utf8)).buffer}decryptFileData(e){return h(this,void 0,void 0,(function*(){if("string"==typeof e.data)throw new Error("Decryption error: data for decryption should be ArrayBuffed.");const t=yield this.getKey();return crypto.subtle.decrypt({name:this.algo,iv:e.metadata},t,e.data)}))}get identifier(){return"ACRH"}get algo(){return"AES-CBC"}getIv(){return crypto.getRandomValues(new Uint8Array(E.BLOCK_SIZE))}getKey(){return h(this,void 0,void 0,(function*(){const e=E.encoder.encode(this.cipherKey),t=yield crypto.subtle.digest("SHA-256",e.buffer);return crypto.subtle.importKey("raw",t,this.algo,!0,["encrypt","decrypt"])}))}bufferToWordArray(e){const t=[];let s;for(s=0;se.toString(16).padStart(2,"0"))).join(""),n=P.encoder.encode(s.slice(0,32)).buffer;return crypto.subtle.importKey("raw",n,"AES-CBC",!0,["encrypt","decrypt"])}))}}P.IV_LENGTH=16,P.encoder=new TextEncoder,P.decoder=new TextDecoder;class M{constructor(e){this.config=e,this.cryptor=new C(Object.assign({},e)),this.fileCryptor=new P}encrypt(e){const t="string"==typeof e?e:M.decoder.decode(e);return{data:this.cryptor.encrypt(t),metadata:null}}encryptFile(e,t){return h(this,void 0,void 0,(function*(){var s;if(!this.config.cipherKey)throw new o("File encryption error: cipher key not set.");return this.fileCryptor.encryptFile(null===(s=this.config)||void 0===s?void 0:s.cipherKey,e,t)}))}decrypt(e){const t="string"==typeof e.data?e.data:y(e.data);return this.cryptor.decrypt(t)}decryptFile(e,t){return h(this,void 0,void 0,(function*(){if(!this.config.cipherKey)throw new o("File encryption error: cipher key not set.");return this.fileCryptor.decryptFile(this.config.cipherKey,e,t)}))}get identifier(){return""}}M.encoder=new TextEncoder,M.decoder=new TextDecoder;class j extends d{static legacyCryptoModule(e){var t;if(!e.cipherKey)throw new o("Crypto module error: cipher key not set.");return new j({default:new M(Object.assign(Object.assign({},e),{useRandomIVs:null===(t=e.useRandomIVs)||void 0===t||t})),cryptors:[new E({cipherKey:e.cipherKey})]})}static aesCbcCryptoModule(e){var t;if(!e.cipherKey)throw new o("Crypto module error: cipher key not set.");return new j({default:new E({cipherKey:e.cipherKey}),cryptors:[new M(Object.assign(Object.assign({},e),{useRandomIVs:null===(t=e.useRandomIVs)||void 0===t||t}))]})}static withDefaultCryptor(e){return new this({default:e})}encrypt(e){const t=e instanceof ArrayBuffer&&this.defaultCryptor.identifier===j.LEGACY_IDENTIFIER?this.defaultCryptor.encrypt(j.decoder.decode(e)):this.defaultCryptor.encrypt(e);if(!t.metadata)return t.data;if("string"==typeof t.data)throw new Error("Encryption error: encrypted data should be ArrayBuffed.");const s=this.getHeaderData(t);return this.concatArrayBuffer(s,t.data)}encryptFile(e,t){return h(this,void 0,void 0,(function*(){if(this.defaultCryptor.identifier===_.LEGACY_IDENTIFIER)return this.defaultCryptor.encryptFile(e,t);const s=yield this.getFileData(e),n=yield this.defaultCryptor.encryptFileData(s);if("string"==typeof n.data)throw new Error("Encryption error: encrypted data should be ArrayBuffed.");return t.create({name:e.name,mimeType:"application/octet-stream",data:this.concatArrayBuffer(this.getHeaderData(n),n.data)})}))}decrypt(e){const t="string"==typeof e?g(e):e,s=_.tryParse(t),n=this.getCryptor(s),r=s.length>0?t.slice(s.length-s.metadataLength,s.length):null;if(t.slice(s.length).byteLength<=0)throw new Error("Decryption error: empty content");return n.decrypt({data:t.slice(s.length),metadata:r})}decryptFile(e,t){return h(this,void 0,void 0,(function*(){const s=yield e.data.arrayBuffer(),n=_.tryParse(s),r=this.getCryptor(n);if((null==r?void 0:r.identifier)===_.LEGACY_IDENTIFIER)return r.decryptFile(e,t);const i=(yield this.getFileData(s)).slice(n.length-n.metadataLength,n.length);return t.create({name:e.name,data:yield this.defaultCryptor.decryptFileData({data:s.slice(n.length),metadata:i})})}))}getCryptorFromId(e){const t=this.getAllCryptors().find((t=>e===t.identifier));if(t)return t;throw Error("Unknown cryptor error")}getCryptor(e){if("string"==typeof e){const t=this.getAllCryptors().find((t=>t.identifier===e));if(t)return t;throw new Error("Unknown cryptor error")}if(e instanceof A)return this.getCryptorFromId(e.identifier)}getHeaderData(e){if(!e.metadata)return;const t=_.from(this.defaultCryptor.identifier,e.metadata),s=new Uint8Array(t.length);let n=0;return s.set(t.data,n),n+=t.length-e.metadata.byteLength,s.set(new Uint8Array(e.metadata),n),s.buffer}concatArrayBuffer(e,t){const s=new Uint8Array(e.byteLength+t.byteLength);return s.set(new Uint8Array(e),0),s.set(new Uint8Array(t),e.byteLength),s.buffer}getFileData(e){return h(this,void 0,void 0,(function*(){if(e instanceof ArrayBuffer)return e;if(e instanceof p)return e.toArrayBuffer();throw new Error("Cannot decrypt/encrypt file. In browsers file encrypt/decrypt supported for string, ArrayBuffer or Blob")}))}}j.LEGACY_IDENTIFIER="";class _{static from(e,t){if(e!==_.LEGACY_IDENTIFIER)return new A(e,t.byteLength)}static tryParse(e){const t=new Uint8Array(e);let s,n,r=null;if(t.byteLength>=4&&(s=t.slice(0,4),this.decoder.decode(s)!==_.SENTINEL))return j.LEGACY_IDENTIFIER;if(!(t.byteLength>=5))throw new Error("Decryption error: invalid header version");if(r=t[4],r>_.MAX_VERSION)throw new Error("Decryption error: Unknown cryptor error");let i=5+_.IDENTIFIER_LENGTH;if(!(t.byteLength>=i))throw new Error("Decryption error: invalid crypto identifier");n=t.slice(5,i);let o=null;if(!(t.byteLength>=i+1))throw new Error("Decryption error: invalid metadata length");return o=t[i],i+=1,255===o&&t.byteLength>=i+2&&(o=new Uint16Array(t.slice(i,i+2)).reduce(((e,t)=>(e<<8)+t),0)),new A(this.decoder.decode(n),o)}}_.SENTINEL="PNED",_.LEGACY_IDENTIFIER="",_.IDENTIFIER_LENGTH=4,_.VERSION=1,_.MAX_VERSION=1,_.decoder=new TextDecoder;class A{constructor(e,t){this._identifier=e,this._metadataLength=t}get identifier(){return this._identifier}set identifier(e){this._identifier=e}get metadataLength(){return this._metadataLength}set metadataLength(e){this._metadataLength=e}get version(){return _.VERSION}get length(){return _.SENTINEL.length+1+_.IDENTIFIER_LENGTH+(this.metadataLength<255?1:3)+this.metadataLength}get data(){let e=0;const t=new Uint8Array(this.length),s=new TextEncoder;t.set(s.encode(_.SENTINEL)),e+=_.SENTINEL.length,t[e]=this.version,e++,this.identifier&&t.set(s.encode(this.identifier),e);const n=this.metadataLength;return e+=_.IDENTIFIER_LENGTH,n<255?t[e]=n:t.set([255,n>>8,255&n],e),t}}A.IDENTIFIER_LENGTH=4,A.SENTINEL="PNED";const R=e=>encodeURIComponent(e).replace(/[!~*'()]/g,(e=>`%${e.charCodeAt(0).toString(16).toUpperCase()}`)),I=(e,t)=>{const s=e.map((e=>R(e)));return s.length?s.join(","):null!=t?t:""},U=(e,t)=>{const s=Object.fromEntries(t.map((e=>[e,!1])));return e.filter((e=>!(t.includes(e)&&!s[e])||(s[e]=!0,!1)))},T=(e,t)=>[...e].filter((s=>t.includes(s)&&e.indexOf(s)===e.lastIndexOf(s)&&t.indexOf(s)===t.lastIndexOf(s)));class F{constructor(e=!1,t){this.keepAlive=e,this.logVerbosity=t}makeSendable(e){let t,s;return e.cancellable&&(s=new AbortController,t={abortController:s,abort:()=>null==s?void 0:s.abort()}),[this.requestFromTransportRequest(e).then((t=>{const n=(new Date).getTime();this.logRequestProcessProgress(t);const r=new Promise(((t,s)=>{const n=setTimeout((()=>{clearTimeout(n),s(new Error("Request timeout"))}),1e3*e.timeout)}));return Promise.race([fetch(t,{signal:null==s?void 0:s.signal}),r]).then((e=>e.arrayBuffer().then((t=>[e,t])))).then((e=>{const s=e[1].byteLength>0?e[1]:void 0,{status:r,headers:i}=e[0],o={};i.forEach(((e,t)=>o[t]=e.toLowerCase()));const a={status:r,url:t.url,headers:o,body:s};if(r>=400)throw c.create(a);return this.logRequestProcessProgress(t,(new Date).getTime()-n,s),a})).catch((e=>{throw c.create(e)}))})),t]}request(e){return e}requestFromTransportRequest(e){return h(this,void 0,void 0,(function*(){let t,s=e.path;if(e.formData&&e.formData.length>0){e.queryParameters={};const s=e.body,n=new FormData;for(const{key:t,value:s}of e.formData)n.append(t,s);try{const e=yield s.toArrayBuffer();n.append("file",new Blob([e],{type:"application/octet-stream"}),s.name)}catch(e){try{const e=yield s.toFileUri();n.append("file",e,s.name)}catch(e){}}t=n}else e.body&&("string"==typeof e.body||e.body instanceof ArrayBuffer)&&(t=e.body);var n;return e.queryParameters&&0!==Object.keys(e.queryParameters).length&&(s=`${s}?${n=e.queryParameters,Object.keys(n).map((e=>{const t=n[e];return Array.isArray(t)?t.map((t=>`${e}=${R(t)}`)).join("&"):`${e}=${R(t)}`})).join("&")}`),new Request(`${e.origin}${s}`,{method:e.method,headers:e.headers,redirect:"follow",body:t})}))}logRequestProcessProgress(e,t,s){if(!this.logVerbosity)return;const{protocol:n,host:r,pathname:i,search:o}=new URL(e.url),a=(new Date).toISOString();if(t){const e=s?F.decoder.decode(s):void 0;console.log(">>>>>>"),console.log(`[${a} / ${t}]`,`\n${n}//${r}${i}`,`\n${o}`,`\n${e}`),console.log("-----")}else console.log("<<<<<"),console.log(`[${a}]`,`\n${n}//${r}${i}`,`\n${o}`),console.log("-----")}}function x(e){const t=e=>"object"==typeof e&&null!==e&&e.constructor===Object,s=e=>"number"==typeof e&&isFinite(e);if(!t(e))return e;const n={};return Object.keys(e).forEach((r=>{const i=(e=>"string"==typeof e||e instanceof String)(r);let o=r;const a=e[r];if(i&&r.indexOf(",")>=0){o=r.split(",").map(Number).reduce(((e,t)=>e+String.fromCharCode(t)),"")}else(s(r)||i&&!isNaN(Number(r)))&&(o=String.fromCharCode(s(r)?r:parseInt(r,10)));n[o]=t(a)?x(a):a})),n}F.decoder=new TextDecoder;const D=e=>{var t,s;return e.serviceWorkerUrl&&!("serviceWorker"in navigator)&&(e.serviceWorkerUrl=null),Object.assign(Object.assign({},(e=>{var t,s,n,r,i,a,c,u,l,h,d,p,g,y,f;const m=Object.assign({},e);if(null!==(t=m.logVerbosity)&&void 0!==t||(m.logVerbosity=!1),null!==(s=m.ssl)&&void 0!==s||(m.ssl=!0),null!==(n=m.transactionalRequestTimeout)&&void 0!==n||(m.transactionalRequestTimeout=15),null!==(r=m.subscribeRequestTimeout)&&void 0!==r||(m.subscribeRequestTimeout=310),null!==(i=m.restore)&&void 0!==i||(m.restore=!1),null!==(a=m.useInstanceId)&&void 0!==a||(m.useInstanceId=!1),null!==(c=m.suppressLeaveEvents)&&void 0!==c||(m.suppressLeaveEvents=!1),null!==(u=m.requestMessageCountThreshold)&&void 0!==u||(m.requestMessageCountThreshold=100),null!==(l=m.autoNetworkDetection)&&void 0!==l||(m.autoNetworkDetection=!1),null!==(h=m.enableEventEngine)&&void 0!==h||(m.enableEventEngine=!1),null!==(d=m.maintainPresenceState)&&void 0!==d||(m.maintainPresenceState=!0),null!==(p=m.keepAlive)&&void 0!==p||(m.keepAlive=!1),m.userId&&m.uuid)throw new o("PubNub client configuration error: use only 'userId'");if(null!==(g=m.userId)&&void 0!==g||(m.userId=m.uuid),!m.userId)throw new o("PubNub client configuration error: 'userId' not set");if(0===(null===(y=m.userId)||void 0===y?void 0:y.trim().length))throw new o("PubNub client configuration error: 'userId' is empty");m.origin||(m.origin=Array.from({length:20},((e,t)=>`ps${t+1}.pndsn.com`)));const b={subscribeKey:m.subscribeKey,publishKey:m.publishKey,secretKey:m.secretKey};void 0!==m.presenceTimeout&&m.presenceTimeout<20&&(m.presenceTimeout=20,console.log("WARNING: Presence timeout is less than the minimum. Using minimum value: ",20)),null!==(f=m.presenceTimeout)&&void 0!==f||(m.presenceTimeout=300);let v=!1,w=!0,S=5,k=!1,E=!0;return void 0!==m.dedupeOnSubscribe&&"boolean"==typeof m.dedupeOnSubscribe&&(k=m.dedupeOnSubscribe),void 0!==m.useRequestId&&"boolean"==typeof m.useRequestId&&(E=m.useRequestId),void 0!==m.announceSuccessfulHeartbeats&&"boolean"==typeof m.announceSuccessfulHeartbeats&&(v=m.announceSuccessfulHeartbeats),void 0!==m.announceFailedHeartbeats&&"boolean"==typeof m.announceFailedHeartbeats&&(w=m.announceFailedHeartbeats),void 0!==m.fileUploadPublishRetryLimit&&"number"==typeof m.fileUploadPublishRetryLimit&&(S=m.fileUploadPublishRetryLimit),Object.assign(Object.assign({},m),{keySet:b,dedupeOnSubscribe:k,maximumCacheSize:100,useRequestId:E,announceSuccessfulHeartbeats:v,announceFailedHeartbeats:w,fileUploadPublishRetryLimit:S})})(e)),{listenToBrowserNetworkEvents:null===(t=e.listenToBrowserNetworkEvents)||void 0===t||t,serviceWorkerUrl:e.serviceWorkerUrl,keepAlive:null===(s=e.keepAlive)||void 0===s||s})};var K={exports:{}}; -/*! lil-uuid - v0.1 - MIT License - https://github.com/lil-js/uuid */!function(e,t){!function(e){var t="0.1.0",s={3:/^[0-9A-F]{8}-[0-9A-F]{4}-3[0-9A-F]{3}-[0-9A-F]{4}-[0-9A-F]{12}$/i,4:/^[0-9A-F]{8}-[0-9A-F]{4}-4[0-9A-F]{3}-[89AB][0-9A-F]{3}-[0-9A-F]{12}$/i,5:/^[0-9A-F]{8}-[0-9A-F]{4}-5[0-9A-F]{3}-[89AB][0-9A-F]{3}-[0-9A-F]{12}$/i,all:/^[0-9A-F]{8}-[0-9A-F]{4}-[0-9A-F]{4}-[0-9A-F]{4}-[0-9A-F]{12}$/i};function n(){var e,t,s="";for(e=0;e<32;e++)t=16*Math.random()|0,8!==e&&12!==e&&16!==e&&20!==e||(s+="-"),s+=(12===e?4:16===e?3&t|8:t).toString(16);return s}function r(e,t){var n=s[t||"all"];return n&&n.test(e)||!1}n.isUUID=r,n.VERSION=t,e.uuid=n,e.isUUID=r}(t),null!==e&&(e.exports=t.uuid)}(K,K.exports);var q=t(K.exports),G={createUUID:()=>q.uuid?q.uuid():q()};const $=(e,t)=>{var s,n,r;null===(s=e.retryConfiguration)||void 0===s||s.validate(),null!==(n=e.useRandomIVs)&&void 0!==n||(e.useRandomIVs=true),e.origin=L(null!==(r=e.ssl)&&void 0!==r&&r,e.origin);const i=e.cryptoModule;i&&delete e.cryptoModule;const o=Object.assign(Object.assign({},e),{_pnsdkSuffix:{},_instanceId:`pn-${G.createUUID()}`,_cryptoModule:void 0,_cipherKey:void 0,_setupCryptoModule:t,get instanceId(){if(this.useInstanceId)return this._instanceId},getUserId(){return this.userId},setUserId(e){if(!e||"string"!=typeof e||0===e.trim().length)throw new Error("Missing or invalid userId parameter. Provide a valid string userId");this.userId=e},getAuthKey(){return this.authKey},setAuthKey(e){this.authKey=e},getFilterExpression(){return this.filterExpression},setFilterExpression(e){this.filterExpression=e},getCipherKey(){return this._cipherKey},setCipherKey(t){this._cipherKey=t,t||!this._cryptoModule?t&&this._setupCryptoModule&&(this._cryptoModule=this._setupCryptoModule({cipherKey:t,useRandomIVs:e.useRandomIVs,customEncrypt:this.getCustomEncrypt(),customDecrypt:this.getCustomDecrypt()})):this._cryptoModule=void 0},getCryptoModule(){return this._cryptoModule},getUseRandomIVs:()=>e.useRandomIVs,setPresenceTimeout(e){this.heartbeatInterval=e/2-1,this.presenceTimeout=e},getPresenceTimeout(){return this.presenceTimeout},getHeartbeatInterval(){return this.heartbeatInterval},setHeartbeatInterval(e){this.heartbeatInterval=e},getTransactionTimeout(){return this.transactionalRequestTimeout},getSubscribeTimeout(){return this.subscribeRequestTimeout},get PubNubFile(){return e.PubNubFile},get version(){return"8.0.1"},getVersion(){return this.version},_addPnsdkSuffix(e,t){this._pnsdkSuffix[e]=`${t}`},_getPnsdkSuffix(e){const t=Object.values(this._pnsdkSuffix).join(e);return t.length>0?e+t:""},getUUID(){return this.getUserId()},setUUID(e){this.setUserId(e)},getCustomEncrypt:()=>e.customEncrypt,getCustomDecrypt:()=>e.customDecrypt});return e.cipherKey?o.setCipherKey(e.cipherKey):i&&(o._cryptoModule=i),o},L=(e,t)=>{const s=e?"https://":"http://";return"string"==typeof t?`${s}${t}`:`${s}${t[Math.floor(Math.random()*t.length)]}`};class B{constructor(e){this.cbor=e}setToken(e){e&&e.length>0?this.token=e:this.token=void 0}getToken(){return this.token}parseToken(e){const t=this.cbor.decodeToken(e);if(void 0!==t){const e=t.res.uuid?Object.keys(t.res.uuid):[],s=Object.keys(t.res.chan),n=Object.keys(t.res.grp),r=t.pat.uuid?Object.keys(t.pat.uuid):[],i=Object.keys(t.pat.chan),o=Object.keys(t.pat.grp),a={version:t.v,timestamp:t.t,ttl:t.ttl,authorized_uuid:t.uuid,signature:t.sig},c=e.length>0,u=s.length>0,l=n.length>0;if(c||u||l){if(a.resources={},c){const s=a.resources.uuids={};e.forEach((e=>s[e]=this.extractPermissions(t.res.uuid[e])))}if(u){const e=a.resources.channels={};s.forEach((s=>e[s]=this.extractPermissions(t.res.chan[s])))}if(l){const e=a.resources.groups={};n.forEach((s=>e[s]=this.extractPermissions(t.res.grp[s])))}}const h=r.length>0,d=i.length>0,p=o.length>0;if(h||d||p){if(a.patterns={},h){const e=a.patterns.uuids={};r.forEach((s=>e[s]=this.extractPermissions(t.pat.uuid[s])))}if(d){const e=a.patterns.channels={};i.forEach((s=>e[s]=this.extractPermissions(t.pat.chan[s])))}if(p){const e=a.patterns.groups={};o.forEach((s=>e[s]=this.extractPermissions(t.pat.grp[s])))}}return t.meta&&Object.keys(t.meta).length>0&&(a.meta=t.meta),a}}extractPermissions(e){const t={read:!1,write:!1,manage:!1,delete:!1,get:!1,update:!1,join:!1};return 128&~e||(t.join=!0),64&~e||(t.update=!0),32&~e||(t.get=!0),8&~e||(t.delete=!0),4&~e||(t.manage=!0),2&~e||(t.write=!0),1&~e||(t.read=!0),t}}var H;!function(e){e.GET="GET",e.POST="POST",e.PATCH="PATCH",e.DELETE="DELETE",e.LOCAL="LOCAL"}(H||(H={}));class z{constructor(e,t,s){this.publishKey=e,this.secretKey=t,this.hasher=s}signature(e){const t=e.path.startsWith("/publish")?H.GET:e.method;let s=`${t}\n${this.publishKey}\n${e.path}\n${this.queryParameters(e.queryParameters)}\n`;if(t===H.POST||t===H.PATCH){const t=e.body;let n;t&&t instanceof ArrayBuffer?n=z.textDecoder.decode(t):t&&"object"!=typeof t&&(n=t),n&&(s+=n)}return`v2.${this.hasher(s,this.secretKey)}`.replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}queryParameters(e){return Object.keys(e).sort().map((t=>{const s=e[t];return Array.isArray(s)?s.sort().map((e=>`${t}=${R(e)}`)).join("&"):`${t}=${R(s)}`})).join("&")}}z.textDecoder=new TextDecoder("utf-8");class V{constructor(e){this.configuration=e;const{clientConfiguration:{keySet:t},shaHMAC:s}=e;t.secretKey&&s&&(this.signatureGenerator=new z(t.publishKey,t.secretKey,s))}makeSendable(e){return this.configuration.transport.makeSendable(this.request(e))}request(e){var t;const{clientConfiguration:s}=this.configuration;return(e=this.configuration.transport.request(e)).queryParameters||(e.queryParameters={}),s.useInstanceId&&(e.queryParameters.instanceid=s.instanceId),e.queryParameters.uuid||(e.queryParameters.uuid=s.userId),s.useRequestId&&(e.queryParameters.requestid=e.identifier),e.queryParameters.pnsdk=this.generatePNSDK(),null!==(t=e.origin)&&void 0!==t||(e.origin=s.origin),this.authenticateRequest(e),this.signRequest(e),e}authenticateRequest(e){var t;if(e.path.startsWith("/v2/auth/")||e.path.startsWith("/v3/pam/")||e.path.startsWith("/time"))return;const{clientConfiguration:s,tokenManager:n}=this.configuration,r=null!==(t=n.getToken())&&void 0!==t?t:s.authKey;r&&(e.queryParameters.auth=r)}signRequest(e){this.signatureGenerator&&!e.path.startsWith("/time")&&(e.queryParameters.timestamp=String(Math.floor((new Date).getTime()/1e3)),e.queryParameters.signature=this.signatureGenerator.signature(e))}generatePNSDK(){const{clientConfiguration:e}=this.configuration;if(e.sdkName)return e.sdkName;let t=`PubNub-JS-${e.sdkFamily}`;e.partnerId&&(t+=`-${e.partnerId}`),t+=`/${e.getVersion()}`;const s=e._getPnsdkSuffix(" ");return s.length>0&&(t+=s),t}}class W{constructor(){this.listeners=[]}addListener(e){this.listeners.includes(e)||this.listeners.push(e)}removeListener(e){this.listeners=this.listeners.filter((t=>t!==e))}removeAllListeners(){this.listeners=[]}announceStatus(e){this.listeners.forEach((t=>{t.status&&t.status(e)}))}announcePresence(e){this.listeners.forEach((t=>{t.presence&&t.presence(e)}))}announceMessage(e){this.listeners.forEach((t=>{t.message&&t.message(e)}))}announceSignal(e){this.listeners.forEach((t=>{t.signal&&t.signal(e)}))}announceMessageAction(e){this.listeners.forEach((t=>{t.messageAction&&t.messageAction(e)}))}announceFile(e){this.listeners.forEach((t=>{t.file&&t.file(e)}))}announceObjects(e){this.listeners.forEach((t=>{t.objects&&t.objects(e)}))}announceNetworkUp(){this.listeners.forEach((e=>{e.status&&e.status({category:i.PNNetworkUpCategory})}))}announceNetworkDown(){this.listeners.forEach((e=>{e.status&&e.status({category:i.PNNetworkDownCategory})}))}announceUser(e){this.listeners.forEach((t=>{t.user&&t.user(e)}))}announceSpace(e){this.listeners.forEach((t=>{t.space&&t.space(e)}))}announceMembership(e){this.listeners.forEach((t=>{t.membership&&t.membership(e)}))}}class J{constructor(e){this.time=e}onReconnect(e){this.callback=e}startPolling(){this.timeTimer=setInterval((()=>this.callTime()),3e3)}stopPolling(){this.timeTimer&&clearInterval(this.timeTimer),this.timeTimer=null}callTime(){this.time((e=>{e.error||(this.stopPolling(),this.callback&&this.callback())}))}}class Q{_config;hashHistory;constructor({config:e}){this.hashHistory=[],this._config=e}getKey(e){const t=(e=>{let t=0;if(0===e.length)return t;for(let s=0;s=this._config.maximumCacheSize&&this.hashHistory.shift(),this.hashHistory.push(this.getKey(e))}clearHistory(){this.hashHistory=[]}}class Y{constructor(e,t,s,n,r,i,o){this.configuration=e,this.listenerManager=t,this.eventEmitter=s,this.subscribeCall=n,this.heartbeatCall=r,this.leaveCall=i,this.reconnectionManager=new J(o),this.dedupingManager=new Q({config:this.configuration}),this.heartbeatChannelGroups={},this.heartbeatChannels={},this.presenceChannelGroups={},this.presenceChannels={},this.heartbeatTimer=null,this.presenceState={},this.pendingChannelGroupSubscriptions=new Set,this.pendingChannelSubscriptions=new Set,this.channelGroups={},this.channels={},this.currentTimetoken="0",this.lastTimetoken="0",this.storedTimetoken=null,this.subscriptionStatusAnnounced=!1,this.isOnline=!0}get subscribedChannels(){return Object.keys(this.channels)}get subscribedChannelGroups(){return Object.keys(this.channelGroups)}get abort(){return this._subscribeAbort}set abort(e){this._subscribeAbort=e}disconnect(){this.stopSubscribeLoop(),this.stopHeartbeatTimer(),this.reconnectionManager.stopPolling()}reconnect(){this.startSubscribeLoop(),this.startHeartbeatTimer()}subscribe(e){const{channels:t,channelGroups:s,timetoken:n,withPresence:r=!1,withHeartbeats:i=!1}=e;n&&(this.lastTimetoken=this.currentTimetoken,this.currentTimetoken=n),"0"!==this.currentTimetoken&&0!==this.currentTimetoken&&(this.storedTimetoken=this.currentTimetoken,this.currentTimetoken=0),null==t||t.forEach((e=>{this.pendingChannelSubscriptions.add(e),this.channels[e]={},r&&(this.presenceChannels[e]={}),(i||this.configuration.getHeartbeatInterval())&&(this.heartbeatChannels[e]={})})),null==s||s.forEach((e=>{this.pendingChannelGroupSubscriptions.add(e),this.channelGroups[e]={},r&&(this.presenceChannelGroups[e]={}),(i||this.configuration.getHeartbeatInterval())&&(this.heartbeatChannelGroups[e]={})})),this.subscriptionStatusAnnounced=!1,this.reconnect()}unsubscribe(e,t){let{channels:s,channelGroups:n}=e;const r=new Set,i=new Set;null==s||s.forEach((e=>{e in this.channels&&(delete this.channels[e],i.add(e),e in this.heartbeatChannels&&delete this.heartbeatChannels[e]),e in this.presenceState&&delete this.presenceState[e],e in this.presenceChannels&&(delete this.presenceChannels[e],i.add(e))})),null==n||n.forEach((e=>{e in this.channelGroups&&(delete this.channelGroups[e],r.add(e),e in this.heartbeatChannelGroups&&delete this.heartbeatChannelGroups[e]),e in this.presenceState&&delete this.presenceState[e],e in this.presenceChannelGroups&&(delete this.presenceChannelGroups[e],r.add(e))})),0===i.size&&0===r.size||(!1!==this.configuration.suppressLeaveEvents||t||(n=Array.from(r),s=Array.from(i),this.leaveCall({channels:s,channelGroups:n},(e=>{const{error:t}=e,r=l(e,["error"]);let i;t&&(e.errorData&&"object"==typeof e.errorData&&"message"in e.errorData&&"string"==typeof e.errorData.message?i=e.errorData.message:"message"in e&&"string"==typeof e.message&&(i=e.message)),this.listenerManager.announceStatus(Object.assign(Object.assign({},r),{error:null!=i&&i,affectedChannels:s,affectedChannelGroups:n,currentTimetoken:this.currentTimetoken,lastTimetoken:this.lastTimetoken}))}))),0===Object.keys(this.channels).length&&0===Object.keys(this.presenceChannels).length&&0===Object.keys(this.channelGroups).length&&0===Object.keys(this.presenceChannelGroups).length&&(this.lastTimetoken=0,this.currentTimetoken=0,this.storedTimetoken=null,this.region=null,this.reconnectionManager.stopPolling()),this.reconnect())}unsubscribeAll(e){this.unsubscribe({channels:this.subscribedChannels,channelGroups:this.subscribedChannelGroups},e)}startSubscribeLoop(){this.stopSubscribeLoop();const e=[...Object.keys(this.channelGroups)],t=[...Object.keys(this.channels)];Object.keys(this.presenceChannelGroups).forEach((t=>e.push(`${t}-pnpres`))),Object.keys(this.presenceChannels).forEach((e=>t.push(`${e}-pnpres`))),0===t.length&&0===e.length||this.subscribeCall({channels:t,channelGroups:e,state:this.presenceState,heartbeat:this.configuration.getPresenceTimeout(),timetoken:this.currentTimetoken,region:null!==this.region?this.region:void 0,filterExpression:this.configuration.filterExpression},((e,t)=>{this.processSubscribeResponse(e,t)}))}stopSubscribeLoop(){this._subscribeAbort&&(this._subscribeAbort(),this._subscribeAbort=null)}processSubscribeResponse(e,t){if(e.error){if("object"==typeof e.errorData&&"name"in e.errorData&&"AbortError"===e.errorData.name||e.category===i.PNCancelledCategory)return;return void(e.category===i.PNTimeoutCategory?this.startSubscribeLoop():e.category===i.PNNetworkIssuesCategory?(this.disconnect(),e.error&&this.configuration.autoNetworkDetection&&this.isOnline&&(this.isOnline=!1,this.listenerManager.announceNetworkDown()),this.reconnectionManager.onReconnect((()=>{this.configuration.autoNetworkDetection&&!this.isOnline&&(this.isOnline=!0,this.listenerManager.announceNetworkUp()),this.reconnect(),this.subscriptionStatusAnnounced=!0;const t={category:i.PNReconnectedCategory,operation:e.operation,lastTimetoken:this.lastTimetoken,currentTimetoken:this.currentTimetoken};this.listenerManager.announceStatus(t)})),this.reconnectionManager.startPolling(),this.listenerManager.announceStatus(e)):e.category===i.PNBadRequestCategory?(this.stopHeartbeatTimer(),this.listenerManager.announceStatus(e)):this.listenerManager.announceStatus(e))}if(this.storedTimetoken?(this.currentTimetoken=this.storedTimetoken,this.storedTimetoken=null):(this.lastTimetoken=this.currentTimetoken,this.currentTimetoken=t.cursor.timetoken),!this.subscriptionStatusAnnounced){const t={category:i.PNConnectedCategory,operation:e.operation,affectedChannels:Array.from(this.pendingChannelSubscriptions),subscribedChannels:this.subscribedChannels,affectedChannelGroups:Array.from(this.pendingChannelGroupSubscriptions),lastTimetoken:this.lastTimetoken,currentTimetoken:this.currentTimetoken};this.subscriptionStatusAnnounced=!0,this.listenerManager.announceStatus(t),this.pendingChannelGroupSubscriptions.clear(),this.pendingChannelSubscriptions.clear()}const{messages:s}=t,{requestMessageCountThreshold:n,dedupeOnSubscribe:r}=this.configuration;n&&s.length>=n&&this.listenerManager.announceStatus({category:i.PNRequestMessageCountExceededCategory,operation:e.operation});try{s.forEach((e=>{if(r){if(this.dedupingManager.isDuplicate(e.data))return;this.dedupingManager.addEntry(e.data)}this.eventEmitter.emitEvent(e)}))}catch(e){const t={error:!0,category:i.PNUnknownCategory,errorData:e,statusCode:0};this.listenerManager.announceStatus(t)}this.region=t.cursor.region,this.startSubscribeLoop()}setState(e){const{state:t,channels:s,channelGroups:n}=e;null==s||s.forEach((e=>e in this.channels&&(this.presenceState[e]=t))),null==n||n.forEach((e=>e in this.channelGroups&&(this.presenceState[e]=t)))}changePresence(e){const{connected:t,channels:s,channelGroups:n}=e;t?(null==s||s.forEach((e=>this.heartbeatChannels[e]={})),null==n||n.forEach((e=>this.heartbeatChannelGroups[e]={}))):(null==s||s.forEach((e=>{e in this.heartbeatChannels&&delete this.heartbeatChannels[e]})),null==n||n.forEach((e=>{e in this.heartbeatChannelGroups&&delete this.heartbeatChannelGroups[e]})),!1===this.configuration.suppressLeaveEvents&&this.leaveCall({channels:s,channelGroups:n},(e=>this.listenerManager.announceStatus(e)))),this.reconnect()}startHeartbeatTimer(){this.stopHeartbeatTimer();const e=this.configuration.getHeartbeatInterval();e&&0!==e&&(this.sendHeartbeat(),this.heartbeatTimer=setInterval((()=>this.sendHeartbeat()),1e3*e))}stopHeartbeatTimer(){this.heartbeatTimer&&(clearInterval(this.heartbeatTimer),this.heartbeatTimer=null)}sendHeartbeat(){const e=Object.keys(this.heartbeatChannelGroups),t=Object.keys(this.heartbeatChannels);0===t.length&&0===e.length||this.heartbeatCall({channels:t,channelGroups:e,heartbeat:this.configuration.getPresenceTimeout(),state:this.presenceState},(e=>{e.error&&this.configuration.announceFailedHeartbeats&&this.listenerManager.announceStatus(e),e.error&&this.configuration.autoNetworkDetection&&this.isOnline&&(this.isOnline=!1,this.disconnect(),this.listenerManager.announceNetworkDown(),this.reconnect()),!e.error&&this.configuration.announceSuccessfulHeartbeats&&this.listenerManager.announceStatus(e)}))}}class X{constructor(e,t,s){this._payload=e,this.setDefaultPayloadStructure(),this.title=t,this.body=s}get payload(){return this._payload}set title(e){this._title=e}set subtitle(e){this._subtitle=e}set body(e){this._body=e}set badge(e){this._badge=e}set sound(e){this._sound=e}setDefaultPayloadStructure(){}toObject(){return{}}}class Z extends X{constructor(){super(...arguments),this._apnsPushType="apns",this._isSilent=!1}get payload(){return this._payload}set configurations(e){e&&e.length&&(this._configurations=e)}get notification(){return this.payload.aps}get title(){return this._title}set title(e){e&&e.length&&(this.payload.aps.alert.title=e,this._title=e)}get subtitle(){return this._subtitle}set subtitle(e){e&&e.length&&(this.payload.aps.alert.subtitle=e,this._subtitle=e)}get body(){return this._body}set body(e){e&&e.length&&(this.payload.aps.alert.body=e,this._body=e)}get badge(){return this._badge}set badge(e){null!=e&&(this.payload.aps.badge=e,this._badge=e)}get sound(){return this._sound}set sound(e){e&&e.length&&(this.payload.aps.sound=e,this._sound=e)}set silent(e){this._isSilent=e}setDefaultPayloadStructure(){this.payload.aps={alert:{}}}toObject(){const e=Object.assign({},this.payload),{aps:t}=e;let{alert:s}=t;if(this._isSilent&&(t["content-available"]=1),"apns2"===this._apnsPushType){if(!this._configurations||!this._configurations.length)throw new ReferenceError("APNS2 configuration is missing");const t=[];this._configurations.forEach((e=>{t.push(this.objectFromAPNS2Configuration(e))})),t.length&&(e.pn_push=t)}return s&&Object.keys(s).length||delete t.alert,this._isSilent&&(delete t.alert,delete t.badge,delete t.sound,s={}),this._isSilent||s&&Object.keys(s).length?e:null}objectFromAPNS2Configuration(e){if(!e.targets||!e.targets.length)throw new ReferenceError("At least one APNS2 target should be provided");const{collapseId:t,expirationDate:s}=e,n={auth_method:"token",targets:e.targets.map((e=>this.objectFromAPNSTarget(e))),version:"v2"};return t&&t.length&&(n.collapse_id=t),s&&(n.expiration=s.toISOString()),n}objectFromAPNSTarget(e){if(!e.topic||!e.topic.length)throw new TypeError("Target 'topic' undefined.");const{topic:t,environment:s="development",excludedDevices:n=[]}=e,r={topic:t,environment:s};return n.length&&(r.excluded_devices=n),r}}class ee extends X{get payload(){return this._payload}get notification(){return this.payload.notification}get data(){return this.payload.data}get title(){return this._title}set title(e){e&&e.length&&(this.payload.notification.title=e,this._title=e)}get body(){return this._body}set body(e){e&&e.length&&(this.payload.notification.body=e,this._body=e)}get sound(){return this._sound}set sound(e){e&&e.length&&(this.payload.notification.sound=e,this._sound=e)}get icon(){return this._icon}set icon(e){e&&e.length&&(this.payload.notification.icon=e,this._icon=e)}get tag(){return this._tag}set tag(e){e&&e.length&&(this.payload.notification.tag=e,this._tag=e)}set silent(e){this._isSilent=e}setDefaultPayloadStructure(){this.payload.notification={},this.payload.data={}}toObject(){let e=Object.assign({},this.payload.data),t=null;const s={};if(Object.keys(this.payload).length>2){const t=l(this.payload,["notification","data"]);e=Object.assign(Object.assign({},e),t)}return this._isSilent?e.notification=this.payload.notification:t=this.payload.notification,Object.keys(e).length&&(s.data=e),t&&Object.keys(t).length&&(s.notification=t),Object.keys(s).length?s:null}}class te{constructor(e,t){this._payload={apns:{},fcm:{}},this._title=e,this._body=t,this.apns=new Z(this._payload.apns,e,t),this.fcm=new ee(this._payload.fcm,e,t)}set debugging(e){this._debugging=e}get title(){return this._title}get subtitle(){return this._subtitle}set subtitle(e){this._subtitle=e,this.apns.subtitle=e,this.fcm.subtitle=e}get body(){return this._body}get badge(){return this._badge}set badge(e){this._badge=e,this.apns.badge=e,this.fcm.badge=e}get sound(){return this._sound}set sound(e){this._sound=e,this.apns.sound=e,this.fcm.sound=e}buildPayload(e){const t={};if(e.includes("apns")||e.includes("apns2")){this.apns._apnsPushType=e.includes("apns")?"apns":"apns2";const s=this.apns.toObject();s&&Object.keys(s).length&&(t.pn_apns=s)}if(e.includes("fcm")){const e=this.fcm.toObject();e&&Object.keys(e).length&&(t.pn_gcm=e)}return Object.keys(t).length&&this._debugging&&(t.pn_debug=!0),t}}class se{constructor(e){this.params=e,this.requestIdentifier=G.createUUID(),this._cancellationController=null}get cancellationController(){return this._cancellationController}set cancellationController(e){this._cancellationController=e}abort(){this&&this.cancellationController&&this.cancellationController.abort()}operation(){throw Error("Should be implemented by subclass.")}validate(){}parse(e){return h(this,void 0,void 0,(function*(){throw Error("Should be implemented by subclass.")}))}request(){var e,t,s,n;const r={method:null!==(t=null===(e=this.params)||void 0===e?void 0:e.method)&&void 0!==t?t:H.GET,path:this.path,queryParameters:this.queryParameters,cancellable:null!==(n=null===(s=this.params)||void 0===s?void 0:s.cancellable)&&void 0!==n&&n,timeout:1e4,identifier:this.requestIdentifier},i=this.headers;if(i&&(r.headers=i),r.method===H.POST||r.method===H.PATCH){const[e,t]=[this.body,this.formData];t&&(r.formData=t),e&&(r.body=e)}return r}get headers(){}get path(){throw Error("`path` getter should be implemented by subclass.")}get queryParameters(){return{}}get formData(){}get body(){}deserializeResponse(e){const t=e.headers["content-type"];if(!t||-1===t.indexOf("javascript")&&-1===t.indexOf("json"))return;const s=se.decoder.decode(e.body);try{return JSON.parse(s)}catch(e){return void console.error("Error parsing JSON response:",e)}}}var ne;se.decoder=new TextDecoder,function(e){e.PNPublishOperation="PNPublishOperation",e.PNSignalOperation="PNSignalOperation",e.PNSubscribeOperation="PNSubscribeOperation",e.PNUnsubscribeOperation="PNUnsubscribeOperation",e.PNWhereNowOperation="PNWhereNowOperation",e.PNHereNowOperation="PNHereNowOperation",e.PNGlobalHereNowOperation="PNGlobalHereNowOperation",e.PNSetStateOperation="PNSetStateOperation",e.PNGetStateOperation="PNGetStateOperation",e.PNHeartbeatOperation="PNHeartbeatOperation",e.PNAddMessageActionOperation="PNAddActionOperation",e.PNRemoveMessageActionOperation="PNRemoveMessageActionOperation",e.PNGetMessageActionsOperation="PNGetMessageActionsOperation",e.PNTimeOperation="PNTimeOperation",e.PNHistoryOperation="PNHistoryOperation",e.PNDeleteMessagesOperation="PNDeleteMessagesOperation",e.PNFetchMessagesOperation="PNFetchMessagesOperation",e.PNMessageCounts="PNMessageCountsOperation",e.PNGetAllUUIDMetadataOperation="PNGetAllUUIDMetadataOperation",e.PNGetUUIDMetadataOperation="PNGetUUIDMetadataOperation",e.PNSetUUIDMetadataOperation="PNSetUUIDMetadataOperation",e.PNRemoveUUIDMetadataOperation="PNRemoveUUIDMetadataOperation",e.PNGetAllChannelMetadataOperation="PNGetAllChannelMetadataOperation",e.PNGetChannelMetadataOperation="PNGetChannelMetadataOperation",e.PNSetChannelMetadataOperation="PNSetChannelMetadataOperation",e.PNRemoveChannelMetadataOperation="PNRemoveChannelMetadataOperation",e.PNGetMembersOperation="PNGetMembersOperation",e.PNSetMembersOperation="PNSetMembersOperation",e.PNGetMembershipsOperation="PNGetMembershipsOperation",e.PNSetMembershipsOperation="PNSetMembershipsOperation",e.PNListFilesOperation="PNListFilesOperation",e.PNGenerateUploadUrlOperation="PNGenerateUploadUrlOperation",e.PNPublishFileOperation="PNPublishFileOperation",e.PNPublishFileMessageOperation="PNPublishFileMessageOperation",e.PNGetFileUrlOperation="PNGetFileUrlOperation",e.PNDownloadFileOperation="PNDownloadFileOperation",e.PNDeleteFileOperation="PNDeleteFileOperation",e.PNAddPushNotificationEnabledChannelsOperation="PNAddPushNotificationEnabledChannelsOperation",e.PNRemovePushNotificationEnabledChannelsOperation="PNRemovePushNotificationEnabledChannelsOperation",e.PNPushNotificationEnabledChannelsOperation="PNPushNotificationEnabledChannelsOperation",e.PNRemoveAllPushNotificationsOperation="PNRemoveAllPushNotificationsOperation",e.PNChannelGroupsOperation="PNChannelGroupsOperation",e.PNRemoveGroupOperation="PNRemoveGroupOperation",e.PNChannelsForGroupOperation="PNChannelsForGroupOperation",e.PNAddChannelsToGroupOperation="PNAddChannelsToGroupOperation",e.PNRemoveChannelsFromGroupOperation="PNRemoveChannelsFromGroupOperation",e.PNAccessManagerGrant="PNAccessManagerGrant",e.PNAccessManagerGrantToken="PNAccessManagerGrantToken",e.PNAccessManagerAudit="PNAccessManagerAudit",e.PNAccessManagerRevokeToken="PNAccessManagerRevokeToken",e.PNHandshakeOperation="PNHandshakeOperation",e.PNReceiveMessagesOperation="PNReceiveMessagesOperation"}(ne||(ne={}));var re=ne;var ie;!function(e){e[e.Presence=-2]="Presence",e[e.Message=-1]="Message",e[e.Signal=1]="Signal",e[e.AppContext=2]="AppContext",e[e.MessageAction=3]="MessageAction",e[e.Files=4]="Files"}(ie||(ie={}));class oe extends se{constructor(e){var t,s,n,r,i,o;super({cancellable:!0}),this.parameters=e,null!==(t=(r=this.parameters).withPresence)&&void 0!==t||(r.withPresence=false),null!==(s=(i=this.parameters).channelGroups)&&void 0!==s||(i.channelGroups=[]),null!==(n=(o=this.parameters).channels)&&void 0!==n||(o.channels=[])}operation(){return re.PNSubscribeOperation}validate(){const{keySet:{subscribeKey:e},channels:t,channelGroups:s}=this.parameters;return e?t||s?void 0:"`channels` and `channelGroups` both should not be empty":"Missing Subscribe Key"}parse(e){return h(this,void 0,void 0,(function*(){let t;try{const s=se.decoder.decode(e.body);t=JSON.parse(s)}catch(e){console.error("Error parsing JSON response:",e)}if(!t)throw new o("Service response error, check status for details",a("Unable to deserialize service response"));const s=t.m.map((e=>{let{e:t}=e;return null!=t||(t=e.c.endsWith("-pnpres")?ie.Presence:ie.Message),"string"==typeof e.d?t==ie.Message?{type:ie.Message,data:this.messageFromEnvelope(e)}:{type:ie.Files,data:this.fileFromEnvelope(e)}:t==ie.Message?{type:ie.Message,data:this.messageFromEnvelope(e)}:t===ie.Presence?{type:ie.Presence,data:this.presenceEventFromEnvelope(e)}:t==ie.Signal?{type:ie.Signal,data:this.signalFromEnvelope(e)}:t===ie.AppContext?{type:ie.AppContext,data:this.appContextFromEnvelope(e)}:t===ie.MessageAction?{type:ie.MessageAction,data:this.messageActionFromEnvelope(e)}:{type:ie.Files,data:this.fileFromEnvelope(e)}}));return{cursor:{timetoken:t.t.t,region:t.t.r},messages:s}}))}get headers(){return{accept:"text/javascript"}}presenceEventFromEnvelope(e){const{d:t}=e,[s,n]=this.subscriptionChannelFromEnvelope(e),r=s.replace("-pnpres",""),i=null!==n?r:null,o=null!==n?n:r;return"string"!=typeof t&&"data"in t&&(t.state=t.data,delete t.data),Object.assign({channel:r,subscription:n,actualChannel:i,subscribedChannel:o,timetoken:e.p.t},t)}messageFromEnvelope(e){const[t,s]=this.subscriptionChannelFromEnvelope(e),[n,r]=this.decryptedData(e.d),i={channel:t,subscription:s,actualChannel:null!==s?t:null,subscribedChannel:null!==s?s:t,timetoken:e.p.t,publisher:e.i,message:n};return e.u&&(i.userMetadata=e.u),r&&(i.error=r),i}signalFromEnvelope(e){const[t,s]=this.subscriptionChannelFromEnvelope(e),n={channel:t,subscription:s,timetoken:e.p.t,publisher:e.i,message:e.d};return e.u&&(n.userMetadata=e.u),n}messageActionFromEnvelope(e){const[t,s]=this.subscriptionChannelFromEnvelope(e),n=e.d;return{channel:t,subscription:s,timetoken:e.p.t,publisher:e.i,event:n.event,data:Object.assign(Object.assign({},n.data),{uuid:e.i})}}appContextFromEnvelope(e){const[t,s]=this.subscriptionChannelFromEnvelope(e),n=e.d;return{channel:t,subscription:s,timetoken:e.p.t,message:n}}fileFromEnvelope(e){const[t,s]=this.subscriptionChannelFromEnvelope(e),[n,r]=this.decryptedData(e.d);let i=r;const o={channel:t,subscription:s,timetoken:e.p.t,publisher:e.i};return e.u&&(o.userMetadata=e.u),n?"string"==typeof n?null!=i||(i="Unexpected file information payload data type."):(o.message=n.message,n.file&&(o.file={id:n.file.id,name:n.file.name,url:this.parameters.getFileUrl({id:n.file.id,name:n.file.name,channel:t})})):null!=i||(i="File information payload is missing."),i&&(o.error=i),o}subscriptionChannelFromEnvelope(e){return[e.c,void 0===e.b?e.c:e.b]}decryptedData(e){if(!this.parameters.crypto||"string"!=typeof e)return[e,void 0];let t,s;try{const s=this.parameters.crypto.decrypt(e);t=s instanceof ArrayBuffer?JSON.parse(ae.decoder.decode(s)):s}catch(e){t=null,s=`Error while decrypting message content: ${e.message}`}return[null!=t?t:e,s]}}class ae extends oe{get path(){var e;const{keySet:{subscribeKey:t},channels:s}=this.parameters;return`/v2/subscribe/${t}/${I(null!==(e=null==s?void 0:s.sort())&&void 0!==e?e:[],",")}/0`}get queryParameters(){const{channelGroups:e,filterExpression:t,heartbeat:s,state:n,timetoken:r,region:i}=this.parameters,o={};return e&&e.length>0&&(o["channel-group"]=e.sort().join(",")),t&&t.length>0&&(o["filter-expr"]=t),s&&(o.heartbeat=s),n&&Object.keys(n).length>0&&(o.state=JSON.stringify(n)),void 0!==r&&"string"==typeof r?r.length>0&&"0"!==r&&(o.tt=r):void 0!==r&&r>0&&(o.tt=r),i&&(o.tr=i),o}}class ce{constructor(e){this.listenerManager=e,this.channelListenerMap=new Map,this.groupListenerMap=new Map}emitEvent(e){if(e.type===ie.Message)this.listenerManager.announceMessage(e.data),this.announce("message",e.data,e.data.channel,e.data.subscription);else if(e.type===ie.Signal)this.listenerManager.announceSignal(e.data),this.announce("signal",e.data,e.data.channel,e.data.subscription);else if(e.type===ie.Presence)this.listenerManager.announcePresence(e.data),this.announce("presence",e.data,e.data.channel,e.data.subscription);else if(e.type===ie.AppContext){const{data:t}=e,{message:s}=t;if(this.listenerManager.announceObjects(t),this.announce("objects",t,t.channel,t.subscription),"uuid"===s.type){const{message:e,channel:n}=t,r=l(t,["message","channel"]),{event:i,type:o}=s,a=l(s,["event","type"]),c=Object.assign(Object.assign({},r),{spaceId:n,message:Object.assign(Object.assign({},a),{event:"set"===i?"updated":"removed",type:"user"})});this.listenerManager.announceUser(c),this.announce("user",c,c.spaceId,c.subscription)}else if("channel"===s.type){const{message:e,channel:n}=t,r=l(t,["message","channel"]),{event:i,type:o}=s,a=l(s,["event","type"]),c=Object.assign(Object.assign({},r),{spaceId:n,message:Object.assign(Object.assign({},a),{event:"set"===i?"updated":"removed",type:"space"})});this.listenerManager.announceSpace(c),this.announce("space",c,c.spaceId,c.subscription)}else if("membership"===s.type){const{message:e,channel:n}=t,r=l(t,["message","channel"]),{event:i,data:o}=s,a=l(s,["event","data"]),{uuid:c,channel:u}=o,h=l(o,["uuid","channel"]),d=Object.assign(Object.assign({},r),{spaceId:n,message:Object.assign(Object.assign({},a),{event:"set"===i?"updated":"removed",data:Object.assign(Object.assign({},h),{user:c,space:u})})});this.listenerManager.announceMembership(d),this.announce("membership",d,d.spaceId,d.subscription)}}else e.type===ie.MessageAction?(this.listenerManager.announceMessageAction(e.data),this.announce("messageAction",e.data,e.data.channel,e.data.subscription)):e.type===ie.Files&&(this.listenerManager.announceFile(e.data),this.announce("file",e.data,e.data.channel,e.data.subscription))}addListener(e,t,s){t&&s?(null==t||t.forEach((t=>{if(this.channelListenerMap.has(t)){const s=this.channelListenerMap.get(t);s.includes(e)||s.push(e)}else this.channelListenerMap.set(t,[e])})),null==s||s.forEach((t=>{if(this.groupListenerMap.has(t)){const s=this.groupListenerMap.get(t);s.includes(e)||s.push(e)}else this.groupListenerMap.set(t,[e])}))):this.listenerManager.addListener(e)}removeListener(e,t,s){t&&s?(null==t||t.forEach((t=>{this.channelListenerMap.has(t)&&this.channelListenerMap.set(t,this.channelListenerMap.get(t).filter((t=>t!==e)))})),null==s||s.forEach((t=>{this.groupListenerMap.has(t)&&this.groupListenerMap.set(t,this.groupListenerMap.get(t).filter((t=>t!==e)))}))):this.listenerManager.removeListener(e)}removeAllListeners(){this.listenerManager.removeAllListeners(),this.channelListenerMap.clear(),this.groupListenerMap.clear()}announce(e,t,s,n){t&&this.channelListenerMap.has(s)&&this.channelListenerMap.get(s).forEach((s=>{const n=s[e];n&&n(t)})),n&&this.groupListenerMap.has(n)&&this.groupListenerMap.get(n).forEach((s=>{const n=s[e];n&&n(t)}))}}class ue{constructor(e=!1){this.sync=e,this.listeners=new Set}subscribe(e){return this.listeners.add(e),()=>{this.listeners.delete(e)}}notify(e){const t=()=>{this.listeners.forEach((t=>{t(e)}))};this.sync?t():setTimeout(t,0)}}class le{transition(e,t){var s;if(this.transitionMap.has(t.type))return null===(s=this.transitionMap.get(t.type))||void 0===s?void 0:s(e,t)}constructor(e){this.label=e,this.transitionMap=new Map,this.enterEffects=[],this.exitEffects=[]}on(e,t){return this.transitionMap.set(e,t),this}with(e,t){return[this,e,null!=t?t:[]]}onEnter(e){return this.enterEffects.push(e),this}onExit(e){return this.exitEffects.push(e),this}}class he extends ue{describe(e){return new le(e)}start(e,t){this.currentState=e,this.currentContext=t,this.notify({type:"engineStarted",state:e,context:t})}transition(e){if(!this.currentState)throw new Error("Start the engine first");this.notify({type:"eventReceived",event:e});const t=this.currentState.transition(this.currentContext,e);if(t){const[s,n,r]=t;for(const e of this.currentState.exitEffects)this.notify({type:"invocationDispatched",invocation:e(this.currentContext)});const i=this.currentState;this.currentState=s;const o=this.currentContext;this.currentContext=n,this.notify({type:"transitionDone",fromState:i,fromContext:o,toState:s,toContext:n,event:e});for(const e of r)this.notify({type:"invocationDispatched",invocation:e});for(const e of this.currentState.enterEffects)this.notify({type:"invocationDispatched",invocation:e(this.currentContext)})}}}class de{constructor(e){this.dependencies=e,this.instances=new Map,this.handlers=new Map}on(e,t){this.handlers.set(e,t)}dispatch(e){if("CANCEL"===e.type){if(this.instances.has(e.payload)){const t=this.instances.get(e.payload);null==t||t.cancel(),this.instances.delete(e.payload)}return}const t=this.handlers.get(e.type);if(!t)throw new Error(`Unhandled invocation '${e.type}'`);const s=t(e.payload,this.dependencies);e.managed&&this.instances.set(e.type,s),s.start()}dispose(){for(const[e,t]of this.instances.entries())t.cancel(),this.instances.delete(e)}}function pe(e,t){const s=function(...s){return{type:e,payload:null==t?void 0:t(...s)}};return s.type=e,s}function ge(e,t){const s=(...s)=>({type:e,payload:t(...s),managed:!1});return s.type=e,s}function ye(e,t){const s=(...s)=>({type:e,payload:t(...s),managed:!0});return s.type=e,s.cancel={type:"CANCEL",payload:e,managed:!1},s}class fe extends Error{constructor(){super("The operation was aborted."),this.name="AbortError",Object.setPrototypeOf(this,new.target.prototype)}}class me extends ue{constructor(){super(...arguments),this._aborted=!1}get aborted(){return this._aborted}throwIfAborted(){if(this._aborted)throw new fe}abort(){this._aborted=!0,this.notify(new fe)}}class be{constructor(e,t){this.payload=e,this.dependencies=t}}class ve extends be{constructor(e,t,s){super(e,t),this.asyncFunction=s,this.abortSignal=new me}start(){this.asyncFunction(this.payload,this.abortSignal,this.dependencies).catch((e=>{}))}cancel(){this.abortSignal.abort()}}const we=e=>(t,s)=>new ve(t,s,e),Se=pe("RECONNECT",(()=>({}))),ke=pe("DISCONNECT",(()=>({}))),Ee=pe("JOINED",((e,t)=>({channels:e,groups:t}))),Oe=pe("LEFT",((e,t)=>({channels:e,groups:t}))),Ce=pe("LEFT_ALL",(()=>({}))),Ne=pe("HEARTBEAT_SUCCESS",(e=>({statusCode:e}))),Pe=pe("HEARTBEAT_FAILURE",(e=>e)),Me=pe("HEARTBEAT_GIVEUP",(()=>({}))),je=pe("TIMES_UP",(()=>({}))),_e=ge("HEARTBEAT",((e,t)=>({channels:e,groups:t}))),Ae=ge("LEAVE",((e,t)=>({channels:e,groups:t}))),Re=ge("EMIT_STATUS",(e=>e)),Ie=ye("WAIT",(()=>({}))),Ue=ye("DELAYED_HEARTBEAT",(e=>e));class Te extends de{constructor(e,t){super(t),this.on(_e.type,we(((t,s,n)=>h(this,[t,s,n],void 0,(function*(t,s,{heartbeat:n,presenceState:r,config:a}){try{yield n(Object.assign(Object.assign({channels:t.channels,channelGroups:t.groups},a.maintainPresenceState&&{state:r}),{heartbeat:a.presenceTimeout}));e.transition(Ne(200))}catch(t){if(t instanceof o){if(t.status&&t.status.category==i.PNCancelledCategory)return;return e.transition(Pe(t))}}}))))),this.on(Ae.type,we(((e,t,s)=>h(this,[e,t,s],void 0,(function*(e,t,{leave:s,config:n}){if(!n.suppressLeaveEvents)try{s({channels:e.channels,channelGroups:e.groups})}catch(e){}}))))),this.on(Ie.type,we(((t,s,n)=>h(this,[t,s,n],void 0,(function*(t,s,{heartbeatDelay:n}){return s.throwIfAborted(),yield n(),s.throwIfAborted(),e.transition(je())}))))),this.on(Ue.type,we(((t,s,n)=>h(this,[t,s,n],void 0,(function*(t,s,{heartbeat:n,retryDelay:r,presenceState:a,config:c}){if(!c.retryConfiguration||!c.retryConfiguration.shouldRetry(t.reason,t.attempts))return e.transition(Me());s.throwIfAborted(),yield r(c.retryConfiguration.getDelay(t.attempts,t.reason)),s.throwIfAborted();try{yield n(Object.assign(Object.assign({channels:t.channels,channelGroups:t.groups},c.maintainPresenceState&&{state:a}),{heartbeat:c.presenceTimeout}));return e.transition(Ne(200))}catch(t){if(t instanceof o){if(t.status&&t.status.category==i.PNCancelledCategory)return;return e.transition(Pe(t))}}}))))),this.on(Re.type,we(((e,t,s)=>h(this,[e,t,s],void 0,(function*(e,t,{emitStatus:s,config:n}){var r;n.announceFailedHeartbeats&&!0===(null===(r=null==e?void 0:e.status)||void 0===r?void 0:r.error)?s(e.status):n.announceSuccessfulHeartbeats&&200===e.statusCode&&s(Object.assign(Object.assign({},e),{operation:re.PNHeartbeatOperation,error:!1}))})))))}}const Fe=new le("HEARTBEAT_STOPPED");Fe.on(Ee.type,((e,t)=>Fe.with({channels:[...e.channels,...t.payload.channels],groups:[...e.groups,...t.payload.groups]}))),Fe.on(Oe.type,((e,t)=>Fe.with({channels:e.channels.filter((e=>!t.payload.channels.includes(e))),groups:e.groups.filter((e=>!t.payload.groups.includes(e)))}))),Fe.on(Se.type,((e,t)=>qe.with({channels:e.channels,groups:e.groups}))),Fe.on(Ce.type,((e,t)=>Ge.with(void 0)));const xe=new le("HEARTBEAT_COOLDOWN");xe.onEnter((()=>Ie())),xe.onExit((()=>Ie.cancel)),xe.on(je.type,((e,t)=>qe.with({channels:e.channels,groups:e.groups}))),xe.on(Ee.type,((e,t)=>qe.with({channels:[...e.channels,...t.payload.channels],groups:[...e.groups,...t.payload.groups]}))),xe.on(Oe.type,((e,t)=>qe.with({channels:e.channels.filter((e=>!t.payload.channels.includes(e))),groups:e.groups.filter((e=>!t.payload.groups.includes(e)))},[Ae(t.payload.channels,t.payload.groups)]))),xe.on(ke.type,(e=>Fe.with({channels:e.channels,groups:e.groups},[Ae(e.channels,e.groups)]))),xe.on(Ce.type,((e,t)=>Ge.with(void 0,[Ae(e.channels,e.groups)])));const De=new le("HEARTBEAT_FAILED");De.on(Ee.type,((e,t)=>qe.with({channels:[...e.channels,...t.payload.channels],groups:[...e.groups,...t.payload.groups]}))),De.on(Oe.type,((e,t)=>qe.with({channels:e.channels.filter((e=>!t.payload.channels.includes(e))),groups:e.groups.filter((e=>!t.payload.groups.includes(e)))},[Ae(t.payload.channels,t.payload.groups)]))),De.on(Se.type,((e,t)=>qe.with({channels:e.channels,groups:e.groups}))),De.on(ke.type,((e,t)=>Fe.with({channels:e.channels,groups:e.groups},[Ae(e.channels,e.groups)]))),De.on(Ce.type,((e,t)=>Ge.with(void 0,[Ae(e.channels,e.groups)])));const Ke=new le("HEARBEAT_RECONNECTING");Ke.onEnter((e=>Ue(e))),Ke.onExit((()=>Ue.cancel)),Ke.on(Ee.type,((e,t)=>qe.with({channels:[...e.channels,...t.payload.channels],groups:[...e.groups,...t.payload.groups]}))),Ke.on(Oe.type,((e,t)=>qe.with({channels:e.channels.filter((e=>!t.payload.channels.includes(e))),groups:e.groups.filter((e=>!t.payload.groups.includes(e)))},[Ae(t.payload.channels,t.payload.groups)]))),Ke.on(ke.type,((e,t)=>{Fe.with({channels:e.channels,groups:e.groups},[Ae(e.channels,e.groups)])})),Ke.on(Ne.type,((e,t)=>xe.with({channels:e.channels,groups:e.groups}))),Ke.on(Pe.type,((e,t)=>Ke.with(Object.assign(Object.assign({},e),{attempts:e.attempts+1,reason:t.payload})))),Ke.on(Me.type,((e,t)=>De.with({channels:e.channels,groups:e.groups}))),Ke.on(Ce.type,((e,t)=>Ge.with(void 0,[Ae(e.channels,e.groups)])));const qe=new le("HEARTBEATING");qe.onEnter((e=>_e(e.channels,e.groups))),qe.on(Ne.type,((e,t)=>xe.with({channels:e.channels,groups:e.groups}))),qe.on(Ee.type,((e,t)=>qe.with({channels:[...e.channels,...t.payload.channels],groups:[...e.groups,...t.payload.groups]}))),qe.on(Oe.type,((e,t)=>qe.with({channels:e.channels.filter((e=>!t.payload.channels.includes(e))),groups:e.groups.filter((e=>!t.payload.groups.includes(e)))},[Ae(t.payload.channels,t.payload.groups)]))),qe.on(Pe.type,((e,t)=>Ke.with(Object.assign(Object.assign({},e),{attempts:0,reason:t.payload})))),qe.on(ke.type,(e=>Fe.with({channels:e.channels,groups:e.groups},[Ae(e.channels,e.groups)]))),qe.on(Ce.type,((e,t)=>Ge.with(void 0,[Ae(e.channels,e.groups)])));const Ge=new le("HEARTBEAT_INACTIVE");Ge.on(Ee.type,((e,t)=>qe.with({channels:t.payload.channels,groups:t.payload.groups})));class $e{get _engine(){return this.engine}constructor(e){this.dependencies=e,this.engine=new he,this.channels=[],this.groups=[],this.dispatcher=new Te(this.engine,e),this._unsubscribeEngine=this.engine.subscribe((e=>{"invocationDispatched"===e.type&&this.dispatcher.dispatch(e.invocation)})),this.engine.start(Ge,void 0)}join({channels:e,groups:t}){this.channels=[...this.channels,...null!=e?e:[]],this.groups=[...this.groups,...null!=t?t:[]],this.engine.transition(Ee(this.channels.slice(0),this.groups.slice(0)))}leave({channels:e,groups:t}){this.dependencies.presenceState&&(null==e||e.forEach((e=>delete this.dependencies.presenceState[e])),null==t||t.forEach((e=>delete this.dependencies.presenceState[e]))),this.engine.transition(Oe(null!=e?e:[],null!=t?t:[]))}leaveAll(){this.engine.transition(Ce())}dispose(){this._unsubscribeEngine(),this.dispatcher.dispose()}}class Le{static LinearRetryPolicy(e){return{delay:e.delay,maximumRetry:e.maximumRetry,shouldRetry(e,t){var s;return 403!==(null===(s=null==e?void 0:e.status)||void 0===s?void 0:s.statusCode)&&this.maximumRetry>t},getDelay(e,t){var s;return 1e3*((null!==(s=t.retryAfter)&&void 0!==s?s:this.delay)+Math.random())},getGiveupReason(e,t){var s;return this.maximumRetry<=t?"retry attempts exhaused.":403===(null===(s=null==e?void 0:e.status)||void 0===s?void 0:s.statusCode)?"forbidden operation.":"unknown error"},validate(){if(this.maximumRetry>10)throw new Error("Maximum retry for linear retry policy can not be more than 10")}}}static ExponentialRetryPolicy(e){return{minimumDelay:e.minimumDelay,maximumDelay:e.maximumDelay,maximumRetry:e.maximumRetry,shouldRetry(e,t){var s;return 403!==(null===(s=null==e?void 0:e.status)||void 0===s?void 0:s.statusCode)&&this.maximumRetry>t},getDelay(e,t){var s;return 1e3*((null!==(s=t.retryAfter)&&void 0!==s?s:Math.min(Math.pow(2,e),this.maximumDelay))+Math.random())},getGiveupReason(e,t){var s;return this.maximumRetry<=t?"retry attempts exhausted.":403===(null===(s=null==e?void 0:e.status)||void 0===s?void 0:s.statusCode)?"forbidden operation.":"unknown error"},validate(){if(this.minimumDelay<2)throw new Error("Minimum delay can not be set less than 2 seconds for retry");if(this.maximumDelay)throw new Error("Maximum delay can not be set more than 150 seconds for retry");if(this.maximumRetry>6)throw new Error("Maximum retry for exponential retry policy can not be more than 6")}}}}const Be=ye("HANDSHAKE",((e,t)=>({channels:e,groups:t}))),He=ye("RECEIVE_MESSAGES",((e,t,s)=>({channels:e,groups:t,cursor:s}))),ze=ge("EMIT_MESSAGES",(e=>e)),Ve=ge("EMIT_STATUS",(e=>e)),We=ye("RECEIVE_RECONNECT",(e=>e)),Je=ye("HANDSHAKE_RECONNECT",(e=>e)),Qe=pe("SUBSCRIPTION_CHANGED",((e,t)=>({channels:e,groups:t}))),Ye=pe("SUBSCRIPTION_RESTORED",((e,t,s,n)=>({channels:e,groups:t,cursor:{timetoken:s,region:null!=n?n:0}}))),Xe=pe("HANDSHAKE_SUCCESS",(e=>e)),Ze=pe("HANDSHAKE_FAILURE",(e=>e)),et=pe("HANDSHAKE_RECONNECT_SUCCESS",(e=>({cursor:e}))),tt=pe("HANDSHAKE_RECONNECT_FAILURE",(e=>e)),st=pe("HANDSHAKE_RECONNECT_GIVEUP",(e=>e)),nt=pe("RECEIVE_SUCCESS",((e,t)=>({cursor:e,events:t}))),rt=pe("RECEIVE_FAILURE",(e=>e)),it=pe("RECEIVE_RECONNECT_SUCCESS",((e,t)=>({cursor:e,events:t}))),ot=pe("RECEIVE_RECONNECT_FAILURE",(e=>e)),at=pe("RECEIVING_RECONNECT_GIVEUP",(e=>e)),ct=pe("DISCONNECT",(()=>({}))),ut=pe("RECONNECT",((e,t)=>({cursor:{timetoken:null!=e?e:"",region:null!=t?t:0}}))),lt=pe("UNSUBSCRIBE_ALL",(()=>({})));class ht extends de{constructor(e,t){super(t),this.on(Be.type,we(((t,s,n)=>h(this,[t,s,n],void 0,(function*(t,s,{handshake:n,presenceState:r,config:a}){s.throwIfAborted();try{const i=yield n(Object.assign({abortSignal:s,channels:t.channels,channelGroups:t.groups,filterExpression:a.filterExpression},a.maintainPresenceState&&{state:r}));return e.transition(Xe(i))}catch(t){if(t instanceof o){if(t.status&&t.status.category==i.PNCancelledCategory)return;return e.transition(Ze(t))}}}))))),this.on(He.type,we(((t,s,n)=>h(this,[t,s,n],void 0,(function*(t,s,{receiveMessages:n,config:r}){s.throwIfAborted();try{const i=yield n({abortSignal:s,channels:t.channels,channelGroups:t.groups,timetoken:t.cursor.timetoken,region:t.cursor.region,filterExpression:r.filterExpression});e.transition(nt(i.cursor,i.messages))}catch(t){if(t instanceof o){if(t.status&&t.status.category==i.PNCancelledCategory)return;if(!s.aborted)return e.transition(rt(t))}}}))))),this.on(ze.type,we(((e,t,s)=>h(this,[e,t,s],void 0,(function*(e,t,{emitMessages:s}){e.length>0&&s(e)}))))),this.on(Ve.type,we(((e,t,s)=>h(this,[e,t,s],void 0,(function*(e,t,{emitStatus:s}){s(e)}))))),this.on(We.type,we(((t,s,n)=>h(this,[t,s,n],void 0,(function*(t,s,{receiveMessages:n,delay:r,config:a}){if(!a.retryConfiguration||!a.retryConfiguration.shouldRetry(t.reason,t.attempts))return e.transition(at(new o(a.retryConfiguration?a.retryConfiguration.getGiveupReason(t.reason,t.attempts):"Unable to complete subscribe messages receive.")));s.throwIfAborted(),yield r(a.retryConfiguration.getDelay(t.attempts,t.reason)),s.throwIfAborted();try{const r=yield n({abortSignal:s,channels:t.channels,channelGroups:t.groups,timetoken:t.cursor.timetoken,region:t.cursor.region,filterExpression:a.filterExpression});return e.transition(it(r.cursor,r.messages))}catch(t){if(t instanceof o){if(t.status&&t.status.category==i.PNCancelledCategory)return;return e.transition(ot(t))}}}))))),this.on(Je.type,we(((t,s,n)=>h(this,[t,s,n],void 0,(function*(t,s,{handshake:n,delay:r,presenceState:a,config:c}){if(!c.retryConfiguration||!c.retryConfiguration.shouldRetry(t.reason,t.attempts))return e.transition(st(new o(c.retryConfiguration?c.retryConfiguration.getGiveupReason(t.reason,t.attempts):"Unable to complete subscribe handshake")));s.throwIfAborted(),yield r(c.retryConfiguration.getDelay(t.attempts,t.reason)),s.throwIfAborted();try{const r=yield n(Object.assign({abortSignal:s,channels:t.channels,channelGroups:t.groups,filterExpression:c.filterExpression},c.maintainPresenceState&&{state:a}));return e.transition(et(r))}catch(t){if(t instanceof o){if(t.status&&t.status.category==i.PNCancelledCategory)return;return e.transition(tt(t))}}})))))}}const dt=new le("HANDSHAKE_FAILED");dt.on(Qe.type,((e,t)=>vt.with({channels:t.payload.channels,groups:t.payload.groups,cursor:e.cursor}))),dt.on(ut.type,((e,t)=>vt.with({channels:e.channels,groups:e.groups,cursor:t.payload.cursor||e.cursor}))),dt.on(Ye.type,((e,t)=>{var s,n;return vt.with({channels:t.payload.channels,groups:t.payload.groups,cursor:{timetoken:t.payload.cursor.timetoken,region:t.payload.cursor.region?t.payload.cursor.region:null!==(n=null===(s=null==e?void 0:e.cursor)||void 0===s?void 0:s.region)&&void 0!==n?n:0}})})),dt.on(lt.type,(e=>wt.with()));const pt=new le("HANDSHAKE_STOPPED");pt.on(Qe.type,((e,t)=>pt.with({channels:t.payload.channels,groups:t.payload.groups,cursor:e.cursor}))),pt.on(ut.type,((e,t)=>vt.with(Object.assign(Object.assign({},e),{cursor:t.payload.cursor||e.cursor})))),pt.on(Ye.type,((e,t)=>{var s;return pt.with({channels:t.payload.channels,groups:t.payload.groups,cursor:{timetoken:t.payload.cursor.timetoken,region:t.payload.cursor.region||(null===(s=null==e?void 0:e.cursor)||void 0===s?void 0:s.region)||0}})})),pt.on(lt.type,(e=>wt.with()));const gt=new le("RECEIVE_FAILED");gt.on(ut.type,((e,t)=>{var s;return vt.with({channels:e.channels,groups:e.groups,cursor:{timetoken:t.payload.cursor.timetoken?null===(s=t.payload.cursor)||void 0===s?void 0:s.timetoken:e.cursor.timetoken,region:t.payload.cursor.region||e.cursor.region}})})),gt.on(Qe.type,((e,t)=>vt.with({channels:t.payload.channels,groups:t.payload.groups,cursor:e.cursor}))),gt.on(Ye.type,((e,t)=>vt.with({channels:t.payload.channels,groups:t.payload.groups,cursor:{timetoken:t.payload.cursor.timetoken,region:t.payload.cursor.region||e.cursor.region}}))),gt.on(lt.type,(e=>wt.with(void 0)));const yt=new le("RECEIVE_STOPPED");yt.on(Qe.type,((e,t)=>yt.with({channels:t.payload.channels,groups:t.payload.groups,cursor:e.cursor}))),yt.on(Ye.type,((e,t)=>yt.with({channels:t.payload.channels,groups:t.payload.groups,cursor:{timetoken:t.payload.cursor.timetoken,region:t.payload.cursor.region||e.cursor.region}}))),yt.on(ut.type,((e,t)=>{var s;return vt.with({channels:e.channels,groups:e.groups,cursor:{timetoken:t.payload.cursor.timetoken?null===(s=t.payload.cursor)||void 0===s?void 0:s.timetoken:e.cursor.timetoken,region:t.payload.cursor.region||e.cursor.region}})})),yt.on(lt.type,(()=>wt.with(void 0)));const ft=new le("RECEIVE_RECONNECTING");ft.onEnter((e=>We(e))),ft.onExit((()=>We.cancel)),ft.on(it.type,((e,t)=>mt.with({channels:e.channels,groups:e.groups,cursor:t.payload.cursor},[ze(t.payload.events)]))),ft.on(ot.type,((e,t)=>ft.with(Object.assign(Object.assign({},e),{attempts:e.attempts+1,reason:t.payload})))),ft.on(at.type,((e,t)=>{var s;return gt.with({groups:e.groups,channels:e.channels,cursor:e.cursor,reason:t.payload},[Ve({category:i.PNDisconnectedUnexpectedlyCategory,error:null===(s=t.payload)||void 0===s?void 0:s.message})])})),ft.on(ct.type,(e=>yt.with({channels:e.channels,groups:e.groups,cursor:e.cursor},[Ve({category:i.PNDisconnectedCategory})]))),ft.on(Ye.type,((e,t)=>mt.with({channels:t.payload.channels,groups:t.payload.groups,cursor:{timetoken:t.payload.cursor.timetoken,region:t.payload.cursor.region||e.cursor.region}}))),ft.on(Qe.type,((e,t)=>mt.with({channels:t.payload.channels,groups:t.payload.groups,cursor:e.cursor}))),ft.on(lt.type,(e=>wt.with(void 0,[Ve({category:i.PNDisconnectedCategory})])));const mt=new le("RECEIVING");mt.onEnter((e=>He(e.channels,e.groups,e.cursor))),mt.onExit((()=>He.cancel)),mt.on(nt.type,((e,t)=>mt.with({channels:e.channels,groups:e.groups,cursor:t.payload.cursor},[ze(t.payload.events)]))),mt.on(Qe.type,((e,t)=>0===t.payload.channels.length&&0===t.payload.groups.length?wt.with(void 0):mt.with({cursor:e.cursor,channels:t.payload.channels,groups:t.payload.groups}))),mt.on(Ye.type,((e,t)=>0===t.payload.channels.length&&0===t.payload.groups.length?wt.with(void 0):mt.with({channels:t.payload.channels,groups:t.payload.groups,cursor:{timetoken:t.payload.cursor.timetoken,region:t.payload.cursor.region||e.cursor.region}}))),mt.on(rt.type,((e,t)=>ft.with(Object.assign(Object.assign({},e),{attempts:0,reason:t.payload})))),mt.on(ct.type,(e=>yt.with({channels:e.channels,groups:e.groups,cursor:e.cursor},[Ve({category:i.PNDisconnectedCategory})]))),mt.on(lt.type,(e=>wt.with(void 0,[Ve({category:i.PNDisconnectedCategory})])));const bt=new le("HANDSHAKE_RECONNECTING");bt.onEnter((e=>Je(e))),bt.onExit((()=>Je.cancel)),bt.on(et.type,((e,t)=>{var s,n;const r={timetoken:(null===(s=e.cursor)||void 0===s?void 0:s.timetoken)?null===(n=e.cursor)||void 0===n?void 0:n.timetoken:t.payload.cursor.timetoken,region:t.payload.cursor.region};return mt.with({channels:e.channels,groups:e.groups,cursor:r},[Ve({category:i.PNConnectedCategory})])})),bt.on(tt.type,((e,t)=>bt.with(Object.assign(Object.assign({},e),{attempts:e.attempts+1,reason:t.payload})))),bt.on(st.type,((e,t)=>{var s;return dt.with({groups:e.groups,channels:e.channels,cursor:e.cursor,reason:t.payload},[Ve({category:i.PNConnectionErrorCategory,error:null===(s=t.payload)||void 0===s?void 0:s.message})])})),bt.on(ct.type,(e=>pt.with({channels:e.channels,groups:e.groups,cursor:e.cursor}))),bt.on(Qe.type,((e,t)=>vt.with({channels:t.payload.channels,groups:t.payload.groups,cursor:e.cursor}))),bt.on(Ye.type,((e,t)=>{var s,n;return vt.with({channels:t.payload.channels,groups:t.payload.groups,cursor:{timetoken:t.payload.cursor.timetoken,region:(null===(s=t.payload.cursor)||void 0===s?void 0:s.region)||(null===(n=null==e?void 0:e.cursor)||void 0===n?void 0:n.region)||0}})})),bt.on(lt.type,(e=>wt.with(void 0)));const vt=new le("HANDSHAKING");vt.onEnter((e=>Be(e.channels,e.groups))),vt.onExit((()=>Be.cancel)),vt.on(Qe.type,((e,t)=>0===t.payload.channels.length&&0===t.payload.groups.length?wt.with(void 0):vt.with({channels:t.payload.channels,groups:t.payload.groups,cursor:e.cursor}))),vt.on(Xe.type,((e,t)=>{var s,n;return mt.with({channels:e.channels,groups:e.groups,cursor:{timetoken:(null===(s=null==e?void 0:e.cursor)||void 0===s?void 0:s.timetoken)?null===(n=null==e?void 0:e.cursor)||void 0===n?void 0:n.timetoken:t.payload.timetoken,region:t.payload.region}},[Ve({category:i.PNConnectedCategory})])})),vt.on(Ze.type,((e,t)=>bt.with({channels:e.channels,groups:e.groups,cursor:e.cursor,attempts:0,reason:t.payload}))),vt.on(ct.type,(e=>pt.with({channels:e.channels,groups:e.groups,cursor:e.cursor}))),vt.on(Ye.type,((e,t)=>{var s;return vt.with({channels:t.payload.channels,groups:t.payload.groups,cursor:{timetoken:t.payload.cursor.timetoken,region:t.payload.cursor.region||(null===(s=null==e?void 0:e.cursor)||void 0===s?void 0:s.region)||0}})})),vt.on(lt.type,(e=>wt.with()));const wt=new le("UNSUBSCRIBED");wt.on(Qe.type,((e,t)=>vt.with({channels:t.payload.channels,groups:t.payload.groups}))),wt.on(Ye.type,((e,t)=>vt.with({channels:t.payload.channels,groups:t.payload.groups,cursor:t.payload.cursor})));class St{get _engine(){return this.engine}constructor(e){this.engine=new he,this.channels=[],this.groups=[],this.dependencies=e,this.dispatcher=new ht(this.engine,e),this._unsubscribeEngine=this.engine.subscribe((e=>{"invocationDispatched"===e.type&&this.dispatcher.dispatch(e.invocation)})),this.engine.start(wt,void 0)}subscribe({channels:e,channelGroups:t,timetoken:s,withPresence:n}){this.channels=[...this.channels,...null!=e?e:[]],this.groups=[...this.groups,...null!=t?t:[]],n&&(this.channels.map((e=>this.channels.push(`${e}-pnpres`))),this.groups.map((e=>this.groups.push(`${e}-pnpres`)))),s?this.engine.transition(Ye(Array.from(new Set([...this.channels,...null!=e?e:[]])),Array.from(new Set([...this.groups,...null!=t?t:[]])),s)):this.engine.transition(Qe(Array.from(new Set([...this.channels,...null!=e?e:[]])),Array.from(new Set([...this.groups,...null!=t?t:[]])))),this.dependencies.join&&this.dependencies.join({channels:Array.from(new Set(this.channels.filter((e=>!e.endsWith("-pnpres"))))),groups:Array.from(new Set(this.groups.filter((e=>!e.endsWith("-pnpres")))))})}unsubscribe({channels:e=[],channelGroups:t=[]}){const s=U(this.channels,[...e,...e.map((e=>`${e}-pnpres`))]),n=U(this.groups,[...t,...t.map((e=>`${e}-pnpres`))]);if(new Set(this.channels).size!==new Set(s).size||new Set(this.groups).size!==new Set(n).size){const r=T(this.channels,e),i=T(this.groups,t);this.dependencies.presenceState&&(null==r||r.forEach((e=>delete this.dependencies.presenceState[e])),null==i||i.forEach((e=>delete this.dependencies.presenceState[e]))),this.channels=s,this.groups=n,this.engine.transition(Qe(Array.from(new Set(this.channels.slice(0))),Array.from(new Set(this.groups.slice(0))))),this.dependencies.leave&&this.dependencies.leave({channels:r.slice(0),groups:i.slice(0)})}}unsubscribeAll(){this.channels=[],this.groups=[],this.dependencies.presenceState&&Object.keys(this.dependencies.presenceState).forEach((e=>{delete this.dependencies.presenceState[e]})),this.engine.transition(Qe(this.channels.slice(0),this.groups.slice(0))),this.dependencies.leaveAll&&this.dependencies.leaveAll()}reconnect({timetoken:e,region:t}){this.engine.transition(ut(e,t))}disconnect(){this.engine.transition(ct()),this.dependencies.leaveAll&&this.dependencies.leaveAll()}getSubscribedChannels(){return Array.from(new Set(this.channels.slice(0)))}getSubscribedChannelGroups(){return Array.from(new Set(this.groups.slice(0)))}dispose(){this.disconnect(),this._unsubscribeEngine(),this.dispatcher.dispose()}}class kt extends se{constructor(e){var t,s;super({method:e.sendByPost?H.POST:H.GET}),this.parameters=e,null!==(t=(s=this.parameters).sendByPost)&&void 0!==t||(s.sendByPost=false)}operation(){return re.PNPublishOperation}validate(){const{message:e,channel:t,keySet:{publishKey:s}}=this.parameters;return t?e?s?void 0:"Missing 'publishKey'":"Missing 'message'":"Missing 'channel'"}parse(e){return h(this,void 0,void 0,(function*(){const t=this.deserializeResponse(e);if(!t)throw new o("Service response error, check status for details",a("Unable to deserialize service response"));return{timetoken:t[2]}}))}get path(){const{message:e,channel:t,keySet:s}=this.parameters,n=this.prepareMessagePayload(e);return`/publish/${s.publishKey}/${s.subscribeKey}/0/${R(t)}/0${this.parameters.sendByPost?"":`/${R(n)}`}`}get queryParameters(){const{meta:e,replicate:t,storeInHistory:s,ttl:n}=this.parameters,r={};return void 0!==s&&(r.store=s?"1":"0"),void 0!==n&&(r.ttl=n),void 0===t||t||(r.norep="true"),e&&"object"==typeof e&&(r.meta=JSON.stringify(e)),r}get headers(){return{"Content-Type":"application/json"}}get body(){return this.prepareMessagePayload(this.parameters.message)}prepareMessagePayload(e){const{crypto:t}=this.parameters;if(!t)return JSON.stringify(e)||"";const s=t.encrypt(JSON.stringify(e));return JSON.stringify("string"==typeof s?s:y(s))}}class Et extends se{constructor(e){super(),this.parameters=e}operation(){return re.PNSignalOperation}validate(){const{message:e,channel:t,keySet:{publishKey:s}}=this.parameters;return t?e?s?void 0:"Missing 'publishKey'":"Missing 'message'":"Missing 'channel'"}parse(e){return h(this,void 0,void 0,(function*(){const t=this.deserializeResponse(e);if(!t)throw new o("Service response error, check status for details",a("Unable to deserialize service response"));return{timetoken:t[2]}}))}get path(){const{keySet:{publishKey:e,subscribeKey:t},channel:s,message:n}=this.parameters,r=JSON.stringify(n);return`/signal/${e}/${t}/0/${R(s)}/0/${R(r)}`}}class Ot extends oe{operation(){return re.PNReceiveMessagesOperation}validate(){const e=super.validate();return e||(this.parameters.timetoken?this.parameters.region?void 0:"region can not be empty":"timetoken can not be empty")}get path(){const{keySet:{subscribeKey:e},channels:t=[]}=this.parameters;return`/v2/subscribe/${e}/${I(t.sort(),",")}/0`}get queryParameters(){const{channelGroups:e,filterExpression:t,timetoken:s,region:n}=this.parameters,r={ee:""};return e&&e.length>0&&(r["channel-group"]=e.sort().join(",")),t&&t.length>0&&(r["filter-expr"]=t),"string"==typeof s?s&&s.length>0&&(r.tt=s):s&&s>0&&(r.tt=s),n&&(r.tr=n),r}}class Ct extends oe{operation(){return re.PNHandshakeOperation}get path(){const{keySet:{subscribeKey:e},channels:t=[]}=this.parameters;return`/v2/subscribe/${e}/${I(t.sort(),",")}/0`}get queryParameters(){const{channelGroups:e,filterExpression:t,state:s}=this.parameters,n={tt:0,ee:""};return e&&e.length>0&&(n["channel-group"]=e.sort().join(",")),t&&t.length>0&&(n["filter-expr"]=t),s&&Object.keys(s).length>0&&(n.state=JSON.stringify(s)),n}}class Nt extends se{constructor(e){var t,s,n,r;super(),this.parameters=e,null!==(t=(n=this.parameters).channels)&&void 0!==t||(n.channels=[]),null!==(s=(r=this.parameters).channelGroups)&&void 0!==s||(r.channelGroups=[])}operation(){return re.PNGetStateOperation}validate(){const{keySet:{subscribeKey:e},channels:t,channelGroups:s}=this.parameters;if(!e)return"Missing Subscribe Key"}parse(e){return h(this,void 0,void 0,(function*(){const t=this.deserializeResponse(e);if(!t)throw new o("Service response error, check status for details",a("Unable to deserialize service response"));if(t.status>=400)throw c.create(e);const{channels:s=[],channelGroups:n=[]}=this.parameters,r={channels:{}};return 1===s.length&&0===n.length?r.channels[s[0]]=t.payload:r.channels=t.payload,r}))}get path(){const{keySet:{subscribeKey:e},uuid:t,channels:s}=this.parameters;return`/v2/presence/sub-key/${e}/channel/${I(null!=s?s:[],",")}/uuid/${t}`}get queryParameters(){const{channelGroups:e}=this.parameters;return e&&0!==e.length?{"channel-group":e.join(",")}:{}}}class Pt extends se{constructor(e){super(),this.parameters=e}operation(){return re.PNSetStateOperation}validate(){const{keySet:{subscribeKey:e},state:t,channels:s=[],channelGroups:n=[]}=this.parameters;return e?t?0===(null==s?void 0:s.length)&&0===(null==n?void 0:n.length)?"Please provide a list of channels and/or channel-groups":void 0:"Missing State":"Missing Subscribe Key"}parse(e){return h(this,void 0,void 0,(function*(){const t=this.deserializeResponse(e);if(!t)throw new o("Service response error, check status for details",a("Unable to deserialize service response"));if(t.status>=400)throw c.create(e);return{state:t.payload}}))}get path(){const{keySet:{subscribeKey:e},uuid:t,channels:s}=this.parameters;return`/v2/presence/sub-key/${e}/channel/${I(null!=s?s:[],",")}/uuid/${R(t)}/data`}get queryParameters(){const{channelGroups:e,state:t}=this.parameters,s={state:JSON.stringify(t)};return e&&0!==e.length&&(s["channel-group"]=e.join(",")),s}}class Mt extends se{constructor(e){super(),this.parameters=e}operation(){return re.PNHeartbeatOperation}validate(){const{keySet:{subscribeKey:e},channels:t=[],channelGroups:s=[]}=this.parameters;return e?0===t.length&&0===s.length?"Please provide a list of channels and/or channel-groups":void 0:"Missing Subscribe Key"}parse(e){return h(this,void 0,void 0,(function*(){const t=this.deserializeResponse(e);if(!t)throw new o("Service response error, check status for details",a("Unable to deserialize service response"));if(t.status>=400)throw c.create(e);return{}}))}get path(){const{keySet:{subscribeKey:e},channels:t}=this.parameters;return`/v2/presence/sub-key/${e}/channel/${I(null!=t?t:[],",")}/heartbeat`}get queryParameters(){const{channelGroups:e,state:t,heartbeat:s}=this.parameters,n={heartbeat:`${s}`};return e&&0!==e.length&&(n["channel-group"]=e.join(",")),t&&(n.state=JSON.stringify(t)),n}}class jt extends se{constructor(e){super(),this.parameters=e,this.parameters.channelGroups&&(this.parameters.channelGroups=Array.from(new Set(this.parameters.channelGroups))),this.parameters.channels&&(this.parameters.channels=Array.from(new Set(this.parameters.channels)))}operation(){return re.PNUnsubscribeOperation}validate(){const{keySet:{subscribeKey:e},channels:t=[],channelGroups:s=[]}=this.parameters;return e?0===t.length&&0===s.length?"At least one `channel` or `channel group` should be provided.":void 0:"Missing Subscribe Key"}parse(e){return h(this,void 0,void 0,(function*(){const t=this.deserializeResponse(e);if(!t)throw new o("Service response error, check status for details",a("Unable to deserialize service response"));if(t.status>=400)throw c.create(e);return{}}))}get path(){var e;const{keySet:{subscribeKey:t},channels:s}=this.parameters;return`/v2/presence/sub-key/${t}/channel/${I(null!==(e=null==s?void 0:s.sort())&&void 0!==e?e:[],",")}/leave`}get queryParameters(){const{channelGroups:e}=this.parameters;return e&&0!==e.length?{"channel-group":e.sort().join(",")}:{}}}class _t extends se{constructor(e){super(),this.parameters=e}operation(){return re.PNWhereNowOperation}validate(){if(!this.parameters.keySet.subscribeKey)return"Missing Subscribe Key"}parse(e){return h(this,void 0,void 0,(function*(){const t=this.deserializeResponse(e);if(!t)throw new o("Service response error, check status for details",a("Unable to deserialize service response"));if(t.status>=400)throw c.create(e);return t.payload?{channels:t.payload.channels}:{channels:[]}}))}get path(){const{keySet:{subscribeKey:e},uuid:t}=this.parameters;return`/v2/presence/sub-key/${e}/uuid/${R(t)}`}}class At extends se{constructor(e){var t,s,n,r,i,o;super(),this.parameters=e,null!==(t=(r=this.parameters).queryParameters)&&void 0!==t||(r.queryParameters={}),null!==(s=(i=this.parameters).includeUUIDs)&&void 0!==s||(i.includeUUIDs=true),null!==(n=(o=this.parameters).includeState)&&void 0!==n||(o.includeState=false)}operation(){const{channels:e=[],channelGroups:t=[]}=this.parameters;return 0===e.length&&0===t.length?re.PNGlobalHereNowOperation:re.PNHereNowOperation}validate(){if(!this.parameters.keySet.subscribeKey)return"Missing Subscribe Key"}parse(e){return h(this,void 0,void 0,(function*(){var t,s;const n=this.deserializeResponse(e);if(!n)throw new o("Service response error, check status for details",a("Unable to deserialize service response"));if(n.status>=400)throw c.create(e);const r="occupancy"in n?1:n.payload.total_channels,i="occupancy"in n?n.occupancy:n.payload.total_channels,u={};let l={};if("occupancy"in n){const e=this.parameters.channels[0];l[e]={uuids:null!==(t=n.uuids)&&void 0!==t?t:[],occupancy:i}}else l=null!==(s=n.payload.channels)&&void 0!==s?s:{};return Object.keys(l).forEach((e=>{const t=l[e];u[e]={occupants:this.parameters.includeUUIDs?t.uuids.map((e=>"string"==typeof e?{uuid:e,state:null}:e)):[],name:e,occupancy:t.occupancy}})),{totalChannels:r,totalOccupancy:i,channels:u}}))}get path(){const{keySet:{subscribeKey:e},channels:t,channelGroups:s}=this.parameters;let n=`/v2/presence/sub-key/${e}`;return(t&&t.length>0||s&&s.length>0)&&(n+=`/channel/${I(null!=t?t:[],",")}`),n}get queryParameters(){const{channelGroups:e,includeUUIDs:t,includeState:s,queryParameters:n}=this.parameters;return Object.assign(Object.assign(Object.assign(Object.assign({},t?{}:{disable_uuids:"1"}),null!=s&&s?{state:"1"}:{}),e&&e.length>0?{"channel-group":e.join(",")}:{}),n)}}class Rt extends se{constructor(e){super({method:H.DELETE}),this.parameters=e}operation(){return re.PNDeleteMessagesOperation}validate(){return this.parameters.keySet.subscribeKey?this.parameters.channel?void 0:"Missing channel":"Missing Subscribe Key"}parse(e){return h(this,void 0,void 0,(function*(){const t=this.deserializeResponse(e);if(!t)throw new o("Service response error, check status for details",a("Unable to deserialize service response"));if(t.status>=400)throw c.create(e);return{}}))}get path(){const{keySet:{subscribeKey:e},channel:t}=this.parameters;return`/v3/history/sub-key/${e}/channel/${R(t)}`}get queryParameters(){const{start:e,end:t}=this.parameters;return Object.assign(Object.assign({},e?{start:e}:{}),t?{end:t}:{})}}class It extends se{constructor(e){super(),this.parameters=e}operation(){return re.PNMessageCounts}validate(){const{keySet:{subscribeKey:e},channels:t,timetoken:s,channelTimetokens:n}=this.parameters;return e?t?s&&n?"`timetoken` and `channelTimetokens` are incompatible together":s||n?n&&n.length>1&&n.length!==t.length?"Length of `channelTimetokens` and `channels` do not match":void 0:"`timetoken` or `channelTimetokens` need to be set":"Missing channels":"Missing Subscribe Key"}parse(e){return h(this,void 0,void 0,(function*(){const t=this.deserializeResponse(e);if(!t)throw new o("Service response error, check status for details",a("Unable to deserialize service response"));if(t.status>=400)throw c.create(e);return{channels:t.channels}}))}get path(){return`/v3/history/sub-key/${this.parameters.keySet.subscribeKey}/message-counts/${I(this.parameters.channels)}`}get queryParameters(){let{channelTimetokens:e}=this.parameters;return this.parameters.timetoken&&(e=[this.parameters.timetoken]),Object.assign(Object.assign({},1===e.length?{timetoken:e[0]}:{}),e.length>1?{channelsTimetoken:e.join(",")}:{})}}class Ut extends se{constructor(e){var t,s,n;super(),this.parameters=e,e.count?e.count=Math.min(e.count,100):e.count=100,null!==(t=e.stringifiedTimeToken)&&void 0!==t||(e.stringifiedTimeToken=false),null!==(s=e.includeMeta)&&void 0!==s||(e.includeMeta=false),null!==(n=e.logVerbosity)&&void 0!==n||(e.logVerbosity=false)}operation(){return re.PNHistoryOperation}validate(){return this.parameters.keySet.subscribeKey?this.parameters.channel?void 0:"Missing channel":"Missing Subscribe Key"}parse(e){return h(this,void 0,void 0,(function*(){const t=this.deserializeResponse(e);if(!t)throw new o("Service response error, check status for details",a("Unable to deserialize service response"));const s=t[0],n=t[1],r=t[2];return Array.isArray(s)?{messages:s.map((e=>{const t=this.processPayload(e.message),s={entry:t.payload,timetoken:e.timetoken};return t.error&&(s.error=t.error),e.meta&&(s.meta=e.meta),s})),startTimeToken:n,endTimeToken:r}:{messages:[],startTimeToken:n,endTimeToken:r}}))}get path(){const{keySet:{subscribeKey:e},channel:t}=this.parameters;return`/v2/history/sub-key/${e}/channel/${R(t)}`}get queryParameters(){const{start:e,end:t,reverse:s,count:n,stringifiedTimeToken:r,includeMeta:i}=this.parameters;return Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({count:n,include_token:"true"},e?{start:e}:{}),t?{end:t}:{}),r?{string_message_token:"true"}:{}),null!=s?{reverse:s.toString()}:{}),i?{include_meta:"true"}:{})}processPayload(e){const{crypto:t,logVerbosity:s}=this.parameters;if(!t||"string"!=typeof e)return{payload:e};let n,r;try{const s=t.decrypt(e);n=s instanceof ArrayBuffer?JSON.parse(Ut.decoder.decode(s)):s}catch(t){s&&console.log("decryption error",t.message),n=e,r=`Error while decrypting message content: ${t.message}`}return{payload:n,error:r}}}var Tt;!function(e){e[e.Message=-1]="Message",e[e.Files=4]="Files"}(Tt||(Tt={}));class Ft extends se{constructor(e){var t,s,n,r,i;super(),this.parameters=e;const o=null!==(t=e.includeMessageActions)&&void 0!==t&&t,a=e.channels.length>1||o?25:100;e.count?e.count=Math.min(e.count,a):e.count=a,e.includeUuid?e.includeUUID=e.includeUuid:null!==(s=e.includeUUID)&&void 0!==s||(e.includeUUID=true),null!==(n=e.stringifiedTimeToken)&&void 0!==n||(e.stringifiedTimeToken=false),null!==(r=e.includeMessageType)&&void 0!==r||(e.includeMessageType=true),null!==(i=e.logVerbosity)&&void 0!==i||(e.logVerbosity=false)}operation(){return re.PNFetchMessagesOperation}validate(){const{keySet:{subscribeKey:e},channels:t,includeMessageActions:s}=this.parameters;return e?t?void 0!==s&&s&&t.length>1?"History can return actions data for a single channel only. Either pass a single channel or disable the includeMessageActions flag.":void 0:"Missing channels":"Missing Subscribe Key"}parse(e){return h(this,void 0,void 0,(function*(){var t;const s=this.deserializeResponse(e);if(!s)throw new o("Service response error, check status for details",a("Unable to deserialize service response"));if(s.status>=400)throw c.create(e);const n=null!==(t=s.channels)&&void 0!==t?t:{},r={};return Object.keys(n).forEach((e=>{r[e]=n[e].map((t=>{null===t.message_type&&(t.message_type=Tt.Message);const s=this.processPayload(e,t),n={channel:e,timetoken:t.timetoken,message:s.payload,messageType:t.message_type,uuid:t.uuid};if(t.actions){const e=n;e.actions=t.actions,e.data=t.actions}return t.meta&&(n.meta=t.meta),s.error&&(n.error=s.error),n}))})),s.more?{channels:r,more:s.more}:{channels:r}}))}get path(){const{keySet:{subscribeKey:e},channels:t,includeMessageActions:s}=this.parameters;return`/v3/${s?"history-with-actions":"history"}/sub-key/${e}/channel/${I(t)}`}get queryParameters(){const{start:e,end:t,count:s,includeMessageType:n,includeMeta:r,includeUUID:i,stringifiedTimeToken:o}=this.parameters;return Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({max:s},e?{start:e}:{}),t?{end:t}:{}),o?{string_message_token:"true"}:{}),void 0!==r&&r?{include_meta:"true"}:{}),i?{include_uuid:"true"}:{}),n?{include_message_type:"true"}:{})}processPayload(e,t){const{crypto:s,logVerbosity:n}=this.parameters;if(!s||"string"!=typeof t.message)return{payload:t.message};let r,i;try{const e=s.decrypt(t.message);r=e instanceof ArrayBuffer?JSON.parse(Ft.decoder.decode(e)):e}catch(e){n&&console.log("decryption error",e.message),r=t.message,i=`Error while decrypting message content: ${e.message}`}if(!i&&r&&t.message_type==Tt.Files&&"object"==typeof r&&this.isFileMessage(r)){const t=r;return{payload:{message:t.message,file:Object.assign(Object.assign({},t.file),{url:this.parameters.getFileUrl({channel:e,id:t.file.id,name:t.file.name})})},error:i}}return{payload:r,error:i}}isFileMessage(e){return void 0!==e.file}}class xt extends se{constructor(e){super(),this.parameters=e}operation(){return re.PNGetMessageActionsOperation}validate(){return this.parameters.keySet.subscribeKey?this.parameters.channel?void 0:"Missing message channel":"Missing Subscribe Key"}parse(e){return h(this,void 0,void 0,(function*(){const t=this.deserializeResponse(e);if(!t)throw new o("Service response error, check status for details",a("Unable to deserialize service response"));if(t.status>=400)throw c.create(e);let s=null,n=null;return t.data.length>0&&(s=t.data[0].actionTimetoken,n=t.data[t.data.length-1].actionTimetoken),{data:t.data,more:t.more,start:s,end:n}}))}get path(){const{keySet:{subscribeKey:e},channel:t}=this.parameters;return`/v1/message-actions/${e}/channel/${R(t)}`}get queryParameters(){const{limit:e,start:t,end:s}=this.parameters;return Object.assign(Object.assign(Object.assign({},t?{start:t}:{}),s?{end:s}:{}),e?{limit:e}:{})}}class Dt extends se{constructor(e){super({method:H.POST}),this.parameters=e}operation(){return re.PNAddMessageActionOperation}validate(){const{keySet:{subscribeKey:e},action:t,channel:s,messageTimetoken:n}=this.parameters;return e?s?n?t?t.value?t.type?t.type.length>15?"Action.type value exceed maximum length of 15":void 0:"Missing Action.type":"Missing Action.value":"Missing Action":"Missing message timetoken":"Missing message channel":"Missing Subscribe Key"}parse(e){return h(this,void 0,void 0,(function*(){const t=this.deserializeResponse(e);if(!t)throw new o("Service response error, check status for details",a("Unable to deserialize service response"));if(t.status>=400)throw c.create(e);return{data:t.data}}))}get headers(){return{"Content-Type":"application/json"}}get path(){const{keySet:{subscribeKey:e},channel:t,messageTimetoken:s}=this.parameters;return`/v1/message-actions/${e}/channel/${R(t)}/message/${s}`}get body(){return JSON.stringify(this.parameters.action)}}class Kt extends se{constructor(e){super({method:H.DELETE}),this.parameters=e}operation(){return re.PNRemoveMessageActionOperation}validate(){const{keySet:{subscribeKey:e},channel:t,messageTimetoken:s,actionTimetoken:n}=this.parameters;return e?t?s?n?void 0:"Missing action timetoken":"Missing message timetoken":"Missing message action channel":"Missing Subscribe Key"}parse(e){return h(this,void 0,void 0,(function*(){const t=this.deserializeResponse(e);if(!t)throw new o("Service response error, check status for details",a("Unable to deserialize service response"));if(t.status>=400)throw c.create(e);return{data:t.data}}))}get path(){const{keySet:{subscribeKey:e},channel:t,actionTimetoken:s,messageTimetoken:n}=this.parameters;return`/v1/message-actions/${e}/channel/${R(t)}/message/${n}/action/${s}`}}class qt extends se{constructor(e){var t,s;super(),this.parameters=e,null!==(t=(s=this.parameters).storeInHistory)&&void 0!==t||(s.storeInHistory=true)}operation(){return re.PNPublishFileMessageOperation}validate(){const{channel:e,fileId:t,fileName:s}=this.parameters;return e?t?s?void 0:"file name can't be empty":"file id can't be empty":"channel can't be empty"}parse(e){return h(this,void 0,void 0,(function*(){const t=this.deserializeResponse(e);if(!t)throw new o("Service response error, check status for details",a("Unable to deserialize service response"));return{timetoken:t[2]}}))}get path(){const{message:e,channel:t,keySet:{publishKey:s,subscribeKey:n},fileId:r,fileName:i}=this.parameters,o=Object.assign({file:{name:i,id:r}},e?{message:e}:{});return`/v1/files/publish-file/${s}/${n}/0/${R(t)}/0/${R(this.prepareMessagePayload(o))}`}get queryParameters(){const{storeInHistory:e,ttl:t,meta:s}=this.parameters;return Object.assign(Object.assign({store:e?"1":"0"},t?{ttl:t}:{}),s&&"object"==typeof s?{meta:JSON.stringify(s)}:{})}prepareMessagePayload(e){const{crypto:t}=this.parameters;if(!t)return JSON.stringify(e)||"";const s=t.encrypt(JSON.stringify(e));return JSON.stringify("string"==typeof s?s:y(s))}}class Gt extends se{constructor(e){super({method:H.LOCAL}),this.parameters=e}operation(){return re.PNGetFileUrlOperation}validate(){const{channel:e,id:t,name:s}=this.parameters;return e?t?s?void 0:"file name can't be empty":"file id can't be empty":"channel can't be empty"}parse(e){return h(this,void 0,void 0,(function*(){return e.url}))}get path(){const{channel:e,id:t,name:s,keySet:{subscribeKey:n}}=this.parameters;return`/v1/files/${n}/channels/${R(e)}/files/${t}/${s}`}}class $t extends se{constructor(e){super({method:H.DELETE}),this.parameters=e}operation(){return re.PNDeleteFileOperation}validate(){const{channel:e,id:t,name:s}=this.parameters;return e?t?s?void 0:"file name can't be empty":"file id can't be empty":"channel can't be empty"}parse(e){return h(this,void 0,void 0,(function*(){const t=this.deserializeResponse(e);if(!t)throw new o("Service response error, check status for details",a("Unable to deserialize service response"));if(t.status>=400)throw c.create(e);return t}))}get path(){const{keySet:{subscribeKey:e},id:t,channel:s,name:n}=this.parameters;return`/v1/files/${e}/channels/${R(s)}/files/${t}/${n}`}}class Lt extends se{constructor(e){var t,s;super(),this.parameters=e,null!==(t=(s=this.parameters).limit)&&void 0!==t||(s.limit=100)}operation(){return re.PNListFilesOperation}validate(){if(!this.parameters.channel)return"channel can't be empty"}parse(e){return h(this,void 0,void 0,(function*(){const t=this.deserializeResponse(e);if(!t)throw new o("Service response error, check status for details",a("Unable to deserialize service response"));if(t.status>=400)throw c.create(e);return t}))}get path(){const{keySet:{subscribeKey:e},channel:t}=this.parameters;return`/v1/files/${e}/channels/${R(t)}/files`}get queryParameters(){const{limit:e,next:t}=this.parameters;return Object.assign({limit:e},t?{next:t}:{})}}class Bt extends se{constructor(e){super({method:H.POST}),this.parameters=e}operation(){return re.PNGenerateUploadUrlOperation}validate(){return this.parameters.channel?this.parameters.name?void 0:"'name' can't be empty":"channel can't be empty"}parse(e){return h(this,void 0,void 0,(function*(){const t=this.deserializeResponse(e);if(!t)throw new o("Service response error, check status for details",a("Unable to deserialize service response"));if(t.status>=400)throw c.create(e);return{id:t.data.id,name:t.data.name,url:t.file_upload_request.url,formFields:t.file_upload_request.form_fields}}))}get path(){const{keySet:{subscribeKey:e},channel:t}=this.parameters;return`/v1/files/${e}/channels/${R(t)}/generate-upload-url`}get body(){return JSON.stringify({name:this.parameters.name})}}class Ht extends se{constructor(e){super({method:H.POST}),this.parameters=e;const t=e.file.mimeType;t&&(e.formFields=e.formFields.map((e=>"Content-Type"===e.name?{name:e.name,value:t}:e)))}operation(){return re.PNPublishFileOperation}validate(){const{fileId:e,fileName:t,file:s,uploadUrl:n}=this.parameters;return e?t?s?n?void 0:"Validation failed: file upload 'url' can't be empty":"Validation failed: 'file' can't be empty":"Validation failed: file 'name' can't be empty":"Validation failed: file 'id' can't be empty"}parse(e){return h(this,void 0,void 0,(function*(){return{status:e.status,message:e.body?Ht.decoder.decode(e.body):"OK"}}))}request(){return Object.assign(Object.assign({},super.request()),{origin:new URL(this.parameters.uploadUrl).origin,timeout:300})}get path(){const{pathname:e,search:t}=new URL(this.parameters.uploadUrl);return`${e}${t}`}get body(){return this.parameters.file}get formData(){return this.parameters.formFields}}class zt{constructor(e){var t;if(this.parameters=e,this.file=null===(t=this.parameters.PubNubFile)||void 0===t?void 0:t.create(e.file),!this.file)throw new Error("File upload error: unable to create File object.")}process(){return h(this,void 0,void 0,(function*(){let e,t;return this.generateFileUploadUrl().then((s=>(e=s.name,t=s.id,this.uploadFile(s)))).then((e=>{if(204!==e.status)throw new o("Upload to bucket was unsuccessful",{error:!0,statusCode:e.status,category:i.PNUnknownCategory,operation:re.PNPublishFileOperation,errorData:{message:e.message}})})).then((()=>this.publishFileMessage(t,e))).catch((e=>{if(e instanceof o)throw e;const t=e instanceof c?e:c.create(e);throw new o("File upload error.",t.toStatus(re.PNPublishFileOperation))}))}))}generateFileUploadUrl(){return h(this,void 0,void 0,(function*(){const e=new Bt(Object.assign(Object.assign({},this.parameters),{name:this.file.name,keySet:this.parameters.keySet}));return this.parameters.sendRequest(e)}))}uploadFile(e){return h(this,void 0,void 0,(function*(){const{cipherKey:t,PubNubFile:s,crypto:n,cryptography:r}=this.parameters,{id:i,name:o,url:a,formFields:c}=e;return this.parameters.PubNubFile.supportsEncryptFile&&(!t&&n?this.file=yield n.encryptFile(this.file,s):t&&r&&(this.file=yield r.encryptFile(t,this.file,s))),this.parameters.sendRequest(new Ht({fileId:i,fileName:o,file:this.file,uploadUrl:a,formFields:c}))}))}publishFileMessage(e,t){return h(this,void 0,void 0,(function*(){var s,n,r,a;let c,u={timetoken:"0"},l=this.parameters.fileUploadPublishRetryLimit,h=!1;do{try{u=yield this.parameters.publishFile(Object.assign(Object.assign({},this.parameters),{fileId:e,fileName:t})),h=!0}catch(e){e instanceof o&&(c=e),l-=1}}while(!h&&l>0);if(h)return{status:200,timetoken:u.timetoken,id:e,name:t};throw new o("Publish failed. You may want to execute that operation manually using pubnub.publishFile",{error:!0,category:null!==(n=null===(s=c.status)||void 0===s?void 0:s.category)&&void 0!==n?n:i.PNUnknownCategory,statusCode:null!==(a=null===(r=c.status)||void 0===r?void 0:r.statusCode)&&void 0!==a?a:0,channel:this.parameters.channel,id:e,name:t})}))}}class Vt extends se{constructor(e){super({method:H.DELETE}),this.parameters=e}operation(){return re.PNAccessManagerRevokeToken}validate(){return this.parameters.keySet.secretKey?this.parameters.token?void 0:"token can't be empty":"Missing Secret Key"}parse(e){return h(this,void 0,void 0,(function*(){const t=this.deserializeResponse(e);if(!t)throw new o("Service response error, check status for details",a("Unable to deserialize service response"));if(t.status>=400)throw c.create(e);return{}}))}get path(){const{keySet:{subscribeKey:e},token:t}=this.parameters;return`/v3/pam/${e}/grant/${R(t)}`}}class Wt extends se{constructor(e){var t,s,n,r;super({method:H.POST}),this.parameters=e,null!==(t=(n=this.parameters).resources)&&void 0!==t||(n.resources={}),null!==(s=(r=this.parameters).patterns)&&void 0!==s||(r.patterns={})}operation(){return re.PNAccessManagerGrantToken}validate(){var e,t,s,n,r,i;const{keySet:{subscribeKey:o,publishKey:a,secretKey:c},resources:u,patterns:l}=this.parameters;if(!o)return"Missing Subscribe Key";if(!a)return"Missing Publish Key";if(!c)return"Missing Secret Key";if(!u&&!l)return"Missing either Resources or Patterns";if(this.isVspPermissions(this.parameters)&&("channels"in(null!==(e=this.parameters.resources)&&void 0!==e?e:{})||"uuids"in(null!==(t=this.parameters.resources)&&void 0!==t?t:{})||"groups"in(null!==(s=this.parameters.resources)&&void 0!==s?s:{})||"channels"in(null!==(n=this.parameters.patterns)&&void 0!==n?n:{})||"uuids"in(null!==(r=this.parameters.patterns)&&void 0!==r?r:{})||"groups"in(null!==(i=this.parameters.patterns)&&void 0!==i?i:{})))return"Cannot mix `users`, `spaces` and `authorizedUserId` with `uuids`, `channels`, `groups` and `authorized_uuid`";let h=!0;return[this.parameters.resources,this.parameters.patterns].forEach((e=>{Object.keys(null!=e?e:{}).forEach((t=>{var s;e&&h&&Object.keys(null!==(s=e[t])&&void 0!==s?s:{}).length>0&&(h=!1)}))})),h?"Missing values for either Resources or Patterns":void 0}parse(e){return h(this,void 0,void 0,(function*(){const t=this.deserializeResponse(e);if(!t)throw new o("Service response error, check status for details",a("Unable to deserialize service response"));if(t.status>=400)throw c.create(e);return t.data.token}))}get path(){return`/v3/pam/${this.parameters.keySet.subscribeKey}/grant`}get body(){const{ttl:e,meta:t}=this.parameters,s=Object.assign({},e||0===e?{ttl:e}:{}),n=this.isVspPermissions(this.parameters)?this.parameters.authorizedUserId:this.parameters.authorized_uuid,r={},i={},o={},a=(e,t,s,n)=>{n[s]||(n[s]={}),n[s][e]=t},{resources:c,patterns:u}=this.parameters;return[c,u].forEach(((e,t)=>{var s,n,r,c,u;const l=0===t?i:o;let h={},d={},p={};l.channels||(l.channels={}),l.groups||(l.groups={}),l.uuids||(l.uuids={}),l.users||(l.users={}),l.spaces||(l.spaces={}),e&&("spaces"in e||"users"in e?(h=null!==(s=e.spaces)&&void 0!==s?s:{},p=null!==(n=e.users)&&void 0!==n?n:{}):("channels"in e||"uuids"in e||"groups"in e)&&(h=null!==(r=e.channels)&&void 0!==r?r:{},d=null!==(c=e.groups)&&void 0!==c?c:{},p=null!==(u=e.uuids)&&void 0!==u?u:{})),Object.keys(h).forEach((e=>a(e,this.extractPermissions(h[e]),"channels",l))),Object.keys(d).forEach((e=>a(e,this.extractPermissions(d[e]),"groups",l))),Object.keys(p).forEach((e=>a(e,this.extractPermissions(p[e]),"uuids",l)))})),n&&(r.uuid=`${n}`),r.resources=i,r.patterns=o,r.meta=null!=t?t:{},s.permissions=r,JSON.stringify(s)}extractPermissions(e){let t=0;return"join"in e&&e.join&&(t|=128),"update"in e&&e.update&&(t|=64),"get"in e&&e.get&&(t|=32),"delete"in e&&e.delete&&(t|=8),"manage"in e&&e.manage&&(t|=4),"write"in e&&e.write&&(t|=2),"read"in e&&e.read&&(t|=1),t}isVspPermissions(e){var t,s,n,r;return"authorizedUserId"in e||"spaces"in(null!==(t=e.resources)&&void 0!==t?t:{})||"users"in(null!==(s=e.resources)&&void 0!==s?s:{})||"spaces"in(null!==(n=e.patterns)&&void 0!==n?n:{})||"users"in(null!==(r=e.patterns)&&void 0!==r?r:{})}}class Jt extends se{constructor(e){var t,s,n,r,i,o,a,c,u,l,h,d,p,g,y,f,m,b,v,w;super(),this.parameters=e,null!==(t=(h=this.parameters).channels)&&void 0!==t||(h.channels=[]),null!==(s=(d=this.parameters).channelGroups)&&void 0!==s||(d.channelGroups=[]),null!==(n=(p=this.parameters).uuids)&&void 0!==n||(p.uuids=[]),null!==(r=(g=this.parameters).read)&&void 0!==r||(g.read=false),null!==(i=(y=this.parameters).write)&&void 0!==i||(y.write=false),null!==(o=(f=this.parameters).delete)&&void 0!==o||(f.delete=false),null!==(a=(m=this.parameters).get)&&void 0!==a||(m.get=false),null!==(c=(b=this.parameters).update)&&void 0!==c||(b.update=false),null!==(u=(v=this.parameters).manage)&&void 0!==u||(v.manage=false),null!==(l=(w=this.parameters).join)&&void 0!==l||(w.join=false)}operation(){return re.PNAccessManagerGrant}validate(){const{keySet:{subscribeKey:e,publishKey:t,secretKey:s},uuids:n=[],channels:r=[],channelGroups:i=[],authKeys:o=[]}=this.parameters;return e?t?s?0!==n.length&&0===o.length?"authKeys are required for grant request on uuids":!n.length||0===r.length&&0===i.length?void 0:"Both channel/channel group and uuid cannot be used in the same request":"Missing Secret Key":"Missing Publish Key":"Missing Subscribe Key"}parse(e){return h(this,void 0,void 0,(function*(){const t=this.deserializeResponse(e);if(!t)throw new o("Service response error, check status for details",a("Unable to deserialize service response"));if(t.status>=400)throw c.create(e);return t.payload}))}get path(){return`/v2/auth/grant/sub-key/${this.parameters.keySet.subscribeKey}`}get queryParameters(){const{channels:e,channelGroups:t,authKeys:s,uuids:n,read:r,write:i,manage:o,delete:a,get:c,join:u,update:l,ttl:h}=this.parameters;return Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},e&&(null==e?void 0:e.length)>0?{channel:e.join(",")}:{}),t&&(null==t?void 0:t.length)>0?{"channel-group":t.join(",")}:{}),s&&(null==s?void 0:s.length)>0?{auth:s.join(",")}:{}),n&&(null==n?void 0:n.length)>0?{"target-uuid":n.join(",")}:{}),{r:r?"1":"0",w:i?"1":"0",m:o?"1":"0",d:a?"1":"0",g:c?"1":"0",j:u?"1":"0",u:l?"1":"0"}),h||0===h?{ttl:h}:{})}}const Qt=[];class Yt extends se{constructor(e){var t,s;super(),this.parameters=e,null!==(t=(s=this.parameters).authKeys)&&void 0!==t||(s.authKeys=Qt)}operation(){return re.PNAccessManagerAudit}validate(){if(!this.parameters.keySet.subscribeKey)return"Missing Subscribe Key"}parse(e){return h(this,void 0,void 0,(function*(){const t=this.deserializeResponse(e);if(!t)throw new o("Service response error, check status for details",a("Unable to deserialize service response"));if(t.status>=400)throw c.create(e);return t.payload}))}get path(){return`/v2/auth/audit/sub-key/${this.parameters.keySet.subscribeKey}`}get queryParameters(){const{channel:e,channelGroup:t,authKeys:s}=this.parameters;return Object.assign(Object.assign(Object.assign({},e?{channel:e}:{}),t?{"channel-group":t}:{}),s&&s.length?{auth:s.join(",")}:{})}}class Xt{subscribe(){var e,t;this.pubnub.subscribe(Object.assign({channels:this.channelNames,channelGroups:this.groupNames},(null===(t=null===(e=this.options)||void 0===e?void 0:e.cursor)||void 0===t?void 0:t.timetoken)&&{timetoken:this.options.cursor.timetoken}))}unsubscribe(){this.pubnub.unsubscribe({channels:this.channelNames.filter((e=>!e.endsWith("-pnpres"))),channelGroups:this.groupNames.filter((e=>!e.endsWith("-pnpres")))})}set onMessage(e){this.listener.message=e}set onPresence(e){this.listener.presence=e}set onSignal(e){this.listener.signal=e}set onObjects(e){this.listener.objects=e}set onMessageAction(e){this.listener.messageAction=e}set onFile(e){this.listener.file=e}addListener(e){this.eventEmitter.addListener(e,this.channelNames.filter((e=>!e.endsWith("-pnpres"))),this.groupNames.filter((e=>!e.endsWith("-pnpres"))))}removeListener(e){this.eventEmitter.removeListener(e,this.channelNames,this.groupNames)}get channels(){return this.channelNames.slice(0)}get channelGroups(){return this.groupNames.slice(0)}}class Zt extends Xt{constructor({channels:e=[],channelGroups:t=[],subscriptionOptions:s,eventEmitter:n,pubnub:r}){super(),this.channelNames=[],this.groupNames=[],this.subscriptionList=[],this.options=s,this.eventEmitter=n,this.pubnub=r,e.filter((e=>!e.endsWith("-pnpres"))).forEach((e=>{const t=this.pubnub.channel(e).subscription(this.options);this.channelNames=[...this.channelNames,...t.channels],this.subscriptionList.push(t)})),t.filter((e=>!e.endsWith("-pnpres"))).forEach((e=>{const t=this.pubnub.channelGroup(e).subscription(this.options);this.groupNames=[...this.groupNames,...t.channelGroups],this.subscriptionList.push(t)})),this.listener={},n.addListener(this.listener,this.channelNames.filter((e=>!e.endsWith("-pnpres"))),this.groupNames.filter((e=>!e.endsWith("-pnpres"))))}addSubscription(e){this.subscriptionList.push(e),this.channelNames=[...this.channelNames,...e.channels],this.groupNames=[...this.groupNames,...e.channelGroups],this.eventEmitter.addListener(this.listener,e.channels,e.channelGroups)}removeSubscription(e){const t=e.channels,s=e.channelGroups;this.channelNames=this.channelNames.filter((e=>!t.includes(e))),this.groupNames=this.groupNames.filter((e=>!s.includes(e))),this.subscriptionList=this.subscriptionList.filter((t=>t!==e)),this.eventEmitter.removeListener(this.listener,t,s)}addSubscriptionSet(e){this.subscriptionList=[...this.subscriptionList,...e.subscriptions],this.channelNames=[...this.channelNames,...e.channels],this.groupNames=[...this.groupNames,...e.channelGroups],this.eventEmitter.addListener(this.listener,e.channels,e.channelGroups)}removeSubscriptionSet(e){const t=e.channels,s=e.channelGroups;this.channelNames=this.channelNames.filter((e=>!t.includes(e))),this.groupNames=this.groupNames.filter((e=>!s.includes(e))),this.subscriptionList=this.subscriptionList.filter((t=>!e.subscriptions.includes(t))),this.eventEmitter.removeListener(this.listener,t,s)}get subscriptions(){return this.subscriptionList.slice(0)}}class es extends Xt{constructor({channels:e,channelGroups:t,subscriptionOptions:s,eventEmitter:n,pubnub:r}){super(),this.channelNames=[],this.groupNames=[],this.channelNames=e,this.groupNames=t,this.options=s,this.pubnub=r,this.eventEmitter=n,this.listener={},n.addListener(this.listener,this.channelNames.filter((e=>!e.endsWith("-pnpres"))),this.groupNames.filter((e=>!e.endsWith("-pnpres"))))}addSubscription(e){return new Zt({channels:[...this.channelNames,...e.channels],channelGroups:[...this.groupNames,...e.channelGroups],subscriptionOptions:Object.assign(Object.assign({},this.options),null==e?void 0:e.options),eventEmitter:this.eventEmitter,pubnub:this.pubnub})}}class ts{constructor(e,t,s){this.id=e,this.eventEmitter=t,this.pubnub=s}subscription(e){return new es({channels:[this.id],channelGroups:[],subscriptionOptions:e,eventEmitter:this.eventEmitter,pubnub:this.pubnub})}}class ss{constructor(e,t,s){this.eventEmitter=t,this.pubnub=s,this.name=e}subscription(e){return new es({channels:[],channelGroups:(null==e?void 0:e.receivePresenceEvents)?[this.name,`${this.name}-pnpres`]:[this.name],subscriptionOptions:e,eventEmitter:this.eventEmitter,pubnub:this.pubnub})}}class ns{constructor(e,t,s){this.id=e,this.eventEmitter=t,this.pubnub=s}subscription(e){return new es({channels:[this.id],channelGroups:[],subscriptionOptions:e,eventEmitter:this.eventEmitter,pubnub:this.pubnub})}}class rs{constructor(e,t,s){this.eventEmitter=t,this.pubnub=s,this.name=e}subscription(e){return new es({channels:(null==e?void 0:e.receivePresenceEvents)?[this.name,`${this.name}-pnpres`]:[this.name],channelGroups:[],subscriptionOptions:e,eventEmitter:this.eventEmitter,pubnub:this.pubnub})}}class is extends se{constructor(e){super(),this.parameters=e}operation(){return re.PNRemoveChannelsFromGroupOperation}validate(){const{keySet:{subscribeKey:e},channels:t,channelGroup:s}=this.parameters;return e?s?t?void 0:"Missing channels":"Missing Channel Group":"Missing Subscribe Key"}parse(e){return h(this,void 0,void 0,(function*(){const t=this.deserializeResponse(e);if(!t)throw new o("Service response error, check status for details",a("Unable to deserialize service response"));if(t.status>=400)throw c.create(e);return{}}))}get path(){const{keySet:{subscribeKey:e},channelGroup:t}=this.parameters;return`/v1/channel-registration/sub-key/${e}/channel-group/${R(t)}`}get queryParameters(){return{remove:this.parameters.channels.join(",")}}}class os extends se{constructor(e){super(),this.parameters=e}operation(){return re.PNAddChannelsToGroupOperation}validate(){const{keySet:{subscribeKey:e},channels:t,channelGroup:s}=this.parameters;return e?s?t?void 0:"Missing channels":"Missing Channel Group":"Missing Subscribe Key"}parse(e){return h(this,void 0,void 0,(function*(){const t=this.deserializeResponse(e);if(!t)throw new o("Service response error, check status for details",a("Unable to deserialize service response"));if(t.status>=400)throw c.create(e);return{}}))}get path(){const{keySet:{subscribeKey:e},channelGroup:t}=this.parameters;return`/v1/channel-registration/sub-key/${e}/channel-group/${R(t)}`}get queryParameters(){return{add:this.parameters.channels.join(",")}}}class as extends se{constructor(e){super(),this.parameters=e}operation(){return re.PNChannelsForGroupOperation}validate(){return this.parameters.keySet.subscribeKey?this.parameters.channelGroup?void 0:"Missing Channel Group":"Missing Subscribe Key"}parse(e){return h(this,void 0,void 0,(function*(){const t=this.deserializeResponse(e);if(!t)throw new o("Service response error, check status for details",a("Unable to deserialize service response"));if(t.status>=400)throw c.create(e);return{channels:t.payload.channels}}))}get path(){const{keySet:{subscribeKey:e},channelGroup:t}=this.parameters;return`/v1/channel-registration/sub-key/${e}/channel-group/${R(t)}`}}class cs extends se{constructor(e){super(),this.parameters=e}operation(){return re.PNRemoveGroupOperation}validate(){return this.parameters.keySet.subscribeKey?this.parameters.channelGroup?void 0:"Missing Channel Group":"Missing Subscribe Key"}parse(e){return h(this,void 0,void 0,(function*(){const t=this.deserializeResponse(e);if(!t)throw new o("Service response error, check status for details",a("Unable to deserialize service response"));if(t.status>=400)throw c.create(e);return{}}))}get path(){const{keySet:{subscribeKey:e},channelGroup:t}=this.parameters;return`/v1/channel-registration/sub-key/${e}/channel-group/${R(t)}/remove`}}class us extends se{constructor(e){super(),this.parameters=e}operation(){return re.PNChannelGroupsOperation}validate(){if(!this.parameters.keySet.subscribeKey)return"Missing Subscribe Key"}parse(e){return h(this,void 0,void 0,(function*(){const t=this.deserializeResponse(e);if(!t)throw new o("Service response error, check status for details",a("Unable to deserialize service response"));if(t.status>=400)throw c.create(e);return{groups:t.payload.groups}}))}get path(){return`/v1/channel-registration/sub-key/${this.parameters.keySet.subscribeKey}/channel-group`}}class ls{constructor(e,t){this.keySet=e,this.sendRequest=t}listChannels(e,t){return h(this,void 0,void 0,(function*(){const s=new as(Object.assign(Object.assign({},e),{keySet:this.keySet}));return t?this.sendRequest(s,t):this.sendRequest(s)}))}listGroups(e){return h(this,void 0,void 0,(function*(){const t=new us({keySet:this.keySet});return e?this.sendRequest(t,e):this.sendRequest(t)}))}addChannels(e,t){return h(this,void 0,void 0,(function*(){const s=new os(Object.assign(Object.assign({},e),{keySet:this.keySet}));return t?this.sendRequest(s,t):this.sendRequest(s)}))}removeChannels(e,t){return h(this,void 0,void 0,(function*(){const s=new is(Object.assign(Object.assign({},e),{keySet:this.keySet}));return t?this.sendRequest(s,t):this.sendRequest(s)}))}deleteGroup(e,t){return h(this,void 0,void 0,(function*(){const s=new cs(Object.assign(Object.assign({},e),{keySet:this.keySet}));return t?this.sendRequest(s,t):this.sendRequest(s)}))}}class hs extends se{constructor(e){var t,s;super(),this.parameters=e,"apns2"===this.parameters.pushGateway&&(null!==(t=(s=this.parameters).environment)&&void 0!==t||(s.environment="development")),this.parameters.count&&this.parameters.count>1e3&&(this.parameters.count=1e3)}operation(){throw Error("Should be implemented in subclass.")}validate(){const{keySet:{subscribeKey:e},action:t,device:s,pushGateway:n}=this.parameters;return e?s?"add"!==t&&"remove"!==t||"channels"in this.parameters&&0!==this.parameters.channels.length?n?"apns2"!==this.parameters.pushGateway||this.parameters.topic?void 0:"Missing APNS2 topic":"Missing GW Type (pushGateway: gcm or apns2)":"Missing Channels":"Missing Device ID (device)":"Missing Subscribe Key"}parse(e){return h(this,void 0,void 0,(function*(){throw Error("Should be implemented in subclass.")}))}get path(){const{keySet:{subscribeKey:e},action:t,device:s,pushGateway:n}=this.parameters;let r="apns2"===n?`/v2/push/sub-key/${e}/devices-apns2/${s}`:`/v1/push/sub-key/${e}/devices/${s}`;return"remove-device"===t&&(r=`${r}/remove`),r}get queryParameters(){const{start:e,count:t}=this.parameters;let s=Object.assign(Object.assign({type:this.parameters.pushGateway},e?{start:e}:{}),t&&t>0?{count:t}:{});if("channels"in this.parameters&&(s[this.parameters.action]=this.parameters.channels.join(",")),"apns2"===this.parameters.pushGateway){const{environment:e,topic:t}=this.parameters;s=Object.assign(Object.assign({},s),{environment:e,topic:t})}return s}}class ds extends hs{constructor(e){super(Object.assign(Object.assign({},e),{action:"remove"}))}operation(){return re.PNRemovePushNotificationEnabledChannelsOperation}parse(e){return h(this,void 0,void 0,(function*(){if(!this.deserializeResponse(e))throw new o("Service response error, check status for details",a("Unable to deserialize service response"));return{}}))}}class ps extends hs{constructor(e){super(Object.assign(Object.assign({},e),{action:"list"}))}operation(){return re.PNPushNotificationEnabledChannelsOperation}parse(e){return h(this,void 0,void 0,(function*(){const t=this.deserializeResponse(e);if(!t)throw new o("Service response error, check status for details",a("Unable to deserialize service response"));return{channels:t}}))}}class gs extends hs{constructor(e){super(Object.assign(Object.assign({},e),{action:"add"}))}operation(){return re.PNAddPushNotificationEnabledChannelsOperation}parse(e){return h(this,void 0,void 0,(function*(){if(!this.deserializeResponse(e))throw new o("Service response error, check status for details",a("Unable to deserialize service response"));return{}}))}}class ys extends hs{constructor(e){super(Object.assign(Object.assign({},e),{action:"remove-device"}))}operation(){return re.PNRemoveAllPushNotificationsOperation}parse(e){return h(this,void 0,void 0,(function*(){if(!this.deserializeResponse(e))throw new o("Service response error, check status for details",a("Unable to deserialize service response"));return{}}))}}class fs{constructor(e,t){this.keySet=e,this.sendRequest=t}listChannels(e,t){return h(this,void 0,void 0,(function*(){const s=new ps(Object.assign(Object.assign({},e),{keySet:this.keySet}));return t?this.sendRequest(s,t):this.sendRequest(s)}))}addChannels(e,t){return h(this,void 0,void 0,(function*(){const s=new gs(Object.assign(Object.assign({},e),{keySet:this.keySet}));return t?this.sendRequest(s,t):this.sendRequest(s)}))}removeChannels(e,t){return h(this,void 0,void 0,(function*(){const s=new ds(Object.assign(Object.assign({},e),{keySet:this.keySet}));return t?this.sendRequest(s,t):this.sendRequest(s)}))}deleteDevice(e,t){return h(this,void 0,void 0,(function*(){const s=new ys(Object.assign(Object.assign({},e),{keySet:this.keySet}));return t?this.sendRequest(s,t):this.sendRequest(s)}))}}class ms extends se{constructor(e){var t,s,n,r,i,o;super(),this.parameters=e,null!==(t=e.include)&&void 0!==t||(e.include={}),null!==(s=(i=e.include).customFields)&&void 0!==s||(i.customFields=false),null!==(n=(o=e.include).totalCount)&&void 0!==n||(o.totalCount=false),null!==(r=e.limit)&&void 0!==r||(e.limit=100)}operation(){return re.PNGetAllChannelMetadataOperation}parse(e){return h(this,void 0,void 0,(function*(){const t=this.deserializeResponse(e);if(!t)throw new o("Service response error, check status for details",a("Unable to deserialize service response"));if(t.status>=400)throw c.create(e);return t}))}get path(){return`/v2/objects/${this.parameters.keySet.subscribeKey}/channels`}get queryParameters(){const{include:e,page:t,filter:s,sort:n,limit:r}=this.parameters,i=Object.entries(null!=n?n:{}).map((([e,t])=>null!==t?`${e}:${t}`:e));return Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({include:["status","type",...e.customFields?["custom"]:[]].join(","),count:`${e.totalCount}`},s?{filter:s}:{}),(null==t?void 0:t.next)?{start:t.next}:{}),(null==t?void 0:t.prev)?{end:t.prev}:{}),r?{limit:r}:{}),i.length?{sort:i}:{})}}class bs extends se{constructor(e){super({method:H.DELETE}),this.parameters=e}operation(){return re.PNRemoveChannelMetadataOperation}validate(){if(!this.parameters.channel)return"Channel cannot be empty"}parse(e){return h(this,void 0,void 0,(function*(){const t=this.deserializeResponse(e);if(!t)throw new o("Service response error, check status for details",a("Unable to deserialize service response"));if(t.status>=400)throw c.create(e);return t}))}get path(){const{keySet:{subscribeKey:e},channel:t}=this.parameters;return`/v2/objects/${e}/channels/${R(t)}`}}class vs extends se{constructor(e){var t,s,n,r,i,o,a,c,u,l,h,d,p,g,y,f;super(),this.parameters=e,null!==(t=e.include)&&void 0!==t||(e.include={}),null!==(s=(l=e.include).customFields)&&void 0!==s||(l.customFields=false),null!==(n=(h=e.include).totalCount)&&void 0!==n||(h.totalCount=false),null!==(r=(d=e.include).statusField)&&void 0!==r||(d.statusField=false),null!==(i=(p=e.include).channelFields)&&void 0!==i||(p.channelFields=false),null!==(o=(g=e.include).customChannelFields)&&void 0!==o||(g.customChannelFields=false),null!==(a=(y=e.include).channelStatusField)&&void 0!==a||(y.channelStatusField=false),null!==(c=(f=e.include).channelTypeField)&&void 0!==c||(f.channelTypeField=false),null!==(u=e.limit)&&void 0!==u||(e.limit=100),this.parameters.userId&&(this.parameters.uuid=this.parameters.userId)}operation(){return re.PNGetMembershipsOperation}validate(){if(!this.parameters.uuid)return"'uuid' cannot be empty"}parse(e){return h(this,void 0,void 0,(function*(){const t=this.deserializeResponse(e);if(!t)throw new o("Service response error, check status for details",a("Unable to deserialize service response"));if(t.status>=400)throw c.create(e);return t}))}get path(){const{keySet:{subscribeKey:e},uuid:t}=this.parameters;return`/v2/objects/${e}/uuids/${R(t)}/channels`}get queryParameters(){const{include:e,page:t,filter:s,sort:n,limit:r}=this.parameters,i=Object.entries(null!=n?n:{}).map((([e,t])=>null!==t?`${e}:${t}`:e)),o=[];return e.statusField&&o.push("status"),e.customFields&&o.push("custom"),e.channelFields&&o.push("channel"),e.channelStatusField&&o.push("channel.status"),e.channelTypeField&&o.push("channel.type"),e.customChannelFields&&o.push("channel.custom"),Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({count:`${e.totalCount}`},o.length>0?{include:o.join(",")}:{}),s?{filter:s}:{}),(null==t?void 0:t.next)?{start:t.next}:{}),(null==t?void 0:t.prev)?{end:t.prev}:{}),r?{limit:r}:{}),i.length?{sort:i}:{})}}class ws extends se{constructor(e){var t,s,n,r,i,o,a,c,u,l;super({method:H.PATCH}),this.parameters=e,null!==(t=e.include)&&void 0!==t||(e.include={}),null!==(s=(a=e.include).customFields)&&void 0!==s||(a.customFields=false),null!==(n=(c=e.include).totalCount)&&void 0!==n||(c.totalCount=false),null!==(r=(u=e.include).channelFields)&&void 0!==r||(u.channelFields=false),null!==(i=(l=e.include).customChannelFields)&&void 0!==i||(l.customChannelFields=false),null!==(o=e.limit)&&void 0!==o||(e.limit=100),this.parameters.userId&&(this.parameters.uuid=this.parameters.userId)}operation(){return re.PNSetMembershipsOperation}validate(){const{uuid:e,channels:t}=this.parameters;return e?t&&0!==t.length?void 0:"Channels cannot be empty":"'uuid' cannot be empty"}parse(e){return h(this,void 0,void 0,(function*(){const t=this.deserializeResponse(e);if(!t)throw new o("Service response error, check status for details",a("Unable to deserialize service response"));if(t.status>=400)throw c.create(e);return t}))}get path(){const{keySet:{subscribeKey:e},uuid:t}=this.parameters;return`/v2/objects/${e}/uuids/${R(t)}/channels`}get queryParameters(){const{include:e,page:t,filter:s,sort:n,limit:r}=this.parameters,i=Object.entries(null!=n?n:{}).map((([e,t])=>null!==t?`${e}:${t}`:e)),o=["channel.status","channel.type","status"];return e.customFields&&o.push("custom"),e.channelFields&&o.push("channel"),e.customChannelFields&&o.push("channel.custom"),Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({count:`${e.totalCount}`},o.length>0?{include:o.join(",")}:{}),s?{filter:s}:{}),(null==t?void 0:t.next)?{start:t.next}:{}),(null==t?void 0:t.prev)?{end:t.prev}:{}),r?{limit:r}:{}),i.length?{sort:i}:{})}get body(){const{channels:e,type:t}=this.parameters;return JSON.stringify({[`${t}`]:e.map((e=>"string"==typeof e?{channel:{id:e}}:{channel:{id:e.id},status:e.status,custom:e.custom}))})}}class Ss extends se{constructor(e){var t,s,n,r;super(),this.parameters=e,null!==(t=e.include)&&void 0!==t||(e.include={}),null!==(s=(r=e.include).customFields)&&void 0!==s||(r.customFields=false),null!==(n=e.limit)&&void 0!==n||(e.limit=100)}operation(){return re.PNGetAllUUIDMetadataOperation}parse(e){return h(this,void 0,void 0,(function*(){const t=this.deserializeResponse(e);if(!t)throw new o("Service response error, check status for details",a("Unable to deserialize service response"));if(t.status>=400)throw c.create(e);return t}))}get path(){return`/v2/objects/${this.parameters.keySet.subscribeKey}/uuids`}get queryParameters(){const{include:e,page:t,filter:s,sort:n,limit:r}=this.parameters,i=Object.entries(null!=n?n:{}).map((([e,t])=>null!==t?`${e}:${t}`:e));return Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({include:["status","type",...e.customFields?["custom"]:[]].join(",")},void 0!==e.totalCount?{count:`${e.totalCount}`}:{}),s?{filter:s}:{}),(null==t?void 0:t.next)?{start:t.next}:{}),(null==t?void 0:t.prev)?{end:t.prev}:{}),r?{limit:r}:{}),i.length?{sort:i}:{})}}class ks extends se{constructor(e){var t,s,n;super(),this.parameters=e,null!==(t=e.include)&&void 0!==t||(e.include={}),null!==(s=(n=e.include).customFields)&&void 0!==s||(n.customFields=true)}operation(){return re.PNGetChannelMetadataOperation}validate(){if(!this.parameters.channel)return"Channel cannot be empty"}parse(e){return h(this,void 0,void 0,(function*(){const t=this.deserializeResponse(e);if(!t)throw new o("Service response error, check status for details",a("Unable to deserialize service response"));if(t.status>=400)throw c.create(e);return t}))}get path(){const{keySet:{subscribeKey:e},channel:t}=this.parameters;return`/v2/objects/${e}/channels/${R(t)}`}get queryParameters(){return{include:["status","type",...this.parameters.include.customFields?["custom"]:[]].join(",")}}}class Es extends se{constructor(e){var t,s,n;super({method:H.PATCH}),this.parameters=e,null!==(t=e.include)&&void 0!==t||(e.include={}),null!==(s=(n=e.include).customFields)&&void 0!==s||(n.customFields=true)}operation(){return re.PNSetChannelMetadataOperation}validate(){return this.parameters.channel?this.parameters.data?void 0:"Data cannot be empty":"Channel cannot be empty"}parse(e){return h(this,void 0,void 0,(function*(){const t=this.deserializeResponse(e);if(!t)throw new o("Service response error, check status for details",a("Unable to deserialize service response"));if(t.status>=400)throw c.create(e);return t}))}get path(){const{keySet:{subscribeKey:e},channel:t}=this.parameters;return`/v2/objects/${e}/channels/${R(t)}`}get queryParameters(){return{include:["status","type",...this.parameters.include.customFields?["custom"]:[]].join(",")}}get body(){return JSON.stringify(this.parameters.data)}}class Os extends se{constructor(e){super({method:H.DELETE}),this.parameters=e,this.parameters.userId&&(this.parameters.uuid=this.parameters.userId)}operation(){return re.PNRemoveUUIDMetadataOperation}validate(){if(!this.parameters.uuid)return"'uuid' cannot be empty"}parse(e){return h(this,void 0,void 0,(function*(){const t=this.deserializeResponse(e);if(!t)throw new o("Service response error, check status for details",a("Unable to deserialize service response"));if(t.status>=400)throw c.create(e);return t}))}get path(){const{keySet:{subscribeKey:e},uuid:t}=this.parameters;return`/v2/objects/${e}/uuids/${R(t)}`}}class Cs extends se{constructor(e){var t,s,n,r,i,o,a,c,u,l,h,d,p,g,y,f;super(),this.parameters=e,null!==(t=e.include)&&void 0!==t||(e.include={}),null!==(s=(l=e.include).customFields)&&void 0!==s||(l.customFields=false),null!==(n=(h=e.include).totalCount)&&void 0!==n||(h.totalCount=false),null!==(r=(d=e.include).statusField)&&void 0!==r||(d.statusField=false),null!==(i=(p=e.include).UUIDFields)&&void 0!==i||(p.UUIDFields=false),null!==(o=(g=e.include).customUUIDFields)&&void 0!==o||(g.customUUIDFields=false),null!==(a=(y=e.include).UUIDStatusField)&&void 0!==a||(y.UUIDStatusField=false),null!==(c=(f=e.include).UUIDTypeField)&&void 0!==c||(f.UUIDTypeField=false),null!==(u=e.limit)&&void 0!==u||(e.limit=100)}operation(){return re.PNSetMembersOperation}validate(){if(!this.parameters.channel)return"Channel cannot be empty"}parse(e){return h(this,void 0,void 0,(function*(){const t=this.deserializeResponse(e);if(!t)throw new o("Service response error, check status for details",a("Unable to deserialize service response"));if(t.status>=400)throw c.create(e);return t}))}get path(){const{keySet:{subscribeKey:e},channel:t}=this.parameters;return`/v2/objects/${e}/channels/${R(t)}/uuids`}get queryParameters(){const{include:e,page:t,filter:s,sort:n,limit:r}=this.parameters,i=Object.entries(null!=n?n:{}).map((([e,t])=>null!==t?`${e}:${t}`:e)),o=[];return e.statusField&&o.push("status"),e.customFields&&o.push("custom"),e.UUIDFields&&o.push("uuid"),e.UUIDStatusField&&o.push("uuid.status"),e.UUIDTypeField&&o.push("uuid.type"),e.customUUIDFields&&o.push("uuid.custom"),Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({count:`${e.totalCount}`},o.length>0?{include:o.join(",")}:{}),s?{filter:s}:{}),(null==t?void 0:t.next)?{start:t.next}:{}),(null==t?void 0:t.prev)?{end:t.prev}:{}),r?{limit:r}:{}),i.length?{sort:i}:{})}}class Ns extends se{constructor(e){var t,s,n,r,i,o,a,c,u,l;super({method:H.PATCH}),this.parameters=e,null!==(t=e.include)&&void 0!==t||(e.include={}),null!==(s=(a=e.include).customFields)&&void 0!==s||(a.customFields=false),null!==(n=(c=e.include).totalCount)&&void 0!==n||(c.totalCount=false),null!==(r=(u=e.include).UUIDFields)&&void 0!==r||(u.UUIDFields=false),null!==(i=(l=e.include).customUUIDFields)&&void 0!==i||(l.customUUIDFields=false),null!==(o=e.limit)&&void 0!==o||(e.limit=100)}operation(){return re.PNSetMembersOperation}validate(){const{channel:e,uuids:t}=this.parameters;return e?t&&0!==t.length?void 0:"UUIDs cannot be empty":"Channel cannot be empty"}parse(e){return h(this,void 0,void 0,(function*(){const t=this.deserializeResponse(e);if(!t)throw new o("Service response error, check status for details",a("Unable to deserialize service response"));if(t.status>=400)throw c.create(e);return t}))}get path(){const{keySet:{subscribeKey:e},channel:t}=this.parameters;return`/v2/objects/${e}/channels/${R(t)}/uuids`}get queryParameters(){const{include:e,page:t,filter:s,sort:n,limit:r}=this.parameters,i=Object.entries(null!=n?n:{}).map((([e,t])=>null!==t?`${e}:${t}`:e)),o=["uuid.status","uuid.type","type"];return e.customFields&&o.push("custom"),e.UUIDFields&&o.push("uuid"),e.customUUIDFields&&o.push("uuid.custom"),Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({count:`${e.totalCount}`},o.length>0?{include:o.join(",")}:{}),s?{filter:s}:{}),(null==t?void 0:t.next)?{start:t.next}:{}),(null==t?void 0:t.prev)?{end:t.prev}:{}),r?{limit:r}:{}),i.length?{sort:i}:{})}get body(){const{uuids:e,type:t}=this.parameters;return JSON.stringify({[`${t}`]:e.map((e=>"string"==typeof e?{uuid:{id:e}}:{uuid:{id:e.id},status:e.status,custom:e.custom}))})}}class Ps extends se{constructor(e){var t,s,n;super(),this.parameters=e,null!==(t=e.include)&&void 0!==t||(e.include={}),null!==(s=(n=e.include).customFields)&&void 0!==s||(n.customFields=true),this.parameters.userId&&(this.parameters.uuid=this.parameters.userId)}operation(){return re.PNGetUUIDMetadataOperation}validate(){if(!this.parameters.uuid)return"'uuid' cannot be empty"}parse(e){return h(this,void 0,void 0,(function*(){const t=this.deserializeResponse(e);if(!t)throw new o("Service response error, check status for details",a("Unable to deserialize service response"));if(t.status>=400)throw c.create(e);return t}))}get path(){const{keySet:{subscribeKey:e},uuid:t}=this.parameters;return`/v2/objects/${e}/uuids/${R(t)}`}get queryParameters(){const{include:e}=this.parameters;return{include:["status","type",...e.customFields?["custom"]:[]].join(",")}}}class Ms extends se{constructor(e){var t,s,n;super({method:H.PATCH}),this.parameters=e,null!==(t=e.include)&&void 0!==t||(e.include={}),null!==(s=(n=e.include).customFields)&&void 0!==s||(n.customFields=true),this.parameters.userId&&(this.parameters.uuid=this.parameters.userId)}operation(){return re.PNSetUUIDMetadataOperation}validate(){return this.parameters.uuid?this.parameters.data?void 0:"Data cannot be empty":"'uuid' cannot be empty"}parse(e){return h(this,void 0,void 0,(function*(){const t=this.deserializeResponse(e);if(!t)throw new o("Service response error, check status for details",a("Unable to deserialize service response"));if(t.status>=400)throw c.create(e);return t}))}get path(){const{keySet:{subscribeKey:e},uuid:t}=this.parameters;return`/v2/objects/${e}/uuids/${R(t)}`}get queryParameters(){return{include:["status","type",...this.parameters.include.customFields?["custom"]:[]].join(",")}}get body(){return JSON.stringify(this.parameters.data)}}class js{constructor(e,t){this.configuration=e,this.sendRequest=t,this.keySet=e.keySet}getAllUUIDMetadata(e,t){return h(this,void 0,void 0,(function*(){return this._getAllUUIDMetadata(e,t)}))}_getAllUUIDMetadata(e,t){return h(this,void 0,void 0,(function*(){const s=e&&"function"!=typeof e?e:{};null!=t||(t="function"==typeof e?e:void 0);const n=new Ss(Object.assign(Object.assign({},s),{keySet:this.keySet}));return t?this.sendRequest(n,t):this.sendRequest(n)}))}getUUIDMetadata(e,t){return h(this,void 0,void 0,(function*(){return this._getUUIDMetadata(e,t)}))}_getUUIDMetadata(e,t){return h(this,void 0,void 0,(function*(){var s;const n=e&&"function"!=typeof e?e:{};null!=t||(t="function"==typeof e?e:void 0),n.userId&&(n.uuid=n.userId),null!==(s=n.uuid)&&void 0!==s||(n.uuid=this.configuration.userId);const r=new Ps(Object.assign(Object.assign({},n),{keySet:this.keySet}));return t?this.sendRequest(r,t):this.sendRequest(r)}))}setUUIDMetadata(e,t){return h(this,void 0,void 0,(function*(){return this._setUUIDMetadata(e,t)}))}_setUUIDMetadata(e,t){return h(this,void 0,void 0,(function*(){var s;e.userId&&(e.uuid=e.userId),null!==(s=e.uuid)&&void 0!==s||(e.uuid=this.configuration.userId);const n=new Ms(Object.assign(Object.assign({},e),{keySet:this.keySet}));return t?this.sendRequest(n,t):this.sendRequest(n)}))}removeUUIDMetadata(e,t){return h(this,void 0,void 0,(function*(){return this._removeUUIDMetadata(e,t)}))}_removeUUIDMetadata(e,t){return h(this,void 0,void 0,(function*(){var s;const n=e&&"function"!=typeof e?e:{};null!=t||(t="function"==typeof e?e:void 0),n.userId&&(n.uuid=n.userId),null!==(s=n.uuid)&&void 0!==s||(n.uuid=this.configuration.userId);const r=new Os(Object.assign(Object.assign({},n),{keySet:this.keySet}));return t?this.sendRequest(r,t):this.sendRequest(r)}))}getAllChannelMetadata(e,t){return h(this,void 0,void 0,(function*(){return this._getAllChannelMetadata(e,t)}))}_getAllChannelMetadata(e,t){return h(this,void 0,void 0,(function*(){const s=e&&"function"!=typeof e?e:{};null!=t||(t="function"==typeof e?e:void 0);const n=new ms(Object.assign(Object.assign({},s),{keySet:this.keySet}));return t?this.sendRequest(n,t):this.sendRequest(n)}))}getChannelMetadata(e,t){return h(this,void 0,void 0,(function*(){return this._getChannelMetadata(e,t)}))}_getChannelMetadata(e,t){return h(this,void 0,void 0,(function*(){const s=new ks(Object.assign(Object.assign({},e),{keySet:this.keySet}));return t?this.sendRequest(s,t):this.sendRequest(s)}))}setChannelMetadata(e,t){return h(this,void 0,void 0,(function*(){return this._setChannelMetadata(e,t)}))}_setChannelMetadata(e,t){return h(this,void 0,void 0,(function*(){const s=new Es(Object.assign(Object.assign({},e),{keySet:this.keySet}));return t?this.sendRequest(s,t):this.sendRequest(s)}))}removeChannelMetadata(e,t){return h(this,void 0,void 0,(function*(){return this._removeChannelMetadata(e,t)}))}_removeChannelMetadata(e,t){return h(this,void 0,void 0,(function*(){const s=new bs(Object.assign(Object.assign({},e),{keySet:this.keySet}));return t?this.sendRequest(s,t):this.sendRequest(s)}))}getChannelMembers(e,t){return h(this,void 0,void 0,(function*(){const s=new Cs(Object.assign(Object.assign({},e),{keySet:this.keySet}));return t?this.sendRequest(s,t):this.sendRequest(s)}))}setChannelMembers(e,t){return h(this,void 0,void 0,(function*(){const s=new Ns(Object.assign(Object.assign({},e),{type:"set",keySet:this.keySet}));return t?this.sendRequest(s,t):this.sendRequest(s)}))}removeChannelMembers(e,t){return h(this,void 0,void 0,(function*(){const s=new Ns(Object.assign(Object.assign({},e),{type:"delete",keySet:this.keySet}));return t?this.sendRequest(s,t):this.sendRequest(s)}))}getMemberships(e,t){return h(this,void 0,void 0,(function*(){var s;const n=e&&"function"!=typeof e?e:{};null!=t||(t="function"==typeof e?e:void 0),n.userId&&(n.uuid=n.userId),null!==(s=n.uuid)&&void 0!==s||(n.uuid=this.configuration.userId);const r=new vs(Object.assign(Object.assign({},n),{keySet:this.keySet}));return t?this.sendRequest(r,t):this.sendRequest(r)}))}setMemberships(e,t){return h(this,void 0,void 0,(function*(){var s;e.userId&&(e.uuid=e.userId),null!==(s=e.uuid)&&void 0!==s||(e.uuid=this.configuration.userId);const n=new ws(Object.assign(Object.assign({},e),{type:"set",keySet:this.keySet}));return t?this.sendRequest(n,t):this.sendRequest(n)}))}removeMemberships(e,t){return h(this,void 0,void 0,(function*(){var s;e.userId&&(e.uuid=e.userId),null!==(s=e.uuid)&&void 0!==s||(e.uuid=this.configuration.userId);const n=new ws(Object.assign(Object.assign({},e),{type:"delete",keySet:this.keySet}));return t?this.sendRequest(n,t):this.sendRequest(n)}))}fetchMemberships(e,t){return h(this,void 0,void 0,(function*(){var s,n;if("spaceId"in e){const n=e,r={channel:null!==(s=n.spaceId)&&void 0!==s?s:n.channel,filter:n.filter,limit:n.limit,page:n.page,include:Object.assign({},n.include),sort:n.sort?Object.fromEntries(Object.entries(n.sort).map((([e,t])=>[e.replace("user","uuid"),t]))):void 0},i=e=>({status:e.status,data:e.data.map((e=>({user:e.uuid,custom:e.custom,updated:e.updated,eTag:e.eTag}))),totalCount:e.totalCount,next:e.next,prev:e.prev});return t?this.getChannelMembers(r,((e,s)=>{t(e,s?i(s):s)})):this.getChannelMembers(r).then(i)}const r=e,i={uuid:null!==(n=r.userId)&&void 0!==n?n:r.uuid,filter:r.filter,limit:r.limit,page:r.page,include:Object.assign({},r.include),sort:r.sort?Object.fromEntries(Object.entries(r.sort).map((([e,t])=>[e.replace("space","channel"),t]))):void 0},o=e=>({status:e.status,data:e.data.map((e=>({space:e.channel,custom:e.custom,updated:e.updated,eTag:e.eTag}))),totalCount:e.totalCount,next:e.next,prev:e.prev});return t?this.getMemberships(i,((e,s)=>{t(e,s?o(s):s)})):this.getMemberships(i).then(o)}))}addMemberships(e,t){return h(this,void 0,void 0,(function*(){var s,n,r,i,o,a;if("spaceId"in e){const i=e,o={channel:null!==(s=i.spaceId)&&void 0!==s?s:i.channel,uuids:null!==(r=null===(n=i.users)||void 0===n?void 0:n.map((e=>"string"==typeof e?e:(e.userId,{id:e.userId,custom:e.custom}))))&&void 0!==r?r:i.uuids,limit:0};return t?this.setChannelMembers(o,t):this.setChannelMembers(o)}const c=e,u={uuid:null!==(i=c.userId)&&void 0!==i?i:c.uuid,channels:null!==(a=null===(o=c.spaces)||void 0===o?void 0:o.map((e=>"string"==typeof e?e:{id:e.spaceId,custom:e.custom})))&&void 0!==a?a:c.channels,limit:0};return t?this.setMemberships(u,t):this.setMemberships(u)}))}}class _s extends se{constructor(){super()}operation(){return re.PNTimeOperation}parse(e){return h(this,void 0,void 0,(function*(){const t=this.deserializeResponse(e);if(!t)throw new o("Service response error, check status for details",a("Unable to deserialize service response"));return{timetoken:t[0]}}))}get path(){return"/time/0"}}class As extends se{constructor(e){super(),this.parameters=e}operation(){return re.PNDownloadFileOperation}validate(){const{channel:e,id:t,name:s}=this.parameters;return e?t?s?void 0:"file name can't be empty":"file id can't be empty":"channel can't be empty"}parse(e){return h(this,void 0,void 0,(function*(){const{cipherKey:t,crypto:s,cryptography:n,name:r,PubNubFile:i}=this.parameters,o=e.headers["content-type"];let a,c=e.body;return i.supportsEncryptFile&&(t||s)&&(t&&n?c=yield n.decrypt(t,c):!t&&s&&(a=yield s.decryptFile(i.create({data:c,name:r,mimeType:o}),i))),a||i.create({data:c,name:r,mimeType:o})}))}get path(){const{keySet:{subscribeKey:e},channel:t,id:s,name:n}=this.parameters;return`/v1/files/${e}/channels/${R(t)}/files/${s}/${n}`}}class Rs{static notificationPayload(e,t){return new te(e,t)}static generateUUID(){return G.createUUID()}constructor(e){if(this._configuration=e.configuration,this.cryptography=e.cryptography,this.tokenManager=e.tokenManager,this.transport=e.transport,this.crypto=e.crypto,this._objects=new js(this._configuration,this.sendRequest.bind(this)),this._channelGroups=new ls(this._configuration.keySet,this.sendRequest.bind(this)),this._push=new fs(this._configuration.keySet,this.sendRequest.bind(this)),this.listenerManager=new W,this.eventEmitter=new ce(this.listenerManager),this._configuration.enableEventEngine){let e=this._configuration.getHeartbeatInterval();this.presenceState={},e&&(this.presenceEventEngine=new $e({heartbeat:this.heartbeat.bind(this),leave:e=>this.makeUnsubscribe(e,(()=>{})),heartbeatDelay:()=>new Promise(((t,s)=>{e=this._configuration.getHeartbeatInterval(),e?setTimeout(t,1e3*e):s(new o("Heartbeat interval has been reset."))})),retryDelay:e=>new Promise((t=>setTimeout(t,e))),emitStatus:e=>this.listenerManager.announceStatus(e),config:this._configuration,presenceState:this.presenceState})),this.eventEngine=new St({handshake:this.subscribeHandshake.bind(this),receiveMessages:this.subscribeReceiveMessages.bind(this),delay:e=>new Promise((t=>setTimeout(t,e))),join:this.join.bind(this),leave:this.leave.bind(this),leaveAll:this.leaveAll.bind(this),presenceState:this.presenceState,config:this._configuration,emitMessages:e=>{try{e.forEach((e=>this.eventEmitter.emitEvent(e)))}catch(e){const t={error:!0,category:i.PNUnknownCategory,errorData:e,statusCode:0};this.listenerManager.announceStatus(t)}},emitStatus:e=>this.listenerManager.announceStatus(e)})}else this.subscriptionManager=new Y(this._configuration,this.listenerManager,this.eventEmitter,this.makeSubscribe.bind(this),this.heartbeat.bind(this),this.makeUnsubscribe.bind(this),this.time.bind(this))}get configuration(){return this._configuration}get _config(){return this.configuration}get authKey(){var e;return null!==(e=this._configuration.authKey)&&void 0!==e?e:void 0}getAuthKey(){return this.authKey}setAuthKey(e){this._configuration.setAuthKey(e)}get userId(){return this._configuration.userId}set userId(e){if(!e||"string"!=typeof e||0===e.trim().length)throw new Error("Missing or invalid userId parameter. Provide a valid string userId");this._configuration.userId=e}getUserId(){return this._configuration.userId}setUserId(e){if(!e||"string"!=typeof e||0===e.trim().length)throw new Error("Missing or invalid userId parameter. Provide a valid string userId");this._configuration.userId=e}get filterExpression(){var e;return null!==(e=this._configuration.getFilterExpression())&&void 0!==e?e:void 0}getFilterExpression(){return this.filterExpression}set filterExpression(e){this._configuration.setFilterExpression(e)}setFilterExpression(e){this.filterExpression=e}get cipherKey(){return this._configuration.getCipherKey()}set cipherKey(e){this._configuration.setCipherKey(e)}setCipherKey(e){this.cipherKey=e}set heartbeatInterval(e){this._configuration.setHeartbeatInterval(e)}setHeartbeatInterval(e){this.heartbeatInterval=e}getVersion(){return this._configuration.getVersion()}_addPnsdkSuffix(e,t){this._configuration._addPnsdkSuffix(e,t)}getUUID(){return this.userId}setUUID(e){this.userId=e}get customEncrypt(){return this._configuration.getCustomEncrypt()}get customDecrypt(){return this._configuration.getCustomDecrypt()}channel(e){return new rs(e,this.eventEmitter,this)}channelGroup(e){return new ss(e,this.eventEmitter,this)}channelMetadata(e){return new ts(e,this.eventEmitter,this)}userMetadata(e){return new ns(e,this.eventEmitter,this)}subscriptionSet(e){return new Zt(Object.assign(Object.assign({},e),{eventEmitter:this.eventEmitter,pubnub:this}))}sendRequest(e,t){return h(this,void 0,void 0,(function*(){const s=e.validate();if(s){if(t)return t(a(s),null);throw new o("Validation failed, check status for details",a(s))}const n=e.request();n.formData&&n.formData.length>0?n.timeout=300:e.operation()===re.PNSubscribeOperation?n.timeout=this._configuration.getSubscribeTimeout():n.timeout=this._configuration.getTransactionTimeout();const r={error:!1,operation:e.operation(),category:i.PNAcknowledgmentCategory,statusCode:0},[u,l]=this.transport.makeSendable(n);return e.cancellationController=l||null,u.then((t=>{if(r.statusCode=t.status,200!==t.status&&204!==t.status){const e=t.headers["content-type"];if(e||-1!==e.indexOf("javascript")||-1!==e.indexOf("json")){const e=JSON.parse(Rs.decoder.decode(t.body));"object"==typeof e&&"error"in e&&e.error&&"object"==typeof e.error&&(r.errorData=e.error)}}return e.parse(t)})).then((e=>t?t(r,e):e)).catch((s=>{const n=s instanceof c?s:c.create(s);if(t)return t(n.toStatus(e.operation()),null);throw n.toPubNubError(e.operation(),"REST API request processing error, check status for details")}))}))}destroy(e){this.subscriptionManager?(this.subscriptionManager.unsubscribeAll(e),this.subscriptionManager.disconnect()):this.eventEngine&&this.eventEngine.dispose()}stop(){this.destroy()}addListener(e){this.listenerManager.addListener(e)}removeListener(e){this.listenerManager.removeListener(e)}removeAllListeners(){this.listenerManager.removeAllListeners()}publish(e,t){return h(this,void 0,void 0,(function*(){const s=new kt(Object.assign(Object.assign({},e),{keySet:this._configuration.keySet,crypto:this._configuration.getCryptoModule()}));return t?this.sendRequest(s,t):this.sendRequest(s)}))}signal(e,t){return h(this,void 0,void 0,(function*(){const s=new Et(Object.assign(Object.assign({},e),{keySet:this._configuration.keySet}));return t?this.sendRequest(s,t):this.sendRequest(s)}))}fire(e,t){return h(this,void 0,void 0,(function*(){return null!=t||(t=()=>{}),this.publish(Object.assign(Object.assign({},e),{replicate:!1,storeInHistory:!1}),t)}))}getSubscribedChannels(){return this.subscriptionManager?this.subscriptionManager.subscribedChannels:this.eventEngine?this.eventEngine.getSubscribedChannels():[]}getSubscribedChannelGroups(){return this.subscriptionManager?this.subscriptionManager.subscribedChannelGroups:this.eventEngine?this.eventEngine.getSubscribedChannelGroups():[]}subscribe(e){this.subscriptionManager?this.subscriptionManager.subscribe(e):this.eventEngine&&this.eventEngine.subscribe(e)}makeSubscribe(e,t){const s=new ae(Object.assign(Object.assign({},e),{keySet:this._configuration.keySet,crypto:this._configuration.getCryptoModule(),getFileUrl:this.getFileUrl.bind(this)}));if(this.sendRequest(s,((e,n)=>{var r;this.subscriptionManager&&(null===(r=this.subscriptionManager.abort)||void 0===r?void 0:r.identifier)===s.requestIdentifier&&(this.subscriptionManager.abort=null),t(e,n)})),this.subscriptionManager){const e=()=>s.abort();e.identifier=s.requestIdentifier,this.subscriptionManager.abort=e}}unsubscribe(e){this.subscriptionManager?this.subscriptionManager.unsubscribe(e):this.eventEngine&&this.eventEngine.unsubscribe(e)}makeUnsubscribe(e,t){this.sendRequest(new jt(Object.assign(Object.assign({},e),{keySet:this._configuration.keySet})),t)}unsubscribeAll(){this.subscriptionManager?this.subscriptionManager.unsubscribeAll():this.eventEngine&&this.eventEngine.unsubscribeAll()}disconnect(){this.subscriptionManager?this.subscriptionManager.disconnect():this.eventEngine&&this.eventEngine.disconnect()}reconnect(e){this.subscriptionManager?this.subscriptionManager.reconnect():this.eventEngine&&this.eventEngine.reconnect(null!=e?e:{})}subscribeHandshake(e){return h(this,void 0,void 0,(function*(){const t=new Ct(Object.assign(Object.assign({},e),{keySet:this._configuration.keySet,crypto:this._configuration.getCryptoModule(),getFileUrl:this.getFileUrl.bind(this)})),s=e.abortSignal.subscribe((e=>{t.abort()}));return this.sendRequest(t).then((e=>(s(),e.cursor)))}))}subscribeReceiveMessages(e){return h(this,void 0,void 0,(function*(){const t=new Ot(Object.assign(Object.assign({},e),{keySet:this._configuration.keySet,crypto:this._configuration.getCryptoModule(),getFileUrl:this.getFileUrl.bind(this)})),s=e.abortSignal.subscribe((e=>{t.abort()}));return this.sendRequest(t).then((e=>(s(),e)))}))}getMessageActions(e,t){return h(this,void 0,void 0,(function*(){const s=new xt(Object.assign(Object.assign({},e),{keySet:this._configuration.keySet}));return t?this.sendRequest(s,t):this.sendRequest(s)}))}addMessageAction(e,t){return h(this,void 0,void 0,(function*(){const s=new Dt(Object.assign(Object.assign({},e),{keySet:this._configuration.keySet}));return t?this.sendRequest(s,t):this.sendRequest(s)}))}removeMessageAction(e,t){return h(this,void 0,void 0,(function*(){const s=new Kt(Object.assign(Object.assign({},e),{keySet:this._configuration.keySet}));return t?this.sendRequest(s,t):this.sendRequest(s)}))}fetchMessages(e,t){return h(this,void 0,void 0,(function*(){const s=new Ft(Object.assign(Object.assign({},e),{keySet:this._configuration.keySet,crypto:this._configuration.getCryptoModule(),getFileUrl:this.getFileUrl.bind(this)}));return t?this.sendRequest(s,t):this.sendRequest(s)}))}deleteMessages(e,t){return h(this,void 0,void 0,(function*(){const s=new Rt(Object.assign(Object.assign({},e),{keySet:this._configuration.keySet}));return t?this.sendRequest(s,t):this.sendRequest(s)}))}messageCounts(e,t){return h(this,void 0,void 0,(function*(){const s=new It(Object.assign(Object.assign({},e),{keySet:this._configuration.keySet}));return t?this.sendRequest(s,t):this.sendRequest(s)}))}history(e,t){return h(this,void 0,void 0,(function*(){const s=new Ut(Object.assign(Object.assign({},e),{keySet:this._configuration.keySet,crypto:this._configuration.getCryptoModule()}));return t?this.sendRequest(s,t):this.sendRequest(s)}))}hereNow(e,t){return h(this,void 0,void 0,(function*(){const s=new At(Object.assign(Object.assign({},e),{keySet:this._configuration.keySet}));return t?this.sendRequest(s,t):this.sendRequest(s)}))}whereNow(e,t){return h(this,void 0,void 0,(function*(){var s;const n=new _t({uuid:null!==(s=e.uuid)&&void 0!==s?s:this._configuration.userId,keySet:this._configuration.keySet});return t?this.sendRequest(n,t):this.sendRequest(n)}))}getState(e,t){return h(this,void 0,void 0,(function*(){var s;const n=new Nt(Object.assign(Object.assign({},e),{uuid:null!==(s=e.uuid)&&void 0!==s?s:this._configuration.userId,keySet:this._configuration.keySet}));return t?this.sendRequest(n,t):this.sendRequest(n)}))}setState(e,t){return h(this,void 0,void 0,(function*(){var s,n;const{keySet:r,userId:i}=this._configuration,o=this._configuration.getPresenceTimeout();let a;if(this._configuration.enableEventEngine&&this.presenceState){const t=this.presenceState;null===(s=e.channels)||void 0===s||s.forEach((s=>t[s]=e.state)),"channelGroups"in e&&(null===(n=e.channelGroups)||void 0===n||n.forEach((s=>t[s]=e.state)))}return a="withHeartbeat"in e?new Mt(Object.assign(Object.assign({},e),{keySet:r,heartbeat:o})):new Pt(Object.assign(Object.assign({},e),{keySet:r,uuid:i})),this.subscriptionManager&&this.subscriptionManager.setState(e),t?this.sendRequest(a,t):this.sendRequest(a)}))}presence(e){var t;null===(t=this.subscriptionManager)||void 0===t||t.changePresence(e)}heartbeat(e,t){return h(this,void 0,void 0,(function*(){const s=new Mt(Object.assign(Object.assign({},e),{keySet:this._configuration.keySet}));return t?this.sendRequest(s,t):this.sendRequest(s)}))}join(e){var t;null===(t=this.presenceEventEngine)||void 0===t||t.join(e)}leave(e){var t;null===(t=this.presenceEventEngine)||void 0===t||t.leave(e)}leaveAll(){var e;null===(e=this.presenceEventEngine)||void 0===e||e.leaveAll()}grantToken(e,t){return h(this,void 0,void 0,(function*(){const s=new Wt(Object.assign(Object.assign({},e),{keySet:this._configuration.keySet}));return t?this.sendRequest(s,t):this.sendRequest(s)}))}revokeToken(e,t){return h(this,void 0,void 0,(function*(){const s=new Vt(Object.assign(Object.assign({},e),{keySet:this._configuration.keySet}));return t?this.sendRequest(s,t):this.sendRequest(s)}))}get token(){return this.tokenManager.getToken()}getToken(){return this.token}set token(e){this.tokenManager.setToken(e)}setToken(e){this.token=e}parseToken(e){return this.tokenManager.parseToken(e)}grant(e,t){return h(this,void 0,void 0,(function*(){const s=new Jt(Object.assign(Object.assign({},e),{keySet:this._configuration.keySet}));return t?this.sendRequest(s,t):this.sendRequest(s)}))}audit(e,t){return h(this,void 0,void 0,(function*(){const s=new Yt(Object.assign(Object.assign({},e),{keySet:this._configuration.keySet}));return t?this.sendRequest(s,t):this.sendRequest(s)}))}get objects(){return this._objects}fetchUsers(e,t){return h(this,void 0,void 0,(function*(){return this.objects._getAllUUIDMetadata(e,t)}))}fetchUser(e,t){return h(this,void 0,void 0,(function*(){return this.objects._getUUIDMetadata(e,t)}))}createUser(e,t){return h(this,void 0,void 0,(function*(){return this.objects._setUUIDMetadata(e,t)}))}updateUser(e,t){return h(this,void 0,void 0,(function*(){return this.objects._setUUIDMetadata(e,t)}))}removeUser(e,t){return h(this,void 0,void 0,(function*(){return this.objects._removeUUIDMetadata(e,t)}))}fetchSpaces(e,t){return h(this,void 0,void 0,(function*(){return this.objects._getAllChannelMetadata(e,t)}))}fetchSpace(e,t){return h(this,void 0,void 0,(function*(){return this.objects._getChannelMetadata(e,t)}))}createSpace(e,t){return h(this,void 0,void 0,(function*(){return this.objects._setChannelMetadata(e,t)}))}updateSpace(e,t){return h(this,void 0,void 0,(function*(){return this.objects._setChannelMetadata(e,t)}))}removeSpace(e,t){return h(this,void 0,void 0,(function*(){return this.objects._removeChannelMetadata(e,t)}))}fetchMemberships(e,t){return h(this,void 0,void 0,(function*(){return this.objects.fetchMemberships(e,t)}))}addMemberships(e,t){return h(this,void 0,void 0,(function*(){return this.objects.addMemberships(e,t)}))}updateMemberships(e,t){return h(this,void 0,void 0,(function*(){return this.objects.addMemberships(e,t)}))}removeMemberships(e,t){return h(this,void 0,void 0,(function*(){var s,n,r;if("spaceId"in e){const r=e,i={channel:null!==(s=r.spaceId)&&void 0!==s?s:r.channel,uuids:null!==(n=r.userIds)&&void 0!==n?n:r.uuids,limit:0};return t?this.objects.removeChannelMembers(i,t):this.objects.removeChannelMembers(i)}const i=e,o={uuid:i.userId,channels:null!==(r=i.spaceIds)&&void 0!==r?r:i.channels,limit:0};return t?this.objects.removeMemberships(o,t):this.objects.removeMemberships(o)}))}get channelGroups(){return this._channelGroups}get push(){return this._push}sendFile(e,t){return h(this,void 0,void 0,(function*(){if(!this._configuration.PubNubFile)throw new Error("Validation failed: 'PubNubFile' not configured or file upload not supported by the platform.");const s=new zt(Object.assign(Object.assign({},e),{keySet:this._configuration.keySet,PubNubFile:this._configuration.PubNubFile,fileUploadPublishRetryLimit:this._configuration.fileUploadPublishRetryLimit,file:e.file,sendRequest:this.sendRequest.bind(this),publishFile:this.publishFile.bind(this),crypto:this._configuration.getCryptoModule(),cryptography:this.cryptography?this.cryptography:void 0})),n={error:!1,operation:re.PNPublishFileOperation,category:i.PNAcknowledgmentCategory,statusCode:0};return s.process().then((e=>(n.statusCode=e.status,t?t(n,e):e))).catch((e=>{let s;throw e instanceof o?s=e.status:e instanceof c&&(s=e.toStatus(n.operation)),t&&s&&t(s,null),new o("REST API request processing error, check status for details",s)}))}))}publishFile(e,t){return h(this,void 0,void 0,(function*(){if(!this._configuration.PubNubFile)throw new Error("Validation failed: 'PubNubFile' not configured or file upload not supported by the platform.");const s=new qt(Object.assign(Object.assign({},e),{keySet:this._configuration.keySet,crypto:this._configuration.getCryptoModule()}));return t?this.sendRequest(s,t):this.sendRequest(s)}))}listFiles(e,t){return h(this,void 0,void 0,(function*(){const s=new Lt(Object.assign(Object.assign({},e),{keySet:this._configuration.keySet}));return t?this.sendRequest(s,t):this.sendRequest(s)}))}getFileUrl(e){var t;const s=this.transport.request(new Gt(Object.assign(Object.assign({},e),{keySet:this._configuration.keySet})).request()),n=null!==(t=s.queryParameters)&&void 0!==t?t:{},r=Object.keys(n).map((e=>{const t=n[e];return Array.isArray(t)?t.map((t=>`${e}=${R(t)}`)).join("&"):`${e}=${R(t)}`})).join("&");return`${s.origin}${s.path}?${r}`}downloadFile(e,t){return h(this,void 0,void 0,(function*(){if(!this._configuration.PubNubFile)throw new Error("Validation failed: 'PubNubFile' not configured or file upload not supported by the platform.");const s=new As(Object.assign(Object.assign({},e),{keySet:this._configuration.keySet,PubNubFile:this._configuration.PubNubFile,cryptography:this.cryptography?this.cryptography:void 0,crypto:this._configuration.getCryptoModule()}));return t?this.sendRequest(s,t):yield this.sendRequest(s)}))}deleteFile(e,t){return h(this,void 0,void 0,(function*(){const s=new $t(Object.assign(Object.assign({},e),{keySet:this._configuration.keySet}));return t?this.sendRequest(s,t):this.sendRequest(s)}))}time(e){return h(this,void 0,void 0,(function*(){const t=new _s;return e?this.sendRequest(t,e):this.sendRequest(t)}))}encrypt(e,t){const s=this._configuration.getCryptoModule();if(!t&&s&&"string"==typeof e){const t=s.encrypt(e);return"string"==typeof t?t:y(t)}if(!this.crypto)throw new Error("Encryption error: cypher key not set");return this.crypto.encrypt(e,t)}decrypt(e,t){const s=this._configuration.getCryptoModule();if(!t&&s){const t=s.decrypt(e);return t instanceof ArrayBuffer?JSON.parse((new TextDecoder).decode(t)):t}if(!this.crypto)throw new Error("Decryption error: cypher key not set");return this.crypto.decrypt(e,t)}encryptFile(e,t){return h(this,void 0,void 0,(function*(){var s;if("string"!=typeof e&&(t=e),!t)throw new Error("File encryption error. Source file is missing.");if(!this._configuration.PubNubFile)throw new Error("File encryption error. File constructor not configured.");if("string"!=typeof e&&!this._configuration.getCryptoModule())throw new Error("File encryption error. Crypto module not configured.");if("string"==typeof e){if(!this.cryptography)throw new Error("File encryption error. File encryption not available");return this.cryptography.encryptFile(e,t,this._configuration.PubNubFile)}return null===(s=this._configuration.getCryptoModule())||void 0===s?void 0:s.encryptFile(t,this._configuration.PubNubFile)}))}decryptFile(e,t){return h(this,void 0,void 0,(function*(){var s;if("string"!=typeof e&&(t=e),!t)throw new Error("File encryption error. Source file is missing.");if(!this._configuration.PubNubFile)throw new Error("File decryption error. File constructor not configured.");if("string"==typeof e&&!this._configuration.getCryptoModule())throw new Error("File decryption error. Crypto module not configured.");if("string"==typeof e){if(!this.cryptography)throw new Error("File decryption error. File decryption not available");return this.cryptography.decryptFile(e,t,this._configuration.PubNubFile)}return null===(s=this._configuration.getCryptoModule())||void 0===s?void 0:s.decryptFile(t,this._configuration.PubNubFile)}))}}Rs.decoder=new TextDecoder,Rs.OPERATIONS=re,Rs.CATEGORIES=i,Rs.ExponentialRetryPolicy=Le.ExponentialRetryPolicy,Rs.LinearRetryPolicy=Le.LinearRetryPolicy;class Is{constructor(e,t){this.decode=e,this.base64ToBinary=t}decodeToken(e){let t="";e.length%4==3?t="=":e.length%4==2&&(t="==");const s=e.replace(/-/gi,"+").replace(/_/gi,"/")+t,n=this.decode(this.base64ToBinary(s));return"object"==typeof n?n:void 0}}class Us extends Rs{constructor(e){var t;const s=D(e),n=Object.assign(Object.assign({},s),{sdkFamily:"Web",PubNubFile:p}),i=$(n,(e=>{if(e.cipherKey)return new j({default:new M(Object.assign({},e)),cryptors:[new E({cipherKey:e.cipherKey})]})})),o=new B(new Is((e=>x(r.decode(e))),g));let a;(i.getCipherKey()||i.secretKey)&&(a=new C({secretKey:i.secretKey,cipherKey:i.getCipherKey(),useRandomIVs:i.getUseRandomIVs(),customEncrypt:i.getCustomEncrypt(),customDecrypt:i.getCustomDecrypt()}));let c=new F(i.keepAlive,i.logVerbosity);s.serviceWorkerUrl&&(c=new u({clientIdentifier:i._instanceId,subscriptionKey:i.subscribeKey,serviceWorkerUrl:s.serviceWorkerUrl,sdkVersion:i.getVersion(),logVerbosity:i.logVerbosity,transport:c}));super({configuration:i,transport:new V({clientConfiguration:i,tokenManager:o,transport:c}),cryptography:new P,tokenManager:o,crypto:a}),(null===(t=e.listenToBrowserNetworkEvents)||void 0===t||t)&&(window.addEventListener("offline",(()=>{this.networkDownDetected()})),window.addEventListener("online",(()=>{this.networkUpDetected()})))}networkDownDetected(){this.listenerManager.announceNetworkDown(),this._configuration.restore?this.disconnect():this.destroy(!0)}networkUpDetected(){this.listenerManager.announceNetworkUp(),this.reconnect()}}return Us.CryptoModule=j,Us})); +!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?module.exports=t():"function"==typeof define&&define.amd?define(t):(e="undefined"!=typeof globalThis?globalThis:e||self).PubNub=t()}(this,(function(){"use strict";var e="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{};function t(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var s={exports:{}};!function(t){!function(e,s){var n=Math.pow(2,-24),r=Math.pow(2,32),i=Math.pow(2,53);var o={encode:function(e){var t,n=new ArrayBuffer(256),o=new DataView(n),a=0;function c(e){for(var s=n.byteLength,r=a+e;s>2,u=0;u>6),r.push(128|63&o)):o<55296?(r.push(224|o>>12),r.push(128|o>>6&63),r.push(128|63&o)):(o=(1023&o)<<10,o|=1023&t.charCodeAt(++n),o+=65536,r.push(240|o>>18),r.push(128|o>>12&63),r.push(128|o>>6&63),r.push(128|63&o))}return d(3,r.length),h(r);default:var p;if(Array.isArray(t))for(d(4,p=t.length),n=0;n>5!==e)throw"Invalid indefinite length element";return s}function f(e,t){for(var s=0;s>10),e.push(56320|1023&n))}}"function"!=typeof t&&(t=function(e){return e}),"function"!=typeof i&&(i=function(){return s});var m=function e(){var r,d,m=l(),b=m>>5,v=31&m;if(7===b)switch(v){case 25:return function(){var e=new ArrayBuffer(4),t=new DataView(e),s=h(),r=32768&s,i=31744&s,o=1023&s;if(31744===i)i=261120;else if(0!==i)i+=114688;else if(0!==o)return o*n;return t.setUint32(0,r<<16|i<<13|o<<13),t.getFloat32(0)}();case 26:return c(o.getFloat32(a),4);case 27:return c(o.getFloat64(a),8)}if((d=g(v))<0&&(b<2||6=0;)S+=d,w.push(u(d));var k=new Uint8Array(S),E=0;for(r=0;r=0;)f(O,d);else f(O,d);return String.fromCharCode.apply(null,O);case 4:var C;if(d<0)for(C=[];!p();)C.push(e());else for(C=new Array(d),r=0;r{const s=new FileReader;s.addEventListener("load",(()=>{if(s.result instanceof ArrayBuffer)return e(s.result)})),s.addEventListener("error",(()=>t(s.error))),s.readAsArrayBuffer(this.data)}))}))}toString(){return i(this,void 0,void 0,(function*(){return new Promise(((e,t)=>{const s=new FileReader;s.addEventListener("load",(()=>{if("string"==typeof s.result)return e(s.result)})),s.addEventListener("error",(()=>{t(s.error)})),s.readAsBinaryString(this.data)}))}))}toStream(){return i(this,void 0,void 0,(function*(){throw new Error("This feature is only supported in Node.js environments.")}))}toFile(){return i(this,void 0,void 0,(function*(){return this.data}))}toFileUri(){return i(this,void 0,void 0,(function*(){throw new Error("This feature is only supported in React Native environments.")}))}toBlob(){return i(this,void 0,void 0,(function*(){return this.data}))}}a.supportsBlob="undefined"!=typeof Blob,a.supportsFile="undefined"!=typeof File,a.supportsBuffer=!1,a.supportsStream=!1,a.supportsString=!0,a.supportsArrayBuffer=!0,a.supportsEncryptFile=!0,a.supportsFileUri=!1;function c(e){const t=e.replace(/==?$/,""),s=Math.floor(t.length/4*3),n=new ArrayBuffer(s),r=new Uint8Array(n);let i=0;function o(){const e=t.charAt(i++),s="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=".indexOf(e);if(-1===s)throw new Error(`Illegal character at ${i}: ${t.charAt(i-1)}`);return s}for(let e=0;e>4,c=(15&s)<<4|n>>2,u=(3&n)<<6|i;r[e]=a,64!=n&&(r[e+1]=c),64!=i&&(r[e+2]=u)}return n}function u(e){let t="";const s="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",n=new Uint8Array(e),r=n.byteLength,i=r%3,o=r-i;let a,c,u,l,h;for(let e=0;e>18,c=(258048&h)>>12,u=(4032&h)>>6,l=63&h,t+=s[a]+s[c]+s[u]+s[l];return 1==i?(h=n[o],a=(252&h)>>2,c=(3&h)<<4,t+=s[a]+s[c]+"=="):2==i&&(h=n[o]<<8|n[o+1],a=(64512&h)>>10,c=(1008&h)>>4,u=(15&h)<<2,t+=s[a]+s[c]+s[u]+"="),t}var l;!function(e){e.PNNetworkIssuesCategory="PNNetworkIssuesCategory",e.PNTimeoutCategory="PNTimeoutCategory",e.PNCancelledCategory="PNCancelledCategory",e.PNBadRequestCategory="PNBadRequestCategory",e.PNAccessDeniedCategory="PNAccessDeniedCategory",e.PNValidationErrorCategory="PNValidationErrorCategory",e.PNAcknowledgmentCategory="PNAcknowledgmentCategory",e.PNUnknownCategory="PNUnknownCategory",e.PNNetworkUpCategory="PNNetworkUpCategory",e.PNNetworkDownCategory="PNNetworkDownCategory",e.PNReconnectedCategory="PNReconnectedCategory",e.PNConnectedCategory="PNConnectedCategory",e.PNRequestMessageCountExceededCategory="PNRequestMessageCountExceededCategory",e.PNDisconnectedCategory="PNDisconnectedCategory",e.PNConnectionErrorCategory="PNConnectionErrorCategory",e.PNDisconnectedUnexpectedlyCategory="PNDisconnectedUnexpectedlyCategory"}(l||(l={}));var h=l;class d extends Error{constructor(e,t){super(e),this.status=t,this.name="PubNubError",this.message=e,Object.setPrototypeOf(this,new.target.prototype)}}function p(e,t){return s=Object.assign({message:e},void 0!==t?{statusCode:t}:{}),null!==(n=s.statusCode)&&void 0!==n||(s.statusCode=0),Object.assign(Object.assign({},s),{statusCode:s.statusCode,category:h.PNValidationErrorCategory,error:!0});var s,n}var g,y,f,m,b,v=v||function(e,t){var s={},n=s.lib={},r=function(){},i=n.Base={extend:function(e){r.prototype=this;var t=new r;return e&&t.mixIn(e),t.hasOwnProperty("init")||(t.init=function(){t.$super.init.apply(this,arguments)}),t.init.prototype=t,t.$super=this,t},create:function(){var e=this.extend();return e.init.apply(e,arguments),e},init:function(){},mixIn:function(e){for(var t in e)e.hasOwnProperty(t)&&(this[t]=e[t]);e.hasOwnProperty("toString")&&(this.toString=e.toString)},clone:function(){return this.init.prototype.extend(this)}},o=n.WordArray=i.extend({init:function(e,t){e=this.words=e||[],this.sigBytes=null!=t?t:4*e.length},toString:function(e){return(e||c).stringify(this)},concat:function(e){var t=this.words,s=e.words,n=this.sigBytes;if(e=e.sigBytes,this.clamp(),n%4)for(var r=0;r>>2]|=(s[r>>>2]>>>24-r%4*8&255)<<24-(n+r)%4*8;else if(65535>>2]=s[r>>>2];else t.push.apply(t,s);return this.sigBytes+=e,this},clamp:function(){var t=this.words,s=this.sigBytes;t[s>>>2]&=4294967295<<32-s%4*8,t.length=e.ceil(s/4)},clone:function(){var e=i.clone.call(this);return e.words=this.words.slice(0),e},random:function(t){for(var s=[],n=0;n>>2]>>>24-n%4*8&255;s.push((r>>>4).toString(16)),s.push((15&r).toString(16))}return s.join("")},parse:function(e){for(var t=e.length,s=[],n=0;n>>3]|=parseInt(e.substr(n,2),16)<<24-n%8*4;return new o.init(s,t/2)}},u=a.Latin1={stringify:function(e){var t=e.words;e=e.sigBytes;for(var s=[],n=0;n>>2]>>>24-n%4*8&255));return s.join("")},parse:function(e){for(var t=e.length,s=[],n=0;n>>2]|=(255&e.charCodeAt(n))<<24-n%4*8;return new o.init(s,t)}},l=a.Utf8={stringify:function(e){try{return decodeURIComponent(escape(u.stringify(e)))}catch(e){throw Error("Malformed UTF-8 data")}},parse:function(e){return u.parse(unescape(encodeURIComponent(e)))}},h=n.BufferedBlockAlgorithm=i.extend({reset:function(){this._data=new o.init,this._nDataBytes=0},_append:function(e){"string"==typeof e&&(e=l.parse(e)),this._data.concat(e),this._nDataBytes+=e.sigBytes},_process:function(t){var s=this._data,n=s.words,r=s.sigBytes,i=this.blockSize,a=r/(4*i);if(t=(a=t?e.ceil(a):e.max((0|a)-this._minBufferSize,0))*i,r=e.min(4*t,r),t){for(var c=0;cu;){var l;e:{l=c;for(var h=e.sqrt(l),d=2;d<=h;d++)if(!(l%d)){l=!1;break e}l=!0}l&&(8>u&&(i[u]=a(e.pow(c,.5))),o[u]=a(e.pow(c,1/3)),u++),c++}var p=[];r=r.SHA256=n.extend({_doReset:function(){this._hash=new s.init(i.slice(0))},_doProcessBlock:function(e,t){for(var s=this._hash.words,n=s[0],r=s[1],i=s[2],a=s[3],c=s[4],u=s[5],l=s[6],h=s[7],d=0;64>d;d++){if(16>d)p[d]=0|e[t+d];else{var g=p[d-15],y=p[d-2];p[d]=((g<<25|g>>>7)^(g<<14|g>>>18)^g>>>3)+p[d-7]+((y<<15|y>>>17)^(y<<13|y>>>19)^y>>>10)+p[d-16]}g=h+((c<<26|c>>>6)^(c<<21|c>>>11)^(c<<7|c>>>25))+(c&u^~c&l)+o[d]+p[d],y=((n<<30|n>>>2)^(n<<19|n>>>13)^(n<<10|n>>>22))+(n&r^n&i^r&i),h=l,l=u,u=c,c=a+g|0,a=i,i=r,r=n,n=g+y|0}s[0]=s[0]+n|0,s[1]=s[1]+r|0,s[2]=s[2]+i|0,s[3]=s[3]+a|0,s[4]=s[4]+c|0,s[5]=s[5]+u|0,s[6]=s[6]+l|0,s[7]=s[7]+h|0},_doFinalize:function(){var t=this._data,s=t.words,n=8*this._nDataBytes,r=8*t.sigBytes;return s[r>>>5]|=128<<24-r%32,s[14+(r+64>>>9<<4)]=e.floor(n/4294967296),s[15+(r+64>>>9<<4)]=n,t.sigBytes=4*s.length,this._process(),this._hash},clone:function(){var e=n.clone.call(this);return e._hash=this._hash.clone(),e}});t.SHA256=n._createHelper(r),t.HmacSHA256=n._createHmacHelper(r)}(Math),y=(g=v).enc.Utf8,g.algo.HMAC=g.lib.Base.extend({init:function(e,t){e=this._hasher=new e.init,"string"==typeof t&&(t=y.parse(t));var s=e.blockSize,n=4*s;t.sigBytes>n&&(t=e.finalize(t)),t.clamp();for(var r=this._oKey=t.clone(),i=this._iKey=t.clone(),o=r.words,a=i.words,c=0;c>>2]>>>24-r%4*8&255)<<16|(t[r+1>>>2]>>>24-(r+1)%4*8&255)<<8|t[r+2>>>2]>>>24-(r+2)%4*8&255,o=0;4>o&&r+.75*o>>6*(3-o)&63));if(t=n.charAt(64))for(;e.length%4;)e.push(t);return e.join("")},parse:function(e){var t=e.length,s=this._map;(n=s.charAt(64))&&-1!=(n=e.indexOf(n))&&(t=n);for(var n=[],r=0,i=0;i>>6-i%4*2;n[r>>>2]|=(o|a)<<24-r%4*8,r++}return m.create(n,r)},_map:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/="},function(e){function t(e,t,s,n,r,i,o){return((e=e+(t&s|~t&n)+r+o)<>>32-i)+t}function s(e,t,s,n,r,i,o){return((e=e+(t&n|s&~n)+r+o)<>>32-i)+t}function n(e,t,s,n,r,i,o){return((e=e+(t^s^n)+r+o)<>>32-i)+t}function r(e,t,s,n,r,i,o){return((e=e+(s^(t|~n))+r+o)<>>32-i)+t}for(var i=v,o=(c=i.lib).WordArray,a=c.Hasher,c=i.algo,u=[],l=0;64>l;l++)u[l]=4294967296*e.abs(e.sin(l+1))|0;c=c.MD5=a.extend({_doReset:function(){this._hash=new o.init([1732584193,4023233417,2562383102,271733878])},_doProcessBlock:function(e,i){for(var o=0;16>o;o++){var a=e[c=i+o];e[c]=16711935&(a<<8|a>>>24)|4278255360&(a<<24|a>>>8)}o=this._hash.words;var c=e[i+0],l=(a=e[i+1],e[i+2]),h=e[i+3],d=e[i+4],p=e[i+5],g=e[i+6],y=e[i+7],f=e[i+8],m=e[i+9],b=e[i+10],v=e[i+11],w=e[i+12],S=e[i+13],k=e[i+14],E=e[i+15],O=t(O=o[0],P=o[1],N=o[2],C=o[3],c,7,u[0]),C=t(C,O,P,N,a,12,u[1]),N=t(N,C,O,P,l,17,u[2]),P=t(P,N,C,O,h,22,u[3]);O=t(O,P,N,C,d,7,u[4]),C=t(C,O,P,N,p,12,u[5]),N=t(N,C,O,P,g,17,u[6]),P=t(P,N,C,O,y,22,u[7]),O=t(O,P,N,C,f,7,u[8]),C=t(C,O,P,N,m,12,u[9]),N=t(N,C,O,P,b,17,u[10]),P=t(P,N,C,O,v,22,u[11]),O=t(O,P,N,C,w,7,u[12]),C=t(C,O,P,N,S,12,u[13]),N=t(N,C,O,P,k,17,u[14]),O=s(O,P=t(P,N,C,O,E,22,u[15]),N,C,a,5,u[16]),C=s(C,O,P,N,g,9,u[17]),N=s(N,C,O,P,v,14,u[18]),P=s(P,N,C,O,c,20,u[19]),O=s(O,P,N,C,p,5,u[20]),C=s(C,O,P,N,b,9,u[21]),N=s(N,C,O,P,E,14,u[22]),P=s(P,N,C,O,d,20,u[23]),O=s(O,P,N,C,m,5,u[24]),C=s(C,O,P,N,k,9,u[25]),N=s(N,C,O,P,h,14,u[26]),P=s(P,N,C,O,f,20,u[27]),O=s(O,P,N,C,S,5,u[28]),C=s(C,O,P,N,l,9,u[29]),N=s(N,C,O,P,y,14,u[30]),O=n(O,P=s(P,N,C,O,w,20,u[31]),N,C,p,4,u[32]),C=n(C,O,P,N,f,11,u[33]),N=n(N,C,O,P,v,16,u[34]),P=n(P,N,C,O,k,23,u[35]),O=n(O,P,N,C,a,4,u[36]),C=n(C,O,P,N,d,11,u[37]),N=n(N,C,O,P,y,16,u[38]),P=n(P,N,C,O,b,23,u[39]),O=n(O,P,N,C,S,4,u[40]),C=n(C,O,P,N,c,11,u[41]),N=n(N,C,O,P,h,16,u[42]),P=n(P,N,C,O,g,23,u[43]),O=n(O,P,N,C,m,4,u[44]),C=n(C,O,P,N,w,11,u[45]),N=n(N,C,O,P,E,16,u[46]),O=r(O,P=n(P,N,C,O,l,23,u[47]),N,C,c,6,u[48]),C=r(C,O,P,N,y,10,u[49]),N=r(N,C,O,P,k,15,u[50]),P=r(P,N,C,O,p,21,u[51]),O=r(O,P,N,C,w,6,u[52]),C=r(C,O,P,N,h,10,u[53]),N=r(N,C,O,P,b,15,u[54]),P=r(P,N,C,O,a,21,u[55]),O=r(O,P,N,C,f,6,u[56]),C=r(C,O,P,N,E,10,u[57]),N=r(N,C,O,P,g,15,u[58]),P=r(P,N,C,O,S,21,u[59]),O=r(O,P,N,C,d,6,u[60]),C=r(C,O,P,N,v,10,u[61]),N=r(N,C,O,P,l,15,u[62]),P=r(P,N,C,O,m,21,u[63]);o[0]=o[0]+O|0,o[1]=o[1]+P|0,o[2]=o[2]+N|0,o[3]=o[3]+C|0},_doFinalize:function(){var t=this._data,s=t.words,n=8*this._nDataBytes,r=8*t.sigBytes;s[r>>>5]|=128<<24-r%32;var i=e.floor(n/4294967296);for(s[15+(r+64>>>9<<4)]=16711935&(i<<8|i>>>24)|4278255360&(i<<24|i>>>8),s[14+(r+64>>>9<<4)]=16711935&(n<<8|n>>>24)|4278255360&(n<<24|n>>>8),t.sigBytes=4*(s.length+1),this._process(),s=(t=this._hash).words,n=0;4>n;n++)r=s[n],s[n]=16711935&(r<<8|r>>>24)|4278255360&(r<<24|r>>>8);return t},clone:function(){var e=a.clone.call(this);return e._hash=this._hash.clone(),e}}),i.MD5=a._createHelper(c),i.HmacMD5=a._createHmacHelper(c)}(Math),function(){var e,t=v,s=(e=t.lib).Base,n=e.WordArray,r=(e=t.algo).EvpKDF=s.extend({cfg:s.extend({keySize:4,hasher:e.MD5,iterations:1}),init:function(e){this.cfg=this.cfg.extend(e)},compute:function(e,t){for(var s=(a=this.cfg).hasher.create(),r=n.create(),i=r.words,o=a.keySize,a=a.iterations;i.length>>2]}},t.BlockCipher=a.extend({cfg:a.cfg.extend({mode:c,padding:l}),reset:function(){a.reset.call(this);var e=(t=this.cfg).iv,t=t.mode;if(this._xformMode==this._ENC_XFORM_MODE)var s=t.createEncryptor;else s=t.createDecryptor,this._minBufferSize=1;this._mode=s.call(t,this,e&&e.words)},_doProcessBlock:function(e,t){this._mode.processBlock(e,t)},_doFinalize:function(){var e=this.cfg.padding;if(this._xformMode==this._ENC_XFORM_MODE){e.pad(this._data,this.blockSize);var t=this._process(!0)}else t=this._process(!0),e.unpad(t);return t},blockSize:4});var h=t.CipherParams=s.extend({init:function(e){this.mixIn(e)},toString:function(e){return(e||this.formatter).stringify(this)}}),d=(c=(p.format={}).OpenSSL={stringify:function(e){var t=e.ciphertext;return((e=e.salt)?n.create([1398893684,1701076831]).concat(e).concat(t):t).toString(i)},parse:function(e){var t=(e=i.parse(e)).words;if(1398893684==t[0]&&1701076831==t[1]){var s=n.create(t.slice(2,4));t.splice(0,4),e.sigBytes-=16}return h.create({ciphertext:e,salt:s})}},t.SerializableCipher=s.extend({cfg:s.extend({format:c}),encrypt:function(e,t,s,n){n=this.cfg.extend(n);var r=e.createEncryptor(s,n);return t=r.finalize(t),r=r.cfg,h.create({ciphertext:t,key:s,iv:r.iv,algorithm:e,mode:r.mode,padding:r.padding,blockSize:e.blockSize,formatter:n.format})},decrypt:function(e,t,s,n){return n=this.cfg.extend(n),t=this._parse(t,n.format),e.createDecryptor(s,n).finalize(t.ciphertext)},_parse:function(e,t){return"string"==typeof e?t.parse(e,this):e}})),p=(p.kdf={}).OpenSSL={execute:function(e,t,s,r){return r||(r=n.random(8)),e=o.create({keySize:t+s}).compute(e,r),s=n.create(e.words.slice(t),4*s),e.sigBytes=4*t,h.create({key:e,iv:s,salt:r})}},g=t.PasswordBasedCipher=d.extend({cfg:d.cfg.extend({kdf:p}),encrypt:function(e,t,s,n){return s=(n=this.cfg.extend(n)).kdf.execute(s,e.keySize,e.ivSize),n.iv=s.iv,(e=d.encrypt.call(this,e,t,s.key,n)).mixIn(s),e},decrypt:function(e,t,s,n){return n=this.cfg.extend(n),t=this._parse(t,n.format),s=n.kdf.execute(s,e.keySize,e.ivSize,t.salt),n.iv=s.iv,d.decrypt.call(this,e,t,s.key,n)}})}(),function(){for(var e=v,t=e.lib.BlockCipher,s=e.algo,n=[],r=[],i=[],o=[],a=[],c=[],u=[],l=[],h=[],d=[],p=[],g=0;256>g;g++)p[g]=128>g?g<<1:g<<1^283;var y=0,f=0;for(g=0;256>g;g++){var m=(m=f^f<<1^f<<2^f<<3^f<<4)>>>8^255&m^99;n[y]=m,r[m]=y;var b=p[y],w=p[b],S=p[w],k=257*p[m]^16843008*m;i[y]=k<<24|k>>>8,o[y]=k<<16|k>>>16,a[y]=k<<8|k>>>24,c[y]=k,k=16843009*S^65537*w^257*b^16843008*y,u[m]=k<<24|k>>>8,l[m]=k<<16|k>>>16,h[m]=k<<8|k>>>24,d[m]=k,y?(y=b^p[p[p[S^b]]],f^=p[p[f]]):y=f=1}var E=[0,1,2,4,8,16,32,64,128,27,54];s=s.AES=t.extend({_doReset:function(){for(var e=(s=this._key).words,t=s.sigBytes/4,s=4*((this._nRounds=t+6)+1),r=this._keySchedule=[],i=0;i>>24]<<24|n[o>>>16&255]<<16|n[o>>>8&255]<<8|n[255&o]):(o=n[(o=o<<8|o>>>24)>>>24]<<24|n[o>>>16&255]<<16|n[o>>>8&255]<<8|n[255&o],o^=E[i/t|0]<<24),r[i]=r[i-t]^o}for(e=this._invKeySchedule=[],t=0;tt||4>=i?o:u[n[o>>>24]]^l[n[o>>>16&255]]^h[n[o>>>8&255]]^d[n[255&o]]},encryptBlock:function(e,t){this._doCryptBlock(e,t,this._keySchedule,i,o,a,c,n)},decryptBlock:function(e,t){var s=e[t+1];e[t+1]=e[t+3],e[t+3]=s,this._doCryptBlock(e,t,this._invKeySchedule,u,l,h,d,r),s=e[t+1],e[t+1]=e[t+3],e[t+3]=s},_doCryptBlock:function(e,t,s,n,r,i,o,a){for(var c=this._nRounds,u=e[t]^s[0],l=e[t+1]^s[1],h=e[t+2]^s[2],d=e[t+3]^s[3],p=4,g=1;g>>24]^r[l>>>16&255]^i[h>>>8&255]^o[255&d]^s[p++],f=n[l>>>24]^r[h>>>16&255]^i[d>>>8&255]^o[255&u]^s[p++],m=n[h>>>24]^r[d>>>16&255]^i[u>>>8&255]^o[255&l]^s[p++];d=n[d>>>24]^r[u>>>16&255]^i[l>>>8&255]^o[255&h]^s[p++],u=y,l=f,h=m}y=(a[u>>>24]<<24|a[l>>>16&255]<<16|a[h>>>8&255]<<8|a[255&d])^s[p++],f=(a[l>>>24]<<24|a[h>>>16&255]<<16|a[d>>>8&255]<<8|a[255&u])^s[p++],m=(a[h>>>24]<<24|a[d>>>16&255]<<16|a[u>>>8&255]<<8|a[255&l])^s[p++],d=(a[d>>>24]<<24|a[u>>>16&255]<<16|a[l>>>8&255]<<8|a[255&h])^s[p++],e[t]=y,e[t+1]=f,e[t+2]=m,e[t+3]=d},keySize:8});e.AES=t._createHelper(s)}(),v.mode.ECB=((b=v.lib.BlockCipherMode.extend()).Encryptor=b.extend({processBlock:function(e,t){this._cipher.encryptBlock(e,t)}}),b.Decryptor=b.extend({processBlock:function(e,t){this._cipher.decryptBlock(e,t)}}),b);var w=t(v);class S{constructor({cipherKey:e}){this.cipherKey=e,this.CryptoJS=w,this.encryptedKey=this.CryptoJS.SHA256(e)}encrypt(e){if(0===("string"==typeof e?e:S.decoder.decode(e)).length)throw new Error("encryption error. empty content");const t=this.getIv();return{metadata:t,data:c(this.CryptoJS.AES.encrypt(e,this.encryptedKey,{iv:this.bufferToWordArray(t),mode:this.CryptoJS.mode.CBC}).ciphertext.toString(this.CryptoJS.enc.Base64))}}encryptFileData(e){return i(this,void 0,void 0,(function*(){const t=yield this.getKey(),s=this.getIv();return{data:yield crypto.subtle.encrypt({name:this.algo,iv:s},t,e),metadata:s}}))}decrypt(e){if("string"==typeof e.data)throw new Error("Decryption error: data for decryption should be ArrayBuffed.");const t=this.bufferToWordArray(new Uint8ClampedArray(e.metadata)),s=this.bufferToWordArray(new Uint8ClampedArray(e.data));return S.encoder.encode(this.CryptoJS.AES.decrypt({ciphertext:s},this.encryptedKey,{iv:t,mode:this.CryptoJS.mode.CBC}).toString(this.CryptoJS.enc.Utf8)).buffer}decryptFileData(e){return i(this,void 0,void 0,(function*(){if("string"==typeof e.data)throw new Error("Decryption error: data for decryption should be ArrayBuffed.");const t=yield this.getKey();return crypto.subtle.decrypt({name:this.algo,iv:e.metadata},t,e.data)}))}get identifier(){return"ACRH"}get algo(){return"AES-CBC"}getIv(){return crypto.getRandomValues(new Uint8Array(S.BLOCK_SIZE))}getKey(){return i(this,void 0,void 0,(function*(){const e=S.encoder.encode(this.cipherKey),t=yield crypto.subtle.digest("SHA-256",e.buffer);return crypto.subtle.importKey("raw",t,this.algo,!0,["encrypt","decrypt"])}))}bufferToWordArray(e){const t=[];let s;for(s=0;se.toString(16).padStart(2,"0"))).join(""),n=C.encoder.encode(s.slice(0,32)).buffer;return crypto.subtle.importKey("raw",n,"AES-CBC",!0,["encrypt","decrypt"])}))}}C.IV_LENGTH=16,C.encoder=new TextEncoder,C.decoder=new TextDecoder;class N{constructor(e){this.config=e,this.cryptor=new E(Object.assign({},e)),this.fileCryptor=new C}encrypt(e){const t="string"==typeof e?e:N.decoder.decode(e);return{data:this.cryptor.encrypt(t),metadata:null}}encryptFile(e,t){return i(this,void 0,void 0,(function*(){var s;if(!this.config.cipherKey)throw new d("File encryption error: cipher key not set.");return this.fileCryptor.encryptFile(null===(s=this.config)||void 0===s?void 0:s.cipherKey,e,t)}))}decrypt(e){const t="string"==typeof e.data?e.data:u(e.data);return this.cryptor.decrypt(t)}decryptFile(e,t){return i(this,void 0,void 0,(function*(){if(!this.config.cipherKey)throw new d("File encryption error: cipher key not set.");return this.fileCryptor.decryptFile(this.config.cipherKey,e,t)}))}get identifier(){return""}}N.encoder=new TextEncoder,N.decoder=new TextDecoder;class P extends o{static legacyCryptoModule(e){var t;if(!e.cipherKey)throw new d("Crypto module error: cipher key not set.");return new P({default:new N(Object.assign(Object.assign({},e),{useRandomIVs:null===(t=e.useRandomIVs)||void 0===t||t})),cryptors:[new S({cipherKey:e.cipherKey})]})}static aesCbcCryptoModule(e){var t;if(!e.cipherKey)throw new d("Crypto module error: cipher key not set.");return new P({default:new S({cipherKey:e.cipherKey}),cryptors:[new N(Object.assign(Object.assign({},e),{useRandomIVs:null===(t=e.useRandomIVs)||void 0===t||t}))]})}static withDefaultCryptor(e){return new this({default:e})}encrypt(e){const t=e instanceof ArrayBuffer&&this.defaultCryptor.identifier===P.LEGACY_IDENTIFIER?this.defaultCryptor.encrypt(P.decoder.decode(e)):this.defaultCryptor.encrypt(e);if(!t.metadata)return t.data;if("string"==typeof t.data)throw new Error("Encryption error: encrypted data should be ArrayBuffed.");const s=this.getHeaderData(t);return this.concatArrayBuffer(s,t.data)}encryptFile(e,t){return i(this,void 0,void 0,(function*(){if(this.defaultCryptor.identifier===M.LEGACY_IDENTIFIER)return this.defaultCryptor.encryptFile(e,t);const s=yield this.getFileData(e),n=yield this.defaultCryptor.encryptFileData(s);if("string"==typeof n.data)throw new Error("Encryption error: encrypted data should be ArrayBuffed.");return t.create({name:e.name,mimeType:"application/octet-stream",data:this.concatArrayBuffer(this.getHeaderData(n),n.data)})}))}decrypt(e){const t="string"==typeof e?c(e):e,s=M.tryParse(t),n=this.getCryptor(s),r=s.length>0?t.slice(s.length-s.metadataLength,s.length):null;if(t.slice(s.length).byteLength<=0)throw new Error("Decryption error: empty content");return n.decrypt({data:t.slice(s.length),metadata:r})}decryptFile(e,t){return i(this,void 0,void 0,(function*(){const s=yield e.data.arrayBuffer(),n=M.tryParse(s),r=this.getCryptor(n);if((null==r?void 0:r.identifier)===M.LEGACY_IDENTIFIER)return r.decryptFile(e,t);const i=(yield this.getFileData(s)).slice(n.length-n.metadataLength,n.length);return t.create({name:e.name,data:yield this.defaultCryptor.decryptFileData({data:s.slice(n.length),metadata:i})})}))}getCryptorFromId(e){const t=this.getAllCryptors().find((t=>e===t.identifier));if(t)return t;throw Error("Unknown cryptor error")}getCryptor(e){if("string"==typeof e){const t=this.getAllCryptors().find((t=>t.identifier===e));if(t)return t;throw new Error("Unknown cryptor error")}if(e instanceof j)return this.getCryptorFromId(e.identifier)}getHeaderData(e){if(!e.metadata)return;const t=M.from(this.defaultCryptor.identifier,e.metadata),s=new Uint8Array(t.length);let n=0;return s.set(t.data,n),n+=t.length-e.metadata.byteLength,s.set(new Uint8Array(e.metadata),n),s.buffer}concatArrayBuffer(e,t){const s=new Uint8Array(e.byteLength+t.byteLength);return s.set(new Uint8Array(e),0),s.set(new Uint8Array(t),e.byteLength),s.buffer}getFileData(e){return i(this,void 0,void 0,(function*(){if(e instanceof ArrayBuffer)return e;if(e instanceof a)return e.toArrayBuffer();throw new Error("Cannot decrypt/encrypt file. In browsers file encrypt/decrypt supported for string, ArrayBuffer or Blob")}))}}P.LEGACY_IDENTIFIER="";class M{static from(e,t){if(e!==M.LEGACY_IDENTIFIER)return new j(e,t.byteLength)}static tryParse(e){const t=new Uint8Array(e);let s,n,r=null;if(t.byteLength>=4&&(s=t.slice(0,4),this.decoder.decode(s)!==M.SENTINEL))return P.LEGACY_IDENTIFIER;if(!(t.byteLength>=5))throw new Error("Decryption error: invalid header version");if(r=t[4],r>M.MAX_VERSION)throw new Error("Decryption error: Unknown cryptor error");let i=5+M.IDENTIFIER_LENGTH;if(!(t.byteLength>=i))throw new Error("Decryption error: invalid crypto identifier");n=t.slice(5,i);let o=null;if(!(t.byteLength>=i+1))throw new Error("Decryption error: invalid metadata length");return o=t[i],i+=1,255===o&&t.byteLength>=i+2&&(o=new Uint16Array(t.slice(i,i+2)).reduce(((e,t)=>(e<<8)+t),0)),new j(this.decoder.decode(n),o)}}M.SENTINEL="PNED",M.LEGACY_IDENTIFIER="",M.IDENTIFIER_LENGTH=4,M.VERSION=1,M.MAX_VERSION=1,M.decoder=new TextDecoder;class j{constructor(e,t){this._identifier=e,this._metadataLength=t}get identifier(){return this._identifier}set identifier(e){this._identifier=e}get metadataLength(){return this._metadataLength}set metadataLength(e){this._metadataLength=e}get version(){return M.VERSION}get length(){return M.SENTINEL.length+1+M.IDENTIFIER_LENGTH+(this.metadataLength<255?1:3)+this.metadataLength}get data(){let e=0;const t=new Uint8Array(this.length),s=new TextEncoder;t.set(s.encode(M.SENTINEL)),e+=M.SENTINEL.length,t[e]=this.version,e++,this.identifier&&t.set(s.encode(this.identifier),e);const n=this.metadataLength;return e+=M.IDENTIFIER_LENGTH,n<255?t[e]=n:t.set([255,n>>8,255&n],e),t}}j.IDENTIFIER_LENGTH=4,j.SENTINEL="PNED";class _ extends Error{static create(e,t){return e instanceof Error?_.createFromError(e):_.createFromServiceResponse(e,t)}static createFromError(e){let t=h.PNUnknownCategory,s="Unknown error",n="Error";if(!e)return new _(s,t,0);if(e instanceof _)return e;if(e instanceof Error&&(s=e.message,n=e.name),"AbortError"===n||-1!==s.indexOf("Aborted"))t=h.PNCancelledCategory,s="Request cancelled";else if(-1!==s.indexOf("timeout"))t=h.PNTimeoutCategory,s="Request timeout";else if(-1!==s.indexOf("network"))t=h.PNNetworkIssuesCategory,s="Network issues";else if("TypeError"===n)t=h.PNBadRequestCategory;else if("FetchError"===n){const n=e.code;["ECONNREFUSED","ENETUNREACH","ENOTFOUND","ECONNRESET","EAI_AGAIN"].includes(n)&&(t=h.PNNetworkIssuesCategory),"ECONNREFUSED"===n?s="Connection refused":"ENETUNREACH"===n?s="Network not reachable":"ENOTFOUND"===n?s="Server not found":"ECONNRESET"===n?s="Connection reset by peer":"EAI_AGAIN"===n?s="Name resolution error":"ETIMEDOUT"===n?(t=h.PNTimeoutCategory,s="Request timeout"):s=`Unknown system error: ${e}`}else"Request timeout"===s&&(t=h.PNTimeoutCategory);return new _(s,t,0,e)}static createFromServiceResponse(e,t){let s,n=h.PNUnknownCategory,r="Unknown error",{status:i}=e;if(null!=t||(t=e.body),402===i?r="Not available for used key set. Contact support@pubnub.com":400===i?(n=h.PNBadRequestCategory,r="Bad request"):403===i&&(n=h.PNAccessDeniedCategory,r="Access denied"),t&&t.byteLength>0){const n=(new TextDecoder).decode(t);if(-1!==e.headers["content-type"].indexOf("text/javascript")||-1!==e.headers["content-type"].indexOf("application/json"))try{const e=JSON.parse(n);"object"!=typeof e||Array.isArray(e)||("error"in e&&(1===e.error||!0===e.error)&&"status"in e&&"number"==typeof e.status&&"message"in e&&"service"in e?(s=e,i=e.status):s=e,"error"in e&&e.error instanceof Error&&(s=e.error))}catch(e){s=n}else if(-1!==e.headers["content-type"].indexOf("xml")){const e=/(.*)<\/Message>/gi.exec(n);r=e?`Upload to bucket failed: ${e[1]}`:"Upload to bucket failed."}else s=n}return new _(r,n,i,s)}constructor(e,t,s,n){super(e),this.category=t,this.statusCode=s,this.errorData=n,this.name="PubNubAPIError"}toStatus(e){return{error:!0,category:this.category,operation:e,statusCode:this.statusCode,errorData:this.errorData}}toPubNubError(e,t){return new d(null!=t?t:this.message,this.toStatus(e))}}class A{constructor(e){this.configuration=e,this.subscriptionWorkerReady=!1,this.workerEventsQueue=[],this.callbacks=new Map,this.setupSubscriptionWorker()}makeSendable(e){if(!e.path.startsWith("/v2/subscribe")&&!e.path.endsWith("/leave"))return this.configuration.transport.makeSendable(e);let t;const s={type:"send-request",clientIdentifier:this.configuration.clientIdentifier,subscriptionKey:this.configuration.subscriptionKey,logVerbosity:this.configuration.logVerbosity,request:e};return e.cancellable&&(t={abort:()=>{const t={type:"cancel-request",clientIdentifier:this.configuration.clientIdentifier,subscriptionKey:this.configuration.subscriptionKey,logVerbosity:this.configuration.logVerbosity,identifier:e.identifier};this.scheduleEventPost(t)}}),[new Promise(((t,n)=>{this.callbacks.set(e.identifier,{resolve:t,reject:n}),this.scheduleEventPost(s)})),t]}request(e){return e}scheduleEventPost(e,t=!1){const s=this.sharedSubscriptionWorker;s?s.port.postMessage(e):t?this.workerEventsQueue.splice(0,0,e):this.workerEventsQueue.push(e)}flushScheduledEvents(){const e=this.sharedSubscriptionWorker;if(!e||0===this.workerEventsQueue.length)return;const t=[];for(let e=0;e!t.includes(e))),this.workerEventsQueue.forEach((t=>e.port.postMessage(t))),this.workerEventsQueue=[]}get sharedSubscriptionWorker(){return this.subscriptionWorkerReady?this.subscriptionWorker:null}setupSubscriptionWorker(){"undefined"!=typeof SharedWorker&&(this.subscriptionWorker=new SharedWorker(this.configuration.workerUrl,`/pubnub-${this.configuration.sdkVersion}`),this.subscriptionWorker.port.start(),this.scheduleEventPost({type:"client-register",clientIdentifier:this.configuration.clientIdentifier,subscriptionKey:this.configuration.subscriptionKey,userId:this.configuration.userId,logVerbosity:this.configuration.logVerbosity,workerLogVerbosity:this.configuration.workerLogVerbosity},!0),this.subscriptionWorker.port.onmessage=e=>this.handleWorkerEvent(e))}handleWorkerEvent(e){const{data:t}=e;if("shared-worker-ping"===t.type||"shared-worker-connected"===t.type||"shared-worker-console-log"===t.type||"shared-worker-console-dir"===t.type||t.clientIdentifier===this.configuration.clientIdentifier)if("shared-worker-connected"===t.type)this.subscriptionWorkerReady=!0,this.flushScheduledEvents();else if("shared-worker-console-log"===t.type)console.log(`[SharedWorker] ${t.message}`);else if("shared-worker-console-dir"===t.type)t.message&&console.log(`[SharedWorker] ${t.message}`),console.dir(t.data);else if("shared-worker-ping"===t.type){const{logVerbosity:e,subscriptionKey:t,clientIdentifier:s}=this.configuration;this.scheduleEventPost({type:"client-pong",subscriptionKey:t,clientIdentifier:s,logVerbosity:e})}else if("request-progress-start"===t.type||"request-progress-end"===t.type)this.logRequestProgress(t);else if("request-process-success"===t.type||"request-process-error"===t.type){const{resolve:e,reject:s}=this.callbacks.get(t.identifier);if("request-process-success"===t.type)e({status:t.response.status,url:t.url,headers:t.response.headers,body:t.response.body});else{let e=h.PNUnknownCategory,n="Unknown error";if(t.error)"NETWORK_ISSUE"===t.error.type?e=h.PNNetworkIssuesCategory:"TIMEOUT"===t.error.type?e=h.PNTimeoutCategory:"ABORTED"===t.error.type&&(e=h.PNCancelledCategory),n=`${t.error.message} (${t.identifier})`;else if(t.response)return s(_.create({url:t.url,headers:t.response.headers,body:t.response.body,status:t.response.status},t.response.body));s(new _(n,e,0,new Error(n)))}}}logRequestProgress(e){var t,s;"request-progress-start"===e.type?(console.log("<<<<<"),console.log(`[${e.timestamp}] ${e.url}\n${JSON.stringify(null!==(t=e.query)&&void 0!==t?t:{})}`),console.log("-----")):(console.log(">>>>>>"),console.log(`[${e.timestamp} / ${e.duration}] ${e.url}\n${JSON.stringify(null!==(s=e.query)&&void 0!==s?s:{})}\n${e.response}`),console.log("-----"))}}const I=e=>encodeURIComponent(e).replace(/[!~*'()]/g,(e=>`%${e.charCodeAt(0).toString(16).toUpperCase()}`)),R=(e,t)=>{const s=e.map((e=>I(e)));return s.length?s.join(","):null!=t?t:""},U=(e,t)=>{const s=Object.fromEntries(t.map((e=>[e,!1])));return e.filter((e=>!(t.includes(e)&&!s[e])||(s[e]=!0,!1)))},T=(e,t)=>[...e].filter((s=>t.includes(s)&&e.indexOf(s)===e.lastIndexOf(s)&&t.indexOf(s)===t.lastIndexOf(s)));class F{constructor(e=!1,t){this.keepAlive=e,this.logVerbosity=t}makeSendable(e){let t,s;return e.cancellable&&(s=new AbortController,t={abortController:s,abort:()=>null==s?void 0:s.abort()}),[this.requestFromTransportRequest(e).then((t=>{const n=(new Date).getTime();this.logRequestProcessProgress(t);const r=new Promise(((t,s)=>{const n=setTimeout((()=>{clearTimeout(n),s(new Error("Request timeout"))}),1e3*e.timeout)}));return Promise.race([fetch(t,{signal:null==s?void 0:s.signal}),r]).then((e=>e.arrayBuffer().then((t=>[e,t])))).then((e=>{const s=e[1].byteLength>0?e[1]:void 0,{status:r,headers:i}=e[0],o={};i.forEach(((e,t)=>o[t]=e.toLowerCase()));const a={status:r,url:t.url,headers:o,body:s};if(r>=400)throw _.create(a);return this.logRequestProcessProgress(t,(new Date).getTime()-n,s),a})).catch((e=>{throw _.create(e)}))})),t]}request(e){return e}requestFromTransportRequest(e){return i(this,void 0,void 0,(function*(){let t,s=e.path;if(e.formData&&e.formData.length>0){e.queryParameters={};const s=e.body,n=new FormData;for(const{key:t,value:s}of e.formData)n.append(t,s);try{const e=yield s.toArrayBuffer();n.append("file",new Blob([e],{type:"application/octet-stream"}),s.name)}catch(e){try{const e=yield s.toFileUri();n.append("file",e,s.name)}catch(e){}}t=n}else e.body&&("string"==typeof e.body||e.body instanceof ArrayBuffer)&&(t=e.body);var n;return e.queryParameters&&0!==Object.keys(e.queryParameters).length&&(s=`${s}?${n=e.queryParameters,Object.keys(n).map((e=>{const t=n[e];return Array.isArray(t)?t.map((t=>`${e}=${I(t)}`)).join("&"):`${e}=${I(t)}`})).join("&")}`),new Request(`${e.origin}${s}`,{method:e.method,headers:e.headers,redirect:"follow",body:t})}))}logRequestProcessProgress(e,t,s){if(!this.logVerbosity)return;const{protocol:n,host:r,pathname:i,search:o}=new URL(e.url),a=(new Date).toISOString();if(t){const e=s?F.decoder.decode(s):void 0;console.log(">>>>>>"),console.log(`[${a} / ${t}]`,`\n${n}//${r}${i}`,`\n${o}`,`\n${e}`),console.log("-----")}else console.log("<<<<<"),console.log(`[${a}]`,`\n${n}//${r}${i}`,`\n${o}`),console.log("-----")}}function x(e){const t=e=>"object"==typeof e&&null!==e&&e.constructor===Object,s=e=>"number"==typeof e&&isFinite(e);if(!t(e))return e;const n={};return Object.keys(e).forEach((r=>{const i=(e=>"string"==typeof e||e instanceof String)(r);let o=r;const a=e[r];if(i&&r.indexOf(",")>=0){o=r.split(",").map(Number).reduce(((e,t)=>e+String.fromCharCode(t)),"")}else(s(r)||i&&!isNaN(Number(r)))&&(o=String.fromCharCode(s(r)?r:parseInt(r,10)));n[o]=t(a)?x(a):a})),n}F.decoder=new TextDecoder;const D=e=>{var t,s,n;return e.subscriptionWorkerUrl&&"undefined"==typeof SharedWorker&&(e.subscriptionWorkerUrl=null),Object.assign(Object.assign({},(e=>{var t,s,n,r,i,o,a,c,u,l,h,p,g,y,f;const m=Object.assign({},e);if(null!==(t=m.logVerbosity)&&void 0!==t||(m.logVerbosity=!1),null!==(s=m.ssl)&&void 0!==s||(m.ssl=!0),null!==(n=m.transactionalRequestTimeout)&&void 0!==n||(m.transactionalRequestTimeout=15),null!==(r=m.subscribeRequestTimeout)&&void 0!==r||(m.subscribeRequestTimeout=310),null!==(i=m.restore)&&void 0!==i||(m.restore=!1),null!==(o=m.useInstanceId)&&void 0!==o||(m.useInstanceId=!1),null!==(a=m.suppressLeaveEvents)&&void 0!==a||(m.suppressLeaveEvents=!1),null!==(c=m.requestMessageCountThreshold)&&void 0!==c||(m.requestMessageCountThreshold=100),null!==(u=m.autoNetworkDetection)&&void 0!==u||(m.autoNetworkDetection=!1),null!==(l=m.enableEventEngine)&&void 0!==l||(m.enableEventEngine=!1),null!==(h=m.maintainPresenceState)&&void 0!==h||(m.maintainPresenceState=!0),null!==(p=m.keepAlive)&&void 0!==p||(m.keepAlive=!1),m.userId&&m.uuid)throw new d("PubNub client configuration error: use only 'userId'");if(null!==(g=m.userId)&&void 0!==g||(m.userId=m.uuid),!m.userId)throw new d("PubNub client configuration error: 'userId' not set");if(0===(null===(y=m.userId)||void 0===y?void 0:y.trim().length))throw new d("PubNub client configuration error: 'userId' is empty");m.origin||(m.origin=Array.from({length:20},((e,t)=>`ps${t+1}.pndsn.com`)));const b={subscribeKey:m.subscribeKey,publishKey:m.publishKey,secretKey:m.secretKey};void 0!==m.presenceTimeout&&m.presenceTimeout<20&&(m.presenceTimeout=20,console.log("WARNING: Presence timeout is less than the minimum. Using minimum value: ",20)),null!==(f=m.presenceTimeout)&&void 0!==f||(m.presenceTimeout=300);let v=!1,w=!0,S=5,k=!1,E=!0;return void 0!==m.dedupeOnSubscribe&&"boolean"==typeof m.dedupeOnSubscribe&&(k=m.dedupeOnSubscribe),void 0!==m.useRequestId&&"boolean"==typeof m.useRequestId&&(E=m.useRequestId),void 0!==m.announceSuccessfulHeartbeats&&"boolean"==typeof m.announceSuccessfulHeartbeats&&(v=m.announceSuccessfulHeartbeats),void 0!==m.announceFailedHeartbeats&&"boolean"==typeof m.announceFailedHeartbeats&&(w=m.announceFailedHeartbeats),void 0!==m.fileUploadPublishRetryLimit&&"number"==typeof m.fileUploadPublishRetryLimit&&(S=m.fileUploadPublishRetryLimit),Object.assign(Object.assign({},m),{keySet:b,dedupeOnSubscribe:k,maximumCacheSize:100,useRequestId:E,announceSuccessfulHeartbeats:v,announceFailedHeartbeats:w,fileUploadPublishRetryLimit:S})})(e)),{listenToBrowserNetworkEvents:null===(t=e.listenToBrowserNetworkEvents)||void 0===t||t,subscriptionWorkerUrl:e.subscriptionWorkerUrl,subscriptionWorkerLogVerbosity:null!==(s=e.subscriptionWorkerLogVerbosity)&&void 0!==s&&s,keepAlive:null===(n=e.keepAlive)||void 0===n||n})};var K={exports:{}}; +/*! lil-uuid - v0.1 - MIT License - https://github.com/lil-js/uuid */!function(e,t){!function(e){var t="0.1.0",s={3:/^[0-9A-F]{8}-[0-9A-F]{4}-3[0-9A-F]{3}-[0-9A-F]{4}-[0-9A-F]{12}$/i,4:/^[0-9A-F]{8}-[0-9A-F]{4}-4[0-9A-F]{3}-[89AB][0-9A-F]{3}-[0-9A-F]{12}$/i,5:/^[0-9A-F]{8}-[0-9A-F]{4}-5[0-9A-F]{3}-[89AB][0-9A-F]{3}-[0-9A-F]{12}$/i,all:/^[0-9A-F]{8}-[0-9A-F]{4}-[0-9A-F]{4}-[0-9A-F]{4}-[0-9A-F]{12}$/i};function n(){var e,t,s="";for(e=0;e<32;e++)t=16*Math.random()|0,8!==e&&12!==e&&16!==e&&20!==e||(s+="-"),s+=(12===e?4:16===e?3&t|8:t).toString(16);return s}function r(e,t){var n=s[t||"all"];return n&&n.test(e)||!1}n.isUUID=r,n.VERSION=t,e.uuid=n,e.isUUID=r}(t),null!==e&&(e.exports=t.uuid)}(K,K.exports);var q=t(K.exports),G={createUUID:()=>q.uuid?q.uuid():q()};const $=(e,t)=>{var s,n,r;null===(s=e.retryConfiguration)||void 0===s||s.validate(),null!==(n=e.useRandomIVs)&&void 0!==n||(e.useRandomIVs=true),e.origin=L(null!==(r=e.ssl)&&void 0!==r&&r,e.origin);const i=e.cryptoModule;i&&delete e.cryptoModule;const o=Object.assign(Object.assign({},e),{_pnsdkSuffix:{},_instanceId:`pn-${G.createUUID()}`,_cryptoModule:void 0,_cipherKey:void 0,_setupCryptoModule:t,get instanceId(){if(this.useInstanceId)return this._instanceId},getUserId(){return this.userId},setUserId(e){if(!e||"string"!=typeof e||0===e.trim().length)throw new Error("Missing or invalid userId parameter. Provide a valid string userId");this.userId=e},getAuthKey(){return this.authKey},setAuthKey(e){this.authKey=e},getFilterExpression(){return this.filterExpression},setFilterExpression(e){this.filterExpression=e},getCipherKey(){return this._cipherKey},setCipherKey(t){this._cipherKey=t,t||!this._cryptoModule?t&&this._setupCryptoModule&&(this._cryptoModule=this._setupCryptoModule({cipherKey:t,useRandomIVs:e.useRandomIVs,customEncrypt:this.getCustomEncrypt(),customDecrypt:this.getCustomDecrypt()})):this._cryptoModule=void 0},getCryptoModule(){return this._cryptoModule},getUseRandomIVs:()=>e.useRandomIVs,setPresenceTimeout(e){this.heartbeatInterval=e/2-1,this.presenceTimeout=e},getPresenceTimeout(){return this.presenceTimeout},getHeartbeatInterval(){return this.heartbeatInterval},setHeartbeatInterval(e){this.heartbeatInterval=e},getTransactionTimeout(){return this.transactionalRequestTimeout},getSubscribeTimeout(){return this.subscribeRequestTimeout},get PubNubFile(){return e.PubNubFile},get version(){return"8.0.1"},getVersion(){return this.version},_addPnsdkSuffix(e,t){this._pnsdkSuffix[e]=`${t}`},_getPnsdkSuffix(e){const t=Object.values(this._pnsdkSuffix).join(e);return t.length>0?e+t:""},getUUID(){return this.getUserId()},setUUID(e){this.setUserId(e)},getCustomEncrypt:()=>e.customEncrypt,getCustomDecrypt:()=>e.customDecrypt});return e.cipherKey?o.setCipherKey(e.cipherKey):i&&(o._cryptoModule=i),o},L=(e,t)=>{const s=e?"https://":"http://";return"string"==typeof t?`${s}${t}`:`${s}${t[Math.floor(Math.random()*t.length)]}`};class B{constructor(e){this.cbor=e}setToken(e){e&&e.length>0?this.token=e:this.token=void 0}getToken(){return this.token}parseToken(e){const t=this.cbor.decodeToken(e);if(void 0!==t){const e=t.res.uuid?Object.keys(t.res.uuid):[],s=Object.keys(t.res.chan),n=Object.keys(t.res.grp),r=t.pat.uuid?Object.keys(t.pat.uuid):[],i=Object.keys(t.pat.chan),o=Object.keys(t.pat.grp),a={version:t.v,timestamp:t.t,ttl:t.ttl,authorized_uuid:t.uuid,signature:t.sig},c=e.length>0,u=s.length>0,l=n.length>0;if(c||u||l){if(a.resources={},c){const s=a.resources.uuids={};e.forEach((e=>s[e]=this.extractPermissions(t.res.uuid[e])))}if(u){const e=a.resources.channels={};s.forEach((s=>e[s]=this.extractPermissions(t.res.chan[s])))}if(l){const e=a.resources.groups={};n.forEach((s=>e[s]=this.extractPermissions(t.res.grp[s])))}}const h=r.length>0,d=i.length>0,p=o.length>0;if(h||d||p){if(a.patterns={},h){const e=a.patterns.uuids={};r.forEach((s=>e[s]=this.extractPermissions(t.pat.uuid[s])))}if(d){const e=a.patterns.channels={};i.forEach((s=>e[s]=this.extractPermissions(t.pat.chan[s])))}if(p){const e=a.patterns.groups={};o.forEach((s=>e[s]=this.extractPermissions(t.pat.grp[s])))}}return t.meta&&Object.keys(t.meta).length>0&&(a.meta=t.meta),a}}extractPermissions(e){const t={read:!1,write:!1,manage:!1,delete:!1,get:!1,update:!1,join:!1};return 128&~e||(t.join=!0),64&~e||(t.update=!0),32&~e||(t.get=!0),8&~e||(t.delete=!0),4&~e||(t.manage=!0),2&~e||(t.write=!0),1&~e||(t.read=!0),t}}var H;!function(e){e.GET="GET",e.POST="POST",e.PATCH="PATCH",e.DELETE="DELETE",e.LOCAL="LOCAL"}(H||(H={}));class z{constructor(e,t,s){this.publishKey=e,this.secretKey=t,this.hasher=s}signature(e){const t=e.path.startsWith("/publish")?H.GET:e.method;let s=`${t}\n${this.publishKey}\n${e.path}\n${this.queryParameters(e.queryParameters)}\n`;if(t===H.POST||t===H.PATCH){const t=e.body;let n;t&&t instanceof ArrayBuffer?n=z.textDecoder.decode(t):t&&"object"!=typeof t&&(n=t),n&&(s+=n)}return`v2.${this.hasher(s,this.secretKey)}`.replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}queryParameters(e){return Object.keys(e).sort().map((t=>{const s=e[t];return Array.isArray(s)?s.sort().map((e=>`${t}=${I(e)}`)).join("&"):`${t}=${I(s)}`})).join("&")}}z.textDecoder=new TextDecoder("utf-8");class V{constructor(e){this.configuration=e;const{clientConfiguration:{keySet:t},shaHMAC:s}=e;t.secretKey&&s&&(this.signatureGenerator=new z(t.publishKey,t.secretKey,s))}makeSendable(e){return this.configuration.transport.makeSendable(this.request(e))}request(e){var t;const{clientConfiguration:s}=this.configuration;return(e=this.configuration.transport.request(e)).queryParameters||(e.queryParameters={}),s.useInstanceId&&(e.queryParameters.instanceid=s.instanceId),e.queryParameters.uuid||(e.queryParameters.uuid=s.userId),s.useRequestId&&(e.queryParameters.requestid=e.identifier),e.queryParameters.pnsdk=this.generatePNSDK(),null!==(t=e.origin)&&void 0!==t||(e.origin=s.origin),this.authenticateRequest(e),this.signRequest(e),e}authenticateRequest(e){var t;if(e.path.startsWith("/v2/auth/")||e.path.startsWith("/v3/pam/")||e.path.startsWith("/time"))return;const{clientConfiguration:s,tokenManager:n}=this.configuration,r=null!==(t=n.getToken())&&void 0!==t?t:s.authKey;r&&(e.queryParameters.auth=r)}signRequest(e){this.signatureGenerator&&!e.path.startsWith("/time")&&(e.queryParameters.timestamp=String(Math.floor((new Date).getTime()/1e3)),e.queryParameters.signature=this.signatureGenerator.signature(e))}generatePNSDK(){const{clientConfiguration:e}=this.configuration;if(e.sdkName)return e.sdkName;let t=`PubNub-JS-${e.sdkFamily}`;e.partnerId&&(t+=`-${e.partnerId}`),t+=`/${e.getVersion()}`;const s=e._getPnsdkSuffix(" ");return s.length>0&&(t+=s),t}}class W{constructor(){this.listeners=[]}addListener(e){this.listeners.includes(e)||this.listeners.push(e)}removeListener(e){this.listeners=this.listeners.filter((t=>t!==e))}removeAllListeners(){this.listeners=[]}announceStatus(e){this.listeners.forEach((t=>{t.status&&t.status(e)}))}announcePresence(e){this.listeners.forEach((t=>{t.presence&&t.presence(e)}))}announceMessage(e){this.listeners.forEach((t=>{t.message&&t.message(e)}))}announceSignal(e){this.listeners.forEach((t=>{t.signal&&t.signal(e)}))}announceMessageAction(e){this.listeners.forEach((t=>{t.messageAction&&t.messageAction(e)}))}announceFile(e){this.listeners.forEach((t=>{t.file&&t.file(e)}))}announceObjects(e){this.listeners.forEach((t=>{t.objects&&t.objects(e)}))}announceNetworkUp(){this.listeners.forEach((e=>{e.status&&e.status({category:h.PNNetworkUpCategory})}))}announceNetworkDown(){this.listeners.forEach((e=>{e.status&&e.status({category:h.PNNetworkDownCategory})}))}announceUser(e){this.listeners.forEach((t=>{t.user&&t.user(e)}))}announceSpace(e){this.listeners.forEach((t=>{t.space&&t.space(e)}))}announceMembership(e){this.listeners.forEach((t=>{t.membership&&t.membership(e)}))}}class J{constructor(e){this.time=e}onReconnect(e){this.callback=e}startPolling(){this.timeTimer=setInterval((()=>this.callTime()),3e3)}stopPolling(){this.timeTimer&&clearInterval(this.timeTimer),this.timeTimer=null}callTime(){this.time((e=>{e.error||(this.stopPolling(),this.callback&&this.callback())}))}}class Q{_config;hashHistory;constructor({config:e}){this.hashHistory=[],this._config=e}getKey(e){const t=(e=>{let t=0;if(0===e.length)return t;for(let s=0;s=this._config.maximumCacheSize&&this.hashHistory.shift(),this.hashHistory.push(this.getKey(e))}clearHistory(){this.hashHistory=[]}}class Y{constructor(e,t,s,n,r,i,o){this.configuration=e,this.listenerManager=t,this.eventEmitter=s,this.subscribeCall=n,this.heartbeatCall=r,this.leaveCall=i,this.reconnectionManager=new J(o),this.dedupingManager=new Q({config:this.configuration}),this.heartbeatChannelGroups={},this.heartbeatChannels={},this.presenceChannelGroups={},this.presenceChannels={},this.heartbeatTimer=null,this.presenceState={},this.pendingChannelGroupSubscriptions=new Set,this.pendingChannelSubscriptions=new Set,this.channelGroups={},this.channels={},this.currentTimetoken="0",this.lastTimetoken="0",this.storedTimetoken=null,this.subscriptionStatusAnnounced=!1,this.isOnline=!0}get subscribedChannels(){return Object.keys(this.channels)}get subscribedChannelGroups(){return Object.keys(this.channelGroups)}get abort(){return this._subscribeAbort}set abort(e){this._subscribeAbort=e}disconnect(){this.stopSubscribeLoop(),this.stopHeartbeatTimer(),this.reconnectionManager.stopPolling()}reconnect(){this.startSubscribeLoop(),this.startHeartbeatTimer()}subscribe(e){const{channels:t,channelGroups:s,timetoken:n,withPresence:r=!1,withHeartbeats:i=!1}=e;n&&(this.lastTimetoken=this.currentTimetoken,this.currentTimetoken=n),"0"!==this.currentTimetoken&&0!==this.currentTimetoken&&(this.storedTimetoken=this.currentTimetoken,this.currentTimetoken=0),null==t||t.forEach((e=>{this.pendingChannelSubscriptions.add(e),this.channels[e]={},r&&(this.presenceChannels[e]={}),(i||this.configuration.getHeartbeatInterval())&&(this.heartbeatChannels[e]={})})),null==s||s.forEach((e=>{this.pendingChannelGroupSubscriptions.add(e),this.channelGroups[e]={},r&&(this.presenceChannelGroups[e]={}),(i||this.configuration.getHeartbeatInterval())&&(this.heartbeatChannelGroups[e]={})})),this.subscriptionStatusAnnounced=!1,this.reconnect()}unsubscribe(e,t){let{channels:s,channelGroups:n}=e;const i=new Set,o=new Set;null==s||s.forEach((e=>{e in this.channels&&(delete this.channels[e],o.add(e),e in this.heartbeatChannels&&delete this.heartbeatChannels[e]),e in this.presenceState&&delete this.presenceState[e],e in this.presenceChannels&&(delete this.presenceChannels[e],o.add(e))})),null==n||n.forEach((e=>{e in this.channelGroups&&(delete this.channelGroups[e],i.add(e),e in this.heartbeatChannelGroups&&delete this.heartbeatChannelGroups[e]),e in this.presenceState&&delete this.presenceState[e],e in this.presenceChannelGroups&&(delete this.presenceChannelGroups[e],i.add(e))})),0===o.size&&0===i.size||(!1!==this.configuration.suppressLeaveEvents||t||(n=Array.from(i),s=Array.from(o),this.leaveCall({channels:s,channelGroups:n},(e=>{const{error:t}=e,i=r(e,["error"]);let o;t&&(e.errorData&&"object"==typeof e.errorData&&"message"in e.errorData&&"string"==typeof e.errorData.message?o=e.errorData.message:"message"in e&&"string"==typeof e.message&&(o=e.message)),this.listenerManager.announceStatus(Object.assign(Object.assign({},i),{error:null!=o&&o,affectedChannels:s,affectedChannelGroups:n,currentTimetoken:this.currentTimetoken,lastTimetoken:this.lastTimetoken}))}))),0===Object.keys(this.channels).length&&0===Object.keys(this.presenceChannels).length&&0===Object.keys(this.channelGroups).length&&0===Object.keys(this.presenceChannelGroups).length&&(this.lastTimetoken=0,this.currentTimetoken=0,this.storedTimetoken=null,this.region=null,this.reconnectionManager.stopPolling()),this.reconnect())}unsubscribeAll(e){this.unsubscribe({channels:this.subscribedChannels,channelGroups:this.subscribedChannelGroups},e)}startSubscribeLoop(){this.stopSubscribeLoop();const e=[...Object.keys(this.channelGroups)],t=[...Object.keys(this.channels)];Object.keys(this.presenceChannelGroups).forEach((t=>e.push(`${t}-pnpres`))),Object.keys(this.presenceChannels).forEach((e=>t.push(`${e}-pnpres`))),0===t.length&&0===e.length||this.subscribeCall({channels:t,channelGroups:e,state:this.presenceState,heartbeat:this.configuration.getPresenceTimeout(),timetoken:this.currentTimetoken,region:null!==this.region?this.region:void 0,filterExpression:this.configuration.filterExpression},((e,t)=>{this.processSubscribeResponse(e,t)}))}stopSubscribeLoop(){this._subscribeAbort&&(this._subscribeAbort(),this._subscribeAbort=null)}processSubscribeResponse(e,t){if(e.error){if("object"==typeof e.errorData&&"name"in e.errorData&&"AbortError"===e.errorData.name||e.category===h.PNCancelledCategory)return;return void(e.category===h.PNTimeoutCategory?this.startSubscribeLoop():e.category===h.PNNetworkIssuesCategory?(this.disconnect(),e.error&&this.configuration.autoNetworkDetection&&this.isOnline&&(this.isOnline=!1,this.listenerManager.announceNetworkDown()),this.reconnectionManager.onReconnect((()=>{this.configuration.autoNetworkDetection&&!this.isOnline&&(this.isOnline=!0,this.listenerManager.announceNetworkUp()),this.reconnect(),this.subscriptionStatusAnnounced=!0;const t={category:h.PNReconnectedCategory,operation:e.operation,lastTimetoken:this.lastTimetoken,currentTimetoken:this.currentTimetoken};this.listenerManager.announceStatus(t)})),this.reconnectionManager.startPolling(),this.listenerManager.announceStatus(e)):e.category===h.PNBadRequestCategory?(this.stopHeartbeatTimer(),this.listenerManager.announceStatus(e)):this.listenerManager.announceStatus(e))}if(this.storedTimetoken?(this.currentTimetoken=this.storedTimetoken,this.storedTimetoken=null):(this.lastTimetoken=this.currentTimetoken,this.currentTimetoken=t.cursor.timetoken),!this.subscriptionStatusAnnounced){const t={category:h.PNConnectedCategory,operation:e.operation,affectedChannels:Array.from(this.pendingChannelSubscriptions),subscribedChannels:this.subscribedChannels,affectedChannelGroups:Array.from(this.pendingChannelGroupSubscriptions),lastTimetoken:this.lastTimetoken,currentTimetoken:this.currentTimetoken};this.subscriptionStatusAnnounced=!0,this.listenerManager.announceStatus(t),this.pendingChannelGroupSubscriptions.clear(),this.pendingChannelSubscriptions.clear()}const{messages:s}=t,{requestMessageCountThreshold:n,dedupeOnSubscribe:r}=this.configuration;n&&s.length>=n&&this.listenerManager.announceStatus({category:h.PNRequestMessageCountExceededCategory,operation:e.operation});try{s.forEach((e=>{if(r){if(this.dedupingManager.isDuplicate(e.data))return;this.dedupingManager.addEntry(e.data)}this.eventEmitter.emitEvent(e)}))}catch(e){const t={error:!0,category:h.PNUnknownCategory,errorData:e,statusCode:0};this.listenerManager.announceStatus(t)}this.region=t.cursor.region,this.startSubscribeLoop()}setState(e){const{state:t,channels:s,channelGroups:n}=e;null==s||s.forEach((e=>e in this.channels&&(this.presenceState[e]=t))),null==n||n.forEach((e=>e in this.channelGroups&&(this.presenceState[e]=t)))}changePresence(e){const{connected:t,channels:s,channelGroups:n}=e;t?(null==s||s.forEach((e=>this.heartbeatChannels[e]={})),null==n||n.forEach((e=>this.heartbeatChannelGroups[e]={}))):(null==s||s.forEach((e=>{e in this.heartbeatChannels&&delete this.heartbeatChannels[e]})),null==n||n.forEach((e=>{e in this.heartbeatChannelGroups&&delete this.heartbeatChannelGroups[e]})),!1===this.configuration.suppressLeaveEvents&&this.leaveCall({channels:s,channelGroups:n},(e=>this.listenerManager.announceStatus(e)))),this.reconnect()}startHeartbeatTimer(){this.stopHeartbeatTimer();const e=this.configuration.getHeartbeatInterval();e&&0!==e&&(this.sendHeartbeat(),this.heartbeatTimer=setInterval((()=>this.sendHeartbeat()),1e3*e))}stopHeartbeatTimer(){this.heartbeatTimer&&(clearInterval(this.heartbeatTimer),this.heartbeatTimer=null)}sendHeartbeat(){const e=Object.keys(this.heartbeatChannelGroups),t=Object.keys(this.heartbeatChannels);0===t.length&&0===e.length||this.heartbeatCall({channels:t,channelGroups:e,heartbeat:this.configuration.getPresenceTimeout(),state:this.presenceState},(e=>{e.error&&this.configuration.announceFailedHeartbeats&&this.listenerManager.announceStatus(e),e.error&&this.configuration.autoNetworkDetection&&this.isOnline&&(this.isOnline=!1,this.disconnect(),this.listenerManager.announceNetworkDown(),this.reconnect()),!e.error&&this.configuration.announceSuccessfulHeartbeats&&this.listenerManager.announceStatus(e)}))}}class X{constructor(e,t,s){this._payload=e,this.setDefaultPayloadStructure(),this.title=t,this.body=s}get payload(){return this._payload}set title(e){this._title=e}set subtitle(e){this._subtitle=e}set body(e){this._body=e}set badge(e){this._badge=e}set sound(e){this._sound=e}setDefaultPayloadStructure(){}toObject(){return{}}}class Z extends X{constructor(){super(...arguments),this._apnsPushType="apns",this._isSilent=!1}get payload(){return this._payload}set configurations(e){e&&e.length&&(this._configurations=e)}get notification(){return this.payload.aps}get title(){return this._title}set title(e){e&&e.length&&(this.payload.aps.alert.title=e,this._title=e)}get subtitle(){return this._subtitle}set subtitle(e){e&&e.length&&(this.payload.aps.alert.subtitle=e,this._subtitle=e)}get body(){return this._body}set body(e){e&&e.length&&(this.payload.aps.alert.body=e,this._body=e)}get badge(){return this._badge}set badge(e){null!=e&&(this.payload.aps.badge=e,this._badge=e)}get sound(){return this._sound}set sound(e){e&&e.length&&(this.payload.aps.sound=e,this._sound=e)}set silent(e){this._isSilent=e}setDefaultPayloadStructure(){this.payload.aps={alert:{}}}toObject(){const e=Object.assign({},this.payload),{aps:t}=e;let{alert:s}=t;if(this._isSilent&&(t["content-available"]=1),"apns2"===this._apnsPushType){if(!this._configurations||!this._configurations.length)throw new ReferenceError("APNS2 configuration is missing");const t=[];this._configurations.forEach((e=>{t.push(this.objectFromAPNS2Configuration(e))})),t.length&&(e.pn_push=t)}return s&&Object.keys(s).length||delete t.alert,this._isSilent&&(delete t.alert,delete t.badge,delete t.sound,s={}),this._isSilent||s&&Object.keys(s).length?e:null}objectFromAPNS2Configuration(e){if(!e.targets||!e.targets.length)throw new ReferenceError("At least one APNS2 target should be provided");const{collapseId:t,expirationDate:s}=e,n={auth_method:"token",targets:e.targets.map((e=>this.objectFromAPNSTarget(e))),version:"v2"};return t&&t.length&&(n.collapse_id=t),s&&(n.expiration=s.toISOString()),n}objectFromAPNSTarget(e){if(!e.topic||!e.topic.length)throw new TypeError("Target 'topic' undefined.");const{topic:t,environment:s="development",excludedDevices:n=[]}=e,r={topic:t,environment:s};return n.length&&(r.excluded_devices=n),r}}class ee extends X{get payload(){return this._payload}get notification(){return this.payload.notification}get data(){return this.payload.data}get title(){return this._title}set title(e){e&&e.length&&(this.payload.notification.title=e,this._title=e)}get body(){return this._body}set body(e){e&&e.length&&(this.payload.notification.body=e,this._body=e)}get sound(){return this._sound}set sound(e){e&&e.length&&(this.payload.notification.sound=e,this._sound=e)}get icon(){return this._icon}set icon(e){e&&e.length&&(this.payload.notification.icon=e,this._icon=e)}get tag(){return this._tag}set tag(e){e&&e.length&&(this.payload.notification.tag=e,this._tag=e)}set silent(e){this._isSilent=e}setDefaultPayloadStructure(){this.payload.notification={},this.payload.data={}}toObject(){let e=Object.assign({},this.payload.data),t=null;const s={};if(Object.keys(this.payload).length>2){const t=r(this.payload,["notification","data"]);e=Object.assign(Object.assign({},e),t)}return this._isSilent?e.notification=this.payload.notification:t=this.payload.notification,Object.keys(e).length&&(s.data=e),t&&Object.keys(t).length&&(s.notification=t),Object.keys(s).length?s:null}}class te{constructor(e,t){this._payload={apns:{},fcm:{}},this._title=e,this._body=t,this.apns=new Z(this._payload.apns,e,t),this.fcm=new ee(this._payload.fcm,e,t)}set debugging(e){this._debugging=e}get title(){return this._title}get subtitle(){return this._subtitle}set subtitle(e){this._subtitle=e,this.apns.subtitle=e,this.fcm.subtitle=e}get body(){return this._body}get badge(){return this._badge}set badge(e){this._badge=e,this.apns.badge=e,this.fcm.badge=e}get sound(){return this._sound}set sound(e){this._sound=e,this.apns.sound=e,this.fcm.sound=e}buildPayload(e){const t={};if(e.includes("apns")||e.includes("apns2")){this.apns._apnsPushType=e.includes("apns")?"apns":"apns2";const s=this.apns.toObject();s&&Object.keys(s).length&&(t.pn_apns=s)}if(e.includes("fcm")){const e=this.fcm.toObject();e&&Object.keys(e).length&&(t.pn_gcm=e)}return Object.keys(t).length&&this._debugging&&(t.pn_debug=!0),t}}class se{constructor(e){this.params=e,this.requestIdentifier=G.createUUID(),this._cancellationController=null}get cancellationController(){return this._cancellationController}set cancellationController(e){this._cancellationController=e}abort(){this&&this.cancellationController&&this.cancellationController.abort()}operation(){throw Error("Should be implemented by subclass.")}validate(){}parse(e){return i(this,void 0,void 0,(function*(){throw Error("Should be implemented by subclass.")}))}request(){var e,t,s,n;const r={method:null!==(t=null===(e=this.params)||void 0===e?void 0:e.method)&&void 0!==t?t:H.GET,path:this.path,queryParameters:this.queryParameters,cancellable:null!==(n=null===(s=this.params)||void 0===s?void 0:s.cancellable)&&void 0!==n&&n,timeout:1e4,identifier:this.requestIdentifier},i=this.headers;if(i&&(r.headers=i),r.method===H.POST||r.method===H.PATCH){const[e,t]=[this.body,this.formData];t&&(r.formData=t),e&&(r.body=e)}return r}get headers(){}get path(){throw Error("`path` getter should be implemented by subclass.")}get queryParameters(){return{}}get formData(){}get body(){}deserializeResponse(e){const t=e.headers["content-type"];if(!t||-1===t.indexOf("javascript")&&-1===t.indexOf("json"))return;const s=se.decoder.decode(e.body);try{return JSON.parse(s)}catch(e){return void console.error("Error parsing JSON response:",e)}}}var ne;se.decoder=new TextDecoder,function(e){e.PNPublishOperation="PNPublishOperation",e.PNSignalOperation="PNSignalOperation",e.PNSubscribeOperation="PNSubscribeOperation",e.PNUnsubscribeOperation="PNUnsubscribeOperation",e.PNWhereNowOperation="PNWhereNowOperation",e.PNHereNowOperation="PNHereNowOperation",e.PNGlobalHereNowOperation="PNGlobalHereNowOperation",e.PNSetStateOperation="PNSetStateOperation",e.PNGetStateOperation="PNGetStateOperation",e.PNHeartbeatOperation="PNHeartbeatOperation",e.PNAddMessageActionOperation="PNAddActionOperation",e.PNRemoveMessageActionOperation="PNRemoveMessageActionOperation",e.PNGetMessageActionsOperation="PNGetMessageActionsOperation",e.PNTimeOperation="PNTimeOperation",e.PNHistoryOperation="PNHistoryOperation",e.PNDeleteMessagesOperation="PNDeleteMessagesOperation",e.PNFetchMessagesOperation="PNFetchMessagesOperation",e.PNMessageCounts="PNMessageCountsOperation",e.PNGetAllUUIDMetadataOperation="PNGetAllUUIDMetadataOperation",e.PNGetUUIDMetadataOperation="PNGetUUIDMetadataOperation",e.PNSetUUIDMetadataOperation="PNSetUUIDMetadataOperation",e.PNRemoveUUIDMetadataOperation="PNRemoveUUIDMetadataOperation",e.PNGetAllChannelMetadataOperation="PNGetAllChannelMetadataOperation",e.PNGetChannelMetadataOperation="PNGetChannelMetadataOperation",e.PNSetChannelMetadataOperation="PNSetChannelMetadataOperation",e.PNRemoveChannelMetadataOperation="PNRemoveChannelMetadataOperation",e.PNGetMembersOperation="PNGetMembersOperation",e.PNSetMembersOperation="PNSetMembersOperation",e.PNGetMembershipsOperation="PNGetMembershipsOperation",e.PNSetMembershipsOperation="PNSetMembershipsOperation",e.PNListFilesOperation="PNListFilesOperation",e.PNGenerateUploadUrlOperation="PNGenerateUploadUrlOperation",e.PNPublishFileOperation="PNPublishFileOperation",e.PNPublishFileMessageOperation="PNPublishFileMessageOperation",e.PNGetFileUrlOperation="PNGetFileUrlOperation",e.PNDownloadFileOperation="PNDownloadFileOperation",e.PNDeleteFileOperation="PNDeleteFileOperation",e.PNAddPushNotificationEnabledChannelsOperation="PNAddPushNotificationEnabledChannelsOperation",e.PNRemovePushNotificationEnabledChannelsOperation="PNRemovePushNotificationEnabledChannelsOperation",e.PNPushNotificationEnabledChannelsOperation="PNPushNotificationEnabledChannelsOperation",e.PNRemoveAllPushNotificationsOperation="PNRemoveAllPushNotificationsOperation",e.PNChannelGroupsOperation="PNChannelGroupsOperation",e.PNRemoveGroupOperation="PNRemoveGroupOperation",e.PNChannelsForGroupOperation="PNChannelsForGroupOperation",e.PNAddChannelsToGroupOperation="PNAddChannelsToGroupOperation",e.PNRemoveChannelsFromGroupOperation="PNRemoveChannelsFromGroupOperation",e.PNAccessManagerGrant="PNAccessManagerGrant",e.PNAccessManagerGrantToken="PNAccessManagerGrantToken",e.PNAccessManagerAudit="PNAccessManagerAudit",e.PNAccessManagerRevokeToken="PNAccessManagerRevokeToken",e.PNHandshakeOperation="PNHandshakeOperation",e.PNReceiveMessagesOperation="PNReceiveMessagesOperation"}(ne||(ne={}));var re=ne;var ie;!function(e){e[e.Presence=-2]="Presence",e[e.Message=-1]="Message",e[e.Signal=1]="Signal",e[e.AppContext=2]="AppContext",e[e.MessageAction=3]="MessageAction",e[e.Files=4]="Files"}(ie||(ie={}));class oe extends se{constructor(e){var t,s,n,r,i,o;super({cancellable:!0}),this.parameters=e,null!==(t=(r=this.parameters).withPresence)&&void 0!==t||(r.withPresence=false),null!==(s=(i=this.parameters).channelGroups)&&void 0!==s||(i.channelGroups=[]),null!==(n=(o=this.parameters).channels)&&void 0!==n||(o.channels=[])}operation(){return re.PNSubscribeOperation}validate(){const{keySet:{subscribeKey:e},channels:t,channelGroups:s}=this.parameters;return e?t||s?void 0:"`channels` and `channelGroups` both should not be empty":"Missing Subscribe Key"}parse(e){return i(this,void 0,void 0,(function*(){let t;try{const s=se.decoder.decode(e.body);t=JSON.parse(s)}catch(e){console.error("Error parsing JSON response:",e)}if(!t)throw new d("Service response error, check status for details",p("Unable to deserialize service response"));const s=t.m.map((e=>{let{e:t}=e;return null!=t||(t=e.c.endsWith("-pnpres")?ie.Presence:ie.Message),"string"==typeof e.d?t==ie.Message?{type:ie.Message,data:this.messageFromEnvelope(e)}:{type:ie.Files,data:this.fileFromEnvelope(e)}:t==ie.Message?{type:ie.Message,data:this.messageFromEnvelope(e)}:t===ie.Presence?{type:ie.Presence,data:this.presenceEventFromEnvelope(e)}:t==ie.Signal?{type:ie.Signal,data:this.signalFromEnvelope(e)}:t===ie.AppContext?{type:ie.AppContext,data:this.appContextFromEnvelope(e)}:t===ie.MessageAction?{type:ie.MessageAction,data:this.messageActionFromEnvelope(e)}:{type:ie.Files,data:this.fileFromEnvelope(e)}}));return{cursor:{timetoken:t.t.t,region:t.t.r},messages:s}}))}get headers(){return{accept:"text/javascript"}}presenceEventFromEnvelope(e){const{d:t}=e,[s,n]=this.subscriptionChannelFromEnvelope(e),r=s.replace("-pnpres",""),i=null!==n?r:null,o=null!==n?n:r;return"string"!=typeof t&&"data"in t&&(t.state=t.data,delete t.data),Object.assign({channel:r,subscription:n,actualChannel:i,subscribedChannel:o,timetoken:e.p.t},t)}messageFromEnvelope(e){const[t,s]=this.subscriptionChannelFromEnvelope(e),[n,r]=this.decryptedData(e.d),i={channel:t,subscription:s,actualChannel:null!==s?t:null,subscribedChannel:null!==s?s:t,timetoken:e.p.t,publisher:e.i,message:n};return e.u&&(i.userMetadata=e.u),r&&(i.error=r),i}signalFromEnvelope(e){const[t,s]=this.subscriptionChannelFromEnvelope(e),n={channel:t,subscription:s,timetoken:e.p.t,publisher:e.i,message:e.d};return e.u&&(n.userMetadata=e.u),n}messageActionFromEnvelope(e){const[t,s]=this.subscriptionChannelFromEnvelope(e),n=e.d;return{channel:t,subscription:s,timetoken:e.p.t,publisher:e.i,event:n.event,data:Object.assign(Object.assign({},n.data),{uuid:e.i})}}appContextFromEnvelope(e){const[t,s]=this.subscriptionChannelFromEnvelope(e),n=e.d;return{channel:t,subscription:s,timetoken:e.p.t,message:n}}fileFromEnvelope(e){const[t,s]=this.subscriptionChannelFromEnvelope(e),[n,r]=this.decryptedData(e.d);let i=r;const o={channel:t,subscription:s,timetoken:e.p.t,publisher:e.i};return e.u&&(o.userMetadata=e.u),n?"string"==typeof n?null!=i||(i="Unexpected file information payload data type."):(o.message=n.message,n.file&&(o.file={id:n.file.id,name:n.file.name,url:this.parameters.getFileUrl({id:n.file.id,name:n.file.name,channel:t})})):null!=i||(i="File information payload is missing."),i&&(o.error=i),o}subscriptionChannelFromEnvelope(e){return[e.c,void 0===e.b?e.c:e.b]}decryptedData(e){if(!this.parameters.crypto||"string"!=typeof e)return[e,void 0];let t,s;try{const s=this.parameters.crypto.decrypt(e);t=s instanceof ArrayBuffer?JSON.parse(ae.decoder.decode(s)):s}catch(e){t=null,s=`Error while decrypting message content: ${e.message}`}return[null!=t?t:e,s]}}class ae extends oe{get path(){var e;const{keySet:{subscribeKey:t},channels:s}=this.parameters;return`/v2/subscribe/${t}/${R(null!==(e=null==s?void 0:s.sort())&&void 0!==e?e:[],",")}/0`}get queryParameters(){const{channelGroups:e,filterExpression:t,heartbeat:s,state:n,timetoken:r,region:i}=this.parameters,o={};return e&&e.length>0&&(o["channel-group"]=e.sort().join(",")),t&&t.length>0&&(o["filter-expr"]=t),s&&(o.heartbeat=s),n&&Object.keys(n).length>0&&(o.state=JSON.stringify(n)),void 0!==r&&"string"==typeof r?r.length>0&&"0"!==r&&(o.tt=r):void 0!==r&&r>0&&(o.tt=r),i&&(o.tr=i),o}}class ce{constructor(e){this.listenerManager=e,this.channelListenerMap=new Map,this.groupListenerMap=new Map}emitEvent(e){if(e.type===ie.Message)this.listenerManager.announceMessage(e.data),this.announce("message",e.data,e.data.channel,e.data.subscription);else if(e.type===ie.Signal)this.listenerManager.announceSignal(e.data),this.announce("signal",e.data,e.data.channel,e.data.subscription);else if(e.type===ie.Presence)this.listenerManager.announcePresence(e.data),this.announce("presence",e.data,e.data.channel,e.data.subscription);else if(e.type===ie.AppContext){const{data:t}=e,{message:s}=t;if(this.listenerManager.announceObjects(t),this.announce("objects",t,t.channel,t.subscription),"uuid"===s.type){const{message:e,channel:n}=t,i=r(t,["message","channel"]),{event:o,type:a}=s,c=r(s,["event","type"]),u=Object.assign(Object.assign({},i),{spaceId:n,message:Object.assign(Object.assign({},c),{event:"set"===o?"updated":"removed",type:"user"})});this.listenerManager.announceUser(u),this.announce("user",u,u.spaceId,u.subscription)}else if("channel"===s.type){const{message:e,channel:n}=t,i=r(t,["message","channel"]),{event:o,type:a}=s,c=r(s,["event","type"]),u=Object.assign(Object.assign({},i),{spaceId:n,message:Object.assign(Object.assign({},c),{event:"set"===o?"updated":"removed",type:"space"})});this.listenerManager.announceSpace(u),this.announce("space",u,u.spaceId,u.subscription)}else if("membership"===s.type){const{message:e,channel:n}=t,i=r(t,["message","channel"]),{event:o,data:a}=s,c=r(s,["event","data"]),{uuid:u,channel:l}=a,h=r(a,["uuid","channel"]),d=Object.assign(Object.assign({},i),{spaceId:n,message:Object.assign(Object.assign({},c),{event:"set"===o?"updated":"removed",data:Object.assign(Object.assign({},h),{user:u,space:l})})});this.listenerManager.announceMembership(d),this.announce("membership",d,d.spaceId,d.subscription)}}else e.type===ie.MessageAction?(this.listenerManager.announceMessageAction(e.data),this.announce("messageAction",e.data,e.data.channel,e.data.subscription)):e.type===ie.Files&&(this.listenerManager.announceFile(e.data),this.announce("file",e.data,e.data.channel,e.data.subscription))}addListener(e,t,s){t&&s?(null==t||t.forEach((t=>{if(this.channelListenerMap.has(t)){const s=this.channelListenerMap.get(t);s.includes(e)||s.push(e)}else this.channelListenerMap.set(t,[e])})),null==s||s.forEach((t=>{if(this.groupListenerMap.has(t)){const s=this.groupListenerMap.get(t);s.includes(e)||s.push(e)}else this.groupListenerMap.set(t,[e])}))):this.listenerManager.addListener(e)}removeListener(e,t,s){t&&s?(null==t||t.forEach((t=>{this.channelListenerMap.has(t)&&this.channelListenerMap.set(t,this.channelListenerMap.get(t).filter((t=>t!==e)))})),null==s||s.forEach((t=>{this.groupListenerMap.has(t)&&this.groupListenerMap.set(t,this.groupListenerMap.get(t).filter((t=>t!==e)))}))):this.listenerManager.removeListener(e)}removeAllListeners(){this.listenerManager.removeAllListeners(),this.channelListenerMap.clear(),this.groupListenerMap.clear()}announce(e,t,s,n){t&&this.channelListenerMap.has(s)&&this.channelListenerMap.get(s).forEach((s=>{const n=s[e];n&&n(t)})),n&&this.groupListenerMap.has(n)&&this.groupListenerMap.get(n).forEach((s=>{const n=s[e];n&&n(t)}))}}class ue{constructor(e=!1){this.sync=e,this.listeners=new Set}subscribe(e){return this.listeners.add(e),()=>{this.listeners.delete(e)}}notify(e){const t=()=>{this.listeners.forEach((t=>{t(e)}))};this.sync?t():setTimeout(t,0)}}class le{transition(e,t){var s;if(this.transitionMap.has(t.type))return null===(s=this.transitionMap.get(t.type))||void 0===s?void 0:s(e,t)}constructor(e){this.label=e,this.transitionMap=new Map,this.enterEffects=[],this.exitEffects=[]}on(e,t){return this.transitionMap.set(e,t),this}with(e,t){return[this,e,null!=t?t:[]]}onEnter(e){return this.enterEffects.push(e),this}onExit(e){return this.exitEffects.push(e),this}}class he extends ue{describe(e){return new le(e)}start(e,t){this.currentState=e,this.currentContext=t,this.notify({type:"engineStarted",state:e,context:t})}transition(e){if(!this.currentState)throw new Error("Start the engine first");this.notify({type:"eventReceived",event:e});const t=this.currentState.transition(this.currentContext,e);if(t){const[s,n,r]=t;for(const e of this.currentState.exitEffects)this.notify({type:"invocationDispatched",invocation:e(this.currentContext)});const i=this.currentState;this.currentState=s;const o=this.currentContext;this.currentContext=n,this.notify({type:"transitionDone",fromState:i,fromContext:o,toState:s,toContext:n,event:e});for(const e of r)this.notify({type:"invocationDispatched",invocation:e});for(const e of this.currentState.enterEffects)this.notify({type:"invocationDispatched",invocation:e(this.currentContext)})}}}class de{constructor(e){this.dependencies=e,this.instances=new Map,this.handlers=new Map}on(e,t){this.handlers.set(e,t)}dispatch(e){if("CANCEL"===e.type){if(this.instances.has(e.payload)){const t=this.instances.get(e.payload);null==t||t.cancel(),this.instances.delete(e.payload)}return}const t=this.handlers.get(e.type);if(!t)throw new Error(`Unhandled invocation '${e.type}'`);const s=t(e.payload,this.dependencies);e.managed&&this.instances.set(e.type,s),s.start()}dispose(){for(const[e,t]of this.instances.entries())t.cancel(),this.instances.delete(e)}}function pe(e,t){const s=function(...s){return{type:e,payload:null==t?void 0:t(...s)}};return s.type=e,s}function ge(e,t){const s=(...s)=>({type:e,payload:t(...s),managed:!1});return s.type=e,s}function ye(e,t){const s=(...s)=>({type:e,payload:t(...s),managed:!0});return s.type=e,s.cancel={type:"CANCEL",payload:e,managed:!1},s}class fe extends Error{constructor(){super("The operation was aborted."),this.name="AbortError",Object.setPrototypeOf(this,new.target.prototype)}}class me extends ue{constructor(){super(...arguments),this._aborted=!1}get aborted(){return this._aborted}throwIfAborted(){if(this._aborted)throw new fe}abort(){this._aborted=!0,this.notify(new fe)}}class be{constructor(e,t){this.payload=e,this.dependencies=t}}class ve extends be{constructor(e,t,s){super(e,t),this.asyncFunction=s,this.abortSignal=new me}start(){this.asyncFunction(this.payload,this.abortSignal,this.dependencies).catch((e=>{}))}cancel(){this.abortSignal.abort()}}const we=e=>(t,s)=>new ve(t,s,e),Se=pe("RECONNECT",(()=>({}))),ke=pe("DISCONNECT",(()=>({}))),Ee=pe("JOINED",((e,t)=>({channels:e,groups:t}))),Oe=pe("LEFT",((e,t)=>({channels:e,groups:t}))),Ce=pe("LEFT_ALL",(()=>({}))),Ne=pe("HEARTBEAT_SUCCESS",(e=>({statusCode:e}))),Pe=pe("HEARTBEAT_FAILURE",(e=>e)),Me=pe("HEARTBEAT_GIVEUP",(()=>({}))),je=pe("TIMES_UP",(()=>({}))),_e=ge("HEARTBEAT",((e,t)=>({channels:e,groups:t}))),Ae=ge("LEAVE",((e,t)=>({channels:e,groups:t}))),Ie=ge("EMIT_STATUS",(e=>e)),Re=ye("WAIT",(()=>({}))),Ue=ye("DELAYED_HEARTBEAT",(e=>e));class Te extends de{constructor(e,t){super(t),this.on(_e.type,we(((t,s,n)=>i(this,[t,s,n],void 0,(function*(t,s,{heartbeat:n,presenceState:r,config:i}){try{yield n(Object.assign(Object.assign({channels:t.channels,channelGroups:t.groups},i.maintainPresenceState&&{state:r}),{heartbeat:i.presenceTimeout}));e.transition(Ne(200))}catch(t){if(t instanceof d){if(t.status&&t.status.category==h.PNCancelledCategory)return;return e.transition(Pe(t))}}}))))),this.on(Ae.type,we(((e,t,s)=>i(this,[e,t,s],void 0,(function*(e,t,{leave:s,config:n}){if(!n.suppressLeaveEvents)try{s({channels:e.channels,channelGroups:e.groups})}catch(e){}}))))),this.on(Re.type,we(((t,s,n)=>i(this,[t,s,n],void 0,(function*(t,s,{heartbeatDelay:n}){return s.throwIfAborted(),yield n(),s.throwIfAborted(),e.transition(je())}))))),this.on(Ue.type,we(((t,s,n)=>i(this,[t,s,n],void 0,(function*(t,s,{heartbeat:n,retryDelay:r,presenceState:i,config:o}){if(!o.retryConfiguration||!o.retryConfiguration.shouldRetry(t.reason,t.attempts))return e.transition(Me());s.throwIfAborted(),yield r(o.retryConfiguration.getDelay(t.attempts,t.reason)),s.throwIfAborted();try{yield n(Object.assign(Object.assign({channels:t.channels,channelGroups:t.groups},o.maintainPresenceState&&{state:i}),{heartbeat:o.presenceTimeout}));return e.transition(Ne(200))}catch(t){if(t instanceof d){if(t.status&&t.status.category==h.PNCancelledCategory)return;return e.transition(Pe(t))}}}))))),this.on(Ie.type,we(((e,t,s)=>i(this,[e,t,s],void 0,(function*(e,t,{emitStatus:s,config:n}){var r;n.announceFailedHeartbeats&&!0===(null===(r=null==e?void 0:e.status)||void 0===r?void 0:r.error)?s(e.status):n.announceSuccessfulHeartbeats&&200===e.statusCode&&s(Object.assign(Object.assign({},e),{operation:re.PNHeartbeatOperation,error:!1}))})))))}}const Fe=new le("HEARTBEAT_STOPPED");Fe.on(Ee.type,((e,t)=>Fe.with({channels:[...e.channels,...t.payload.channels],groups:[...e.groups,...t.payload.groups]}))),Fe.on(Oe.type,((e,t)=>Fe.with({channels:e.channels.filter((e=>!t.payload.channels.includes(e))),groups:e.groups.filter((e=>!t.payload.groups.includes(e)))}))),Fe.on(Se.type,((e,t)=>qe.with({channels:e.channels,groups:e.groups}))),Fe.on(Ce.type,((e,t)=>Ge.with(void 0)));const xe=new le("HEARTBEAT_COOLDOWN");xe.onEnter((()=>Re())),xe.onExit((()=>Re.cancel)),xe.on(je.type,((e,t)=>qe.with({channels:e.channels,groups:e.groups}))),xe.on(Ee.type,((e,t)=>qe.with({channels:[...e.channels,...t.payload.channels],groups:[...e.groups,...t.payload.groups]}))),xe.on(Oe.type,((e,t)=>qe.with({channels:e.channels.filter((e=>!t.payload.channels.includes(e))),groups:e.groups.filter((e=>!t.payload.groups.includes(e)))},[Ae(t.payload.channels,t.payload.groups)]))),xe.on(ke.type,(e=>Fe.with({channels:e.channels,groups:e.groups},[Ae(e.channels,e.groups)]))),xe.on(Ce.type,((e,t)=>Ge.with(void 0,[Ae(e.channels,e.groups)])));const De=new le("HEARTBEAT_FAILED");De.on(Ee.type,((e,t)=>qe.with({channels:[...e.channels,...t.payload.channels],groups:[...e.groups,...t.payload.groups]}))),De.on(Oe.type,((e,t)=>qe.with({channels:e.channels.filter((e=>!t.payload.channels.includes(e))),groups:e.groups.filter((e=>!t.payload.groups.includes(e)))},[Ae(t.payload.channels,t.payload.groups)]))),De.on(Se.type,((e,t)=>qe.with({channels:e.channels,groups:e.groups}))),De.on(ke.type,((e,t)=>Fe.with({channels:e.channels,groups:e.groups},[Ae(e.channels,e.groups)]))),De.on(Ce.type,((e,t)=>Ge.with(void 0,[Ae(e.channels,e.groups)])));const Ke=new le("HEARBEAT_RECONNECTING");Ke.onEnter((e=>Ue(e))),Ke.onExit((()=>Ue.cancel)),Ke.on(Ee.type,((e,t)=>qe.with({channels:[...e.channels,...t.payload.channels],groups:[...e.groups,...t.payload.groups]}))),Ke.on(Oe.type,((e,t)=>qe.with({channels:e.channels.filter((e=>!t.payload.channels.includes(e))),groups:e.groups.filter((e=>!t.payload.groups.includes(e)))},[Ae(t.payload.channels,t.payload.groups)]))),Ke.on(ke.type,((e,t)=>{Fe.with({channels:e.channels,groups:e.groups},[Ae(e.channels,e.groups)])})),Ke.on(Ne.type,((e,t)=>xe.with({channels:e.channels,groups:e.groups}))),Ke.on(Pe.type,((e,t)=>Ke.with(Object.assign(Object.assign({},e),{attempts:e.attempts+1,reason:t.payload})))),Ke.on(Me.type,((e,t)=>De.with({channels:e.channels,groups:e.groups}))),Ke.on(Ce.type,((e,t)=>Ge.with(void 0,[Ae(e.channels,e.groups)])));const qe=new le("HEARTBEATING");qe.onEnter((e=>_e(e.channels,e.groups))),qe.on(Ne.type,((e,t)=>xe.with({channels:e.channels,groups:e.groups}))),qe.on(Ee.type,((e,t)=>qe.with({channels:[...e.channels,...t.payload.channels],groups:[...e.groups,...t.payload.groups]}))),qe.on(Oe.type,((e,t)=>qe.with({channels:e.channels.filter((e=>!t.payload.channels.includes(e))),groups:e.groups.filter((e=>!t.payload.groups.includes(e)))},[Ae(t.payload.channels,t.payload.groups)]))),qe.on(Pe.type,((e,t)=>Ke.with(Object.assign(Object.assign({},e),{attempts:0,reason:t.payload})))),qe.on(ke.type,(e=>Fe.with({channels:e.channels,groups:e.groups},[Ae(e.channels,e.groups)]))),qe.on(Ce.type,((e,t)=>Ge.with(void 0,[Ae(e.channels,e.groups)])));const Ge=new le("HEARTBEAT_INACTIVE");Ge.on(Ee.type,((e,t)=>qe.with({channels:t.payload.channels,groups:t.payload.groups})));class $e{get _engine(){return this.engine}constructor(e){this.dependencies=e,this.engine=new he,this.channels=[],this.groups=[],this.dispatcher=new Te(this.engine,e),this._unsubscribeEngine=this.engine.subscribe((e=>{"invocationDispatched"===e.type&&this.dispatcher.dispatch(e.invocation)})),this.engine.start(Ge,void 0)}join({channels:e,groups:t}){this.channels=[...this.channels,...null!=e?e:[]],this.groups=[...this.groups,...null!=t?t:[]],this.engine.transition(Ee(this.channels.slice(0),this.groups.slice(0)))}leave({channels:e,groups:t}){this.dependencies.presenceState&&(null==e||e.forEach((e=>delete this.dependencies.presenceState[e])),null==t||t.forEach((e=>delete this.dependencies.presenceState[e]))),this.engine.transition(Oe(null!=e?e:[],null!=t?t:[]))}leaveAll(){this.engine.transition(Ce())}dispose(){this._unsubscribeEngine(),this.dispatcher.dispose()}}class Le{static LinearRetryPolicy(e){return{delay:e.delay,maximumRetry:e.maximumRetry,shouldRetry(e,t){var s;return 403!==(null===(s=null==e?void 0:e.status)||void 0===s?void 0:s.statusCode)&&this.maximumRetry>t},getDelay(e,t){var s;return 1e3*((null!==(s=t.retryAfter)&&void 0!==s?s:this.delay)+Math.random())},getGiveupReason(e,t){var s;return this.maximumRetry<=t?"retry attempts exhaused.":403===(null===(s=null==e?void 0:e.status)||void 0===s?void 0:s.statusCode)?"forbidden operation.":"unknown error"},validate(){if(this.maximumRetry>10)throw new Error("Maximum retry for linear retry policy can not be more than 10")}}}static ExponentialRetryPolicy(e){return{minimumDelay:e.minimumDelay,maximumDelay:e.maximumDelay,maximumRetry:e.maximumRetry,shouldRetry(e,t){var s;return 403!==(null===(s=null==e?void 0:e.status)||void 0===s?void 0:s.statusCode)&&this.maximumRetry>t},getDelay(e,t){var s;return 1e3*((null!==(s=t.retryAfter)&&void 0!==s?s:Math.min(Math.pow(2,e),this.maximumDelay))+Math.random())},getGiveupReason(e,t){var s;return this.maximumRetry<=t?"retry attempts exhausted.":403===(null===(s=null==e?void 0:e.status)||void 0===s?void 0:s.statusCode)?"forbidden operation.":"unknown error"},validate(){if(this.minimumDelay<2)throw new Error("Minimum delay can not be set less than 2 seconds for retry");if(this.maximumDelay)throw new Error("Maximum delay can not be set more than 150 seconds for retry");if(this.maximumRetry>6)throw new Error("Maximum retry for exponential retry policy can not be more than 6")}}}}const Be=ye("HANDSHAKE",((e,t)=>({channels:e,groups:t}))),He=ye("RECEIVE_MESSAGES",((e,t,s)=>({channels:e,groups:t,cursor:s}))),ze=ge("EMIT_MESSAGES",(e=>e)),Ve=ge("EMIT_STATUS",(e=>e)),We=ye("RECEIVE_RECONNECT",(e=>e)),Je=ye("HANDSHAKE_RECONNECT",(e=>e)),Qe=pe("SUBSCRIPTION_CHANGED",((e,t)=>({channels:e,groups:t}))),Ye=pe("SUBSCRIPTION_RESTORED",((e,t,s,n)=>({channels:e,groups:t,cursor:{timetoken:s,region:null!=n?n:0}}))),Xe=pe("HANDSHAKE_SUCCESS",(e=>e)),Ze=pe("HANDSHAKE_FAILURE",(e=>e)),et=pe("HANDSHAKE_RECONNECT_SUCCESS",(e=>({cursor:e}))),tt=pe("HANDSHAKE_RECONNECT_FAILURE",(e=>e)),st=pe("HANDSHAKE_RECONNECT_GIVEUP",(e=>e)),nt=pe("RECEIVE_SUCCESS",((e,t)=>({cursor:e,events:t}))),rt=pe("RECEIVE_FAILURE",(e=>e)),it=pe("RECEIVE_RECONNECT_SUCCESS",((e,t)=>({cursor:e,events:t}))),ot=pe("RECEIVE_RECONNECT_FAILURE",(e=>e)),at=pe("RECEIVING_RECONNECT_GIVEUP",(e=>e)),ct=pe("DISCONNECT",(()=>({}))),ut=pe("RECONNECT",((e,t)=>({cursor:{timetoken:null!=e?e:"",region:null!=t?t:0}}))),lt=pe("UNSUBSCRIBE_ALL",(()=>({})));class ht extends de{constructor(e,t){super(t),this.on(Be.type,we(((t,s,n)=>i(this,[t,s,n],void 0,(function*(t,s,{handshake:n,presenceState:r,config:i}){s.throwIfAborted();try{const o=yield n(Object.assign({abortSignal:s,channels:t.channels,channelGroups:t.groups,filterExpression:i.filterExpression},i.maintainPresenceState&&{state:r}));return e.transition(Xe(o))}catch(t){if(t instanceof d){if(t.status&&t.status.category==h.PNCancelledCategory)return;return e.transition(Ze(t))}}}))))),this.on(He.type,we(((t,s,n)=>i(this,[t,s,n],void 0,(function*(t,s,{receiveMessages:n,config:r}){s.throwIfAborted();try{const i=yield n({abortSignal:s,channels:t.channels,channelGroups:t.groups,timetoken:t.cursor.timetoken,region:t.cursor.region,filterExpression:r.filterExpression});e.transition(nt(i.cursor,i.messages))}catch(t){if(t instanceof d){if(t.status&&t.status.category==h.PNCancelledCategory)return;if(!s.aborted)return e.transition(rt(t))}}}))))),this.on(ze.type,we(((e,t,s)=>i(this,[e,t,s],void 0,(function*(e,t,{emitMessages:s}){e.length>0&&s(e)}))))),this.on(Ve.type,we(((e,t,s)=>i(this,[e,t,s],void 0,(function*(e,t,{emitStatus:s}){s(e)}))))),this.on(We.type,we(((t,s,n)=>i(this,[t,s,n],void 0,(function*(t,s,{receiveMessages:n,delay:r,config:i}){if(!i.retryConfiguration||!i.retryConfiguration.shouldRetry(t.reason,t.attempts))return e.transition(at(new d(i.retryConfiguration?i.retryConfiguration.getGiveupReason(t.reason,t.attempts):"Unable to complete subscribe messages receive.")));s.throwIfAborted(),yield r(i.retryConfiguration.getDelay(t.attempts,t.reason)),s.throwIfAborted();try{const r=yield n({abortSignal:s,channels:t.channels,channelGroups:t.groups,timetoken:t.cursor.timetoken,region:t.cursor.region,filterExpression:i.filterExpression});return e.transition(it(r.cursor,r.messages))}catch(t){if(t instanceof d){if(t.status&&t.status.category==h.PNCancelledCategory)return;return e.transition(ot(t))}}}))))),this.on(Je.type,we(((t,s,n)=>i(this,[t,s,n],void 0,(function*(t,s,{handshake:n,delay:r,presenceState:i,config:o}){if(!o.retryConfiguration||!o.retryConfiguration.shouldRetry(t.reason,t.attempts))return e.transition(st(new d(o.retryConfiguration?o.retryConfiguration.getGiveupReason(t.reason,t.attempts):"Unable to complete subscribe handshake")));s.throwIfAborted(),yield r(o.retryConfiguration.getDelay(t.attempts,t.reason)),s.throwIfAborted();try{const r=yield n(Object.assign({abortSignal:s,channels:t.channels,channelGroups:t.groups,filterExpression:o.filterExpression},o.maintainPresenceState&&{state:i}));return e.transition(et(r))}catch(t){if(t instanceof d){if(t.status&&t.status.category==h.PNCancelledCategory)return;return e.transition(tt(t))}}})))))}}const dt=new le("HANDSHAKE_FAILED");dt.on(Qe.type,((e,t)=>vt.with({channels:t.payload.channels,groups:t.payload.groups,cursor:e.cursor}))),dt.on(ut.type,((e,t)=>vt.with({channels:e.channels,groups:e.groups,cursor:t.payload.cursor||e.cursor}))),dt.on(Ye.type,((e,t)=>{var s,n;return vt.with({channels:t.payload.channels,groups:t.payload.groups,cursor:{timetoken:t.payload.cursor.timetoken,region:t.payload.cursor.region?t.payload.cursor.region:null!==(n=null===(s=null==e?void 0:e.cursor)||void 0===s?void 0:s.region)&&void 0!==n?n:0}})})),dt.on(lt.type,(e=>wt.with()));const pt=new le("HANDSHAKE_STOPPED");pt.on(Qe.type,((e,t)=>pt.with({channels:t.payload.channels,groups:t.payload.groups,cursor:e.cursor}))),pt.on(ut.type,((e,t)=>vt.with(Object.assign(Object.assign({},e),{cursor:t.payload.cursor||e.cursor})))),pt.on(Ye.type,((e,t)=>{var s;return pt.with({channels:t.payload.channels,groups:t.payload.groups,cursor:{timetoken:t.payload.cursor.timetoken,region:t.payload.cursor.region||(null===(s=null==e?void 0:e.cursor)||void 0===s?void 0:s.region)||0}})})),pt.on(lt.type,(e=>wt.with()));const gt=new le("RECEIVE_FAILED");gt.on(ut.type,((e,t)=>{var s;return vt.with({channels:e.channels,groups:e.groups,cursor:{timetoken:t.payload.cursor.timetoken?null===(s=t.payload.cursor)||void 0===s?void 0:s.timetoken:e.cursor.timetoken,region:t.payload.cursor.region||e.cursor.region}})})),gt.on(Qe.type,((e,t)=>vt.with({channels:t.payload.channels,groups:t.payload.groups,cursor:e.cursor}))),gt.on(Ye.type,((e,t)=>vt.with({channels:t.payload.channels,groups:t.payload.groups,cursor:{timetoken:t.payload.cursor.timetoken,region:t.payload.cursor.region||e.cursor.region}}))),gt.on(lt.type,(e=>wt.with(void 0)));const yt=new le("RECEIVE_STOPPED");yt.on(Qe.type,((e,t)=>yt.with({channels:t.payload.channels,groups:t.payload.groups,cursor:e.cursor}))),yt.on(Ye.type,((e,t)=>yt.with({channels:t.payload.channels,groups:t.payload.groups,cursor:{timetoken:t.payload.cursor.timetoken,region:t.payload.cursor.region||e.cursor.region}}))),yt.on(ut.type,((e,t)=>{var s;return vt.with({channels:e.channels,groups:e.groups,cursor:{timetoken:t.payload.cursor.timetoken?null===(s=t.payload.cursor)||void 0===s?void 0:s.timetoken:e.cursor.timetoken,region:t.payload.cursor.region||e.cursor.region}})})),yt.on(lt.type,(()=>wt.with(void 0)));const ft=new le("RECEIVE_RECONNECTING");ft.onEnter((e=>We(e))),ft.onExit((()=>We.cancel)),ft.on(it.type,((e,t)=>mt.with({channels:e.channels,groups:e.groups,cursor:t.payload.cursor},[ze(t.payload.events)]))),ft.on(ot.type,((e,t)=>ft.with(Object.assign(Object.assign({},e),{attempts:e.attempts+1,reason:t.payload})))),ft.on(at.type,((e,t)=>{var s;return gt.with({groups:e.groups,channels:e.channels,cursor:e.cursor,reason:t.payload},[Ve({category:h.PNDisconnectedUnexpectedlyCategory,error:null===(s=t.payload)||void 0===s?void 0:s.message})])})),ft.on(ct.type,(e=>yt.with({channels:e.channels,groups:e.groups,cursor:e.cursor},[Ve({category:h.PNDisconnectedCategory})]))),ft.on(Ye.type,((e,t)=>mt.with({channels:t.payload.channels,groups:t.payload.groups,cursor:{timetoken:t.payload.cursor.timetoken,region:t.payload.cursor.region||e.cursor.region}}))),ft.on(Qe.type,((e,t)=>mt.with({channels:t.payload.channels,groups:t.payload.groups,cursor:e.cursor}))),ft.on(lt.type,(e=>wt.with(void 0,[Ve({category:h.PNDisconnectedCategory})])));const mt=new le("RECEIVING");mt.onEnter((e=>He(e.channels,e.groups,e.cursor))),mt.onExit((()=>He.cancel)),mt.on(nt.type,((e,t)=>mt.with({channels:e.channels,groups:e.groups,cursor:t.payload.cursor},[ze(t.payload.events)]))),mt.on(Qe.type,((e,t)=>0===t.payload.channels.length&&0===t.payload.groups.length?wt.with(void 0):mt.with({cursor:e.cursor,channels:t.payload.channels,groups:t.payload.groups}))),mt.on(Ye.type,((e,t)=>0===t.payload.channels.length&&0===t.payload.groups.length?wt.with(void 0):mt.with({channels:t.payload.channels,groups:t.payload.groups,cursor:{timetoken:t.payload.cursor.timetoken,region:t.payload.cursor.region||e.cursor.region}}))),mt.on(rt.type,((e,t)=>ft.with(Object.assign(Object.assign({},e),{attempts:0,reason:t.payload})))),mt.on(ct.type,(e=>yt.with({channels:e.channels,groups:e.groups,cursor:e.cursor},[Ve({category:h.PNDisconnectedCategory})]))),mt.on(lt.type,(e=>wt.with(void 0,[Ve({category:h.PNDisconnectedCategory})])));const bt=new le("HANDSHAKE_RECONNECTING");bt.onEnter((e=>Je(e))),bt.onExit((()=>Je.cancel)),bt.on(et.type,((e,t)=>{var s,n;const r={timetoken:(null===(s=e.cursor)||void 0===s?void 0:s.timetoken)?null===(n=e.cursor)||void 0===n?void 0:n.timetoken:t.payload.cursor.timetoken,region:t.payload.cursor.region};return mt.with({channels:e.channels,groups:e.groups,cursor:r},[Ve({category:h.PNConnectedCategory})])})),bt.on(tt.type,((e,t)=>bt.with(Object.assign(Object.assign({},e),{attempts:e.attempts+1,reason:t.payload})))),bt.on(st.type,((e,t)=>{var s;return dt.with({groups:e.groups,channels:e.channels,cursor:e.cursor,reason:t.payload},[Ve({category:h.PNConnectionErrorCategory,error:null===(s=t.payload)||void 0===s?void 0:s.message})])})),bt.on(ct.type,(e=>pt.with({channels:e.channels,groups:e.groups,cursor:e.cursor}))),bt.on(Qe.type,((e,t)=>vt.with({channels:t.payload.channels,groups:t.payload.groups,cursor:e.cursor}))),bt.on(Ye.type,((e,t)=>{var s,n;return vt.with({channels:t.payload.channels,groups:t.payload.groups,cursor:{timetoken:t.payload.cursor.timetoken,region:(null===(s=t.payload.cursor)||void 0===s?void 0:s.region)||(null===(n=null==e?void 0:e.cursor)||void 0===n?void 0:n.region)||0}})})),bt.on(lt.type,(e=>wt.with(void 0)));const vt=new le("HANDSHAKING");vt.onEnter((e=>Be(e.channels,e.groups))),vt.onExit((()=>Be.cancel)),vt.on(Qe.type,((e,t)=>0===t.payload.channels.length&&0===t.payload.groups.length?wt.with(void 0):vt.with({channels:t.payload.channels,groups:t.payload.groups,cursor:e.cursor}))),vt.on(Xe.type,((e,t)=>{var s,n;return mt.with({channels:e.channels,groups:e.groups,cursor:{timetoken:(null===(s=null==e?void 0:e.cursor)||void 0===s?void 0:s.timetoken)?null===(n=null==e?void 0:e.cursor)||void 0===n?void 0:n.timetoken:t.payload.timetoken,region:t.payload.region}},[Ve({category:h.PNConnectedCategory})])})),vt.on(Ze.type,((e,t)=>bt.with({channels:e.channels,groups:e.groups,cursor:e.cursor,attempts:0,reason:t.payload}))),vt.on(ct.type,(e=>pt.with({channels:e.channels,groups:e.groups,cursor:e.cursor}))),vt.on(Ye.type,((e,t)=>{var s;return vt.with({channels:t.payload.channels,groups:t.payload.groups,cursor:{timetoken:t.payload.cursor.timetoken,region:t.payload.cursor.region||(null===(s=null==e?void 0:e.cursor)||void 0===s?void 0:s.region)||0}})})),vt.on(lt.type,(e=>wt.with()));const wt=new le("UNSUBSCRIBED");wt.on(Qe.type,((e,t)=>vt.with({channels:t.payload.channels,groups:t.payload.groups}))),wt.on(Ye.type,((e,t)=>vt.with({channels:t.payload.channels,groups:t.payload.groups,cursor:t.payload.cursor})));class St{get _engine(){return this.engine}constructor(e){this.engine=new he,this.channels=[],this.groups=[],this.dependencies=e,this.dispatcher=new ht(this.engine,e),this._unsubscribeEngine=this.engine.subscribe((e=>{"invocationDispatched"===e.type&&this.dispatcher.dispatch(e.invocation)})),this.engine.start(wt,void 0)}subscribe({channels:e,channelGroups:t,timetoken:s,withPresence:n}){this.channels=[...this.channels,...null!=e?e:[]],this.groups=[...this.groups,...null!=t?t:[]],n&&(this.channels.map((e=>this.channels.push(`${e}-pnpres`))),this.groups.map((e=>this.groups.push(`${e}-pnpres`)))),s?this.engine.transition(Ye(Array.from(new Set([...this.channels,...null!=e?e:[]])),Array.from(new Set([...this.groups,...null!=t?t:[]])),s)):this.engine.transition(Qe(Array.from(new Set([...this.channels,...null!=e?e:[]])),Array.from(new Set([...this.groups,...null!=t?t:[]])))),this.dependencies.join&&this.dependencies.join({channels:Array.from(new Set(this.channels.filter((e=>!e.endsWith("-pnpres"))))),groups:Array.from(new Set(this.groups.filter((e=>!e.endsWith("-pnpres")))))})}unsubscribe({channels:e=[],channelGroups:t=[]}){const s=U(this.channels,[...e,...e.map((e=>`${e}-pnpres`))]),n=U(this.groups,[...t,...t.map((e=>`${e}-pnpres`))]);if(new Set(this.channels).size!==new Set(s).size||new Set(this.groups).size!==new Set(n).size){const r=T(this.channels,e),i=T(this.groups,t);this.dependencies.presenceState&&(null==r||r.forEach((e=>delete this.dependencies.presenceState[e])),null==i||i.forEach((e=>delete this.dependencies.presenceState[e]))),this.channels=s,this.groups=n,this.engine.transition(Qe(Array.from(new Set(this.channels.slice(0))),Array.from(new Set(this.groups.slice(0))))),this.dependencies.leave&&this.dependencies.leave({channels:r.slice(0),groups:i.slice(0)})}}unsubscribeAll(){this.channels=[],this.groups=[],this.dependencies.presenceState&&Object.keys(this.dependencies.presenceState).forEach((e=>{delete this.dependencies.presenceState[e]})),this.engine.transition(Qe(this.channels.slice(0),this.groups.slice(0))),this.dependencies.leaveAll&&this.dependencies.leaveAll()}reconnect({timetoken:e,region:t}){this.engine.transition(ut(e,t))}disconnect(){this.engine.transition(ct()),this.dependencies.leaveAll&&this.dependencies.leaveAll()}getSubscribedChannels(){return Array.from(new Set(this.channels.slice(0)))}getSubscribedChannelGroups(){return Array.from(new Set(this.groups.slice(0)))}dispose(){this.disconnect(),this._unsubscribeEngine(),this.dispatcher.dispose()}}class kt extends se{constructor(e){var t,s;super({method:e.sendByPost?H.POST:H.GET}),this.parameters=e,null!==(t=(s=this.parameters).sendByPost)&&void 0!==t||(s.sendByPost=false)}operation(){return re.PNPublishOperation}validate(){const{message:e,channel:t,keySet:{publishKey:s}}=this.parameters;return t?e?s?void 0:"Missing 'publishKey'":"Missing 'message'":"Missing 'channel'"}parse(e){return i(this,void 0,void 0,(function*(){const t=this.deserializeResponse(e);if(!t)throw new d("Service response error, check status for details",p("Unable to deserialize service response"));return{timetoken:t[2]}}))}get path(){const{message:e,channel:t,keySet:s}=this.parameters,n=this.prepareMessagePayload(e);return`/publish/${s.publishKey}/${s.subscribeKey}/0/${I(t)}/0${this.parameters.sendByPost?"":`/${I(n)}`}`}get queryParameters(){const{meta:e,replicate:t,storeInHistory:s,ttl:n}=this.parameters,r={};return void 0!==s&&(r.store=s?"1":"0"),void 0!==n&&(r.ttl=n),void 0===t||t||(r.norep="true"),e&&"object"==typeof e&&(r.meta=JSON.stringify(e)),r}get headers(){return{"Content-Type":"application/json"}}get body(){return this.prepareMessagePayload(this.parameters.message)}prepareMessagePayload(e){const{crypto:t}=this.parameters;if(!t)return JSON.stringify(e)||"";const s=t.encrypt(JSON.stringify(e));return JSON.stringify("string"==typeof s?s:u(s))}}class Et extends se{constructor(e){super(),this.parameters=e}operation(){return re.PNSignalOperation}validate(){const{message:e,channel:t,keySet:{publishKey:s}}=this.parameters;return t?e?s?void 0:"Missing 'publishKey'":"Missing 'message'":"Missing 'channel'"}parse(e){return i(this,void 0,void 0,(function*(){const t=this.deserializeResponse(e);if(!t)throw new d("Service response error, check status for details",p("Unable to deserialize service response"));return{timetoken:t[2]}}))}get path(){const{keySet:{publishKey:e,subscribeKey:t},channel:s,message:n}=this.parameters,r=JSON.stringify(n);return`/signal/${e}/${t}/0/${I(s)}/0/${I(r)}`}}class Ot extends oe{operation(){return re.PNReceiveMessagesOperation}validate(){const e=super.validate();return e||(this.parameters.timetoken?this.parameters.region?void 0:"region can not be empty":"timetoken can not be empty")}get path(){const{keySet:{subscribeKey:e},channels:t=[]}=this.parameters;return`/v2/subscribe/${e}/${R(t.sort(),",")}/0`}get queryParameters(){const{channelGroups:e,filterExpression:t,timetoken:s,region:n}=this.parameters,r={ee:""};return e&&e.length>0&&(r["channel-group"]=e.sort().join(",")),t&&t.length>0&&(r["filter-expr"]=t),"string"==typeof s?s&&s.length>0&&(r.tt=s):s&&s>0&&(r.tt=s),n&&(r.tr=n),r}}class Ct extends oe{operation(){return re.PNHandshakeOperation}get path(){const{keySet:{subscribeKey:e},channels:t=[]}=this.parameters;return`/v2/subscribe/${e}/${R(t.sort(),",")}/0`}get queryParameters(){const{channelGroups:e,filterExpression:t,state:s}=this.parameters,n={tt:0,ee:""};return e&&e.length>0&&(n["channel-group"]=e.sort().join(",")),t&&t.length>0&&(n["filter-expr"]=t),s&&Object.keys(s).length>0&&(n.state=JSON.stringify(s)),n}}class Nt extends se{constructor(e){var t,s,n,r;super(),this.parameters=e,null!==(t=(n=this.parameters).channels)&&void 0!==t||(n.channels=[]),null!==(s=(r=this.parameters).channelGroups)&&void 0!==s||(r.channelGroups=[])}operation(){return re.PNGetStateOperation}validate(){const{keySet:{subscribeKey:e},channels:t,channelGroups:s}=this.parameters;if(!e)return"Missing Subscribe Key"}parse(e){return i(this,void 0,void 0,(function*(){const t=this.deserializeResponse(e);if(!t)throw new d("Service response error, check status for details",p("Unable to deserialize service response"));if(t.status>=400)throw _.create(e);const{channels:s=[],channelGroups:n=[]}=this.parameters,r={channels:{}};return 1===s.length&&0===n.length?r.channels[s[0]]=t.payload:r.channels=t.payload,r}))}get path(){const{keySet:{subscribeKey:e},uuid:t,channels:s}=this.parameters;return`/v2/presence/sub-key/${e}/channel/${R(null!=s?s:[],",")}/uuid/${t}`}get queryParameters(){const{channelGroups:e}=this.parameters;return e&&0!==e.length?{"channel-group":e.join(",")}:{}}}class Pt extends se{constructor(e){super(),this.parameters=e}operation(){return re.PNSetStateOperation}validate(){const{keySet:{subscribeKey:e},state:t,channels:s=[],channelGroups:n=[]}=this.parameters;return e?t?0===(null==s?void 0:s.length)&&0===(null==n?void 0:n.length)?"Please provide a list of channels and/or channel-groups":void 0:"Missing State":"Missing Subscribe Key"}parse(e){return i(this,void 0,void 0,(function*(){const t=this.deserializeResponse(e);if(!t)throw new d("Service response error, check status for details",p("Unable to deserialize service response"));if(t.status>=400)throw _.create(e);return{state:t.payload}}))}get path(){const{keySet:{subscribeKey:e},uuid:t,channels:s}=this.parameters;return`/v2/presence/sub-key/${e}/channel/${R(null!=s?s:[],",")}/uuid/${I(t)}/data`}get queryParameters(){const{channelGroups:e,state:t}=this.parameters,s={state:JSON.stringify(t)};return e&&0!==e.length&&(s["channel-group"]=e.join(",")),s}}class Mt extends se{constructor(e){super(),this.parameters=e}operation(){return re.PNHeartbeatOperation}validate(){const{keySet:{subscribeKey:e},channels:t=[],channelGroups:s=[]}=this.parameters;return e?0===t.length&&0===s.length?"Please provide a list of channels and/or channel-groups":void 0:"Missing Subscribe Key"}parse(e){return i(this,void 0,void 0,(function*(){const t=this.deserializeResponse(e);if(!t)throw new d("Service response error, check status for details",p("Unable to deserialize service response"));if(t.status>=400)throw _.create(e);return{}}))}get path(){const{keySet:{subscribeKey:e},channels:t}=this.parameters;return`/v2/presence/sub-key/${e}/channel/${R(null!=t?t:[],",")}/heartbeat`}get queryParameters(){const{channelGroups:e,state:t,heartbeat:s}=this.parameters,n={heartbeat:`${s}`};return e&&0!==e.length&&(n["channel-group"]=e.join(",")),t&&(n.state=JSON.stringify(t)),n}}class jt extends se{constructor(e){super(),this.parameters=e,this.parameters.channelGroups&&(this.parameters.channelGroups=Array.from(new Set(this.parameters.channelGroups))),this.parameters.channels&&(this.parameters.channels=Array.from(new Set(this.parameters.channels)))}operation(){return re.PNUnsubscribeOperation}validate(){const{keySet:{subscribeKey:e},channels:t=[],channelGroups:s=[]}=this.parameters;return e?0===t.length&&0===s.length?"At least one `channel` or `channel group` should be provided.":void 0:"Missing Subscribe Key"}parse(e){return i(this,void 0,void 0,(function*(){const t=this.deserializeResponse(e);if(!t)throw new d("Service response error, check status for details",p("Unable to deserialize service response"));if(t.status>=400)throw _.create(e);return{}}))}get path(){var e;const{keySet:{subscribeKey:t},channels:s}=this.parameters;return`/v2/presence/sub-key/${t}/channel/${R(null!==(e=null==s?void 0:s.sort())&&void 0!==e?e:[],",")}/leave`}get queryParameters(){const{channelGroups:e}=this.parameters;return e&&0!==e.length?{"channel-group":e.sort().join(",")}:{}}}class _t extends se{constructor(e){super(),this.parameters=e}operation(){return re.PNWhereNowOperation}validate(){if(!this.parameters.keySet.subscribeKey)return"Missing Subscribe Key"}parse(e){return i(this,void 0,void 0,(function*(){const t=this.deserializeResponse(e);if(!t)throw new d("Service response error, check status for details",p("Unable to deserialize service response"));if(t.status>=400)throw _.create(e);return t.payload?{channels:t.payload.channels}:{channels:[]}}))}get path(){const{keySet:{subscribeKey:e},uuid:t}=this.parameters;return`/v2/presence/sub-key/${e}/uuid/${I(t)}`}}class At extends se{constructor(e){var t,s,n,r,i,o;super(),this.parameters=e,null!==(t=(r=this.parameters).queryParameters)&&void 0!==t||(r.queryParameters={}),null!==(s=(i=this.parameters).includeUUIDs)&&void 0!==s||(i.includeUUIDs=true),null!==(n=(o=this.parameters).includeState)&&void 0!==n||(o.includeState=false)}operation(){const{channels:e=[],channelGroups:t=[]}=this.parameters;return 0===e.length&&0===t.length?re.PNGlobalHereNowOperation:re.PNHereNowOperation}validate(){if(!this.parameters.keySet.subscribeKey)return"Missing Subscribe Key"}parse(e){return i(this,void 0,void 0,(function*(){var t,s;const n=this.deserializeResponse(e);if(!n)throw new d("Service response error, check status for details",p("Unable to deserialize service response"));if(n.status>=400)throw _.create(e);const r="occupancy"in n?1:n.payload.total_channels,i="occupancy"in n?n.occupancy:n.payload.total_channels,o={};let a={};if("occupancy"in n){const e=this.parameters.channels[0];a[e]={uuids:null!==(t=n.uuids)&&void 0!==t?t:[],occupancy:i}}else a=null!==(s=n.payload.channels)&&void 0!==s?s:{};return Object.keys(a).forEach((e=>{const t=a[e];o[e]={occupants:this.parameters.includeUUIDs?t.uuids.map((e=>"string"==typeof e?{uuid:e,state:null}:e)):[],name:e,occupancy:t.occupancy}})),{totalChannels:r,totalOccupancy:i,channels:o}}))}get path(){const{keySet:{subscribeKey:e},channels:t,channelGroups:s}=this.parameters;let n=`/v2/presence/sub-key/${e}`;return(t&&t.length>0||s&&s.length>0)&&(n+=`/channel/${R(null!=t?t:[],",")}`),n}get queryParameters(){const{channelGroups:e,includeUUIDs:t,includeState:s,queryParameters:n}=this.parameters;return Object.assign(Object.assign(Object.assign(Object.assign({},t?{}:{disable_uuids:"1"}),null!=s&&s?{state:"1"}:{}),e&&e.length>0?{"channel-group":e.join(",")}:{}),n)}}class It extends se{constructor(e){super({method:H.DELETE}),this.parameters=e}operation(){return re.PNDeleteMessagesOperation}validate(){return this.parameters.keySet.subscribeKey?this.parameters.channel?void 0:"Missing channel":"Missing Subscribe Key"}parse(e){return i(this,void 0,void 0,(function*(){const t=this.deserializeResponse(e);if(!t)throw new d("Service response error, check status for details",p("Unable to deserialize service response"));if(t.status>=400)throw _.create(e);return{}}))}get path(){const{keySet:{subscribeKey:e},channel:t}=this.parameters;return`/v3/history/sub-key/${e}/channel/${I(t)}`}get queryParameters(){const{start:e,end:t}=this.parameters;return Object.assign(Object.assign({},e?{start:e}:{}),t?{end:t}:{})}}class Rt extends se{constructor(e){super(),this.parameters=e}operation(){return re.PNMessageCounts}validate(){const{keySet:{subscribeKey:e},channels:t,timetoken:s,channelTimetokens:n}=this.parameters;return e?t?s&&n?"`timetoken` and `channelTimetokens` are incompatible together":s||n?n&&n.length>1&&n.length!==t.length?"Length of `channelTimetokens` and `channels` do not match":void 0:"`timetoken` or `channelTimetokens` need to be set":"Missing channels":"Missing Subscribe Key"}parse(e){return i(this,void 0,void 0,(function*(){const t=this.deserializeResponse(e);if(!t)throw new d("Service response error, check status for details",p("Unable to deserialize service response"));if(t.status>=400)throw _.create(e);return{channels:t.channels}}))}get path(){return`/v3/history/sub-key/${this.parameters.keySet.subscribeKey}/message-counts/${R(this.parameters.channels)}`}get queryParameters(){let{channelTimetokens:e}=this.parameters;return this.parameters.timetoken&&(e=[this.parameters.timetoken]),Object.assign(Object.assign({},1===e.length?{timetoken:e[0]}:{}),e.length>1?{channelsTimetoken:e.join(",")}:{})}}class Ut extends se{constructor(e){var t,s,n;super(),this.parameters=e,e.count?e.count=Math.min(e.count,100):e.count=100,null!==(t=e.stringifiedTimeToken)&&void 0!==t||(e.stringifiedTimeToken=false),null!==(s=e.includeMeta)&&void 0!==s||(e.includeMeta=false),null!==(n=e.logVerbosity)&&void 0!==n||(e.logVerbosity=false)}operation(){return re.PNHistoryOperation}validate(){return this.parameters.keySet.subscribeKey?this.parameters.channel?void 0:"Missing channel":"Missing Subscribe Key"}parse(e){return i(this,void 0,void 0,(function*(){const t=this.deserializeResponse(e);if(!t)throw new d("Service response error, check status for details",p("Unable to deserialize service response"));const s=t[0],n=t[1],r=t[2];return Array.isArray(s)?{messages:s.map((e=>{const t=this.processPayload(e.message),s={entry:t.payload,timetoken:e.timetoken};return t.error&&(s.error=t.error),e.meta&&(s.meta=e.meta),s})),startTimeToken:n,endTimeToken:r}:{messages:[],startTimeToken:n,endTimeToken:r}}))}get path(){const{keySet:{subscribeKey:e},channel:t}=this.parameters;return`/v2/history/sub-key/${e}/channel/${I(t)}`}get queryParameters(){const{start:e,end:t,reverse:s,count:n,stringifiedTimeToken:r,includeMeta:i}=this.parameters;return Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({count:n,include_token:"true"},e?{start:e}:{}),t?{end:t}:{}),r?{string_message_token:"true"}:{}),null!=s?{reverse:s.toString()}:{}),i?{include_meta:"true"}:{})}processPayload(e){const{crypto:t,logVerbosity:s}=this.parameters;if(!t||"string"!=typeof e)return{payload:e};let n,r;try{const s=t.decrypt(e);n=s instanceof ArrayBuffer?JSON.parse(Ut.decoder.decode(s)):s}catch(t){s&&console.log("decryption error",t.message),n=e,r=`Error while decrypting message content: ${t.message}`}return{payload:n,error:r}}}var Tt;!function(e){e[e.Message=-1]="Message",e[e.Files=4]="Files"}(Tt||(Tt={}));class Ft extends se{constructor(e){var t,s,n,r,i;super(),this.parameters=e;const o=null!==(t=e.includeMessageActions)&&void 0!==t&&t,a=e.channels.length>1||o?25:100;e.count?e.count=Math.min(e.count,a):e.count=a,e.includeUuid?e.includeUUID=e.includeUuid:null!==(s=e.includeUUID)&&void 0!==s||(e.includeUUID=true),null!==(n=e.stringifiedTimeToken)&&void 0!==n||(e.stringifiedTimeToken=false),null!==(r=e.includeMessageType)&&void 0!==r||(e.includeMessageType=true),null!==(i=e.logVerbosity)&&void 0!==i||(e.logVerbosity=false)}operation(){return re.PNFetchMessagesOperation}validate(){const{keySet:{subscribeKey:e},channels:t,includeMessageActions:s}=this.parameters;return e?t?void 0!==s&&s&&t.length>1?"History can return actions data for a single channel only. Either pass a single channel or disable the includeMessageActions flag.":void 0:"Missing channels":"Missing Subscribe Key"}parse(e){return i(this,void 0,void 0,(function*(){var t;const s=this.deserializeResponse(e);if(!s)throw new d("Service response error, check status for details",p("Unable to deserialize service response"));if(s.status>=400)throw _.create(e);const n=null!==(t=s.channels)&&void 0!==t?t:{},r={};return Object.keys(n).forEach((e=>{r[e]=n[e].map((t=>{null===t.message_type&&(t.message_type=Tt.Message);const s=this.processPayload(e,t),n={channel:e,timetoken:t.timetoken,message:s.payload,messageType:t.message_type,uuid:t.uuid};if(t.actions){const e=n;e.actions=t.actions,e.data=t.actions}return t.meta&&(n.meta=t.meta),s.error&&(n.error=s.error),n}))})),s.more?{channels:r,more:s.more}:{channels:r}}))}get path(){const{keySet:{subscribeKey:e},channels:t,includeMessageActions:s}=this.parameters;return`/v3/${s?"history-with-actions":"history"}/sub-key/${e}/channel/${R(t)}`}get queryParameters(){const{start:e,end:t,count:s,includeMessageType:n,includeMeta:r,includeUUID:i,stringifiedTimeToken:o}=this.parameters;return Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({max:s},e?{start:e}:{}),t?{end:t}:{}),o?{string_message_token:"true"}:{}),void 0!==r&&r?{include_meta:"true"}:{}),i?{include_uuid:"true"}:{}),n?{include_message_type:"true"}:{})}processPayload(e,t){const{crypto:s,logVerbosity:n}=this.parameters;if(!s||"string"!=typeof t.message)return{payload:t.message};let r,i;try{const e=s.decrypt(t.message);r=e instanceof ArrayBuffer?JSON.parse(Ft.decoder.decode(e)):e}catch(e){n&&console.log("decryption error",e.message),r=t.message,i=`Error while decrypting message content: ${e.message}`}if(!i&&r&&t.message_type==Tt.Files&&"object"==typeof r&&this.isFileMessage(r)){const t=r;return{payload:{message:t.message,file:Object.assign(Object.assign({},t.file),{url:this.parameters.getFileUrl({channel:e,id:t.file.id,name:t.file.name})})},error:i}}return{payload:r,error:i}}isFileMessage(e){return void 0!==e.file}}class xt extends se{constructor(e){super(),this.parameters=e}operation(){return re.PNGetMessageActionsOperation}validate(){return this.parameters.keySet.subscribeKey?this.parameters.channel?void 0:"Missing message channel":"Missing Subscribe Key"}parse(e){return i(this,void 0,void 0,(function*(){const t=this.deserializeResponse(e);if(!t)throw new d("Service response error, check status for details",p("Unable to deserialize service response"));if(t.status>=400)throw _.create(e);let s=null,n=null;return t.data.length>0&&(s=t.data[0].actionTimetoken,n=t.data[t.data.length-1].actionTimetoken),{data:t.data,more:t.more,start:s,end:n}}))}get path(){const{keySet:{subscribeKey:e},channel:t}=this.parameters;return`/v1/message-actions/${e}/channel/${I(t)}`}get queryParameters(){const{limit:e,start:t,end:s}=this.parameters;return Object.assign(Object.assign(Object.assign({},t?{start:t}:{}),s?{end:s}:{}),e?{limit:e}:{})}}class Dt extends se{constructor(e){super({method:H.POST}),this.parameters=e}operation(){return re.PNAddMessageActionOperation}validate(){const{keySet:{subscribeKey:e},action:t,channel:s,messageTimetoken:n}=this.parameters;return e?s?n?t?t.value?t.type?t.type.length>15?"Action.type value exceed maximum length of 15":void 0:"Missing Action.type":"Missing Action.value":"Missing Action":"Missing message timetoken":"Missing message channel":"Missing Subscribe Key"}parse(e){return i(this,void 0,void 0,(function*(){const t=this.deserializeResponse(e);if(!t)throw new d("Service response error, check status for details",p("Unable to deserialize service response"));if(t.status>=400)throw _.create(e);return{data:t.data}}))}get headers(){return{"Content-Type":"application/json"}}get path(){const{keySet:{subscribeKey:e},channel:t,messageTimetoken:s}=this.parameters;return`/v1/message-actions/${e}/channel/${I(t)}/message/${s}`}get body(){return JSON.stringify(this.parameters.action)}}class Kt extends se{constructor(e){super({method:H.DELETE}),this.parameters=e}operation(){return re.PNRemoveMessageActionOperation}validate(){const{keySet:{subscribeKey:e},channel:t,messageTimetoken:s,actionTimetoken:n}=this.parameters;return e?t?s?n?void 0:"Missing action timetoken":"Missing message timetoken":"Missing message action channel":"Missing Subscribe Key"}parse(e){return i(this,void 0,void 0,(function*(){const t=this.deserializeResponse(e);if(!t)throw new d("Service response error, check status for details",p("Unable to deserialize service response"));if(t.status>=400)throw _.create(e);return{data:t.data}}))}get path(){const{keySet:{subscribeKey:e},channel:t,actionTimetoken:s,messageTimetoken:n}=this.parameters;return`/v1/message-actions/${e}/channel/${I(t)}/message/${n}/action/${s}`}}class qt extends se{constructor(e){var t,s;super(),this.parameters=e,null!==(t=(s=this.parameters).storeInHistory)&&void 0!==t||(s.storeInHistory=true)}operation(){return re.PNPublishFileMessageOperation}validate(){const{channel:e,fileId:t,fileName:s}=this.parameters;return e?t?s?void 0:"file name can't be empty":"file id can't be empty":"channel can't be empty"}parse(e){return i(this,void 0,void 0,(function*(){const t=this.deserializeResponse(e);if(!t)throw new d("Service response error, check status for details",p("Unable to deserialize service response"));return{timetoken:t[2]}}))}get path(){const{message:e,channel:t,keySet:{publishKey:s,subscribeKey:n},fileId:r,fileName:i}=this.parameters,o=Object.assign({file:{name:i,id:r}},e?{message:e}:{});return`/v1/files/publish-file/${s}/${n}/0/${I(t)}/0/${I(this.prepareMessagePayload(o))}`}get queryParameters(){const{storeInHistory:e,ttl:t,meta:s}=this.parameters;return Object.assign(Object.assign({store:e?"1":"0"},t?{ttl:t}:{}),s&&"object"==typeof s?{meta:JSON.stringify(s)}:{})}prepareMessagePayload(e){const{crypto:t}=this.parameters;if(!t)return JSON.stringify(e)||"";const s=t.encrypt(JSON.stringify(e));return JSON.stringify("string"==typeof s?s:u(s))}}class Gt extends se{constructor(e){super({method:H.LOCAL}),this.parameters=e}operation(){return re.PNGetFileUrlOperation}validate(){const{channel:e,id:t,name:s}=this.parameters;return e?t?s?void 0:"file name can't be empty":"file id can't be empty":"channel can't be empty"}parse(e){return i(this,void 0,void 0,(function*(){return e.url}))}get path(){const{channel:e,id:t,name:s,keySet:{subscribeKey:n}}=this.parameters;return`/v1/files/${n}/channels/${I(e)}/files/${t}/${s}`}}class $t extends se{constructor(e){super({method:H.DELETE}),this.parameters=e}operation(){return re.PNDeleteFileOperation}validate(){const{channel:e,id:t,name:s}=this.parameters;return e?t?s?void 0:"file name can't be empty":"file id can't be empty":"channel can't be empty"}parse(e){return i(this,void 0,void 0,(function*(){const t=this.deserializeResponse(e);if(!t)throw new d("Service response error, check status for details",p("Unable to deserialize service response"));if(t.status>=400)throw _.create(e);return t}))}get path(){const{keySet:{subscribeKey:e},id:t,channel:s,name:n}=this.parameters;return`/v1/files/${e}/channels/${I(s)}/files/${t}/${n}`}}class Lt extends se{constructor(e){var t,s;super(),this.parameters=e,null!==(t=(s=this.parameters).limit)&&void 0!==t||(s.limit=100)}operation(){return re.PNListFilesOperation}validate(){if(!this.parameters.channel)return"channel can't be empty"}parse(e){return i(this,void 0,void 0,(function*(){const t=this.deserializeResponse(e);if(!t)throw new d("Service response error, check status for details",p("Unable to deserialize service response"));if(t.status>=400)throw _.create(e);return t}))}get path(){const{keySet:{subscribeKey:e},channel:t}=this.parameters;return`/v1/files/${e}/channels/${I(t)}/files`}get queryParameters(){const{limit:e,next:t}=this.parameters;return Object.assign({limit:e},t?{next:t}:{})}}class Bt extends se{constructor(e){super({method:H.POST}),this.parameters=e}operation(){return re.PNGenerateUploadUrlOperation}validate(){return this.parameters.channel?this.parameters.name?void 0:"'name' can't be empty":"channel can't be empty"}parse(e){return i(this,void 0,void 0,(function*(){const t=this.deserializeResponse(e);if(!t)throw new d("Service response error, check status for details",p("Unable to deserialize service response"));if(t.status>=400)throw _.create(e);return{id:t.data.id,name:t.data.name,url:t.file_upload_request.url,formFields:t.file_upload_request.form_fields}}))}get path(){const{keySet:{subscribeKey:e},channel:t}=this.parameters;return`/v1/files/${e}/channels/${I(t)}/generate-upload-url`}get body(){return JSON.stringify({name:this.parameters.name})}}class Ht extends se{constructor(e){super({method:H.POST}),this.parameters=e;const t=e.file.mimeType;t&&(e.formFields=e.formFields.map((e=>"Content-Type"===e.name?{name:e.name,value:t}:e)))}operation(){return re.PNPublishFileOperation}validate(){const{fileId:e,fileName:t,file:s,uploadUrl:n}=this.parameters;return e?t?s?n?void 0:"Validation failed: file upload 'url' can't be empty":"Validation failed: 'file' can't be empty":"Validation failed: file 'name' can't be empty":"Validation failed: file 'id' can't be empty"}parse(e){return i(this,void 0,void 0,(function*(){return{status:e.status,message:e.body?Ht.decoder.decode(e.body):"OK"}}))}request(){return Object.assign(Object.assign({},super.request()),{origin:new URL(this.parameters.uploadUrl).origin,timeout:300})}get path(){const{pathname:e,search:t}=new URL(this.parameters.uploadUrl);return`${e}${t}`}get body(){return this.parameters.file}get formData(){return this.parameters.formFields}}class zt{constructor(e){var t;if(this.parameters=e,this.file=null===(t=this.parameters.PubNubFile)||void 0===t?void 0:t.create(e.file),!this.file)throw new Error("File upload error: unable to create File object.")}process(){return i(this,void 0,void 0,(function*(){let e,t;return this.generateFileUploadUrl().then((s=>(e=s.name,t=s.id,this.uploadFile(s)))).then((e=>{if(204!==e.status)throw new d("Upload to bucket was unsuccessful",{error:!0,statusCode:e.status,category:h.PNUnknownCategory,operation:re.PNPublishFileOperation,errorData:{message:e.message}})})).then((()=>this.publishFileMessage(t,e))).catch((e=>{if(e instanceof d)throw e;const t=e instanceof _?e:_.create(e);throw new d("File upload error.",t.toStatus(re.PNPublishFileOperation))}))}))}generateFileUploadUrl(){return i(this,void 0,void 0,(function*(){const e=new Bt(Object.assign(Object.assign({},this.parameters),{name:this.file.name,keySet:this.parameters.keySet}));return this.parameters.sendRequest(e)}))}uploadFile(e){return i(this,void 0,void 0,(function*(){const{cipherKey:t,PubNubFile:s,crypto:n,cryptography:r}=this.parameters,{id:i,name:o,url:a,formFields:c}=e;return this.parameters.PubNubFile.supportsEncryptFile&&(!t&&n?this.file=yield n.encryptFile(this.file,s):t&&r&&(this.file=yield r.encryptFile(t,this.file,s))),this.parameters.sendRequest(new Ht({fileId:i,fileName:o,file:this.file,uploadUrl:a,formFields:c}))}))}publishFileMessage(e,t){return i(this,void 0,void 0,(function*(){var s,n,r,i;let o,a={timetoken:"0"},c=this.parameters.fileUploadPublishRetryLimit,u=!1;do{try{a=yield this.parameters.publishFile(Object.assign(Object.assign({},this.parameters),{fileId:e,fileName:t})),u=!0}catch(e){e instanceof d&&(o=e),c-=1}}while(!u&&c>0);if(u)return{status:200,timetoken:a.timetoken,id:e,name:t};throw new d("Publish failed. You may want to execute that operation manually using pubnub.publishFile",{error:!0,category:null!==(n=null===(s=o.status)||void 0===s?void 0:s.category)&&void 0!==n?n:h.PNUnknownCategory,statusCode:null!==(i=null===(r=o.status)||void 0===r?void 0:r.statusCode)&&void 0!==i?i:0,channel:this.parameters.channel,id:e,name:t})}))}}class Vt extends se{constructor(e){super({method:H.DELETE}),this.parameters=e}operation(){return re.PNAccessManagerRevokeToken}validate(){return this.parameters.keySet.secretKey?this.parameters.token?void 0:"token can't be empty":"Missing Secret Key"}parse(e){return i(this,void 0,void 0,(function*(){const t=this.deserializeResponse(e);if(!t)throw new d("Service response error, check status for details",p("Unable to deserialize service response"));if(t.status>=400)throw _.create(e);return{}}))}get path(){const{keySet:{subscribeKey:e},token:t}=this.parameters;return`/v3/pam/${e}/grant/${I(t)}`}}class Wt extends se{constructor(e){var t,s,n,r;super({method:H.POST}),this.parameters=e,null!==(t=(n=this.parameters).resources)&&void 0!==t||(n.resources={}),null!==(s=(r=this.parameters).patterns)&&void 0!==s||(r.patterns={})}operation(){return re.PNAccessManagerGrantToken}validate(){var e,t,s,n,r,i;const{keySet:{subscribeKey:o,publishKey:a,secretKey:c},resources:u,patterns:l}=this.parameters;if(!o)return"Missing Subscribe Key";if(!a)return"Missing Publish Key";if(!c)return"Missing Secret Key";if(!u&&!l)return"Missing either Resources or Patterns";if(this.isVspPermissions(this.parameters)&&("channels"in(null!==(e=this.parameters.resources)&&void 0!==e?e:{})||"uuids"in(null!==(t=this.parameters.resources)&&void 0!==t?t:{})||"groups"in(null!==(s=this.parameters.resources)&&void 0!==s?s:{})||"channels"in(null!==(n=this.parameters.patterns)&&void 0!==n?n:{})||"uuids"in(null!==(r=this.parameters.patterns)&&void 0!==r?r:{})||"groups"in(null!==(i=this.parameters.patterns)&&void 0!==i?i:{})))return"Cannot mix `users`, `spaces` and `authorizedUserId` with `uuids`, `channels`, `groups` and `authorized_uuid`";let h=!0;return[this.parameters.resources,this.parameters.patterns].forEach((e=>{Object.keys(null!=e?e:{}).forEach((t=>{var s;e&&h&&Object.keys(null!==(s=e[t])&&void 0!==s?s:{}).length>0&&(h=!1)}))})),h?"Missing values for either Resources or Patterns":void 0}parse(e){return i(this,void 0,void 0,(function*(){const t=this.deserializeResponse(e);if(!t)throw new d("Service response error, check status for details",p("Unable to deserialize service response"));if(t.status>=400)throw _.create(e);return t.data.token}))}get path(){return`/v3/pam/${this.parameters.keySet.subscribeKey}/grant`}get body(){const{ttl:e,meta:t}=this.parameters,s=Object.assign({},e||0===e?{ttl:e}:{}),n=this.isVspPermissions(this.parameters)?this.parameters.authorizedUserId:this.parameters.authorized_uuid,r={},i={},o={},a=(e,t,s,n)=>{n[s]||(n[s]={}),n[s][e]=t},{resources:c,patterns:u}=this.parameters;return[c,u].forEach(((e,t)=>{var s,n,r,c,u;const l=0===t?i:o;let h={},d={},p={};l.channels||(l.channels={}),l.groups||(l.groups={}),l.uuids||(l.uuids={}),l.users||(l.users={}),l.spaces||(l.spaces={}),e&&("spaces"in e||"users"in e?(h=null!==(s=e.spaces)&&void 0!==s?s:{},p=null!==(n=e.users)&&void 0!==n?n:{}):("channels"in e||"uuids"in e||"groups"in e)&&(h=null!==(r=e.channels)&&void 0!==r?r:{},d=null!==(c=e.groups)&&void 0!==c?c:{},p=null!==(u=e.uuids)&&void 0!==u?u:{})),Object.keys(h).forEach((e=>a(e,this.extractPermissions(h[e]),"channels",l))),Object.keys(d).forEach((e=>a(e,this.extractPermissions(d[e]),"groups",l))),Object.keys(p).forEach((e=>a(e,this.extractPermissions(p[e]),"uuids",l)))})),n&&(r.uuid=`${n}`),r.resources=i,r.patterns=o,r.meta=null!=t?t:{},s.permissions=r,JSON.stringify(s)}extractPermissions(e){let t=0;return"join"in e&&e.join&&(t|=128),"update"in e&&e.update&&(t|=64),"get"in e&&e.get&&(t|=32),"delete"in e&&e.delete&&(t|=8),"manage"in e&&e.manage&&(t|=4),"write"in e&&e.write&&(t|=2),"read"in e&&e.read&&(t|=1),t}isVspPermissions(e){var t,s,n,r;return"authorizedUserId"in e||"spaces"in(null!==(t=e.resources)&&void 0!==t?t:{})||"users"in(null!==(s=e.resources)&&void 0!==s?s:{})||"spaces"in(null!==(n=e.patterns)&&void 0!==n?n:{})||"users"in(null!==(r=e.patterns)&&void 0!==r?r:{})}}class Jt extends se{constructor(e){var t,s,n,r,i,o,a,c,u,l,h,d,p,g,y,f,m,b,v,w;super(),this.parameters=e,null!==(t=(h=this.parameters).channels)&&void 0!==t||(h.channels=[]),null!==(s=(d=this.parameters).channelGroups)&&void 0!==s||(d.channelGroups=[]),null!==(n=(p=this.parameters).uuids)&&void 0!==n||(p.uuids=[]),null!==(r=(g=this.parameters).read)&&void 0!==r||(g.read=false),null!==(i=(y=this.parameters).write)&&void 0!==i||(y.write=false),null!==(o=(f=this.parameters).delete)&&void 0!==o||(f.delete=false),null!==(a=(m=this.parameters).get)&&void 0!==a||(m.get=false),null!==(c=(b=this.parameters).update)&&void 0!==c||(b.update=false),null!==(u=(v=this.parameters).manage)&&void 0!==u||(v.manage=false),null!==(l=(w=this.parameters).join)&&void 0!==l||(w.join=false)}operation(){return re.PNAccessManagerGrant}validate(){const{keySet:{subscribeKey:e,publishKey:t,secretKey:s},uuids:n=[],channels:r=[],channelGroups:i=[],authKeys:o=[]}=this.parameters;return e?t?s?0!==n.length&&0===o.length?"authKeys are required for grant request on uuids":!n.length||0===r.length&&0===i.length?void 0:"Both channel/channel group and uuid cannot be used in the same request":"Missing Secret Key":"Missing Publish Key":"Missing Subscribe Key"}parse(e){return i(this,void 0,void 0,(function*(){const t=this.deserializeResponse(e);if(!t)throw new d("Service response error, check status for details",p("Unable to deserialize service response"));if(t.status>=400)throw _.create(e);return t.payload}))}get path(){return`/v2/auth/grant/sub-key/${this.parameters.keySet.subscribeKey}`}get queryParameters(){const{channels:e,channelGroups:t,authKeys:s,uuids:n,read:r,write:i,manage:o,delete:a,get:c,join:u,update:l,ttl:h}=this.parameters;return Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},e&&(null==e?void 0:e.length)>0?{channel:e.join(",")}:{}),t&&(null==t?void 0:t.length)>0?{"channel-group":t.join(",")}:{}),s&&(null==s?void 0:s.length)>0?{auth:s.join(",")}:{}),n&&(null==n?void 0:n.length)>0?{"target-uuid":n.join(",")}:{}),{r:r?"1":"0",w:i?"1":"0",m:o?"1":"0",d:a?"1":"0",g:c?"1":"0",j:u?"1":"0",u:l?"1":"0"}),h||0===h?{ttl:h}:{})}}const Qt=[];class Yt extends se{constructor(e){var t,s;super(),this.parameters=e,null!==(t=(s=this.parameters).authKeys)&&void 0!==t||(s.authKeys=Qt)}operation(){return re.PNAccessManagerAudit}validate(){if(!this.parameters.keySet.subscribeKey)return"Missing Subscribe Key"}parse(e){return i(this,void 0,void 0,(function*(){const t=this.deserializeResponse(e);if(!t)throw new d("Service response error, check status for details",p("Unable to deserialize service response"));if(t.status>=400)throw _.create(e);return t.payload}))}get path(){return`/v2/auth/audit/sub-key/${this.parameters.keySet.subscribeKey}`}get queryParameters(){const{channel:e,channelGroup:t,authKeys:s}=this.parameters;return Object.assign(Object.assign(Object.assign({},e?{channel:e}:{}),t?{"channel-group":t}:{}),s&&s.length?{auth:s.join(",")}:{})}}class Xt{subscribe(){var e,t;this.pubnub.subscribe(Object.assign({channels:this.channelNames,channelGroups:this.groupNames},(null===(t=null===(e=this.options)||void 0===e?void 0:e.cursor)||void 0===t?void 0:t.timetoken)&&{timetoken:this.options.cursor.timetoken}))}unsubscribe(){this.pubnub.unsubscribe({channels:this.channelNames.filter((e=>!e.endsWith("-pnpres"))),channelGroups:this.groupNames.filter((e=>!e.endsWith("-pnpres")))})}set onMessage(e){this.listener.message=e}set onPresence(e){this.listener.presence=e}set onSignal(e){this.listener.signal=e}set onObjects(e){this.listener.objects=e}set onMessageAction(e){this.listener.messageAction=e}set onFile(e){this.listener.file=e}addListener(e){this.eventEmitter.addListener(e,this.channelNames.filter((e=>!e.endsWith("-pnpres"))),this.groupNames.filter((e=>!e.endsWith("-pnpres"))))}removeListener(e){this.eventEmitter.removeListener(e,this.channelNames,this.groupNames)}get channels(){return this.channelNames.slice(0)}get channelGroups(){return this.groupNames.slice(0)}}class Zt extends Xt{constructor({channels:e=[],channelGroups:t=[],subscriptionOptions:s,eventEmitter:n,pubnub:r}){super(),this.channelNames=[],this.groupNames=[],this.subscriptionList=[],this.options=s,this.eventEmitter=n,this.pubnub=r,e.filter((e=>!e.endsWith("-pnpres"))).forEach((e=>{const t=this.pubnub.channel(e).subscription(this.options);this.channelNames=[...this.channelNames,...t.channels],this.subscriptionList.push(t)})),t.filter((e=>!e.endsWith("-pnpres"))).forEach((e=>{const t=this.pubnub.channelGroup(e).subscription(this.options);this.groupNames=[...this.groupNames,...t.channelGroups],this.subscriptionList.push(t)})),this.listener={},n.addListener(this.listener,this.channelNames.filter((e=>!e.endsWith("-pnpres"))),this.groupNames.filter((e=>!e.endsWith("-pnpres"))))}addSubscription(e){this.subscriptionList.push(e),this.channelNames=[...this.channelNames,...e.channels],this.groupNames=[...this.groupNames,...e.channelGroups],this.eventEmitter.addListener(this.listener,e.channels,e.channelGroups)}removeSubscription(e){const t=e.channels,s=e.channelGroups;this.channelNames=this.channelNames.filter((e=>!t.includes(e))),this.groupNames=this.groupNames.filter((e=>!s.includes(e))),this.subscriptionList=this.subscriptionList.filter((t=>t!==e)),this.eventEmitter.removeListener(this.listener,t,s)}addSubscriptionSet(e){this.subscriptionList=[...this.subscriptionList,...e.subscriptions],this.channelNames=[...this.channelNames,...e.channels],this.groupNames=[...this.groupNames,...e.channelGroups],this.eventEmitter.addListener(this.listener,e.channels,e.channelGroups)}removeSubscriptionSet(e){const t=e.channels,s=e.channelGroups;this.channelNames=this.channelNames.filter((e=>!t.includes(e))),this.groupNames=this.groupNames.filter((e=>!s.includes(e))),this.subscriptionList=this.subscriptionList.filter((t=>!e.subscriptions.includes(t))),this.eventEmitter.removeListener(this.listener,t,s)}get subscriptions(){return this.subscriptionList.slice(0)}}class es extends Xt{constructor({channels:e,channelGroups:t,subscriptionOptions:s,eventEmitter:n,pubnub:r}){super(),this.channelNames=[],this.groupNames=[],this.channelNames=e,this.groupNames=t,this.options=s,this.pubnub=r,this.eventEmitter=n,this.listener={},n.addListener(this.listener,this.channelNames.filter((e=>!e.endsWith("-pnpres"))),this.groupNames.filter((e=>!e.endsWith("-pnpres"))))}addSubscription(e){return new Zt({channels:[...this.channelNames,...e.channels],channelGroups:[...this.groupNames,...e.channelGroups],subscriptionOptions:Object.assign(Object.assign({},this.options),null==e?void 0:e.options),eventEmitter:this.eventEmitter,pubnub:this.pubnub})}}class ts{constructor(e,t,s){this.id=e,this.eventEmitter=t,this.pubnub=s}subscription(e){return new es({channels:[this.id],channelGroups:[],subscriptionOptions:e,eventEmitter:this.eventEmitter,pubnub:this.pubnub})}}class ss{constructor(e,t,s){this.eventEmitter=t,this.pubnub=s,this.name=e}subscription(e){return new es({channels:[],channelGroups:(null==e?void 0:e.receivePresenceEvents)?[this.name,`${this.name}-pnpres`]:[this.name],subscriptionOptions:e,eventEmitter:this.eventEmitter,pubnub:this.pubnub})}}class ns{constructor(e,t,s){this.id=e,this.eventEmitter=t,this.pubnub=s}subscription(e){return new es({channels:[this.id],channelGroups:[],subscriptionOptions:e,eventEmitter:this.eventEmitter,pubnub:this.pubnub})}}class rs{constructor(e,t,s){this.eventEmitter=t,this.pubnub=s,this.name=e}subscription(e){return new es({channels:(null==e?void 0:e.receivePresenceEvents)?[this.name,`${this.name}-pnpres`]:[this.name],channelGroups:[],subscriptionOptions:e,eventEmitter:this.eventEmitter,pubnub:this.pubnub})}}class is extends se{constructor(e){super(),this.parameters=e}operation(){return re.PNRemoveChannelsFromGroupOperation}validate(){const{keySet:{subscribeKey:e},channels:t,channelGroup:s}=this.parameters;return e?s?t?void 0:"Missing channels":"Missing Channel Group":"Missing Subscribe Key"}parse(e){return i(this,void 0,void 0,(function*(){const t=this.deserializeResponse(e);if(!t)throw new d("Service response error, check status for details",p("Unable to deserialize service response"));if(t.status>=400)throw _.create(e);return{}}))}get path(){const{keySet:{subscribeKey:e},channelGroup:t}=this.parameters;return`/v1/channel-registration/sub-key/${e}/channel-group/${I(t)}`}get queryParameters(){return{remove:this.parameters.channels.join(",")}}}class os extends se{constructor(e){super(),this.parameters=e}operation(){return re.PNAddChannelsToGroupOperation}validate(){const{keySet:{subscribeKey:e},channels:t,channelGroup:s}=this.parameters;return e?s?t?void 0:"Missing channels":"Missing Channel Group":"Missing Subscribe Key"}parse(e){return i(this,void 0,void 0,(function*(){const t=this.deserializeResponse(e);if(!t)throw new d("Service response error, check status for details",p("Unable to deserialize service response"));if(t.status>=400)throw _.create(e);return{}}))}get path(){const{keySet:{subscribeKey:e},channelGroup:t}=this.parameters;return`/v1/channel-registration/sub-key/${e}/channel-group/${I(t)}`}get queryParameters(){return{add:this.parameters.channels.join(",")}}}class as extends se{constructor(e){super(),this.parameters=e}operation(){return re.PNChannelsForGroupOperation}validate(){return this.parameters.keySet.subscribeKey?this.parameters.channelGroup?void 0:"Missing Channel Group":"Missing Subscribe Key"}parse(e){return i(this,void 0,void 0,(function*(){const t=this.deserializeResponse(e);if(!t)throw new d("Service response error, check status for details",p("Unable to deserialize service response"));if(t.status>=400)throw _.create(e);return{channels:t.payload.channels}}))}get path(){const{keySet:{subscribeKey:e},channelGroup:t}=this.parameters;return`/v1/channel-registration/sub-key/${e}/channel-group/${I(t)}`}}class cs extends se{constructor(e){super(),this.parameters=e}operation(){return re.PNRemoveGroupOperation}validate(){return this.parameters.keySet.subscribeKey?this.parameters.channelGroup?void 0:"Missing Channel Group":"Missing Subscribe Key"}parse(e){return i(this,void 0,void 0,(function*(){const t=this.deserializeResponse(e);if(!t)throw new d("Service response error, check status for details",p("Unable to deserialize service response"));if(t.status>=400)throw _.create(e);return{}}))}get path(){const{keySet:{subscribeKey:e},channelGroup:t}=this.parameters;return`/v1/channel-registration/sub-key/${e}/channel-group/${I(t)}/remove`}}class us extends se{constructor(e){super(),this.parameters=e}operation(){return re.PNChannelGroupsOperation}validate(){if(!this.parameters.keySet.subscribeKey)return"Missing Subscribe Key"}parse(e){return i(this,void 0,void 0,(function*(){const t=this.deserializeResponse(e);if(!t)throw new d("Service response error, check status for details",p("Unable to deserialize service response"));if(t.status>=400)throw _.create(e);return{groups:t.payload.groups}}))}get path(){return`/v1/channel-registration/sub-key/${this.parameters.keySet.subscribeKey}/channel-group`}}class ls{constructor(e,t){this.keySet=e,this.sendRequest=t}listChannels(e,t){return i(this,void 0,void 0,(function*(){const s=new as(Object.assign(Object.assign({},e),{keySet:this.keySet}));return t?this.sendRequest(s,t):this.sendRequest(s)}))}listGroups(e){return i(this,void 0,void 0,(function*(){const t=new us({keySet:this.keySet});return e?this.sendRequest(t,e):this.sendRequest(t)}))}addChannels(e,t){return i(this,void 0,void 0,(function*(){const s=new os(Object.assign(Object.assign({},e),{keySet:this.keySet}));return t?this.sendRequest(s,t):this.sendRequest(s)}))}removeChannels(e,t){return i(this,void 0,void 0,(function*(){const s=new is(Object.assign(Object.assign({},e),{keySet:this.keySet}));return t?this.sendRequest(s,t):this.sendRequest(s)}))}deleteGroup(e,t){return i(this,void 0,void 0,(function*(){const s=new cs(Object.assign(Object.assign({},e),{keySet:this.keySet}));return t?this.sendRequest(s,t):this.sendRequest(s)}))}}class hs extends se{constructor(e){var t,s;super(),this.parameters=e,"apns2"===this.parameters.pushGateway&&(null!==(t=(s=this.parameters).environment)&&void 0!==t||(s.environment="development")),this.parameters.count&&this.parameters.count>1e3&&(this.parameters.count=1e3)}operation(){throw Error("Should be implemented in subclass.")}validate(){const{keySet:{subscribeKey:e},action:t,device:s,pushGateway:n}=this.parameters;return e?s?"add"!==t&&"remove"!==t||"channels"in this.parameters&&0!==this.parameters.channels.length?n?"apns2"!==this.parameters.pushGateway||this.parameters.topic?void 0:"Missing APNS2 topic":"Missing GW Type (pushGateway: gcm or apns2)":"Missing Channels":"Missing Device ID (device)":"Missing Subscribe Key"}parse(e){return i(this,void 0,void 0,(function*(){throw Error("Should be implemented in subclass.")}))}get path(){const{keySet:{subscribeKey:e},action:t,device:s,pushGateway:n}=this.parameters;let r="apns2"===n?`/v2/push/sub-key/${e}/devices-apns2/${s}`:`/v1/push/sub-key/${e}/devices/${s}`;return"remove-device"===t&&(r=`${r}/remove`),r}get queryParameters(){const{start:e,count:t}=this.parameters;let s=Object.assign(Object.assign({type:this.parameters.pushGateway},e?{start:e}:{}),t&&t>0?{count:t}:{});if("channels"in this.parameters&&(s[this.parameters.action]=this.parameters.channels.join(",")),"apns2"===this.parameters.pushGateway){const{environment:e,topic:t}=this.parameters;s=Object.assign(Object.assign({},s),{environment:e,topic:t})}return s}}class ds extends hs{constructor(e){super(Object.assign(Object.assign({},e),{action:"remove"}))}operation(){return re.PNRemovePushNotificationEnabledChannelsOperation}parse(e){return i(this,void 0,void 0,(function*(){if(!this.deserializeResponse(e))throw new d("Service response error, check status for details",p("Unable to deserialize service response"));return{}}))}}class ps extends hs{constructor(e){super(Object.assign(Object.assign({},e),{action:"list"}))}operation(){return re.PNPushNotificationEnabledChannelsOperation}parse(e){return i(this,void 0,void 0,(function*(){const t=this.deserializeResponse(e);if(!t)throw new d("Service response error, check status for details",p("Unable to deserialize service response"));return{channels:t}}))}}class gs extends hs{constructor(e){super(Object.assign(Object.assign({},e),{action:"add"}))}operation(){return re.PNAddPushNotificationEnabledChannelsOperation}parse(e){return i(this,void 0,void 0,(function*(){if(!this.deserializeResponse(e))throw new d("Service response error, check status for details",p("Unable to deserialize service response"));return{}}))}}class ys extends hs{constructor(e){super(Object.assign(Object.assign({},e),{action:"remove-device"}))}operation(){return re.PNRemoveAllPushNotificationsOperation}parse(e){return i(this,void 0,void 0,(function*(){if(!this.deserializeResponse(e))throw new d("Service response error, check status for details",p("Unable to deserialize service response"));return{}}))}}class fs{constructor(e,t){this.keySet=e,this.sendRequest=t}listChannels(e,t){return i(this,void 0,void 0,(function*(){const s=new ps(Object.assign(Object.assign({},e),{keySet:this.keySet}));return t?this.sendRequest(s,t):this.sendRequest(s)}))}addChannels(e,t){return i(this,void 0,void 0,(function*(){const s=new gs(Object.assign(Object.assign({},e),{keySet:this.keySet}));return t?this.sendRequest(s,t):this.sendRequest(s)}))}removeChannels(e,t){return i(this,void 0,void 0,(function*(){const s=new ds(Object.assign(Object.assign({},e),{keySet:this.keySet}));return t?this.sendRequest(s,t):this.sendRequest(s)}))}deleteDevice(e,t){return i(this,void 0,void 0,(function*(){const s=new ys(Object.assign(Object.assign({},e),{keySet:this.keySet}));return t?this.sendRequest(s,t):this.sendRequest(s)}))}}class ms extends se{constructor(e){var t,s,n,r,i,o;super(),this.parameters=e,null!==(t=e.include)&&void 0!==t||(e.include={}),null!==(s=(i=e.include).customFields)&&void 0!==s||(i.customFields=false),null!==(n=(o=e.include).totalCount)&&void 0!==n||(o.totalCount=false),null!==(r=e.limit)&&void 0!==r||(e.limit=100)}operation(){return re.PNGetAllChannelMetadataOperation}parse(e){return i(this,void 0,void 0,(function*(){const t=this.deserializeResponse(e);if(!t)throw new d("Service response error, check status for details",p("Unable to deserialize service response"));if(t.status>=400)throw _.create(e);return t}))}get path(){return`/v2/objects/${this.parameters.keySet.subscribeKey}/channels`}get queryParameters(){const{include:e,page:t,filter:s,sort:n,limit:r}=this.parameters,i=Object.entries(null!=n?n:{}).map((([e,t])=>null!==t?`${e}:${t}`:e));return Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({include:["status","type",...e.customFields?["custom"]:[]].join(","),count:`${e.totalCount}`},s?{filter:s}:{}),(null==t?void 0:t.next)?{start:t.next}:{}),(null==t?void 0:t.prev)?{end:t.prev}:{}),r?{limit:r}:{}),i.length?{sort:i}:{})}}class bs extends se{constructor(e){super({method:H.DELETE}),this.parameters=e}operation(){return re.PNRemoveChannelMetadataOperation}validate(){if(!this.parameters.channel)return"Channel cannot be empty"}parse(e){return i(this,void 0,void 0,(function*(){const t=this.deserializeResponse(e);if(!t)throw new d("Service response error, check status for details",p("Unable to deserialize service response"));if(t.status>=400)throw _.create(e);return t}))}get path(){const{keySet:{subscribeKey:e},channel:t}=this.parameters;return`/v2/objects/${e}/channels/${I(t)}`}}class vs extends se{constructor(e){var t,s,n,r,i,o,a,c,u,l,h,d,p,g,y,f;super(),this.parameters=e,null!==(t=e.include)&&void 0!==t||(e.include={}),null!==(s=(l=e.include).customFields)&&void 0!==s||(l.customFields=false),null!==(n=(h=e.include).totalCount)&&void 0!==n||(h.totalCount=false),null!==(r=(d=e.include).statusField)&&void 0!==r||(d.statusField=false),null!==(i=(p=e.include).channelFields)&&void 0!==i||(p.channelFields=false),null!==(o=(g=e.include).customChannelFields)&&void 0!==o||(g.customChannelFields=false),null!==(a=(y=e.include).channelStatusField)&&void 0!==a||(y.channelStatusField=false),null!==(c=(f=e.include).channelTypeField)&&void 0!==c||(f.channelTypeField=false),null!==(u=e.limit)&&void 0!==u||(e.limit=100),this.parameters.userId&&(this.parameters.uuid=this.parameters.userId)}operation(){return re.PNGetMembershipsOperation}validate(){if(!this.parameters.uuid)return"'uuid' cannot be empty"}parse(e){return i(this,void 0,void 0,(function*(){const t=this.deserializeResponse(e);if(!t)throw new d("Service response error, check status for details",p("Unable to deserialize service response"));if(t.status>=400)throw _.create(e);return t}))}get path(){const{keySet:{subscribeKey:e},uuid:t}=this.parameters;return`/v2/objects/${e}/uuids/${I(t)}/channels`}get queryParameters(){const{include:e,page:t,filter:s,sort:n,limit:r}=this.parameters,i=Object.entries(null!=n?n:{}).map((([e,t])=>null!==t?`${e}:${t}`:e)),o=[];return e.statusField&&o.push("status"),e.customFields&&o.push("custom"),e.channelFields&&o.push("channel"),e.channelStatusField&&o.push("channel.status"),e.channelTypeField&&o.push("channel.type"),e.customChannelFields&&o.push("channel.custom"),Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({count:`${e.totalCount}`},o.length>0?{include:o.join(",")}:{}),s?{filter:s}:{}),(null==t?void 0:t.next)?{start:t.next}:{}),(null==t?void 0:t.prev)?{end:t.prev}:{}),r?{limit:r}:{}),i.length?{sort:i}:{})}}class ws extends se{constructor(e){var t,s,n,r,i,o,a,c,u,l;super({method:H.PATCH}),this.parameters=e,null!==(t=e.include)&&void 0!==t||(e.include={}),null!==(s=(a=e.include).customFields)&&void 0!==s||(a.customFields=false),null!==(n=(c=e.include).totalCount)&&void 0!==n||(c.totalCount=false),null!==(r=(u=e.include).channelFields)&&void 0!==r||(u.channelFields=false),null!==(i=(l=e.include).customChannelFields)&&void 0!==i||(l.customChannelFields=false),null!==(o=e.limit)&&void 0!==o||(e.limit=100),this.parameters.userId&&(this.parameters.uuid=this.parameters.userId)}operation(){return re.PNSetMembershipsOperation}validate(){const{uuid:e,channels:t}=this.parameters;return e?t&&0!==t.length?void 0:"Channels cannot be empty":"'uuid' cannot be empty"}parse(e){return i(this,void 0,void 0,(function*(){const t=this.deserializeResponse(e);if(!t)throw new d("Service response error, check status for details",p("Unable to deserialize service response"));if(t.status>=400)throw _.create(e);return t}))}get path(){const{keySet:{subscribeKey:e},uuid:t}=this.parameters;return`/v2/objects/${e}/uuids/${I(t)}/channels`}get queryParameters(){const{include:e,page:t,filter:s,sort:n,limit:r}=this.parameters,i=Object.entries(null!=n?n:{}).map((([e,t])=>null!==t?`${e}:${t}`:e)),o=["channel.status","channel.type","status"];return e.customFields&&o.push("custom"),e.channelFields&&o.push("channel"),e.customChannelFields&&o.push("channel.custom"),Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({count:`${e.totalCount}`},o.length>0?{include:o.join(",")}:{}),s?{filter:s}:{}),(null==t?void 0:t.next)?{start:t.next}:{}),(null==t?void 0:t.prev)?{end:t.prev}:{}),r?{limit:r}:{}),i.length?{sort:i}:{})}get body(){const{channels:e,type:t}=this.parameters;return JSON.stringify({[`${t}`]:e.map((e=>"string"==typeof e?{channel:{id:e}}:{channel:{id:e.id},status:e.status,custom:e.custom}))})}}class Ss extends se{constructor(e){var t,s,n,r;super(),this.parameters=e,null!==(t=e.include)&&void 0!==t||(e.include={}),null!==(s=(r=e.include).customFields)&&void 0!==s||(r.customFields=false),null!==(n=e.limit)&&void 0!==n||(e.limit=100)}operation(){return re.PNGetAllUUIDMetadataOperation}parse(e){return i(this,void 0,void 0,(function*(){const t=this.deserializeResponse(e);if(!t)throw new d("Service response error, check status for details",p("Unable to deserialize service response"));if(t.status>=400)throw _.create(e);return t}))}get path(){return`/v2/objects/${this.parameters.keySet.subscribeKey}/uuids`}get queryParameters(){const{include:e,page:t,filter:s,sort:n,limit:r}=this.parameters,i=Object.entries(null!=n?n:{}).map((([e,t])=>null!==t?`${e}:${t}`:e));return Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({include:["status","type",...e.customFields?["custom"]:[]].join(",")},void 0!==e.totalCount?{count:`${e.totalCount}`}:{}),s?{filter:s}:{}),(null==t?void 0:t.next)?{start:t.next}:{}),(null==t?void 0:t.prev)?{end:t.prev}:{}),r?{limit:r}:{}),i.length?{sort:i}:{})}}class ks extends se{constructor(e){var t,s,n;super(),this.parameters=e,null!==(t=e.include)&&void 0!==t||(e.include={}),null!==(s=(n=e.include).customFields)&&void 0!==s||(n.customFields=true)}operation(){return re.PNGetChannelMetadataOperation}validate(){if(!this.parameters.channel)return"Channel cannot be empty"}parse(e){return i(this,void 0,void 0,(function*(){const t=this.deserializeResponse(e);if(!t)throw new d("Service response error, check status for details",p("Unable to deserialize service response"));if(t.status>=400)throw _.create(e);return t}))}get path(){const{keySet:{subscribeKey:e},channel:t}=this.parameters;return`/v2/objects/${e}/channels/${I(t)}`}get queryParameters(){return{include:["status","type",...this.parameters.include.customFields?["custom"]:[]].join(",")}}}class Es extends se{constructor(e){var t,s,n;super({method:H.PATCH}),this.parameters=e,null!==(t=e.include)&&void 0!==t||(e.include={}),null!==(s=(n=e.include).customFields)&&void 0!==s||(n.customFields=true)}operation(){return re.PNSetChannelMetadataOperation}validate(){return this.parameters.channel?this.parameters.data?void 0:"Data cannot be empty":"Channel cannot be empty"}parse(e){return i(this,void 0,void 0,(function*(){const t=this.deserializeResponse(e);if(!t)throw new d("Service response error, check status for details",p("Unable to deserialize service response"));if(t.status>=400)throw _.create(e);return t}))}get path(){const{keySet:{subscribeKey:e},channel:t}=this.parameters;return`/v2/objects/${e}/channels/${I(t)}`}get queryParameters(){return{include:["status","type",...this.parameters.include.customFields?["custom"]:[]].join(",")}}get body(){return JSON.stringify(this.parameters.data)}}class Os extends se{constructor(e){super({method:H.DELETE}),this.parameters=e,this.parameters.userId&&(this.parameters.uuid=this.parameters.userId)}operation(){return re.PNRemoveUUIDMetadataOperation}validate(){if(!this.parameters.uuid)return"'uuid' cannot be empty"}parse(e){return i(this,void 0,void 0,(function*(){const t=this.deserializeResponse(e);if(!t)throw new d("Service response error, check status for details",p("Unable to deserialize service response"));if(t.status>=400)throw _.create(e);return t}))}get path(){const{keySet:{subscribeKey:e},uuid:t}=this.parameters;return`/v2/objects/${e}/uuids/${I(t)}`}}class Cs extends se{constructor(e){var t,s,n,r,i,o,a,c,u,l,h,d,p,g,y,f;super(),this.parameters=e,null!==(t=e.include)&&void 0!==t||(e.include={}),null!==(s=(l=e.include).customFields)&&void 0!==s||(l.customFields=false),null!==(n=(h=e.include).totalCount)&&void 0!==n||(h.totalCount=false),null!==(r=(d=e.include).statusField)&&void 0!==r||(d.statusField=false),null!==(i=(p=e.include).UUIDFields)&&void 0!==i||(p.UUIDFields=false),null!==(o=(g=e.include).customUUIDFields)&&void 0!==o||(g.customUUIDFields=false),null!==(a=(y=e.include).UUIDStatusField)&&void 0!==a||(y.UUIDStatusField=false),null!==(c=(f=e.include).UUIDTypeField)&&void 0!==c||(f.UUIDTypeField=false),null!==(u=e.limit)&&void 0!==u||(e.limit=100)}operation(){return re.PNSetMembersOperation}validate(){if(!this.parameters.channel)return"Channel cannot be empty"}parse(e){return i(this,void 0,void 0,(function*(){const t=this.deserializeResponse(e);if(!t)throw new d("Service response error, check status for details",p("Unable to deserialize service response"));if(t.status>=400)throw _.create(e);return t}))}get path(){const{keySet:{subscribeKey:e},channel:t}=this.parameters;return`/v2/objects/${e}/channels/${I(t)}/uuids`}get queryParameters(){const{include:e,page:t,filter:s,sort:n,limit:r}=this.parameters,i=Object.entries(null!=n?n:{}).map((([e,t])=>null!==t?`${e}:${t}`:e)),o=[];return e.statusField&&o.push("status"),e.customFields&&o.push("custom"),e.UUIDFields&&o.push("uuid"),e.UUIDStatusField&&o.push("uuid.status"),e.UUIDTypeField&&o.push("uuid.type"),e.customUUIDFields&&o.push("uuid.custom"),Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({count:`${e.totalCount}`},o.length>0?{include:o.join(",")}:{}),s?{filter:s}:{}),(null==t?void 0:t.next)?{start:t.next}:{}),(null==t?void 0:t.prev)?{end:t.prev}:{}),r?{limit:r}:{}),i.length?{sort:i}:{})}}class Ns extends se{constructor(e){var t,s,n,r,i,o,a,c,u,l;super({method:H.PATCH}),this.parameters=e,null!==(t=e.include)&&void 0!==t||(e.include={}),null!==(s=(a=e.include).customFields)&&void 0!==s||(a.customFields=false),null!==(n=(c=e.include).totalCount)&&void 0!==n||(c.totalCount=false),null!==(r=(u=e.include).UUIDFields)&&void 0!==r||(u.UUIDFields=false),null!==(i=(l=e.include).customUUIDFields)&&void 0!==i||(l.customUUIDFields=false),null!==(o=e.limit)&&void 0!==o||(e.limit=100)}operation(){return re.PNSetMembersOperation}validate(){const{channel:e,uuids:t}=this.parameters;return e?t&&0!==t.length?void 0:"UUIDs cannot be empty":"Channel cannot be empty"}parse(e){return i(this,void 0,void 0,(function*(){const t=this.deserializeResponse(e);if(!t)throw new d("Service response error, check status for details",p("Unable to deserialize service response"));if(t.status>=400)throw _.create(e);return t}))}get path(){const{keySet:{subscribeKey:e},channel:t}=this.parameters;return`/v2/objects/${e}/channels/${I(t)}/uuids`}get queryParameters(){const{include:e,page:t,filter:s,sort:n,limit:r}=this.parameters,i=Object.entries(null!=n?n:{}).map((([e,t])=>null!==t?`${e}:${t}`:e)),o=["uuid.status","uuid.type","type"];return e.customFields&&o.push("custom"),e.UUIDFields&&o.push("uuid"),e.customUUIDFields&&o.push("uuid.custom"),Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({count:`${e.totalCount}`},o.length>0?{include:o.join(",")}:{}),s?{filter:s}:{}),(null==t?void 0:t.next)?{start:t.next}:{}),(null==t?void 0:t.prev)?{end:t.prev}:{}),r?{limit:r}:{}),i.length?{sort:i}:{})}get body(){const{uuids:e,type:t}=this.parameters;return JSON.stringify({[`${t}`]:e.map((e=>"string"==typeof e?{uuid:{id:e}}:{uuid:{id:e.id},status:e.status,custom:e.custom}))})}}class Ps extends se{constructor(e){var t,s,n;super(),this.parameters=e,null!==(t=e.include)&&void 0!==t||(e.include={}),null!==(s=(n=e.include).customFields)&&void 0!==s||(n.customFields=true),this.parameters.userId&&(this.parameters.uuid=this.parameters.userId)}operation(){return re.PNGetUUIDMetadataOperation}validate(){if(!this.parameters.uuid)return"'uuid' cannot be empty"}parse(e){return i(this,void 0,void 0,(function*(){const t=this.deserializeResponse(e);if(!t)throw new d("Service response error, check status for details",p("Unable to deserialize service response"));if(t.status>=400)throw _.create(e);return t}))}get path(){const{keySet:{subscribeKey:e},uuid:t}=this.parameters;return`/v2/objects/${e}/uuids/${I(t)}`}get queryParameters(){const{include:e}=this.parameters;return{include:["status","type",...e.customFields?["custom"]:[]].join(",")}}}class Ms extends se{constructor(e){var t,s,n;super({method:H.PATCH}),this.parameters=e,null!==(t=e.include)&&void 0!==t||(e.include={}),null!==(s=(n=e.include).customFields)&&void 0!==s||(n.customFields=true),this.parameters.userId&&(this.parameters.uuid=this.parameters.userId)}operation(){return re.PNSetUUIDMetadataOperation}validate(){return this.parameters.uuid?this.parameters.data?void 0:"Data cannot be empty":"'uuid' cannot be empty"}parse(e){return i(this,void 0,void 0,(function*(){const t=this.deserializeResponse(e);if(!t)throw new d("Service response error, check status for details",p("Unable to deserialize service response"));if(t.status>=400)throw _.create(e);return t}))}get path(){const{keySet:{subscribeKey:e},uuid:t}=this.parameters;return`/v2/objects/${e}/uuids/${I(t)}`}get queryParameters(){return{include:["status","type",...this.parameters.include.customFields?["custom"]:[]].join(",")}}get body(){return JSON.stringify(this.parameters.data)}}class js{constructor(e,t){this.configuration=e,this.sendRequest=t,this.keySet=e.keySet}getAllUUIDMetadata(e,t){return i(this,void 0,void 0,(function*(){return this._getAllUUIDMetadata(e,t)}))}_getAllUUIDMetadata(e,t){return i(this,void 0,void 0,(function*(){const s=e&&"function"!=typeof e?e:{};null!=t||(t="function"==typeof e?e:void 0);const n=new Ss(Object.assign(Object.assign({},s),{keySet:this.keySet}));return t?this.sendRequest(n,t):this.sendRequest(n)}))}getUUIDMetadata(e,t){return i(this,void 0,void 0,(function*(){return this._getUUIDMetadata(e,t)}))}_getUUIDMetadata(e,t){return i(this,void 0,void 0,(function*(){var s;const n=e&&"function"!=typeof e?e:{};null!=t||(t="function"==typeof e?e:void 0),n.userId&&(n.uuid=n.userId),null!==(s=n.uuid)&&void 0!==s||(n.uuid=this.configuration.userId);const r=new Ps(Object.assign(Object.assign({},n),{keySet:this.keySet}));return t?this.sendRequest(r,t):this.sendRequest(r)}))}setUUIDMetadata(e,t){return i(this,void 0,void 0,(function*(){return this._setUUIDMetadata(e,t)}))}_setUUIDMetadata(e,t){return i(this,void 0,void 0,(function*(){var s;e.userId&&(e.uuid=e.userId),null!==(s=e.uuid)&&void 0!==s||(e.uuid=this.configuration.userId);const n=new Ms(Object.assign(Object.assign({},e),{keySet:this.keySet}));return t?this.sendRequest(n,t):this.sendRequest(n)}))}removeUUIDMetadata(e,t){return i(this,void 0,void 0,(function*(){return this._removeUUIDMetadata(e,t)}))}_removeUUIDMetadata(e,t){return i(this,void 0,void 0,(function*(){var s;const n=e&&"function"!=typeof e?e:{};null!=t||(t="function"==typeof e?e:void 0),n.userId&&(n.uuid=n.userId),null!==(s=n.uuid)&&void 0!==s||(n.uuid=this.configuration.userId);const r=new Os(Object.assign(Object.assign({},n),{keySet:this.keySet}));return t?this.sendRequest(r,t):this.sendRequest(r)}))}getAllChannelMetadata(e,t){return i(this,void 0,void 0,(function*(){return this._getAllChannelMetadata(e,t)}))}_getAllChannelMetadata(e,t){return i(this,void 0,void 0,(function*(){const s=e&&"function"!=typeof e?e:{};null!=t||(t="function"==typeof e?e:void 0);const n=new ms(Object.assign(Object.assign({},s),{keySet:this.keySet}));return t?this.sendRequest(n,t):this.sendRequest(n)}))}getChannelMetadata(e,t){return i(this,void 0,void 0,(function*(){return this._getChannelMetadata(e,t)}))}_getChannelMetadata(e,t){return i(this,void 0,void 0,(function*(){const s=new ks(Object.assign(Object.assign({},e),{keySet:this.keySet}));return t?this.sendRequest(s,t):this.sendRequest(s)}))}setChannelMetadata(e,t){return i(this,void 0,void 0,(function*(){return this._setChannelMetadata(e,t)}))}_setChannelMetadata(e,t){return i(this,void 0,void 0,(function*(){const s=new Es(Object.assign(Object.assign({},e),{keySet:this.keySet}));return t?this.sendRequest(s,t):this.sendRequest(s)}))}removeChannelMetadata(e,t){return i(this,void 0,void 0,(function*(){return this._removeChannelMetadata(e,t)}))}_removeChannelMetadata(e,t){return i(this,void 0,void 0,(function*(){const s=new bs(Object.assign(Object.assign({},e),{keySet:this.keySet}));return t?this.sendRequest(s,t):this.sendRequest(s)}))}getChannelMembers(e,t){return i(this,void 0,void 0,(function*(){const s=new Cs(Object.assign(Object.assign({},e),{keySet:this.keySet}));return t?this.sendRequest(s,t):this.sendRequest(s)}))}setChannelMembers(e,t){return i(this,void 0,void 0,(function*(){const s=new Ns(Object.assign(Object.assign({},e),{type:"set",keySet:this.keySet}));return t?this.sendRequest(s,t):this.sendRequest(s)}))}removeChannelMembers(e,t){return i(this,void 0,void 0,(function*(){const s=new Ns(Object.assign(Object.assign({},e),{type:"delete",keySet:this.keySet}));return t?this.sendRequest(s,t):this.sendRequest(s)}))}getMemberships(e,t){return i(this,void 0,void 0,(function*(){var s;const n=e&&"function"!=typeof e?e:{};null!=t||(t="function"==typeof e?e:void 0),n.userId&&(n.uuid=n.userId),null!==(s=n.uuid)&&void 0!==s||(n.uuid=this.configuration.userId);const r=new vs(Object.assign(Object.assign({},n),{keySet:this.keySet}));return t?this.sendRequest(r,t):this.sendRequest(r)}))}setMemberships(e,t){return i(this,void 0,void 0,(function*(){var s;e.userId&&(e.uuid=e.userId),null!==(s=e.uuid)&&void 0!==s||(e.uuid=this.configuration.userId);const n=new ws(Object.assign(Object.assign({},e),{type:"set",keySet:this.keySet}));return t?this.sendRequest(n,t):this.sendRequest(n)}))}removeMemberships(e,t){return i(this,void 0,void 0,(function*(){var s;e.userId&&(e.uuid=e.userId),null!==(s=e.uuid)&&void 0!==s||(e.uuid=this.configuration.userId);const n=new ws(Object.assign(Object.assign({},e),{type:"delete",keySet:this.keySet}));return t?this.sendRequest(n,t):this.sendRequest(n)}))}fetchMemberships(e,t){return i(this,void 0,void 0,(function*(){var s,n;if("spaceId"in e){const n=e,r={channel:null!==(s=n.spaceId)&&void 0!==s?s:n.channel,filter:n.filter,limit:n.limit,page:n.page,include:Object.assign({},n.include),sort:n.sort?Object.fromEntries(Object.entries(n.sort).map((([e,t])=>[e.replace("user","uuid"),t]))):void 0},i=e=>({status:e.status,data:e.data.map((e=>({user:e.uuid,custom:e.custom,updated:e.updated,eTag:e.eTag}))),totalCount:e.totalCount,next:e.next,prev:e.prev});return t?this.getChannelMembers(r,((e,s)=>{t(e,s?i(s):s)})):this.getChannelMembers(r).then(i)}const r=e,i={uuid:null!==(n=r.userId)&&void 0!==n?n:r.uuid,filter:r.filter,limit:r.limit,page:r.page,include:Object.assign({},r.include),sort:r.sort?Object.fromEntries(Object.entries(r.sort).map((([e,t])=>[e.replace("space","channel"),t]))):void 0},o=e=>({status:e.status,data:e.data.map((e=>({space:e.channel,custom:e.custom,updated:e.updated,eTag:e.eTag}))),totalCount:e.totalCount,next:e.next,prev:e.prev});return t?this.getMemberships(i,((e,s)=>{t(e,s?o(s):s)})):this.getMemberships(i).then(o)}))}addMemberships(e,t){return i(this,void 0,void 0,(function*(){var s,n,r,i,o,a;if("spaceId"in e){const i=e,o={channel:null!==(s=i.spaceId)&&void 0!==s?s:i.channel,uuids:null!==(r=null===(n=i.users)||void 0===n?void 0:n.map((e=>"string"==typeof e?e:(e.userId,{id:e.userId,custom:e.custom}))))&&void 0!==r?r:i.uuids,limit:0};return t?this.setChannelMembers(o,t):this.setChannelMembers(o)}const c=e,u={uuid:null!==(i=c.userId)&&void 0!==i?i:c.uuid,channels:null!==(a=null===(o=c.spaces)||void 0===o?void 0:o.map((e=>"string"==typeof e?e:{id:e.spaceId,custom:e.custom})))&&void 0!==a?a:c.channels,limit:0};return t?this.setMemberships(u,t):this.setMemberships(u)}))}}class _s extends se{constructor(){super()}operation(){return re.PNTimeOperation}parse(e){return i(this,void 0,void 0,(function*(){const t=this.deserializeResponse(e);if(!t)throw new d("Service response error, check status for details",p("Unable to deserialize service response"));return{timetoken:t[0]}}))}get path(){return"/time/0"}}class As extends se{constructor(e){super(),this.parameters=e}operation(){return re.PNDownloadFileOperation}validate(){const{channel:e,id:t,name:s}=this.parameters;return e?t?s?void 0:"file name can't be empty":"file id can't be empty":"channel can't be empty"}parse(e){return i(this,void 0,void 0,(function*(){const{cipherKey:t,crypto:s,cryptography:n,name:r,PubNubFile:i}=this.parameters,o=e.headers["content-type"];let a,c=e.body;return i.supportsEncryptFile&&(t||s)&&(t&&n?c=yield n.decrypt(t,c):!t&&s&&(a=yield s.decryptFile(i.create({data:c,name:r,mimeType:o}),i))),a||i.create({data:c,name:r,mimeType:o})}))}get path(){const{keySet:{subscribeKey:e},channel:t,id:s,name:n}=this.parameters;return`/v1/files/${e}/channels/${I(t)}/files/${s}/${n}`}}class Is{static notificationPayload(e,t){return new te(e,t)}static generateUUID(){return G.createUUID()}constructor(e){if(this._configuration=e.configuration,this.cryptography=e.cryptography,this.tokenManager=e.tokenManager,this.transport=e.transport,this.crypto=e.crypto,this._objects=new js(this._configuration,this.sendRequest.bind(this)),this._channelGroups=new ls(this._configuration.keySet,this.sendRequest.bind(this)),this._push=new fs(this._configuration.keySet,this.sendRequest.bind(this)),this.listenerManager=new W,this.eventEmitter=new ce(this.listenerManager),this._configuration.enableEventEngine){let e=this._configuration.getHeartbeatInterval();this.presenceState={},e&&(this.presenceEventEngine=new $e({heartbeat:this.heartbeat.bind(this),leave:e=>this.makeUnsubscribe(e,(()=>{})),heartbeatDelay:()=>new Promise(((t,s)=>{e=this._configuration.getHeartbeatInterval(),e?setTimeout(t,1e3*e):s(new d("Heartbeat interval has been reset."))})),retryDelay:e=>new Promise((t=>setTimeout(t,e))),emitStatus:e=>this.listenerManager.announceStatus(e),config:this._configuration,presenceState:this.presenceState})),this.eventEngine=new St({handshake:this.subscribeHandshake.bind(this),receiveMessages:this.subscribeReceiveMessages.bind(this),delay:e=>new Promise((t=>setTimeout(t,e))),join:this.join.bind(this),leave:this.leave.bind(this),leaveAll:this.leaveAll.bind(this),presenceState:this.presenceState,config:this._configuration,emitMessages:e=>{try{e.forEach((e=>this.eventEmitter.emitEvent(e)))}catch(e){const t={error:!0,category:h.PNUnknownCategory,errorData:e,statusCode:0};this.listenerManager.announceStatus(t)}},emitStatus:e=>this.listenerManager.announceStatus(e)})}else this.subscriptionManager=new Y(this._configuration,this.listenerManager,this.eventEmitter,this.makeSubscribe.bind(this),this.heartbeat.bind(this),this.makeUnsubscribe.bind(this),this.time.bind(this))}get configuration(){return this._configuration}get _config(){return this.configuration}get authKey(){var e;return null!==(e=this._configuration.authKey)&&void 0!==e?e:void 0}getAuthKey(){return this.authKey}setAuthKey(e){this._configuration.setAuthKey(e)}get userId(){return this._configuration.userId}set userId(e){if(!e||"string"!=typeof e||0===e.trim().length)throw new Error("Missing or invalid userId parameter. Provide a valid string userId");this._configuration.userId=e}getUserId(){return this._configuration.userId}setUserId(e){if(!e||"string"!=typeof e||0===e.trim().length)throw new Error("Missing or invalid userId parameter. Provide a valid string userId");this._configuration.userId=e}get filterExpression(){var e;return null!==(e=this._configuration.getFilterExpression())&&void 0!==e?e:void 0}getFilterExpression(){return this.filterExpression}set filterExpression(e){this._configuration.setFilterExpression(e)}setFilterExpression(e){this.filterExpression=e}get cipherKey(){return this._configuration.getCipherKey()}set cipherKey(e){this._configuration.setCipherKey(e)}setCipherKey(e){this.cipherKey=e}set heartbeatInterval(e){this._configuration.setHeartbeatInterval(e)}setHeartbeatInterval(e){this.heartbeatInterval=e}getVersion(){return this._configuration.getVersion()}_addPnsdkSuffix(e,t){this._configuration._addPnsdkSuffix(e,t)}getUUID(){return this.userId}setUUID(e){this.userId=e}get customEncrypt(){return this._configuration.getCustomEncrypt()}get customDecrypt(){return this._configuration.getCustomDecrypt()}channel(e){return new rs(e,this.eventEmitter,this)}channelGroup(e){return new ss(e,this.eventEmitter,this)}channelMetadata(e){return new ts(e,this.eventEmitter,this)}userMetadata(e){return new ns(e,this.eventEmitter,this)}subscriptionSet(e){return new Zt(Object.assign(Object.assign({},e),{eventEmitter:this.eventEmitter,pubnub:this}))}sendRequest(e,t){return i(this,void 0,void 0,(function*(){const s=e.validate();if(s){if(t)return t(p(s),null);throw new d("Validation failed, check status for details",p(s))}const n=e.request();n.formData&&n.formData.length>0?n.timeout=300:e.operation()===re.PNSubscribeOperation?n.timeout=this._configuration.getSubscribeTimeout():n.timeout=this._configuration.getTransactionTimeout();const r={error:!1,operation:e.operation(),category:h.PNAcknowledgmentCategory,statusCode:0},[i,o]=this.transport.makeSendable(n);return e.cancellationController=o||null,i.then((t=>{if(r.statusCode=t.status,200!==t.status&&204!==t.status){const e=t.headers["content-type"];if(e||-1!==e.indexOf("javascript")||-1!==e.indexOf("json")){const e=JSON.parse(Is.decoder.decode(t.body));"object"==typeof e&&"error"in e&&e.error&&"object"==typeof e.error&&(r.errorData=e.error)}}return e.parse(t)})).then((e=>t?t(r,e):e)).catch((s=>{const n=s instanceof _?s:_.create(s);if(t)return t(n.toStatus(e.operation()),null);throw n.toPubNubError(e.operation(),"REST API request processing error, check status for details")}))}))}destroy(e){this.subscriptionManager?(this.subscriptionManager.unsubscribeAll(e),this.subscriptionManager.disconnect()):this.eventEngine&&this.eventEngine.dispose()}stop(){this.destroy()}addListener(e){this.listenerManager.addListener(e)}removeListener(e){this.listenerManager.removeListener(e)}removeAllListeners(){this.listenerManager.removeAllListeners()}publish(e,t){return i(this,void 0,void 0,(function*(){const s=new kt(Object.assign(Object.assign({},e),{keySet:this._configuration.keySet,crypto:this._configuration.getCryptoModule()}));return t?this.sendRequest(s,t):this.sendRequest(s)}))}signal(e,t){return i(this,void 0,void 0,(function*(){const s=new Et(Object.assign(Object.assign({},e),{keySet:this._configuration.keySet}));return t?this.sendRequest(s,t):this.sendRequest(s)}))}fire(e,t){return i(this,void 0,void 0,(function*(){return null!=t||(t=()=>{}),this.publish(Object.assign(Object.assign({},e),{replicate:!1,storeInHistory:!1}),t)}))}getSubscribedChannels(){return this.subscriptionManager?this.subscriptionManager.subscribedChannels:this.eventEngine?this.eventEngine.getSubscribedChannels():[]}getSubscribedChannelGroups(){return this.subscriptionManager?this.subscriptionManager.subscribedChannelGroups:this.eventEngine?this.eventEngine.getSubscribedChannelGroups():[]}subscribe(e){this.subscriptionManager?this.subscriptionManager.subscribe(e):this.eventEngine&&this.eventEngine.subscribe(e)}makeSubscribe(e,t){const s=new ae(Object.assign(Object.assign({},e),{keySet:this._configuration.keySet,crypto:this._configuration.getCryptoModule(),getFileUrl:this.getFileUrl.bind(this)}));if(this.sendRequest(s,((e,n)=>{var r;this.subscriptionManager&&(null===(r=this.subscriptionManager.abort)||void 0===r?void 0:r.identifier)===s.requestIdentifier&&(this.subscriptionManager.abort=null),t(e,n)})),this.subscriptionManager){const e=()=>s.abort();e.identifier=s.requestIdentifier,this.subscriptionManager.abort=e}}unsubscribe(e){this.subscriptionManager?this.subscriptionManager.unsubscribe(e):this.eventEngine&&this.eventEngine.unsubscribe(e)}makeUnsubscribe(e,t){this.sendRequest(new jt(Object.assign(Object.assign({},e),{keySet:this._configuration.keySet})),t)}unsubscribeAll(){this.subscriptionManager?this.subscriptionManager.unsubscribeAll():this.eventEngine&&this.eventEngine.unsubscribeAll()}disconnect(){this.subscriptionManager?this.subscriptionManager.disconnect():this.eventEngine&&this.eventEngine.disconnect()}reconnect(e){this.subscriptionManager?this.subscriptionManager.reconnect():this.eventEngine&&this.eventEngine.reconnect(null!=e?e:{})}subscribeHandshake(e){return i(this,void 0,void 0,(function*(){const t=new Ct(Object.assign(Object.assign({},e),{keySet:this._configuration.keySet,crypto:this._configuration.getCryptoModule(),getFileUrl:this.getFileUrl.bind(this)})),s=e.abortSignal.subscribe((e=>{t.abort()}));return this.sendRequest(t).then((e=>(s(),e.cursor)))}))}subscribeReceiveMessages(e){return i(this,void 0,void 0,(function*(){const t=new Ot(Object.assign(Object.assign({},e),{keySet:this._configuration.keySet,crypto:this._configuration.getCryptoModule(),getFileUrl:this.getFileUrl.bind(this)})),s=e.abortSignal.subscribe((e=>{t.abort()}));return this.sendRequest(t).then((e=>(s(),e)))}))}getMessageActions(e,t){return i(this,void 0,void 0,(function*(){const s=new xt(Object.assign(Object.assign({},e),{keySet:this._configuration.keySet}));return t?this.sendRequest(s,t):this.sendRequest(s)}))}addMessageAction(e,t){return i(this,void 0,void 0,(function*(){const s=new Dt(Object.assign(Object.assign({},e),{keySet:this._configuration.keySet}));return t?this.sendRequest(s,t):this.sendRequest(s)}))}removeMessageAction(e,t){return i(this,void 0,void 0,(function*(){const s=new Kt(Object.assign(Object.assign({},e),{keySet:this._configuration.keySet}));return t?this.sendRequest(s,t):this.sendRequest(s)}))}fetchMessages(e,t){return i(this,void 0,void 0,(function*(){const s=new Ft(Object.assign(Object.assign({},e),{keySet:this._configuration.keySet,crypto:this._configuration.getCryptoModule(),getFileUrl:this.getFileUrl.bind(this)}));return t?this.sendRequest(s,t):this.sendRequest(s)}))}deleteMessages(e,t){return i(this,void 0,void 0,(function*(){const s=new It(Object.assign(Object.assign({},e),{keySet:this._configuration.keySet}));return t?this.sendRequest(s,t):this.sendRequest(s)}))}messageCounts(e,t){return i(this,void 0,void 0,(function*(){const s=new Rt(Object.assign(Object.assign({},e),{keySet:this._configuration.keySet}));return t?this.sendRequest(s,t):this.sendRequest(s)}))}history(e,t){return i(this,void 0,void 0,(function*(){const s=new Ut(Object.assign(Object.assign({},e),{keySet:this._configuration.keySet,crypto:this._configuration.getCryptoModule()}));return t?this.sendRequest(s,t):this.sendRequest(s)}))}hereNow(e,t){return i(this,void 0,void 0,(function*(){const s=new At(Object.assign(Object.assign({},e),{keySet:this._configuration.keySet}));return t?this.sendRequest(s,t):this.sendRequest(s)}))}whereNow(e,t){return i(this,void 0,void 0,(function*(){var s;const n=new _t({uuid:null!==(s=e.uuid)&&void 0!==s?s:this._configuration.userId,keySet:this._configuration.keySet});return t?this.sendRequest(n,t):this.sendRequest(n)}))}getState(e,t){return i(this,void 0,void 0,(function*(){var s;const n=new Nt(Object.assign(Object.assign({},e),{uuid:null!==(s=e.uuid)&&void 0!==s?s:this._configuration.userId,keySet:this._configuration.keySet}));return t?this.sendRequest(n,t):this.sendRequest(n)}))}setState(e,t){return i(this,void 0,void 0,(function*(){var s,n;const{keySet:r,userId:i}=this._configuration,o=this._configuration.getPresenceTimeout();let a;if(this._configuration.enableEventEngine&&this.presenceState){const t=this.presenceState;null===(s=e.channels)||void 0===s||s.forEach((s=>t[s]=e.state)),"channelGroups"in e&&(null===(n=e.channelGroups)||void 0===n||n.forEach((s=>t[s]=e.state)))}return a="withHeartbeat"in e?new Mt(Object.assign(Object.assign({},e),{keySet:r,heartbeat:o})):new Pt(Object.assign(Object.assign({},e),{keySet:r,uuid:i})),this.subscriptionManager&&this.subscriptionManager.setState(e),t?this.sendRequest(a,t):this.sendRequest(a)}))}presence(e){var t;null===(t=this.subscriptionManager)||void 0===t||t.changePresence(e)}heartbeat(e,t){return i(this,void 0,void 0,(function*(){const s=new Mt(Object.assign(Object.assign({},e),{keySet:this._configuration.keySet}));return t?this.sendRequest(s,t):this.sendRequest(s)}))}join(e){var t;null===(t=this.presenceEventEngine)||void 0===t||t.join(e)}leave(e){var t;null===(t=this.presenceEventEngine)||void 0===t||t.leave(e)}leaveAll(){var e;null===(e=this.presenceEventEngine)||void 0===e||e.leaveAll()}grantToken(e,t){return i(this,void 0,void 0,(function*(){const s=new Wt(Object.assign(Object.assign({},e),{keySet:this._configuration.keySet}));return t?this.sendRequest(s,t):this.sendRequest(s)}))}revokeToken(e,t){return i(this,void 0,void 0,(function*(){const s=new Vt(Object.assign(Object.assign({},e),{keySet:this._configuration.keySet}));return t?this.sendRequest(s,t):this.sendRequest(s)}))}get token(){return this.tokenManager.getToken()}getToken(){return this.token}set token(e){this.tokenManager.setToken(e)}setToken(e){this.token=e}parseToken(e){return this.tokenManager.parseToken(e)}grant(e,t){return i(this,void 0,void 0,(function*(){const s=new Jt(Object.assign(Object.assign({},e),{keySet:this._configuration.keySet}));return t?this.sendRequest(s,t):this.sendRequest(s)}))}audit(e,t){return i(this,void 0,void 0,(function*(){const s=new Yt(Object.assign(Object.assign({},e),{keySet:this._configuration.keySet}));return t?this.sendRequest(s,t):this.sendRequest(s)}))}get objects(){return this._objects}fetchUsers(e,t){return i(this,void 0,void 0,(function*(){return this.objects._getAllUUIDMetadata(e,t)}))}fetchUser(e,t){return i(this,void 0,void 0,(function*(){return this.objects._getUUIDMetadata(e,t)}))}createUser(e,t){return i(this,void 0,void 0,(function*(){return this.objects._setUUIDMetadata(e,t)}))}updateUser(e,t){return i(this,void 0,void 0,(function*(){return this.objects._setUUIDMetadata(e,t)}))}removeUser(e,t){return i(this,void 0,void 0,(function*(){return this.objects._removeUUIDMetadata(e,t)}))}fetchSpaces(e,t){return i(this,void 0,void 0,(function*(){return this.objects._getAllChannelMetadata(e,t)}))}fetchSpace(e,t){return i(this,void 0,void 0,(function*(){return this.objects._getChannelMetadata(e,t)}))}createSpace(e,t){return i(this,void 0,void 0,(function*(){return this.objects._setChannelMetadata(e,t)}))}updateSpace(e,t){return i(this,void 0,void 0,(function*(){return this.objects._setChannelMetadata(e,t)}))}removeSpace(e,t){return i(this,void 0,void 0,(function*(){return this.objects._removeChannelMetadata(e,t)}))}fetchMemberships(e,t){return i(this,void 0,void 0,(function*(){return this.objects.fetchMemberships(e,t)}))}addMemberships(e,t){return i(this,void 0,void 0,(function*(){return this.objects.addMemberships(e,t)}))}updateMemberships(e,t){return i(this,void 0,void 0,(function*(){return this.objects.addMemberships(e,t)}))}removeMemberships(e,t){return i(this,void 0,void 0,(function*(){var s,n,r;if("spaceId"in e){const r=e,i={channel:null!==(s=r.spaceId)&&void 0!==s?s:r.channel,uuids:null!==(n=r.userIds)&&void 0!==n?n:r.uuids,limit:0};return t?this.objects.removeChannelMembers(i,t):this.objects.removeChannelMembers(i)}const i=e,o={uuid:i.userId,channels:null!==(r=i.spaceIds)&&void 0!==r?r:i.channels,limit:0};return t?this.objects.removeMemberships(o,t):this.objects.removeMemberships(o)}))}get channelGroups(){return this._channelGroups}get push(){return this._push}sendFile(e,t){return i(this,void 0,void 0,(function*(){if(!this._configuration.PubNubFile)throw new Error("Validation failed: 'PubNubFile' not configured or file upload not supported by the platform.");const s=new zt(Object.assign(Object.assign({},e),{keySet:this._configuration.keySet,PubNubFile:this._configuration.PubNubFile,fileUploadPublishRetryLimit:this._configuration.fileUploadPublishRetryLimit,file:e.file,sendRequest:this.sendRequest.bind(this),publishFile:this.publishFile.bind(this),crypto:this._configuration.getCryptoModule(),cryptography:this.cryptography?this.cryptography:void 0})),n={error:!1,operation:re.PNPublishFileOperation,category:h.PNAcknowledgmentCategory,statusCode:0};return s.process().then((e=>(n.statusCode=e.status,t?t(n,e):e))).catch((e=>{let s;throw e instanceof d?s=e.status:e instanceof _&&(s=e.toStatus(n.operation)),t&&s&&t(s,null),new d("REST API request processing error, check status for details",s)}))}))}publishFile(e,t){return i(this,void 0,void 0,(function*(){if(!this._configuration.PubNubFile)throw new Error("Validation failed: 'PubNubFile' not configured or file upload not supported by the platform.");const s=new qt(Object.assign(Object.assign({},e),{keySet:this._configuration.keySet,crypto:this._configuration.getCryptoModule()}));return t?this.sendRequest(s,t):this.sendRequest(s)}))}listFiles(e,t){return i(this,void 0,void 0,(function*(){const s=new Lt(Object.assign(Object.assign({},e),{keySet:this._configuration.keySet}));return t?this.sendRequest(s,t):this.sendRequest(s)}))}getFileUrl(e){var t;const s=this.transport.request(new Gt(Object.assign(Object.assign({},e),{keySet:this._configuration.keySet})).request()),n=null!==(t=s.queryParameters)&&void 0!==t?t:{},r=Object.keys(n).map((e=>{const t=n[e];return Array.isArray(t)?t.map((t=>`${e}=${I(t)}`)).join("&"):`${e}=${I(t)}`})).join("&");return`${s.origin}${s.path}?${r}`}downloadFile(e,t){return i(this,void 0,void 0,(function*(){if(!this._configuration.PubNubFile)throw new Error("Validation failed: 'PubNubFile' not configured or file upload not supported by the platform.");const s=new As(Object.assign(Object.assign({},e),{keySet:this._configuration.keySet,PubNubFile:this._configuration.PubNubFile,cryptography:this.cryptography?this.cryptography:void 0,crypto:this._configuration.getCryptoModule()}));return t?this.sendRequest(s,t):yield this.sendRequest(s)}))}deleteFile(e,t){return i(this,void 0,void 0,(function*(){const s=new $t(Object.assign(Object.assign({},e),{keySet:this._configuration.keySet}));return t?this.sendRequest(s,t):this.sendRequest(s)}))}time(e){return i(this,void 0,void 0,(function*(){const t=new _s;return e?this.sendRequest(t,e):this.sendRequest(t)}))}encrypt(e,t){const s=this._configuration.getCryptoModule();if(!t&&s&&"string"==typeof e){const t=s.encrypt(e);return"string"==typeof t?t:u(t)}if(!this.crypto)throw new Error("Encryption error: cypher key not set");return this.crypto.encrypt(e,t)}decrypt(e,t){const s=this._configuration.getCryptoModule();if(!t&&s){const t=s.decrypt(e);return t instanceof ArrayBuffer?JSON.parse((new TextDecoder).decode(t)):t}if(!this.crypto)throw new Error("Decryption error: cypher key not set");return this.crypto.decrypt(e,t)}encryptFile(e,t){return i(this,void 0,void 0,(function*(){var s;if("string"!=typeof e&&(t=e),!t)throw new Error("File encryption error. Source file is missing.");if(!this._configuration.PubNubFile)throw new Error("File encryption error. File constructor not configured.");if("string"!=typeof e&&!this._configuration.getCryptoModule())throw new Error("File encryption error. Crypto module not configured.");if("string"==typeof e){if(!this.cryptography)throw new Error("File encryption error. File encryption not available");return this.cryptography.encryptFile(e,t,this._configuration.PubNubFile)}return null===(s=this._configuration.getCryptoModule())||void 0===s?void 0:s.encryptFile(t,this._configuration.PubNubFile)}))}decryptFile(e,t){return i(this,void 0,void 0,(function*(){var s;if("string"!=typeof e&&(t=e),!t)throw new Error("File encryption error. Source file is missing.");if(!this._configuration.PubNubFile)throw new Error("File decryption error. File constructor not configured.");if("string"==typeof e&&!this._configuration.getCryptoModule())throw new Error("File decryption error. Crypto module not configured.");if("string"==typeof e){if(!this.cryptography)throw new Error("File decryption error. File decryption not available");return this.cryptography.decryptFile(e,t,this._configuration.PubNubFile)}return null===(s=this._configuration.getCryptoModule())||void 0===s?void 0:s.decryptFile(t,this._configuration.PubNubFile)}))}}Is.decoder=new TextDecoder,Is.OPERATIONS=re,Is.CATEGORIES=h,Is.ExponentialRetryPolicy=Le.ExponentialRetryPolicy,Is.LinearRetryPolicy=Le.LinearRetryPolicy;class Rs{constructor(e,t){this.decode=e,this.base64ToBinary=t}decodeToken(e){let t="";e.length%4==3?t="=":e.length%4==2&&(t="==");const s=e.replace(/-/gi,"+").replace(/_/gi,"/")+t,n=this.decode(this.base64ToBinary(s));return"object"==typeof n?n:void 0}}class Us extends Is{constructor(e){var t;const s=D(e),r=Object.assign(Object.assign({},s),{sdkFamily:"Web",PubNubFile:a}),i=$(r,(e=>{if(e.cipherKey)return new P({default:new N(Object.assign({},e)),cryptors:[new S({cipherKey:e.cipherKey})]})})),o=new B(new Rs((e=>x(n.decode(e))),c));let u;(i.getCipherKey()||i.secretKey)&&(u=new E({secretKey:i.secretKey,cipherKey:i.getCipherKey(),useRandomIVs:i.getUseRandomIVs(),customEncrypt:i.getCustomEncrypt(),customDecrypt:i.getCustomDecrypt()}));let l=new F(i.keepAlive,i.logVerbosity);s.subscriptionWorkerUrl&&(l=new A({clientIdentifier:i._instanceId,subscriptionKey:i.subscribeKey,userId:i.getUserId(),workerUrl:s.subscriptionWorkerUrl,sdkVersion:i.getVersion(),logVerbosity:i.logVerbosity,workerLogVerbosity:r.subscriptionWorkerLogVerbosity,transport:l}));super({configuration:i,transport:new V({clientConfiguration:i,tokenManager:o,transport:l}),cryptography:new C,tokenManager:o,crypto:u}),(null===(t=e.listenToBrowserNetworkEvents)||void 0===t||t)&&(window.addEventListener("offline",(()=>{this.networkDownDetected()})),window.addEventListener("online",(()=>{this.networkUpDetected()})))}networkDownDetected(){this.listenerManager.announceNetworkDown(),this._configuration.restore?this.disconnect():this.destroy(!0)}networkUpDetected(){this.listenerManager.announceNetworkUp(),this.reconnect()}}return Us.CryptoModule=P,Us})); diff --git a/dist/web/pubnub.worker.js b/dist/web/pubnub.worker.js index 31a3ef3ac..b033cf48e 100644 --- a/dist/web/pubnub.worker.js +++ b/dist/web/pubnub.worker.js @@ -106,11 +106,27 @@ * Service worker provides support for PubNub subscription feature to give better user experience across * multiple opened pages. */ + /** + * How often PING request should be sent to the PubNub clients. + */ + const clientPingRequestInterval = 5000; // region State /** * Service `ArrayBuffer` response decoder. */ const decoder = new TextDecoder(); + /** + * Whether `Subscription` worker should print debug information to the console or not. + */ + let logVerbosity = false; + /** + * PubNub clients active ping interval. + */ + let pingInterval; + /** + * Unique shared worker instance identifier. + */ + const sharedWorkerIdentifier = uuidGenerator.createUUID(); /** * Map of identifiers, scheduled by the Service Worker, to their abort controllers. * @@ -132,11 +148,11 @@ */ const presenceState = {}; /** - * Per-subscription key map of client identifiers to the Service Worker {@link Client} identifier. + * Per-subscription key map of client identifiers to the Shared Worker {@link MessagePort}. * - * Service Worker {@link Client} represent pages at which PubNub clients registered Service Workers. + * Shared Worker {@link MessagePort} represent specific PubNub client which connected to the Shared Worker. */ - const serviceWorkerClients = {}; + const sharedWorkerClients = {}; /** * List of ongoing subscription requests. * @@ -149,33 +165,45 @@ // -------------------------------------------------------- // region Event Handlers /** - * Listen for Service Worker activation. - */ - self.addEventListener('activate', (event) => { - event.waitUntil(self.clients.claim()); - }); - /** - * Listen for events from the client. + * Handle new PubNub client 'connection'. + * + * Echo listeners to let `SharedWorker` users that it is ready. + * + * @param event - Remote `SharedWorker` client connection event. */ - self.addEventListener('message', (event) => { - // Ignoring requests sent from other service workers. - if (!validateEventPayload(event)) - return; - const data = event.data; - if (data.type === 'send-request') { - if (data.request.path.startsWith('/v2/subscribe')) { - registerClientIfRequired(event); - handleSendSubscribeRequestEvent(data); - } - else { - if (!pubNubClients[data.clientIdentifier]) - registerClientIfRequired(event); - handleSendLeaveRequestEvent(event); - } - } - else if (data.type === 'cancel-request') - handleCancelRequestEvent(data); - }); + self.onconnect = (event) => { + consoleLog('New PubNub Client connected to the Subscription Shared Worker.'); + event.ports.forEach((receiver) => { + receiver.start(); + receiver.onmessage = (event) => { + // Ignoring unknown event payloads. + if (!validateEventPayload(event)) + return; + const data = event.data; + if (data.type === 'client-register') { + if (!logVerbosity && data.workerLogVerbosity) + logVerbosity = true; + // Appending information about messaging port for responses. + data.port = receiver; + registerClientIfRequired(data); + consoleLog(`Client '${data.clientIdentifier}' registered with '${sharedWorkerIdentifier}' shared worker`); + } + else if (data.type === 'client-pong') + handleClientPong(data); + else if (data.type === 'send-request') { + if (data.request.path.startsWith('/v2/subscribe')) { + updateClientStateIfRequired(data); + handleSendSubscribeRequestEvent(data); + } + else + handleSendLeaveRequestEvent(data); + } + else if (data.type === 'cancel-request') + handleCancelRequestEvent(data); + }; + receiver.postMessage({ type: 'shared-worker-connected' }); + }); + }; /** * Handle client request to send subscription request. * @@ -187,7 +215,7 @@ if (client) notifyRequestProcessing('start', [client], new Date().toISOString()); if (typeof requestOrId === 'string') { - if (client) { + if (client && client.subscription) { // Updating client timetoken information. client.subscription.previousTimetoken = client.subscription.timetoken; client.subscription.timetoken = serviceRequests[requestOrId].timetoken; @@ -208,14 +236,14 @@ // Clean up scheduled request and client references to it. markRequestCompleted(clients, requestOrId.identifier); }); + consoleLog(`'${Object.keys(serviceRequests).length}' subscription request currently active.`); }; /** * Handle client request to leave request. * - * @param event - Leave event details. + * @param data - Leave event details. */ - const handleSendLeaveRequestEvent = (event) => { - const data = event.data; + const handleSendLeaveRequestEvent = (data) => { const request = leaveTransportRequestFromEvent(data); const client = pubNubClients[data.clientIdentifier]; if (!client) @@ -228,10 +256,7 @@ result.url = `${data.request.origin}${data.request.path}`; result.clientIdentifier = data.clientIdentifier; result.identifier = data.request.identifier; - publishClientEvent(event.source.id, result).then((sent) => { - if (sent) - invalidateClient(client.subscriptionKey, client.clientIdentifier, client.userId); - }); + publishClientEvent(client, result); return; } sendRequest(request, () => [client], (clients, response) => { @@ -241,6 +266,7 @@ // Notify each PubNub client which awaited for response. notifyRequestProcessingResult(clients, null, data.request, requestProcessingError(error)); }); + consoleLog(`Started leave request.`, client); }; /** * Handle cancel request event. @@ -251,7 +277,9 @@ */ const handleCancelRequestEvent = (event) => { const client = pubNubClients[event.clientIdentifier]; - const serviceRequestId = client ? client.subscription.serviceRequestId : undefined; + if (!client || !client.subscription) + return; + const serviceRequestId = client.subscription.serviceRequestId; if (!client || !serviceRequestId) return; // Unset awaited requests. @@ -335,7 +363,7 @@ * @returns List of PubNub client state objects for Service Worker. */ const clientsForRequest = (identifier) => { - return Object.values(pubNubClients).filter((client) => client !== undefined && client.subscription.serviceRequestId === identifier); + return Object.values(pubNubClients).filter((client) => client !== undefined && client.subscription !== undefined && client.subscription.serviceRequestId === identifier); }; /** * Clean up PubNub client states from ongoing request. @@ -348,8 +376,10 @@ const markRequestCompleted = (clients, requestId) => { delete serviceRequests[requestId]; clients.forEach((client) => { - delete client.subscription.request; - delete client.subscription.serviceRequestId; + if (client.subscription) { + delete client.subscription.request; + delete client.subscription.serviceRequestId; + } }); }; /** @@ -390,7 +420,8 @@ const subscribeTransportRequestFromEvent = (event) => { var _a, _b, _c, _d; const client = pubNubClients[event.clientIdentifier]; - const clients = clientsForSendSubscribeRequestEvent(client.subscription.previousTimetoken, event); + const subscription = client.subscription; + const clients = clientsForSendSubscribeRequestEvent(subscription.previousTimetoken, event); const serviceRequestId = uuidGenerator.createUUID(); const request = Object.assign({}, event.request); if (clients.length > 1) { @@ -400,10 +431,10 @@ return activeRequestId; const state = ((_a = presenceState[client.subscriptionKey]) !== null && _a !== void 0 ? _a : {})[client.userId]; const aggregatedState = {}; - const channelGroups = new Set(client.subscription.channelGroups); - const channels = new Set(client.subscription.channels); - if (state && client.subscription.objectsWithState.length) { - client.subscription.objectsWithState.forEach((name) => { + const channelGroups = new Set(subscription.channelGroups); + const channels = new Set(subscription.channels); + if (state && subscription.objectsWithState.length) { + subscription.objectsWithState.forEach((name) => { const objectState = state[name]; if (objectState) aggregatedState[name] = objectState; @@ -412,7 +443,7 @@ for (const client of clients) { const { subscription } = client; // Skip clients which already have active subscription request. - if (subscription.serviceRequestId) + if (!subscription || !subscription.serviceRequestId) continue; subscription.channelGroups.forEach(channelGroups.add, channelGroups); subscription.channels.forEach(channels.add, channels); @@ -452,12 +483,21 @@ serviceRequests[serviceRequestId] = { requestId: serviceRequestId, timetoken: (_d = request.queryParameters.tt) !== null && _d !== void 0 ? _d : '0', - channelGroups: client.subscription.channelGroups, - channels: client.subscription.channels, + channelGroups: subscription.channelGroups, + channels: subscription.channels, }; } - client.subscription.serviceRequestId = serviceRequestId; + subscription.serviceRequestId = serviceRequestId; request.identifier = serviceRequestId; + if (logVerbosity) { + const clientIds = clients + .reduce((identifiers, { clientIdentifier }) => { + identifiers.push(clientIdentifier); + return identifiers; + }, []) + .join(','); + consoleDir(serviceRequests[serviceRequestId], `Started aggregated request for clients: ${clientIds}`); + } return request; }; /** @@ -476,7 +516,7 @@ let channelGroups = channelGroupsFromRequest(event.request); let channels = channelsFromRequest(event.request); const request = Object.assign({}, event.request); - if (client) { + if (client && client.subscription) { const { subscription } = client; if (channels.length) subscription.channels = subscription.channels.filter((channel) => !channels.includes(channel)); @@ -486,15 +526,28 @@ } // Filter out channels and groups which is still in use by the other PubNub client instances. for (const client of clients) { + const subscription = client.subscription; + if (subscription === undefined) + continue; if (client.clientIdentifier === event.clientIdentifier) continue; if (channels.length) - channels = channels.filter((channel) => !client.subscription.channels.includes(channel)); + channels = channels.filter((channel) => !subscription.channels.includes(channel)); if (channelGroups.length) - channelGroups = channelGroups.filter((group) => !client.subscription.channelGroups.includes(group)); + channelGroups = channelGroups.filter((group) => !subscription.channelGroups.includes(group)); } - if (channels.length === 0 && channelGroups.length === 0) + if (channels.length === 0 && channelGroups.length === 0) { + if (logVerbosity && client) { + const clientIds = clients + .reduce((identifiers, { clientIdentifier }) => { + identifiers.push(clientIdentifier); + return identifiers; + }, []) + .join(','); + consoleLog(`Specified channels and groups still in use by other clients: ${clientIds}. Ignoring leave request.`, client); + } return undefined; + } // Update request channels list (if required). if (channels.length) { const pathComponents = request.path.split('/'); @@ -507,18 +560,22 @@ return request; }; /** - * Send event to all service worker clients. + * Send event to the specific PubNub client. * - * @param identifier - Service Worker receiving {@link Client} identifier. - * @param event - Service worker event object. + * @param client - State for the client which should receive {@link event}. + * @param event - Subscription worker event object. */ - const publishClientEvent = (identifier, event) => { - return self.clients.get(identifier).then((client) => { - if (!client) - return false; - client.postMessage(event); + const publishClientEvent = (client, event) => { + var _a; + const receiver = ((_a = sharedWorkerClients[client.subscriptionKey]) !== null && _a !== void 0 ? _a : {})[client.clientIdentifier]; + if (!receiver) + return false; + try { + receiver.postMessage(event); return true; - }); + } + catch (error) { } + return false; }; /** * Send request processing update. @@ -535,7 +592,7 @@ var _a; if (clients.length === 0) return; - const clientIds = (_a = serviceWorkerClients[clients[0].subscriptionKey]) !== null && _a !== void 0 ? _a : {}; + const clientIds = (_a = sharedWorkerClients[clients[0].subscriptionKey]) !== null && _a !== void 0 ? _a : {}; let event; if (type === 'start') { event = { @@ -564,17 +621,17 @@ duration: duration, }; } - clients.forEach((client) => { + for (const client of clients) { + if (client.subscription === undefined) + continue; const serviceWorkerClientId = clientIds[client.clientIdentifier]; const { request: clientRequest } = client.subscription; const decidedRequest = clientRequest !== null && clientRequest !== void 0 ? clientRequest : request; if (client.logVerbosity && serviceWorkerClientId && decidedRequest) { - publishClientEvent(serviceWorkerClientId, Object.assign(Object.assign({}, event), { clientIdentifier: client.clientIdentifier, url: `${decidedRequest.origin}${decidedRequest.path}`, query: decidedRequest.queryParameters })).then((sent) => { - if (sent) - invalidateClient(client.subscriptionKey, client.clientIdentifier, client.userId); - }); + const payload = Object.assign(Object.assign({}, event), { clientIdentifier: client.clientIdentifier, url: `${decidedRequest.origin}${decidedRequest.path}`, query: decidedRequest.queryParameters }); + publishClientEvent(client, payload); } - }); + } }; /** * Send request processing result event. @@ -590,7 +647,7 @@ return; if (!result && !response) return; - const clientIds = (_a = serviceWorkerClients[clients[0].subscriptionKey]) !== null && _a !== void 0 ? _a : {}; + const clientIds = (_a = sharedWorkerClients[clients[0].subscriptionKey]) !== null && _a !== void 0 ? _a : {}; if (!result && response) { result = response[0].status >= 400 @@ -598,17 +655,17 @@ requestProcessingError(undefined, response) : requestProcessingSuccess(response); } - clients.forEach((client) => { + for (const client of clients) { + if (client.subscription === undefined) + continue; const serviceWorkerClientId = clientIds[client.clientIdentifier]; const { request: clientRequest } = client.subscription; const decidedRequest = clientRequest !== null && clientRequest !== void 0 ? clientRequest : request; if (serviceWorkerClientId && decidedRequest) { - publishClientEvent(serviceWorkerClientId, Object.assign(Object.assign({}, result), { clientIdentifier: client.clientIdentifier, identifier: decidedRequest.identifier, url: `${decidedRequest.origin}${decidedRequest.path}` })).then((sent) => { - if (sent) - invalidateClient(client.subscriptionKey, client.clientIdentifier, client.userId); - }); + const payload = Object.assign(Object.assign({}, result), { clientIdentifier: client.clientIdentifier, identifier: decidedRequest.identifier, url: `${decidedRequest.origin}${decidedRequest.path}` }); + publishClientEvent(client, payload); } - }); + } }; /** * Create processing success event from service response. @@ -696,82 +753,111 @@ * @param event - Base information about PubNub client instance and Service Worker {@link Client}. */ const registerClientIfRequired = (event) => { - var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p, _q, _r, _s, _t, _u; - var _v, _w, _x, _y, _z, _0, _1, _2, _3, _4, _5; - const information = event.data; - const { clientIdentifier } = information; - const query = information.request.queryParameters; - let client = pubNubClients[clientIdentifier]; - if (!client) { - const isPresenceLeave = !information.request.path.startsWith('/v2/subscribe'); - const channelGroupQuery = !isPresenceLeave ? ((_a = query['channel-group']) !== null && _a !== void 0 ? _a : '') : ''; - const state = !isPresenceLeave ? ((_b = query.state) !== null && _b !== void 0 ? _b : '') : ''; - client = pubNubClients[clientIdentifier] = { - clientIdentifier, - subscriptionKey: information.subscriptionKey, - userId: query.uuid, - authKey: ((_c = query.auth) !== null && _c !== void 0 ? _c : ''), - logVerbosity: information.logVerbosity, - subscription: { - path: !isPresenceLeave ? information.request.path : '', - channelGroupQuery: !isPresenceLeave ? channelGroupQuery : '', - channels: !isPresenceLeave ? channelsFromRequest(information.request) : [], - channelGroups: !isPresenceLeave ? channelGroupsFromRequest(information.request) : [], - previousTimetoken: !isPresenceLeave ? ((_d = query.tt) !== null && _d !== void 0 ? _d : '0') : '0', - timetoken: !isPresenceLeave ? ((_e = query.tt) !== null && _e !== void 0 ? _e : '0') : '0', - request: !isPresenceLeave ? information.request : undefined, - objectsWithState: [], - filterExpression: !isPresenceLeave ? ((_f = query['filter-expr']) !== null && _f !== void 0 ? _f : '') : undefined, - }, + var _a, _b; + var _c, _d; + const { clientIdentifier } = event; + if (pubNubClients[clientIdentifier]) + return; + const client = (pubNubClients[clientIdentifier] = { + clientIdentifier, + subscriptionKey: event.subscriptionKey, + userId: event.userId, + logVerbosity: event.logVerbosity, + }); + // Map registered PubNub client to its subscription key. + const clientsBySubscriptionKey = ((_a = pubNubClientsBySubscriptionKey[_c = event.subscriptionKey]) !== null && _a !== void 0 ? _a : (pubNubClientsBySubscriptionKey[_c] = [])); + if (clientsBySubscriptionKey.every((entry) => entry.clientIdentifier !== clientIdentifier)) + clientsBySubscriptionKey.push(client); + // Binding PubNub client to the MessagePort (receiver). + ((_b = sharedWorkerClients[_d = event.subscriptionKey]) !== null && _b !== void 0 ? _b : (sharedWorkerClients[_d] = {}))[clientIdentifier] = event.port; + consoleLog(`Registered PubNub client with '${clientIdentifier}' identifier. ` + + `'${Object.keys(pubNubClients).length}' clients currently active.`); + if (!pingInterval && Object.keys(pubNubClients).length > 0) { + consoleLog(`Setup PubNub client ping event ${clientPingRequestInterval / 1000} seconds`); + pingInterval = setInterval(() => pingClients(), clientPingRequestInterval); + } + }; + /** + * Update information about previously registered client. + * + * Use information from request to populate list of channels and other useful information. + * + * @param event - Send request. + */ + const updateClientStateIfRequired = (event) => { + var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l; + var _m, _o, _p, _q, _r, _s, _t, _u, _v; + const query = event.request.queryParameters; + const { clientIdentifier } = event; + const client = pubNubClients[clientIdentifier]; + // This should never happen. + if (!client) + return; + const channelGroupQuery = ((_a = query['channel-group']) !== null && _a !== void 0 ? _a : ''); + const state = ((_b = query.state) !== null && _b !== void 0 ? _b : ''); + let subscription = client.subscription; + if (!subscription) { + subscription = { + path: '', + channelGroupQuery: '', + channels: [], + channelGroups: [], + previousTimetoken: '0', + timetoken: '0', + objectsWithState: [], }; - if (!isPresenceLeave && state.length > 0) { + if (state.length > 0) { const parsedState = JSON.parse(state); - const userState = ((_h = (_w = ((_g = presenceState[_v = client.subscriptionKey]) !== null && _g !== void 0 ? _g : (presenceState[_v] = {})))[_x = client.userId]) !== null && _h !== void 0 ? _h : (_w[_x] = {})); + const userState = ((_d = (_o = ((_c = presenceState[_m = client.subscriptionKey]) !== null && _c !== void 0 ? _c : (presenceState[_m] = {})))[_p = client.userId]) !== null && _d !== void 0 ? _d : (_o[_p] = {})); Object.entries(parsedState).forEach(([objectName, value]) => (userState[objectName] = value)); - client.subscription.objectsWithState = Object.keys(parsedState); + subscription.objectsWithState = Object.keys(parsedState); } - // Map registered PubNub client to its subscription key. - const clientsBySubscriptionKey = ((_j = pubNubClientsBySubscriptionKey[_y = information.subscriptionKey]) !== null && _j !== void 0 ? _j : (pubNubClientsBySubscriptionKey[_y] = [])); - if (clientsBySubscriptionKey.every((entry) => entry.clientIdentifier !== clientIdentifier)) - clientsBySubscriptionKey.push(client); - // Binding PubNub client to the page (Service Worker Client). - ((_k = serviceWorkerClients[_z = information.subscriptionKey]) !== null && _k !== void 0 ? _k : (serviceWorkerClients[_z] = {}))[clientIdentifier] = event.source.id; + client.subscription = subscription; } else { - const channelGroupQuery = ((_l = query['channel-group']) !== null && _l !== void 0 ? _l : ''); - const state = ((_m = query.state) !== null && _m !== void 0 ? _m : ''); - client.subscription.filterExpression = ((_o = query['filter-expr']) !== null && _o !== void 0 ? _o : ''); - client.subscription.previousTimetoken = client.subscription.timetoken; - client.subscription.timetoken = ((_p = query.tt) !== null && _p !== void 0 ? _p : '0'); - client.subscription.request = information.request; - client.authKey = ((_q = query.auth) !== null && _q !== void 0 ? _q : ''); - client.userId = query.uuid; - if (client.subscription.path !== information.request.path) { - client.subscription.path = information.request.path; - client.subscription.channels = channelsFromRequest(information.request); - } - if (client.subscription.channelGroupQuery !== channelGroupQuery) { - client.subscription.channelGroupQuery = channelGroupQuery; - client.subscription.channelGroups = channelGroupsFromRequest(information.request); - } + subscription.previousTimetoken = subscription.timetoken; if (state.length > 0) { const parsedState = JSON.parse(state); - const userState = ((_s = (_1 = ((_r = presenceState[_0 = client.subscriptionKey]) !== null && _r !== void 0 ? _r : (presenceState[_0] = {})))[_2 = client.userId]) !== null && _s !== void 0 ? _s : (_1[_2] = {})); + const userState = ((_f = (_r = ((_e = presenceState[_q = client.subscriptionKey]) !== null && _e !== void 0 ? _e : (presenceState[_q] = {})))[_s = client.userId]) !== null && _f !== void 0 ? _f : (_r[_s] = {})); Object.entries(parsedState).forEach(([objectName, value]) => (userState[objectName] = value)); // Clean up state for objects where presence state has been reset. - for (const objectName of client.subscription.objectsWithState) + for (const objectName of subscription.objectsWithState) if (!parsedState[objectName]) delete userState[objectName]; - client.subscription.objectsWithState = Object.keys(parsedState); + subscription.objectsWithState = Object.keys(parsedState); } // Handle potential presence state reset. - else if (client.subscription.objectsWithState.length) { - const userState = ((_u = (_4 = ((_t = presenceState[_3 = client.subscriptionKey]) !== null && _t !== void 0 ? _t : (presenceState[_3] = {})))[_5 = client.userId]) !== null && _u !== void 0 ? _u : (_4[_5] = {})); - for (const objectName of client.subscription.objectsWithState) + else if (subscription.objectsWithState.length) { + const userState = ((_h = (_u = ((_g = presenceState[_t = client.subscriptionKey]) !== null && _g !== void 0 ? _g : (presenceState[_t] = {})))[_v = client.userId]) !== null && _h !== void 0 ? _h : (_u[_v] = {})); + for (const objectName of subscription.objectsWithState) delete userState[objectName]; - client.subscription.objectsWithState = []; + subscription.objectsWithState = []; } } + if (subscription.path !== event.request.path) { + subscription.path = event.request.path; + subscription.channels = channelsFromRequest(event.request); + } + if (subscription.channelGroupQuery !== channelGroupQuery) { + subscription.channelGroupQuery = channelGroupQuery; + subscription.channelGroups = channelGroupsFromRequest(event.request); + } + subscription.request = event.request; + subscription.filterExpression = ((_j = query['filter-expr']) !== null && _j !== void 0 ? _j : ''); + subscription.timetoken = ((_k = query.tt) !== null && _k !== void 0 ? _k : '0'); + client.authKey = ((_l = query.auth) !== null && _l !== void 0 ? _l : ''); + client.userId = query.uuid; + }; + /** + * Handle PubNub client response on PING request. + * + * @param event - Information about client which responded on PING request. + */ + const handleClientPong = (event) => { + const client = pubNubClients[event.clientIdentifier]; + if (!client) + return; + client.lastPongEvent = new Date().getTime() / 1000; }; /** * Clean up resources used by registered PubNub client instance. @@ -779,9 +865,8 @@ * @param subscriptionKey - Subscription key which has been used by the * invalidated instance. * @param clientId - Unique PubNub client identifier. - * @param userId - Unique identifier of the user used by PubNub client instance. */ - const invalidateClient = (subscriptionKey, clientId, userId) => { + const invalidateClient = (subscriptionKey, clientId) => { delete pubNubClients[clientId]; let clients = pubNubClientsBySubscriptionKey[subscriptionKey]; if (clients) { @@ -796,25 +881,23 @@ delete presenceState[subscriptionKey]; // Clean up service workers client linkage to PubNub clients. if (clients.length > 0) { - const workerClients = serviceWorkerClients[subscriptionKey]; + const workerClients = sharedWorkerClients[subscriptionKey]; if (workerClients) { delete workerClients[clientId]; if (Object.keys(workerClients).length === 0) - delete serviceWorkerClients[subscriptionKey]; + delete sharedWorkerClients[subscriptionKey]; } } else - delete serviceWorkerClients[subscriptionKey]; + delete sharedWorkerClients[subscriptionKey]; } + consoleLog(`Invalidate '${clientId}' client. '${Object.keys(pubNubClients).length}' clients currently active.`); }; /** * Validate received event payload. */ const validateEventPayload = (event) => { - if (!event.source || !(event.source instanceof Client)) - return false; - const data = event.data; - const { clientIdentifier, subscriptionKey, logVerbosity } = data; + const { clientIdentifier, subscriptionKey, logVerbosity } = event.data; if (logVerbosity === undefined || typeof logVerbosity !== 'boolean') return false; if (!clientIdentifier || typeof clientIdentifier !== 'string') @@ -822,7 +905,7 @@ return !(!subscriptionKey || typeof subscriptionKey !== 'string'); }; /** - * Search for active subscription for one of the passed {@link serviceWorkerClients}. + * Search for active subscription for one of the passed {@link sharedWorkerClients}. * * @param activeClients - List of suitable registered PubNub clients. * @param event - Send Subscriber Request event data. @@ -840,9 +923,13 @@ for (const client of activeClients) { const { subscription } = client; // Skip PubNub clients which doesn't await for subscription response. - if (!subscription.serviceRequestId) + if (!subscription || !subscription.serviceRequestId) continue; + const sourceClient = pubNubClients[event.clientIdentifier]; + const requestId = subscription.serviceRequestId; if (subscription.path === requestPath && subscription.channelGroupQuery === channelGroupQuery) { + consoleLog(`Found identical request started by '${client.clientIdentifier}' client. +Waiting for existing '${requestId}' request completion.`, sourceClient); return subscription.serviceRequestId; } else { @@ -856,6 +943,8 @@ continue; if (channelGroups.length && !includesStrings(scheduledRequest.channelGroups, channelGroups)) continue; + consoleDir(scheduledRequest, `'${event.request.identifier}' request channels and groups are subset of ongoing '${requestId}' request +which has started by '${client.clientIdentifier}' client. Waiting for existing '${requestId}' request completion.`, sourceClient); return subscription.serviceRequestId; } } @@ -885,6 +974,7 @@ const userId = query.uuid; return ((_c = pubNubClientsBySubscriptionKey[event.subscriptionKey]) !== null && _c !== void 0 ? _c : []).filter((client) => client.userId === userId && client.authKey === authKey && + client.subscription && client.subscription.filterExpression === filterExpression && (timetoken === '0' || client.subscription.previousTimetoken === '0' || @@ -944,6 +1034,74 @@ const set = new Set(main); return sub.every(set.has, set); }; + /** + * Send PubNub client PING request to identify disconnected instances. + */ + const pingClients = () => { + consoleLog(`Pinging clients...`); + const payload = { type: 'shared-worker-ping' }; + Object.values(pubNubClients).forEach((client) => { + let clientInvalidated = false; + if (client && client.lastPingRequest) { + consoleLog(`Checking whether ${client.clientIdentifier} ping has been sent too long ago...`); + // Check whether client never respond or last response was too long time ago. + if (!client.lastPongEvent || + Math.abs(client.lastPongEvent - client.lastPingRequest) > (clientPingRequestInterval / 1000) * 0.5) { + clientInvalidated = true; + consoleLog(`'${client.clientIdentifier}' client is inactive. Invalidating.`); + invalidateClient(client.subscriptionKey, client.clientIdentifier); + } + } + if (client && !clientInvalidated) { + consoleLog(`Sending ping to ${client.clientIdentifier}...`); + client.lastPingRequest = new Date().getTime() / 1000; + publishClientEvent(client, payload); + } + }); + // Cancel interval if there is no active clients. + if (Object.keys(pubNubClients).length === 0 && pingInterval) + clearInterval(pingInterval); + }; + /** + * Print message on the worker's clients console. + * + * @param message - Message which should be printed. + * @param [client] - Target client to which log message should be sent. + */ + const consoleLog = (message, client) => { + if (!logVerbosity) + return; + const clients = client ? [client] : Object.values(pubNubClients); + const payload = { + type: 'shared-worker-console-log', + message, + }; + clients.forEach((client) => { + if (client) + publishClientEvent(client, payload); + }); + }; + /** + * Print message on the worker's clients console. + * + * @param data - Data which should be printed into the console. + * @param [message] - Message which should be printed before {@link data}. + * @param [client] - Target client to which log message should be sent. + */ + const consoleDir = (data, message, client) => { + if (!logVerbosity) + return; + const clients = client ? [client] : Object.values(pubNubClients); + const payload = { + type: 'shared-worker-console-dir', + message, + data, + }; + clients.forEach((client) => { + if (client) + publishClientEvent(client, payload); + }); + }; /** * Stringify request query key / value pairs. * diff --git a/dist/web/pubnub.worker.min.js b/dist/web/pubnub.worker.min.js index 864385802..17cca5554 100644 --- a/dist/web/pubnub.worker.min.js +++ b/dist/web/pubnub.worker.min.js @@ -1,2 +1,2 @@ -!function(e){"function"==typeof define&&define.amd?define(e):e()}((function(){"use strict";function e(e,t,n,i){return new(n||(n=Promise))((function(s,r){function o(e){try{c(i.next(e))}catch(e){r(e)}}function u(e){try{c(i.throw(e))}catch(e){r(e)}}function c(e){var t;e.done?s(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(o,u)}c((i=i.apply(e,t||[])).next())}))}"function"==typeof SuppressedError&&SuppressedError;"undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self&&self;function t(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var n,i,s={exports:{}}; -/*! lil-uuid - v0.1 - MIT License - https://github.com/lil-js/uuid */n=s,function(e){var t="0.1.0",n={3:/^[0-9A-F]{8}-[0-9A-F]{4}-3[0-9A-F]{3}-[0-9A-F]{4}-[0-9A-F]{12}$/i,4:/^[0-9A-F]{8}-[0-9A-F]{4}-4[0-9A-F]{3}-[89AB][0-9A-F]{3}-[0-9A-F]{12}$/i,5:/^[0-9A-F]{8}-[0-9A-F]{4}-5[0-9A-F]{3}-[89AB][0-9A-F]{3}-[0-9A-F]{12}$/i,all:/^[0-9A-F]{8}-[0-9A-F]{4}-[0-9A-F]{4}-[0-9A-F]{4}-[0-9A-F]{12}$/i};function i(){var e,t,n="";for(e=0;e<32;e++)t=16*Math.random()|0,8!==e&&12!==e&&16!==e&&20!==e||(n+="-"),n+=(12===e?4:16===e?3&t|8:t).toString(16);return n}function s(e,t){var i=n[t||"all"];return i&&i.test(e)||!1}i.isUUID=s,i.VERSION=t,e.uuid=i,e.isUUID=s}(i=s.exports),null!==n&&(n.exports=i.uuid);var r=t(s.exports),o={createUUID:()=>r.uuid?r.uuid():r()};const u=new TextDecoder,c=new Map,l={},a={},d={},p={},f={};self.addEventListener("activate",(e=>{e.waitUntil(self.clients.claim())})),self.addEventListener("message",(e=>{if(!K(e))return;const t=e.data;"send-request"===t.type?t.request.path.startsWith("/v2/subscribe")?(k(e),h(t)):(l[t.clientIdentifier]||k(e),b(e)):"cancel-request"===t.type&&v(t)}));const h=e=>{const t=j(e),n=l[e.clientIdentifier];n&&w("start",[n],(new Date).toISOString()),"string"!=typeof t?(e.request.cancellable&&c.set(t.identifier,new AbortController),g(t,(()=>q(t.identifier)),((e,n)=>{E(e,n),I(e,t.identifier)}),((e,n)=>{E(e,null,t,T(n)),I(e,t.identifier)}))):n&&(n.subscription.previousTimetoken=n.subscription.timetoken,n.subscription.timetoken=f[t].timetoken,n.subscription.serviceRequestId=t)},b=e=>{const t=e.data,n=O(t),i=l[t.clientIdentifier];if(i){if(!n){const n=(new TextEncoder).encode('{"status": 200, "action": "leave", "message": "OK", "service":"Presence"}'),s=new Headers({"Content-Type":'text/javascript; charset="UTF-8"',"Content-Length":"74"}),r=new Response(n,{status:200,headers:s}),o=S([r,n]);return o.url=`${t.request.origin}${t.request.path}`,o.clientIdentifier=t.clientIdentifier,o.identifier=t.request.identifier,void A(e.source.id,o).then((e=>{e&&x(i.subscriptionKey,i.clientIdentifier,i.userId)}))}g(n,(()=>[i]),((e,n)=>{E(e,n,t.request)}),((e,n)=>{E(e,null,t.request,T(n))}))}},v=e=>{const t=l[e.clientIdentifier],n=t?t.subscription.serviceRequestId:void 0;if(t&&n&&(delete t.subscription.serviceRequestId,delete t.subscription.request,0===q(n).length)){const e=c.get(n);c.delete(n),delete f[n],e&&e.abort()}},g=(t,n,i,s)=>{e(void 0,void 0,void 0,(function*(){var e;const r=(new Date).getTime();Promise.race([fetch(m(t),{signal:null===(e=c.get(t.identifier))||void 0===e?void 0:e.signal,keepalive:!0}),y(t.identifier,t.timeout)]).then((e=>e.arrayBuffer().then((t=>[e,t])))).then((e=>{const s=e[1].byteLength>0?e[1]:void 0,o=n();0!==o.length&&(w("end",o,(new Date).toISOString(),t,s,e[0].headers.get("Content-Type"),(new Date).getTime()-r),i(o,e))})).catch((e=>{const t=n();0!==t.length&&s(t,e)}))}))},y=(e,t)=>new Promise(((n,i)=>{const s=setTimeout((()=>{c.delete(e),clearTimeout(s),i(new Error("Request timeout"))}),1e3*t)})),q=e=>Object.values(l).filter((t=>void 0!==t&&t.subscription.serviceRequestId===e)),I=(e,t)=>{delete f[t],e.forEach((e=>{delete e.subscription.request,delete e.subscription.serviceRequestId}))},m=e=>{let t;const n=e.queryParameters;let i=e.path;if(e.headers){t={};for(const[n,i]of Object.entries(e.headers))t[n]=i}return n&&0!==Object.keys(n).length&&(i=`${i}?${W(n)}`),new Request(`${e.origin}${i}`,{method:e.method,headers:t,redirect:"follow"})},j=e=>{var t,n,i,s;const r=l[e.clientIdentifier],u=R(r.subscription.previousTimetoken,e),c=o.createUUID(),a=Object.assign({},e.request);if(u.length>1){const s=F(u,e);if(s)return s;const o=(null!==(t=d[r.subscriptionKey])&&void 0!==t?t:{})[r.userId],l={},p=new Set(r.subscription.channelGroups),h=new Set(r.subscription.channels);o&&r.subscription.objectsWithState.length&&r.subscription.objectsWithState.forEach((e=>{const t=o[e];t&&(l[e]=t)}));for(const e of u){const{subscription:t}=e;t.serviceRequestId||(t.channelGroups.forEach(p.add,p),t.channels.forEach(h.add,h),t.serviceRequestId=c,o&&t.objectsWithState.forEach((e=>{const t=o[e];t&&!l[e]&&(l[e]=t)})))}const b=null!==(n=f[c])&&void 0!==n?n:f[c]={requestId:c,timetoken:null!==(i=a.queryParameters.tt)&&void 0!==i?i:"0",channelGroups:[],channels:[]};if(h.size){b.channels=Array.from(h).sort();const e=a.path.split("/");e[4]=b.channels.join(","),a.path=e.join("/")}p.size&&(b.channelGroups=Array.from(p).sort(),a.queryParameters["channel-group"]=b.channelGroups.join(",")),Object.keys(l).length&&(a.queryParameters.state=JSON.stringify(l))}else f[c]={requestId:c,timetoken:null!==(s=a.queryParameters.tt)&&void 0!==s?s:"0",channelGroups:r.subscription.channelGroups,channels:r.subscription.channels};return r.subscription.serviceRequestId=c,a.identifier=c,a},O=e=>{const t=l[e.clientIdentifier],n=$(e);let i=P(e.request),s=G(e.request);const r=Object.assign({},e.request);if(t){const{subscription:e}=t;s.length&&(e.channels=e.channels.filter((e=>!s.includes(e)))),i.length&&(e.channelGroups=e.channelGroups.filter((e=>!i.includes(e))))}for(const t of n)t.clientIdentifier!==e.clientIdentifier&&(s.length&&(s=s.filter((e=>!t.subscription.channels.includes(e)))),i.length&&(i=i.filter((e=>!t.subscription.channelGroups.includes(e)))));if(0!==s.length||0!==i.length){if(s.length){const e=r.path.split("/");e[4]=s.join(","),r.path=e.join("/")}return i.length&&(r.queryParameters["channel-group"]=i.join(",")),r}},A=(e,t)=>self.clients.get(e).then((e=>!!e&&(e.postMessage(t),!0))),w=(e,t,n,i,s,r,o)=>{var c;if(0===t.length)return;const l=null!==(c=p[t[0].subscriptionKey])&&void 0!==c?c:{};let a;if("start"===e)a={type:"request-progress-start",clientIdentifier:"",url:"",timestamp:n};else{let e;s&&r&&(-1!==r.indexOf("text/javascript")||-1!==r.indexOf("application/json")||-1!==r.indexOf("text/plain")||-1!==r.indexOf("text/html"))&&(e=u.decode(s)),a={type:"request-progress-end",clientIdentifier:"",url:"",response:e,timestamp:n,duration:o}}t.forEach((e=>{const t=l[e.clientIdentifier],{request:n}=e.subscription,s=null!=n?n:i;e.logVerbosity&&t&&s&&A(t,Object.assign(Object.assign({},a),{clientIdentifier:e.clientIdentifier,url:`${s.origin}${s.path}`,query:s.queryParameters})).then((t=>{t&&x(e.subscriptionKey,e.clientIdentifier,e.userId)}))}))},E=(e,t,n,i)=>{var s;if(0===e.length)return;if(!i&&!t)return;const r=null!==(s=p[e[0].subscriptionKey])&&void 0!==s?s:{};!i&&t&&(i=t[0].status>=400?T(void 0,t):S(t)),e.forEach((e=>{const t=r[e.clientIdentifier],{request:s}=e.subscription,o=null!=s?s:n;t&&o&&A(t,Object.assign(Object.assign({},i),{clientIdentifier:e.clientIdentifier,identifier:o.identifier,url:`${o.origin}${o.path}`})).then((t=>{t&&x(e.subscriptionKey,e.clientIdentifier,e.userId)}))}))},S=e=>{var t;const[n,i]=e,s=i.byteLength>0?i:void 0,r=parseInt(null!==(t=n.headers.get("Content-Length"))&&void 0!==t?t:"0",10),o=n.headers.get("Content-Type"),u={};return n.headers.forEach(((e,t)=>u[t]=e.toLowerCase())),{type:"request-process-success",clientIdentifier:"",identifier:"",url:"",response:{contentLength:r,contentType:o,headers:u,status:n.status,body:s}}},T=(e,t)=>{if(t)return Object.assign(Object.assign({},S(t)),{type:"request-process-error"});let n="NETWORK_ISSUE",i="Unknown error",s="Error";return e&&e instanceof Error&&(i=e.message,s=e.name),"AbortError"===s?(i="Request aborted",n="ABORTED"):"Request timeout"===i&&(n="TIMEOUT"),{type:"request-process-error",clientIdentifier:"",identifier:"",url:"",error:{name:s,type:n,message:i}}},k=e=>{var t,n,i,s,r,o,u,c,f,h,b,v,g,y,q,I,m,j,O,A,w,E,S,T,k,x,K,F,R,$;const U=e.data,{clientIdentifier:W}=U,C=U.request.queryParameters;let D=l[W];if(D){const e=null!==(b=C["channel-group"])&&void 0!==b?b:"",t=null!==(v=C.state)&&void 0!==v?v:"";if(D.subscription.filterExpression=null!==(g=C["filter-expr"])&&void 0!==g?g:"",D.subscription.previousTimetoken=D.subscription.timetoken,D.subscription.timetoken=null!==(y=C.tt)&&void 0!==y?y:"0",D.subscription.request=U.request,D.authKey=null!==(q=C.auth)&&void 0!==q?q:"",D.userId=C.uuid,D.subscription.path!==U.request.path&&(D.subscription.path=U.request.path,D.subscription.channels=G(U.request)),D.subscription.channelGroupQuery!==e&&(D.subscription.channelGroupQuery=e,D.subscription.channelGroups=P(U.request)),t.length>0){const e=JSON.parse(t),n=null!==(m=(x=null!==(I=d[k=D.subscriptionKey])&&void 0!==I?I:d[k]={})[K=D.userId])&&void 0!==m?m:x[K]={};Object.entries(e).forEach((([e,t])=>n[e]=t));for(const t of D.subscription.objectsWithState)e[t]||delete n[t];D.subscription.objectsWithState=Object.keys(e)}else if(D.subscription.objectsWithState.length){const e=null!==(O=(R=null!==(j=d[F=D.subscriptionKey])&&void 0!==j?j:d[F]={})[$=D.userId])&&void 0!==O?O:R[$]={};for(const t of D.subscription.objectsWithState)delete e[t];D.subscription.objectsWithState=[]}}else{const b=!U.request.path.startsWith("/v2/subscribe"),v=b?"":null!==(t=C["channel-group"])&&void 0!==t?t:"",g=b?"":null!==(n=C.state)&&void 0!==n?n:"";if(D=l[W]={clientIdentifier:W,subscriptionKey:U.subscriptionKey,userId:C.uuid,authKey:null!==(i=C.auth)&&void 0!==i?i:"",logVerbosity:U.logVerbosity,subscription:{path:b?"":U.request.path,channelGroupQuery:b?"":v,channels:b?[]:G(U.request),channelGroups:b?[]:P(U.request),previousTimetoken:b?"0":null!==(s=C.tt)&&void 0!==s?s:"0",timetoken:b?"0":null!==(r=C.tt)&&void 0!==r?r:"0",request:b?void 0:U.request,objectsWithState:[],filterExpression:b?void 0:null!==(o=C["filter-expr"])&&void 0!==o?o:""}},!b&&g.length>0){const e=JSON.parse(g),t=null!==(c=(w=null!==(u=d[A=D.subscriptionKey])&&void 0!==u?u:d[A]={})[E=D.userId])&&void 0!==c?c:w[E]={};Object.entries(e).forEach((([e,n])=>t[e]=n)),D.subscription.objectsWithState=Object.keys(e)}const y=null!==(f=a[S=U.subscriptionKey])&&void 0!==f?f:a[S]=[];y.every((e=>e.clientIdentifier!==W))&&y.push(D),(null!==(h=p[T=U.subscriptionKey])&&void 0!==h?h:p[T]={})[W]=e.source.id}},x=(e,t,n)=>{delete l[t];let i=a[e];if(i)if(i=i.filter((e=>e.clientIdentifier!==t)),i.length>0?a[e]=i:delete a[e],0===i.length&&delete d[e],i.length>0){const n=p[e];n&&(delete n[t],0===Object.keys(n).length&&delete p[e])}else delete p[e]},K=e=>{if(!(e.source&&e.source instanceof Client))return!1;const t=e.data,{clientIdentifier:n,subscriptionKey:i,logVerbosity:s}=t;return void 0!==s&&"boolean"==typeof s&&(!(!n||"string"!=typeof n)&&!(!i||"string"!=typeof i))},F=(e,t)=>{var n;const i=null!==(n=t.request.queryParameters["channel-group"])&&void 0!==n?n:"",s=t.request.path;let r,o;for(const n of e){const{subscription:e}=n;if(e.serviceRequestId){if(e.path===s&&e.channelGroupQuery===i)return e.serviceRequestId;{const n=f[e.serviceRequestId];if(r||(r=P(t.request)),o||(o=G(t.request)),o.length&&!U(n.channels,o))continue;if(r.length&&!U(n.channelGroups,r))continue;return e.serviceRequestId}}}},R=(e,t)=>{var n,i,s;const r=t.request.queryParameters,o=null!==(n=r["filter-expr"])&&void 0!==n?n:"",u=null!==(i=r.auth)&&void 0!==i?i:"",c=r.uuid;return(null!==(s=a[t.subscriptionKey])&&void 0!==s?s:[]).filter((t=>t.userId===c&&t.authKey===u&&t.subscription.filterExpression===o&&("0"===e||"0"===t.subscription.previousTimetoken||t.subscription.previousTimetoken===e)))},$=e=>{var t,n;const i=e.request.queryParameters,s=null!==(t=i.auth)&&void 0!==t?t:"",r=i.uuid;return(null!==(n=a[e.subscriptionKey])&&void 0!==n?n:[]).filter((e=>e.userId===r&&e.authKey===s))},G=e=>{const t=e.path.split("/")[e.path.startsWith("/v2/subscribe/")?4:6];return","===t?[]:t.split(",").filter((e=>e.length>0))},P=e=>{var t;const n=null!==(t=e.queryParameters["channel-group"])&&void 0!==t?t:"";return 0===n.length?[]:n.split(",").filter((e=>e.length>0))},U=(e,t)=>{const n=new Set(e);return t.every(n.has,n)},W=e=>Object.keys(e).map((t=>{const n=e[t];return Array.isArray(n)?n.map((e=>`${t}=${C(e)}`)).join("&"):`${t}=${C(n)}`})).join("&"),C=e=>encodeURIComponent(e).replace(/[!~*'()]/g,(e=>`%${e.charCodeAt(0).toString(16).toUpperCase()}`))})); +!function(e){"function"==typeof define&&define.amd?define(e):e()}((function(){"use strict";function e(e,t,n,i){return new(n||(n=Promise))((function(r,s){function o(e){try{u(i.next(e))}catch(e){s(e)}}function c(e){try{u(i.throw(e))}catch(e){s(e)}}function u(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(o,c)}u((i=i.apply(e,t||[])).next())}))}"function"==typeof SuppressedError&&SuppressedError;"undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self&&self;function t(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var n,i,r={exports:{}}; +/*! lil-uuid - v0.1 - MIT License - https://github.com/lil-js/uuid */n=r,function(e){var t="0.1.0",n={3:/^[0-9A-F]{8}-[0-9A-F]{4}-3[0-9A-F]{3}-[0-9A-F]{4}-[0-9A-F]{12}$/i,4:/^[0-9A-F]{8}-[0-9A-F]{4}-4[0-9A-F]{3}-[89AB][0-9A-F]{3}-[0-9A-F]{12}$/i,5:/^[0-9A-F]{8}-[0-9A-F]{4}-5[0-9A-F]{3}-[89AB][0-9A-F]{3}-[0-9A-F]{12}$/i,all:/^[0-9A-F]{8}-[0-9A-F]{4}-[0-9A-F]{4}-[0-9A-F]{4}-[0-9A-F]{12}$/i};function i(){var e,t,n="";for(e=0;e<32;e++)t=16*Math.random()|0,8!==e&&12!==e&&16!==e&&20!==e||(n+="-"),n+=(12===e?4:16===e?3&t|8:t).toString(16);return n}function r(e,t){var i=n[t||"all"];return i&&i.test(e)||!1}i.isUUID=r,i.VERSION=t,e.uuid=i,e.isUUID=r}(i=r.exports),null!==n&&(n.exports=i.uuid);var s=t(r.exports),o={createUUID:()=>s.uuid?s.uuid():s()};const c=5e3,u=new TextDecoder;let l,a=!1;const d=o.createUUID(),f=new Map,p={},h={},g={},b={},v={};self.onconnect=e=>{V("New PubNub Client connected to the Subscription Shared Worker."),e.ports.forEach((e=>{e.start(),e.onmessage=t=>{if(!G(t))return;const n=t.data;"client-register"===n.type?(!a&&n.workerLogVerbosity&&(a=!0),n.port=e,x(n),V(`Client '${n.clientIdentifier}' registered with '${d}' shared worker`)):"client-pong"===n.type?K(n):"send-request"===n.type?n.request.path.startsWith("/v2/subscribe")?(F(n),y(n)):q(n):"cancel-request"===n.type&&I(n)},e.postMessage({type:"shared-worker-connected"})}))};const y=e=>{const t=k(e),n=p[e.clientIdentifier];n&&E("start",[n],(new Date).toISOString()),"string"!=typeof t?(e.request.cancellable&&f.set(t.identifier,new AbortController),m(t,(()=>O(t.identifier)),((e,n)=>{P(e,n),w(e,t.identifier)}),((e,n)=>{P(e,null,t,T(n)),w(e,t.identifier)})),V(`'${Object.keys(v).length}' subscription request currently active.`)):n&&n.subscription&&(n.subscription.previousTimetoken=n.subscription.timetoken,n.subscription.timetoken=v[t].timetoken,n.subscription.serviceRequestId=t)},q=e=>{const t=S(e),n=p[e.clientIdentifier];if(n){if(!t){const t=(new TextEncoder).encode('{"status": 200, "action": "leave", "message": "OK", "service":"Presence"}'),i=new Headers({"Content-Type":'text/javascript; charset="UTF-8"',"Content-Length":"74"}),r=new Response(t,{status:200,headers:i}),s=R([r,t]);return s.url=`${e.request.origin}${e.request.path}`,s.clientIdentifier=e.clientIdentifier,s.identifier=e.request.identifier,void A(n,s)}m(t,(()=>[n]),((t,n)=>{P(t,n,e.request)}),((t,n)=>{P(t,null,e.request,T(n))})),V("Started leave request.",n)}},I=e=>{const t=p[e.clientIdentifier];if(!t||!t.subscription)return;const n=t.subscription.serviceRequestId;if(t&&n&&(delete t.subscription.serviceRequestId,delete t.subscription.request,0===O(n).length)){const e=f.get(n);f.delete(n),delete v[n],e&&e.abort()}},m=(t,n,i,r)=>{e(void 0,void 0,void 0,(function*(){var e;const s=(new Date).getTime();Promise.race([fetch($(t),{signal:null===(e=f.get(t.identifier))||void 0===e?void 0:e.signal,keepalive:!0}),j(t.identifier,t.timeout)]).then((e=>e.arrayBuffer().then((t=>[e,t])))).then((e=>{const r=e[1].byteLength>0?e[1]:void 0,o=n();0!==o.length&&(E("end",o,(new Date).toISOString(),t,r,e[0].headers.get("Content-Type"),(new Date).getTime()-s),i(o,e))})).catch((e=>{const t=n();0!==t.length&&r(t,e)}))}))},j=(e,t)=>new Promise(((n,i)=>{const r=setTimeout((()=>{f.delete(e),clearTimeout(r),i(new Error("Request timeout"))}),1e3*t)})),O=e=>Object.values(p).filter((t=>void 0!==t&&void 0!==t.subscription&&t.subscription.serviceRequestId===e)),w=(e,t)=>{delete v[t],e.forEach((e=>{e.subscription&&(delete e.subscription.request,delete e.subscription.serviceRequestId)}))},$=e=>{let t;const n=e.queryParameters;let i=e.path;if(e.headers){t={};for(const[n,i]of Object.entries(e.headers))t[n]=i}return n&&0!==Object.keys(n).length&&(i=`${i}?${Q(n)}`),new Request(`${e.origin}${i}`,{method:e.method,headers:t,redirect:"follow"})},k=e=>{var t,n,i,r;const s=p[e.clientIdentifier],c=s.subscription,u=W(c.previousTimetoken,e),l=o.createUUID(),d=Object.assign({},e.request);if(u.length>1){const r=U(u,e);if(r)return r;const o=(null!==(t=g[s.subscriptionKey])&&void 0!==t?t:{})[s.userId],a={},f=new Set(c.channelGroups),p=new Set(c.channels);o&&c.objectsWithState.length&&c.objectsWithState.forEach((e=>{const t=o[e];t&&(a[e]=t)}));for(const e of u){const{subscription:t}=e;t&&t.serviceRequestId&&(t.channelGroups.forEach(f.add,f),t.channels.forEach(p.add,p),t.serviceRequestId=l,o&&t.objectsWithState.forEach((e=>{const t=o[e];t&&!a[e]&&(a[e]=t)})))}const h=null!==(n=v[l])&&void 0!==n?n:v[l]={requestId:l,timetoken:null!==(i=d.queryParameters.tt)&&void 0!==i?i:"0",channelGroups:[],channels:[]};if(p.size){h.channels=Array.from(p).sort();const e=d.path.split("/");e[4]=h.channels.join(","),d.path=e.join("/")}f.size&&(h.channelGroups=Array.from(f).sort(),d.queryParameters["channel-group"]=h.channelGroups.join(",")),Object.keys(a).length&&(d.queryParameters.state=JSON.stringify(a))}else v[l]={requestId:l,timetoken:null!==(r=d.queryParameters.tt)&&void 0!==r?r:"0",channelGroups:c.channelGroups,channels:c.channels};if(c.serviceRequestId=l,d.identifier=l,a){const e=u.reduce(((e,{clientIdentifier:t})=>(e.push(t),e)),[]).join(",");B(v[l],`Started aggregated request for clients: ${e}`)}return d},S=e=>{const t=p[e.clientIdentifier],n=C(e);let i=N(e.request),r=D(e.request);const s=Object.assign({},e.request);if(t&&t.subscription){const{subscription:e}=t;r.length&&(e.channels=e.channels.filter((e=>!r.includes(e)))),i.length&&(e.channelGroups=e.channelGroups.filter((e=>!i.includes(e))))}for(const t of n){const n=t.subscription;void 0!==n&&(t.clientIdentifier!==e.clientIdentifier&&(r.length&&(r=r.filter((e=>!n.channels.includes(e)))),i.length&&(i=i.filter((e=>!n.channelGroups.includes(e))))))}if(0!==r.length||0!==i.length){if(r.length){const e=s.path.split("/");e[4]=r.join(","),s.path=e.join("/")}return i.length&&(s.queryParameters["channel-group"]=i.join(",")),s}if(a&&t){const e=n.reduce(((e,{clientIdentifier:t})=>(e.push(t),e)),[]).join(",");V(`Specified channels and groups still in use by other clients: ${e}. Ignoring leave request.`,t)}},A=(e,t)=>{var n;const i=(null!==(n=b[e.subscriptionKey])&&void 0!==n?n:{})[e.clientIdentifier];if(!i)return!1;try{return i.postMessage(t),!0}catch(e){}return!1},E=(e,t,n,i,r,s,o)=>{var c;if(0===t.length)return;const l=null!==(c=b[t[0].subscriptionKey])&&void 0!==c?c:{};let a;if("start"===e)a={type:"request-progress-start",clientIdentifier:"",url:"",timestamp:n};else{let e;r&&s&&(-1!==s.indexOf("text/javascript")||-1!==s.indexOf("application/json")||-1!==s.indexOf("text/plain")||-1!==s.indexOf("text/html"))&&(e=u.decode(r)),a={type:"request-progress-end",clientIdentifier:"",url:"",response:e,timestamp:n,duration:o}}for(const e of t){if(void 0===e.subscription)continue;const t=l[e.clientIdentifier],{request:n}=e.subscription,r=null!=n?n:i;if(e.logVerbosity&&t&&r){const t=Object.assign(Object.assign({},a),{clientIdentifier:e.clientIdentifier,url:`${r.origin}${r.path}`,query:r.queryParameters});A(e,t)}}},P=(e,t,n,i)=>{var r;if(0===e.length)return;if(!i&&!t)return;const s=null!==(r=b[e[0].subscriptionKey])&&void 0!==r?r:{};!i&&t&&(i=t[0].status>=400?T(void 0,t):R(t));for(const t of e){if(void 0===t.subscription)continue;const e=s[t.clientIdentifier],{request:r}=t.subscription,o=null!=r?r:n;if(e&&o){const e=Object.assign(Object.assign({},i),{clientIdentifier:t.clientIdentifier,identifier:o.identifier,url:`${o.origin}${o.path}`});A(t,e)}}},R=e=>{var t;const[n,i]=e,r=i.byteLength>0?i:void 0,s=parseInt(null!==(t=n.headers.get("Content-Length"))&&void 0!==t?t:"0",10),o=n.headers.get("Content-Type"),c={};return n.headers.forEach(((e,t)=>c[t]=e.toLowerCase())),{type:"request-process-success",clientIdentifier:"",identifier:"",url:"",response:{contentLength:s,contentType:o,headers:c,status:n.status,body:r}}},T=(e,t)=>{if(t)return Object.assign(Object.assign({},R(t)),{type:"request-process-error"});let n="NETWORK_ISSUE",i="Unknown error",r="Error";return e&&e instanceof Error&&(i=e.message,r=e.name),"AbortError"===r?(i="Request aborted",n="ABORTED"):"Request timeout"===i&&(n="TIMEOUT"),{type:"request-process-error",clientIdentifier:"",identifier:"",url:"",error:{name:r,type:n,message:i}}},x=e=>{var t,n,i,r;const{clientIdentifier:s}=e;if(p[s])return;const o=p[s]={clientIdentifier:s,subscriptionKey:e.subscriptionKey,userId:e.userId,logVerbosity:e.logVerbosity},u=null!==(t=h[i=e.subscriptionKey])&&void 0!==t?t:h[i]=[];u.every((e=>e.clientIdentifier!==s))&&u.push(o),(null!==(n=b[r=e.subscriptionKey])&&void 0!==n?n:b[r]={})[s]=e.port,V(`Registered PubNub client with '${s}' identifier. '${Object.keys(p).length}' clients currently active.`),!l&&Object.keys(p).length>0&&(V("Setup PubNub client ping event 5 seconds"),l=setInterval((()=>M()),c))},F=e=>{var t,n,i,r,s,o,c,u,l,a,d,f,h,b,v,y,q,I,m,j;const O=e.request.queryParameters,{clientIdentifier:w}=e,$=p[w];if(!$)return;const k=null!==(t=O["channel-group"])&&void 0!==t?t:"",S=null!==(n=O.state)&&void 0!==n?n:"";let A=$.subscription;if(A){if(A.previousTimetoken=A.timetoken,S.length>0){const e=JSON.parse(S),t=null!==(o=(y=null!==(s=g[v=$.subscriptionKey])&&void 0!==s?s:g[v]={})[q=$.userId])&&void 0!==o?o:y[q]={};Object.entries(e).forEach((([e,n])=>t[e]=n));for(const n of A.objectsWithState)e[n]||delete t[n];A.objectsWithState=Object.keys(e)}else if(A.objectsWithState.length){const e=null!==(u=(m=null!==(c=g[I=$.subscriptionKey])&&void 0!==c?c:g[I]={})[j=$.userId])&&void 0!==u?u:m[j]={};for(const t of A.objectsWithState)delete e[t];A.objectsWithState=[]}}else{if(A={path:"",channelGroupQuery:"",channels:[],channelGroups:[],previousTimetoken:"0",timetoken:"0",objectsWithState:[]},S.length>0){const e=JSON.parse(S),t=null!==(r=(h=null!==(i=g[f=$.subscriptionKey])&&void 0!==i?i:g[f]={})[b=$.userId])&&void 0!==r?r:h[b]={};Object.entries(e).forEach((([e,n])=>t[e]=n)),A.objectsWithState=Object.keys(e)}$.subscription=A}A.path!==e.request.path&&(A.path=e.request.path,A.channels=D(e.request)),A.channelGroupQuery!==k&&(A.channelGroupQuery=k,A.channelGroups=N(e.request)),A.request=e.request,A.filterExpression=null!==(l=O["filter-expr"])&&void 0!==l?l:"",A.timetoken=null!==(a=O.tt)&&void 0!==a?a:"0",$.authKey=null!==(d=O.auth)&&void 0!==d?d:"",$.userId=O.uuid},K=e=>{const t=p[e.clientIdentifier];t&&(t.lastPongEvent=(new Date).getTime()/1e3)},G=e=>{const{clientIdentifier:t,subscriptionKey:n,logVerbosity:i}=e.data;return void 0!==i&&"boolean"==typeof i&&(!(!t||"string"!=typeof t)&&!(!n||"string"!=typeof n))},U=(e,t)=>{var n;const i=null!==(n=t.request.queryParameters["channel-group"])&&void 0!==n?n:"",r=t.request.path;let s,o;for(const n of e){const{subscription:e}=n;if(!e||!e.serviceRequestId)continue;const c=p[t.clientIdentifier],u=e.serviceRequestId;if(e.path===r&&e.channelGroupQuery===i)return V(`Found identical request started by '${n.clientIdentifier}' client. \nWaiting for existing '${u}' request completion.`,c),e.serviceRequestId;{const i=v[e.serviceRequestId];if(s||(s=N(t.request)),o||(o=D(t.request)),o.length&&!L(i.channels,o))continue;if(s.length&&!L(i.channelGroups,s))continue;return B(i,`'${t.request.identifier}' request channels and groups are subset of ongoing '${u}' request \nwhich has started by '${n.clientIdentifier}' client. Waiting for existing '${u}' request completion.`,c),e.serviceRequestId}}},W=(e,t)=>{var n,i,r;const s=t.request.queryParameters,o=null!==(n=s["filter-expr"])&&void 0!==n?n:"",c=null!==(i=s.auth)&&void 0!==i?i:"",u=s.uuid;return(null!==(r=h[t.subscriptionKey])&&void 0!==r?r:[]).filter((t=>t.userId===u&&t.authKey===c&&t.subscription&&t.subscription.filterExpression===o&&("0"===e||"0"===t.subscription.previousTimetoken||t.subscription.previousTimetoken===e)))},C=e=>{var t,n;const i=e.request.queryParameters,r=null!==(t=i.auth)&&void 0!==t?t:"",s=i.uuid;return(null!==(n=h[e.subscriptionKey])&&void 0!==n?n:[]).filter((e=>e.userId===s&&e.authKey===r))},D=e=>{const t=e.path.split("/")[e.path.startsWith("/v2/subscribe/")?4:6];return","===t?[]:t.split(",").filter((e=>e.length>0))},N=e=>{var t;const n=null!==(t=e.queryParameters["channel-group"])&&void 0!==t?t:"";return 0===n.length?[]:n.split(",").filter((e=>e.length>0))},L=(e,t)=>{const n=new Set(e);return t.every(n.has,n)},M=()=>{V("Pinging clients...");const e={type:"shared-worker-ping"};Object.values(p).forEach((t=>{let n=!1;t&&t.lastPingRequest&&(V(`Checking whether ${t.clientIdentifier} ping has been sent too long ago...`),(!t.lastPongEvent||Math.abs(t.lastPongEvent-t.lastPingRequest)>2.5)&&(n=!0,V(`'${t.clientIdentifier}' client is inactive. Invalidating.`),((e,t)=>{delete p[t];let n=h[e];if(n)if(n=n.filter((e=>e.clientIdentifier!==t)),n.length>0?h[e]=n:delete h[e],0===n.length&&delete g[e],n.length>0){const n=b[e];n&&(delete n[t],0===Object.keys(n).length&&delete b[e])}else delete b[e];V(`Invalidate '${t}' client. '${Object.keys(p).length}' clients currently active.`)})(t.subscriptionKey,t.clientIdentifier))),t&&!n&&(V(`Sending ping to ${t.clientIdentifier}...`),t.lastPingRequest=(new Date).getTime()/1e3,A(t,e))})),0===Object.keys(p).length&&l&&clearInterval(l)},V=(e,t)=>{if(!a)return;const n=t?[t]:Object.values(p),i={type:"shared-worker-console-log",message:e};n.forEach((e=>{e&&A(e,i)}))},B=(e,t,n)=>{if(!a)return;const i=n?[n]:Object.values(p),r={type:"shared-worker-console-dir",message:t,data:e};i.forEach((e=>{e&&A(e,r)}))},Q=e=>Object.keys(e).map((t=>{const n=e[t];return Array.isArray(n)?n.map((e=>`${t}=${J(e)}`)).join("&"):`${t}=${J(n)}`})).join("&"),J=e=>encodeURIComponent(e).replace(/[!~*'()]/g,(e=>`%${e.charCodeAt(0).toString(16).toUpperCase()}`))})); diff --git a/lib/core/utils.js b/lib/core/utils.js index 2bd14eee4..512d80040 100644 --- a/lib/core/utils.js +++ b/lib/core/utils.js @@ -1,6 +1,6 @@ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); -exports.queryStringFromObject = exports.findUniqueCommonElements = exports.removeSingleOccurance = exports.encodeNames = exports.encodeString = void 0; +exports.queryStringFromObject = exports.findUniqueCommonElements = exports.removeSingleOccurrence = exports.encodeNames = exports.encodeString = void 0; const encodeString = (input) => { return encodeURIComponent(input).replace(/[!~*'()]/g, (x) => `%${x.charCodeAt(0).toString(16).toUpperCase()}`); }; @@ -10,7 +10,7 @@ const encodeNames = (names, defaultString) => { return encodedNames.length ? encodedNames.join(',') : defaultString !== null && defaultString !== void 0 ? defaultString : ''; }; exports.encodeNames = encodeNames; -const removeSingleOccurance = (source, elementsToRemove) => { +const removeSingleOccurrence = (source, elementsToRemove) => { const removed = Object.fromEntries(elementsToRemove.map((prop) => [prop, false])); return source.filter((e) => { if (elementsToRemove.includes(e) && !removed[e]) { @@ -20,7 +20,7 @@ const removeSingleOccurance = (source, elementsToRemove) => { return true; }); }; -exports.removeSingleOccurance = removeSingleOccurance; +exports.removeSingleOccurrence = removeSingleOccurrence; const findUniqueCommonElements = (a, b) => { return [...a].filter((value) => b.includes(value) && a.indexOf(value) === a.lastIndexOf(value) && b.indexOf(value) === b.lastIndexOf(value)); }; diff --git a/lib/event-engine/index.js b/lib/event-engine/index.js index fd48c7427..697416481 100644 --- a/lib/event-engine/index.js +++ b/lib/event-engine/index.js @@ -67,11 +67,11 @@ class EventEngine { } } unsubscribe({ channels = [], channelGroups = [] }) { - const filteredChannels = utils.removeSingleOccurance(this.channels, [ + const filteredChannels = utils.removeSingleOccurrence(this.channels, [ ...channels, ...channels.map((c) => `${c}-pnpres`), ]); - const filteredGroups = utils.removeSingleOccurance(this.groups, [ + const filteredGroups = utils.removeSingleOccurrence(this.groups, [ ...channelGroups, ...channelGroups.map((c) => `${c}-pnpres`), ]); diff --git a/lib/node/index.js b/lib/node/index.js index 5fd5e321e..45fb6690c 100644 --- a/lib/node/index.js +++ b/lib/node/index.js @@ -2,7 +2,6 @@ var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; -var _a; const cbor_sync_1 = __importDefault(require("cbor-sync")); const buffer_1 = require("buffer"); const nodeCryptoModule_1 = require("../crypto/modules/NodeCryptoModule/nodeCryptoModule"); @@ -18,50 +17,50 @@ const cryptography_1 = __importDefault(require("../core/components/cryptography" const pubnub_error_1 = require("../errors/pubnub-error"); const pubnub_common_1 = require("../core/pubnub-common"); const common_1 = __importDefault(require("../cbor/common")); -module.exports = (_a = class PubNub extends pubnub_common_1.PubNubCore { - constructor(configuration) { - const configurationCopy = (0, configuration_2.setDefaults)(configuration); - const platformConfiguration = Object.assign(Object.assign({}, configurationCopy), { sdkFamily: 'Nodejs', PubNubFile: node_1.default }); - const clientConfiguration = (0, configuration_1.makeConfiguration)(platformConfiguration, (cryptoConfiguration) => { - if (!cryptoConfiguration.cipherKey) - return undefined; - return new nodeCryptoModule_1.CryptoModule({ - default: new nodeCryptoModule_1.LegacyCryptor(Object.assign({}, cryptoConfiguration)), - cryptors: [new nodeCryptoModule_1.AesCbcCryptor({ cipherKey: cryptoConfiguration.cipherKey })], - }); +class PubNub extends pubnub_common_1.PubNubCore { + constructor(configuration) { + const configurationCopy = (0, configuration_2.setDefaults)(configuration); + const platformConfiguration = Object.assign(Object.assign({}, configurationCopy), { sdkFamily: 'Nodejs', PubNubFile: node_1.default }); + const clientConfiguration = (0, configuration_1.makeConfiguration)(platformConfiguration, (cryptoConfiguration) => { + if (!cryptoConfiguration.cipherKey) + return undefined; + return new nodeCryptoModule_1.CryptoModule({ + default: new nodeCryptoModule_1.LegacyCryptor(Object.assign({}, cryptoConfiguration)), + cryptors: [new nodeCryptoModule_1.AesCbcCryptor({ cipherKey: cryptoConfiguration.cipherKey })], }); - const tokenManager = new token_manager_1.TokenManager(new common_1.default((buffer) => cbor_sync_1.default.decode(buffer_1.Buffer.from(buffer)), base64_codec_1.decode)); - const crypto = new cryptography_1.default({ - secretKey: clientConfiguration.secretKey, - cipherKey: clientConfiguration.getCipherKey(), - useRandomIVs: clientConfiguration.getUseRandomIVs(), - customEncrypt: clientConfiguration.getCustomEncrypt(), - customDecrypt: clientConfiguration.getCustomDecrypt(), - }); - const transport = new node_transport_1.NodeTransport(configuration.keepAlive, configuration.keepAliveSettings); - const transportMiddleware = new middleware_1.PubNubMiddleware({ - clientConfiguration, - tokenManager, - transport, - shaHMAC: crypto === null || crypto === void 0 ? void 0 : crypto.HMACSHA256.bind(crypto), - }); - super({ - configuration: clientConfiguration, - transport: transportMiddleware, - cryptography: new node_2.default(), - tokenManager, - crypto, - }); - this.File = node_1.default; - this.nodeTransport = transport; - } - setProxy(configuration) { - var _b; - if (configuration && ((_b = this._configuration.keepAlive) !== null && _b !== void 0 ? _b : false)) - throw new pubnub_error_1.PubNubError("Can't set 'proxy' because already configured for 'keepAlive'"); - this.nodeTransport.setProxy(configuration); - this.reconnect(); - } - }, - _a.CryptoModule = nodeCryptoModule_1.CryptoModule, - _a); + }); + const tokenManager = new token_manager_1.TokenManager(new common_1.default((buffer) => cbor_sync_1.default.decode(buffer_1.Buffer.from(buffer)), base64_codec_1.decode)); + const crypto = new cryptography_1.default({ + secretKey: clientConfiguration.secretKey, + cipherKey: clientConfiguration.getCipherKey(), + useRandomIVs: clientConfiguration.getUseRandomIVs(), + customEncrypt: clientConfiguration.getCustomEncrypt(), + customDecrypt: clientConfiguration.getCustomDecrypt(), + }); + const transport = new node_transport_1.NodeTransport(configuration.keepAlive, configuration.keepAliveSettings); + const transportMiddleware = new middleware_1.PubNubMiddleware({ + clientConfiguration, + tokenManager, + transport, + shaHMAC: crypto === null || crypto === void 0 ? void 0 : crypto.HMACSHA256.bind(crypto), + }); + super({ + configuration: clientConfiguration, + transport: transportMiddleware, + cryptography: new node_2.default(), + tokenManager, + crypto, + }); + this.File = node_1.default; + this.nodeTransport = transport; + } + setProxy(configuration) { + var _a; + if (configuration && ((_a = this._configuration.keepAlive) !== null && _a !== void 0 ? _a : false)) + throw new pubnub_error_1.PubNubError("Can't set 'proxy' because already configured for 'keepAlive'"); + this.nodeTransport.setProxy(configuration); + this.reconnect(); + } +} +PubNub.CryptoModule = nodeCryptoModule_1.CryptoModule; +module.exports = PubNub; diff --git a/lib/types/cbor/common.d.ts b/lib/types/cbor/common.d.ts new file mode 100644 index 000000000..cb0ff5c3b --- /dev/null +++ b/lib/types/cbor/common.d.ts @@ -0,0 +1 @@ +export {}; diff --git a/lib/types/core/components/abort_signal.d.ts b/lib/types/core/components/abort_signal.d.ts new file mode 100644 index 000000000..926a042d3 --- /dev/null +++ b/lib/types/core/components/abort_signal.d.ts @@ -0,0 +1,4 @@ +export declare class AbortError extends Error { + name: string; + constructor(); +} diff --git a/lib/types/core/components/base64_codec.d.ts b/lib/types/core/components/base64_codec.d.ts new file mode 100644 index 000000000..cb0ff5c3b --- /dev/null +++ b/lib/types/core/components/base64_codec.d.ts @@ -0,0 +1 @@ +export {}; diff --git a/lib/types/core/components/configuration.d.ts b/lib/types/core/components/configuration.d.ts new file mode 100644 index 000000000..cb0ff5c3b --- /dev/null +++ b/lib/types/core/components/configuration.d.ts @@ -0,0 +1 @@ +export {}; diff --git a/lib/types/core/components/cryptography/hmac-sha256.d.ts b/lib/types/core/components/cryptography/hmac-sha256.d.ts new file mode 100644 index 000000000..112f25199 --- /dev/null +++ b/lib/types/core/components/cryptography/hmac-sha256.d.ts @@ -0,0 +1,3 @@ +export namespace mode { + let ECB: any; +} diff --git a/lib/types/core/components/cryptography/index.d.ts b/lib/types/core/components/cryptography/index.d.ts new file mode 100644 index 000000000..ff88b48b7 --- /dev/null +++ b/lib/types/core/components/cryptography/index.d.ts @@ -0,0 +1,30 @@ +import { CryptorConfiguration } from '../../interfaces/crypto-module'; +import { Payload } from '../../types/api'; +type CryptoConfiguration = { + encryptKey?: boolean; + keyEncoding?: 'hex' | 'utf8' | 'base64' | 'binary'; + keyLength?: 128 | 256; + mode?: 'ecb' | 'cbc'; +}; +export default class { + private readonly configuration; + private iv; + private allowedKeyEncodings; + private allowedKeyLengths; + private allowedModes; + private readonly defaultOptions; + constructor(configuration: CryptorConfiguration); + HMACSHA256(data: string): string; + SHA256(data: string): string; + encrypt(data: string | Payload, customCipherKey?: string, options?: CryptoConfiguration): string; + decrypt(data: string, customCipherKey?: string, options?: CryptoConfiguration): Payload | null; + private pnEncrypt; + private pnDecrypt; + private parseOptions; + private decodeKey; + private getPaddedKey; + private getMode; + private getIV; + private getRandomIV; +} +export {}; diff --git a/lib/types/core/components/deduping_manager.d.ts b/lib/types/core/components/deduping_manager.d.ts new file mode 100644 index 000000000..121ef9cf6 --- /dev/null +++ b/lib/types/core/components/deduping_manager.d.ts @@ -0,0 +1,11 @@ +export default class _default { + constructor({ config }: { + config: any; + }); + _config: any; + hashHistory: any[]; + getKey(message: any): string; + isDuplicate(message: any): boolean; + addEntry(message: any): void; + clearHistory(): void; +} diff --git a/lib/types/core/components/eventEmitter.d.ts b/lib/types/core/components/eventEmitter.d.ts new file mode 100644 index 000000000..cb0ff5c3b --- /dev/null +++ b/lib/types/core/components/eventEmitter.d.ts @@ -0,0 +1 @@ +export {}; diff --git a/lib/types/core/components/listener_manager.d.ts b/lib/types/core/components/listener_manager.d.ts new file mode 100644 index 000000000..fec05ebba --- /dev/null +++ b/lib/types/core/components/listener_manager.d.ts @@ -0,0 +1,14 @@ +import * as Subscription from '../types/api/subscription'; +import { Status, StatusEvent } from '../types/api'; +export type Listener = { + message?: (message: Subscription.Message) => void; + signal?: (signal: Subscription.Signal) => void; + presence?: (presence: Subscription.Presence) => void; + objects?: (object: Subscription.AppContextObject) => void; + messageAction?: (action: Subscription.MessageAction) => void; + file?: (file: Subscription.File) => void; + status?: (status: Status | StatusEvent) => void; + user?: (user: Subscription.UserAppContextObject) => void; + space?: (space: Subscription.SpaceAppContextObject) => void; + membership?: (membership: Subscription.VSPMembershipAppContextObject) => void; +}; diff --git a/lib/types/core/components/push_payload.d.ts b/lib/types/core/components/push_payload.d.ts new file mode 100644 index 000000000..30be0cc7c --- /dev/null +++ b/lib/types/core/components/push_payload.d.ts @@ -0,0 +1,156 @@ +type APNSPayload = { + aps: { + alert?: { + title?: string; + subtitle?: string; + body?: string; + }; + badge?: number | null; + sound?: string; + 'content-available'?: 1; + }; + pn_push: PubNubAPNS2Configuration[]; +}; +type APNS2Configuration = { + collapseId?: string; + expirationDate?: Date; + targets: APNS2Target[]; +}; +type PubNubAPNS2Configuration = { + auth_method: 'token'; + targets: PubNubAPNS2Target[]; + collapse_id?: string; + expiration?: string; + version: 'v2'; +}; +type APNS2Target = { + topic: string; + environment?: 'development' | 'production'; + excludedDevices?: string[]; +}; +type PubNubAPNS2Target = Omit & { + excluded_devices?: string[]; +}; +type FCMPayload = { + notification?: { + title?: string; + body?: string; + icon?: string; + sound?: string; + tag?: string; + }; + data?: { + notification?: FCMPayload['notification']; + }; +}; +declare class BaseNotificationPayload { + protected _title?: string; + protected _subtitle?: string; + protected _sound?: string; + protected _badge?: number | null; + protected _body?: string; + protected _payload: unknown; + constructor(payload: unknown, title?: string, body?: string); + get payload(): unknown; + set title(value: string | undefined); + set subtitle(value: string | undefined); + set body(value: string | undefined); + set badge(value: number | null | undefined); + set sound(value: string | undefined); + protected setDefaultPayloadStructure(): void; + toObject(): unknown; +} +export declare class APNSNotificationPayload extends BaseNotificationPayload { + private _configurations?; + private _apnsPushType; + private _isSilent; + get payload(): APNSPayload; + set configurations(value: APNS2Configuration[]); + get notification(): { + alert?: { + title?: string | undefined; + subtitle?: string | undefined; + body?: string | undefined; + } | undefined; + badge?: number | null | undefined; + sound?: string | undefined; + 'content-available'?: 1 | undefined; + }; + get title(): string | undefined; + set title(value: string | undefined); + get subtitle(): string | undefined; + set subtitle(value: string | undefined); + get body(): string | undefined; + set body(value: string | undefined); + get badge(): number | null | undefined; + set badge(value: number | null | undefined); + get sound(): string | undefined; + set sound(value: string | undefined); + set silent(value: boolean); + protected setDefaultPayloadStructure(): void; + toObject(): APNSPayload | null; + private objectFromAPNS2Configuration; + private objectFromAPNSTarget; +} +export declare class FCMNotificationPayload extends BaseNotificationPayload { + private _isSilent?; + private _icon?; + private _tag?; + get payload(): FCMPayload; + get notification(): { + title?: string | undefined; + body?: string | undefined; + icon?: string | undefined; + sound?: string | undefined; + tag?: string | undefined; + } | undefined; + get data(): { + notification?: { + title?: string | undefined; + body?: string | undefined; + icon?: string | undefined; + sound?: string | undefined; + tag?: string | undefined; + } | undefined; + } | undefined; + get title(): string | undefined; + set title(value: string | undefined); + get body(): string | undefined; + set body(value: string | undefined); + get sound(): string | undefined; + set sound(value: string | undefined); + get icon(): string | undefined; + set icon(value: string | undefined); + get tag(): string | undefined; + set tag(value: string | undefined); + set silent(value: boolean); + protected setDefaultPayloadStructure(): void; + toObject(): FCMPayload | null; +} +declare class NotificationsPayload { + private readonly _payload; + private _debugging?; + private readonly _title; + private _subtitle?; + private readonly _body; + private _badge?; + private _sound?; + apns: APNSNotificationPayload; + fcm: FCMNotificationPayload; + constructor(title: string, body: string); + set debugging(value: boolean); + get title(): string; + get subtitle(): string | undefined; + set subtitle(value: string | undefined); + get body(): string; + get badge(): number | undefined; + set badge(value: number | undefined); + get sound(): string | undefined; + set sound(value: string | undefined); + buildPayload(platforms: string[]): { + pn_apns?: APNSPayload | undefined; + pn_gcm?: FCMPayload | undefined; + pn_debug?: boolean | undefined; + }; +} +export default NotificationsPayload; diff --git a/lib/types/core/components/reconnection_manager.d.ts b/lib/types/core/components/reconnection_manager.d.ts new file mode 100644 index 000000000..cb0ff5c3b --- /dev/null +++ b/lib/types/core/components/reconnection_manager.d.ts @@ -0,0 +1 @@ +export {}; diff --git a/lib/types/core/components/request.d.ts b/lib/types/core/components/request.d.ts new file mode 100644 index 000000000..cb0ff5c3b --- /dev/null +++ b/lib/types/core/components/request.d.ts @@ -0,0 +1 @@ +export {}; diff --git a/lib/types/core/components/stringify_buffer_keys.d.ts b/lib/types/core/components/stringify_buffer_keys.d.ts new file mode 100644 index 000000000..cb0ff5c3b --- /dev/null +++ b/lib/types/core/components/stringify_buffer_keys.d.ts @@ -0,0 +1 @@ +export {}; diff --git a/lib/types/core/components/subject.d.ts b/lib/types/core/components/subject.d.ts new file mode 100644 index 000000000..cb0ff5c3b --- /dev/null +++ b/lib/types/core/components/subject.d.ts @@ -0,0 +1 @@ +export {}; diff --git a/lib/types/core/components/subscription-manager.d.ts b/lib/types/core/components/subscription-manager.d.ts new file mode 100644 index 000000000..cb0ff5c3b --- /dev/null +++ b/lib/types/core/components/subscription-manager.d.ts @@ -0,0 +1 @@ +export {}; diff --git a/lib/types/core/components/token_manager.d.ts b/lib/types/core/components/token_manager.d.ts new file mode 100644 index 000000000..cb0ff5c3b --- /dev/null +++ b/lib/types/core/components/token_manager.d.ts @@ -0,0 +1 @@ +export {}; diff --git a/lib/types/core/components/uuid.d.ts b/lib/types/core/components/uuid.d.ts new file mode 100644 index 000000000..0131316e7 --- /dev/null +++ b/lib/types/core/components/uuid.d.ts @@ -0,0 +1,4 @@ +declare const _default: { + createUUID(): any; +}; +export default _default; diff --git a/lib/types/core/constants/categories.d.ts b/lib/types/core/constants/categories.d.ts new file mode 100644 index 000000000..a56853dae --- /dev/null +++ b/lib/types/core/constants/categories.d.ts @@ -0,0 +1,19 @@ +declare enum StatusCategory { + PNNetworkIssuesCategory = "PNNetworkIssuesCategory", + PNTimeoutCategory = "PNTimeoutCategory", + PNCancelledCategory = "PNCancelledCategory", + PNBadRequestCategory = "PNBadRequestCategory", + PNAccessDeniedCategory = "PNAccessDeniedCategory", + PNValidationErrorCategory = "PNValidationErrorCategory", + PNAcknowledgmentCategory = "PNAcknowledgmentCategory", + PNUnknownCategory = "PNUnknownCategory", + PNNetworkUpCategory = "PNNetworkUpCategory", + PNNetworkDownCategory = "PNNetworkDownCategory", + PNReconnectedCategory = "PNReconnectedCategory", + PNConnectedCategory = "PNConnectedCategory", + PNRequestMessageCountExceededCategory = "PNRequestMessageCountExceededCategory", + PNDisconnectedCategory = "PNDisconnectedCategory", + PNConnectionErrorCategory = "PNConnectionErrorCategory", + PNDisconnectedUnexpectedlyCategory = "PNDisconnectedUnexpectedlyCategory" +} +export default StatusCategory; diff --git a/lib/types/core/constants/operations.d.ts b/lib/types/core/constants/operations.d.ts new file mode 100644 index 000000000..c7b7ec87b --- /dev/null +++ b/lib/types/core/constants/operations.d.ts @@ -0,0 +1,55 @@ +declare enum RequestOperation { + PNPublishOperation = "PNPublishOperation", + PNSignalOperation = "PNSignalOperation", + PNSubscribeOperation = "PNSubscribeOperation", + PNUnsubscribeOperation = "PNUnsubscribeOperation", + PNWhereNowOperation = "PNWhereNowOperation", + PNHereNowOperation = "PNHereNowOperation", + PNGlobalHereNowOperation = "PNGlobalHereNowOperation", + PNSetStateOperation = "PNSetStateOperation", + PNGetStateOperation = "PNGetStateOperation", + PNHeartbeatOperation = "PNHeartbeatOperation", + PNAddMessageActionOperation = "PNAddActionOperation", + PNRemoveMessageActionOperation = "PNRemoveMessageActionOperation", + PNGetMessageActionsOperation = "PNGetMessageActionsOperation", + PNTimeOperation = "PNTimeOperation", + PNHistoryOperation = "PNHistoryOperation", + PNDeleteMessagesOperation = "PNDeleteMessagesOperation", + PNFetchMessagesOperation = "PNFetchMessagesOperation", + PNMessageCounts = "PNMessageCountsOperation", + PNGetAllUUIDMetadataOperation = "PNGetAllUUIDMetadataOperation", + PNGetUUIDMetadataOperation = "PNGetUUIDMetadataOperation", + PNSetUUIDMetadataOperation = "PNSetUUIDMetadataOperation", + PNRemoveUUIDMetadataOperation = "PNRemoveUUIDMetadataOperation", + PNGetAllChannelMetadataOperation = "PNGetAllChannelMetadataOperation", + PNGetChannelMetadataOperation = "PNGetChannelMetadataOperation", + PNSetChannelMetadataOperation = "PNSetChannelMetadataOperation", + PNRemoveChannelMetadataOperation = "PNRemoveChannelMetadataOperation", + PNGetMembersOperation = "PNGetMembersOperation", + PNSetMembersOperation = "PNSetMembersOperation", + PNGetMembershipsOperation = "PNGetMembershipsOperation", + PNSetMembershipsOperation = "PNSetMembershipsOperation", + PNListFilesOperation = "PNListFilesOperation", + PNGenerateUploadUrlOperation = "PNGenerateUploadUrlOperation", + PNPublishFileOperation = "PNPublishFileOperation", + PNPublishFileMessageOperation = "PNPublishFileMessageOperation", + PNGetFileUrlOperation = "PNGetFileUrlOperation", + PNDownloadFileOperation = "PNDownloadFileOperation", + PNDeleteFileOperation = "PNDeleteFileOperation", + PNAddPushNotificationEnabledChannelsOperation = "PNAddPushNotificationEnabledChannelsOperation", + PNRemovePushNotificationEnabledChannelsOperation = "PNRemovePushNotificationEnabledChannelsOperation", + PNPushNotificationEnabledChannelsOperation = "PNPushNotificationEnabledChannelsOperation", + PNRemoveAllPushNotificationsOperation = "PNRemoveAllPushNotificationsOperation", + PNChannelGroupsOperation = "PNChannelGroupsOperation", + PNRemoveGroupOperation = "PNRemoveGroupOperation", + PNChannelsForGroupOperation = "PNChannelsForGroupOperation", + PNAddChannelsToGroupOperation = "PNAddChannelsToGroupOperation", + PNRemoveChannelsFromGroupOperation = "PNRemoveChannelsFromGroupOperation", + PNAccessManagerGrant = "PNAccessManagerGrant", + PNAccessManagerGrantToken = "PNAccessManagerGrantToken", + PNAccessManagerAudit = "PNAccessManagerAudit", + PNAccessManagerRevokeToken = "PNAccessManagerRevokeToken", + PNHandshakeOperation = "PNHandshakeOperation", + PNReceiveMessagesOperation = "PNReceiveMessagesOperation" +} +export default RequestOperation; diff --git a/lib/types/core/endpoints/access_manager/audit.d.ts b/lib/types/core/endpoints/access_manager/audit.d.ts new file mode 100644 index 000000000..cb0ff5c3b --- /dev/null +++ b/lib/types/core/endpoints/access_manager/audit.d.ts @@ -0,0 +1 @@ +export {}; diff --git a/lib/types/core/endpoints/access_manager/grant.d.ts b/lib/types/core/endpoints/access_manager/grant.d.ts new file mode 100644 index 000000000..cb0ff5c3b --- /dev/null +++ b/lib/types/core/endpoints/access_manager/grant.d.ts @@ -0,0 +1 @@ +export {}; diff --git a/lib/types/core/endpoints/access_manager/grant_token.d.ts b/lib/types/core/endpoints/access_manager/grant_token.d.ts new file mode 100644 index 000000000..cb0ff5c3b --- /dev/null +++ b/lib/types/core/endpoints/access_manager/grant_token.d.ts @@ -0,0 +1 @@ +export {}; diff --git a/lib/types/core/endpoints/access_manager/revoke_token.d.ts b/lib/types/core/endpoints/access_manager/revoke_token.d.ts new file mode 100644 index 000000000..cb0ff5c3b --- /dev/null +++ b/lib/types/core/endpoints/access_manager/revoke_token.d.ts @@ -0,0 +1 @@ +export {}; diff --git a/lib/types/core/endpoints/actions/add_message_action.d.ts b/lib/types/core/endpoints/actions/add_message_action.d.ts new file mode 100644 index 000000000..cb0ff5c3b --- /dev/null +++ b/lib/types/core/endpoints/actions/add_message_action.d.ts @@ -0,0 +1 @@ +export {}; diff --git a/lib/types/core/endpoints/actions/get_message_actions.d.ts b/lib/types/core/endpoints/actions/get_message_actions.d.ts new file mode 100644 index 000000000..cb0ff5c3b --- /dev/null +++ b/lib/types/core/endpoints/actions/get_message_actions.d.ts @@ -0,0 +1 @@ +export {}; diff --git a/lib/types/core/endpoints/actions/remove_message_action.d.ts b/lib/types/core/endpoints/actions/remove_message_action.d.ts new file mode 100644 index 000000000..cb0ff5c3b --- /dev/null +++ b/lib/types/core/endpoints/actions/remove_message_action.d.ts @@ -0,0 +1 @@ +export {}; diff --git a/lib/types/core/endpoints/channel_groups/add_channels.d.ts b/lib/types/core/endpoints/channel_groups/add_channels.d.ts new file mode 100644 index 000000000..cb0ff5c3b --- /dev/null +++ b/lib/types/core/endpoints/channel_groups/add_channels.d.ts @@ -0,0 +1 @@ +export {}; diff --git a/lib/types/core/endpoints/channel_groups/delete_group.d.ts b/lib/types/core/endpoints/channel_groups/delete_group.d.ts new file mode 100644 index 000000000..cb0ff5c3b --- /dev/null +++ b/lib/types/core/endpoints/channel_groups/delete_group.d.ts @@ -0,0 +1 @@ +export {}; diff --git a/lib/types/core/endpoints/channel_groups/list_channels.d.ts b/lib/types/core/endpoints/channel_groups/list_channels.d.ts new file mode 100644 index 000000000..cb0ff5c3b --- /dev/null +++ b/lib/types/core/endpoints/channel_groups/list_channels.d.ts @@ -0,0 +1 @@ +export {}; diff --git a/lib/types/core/endpoints/channel_groups/list_groups.d.ts b/lib/types/core/endpoints/channel_groups/list_groups.d.ts new file mode 100644 index 000000000..cb0ff5c3b --- /dev/null +++ b/lib/types/core/endpoints/channel_groups/list_groups.d.ts @@ -0,0 +1 @@ +export {}; diff --git a/lib/types/core/endpoints/channel_groups/remove_channels.d.ts b/lib/types/core/endpoints/channel_groups/remove_channels.d.ts new file mode 100644 index 000000000..cb0ff5c3b --- /dev/null +++ b/lib/types/core/endpoints/channel_groups/remove_channels.d.ts @@ -0,0 +1 @@ +export {}; diff --git a/lib/types/core/endpoints/fetch_messages.d.ts b/lib/types/core/endpoints/fetch_messages.d.ts new file mode 100644 index 000000000..cb0ff5c3b --- /dev/null +++ b/lib/types/core/endpoints/fetch_messages.d.ts @@ -0,0 +1 @@ +export {}; diff --git a/lib/types/core/endpoints/file_upload/delete_file.d.ts b/lib/types/core/endpoints/file_upload/delete_file.d.ts new file mode 100644 index 000000000..cb0ff5c3b --- /dev/null +++ b/lib/types/core/endpoints/file_upload/delete_file.d.ts @@ -0,0 +1 @@ +export {}; diff --git a/lib/types/core/endpoints/file_upload/download_file.d.ts b/lib/types/core/endpoints/file_upload/download_file.d.ts new file mode 100644 index 000000000..cb0ff5c3b --- /dev/null +++ b/lib/types/core/endpoints/file_upload/download_file.d.ts @@ -0,0 +1 @@ +export {}; diff --git a/lib/types/core/endpoints/file_upload/generate_upload_url.d.ts b/lib/types/core/endpoints/file_upload/generate_upload_url.d.ts new file mode 100644 index 000000000..cb0ff5c3b --- /dev/null +++ b/lib/types/core/endpoints/file_upload/generate_upload_url.d.ts @@ -0,0 +1 @@ +export {}; diff --git a/lib/types/core/endpoints/file_upload/get_file_url.d.ts b/lib/types/core/endpoints/file_upload/get_file_url.d.ts new file mode 100644 index 000000000..cb0ff5c3b --- /dev/null +++ b/lib/types/core/endpoints/file_upload/get_file_url.d.ts @@ -0,0 +1 @@ +export {}; diff --git a/lib/types/core/endpoints/file_upload/list_files.d.ts b/lib/types/core/endpoints/file_upload/list_files.d.ts new file mode 100644 index 000000000..cb0ff5c3b --- /dev/null +++ b/lib/types/core/endpoints/file_upload/list_files.d.ts @@ -0,0 +1 @@ +export {}; diff --git a/lib/types/core/endpoints/file_upload/publish_file.d.ts b/lib/types/core/endpoints/file_upload/publish_file.d.ts new file mode 100644 index 000000000..cb0ff5c3b --- /dev/null +++ b/lib/types/core/endpoints/file_upload/publish_file.d.ts @@ -0,0 +1 @@ +export {}; diff --git a/lib/types/core/endpoints/file_upload/send_file.d.ts b/lib/types/core/endpoints/file_upload/send_file.d.ts new file mode 100644 index 000000000..cb0ff5c3b --- /dev/null +++ b/lib/types/core/endpoints/file_upload/send_file.d.ts @@ -0,0 +1 @@ +export {}; diff --git a/lib/types/core/endpoints/file_upload/upload-file.d.ts b/lib/types/core/endpoints/file_upload/upload-file.d.ts new file mode 100644 index 000000000..cb0ff5c3b --- /dev/null +++ b/lib/types/core/endpoints/file_upload/upload-file.d.ts @@ -0,0 +1 @@ +export {}; diff --git a/lib/types/core/endpoints/history/delete_messages.d.ts b/lib/types/core/endpoints/history/delete_messages.d.ts new file mode 100644 index 000000000..cb0ff5c3b --- /dev/null +++ b/lib/types/core/endpoints/history/delete_messages.d.ts @@ -0,0 +1 @@ +export {}; diff --git a/lib/types/core/endpoints/history/get_history.d.ts b/lib/types/core/endpoints/history/get_history.d.ts new file mode 100644 index 000000000..cb0ff5c3b --- /dev/null +++ b/lib/types/core/endpoints/history/get_history.d.ts @@ -0,0 +1 @@ +export {}; diff --git a/lib/types/core/endpoints/history/message_counts.d.ts b/lib/types/core/endpoints/history/message_counts.d.ts new file mode 100644 index 000000000..cb0ff5c3b --- /dev/null +++ b/lib/types/core/endpoints/history/message_counts.d.ts @@ -0,0 +1 @@ +export {}; diff --git a/lib/types/core/endpoints/objects/channel/get.d.ts b/lib/types/core/endpoints/objects/channel/get.d.ts new file mode 100644 index 000000000..cb0ff5c3b --- /dev/null +++ b/lib/types/core/endpoints/objects/channel/get.d.ts @@ -0,0 +1 @@ +export {}; diff --git a/lib/types/core/endpoints/objects/channel/get_all.d.ts b/lib/types/core/endpoints/objects/channel/get_all.d.ts new file mode 100644 index 000000000..cb0ff5c3b --- /dev/null +++ b/lib/types/core/endpoints/objects/channel/get_all.d.ts @@ -0,0 +1 @@ +export {}; diff --git a/lib/types/core/endpoints/objects/channel/remove.d.ts b/lib/types/core/endpoints/objects/channel/remove.d.ts new file mode 100644 index 000000000..cb0ff5c3b --- /dev/null +++ b/lib/types/core/endpoints/objects/channel/remove.d.ts @@ -0,0 +1 @@ +export {}; diff --git a/lib/types/core/endpoints/objects/channel/set.d.ts b/lib/types/core/endpoints/objects/channel/set.d.ts new file mode 100644 index 000000000..cb0ff5c3b --- /dev/null +++ b/lib/types/core/endpoints/objects/channel/set.d.ts @@ -0,0 +1 @@ +export {}; diff --git a/lib/types/core/endpoints/objects/member/get.d.ts b/lib/types/core/endpoints/objects/member/get.d.ts new file mode 100644 index 000000000..cb0ff5c3b --- /dev/null +++ b/lib/types/core/endpoints/objects/member/get.d.ts @@ -0,0 +1 @@ +export {}; diff --git a/lib/types/core/endpoints/objects/member/set.d.ts b/lib/types/core/endpoints/objects/member/set.d.ts new file mode 100644 index 000000000..cb0ff5c3b --- /dev/null +++ b/lib/types/core/endpoints/objects/member/set.d.ts @@ -0,0 +1 @@ +export {}; diff --git a/lib/types/core/endpoints/objects/membership/get.d.ts b/lib/types/core/endpoints/objects/membership/get.d.ts new file mode 100644 index 000000000..cb0ff5c3b --- /dev/null +++ b/lib/types/core/endpoints/objects/membership/get.d.ts @@ -0,0 +1 @@ +export {}; diff --git a/lib/types/core/endpoints/objects/membership/set.d.ts b/lib/types/core/endpoints/objects/membership/set.d.ts new file mode 100644 index 000000000..cb0ff5c3b --- /dev/null +++ b/lib/types/core/endpoints/objects/membership/set.d.ts @@ -0,0 +1 @@ +export {}; diff --git a/lib/types/core/endpoints/objects/uuid/get.d.ts b/lib/types/core/endpoints/objects/uuid/get.d.ts new file mode 100644 index 000000000..cb0ff5c3b --- /dev/null +++ b/lib/types/core/endpoints/objects/uuid/get.d.ts @@ -0,0 +1 @@ +export {}; diff --git a/lib/types/core/endpoints/objects/uuid/get_all.d.ts b/lib/types/core/endpoints/objects/uuid/get_all.d.ts new file mode 100644 index 000000000..cb0ff5c3b --- /dev/null +++ b/lib/types/core/endpoints/objects/uuid/get_all.d.ts @@ -0,0 +1 @@ +export {}; diff --git a/lib/types/core/endpoints/objects/uuid/remove.d.ts b/lib/types/core/endpoints/objects/uuid/remove.d.ts new file mode 100644 index 000000000..cb0ff5c3b --- /dev/null +++ b/lib/types/core/endpoints/objects/uuid/remove.d.ts @@ -0,0 +1 @@ +export {}; diff --git a/lib/types/core/endpoints/objects/uuid/set.d.ts b/lib/types/core/endpoints/objects/uuid/set.d.ts new file mode 100644 index 000000000..cb0ff5c3b --- /dev/null +++ b/lib/types/core/endpoints/objects/uuid/set.d.ts @@ -0,0 +1 @@ +export {}; diff --git a/lib/types/core/endpoints/presence/get_state.d.ts b/lib/types/core/endpoints/presence/get_state.d.ts new file mode 100644 index 000000000..cb0ff5c3b --- /dev/null +++ b/lib/types/core/endpoints/presence/get_state.d.ts @@ -0,0 +1 @@ +export {}; diff --git a/lib/types/core/endpoints/presence/heartbeat.d.ts b/lib/types/core/endpoints/presence/heartbeat.d.ts new file mode 100644 index 000000000..cb0ff5c3b --- /dev/null +++ b/lib/types/core/endpoints/presence/heartbeat.d.ts @@ -0,0 +1 @@ +export {}; diff --git a/lib/types/core/endpoints/presence/here_now.d.ts b/lib/types/core/endpoints/presence/here_now.d.ts new file mode 100644 index 000000000..cb0ff5c3b --- /dev/null +++ b/lib/types/core/endpoints/presence/here_now.d.ts @@ -0,0 +1 @@ +export {}; diff --git a/lib/types/core/endpoints/presence/leave.d.ts b/lib/types/core/endpoints/presence/leave.d.ts new file mode 100644 index 000000000..cb0ff5c3b --- /dev/null +++ b/lib/types/core/endpoints/presence/leave.d.ts @@ -0,0 +1 @@ +export {}; diff --git a/lib/types/core/endpoints/presence/set_state.d.ts b/lib/types/core/endpoints/presence/set_state.d.ts new file mode 100644 index 000000000..cb0ff5c3b --- /dev/null +++ b/lib/types/core/endpoints/presence/set_state.d.ts @@ -0,0 +1 @@ +export {}; diff --git a/lib/types/core/endpoints/presence/where_now.d.ts b/lib/types/core/endpoints/presence/where_now.d.ts new file mode 100644 index 000000000..cb0ff5c3b --- /dev/null +++ b/lib/types/core/endpoints/presence/where_now.d.ts @@ -0,0 +1 @@ +export {}; diff --git a/lib/types/core/endpoints/publish.d.ts b/lib/types/core/endpoints/publish.d.ts new file mode 100644 index 000000000..7b4e99310 --- /dev/null +++ b/lib/types/core/endpoints/publish.d.ts @@ -0,0 +1,15 @@ +import { CryptoModule } from '../interfaces/crypto-module'; +import { Payload } from '../types/api'; +export type PublishParameters = { + channel: string; + message: Payload; + storeInHistory?: boolean; + sendByPost?: boolean; + meta?: Payload; + ttl?: number; + replicate?: boolean; + [key: string]: string | number | boolean | undefined | Payload | CryptoModule; +}; +export type PublishResponse = { + timetoken: string; +}; diff --git a/lib/types/core/endpoints/push/add_push_channels.d.ts b/lib/types/core/endpoints/push/add_push_channels.d.ts new file mode 100644 index 000000000..cb0ff5c3b --- /dev/null +++ b/lib/types/core/endpoints/push/add_push_channels.d.ts @@ -0,0 +1 @@ +export {}; diff --git a/lib/types/core/endpoints/push/list_push_channels.d.ts b/lib/types/core/endpoints/push/list_push_channels.d.ts new file mode 100644 index 000000000..cb0ff5c3b --- /dev/null +++ b/lib/types/core/endpoints/push/list_push_channels.d.ts @@ -0,0 +1 @@ +export {}; diff --git a/lib/types/core/endpoints/push/push.d.ts b/lib/types/core/endpoints/push/push.d.ts new file mode 100644 index 000000000..cb0ff5c3b --- /dev/null +++ b/lib/types/core/endpoints/push/push.d.ts @@ -0,0 +1 @@ +export {}; diff --git a/lib/types/core/endpoints/push/remove_device.d.ts b/lib/types/core/endpoints/push/remove_device.d.ts new file mode 100644 index 000000000..cb0ff5c3b --- /dev/null +++ b/lib/types/core/endpoints/push/remove_device.d.ts @@ -0,0 +1 @@ +export {}; diff --git a/lib/types/core/endpoints/push/remove_push_channels.d.ts b/lib/types/core/endpoints/push/remove_push_channels.d.ts new file mode 100644 index 000000000..cb0ff5c3b --- /dev/null +++ b/lib/types/core/endpoints/push/remove_push_channels.d.ts @@ -0,0 +1 @@ +export {}; diff --git a/lib/types/core/endpoints/signal.d.ts b/lib/types/core/endpoints/signal.d.ts new file mode 100644 index 000000000..6b739aac8 --- /dev/null +++ b/lib/types/core/endpoints/signal.d.ts @@ -0,0 +1,8 @@ +import { Payload } from '../types/api'; +export type SignalParameters = { + channel: string; + message: Payload; +}; +export type SignalResponse = { + timetoken: string; +}; diff --git a/lib/types/core/endpoints/subscribe.d.ts b/lib/types/core/endpoints/subscribe.d.ts new file mode 100644 index 000000000..cb0ff5c3b --- /dev/null +++ b/lib/types/core/endpoints/subscribe.d.ts @@ -0,0 +1 @@ +export {}; diff --git a/lib/types/core/endpoints/subscriptionUtils/handshake.d.ts b/lib/types/core/endpoints/subscriptionUtils/handshake.d.ts new file mode 100644 index 000000000..cb0ff5c3b --- /dev/null +++ b/lib/types/core/endpoints/subscriptionUtils/handshake.d.ts @@ -0,0 +1 @@ +export {}; diff --git a/lib/types/core/endpoints/subscriptionUtils/receiveMessages.d.ts b/lib/types/core/endpoints/subscriptionUtils/receiveMessages.d.ts new file mode 100644 index 000000000..cb0ff5c3b --- /dev/null +++ b/lib/types/core/endpoints/subscriptionUtils/receiveMessages.d.ts @@ -0,0 +1 @@ +export {}; diff --git a/lib/types/core/endpoints/time.d.ts b/lib/types/core/endpoints/time.d.ts new file mode 100644 index 000000000..e02a488b9 --- /dev/null +++ b/lib/types/core/endpoints/time.d.ts @@ -0,0 +1,3 @@ +export type TimeResponse = { + timetoken: string; +}; diff --git a/lib/types/core/interfaces/configuration.d.ts b/lib/types/core/interfaces/configuration.d.ts new file mode 100644 index 000000000..b6debb50c --- /dev/null +++ b/lib/types/core/interfaces/configuration.d.ts @@ -0,0 +1,74 @@ +import { PubNubFileConstructor, PubNubFileInterface } from '../types/file'; +import { RequestRetryPolicy } from '../../event-engine/core/retryPolicy'; +import { CryptoModule } from './crypto-module'; +import { Payload } from '../types/api'; +export type UserConfiguration = { + subscribeKey: string; + subscribe_key?: string; + publishKey?: string; + publish_key?: string; + secretKey?: string; + secret_key?: string; + userId?: string; + authKey?: string | null; + logVerbosity?: boolean; + ssl?: boolean; + origin?: string | string[]; + presenceTimeout?: number; + heartbeatInterval?: number; + transactionalRequestTimeout?: number; + subscribeRequestTimeout?: number; + restore?: boolean; + useInstanceId?: boolean; + suppressLeaveEvents?: boolean; + requestMessageCountThreshold?: number; + autoNetworkDetection?: boolean; + enableEventEngine?: boolean; + retryConfiguration?: RequestRetryPolicy; + maintainPresenceState?: boolean; + uuid?: string; + keepAlive?: boolean; + sdkName?: string; + partnerId?: string; +}; +export type PlatformConfiguration = { + sdkFamily: string; + cryptoModule?: CryptoModule; + PubNubFile?: PubNubFileConstructor; + cipherKey?: string; + useRandomIVs?: boolean; + customEncrypt?: (data: string | Payload) => string; + customDecrypt?: (data: string) => string; +}; +export interface ClientConfiguration { + getUserId(): string; + setUserId(value: string): void; + setAuthKey(authKey: string | null): void; + getFilterExpression(): string | undefined | null; + setFilterExpression(expression: string | null | undefined): void; + setCipherKey(key: string | undefined): void; + get version(): string; + getVersion(): string; + _addPnsdkSuffix(name: string, suffix: string | number): void; + getUUID(): string; + setUUID(value: string): void; +} +export interface PrivateClientConfiguration extends ClientConfiguration, Omit { + getAuthKey(): string | undefined | null; + getCryptoModule(): CryptoModule | undefined; + getPresenceTimeout(): number; + setPresenceTimeout(timeout: number): void; + getHeartbeatInterval(): number | undefined; + setHeartbeatInterval(interval: number): void; + getTransactionTimeout(): number; + getSubscribeTimeout(): number; + get PubNubFile(): PubNubFileConstructor | undefined; + get instanceId(): string | undefined; + get sdkFamily(): string; + _getPnsdkSuffix(separator: string): string; + getCipherKey(): string | undefined; + getUseRandomIVs(): boolean | undefined; + getCustomEncrypt(): ((data: string | Payload) => string) | undefined; + getCustomDecrypt(): ((data: string) => string) | undefined; +} +export declare const setDefaults: (configuration: UserConfiguration) => ExtendedConfiguration; diff --git a/lib/types/core/interfaces/crypto-module.d.ts b/lib/types/core/interfaces/crypto-module.d.ts new file mode 100644 index 000000000..8629730da --- /dev/null +++ b/lib/types/core/interfaces/crypto-module.d.ts @@ -0,0 +1,33 @@ +import { PubNubFileConstructor, PubNubFileInterface } from '../types/file'; +import { Payload } from '../types/api'; +export type CryptoModuleConfiguration = { + default: C; + cryptors?: C[]; +}; +export type CryptorConfiguration = { + cipherKey?: string; + secretKey?: string; + useRandomIVs?: boolean; + customEncrypt?: (data: string | Payload) => string; + customDecrypt?: (data: string) => string; +}; +export interface CryptoModule { + encrypt(data: ArrayBuffer | string): ArrayBuffer | string; + encryptFile(file: PubNubFileInterface, File: PubNubFileConstructor): Promise; + decrypt(data: ArrayBuffer | string): ArrayBuffer | Payload | null; + decryptFile(file: PubNubFileInterface, File: PubNubFileConstructor): Promise; +} +export declare abstract class AbstractCryptoModule implements CryptoModule { + protected static encoder: TextEncoder; + protected static decoder: TextDecoder; + defaultCryptor: C; + cryptors: C[]; + static legacyCryptoModule(config: CryptorConfiguration): CryptoModule; + static aesCbcCryptoModule(config: CryptorConfiguration): CryptoModule; + constructor(configuration: CryptoModuleConfiguration); + abstract encrypt(data: ArrayBuffer | string): ArrayBuffer | string; + abstract encryptFile(file: PubNubFileInterface, File: PubNubFileConstructor): Promise; + abstract decrypt(data: ArrayBuffer | string): ArrayBuffer | Payload | null; + abstract decryptFile(file: PubNubFileInterface, File: PubNubFileConstructor): Promise; + protected getAllCryptors(): C[]; +} diff --git a/lib/types/core/interfaces/cryptography.d.ts b/lib/types/core/interfaces/cryptography.d.ts new file mode 100644 index 000000000..cfdfb1a2c --- /dev/null +++ b/lib/types/core/interfaces/cryptography.d.ts @@ -0,0 +1,7 @@ +import { PubNubFileConstructor, PubNubFileInterface } from '../types/file'; +export interface Cryptography { + encrypt(key: string, input: Types): Promise; + decrypt(key: string, input: Types): Promise; + encryptFile(key: string, file: PubNubFileInterface, File: PubNubFileConstructor): Promise; + decryptFile(key: string, file: PubNubFileInterface, File: PubNubFileConstructor): Promise; +} diff --git a/lib/types/core/interfaces/request.d.ts b/lib/types/core/interfaces/request.d.ts new file mode 100644 index 000000000..cb0ff5c3b --- /dev/null +++ b/lib/types/core/interfaces/request.d.ts @@ -0,0 +1 @@ +export {}; diff --git a/lib/types/core/interfaces/transport.d.ts b/lib/types/core/interfaces/transport.d.ts new file mode 100644 index 000000000..1b081f700 --- /dev/null +++ b/lib/types/core/interfaces/transport.d.ts @@ -0,0 +1,12 @@ +import { CancellationController, TransportRequest } from '../types/transport-request'; +import { TransportResponse } from '../types/transport-response'; +export type TransportKeepAlive = { + keepAliveMsecs?: number; + maxSockets?: number; + maxFreeSockets?: number; + timeout?: number; +}; +export interface Transport { + makeSendable(req: TransportRequest): [Promise, CancellationController | undefined]; + request(req: TransportRequest): TransportRequest; +} diff --git a/lib/types/core/pubnub-channel-groups.d.ts b/lib/types/core/pubnub-channel-groups.d.ts new file mode 100644 index 000000000..efcecac4d --- /dev/null +++ b/lib/types/core/pubnub-channel-groups.d.ts @@ -0,0 +1,17 @@ +import { KeySet, ResultCallback, SendRequestFunction, StatusCallback } from './types/api'; +import * as ChannelGroups from './types/api/channel-groups'; +export default class PubnubChannelGroups { + private readonly keySet; + private readonly sendRequest; + constructor(keySet: KeySet, sendRequest: SendRequestFunction); + listChannels(parameters: ChannelGroups.ListChannelGroupChannelsParameters, callback: ResultCallback): void; + listChannels(parameters: ChannelGroups.ListChannelGroupChannelsParameters): Promise; + listGroups(callback: ResultCallback): void; + listGroups(): Promise; + addChannels(parameters: ChannelGroups.ManageChannelGroupChannelsParameters, callback: StatusCallback): void; + addChannels(parameters: ChannelGroups.ManageChannelGroupChannelsParameters): Promise>; + removeChannels(parameters: ChannelGroups.ManageChannelGroupChannelsParameters, callback: StatusCallback): void; + removeChannels(parameters: ChannelGroups.ManageChannelGroupChannelsParameters): Promise>; + deleteGroup(parameters: ChannelGroups.DeleteChannelGroupParameters, callback: StatusCallback): void; + deleteGroup(parameters: ChannelGroups.DeleteChannelGroupParameters): Promise>; +} diff --git a/lib/types/core/pubnub-common.d.ts b/lib/types/core/pubnub-common.d.ts new file mode 100644 index 000000000..02fea41d4 --- /dev/null +++ b/lib/types/core/pubnub-common.d.ts @@ -0,0 +1,230 @@ +import { Listener } from './components/listener_manager'; +import NotificationsPayload from './components/push_payload'; +import { TokenManager } from './components/token_manager'; +import Crypto from './components/cryptography/index'; +import { Payload, ResultCallback } from './types/api'; +import { ClientConfiguration, PrivateClientConfiguration } from './interfaces/configuration'; +import { Cryptography } from './interfaces/cryptography'; +import { Transport } from './interfaces/transport'; +import RequestOperation from './constants/operations'; +import StatusCategory from './constants/categories'; +import { RetryPolicy } from '../event-engine/core/retryPolicy'; +import * as Publish from './endpoints/publish'; +import * as Signal from './endpoints/signal'; +import * as Subscription from './types/api/subscription'; +import * as Presence from './types/api/presence'; +import * as History from './types/api/history'; +import * as MessageAction from './types/api/message-action'; +import * as FileSharing from './types/api/file-sharing'; +import { PubNubFileInterface } from './types/file'; +import * as PAM from './types/api/access-panager'; +import { SubscriptionOptions } from '../entities/commonTypes'; +import { ChannelMetadata } from '../entities/ChannelMetadata'; +import { SubscriptionSet } from '../entities/SubscriptionSet'; +import { ChannelGroup } from '../entities/ChannelGroup'; +import { UserMetadata } from '../entities/UserMetadata'; +import { Channel } from '../entities/Channel'; +import PubNubChannelGroups from './pubnub-channel-groups'; +import PubNubPushNotifications from './pubnub-push'; +import * as AppContext from './types/api/app-context'; +import PubNubObjects from './pubnub-objects'; +import * as Time from './endpoints/time'; +type ClientInstanceConfiguration = { + configuration: PrivateClientConfiguration; + transport: Transport; + tokenManager: TokenManager; + cryptography?: Cryptography; + crypto?: Crypto; +}; +export declare class PubNubCore = Record> { + static OPERATIONS: typeof RequestOperation; + static CATEGORIES: typeof StatusCategory; + static ExponentialRetryPolicy: typeof RetryPolicy.ExponentialRetryPolicy; + static LinearRetryPolicy: typeof RetryPolicy.LinearRetryPolicy; + static notificationPayload(title: string, body: string): NotificationsPayload; + static generateUUID(): any; + constructor(configuration: ClientInstanceConfiguration); + get configuration(): ClientConfiguration; + get _config(): ClientConfiguration; + get authKey(): string | undefined; + getAuthKey(): string | undefined; + setAuthKey(authKey: string): void; + get userId(): string; + set userId(value: string); + getUserId(): string; + setUserId(value: string): void; + get filterExpression(): string | undefined; + getFilterExpression(): string | undefined; + set filterExpression(expression: string | null | undefined); + setFilterExpression(expression: string | null): void; + get cipherKey(): string | undefined; + set cipherKey(key: string | undefined); + setCipherKey(key: string): void; + set heartbeatInterval(interval: number); + setHeartbeatInterval(interval: number): void; + getVersion(): string; + _addPnsdkSuffix(name: string, suffix: string | number): void; + getUUID(): string; + setUUID(value: string): void; + get customEncrypt(): ((data: string) => string) | undefined; + get customDecrypt(): ((data: string) => string) | undefined; + channel(name: string): Channel; + channelGroup(name: string): ChannelGroup; + channelMetadata(id: string): ChannelMetadata; + userMetadata(id: string): UserMetadata; + subscriptionSet(parameters: { + channels?: string[]; + channelGroups?: string[]; + subscriptionOptions?: SubscriptionOptions; + }): SubscriptionSet; + private sendRequest; + destroy(isOffline?: boolean): void; + stop(): void; + addListener(listener: Listener): void; + removeListener(listener: Listener): void; + removeAllListeners(): void; + publish(parameters: Publish.PublishParameters, callback: ResultCallback): void; + publish(parameters: Publish.PublishParameters): Promise; + signal(parameters: Signal.SignalParameters, callback: ResultCallback): void; + signal(parameters: Signal.SignalParameters): Promise; + fire(parameters: Publish.PublishParameters, callback: ResultCallback): void; + fire(parameters: Publish.PublishParameters): Promise; + getSubscribedChannels(): string[]; + getSubscribedChannelGroups(): string[]; + subscribe(parameters: Subscription.SubscribeParameters): void; + private makeSubscribe; + unsubscribe(parameters: Presence.PresenceLeaveParameters): void; + private makeUnsubscribe; + unsubscribeAll(): void; + disconnect(): void; + reconnect(parameters?: { + timetoken?: string; + region?: number; + }): void; + private subscribeHandshake; + private subscribeReceiveMessages; + getMessageActions(parameters: MessageAction.GetMessageActionsParameters, callback: ResultCallback): void; + getMessageActions(parameters: MessageAction.GetMessageActionsParameters): Promise; + addMessageAction(parameters: MessageAction.AddMessageActionParameters, callback: ResultCallback): void; + addMessageAction(parameters: MessageAction.AddMessageActionParameters): Promise; + removeMessageAction(parameters: MessageAction.RemoveMessageActionParameters, callback: ResultCallback): void; + removeMessageAction(parameters: MessageAction.RemoveMessageActionParameters): Promise; + fetchMessages(parameters: History.FetchMessagesParameters, callback: ResultCallback): void; + fetchMessages(parameters: History.FetchMessagesParameters): Promise; + deleteMessages(parameters: History.DeleteMessagesParameters, callback: ResultCallback): void; + deleteMessages(parameters: History.DeleteMessagesParameters): Promise; + messageCounts(parameters: History.MessageCountParameters, callback: ResultCallback): void; + messageCounts(parameters: History.MessageCountParameters): Promise; + history(parameters: History.GetHistoryParameters, callback: ResultCallback): void; + history(parameters: History.GetHistoryParameters): Promise; + hereNow(parameters: Presence.HereNowParameters, callback: ResultCallback): void; + hereNow(parameters: Presence.HereNowParameters): Promise; + whereNow(parameters: Presence.WhereNowParameters, callback: ResultCallback): void; + whereNow(parameters: Presence.WhereNowParameters): Promise; + getState(parameters: Presence.GetPresenceStateParameters, callback: ResultCallback): void; + getState(parameters: Presence.GetPresenceStateParameters): Promise; + setState(parameters: Presence.SetPresenceStateParameters | Presence.SetPresenceStateWithHeartbeatParameters, callback: ResultCallback): void; + setState(parameters: Presence.SetPresenceStateParameters | Presence.SetPresenceStateWithHeartbeatParameters): Promise; + presence(parameters: { + connected: boolean; + channels?: string[]; + channelGroups?: string[]; + }): void; + private heartbeat; + private join; + private leave; + private leaveAll; + grantToken(parameters: PAM.GrantTokenParameters, callback: ResultCallback): void; + grantToken(parameters: PAM.GrantTokenParameters): Promise; + revokeToken(parameters: PAM.RevokeParameters, callback: ResultCallback): void; + revokeToken(parameters: PAM.RevokeParameters): Promise; + get token(): string | undefined; + getToken(): string | undefined; + set token(token: string | undefined); + setToken(token: string | undefined): void; + parseToken(token: string): { + version: number; + timestamp: number; + ttl: number; + resources?: Partial>> | undefined; + patterns?: Partial>> | undefined; + authorized_uuid?: string | undefined; + signature: ArrayBuffer; + meta?: Payload | undefined; + } | undefined; + grant(parameters: PAM.GrantParameters, callback: ResultCallback): void; + grant(parameters: PAM.GrantParameters): Promise; + audit(parameters: PAM.AuditParameters, callback: ResultCallback): void; + audit(parameters: PAM.AuditParameters): Promise; + get objects(): PubNubObjects; + fetchUsers(callback: ResultCallback>): void; + fetchUsers(parameters: AppContext.GetAllMetadataParameters>, callback: ResultCallback>): void; + fetchUsers(parameters?: AppContext.GetAllMetadataParameters>): Promise>; + fetchUser(callback: ResultCallback>): void; + fetchUser(parameters: AppContext.GetUUIDMetadataParameters, callback: ResultCallback>): void; + fetchUser(parameters?: AppContext.GetUUIDMetadataParameters): Promise>; + createUser(parameters: AppContext.SetUUIDMetadataParameters, callback: ResultCallback>): void; + createUser(parameters: AppContext.SetUUIDMetadataParameters): Promise>; + updateUser(parameters: AppContext.SetUUIDMetadataParameters, callback: ResultCallback>): void; + updateUser(parameters: AppContext.SetUUIDMetadataParameters): Promise>; + removeUser(callback: ResultCallback): void; + removeUser(parameters: AppContext.RemoveUUIDMetadataParameters, callback: ResultCallback): void; + removeUser(parameters?: AppContext.RemoveUUIDMetadataParameters): Promise; + fetchSpaces(callback: ResultCallback>): void; + fetchSpaces(parameters: AppContext.GetAllMetadataParameters>, callback: ResultCallback>): void; + fetchSpaces(parameters?: AppContext.GetAllMetadataParameters>): Promise>; + fetchSpace(parameters: AppContext.GetChannelMetadataParameters, callback: ResultCallback>): void; + fetchSpace(parameters: AppContext.GetChannelMetadataParameters): Promise>; + createSpace(parameters: AppContext.SetChannelMetadataParameters, callback: ResultCallback>): void; + createSpace(parameters: AppContext.SetChannelMetadataParameters): Promise>; + updateSpace(parameters: AppContext.SetChannelMetadataParameters, callback: ResultCallback>): void; + updateSpace(parameters: AppContext.SetChannelMetadataParameters): Promise>; + removeSpace(parameters: AppContext.RemoveChannelMetadataParameters, callback: ResultCallback): void; + removeSpace(parameters: AppContext.RemoveChannelMetadataParameters): Promise; + fetchMemberships(parameters: AppContext.GetMembershipsParameters | AppContext.GetMembersParameters, callback: ResultCallback | AppContext.UserMembersResponse>): void; + fetchMemberships(parameters: AppContext.GetMembershipsParameters | AppContext.GetMembersParameters): Promise | AppContext.UserMembersResponse>; + addMemberships(parameters: AppContext.SetMembershipsParameters | AppContext.SetChannelMembersParameters, callback: ResultCallback | AppContext.SetMembersResponse>): void; + addMemberships(parameters: AppContext.SetMembershipsParameters | AppContext.SetChannelMembersParameters): Promise | AppContext.SetMembersResponse>; + updateMemberships(parameters: AppContext.SetMembershipsParameters | AppContext.SetChannelMembersParameters, callback: ResultCallback | AppContext.SetMembersResponse>): void; + updateMemberships(parameters: AppContext.SetMembershipsParameters | AppContext.SetChannelMembersParameters): Promise | AppContext.SetMembersResponse>; + removeMemberships(parameters: AppContext.RemoveMembersParameters | AppContext.RemoveMembershipsParameters, callback: ResultCallback | AppContext.RemoveMembershipsResponse>): void; + removeMemberships(parameters: AppContext.RemoveMembersParameters | AppContext.RemoveMembershipsParameters): Promise>; + get channelGroups(): PubNubChannelGroups; + get push(): PubNubPushNotifications; + sendFile(parameters: FileSharing.SendFileParameters, callback: ResultCallback): void; + sendFile(parameters: FileSharing.SendFileParameters): Promise; + publishFile(parameters: FileSharing.PublishFileMessageParameters, callback: ResultCallback): void; + publishFile(parameters: FileSharing.PublishFileMessageParameters): Promise; + listFiles(parameters: FileSharing.ListFilesParameters, callback: ResultCallback): void; + listFiles(parameters: FileSharing.ListFilesParameters): Promise; + getFileUrl(parameters: FileSharing.FileUrlParameters): FileSharing.FileUrlResponse; + downloadFile(parameters: FileSharing.DownloadFileParameters, callback: ResultCallback): void; + downloadFile(parameters: FileSharing.DownloadFileParameters): Promise; + deleteFile(parameters: FileSharing.DeleteFileParameters, callback: ResultCallback): void; + deleteFile(parameters: FileSharing.DeleteFileParameters): Promise; + time(callback: ResultCallback): void; + time(): Promise; + encrypt(data: string | Payload, customCipherKey?: string): string; + decrypt(data: string, customCipherKey?: string): Payload | null; + encryptFile(file: PubNubFileInterface): Promise; + encryptFile(key: string, file: PubNubFileInterface): Promise; + decryptFile(file: PubNubFileInterface): Promise; + decryptFile(key: string | PubNubFileInterface, file?: PubNubFileInterface): Promise; +} +export {}; diff --git a/lib/types/core/pubnub-objects.d.ts b/lib/types/core/pubnub-objects.d.ts new file mode 100644 index 000000000..5dc0b3e44 --- /dev/null +++ b/lib/types/core/pubnub-objects.d.ts @@ -0,0 +1,52 @@ +import { ResultCallback, SendRequestFunction } from './types/api'; +import { PrivateClientConfiguration } from './interfaces/configuration'; +import * as AppContext from './types/api/app-context'; +export default class PubNubObjects { + private readonly configuration; + private readonly sendRequest; + private readonly keySet; + constructor(configuration: PrivateClientConfiguration, sendRequest: SendRequestFunction); + getAllUUIDMetadata(callback: ResultCallback>): void; + getAllUUIDMetadata(parameters: AppContext.GetAllMetadataParameters>, callback: ResultCallback>): void; + getAllUUIDMetadata(parameters?: AppContext.GetAllMetadataParameters>): Promise>; + _getAllUUIDMetadata(parametersOrCallback?: AppContext.GetAllMetadataParameters> | ResultCallback>, callback?: ResultCallback>): Promise | void>; + getUUIDMetadata(callback: ResultCallback>): void; + getUUIDMetadata(parameters: AppContext.GetUUIDMetadataParameters, callback: ResultCallback>): void; + getUUIDMetadata(parameters?: AppContext.GetUUIDMetadataParameters): Promise>; + _getUUIDMetadata(parametersOrCallback?: AppContext.GetUUIDMetadataParameters | ResultCallback>, callback?: ResultCallback>): Promise | void>; + setUUIDMetadata(parameters: AppContext.SetUUIDMetadataParameters, callback: ResultCallback>): void; + setUUIDMetadata(parameters: AppContext.SetUUIDMetadataParameters): Promise>; + _setUUIDMetadata(parameters: AppContext.SetUUIDMetadataParameters, callback?: ResultCallback>): Promise | void>; + removeUUIDMetadata(callback: ResultCallback): void; + removeUUIDMetadata(parameters: AppContext.RemoveUUIDMetadataParameters, callback: ResultCallback): void; + removeUUIDMetadata(parameters?: AppContext.RemoveUUIDMetadataParameters): Promise; + _removeUUIDMetadata(parametersOrCallback?: AppContext.RemoveUUIDMetadataParameters | ResultCallback, callback?: ResultCallback): Promise; + getAllChannelMetadata(callback: ResultCallback>): void; + getAllChannelMetadata(parameters: AppContext.GetAllMetadataParameters>, callback: ResultCallback>): void; + getAllChannelMetadata(parameters?: AppContext.GetAllMetadataParameters>): Promise>; + _getAllChannelMetadata(parametersOrCallback?: AppContext.GetAllMetadataParameters> | ResultCallback>, callback?: ResultCallback>): Promise | void>; + getChannelMetadata(parameters: AppContext.GetChannelMetadataParameters, callback: ResultCallback>): void; + getChannelMetadata(parameters: AppContext.GetChannelMetadataParameters): Promise>; + _getChannelMetadata(parameters: AppContext.GetChannelMetadataParameters, callback?: ResultCallback>): Promise | void>; + setChannelMetadata(parameters: AppContext.SetChannelMetadataParameters, callback: ResultCallback>): void; + setChannelMetadata(parameters: AppContext.SetChannelMetadataParameters): Promise>; + _setChannelMetadata(parameters: AppContext.SetChannelMetadataParameters, callback?: ResultCallback>): Promise | void>; + removeChannelMetadata(parameters: AppContext.RemoveChannelMetadataParameters, callback: ResultCallback): void; + removeChannelMetadata(parameters: AppContext.RemoveChannelMetadataParameters): Promise; + _removeChannelMetadata(parameters: AppContext.RemoveChannelMetadataParameters, callback?: ResultCallback): Promise; + getChannelMembers(parameters: AppContext.GetMembersParameters, callback: ResultCallback>): void; + getChannelMembers(parameters: AppContext.GetMembersParameters): Promise>; + setChannelMembers(parameters: AppContext.SetChannelMembersParameters, callback: ResultCallback>): void; + setChannelMembers(parameters: AppContext.SetChannelMembersParameters): Promise>; + removeChannelMembers(parameters: AppContext.RemoveMembersParameters, callback: ResultCallback>): void; + removeChannelMembers(parameters: AppContext.RemoveMembersParameters): Promise>; + getMemberships(callback: ResultCallback>): void; + getMemberships(parameters: AppContext.GetMembershipsParameters, callback: ResultCallback>): void; + getMemberships(parameters?: AppContext.GetMembershipsParameters): Promise>; + setMemberships(parameters: AppContext.SetMembershipsParameters, callback: ResultCallback>): void; + setMemberships(parameters: AppContext.SetMembershipsParameters): Promise>; + removeMemberships(parameters: AppContext.RemoveMembershipsParameters, callback: ResultCallback>): void; + removeMemberships(parameters: AppContext.RemoveMembershipsParameters): Promise>; + fetchMemberships(parameters: AppContext.GetMembershipsParameters | AppContext.GetMembersParameters, callback?: ResultCallback | AppContext.UserMembersResponse>): Promise | AppContext.UserMembersResponse | void>; + addMemberships(parameters: AppContext.SetMembershipsParameters | AppContext.SetChannelMembersParameters, callback?: ResultCallback | AppContext.SetMembersResponse>): Promise | AppContext.SetMembersResponse | void>; +} diff --git a/lib/types/core/pubnub-push.d.ts b/lib/types/core/pubnub-push.d.ts new file mode 100644 index 000000000..32bd72558 --- /dev/null +++ b/lib/types/core/pubnub-push.d.ts @@ -0,0 +1,15 @@ +import { KeySet, ResultCallback, SendRequestFunction, StatusCallback } from './types/api'; +import * as Push from './types/api/push'; +export default class PubNubPushNotifications { + private readonly keySet; + private readonly sendRequest; + constructor(keySet: KeySet, sendRequest: SendRequestFunction); + listChannels(parameters: Push.ListDeviceChannelsParameters, callback: ResultCallback): void; + listChannels(parameters: Push.ListDeviceChannelsParameters): Promise; + addChannels(parameters: Push.ManageDeviceChannelsParameters, callback: StatusCallback): void; + addChannels(parameters: Push.ManageDeviceChannelsParameters): Promise; + removeChannels(parameters: Push.ManageDeviceChannelsParameters, callback: StatusCallback): void; + removeChannels(parameters: Push.ManageDeviceChannelsParameters): Promise; + deleteDevice(parameters: Push.RemoveDeviceParameters, callback: StatusCallback): void; + deleteDevice(parameters: Push.RemoveDeviceParameters): Promise; +} diff --git a/lib/types/core/types/api/access-panager.d.ts b/lib/types/core/types/api/access-panager.d.ts new file mode 100644 index 000000000..70ad4f31e --- /dev/null +++ b/lib/types/core/types/api/access-panager.d.ts @@ -0,0 +1,124 @@ +export type Metadata = Record; +export type ChannelTokenPermissions = { + read?: boolean; + write?: boolean; + get?: boolean; + manage?: boolean; + update?: boolean; + join?: boolean; + delete?: boolean; +}; +type SpaceTokenPermissions = ChannelTokenPermissions; +export type ChannelGroupTokenPermissions = { + read?: boolean; + manage?: boolean; +}; +export type UuidTokenPermissions = { + get?: boolean; + update?: boolean; + delete?: boolean; +}; +type UserTokenPermissions = UuidTokenPermissions; +export type ObjectsGrantTokenParameters = { + ttl: number; + resources?: { + spaces?: Record; + users?: Record; + }; + patterns?: { + spaces?: Record; + users?: Record; + }; + meta?: Metadata; + authorizedUserId?: string; +}; +export type GrantTokenParameters = { + ttl: number; + resources?: { + uuids?: Record; + channels?: Record; + groups?: Record; + }; + patterns?: { + uuids?: Record; + channels?: Record; + groups?: Record; + }; + meta?: Metadata; + authorized_uuid?: string; +}; +export type GrantTokenResponse = string; +export type RevokeParameters = { + token: string; +}; +export type RevokeTokenResponse = Record; +type ChannelPermissions = { + r?: 0 | 1; + w?: 0 | 1; + d?: 0 | 1; + g?: 0 | 1; + u?: 0 | 1; + m?: 0 | 1; + j?: 0 | 1; + ttl?: number; +}; +type ChannelGroupPermissions = { + r?: 0 | 1; + m?: 0 | 1; + ttl?: number; +}; +type UserPermissions = { + g?: 0 | 1; + u?: 0 | 1; + d?: 0 | 1; + ttl?: number; +}; +type BaseAuditResponse = { + level: Level; + subscribe_key: string; + ttl?: number; +}; +type AuthKeysPermissions = { + auths: Record; +}; +type ChannelPermissionsResponse = BaseAuditResponse<'channel+auth'> & { + channel: string; +} & AuthKeysPermissions; +type ChannelsPermissionsResponse = BaseAuditResponse<'channel'> & { + channels: Record>; +}; +type ChannelGroupPermissionsResponse = BaseAuditResponse<'channel-group+auth'> & { + 'channel-group': string; +} & AuthKeysPermissions; +type ChannelGroupsPermissionsResponse = BaseAuditResponse<'channel'> & { + 'channel-groups': Record>; +}; +type UserPermissionsResponse = BaseAuditResponse<'user'> & { + channel: string; +} & AuthKeysPermissions; +type SubKeyPermissionsResponse = BaseAuditResponse<'subkey'> & { + channels: Record>; + 'channel-groups': Record>; + objects: Record>; +}; +export type PermissionsResponse = ChannelPermissionsResponse | ChannelsPermissionsResponse | ChannelGroupPermissionsResponse | ChannelGroupsPermissionsResponse | UserPermissionsResponse | SubKeyPermissionsResponse; +export type AuditParameters = { + channel?: string; + channelGroup?: string; + authKeys?: string[]; +}; +export type GrantParameters = { + channels?: string[]; + channelGroups?: string[]; + uuids?: string[]; + authKeys?: string[]; + read?: boolean; + write?: boolean; + delete?: boolean; + get?: boolean; + update?: boolean; + manage?: boolean; + join?: boolean; + ttl?: number; +}; +export {}; diff --git a/lib/types/core/types/api/app-context.d.ts b/lib/types/core/types/api/app-context.d.ts new file mode 100644 index 000000000..eea32fe4e --- /dev/null +++ b/lib/types/core/types/api/app-context.d.ts @@ -0,0 +1,207 @@ +type PartialNullable = { + [P in keyof T]?: T[P] | null; +}; +export type CustomData = { + [key: string]: string | number | boolean | null; +}; +type ObjectParameters = { + custom?: Custom; +}; +export type ObjectData = { + id: string; + updated: string; + eTag: string; + custom?: Custom | null; +}; +type ObjectsRelation = { + id: string; + status?: string; + custom?: Custom; +}; +type Page = { + next?: string; + prev?: string; +}; +type IncludeOptions = { + totalCount?: boolean; + customFields?: boolean; +}; +type MembershipsIncludeOptions = IncludeOptions & { + channelFields?: boolean; + customChannelFields?: boolean; + statusField?: boolean; + channelStatusField?: boolean; + channelTypeField?: boolean; +}; +type MembersIncludeOptions = IncludeOptions & { + UUIDFields?: boolean; + customUUIDFields?: boolean; + statusField?: boolean; + UUIDStatusField?: boolean; + UUIDTypeField?: boolean; +}; +type PagedRequestParameters = { + include?: Include; + filter?: string; + sort?: Sort; + limit?: number; + page?: Page; +}; +type ObjectResponse = { + status: number; + data: ObjectType; +}; +type PagedResponse = ObjectResponse & { + totalCount?: number; + next?: string; + prev?: string; +}; +type MetadataSortingOptions = keyof Omit | ({ + [K in keyof Omit]?: 'asc' | 'desc' | null; +} & { + [key: `custom.${string}`]: 'asc' | 'desc' | null; +}); +type MembershipsSortingOptions = 'channel.id' | 'channel.name' | 'channel.description' | 'channel.updated' | 'space.id' | 'space.name' | 'space.description' | 'space.updated' | 'updated' | { + 'channel.id'?: 'asc' | 'desc' | null; + 'channel.name'?: 'asc' | 'desc' | null; + 'channel.description'?: 'asc' | 'desc' | null; + 'channel.updated'?: 'asc' | 'desc' | null; + 'space.id'?: 'asc' | 'desc' | null; + 'space.name'?: 'asc' | 'desc' | null; + 'space.description'?: 'asc' | 'desc' | null; + 'space.updated'?: 'asc' | 'desc' | null; + updated?: 'asc' | 'desc' | null; +}; +type MembersSortingOptions = 'uuid.id' | 'uuid.name' | 'uuid.updated' | 'user.id' | 'user.name' | 'user.updated' | 'updated' | { + 'uuid.id'?: 'asc' | 'desc' | null; + 'uuid.name'?: 'asc' | 'desc' | null; + 'uuid.updated'?: 'asc' | 'desc' | null; + 'user.id'?: 'asc' | 'desc' | null; + 'user.name'?: 'asc' | 'desc' | null; + 'user.updated'?: 'asc' | 'desc' | null; + updated?: 'asc' | 'desc' | null; +}; +export type GetAllMetadataParameters = PagedRequestParameters>; +type UUIDMetadataFields = { + name?: string; + email?: string; + externalId?: string; + profileUrl?: string; + type?: string; + status?: string; +}; +type UUIDMetadata = ObjectParameters & Partial; +export type UUIDMetadataObject = ObjectData & PartialNullable; +export type GetAllUUIDMetadataResponse = PagedResponse>; +export type GetUUIDMetadataParameters = { + uuid?: string; + userId?: string; + include?: Omit; +}; +export type GetUUIDMetadataResponse = ObjectResponse>; +export type SetUUIDMetadataParameters = { + uuid?: string; + userId?: string; + data: UUIDMetadata; + include?: Omit; +}; +export type SetUUIDMetadataResponse = ObjectResponse>; +export type RemoveUUIDMetadataParameters = { + uuid?: string; + userId?: string; +}; +export type RemoveUUIDMetadataResponse = ObjectResponse>; +type ChannelMetadataFields = { + name?: string; + description?: string; + type?: string; + status?: string; +}; +type ChannelMetadata = ObjectParameters & Partial; +export type ChannelMetadataObject = ObjectData & PartialNullable; +export type GetAllChannelMetadataResponse = PagedResponse>; +export type GetChannelMetadataParameters = { + channel: string; + spaceId?: string; + include?: Omit; +}; +export type GetChannelMetadataResponse = ObjectResponse>; +export type SetChannelMetadataParameters = { + channel: string; + spaceId?: string; + data: ChannelMetadata; + include?: Omit; +}; +export type SetChannelMetadataResponse = ObjectResponse>; +export type RemoveChannelMetadataParameters = { + channel: string; + spaceId?: string; +}; +export type RemoveChannelMetadataResponse = ObjectResponse>; +type MembershipsObject = Omit, 'id'> & { + channel: ChannelMetadataObject | { + id: string; + }; +}; +type MembershipsResponse = PagedResponse>; +export type GetMembershipsParameters = PagedRequestParameters & { + uuid?: string; + userId?: string; +}; +export type GetMembershipsResponse = MembershipsResponse; +export type SetMembershipsParameters = PagedRequestParameters, MembershipsSortingOptions> & { + uuid?: string; + userId?: string; + channels: Array>; + spaces?: Array, 'id'> & { + spaceId: string; + })>; +}; +export type SetMembershipsResponse = MembershipsResponse; +export type RemoveMembershipsParameters = PagedRequestParameters & { + uuid?: string; + userId?: string; + channels: string[]; + spaceIds?: string[]; +}; +export type RemoveMembershipsResponse = MembershipsResponse; +type MembersObject = Omit, 'id'> & { + uuid: UUIDMetadataObject | { + id: string; + }; +}; +type MembersResponse = PagedResponse>; +export type GetMembersParameters = PagedRequestParameters & { + channel: string; + spaceId?: string; +}; +export type GetMembersResponse = MembersResponse; +export type SetChannelMembersParameters = PagedRequestParameters, MembersSortingOptions> & { + channel: string; + spaceId?: string; + uuids: Array>; + users?: Array, 'id'> & { + userId: string; + })>; +}; +export type SetMembersResponse = MembersResponse; +export type RemoveMembersParameters = PagedRequestParameters & { + channel: string; + spaceId?: string; + uuids: string[]; + userIds?: string[]; +}; +export type RemoveMembersResponse = MembersResponse; +type UserMembersObject = Omit, 'id'> & { + user: UUIDMetadataObject | { + id: string; + }; +}; +export type UserMembersResponse = PagedResponse>; +type SpaceMembershipObject = Omit, 'id'> & { + space: ChannelMetadataObject | { + id: string; + }; +}; +export type SpaceMembershipsResponse = PagedResponse>; +export {}; diff --git a/lib/types/core/types/api/channel-groups.d.ts b/lib/types/core/types/api/channel-groups.d.ts new file mode 100644 index 000000000..c2408d009 --- /dev/null +++ b/lib/types/core/types/api/channel-groups.d.ts @@ -0,0 +1,18 @@ +export type ManageChannelGroupChannelsParameters = { + channelGroup: string; + channels: string[]; +}; +export type ManageChannelGroupChannelsResponse = Record; +export type ListAllChannelGroupsResponse = { + groups: string[]; +}; +export type ListChannelGroupChannelsParameters = { + channelGroup: string; +}; +export type ListChannelGroupChannelsResponse = { + channels: string[]; +}; +export type DeleteChannelGroupParameters = { + channelGroup: string; +}; +export type DeleteChannelGroupResponse = Record; diff --git a/lib/types/core/types/api/file-sharing.d.ts b/lib/types/core/types/api/file-sharing.d.ts new file mode 100644 index 000000000..dbc5552a4 --- /dev/null +++ b/lib/types/core/types/api/file-sharing.d.ts @@ -0,0 +1,85 @@ +import { PubNubFileInterface } from '../file'; +import { Payload } from './index'; +export type SharedFile = { + name: string; + id: string; + size: number; + created: string; +}; +export type ListFilesParameters = { + channel: string; + limit?: number; + next?: string; +}; +export type ListFilesResponse = { + status: number; + data: SharedFile[]; + next: string; + count: number; +}; +export type SendFileParameters = Omit & { + channel: string; + file: FileParameters; +}; +export type SendFileResponse = PublishFileMessageResponse & { + status: number; + name: string; + id: string; +}; +export type UploadFileParameters = { + fileId: string; + fileName: string; + file: PubNubFileInterface; + uploadUrl: string; + formFields: { + name: string; + value: string; + }[]; +}; +export type UploadFileResponse = { + status: number; + message: Payload; +}; +export type GenerateFileUploadUrlParameters = { + channel: string; + name: string; +}; +export type GenerateFileUploadUrlResponse = { + id: string; + name: string; + url: string; + formFields: { + name: string; + value: string; + }[]; +}; +export type PublishFileMessageParameters = { + channel: string; + message?: Payload; + cipherKey?: string; + fileId: string; + fileName: string; + storeInHistory?: boolean; + ttl?: number; + meta?: Payload; +}; +export type PublishFileMessageResponse = { + timetoken: string; +}; +export type DownloadFileParameters = FileUrlParameters & { + cipherKey?: string; +}; +export type FileUrlParameters = { + channel: string; + id: string; + name: string; +}; +export type FileUrlResponse = string; +export type DeleteFileParameters = { + channel: string; + id: string; + name: string; +}; +export type DeleteFileResponse = { + status: number; +}; diff --git a/lib/types/core/types/api/history.d.ts b/lib/types/core/types/api/history.d.ts new file mode 100644 index 000000000..cdb748fc2 --- /dev/null +++ b/lib/types/core/types/api/history.d.ts @@ -0,0 +1,105 @@ +import { Payload } from './index'; +export type GetHistoryParameters = { + channel: string; + count?: number; + includeMeta?: boolean; + start?: string; + end?: string; + reverse?: boolean; + stringifiedTimeToken?: boolean; +}; +export type GetHistoryResponse = { + messages: { + entry: Payload; + timetoken: string | number; + meta?: Payload; + error?: string; + }[]; + startTimeToken: string | number; + endTimeToken: string | number; +}; +export declare enum PubNubMessageType { + Message = -1, + Files = 4 +} +export type Actions = { + [t: string]: { + [v: string]: { + uuid: string; + actionTimetoken: string; + }; + }; +}; +export type MoreActions = { + url: string; + start: string; + max: number; +}; +type BaseFetchedMessage = { + channel: string; + timetoken: string | number; + uuid?: string; + meta?: Payload; + error?: string; +}; +export type RegularMessage = BaseFetchedMessage & { + message: Payload; + messageType?: PubNubMessageType.Message; +}; +export type FileMessage = BaseFetchedMessage & { + message: { + message?: Payload; + file: { + id: string; + name: string; + 'mime-type': string; + size: number; + url: string; + }; + }; + messageType?: PubNubMessageType.Files; +}; +export type FetchedMessage = RegularMessage | FileMessage; +export type FetchedMessageWithActions = FetchedMessage & { + actions?: Actions; + data?: Actions; +}; +export type FetchMessagesParameters = { + channels: string[]; + count?: number; + includeMessageType?: boolean; + includeUUID?: boolean; + includeUuid?: boolean; + includeMeta?: boolean; + includeMessageActions?: boolean; + start?: string; + end?: string; + stringifiedTimeToken?: boolean; +}; +export type FetchMessagesForChannelsResponse = { + channels: { + [p: string]: FetchedMessage[]; + }; +}; +export type FetchMessagesWithActionsResponse = { + channels: { + [p: string]: FetchedMessageWithActions[]; + }; + more: MoreActions; +}; +export type FetchMessagesResponse = FetchMessagesForChannelsResponse | FetchMessagesWithActionsResponse; +export type MessageCountParameters = { + channels: string[]; + channelTimetokens?: string[]; + timetoken?: string; +}; +export type MessageCountResponse = { + channels: Record; +}; +export type DeleteMessagesParameters = { + channel: string; + start?: string; + end?: string; +}; +export type DeleteMessagesResponse = Record; +export {}; diff --git a/lib/types/core/types/api/index.d.ts b/lib/types/core/types/api/index.d.ts new file mode 100644 index 000000000..a76d7e94e --- /dev/null +++ b/lib/types/core/types/api/index.d.ts @@ -0,0 +1,33 @@ +import { AbstractRequest } from '../../components/request'; +import RequestOperation from '../../constants/operations'; +import StatusCategory from '../../constants/categories'; +export type KeySet = { + subscribeKey: string; + publishKey?: string; + secretKey?: string; +}; +export type SendRequestFunction = (request: AbstractRequest, callback?: ResultCallback) => Promise; +export type ResultCallback = (status: Status, response: ResponseType | null) => void; +export type StatusCallback = (status: Status) => void; +export type Status = { + error: boolean; + category: StatusCategory; + operation?: RequestOperation; + statusCode: number; + errorData?: Error | Payload; + [p: string]: Payload | Error | undefined; +}; +export type StatusEvent = { + category: StatusCategory; + operation?: RequestOperation; + error?: string | boolean; + affectedChannels?: string[]; + subscribedChannels?: string[]; + affectedChannelGroups?: string[]; + lastTimetoken?: number | string; + currentTimetoken?: number | string; +}; +export type Query = Record; +export type Payload = string | number | boolean | { + [key: string]: Payload | null; +} | Payload[]; diff --git a/lib/types/core/types/api/message-action.d.ts b/lib/types/core/types/api/message-action.d.ts new file mode 100644 index 000000000..aee3c2454 --- /dev/null +++ b/lib/types/core/types/api/message-action.d.ts @@ -0,0 +1,44 @@ +export type MessageAction = { + type: string; + value: string; + uuid: string; + actionTimetoken: string; + messageTimetoken: string; +}; +export type MoreMessageActions = { + url: string; + start: string; + end: string; + limit: number; +}; +export type AddMessageActionParameters = { + channel: string; + messageTimetoken: string; + action: { + type: string; + value: string; + }; +}; +export type AddMessageActionResponse = { + data: MessageAction; +}; +export type GetMessageActionsParameters = { + channel: string; + start?: string; + end?: string; + limit?: number; +}; +export type GetMessageActionsResponse = { + data: MessageAction[]; + start: string | null; + end: string | null; + more?: MoreMessageActions; +}; +export type RemoveMessageActionParameters = { + channel: string; + messageTimetoken: string; + actionTimetoken: string; +}; +export type RemoveMessageActionResponse = { + data: Record; +}; diff --git a/lib/types/core/types/api/presence.d.ts b/lib/types/core/types/api/presence.d.ts new file mode 100644 index 000000000..ef1fb4b1f --- /dev/null +++ b/lib/types/core/types/api/presence.d.ts @@ -0,0 +1,61 @@ +import { Payload } from './index'; +export type GetPresenceStateParameters = { + uuid?: string; + channels?: string[]; + channelGroups?: string[]; +}; +export type GetPresenceStateResponse = { + channels: Record; +}; +export type SetPresenceStateParameters = { + channels?: string[]; + channelGroups?: string[]; + state: Payload; +}; +export type SetPresenceStateWithHeartbeatParameters = { + channels?: string[]; + state: Payload; + withHeartbeat: boolean; +}; +export type SetPresenceStateResponse = { + state: Payload; +}; +export type PresenceHeartbeatParameters = { + heartbeat: number; + channels?: string[]; + channelGroups?: string[]; + state?: Payload; +}; +export type PresenceHeartbeatResponse = Record; +export type PresenceLeaveParameters = { + channels?: string[]; + channelGroups?: string[]; +}; +export type PresenceLeaveResponse = Record; +export type HereNowParameters = { + channels?: string[]; + channelGroups?: string[]; + includeUUIDs?: boolean; + includeState?: boolean; + queryParameters?: Record; +}; +export type HereNowResponse = { + totalChannels: number; + totalOccupancy: number; + channels: { + [p: string]: { + occupants: { + uuid: string; + state?: Payload | null; + }[]; + name: string; + occupancy: number; + }; + }; +}; +export type WhereNowParameters = { + uuid?: string; +}; +export type WhereNowResponse = { + channels: string[]; +}; diff --git a/lib/types/core/types/api/push-notifications.d.ts b/lib/types/core/types/api/push-notifications.d.ts new file mode 100644 index 000000000..8a71a4dee --- /dev/null +++ b/lib/types/core/types/api/push-notifications.d.ts @@ -0,0 +1,14 @@ +type PushGateway = 'apns2' | 'gcm'; +type DevicePush = { + device: string; + pushGateway: PushGateway; +}; +export type ManageDeviceChannelsParameters = { + channels: string[]; +} & DevicePush; +export type ListDeviceChannelsParameters = DevicePush; +export type ListDeviceChannelsResponse = { + channels: string[]; +}; +export type DeleteDeviceParameters = DevicePush; +export {}; diff --git a/lib/types/core/types/api/push.d.ts b/lib/types/core/types/api/push.d.ts new file mode 100644 index 000000000..1b8cf0763 --- /dev/null +++ b/lib/types/core/types/api/push.d.ts @@ -0,0 +1,32 @@ +type ManagedDeviceChannels = { + channels: string[]; + device: string; + start?: string; + count?: number; +}; +type ListFCMDeviceChannelsParameters = Omit; +type ListAPNSDeviceChannelsParameters = Omit; +type ListAPNS2DeviceChannelsParameters = Omit; +export type ListDeviceChannelsParameters = ListFCMDeviceChannelsParameters | ListAPNSDeviceChannelsParameters | ListAPNS2DeviceChannelsParameters; +export type ListDeviceChannelsResponse = { + channels: string[]; +}; +type ManageFCMDeviceChannelsParameters = ManagedDeviceChannels & { + pushGateway: 'gcm'; +}; +type ManageAPNSDeviceChannelsParameters = ManagedDeviceChannels & { + pushGateway: 'apns'; +}; +type ManageAPNS2DeviceChannelsParameters = ManagedDeviceChannels & { + pushGateway: 'apns2'; + environment?: 'development' | 'production'; + topic: string; +}; +export type ManageDeviceChannelsParameters = ManageFCMDeviceChannelsParameters | ManageAPNSDeviceChannelsParameters | ManageAPNS2DeviceChannelsParameters; +export type ManageDeviceChannelsResponse = Record; +type RemoveFCMDeviceParameters = Omit; +type RemoveAPNSDeviceParameters = Omit; +type RemoveAPNS2DeviceParameters = Omit; +export type RemoveDeviceParameters = RemoveFCMDeviceParameters | RemoveAPNSDeviceParameters | RemoveAPNS2DeviceParameters; +export type RemoveDeviceResponse = Record; +export {}; diff --git a/lib/types/core/types/api/subscription.d.ts b/lib/types/core/types/api/subscription.d.ts new file mode 100644 index 000000000..24b2396ed --- /dev/null +++ b/lib/types/core/types/api/subscription.d.ts @@ -0,0 +1,96 @@ +import { RequestParameters as SubscribeRequestParameters, VSPMembershipObjectData, AppContextObjectData, MessageActionData, PubNubEventType, SpaceObjectData, UserObjectData, PresenceData, FileData } from '../../endpoints/subscribe'; +import { AbortSignal } from '../../components/abort_signal'; +import { Payload } from './index'; +export type SubscriptionCursor = { + timetoken: string | number; + region?: number; +}; +type Event = { + channel: string; + subscription: string | null; + timetoken: string; +}; +type LegacyEvent = Event & { + actualChannel?: string | null; + subscribedChannel?: string; +}; +export type Presence = LegacyEvent & PresenceData; +type PresenceEvent = { + type: PubNubEventType.Presence; + data: Presence; +}; +type PublishedData = { + publisher?: string; + userMetadata?: { + [p: string]: Payload; + }; + message: Payload; +}; +export type Message = LegacyEvent & PublishedData & { + error?: string; +}; +type MessageEvent = { + type: PubNubEventType.Message; + data: Message; +}; +export type Signal = Event & PublishedData; +type SignalEvent = { + type: PubNubEventType.Signal; + data: Signal; +}; +export type MessageAction = Event & Omit & { + publisher?: string; + data: MessageActionData['data'] & { + uuid: string; + }; +}; +type MessageActionEvent = { + type: PubNubEventType.MessageAction; + data: MessageAction; +}; +export type AppContextObject = Event & { + message: AppContextObjectData; +}; +export type UserAppContextObject = Omit & { + spaceId: string; + message: UserObjectData; +}; +export type SpaceAppContextObject = Omit & { + spaceId: string; + message: SpaceObjectData; +}; +export type VSPMembershipAppContextObject = Omit & { + spaceId: string; + message: VSPMembershipObjectData; +}; +type AppContextEvent = { + type: PubNubEventType.AppContext; + data: AppContextObject; +}; +export type File = Event & Omit & Omit & { + message?: Payload; + file?: FileData['file'] & { + url: string; + }; + error?: string; +}; +type FileEvent = { + type: PubNubEventType.Files; + data: File; +}; +export type CancelableSubscribeParameters = Omit & { + abortSignal: AbortSignal; +}; +export type SubscribeParameters = { + channels?: string[]; + channelGroups?: string[]; + timetoken?: string | number; + withPresence?: boolean; + state?: Record; + withHeartbeats?: boolean; +}; +export type SubscriptionResponse = { + cursor: SubscriptionCursor; + messages: (PresenceEvent | MessageEvent | SignalEvent | MessageActionEvent | AppContextEvent | FileEvent)[]; +}; +export {}; diff --git a/lib/types/core/types/file.d.ts b/lib/types/core/types/file.d.ts new file mode 100644 index 000000000..fc6d3d7f4 --- /dev/null +++ b/lib/types/core/types/file.d.ts @@ -0,0 +1,24 @@ +export type PubNubBasicFileParameters = { + data: string | ArrayBuffer; + name: string; + mimeType?: string; +}; +export interface PubNubFileInterface { + name: string; + mimeType?: string; + contentLength?: number; + toArrayBuffer(): Promise; + toFileUri(): Promise>; +} +export interface PubNubFileConstructor { + supportsBlob: boolean; + supportsFile: boolean; + supportsBuffer: boolean; + supportsStream: boolean; + supportsString: boolean; + supportsArrayBuffer: boolean; + supportsEncryptFile: boolean; + supportsFileUri: boolean; + create(file: ConstructorParameters): File; + new (file: ConstructorParameters): File; +} diff --git a/lib/types/core/types/transport-request.d.ts b/lib/types/core/types/transport-request.d.ts new file mode 100644 index 000000000..db7da1684 --- /dev/null +++ b/lib/types/core/types/transport-request.d.ts @@ -0,0 +1,24 @@ +import { PubNubFileInterface } from './file'; +import { Query } from './api'; +export declare enum TransportMethod { + GET = "GET", + POST = "POST", + PATCH = "PATCH", + DELETE = "DELETE", + LOCAL = "LOCAL" +} +export type CancellationController = { + abort: () => void; +}; +export type TransportRequest = { + origin?: string; + path: string; + queryParameters?: Query; + method: TransportMethod; + headers?: Record; + formData?: Record[]; + body?: ArrayBuffer | PubNubFileInterface | string; + timeout: number; + cancellable: boolean; + identifier: string; +}; diff --git a/lib/types/core/types/transport-response.d.ts b/lib/types/core/types/transport-response.d.ts new file mode 100644 index 000000000..6c059d060 --- /dev/null +++ b/lib/types/core/types/transport-response.d.ts @@ -0,0 +1,6 @@ +export type TransportResponse = { + url: string; + status: number; + headers: Record; + body?: ArrayBuffer; +}; diff --git a/lib/types/core/utils.d.ts b/lib/types/core/utils.d.ts new file mode 100644 index 000000000..148db9a49 --- /dev/null +++ b/lib/types/core/utils.d.ts @@ -0,0 +1,6 @@ +import { Query } from './types/api'; +export declare const encodeString: (input: string | number) => string; +export declare const encodeNames: (names: string[], defaultString?: string) => string; +export declare const removeSingleOccurrence: (source: string[], elementsToRemove: string[]) => string[]; +export declare const findUniqueCommonElements: (a: string[], b: string[]) => string[]; +export declare const queryStringFromObject: (query: Query) => string; diff --git a/lib/types/crypto/index.d.ts b/lib/types/crypto/index.d.ts new file mode 100644 index 000000000..e69de29bb diff --git a/lib/types/crypto/modules/NodeCryptoModule/ICryptor.d.ts b/lib/types/crypto/modules/NodeCryptoModule/ICryptor.d.ts new file mode 100644 index 000000000..934139069 --- /dev/null +++ b/lib/types/crypto/modules/NodeCryptoModule/ICryptor.d.ts @@ -0,0 +1,18 @@ +/// +/// +export type EncryptedDataType = { + data: Buffer | string; + metadata: Buffer | null; +}; +export type EncryptedStream = { + stream: NodeJS.ReadableStream; + metadataLength: number; + metadata?: Buffer | undefined; +}; +export interface ICryptor { + get identifier(): string; + encrypt(data: BufferSource | string): EncryptedDataType; + encryptStream(stream: NodeJS.ReadableStream): Promise; + decrypt(data: EncryptedDataType): ArrayBuffer; + decryptStream(stream: EncryptedStream): Promise; +} diff --git a/lib/types/crypto/modules/NodeCryptoModule/ILegacyCryptor.d.ts b/lib/types/crypto/modules/NodeCryptoModule/ILegacyCryptor.d.ts new file mode 100644 index 000000000..b41a01098 --- /dev/null +++ b/lib/types/crypto/modules/NodeCryptoModule/ILegacyCryptor.d.ts @@ -0,0 +1,11 @@ +import PubNubFile, { PubNubFileParameters } from '../../../file/modules/node'; +import { PubNubFileConstructor } from '../../../core/types/file'; +import { Payload } from '../../../core/types/api'; +import { EncryptedDataType } from './ICryptor'; +export interface ILegacyCryptor { + get identifier(): string; + encrypt(data: string): EncryptedDataType; + encryptFile(file: PubNubFile, File: PubNubFileConstructor): Promise; + decrypt(data: EncryptedDataType): Payload | null; + decryptFile(file: PubNubFile, File: PubNubFileConstructor): Promise; +} diff --git a/lib/types/crypto/modules/NodeCryptoModule/aesCbcCryptor.d.ts b/lib/types/crypto/modules/NodeCryptoModule/aesCbcCryptor.d.ts new file mode 100644 index 000000000..ac56f1db9 --- /dev/null +++ b/lib/types/crypto/modules/NodeCryptoModule/aesCbcCryptor.d.ts @@ -0,0 +1,25 @@ +/// +/// +/// +import { PassThrough } from 'stream'; +import { ICryptor, EncryptedDataType, EncryptedStream } from './ICryptor'; +export default class AesCbcCryptor implements ICryptor { + static BLOCK_SIZE: number; + static encoder: TextEncoder; + cipherKey: string; + constructor({ cipherKey }: { + cipherKey: string; + }); + encrypt(data: ArrayBuffer | string): EncryptedDataType; + encryptStream(stream: NodeJS.ReadableStream): Promise<{ + stream: PassThrough; + metadata: Buffer; + metadataLength: number; + }>; + decrypt(input: EncryptedDataType): ArrayBuffer; + decryptStream(stream: EncryptedStream): Promise; + get identifier(): string; + private get algo(); + private getIv; + private getKey; +} diff --git a/lib/types/crypto/modules/NodeCryptoModule/legacyCryptor.d.ts b/lib/types/crypto/modules/NodeCryptoModule/legacyCryptor.d.ts new file mode 100644 index 000000000..39bb14f3d --- /dev/null +++ b/lib/types/crypto/modules/NodeCryptoModule/legacyCryptor.d.ts @@ -0,0 +1,18 @@ +import PubNubFile, { PubNubFileParameters } from '../../../file/modules/node'; +import { CryptorConfiguration } from '../../../core/interfaces/crypto-module'; +import Crypto from '../../../core/components/cryptography/index'; +import { PubNubFileConstructor } from '../../../core/types/file'; +import { ILegacyCryptor } from './ILegacyCryptor'; +import { EncryptedDataType } from './ICryptor'; +import FileCryptor from '../node'; +export default class LegacyCryptor implements ILegacyCryptor { + config: CryptorConfiguration; + fileCryptor: FileCryptor; + cryptor: Crypto; + constructor(config: CryptorConfiguration); + encrypt(data: string): EncryptedDataType; + encryptFile(file: PubNubFile, File: PubNubFileConstructor): Promise; + decrypt(encryptedData: EncryptedDataType): import("../../../core/types/api").Payload | null; + decryptFile(file: PubNubFile, File: PubNubFileConstructor): Promise; + get identifier(): string; +} diff --git a/lib/types/crypto/modules/NodeCryptoModule/nodeCryptoModule.d.ts b/lib/types/crypto/modules/NodeCryptoModule/nodeCryptoModule.d.ts new file mode 100644 index 000000000..a55a0ce33 --- /dev/null +++ b/lib/types/crypto/modules/NodeCryptoModule/nodeCryptoModule.d.ts @@ -0,0 +1,26 @@ +import { AbstractCryptoModule, CryptorConfiguration } from '../../../core/interfaces/crypto-module'; +import PubNubFile, { PubNubFileParameters } from '../../../file/modules/node'; +import { PubNubFileConstructor } from '../../../core/types/file'; +import { ICryptor } from './ICryptor'; +import { ILegacyCryptor } from './ILegacyCryptor'; +import AesCbcCryptor from './aesCbcCryptor'; +import LegacyCryptor from './legacyCryptor'; +export { LegacyCryptor, AesCbcCryptor }; +type CryptorType = ICryptor | ILegacyCryptor; +export declare class CryptoModule extends AbstractCryptoModule { + static LEGACY_IDENTIFIER: string; + static legacyCryptoModule(config: CryptorConfiguration): CryptoModule; + static aesCbcCryptoModule(config: CryptorConfiguration): CryptoModule; + static withDefaultCryptor(defaultCryptor: CryptorType): CryptoModule; + encrypt(data: ArrayBuffer | string): string | ArrayBuffer; + encryptFile(file: PubNubFile, File: PubNubFileConstructor): Promise; + decrypt(data: ArrayBuffer | string): ArrayBuffer | import("../../../core/types/api").Payload | null; + decryptFile(file: PubNubFile, File: PubNubFileConstructor): Promise; + private getLegacyCryptor; + private getCryptorFromId; + private getCryptor; + private getHeaderData; + private concatArrayBuffer; + private onStreamReadable; + private decryptLegacyFileStream; +} diff --git a/lib/types/crypto/modules/node.d.ts b/lib/types/crypto/modules/node.d.ts new file mode 100644 index 000000000..0a35ba46b --- /dev/null +++ b/lib/types/crypto/modules/node.d.ts @@ -0,0 +1,23 @@ +/// +/// +import { Readable, PassThrough, Transform } from 'stream'; +import { Buffer } from 'buffer'; +import PubNubFile, { PubNubFileParameters } from '../../file/modules/node'; +import { Cryptography } from '../../core/interfaces/cryptography'; +import { PubNubFileConstructor } from '../../core/types/file'; +export default class NodeCryptography implements Cryptography { + static IV_LENGTH: number; + encrypt(key: string, input: string | ArrayBuffer | Buffer | Readable): Promise; + private encryptBuffer; + private encryptStream; + private encryptString; + encryptFile(key: string, file: PubNubFile, File: PubNubFileConstructor): Promise; + decrypt(key: string, input: string | ArrayBuffer | Buffer | Readable): Promise; + private decryptBuffer; + private decryptStream; + private decryptString; + decryptFile(key: string, file: PubNubFile, File: PubNubFileConstructor): Promise; + private get algo(); + private getKey; + private getIv; +} diff --git a/lib/types/entities/Channel.d.ts b/lib/types/entities/Channel.d.ts new file mode 100644 index 000000000..fdeb23a76 --- /dev/null +++ b/lib/types/entities/Channel.d.ts @@ -0,0 +1,11 @@ +import type { PubNubCore as PubNub } from '../core/pubnub-common'; +import EventEmitter from '../core/components/eventEmitter'; +import { SubscriptionOptions } from './commonTypes'; +import { Subscription } from './Subscription'; +export declare class Channel { + private readonly eventEmitter; + private readonly pubnub; + private readonly name; + constructor(channelName: string, eventEmitter: EventEmitter, pubnub: PubNub); + subscription(subscriptionOptions?: SubscriptionOptions): Subscription; +} diff --git a/lib/types/entities/ChannelGroup.d.ts b/lib/types/entities/ChannelGroup.d.ts new file mode 100644 index 000000000..a1c383d59 --- /dev/null +++ b/lib/types/entities/ChannelGroup.d.ts @@ -0,0 +1,11 @@ +import type { PubNubCore as PubNub } from '../core/pubnub-common'; +import EventEmitter from '../core/components/eventEmitter'; +import { SubscriptionOptions } from './commonTypes'; +import { Subscription } from './Subscription'; +export declare class ChannelGroup { + private readonly eventEmitter; + private readonly pubnub; + private readonly name; + constructor(channelGroup: string, eventEmitter: EventEmitter, pubnub: PubNub); + subscription(subscriptionOptions?: SubscriptionOptions): Subscription; +} diff --git a/lib/types/entities/ChannelMetadata.d.ts b/lib/types/entities/ChannelMetadata.d.ts new file mode 100644 index 000000000..101562ad0 --- /dev/null +++ b/lib/types/entities/ChannelMetadata.d.ts @@ -0,0 +1,11 @@ +import type { PubNubCore as PubNub } from '../core/pubnub-common'; +import EventEmitter from '../core/components/eventEmitter'; +import { SubscriptionOptions } from './commonTypes'; +import { Subscription } from './Subscription'; +export declare class ChannelMetadata { + private readonly id; + private readonly eventEmitter; + private readonly pubnub; + constructor(id: string, eventEmitter: EventEmitter, pubnub: PubNub); + subscription(subscriptionOptions?: SubscriptionOptions): Subscription; +} diff --git a/lib/types/entities/SubscribeCapable.d.ts b/lib/types/entities/SubscribeCapable.d.ts new file mode 100644 index 000000000..b4ca7001d --- /dev/null +++ b/lib/types/entities/SubscribeCapable.d.ts @@ -0,0 +1,25 @@ +import type { PubNubCore as PubNub } from '../core/pubnub-common'; +import { Listener } from '../core/components/listener_manager'; +import * as Subscription from '../core/types/api/subscription'; +import EventEmitter from '../core/components/eventEmitter'; +import { SubscriptionOptions } from './commonTypes'; +export declare abstract class SubscribeCapable { + protected abstract channelNames: string[]; + protected abstract groupNames: string[]; + protected abstract listener: Listener; + protected abstract eventEmitter: EventEmitter; + protected abstract pubnub: PubNub; + protected abstract options?: SubscriptionOptions; + subscribe(): void; + unsubscribe(): void; + set onMessage(onMessageListener: (messageEvent: Subscription.Message) => void); + set onPresence(onPresenceListener: (presenceEvent: Subscription.Presence) => void); + set onSignal(onSignalListener: (signalEvent: Subscription.Signal) => void); + set onObjects(onObjectsListener: (objectsEvent: Subscription.AppContextObject) => void); + set onMessageAction(messageActionEventListener: (messageActionEvent: Subscription.MessageAction) => void); + set onFile(fileEventListener: (fileEvent: Subscription.File) => void); + addListener(listener: Listener): void; + removeListener(listener: Listener): void; + get channels(): string[]; + get channelGroups(): string[]; +} diff --git a/lib/types/entities/Subscription.d.ts b/lib/types/entities/Subscription.d.ts new file mode 100644 index 000000000..ca7002a27 --- /dev/null +++ b/lib/types/entities/Subscription.d.ts @@ -0,0 +1,22 @@ +import type { PubNubCore as PubNub } from '../core/pubnub-common'; +import { Listener } from '../core/components/listener_manager'; +import EventEmitter from '../core/components/eventEmitter'; +import { SubscribeCapable } from './SubscribeCapable'; +import { SubscriptionOptions } from './commonTypes'; +import { SubscriptionSet } from './SubscriptionSet'; +export declare class Subscription extends SubscribeCapable { + protected channelNames: string[]; + protected groupNames: string[]; + protected options?: SubscriptionOptions; + protected pubnub: PubNub; + protected eventEmitter: EventEmitter; + protected listener: Listener; + constructor({ channels, channelGroups, subscriptionOptions, eventEmitter, pubnub, }: { + channels: string[]; + channelGroups: string[]; + subscriptionOptions?: SubscriptionOptions; + eventEmitter: EventEmitter; + pubnub: PubNub; + }); + addSubscription(subscription: Subscription): SubscriptionSet; +} diff --git a/lib/types/entities/SubscriptionSet.d.ts b/lib/types/entities/SubscriptionSet.d.ts new file mode 100644 index 000000000..a7e0c2465 --- /dev/null +++ b/lib/types/entities/SubscriptionSet.d.ts @@ -0,0 +1,27 @@ +import type { PubNubCore as PubNub } from '../core/pubnub-common'; +import { Listener } from '../core/components/listener_manager'; +import EventEmitter from '../core/components/eventEmitter'; +import { SubscribeCapable } from './SubscribeCapable'; +import { SubscriptionOptions } from './commonTypes'; +import { Subscription } from './Subscription'; +export declare class SubscriptionSet extends SubscribeCapable { + protected channelNames: string[]; + protected groupNames: string[]; + protected options?: SubscriptionOptions; + protected pubnub: PubNub; + protected eventEmitter: EventEmitter; + protected subscriptionList: Subscription[]; + protected listener: Listener; + constructor({ channels, channelGroups, subscriptionOptions, eventEmitter, pubnub, }: { + channels?: string[]; + channelGroups?: string[]; + subscriptionOptions?: SubscriptionOptions; + eventEmitter: EventEmitter; + pubnub: PubNub; + }); + addSubscription(subscription: Subscription): void; + removeSubscription(subscription: Subscription): void; + addSubscriptionSet(subscriptionSet: SubscriptionSet): void; + removeSubscriptionSet(subscriptionSet: SubscriptionSet): void; + get subscriptions(): Subscription[]; +} diff --git a/lib/types/entities/UserMetadata.d.ts b/lib/types/entities/UserMetadata.d.ts new file mode 100644 index 000000000..354ef437d --- /dev/null +++ b/lib/types/entities/UserMetadata.d.ts @@ -0,0 +1,11 @@ +import type { PubNubCore as PubNub } from '../core/pubnub-common'; +import EventEmitter from '../core/components/eventEmitter'; +import { SubscriptionOptions } from './commonTypes'; +import { Subscription } from './Subscription'; +export declare class UserMetadata { + private readonly id; + private readonly eventEmitter; + private readonly pubnub; + constructor(id: string, eventEmitter: EventEmitter, pubnub: PubNub); + subscription(subscriptionOptions?: SubscriptionOptions): Subscription; +} diff --git a/lib/types/entities/commonTypes.d.ts b/lib/types/entities/commonTypes.d.ts new file mode 100644 index 000000000..170abf0d4 --- /dev/null +++ b/lib/types/entities/commonTypes.d.ts @@ -0,0 +1,7 @@ +export type SubscriptionOptions = { + cursor?: { + timetoken?: string; + region?: number; + }; + receivePresenceEvents?: boolean; +}; diff --git a/lib/types/errors/pubnub-api-error.d.ts b/lib/types/errors/pubnub-api-error.d.ts new file mode 100644 index 000000000..037db6967 --- /dev/null +++ b/lib/types/errors/pubnub-api-error.d.ts @@ -0,0 +1,16 @@ +import { TransportResponse } from '../core/types/transport-response'; +import RequestOperation from '../core/constants/operations'; +import StatusCategory from '../core/constants/categories'; +import { Payload, Status } from '../core/types/api'; +import { PubNubError } from './pubnub-error'; +export declare class PubNubAPIError extends Error { + readonly category: StatusCategory; + readonly statusCode: number; + readonly errorData?: Error | Payload | undefined; + static create(errorOrResponse: Error | TransportResponse, data?: ArrayBuffer): PubNubAPIError; + private static createFromError; + private static createFromServiceResponse; + constructor(message: string, category: StatusCategory, statusCode: number, errorData?: Error | Payload | undefined); + toStatus(operation: RequestOperation): Status; + toPubNubError(operation: RequestOperation, message?: string): PubNubError; +} diff --git a/lib/types/errors/pubnub-error.d.ts b/lib/types/errors/pubnub-error.d.ts new file mode 100644 index 000000000..549b195f9 --- /dev/null +++ b/lib/types/errors/pubnub-error.d.ts @@ -0,0 +1,6 @@ +import { Status } from '../core/types/api'; +export declare class PubNubError extends Error { + status?: Status | undefined; + constructor(message: string, status?: Status | undefined); +} +export declare function createValidationError(message: string, statusCode?: number): Status; diff --git a/lib/types/event-engine/core/change.d.ts b/lib/types/event-engine/core/change.d.ts new file mode 100644 index 000000000..7aaf7a029 --- /dev/null +++ b/lib/types/event-engine/core/change.d.ts @@ -0,0 +1,24 @@ +import { State } from './state'; +import { EventTypeFromMap, GenericMap, InvocationTypeFromMap } from './types'; +export type EngineStarted = { + type: 'engineStarted'; + state: State; + context: any; +}; +export type EventReceived = { + type: 'eventReceived'; + event: EventTypeFromMap; +}; +export type TransitionDone = { + type: 'transitionDone'; + event: EventTypeFromMap; + fromState: State; + toState: State; + fromContext: any; + toContext: any; +}; +export type InvocationDispatched = { + type: 'invocationDispatched'; + invocation: InvocationTypeFromMap; +}; +export type Change = TransitionDone | InvocationDispatched | EngineStarted | EventReceived; diff --git a/lib/types/event-engine/core/dispatcher.d.ts b/lib/types/event-engine/core/dispatcher.d.ts new file mode 100644 index 000000000..d70bc9359 --- /dev/null +++ b/lib/types/event-engine/core/dispatcher.d.ts @@ -0,0 +1,13 @@ +import { Handler } from './handler'; +import { GenericInvocation, GenericMap, InvocationTypeFromMap } from './types'; +type HandlerCreator = (payload: Payload, dependencies: Dependencies) => Handler; +export declare class Dispatcher> { + private readonly dependencies; + constructor(dependencies: Dependencies); + private instances; + private handlers; + on(type: K, handlerCreator: HandlerCreator): void; + dispatch(invocation: Invocation): void; + dispose(): void; +} +export {}; diff --git a/lib/types/event-engine/core/engine.d.ts b/lib/types/event-engine/core/engine.d.ts new file mode 100644 index 000000000..ba108d423 --- /dev/null +++ b/lib/types/event-engine/core/engine.d.ts @@ -0,0 +1,11 @@ +import { Subject } from '../../core/components/subject'; +import { Change } from './change'; +import { State } from './state'; +import { GenericMap, Event } from './types'; +export declare class Engine extends Subject> { + describe(label: string): State; + private currentState?; + private currentContext?; + start(initialState: State, initialContext: Context): void; + transition(event: Event): void; +} diff --git a/lib/types/event-engine/core/handler.d.ts b/lib/types/event-engine/core/handler.d.ts new file mode 100644 index 000000000..c8a53c875 --- /dev/null +++ b/lib/types/event-engine/core/handler.d.ts @@ -0,0 +1,18 @@ +import { AbortSignal } from '../../core/components/abort_signal'; +export declare abstract class Handler { + protected payload: Payload; + protected readonly dependencies: Dependencies; + constructor(payload: Payload, dependencies: Dependencies); + abstract start(): void; + abstract cancel(): void; +} +type AsyncHandlerFunction = (payload: Payload, abortSignal: AbortSignal, dependencies: Dependencies) => Promise; +declare class AsyncHandler extends Handler { + private asyncFunction; + abortSignal: AbortSignal; + constructor(payload: Payload, dependencies: Dependencies, asyncFunction: AsyncHandlerFunction); + start(): void; + cancel(): void; +} +export declare const asyncHandler: (handlerFunction: AsyncHandlerFunction) => (payload: Payload, dependencies: Dependencies) => AsyncHandler; +export {}; diff --git a/lib/types/event-engine/core/index.d.ts b/lib/types/event-engine/core/index.d.ts new file mode 100644 index 000000000..b8eab6782 --- /dev/null +++ b/lib/types/event-engine/core/index.d.ts @@ -0,0 +1,4 @@ +export { Engine } from './engine'; +export { Dispatcher } from './dispatcher'; +export { MapOf, createEvent, createEffect, createManagedEffect } from './types'; +export { asyncHandler } from './handler'; diff --git a/lib/types/event-engine/core/retryPolicy.d.ts b/lib/types/event-engine/core/retryPolicy.d.ts new file mode 100644 index 000000000..628c73d13 --- /dev/null +++ b/lib/types/event-engine/core/retryPolicy.d.ts @@ -0,0 +1,26 @@ +import { PubNubError } from '../../errors/pubnub-error'; +export declare class RetryPolicy { + static LinearRetryPolicy(configuration: LinearRetryPolicyConfiguration): RequestRetryPolicy & LinearRetryPolicyConfiguration; + static ExponentialRetryPolicy(configuration: ExponentialRetryPolicyConfiguration): RequestRetryPolicy & ExponentialRetryPolicyConfiguration; +} +export type RequestRetryPolicy = { + shouldRetry(reason: PubNubError & { + retryAfter?: number; + }, attempt: number): boolean; + getDelay(attempt: number, reason: PubNubError & { + retryAfter?: number; + }): number; + getGiveupReason(reason: PubNubError & { + retryAfter?: number; + }, attempt: number): string; + validate(): void; +}; +export type LinearRetryPolicyConfiguration = { + delay: number; + maximumRetry: number; +}; +export type ExponentialRetryPolicyConfiguration = { + minimumDelay: number; + maximumDelay: number; + maximumRetry: number; +}; diff --git a/lib/types/event-engine/core/state.d.ts b/lib/types/event-engine/core/state.d.ts new file mode 100644 index 000000000..59b3bb534 --- /dev/null +++ b/lib/types/event-engine/core/state.d.ts @@ -0,0 +1,21 @@ +import { Event, EventOfType, GenericInvocation, GenericMap, InvocationTypeFromMap } from './types'; +export type TransitionFunction> = { + (context: Context, event: EventType): Transition | void; +}; +export type Transition = [ + State, + Context, + InvocationTypeFromMap[] +]; +export declare class State { + label: string; + private transitionMap; + transition(context: Context, event: EventOfType): void | Transition; + constructor(label: string); + on(eventType: K, transition: TransitionFunction>): this; + with(context: Context, effects?: InvocationTypeFromMap[]): Transition; + enterEffects: ((context: Context) => InvocationTypeFromMap)[]; + exitEffects: ((context: Context) => InvocationTypeFromMap)[]; + onEnter(effect: (context: Context) => GenericInvocation): this; + onExit(effect: (context: Context) => GenericInvocation): this; +} diff --git a/lib/types/event-engine/core/types.d.ts b/lib/types/event-engine/core/types.d.ts new file mode 100644 index 000000000..14524f0ec --- /dev/null +++ b/lib/types/event-engine/core/types.d.ts @@ -0,0 +1,45 @@ +export type Event = { + type: T; + payload: P; +}; +export type Invocation = { + type: T; + payload: P; + managed: boolean; +}; +export type GenericEvent = Event; +export type GenericInvocation = Invocation; +export type GenericMap = Record; +export type EventTypeFromMap = { + [T in keyof Map & string]: Event; +}[keyof Map & string]; +export type InvocationTypeFromMap = { + [T in keyof Map & string]: Invocation; +}[keyof Map & string]; +export type EventOfType = Event; +export type InvocationOfType = Invocation; +type EventCreator = { + (...args: S): Event; + type: K; +}; +export declare function createEvent(type: K, fn: (...args: S) => P): EventCreator; +export type MapOf { + type: string | number | symbol; + payload: any; +}> = { + [K in ReturnType['type']]: (ReturnType & { + type: K; + })['payload']; +}; +type EffectCreator = { + (...args: S): Invocation; + type: K; +}; +type ManagedEffectCreator = { + (...args: S): Invocation; + type: K; + cancel: Invocation<'CANCEL', K>; +}; +export declare function createEffect(type: K, fn: (...args: S) => P): EffectCreator; +export declare function createManagedEffect(type: K, fn: (...args: S) => P): ManagedEffectCreator; +export {}; diff --git a/lib/types/event-engine/dispatcher.d.ts b/lib/types/event-engine/dispatcher.d.ts new file mode 100644 index 000000000..b2afbeb72 --- /dev/null +++ b/lib/types/event-engine/dispatcher.d.ts @@ -0,0 +1,27 @@ +import { PrivateClientConfiguration } from '../core/interfaces/configuration'; +import * as Subscription from '../core/types/api/subscription'; +import { Dispatcher, Engine } from './core'; +import * as effects from './effects'; +import * as events from './events'; +import { Payload, StatusEvent } from '../core/types/api'; +export type Dependencies = { + handshake: (parameters: Subscription.CancelableSubscribeParameters) => Promise; + receiveMessages: (parameters: Subscription.CancelableSubscribeParameters) => Promise; + join?: (parameters: { + channels?: string[]; + groups?: string[]; + }) => void; + leave?: (parameters: { + channels?: string[]; + groups?: string[]; + }) => void; + leaveAll?: () => void; + presenceState: Record; + config: PrivateClientConfiguration; + delay: (milliseconds: number) => Promise; + emitMessages: (events: Subscription.SubscriptionResponse['messages']) => void; + emitStatus: (status: StatusEvent) => void; +}; +export declare class EventEngineDispatcher extends Dispatcher { + constructor(engine: Engine, dependencies: Dependencies); +} diff --git a/lib/types/event-engine/effects.d.ts b/lib/types/event-engine/effects.d.ts new file mode 100644 index 000000000..803ce383b --- /dev/null +++ b/lib/types/event-engine/effects.d.ts @@ -0,0 +1,77 @@ +import { MapOf } from './core'; +import { HandshakeReconnectingStateContext } from './states/handshake_reconnecting'; +import { ReceiveReconnectingStateContext } from './states/receive_reconnecting'; +import * as Subscription from '../core/types/api/subscription'; +import { StatusEvent } from '../core/types/api'; +export declare const handshake: { + (channels: string[], groups: string[]): import("./core/types").Invocation<"HANDSHAKE", { + channels: string[]; + groups: string[]; + }>; + type: "HANDSHAKE"; + cancel: import("./core/types").Invocation<"CANCEL", "HANDSHAKE">; +}; +export declare const receiveMessages: { + (channels: string[], groups: string[], cursor: Subscription.SubscriptionCursor): import("./core/types").Invocation<"RECEIVE_MESSAGES", { + channels: string[]; + groups: string[]; + cursor: Subscription.SubscriptionCursor; + }>; + type: "RECEIVE_MESSAGES"; + cancel: import("./core/types").Invocation<"CANCEL", "RECEIVE_MESSAGES">; +}; +export declare const emitMessages: { + (events: ({ + type: import("../core/endpoints/subscribe").PubNubEventType.Presence; + data: Subscription.Presence; + } | { + type: import("../core/endpoints/subscribe").PubNubEventType.Message; + data: Subscription.Message; + } | { + type: import("../core/endpoints/subscribe").PubNubEventType.Signal; + data: Subscription.Signal; + } | { + type: import("../core/endpoints/subscribe").PubNubEventType.MessageAction; + data: Subscription.MessageAction; + } | { + type: import("../core/endpoints/subscribe").PubNubEventType.AppContext; + data: Subscription.AppContextObject; + } | { + type: import("../core/endpoints/subscribe").PubNubEventType.Files; + data: Subscription.File; + })[]): import("./core/types").Invocation<"EMIT_MESSAGES", ({ + type: import("../core/endpoints/subscribe").PubNubEventType.Presence; + data: Subscription.Presence; + } | { + type: import("../core/endpoints/subscribe").PubNubEventType.Message; + data: Subscription.Message; + } | { + type: import("../core/endpoints/subscribe").PubNubEventType.Signal; + data: Subscription.Signal; + } | { + type: import("../core/endpoints/subscribe").PubNubEventType.MessageAction; + data: Subscription.MessageAction; + } | { + type: import("../core/endpoints/subscribe").PubNubEventType.AppContext; + data: Subscription.AppContextObject; + } | { + type: import("../core/endpoints/subscribe").PubNubEventType.Files; + data: Subscription.File; + })[]>; + type: "EMIT_MESSAGES"; +}; +export declare const emitStatus: { + (status: StatusEvent): import("./core/types").Invocation<"EMIT_STATUS", StatusEvent>; + type: "EMIT_STATUS"; +}; +export declare const receiveReconnect: { + (context: ReceiveReconnectingStateContext): import("./core/types").Invocation<"RECEIVE_RECONNECT", ReceiveReconnectingStateContext>; + type: "RECEIVE_RECONNECT"; + cancel: import("./core/types").Invocation<"CANCEL", "RECEIVE_RECONNECT">; +}; +export declare const handshakeReconnect: { + (context: HandshakeReconnectingStateContext): import("./core/types").Invocation<"HANDSHAKE_RECONNECT", HandshakeReconnectingStateContext>; + type: "HANDSHAKE_RECONNECT"; + cancel: import("./core/types").Invocation<"CANCEL", "HANDSHAKE_RECONNECT">; +}; +export type Effects = MapOf; diff --git a/lib/types/event-engine/events.d.ts b/lib/types/event-engine/events.d.ts new file mode 100644 index 000000000..98418cab9 --- /dev/null +++ b/lib/types/event-engine/events.d.ts @@ -0,0 +1,159 @@ +import * as Subscription from '../core/types/api/subscription'; +import { PubNubError } from '../errors/pubnub-error'; +import { MapOf } from './core'; +export declare const subscriptionChange: { + (channels: string[], groups: string[]): import("./core/types").Event<"SUBSCRIPTION_CHANGED", { + channels: string[]; + groups: string[]; + }>; + type: "SUBSCRIPTION_CHANGED"; +}; +export declare const restore: { + (channels: string[], groups: string[], timetoken: string | number, region?: number | undefined): import("./core/types").Event<"SUBSCRIPTION_RESTORED", { + channels: string[]; + groups: string[]; + cursor: { + timetoken: string | number; + region: number; + }; + }>; + type: "SUBSCRIPTION_RESTORED"; +}; +export declare const handshakeSuccess: { + (cursor: Subscription.SubscriptionCursor): import("./core/types").Event<"HANDSHAKE_SUCCESS", Subscription.SubscriptionCursor>; + type: "HANDSHAKE_SUCCESS"; +}; +export declare const handshakeFailure: { + (error: PubNubError): import("./core/types").Event<"HANDSHAKE_FAILURE", PubNubError>; + type: "HANDSHAKE_FAILURE"; +}; +export declare const handshakeReconnectSuccess: { + (cursor: Subscription.SubscriptionCursor): import("./core/types").Event<"HANDSHAKE_RECONNECT_SUCCESS", { + cursor: Subscription.SubscriptionCursor; + }>; + type: "HANDSHAKE_RECONNECT_SUCCESS"; +}; +export declare const handshakeReconnectFailure: { + (error: PubNubError): import("./core/types").Event<"HANDSHAKE_RECONNECT_FAILURE", PubNubError>; + type: "HANDSHAKE_RECONNECT_FAILURE"; +}; +export declare const handshakeReconnectGiveup: { + (error: PubNubError): import("./core/types").Event<"HANDSHAKE_RECONNECT_GIVEUP", PubNubError>; + type: "HANDSHAKE_RECONNECT_GIVEUP"; +}; +export declare const receiveSuccess: { + (cursor: Subscription.SubscriptionCursor, events: ({ + type: import("../core/endpoints/subscribe").PubNubEventType.Presence; + data: Subscription.Presence; + } | { + type: import("../core/endpoints/subscribe").PubNubEventType.Message; + data: Subscription.Message; + } | { + type: import("../core/endpoints/subscribe").PubNubEventType.Signal; + data: Subscription.Signal; + } | { + type: import("../core/endpoints/subscribe").PubNubEventType.MessageAction; + data: Subscription.MessageAction; + } | { + type: import("../core/endpoints/subscribe").PubNubEventType.AppContext; + data: Subscription.AppContextObject; + } | { + type: import("../core/endpoints/subscribe").PubNubEventType.Files; + data: Subscription.File; + })[]): import("./core/types").Event<"RECEIVE_SUCCESS", { + cursor: Subscription.SubscriptionCursor; + events: ({ + type: import("../core/endpoints/subscribe").PubNubEventType.Presence; + data: Subscription.Presence; + } | { + type: import("../core/endpoints/subscribe").PubNubEventType.Message; + data: Subscription.Message; + } | { + type: import("../core/endpoints/subscribe").PubNubEventType.Signal; + data: Subscription.Signal; + } | { + type: import("../core/endpoints/subscribe").PubNubEventType.MessageAction; + data: Subscription.MessageAction; + } | { + type: import("../core/endpoints/subscribe").PubNubEventType.AppContext; + data: Subscription.AppContextObject; + } | { + type: import("../core/endpoints/subscribe").PubNubEventType.Files; + data: Subscription.File; + })[]; + }>; + type: "RECEIVE_SUCCESS"; +}; +export declare const receiveFailure: { + (error: PubNubError): import("./core/types").Event<"RECEIVE_FAILURE", PubNubError>; + type: "RECEIVE_FAILURE"; +}; +export declare const receiveReconnectSuccess: { + (cursor: Subscription.SubscriptionCursor, events: ({ + type: import("../core/endpoints/subscribe").PubNubEventType.Presence; + data: Subscription.Presence; + } | { + type: import("../core/endpoints/subscribe").PubNubEventType.Message; + data: Subscription.Message; + } | { + type: import("../core/endpoints/subscribe").PubNubEventType.Signal; + data: Subscription.Signal; + } | { + type: import("../core/endpoints/subscribe").PubNubEventType.MessageAction; + data: Subscription.MessageAction; + } | { + type: import("../core/endpoints/subscribe").PubNubEventType.AppContext; + data: Subscription.AppContextObject; + } | { + type: import("../core/endpoints/subscribe").PubNubEventType.Files; + data: Subscription.File; + })[]): import("./core/types").Event<"RECEIVE_RECONNECT_SUCCESS", { + cursor: Subscription.SubscriptionCursor; + events: ({ + type: import("../core/endpoints/subscribe").PubNubEventType.Presence; + data: Subscription.Presence; + } | { + type: import("../core/endpoints/subscribe").PubNubEventType.Message; + data: Subscription.Message; + } | { + type: import("../core/endpoints/subscribe").PubNubEventType.Signal; + data: Subscription.Signal; + } | { + type: import("../core/endpoints/subscribe").PubNubEventType.MessageAction; + data: Subscription.MessageAction; + } | { + type: import("../core/endpoints/subscribe").PubNubEventType.AppContext; + data: Subscription.AppContextObject; + } | { + type: import("../core/endpoints/subscribe").PubNubEventType.Files; + data: Subscription.File; + })[]; + }>; + type: "RECEIVE_RECONNECT_SUCCESS"; +}; +export declare const receiveReconnectFailure: { + (error: PubNubError): import("./core/types").Event<"RECEIVE_RECONNECT_FAILURE", PubNubError>; + type: "RECEIVE_RECONNECT_FAILURE"; +}; +export declare const receiveReconnectGiveup: { + (error: PubNubError): import("./core/types").Event<"RECEIVING_RECONNECT_GIVEUP", PubNubError>; + type: "RECEIVING_RECONNECT_GIVEUP"; +}; +export declare const disconnect: { + (): import("./core/types").Event<"DISCONNECT", {}>; + type: "DISCONNECT"; +}; +export declare const reconnect: { + (timetoken?: string | undefined, region?: number | undefined): import("./core/types").Event<"RECONNECT", { + cursor: { + timetoken: string; + region: number; + }; + }>; + type: "RECONNECT"; +}; +export declare const unsubscribeAll: { + (): import("./core/types").Event<"UNSUBSCRIBE_ALL", {}>; + type: "UNSUBSCRIBE_ALL"; +}; +export type Events = MapOf; diff --git a/lib/types/event-engine/index.d.ts b/lib/types/event-engine/index.d.ts new file mode 100644 index 000000000..2542bfa3b --- /dev/null +++ b/lib/types/event-engine/index.d.ts @@ -0,0 +1,33 @@ +import { Engine } from './core'; +import { Dependencies } from './dispatcher'; +import * as effects from './effects'; +import * as events from './events'; +export declare class EventEngine { + private engine; + private dispatcher; + private dependencies; + get _engine(): Engine; + private readonly _unsubscribeEngine; + constructor(dependencies: Dependencies); + channels: string[]; + groups: string[]; + subscribe({ channels, channelGroups, timetoken, withPresence, }: { + channels?: string[]; + channelGroups?: string[]; + timetoken?: string | number; + withPresence?: boolean; + }): void; + unsubscribe({ channels, channelGroups }: { + channels?: string[]; + channelGroups?: string[]; + }): void; + unsubscribeAll(): void; + reconnect({ timetoken, region }: { + timetoken?: string; + region?: number; + }): void; + disconnect(): void; + getSubscribedChannels(): string[]; + getSubscribedChannelGroups(): string[]; + dispose(): void; +} diff --git a/lib/types/event-engine/presence/dispatcher.d.ts b/lib/types/event-engine/presence/dispatcher.d.ts new file mode 100644 index 000000000..9fdf3de45 --- /dev/null +++ b/lib/types/event-engine/presence/dispatcher.d.ts @@ -0,0 +1,18 @@ +import { PrivateClientConfiguration } from '../../core/interfaces/configuration'; +import { Dispatcher, Engine } from '../core'; +import * as Presence from '../../core/types/api/presence'; +import { Payload, ResultCallback } from '../../core/types/api'; +import * as effects from './effects'; +import * as events from './events'; +export type Dependencies = { + heartbeat: (parameters: Presence.PresenceHeartbeatParameters, callback?: ResultCallback) => Promise; + leave: (parameters: Presence.PresenceLeaveParameters) => void; + heartbeatDelay: () => Promise; + retryDelay: (milliseconds: number) => Promise; + config: PrivateClientConfiguration; + presenceState: Record; + emitStatus: (status: any) => void; +}; +export declare class PresenceEventEngineDispatcher extends Dispatcher { + constructor(engine: Engine, dependencies: Dependencies); +} diff --git a/lib/types/event-engine/presence/effects.d.ts b/lib/types/event-engine/presence/effects.d.ts new file mode 100644 index 000000000..a905c6835 --- /dev/null +++ b/lib/types/event-engine/presence/effects.d.ts @@ -0,0 +1,31 @@ +import { MapOf } from '../core'; +import { HeartbeatReconnectingStateContext } from './states/heartbeat_reconnecting'; +export declare const heartbeat: { + (channels: string[], groups: string[]): import("../core/types").Invocation<"HEARTBEAT", { + channels: string[]; + groups: string[]; + }>; + type: "HEARTBEAT"; +}; +export declare const leave: { + (channels: string[], groups: string[]): import("../core/types").Invocation<"LEAVE", { + channels: string[]; + groups: string[]; + }>; + type: "LEAVE"; +}; +export declare const emitStatus: { + (status: any): import("../core/types").Invocation<"EMIT_STATUS", any>; + type: "EMIT_STATUS"; +}; +export declare const wait: { + (): import("../core/types").Invocation<"WAIT", {}>; + type: "WAIT"; + cancel: import("../core/types").Invocation<"CANCEL", "WAIT">; +}; +export declare const delayedHeartbeat: { + (context: HeartbeatReconnectingStateContext): import("../core/types").Invocation<"DELAYED_HEARTBEAT", HeartbeatReconnectingStateContext>; + type: "DELAYED_HEARTBEAT"; + cancel: import("../core/types").Invocation<"CANCEL", "DELAYED_HEARTBEAT">; +}; +export type Effects = MapOf; diff --git a/lib/types/event-engine/presence/events.d.ts b/lib/types/event-engine/presence/events.d.ts new file mode 100644 index 000000000..cfceec153 --- /dev/null +++ b/lib/types/event-engine/presence/events.d.ts @@ -0,0 +1,47 @@ +import { PubNubError } from '../../errors/pubnub-error'; +import { MapOf } from '../core'; +export declare const reconnect: { + (): import("../core/types").Event<"RECONNECT", {}>; + type: "RECONNECT"; +}; +export declare const disconnect: { + (): import("../core/types").Event<"DISCONNECT", {}>; + type: "DISCONNECT"; +}; +export declare const joined: { + (channels: string[], groups: string[]): import("../core/types").Event<"JOINED", { + channels: string[]; + groups: string[]; + }>; + type: "JOINED"; +}; +export declare const left: { + (channels: string[], groups: string[]): import("../core/types").Event<"LEFT", { + channels: string[]; + groups: string[]; + }>; + type: "LEFT"; +}; +export declare const leftAll: { + (): import("../core/types").Event<"LEFT_ALL", {}>; + type: "LEFT_ALL"; +}; +export declare const heartbeatSuccess: { + (statusCode: number): import("../core/types").Event<"HEARTBEAT_SUCCESS", { + statusCode: number; + }>; + type: "HEARTBEAT_SUCCESS"; +}; +export declare const heartbeatFailure: { + (error: PubNubError): import("../core/types").Event<"HEARTBEAT_FAILURE", PubNubError>; + type: "HEARTBEAT_FAILURE"; +}; +export declare const heartbeatGiveup: { + (): import("../core/types").Event<"HEARTBEAT_GIVEUP", {}>; + type: "HEARTBEAT_GIVEUP"; +}; +export declare const timesUp: { + (): import("../core/types").Event<"TIMES_UP", {}>; + type: "TIMES_UP"; +}; +export type Events = MapOf; diff --git a/lib/types/event-engine/presence/presence.d.ts b/lib/types/event-engine/presence/presence.d.ts new file mode 100644 index 000000000..42f82e750 --- /dev/null +++ b/lib/types/event-engine/presence/presence.d.ts @@ -0,0 +1,24 @@ +import { Engine } from '../core'; +import * as events from './events'; +import * as effects from './effects'; +import { Dependencies } from './dispatcher'; +export declare class PresenceEventEngine { + private dependencies; + private engine; + private dispatcher; + get _engine(): Engine; + private _unsubscribeEngine; + constructor(dependencies: Dependencies); + channels: string[]; + groups: string[]; + join({ channels, groups }: { + channels?: string[]; + groups?: string[]; + }): void; + leave({ channels, groups }: { + channels?: string[]; + groups?: string[]; + }): void; + leaveAll(): void; + dispose(): void; +} diff --git a/lib/types/event-engine/presence/states/heartbeat_cooldown.d.ts b/lib/types/event-engine/presence/states/heartbeat_cooldown.d.ts new file mode 100644 index 000000000..6b2273d2b --- /dev/null +++ b/lib/types/event-engine/presence/states/heartbeat_cooldown.d.ts @@ -0,0 +1,8 @@ +import { State } from '../../core/state'; +import { Events } from '../events'; +import { Effects } from '../effects'; +export type HeartbeatCooldownStateContext = { + channels: string[]; + groups: string[]; +}; +export declare const HeartbeatCooldownState: State; diff --git a/lib/types/event-engine/presence/states/heartbeat_failed.d.ts b/lib/types/event-engine/presence/states/heartbeat_failed.d.ts new file mode 100644 index 000000000..dce365993 --- /dev/null +++ b/lib/types/event-engine/presence/states/heartbeat_failed.d.ts @@ -0,0 +1,8 @@ +import { State } from '../../core/state'; +import { Events } from '../events'; +import { Effects } from '../effects'; +export type HeartbeatFailedStateContext = { + channels: string[]; + groups: string[]; +}; +export declare const HeartbeatFailedState: State; diff --git a/lib/types/event-engine/presence/states/heartbeat_inactive.d.ts b/lib/types/event-engine/presence/states/heartbeat_inactive.d.ts new file mode 100644 index 000000000..d39ebfb4f --- /dev/null +++ b/lib/types/event-engine/presence/states/heartbeat_inactive.d.ts @@ -0,0 +1,4 @@ +import { State } from '../../core/state'; +import { Effects } from '../effects'; +import { Events } from '../events'; +export declare const HeartbeatInactiveState: State; diff --git a/lib/types/event-engine/presence/states/heartbeat_reconnecting.d.ts b/lib/types/event-engine/presence/states/heartbeat_reconnecting.d.ts new file mode 100644 index 000000000..3a3044a0b --- /dev/null +++ b/lib/types/event-engine/presence/states/heartbeat_reconnecting.d.ts @@ -0,0 +1,11 @@ +import { PubNubError } from '../../../errors/pubnub-error'; +import { State } from '../../core/state'; +import { Events } from '../events'; +import { Effects } from '../effects'; +export type HeartbeatReconnectingStateContext = { + channels: string[]; + groups: string[]; + attempts: number; + reason: PubNubError; +}; +export declare const HearbeatReconnectingState: State; diff --git a/lib/types/event-engine/presence/states/heartbeat_stopped.d.ts b/lib/types/event-engine/presence/states/heartbeat_stopped.d.ts new file mode 100644 index 000000000..9df101a87 --- /dev/null +++ b/lib/types/event-engine/presence/states/heartbeat_stopped.d.ts @@ -0,0 +1,8 @@ +import { State } from '../../core/state'; +import { Effects } from '../effects'; +import { Events } from '../events'; +export type HeartbeatStoppedStateContext = { + channels: string[]; + groups: string[]; +}; +export declare const HeartbeatStoppedState: State; diff --git a/lib/types/event-engine/presence/states/heartbeating.d.ts b/lib/types/event-engine/presence/states/heartbeating.d.ts new file mode 100644 index 000000000..57bc59f8f --- /dev/null +++ b/lib/types/event-engine/presence/states/heartbeating.d.ts @@ -0,0 +1,8 @@ +import { State } from '../../core/state'; +import { Events } from '../events'; +import { Effects } from '../effects'; +export type HeartbeatingStateContext = { + channels: string[]; + groups: string[]; +}; +export declare const HeartbeatingState: State; diff --git a/lib/types/event-engine/states/handshake_failed.d.ts b/lib/types/event-engine/states/handshake_failed.d.ts new file mode 100644 index 000000000..be8769ab6 --- /dev/null +++ b/lib/types/event-engine/states/handshake_failed.d.ts @@ -0,0 +1,12 @@ +import { State } from '../core/state'; +import { Effects } from '../effects'; +import { Events } from '../events'; +import { PubNubError } from '../../errors/pubnub-error'; +import * as Subscription from '../../core/types/api/subscription'; +export type HandshakeFailedStateContext = { + channels: string[]; + groups: string[]; + cursor?: Subscription.SubscriptionCursor; + reason: PubNubError; +}; +export declare const HandshakeFailedState: State; diff --git a/lib/types/event-engine/states/handshake_reconnecting.d.ts b/lib/types/event-engine/states/handshake_reconnecting.d.ts new file mode 100644 index 000000000..ed2817320 --- /dev/null +++ b/lib/types/event-engine/states/handshake_reconnecting.d.ts @@ -0,0 +1,13 @@ +import { PubNubError } from '../../errors/pubnub-error'; +import { State } from '../core/state'; +import { Effects } from '../effects'; +import { Events } from '../events'; +import * as Subscription from '../../core/types/api/subscription'; +export type HandshakeReconnectingStateContext = { + channels: string[]; + groups: string[]; + cursor?: Subscription.SubscriptionCursor; + attempts: number; + reason: PubNubError; +}; +export declare const HandshakeReconnectingState: State; diff --git a/lib/types/event-engine/states/handshake_stopped.d.ts b/lib/types/event-engine/states/handshake_stopped.d.ts new file mode 100644 index 000000000..40ffa7c4c --- /dev/null +++ b/lib/types/event-engine/states/handshake_stopped.d.ts @@ -0,0 +1,11 @@ +import { State } from '../core/state'; +import { Effects } from '../effects'; +import { Events } from '../events'; +import * as Subscription from '../../core/types/api/subscription'; +type HandshakeStoppedStateContext = { + channels: string[]; + groups: string[]; + cursor?: Subscription.SubscriptionCursor; +}; +export declare const HandshakeStoppedState: State; +export {}; diff --git a/lib/types/event-engine/states/handshaking.d.ts b/lib/types/event-engine/states/handshaking.d.ts new file mode 100644 index 000000000..cff30ca43 --- /dev/null +++ b/lib/types/event-engine/states/handshaking.d.ts @@ -0,0 +1,10 @@ +import { State } from '../core/state'; +import { Effects } from '../effects'; +import { Events } from '../events'; +import * as Subscription from '../../core/types/api/subscription'; +export type HandshakingStateContext = { + channels: string[]; + groups: string[]; + cursor?: Subscription.SubscriptionCursor; +}; +export declare const HandshakingState: State; diff --git a/lib/types/event-engine/states/receive_failed.d.ts b/lib/types/event-engine/states/receive_failed.d.ts new file mode 100644 index 000000000..925a8f857 --- /dev/null +++ b/lib/types/event-engine/states/receive_failed.d.ts @@ -0,0 +1,12 @@ +import { State } from '../core/state'; +import { Effects } from '../effects'; +import { Events } from '../events'; +import { PubNubError } from '../../errors/pubnub-error'; +import * as Subscription from '../../core/types/api/subscription'; +export type ReceiveFailedStateContext = { + channels: string[]; + groups: string[]; + cursor: Subscription.SubscriptionCursor; + reason: PubNubError; +}; +export declare const ReceiveFailedState: State; diff --git a/lib/types/event-engine/states/receive_reconnecting.d.ts b/lib/types/event-engine/states/receive_reconnecting.d.ts new file mode 100644 index 000000000..399e76ada --- /dev/null +++ b/lib/types/event-engine/states/receive_reconnecting.d.ts @@ -0,0 +1,13 @@ +import { PubNubError } from '../../errors/pubnub-error'; +import { State } from '../core/state'; +import { Effects } from '../effects'; +import { Events } from '../events'; +import * as Subscription from '../../core/types/api/subscription'; +export type ReceiveReconnectingStateContext = { + channels: string[]; + groups: string[]; + cursor: Subscription.SubscriptionCursor; + attempts: number; + reason: PubNubError; +}; +export declare const ReceiveReconnectingState: State; diff --git a/lib/types/event-engine/states/receive_stopped.d.ts b/lib/types/event-engine/states/receive_stopped.d.ts new file mode 100644 index 000000000..85a3986be --- /dev/null +++ b/lib/types/event-engine/states/receive_stopped.d.ts @@ -0,0 +1,11 @@ +import { State } from '../core/state'; +import { Effects } from '../effects'; +import { Events } from '../events'; +import * as Subscription from '../../core/types/api/subscription'; +type ReceiveStoppedStateContext = { + channels: string[]; + groups: string[]; + cursor: Subscription.SubscriptionCursor; +}; +export declare const ReceiveStoppedState: State; +export {}; diff --git a/lib/types/event-engine/states/receiving.d.ts b/lib/types/event-engine/states/receiving.d.ts new file mode 100644 index 000000000..221353f4f --- /dev/null +++ b/lib/types/event-engine/states/receiving.d.ts @@ -0,0 +1,10 @@ +import { State } from '../core/state'; +import { Effects } from '../effects'; +import { Events } from '../events'; +import * as Subscription from '../../core/types/api/subscription'; +export type ReceivingStateContext = { + channels: string[]; + groups: string[]; + cursor: Subscription.SubscriptionCursor; +}; +export declare const ReceivingState: State; diff --git a/lib/types/event-engine/states/unsubscribed.d.ts b/lib/types/event-engine/states/unsubscribed.d.ts new file mode 100644 index 000000000..ad8a2f25a --- /dev/null +++ b/lib/types/event-engine/states/unsubscribed.d.ts @@ -0,0 +1,4 @@ +import { State } from '../core/state'; +import { Effects } from '../effects'; +import { Events } from '../events'; +export declare const UnsubscribedState: State; diff --git a/lib/types/file/modules/node.d.ts b/lib/types/file/modules/node.d.ts new file mode 100644 index 000000000..63ad822b1 --- /dev/null +++ b/lib/types/file/modules/node.d.ts @@ -0,0 +1,35 @@ +/// +/// +import { Readable, PassThrough } from 'stream'; +import { Buffer } from 'buffer'; +import { PubNubFileInterface } from '../../core/types/file'; +export type PubNubFileParameters = { + stream?: Readable; + data?: Buffer | ArrayBuffer | string; + encoding?: StringEncoding; + name: string; + mimeType?: string; +}; +export default class PubNubFile implements PubNubFileInterface { + static supportsBlob: boolean; + static supportsFile: boolean; + static supportsBuffer: boolean; + static supportsStream: boolean; + static supportsString: boolean; + static supportsArrayBuffer: boolean; + static supportsEncryptFile: boolean; + static supportsFileUri: boolean; + readonly data: Readable | Buffer; + contentLength?: number; + mimeType: string; + name: string; + static create(file: PubNubFileParameters): PubNubFile; + constructor(file: PubNubFileParameters); + toBuffer(): Promise; + toArrayBuffer(): Promise; + toString(encoding?: BufferEncoding): Promise; + toStream(): Promise; + toFile(): Promise; + toFileUri(): Promise>; + toBlob(): Promise; +} diff --git a/lib/types/file/modules/react-native.d.ts b/lib/types/file/modules/react-native.d.ts new file mode 100644 index 000000000..ff707b6bd --- /dev/null +++ b/lib/types/file/modules/react-native.d.ts @@ -0,0 +1,40 @@ +import { PubNubFileInterface } from '../../core/types/file'; +type FileUri = { + uri: string; + name: string; + mimeType?: string; +}; +type ReadableFile = { + arrayBuffer: () => Promise; + blob: () => Promise; + text: () => Promise; +}; +export type PubNubFileParameters = File | FileUri | ReadableFile | { + data: string | Blob | ArrayBuffer | ArrayBufferView; + name: string; + mimeType?: string; +}; +export declare class PubNubFile implements PubNubFileInterface { + static supportsBlob: boolean; + static supportsFile: boolean; + static supportsBuffer: boolean; + static supportsStream: boolean; + static supportsString: boolean; + static supportsArrayBuffer: boolean; + static supportsEncryptFile: boolean; + static supportsFileUri: boolean; + readonly data: File | FileUri | ReadableFile; + contentLength?: number; + mimeType: string; + name: string; + static create(file: PubNubFileParameters): PubNubFile; + constructor(file: PubNubFileParameters); + toBuffer(): Promise; + toArrayBuffer(): Promise; + toString(): Promise; + toStream(): Promise; + toFile(): Promise; + toFileUri(): Promise; + toBlob(): Promise; +} +export default PubNubFile; diff --git a/lib/types/models/Cursor.d.ts b/lib/types/models/Cursor.d.ts new file mode 100644 index 000000000..8ba000353 --- /dev/null +++ b/lib/types/models/Cursor.d.ts @@ -0,0 +1,4 @@ +export type Cursor = { + readonly timetoken: string; + readonly region: number; +}; diff --git a/lib/types/node/configuration.d.ts b/lib/types/node/configuration.d.ts new file mode 100644 index 000000000..042052553 --- /dev/null +++ b/lib/types/node/configuration.d.ts @@ -0,0 +1,13 @@ +import { UserConfiguration, ExtendedConfiguration } from '../core/interfaces/configuration'; +import { TransportKeepAlive } from '../core/interfaces/transport'; +import { Payload } from '../core/types/api'; +import { CryptoModule } from '../core/interfaces/crypto-module'; +export type PubNubConfiguration = UserConfiguration & { + keepAliveSettings?: TransportKeepAlive; + cryptoModule?: CryptoModule; + cipherKey?: string; + useRandomIVs?: boolean; + customEncrypt?: (data: string | Payload) => string; + customDecrypt?: (data: string) => string; +}; +export declare const setDefaults: (configuration: PubNubConfiguration) => PubNubConfiguration & ExtendedConfiguration; diff --git a/lib/types/node/index.d.ts b/lib/types/node/index.d.ts new file mode 100644 index 000000000..f1005d985 --- /dev/null +++ b/lib/types/node/index.d.ts @@ -0,0 +1,18 @@ +/// +/// +import { ProxyAgentOptions } from 'proxy-agent'; +import { Readable } from 'stream'; +import { Buffer } from 'buffer'; +import { CryptoModule } from '../crypto/modules/NodeCryptoModule/nodeCryptoModule'; +import PubNubFile, { PubNubFileParameters } from '../file/modules/node'; +import { PubNubConfiguration } from './configuration'; +import { PubNubFileConstructor } from '../core/types/file'; +import { PubNubCore } from '../core/pubnub-common'; +declare class PubNub extends PubNubCore { + static CryptoModule: typeof CryptoModule; + File: PubNubFileConstructor; + private nodeTransport; + constructor(configuration: PubNubConfiguration); + setProxy(configuration?: ProxyAgentOptions): void; +} +export = PubNub; diff --git a/lib/types/react_native/configuration.d.ts b/lib/types/react_native/configuration.d.ts new file mode 100644 index 000000000..f2f28948b --- /dev/null +++ b/lib/types/react_native/configuration.d.ts @@ -0,0 +1,3 @@ +import { ExtendedConfiguration, UserConfiguration } from '../core/interfaces/configuration'; +export type PubNubConfiguration = UserConfiguration; +export declare const setDefaults: (configuration: PubNubConfiguration) => PubNubConfiguration & ExtendedConfiguration; diff --git a/lib/types/react_native/index.d.ts b/lib/types/react_native/index.d.ts new file mode 100644 index 000000000..aff2a70fa --- /dev/null +++ b/lib/types/react_native/index.d.ts @@ -0,0 +1,7 @@ +import 'react-native-url-polyfill/auto'; +import { PubNubFileParameters } from '../file/modules/react-native'; +import { PubNubConfiguration } from './configuration'; +import { PubNubCore } from '../core/pubnub-common'; +export default class PubNub extends PubNubCore { + constructor(configuration: PubNubConfiguration); +} diff --git a/lib/types/transport/middleware.d.ts b/lib/types/transport/middleware.d.ts new file mode 100644 index 000000000..6d88feba4 --- /dev/null +++ b/lib/types/transport/middleware.d.ts @@ -0,0 +1,30 @@ +import { TransportRequest } from '../core/types/transport-request'; +import { PrivateClientConfiguration } from '../core/interfaces/configuration'; +import { TokenManager } from '../core/components/token_manager'; +import { Transport } from '../core/interfaces/transport'; +type PubNubMiddlewareConfiguration = { + clientConfiguration: PrivateClientConfiguration; + tokenManager: TokenManager; + shaHMAC?: (data: string) => string; + transport: Transport; +}; +export declare class RequestSignature { + private publishKey; + private secretKey; + private hasher; + private static textDecoder; + constructor(publishKey: string, secretKey: string, hasher: (input: string, secret: string) => string); + signature(req: TransportRequest): string; + private queryParameters; +} +export declare class PubNubMiddleware implements Transport { + private configuration; + signatureGenerator?: RequestSignature; + constructor(configuration: PubNubMiddlewareConfiguration); + makeSendable(req: TransportRequest): [Promise, import("../core/types/transport-request").CancellationController | undefined]; + request(req: TransportRequest): TransportRequest; + private authenticateRequest; + private signRequest; + private generatePNSDK; +} +export {}; diff --git a/lib/types/transport/node-transport.d.ts b/lib/types/transport/node-transport.d.ts new file mode 100644 index 000000000..b7af775eb --- /dev/null +++ b/lib/types/transport/node-transport.d.ts @@ -0,0 +1,22 @@ +import { Request } from 'node-fetch'; +import { ProxyAgentOptions } from 'proxy-agent'; +import { CancellationController, TransportRequest } from '../core/types/transport-request'; +import { Transport, TransportKeepAlive } from '../core/interfaces/transport'; +import { TransportResponse } from '../core/types/transport-response'; +export declare class NodeTransport implements Transport { + private readonly keepAlive; + private readonly keepAliveSettings; + private readonly logVerbosity; + protected static decoder: TextDecoder; + private proxyConfiguration?; + private proxyAgent?; + private httpsAgent?; + private httpAgent?; + constructor(keepAlive?: boolean, keepAliveSettings?: TransportKeepAlive, logVerbosity?: boolean); + setProxy(configuration?: ProxyAgentOptions): void; + makeSendable(req: TransportRequest): [Promise, CancellationController | undefined]; + request(req: TransportRequest): TransportRequest; + private requestFromTransportRequest; + private agentForTransportRequest; + protected logRequestProcessProgress(request: Request, elapsed?: number, body?: ArrayBuffer): void; +} diff --git a/lib/types/transport/web-react-native-transport.d.ts b/lib/types/transport/web-react-native-transport.d.ts new file mode 100644 index 000000000..2a5f650dd --- /dev/null +++ b/lib/types/transport/web-react-native-transport.d.ts @@ -0,0 +1,13 @@ +import { CancellationController, TransportRequest } from '../core/types/transport-request'; +import { TransportResponse } from '../core/types/transport-response'; +import { Transport } from '../core/interfaces/transport'; +export declare class WebReactNativeTransport implements Transport { + private keepAlive; + private readonly logVerbosity; + protected static decoder: TextDecoder; + constructor(keepAlive: boolean, logVerbosity: boolean); + makeSendable(req: TransportRequest): [Promise, CancellationController | undefined]; + request(req: TransportRequest): TransportRequest; + private requestFromTransportRequest; + protected logRequestProcessProgress(request: Request, elapsed?: number, body?: ArrayBuffer): void; +} diff --git a/package-lock.json b/package-lock.json index a075d7e07..22d3060ef 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,12 +1,12 @@ { "name": "pubnub", - "version": "8.0.0", + "version": "8.0.1", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "pubnub", - "version": "8.0.0", + "version": "8.0.1", "license": "SEE LICENSE IN LICENSE", "dependencies": { "agentkeepalive": "^3.5.2", diff --git a/package.json b/package.json index 6eeacb20e..5c26ca43c 100644 --- a/package.json +++ b/package.json @@ -40,6 +40,7 @@ "type": "git", "url": "git://github.com/pubnub/javascript.git" }, + "keywords": [ "cloud", "publish", diff --git a/rollup.config.js b/rollup.config.js index 9eeb322f3..cc481e66e 100644 --- a/rollup.config.js +++ b/rollup.config.js @@ -54,7 +54,7 @@ export default [ ], }, { - input: 'src/transport/service-worker/subscription-service-worker.ts', + input: 'src/transport/subscription-worker/subscription-worker.ts', output: { file: join(dirname(browser), basename(browser, '.min.js') + '.worker.min.js'), format: 'umd', @@ -69,7 +69,7 @@ export default [ ], }, { - input: 'src/transport/service-worker/subscription-service-worker.ts', + input: 'src/transport/subscription-worker/subscription-worker.ts', output: { file: join(dirname(browser), basename(browser, '.min.js') + '.worker.js'), format: 'umd', @@ -158,7 +158,7 @@ export default [ ], }, { - input: 'src/transport/service-worker/subscription-service-worker.ts', + input: 'src/transport/subscription-worker/subscription-worker.ts', output: { file: `upload/gzip/pubnub.worker.${version}.min.js`, format: 'umd', @@ -174,7 +174,7 @@ export default [ ], }, { - input: 'src/transport/service-worker/subscription-service-worker.ts', + input: 'src/transport/subscription-worker/subscription-worker.ts', output: { file: `upload/gzip/pubnub.worker.${version}.js`, format: 'umd', @@ -189,7 +189,7 @@ export default [ ], }, { - input: 'src/transport/service-worker/subscription-service-worker.ts', + input: 'src/transport/subscription-worker/subscription-worker.ts', output: { file: `upload/normal/pubnub.worker.${version}.min.js`, format: 'umd', @@ -204,7 +204,7 @@ export default [ ], }, { - input: 'src/transport/service-worker/subscription-service-worker.ts', + input: 'src/transport/subscription-worker/subscription-worker.ts', output: { file: `upload/normal/pubnub.worker.${version}.js`, format: 'umd', diff --git a/src/cbor/common.ts b/src/cbor/common.ts index a4149ca82..26c0ba1dd 100644 --- a/src/cbor/common.ts +++ b/src/cbor/common.ts @@ -4,6 +4,8 @@ /** * CBOR data decoder. + * + * @internal */ export default class Cbor { constructor( diff --git a/src/core/components/abort_signal.ts b/src/core/components/abort_signal.ts index ac990b782..caffb93c3 100644 --- a/src/core/components/abort_signal.ts +++ b/src/core/components/abort_signal.ts @@ -10,6 +10,11 @@ export class AbortError extends Error { } } +/** + * Event Engine stored effect processing cancellation signal. + * + * @internal + */ export class AbortSignal extends Subject { private _aborted = false; diff --git a/src/core/components/base64_codec.ts b/src/core/components/base64_codec.ts index 7908d5c75..c447673b7 100644 --- a/src/core/components/base64_codec.ts +++ b/src/core/components/base64_codec.ts @@ -5,6 +5,8 @@ const BASE64_CHARMAP = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123 * * @param paddedInput Base64 string with padding * @returns ArrayBuffer with decoded data + * + * @internal */ export function decode(paddedInput: string): ArrayBuffer { // Remove up to last two equal signs. @@ -54,6 +56,14 @@ export function decode(paddedInput: string): ArrayBuffer { return data; } +/** + * Encode `ArrayBuffer` as a Base64 encoded string. + * + * @param input ArrayBuffer with source data. + * @returns Base64 string with padding. + * + * @internal + */ export function encode(input: ArrayBuffer): string { let base64 = ''; const encodings = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'; diff --git a/src/core/components/configuration.ts b/src/core/components/configuration.ts index d46d2c5f1..316a122c6 100644 --- a/src/core/components/configuration.ts +++ b/src/core/components/configuration.ts @@ -15,6 +15,8 @@ import { Payload } from '../types/api'; /** * Whether encryption (if set) should use random initialization vector or not. + * + * @internal */ const USE_RANDOM_INITIALIZATION_VECTOR = true; // endregion @@ -23,6 +25,8 @@ const USE_RANDOM_INITIALIZATION_VECTOR = true; * Crypto Module instance configuration function. * * Function will be used each time when `cipherKey` will be changed. + * + * @internal */ type SetupCryptoModule = (configuration: CryptorConfiguration) => CryptoModule | undefined; @@ -69,6 +73,8 @@ type PrivateConfigurationFields = { * @param setupCryptoModule - Platform-provided {@link CryptoModule} configuration block. * * @returns `PubNub` client private configuration. + * + * @internal */ export const makeConfiguration = ( base: ExtendedConfiguration & PlatformConfiguration, diff --git a/src/core/components/deduping_manager.js b/src/core/components/deduping_manager.js index ab8aa9607..7d1503ce8 100644 --- a/src/core/components/deduping_manager.js +++ b/src/core/components/deduping_manager.js @@ -11,6 +11,11 @@ const hashCode = (payload) => { return hash; }; +/** + * Real-time events deduplication manager. + * + * @internal + */ export default class { _config; diff --git a/src/core/components/eventEmitter.ts b/src/core/components/eventEmitter.ts index 7f10d3112..bedc98ac8 100644 --- a/src/core/components/eventEmitter.ts +++ b/src/core/components/eventEmitter.ts @@ -2,6 +2,14 @@ import { Listener, ListenerManager } from './listener_manager'; import * as Subscription from '../types/api/subscription'; import { PubNubEventType } from '../endpoints/subscribe'; +/** + * Real-time events' emitter. + * + * Emitter responsible for forwarding received real-time events to the closures which has been + * registered for specific events handling. + * + * @internal + */ export default class EventEmitter { /** * Map of channels to listener callbacks for them. diff --git a/src/core/components/listener_manager.ts b/src/core/components/listener_manager.ts index 49e4c47d5..dd8d56040 100644 --- a/src/core/components/listener_manager.ts +++ b/src/core/components/listener_manager.ts @@ -95,6 +95,8 @@ export type Listener = { /** * Real-time listeners' manager. + * + * @internal */ export class ListenerManager { /** diff --git a/src/core/components/reconnection_manager.ts b/src/core/components/reconnection_manager.ts index eac22539b..2b3c18ba3 100644 --- a/src/core/components/reconnection_manager.ts +++ b/src/core/components/reconnection_manager.ts @@ -6,6 +6,13 @@ import { PubNubCore } from '../pubnub-common'; +/** + * Network "discovery" manager. + * + * Manager perform periodic `time` API calls to identify network availability. + * + * @internal + */ export class ReconnectionManager { /** * Successful availability check callback. diff --git a/src/core/components/request.ts b/src/core/components/request.ts index c0f328c73..f39499610 100644 --- a/src/core/components/request.ts +++ b/src/core/components/request.ts @@ -8,6 +8,8 @@ import uuidGenerator from './uuid'; /** * Base REST API request class. + * + * @internal */ export abstract class AbstractRequest implements Request { /** diff --git a/src/core/components/stringify_buffer_keys.ts b/src/core/components/stringify_buffer_keys.ts index 2b9247ff1..eff039140 100644 --- a/src/core/components/stringify_buffer_keys.ts +++ b/src/core/components/stringify_buffer_keys.ts @@ -1,3 +1,12 @@ +/** + * Re-map CBOR object keys from potentially C buffer strings to actual strings. + * + * @param obj CBOR which should be remapped to stringified keys. + * + * @returns Dictionary with stringified keys. + * + * @internal + */ export function stringifyBufferKeys(obj: unknown): Record { const isObject = (value: unknown): value is Record => typeof value === 'object' && value !== null && value.constructor === Object; diff --git a/src/core/components/subject.ts b/src/core/components/subject.ts index cad6fdffd..67d53a77a 100644 --- a/src/core/components/subject.ts +++ b/src/core/components/subject.ts @@ -1,5 +1,8 @@ type Listener = (event: T) => void; +/** + * @internal + */ export class Subject { protected listeners: Set> = new Set(); diff --git a/src/core/components/subscription-manager.ts b/src/core/components/subscription-manager.ts index 3f295c200..19b74ffdc 100644 --- a/src/core/components/subscription-manager.ts +++ b/src/core/components/subscription-manager.ts @@ -18,6 +18,8 @@ import EventEmitter from './eventEmitter'; /** * Subscription loop manager. + * + * @internal */ export class SubscriptionManager { /** diff --git a/src/core/components/token_manager.ts b/src/core/components/token_manager.ts index 97c5944d3..e60cf2a3f 100644 --- a/src/core/components/token_manager.ts +++ b/src/core/components/token_manager.ts @@ -192,6 +192,8 @@ type RawToken = { * REST API access token manager. * * Manager maintains active access token and let parse it to get information about permissions. + * + * @internal */ export class TokenManager { /** diff --git a/src/core/endpoints/access_manager/audit.ts b/src/core/endpoints/access_manager/audit.ts index e9aa8b8fd..bfcea42d3 100644 --- a/src/core/endpoints/access_manager/audit.ts +++ b/src/core/endpoints/access_manager/audit.ts @@ -64,6 +64,8 @@ type ServiceResponse = { /** * Permissions audit request. + * + * @internal */ export class AuditRequest extends AbstractRequest { constructor(private readonly parameters: RequestParameters) { diff --git a/src/core/endpoints/access_manager/grant.ts b/src/core/endpoints/access_manager/grant.ts index 43b98208d..bf83c69b1 100644 --- a/src/core/endpoints/access_manager/grant.ts +++ b/src/core/endpoints/access_manager/grant.ts @@ -94,6 +94,8 @@ type ServiceResponse = { /** * Grant permissions request. + * + * @internal */ export class GrantRequest extends AbstractRequest { constructor(private readonly parameters: RequestParameters) { diff --git a/src/core/endpoints/access_manager/grant_token.ts b/src/core/endpoints/access_manager/grant_token.ts index cd9b898dd..5c6d5de6a 100644 --- a/src/core/endpoints/access_manager/grant_token.ts +++ b/src/core/endpoints/access_manager/grant_token.ts @@ -88,6 +88,8 @@ type ServiceResponse = { /** * Grant token permissions request. + * + * @internal */ export class GrantTokenRequest extends AbstractRequest { constructor(private readonly parameters: RequestParameters) { diff --git a/src/core/endpoints/access_manager/revoke_token.ts b/src/core/endpoints/access_manager/revoke_token.ts index da4d95578..0063dab80 100644 --- a/src/core/endpoints/access_manager/revoke_token.ts +++ b/src/core/endpoints/access_manager/revoke_token.ts @@ -52,6 +52,8 @@ type ServiceResponse = { * Access token revoke request. * * Invalidate token and permissions which has been granted for it. + * + * @internal */ export class RevokeTokenRequest extends AbstractRequest { constructor(private readonly parameters: RequestParameters) { diff --git a/src/core/endpoints/actions/add_message_action.ts b/src/core/endpoints/actions/add_message_action.ts index e14a4142a..6f1192b58 100644 --- a/src/core/endpoints/actions/add_message_action.ts +++ b/src/core/endpoints/actions/add_message_action.ts @@ -45,6 +45,8 @@ type ServiceResponse = { /** * Add Message Reaction request. + * + * @internal */ export class AddMessageActionRequest extends AbstractRequest { constructor(private readonly parameters: RequestParameters) { diff --git a/src/core/endpoints/actions/get_message_actions.ts b/src/core/endpoints/actions/get_message_actions.ts index 60a729830..1bd8bb02b 100644 --- a/src/core/endpoints/actions/get_message_actions.ts +++ b/src/core/endpoints/actions/get_message_actions.ts @@ -49,6 +49,8 @@ type ServiceResponse = { /** * Fetch channel message actions request. + * + * @internal */ export class GetMessageActionsRequest extends AbstractRequest { constructor(private readonly parameters: RequestParameters) { diff --git a/src/core/endpoints/actions/remove_message_action.ts b/src/core/endpoints/actions/remove_message_action.ts index a7b397d7c..8c2eed84e 100644 --- a/src/core/endpoints/actions/remove_message_action.ts +++ b/src/core/endpoints/actions/remove_message_action.ts @@ -45,6 +45,8 @@ type ServiceResponse = { /** * Remove specific message action request. + * + * @internal */ export class RemoveMessageAction extends AbstractRequest { constructor(private readonly parameters: RequestParameters) { diff --git a/src/core/endpoints/channel_groups/add_channels.ts b/src/core/endpoints/channel_groups/add_channels.ts index 326e742c9..ad5e5473d 100644 --- a/src/core/endpoints/channel_groups/add_channels.ts +++ b/src/core/endpoints/channel_groups/add_channels.ts @@ -54,6 +54,8 @@ type ServiceResponse = { /** * Add channel group channels request. + * + * @internal */ export class AddChannelGroupChannelsRequest extends AbstractRequest { constructor(private readonly parameters: RequestParameters) { diff --git a/src/core/endpoints/channel_groups/delete_group.ts b/src/core/endpoints/channel_groups/delete_group.ts index e06a68c28..526e91098 100644 --- a/src/core/endpoints/channel_groups/delete_group.ts +++ b/src/core/endpoints/channel_groups/delete_group.ts @@ -54,6 +54,8 @@ type ServiceResponse = { /** * Channel group delete request. + * + * @internal */ export class DeleteChannelGroupRequest extends AbstractRequest { constructor(private readonly parameters: RequestParameters) { diff --git a/src/core/endpoints/channel_groups/list_channels.ts b/src/core/endpoints/channel_groups/list_channels.ts index d5bf3b8fa..a7d66308e 100644 --- a/src/core/endpoints/channel_groups/list_channels.ts +++ b/src/core/endpoints/channel_groups/list_channels.ts @@ -69,6 +69,8 @@ type ServiceResponse = { /** * List Channel Group Channels request. + * + * @internal */ export class ListChannelGroupChannels extends AbstractRequest { constructor(private readonly parameters: RequestParameters) { diff --git a/src/core/endpoints/channel_groups/list_groups.ts b/src/core/endpoints/channel_groups/list_groups.ts index 2d4ef4a02..531da6f4f 100644 --- a/src/core/endpoints/channel_groups/list_groups.ts +++ b/src/core/endpoints/channel_groups/list_groups.ts @@ -68,6 +68,8 @@ type ServiceResponse = { /** * List all channel groups request. + * + * @internal */ export class ListChannelGroupsRequest extends AbstractRequest { constructor(private readonly parameters: RequestParameters) { diff --git a/src/core/endpoints/channel_groups/remove_channels.ts b/src/core/endpoints/channel_groups/remove_channels.ts index 0301d36e5..d8f78d1c9 100644 --- a/src/core/endpoints/channel_groups/remove_channels.ts +++ b/src/core/endpoints/channel_groups/remove_channels.ts @@ -54,6 +54,8 @@ type ServiceResponse = { /** * Remove channel group channels request. + * + * @internal */ // prettier-ignore export class RemoveChannelGroupChannelsRequest extends AbstractRequest< diff --git a/src/core/endpoints/fetch_messages.ts b/src/core/endpoints/fetch_messages.ts index cb5927495..a8b0298b0 100644 --- a/src/core/endpoints/fetch_messages.ts +++ b/src/core/endpoints/fetch_messages.ts @@ -162,6 +162,8 @@ type ServiceResponse = { /** * Fetch messages from channels request. + * + * @internal */ export class FetchMessagesRequest extends AbstractRequest { constructor(private readonly parameters: RequestParameters) { diff --git a/src/core/endpoints/file_upload/delete_file.ts b/src/core/endpoints/file_upload/delete_file.ts index 7ccacb914..fc5dcc976 100644 --- a/src/core/endpoints/file_upload/delete_file.ts +++ b/src/core/endpoints/file_upload/delete_file.ts @@ -40,6 +40,8 @@ type ServiceResponse = { /** * Delete File request. + * + * @internal */ export class DeleteFileRequest extends AbstractRequest { constructor(private readonly parameters: RequestParameters) { diff --git a/src/core/endpoints/file_upload/download_file.ts b/src/core/endpoints/file_upload/download_file.ts index 6f91ec76a..9d1c9bade 100644 --- a/src/core/endpoints/file_upload/download_file.ts +++ b/src/core/endpoints/file_upload/download_file.ts @@ -45,6 +45,8 @@ type RequestParameters = FileSharing.DownloadFileParameters & { /** * Download File request. + * + * @internal */ export class DownloadFileRequest< PlatformFile extends Partial = Record, diff --git a/src/core/endpoints/file_upload/generate_upload_url.ts b/src/core/endpoints/file_upload/generate_upload_url.ts index 8f1b43b1c..264d57365 100644 --- a/src/core/endpoints/file_upload/generate_upload_url.ts +++ b/src/core/endpoints/file_upload/generate_upload_url.ts @@ -100,6 +100,8 @@ type ServiceResponse = { /** * Generate File Upload Url request. + * + * @internal */ export class GenerateFileUploadUrlRequest extends AbstractRequest { constructor(private readonly parameters: RequestParameters) { diff --git a/src/core/endpoints/file_upload/get_file_url.ts b/src/core/endpoints/file_upload/get_file_url.ts index 300ed96d6..449284416 100644 --- a/src/core/endpoints/file_upload/get_file_url.ts +++ b/src/core/endpoints/file_upload/get_file_url.ts @@ -30,6 +30,8 @@ type RequestParameters = FileSharing.FileUrlParameters & { * File download Url generation request. * * Local request which generates Url to download shared file from the specific channel. + * + * @internal */ export class GetFileDownloadUrlRequest extends AbstractRequest { /** diff --git a/src/core/endpoints/file_upload/list_files.ts b/src/core/endpoints/file_upload/list_files.ts index 0d1f95304..7f899f7ea 100644 --- a/src/core/endpoints/file_upload/list_files.ts +++ b/src/core/endpoints/file_upload/list_files.ts @@ -65,6 +65,8 @@ type ServiceResponse = { /** * Files List request. + * + * @internal */ export class FilesListRequest extends AbstractRequest { constructor(private readonly parameters: RequestParameters) { diff --git a/src/core/endpoints/file_upload/publish_file.ts b/src/core/endpoints/file_upload/publish_file.ts index a88fd5682..0c9af86e6 100644 --- a/src/core/endpoints/file_upload/publish_file.ts +++ b/src/core/endpoints/file_upload/publish_file.ts @@ -49,6 +49,11 @@ type RequestParameters = FileSharing.PublishFileMessageParameters & { type ServiceResponse = [0 | 1, string, string]; // endregion +/** + * Publish shared file information request. + * + * @internal + */ export class PublishFileMessageRequest extends AbstractRequest { constructor(private readonly parameters: RequestParameters) { super(); diff --git a/src/core/endpoints/file_upload/send_file.ts b/src/core/endpoints/file_upload/send_file.ts index 0c50dfae6..97fad2f1c 100644 --- a/src/core/endpoints/file_upload/send_file.ts +++ b/src/core/endpoints/file_upload/send_file.ts @@ -72,6 +72,8 @@ type RequestParameters = FileSharing.SendFileParameters { /** diff --git a/src/core/endpoints/file_upload/upload-file.ts b/src/core/endpoints/file_upload/upload-file.ts index 7147e819c..e63e8c6b4 100644 --- a/src/core/endpoints/file_upload/upload-file.ts +++ b/src/core/endpoints/file_upload/upload-file.ts @@ -11,6 +11,8 @@ import { PubNubFileInterface } from '../../types/file'; /** * File Upload request. + * + * @internal */ export class UploadFileRequest extends AbstractRequest { constructor(private readonly parameters: FileSharing.UploadFileParameters) { diff --git a/src/core/endpoints/history/delete_messages.ts b/src/core/endpoints/history/delete_messages.ts index f2a4f8269..4a12022eb 100644 --- a/src/core/endpoints/history/delete_messages.ts +++ b/src/core/endpoints/history/delete_messages.ts @@ -50,6 +50,8 @@ type ServiceResponse = { /** * Delete messages from channel history. + * + * @internal */ export class DeleteMessageRequest extends AbstractRequest { constructor(private readonly parameters: RequestParameters) { diff --git a/src/core/endpoints/history/get_history.ts b/src/core/endpoints/history/get_history.ts index 206a05b57..b340aba49 100644 --- a/src/core/endpoints/history/get_history.ts +++ b/src/core/endpoints/history/get_history.ts @@ -103,6 +103,8 @@ type ServiceResponse = [ /** * Get single channel messages request. + * + * @internal */ export class GetHistoryRequest extends AbstractRequest { constructor(private readonly parameters: RequestParameters) { diff --git a/src/core/endpoints/history/message_counts.ts b/src/core/endpoints/history/message_counts.ts index 6672fe8e4..8413b6b3b 100644 --- a/src/core/endpoints/history/message_counts.ts +++ b/src/core/endpoints/history/message_counts.ts @@ -68,6 +68,11 @@ type ServiceResponse = { }; // endregion +/** + * Count messages request. + * + * @internal + */ export class MessageCountRequest extends AbstractRequest { constructor(private readonly parameters: RequestParameters) { super(); diff --git a/src/core/endpoints/objects/channel/get.ts b/src/core/endpoints/objects/channel/get.ts index 3c1534218..6136f62c9 100644 --- a/src/core/endpoints/objects/channel/get.ts +++ b/src/core/endpoints/objects/channel/get.ts @@ -40,6 +40,8 @@ type RequestParameters = AppContext.GetChannelMetadataParameters & { /** * Get Channel Metadata request. + * + * @internal */ export class GetChannelMetadataRequest< Response extends AppContext.GetChannelMetadataResponse, diff --git a/src/core/endpoints/objects/channel/get_all.ts b/src/core/endpoints/objects/channel/get_all.ts index cd442c42f..b4f97889b 100644 --- a/src/core/endpoints/objects/channel/get_all.ts +++ b/src/core/endpoints/objects/channel/get_all.ts @@ -50,6 +50,8 @@ type RequestParameters, diff --git a/src/core/endpoints/objects/channel/remove.ts b/src/core/endpoints/objects/channel/remove.ts index 50918491d..05148fdc4 100644 --- a/src/core/endpoints/objects/channel/remove.ts +++ b/src/core/endpoints/objects/channel/remove.ts @@ -30,6 +30,8 @@ type RequestParameters = AppContext.RemoveChannelMetadataParameters & { /** * Remove Channel Metadata request. + * + * @internal */ export class RemoveChannelMetadataRequest< Response extends AppContext.RemoveChannelMetadataResponse, diff --git a/src/core/endpoints/objects/channel/set.ts b/src/core/endpoints/objects/channel/set.ts index 555604d2c..57482a05e 100644 --- a/src/core/endpoints/objects/channel/set.ts +++ b/src/core/endpoints/objects/channel/set.ts @@ -41,6 +41,8 @@ type RequestParameters = AppContext.SetChannelMetadataParameters, diff --git a/src/core/endpoints/objects/member/get.ts b/src/core/endpoints/objects/member/get.ts index 1b80c78b8..2425c258e 100644 --- a/src/core/endpoints/objects/member/get.ts +++ b/src/core/endpoints/objects/member/get.ts @@ -75,6 +75,8 @@ type RequestParameters = AppContext.GetMembersParameters & { /** * Get Channel Members request. + * + * @internal */ export class GetChannelMembersRequest< Response extends AppContext.GetMembersResponse, diff --git a/src/core/endpoints/objects/member/set.ts b/src/core/endpoints/objects/member/set.ts index c5bb2500d..f0d5b3ed7 100644 --- a/src/core/endpoints/objects/member/set.ts +++ b/src/core/endpoints/objects/member/set.ts @@ -66,6 +66,8 @@ type RequestParameters = AppContext.SetChannelMembersParameters, diff --git a/src/core/endpoints/objects/membership/get.ts b/src/core/endpoints/objects/membership/get.ts index 34e2b6dab..30048e526 100644 --- a/src/core/endpoints/objects/membership/get.ts +++ b/src/core/endpoints/objects/membership/get.ts @@ -75,6 +75,8 @@ type RequestParameters = AppContext.GetMembershipsParameters & { /** * Get UUID Memberships request. + * + * @internal */ export class GetUUIDMembershipsRequest< Response extends AppContext.GetMembershipsResponse, diff --git a/src/core/endpoints/objects/membership/set.ts b/src/core/endpoints/objects/membership/set.ts index 1633dcce1..5b1edc29e 100644 --- a/src/core/endpoints/objects/membership/set.ts +++ b/src/core/endpoints/objects/membership/set.ts @@ -66,6 +66,8 @@ type RequestParameters = AppContext.SetMembershipsParameters, diff --git a/src/core/endpoints/objects/uuid/get.ts b/src/core/endpoints/objects/uuid/get.ts index 7a93648aa..b58342797 100644 --- a/src/core/endpoints/objects/uuid/get.ts +++ b/src/core/endpoints/objects/uuid/get.ts @@ -40,6 +40,8 @@ type RequestParameters = AppContext.GetUUIDMetadataParameters & { /** * Get UUID Metadata request. + * + * @internal */ export class GetUUIDMetadataRequest< Response extends AppContext.GetUUIDMetadataResponse, diff --git a/src/core/endpoints/objects/uuid/get_all.ts b/src/core/endpoints/objects/uuid/get_all.ts index c7b5efca8..744a4d6e8 100644 --- a/src/core/endpoints/objects/uuid/get_all.ts +++ b/src/core/endpoints/objects/uuid/get_all.ts @@ -43,6 +43,11 @@ type RequestParameters, Custom extends AppContext.CustomData = AppContext.CustomData, diff --git a/src/core/endpoints/objects/uuid/remove.ts b/src/core/endpoints/objects/uuid/remove.ts index 2bc521d6f..b84707fde 100644 --- a/src/core/endpoints/objects/uuid/remove.ts +++ b/src/core/endpoints/objects/uuid/remove.ts @@ -30,6 +30,8 @@ type RequestParameters = AppContext.RemoveUUIDMetadataParameters & { /** * Remove UUID Metadata request. + * + * @internal */ export class RemoveUUIDMetadataRequest< Response extends AppContext.RemoveUUIDMetadataResponse, diff --git a/src/core/endpoints/objects/uuid/set.ts b/src/core/endpoints/objects/uuid/set.ts index 9ba8736c7..403ebd1aa 100644 --- a/src/core/endpoints/objects/uuid/set.ts +++ b/src/core/endpoints/objects/uuid/set.ts @@ -41,6 +41,8 @@ type RequestParameters = AppContext.SetUUIDMetadataParameters, diff --git a/src/core/endpoints/presence/get_state.ts b/src/core/endpoints/presence/get_state.ts index ede87639e..3a00f1893 100644 --- a/src/core/endpoints/presence/get_state.ts +++ b/src/core/endpoints/presence/get_state.ts @@ -59,6 +59,8 @@ type ServiceResponse = { /** * Get `uuid` presence state request. + * + * @internal */ export class GetPresenceStateRequest extends AbstractRequest { constructor(private readonly parameters: RequestParameters) { diff --git a/src/core/endpoints/presence/heartbeat.ts b/src/core/endpoints/presence/heartbeat.ts index 80c26f1d3..71eeece41 100644 --- a/src/core/endpoints/presence/heartbeat.ts +++ b/src/core/endpoints/presence/heartbeat.ts @@ -47,6 +47,11 @@ type ServiceResponse = { }; // endregion +/** + * Announce `uuid` presence request. + * + * @internal + */ export class HeartbeatRequest extends AbstractRequest { constructor(private readonly parameters: RequestParameters) { super(); diff --git a/src/core/endpoints/presence/here_now.ts b/src/core/endpoints/presence/here_now.ts index 79eaa7af3..db494f9ad 100644 --- a/src/core/endpoints/presence/here_now.ts +++ b/src/core/endpoints/presence/here_now.ts @@ -124,6 +124,11 @@ type MultipleChannelServiceResponse = BasicServiceResponse & { type ServiceResponse = SingleChannelServiceResponse | MultipleChannelServiceResponse; // endregion +/** + * Channel presence request. + * + * @internal + */ export class HereNowRequest extends AbstractRequest { constructor(private readonly parameters: RequestParameters) { super(); diff --git a/src/core/endpoints/presence/leave.ts b/src/core/endpoints/presence/leave.ts index 4dfb32194..36ff29c1f 100644 --- a/src/core/endpoints/presence/leave.ts +++ b/src/core/endpoints/presence/leave.ts @@ -52,6 +52,11 @@ type ServiceResponse = { }; // endregion +/** + * Announce user leave request. + * + * @internal + */ export class PresenceLeaveRequest extends AbstractRequest { constructor(private readonly parameters: RequestParameters) { super(); diff --git a/src/core/endpoints/presence/set_state.ts b/src/core/endpoints/presence/set_state.ts index 583ff2343..9e0776bef 100644 --- a/src/core/endpoints/presence/set_state.ts +++ b/src/core/endpoints/presence/set_state.ts @@ -59,6 +59,8 @@ type ServiceResponse = { /** * Set `uuid` presence state request. + * + * @internal */ export class SetPresenceStateRequest extends AbstractRequest { constructor(private readonly parameters: RequestParameters) { diff --git a/src/core/endpoints/presence/where_now.ts b/src/core/endpoints/presence/where_now.ts index 379b578a3..533a3f73b 100644 --- a/src/core/endpoints/presence/where_now.ts +++ b/src/core/endpoints/presence/where_now.ts @@ -57,6 +57,11 @@ type ServiceResponse = { }; // endregion +/** + * Get `uuid` presence request. + * + * @internal + */ export class WhereNowRequest extends AbstractRequest { constructor(private readonly parameters: RequestParameters) { super(); diff --git a/src/core/endpoints/publish.ts b/src/core/endpoints/publish.ts index 93f369c8b..47c9110e2 100644 --- a/src/core/endpoints/publish.ts +++ b/src/core/endpoints/publish.ts @@ -127,6 +127,8 @@ type ServiceResponse = [0 | 1, string, string]; * * Request will normalize and encrypt (if required) provided data and push it to the specified * channel. + * + * @internal */ export class PublishRequest extends AbstractRequest { /** diff --git a/src/core/endpoints/push/add_push_channels.ts b/src/core/endpoints/push/add_push_channels.ts index 8692f4b50..5265071d9 100644 --- a/src/core/endpoints/push/add_push_channels.ts +++ b/src/core/endpoints/push/add_push_channels.ts @@ -32,6 +32,8 @@ type ServiceResponse = [0 | 1, string]; /** * Register channels with device push request. + * + * @internal */ // prettier-ignore export class AddDevicePushNotificationChannelsRequest extends BasePushNotificationChannelsRequest< diff --git a/src/core/endpoints/push/list_push_channels.ts b/src/core/endpoints/push/list_push_channels.ts index 725bbbefc..1892463a3 100644 --- a/src/core/endpoints/push/list_push_channels.ts +++ b/src/core/endpoints/push/list_push_channels.ts @@ -32,6 +32,8 @@ type ServiceResponse = string[]; /** * List device push enabled channels request. + * + * @internal */ // prettier-ignore export class ListDevicePushNotificationChannelsRequest extends BasePushNotificationChannelsRequest< diff --git a/src/core/endpoints/push/push.ts b/src/core/endpoints/push/push.ts index 20e231d62..660435f30 100644 --- a/src/core/endpoints/push/push.ts +++ b/src/core/endpoints/push/push.ts @@ -47,6 +47,8 @@ type RequestParameters = (Push.ManageDeviceChannelsParameters | Push.RemoveDevic /** * Base push notification request. + * + * @internal */ export class BasePushNotificationChannelsRequest extends AbstractRequest { constructor(private readonly parameters: RequestParameters) { diff --git a/src/core/endpoints/push/remove_device.ts b/src/core/endpoints/push/remove_device.ts index 5fd4235f3..e0108d5fe 100644 --- a/src/core/endpoints/push/remove_device.ts +++ b/src/core/endpoints/push/remove_device.ts @@ -32,6 +32,8 @@ type ServiceResponse = [0 | 1, string]; /** * Unregister device push notifications request. + * + * @internal */ // prettier-ignore export class RemoveDevicePushNotificationRequest extends BasePushNotificationChannelsRequest< diff --git a/src/core/endpoints/push/remove_push_channels.ts b/src/core/endpoints/push/remove_push_channels.ts index 69a939045..ce4fac47e 100644 --- a/src/core/endpoints/push/remove_push_channels.ts +++ b/src/core/endpoints/push/remove_push_channels.ts @@ -32,6 +32,8 @@ type ServiceResponse = [0 | 1, string]; /** * Unregister channels from device push request. + * + * @internal */ // prettier-ignore export class RemoveDevicePushNotificationChannelsRequest extends BasePushNotificationChannelsRequest< diff --git a/src/core/endpoints/signal.ts b/src/core/endpoints/signal.ts index b17379d89..5d1c84d05 100644 --- a/src/core/endpoints/signal.ts +++ b/src/core/endpoints/signal.ts @@ -57,6 +57,11 @@ type RequestParameters = SignalParameters & { type ServiceResponse = [0 | 1, string, string]; // endregion +/** + * Signal data (size-limited) publish request. + * + * @internal + */ export class SignalRequest extends AbstractRequest { constructor(private readonly parameters: RequestParameters) { super(); diff --git a/src/core/endpoints/subscribe.ts b/src/core/endpoints/subscribe.ts index d31302ce5..ee179ab24 100644 --- a/src/core/endpoints/subscribe.ts +++ b/src/core/endpoints/subscribe.ts @@ -32,6 +32,8 @@ const WITH_PRESENCE = false; /** * PubNub-defined event types by payload. + * + * @internal */ export enum PubNubEventType { /** @@ -191,6 +193,8 @@ type PresenceStateChangeData = { /** * Channel presence service response. + * + * @internal */ export type PresenceData = PresenceIntervalData | PresenceChangeData | PresenceStateChangeData; // endregion @@ -198,6 +202,8 @@ export type PresenceData = PresenceIntervalData | PresenceChangeData | PresenceS // region Message Actions service response /** * Message reaction change service response. + * + * @internal */ export type MessageActionData = { /** @@ -303,6 +309,8 @@ type ChannelObjectData = ObjectData< /** * `Space` object change real-time service response. + * + * @internal */ export type SpaceObjectData = ObjectData< AppContextVSPEvents, @@ -317,6 +325,8 @@ type UuidObjectData = ObjectData { constructor(protected readonly parameters: RequestParameters) { @@ -840,6 +860,8 @@ export class BaseSubscribeRequest extends AbstractRequest { constructor() { super(); diff --git a/src/core/interfaces/configuration.ts b/src/core/interfaces/configuration.ts index 4003f427b..dc8409957 100644 --- a/src/core/interfaces/configuration.ts +++ b/src/core/interfaces/configuration.ts @@ -325,6 +325,8 @@ export type UserConfiguration = { * Extended client configuration. * * Extended configuration contains unannounced configuration options. + * + * @internal */ export type ExtendedConfiguration = UserConfiguration & { /** diff --git a/src/core/interfaces/request.ts b/src/core/interfaces/request.ts index 77168006f..df1e443b7 100644 --- a/src/core/interfaces/request.ts +++ b/src/core/interfaces/request.ts @@ -4,6 +4,8 @@ import RequestOperation from '../constants/operations'; /** * General REST API call request interface. + * + * @internal */ export interface Request { /** diff --git a/src/core/pubnub-common.ts b/src/core/pubnub-common.ts index bfac679c0..fbde5b550 100644 --- a/src/core/pubnub-common.ts +++ b/src/core/pubnub-common.ts @@ -150,6 +150,8 @@ export class PubNubCore< > { /** * PubNub client configuration. + * + * @internal */ protected readonly _configuration: PrivateClientConfiguration; @@ -157,71 +159,98 @@ export class PubNubCore< * Subscription loop manager. * * **Note:** Manager created when EventEngine is off. + * + * @internal */ private readonly subscriptionManager?: SubscriptionManager; /** * Transport for network requests processing. + * + * @internal */ protected readonly transport: Transport; /** * REST API endpoints access tokens manager. + * + * @internal */ private readonly tokenManager: TokenManager; /** * Legacy crypto module implementation. + * + * @internal */ private readonly cryptography?: Cryptography; /** * Legacy crypto (legacy data encryption / decryption and request signature support). + * + * @internal */ private readonly crypto?: Crypto; /** * Real-time event listeners manager. + * + * @internal */ protected readonly listenerManager: ListenerManager; /** * User's presence event engine. + * + * @internal */ private presenceEventEngine?: PresenceEventEngine; /** * Subscription event engine. + * + * @internal */ private readonly eventEngine?: EventEngine; /** * Client-managed presence information. + * + * @internal */ private readonly presenceState?: Record; /** * Real-time events emitter. + * + * @internal */ private readonly eventEmitter: EventEmitter; /** * PubNub App Context REST API entry point. + * + * @internal */ private readonly _objects: PubNubObjects; /** * PubNub Channel Group REST API entry point. */ + // @internal @ts-ignore private readonly _channelGroups: PubNubChannelGroups; /** * PubNub Push Notification REST API entry point. + * + * @internal */ private readonly _push: PubNubPushNotifications; /** - * {@link ArrayBuffer} to {@link string} decoder. + * {@link ArrayBuffer} to {@link string} decoder. + * + * @internal */ private static decoder = new TextDecoder(); diff --git a/src/core/utils.ts b/src/core/utils.ts index dc65d95b4..5cee8bf45 100644 --- a/src/core/utils.ts +++ b/src/core/utils.ts @@ -27,7 +27,7 @@ export const encodeNames = (names: string[], defaultString?: string) => { return encodedNames.length ? encodedNames.join(',') : defaultString ?? ''; }; -export const removeSingleOccurance = (source: string[], elementsToRemove: string[]) => { +export const removeSingleOccurrence = (source: string[], elementsToRemove: string[]) => { const removed = Object.fromEntries(elementsToRemove.map((prop) => [prop, false])); return source.filter((e) => { diff --git a/src/event-engine/index.ts b/src/event-engine/index.ts index 871d78c7e..983a659c5 100644 --- a/src/event-engine/index.ts +++ b/src/event-engine/index.ts @@ -76,12 +76,12 @@ export class EventEngine { } unsubscribe({ channels = [], channelGroups = [] }: { channels?: string[]; channelGroups?: string[] }): void { - const filteredChannels = utils.removeSingleOccurance(this.channels, [ + const filteredChannels = utils.removeSingleOccurrence(this.channels, [ ...channels, ...channels.map((c) => `${c}-pnpres`), ]); - const filteredGroups = utils.removeSingleOccurance(this.groups, [ + const filteredGroups = utils.removeSingleOccurrence(this.groups, [ ...channelGroups, ...channelGroups.map((c) => `${c}-pnpres`), ]); diff --git a/src/node/configuration.ts b/src/node/configuration.ts index a3c5d2b99..e23d744d8 100644 --- a/src/node/configuration.ts +++ b/src/node/configuration.ts @@ -7,9 +7,9 @@ import { ExtendedConfiguration, setDefaults as setBaseDefaults, } from '../core/interfaces/configuration'; -import { CryptoModule } from '../crypto/modules/NodeCryptoModule/nodeCryptoModule'; import { TransportKeepAlive } from '../core/interfaces/transport'; import { Payload } from '../core/types/api'; +import { CryptoModule } from '../core/interfaces/crypto-module'; // -------------------------------------------------------- // ----------------------- Defaults ----------------------- diff --git a/src/node/index.ts b/src/node/index.ts index a3ac1273b..63f3b1d4f 100755 --- a/src/node/index.ts +++ b/src/node/index.ts @@ -22,7 +22,7 @@ import Cbor from '../cbor/common'; /** * PubNub client for Node.js platform. */ -export = class PubNub extends PubNubCore { +class PubNub extends PubNubCore { /** * Data encryption / decryption module constructor. */ @@ -104,4 +104,6 @@ export = class PubNub extends PubNubCore void; reject: (value: Error) => void }>; /** - * Subscription service worker. + * Subscription shared worker. * - * **Note:** Web PubNub SDK Transport provider adjustment for explicit subscription feature support. + * **Note:** Browser PubNub SDK Transport provider adjustment for explicit subscription / leave features support. */ - serviceWorkerRegistration?: ServiceWorkerRegistration; + subscriptionWorker?: SharedWorker; /** * Queue of events for service worker. * * Keep list of events which should be sent to the worker after its activation. */ - serviceWorkerEventsQueue: PubNubSubscriptionServiceWorker.ClientEvent[]; + workerEventsQueue: PubNubSubscriptionWorker.ClientEvent[]; + + /** + * Whether subscription worker has been initialized and ready to handle events. + */ + subscriptionWorkerReady: boolean = false; constructor(private readonly configuration: PubNubMiddlewareConfiguration) { - this.serviceWorkerEventsQueue = []; + this.workerEventsQueue = []; this.callbacks = new Map(); - this.setupServiceWorker(); + this.setupSubscriptionWorker(); } makeSendable(req: TransportRequest): [Promise, CancellationController | undefined] { @@ -87,7 +102,7 @@ export class SubscriptionServiceWorkerMiddleware implements Transport { return this.configuration.transport.makeSendable(req); let controller: CancellationController | undefined; - const sendRequestEvent: PubNubSubscriptionServiceWorker.SendRequestEvent = { + const sendRequestEvent: PubNubSubscriptionWorker.SendRequestEvent = { type: 'send-request', clientIdentifier: this.configuration.clientIdentifier, subscriptionKey: this.configuration.subscriptionKey, @@ -98,7 +113,7 @@ export class SubscriptionServiceWorkerMiddleware implements Transport { if (req.cancellable) { controller = { abort: () => { - const cancelRequest: PubNubSubscriptionServiceWorker.CancelRequestEvent = { + const cancelRequest: PubNubSubscriptionWorker.CancelRequestEvent = { type: 'cancel-request', clientIdentifier: this.configuration.clientIdentifier, subscriptionKey: this.configuration.subscriptionKey, @@ -130,42 +145,42 @@ export class SubscriptionServiceWorkerMiddleware implements Transport { } /** - * Schedule {@link event} publish to the service worker. + * Schedule {@link event} publish to the subscription worker. * - * Service worker may not be ready for events processing and this method build queue for the time when worker will be - * ready. + * Subscription worker may not be ready for events processing and this method build queue for the time when worker + * will be ready. * - * @param event - Event payload for service worker. + * @param event - Event payload for the subscription worker. * @param outOfOrder - Whether event should be processed first then enqueued queue. */ - private scheduleEventPost(event: PubNubSubscriptionServiceWorker.ClientEvent, outOfOrder: boolean = false) { - // Trigger request processing by Web Worker. - const serviceWorker = this.serviceWorker; - if (serviceWorker) serviceWorker.postMessage(event); + private scheduleEventPost(event: PubNubSubscriptionWorker.ClientEvent, outOfOrder: boolean = false) { + // Trigger request processing by subscription worker. + const subscriptionWorker = this.sharedSubscriptionWorker; + if (subscriptionWorker) subscriptionWorker.port.postMessage(event); else { - if (outOfOrder) this.serviceWorkerEventsQueue.splice(0, 0, event); - else this.serviceWorkerEventsQueue.push(event); + if (outOfOrder) this.workerEventsQueue.splice(0, 0, event); + else this.workerEventsQueue.push(event); } } /** - * Dequeue and post events from the queue to the service worker. + * Dequeue and post events from the queue to the subscription worker. */ private flushScheduledEvents(): void { - // Trigger request processing by Web Worker. - const serviceWorker = this.serviceWorker; - if (!serviceWorker || this.serviceWorkerEventsQueue.length === 0) return; + // Trigger request processing by subscription worker. + const subscriptionWorker = this.sharedSubscriptionWorker; + if (!subscriptionWorker || this.workerEventsQueue.length === 0) return; // Clean up from cancelled events. - const outdatedEvents: PubNubSubscriptionServiceWorker.ClientEvent[] = []; - for (let i = 0; i < this.serviceWorkerEventsQueue.length; i++) { - const event = this.serviceWorkerEventsQueue[i]; + const outdatedEvents: PubNubSubscriptionWorker.ClientEvent[] = []; + for (let i = 0; i < this.workerEventsQueue.length; i++) { + const event = this.workerEventsQueue[i]; // Check whether found request cancel event to search for request send event it cancels. if (event.type !== 'cancel-request' || i === 0) continue; for (let j = 0; j < i; j++) { - const otherEvent = this.serviceWorkerEventsQueue[j]; + const otherEvent = this.workerEventsQueue[j]; if (otherEvent.type !== 'send-request') continue; // Collect outdated events if identifiers match. @@ -177,73 +192,77 @@ export class SubscriptionServiceWorkerMiddleware implements Transport { } // Actualizing events queue. - this.serviceWorkerEventsQueue = this.serviceWorkerEventsQueue.filter((event) => !outdatedEvents.includes(event)); - this.serviceWorkerEventsQueue.forEach((event) => serviceWorker.postMessage(event)); - this.serviceWorkerEventsQueue = []; + this.workerEventsQueue = this.workerEventsQueue.filter((event) => !outdatedEvents.includes(event)); + this.workerEventsQueue.forEach((event) => subscriptionWorker.port.postMessage(event)); + this.workerEventsQueue = []; } /** - * Subscription service worker. + * Subscription worker. * - * @returns Service worker which has been registered by the PubNub SDK. + * @returns Worker which has been registered by the PubNub SDK. */ - private get serviceWorker() { - return this.serviceWorkerRegistration ? this.serviceWorkerRegistration.active : null; + private get sharedSubscriptionWorker() { + return this.subscriptionWorkerReady ? this.subscriptionWorker : null; } - private setupServiceWorker(): void { - if (!('serviceWorker' in navigator)) return; - const serviceWorkerContainer = navigator.serviceWorker as ServiceWorkerContainer; - serviceWorkerContainer - .register(this.configuration.serviceWorkerUrl, { - scope: `/pubnub-${this.configuration.sdkVersion}`, - }) - .then((registration) => { - this.serviceWorkerRegistration = registration; - - // Flush any pending service worker events. - if (registration.active) this.flushScheduledEvents(); - - /** - * Listening for service worker code update. - * - * It is possible that one of the tabs will open with newer SDK version and Subscription Service Worker - * will be re-installed - in this case we need to "rehydrate" it. - * - * After re-installation of new service worker it will lose all accumulated state and client need to - * re-introduce itself and its state. - */ - this.serviceWorkerRegistration.addEventListener('updatefound', () => { - if (!this.serviceWorkerRegistration) return; - - // New service installing right now. - const serviceWorker = this.serviceWorkerRegistration.installing!; - - const stateChangeListener = () => { - // Flush any pending service worker events. - if (serviceWorker.state === 'activated') { - // Flush any pending service worker events. - this.flushScheduledEvents(); - } else if (serviceWorker.state === 'redundant') { - // Clean up listener from deprecated service worker version. - serviceWorker.removeEventListener('statechange', stateChangeListener); - } - }; - - serviceWorker.addEventListener('statechange', stateChangeListener); - }); - }); - - serviceWorkerContainer.addEventListener('message', (event) => this.handleServiceWorkerEvent(event)); + private setupSubscriptionWorker(): void { + if (typeof SharedWorker === 'undefined') return; + + this.subscriptionWorker = new SharedWorker( + this.configuration.workerUrl, + `/pubnub-${this.configuration.sdkVersion}`, + ); + + this.subscriptionWorker.port.start(); + + // Register PubNub client within subscription worker. + this.scheduleEventPost( + { + type: 'client-register', + clientIdentifier: this.configuration.clientIdentifier, + subscriptionKey: this.configuration.subscriptionKey, + userId: this.configuration.userId, + logVerbosity: this.configuration.logVerbosity, + workerLogVerbosity: this.configuration.workerLogVerbosity, + }, + true, + ); + + this.subscriptionWorker.port.onmessage = (event) => this.handleWorkerEvent(event); } - private handleServiceWorkerEvent(event: MessageEvent) { + private handleWorkerEvent(event: MessageEvent) { const { data } = event; // Ignoring updates not related to this instance. - if (data.clientIdentifier !== this.configuration.clientIdentifier) return; - - if (data.type === 'request-progress-start' || data.type === 'request-progress-end') { + if ( + data.type !== 'shared-worker-ping' && + data.type !== 'shared-worker-connected' && + data.type !== 'shared-worker-console-log' && + data.type !== 'shared-worker-console-dir' && + data.clientIdentifier !== this.configuration.clientIdentifier + ) + return; + + if (data.type === 'shared-worker-connected') { + this.subscriptionWorkerReady = true; + this.flushScheduledEvents(); + } else if (data.type === 'shared-worker-console-log') { + console.log(`[SharedWorker] ${data.message}`); + } else if (data.type === 'shared-worker-console-dir') { + if (data.message) console.log(`[SharedWorker] ${data.message}`); + console.dir(data.data); + } else if (data.type === 'shared-worker-ping') { + const { logVerbosity, subscriptionKey, clientIdentifier } = this.configuration; + + this.scheduleEventPost({ + type: 'client-pong', + subscriptionKey, + clientIdentifier, + logVerbosity, + }); + } else if (data.type === 'request-progress-start' || data.type === 'request-progress-end') { this.logRequestProgress(data); } else if (data.type === 'request-process-success' || data.type === 'request-process-error') { const { resolve, reject } = this.callbacks!.get(data.identifier)!; @@ -289,9 +308,9 @@ export class SubscriptionServiceWorkerMiddleware implements Transport { /** * Print request progress information. * - * @param information - Request progress information from Web Worker. + * @param information - Request progress information from worker. */ - private logRequestProgress(information: PubNubSubscriptionServiceWorker.RequestSendingProgress) { + private logRequestProgress(information: PubNubSubscriptionWorker.RequestSendingProgress) { if (information.type === 'request-progress-start') { console.log('<<<<<'); console.log(`[${information.timestamp}] ${information.url}\n${JSON.stringify(information.query ?? {})}`); diff --git a/src/transport/service-worker/subscription-service-worker.ts b/src/transport/subscription-worker/subscription-worker.ts similarity index 71% rename from src/transport/service-worker/subscription-service-worker.ts rename to src/transport/subscription-worker/subscription-worker.ts index 970ded65a..84fb67c60 100644 --- a/src/transport/service-worker/subscription-service-worker.ts +++ b/src/transport/subscription-worker/subscription-worker.ts @@ -34,6 +34,28 @@ type BasicEvent = { * Whether verbose logging enabled or not. */ logVerbosity: boolean; + + /** + * Whether verbose logging should be enabled for `Subscription` worker should print debug messages or not. + */ + workerLogVerbosity?: boolean; +}; + +/** + * PubNub client registration event. + */ +export type RegisterEvent = BasicEvent & { + type: 'client-register'; + + /** + * Unique identifier of the user for which PubNub SDK client has been created. + */ + userId: string; + + /** + * Specific PubNub client instance communication port. + */ + port?: MessagePort; }; /** @@ -62,13 +84,29 @@ export type CancelRequestEvent = BasicEvent & { identifier: string; }; +/** + * Client response on PING request. + */ +export type PongEvent = BasicEvent & { + type: 'client-pong'; +}; + /** * List of known events from the PubNub Core. */ -export type ClientEvent = SendRequestEvent | CancelRequestEvent; +export type ClientEvent = RegisterEvent | PongEvent | SendRequestEvent | CancelRequestEvent; // endregion -// region Service Worker +// region Subscription Worker +/** + * Shared subscription worker connected event. + * + * Event signal shared worker client that worker can be used. + */ +export type SharedWorkerConnected = { + type: 'shared-worker-connected'; +}; + /** * {@link Request} processing start event. * @@ -249,10 +287,57 @@ export type RequestSendingSuccess = { */ export type RequestSendingResult = RequestSendingError | RequestSendingSuccess; +/** + * Send message to debug console. + */ +export type SharedWorkerConsoleLog = { + type: 'shared-worker-console-log'; + + /** + * Message which should be printed into the console. + */ + message: string; +}; +/** + * Send message to debug console. + */ +export type SharedWorkerConsoleDir = { + type: 'shared-worker-console-dir'; + + /** + * Message which should be printed into the console before {@link data}. + */ + message?: string; + + /** + * Data which should be printed into the console. + */ + data: Payload; +}; + +/** + * Shared worker console output request. + */ +export type SharedWorkerConsole = SharedWorkerConsoleLog | SharedWorkerConsoleDir; + +/** + * Shared worker client ping request. + * + * Ping used to discover disconnected PubNub instances. + */ +export type SharedWorkerPing = { + type: 'shared-worker-ping'; +}; + /** * List of known events from the PubNub Subscription Service Worker. */ -export type ServiceWorkerEvent = RequestSendingProgress | RequestSendingResult; +export type SubscriptionWorkerEvent = + | SharedWorkerConnected + | SharedWorkerConsole + | SharedWorkerPing + | RequestSendingProgress + | RequestSendingResult; /** * PubNub client state representation in Service Worker. @@ -284,13 +369,23 @@ type PubNubClientState = { */ logVerbosity: boolean; + /** + * Last time when PING request has been sent. + */ + lastPingRequest?: number; + + /** + * Last time when PubNub client respond with PONG event. + */ + lastPongEvent?: number; + /** * Current subscription session information. * * **Note:** Information updated each time when PubNub client instance schedule `subscribe` or * `unsubscribe` requests. */ - subscription: { + subscription?: { /** * Subscription REST API uri path. * @@ -361,7 +456,12 @@ type PubNubClientState = { // -------------------------------------------------------- // region Service Worker -declare const self: ServiceWorkerGlobalScope; +declare const self: SharedWorkerGlobalScope; + +/** + * How often PING request should be sent to the PubNub clients. + */ +const clientPingRequestInterval = 5000; // region State /** @@ -369,6 +469,21 @@ declare const self: ServiceWorkerGlobalScope; */ const decoder = new TextDecoder(); +/** + * Whether `Subscription` worker should print debug information to the console or not. + */ +let logVerbosity: boolean = false; + +/** + * PubNub clients active ping interval. + */ +let pingInterval: number | undefined; + +/** + * Unique shared worker instance identifier. + */ +const sharedWorkerIdentifier = uuidGenerator.createUUID(); + /** * Map of identifiers, scheduled by the Service Worker, to their abort controllers. * @@ -400,12 +515,12 @@ const presenceState: { } = {}; /** - * Per-subscription key map of client identifiers to the Service Worker {@link Client} identifier. + * Per-subscription key map of client identifiers to the Shared Worker {@link MessagePort}. * - * Service Worker {@link Client} represent pages at which PubNub clients registered Service Workers. + * Shared Worker {@link MessagePort} represent specific PubNub client which connected to the Shared Worker. */ -const serviceWorkerClients: { - [subscriptionKey: string]: { [clientId: string]: string | undefined } | undefined; +const sharedWorkerClients: { + [subscriptionKey: string]: { [clientId: string]: MessagePort | undefined } | undefined; } = {}; /** @@ -444,31 +559,44 @@ const serviceRequests: { // region Event Handlers /** - * Listen for Service Worker activation. + * Handle new PubNub client 'connection'. + * + * Echo listeners to let `SharedWorker` users that it is ready. + * + * @param event - Remote `SharedWorker` client connection event. */ -self.addEventListener('activate', (event) => { - event.waitUntil(self.clients.claim()); -}); +self.onconnect = (event) => { + consoleLog('New PubNub Client connected to the Subscription Shared Worker.'); -/** - * Listen for events from the client. - */ -self.addEventListener('message', (event) => { - // Ignoring requests sent from other service workers. - if (!validateEventPayload(event)) return; + event.ports.forEach((receiver) => { + receiver.start(); - const data = event.data as ClientEvent; + receiver.onmessage = (event: MessageEvent) => { + // Ignoring unknown event payloads. + if (!validateEventPayload(event)) return; - if (data.type === 'send-request') { - if (data.request.path.startsWith('/v2/subscribe')) { - registerClientIfRequired(event); - handleSendSubscribeRequestEvent(data); - } else { - if (!pubNubClients[data.clientIdentifier]) registerClientIfRequired(event); - handleSendLeaveRequestEvent(event); - } - } else if (data.type === 'cancel-request') handleCancelRequestEvent(data); -}); + const data = event.data as ClientEvent; + + if (data.type === 'client-register') { + if (!logVerbosity && data.workerLogVerbosity) logVerbosity = true; + + // Appending information about messaging port for responses. + data.port = receiver; + registerClientIfRequired(data); + + consoleLog(`Client '${data.clientIdentifier}' registered with '${sharedWorkerIdentifier}' shared worker`); + } else if (data.type === 'client-pong') handleClientPong(data); + else if (data.type === 'send-request') { + if (data.request.path.startsWith('/v2/subscribe')) { + updateClientStateIfRequired(data); + handleSendSubscribeRequestEvent(data); + } else handleSendLeaveRequestEvent(data); + } else if (data.type === 'cancel-request') handleCancelRequestEvent(data); + }; + + receiver.postMessage({ type: 'shared-worker-connected' }); + }); +}; /** * Handle client request to send subscription request. @@ -482,7 +610,7 @@ const handleSendSubscribeRequestEvent = (event: SendRequestEvent) => { if (client) notifyRequestProcessing('start', [client], new Date().toISOString()); if (typeof requestOrId === 'string') { - if (client) { + if (client && client.subscription) { // Updating client timetoken information. client.subscription.previousTimetoken = client.subscription.timetoken; client.subscription.timetoken = serviceRequests[requestOrId].timetoken; @@ -511,15 +639,16 @@ const handleSendSubscribeRequestEvent = (event: SendRequestEvent) => { markRequestCompleted(clients, requestOrId.identifier); }, ); + + consoleLog(`'${Object.keys(serviceRequests).length}' subscription request currently active.`); }; /** * Handle client request to leave request. * - * @param event - Leave event details. + * @param data - Leave event details. */ -const handleSendLeaveRequestEvent = (event: ExtendableMessageEvent) => { - const data = event.data as SendRequestEvent; +const handleSendLeaveRequestEvent = (data: SendRequestEvent) => { const request = leaveTransportRequestFromEvent(data); const client = pubNubClients[data.clientIdentifier]; @@ -533,9 +662,7 @@ const handleSendLeaveRequestEvent = (event: ExtendableMessageEvent) => { result.clientIdentifier = data.clientIdentifier; result.identifier = data.request.identifier; - publishClientEvent((event.source! as Client).id, result).then((sent) => { - if (sent) invalidateClient(client.subscriptionKey, client.clientIdentifier, client.userId); - }); + publishClientEvent(client, result); return; } @@ -551,6 +678,8 @@ const handleSendLeaveRequestEvent = (event: ExtendableMessageEvent) => { notifyRequestProcessingResult(clients, null, data.request, requestProcessingError(error)); }, ); + + consoleLog(`Started leave request.`, client); }; /** @@ -562,7 +691,9 @@ const handleSendLeaveRequestEvent = (event: ExtendableMessageEvent) => { */ const handleCancelRequestEvent = (event: CancelRequestEvent) => { const client = pubNubClients[event.clientIdentifier]; - const serviceRequestId = client ? client.subscription.serviceRequestId : undefined; + if (!client || !client.subscription) return; + + const serviceRequestId = client.subscription.serviceRequestId; if (!client || !serviceRequestId) return; // Unset awaited requests. @@ -673,7 +804,7 @@ const requestTimeoutTimer = (requestId: string, requestTimeout: number) => const clientsForRequest = (identifier: string) => { return Object.values(pubNubClients).filter( (client): client is PubNubClientState => - client !== undefined && client.subscription.serviceRequestId === identifier, + client !== undefined && client.subscription !== undefined && client.subscription.serviceRequestId === identifier, ); }; @@ -689,8 +820,10 @@ const markRequestCompleted = (clients: PubNubClientState[], requestId: string) = delete serviceRequests[requestId]; clients.forEach((client) => { - delete client.subscription.request; - delete client.subscription.serviceRequestId; + if (client.subscription) { + delete client.subscription.request; + delete client.subscription.serviceRequestId; + } }); }; @@ -734,7 +867,8 @@ const requestFromTransportRequest = (req: TransportRequest): Request => { */ const subscribeTransportRequestFromEvent = (event: SendRequestEvent): TransportRequest | string => { const client = pubNubClients[event.clientIdentifier]!; - const clients = clientsForSendSubscribeRequestEvent(client.subscription.previousTimetoken, event); + const subscription = client.subscription!; + const clients = clientsForSendSubscribeRequestEvent(subscription.previousTimetoken, event); const serviceRequestId = uuidGenerator.createUUID(); const request = { ...event.request }; @@ -746,11 +880,11 @@ const subscribeTransportRequestFromEvent = (event: SendRequestEvent): TransportR const state = (presenceState[client.subscriptionKey] ?? {})[client.userId]; const aggregatedState: Record = {}; - const channelGroups = new Set(client.subscription.channelGroups); - const channels = new Set(client.subscription.channels); + const channelGroups = new Set(subscription.channelGroups); + const channels = new Set(subscription.channels); - if (state && client.subscription.objectsWithState.length) { - client.subscription.objectsWithState.forEach((name) => { + if (state && subscription.objectsWithState.length) { + subscription.objectsWithState.forEach((name) => { const objectState = state[name]; if (objectState) aggregatedState[name] = objectState; }); @@ -759,7 +893,7 @@ const subscribeTransportRequestFromEvent = (event: SendRequestEvent): TransportR for (const client of clients) { const { subscription } = client!; // Skip clients which already have active subscription request. - if (subscription.serviceRequestId) continue; + if (!subscription || !subscription.serviceRequestId) continue; subscription.channelGroups.forEach(channelGroups.add, channelGroups); subscription.channels.forEach(channels.add, channels); @@ -803,14 +937,25 @@ const subscribeTransportRequestFromEvent = (event: SendRequestEvent): TransportR serviceRequests[serviceRequestId] = { requestId: serviceRequestId, timetoken: (request.queryParameters!.tt as string) ?? '0', - channelGroups: client.subscription.channelGroups, - channels: client.subscription.channels, + channelGroups: subscription.channelGroups, + channels: subscription.channels, }; } - client.subscription.serviceRequestId = serviceRequestId; + subscription.serviceRequestId = serviceRequestId; request.identifier = serviceRequestId; + if (logVerbosity) { + const clientIds = clients + .reduce((identifiers: string[], { clientIdentifier }) => { + identifiers.push(clientIdentifier); + return identifiers; + }, []) + .join(','); + + consoleDir(serviceRequests[serviceRequestId], `Started aggregated request for clients: ${clientIds}`); + } + return request; }; @@ -831,7 +976,7 @@ const leaveTransportRequestFromEvent = (event: SendRequestEvent): TransportReque let channels = channelsFromRequest(event.request); const request = { ...event.request }; - if (client) { + if (client && client.subscription) { const { subscription } = client; if (channels.length) subscription.channels = subscription.channels.filter((channel) => !channels.includes(channel)); if (channelGroups.length) { @@ -841,13 +986,31 @@ const leaveTransportRequestFromEvent = (event: SendRequestEvent): TransportReque // Filter out channels and groups which is still in use by the other PubNub client instances. for (const client of clients) { + const subscription = client.subscription; + if (subscription === undefined) continue; if (client.clientIdentifier === event.clientIdentifier) continue; - if (channels.length) channels = channels.filter((channel) => !client.subscription.channels.includes(channel)); + if (channels.length) channels = channels.filter((channel) => !subscription.channels.includes(channel)); if (channelGroups.length) - channelGroups = channelGroups.filter((group) => !client.subscription.channelGroups.includes(group)); + channelGroups = channelGroups.filter((group) => !subscription.channelGroups.includes(group)); } - if (channels.length === 0 && channelGroups.length === 0) return undefined; + if (channels.length === 0 && channelGroups.length === 0) { + if (logVerbosity && client) { + const clientIds = clients + .reduce((identifiers: string[], { clientIdentifier }) => { + identifiers.push(clientIdentifier); + return identifiers; + }, []) + .join(','); + + consoleLog( + `Specified channels and groups still in use by other clients: ${clientIds}. Ignoring leave request.`, + client, + ); + } + + return undefined; + } // Update request channels list (if required). if (channels.length) { @@ -863,18 +1026,21 @@ const leaveTransportRequestFromEvent = (event: SendRequestEvent): TransportReque }; /** - * Send event to all service worker clients. + * Send event to the specific PubNub client. * - * @param identifier - Service Worker receiving {@link Client} identifier. - * @param event - Service worker event object. + * @param client - State for the client which should receive {@link event}. + * @param event - Subscription worker event object. */ -const publishClientEvent = (identifier: string, event: ServiceWorkerEvent) => { - return self.clients.get(identifier).then((client) => { - if (!client) return false; +const publishClientEvent = (client: PubNubClientState, event: SubscriptionWorkerEvent) => { + const receiver = (sharedWorkerClients[client.subscriptionKey] ?? {})[client.clientIdentifier]; + if (!receiver) return false; - client.postMessage(event); + try { + receiver.postMessage(event); return true; - }); + } catch (error) {} + + return false; }; /** @@ -899,7 +1065,7 @@ const notifyRequestProcessing = ( ) => { if (clients.length === 0) return; - const clientIds = serviceWorkerClients[clients[0].subscriptionKey] ?? {}; + const clientIds = sharedWorkerClients[clients[0].subscriptionKey] ?? {}; let event: RequestSendingProgress; if (type === 'start') { @@ -932,22 +1098,24 @@ const notifyRequestProcessing = ( }; } - clients.forEach((client) => { + for (const client of clients) { + if (client.subscription === undefined) continue; + const serviceWorkerClientId = clientIds[client.clientIdentifier]; const { request: clientRequest } = client.subscription; const decidedRequest = clientRequest ?? request; if (client.logVerbosity && serviceWorkerClientId && decidedRequest) { - publishClientEvent(serviceWorkerClientId, { + const payload = { ...event, clientIdentifier: client.clientIdentifier, url: `${decidedRequest.origin}${decidedRequest.path}`, query: decidedRequest.queryParameters, - }).then((sent) => { - if (sent) invalidateClient(client.subscriptionKey, client.clientIdentifier, client.userId); - }); + }; + + publishClientEvent(client, payload); } - }); + } }; /** @@ -967,7 +1135,7 @@ const notifyRequestProcessingResult = ( if (clients.length === 0) return; if (!result && !response) return; - const clientIds = serviceWorkerClients[clients[0].subscriptionKey] ?? {}; + const clientIds = sharedWorkerClients[clients[0].subscriptionKey] ?? {}; if (!result && response) { result = @@ -977,22 +1145,24 @@ const notifyRequestProcessingResult = ( : requestProcessingSuccess(response); } - clients.forEach((client) => { + for (const client of clients) { + if (client.subscription === undefined) continue; + const serviceWorkerClientId = clientIds[client.clientIdentifier]; const { request: clientRequest } = client.subscription; const decidedRequest = clientRequest ?? request; if (serviceWorkerClientId && decidedRequest) { - publishClientEvent(serviceWorkerClientId, { + const payload = { ...result!, clientIdentifier: client.clientIdentifier, identifier: decidedRequest.identifier, url: `${decidedRequest.origin}${decidedRequest.path}`, - }).then((sent) => { - if (sent) invalidateClient(client.subscriptionKey, client.clientIdentifier, client.userId); - }); + }; + + publishClientEvent(client, payload); } - }); + } }; /** @@ -1089,71 +1259,79 @@ const requestProcessingError = (error?: unknown, res?: [Response, ArrayBuffer]): * * @param event - Base information about PubNub client instance and Service Worker {@link Client}. */ -const registerClientIfRequired = (event: ExtendableMessageEvent) => { - const information = event.data as SendRequestEvent; - const { clientIdentifier } = information; - const query = information.request.queryParameters!; - - let client = pubNubClients[clientIdentifier]; - - if (!client) { - const isPresenceLeave = !information.request.path.startsWith('/v2/subscribe'); - const channelGroupQuery = !isPresenceLeave ? ((query!['channel-group'] ?? '') as string) : ''; - const state = !isPresenceLeave ? ((query.state ?? '') as string) : ''; - - client = pubNubClients[clientIdentifier] = { - clientIdentifier, - subscriptionKey: information.subscriptionKey, - userId: query.uuid as string, - authKey: (query.auth ?? '') as string, - logVerbosity: information.logVerbosity, - subscription: { - path: !isPresenceLeave ? information.request.path : '', - channelGroupQuery: !isPresenceLeave ? channelGroupQuery : '', - channels: !isPresenceLeave ? channelsFromRequest(information.request) : [], - channelGroups: !isPresenceLeave ? channelGroupsFromRequest(information.request) : [], - previousTimetoken: !isPresenceLeave ? ((query.tt ?? '0') as string) : '0', - timetoken: !isPresenceLeave ? ((query.tt ?? '0') as string) : '0', - request: !isPresenceLeave ? information.request : undefined, - objectsWithState: [], - filterExpression: !isPresenceLeave ? ((query['filter-expr'] ?? '') as string) : undefined, - }, +const registerClientIfRequired = (event: RegisterEvent) => { + const { clientIdentifier } = event; + + if (pubNubClients[clientIdentifier]) return; + + const client = (pubNubClients[clientIdentifier] = { + clientIdentifier, + subscriptionKey: event.subscriptionKey, + userId: event.userId, + logVerbosity: event.logVerbosity, + }); + + // Map registered PubNub client to its subscription key. + const clientsBySubscriptionKey = (pubNubClientsBySubscriptionKey[event.subscriptionKey] ??= []); + if (clientsBySubscriptionKey.every((entry) => entry.clientIdentifier !== clientIdentifier)) + clientsBySubscriptionKey.push(client); + + // Binding PubNub client to the MessagePort (receiver). + (sharedWorkerClients[event.subscriptionKey] ??= {})[clientIdentifier] = event.port; + + consoleLog( + `Registered PubNub client with '${clientIdentifier}' identifier. ` + + `'${Object.keys(pubNubClients).length}' clients currently active.`, + ); + + if (!pingInterval && Object.keys(pubNubClients).length > 0) { + consoleLog(`Setup PubNub client ping event ${clientPingRequestInterval / 1000} seconds`); + pingInterval = setInterval(() => pingClients(), clientPingRequestInterval) as unknown as number; + } +}; + +/** + * Update information about previously registered client. + * + * Use information from request to populate list of channels and other useful information. + * + * @param event - Send request. + */ +const updateClientStateIfRequired = (event: SendRequestEvent) => { + const query = event.request.queryParameters!; + const { clientIdentifier } = event; + + const client = pubNubClients[clientIdentifier]; + + // This should never happen. + if (!client) return; + + const channelGroupQuery = (query!['channel-group'] ?? '') as string; + const state = (query.state ?? '') as string; + + let subscription = client.subscription; + if (!subscription) { + subscription = { + path: '', + channelGroupQuery: '', + channels: [], + channelGroups: [], + previousTimetoken: '0', + timetoken: '0', + objectsWithState: [], }; - if (!isPresenceLeave && state.length > 0) { + if (state.length > 0) { const parsedState = JSON.parse(state) as Record; const userState = ((presenceState[client.subscriptionKey] ??= {})[client.userId] ??= {}); Object.entries(parsedState).forEach(([objectName, value]) => (userState[objectName] = value)); - client.subscription.objectsWithState = Object.keys(parsedState); + subscription.objectsWithState = Object.keys(parsedState); } - // Map registered PubNub client to its subscription key. - const clientsBySubscriptionKey = (pubNubClientsBySubscriptionKey[information.subscriptionKey] ??= []); - if (clientsBySubscriptionKey.every((entry) => entry.clientIdentifier !== clientIdentifier)) - clientsBySubscriptionKey.push(client); - - // Binding PubNub client to the page (Service Worker Client). - (serviceWorkerClients[information.subscriptionKey] ??= {})[clientIdentifier] = (event.source! as Client).id; + client.subscription = subscription; } else { - const channelGroupQuery = (query!['channel-group'] ?? '') as string; - const state = (query.state ?? '') as string; - client.subscription.filterExpression = (query['filter-expr'] ?? '') as string; - client.subscription.previousTimetoken = client.subscription.timetoken; - client.subscription.timetoken = (query.tt ?? '0') as string; - client.subscription.request = information.request; - client.authKey = (query.auth ?? '') as string; - client.userId = query.uuid as string; - - if (client.subscription.path !== information.request.path) { - client.subscription.path = information.request.path; - client.subscription.channels = channelsFromRequest(information.request); - } - - if (client.subscription.channelGroupQuery !== channelGroupQuery) { - client.subscription.channelGroupQuery = channelGroupQuery; - client.subscription.channelGroups = channelGroupsFromRequest(information.request); - } + subscription.previousTimetoken = subscription.timetoken; if (state.length > 0) { const parsedState = JSON.parse(state) as Record; @@ -1161,18 +1339,48 @@ const registerClientIfRequired = (event: ExtendableMessageEvent) => { Object.entries(parsedState).forEach(([objectName, value]) => (userState[objectName] = value)); // Clean up state for objects where presence state has been reset. - for (const objectName of client.subscription.objectsWithState) + for (const objectName of subscription.objectsWithState) if (!parsedState[objectName]) delete userState[objectName]; - client.subscription.objectsWithState = Object.keys(parsedState); + + subscription.objectsWithState = Object.keys(parsedState); } // Handle potential presence state reset. - else if (client.subscription.objectsWithState.length) { + else if (subscription.objectsWithState.length) { const userState = ((presenceState[client.subscriptionKey] ??= {})[client.userId] ??= {}); - for (const objectName of client.subscription.objectsWithState) delete userState[objectName]; - client.subscription.objectsWithState = []; + for (const objectName of subscription.objectsWithState) delete userState[objectName]; + subscription.objectsWithState = []; } } + + if (subscription.path !== event.request.path) { + subscription.path = event.request.path; + subscription.channels = channelsFromRequest(event.request); + } + + if (subscription.channelGroupQuery !== channelGroupQuery) { + subscription.channelGroupQuery = channelGroupQuery; + subscription.channelGroups = channelGroupsFromRequest(event.request); + } + + subscription.request = event.request; + subscription.filterExpression = (query['filter-expr'] ?? '') as string; + subscription.timetoken = (query.tt ?? '0') as string; + client.authKey = (query.auth ?? '') as string; + client.userId = query.uuid as string; +}; + +/** + * Handle PubNub client response on PING request. + * + * @param event - Information about client which responded on PING request. + */ +const handleClientPong = (event: PongEvent) => { + const client = pubNubClients[event.clientIdentifier]; + + if (!client) return; + + client.lastPongEvent = new Date().getTime() / 1000; }; /** @@ -1181,9 +1389,8 @@ const registerClientIfRequired = (event: ExtendableMessageEvent) => { * @param subscriptionKey - Subscription key which has been used by the * invalidated instance. * @param clientId - Unique PubNub client identifier. - * @param userId - Unique identifier of the user used by PubNub client instance. */ -const invalidateClient = (subscriptionKey: string, clientId: string, userId: string) => { +const invalidateClient = (subscriptionKey: string, clientId: string) => { delete pubNubClients[clientId]; let clients = pubNubClientsBySubscriptionKey[subscriptionKey]; @@ -1198,24 +1405,23 @@ const invalidateClient = (subscriptionKey: string, clientId: string, userId: str // Clean up service workers client linkage to PubNub clients. if (clients.length > 0) { - const workerClients = serviceWorkerClients[subscriptionKey]; + const workerClients = sharedWorkerClients[subscriptionKey]; if (workerClients) { delete workerClients[clientId]; - if (Object.keys(workerClients).length === 0) delete serviceWorkerClients[subscriptionKey]; + if (Object.keys(workerClients).length === 0) delete sharedWorkerClients[subscriptionKey]; } - } else delete serviceWorkerClients[subscriptionKey]; + } else delete sharedWorkerClients[subscriptionKey]; } + + consoleLog(`Invalidate '${clientId}' client. '${Object.keys(pubNubClients).length}' clients currently active.`); }; /** * Validate received event payload. */ -const validateEventPayload = (event: ExtendableMessageEvent): boolean => { - if (!event.source || !(event.source instanceof Client)) return false; - const data = event.data as ClientEvent; - - const { clientIdentifier, subscriptionKey, logVerbosity } = data as ClientEvent; +const validateEventPayload = (event: MessageEvent): boolean => { + const { clientIdentifier, subscriptionKey, logVerbosity } = event.data as ClientEvent; if (logVerbosity === undefined || typeof logVerbosity !== 'boolean') return false; if (!clientIdentifier || typeof clientIdentifier !== 'string') return false; @@ -1223,7 +1429,7 @@ const validateEventPayload = (event: ExtendableMessageEvent): boolean => { }; /** - * Search for active subscription for one of the passed {@link serviceWorkerClients}. + * Search for active subscription for one of the passed {@link sharedWorkerClients}. * * @param activeClients - List of suitable registered PubNub clients. * @param event - Send Subscriber Request event data. @@ -1244,9 +1450,17 @@ const activeSubscriptionForEvent = ( for (const client of activeClients) { const { subscription } = client; // Skip PubNub clients which doesn't await for subscription response. - if (!subscription.serviceRequestId) continue; + if (!subscription || !subscription.serviceRequestId) continue; + const sourceClient = pubNubClients[event.clientIdentifier]; + const requestId = subscription.serviceRequestId; if (subscription.path === requestPath && subscription.channelGroupQuery === channelGroupQuery) { + consoleLog( + `Found identical request started by '${client.clientIdentifier}' client. +Waiting for existing '${requestId}' request completion.`, + sourceClient, + ); + return subscription.serviceRequestId; } else { const scheduledRequest = serviceRequests[subscription.serviceRequestId]; @@ -1257,6 +1471,13 @@ const activeSubscriptionForEvent = ( if (channels.length && !includesStrings(scheduledRequest.channels, channels)) continue; if (channelGroups.length && !includesStrings(scheduledRequest.channelGroups, channelGroups)) continue; + consoleDir( + scheduledRequest, + `'${event.request.identifier}' request channels and groups are subset of ongoing '${requestId}' request +which has started by '${client.clientIdentifier}' client. Waiting for existing '${requestId}' request completion.`, + sourceClient, + ); + return subscription.serviceRequestId; } } @@ -1290,6 +1511,7 @@ const clientsForSendSubscribeRequestEvent = (timetoken: string, event: SendReque (client) => client.userId === userId && client.authKey === authKey && + client.subscription && client.subscription.filterExpression === filterExpression && (timetoken === '0' || client.subscription.previousTimetoken === '0' || @@ -1356,6 +1578,83 @@ const includesStrings = (main: string[], sub: string[]) => { return sub.every(set.has, set); }; +/** + * Send PubNub client PING request to identify disconnected instances. + */ +const pingClients = () => { + consoleLog(`Pinging clients...`); + const payload: SharedWorkerPing = { type: 'shared-worker-ping' }; + + Object.values(pubNubClients).forEach((client) => { + let clientInvalidated = false; + + if (client && client.lastPingRequest) { + consoleLog(`Checking whether ${client.clientIdentifier} ping has been sent too long ago...`); + // Check whether client never respond or last response was too long time ago. + if ( + !client.lastPongEvent || + Math.abs(client.lastPongEvent - client.lastPingRequest) > (clientPingRequestInterval / 1000) * 0.5 + ) { + clientInvalidated = true; + + consoleLog(`'${client.clientIdentifier}' client is inactive. Invalidating.`); + invalidateClient(client.subscriptionKey, client.clientIdentifier); + } + } + + if (client && !clientInvalidated) { + consoleLog(`Sending ping to ${client.clientIdentifier}...`); + client.lastPingRequest = new Date().getTime() / 1000; + publishClientEvent(client, payload); + } + }); + + // Cancel interval if there is no active clients. + if (Object.keys(pubNubClients).length === 0 && pingInterval) clearInterval(pingInterval); +}; + +/** + * Print message on the worker's clients console. + * + * @param message - Message which should be printed. + * @param [client] - Target client to which log message should be sent. + */ +const consoleLog = (message: string, client?: PubNubClientState): void => { + if (!logVerbosity) return; + + const clients = client ? [client] : Object.values(pubNubClients); + const payload: SharedWorkerConsoleLog = { + type: 'shared-worker-console-log', + message, + }; + + clients.forEach((client) => { + if (client) publishClientEvent(client, payload); + }); +}; + +/** + * Print message on the worker's clients console. + * + * @param data - Data which should be printed into the console. + * @param [message] - Message which should be printed before {@link data}. + * @param [client] - Target client to which log message should be sent. + */ +const consoleDir = (data: Payload, message?: string, client?: PubNubClientState): void => { + if (!logVerbosity) return; + + const clients = client ? [client] : Object.values(pubNubClients); + const payload: SharedWorkerConsoleDir = { + type: 'shared-worker-console-dir', + message, + data, + }; + + clients.forEach((client) => { + if (client) publishClientEvent(client, payload); + }); +}; + /** * Stringify request query key / value pairs. * diff --git a/src/web/components/configuration.ts b/src/web/components/configuration.ts index 651cd1530..06e65c335 100644 --- a/src/web/components/configuration.ts +++ b/src/web/components/configuration.ts @@ -3,6 +3,7 @@ import { ExtendedConfiguration, setDefaults as setBaseDefaults, } from '../../core/interfaces/configuration'; +import { CryptoModule } from '../../core/interfaces/crypto-module'; // -------------------------------------------------------- // ----------------------- Defaults ----------------------- @@ -17,6 +18,11 @@ import { */ const LISTEN_TO_BROWSER_NETWORK_EVENTS = true; +/** + * Whether verbose logging should be enabled for `Subscription` worker to print debug messages or not. + */ +const SUBSCRIPTION_WORKER_LOG_VERBOSITY = false; + /** * Whether PubNub client should try to utilize existing TCP connection for new requests or not. */ @@ -45,7 +51,14 @@ export type PubNubConfiguration = UserConfiguration & { * statics provided from `subdomain.main.com` and page loaded from `account.main.com` - then server should be * configured to serve worker file from `account.main.com`. */ - serviceWorkerUrl?: string | null; + subscriptionWorkerUrl?: string | null; + + /** + * Whether verbose logging should be enabled for `Subscription` worker should print debug messages or not. + * + * @default `false` + */ + subscriptionWorkerLogVerbosity?: boolean; /** * If set to `true`, SDK will use the same TCP connection for each HTTP request, instead of @@ -54,23 +67,57 @@ export type PubNubConfiguration = UserConfiguration & { * @default `true` */ keepAlive?: boolean; + + /** + * The cryptography module used for encryption and decryption of messages and files. Takes the + * {@link cipherKey} and {@link useRandomIVs} parameters as arguments. + * + * For more information, refer to the + * {@link /docs/sdks/javascript/api-reference/configuration#cryptomodule|cryptoModule} section. + * + * @default `not set` + */ + cryptoModule?: CryptoModule; + + // region Deprecated parameters + /** + * If passed, will encrypt the payloads. + * + * @deprecated Pass it to {@link cryptoModule} instead. + */ + cipherKey?: string; + + /** + * When `true` the initialization vector (IV) is random for all requests (not just for file + * upload). + * When `false` the IV is hard-coded for all requests except for file upload. + * + * @default `true` + * + * @deprecated Pass it to {@link cryptoModule} instead. + */ + useRandomIVs?: boolean; }; /** * Apply configuration default values. * * @param configuration - User-provided configuration. + * + * @internal */ export const setDefaults = (configuration: PubNubConfiguration): PubNubConfiguration & ExtendedConfiguration => { // Force disable service workers if environment doesn't support them. - if (configuration.serviceWorkerUrl && !('serviceWorker' in navigator)) configuration.serviceWorkerUrl = null; + if (configuration.subscriptionWorkerUrl && typeof SharedWorker === 'undefined') + configuration.subscriptionWorkerUrl = null; return { // Set base configuration defaults. ...setBaseDefaults(configuration), // Set platform-specific options. listenToBrowserNetworkEvents: configuration.listenToBrowserNetworkEvents ?? LISTEN_TO_BROWSER_NETWORK_EVENTS, - serviceWorkerUrl: configuration.serviceWorkerUrl, + subscriptionWorkerUrl: configuration.subscriptionWorkerUrl, + subscriptionWorkerLogVerbosity: configuration.subscriptionWorkerLogVerbosity ?? SUBSCRIPTION_WORKER_LOG_VERBOSITY, keepAlive: configuration.keepAlive ?? KEEP_ALIVE, }; }; diff --git a/src/web/index.ts b/src/web/index.ts index 5fc10654b..7cf367027 100644 --- a/src/web/index.ts +++ b/src/web/index.ts @@ -4,8 +4,8 @@ import CborReader from 'cbor-js'; // eslint-disable-next-line max-len -import { SubscriptionServiceWorkerMiddleware } from '../transport/service-worker/subscription-service-worker-middleware'; import { AesCbcCryptor, LegacyCryptor, WebCryptoModule } from '../crypto/modules/WebCryptoModule/webCryptoModule'; +import { SubscriptionWorkerMiddleware } from '../transport/subscription-worker/subscription-worker-middleware'; import { WebReactNativeTransport } from '../transport/web-react-native-transport'; import { stringifyBufferKeys } from '../core/components/stringify_buffer_keys'; import { PubNubConfiguration, setDefaults } from './components/configuration'; @@ -69,14 +69,17 @@ export default class PubNub extends PubNubCore Date: Wed, 15 May 2024 21:32:16 +0300 Subject: [PATCH 2/3] docs(declaration): add comments into generated declaration files --- dist/web/pubnub.js | 2 + lib/cbor/common.js | 15 + lib/core/components/abort_signal.js | 5 + lib/core/components/base64_codec.js | 50 +- lib/core/components/configuration.js | 37 + .../components/cryptography/hmac-sha256.js | 14 + lib/core/components/cryptography/index.js | 139 ++- lib/core/components/deduping_manager.js | 10 +- lib/core/components/eventEmitter.js | 49 + lib/core/components/listener_manager.js | 91 ++ lib/core/components/push_payload.js | 248 ++++ lib/core/components/reconnection_manager.js | 23 + lib/core/components/request.js | 81 ++ lib/core/components/stringify_buffer_keys.js | 9 + lib/core/components/subject.js | 3 + lib/core/components/subscription-manager.js | 44 + lib/core/components/token_manager.js | 37 + lib/core/components/uuid.js | 1 + lib/core/constants/categories.js | 62 + lib/core/constants/operations.js | 183 +++ lib/core/endpoints/access_manager/audit.js | 17 + lib/core/endpoints/access_manager/grant.js | 35 + .../endpoints/access_manager/grant_token.js | 28 + .../endpoints/access_manager/revoke_token.js | 11 + .../endpoints/actions/add_message_action.js | 9 + .../endpoints/actions/get_message_actions.js | 9 + .../actions/remove_message_action.js | 9 + .../endpoints/channel_groups/add_channels.js | 9 + .../endpoints/channel_groups/delete_group.js | 9 + .../endpoints/channel_groups/list_channels.js | 9 + .../endpoints/channel_groups/list_groups.js | 9 + .../channel_groups/remove_channels.js | 10 + lib/core/endpoints/fetch_messages.js | 52 + lib/core/endpoints/file_upload/delete_file.js | 9 + .../endpoints/file_upload/download_file.js | 9 + .../file_upload/generate_upload_url.js | 9 + .../endpoints/file_upload/get_file_url.js | 16 + lib/core/endpoints/file_upload/list_files.js | 17 + .../endpoints/file_upload/publish_file.js | 28 + lib/core/endpoints/file_upload/send_file.js | 24 + lib/core/endpoints/file_upload/upload-file.js | 9 + lib/core/endpoints/history/delete_messages.js | 9 + lib/core/endpoints/history/get_history.js | 27 + lib/core/endpoints/history/message_counts.js | 9 + lib/core/endpoints/objects/channel/get.js | 17 + lib/core/endpoints/objects/channel/get_all.js | 23 + lib/core/endpoints/objects/channel/remove.js | 9 + lib/core/endpoints/objects/channel/set.js | 17 + lib/core/endpoints/objects/member/get.js | 38 + lib/core/endpoints/objects/member/set.js | 29 + lib/core/endpoints/objects/membership/get.js | 39 + lib/core/endpoints/objects/membership/set.js | 30 + lib/core/endpoints/objects/uuid/get.js | 18 + lib/core/endpoints/objects/uuid/get_all.js | 20 + lib/core/endpoints/objects/uuid/remove.js | 10 + lib/core/endpoints/objects/uuid/set.js | 18 + lib/core/endpoints/presence/get_state.js | 10 + lib/core/endpoints/presence/heartbeat.js | 9 + lib/core/endpoints/presence/here_now.js | 22 + lib/core/endpoints/presence/leave.js | 9 + lib/core/endpoints/presence/set_state.js | 9 + lib/core/endpoints/presence/where_now.js | 9 + lib/core/endpoints/publish.js | 36 + lib/core/endpoints/push/add_push_channels.js | 10 + lib/core/endpoints/push/list_push_channels.js | 10 + lib/core/endpoints/push/push.js | 20 + lib/core/endpoints/push/remove_device.js | 10 + .../endpoints/push/remove_push_channels.js | 10 + lib/core/endpoints/signal.js | 9 + lib/core/endpoints/subscribe.js | 76 ++ .../endpoints/subscriptionUtils/handshake.js | 10 + .../subscriptionUtils/receiveMessages.js | 8 + lib/core/endpoints/time.js | 9 + lib/core/interfaces/configuration.js | 98 +- lib/core/interfaces/crypto-module.js | 42 + lib/core/interfaces/cryptography.js | 3 + lib/core/pubnub-channel-groups.js | 51 +- lib/core/pubnub-common.js | 909 ++++++++++++++ lib/core/pubnub-objects.js | 227 +++- lib/core/pubnub-push.js | 33 +- lib/core/types/api/access-panager.js | 2 + lib/core/types/api/app-context.js | 1 + lib/core/types/api/file-sharing.js | 4 + lib/core/types/api/history.js | 17 + lib/core/types/api/index.js | 1 + lib/core/types/api/presence.js | 1 + lib/core/types/api/push.js | 1 + lib/core/types/file.js | 3 + lib/core/types/transport-request.js | 22 + lib/core/utils.js | 25 + lib/crypto/index.js | 1 + .../modules/NodeCryptoModule/ICryptor.js | 3 + .../NodeCryptoModule/ILegacyCryptor.js | 3 + .../modules/NodeCryptoModule/aesCbcCryptor.js | 43 + .../modules/NodeCryptoModule/legacyCryptor.js | 20 + .../NodeCryptoModule/nodeCryptoModule.js | 111 ++ lib/crypto/modules/node.js | 94 ++ lib/errors/pubnub-api-error.js | 58 + lib/event-engine/core/change.js | 1 + lib/event-engine/core/dispatcher.js | 1 + lib/event-engine/core/engine.js | 1 + lib/event-engine/core/handler.js | 2 + lib/event-engine/core/retryPolicy.js | 2 + lib/event-engine/core/state.js | 1 + lib/event-engine/core/types.js | 1 + lib/event-engine/presence/effects.js | 1 + lib/file/modules/node.js | 72 ++ lib/file/modules/react-native.js | 78 ++ lib/node/configuration.js | 23 +- lib/node/index.js | 21 + lib/react_native/configuration.js | 7 + lib/react_native/index.js | 8 + lib/transport/middleware.js | 30 + lib/transport/node-transport.js | 52 + lib/transport/web-react-native-transport.js | 35 + lib/types/cbor/common.d.ts | 3 + lib/types/core/components/configuration.d.ts | 3 + .../core/components/cryptography/index.d.ts | 113 ++ .../core/components/deduping_manager.d.ts | 5 + .../core/components/listener_manager.d.ts | 62 + lib/types/core/components/push_payload.d.ts | 480 ++++++++ .../core/components/reconnection_manager.d.ts | 5 + .../core/components/subscription-manager.d.ts | 3 + lib/types/core/components/token_manager.d.ts | 3 + lib/types/core/constants/categories.d.ts | 56 + lib/types/core/constants/operations.d.ts | 148 +++ .../core/endpoints/access_manager/audit.d.ts | 3 + .../core/endpoints/access_manager/grant.d.ts | 3 + .../endpoints/access_manager/grant_token.d.ts | 3 + .../access_manager/revoke_token.d.ts | 3 + .../endpoints/actions/add_message_action.d.ts | 3 + .../actions/get_message_actions.d.ts | 3 + .../actions/remove_message_action.d.ts | 3 + .../channel_groups/add_channels.d.ts | 3 + .../channel_groups/delete_group.d.ts | 3 + .../channel_groups/list_channels.d.ts | 3 + .../endpoints/channel_groups/list_groups.d.ts | 3 + .../channel_groups/remove_channels.d.ts | 3 + lib/types/core/endpoints/fetch_messages.d.ts | 3 + .../endpoints/file_upload/delete_file.d.ts | 3 + .../endpoints/file_upload/download_file.d.ts | 3 + .../file_upload/generate_upload_url.d.ts | 3 + .../endpoints/file_upload/get_file_url.d.ts | 3 + .../endpoints/file_upload/list_files.d.ts | 3 + .../endpoints/file_upload/publish_file.d.ts | 3 + .../endpoints/file_upload/upload-file.d.ts | 3 + .../endpoints/history/delete_messages.d.ts | 3 + .../core/endpoints/history/get_history.d.ts | 3 + .../endpoints/history/message_counts.d.ts | 3 + .../core/endpoints/objects/channel/get.d.ts | 3 + .../endpoints/objects/channel/get_all.d.ts | 3 + .../endpoints/objects/channel/remove.d.ts | 3 + .../core/endpoints/objects/channel/set.d.ts | 3 + .../core/endpoints/objects/member/get.d.ts | 3 + .../core/endpoints/objects/member/set.d.ts | 3 + .../endpoints/objects/membership/get.d.ts | 3 + .../endpoints/objects/membership/set.d.ts | 3 + .../core/endpoints/objects/uuid/get.d.ts | 3 + .../core/endpoints/objects/uuid/get_all.d.ts | 3 + .../core/endpoints/objects/uuid/remove.d.ts | 3 + .../core/endpoints/objects/uuid/set.d.ts | 3 + .../core/endpoints/presence/get_state.d.ts | 3 + .../core/endpoints/presence/heartbeat.d.ts | 3 + .../core/endpoints/presence/here_now.d.ts | 3 + lib/types/core/endpoints/presence/leave.d.ts | 3 + .../core/endpoints/presence/set_state.d.ts | 3 + .../core/endpoints/presence/where_now.d.ts | 3 + lib/types/core/endpoints/publish.d.ts | 54 + .../endpoints/push/add_push_channels.d.ts | 3 + .../endpoints/push/list_push_channels.d.ts | 3 + lib/types/core/endpoints/push/push.d.ts | 3 + .../core/endpoints/push/remove_device.d.ts | 3 + .../endpoints/push/remove_push_channels.d.ts | 3 + lib/types/core/endpoints/signal.d.ts | 20 + lib/types/core/endpoints/subscribe.d.ts | 3 + .../subscriptionUtils/handshake.d.ts | 3 + .../subscriptionUtils/receiveMessages.d.ts | 3 + lib/types/core/endpoints/time.d.ts | 9 + lib/types/core/interfaces/configuration.d.ts | 264 +++- lib/types/core/interfaces/crypto-module.d.ts | 119 ++ lib/types/core/interfaces/cryptography.d.ts | 47 + lib/types/core/interfaces/transport.d.ts | 49 + lib/types/core/pubnub-channel-groups.d.ts | 69 ++ lib/types/core/pubnub-common.d.ts | 1070 +++++++++++++++++ lib/types/core/pubnub-objects.d.ts | 312 +++++ lib/types/core/pubnub-push.d.ts | 49 + lib/types/core/types/api/access-panager.d.ts | 342 ++++++ lib/types/core/types/api/app-context.d.ts | 668 ++++++++++ lib/types/core/types/api/channel-groups.d.ts | 39 + lib/types/core/types/api/file-sharing.d.ts | 272 +++++ lib/types/core/types/api/history.d.ts | 290 +++++ lib/types/core/types/api/index.d.ts | 88 ++ lib/types/core/types/api/message-action.d.ts | 109 ++ lib/types/core/types/api/presence.d.ts | 149 +++ .../core/types/api/push-notifications.d.ts | 34 + lib/types/core/types/api/push.d.ts | 90 ++ lib/types/core/types/api/subscription.d.ts | 200 +++ lib/types/core/types/file.d.ts | 80 ++ lib/types/core/types/transport-request.d.ts | 73 ++ lib/types/core/types/transport-response.d.ts | 17 + lib/types/core/utils.d.ts | 25 + .../modules/NodeCryptoModule/ICryptor.d.ts | 68 ++ .../NodeCryptoModule/ILegacyCryptor.d.ts | 49 + .../NodeCryptoModule/aesCbcCryptor.d.ts | 32 + .../NodeCryptoModule/legacyCryptor.d.ts | 15 + .../NodeCryptoModule/nodeCryptoModule.d.ts | 82 ++ lib/types/crypto/modules/node.d.ts | 74 ++ lib/types/errors/pubnub-api-error.d.ts | 57 + lib/types/event-engine/core/retryPolicy.d.ts | 32 + lib/types/file/modules/node.d.ts | 99 ++ lib/types/file/modules/react-native.d.ts | 95 ++ lib/types/node/configuration.d.ts | 45 +- lib/types/node/index.d.ts | 20 + lib/types/react_native/configuration.d.ts | 6 +- lib/types/react_native/index.d.ts | 3 + lib/types/transport/middleware.d.ts | 43 + lib/types/transport/node-transport.d.ts | 47 + .../transport/web-react-native-transport.d.ts | 23 + src/core/interfaces/configuration.ts | 6 + src/node/configuration.ts | 2 + src/react_native/configuration.ts | 2 + tsconfig.json | 1 - 222 files changed, 10450 insertions(+), 55 deletions(-) diff --git a/dist/web/pubnub.js b/dist/web/pubnub.js index 5ee09af9b..e639ef0e6 100644 --- a/dist/web/pubnub.js +++ b/dist/web/pubnub.js @@ -3521,6 +3521,8 @@ * Apply configuration default values. * * @param configuration - User-provided configuration. + * + * @internal */ const setDefaults$1 = (configuration) => { var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p, _q; diff --git a/lib/cbor/common.js b/lib/cbor/common.js index 29a9f2a2c..bd5b2e965 100644 --- a/lib/cbor/common.js +++ b/lib/cbor/common.js @@ -1,10 +1,25 @@ "use strict"; +/** + * Cbor decoder module. + */ Object.defineProperty(exports, "__esModule", { value: true }); +/** + * CBOR data decoder. + * + * @internal + */ class Cbor { constructor(decode, base64ToBinary) { this.decode = decode; this.base64ToBinary = base64ToBinary; } + /** + * Decode CBOR base64-encoded object. + * + * @param tokenString - Base64-encoded token. + * + * @returns Token object decoded from CBOR. + */ decodeToken(tokenString) { let padding = ''; if (tokenString.length % 4 === 3) diff --git a/lib/core/components/abort_signal.js b/lib/core/components/abort_signal.js index 6d51ec546..59ca4f8f3 100644 --- a/lib/core/components/abort_signal.js +++ b/lib/core/components/abort_signal.js @@ -10,6 +10,11 @@ class AbortError extends Error { } } exports.AbortError = AbortError; +/** + * Event Engine stored effect processing cancellation signal. + * + * @internal + */ class AbortSignal extends subject_1.Subject { constructor() { super(...arguments); diff --git a/lib/core/components/base64_codec.js b/lib/core/components/base64_codec.js index 4bac838e0..aa22d1d64 100644 --- a/lib/core/components/base64_codec.js +++ b/lib/core/components/base64_codec.js @@ -2,12 +2,26 @@ Object.defineProperty(exports, "__esModule", { value: true }); exports.encode = exports.decode = void 0; const BASE64_CHARMAP = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/='; +/** + * Decode a Base64 encoded string. + * + * @param paddedInput Base64 string with padding + * @returns ArrayBuffer with decoded data + * + * @internal + */ function decode(paddedInput) { + // Remove up to last two equal signs. const input = paddedInput.replace(/==?$/, ''); const outputLength = Math.floor((input.length / 4) * 3); + // Prepare output buffer. const data = new ArrayBuffer(outputLength); const view = new Uint8Array(data); let cursor = 0; + /** + * Returns the next integer representation of a sixtet of bytes from the input + * @returns sixtet of bytes + */ function nextSixtet() { const char = input.charAt(cursor++); const index = BASE64_CHARMAP.indexOf(char); @@ -17,14 +31,17 @@ function decode(paddedInput) { return index; } for (let i = 0; i < outputLength; i += 3) { + // Obtain four sixtets const sx1 = nextSixtet(); const sx2 = nextSixtet(); const sx3 = nextSixtet(); const sx4 = nextSixtet(); + // Encode them as three octets const oc1 = ((sx1 & 0b00111111) << 2) | (sx2 >> 4); const oc2 = ((sx2 & 0b00001111) << 4) | (sx3 >> 2); const oc3 = ((sx3 & 0b00000011) << 6) | (sx4 >> 0); view[i] = oc1; + // Skip padding bytes. if (sx3 != 64) view[i + 1] = oc2; if (sx4 != 64) @@ -33,6 +50,14 @@ function decode(paddedInput) { return data; } exports.decode = decode; +/** + * Encode `ArrayBuffer` as a Base64 encoded string. + * + * @param input ArrayBuffer with source data. + * @returns Base64 string with padding. + * + * @internal + */ function encode(input) { let base64 = ''; const encodings = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'; @@ -42,25 +67,32 @@ function encode(input) { const mainLength = byteLength - byteRemainder; let a, b, c, d; let chunk; + // Main loop deals with bytes in chunks of 3 for (let i = 0; i < mainLength; i = i + 3) { + // Combine the three bytes into a single integer chunk = (bytes[i] << 16) | (bytes[i + 1] << 8) | bytes[i + 2]; - a = (chunk & 16515072) >> 18; - b = (chunk & 258048) >> 12; - c = (chunk & 4032) >> 6; - d = chunk & 63; + // Use bitmasks to extract 6-bit segments from the triplet + a = (chunk & 16515072) >> 18; // 16515072 = (2^6 - 1) << 18 + b = (chunk & 258048) >> 12; // 258048 = (2^6 - 1) << 12 + c = (chunk & 4032) >> 6; // 4032 = (2^6 - 1) << 6 + d = chunk & 63; // 63 = 2^6 - 1 + // Convert the raw binary segments to the appropriate ASCII encoding base64 += encodings[a] + encodings[b] + encodings[c] + encodings[d]; } + // Deal with the remaining bytes and padding if (byteRemainder == 1) { chunk = bytes[mainLength]; - a = (chunk & 252) >> 2; - b = (chunk & 3) << 4; + a = (chunk & 252) >> 2; // 252 = (2^6 - 1) << 2 + // Set the 4 least significant bits to zero + b = (chunk & 3) << 4; // 3 = 2^2 - 1 base64 += encodings[a] + encodings[b] + '=='; } else if (byteRemainder == 2) { chunk = (bytes[mainLength] << 8) | bytes[mainLength + 1]; - a = (chunk & 64512) >> 10; - b = (chunk & 1008) >> 4; - c = (chunk & 15) << 2; + a = (chunk & 64512) >> 10; // 64512 = (2^6 - 1) << 10 + b = (chunk & 1008) >> 4; // 1008 = (2^6 - 1) << 4 + // Set the 2 least significant bits to zero + c = (chunk & 15) << 2; // 15 = 2^4 - 1 base64 += encodings[a] + encodings[b] + encodings[c] + '='; } return base64; diff --git a/lib/core/components/configuration.js b/lib/core/components/configuration.js index 07ff0840d..f70622c7a 100644 --- a/lib/core/components/configuration.js +++ b/lib/core/components/configuration.js @@ -1,15 +1,39 @@ "use strict"; +/** + * {@link PubNub} client configuration module. + */ var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", { value: true }); exports.makeConfiguration = void 0; const uuid_1 = __importDefault(require("./uuid")); +// -------------------------------------------------------- +// ----------------------- Defaults ----------------------- +// -------------------------------------------------------- +// region Defaults +/** + * Whether encryption (if set) should use random initialization vector or not. + * + * @internal + */ const USE_RANDOM_INITIALIZATION_VECTOR = true; +/** + * Create {@link PubNub} client private configuration object. + * + * @param base - User- and platform-provided configuration. + * @param setupCryptoModule - Platform-provided {@link CryptoModule} configuration block. + * + * @returns `PubNub` client private configuration. + * + * @internal + */ const makeConfiguration = (base, setupCryptoModule) => { var _a, _b, _c; + // Ensure that retry policy has proper configuration (if has been set). (_a = base.retryConfiguration) === null || _a === void 0 ? void 0 : _a.validate(); (_b = base.useRandomIVs) !== null && _b !== void 0 ? _b : (base.useRandomIVs = USE_RANDOM_INITIALIZATION_VECTOR); + // Override origin value. base.origin = standardOrigin((_c = base.ssl) !== null && _c !== void 0 ? _c : false, base.origin); const cryptoModule = base.cryptoModule; if (cryptoModule) @@ -98,6 +122,10 @@ const makeConfiguration = (base, setupCryptoModule) => { const sdk = Object.values(this._pnsdkSuffix).join(separator); return sdk.length > 0 ? separator + sdk : ''; }, + // -------------------------------------------------------- + // ---------------------- Deprecated ---------------------- + // -------------------------------------------------------- + // region Deprecated getUUID() { return this.getUserId(); }, @@ -110,6 +138,7 @@ const makeConfiguration = (base, setupCryptoModule) => { getCustomDecrypt() { return base.customDecrypt; } }); + // Setup `CryptoModule` if possible. if (base.cipherKey) clientConfiguration.setCipherKey(base.cipherKey); else if (cryptoModule) @@ -117,6 +146,14 @@ const makeConfiguration = (base, setupCryptoModule) => { return clientConfiguration; }; exports.makeConfiguration = makeConfiguration; +/** + * Decide {@lin PubNub} service REST API origin. + * + * @param secure - Whether preferred to use secured connection or not. + * @param origin - User-provided or default origin. + * + * @returns `PubNub` REST API endpoints origin. + */ const standardOrigin = (secure, origin) => { const protocol = secure ? 'https://' : 'http://'; if (typeof origin === 'string') diff --git a/lib/core/components/cryptography/hmac-sha256.js b/lib/core/components/cryptography/hmac-sha256.js index 7f5e5716a..4b8616de3 100644 --- a/lib/core/components/cryptography/hmac-sha256.js +++ b/lib/core/components/cryptography/hmac-sha256.js @@ -1,4 +1,11 @@ "use strict"; +/*eslint-disable */ +/* + CryptoJS v3.1.2 + code.google.com/p/crypto-js + (c) 2009-2013 by Jeff Mott. All rights reserved. + code.google.com/p/crypto-js/wiki/License + */ var CryptoJS = CryptoJS || (function (h, s) { var f = {}, g = (f.lib = {}), q = function () { }, m = (g.Base = { @@ -170,6 +177,7 @@ var CryptoJS = CryptoJS || var t = (f.algo = {}); return f; })(Math); +// SHA256 (function (h) { for (var s = CryptoJS, f = s.lib, g = f.WordArray, q = f.Hasher, f = s.algo, m = [], r = [], l = function (a) { return (4294967296 * (a - (a | 0))) | 0; @@ -248,6 +256,7 @@ var CryptoJS = CryptoJS || s.SHA256 = q._createHelper(f); s.HmacSHA256 = q._createHmacHelper(f); })(Math); +// HMAC SHA256 (function () { var h = CryptoJS, s = h.enc.Utf8; h.algo.HMAC = h.lib.Base.extend({ @@ -279,6 +288,7 @@ var CryptoJS = CryptoJS || }, }); })(); +// Base64 (function () { var u = CryptoJS, p = u.lib.WordArray; u.enc.Base64 = { @@ -310,6 +320,7 @@ var CryptoJS = CryptoJS || _map: 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=', }; })(); +// BlockCipher (function (u) { function p(b, n, a, c, e, j, k) { b = b + ((n & a) | (~n & c)) + e + k; @@ -390,6 +401,7 @@ var CryptoJS = CryptoJS || return s.create(p).compute(d, l); }; })(); +// Cipher CryptoJS.lib.Cipher || (function (u) { var p = CryptoJS, d = p.lib, l = d.Base, s = d.WordArray, t = d.BufferedBlockAlgorithm, r = p.enc.Base64, w = p.algo.EvpKDF, v = (d.Cipher = t.extend({ @@ -586,6 +598,7 @@ CryptoJS.lib.Cipher || }, })); })(); +// AES (function () { for (var u = CryptoJS, p = u.lib.BlockCipher, d = u.algo, l = [], s = [], t = [], r = [], w = [], v = [], b = [], x = [], q = [], n = [], a = [], c = 0; 256 > c; c++) a[c] = 128 > c ? c << 1 : (c << 1) ^ 283; @@ -656,6 +669,7 @@ CryptoJS.lib.Cipher || })); u.AES = p._createHelper(d); })(); +// Mode ECB CryptoJS.mode.ECB = (function () { var ECB = CryptoJS.lib.BlockCipherMode.extend(); ECB.Encryptor = ECB.extend({ diff --git a/lib/core/components/cryptography/index.js b/lib/core/components/cryptography/index.js index 434020616..fad0763a5 100644 --- a/lib/core/components/cryptography/index.js +++ b/lib/core/components/cryptography/index.js @@ -1,24 +1,48 @@ "use strict"; +/** + * Legacy cryptography module. + */ var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", { value: true }); const base64_codec_1 = require("../base64_codec"); const hmac_sha256_1 = __importDefault(require("./hmac-sha256")); +/** + * Convert bytes array to words array. + * + * @param b - Bytes array (buffer) which should be converted. + * + * @returns Word sized array. + */ +/* eslint-disable @typescript-eslint/no-explicit-any */ function bufferToWordArray(b) { const wa = []; let i; for (i = 0; i < b.length; i += 1) { wa[(i / 4) | 0] |= b[i] << (24 - 8 * i); } + // @ts-expect-error Bundled library without types. return hmac_sha256_1.default.lib.WordArray.create(wa, b.length); } class default_1 { constructor(configuration) { this.configuration = configuration; + /** + * Crypto initialization vector. + */ this.iv = '0123456789012345'; + /** + * List os allowed cipher key encodings. + */ this.allowedKeyEncodings = ['hex', 'utf8', 'base64', 'binary']; + /** + * Allowed cipher key lengths. + */ this.allowedKeyLengths = [128, 256]; + /** + * Allowed crypto modes. + */ this.allowedModes = ['ecb', 'cbc']; this.defaultOptions = { encryptKey: true, @@ -27,23 +51,67 @@ class default_1 { mode: 'cbc', }; } + /** + * Generate HMAC-SHA256 hash from input data. + * + * @param data - Data from which hash should be generated. + * + * @returns HMAC-SHA256 hash from provided `data`. + */ HMACSHA256(data) { + // @ts-expect-error Bundled library without types. const hash = hmac_sha256_1.default.HmacSHA256(data, this.configuration.secretKey); + // @ts-expect-error Bundled library without types. return hash.toString(hmac_sha256_1.default.enc.Base64); } + /** + * Generate SHA256 hash from input data. + * + * @param data - Data from which hash should be generated. + * + * @returns SHA256 hash from provided `data`. + */ SHA256(data) { + // @ts-expect-error Bundled library without types. return hmac_sha256_1.default.SHA256(data).toString(hmac_sha256_1.default.enc.Hex); } + /** + * Encrypt provided data. + * + * @param data - Source data which should be encrypted. + * @param [customCipherKey] - Custom cipher key (different from defined on client level). + * @param [options] - Specific crypto configuration options. + * + * @returns Encrypted `data`. + */ encrypt(data, customCipherKey, options) { if (this.configuration.customEncrypt) return this.configuration.customEncrypt(data); return this.pnEncrypt(data, customCipherKey, options); } + /** + * Decrypt provided data. + * + * @param data - Encrypted data which should be decrypted. + * @param [customCipherKey] - Custom cipher key (different from defined on client level). + * @param [options] - Specific crypto configuration options. + * + * @returns Decrypted `data`. + */ decrypt(data, customCipherKey, options) { if (this.configuration.customDecrypt) return this.configuration.customDecrypt(data); return this.pnDecrypt(data, customCipherKey, options); } + /** + * Encrypt provided data. + * + * @param data - Source data which should be encrypted. + * @param [customCipherKey] - Custom cipher key (different from defined on client level). + * @param [options] - Specific crypto configuration options. + * + * @returns Encrypted `data` as string. + */ pnEncrypt(data, customCipherKey, options) { const decidedCipherKey = customCipherKey !== null && customCipherKey !== void 0 ? customCipherKey : this.configuration.cipherKey; if (!decidedCipherKey) @@ -53,14 +121,27 @@ class default_1 { const cipherKey = this.getPaddedKey(decidedCipherKey, options); if (this.configuration.useRandomIVs) { const waIv = this.getRandomIV(); + // @ts-expect-error Bundled library without types. const waPayload = hmac_sha256_1.default.AES.encrypt(data, cipherKey, { iv: waIv, mode }).ciphertext; + // @ts-expect-error Bundled library without types. return waIv.clone().concat(waPayload.clone()).toString(hmac_sha256_1.default.enc.Base64); } const iv = this.getIV(options); + // @ts-expect-error Bundled library without types. const encryptedHexArray = hmac_sha256_1.default.AES.encrypt(data, cipherKey, { iv, mode }).ciphertext; + // @ts-expect-error Bundled library without types. const base64Encrypted = encryptedHexArray.toString(hmac_sha256_1.default.enc.Base64); return base64Encrypted || data; } + /** + * Decrypt provided data. + * + * @param data - Encrypted data which should be decrypted. + * @param [customCipherKey] - Custom cipher key (different from defined on client level). + * @param [options] - Specific crypto configuration options. + * + * @returns Decrypted `data`. + */ pnDecrypt(data, customCipherKey, options) { const decidedCipherKey = customCipherKey !== null && customCipherKey !== void 0 ? customCipherKey : this.configuration.cipherKey; if (!decidedCipherKey) @@ -73,7 +154,10 @@ class default_1 { const iv = bufferToWordArray(ciphertext.slice(0, 16)); const payload = bufferToWordArray(ciphertext.slice(16)); try { - const plainJSON = hmac_sha256_1.default.AES.decrypt({ ciphertext: payload }, cipherKey, { iv, mode }).toString(hmac_sha256_1.default.enc.Utf8); + // @ts-expect-error Bundled library without types. + const plainJSON = hmac_sha256_1.default.AES.decrypt({ ciphertext: payload }, cipherKey, { iv, mode }).toString( + // @ts-expect-error Bundled library without types. + hmac_sha256_1.default.enc.Utf8); return JSON.parse(plainJSON); } catch (e) { @@ -83,7 +167,9 @@ class default_1 { else { const iv = this.getIV(options); try { + // @ts-expect-error Bundled library without types. const ciphertext = hmac_sha256_1.default.enc.Base64.parse(data); + // @ts-expect-error Bundled library without types. const plainJSON = hmac_sha256_1.default.AES.decrypt({ ciphertext }, cipherKey, { iv, mode }).toString(hmac_sha256_1.default.enc.Utf8); return JSON.parse(plainJSON); } @@ -92,16 +178,25 @@ class default_1 { } } } + /** + * Pre-process provided custom crypto configuration. + * + * @param incomingOptions - Configuration which should be pre-processed before use. + * + * @returns Normalized crypto configuration options. + */ parseOptions(incomingOptions) { var _a, _b, _c, _d; if (!incomingOptions) return this.defaultOptions; + // Defaults const options = { encryptKey: (_a = incomingOptions.encryptKey) !== null && _a !== void 0 ? _a : this.defaultOptions.encryptKey, keyEncoding: (_b = incomingOptions.keyEncoding) !== null && _b !== void 0 ? _b : this.defaultOptions.keyEncoding, keyLength: (_c = incomingOptions.keyLength) !== null && _c !== void 0 ? _c : this.defaultOptions.keyLength, mode: (_d = incomingOptions.mode) !== null && _d !== void 0 ? _d : this.defaultOptions.mode, }; + // Validation if (this.allowedKeyEncodings.indexOf(options.keyEncoding.toLowerCase()) === -1) options.keyEncoding = this.defaultOptions.keyEncoding; if (this.allowedKeyLengths.indexOf(options.keyLength) === -1) @@ -110,28 +205,70 @@ class default_1 { options.mode = this.defaultOptions.mode; return options; } + /** + * Decode provided cipher key. + * + * @param key - Key in `encoding` provided by `options`. + * @param options - Crypto configuration options with cipher key details. + * + * @returns Array buffer with decoded key. + */ decodeKey(key, options) { + // @ts-expect-error Bundled library without types. if (options.keyEncoding === 'base64') return hmac_sha256_1.default.enc.Base64.parse(key); + // @ts-expect-error Bundled library without types. if (options.keyEncoding === 'hex') return hmac_sha256_1.default.enc.Hex.parse(key); return key; } + /** + * Add padding to the cipher key. + * + * @param key - Key which should be padded. + * @param options - Crypto configuration options with cipher key details. + * + * @returns Properly padded cipher key. + */ getPaddedKey(key, options) { key = this.decodeKey(key, options); + // @ts-expect-error Bundled library without types. if (options.encryptKey) return hmac_sha256_1.default.enc.Utf8.parse(this.SHA256(key).slice(0, 32)); return key; } + /** + * Cipher mode. + * + * @param options - Crypto configuration with information about cipher mode. + * + * @returns Crypto cipher mode. + */ getMode(options) { + // @ts-expect-error Bundled library without types. if (options.mode === 'ecb') return hmac_sha256_1.default.mode.ECB; + // @ts-expect-error Bundled library without types. return hmac_sha256_1.default.mode.CBC; } + /** + * Cipher initialization vector. + * + * @param options - Crypto configuration with information about cipher mode. + * + * @returns Initialization vector. + */ getIV(options) { + // @ts-expect-error Bundled library without types. return options.mode === 'cbc' ? hmac_sha256_1.default.enc.Utf8.parse(this.iv) : null; } + /** + * Random initialization vector. + * + * @returns Generated random initialization vector. + */ getRandomIV() { + // @ts-expect-error Bundled library without types. return hmac_sha256_1.default.lib.WordArray.random(16); } } diff --git a/lib/core/components/deduping_manager.js b/lib/core/components/deduping_manager.js index 0f30833c4..ae7904bb3 100644 --- a/lib/core/components/deduping_manager.js +++ b/lib/core/components/deduping_manager.js @@ -1,4 +1,5 @@ "use strict"; +/* */ Object.defineProperty(exports, "__esModule", { value: true }); const hashCode = (payload) => { let hash = 0; @@ -6,11 +7,16 @@ const hashCode = (payload) => { return hash; for (let i = 0; i < payload.length; i += 1) { const character = payload.charCodeAt(i); - hash = (hash << 5) - hash + character; - hash = hash & hash; + hash = (hash << 5) - hash + character; // eslint-disable-line + hash = hash & hash; // eslint-disable-line } return hash; }; +/** + * Real-time events deduplication manager. + * + * @internal + */ class default_1 { constructor({ config }) { this.hashHistory = []; diff --git a/lib/core/components/eventEmitter.js b/lib/core/components/eventEmitter.js index f843210ca..d995bd428 100644 --- a/lib/core/components/eventEmitter.js +++ b/lib/core/components/eventEmitter.js @@ -12,12 +12,33 @@ var __rest = (this && this.__rest) || function (s, e) { }; Object.defineProperty(exports, "__esModule", { value: true }); const subscribe_1 = require("../endpoints/subscribe"); +/** + * Real-time events' emitter. + * + * Emitter responsible for forwarding received real-time events to the closures which has been + * registered for specific events handling. + * + * @internal + */ class EventEmitter { constructor(listenerManager) { this.listenerManager = listenerManager; + /** + * Map of channels to listener callbacks for them. + */ this.channelListenerMap = new Map(); + /** + * Map of channel group names to the listener callbacks for them. + */ this.groupListenerMap = new Map(); } + /** + * Emit specific real-time event. + * + * Proper listener will be notified basing on event `type`. + * + * @param event - Received real-time event. + */ emitEvent(event) { if (event.type === subscribe_1.PubNubEventType.Message) { this.listenerManager.announceMessage(event.data); @@ -68,7 +89,15 @@ class EventEmitter { this.announce('file', event.data, event.data.channel, event.data.subscription); } } + /** + * Register real-time event listener for specific channels and groups. + * + * @param listener - Listener with event callbacks to handle different types of events. + * @param channels - List of channels for which listener should be registered. + * @param groups - List of channel groups for which listener should be registered. + */ addListener(listener, channels, groups) { + // Register event-listener listener globally. if (!(channels && groups)) { this.listenerManager.addListener(listener); } @@ -93,6 +122,13 @@ class EventEmitter { }); } } + /** + * Remove real-time event listener. + * + * @param listener - Event listeners which should be removed. + * @param channels - List of channels for which listener should be removed. + * @param groups - List of channel groups for which listener should be removed. + */ removeListener(listener, channels, groups) { if (!(channels && groups)) { this.listenerManager.removeListener(listener); @@ -110,21 +146,34 @@ class EventEmitter { }); } } + /** + * Clear all real-time event listeners. + */ removeAllListeners() { this.listenerManager.removeAllListeners(); this.channelListenerMap.clear(); this.groupListenerMap.clear(); } + /** + * Announce real-time event to all listeners. + * + * @param type - Type of event which should be announced. + * @param event - Announced real-time event payload. + * @param channel - Name of the channel for which registered listeners should be notified. + * @param group - Name of the channel group for which registered listeners should be notified. + */ announce(type, event, channel, group) { if (event && this.channelListenerMap.has(channel)) this.channelListenerMap.get(channel).forEach((listener) => { const typedListener = listener[type]; + // @ts-expect-error Dynamic events mapping. if (typedListener) typedListener(event); }); if (group && this.groupListenerMap.has(group)) this.groupListenerMap.get(group).forEach((listener) => { const typedListener = listener[type]; + // @ts-expect-error Dynamic events mapping. if (typedListener) typedListener(event); }); diff --git a/lib/core/components/listener_manager.js b/lib/core/components/listener_manager.js index 37778be75..59072e7ed 100644 --- a/lib/core/components/listener_manager.js +++ b/lib/core/components/listener_manager.js @@ -1,67 +1,130 @@ "use strict"; +/** + * Events listener manager module. + */ var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", { value: true }); exports.ListenerManager = void 0; const categories_1 = __importDefault(require("../constants/categories")); +/** + * Real-time listeners' manager. + * + * @internal + */ class ListenerManager { constructor() { + /** + * List of registered event listeners. + */ this.listeners = []; + // endregion } + /** + * Register new real-time events listener. + * + * @param listener - Listener with event callbacks to handle different types of events. + */ addListener(listener) { if (this.listeners.includes(listener)) return; this.listeners.push(listener); } + /** + * Remove real-time event listener. + * + * @param listener - Event listeners which should be removed. + */ removeListener(listener) { this.listeners = this.listeners.filter((storedListener) => storedListener !== listener); } + /** + * Clear all real-time event listeners. + */ removeAllListeners() { this.listeners = []; } + /** + * Announce PubNub client status change event. + * + * @param status - PubNub client status. + */ announceStatus(status) { this.listeners.forEach((listener) => { if (listener.status) listener.status(status); }); } + /** + * Announce channel presence change event. + * + * @param presence - Channel presence change information. + */ announcePresence(presence) { this.listeners.forEach((listener) => { if (listener.presence) listener.presence(presence); }); } + /** + * Announce real-time message event. + * + * @param message - Received real-time message. + */ announceMessage(message) { this.listeners.forEach((listener) => { if (listener.message) listener.message(message); }); } + /** + * Announce real-time signal event. + * + * @param signal - Received real-time signal. + */ announceSignal(signal) { this.listeners.forEach((listener) => { if (listener.signal) listener.signal(signal); }); } + /** + * Announce message actions change event. + * + * @param messageAction - Message action change information. + */ announceMessageAction(messageAction) { this.listeners.forEach((listener) => { if (listener.messageAction) listener.messageAction(messageAction); }); } + /** + * Announce fie share event. + * + * @param file - Shared file information. + */ announceFile(file) { this.listeners.forEach((listener) => { if (listener.file) listener.file(file); }); } + /** + * Announce App Context Object change event. + * + * @param object - App Context change information. + */ announceObjects(object) { this.listeners.forEach((listener) => { if (listener.objects) listener.objects(object); }); } + /** + * Announce network up status. + */ announceNetworkUp() { this.listeners.forEach((listener) => { if (listener.status) { @@ -71,6 +134,9 @@ class ListenerManager { } }); } + /** + * Announce network down status. + */ announceNetworkDown() { this.listeners.forEach((listener) => { if (listener.status) { @@ -80,18 +146,43 @@ class ListenerManager { } }); } + // -------------------------------------------------------- + // ---------------------- Deprecated ---------------------- + // -------------------------------------------------------- + // region Deprecated + /** + * Announce User App Context Object change event. + * + * @param user - User App Context change information. + * + * @deprecated Use {@link announceObjects} method instead. + */ announceUser(user) { this.listeners.forEach((listener) => { if (listener.user) listener.user(user); }); } + /** + * Announce Space App Context Object change event. + * + * @param space - Space App Context change information. + * + * @deprecated Use {@link announceObjects} method instead. + */ announceSpace(space) { this.listeners.forEach((listener) => { if (listener.space) listener.space(space); }); } + /** + * Announce VSP Membership App Context Object change event. + * + * @param membership - VSP Membership App Context change information. + * + * @deprecated Use {@link announceObjects} method instead. + */ announceMembership(membership) { this.listeners.forEach((listener) => { if (listener.membership) diff --git a/lib/core/components/push_payload.js b/lib/core/components/push_payload.js index e2196cd9b..005ffd348 100644 --- a/lib/core/components/push_payload.js +++ b/lib/core/components/push_payload.js @@ -1,4 +1,8 @@ "use strict"; +// -------------------------------------------------------- +// ------------------------ Types ------------------------- +// -------------------------------------------------------- +// region Types var __rest = (this && this.__rest) || function (s, e) { var t = {}; for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0) @@ -12,6 +16,11 @@ var __rest = (this && this.__rest) || function (s, e) { }; Object.defineProperty(exports, "__esModule", { value: true }); exports.FCMNotificationPayload = exports.APNSNotificationPayload = void 0; +// endregion +// endregion +/** + * Base notification payload object. + */ class BaseNotificationPayload { constructor(payload, title, body) { this._payload = payload; @@ -19,91 +28,205 @@ class BaseNotificationPayload { this.title = title; this.body = body; } + /** + * Retrieve resulting notification payload content for message. + * + * @returns Preformatted push notification payload data. + */ get payload() { return this._payload; } + /** + * Update notification title. + * + * @param value - New notification title. + */ set title(value) { this._title = value; } + /** + * Update notification subtitle. + * + * @param value - New second-line notification title. + */ set subtitle(value) { this._subtitle = value; } + /** + * Update notification body. + * + * @param value - Update main notification message (shown when expanded). + */ set body(value) { this._body = value; } + /** + * Update application badge number. + * + * @param value - Number which should be shown in application badge upon receiving notification. + */ set badge(value) { this._badge = value; } + /** + * Update notification sound. + * + * @param value - Name of the sound file which should be played upon notification receive. + */ set sound(value) { this._sound = value; } + /** + * Platform-specific structure initialization. + */ setDefaultPayloadStructure() { } + /** + * Translate data object into PubNub push notification payload object. + * + * @returns Preformatted push notification payload. + */ toObject() { return {}; } } +/** + * Message payload for Apple Push Notification Service. + */ class APNSNotificationPayload extends BaseNotificationPayload { constructor() { super(...arguments); + /** + * Type of push notification service for which payload will be created. + */ this._apnsPushType = 'apns'; + /** + * Whether resulting payload should trigger silent notification or not. + */ this._isSilent = false; } get payload() { return this._payload; } + /** + * Update notification receivers configuration. + * + * @param value - New APNS2 configurations. + */ set configurations(value) { if (!value || !value.length) return; this._configurations = value; } + /** + * Notification payload. + * + * @returns Platform-specific part of PubNub notification payload. + */ get notification() { return this.payload.aps; } + /** + * Notification title. + * + * @returns Main notification title. + */ get title() { return this._title; } + /** + * Update notification title. + * + * @param value - New notification title. + */ set title(value) { if (!value || !value.length) return; this.payload.aps.alert.title = value; this._title = value; } + /** + * Notification subtitle. + * + * @returns Second-line notification title. + */ get subtitle() { return this._subtitle; } + /** + * Update notification subtitle. + * + * @param value - New second-line notification title. + */ set subtitle(value) { if (!value || !value.length) return; this.payload.aps.alert.subtitle = value; this._subtitle = value; } + /** + * Notification body. + * + * @returns Main notification message (shown when expanded). + */ get body() { return this._body; } + /** + * Update notification body. + * + * @param value - Update main notification message (shown when expanded). + */ set body(value) { if (!value || !value.length) return; this.payload.aps.alert.body = value; this._body = value; } + /** + * Retrieve unread notifications number. + * + * @returns Number of unread notifications which should be shown on application badge. + */ get badge() { return this._badge; } + /** + * Update application badge number. + * + * @param value - Number which should be shown in application badge upon receiving notification. + */ set badge(value) { if (value === undefined || value === null) return; this.payload.aps.badge = value; this._badge = value; } + /** + * Retrieve notification sound file. + * + * @returns Notification sound file name from resource bundle. + */ get sound() { return this._sound; } + /** + * Update notification sound. + * + * @param value - Name of the sound file which should be played upon notification receive. + */ set sound(value) { if (!value || !value.length) return; this.payload.aps.sound = value; this._sound = value; } + /** + * Set whether notification should be silent or not. + * + * `content-available` notification type will be used to deliver silent notification if set to `true`. + * + * @param value - Whether notification should be sent as silent or not. + */ set silent(value) { this._isSilent = value; } @@ -136,6 +259,13 @@ class APNSNotificationPayload extends BaseNotificationPayload { } return this._isSilent || (alert && Object.keys(alert).length) ? payload : null; } + /** + * Create PubNub push notification service APNS2 configuration information object. + * + * @param configuration - Source user-provided APNS2 configuration. + * + * @returns Preformatted for PubNub service APNS2 configuration information. + */ objectFromAPNS2Configuration(configuration) { if (!configuration.targets || !configuration.targets.length) throw new ReferenceError('At least one APNS2 target should be provided'); @@ -151,6 +281,13 @@ class APNSNotificationPayload extends BaseNotificationPayload { objectifiedConfiguration.expiration = expirationDate.toISOString(); return objectifiedConfiguration; } + /** + * Create PubNub push notification service APNS2 target information object. + * + * @param target - Source user-provided data. + * + * @returns Preformatted for PubNub service APNS2 target information. + */ objectFromAPNSTarget(target) { if (!target.topic || !target.topic.length) throw new TypeError("Target 'topic' undefined."); @@ -162,46 +299,99 @@ class APNSNotificationPayload extends BaseNotificationPayload { } } exports.APNSNotificationPayload = APNSNotificationPayload; +/** + * Message payload for Firebase Clouse Messaging service. + */ class FCMNotificationPayload extends BaseNotificationPayload { get payload() { return this._payload; } + /** + * Notification payload. + * + * @returns Platform-specific part of PubNub notification payload. + */ get notification() { return this.payload.notification; } + /** + * Silent notification payload. + * + * @returns Silent notification payload (data notification). + */ get data() { return this.payload.data; } + /** + * Notification title. + * + * @returns Main notification title. + */ get title() { return this._title; } + /** + * Update notification title. + * + * @param value - New notification title. + */ set title(value) { if (!value || !value.length) return; this.payload.notification.title = value; this._title = value; } + /** + * Notification body. + * + * @returns Main notification message (shown when expanded). + */ get body() { return this._body; } + /** + * Update notification body. + * + * @param value - Update main notification message (shown when expanded). + */ set body(value) { if (!value || !value.length) return; this.payload.notification.body = value; this._body = value; } + /** + * Retrieve notification sound file. + * + * @returns Notification sound file name from resource bundle. + */ get sound() { return this._sound; } + /** + * Update notification sound. + * + * @param value - Name of the sound file which should be played upon notification receive. + */ set sound(value) { if (!value || !value.length) return; this.payload.notification.sound = value; this._sound = value; } + /** + * Retrieve notification icon file. + * + * @returns Notification icon file name from resource bundle. + */ get icon() { return this._icon; } + /** + * Update notification icon. + * + * @param value - Name of the icon file which should be shown on notification. + */ set icon(value) { if (!value || !value.length) return; @@ -217,6 +407,13 @@ class FCMNotificationPayload extends BaseNotificationPayload { this.payload.notification.tag = value; this._tag = value; } + /** + * Set whether notification should be silent or not. + * + * All notification data will be sent under `data` field if set to `true`. + * + * @param value - Whether notification should be sent as silent or not. + */ set silent(value) { this._isSilent = value; } @@ -228,6 +425,7 @@ class FCMNotificationPayload extends BaseNotificationPayload { let data = Object.assign({}, this.payload.data); let notification = null; const payload = {}; + // Check whether additional data has been passed outside 'data' object and put it into it if required. if (Object.keys(this.payload).length > 2) { const _a = this.payload, { notification: initialNotification, data: initialData } = _a, additionalData = __rest(_a, ["notification", "data"]); data = Object.assign(Object.assign({}, data), additionalData); @@ -255,39 +453,89 @@ class NotificationsPayload { set debugging(value) { this._debugging = value; } + /** + * Notification title. + * + * @returns Main notification title. + */ get title() { return this._title; } + /** + * Notification subtitle. + * + * @returns Second-line notification title. + */ get subtitle() { return this._subtitle; } + /** + * Update notification subtitle. + * + * @param value - New second-line notification title. + */ set subtitle(value) { this._subtitle = value; this.apns.subtitle = value; this.fcm.subtitle = value; } + /** + * Notification body. + * + * @returns Main notification message (shown when expanded). + */ get body() { return this._body; } + /** + * Retrieve unread notifications number. + * + * @returns Number of unread notifications which should be shown on application badge. + */ get badge() { return this._badge; } + /** + * Update application badge number. + * + * @param value - Number which should be shown in application badge upon receiving notification. + */ set badge(value) { this._badge = value; this.apns.badge = value; this.fcm.badge = value; } + /** + * Retrieve notification sound file. + * + * @returns Notification sound file name from resource bundle. + */ get sound() { return this._sound; } + /** + * Update notification sound. + * + * @param value - Name of the sound file which should be played upon notification receive. + */ set sound(value) { this._sound = value; this.apns.sound = value; this.fcm.sound = value; } + /** + * Build notifications platform for requested platforms. + * + * @param platforms - List of platforms for which payload should be added to final dictionary. Supported values: + * gcm, apns, and apns2. + * + * @returns Object with data, which can be sent with publish method call and trigger remote notifications for + * specified platforms. + */ buildPayload(platforms) { const payload = {}; if (platforms.includes('apns') || platforms.includes('apns2')) { + // @ts-expect-error Override APNS version. this.apns._apnsPushType = platforms.includes('apns') ? 'apns' : 'apns2'; const apnsPayload = this.apns.toObject(); if (apnsPayload && Object.keys(apnsPayload).length) diff --git a/lib/core/components/reconnection_manager.js b/lib/core/components/reconnection_manager.js index bc3065231..731bd261e 100644 --- a/lib/core/components/reconnection_manager.js +++ b/lib/core/components/reconnection_manager.js @@ -1,16 +1,39 @@ "use strict"; +/** + * Subscription reconnection-manager. + * + * **Note:** Reconnection manger rely on legacy time-based availability check. + */ Object.defineProperty(exports, "__esModule", { value: true }); exports.ReconnectionManager = void 0; +/** + * Network "discovery" manager. + * + * Manager perform periodic `time` API calls to identify network availability. + * + * @internal + */ class ReconnectionManager { constructor(time) { this.time = time; } + /** + * Configure reconnection handler. + * + * @param callback - Successful availability check notify callback. + */ onReconnect(callback) { this.callback = callback; } + /** + * Start periodic "availability" check. + */ startPolling() { this.timeTimer = setInterval(() => this.callTime(), 3000); } + /** + * Stop periodic "availability" check. + */ stopPolling() { if (this.timeTimer) clearInterval(this.timeTimer); diff --git a/lib/core/components/request.js b/lib/core/components/request.js index 9da7e686b..0a2e3af5a 100644 --- a/lib/core/components/request.js +++ b/lib/core/components/request.js @@ -15,33 +15,82 @@ Object.defineProperty(exports, "__esModule", { value: true }); exports.AbstractRequest = void 0; const transport_request_1 = require("../types/transport-request"); const uuid_1 = __importDefault(require("./uuid")); +/** + * Base REST API request class. + * + * @internal + */ class AbstractRequest { + /** + * Construct base request. + * + * Constructed request by default won't be cancellable and performed using `GET` HTTP method. + * + * @param params - Request configuration parameters. + */ constructor(params) { this.params = params; + /** + * Unique request identifier. + */ this.requestIdentifier = uuid_1.default.createUUID(); this._cancellationController = null; } + /** + * Retrieve configured cancellation controller. + * + * @returns Cancellation controller. + */ get cancellationController() { return this._cancellationController; } + /** + * Update request cancellation controller. + * + * Controller itself provided by transport provider implementation and set only when request + * sending has been scheduled. + * + * @param controller - Cancellation controller or `null` to reset it. + */ set cancellationController(controller) { this._cancellationController = controller; } + /** + * Abort request if possible. + */ abort() { if (this && this.cancellationController) this.cancellationController.abort(); } + /** + * Target REST API endpoint operation type. + */ operation() { throw Error('Should be implemented by subclass.'); } + /** + * Validate user-provided data before scheduling request. + * + * @returns Error message if request can't be sent without missing or malformed parameters. + */ validate() { return undefined; } + /** + * Parse service response. + * + * @param _response - Raw service response which should be parsed. + */ parse(_response) { return __awaiter(this, void 0, void 0, function* () { throw Error('Should be implemented by subclass.'); }); } + /** + * Create platform-agnostic request object. + * + * @returns Request object which can be processed using platform-specific requirements. + */ request() { var _a, _b, _c, _d; const request = { @@ -52,9 +101,11 @@ class AbstractRequest { timeout: 10000, identifier: this.requestIdentifier, }; + // Attach headers (if required). const headers = this.headers; if (headers) request.headers = headers; + // Attach body (if required). if (request.method === transport_request_1.TransportMethod.POST || request.method === transport_request_1.TransportMethod.PATCH) { const [body, formData] = [this.body, this.formData]; if (formData) @@ -64,21 +115,48 @@ class AbstractRequest { } return request; } + /** + * Target REST API endpoint request headers getter. + * + * @returns Key/value headers which should be used with request. + */ get headers() { return undefined; } + /** + * Target REST API endpoint request path getter. + * + * @returns REST API path. + */ get path() { throw Error('`path` getter should be implemented by subclass.'); } + /** + * Target REST API endpoint request query parameters getter. + * + * @returns Key/value pairs which should be appended to the REST API path. + */ get queryParameters() { return {}; } get formData() { return undefined; } + /** + * Target REST API Request body payload getter. + * + * @returns Buffer of stringified data which should be sent with `POST` or `PATCH` request. + */ get body() { return undefined; } + /** + * Deserialize service response. + * + * @param response - Transparent response object with headers and body information. + * + * @returns Deserialized data or `undefined` in case of `JSON.parse(..)` error. + */ deserializeResponse(response) { const contentType = response.headers['content-type']; if (!contentType || (contentType.indexOf('javascript') === -1 && contentType.indexOf('json') === -1)) @@ -95,4 +173,7 @@ class AbstractRequest { } } exports.AbstractRequest = AbstractRequest; +/** + * Service `ArrayBuffer` response decoder. + */ AbstractRequest.decoder = new TextDecoder(); diff --git a/lib/core/components/stringify_buffer_keys.js b/lib/core/components/stringify_buffer_keys.js index 1a0b1692b..c9c405834 100644 --- a/lib/core/components/stringify_buffer_keys.js +++ b/lib/core/components/stringify_buffer_keys.js @@ -1,6 +1,15 @@ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.stringifyBufferKeys = void 0; +/** + * Re-map CBOR object keys from potentially C buffer strings to actual strings. + * + * @param obj CBOR which should be remapped to stringified keys. + * + * @returns Dictionary with stringified keys. + * + * @internal + */ function stringifyBufferKeys(obj) { const isObject = (value) => typeof value === 'object' && value !== null && value.constructor === Object; const isString = (value) => typeof value === 'string' || value instanceof String; diff --git a/lib/core/components/subject.js b/lib/core/components/subject.js index fed3f3ade..e483d4954 100644 --- a/lib/core/components/subject.js +++ b/lib/core/components/subject.js @@ -1,6 +1,9 @@ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.Subject = void 0; +/** + * @internal + */ class Subject { constructor(sync = false) { this.sync = sync; diff --git a/lib/core/components/subscription-manager.js b/lib/core/components/subscription-manager.js index fa7d37902..1f5139485 100644 --- a/lib/core/components/subscription-manager.js +++ b/lib/core/components/subscription-manager.js @@ -1,4 +1,7 @@ "use strict"; +/** + * Subscription manager module. + */ var __rest = (this && this.__rest) || function (s, e) { var t = {}; for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0) @@ -19,6 +22,11 @@ const reconnection_manager_1 = require("./reconnection_manager"); const categories_1 = __importDefault(require("../constants/categories")); const categories_2 = __importDefault(require("../constants/categories")); const deduping_manager_1 = __importDefault(require("./deduping_manager")); +/** + * Subscription loop manager. + * + * @internal + */ class SubscriptionManager { constructor(configuration, listenerManager, eventEmitter, subscribeCall, heartbeatCall, leaveCall, time) { this.configuration = configuration; @@ -45,6 +53,7 @@ class SubscriptionManager { this.subscriptionStatusAnnounced = false; this.isOnline = true; } + // region Information get subscribedChannels() { return Object.keys(this.channels); } @@ -57,6 +66,8 @@ class SubscriptionManager { set abort(call) { this._subscribeAbort = call; } + // endregion + // region Subscription disconnect() { this.stopSubscribeLoop(); this.stopHeartbeatTimer(); @@ -66,6 +77,11 @@ class SubscriptionManager { this.startSubscribeLoop(); this.startHeartbeatTimer(); } + /** + * Update channels and groups used in subscription loop. + * + * @param parameters - Subscribe configuration parameters. + */ subscribe(parameters) { const { channels, channelGroups, timetoken, withPresence = false, withHeartbeats = false } = parameters; if (timetoken) { @@ -127,6 +143,7 @@ class SubscriptionManager { actualChannelGroups.add(group); } }); + // There is no need to unsubscribe to empty list of data sources. if (actualChannels.size === 0 && actualChannelGroups.size === 0) return; if (this.configuration.suppressLeaveEvents === false && !isOffline) { @@ -171,6 +188,7 @@ class SubscriptionManager { const channels = [...Object.keys(this.channels)]; Object.keys(this.presenceChannelGroups).forEach((group) => channelGroups.push(`${group}-pnpres`)); Object.keys(this.presenceChannels).forEach((channel) => channels.push(`${channel}-pnpres`)); + // There is no need to start subscription loop for empty list of data sources. if (channels.length === 0 && channelGroups.length === 0) return; this.subscribeCall({ @@ -191,8 +209,12 @@ class SubscriptionManager { this._subscribeAbort = null; } } + /** + * Process subscribe REST API endpoint response. + */ processSubscribeResponse(status, result) { if (status.error) { + // Ignore aborted request. if ((typeof status.errorData === 'object' && 'name' in status.errorData && status.errorData.name === 'AbortError') || @@ -254,6 +276,7 @@ class SubscriptionManager { }; this.subscriptionStatusAnnounced = true; this.listenerManager.announceStatus(connected); + // Clear pending channels and groups. this.pendingChannelGroupSubscriptions.clear(); this.pendingChannelSubscriptions.clear(); } @@ -287,11 +310,23 @@ class SubscriptionManager { this.region = result.cursor.region; this.startSubscribeLoop(); } + // endregion + // region Presence + /** + * Update `uuid` state which should be sent with subscribe request. + * + * @param parameters - Channels and groups with state which should be associated to `uuid`. + */ setState(parameters) { const { state, channels, channelGroups } = parameters; channels === null || channels === void 0 ? void 0 : channels.forEach((channel) => channel in this.channels && (this.presenceState[channel] = state)); channelGroups === null || channelGroups === void 0 ? void 0 : channelGroups.forEach((group) => group in this.channelGroups && (this.presenceState[group] = state)); } + /** + * Manual presence management. + * + * @param parameters - Desired presence state for provided list of channels and groups. + */ changePresence(parameters) { const { connected, channels, channelGroups } = parameters; if (connected) { @@ -321,15 +356,24 @@ class SubscriptionManager { this.sendHeartbeat(); this.heartbeatTimer = setInterval(() => this.sendHeartbeat(), heartbeatInterval * 1000); } + /** + * Stop heartbeat. + * + * Stop timer which trigger {@link HeartbeatRequest} sending with configured presence intervals. + */ stopHeartbeatTimer() { if (!this.heartbeatTimer) return; clearInterval(this.heartbeatTimer); this.heartbeatTimer = null; } + /** + * Send heartbeat request. + */ sendHeartbeat() { const heartbeatChannelGroups = Object.keys(this.heartbeatChannelGroups); const heartbeatChannels = Object.keys(this.heartbeatChannels); + // There is no need to start heartbeat loop if there is no channels and groups to use. if (heartbeatChannels.length === 0 && heartbeatChannelGroups.length === 0) return; this.heartbeatCall({ diff --git a/lib/core/components/token_manager.js b/lib/core/components/token_manager.js index 9ada86a34..422a7dd8c 100644 --- a/lib/core/components/token_manager.js +++ b/lib/core/components/token_manager.js @@ -1,19 +1,49 @@ "use strict"; +/** + * PubNub Access Token Manager module. + */ Object.defineProperty(exports, "__esModule", { value: true }); exports.TokenManager = void 0; +// endregion +/** + * REST API access token manager. + * + * Manager maintains active access token and let parse it to get information about permissions. + * + * @internal + */ class TokenManager { constructor(cbor) { this.cbor = cbor; } + /** + * Update REST API access token. + * + * **Note:** Token will be applied only for next requests and won't affect ongoing requests. + * + * @param [token] - Access token which should be used to access PubNub REST API. + */ setToken(token) { if (token && token.length > 0) this.token = token; else this.token = undefined; } + /** + * REST API access token. + * + * @returns Previously configured REST API access token. + */ getToken() { return this.token; } + /** + * Parse Base64-encoded access token. + * + * @param tokenString - Base64-encoded access token. + * + * @returns Information about resources and permissions which has been granted for them. + */ parseToken(tokenString) { const parsed = this.cbor.decodeToken(tokenString); if (parsed !== undefined) { @@ -72,6 +102,13 @@ class TokenManager { } return undefined; } + /** + * Extract resource access permission information. + * + * @param permissions - Bit-encoded resource permissions. + * + * @returns Human-readable resource permissions. + */ extractPermissions(permissions) { const permissionsResult = { read: false, diff --git a/lib/core/components/uuid.js b/lib/core/components/uuid.js index deb3c187f..4d1255653 100644 --- a/lib/core/components/uuid.js +++ b/lib/core/components/uuid.js @@ -9,6 +9,7 @@ exports.default = { if (lil_uuid_1.default.uuid) { return lil_uuid_1.default.uuid(); } + // @ts-expect-error Depending on module type it may be callable. return (0, lil_uuid_1.default)(); }, }; diff --git a/lib/core/constants/categories.js b/lib/core/constants/categories.js index de7657670..faab584be 100644 --- a/lib/core/constants/categories.js +++ b/lib/core/constants/categories.js @@ -1,22 +1,84 @@ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); +/** + * Request processing status categories. + */ var StatusCategory; (function (StatusCategory) { + /** + * Call failed when network was unable to complete the call. + */ StatusCategory["PNNetworkIssuesCategory"] = "PNNetworkIssuesCategory"; + /** + * Network call timed out. + */ StatusCategory["PNTimeoutCategory"] = "PNTimeoutCategory"; + /** + * Request has been cancelled. + */ StatusCategory["PNCancelledCategory"] = "PNCancelledCategory"; + /** + * Server responded with bad response. + */ StatusCategory["PNBadRequestCategory"] = "PNBadRequestCategory"; + /** + * Server responded with access denied. + */ StatusCategory["PNAccessDeniedCategory"] = "PNAccessDeniedCategory"; + /** + * Incomplete parameters provided for used endpoint. + */ StatusCategory["PNValidationErrorCategory"] = "PNValidationErrorCategory"; + /** + * PubNub request acknowledgment status. + * + * Some API endpoints respond with request processing status w/o useful data. + */ StatusCategory["PNAcknowledgmentCategory"] = "PNAcknowledgmentCategory"; + /** + * Something strange happened; please check the logs. + */ StatusCategory["PNUnknownCategory"] = "PNUnknownCategory"; + // -------------------------------------------------------- + // --------------------- Network status ------------------- + // -------------------------------------------------------- + /** + * SDK will announce when the network appears to be connected again. + */ StatusCategory["PNNetworkUpCategory"] = "PNNetworkUpCategory"; + /** + * SDK will announce when the network appears to down. + */ StatusCategory["PNNetworkDownCategory"] = "PNNetworkDownCategory"; + // -------------------------------------------------------- + // -------------------- Real-time events ------------------ + // -------------------------------------------------------- + /** + * PubNub client reconnected to the real-time updates stream. + */ StatusCategory["PNReconnectedCategory"] = "PNReconnectedCategory"; + /** + * PubNub client connected to the real-time updates stream. + */ StatusCategory["PNConnectedCategory"] = "PNConnectedCategory"; + /** + * Received real-time updates exceed specified threshold. + * + * After temporary disconnection and catchup, this category means that potentially some + * real-time updates have been pushed into `storage` and need to be requested separately. + */ StatusCategory["PNRequestMessageCountExceededCategory"] = "PNRequestMessageCountExceededCategory"; + /** + * PubNub client disconnected from the real-time updates streams. + */ StatusCategory["PNDisconnectedCategory"] = "PNDisconnectedCategory"; + /** + * PubNub client wasn't able to connect to the real-time updates streams. + */ StatusCategory["PNConnectionErrorCategory"] = "PNConnectionErrorCategory"; + /** + * PubNub client unexpectedly disconnected from the real-time updates streams. + */ StatusCategory["PNDisconnectedUnexpectedlyCategory"] = "PNDisconnectedUnexpectedlyCategory"; })(StatusCategory || (StatusCategory = {})); exports.default = StatusCategory; diff --git a/lib/core/constants/operations.js b/lib/core/constants/operations.js index c30b7e919..dc348150f 100644 --- a/lib/core/constants/operations.js +++ b/lib/core/constants/operations.js @@ -1,57 +1,240 @@ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); +/* */ var RequestOperation; (function (RequestOperation) { + // -------------------------------------------------------- + // ---------------------- Publish API --------------------- + // -------------------------------------------------------- + /** + * Data publish REST API operation. + */ RequestOperation["PNPublishOperation"] = "PNPublishOperation"; + /** + * Signal sending REST API operation. + */ RequestOperation["PNSignalOperation"] = "PNSignalOperation"; + // -------------------------------------------------------- + // --------------------- Subscribe API -------------------- + // -------------------------------------------------------- + /** + * Subscribe for real-time updates REST API operation. + * + * User's presence change on specified entities will trigger `join` event. + */ RequestOperation["PNSubscribeOperation"] = "PNSubscribeOperation"; + /** + * Unsubscribe from real-time updates REST API operation. + * + * User's presence change on specified entities will trigger `leave` event. + */ RequestOperation["PNUnsubscribeOperation"] = "PNUnsubscribeOperation"; + // -------------------------------------------------------- + // --------------------- Presence API --------------------- + // -------------------------------------------------------- + /** + * Fetch user's presence information REST API operation. + */ RequestOperation["PNWhereNowOperation"] = "PNWhereNowOperation"; + /** + * Fetch channel's presence information REST API operation. + */ RequestOperation["PNHereNowOperation"] = "PNHereNowOperation"; + /** + * Fetch global presence information REST API operation. + */ RequestOperation["PNGlobalHereNowOperation"] = "PNGlobalHereNowOperation"; + /** + * Update user's information associated with specified channel REST API operation. + */ RequestOperation["PNSetStateOperation"] = "PNSetStateOperation"; + /** + * Fetch user's information associated with the specified channel REST API operation. + */ RequestOperation["PNGetStateOperation"] = "PNGetStateOperation"; + /** + * Announce presence on managed channels REST API operation. + */ RequestOperation["PNHeartbeatOperation"] = "PNHeartbeatOperation"; + // -------------------------------------------------------- + // ----------------- Message Reaction API ----------------- + // -------------------------------------------------------- + /** + * Add a reaction to the specified message REST API operation. + */ RequestOperation["PNAddMessageActionOperation"] = "PNAddActionOperation"; + /** + * Remove reaction from the specified message REST API operation. + */ RequestOperation["PNRemoveMessageActionOperation"] = "PNRemoveMessageActionOperation"; + /** + * Fetch reactions for specific message REST API operation. + */ RequestOperation["PNGetMessageActionsOperation"] = "PNGetMessageActionsOperation"; RequestOperation["PNTimeOperation"] = "PNTimeOperation"; + // -------------------------------------------------------- + // ---------------------- Storage API --------------------- + // -------------------------------------------------------- + /** + * Channel history REST API operation. + */ RequestOperation["PNHistoryOperation"] = "PNHistoryOperation"; + /** + * Delete messages from channel history REST API operation. + */ RequestOperation["PNDeleteMessagesOperation"] = "PNDeleteMessagesOperation"; + /** + * History for channels REST API operation. + */ RequestOperation["PNFetchMessagesOperation"] = "PNFetchMessagesOperation"; + /** + * Number of messages for channels in specified time frame REST API operation. + */ RequestOperation["PNMessageCounts"] = "PNMessageCountsOperation"; + // -------------------------------------------------------- + // -------------------- App Context API ------------------- + // -------------------------------------------------------- + /** + * Fetch users metadata REST API operation. + */ RequestOperation["PNGetAllUUIDMetadataOperation"] = "PNGetAllUUIDMetadataOperation"; + /** + * Fetch user metadata REST API operation. + */ RequestOperation["PNGetUUIDMetadataOperation"] = "PNGetUUIDMetadataOperation"; + /** + * Set user metadata REST API operation. + */ RequestOperation["PNSetUUIDMetadataOperation"] = "PNSetUUIDMetadataOperation"; + /** + * Remove user metadata REST API operation. + */ RequestOperation["PNRemoveUUIDMetadataOperation"] = "PNRemoveUUIDMetadataOperation"; + /** + * Fetch channels metadata REST API operation. + */ RequestOperation["PNGetAllChannelMetadataOperation"] = "PNGetAllChannelMetadataOperation"; + /** + * Fetch channel metadata REST API operation. + */ RequestOperation["PNGetChannelMetadataOperation"] = "PNGetChannelMetadataOperation"; + /** + * Set channel metadata REST API operation. + */ RequestOperation["PNSetChannelMetadataOperation"] = "PNSetChannelMetadataOperation"; + /** + * Remove channel metadata REST API operation. + */ RequestOperation["PNRemoveChannelMetadataOperation"] = "PNRemoveChannelMetadataOperation"; + /** + * Fetch channel members REST API operation. + */ RequestOperation["PNGetMembersOperation"] = "PNGetMembersOperation"; + /** + * Update channel members REST API operation. + */ RequestOperation["PNSetMembersOperation"] = "PNSetMembersOperation"; + /** + * Fetch channel memberships REST API operation. + */ RequestOperation["PNGetMembershipsOperation"] = "PNGetMembershipsOperation"; + /** + * Update channel memberships REST API operation. + */ RequestOperation["PNSetMembershipsOperation"] = "PNSetMembershipsOperation"; + // -------------------------------------------------------- + // -------------------- File Upload API ------------------- + // -------------------------------------------------------- + /** + * Fetch list of files sent to the channel REST API operation. + */ RequestOperation["PNListFilesOperation"] = "PNListFilesOperation"; + /** + * Retrieve file upload URL REST API operation. + */ RequestOperation["PNGenerateUploadUrlOperation"] = "PNGenerateUploadUrlOperation"; + /** + * Upload file to the channel REST API operation. + */ RequestOperation["PNPublishFileOperation"] = "PNPublishFileOperation"; + /** + * Publish File Message to the channel REST API operation. + */ RequestOperation["PNPublishFileMessageOperation"] = "PNPublishFileMessageOperation"; + /** + * Retrieve file download URL REST API operation. + */ RequestOperation["PNGetFileUrlOperation"] = "PNGetFileUrlOperation"; + /** + * Download file from the channel REST API operation. + */ RequestOperation["PNDownloadFileOperation"] = "PNDownloadFileOperation"; + /** + * Delete file sent to the channel REST API operation. + */ RequestOperation["PNDeleteFileOperation"] = "PNDeleteFileOperation"; + // -------------------------------------------------------- + // -------------------- Mobile Push API ------------------- + // -------------------------------------------------------- + /** + * Register channels with device push notifications REST API operation. + */ RequestOperation["PNAddPushNotificationEnabledChannelsOperation"] = "PNAddPushNotificationEnabledChannelsOperation"; + /** + * Unregister channels with device push notifications REST API operation. + */ RequestOperation["PNRemovePushNotificationEnabledChannelsOperation"] = "PNRemovePushNotificationEnabledChannelsOperation"; + /** + * Fetch list of channels with enabled push notifications for device REST API operation. + */ RequestOperation["PNPushNotificationEnabledChannelsOperation"] = "PNPushNotificationEnabledChannelsOperation"; + /** + * Disable push notifications for device REST API operation. + */ RequestOperation["PNRemoveAllPushNotificationsOperation"] = "PNRemoveAllPushNotificationsOperation"; + // -------------------------------------------------------- + // ------------------ Channel Groups API ------------------ + // -------------------------------------------------------- + /** + * Fetch channels groups list REST API operation. + */ RequestOperation["PNChannelGroupsOperation"] = "PNChannelGroupsOperation"; + /** + * Remove specified channel group REST API operation. + */ RequestOperation["PNRemoveGroupOperation"] = "PNRemoveGroupOperation"; + /** + * Fetch list of channels for the specified channel group REST API operation. + */ RequestOperation["PNChannelsForGroupOperation"] = "PNChannelsForGroupOperation"; + /** + * Add list of channels to the specified channel group REST API operation. + */ RequestOperation["PNAddChannelsToGroupOperation"] = "PNAddChannelsToGroupOperation"; + /** + * Remove list of channels from the specified channel group REST API operation. + */ RequestOperation["PNRemoveChannelsFromGroupOperation"] = "PNRemoveChannelsFromGroupOperation"; + // -------------------------------------------------------- + // ----------------------- PAM API ------------------------ + // -------------------------------------------------------- + /** + * Generate authorized token REST API operation. + */ RequestOperation["PNAccessManagerGrant"] = "PNAccessManagerGrant"; + /** + * Generate authorized token REST API operation. + */ RequestOperation["PNAccessManagerGrantToken"] = "PNAccessManagerGrantToken"; RequestOperation["PNAccessManagerAudit"] = "PNAccessManagerAudit"; + /** + * Revoke authorized token REST API operation. + */ RequestOperation["PNAccessManagerRevokeToken"] = "PNAccessManagerRevokeToken"; + // + // -------------------------------------------------------- + // ---------------- Subscription Utility ------------------ + // -------------------------------------------------------- RequestOperation["PNHandshakeOperation"] = "PNHandshakeOperation"; RequestOperation["PNReceiveMessagesOperation"] = "PNReceiveMessagesOperation"; })(RequestOperation || (RequestOperation = {})); diff --git a/lib/core/endpoints/access_manager/audit.js b/lib/core/endpoints/access_manager/audit.js index e39aeb6d0..a405e8010 100644 --- a/lib/core/endpoints/access_manager/audit.js +++ b/lib/core/endpoints/access_manager/audit.js @@ -1,4 +1,7 @@ "use strict"; +/** + * PAM Audit REST API module. + */ var __awaiter = (this && this.__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) { @@ -17,13 +20,27 @@ const pubnub_error_1 = require("../../../errors/pubnub-error"); const pubnub_api_error_1 = require("../../../errors/pubnub-api-error"); const request_1 = require("../../components/request"); const operations_1 = __importDefault(require("../../constants/operations")); +// -------------------------------------------------------- +// ----------------------- Defaults ----------------------- +// -------------------------------------------------------- +// region Defaults +/** + * Auth keys for which permissions should be audited. + */ const AUTH_KEYS = []; +// endregion +/** + * Permissions audit request. + * + * @internal + */ class AuditRequest extends request_1.AbstractRequest { constructor(parameters) { var _a; var _b; super(); this.parameters = parameters; + // Apply default request parameters. (_a = (_b = this.parameters).authKeys) !== null && _a !== void 0 ? _a : (_b.authKeys = AUTH_KEYS); } operation() { diff --git a/lib/core/endpoints/access_manager/grant.js b/lib/core/endpoints/access_manager/grant.js index dfb15e873..9ed997fae 100644 --- a/lib/core/endpoints/access_manager/grant.js +++ b/lib/core/endpoints/access_manager/grant.js @@ -1,4 +1,7 @@ "use strict"; +/** + * PAM Grant REST API module. + */ var __awaiter = (this && this.__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) { @@ -17,19 +20,51 @@ const pubnub_error_1 = require("../../../errors/pubnub-error"); const pubnub_api_error_1 = require("../../../errors/pubnub-api-error"); const request_1 = require("../../components/request"); const operations_1 = __importDefault(require("../../constants/operations")); +// -------------------------------------------------------- +// ----------------------- Defaults ----------------------- +// -------------------------------------------------------- +// region Defaults +/** + * Resources `read` permission. + */ const READ_PERMISSION = false; +/** + * Resources `write` permission. + */ const WRITE_PERMISSION = false; +/** + * Resources `delete` permission. + */ const DELETE_PERMISSION = false; +/** + * Resources `get` permission. + */ const GET_PERMISSION = false; +/** + * Resources `update` permission. + */ const UPDATE_PERMISSION = false; +/** + * Resources `manage` permission. + */ const MANAGE_PERMISSION = false; +/** + * Resources `join` permission. + */ const JOIN_PERMISSION = false; +// endregion +/** + * Grant permissions request. + * + * @internal + */ class GrantRequest extends request_1.AbstractRequest { constructor(parameters) { var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k; var _l, _m, _o, _p, _q, _r, _s, _t, _u, _v; super(); this.parameters = parameters; + // Apply defaults. (_a = (_l = this.parameters).channels) !== null && _a !== void 0 ? _a : (_l.channels = []); (_b = (_m = this.parameters).channelGroups) !== null && _b !== void 0 ? _b : (_m.channelGroups = []); (_c = (_o = this.parameters).uuids) !== null && _c !== void 0 ? _c : (_o.uuids = []); diff --git a/lib/core/endpoints/access_manager/grant_token.js b/lib/core/endpoints/access_manager/grant_token.js index 2c420331f..0eb0cc788 100644 --- a/lib/core/endpoints/access_manager/grant_token.js +++ b/lib/core/endpoints/access_manager/grant_token.js @@ -1,4 +1,7 @@ "use strict"; +/** + * PAM Grant Token REST API module. + */ var __awaiter = (this && this.__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) { @@ -18,12 +21,19 @@ const pubnub_api_error_1 = require("../../../errors/pubnub-api-error"); const transport_request_1 = require("../../types/transport-request"); const request_1 = require("../../components/request"); const operations_1 = __importDefault(require("../../constants/operations")); +// endregion +/** + * Grant token permissions request. + * + * @internal + */ class GrantTokenRequest extends request_1.AbstractRequest { constructor(parameters) { var _a, _b; var _c, _d; super({ method: transport_request_1.TransportMethod.POST }); this.parameters = parameters; + // Apply defaults. (_a = (_c = this.parameters).resources) !== null && _a !== void 0 ? _a : (_c.resources = {}); (_b = (_d = this.parameters).patterns) !== null && _b !== void 0 ? _b : (_d.patterns = {}); } @@ -54,6 +64,7 @@ class GrantTokenRequest extends request_1.AbstractRequest { [this.parameters.resources, this.parameters.patterns].forEach((refPerm) => { Object.keys(refPerm !== null && refPerm !== void 0 ? refPerm : {}).forEach((scope) => { var _a; + // @ts-expect-error Permissions with backward compatibility. if (refPerm && permissionsEmpty && Object.keys((_a = refPerm[scope]) !== null && _a !== void 0 ? _a : {}).length > 0) { permissionsEmpty = false; } @@ -103,11 +114,14 @@ class GrantTokenRequest extends request_1.AbstractRequest { target.groups = {}; if (!target.uuids) target.uuids = {}; + // @ts-expect-error Not used, needed for api backward compatibility if (!target.users) target.users = {}; + // @ts-expect-error Not used, needed for api backward compatibility if (!target.spaces) target.spaces = {}; if (refPerm) { + // Check whether working with legacy Objects permissions. if ('spaces' in refPerm || 'users' in refPerm) { channelsPermissions = (_a = refPerm.spaces) !== null && _a !== void 0 ? _a : {}; uuidsPermissions = (_b = refPerm.users) !== null && _b !== void 0 ? _b : {}; @@ -130,6 +144,13 @@ class GrantTokenRequest extends request_1.AbstractRequest { body.permissions = permissions; return JSON.stringify(body); } + /** + * Extract permissions bit from permission configuration object. + * + * @param permissions - User provided scope-based permissions. + * + * @returns Permissions bit. + */ extractPermissions(permissions) { let permissionsResult = 0; if ('join' in permissions && permissions.join) @@ -148,6 +169,13 @@ class GrantTokenRequest extends request_1.AbstractRequest { permissionsResult |= 1; return permissionsResult; } + /** + * Check whether provided parameters is part of legacy VSP access token configuration. + * + * @param parameters - Parameters which should be checked. + * + * @returns VSP request parameters if it is legacy configuration. + */ isVspPermissions(parameters) { var _a, _b, _c, _d; return ('authorizedUserId' in parameters || diff --git a/lib/core/endpoints/access_manager/revoke_token.js b/lib/core/endpoints/access_manager/revoke_token.js index 648136fcc..03b9e4111 100644 --- a/lib/core/endpoints/access_manager/revoke_token.js +++ b/lib/core/endpoints/access_manager/revoke_token.js @@ -1,4 +1,7 @@ "use strict"; +/** + * PAM Revoke Token REST API module. + */ var __awaiter = (this && this.__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) { @@ -19,6 +22,14 @@ const transport_request_1 = require("../../types/transport-request"); const request_1 = require("../../components/request"); const operations_1 = __importDefault(require("../../constants/operations")); const utils_1 = require("../../utils"); +// endregion +/** + * Access token revoke request. + * + * Invalidate token and permissions which has been granted for it. + * + * @internal + */ class RevokeTokenRequest extends request_1.AbstractRequest { constructor(parameters) { super({ method: transport_request_1.TransportMethod.DELETE }); diff --git a/lib/core/endpoints/actions/add_message_action.js b/lib/core/endpoints/actions/add_message_action.js index 6f82bd0d5..a44be3601 100644 --- a/lib/core/endpoints/actions/add_message_action.js +++ b/lib/core/endpoints/actions/add_message_action.js @@ -1,4 +1,7 @@ "use strict"; +/** + * Add Message Action REST API module. + */ var __awaiter = (this && this.__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) { @@ -19,6 +22,12 @@ const transport_request_1 = require("../../types/transport-request"); const request_1 = require("../../components/request"); const operations_1 = __importDefault(require("../../constants/operations")); const utils_1 = require("../../utils"); +// endregion +/** + * Add Message Reaction request. + * + * @internal + */ class AddMessageActionRequest extends request_1.AbstractRequest { constructor(parameters) { super({ method: transport_request_1.TransportMethod.POST }); diff --git a/lib/core/endpoints/actions/get_message_actions.js b/lib/core/endpoints/actions/get_message_actions.js index 3a0ffcd86..caad2356c 100644 --- a/lib/core/endpoints/actions/get_message_actions.js +++ b/lib/core/endpoints/actions/get_message_actions.js @@ -1,4 +1,7 @@ "use strict"; +/** + * Get Message Actions REST API module. + */ var __awaiter = (this && this.__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) { @@ -18,6 +21,12 @@ const pubnub_api_error_1 = require("../../../errors/pubnub-api-error"); const request_1 = require("../../components/request"); const operations_1 = __importDefault(require("../../constants/operations")); const utils_1 = require("../../utils"); +// endregion +/** + * Fetch channel message actions request. + * + * @internal + */ class GetMessageActionsRequest extends request_1.AbstractRequest { constructor(parameters) { super(); diff --git a/lib/core/endpoints/actions/remove_message_action.js b/lib/core/endpoints/actions/remove_message_action.js index 95d0a1969..9d3c94661 100644 --- a/lib/core/endpoints/actions/remove_message_action.js +++ b/lib/core/endpoints/actions/remove_message_action.js @@ -1,4 +1,7 @@ "use strict"; +/** + * Remove Message Action REST API module. + */ var __awaiter = (this && this.__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) { @@ -19,6 +22,12 @@ const transport_request_1 = require("../../types/transport-request"); const request_1 = require("../../components/request"); const operations_1 = __importDefault(require("../../constants/operations")); const utils_1 = require("../../utils"); +// endregion +/** + * Remove specific message action request. + * + * @internal + */ class RemoveMessageAction extends request_1.AbstractRequest { constructor(parameters) { super({ method: transport_request_1.TransportMethod.DELETE }); diff --git a/lib/core/endpoints/channel_groups/add_channels.js b/lib/core/endpoints/channel_groups/add_channels.js index aa4720f56..32eedf351 100644 --- a/lib/core/endpoints/channel_groups/add_channels.js +++ b/lib/core/endpoints/channel_groups/add_channels.js @@ -1,4 +1,7 @@ "use strict"; +/** + * Add channel group channels REST API module. + */ var __awaiter = (this && this.__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) { @@ -18,6 +21,12 @@ const pubnub_api_error_1 = require("../../../errors/pubnub-api-error"); const request_1 = require("../../components/request"); const operations_1 = __importDefault(require("../../constants/operations")); const utils_1 = require("../../utils"); +// endregion +/** + * Add channel group channels request. + * + * @internal + */ class AddChannelGroupChannelsRequest extends request_1.AbstractRequest { constructor(parameters) { super(); diff --git a/lib/core/endpoints/channel_groups/delete_group.js b/lib/core/endpoints/channel_groups/delete_group.js index e1def77fa..618024148 100644 --- a/lib/core/endpoints/channel_groups/delete_group.js +++ b/lib/core/endpoints/channel_groups/delete_group.js @@ -1,4 +1,7 @@ "use strict"; +/** + * Delete channel group REST API module. + */ var __awaiter = (this && this.__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) { @@ -18,6 +21,12 @@ const pubnub_api_error_1 = require("../../../errors/pubnub-api-error"); const request_1 = require("../../components/request"); const operations_1 = __importDefault(require("../../constants/operations")); const utils_1 = require("../../utils"); +// endregion +/** + * Channel group delete request. + * + * @internal + */ class DeleteChannelGroupRequest extends request_1.AbstractRequest { constructor(parameters) { super(); diff --git a/lib/core/endpoints/channel_groups/list_channels.js b/lib/core/endpoints/channel_groups/list_channels.js index 247359860..83101c9e9 100644 --- a/lib/core/endpoints/channel_groups/list_channels.js +++ b/lib/core/endpoints/channel_groups/list_channels.js @@ -1,4 +1,7 @@ "use strict"; +/** + * List channel group channels REST API module. + */ var __awaiter = (this && this.__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) { @@ -18,6 +21,12 @@ const pubnub_api_error_1 = require("../../../errors/pubnub-api-error"); const request_1 = require("../../components/request"); const operations_1 = __importDefault(require("../../constants/operations")); const utils_1 = require("../../utils"); +// endregion +/** + * List Channel Group Channels request. + * + * @internal + */ class ListChannelGroupChannels extends request_1.AbstractRequest { constructor(parameters) { super(); diff --git a/lib/core/endpoints/channel_groups/list_groups.js b/lib/core/endpoints/channel_groups/list_groups.js index 6e8b8b6b1..06deb4a01 100644 --- a/lib/core/endpoints/channel_groups/list_groups.js +++ b/lib/core/endpoints/channel_groups/list_groups.js @@ -1,4 +1,7 @@ "use strict"; +/** + * List All Channel Groups REST API module. + */ var __awaiter = (this && this.__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) { @@ -17,6 +20,12 @@ const pubnub_error_1 = require("../../../errors/pubnub-error"); const pubnub_api_error_1 = require("../../../errors/pubnub-api-error"); const request_1 = require("../../components/request"); const operations_1 = __importDefault(require("../../constants/operations")); +// endregion +/** + * List all channel groups request. + * + * @internal + */ class ListChannelGroupsRequest extends request_1.AbstractRequest { constructor(parameters) { super(); diff --git a/lib/core/endpoints/channel_groups/remove_channels.js b/lib/core/endpoints/channel_groups/remove_channels.js index cca35a99f..2afed498b 100644 --- a/lib/core/endpoints/channel_groups/remove_channels.js +++ b/lib/core/endpoints/channel_groups/remove_channels.js @@ -1,4 +1,7 @@ "use strict"; +/** + * Remove channel group channels REST API module. + */ var __awaiter = (this && this.__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) { @@ -18,6 +21,13 @@ const pubnub_api_error_1 = require("../../../errors/pubnub-api-error"); const request_1 = require("../../components/request"); const operations_1 = __importDefault(require("../../constants/operations")); const utils_1 = require("../../utils"); +// endregion +/** + * Remove channel group channels request. + * + * @internal + */ +// prettier-ignore class RemoveChannelGroupChannelsRequest extends request_1.AbstractRequest { constructor(parameters) { super(); diff --git a/lib/core/endpoints/fetch_messages.js b/lib/core/endpoints/fetch_messages.js index f3935c84e..dd94e6824 100644 --- a/lib/core/endpoints/fetch_messages.js +++ b/lib/core/endpoints/fetch_messages.js @@ -1,4 +1,7 @@ "use strict"; +/** + * Fetch messages REST API module. + */ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { if (k2 === undefined) k2 = k; var desc = Object.getOwnPropertyDescriptor(m, k); @@ -42,17 +45,47 @@ const request_1 = require("../components/request"); const operations_1 = __importDefault(require("../constants/operations")); const History = __importStar(require("../types/api/history")); const utils_1 = require("../utils"); +// -------------------------------------------------------- +// ---------------------- Defaults ------------------------ +// -------------------------------------------------------- +// region Defaults +/** + * Whether verbose logging enabled or not. + */ const LOG_VERBOSITY = false; +/** + * Whether message type should be returned or not. + */ const INCLUDE_MESSAGE_TYPE = true; +/** + * Whether timetokens should be returned as strings by default or not. + */ const STRINGIFY_TIMETOKENS = false; +/** + * Whether message publisher `uuid` should be returned or not. + */ const INCLUDE_UUID = true; +/** + * Default number of messages which can be returned for single channel, and it is maximum as well. + */ const SINGLE_CHANNEL_MESSAGES_COUNT = 100; +/** + * Default number of messages which can be returned for multiple channels or when fetched + * message actions. + */ const MULTIPLE_CHANNELS_MESSAGES_COUNT = 25; +// endregion +/** + * Fetch messages from channels request. + * + * @internal + */ class FetchMessagesRequest extends request_1.AbstractRequest { constructor(parameters) { var _a, _b, _c, _d, _e; super(); this.parameters = parameters; + // Apply defaults. const includeMessageActions = (_a = parameters.includeMessageActions) !== null && _a !== void 0 ? _a : false; const defaultCount = parameters.channels.length > 1 || includeMessageActions ? MULTIPLE_CHANNELS_MESSAGES_COUNT @@ -94,7 +127,9 @@ class FetchMessagesRequest extends request_1.AbstractRequest { const responseChannels = (_a = serviceResponse.channels) !== null && _a !== void 0 ? _a : {}; const channels = {}; Object.keys(responseChannels).forEach((channel) => { + // Map service response to expected data object type structure. channels[channel] = responseChannels[channel].map((payload) => { + // `null` message type means regular message. if (payload.message_type === null) payload.message_type = History.PubNubMessageType.Message; const processedPayload = this.processPayload(channel, payload); @@ -108,6 +143,8 @@ class FetchMessagesRequest extends request_1.AbstractRequest { if (payload.actions) { const itemWithActions = item; itemWithActions.actions = payload.actions; + // Backward compatibility for existing users. + // TODO: Remove in next release. itemWithActions.data = payload.actions; } if (payload.meta) @@ -131,6 +168,14 @@ class FetchMessagesRequest extends request_1.AbstractRequest { const { start, end, count, includeMessageType, includeMeta, includeUUID, stringifiedTimeToken } = this.parameters; return Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({ max: count }, (start ? { start } : {})), (end ? { end } : {})), (stringifiedTimeToken ? { string_message_token: 'true' } : {})), (includeMeta !== undefined && includeMeta ? { include_meta: 'true' } : {})), (includeUUID ? { include_uuid: 'true' } : {})), (includeMessageType ? { include_message_type: 'true' } : {})); } + /** + * Parse single channel data entry. + * + * @param channel - Channel for which {@link payload} should be processed. + * @param payload - Source payload which should be processed and parsed to expected type. + * + * @returns + */ processPayload(channel, payload) { const { crypto, logVerbosity } = this.parameters; if (!crypto || typeof payload.message !== 'string') @@ -166,6 +211,13 @@ class FetchMessagesRequest extends request_1.AbstractRequest { } return { payload: decryptedPayload, error }; } + /** + * Check whether `payload` potentially represents file message. + * + * @param payload - Fetched message payload. + * + * @returns `true` if payload can be {@link History#FileMessage|FileMessage}. + */ isFileMessage(payload) { return payload.file !== undefined; } diff --git a/lib/core/endpoints/file_upload/delete_file.js b/lib/core/endpoints/file_upload/delete_file.js index 00f0a40b5..0721e6f0a 100644 --- a/lib/core/endpoints/file_upload/delete_file.js +++ b/lib/core/endpoints/file_upload/delete_file.js @@ -1,4 +1,7 @@ "use strict"; +/** + * Delete file REST API module. + */ var __awaiter = (this && this.__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) { @@ -19,6 +22,12 @@ const transport_request_1 = require("../../types/transport-request"); const request_1 = require("../../components/request"); const operations_1 = __importDefault(require("../../constants/operations")); const utils_1 = require("../../utils"); +// endregion +/** + * Delete File request. + * + * @internal + */ class DeleteFileRequest extends request_1.AbstractRequest { constructor(parameters) { super({ method: transport_request_1.TransportMethod.DELETE }); diff --git a/lib/core/endpoints/file_upload/download_file.js b/lib/core/endpoints/file_upload/download_file.js index a5d6fae93..fb99ccc31 100644 --- a/lib/core/endpoints/file_upload/download_file.js +++ b/lib/core/endpoints/file_upload/download_file.js @@ -1,4 +1,7 @@ "use strict"; +/** + * Download File REST API module. + */ var __awaiter = (this && this.__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) { @@ -16,6 +19,12 @@ exports.DownloadFileRequest = void 0; const request_1 = require("../../components/request"); const operations_1 = __importDefault(require("../../constants/operations")); const utils_1 = require("../../utils"); +// endregion +/** + * Download File request. + * + * @internal + */ class DownloadFileRequest extends request_1.AbstractRequest { constructor(parameters) { super(); diff --git a/lib/core/endpoints/file_upload/generate_upload_url.js b/lib/core/endpoints/file_upload/generate_upload_url.js index 4f89bc5c5..9a107a47d 100644 --- a/lib/core/endpoints/file_upload/generate_upload_url.js +++ b/lib/core/endpoints/file_upload/generate_upload_url.js @@ -1,4 +1,7 @@ "use strict"; +/** + * Generate file upload URL REST API request. + */ var __awaiter = (this && this.__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) { @@ -19,6 +22,12 @@ const transport_request_1 = require("../../types/transport-request"); const request_1 = require("../../components/request"); const operations_1 = __importDefault(require("../../constants/operations")); const utils_1 = require("../../utils"); +// endregion +/** + * Generate File Upload Url request. + * + * @internal + */ class GenerateFileUploadUrlRequest extends request_1.AbstractRequest { constructor(parameters) { super({ method: transport_request_1.TransportMethod.POST }); diff --git a/lib/core/endpoints/file_upload/get_file_url.js b/lib/core/endpoints/file_upload/get_file_url.js index 91879738f..5a17b3ab1 100644 --- a/lib/core/endpoints/file_upload/get_file_url.js +++ b/lib/core/endpoints/file_upload/get_file_url.js @@ -1,4 +1,7 @@ "use strict"; +/** + * File sharing REST API module. + */ var __awaiter = (this && this.__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) { @@ -17,7 +20,20 @@ const transport_request_1 = require("../../types/transport-request"); const request_1 = require("../../components/request"); const operations_1 = __importDefault(require("../../constants/operations")); const utils_1 = require("../../utils"); +// endregion +/** + * File download Url generation request. + * + * Local request which generates Url to download shared file from the specific channel. + * + * @internal + */ class GetFileDownloadUrlRequest extends request_1.AbstractRequest { + /** + * Construct file download Url generation request. + * + * @param parameters - Request configuration. + */ constructor(parameters) { super({ method: transport_request_1.TransportMethod.LOCAL }); this.parameters = parameters; diff --git a/lib/core/endpoints/file_upload/list_files.js b/lib/core/endpoints/file_upload/list_files.js index f258331b8..513fe6525 100644 --- a/lib/core/endpoints/file_upload/list_files.js +++ b/lib/core/endpoints/file_upload/list_files.js @@ -1,4 +1,7 @@ "use strict"; +/** + * List Files REST API module. + */ var __awaiter = (this && this.__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) { @@ -18,13 +21,27 @@ const pubnub_api_error_1 = require("../../../errors/pubnub-api-error"); const request_1 = require("../../components/request"); const operations_1 = __importDefault(require("../../constants/operations")); const utils_1 = require("../../utils"); +// -------------------------------------------------------- +// ----------------------- Defaults ----------------------- +// -------------------------------------------------------- +// region Defaults +/** + * Number of files to return in response. + */ const LIMIT = 100; +// endregion +/** + * Files List request. + * + * @internal + */ class FilesListRequest extends request_1.AbstractRequest { constructor(parameters) { var _a; var _b; super(); this.parameters = parameters; + // Apply default request parameters. (_a = (_b = this.parameters).limit) !== null && _a !== void 0 ? _a : (_b.limit = LIMIT); } operation() { diff --git a/lib/core/endpoints/file_upload/publish_file.js b/lib/core/endpoints/file_upload/publish_file.js index f69228964..20c6d4c63 100644 --- a/lib/core/endpoints/file_upload/publish_file.js +++ b/lib/core/endpoints/file_upload/publish_file.js @@ -1,4 +1,7 @@ "use strict"; +/** + * Publish File Message REST API module. + */ var __awaiter = (this && this.__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) { @@ -18,13 +21,27 @@ const request_1 = require("../../components/request"); const operations_1 = __importDefault(require("../../constants/operations")); const base64_codec_1 = require("../../components/base64_codec"); const utils_1 = require("../../utils"); +// -------------------------------------------------------- +// ----------------------- Defaults ----------------------- +// -------------------------------------------------------- +// region Defaults +/** + * Whether published file messages should be stored in the channel's history. + */ const STORE_IN_HISTORY = true; +// endregion +/** + * Publish shared file information request. + * + * @internal + */ class PublishFileMessageRequest extends request_1.AbstractRequest { constructor(parameters) { var _a; var _b; super(); this.parameters = parameters; + // Apply default request parameters. (_a = (_b = this.parameters).storeInHistory) !== null && _a !== void 0 ? _a : (_b.storeInHistory = STORE_IN_HISTORY); } operation() { @@ -59,6 +76,17 @@ class PublishFileMessageRequest extends request_1.AbstractRequest { const { storeInHistory, ttl, meta } = this.parameters; return Object.assign(Object.assign({ store: storeInHistory ? '1' : '0' }, (ttl ? { ttl } : {})), (meta && typeof meta === 'object' ? { meta: JSON.stringify(meta) } : {})); } + /** + * Pre-process provided data. + * + * Data will be "normalized" and encrypted if `cryptoModule` has been provided. + * + * @param payload - User-provided data which should be pre-processed before use. + * + * @returns Payload which can be used as part of request URL or body. + * + * @throws {Error} in case if provided `payload` or results of `encryption` can't be stringified. + */ prepareMessagePayload(payload) { const { crypto } = this.parameters; if (!crypto) diff --git a/lib/core/endpoints/file_upload/send_file.js b/lib/core/endpoints/file_upload/send_file.js index ca036ee19..5041464d5 100644 --- a/lib/core/endpoints/file_upload/send_file.js +++ b/lib/core/endpoints/file_upload/send_file.js @@ -19,6 +19,12 @@ const operations_1 = __importDefault(require("../../constants/operations")); const upload_file_1 = require("./upload-file"); const pubnub_api_error_1 = require("../../../errors/pubnub-api-error"); const categories_1 = __importDefault(require("../../constants/categories")); +// endregion +/** + * Send file composed request. + * + * @internal + */ class SendFileRequest { constructor(parameters) { var _a; @@ -27,6 +33,11 @@ class SendFileRequest { if (!this.file) throw new Error('File upload error: unable to create File object.'); } + /** + * Process user-input and upload file. + * + * @returns File upload request response. + */ process() { return __awaiter(this, void 0, void 0, function* () { let fileName; @@ -57,16 +68,29 @@ class SendFileRequest { }); }); } + /** + * Generate pre-signed file upload Url. + * + * @returns File upload credentials. + */ generateFileUploadUrl() { return __awaiter(this, void 0, void 0, function* () { const request = new generate_upload_url_1.GenerateFileUploadUrlRequest(Object.assign(Object.assign({}, this.parameters), { name: this.file.name, keySet: this.parameters.keySet })); return this.parameters.sendRequest(request); }); } + /** + * Prepare and upload {@link PubNub} File object to remote storage. + * + * @param uploadParameters - File upload request parameters. + * + * @returns + */ uploadFile(uploadParameters) { return __awaiter(this, void 0, void 0, function* () { const { cipherKey, PubNubFile, crypto, cryptography } = this.parameters; const { id, name, url, formFields } = uploadParameters; + // Encrypt file if possible. if (this.parameters.PubNubFile.supportsEncryptFile) { if (!cipherKey && crypto) this.file = (yield crypto.encryptFile(this.file, PubNubFile)); diff --git a/lib/core/endpoints/file_upload/upload-file.js b/lib/core/endpoints/file_upload/upload-file.js index fefdb0f2b..15546c973 100644 --- a/lib/core/endpoints/file_upload/upload-file.js +++ b/lib/core/endpoints/file_upload/upload-file.js @@ -1,4 +1,7 @@ "use strict"; +/** + * Upload file REST API request. + */ var __awaiter = (this && this.__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) { @@ -16,10 +19,16 @@ exports.UploadFileRequest = void 0; const transport_request_1 = require("../../types/transport-request"); const request_1 = require("../../components/request"); const operations_1 = __importDefault(require("../../constants/operations")); +/** + * File Upload request. + * + * @internal + */ class UploadFileRequest extends request_1.AbstractRequest { constructor(parameters) { super({ method: transport_request_1.TransportMethod.POST }); this.parameters = parameters; + // Use file's actual mime type if available. const mimeType = parameters.file.mimeType; if (mimeType) { parameters.formFields = parameters.formFields.map((entry) => { diff --git a/lib/core/endpoints/history/delete_messages.js b/lib/core/endpoints/history/delete_messages.js index 6556ff638..3c4814a80 100644 --- a/lib/core/endpoints/history/delete_messages.js +++ b/lib/core/endpoints/history/delete_messages.js @@ -1,4 +1,7 @@ "use strict"; +/** + * Delete messages REST API module. + */ var __awaiter = (this && this.__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) { @@ -19,6 +22,12 @@ const transport_request_1 = require("../../types/transport-request"); const request_1 = require("../../components/request"); const operations_1 = __importDefault(require("../../constants/operations")); const utils_1 = require("../../utils"); +// endregion +/** + * Delete messages from channel history. + * + * @internal + */ class DeleteMessageRequest extends request_1.AbstractRequest { constructor(parameters) { super({ method: transport_request_1.TransportMethod.DELETE }); diff --git a/lib/core/endpoints/history/get_history.js b/lib/core/endpoints/history/get_history.js index 02691675a..ff6c28dd7 100644 --- a/lib/core/endpoints/history/get_history.js +++ b/lib/core/endpoints/history/get_history.js @@ -1,4 +1,7 @@ "use strict"; +/** + * Get history REST API module. + */ var __awaiter = (this && this.__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) { @@ -17,15 +20,38 @@ const pubnub_error_1 = require("../../../errors/pubnub-error"); const request_1 = require("../../components/request"); const operations_1 = __importDefault(require("../../constants/operations")); const utils_1 = require("../../utils"); +// -------------------------------------------------------- +// ---------------------- Defaults ------------------------ +// -------------------------------------------------------- +// region Defaults +/** + * Whether verbose logging enabled or not. + */ const LOG_VERBOSITY = false; +/** + * Whether associated message metadata should be returned or not. + */ const INCLUDE_METADATA = false; +/** + * Whether timetokens should be returned as strings by default or not. + */ const STRINGIFY_TIMETOKENS = false; +/** + * Default and maximum number of messages which should be returned. + */ const MESSAGES_COUNT = 100; +// endregion +/** + * Get single channel messages request. + * + * @internal + */ class GetHistoryRequest extends request_1.AbstractRequest { constructor(parameters) { var _a, _b, _c; super(); this.parameters = parameters; + // Apply defaults. if (parameters.count) parameters.count = Math.min(parameters.count, MESSAGES_COUNT); else @@ -51,6 +77,7 @@ class GetHistoryRequest extends request_1.AbstractRequest { const messages = serviceResponse[0]; const startTimeToken = serviceResponse[1]; const endTimeToken = serviceResponse[2]; + // Handle malformed get history response. if (!Array.isArray(messages)) return { messages: [], startTimeToken, endTimeToken }; return { diff --git a/lib/core/endpoints/history/message_counts.js b/lib/core/endpoints/history/message_counts.js index 66fb9ec0c..d8641eede 100644 --- a/lib/core/endpoints/history/message_counts.js +++ b/lib/core/endpoints/history/message_counts.js @@ -1,4 +1,7 @@ "use strict"; +/** + * Messages count REST API module. + */ var __awaiter = (this && this.__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) { @@ -18,6 +21,12 @@ const pubnub_api_error_1 = require("../../../errors/pubnub-api-error"); const request_1 = require("../../components/request"); const operations_1 = __importDefault(require("../../constants/operations")); const utils_1 = require("../../utils"); +// endregion +/** + * Count messages request. + * + * @internal + */ class MessageCountRequest extends request_1.AbstractRequest { constructor(parameters) { super(); diff --git a/lib/core/endpoints/objects/channel/get.js b/lib/core/endpoints/objects/channel/get.js index d7c3b86ed..aa5b1830d 100644 --- a/lib/core/endpoints/objects/channel/get.js +++ b/lib/core/endpoints/objects/channel/get.js @@ -1,4 +1,7 @@ "use strict"; +/** + * Get Channel Metadata REST API module. + */ var __awaiter = (this && this.__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) { @@ -18,13 +21,27 @@ const pubnub_api_error_1 = require("../../../../errors/pubnub-api-error"); const request_1 = require("../../../components/request"); const operations_1 = __importDefault(require("../../../constants/operations")); const utils_1 = require("../../../utils"); +// -------------------------------------------------------- +// ----------------------- Defaults ----------------------- +// -------------------------------------------------------- +// region Defaults +/** + * Whether `Channel` custom field should be included by default or not. + */ const INCLUDE_CUSTOM_FIELDS = true; +// endregion +/** + * Get Channel Metadata request. + * + * @internal + */ class GetChannelMetadataRequest extends request_1.AbstractRequest { constructor(parameters) { var _a, _b; var _c; super(); this.parameters = parameters; + // Apply default request parameters. (_a = parameters.include) !== null && _a !== void 0 ? _a : (parameters.include = {}); (_b = (_c = parameters.include).customFields) !== null && _b !== void 0 ? _b : (_c.customFields = INCLUDE_CUSTOM_FIELDS); } diff --git a/lib/core/endpoints/objects/channel/get_all.js b/lib/core/endpoints/objects/channel/get_all.js index 228568d77..3019266fd 100644 --- a/lib/core/endpoints/objects/channel/get_all.js +++ b/lib/core/endpoints/objects/channel/get_all.js @@ -1,4 +1,7 @@ "use strict"; +/** + * Get All Channel Metadata REST API module. + */ var __awaiter = (this && this.__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) { @@ -17,15 +20,35 @@ const pubnub_error_1 = require("../../../../errors/pubnub-error"); const pubnub_api_error_1 = require("../../../../errors/pubnub-api-error"); const request_1 = require("../../../components/request"); const operations_1 = __importDefault(require("../../../constants/operations")); +// -------------------------------------------------------- +// ----------------------- Defaults ----------------------- +// -------------------------------------------------------- +// region Defaults +/** + * Whether `Channel` custom fields should be included in response or not. + */ const INCLUDE_CUSTOM_FIELDS = false; +/** + * Whether total number of channels should be included in response or not. + */ const INCLUDE_TOTAL_COUNT = false; +/** + * Number of objects to return in response. + */ const LIMIT = 100; +// endregion +/** + * Get All Channels Metadata request. + * + * @internal + */ class GetAllChannelsMetadataRequest extends request_1.AbstractRequest { constructor(parameters) { var _a, _b, _c, _d; var _e, _f; super(); this.parameters = parameters; + // Apply default request parameters. (_a = parameters.include) !== null && _a !== void 0 ? _a : (parameters.include = {}); (_b = (_e = parameters.include).customFields) !== null && _b !== void 0 ? _b : (_e.customFields = INCLUDE_CUSTOM_FIELDS); (_c = (_f = parameters.include).totalCount) !== null && _c !== void 0 ? _c : (_f.totalCount = INCLUDE_TOTAL_COUNT); diff --git a/lib/core/endpoints/objects/channel/remove.js b/lib/core/endpoints/objects/channel/remove.js index 725b652ad..2b0db8890 100644 --- a/lib/core/endpoints/objects/channel/remove.js +++ b/lib/core/endpoints/objects/channel/remove.js @@ -1,4 +1,7 @@ "use strict"; +/** + * Remove Channel Metadata REST API module. + */ var __awaiter = (this && this.__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) { @@ -19,6 +22,12 @@ const transport_request_1 = require("../../../types/transport-request"); const request_1 = require("../../../components/request"); const operations_1 = __importDefault(require("../../../constants/operations")); const utils_1 = require("../../../utils"); +// endregion +/** + * Remove Channel Metadata request. + * + * @internal + */ class RemoveChannelMetadataRequest extends request_1.AbstractRequest { constructor(parameters) { super({ method: transport_request_1.TransportMethod.DELETE }); diff --git a/lib/core/endpoints/objects/channel/set.js b/lib/core/endpoints/objects/channel/set.js index 6d903debb..b127ac4c1 100644 --- a/lib/core/endpoints/objects/channel/set.js +++ b/lib/core/endpoints/objects/channel/set.js @@ -1,4 +1,7 @@ "use strict"; +/** + * Set Channel Metadata REST API module. + */ var __awaiter = (this && this.__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) { @@ -19,13 +22,27 @@ const transport_request_1 = require("../../../types/transport-request"); const request_1 = require("../../../components/request"); const operations_1 = __importDefault(require("../../../constants/operations")); const utils_1 = require("../../../utils"); +// -------------------------------------------------------- +// ----------------------- Defaults ----------------------- +// -------------------------------------------------------- +// region Defaults +/** + * Whether `Channel` custom field should be included by default or not. + */ const INCLUDE_CUSTOM_FIELDS = true; +// endregion +/** + * Set Channel Metadata request. + * + * @internal + */ class SetChannelMetadataRequest extends request_1.AbstractRequest { constructor(parameters) { var _a, _b; var _c; super({ method: transport_request_1.TransportMethod.PATCH }); this.parameters = parameters; + // Apply default request parameters. (_a = parameters.include) !== null && _a !== void 0 ? _a : (parameters.include = {}); (_b = (_c = parameters.include).customFields) !== null && _b !== void 0 ? _b : (_c.customFields = INCLUDE_CUSTOM_FIELDS); } diff --git a/lib/core/endpoints/objects/member/get.js b/lib/core/endpoints/objects/member/get.js index 4329df0fc..348855612 100644 --- a/lib/core/endpoints/objects/member/get.js +++ b/lib/core/endpoints/objects/member/get.js @@ -1,4 +1,7 @@ "use strict"; +/** + * Get Channel Members REST API module. + */ var __awaiter = (this && this.__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) { @@ -18,20 +21,55 @@ const pubnub_api_error_1 = require("../../../../errors/pubnub-api-error"); const request_1 = require("../../../components/request"); const operations_1 = __importDefault(require("../../../constants/operations")); const utils_1 = require("../../../utils"); +// -------------------------------------------------------- +// ----------------------- Defaults ----------------------- +// -------------------------------------------------------- +// region Defaults +/** + * Whether `Member` custom field should be included in response or not. + */ const INCLUDE_CUSTOM_FIELDS = false; +/** + * Whether member's status field should be included in response or not. + */ const INCLUDE_STATUS = false; +/** + * Whether total number of members should be included in response or not. + */ const INCLUDE_TOTAL_COUNT = false; +/** + * Whether `UUID` fields should be included in response or not. + */ const INCLUDE_UUID_FIELDS = false; +/** + * Whether `UUID` status field should be included in response or not. + */ const INCLUDE_UUID_STATUS_FIELD = false; +/** + * Whether `UUID` type field should be included in response or not. + */ const INCLUDE_UUID_TYPE_FIELD = false; +/** + * Whether `UUID` custom field should be included in response or not. + */ const INCLUDE_UUID_CUSTOM_FIELDS = false; +/** + * Number of objects to return in response. + */ const LIMIT = 100; +// endregion +/** + * Get Channel Members request. + * + * @internal + */ class GetChannelMembersRequest extends request_1.AbstractRequest { constructor(parameters) { var _a, _b, _c, _d, _e, _f, _g, _h, _j; var _k, _l, _m, _o, _p, _q, _r; super(); this.parameters = parameters; + // Apply default request parameters. (_a = parameters.include) !== null && _a !== void 0 ? _a : (parameters.include = {}); (_b = (_k = parameters.include).customFields) !== null && _b !== void 0 ? _b : (_k.customFields = INCLUDE_CUSTOM_FIELDS); (_c = (_l = parameters.include).totalCount) !== null && _c !== void 0 ? _c : (_l.totalCount = INCLUDE_TOTAL_COUNT); diff --git a/lib/core/endpoints/objects/member/set.js b/lib/core/endpoints/objects/member/set.js index 6d6ba7cb5..344469b01 100644 --- a/lib/core/endpoints/objects/member/set.js +++ b/lib/core/endpoints/objects/member/set.js @@ -1,4 +1,7 @@ "use strict"; +/** + * Set Channel Members REST API module. + */ var __awaiter = (this && this.__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) { @@ -19,17 +22,43 @@ const transport_request_1 = require("../../../types/transport-request"); const request_1 = require("../../../components/request"); const operations_1 = __importDefault(require("../../../constants/operations")); const utils_1 = require("../../../utils"); +// -------------------------------------------------------- +// ----------------------- Defaults ----------------------- +// -------------------------------------------------------- +// region Defaults +/** + * Whether `Member` custom field should be included in response or not. + */ const INCLUDE_CUSTOM_FIELDS = false; +/** + * Whether total number of members should be included in response or not. + */ const INCLUDE_TOTAL_COUNT = false; +/** + * Whether `UUID` fields should be included in response or not. + */ const INCLUDE_UUID_FIELDS = false; +/** + * Whether `UUID` custom field should be included in response or not. + */ const INCLUDE_UUID_CUSTOM_FIELDS = false; +/** + * Number of objects to return in response. + */ const LIMIT = 100; +// endregion +/** + * Set Channel Members request. + * + * @internal + */ class SetChannelMembersRequest extends request_1.AbstractRequest { constructor(parameters) { var _a, _b, _c, _d, _e, _f; var _g, _h, _j, _k; super({ method: transport_request_1.TransportMethod.PATCH }); this.parameters = parameters; + // Apply default request parameters. (_a = parameters.include) !== null && _a !== void 0 ? _a : (parameters.include = {}); (_b = (_g = parameters.include).customFields) !== null && _b !== void 0 ? _b : (_g.customFields = INCLUDE_CUSTOM_FIELDS); (_c = (_h = parameters.include).totalCount) !== null && _c !== void 0 ? _c : (_h.totalCount = INCLUDE_TOTAL_COUNT); diff --git a/lib/core/endpoints/objects/membership/get.js b/lib/core/endpoints/objects/membership/get.js index bc588f76c..7444536f2 100644 --- a/lib/core/endpoints/objects/membership/get.js +++ b/lib/core/endpoints/objects/membership/get.js @@ -1,4 +1,7 @@ "use strict"; +/** + * Get UUID Memberships REST API module. + */ var __awaiter = (this && this.__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) { @@ -18,20 +21,55 @@ const pubnub_api_error_1 = require("../../../../errors/pubnub-api-error"); const request_1 = require("../../../components/request"); const operations_1 = __importDefault(require("../../../constants/operations")); const utils_1 = require("../../../utils"); +// -------------------------------------------------------- +// ----------------------- Defaults ----------------------- +// -------------------------------------------------------- +// region Defaults +/** + * Whether `Membership` custom field should be included in response or not. + */ const INCLUDE_CUSTOM_FIELDS = false; +/** + * Whether membership's status field should be included in response or not. + */ const INCLUDE_STATUS = false; +/** + * Whether total number of memberships should be included in response or not. + */ const INCLUDE_TOTAL_COUNT = false; +/** + * Whether `Channel` fields should be included in response or not. + */ const INCLUDE_CHANNEL_FIELDS = false; +/** + * Whether `Channel` status field should be included in response or not. + */ const INCLUDE_CHANNEL_STATUS_FIELD = false; +/** + * Whether `Channel` type field should be included in response or not. + */ const INCLUDE_CHANNEL_TYPE_FIELD = false; +/** + * Whether `Channel` custom field should be included in response or not. + */ const INCLUDE_CHANNEL_CUSTOM_FIELDS = false; +/** + * Number of objects to return in response. + */ const LIMIT = 100; +// endregion +/** + * Get UUID Memberships request. + * + * @internal + */ class GetUUIDMembershipsRequest extends request_1.AbstractRequest { constructor(parameters) { var _a, _b, _c, _d, _e, _f, _g, _h, _j; var _k, _l, _m, _o, _p, _q, _r; super(); this.parameters = parameters; + // Apply default request parameters. (_a = parameters.include) !== null && _a !== void 0 ? _a : (parameters.include = {}); (_b = (_k = parameters.include).customFields) !== null && _b !== void 0 ? _b : (_k.customFields = INCLUDE_CUSTOM_FIELDS); (_c = (_l = parameters.include).totalCount) !== null && _c !== void 0 ? _c : (_l.totalCount = INCLUDE_TOTAL_COUNT); @@ -41,6 +79,7 @@ class GetUUIDMembershipsRequest extends request_1.AbstractRequest { (_g = (_q = parameters.include).channelStatusField) !== null && _g !== void 0 ? _g : (_q.channelStatusField = INCLUDE_CHANNEL_STATUS_FIELD); (_h = (_r = parameters.include).channelTypeField) !== null && _h !== void 0 ? _h : (_r.channelTypeField = INCLUDE_CHANNEL_TYPE_FIELD); (_j = parameters.limit) !== null && _j !== void 0 ? _j : (parameters.limit = LIMIT); + // Remap for backward compatibility. if (this.parameters.userId) this.parameters.uuid = this.parameters.userId; } diff --git a/lib/core/endpoints/objects/membership/set.js b/lib/core/endpoints/objects/membership/set.js index 10aaa32e3..9ed9fcabe 100644 --- a/lib/core/endpoints/objects/membership/set.js +++ b/lib/core/endpoints/objects/membership/set.js @@ -1,4 +1,7 @@ "use strict"; +/** + * Set UUID Memberships REST API module. + */ var __awaiter = (this && this.__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) { @@ -19,23 +22,50 @@ const transport_request_1 = require("../../../types/transport-request"); const request_1 = require("../../../components/request"); const operations_1 = __importDefault(require("../../../constants/operations")); const utils_1 = require("../../../utils"); +// -------------------------------------------------------- +// ----------------------- Defaults ----------------------- +// -------------------------------------------------------- +// region Defaults +/** + * Whether `Membership` custom field should be included in response or not. + */ const INCLUDE_CUSTOM_FIELDS = false; +/** + * Whether total number of memberships should be included in response or not. + */ const INCLUDE_TOTAL_COUNT = false; +/** + * Whether `Channel` fields should be included in response or not. + */ const INCLUDE_CHANNEL_FIELDS = false; +/** + * Whether `Channel` custom field should be included in response or not. + */ const INCLUDE_CHANNEL_CUSTOM_FIELDS = false; +/** + * Number of objects to return in response. + */ const LIMIT = 100; +// endregion +/** + * Set UUID Memberships request. + * + * @internal + */ class SetUUIDMembershipsRequest extends request_1.AbstractRequest { constructor(parameters) { var _a, _b, _c, _d, _e, _f; var _g, _h, _j, _k; super({ method: transport_request_1.TransportMethod.PATCH }); this.parameters = parameters; + // Apply default request parameters. (_a = parameters.include) !== null && _a !== void 0 ? _a : (parameters.include = {}); (_b = (_g = parameters.include).customFields) !== null && _b !== void 0 ? _b : (_g.customFields = INCLUDE_CUSTOM_FIELDS); (_c = (_h = parameters.include).totalCount) !== null && _c !== void 0 ? _c : (_h.totalCount = INCLUDE_TOTAL_COUNT); (_d = (_j = parameters.include).channelFields) !== null && _d !== void 0 ? _d : (_j.channelFields = INCLUDE_CHANNEL_FIELDS); (_e = (_k = parameters.include).customChannelFields) !== null && _e !== void 0 ? _e : (_k.customChannelFields = INCLUDE_CHANNEL_CUSTOM_FIELDS); (_f = parameters.limit) !== null && _f !== void 0 ? _f : (parameters.limit = LIMIT); + // Remap for backward compatibility. if (this.parameters.userId) this.parameters.uuid = this.parameters.userId; } diff --git a/lib/core/endpoints/objects/uuid/get.js b/lib/core/endpoints/objects/uuid/get.js index 56383f4dd..b0f5135c8 100644 --- a/lib/core/endpoints/objects/uuid/get.js +++ b/lib/core/endpoints/objects/uuid/get.js @@ -1,4 +1,7 @@ "use strict"; +/** + * Get UUID Metadata REST API module. + */ var __awaiter = (this && this.__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) { @@ -18,15 +21,30 @@ const pubnub_api_error_1 = require("../../../../errors/pubnub-api-error"); const request_1 = require("../../../components/request"); const operations_1 = __importDefault(require("../../../constants/operations")); const utils_1 = require("../../../utils"); +// -------------------------------------------------------- +// ----------------------- Defaults ----------------------- +// -------------------------------------------------------- +// region Defaults +/** + * Whether UUID custom field should be included by default or not. + */ const INCLUDE_CUSTOM_FIELDS = true; +// endregion +/** + * Get UUID Metadata request. + * + * @internal + */ class GetUUIDMetadataRequest extends request_1.AbstractRequest { constructor(parameters) { var _a, _b; var _c; super(); this.parameters = parameters; + // Apply default request parameters. (_a = parameters.include) !== null && _a !== void 0 ? _a : (parameters.include = {}); (_b = (_c = parameters.include).customFields) !== null && _b !== void 0 ? _b : (_c.customFields = INCLUDE_CUSTOM_FIELDS); + // Remap for backward compatibility. if (this.parameters.userId) this.parameters.uuid = this.parameters.userId; } diff --git a/lib/core/endpoints/objects/uuid/get_all.js b/lib/core/endpoints/objects/uuid/get_all.js index eae9bce3b..778084b0f 100644 --- a/lib/core/endpoints/objects/uuid/get_all.js +++ b/lib/core/endpoints/objects/uuid/get_all.js @@ -1,4 +1,7 @@ "use strict"; +/** + * Get All UUID Metadata REST API module. + */ var __awaiter = (this && this.__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) { @@ -17,14 +20,31 @@ const pubnub_error_1 = require("../../../../errors/pubnub-error"); const pubnub_api_error_1 = require("../../../../errors/pubnub-api-error"); const request_1 = require("../../../components/request"); const operations_1 = __importDefault(require("../../../constants/operations")); +// -------------------------------------------------------- +// ----------------------- Defaults ----------------------- +// -------------------------------------------------------- +// region Defaults +/** + * Whether `Channel` custom field should be included by default or not. + */ const INCLUDE_CUSTOM_FIELDS = false; +/** + * Number of objects to return in response. + */ const LIMIT = 100; +// endregion +/** + * Get All UUIDs Metadata request. + * + * @internal + */ class GetAllUUIDMetadataRequest extends request_1.AbstractRequest { constructor(parameters) { var _a, _b, _c; var _d; super(); this.parameters = parameters; + // Apply default request parameters. (_a = parameters.include) !== null && _a !== void 0 ? _a : (parameters.include = {}); (_b = (_d = parameters.include).customFields) !== null && _b !== void 0 ? _b : (_d.customFields = INCLUDE_CUSTOM_FIELDS); (_c = parameters.limit) !== null && _c !== void 0 ? _c : (parameters.limit = LIMIT); diff --git a/lib/core/endpoints/objects/uuid/remove.js b/lib/core/endpoints/objects/uuid/remove.js index 9268a7792..09025de72 100644 --- a/lib/core/endpoints/objects/uuid/remove.js +++ b/lib/core/endpoints/objects/uuid/remove.js @@ -1,4 +1,7 @@ "use strict"; +/** + * Remove UUID Metadata REST API module. + */ var __awaiter = (this && this.__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) { @@ -19,10 +22,17 @@ const transport_request_1 = require("../../../types/transport-request"); const request_1 = require("../../../components/request"); const operations_1 = __importDefault(require("../../../constants/operations")); const utils_1 = require("../../../utils"); +// endregion +/** + * Remove UUID Metadata request. + * + * @internal + */ class RemoveUUIDMetadataRequest extends request_1.AbstractRequest { constructor(parameters) { super({ method: transport_request_1.TransportMethod.DELETE }); this.parameters = parameters; + // Remap for backward compatibility. if (this.parameters.userId) this.parameters.uuid = this.parameters.userId; } diff --git a/lib/core/endpoints/objects/uuid/set.js b/lib/core/endpoints/objects/uuid/set.js index 075c97b74..cdc3252e0 100644 --- a/lib/core/endpoints/objects/uuid/set.js +++ b/lib/core/endpoints/objects/uuid/set.js @@ -1,4 +1,7 @@ "use strict"; +/** + * Set UUID Metadata REST API module. + */ var __awaiter = (this && this.__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) { @@ -19,15 +22,30 @@ const transport_request_1 = require("../../../types/transport-request"); const request_1 = require("../../../components/request"); const operations_1 = __importDefault(require("../../../constants/operations")); const utils_1 = require("../../../utils"); +// -------------------------------------------------------- +// ----------------------- Defaults ----------------------- +// -------------------------------------------------------- +// region Defaults +/** + * Whether `Channel` custom field should be included by default or not. + */ const INCLUDE_CUSTOM_FIELDS = true; +// endregion +/** + * Set UUID Metadata request. + * + * @internal + */ class SetUUIDMetadataRequest extends request_1.AbstractRequest { constructor(parameters) { var _a, _b; var _c; super({ method: transport_request_1.TransportMethod.PATCH }); this.parameters = parameters; + // Apply default request parameters. (_a = parameters.include) !== null && _a !== void 0 ? _a : (parameters.include = {}); (_b = (_c = parameters.include).customFields) !== null && _b !== void 0 ? _b : (_c.customFields = INCLUDE_CUSTOM_FIELDS); + // Remap for backward compatibility. if (this.parameters.userId) this.parameters.uuid = this.parameters.userId; } diff --git a/lib/core/endpoints/presence/get_state.js b/lib/core/endpoints/presence/get_state.js index 8373628e2..76f447c62 100644 --- a/lib/core/endpoints/presence/get_state.js +++ b/lib/core/endpoints/presence/get_state.js @@ -1,4 +1,7 @@ "use strict"; +/** + * Get Presence State REST API module. + */ var __awaiter = (this && this.__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) { @@ -18,12 +21,19 @@ const pubnub_api_error_1 = require("../../../errors/pubnub-api-error"); const request_1 = require("../../components/request"); const operations_1 = __importDefault(require("../../constants/operations")); const utils_1 = require("../../utils"); +// endregion +/** + * Get `uuid` presence state request. + * + * @internal + */ class GetPresenceStateRequest extends request_1.AbstractRequest { constructor(parameters) { var _a, _b; var _c, _d; super(); this.parameters = parameters; + // Apply defaults. (_a = (_c = this.parameters).channels) !== null && _a !== void 0 ? _a : (_c.channels = []); (_b = (_d = this.parameters).channelGroups) !== null && _b !== void 0 ? _b : (_d.channelGroups = []); } diff --git a/lib/core/endpoints/presence/heartbeat.js b/lib/core/endpoints/presence/heartbeat.js index 52de83f8e..d5925a85c 100644 --- a/lib/core/endpoints/presence/heartbeat.js +++ b/lib/core/endpoints/presence/heartbeat.js @@ -1,4 +1,7 @@ "use strict"; +/** + * Announce heartbeat REST API module. + */ var __awaiter = (this && this.__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) { @@ -18,6 +21,12 @@ const pubnub_api_error_1 = require("../../../errors/pubnub-api-error"); const request_1 = require("../../components/request"); const operations_1 = __importDefault(require("../../constants/operations")); const utils_1 = require("../../utils"); +// endregion +/** + * Announce `uuid` presence request. + * + * @internal + */ class HeartbeatRequest extends request_1.AbstractRequest { constructor(parameters) { super(); diff --git a/lib/core/endpoints/presence/here_now.js b/lib/core/endpoints/presence/here_now.js index 6900d5929..fd8319701 100644 --- a/lib/core/endpoints/presence/here_now.js +++ b/lib/core/endpoints/presence/here_now.js @@ -1,4 +1,7 @@ "use strict"; +/** + * Channels / channel groups presence REST API module. + */ var __awaiter = (this && this.__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) { @@ -18,14 +21,31 @@ const pubnub_api_error_1 = require("../../../errors/pubnub-api-error"); const request_1 = require("../../components/request"); const operations_1 = __importDefault(require("../../constants/operations")); const utils_1 = require("../../utils"); +// -------------------------------------------------------- +// ----------------------- Defaults ----------------------- +// -------------------------------------------------------- +// region Defaults +/** + * Whether `uuid` should be included in response or not. + */ const INCLUDE_UUID = true; +/** + * Whether state associated with `uuid` should be included in response or not. + */ const INCLUDE_STATE = false; +// endregion +/** + * Channel presence request. + * + * @internal + */ class HereNowRequest extends request_1.AbstractRequest { constructor(parameters) { var _a, _b, _c; var _d, _e, _f; super(); this.parameters = parameters; + // Apply defaults. (_a = (_d = this.parameters).queryParameters) !== null && _a !== void 0 ? _a : (_d.queryParameters = {}); (_b = (_e = this.parameters).includeUUIDs) !== null && _b !== void 0 ? _b : (_e.includeUUIDs = INCLUDE_UUID); (_c = (_f = this.parameters).includeState) !== null && _c !== void 0 ? _c : (_f.includeState = INCLUDE_STATE); @@ -49,10 +69,12 @@ class HereNowRequest extends request_1.AbstractRequest { } else if (serviceResponse.status >= 400) throw pubnub_api_error_1.PubNubAPIError.create(response); + // Extract general presence information. const totalChannels = 'occupancy' in serviceResponse ? 1 : serviceResponse.payload.total_channels; const totalOccupancy = 'occupancy' in serviceResponse ? serviceResponse.occupancy : serviceResponse.payload.total_channels; const channelsPresence = {}; let channels = {}; + // Remap single channel presence to multiple channels presence response. if ('occupancy' in serviceResponse) { const channel = this.parameters.channels[0]; channels[channel] = { uuids: (_a = serviceResponse.uuids) !== null && _a !== void 0 ? _a : [], occupancy: totalOccupancy }; diff --git a/lib/core/endpoints/presence/leave.js b/lib/core/endpoints/presence/leave.js index ec29564ba..fd06272b6 100644 --- a/lib/core/endpoints/presence/leave.js +++ b/lib/core/endpoints/presence/leave.js @@ -1,4 +1,7 @@ "use strict"; +/** + * Announce leave REST API module. + */ var __awaiter = (this && this.__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) { @@ -18,6 +21,12 @@ const pubnub_api_error_1 = require("../../../errors/pubnub-api-error"); const request_1 = require("../../components/request"); const operations_1 = __importDefault(require("../../constants/operations")); const utils_1 = require("../../utils"); +// endregion +/** + * Announce user leave request. + * + * @internal + */ class PresenceLeaveRequest extends request_1.AbstractRequest { constructor(parameters) { super(); diff --git a/lib/core/endpoints/presence/set_state.js b/lib/core/endpoints/presence/set_state.js index 8ecfd935d..faba64205 100644 --- a/lib/core/endpoints/presence/set_state.js +++ b/lib/core/endpoints/presence/set_state.js @@ -1,4 +1,7 @@ "use strict"; +/** + * Set Presence State REST API module. + */ var __awaiter = (this && this.__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) { @@ -18,6 +21,12 @@ const pubnub_api_error_1 = require("../../../errors/pubnub-api-error"); const request_1 = require("../../components/request"); const operations_1 = __importDefault(require("../../constants/operations")); const utils_1 = require("../../utils"); +// endregion +/** + * Set `uuid` presence state request. + * + * @internal + */ class SetPresenceStateRequest extends request_1.AbstractRequest { constructor(parameters) { super(); diff --git a/lib/core/endpoints/presence/where_now.js b/lib/core/endpoints/presence/where_now.js index a536e143b..daa44632f 100644 --- a/lib/core/endpoints/presence/where_now.js +++ b/lib/core/endpoints/presence/where_now.js @@ -1,4 +1,7 @@ "use strict"; +/** + * `uuid` presence REST API module. + */ var __awaiter = (this && this.__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) { @@ -18,6 +21,12 @@ const pubnub_api_error_1 = require("../../../errors/pubnub-api-error"); const request_1 = require("../../components/request"); const operations_1 = __importDefault(require("../../constants/operations")); const utils_1 = require("../../utils"); +// endregion +/** + * Get `uuid` presence request. + * + * @internal + */ class WhereNowRequest extends request_1.AbstractRequest { constructor(parameters) { super(); diff --git a/lib/core/endpoints/publish.js b/lib/core/endpoints/publish.js index cd5d55ffb..1a38b0aa9 100644 --- a/lib/core/endpoints/publish.js +++ b/lib/core/endpoints/publish.js @@ -1,4 +1,7 @@ "use strict"; +/** + * Publish REST API module. + */ var __awaiter = (this && this.__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) { @@ -19,13 +22,35 @@ const request_1 = require("../components/request"); const operations_1 = __importDefault(require("../constants/operations")); const base64_codec_1 = require("../components/base64_codec"); const utils_1 = require("../utils"); +// -------------------------------------------------------- +// ----------------------- Defaults ----------------------- +// -------------------------------------------------------- +// region Defaults +/** + * Whether data is published used `POST` body or not. + */ const SEND_BY_POST = false; +// endregion +/** + * Data publish request. + * + * Request will normalize and encrypt (if required) provided data and push it to the specified + * channel. + * + * @internal + */ class PublishRequest extends request_1.AbstractRequest { + /** + * Construct data publish request. + * + * @param parameters - Request configuration. + */ constructor(parameters) { var _a; var _b; super({ method: parameters.sendByPost ? transport_request_1.TransportMethod.POST : transport_request_1.TransportMethod.GET }); this.parameters = parameters; + // Apply default request parameters. (_a = (_b = this.parameters).sendByPost) !== null && _a !== void 0 ? _a : (_b.sendByPost = SEND_BY_POST); } operation() { @@ -72,6 +97,17 @@ class PublishRequest extends request_1.AbstractRequest { get body() { return this.prepareMessagePayload(this.parameters.message); } + /** + * Pre-process provided data. + * + * Data will be "normalized" and encrypted if `cryptoModule` has been provided. + * + * @param payload - User-provided data which should be pre-processed before use. + * + * @returns Payload which can be used as part of request URL or body. + * + * @throws {Error} in case if provided `payload` or results of `encryption` can't be stringified. + */ prepareMessagePayload(payload) { const { crypto } = this.parameters; if (!crypto) diff --git a/lib/core/endpoints/push/add_push_channels.js b/lib/core/endpoints/push/add_push_channels.js index 7e6ca21d2..9cc2257b0 100644 --- a/lib/core/endpoints/push/add_push_channels.js +++ b/lib/core/endpoints/push/add_push_channels.js @@ -1,4 +1,7 @@ "use strict"; +/** + * Register Channels with Device push REST API module. + */ var __awaiter = (this && this.__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) { @@ -16,6 +19,13 @@ exports.AddDevicePushNotificationChannelsRequest = void 0; const pubnub_error_1 = require("../../../errors/pubnub-error"); const push_1 = require("./push"); const operations_1 = __importDefault(require("../../constants/operations")); +// endregion +/** + * Register channels with device push request. + * + * @internal + */ +// prettier-ignore class AddDevicePushNotificationChannelsRequest extends push_1.BasePushNotificationChannelsRequest { constructor(parameters) { super(Object.assign(Object.assign({}, parameters), { action: 'add' })); diff --git a/lib/core/endpoints/push/list_push_channels.js b/lib/core/endpoints/push/list_push_channels.js index 355026b81..0f55b55c2 100644 --- a/lib/core/endpoints/push/list_push_channels.js +++ b/lib/core/endpoints/push/list_push_channels.js @@ -1,4 +1,7 @@ "use strict"; +/** + * List Device push enabled channels REST API module. + */ var __awaiter = (this && this.__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) { @@ -16,6 +19,13 @@ exports.ListDevicePushNotificationChannelsRequest = void 0; const pubnub_error_1 = require("../../../errors/pubnub-error"); const push_1 = require("./push"); const operations_1 = __importDefault(require("../../constants/operations")); +// endregion +/** + * List device push enabled channels request. + * + * @internal + */ +// prettier-ignore class ListDevicePushNotificationChannelsRequest extends push_1.BasePushNotificationChannelsRequest { constructor(parameters) { super(Object.assign(Object.assign({}, parameters), { action: 'list' })); diff --git a/lib/core/endpoints/push/push.js b/lib/core/endpoints/push/push.js index 82c63aab4..5bd84beff 100644 --- a/lib/core/endpoints/push/push.js +++ b/lib/core/endpoints/push/push.js @@ -1,4 +1,7 @@ "use strict"; +/** + * Manage channels enabled for device push REST API module. + */ var __awaiter = (this && this.__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) { @@ -11,14 +14,31 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge Object.defineProperty(exports, "__esModule", { value: true }); exports.BasePushNotificationChannelsRequest = void 0; const request_1 = require("../../components/request"); +// -------------------------------------------------------- +// ----------------------- Defaults ----------------------- +// -------------------------------------------------------- +// region Defaults +/** + * Environment for which APNS2 notifications + */ const ENVIRONMENT = 'development'; +/** + * Maximum number of channels in `list` response. + */ const MAX_COUNT = 1000; +// endregion +/** + * Base push notification request. + * + * @internal + */ class BasePushNotificationChannelsRequest extends request_1.AbstractRequest { constructor(parameters) { var _a; var _b; super(); this.parameters = parameters; + // Apply request defaults if (this.parameters.pushGateway === 'apns2') (_a = (_b = this.parameters).environment) !== null && _a !== void 0 ? _a : (_b.environment = ENVIRONMENT); if (this.parameters.count && this.parameters.count > MAX_COUNT) diff --git a/lib/core/endpoints/push/remove_device.js b/lib/core/endpoints/push/remove_device.js index 4e71bc5ce..d3857c1fa 100644 --- a/lib/core/endpoints/push/remove_device.js +++ b/lib/core/endpoints/push/remove_device.js @@ -1,4 +1,7 @@ "use strict"; +/** + * Unregister Device push REST API module. + */ var __awaiter = (this && this.__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) { @@ -16,6 +19,13 @@ exports.RemoveDevicePushNotificationRequest = void 0; const pubnub_error_1 = require("../../../errors/pubnub-error"); const push_1 = require("./push"); const operations_1 = __importDefault(require("../../constants/operations")); +// endregion +/** + * Unregister device push notifications request. + * + * @internal + */ +// prettier-ignore class RemoveDevicePushNotificationRequest extends push_1.BasePushNotificationChannelsRequest { constructor(parameters) { super(Object.assign(Object.assign({}, parameters), { action: 'remove-device' })); diff --git a/lib/core/endpoints/push/remove_push_channels.js b/lib/core/endpoints/push/remove_push_channels.js index 96d179ae7..7243bd2bd 100644 --- a/lib/core/endpoints/push/remove_push_channels.js +++ b/lib/core/endpoints/push/remove_push_channels.js @@ -1,4 +1,7 @@ "use strict"; +/** + * Unregister Channels from Device push REST API module. + */ var __awaiter = (this && this.__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) { @@ -16,6 +19,13 @@ exports.RemoveDevicePushNotificationChannelsRequest = void 0; const pubnub_error_1 = require("../../../errors/pubnub-error"); const push_1 = require("./push"); const operations_1 = __importDefault(require("../../constants/operations")); +// endregion +/** + * Unregister channels from device push request. + * + * @internal + */ +// prettier-ignore class RemoveDevicePushNotificationChannelsRequest extends push_1.BasePushNotificationChannelsRequest { constructor(parameters) { super(Object.assign(Object.assign({}, parameters), { action: 'remove' })); diff --git a/lib/core/endpoints/signal.js b/lib/core/endpoints/signal.js index ad60cb35e..e3e5ea344 100644 --- a/lib/core/endpoints/signal.js +++ b/lib/core/endpoints/signal.js @@ -1,4 +1,7 @@ "use strict"; +/** + * Signal REST API module. + */ var __awaiter = (this && this.__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) { @@ -17,6 +20,12 @@ const pubnub_error_1 = require("../../errors/pubnub-error"); const request_1 = require("../components/request"); const operations_1 = __importDefault(require("../constants/operations")); const utils_1 = require("../utils"); +// endregion +/** + * Signal data (size-limited) publish request. + * + * @internal + */ class SignalRequest extends request_1.AbstractRequest { constructor(parameters) { super(); diff --git a/lib/core/endpoints/subscribe.js b/lib/core/endpoints/subscribe.js index 2588611e4..846186b5f 100644 --- a/lib/core/endpoints/subscribe.js +++ b/lib/core/endpoints/subscribe.js @@ -1,4 +1,7 @@ "use strict"; +/** + * Subscription REST API module. + */ var __awaiter = (this && this.__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) { @@ -17,22 +20,70 @@ const pubnub_error_1 = require("../../errors/pubnub-error"); const request_1 = require("../components/request"); const operations_1 = __importDefault(require("../constants/operations")); const utils_1 = require("../utils"); +// -------------------------------------------------------- +// ---------------------- Defaults ------------------------ +// -------------------------------------------------------- +// region Defaults +/** + * Whether should subscribe to channels / groups presence announcements or not. + */ const WITH_PRESENCE = false; +// endregion +// -------------------------------------------------------- +// ------------------------ Types ------------------------- +// -------------------------------------------------------- +// region Types +/** + * PubNub-defined event types by payload. + * + * @internal + */ var PubNubEventType; (function (PubNubEventType) { + /** + * Presence change event. + */ PubNubEventType[PubNubEventType["Presence"] = -2] = "Presence"; + /** + * Regular message event. + * + * **Note:** This is default type assigned for non-presence events if `e` field is missing. + */ PubNubEventType[PubNubEventType["Message"] = -1] = "Message"; + /** + * Signal data event. + */ PubNubEventType[PubNubEventType["Signal"] = 1] = "Signal"; + /** + * App Context object event. + */ PubNubEventType[PubNubEventType["AppContext"] = 2] = "AppContext"; + /** + * Message reaction event. + */ PubNubEventType[PubNubEventType["MessageAction"] = 3] = "MessageAction"; + /** + * Files event. + */ PubNubEventType[PubNubEventType["Files"] = 4] = "Files"; })(PubNubEventType || (exports.PubNubEventType = PubNubEventType = {})); +// endregion +/** + * Base subscription request implementation. + * + * Subscription request used in small variations in two cases: + * - subscription manager + * - event engine + * + * @internal + */ class BaseSubscribeRequest extends request_1.AbstractRequest { constructor(parameters) { var _a, _b, _c; var _d, _e, _f; super({ cancellable: true }); this.parameters = parameters; + // Apply default request parameters. (_a = (_d = this.parameters).withPresence) !== null && _a !== void 0 ? _a : (_d.withPresence = WITH_PRESENCE); (_b = (_e = this.parameters).channelGroups) !== null && _b !== void 0 ? _b : (_e.channelGroups = []); (_c = (_f = this.parameters).channels) !== null && _c !== void 0 ? _c : (_f.channels = []); @@ -63,7 +114,9 @@ class BaseSubscribeRequest extends request_1.AbstractRequest { } const events = serviceResponse.m.map((envelope) => { let { e: eventType } = envelope; + // Resolve missing event type. eventType !== null && eventType !== void 0 ? eventType : (eventType = envelope.c.endsWith('-pnpres') ? PubNubEventType.Presence : PubNubEventType.Message); + // Check whether payload is string (potentially encrypted data). if (typeof envelope.d === 'string') { if (eventType == PubNubEventType.Message) { return { @@ -120,13 +173,20 @@ class BaseSubscribeRequest extends request_1.AbstractRequest { get headers() { return { accept: 'text/javascript' }; } + // -------------------------------------------------------- + // ------------------ Envelope parsing -------------------- + // -------------------------------------------------------- + // region Envelope parsing presenceEventFromEnvelope(envelope) { const { d: payload } = envelope; const [channel, subscription] = this.subscriptionChannelFromEnvelope(envelope); + // Clean up channel and subscription name from presence suffix. const trimmedChannel = channel.replace('-pnpres', ''); + // Backward compatibility with deprecated properties. const actualChannel = subscription !== null ? trimmedChannel : null; const subscribedChannel = subscription !== null ? subscription : trimmedChannel; if (typeof payload !== 'string' && 'data' in payload) { + // @ts-expect-error This is `state-change` object which should have `state` field. payload['state'] = payload.data; delete payload.data; } @@ -137,8 +197,10 @@ class BaseSubscribeRequest extends request_1.AbstractRequest { messageFromEnvelope(envelope) { const [channel, subscription] = this.subscriptionChannelFromEnvelope(envelope); const [message, decryptionError] = this.decryptedData(envelope.d); + // Backward compatibility with deprecated properties. const actualChannel = subscription !== null ? channel : null; const subscribedChannel = subscription !== null ? subscription : channel; + // Basic message event payload. const event = { channel, subscription, @@ -193,6 +255,7 @@ class BaseSubscribeRequest extends request_1.AbstractRequest { const [channel, subscription] = this.subscriptionChannelFromEnvelope(envelope); const [file, decryptionError] = this.decryptedData(envelope.d); let errorMessage = decryptionError; + // Basic file event payload. const event = { channel, subscription, @@ -219,9 +282,17 @@ class BaseSubscribeRequest extends request_1.AbstractRequest { event.error = errorMessage; return event; } + // endregion subscriptionChannelFromEnvelope(envelope) { return [envelope.c, envelope.b === undefined ? envelope.c : envelope.b]; } + /** + * Decrypt provided `data`. + * + * @param [data] - Message or file information which should be decrypted if possible. + * + * @returns Tuple with decrypted data and decryption error (if any). + */ decryptedData(data) { if (!this.parameters.crypto || typeof data !== 'string') return [data, undefined]; @@ -242,6 +313,11 @@ class BaseSubscribeRequest extends request_1.AbstractRequest { } } exports.BaseSubscribeRequest = BaseSubscribeRequest; +/** + * Subscribe request. + * + * @internal + */ class SubscribeRequest extends BaseSubscribeRequest { get path() { var _a; diff --git a/lib/core/endpoints/subscriptionUtils/handshake.js b/lib/core/endpoints/subscriptionUtils/handshake.js index 36e175b4d..fc13544b4 100644 --- a/lib/core/endpoints/subscriptionUtils/handshake.js +++ b/lib/core/endpoints/subscriptionUtils/handshake.js @@ -1,4 +1,7 @@ "use strict"; +/** + * Handshake subscribe REST API module. + */ var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; @@ -7,6 +10,13 @@ exports.HandshakeSubscribeRequest = void 0; const operations_1 = __importDefault(require("../../constants/operations")); const subscribe_1 = require("../subscribe"); const utils_1 = require("../../utils"); +/** + * Handshake subscribe request. + * + * Separate subscribe request required by Event Engine. + * + * @internal + */ class HandshakeSubscribeRequest extends subscribe_1.BaseSubscribeRequest { operation() { return operations_1.default.PNHandshakeOperation; diff --git a/lib/core/endpoints/subscriptionUtils/receiveMessages.js b/lib/core/endpoints/subscriptionUtils/receiveMessages.js index c78a73f84..f597d82fd 100644 --- a/lib/core/endpoints/subscriptionUtils/receiveMessages.js +++ b/lib/core/endpoints/subscriptionUtils/receiveMessages.js @@ -1,4 +1,7 @@ "use strict"; +/** + * Receive messages subscribe REST API module. + */ var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; @@ -7,6 +10,11 @@ exports.ReceiveMessagesSubscribeRequest = void 0; const operations_1 = __importDefault(require("../../constants/operations")); const subscribe_1 = require("../subscribe"); const utils_1 = require("../../utils"); +/** + * Receive messages subscribe request. + * + * @internal + */ class ReceiveMessagesSubscribeRequest extends subscribe_1.BaseSubscribeRequest { operation() { return operations_1.default.PNReceiveMessagesOperation; diff --git a/lib/core/endpoints/time.js b/lib/core/endpoints/time.js index a09d61681..ce2e5a3a6 100644 --- a/lib/core/endpoints/time.js +++ b/lib/core/endpoints/time.js @@ -1,4 +1,7 @@ "use strict"; +/** + * Time REST API module. + */ var __awaiter = (this && this.__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) { @@ -16,6 +19,12 @@ exports.TimeRequest = void 0; const pubnub_error_1 = require("../../errors/pubnub-error"); const request_1 = require("../components/request"); const operations_1 = __importDefault(require("../constants/operations")); +// endregion +/** + * Get current PubNub high-precision time request. + * + * @internal + */ class TimeRequest extends request_1.AbstractRequest { constructor() { super(); diff --git a/lib/core/interfaces/configuration.js b/lib/core/interfaces/configuration.js index bd776878e..170f986bc 100644 --- a/lib/core/interfaces/configuration.js +++ b/lib/core/interfaces/configuration.js @@ -1,28 +1,101 @@ "use strict"; +/** + * {@link PubNub} client configuration module. + */ Object.defineProperty(exports, "__esModule", { value: true }); exports.setDefaults = void 0; const pubnub_error_1 = require("../../errors/pubnub-error"); +// -------------------------------------------------------- +// ----------------------- Defaults ----------------------- +// -------------------------------------------------------- +// region Defaults +/** + * Whether secured connection should be used by or not. + */ const USE_SSL = true; +/** + * Whether PubNub client should catch up subscription after network issues. + */ const RESTORE = false; +/** + * Whether network availability change should be announced with `PNNetworkDownCategory` and + * `PNNetworkUpCategory` state or not. + */ const AUTO_NETWORK_DETECTION = false; +/** + * Whether messages should be de-duplicated before announcement or not. + */ const DEDUPE_ON_SUBSCRIBE = false; +/** + * Maximum cache which should be used for message de-duplication functionality. + */ const DEDUPE_CACHE_SIZE = 100; +/** + * Maximum number of file message publish retries. + */ const FILE_PUBLISH_RETRY_LIMIT = 5; +/** + * Whether subscription event engine should be used or not. + */ const ENABLE_EVENT_ENGINE = false; +/** + * Whether configured user presence state should be maintained by the PubNub client or not. + */ const MAINTAIN_PRESENCE_STATE = true; +/** + * Whether PubNub client should try to utilize existing TCP connection for new requests or not. + */ const KEEP_ALIVE = false; +/** + * Whether verbose logging should be enabled or not. + */ const USE_VERBOSE_LOGGING = false; +/** + * Whether leave events should be suppressed or not. + */ const SUPPRESS_LEAVE_EVENTS = false; +/** + * Whether heartbeat request failure should be announced or not. + */ const ANNOUNCE_HEARTBEAT_FAILURE = true; +/** + * Whether heartbeat request success should be announced or not. + */ const ANNOUNCE_HEARTBEAT_SUCCESS = false; +/** + * Whether PubNub client instance id should be added to the requests or not. + */ const USE_INSTANCE_ID = false; +/** + * Whether unique identifier should be added to the request or not. + */ const USE_REQUEST_ID = true; +/** + * Transactional requests timeout. + */ const TRANSACTIONAL_REQUEST_TIMEOUT = 15; +/** + * Subscription request timeout. + */ const SUBSCRIBE_REQUEST_TIMEOUT = 310; +/** + * Default user presence timeout. + */ const PRESENCE_TIMEOUT = 300; +/** + * Minimum user presence timeout. + */ const PRESENCE_TIMEOUT_MINIMUM = 20; +/** + * Apply configuration default values. + * + * @param configuration - User-provided configuration. + * + * @internal + */ const setDefaults = (configuration) => { var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p, _q; + // Copy configuration. const configurationCopy = Object.assign({}, configuration); (_a = configurationCopy.logVerbosity) !== null && _a !== void 0 ? _a : (configurationCopy.logVerbosity = USE_VERBOSE_LOGGING); (_b = configurationCopy.ssl) !== null && _b !== void 0 ? _b : (configurationCopy.ssl = USE_SSL); @@ -43,6 +116,7 @@ const setDefaults = (configuration) => { throw new pubnub_error_1.PubNubError("PubNub client configuration error: 'userId' not set"); else if (((_p = configurationCopy.userId) === null || _p === void 0 ? void 0 : _p.trim().length) === 0) throw new pubnub_error_1.PubNubError("PubNub client configuration error: 'userId' is empty"); + // Generate default origin subdomains. if (!configurationCopy.origin) configurationCopy.origin = Array.from({ length: 20 }, (_, i) => `ps${i + 1}.pndsn.com`); const keySet = { @@ -52,31 +126,49 @@ const setDefaults = (configuration) => { }; if (configurationCopy.presenceTimeout !== undefined && configurationCopy.presenceTimeout < PRESENCE_TIMEOUT_MINIMUM) { configurationCopy.presenceTimeout = PRESENCE_TIMEOUT_MINIMUM; + // eslint-disable-next-line no-console console.log('WARNING: Presence timeout is less than the minimum. Using minimum value: ', PRESENCE_TIMEOUT_MINIMUM); } (_q = configurationCopy.presenceTimeout) !== null && _q !== void 0 ? _q : (configurationCopy.presenceTimeout = PRESENCE_TIMEOUT); + // Apply extended configuration defaults. let announceSuccessfulHeartbeats = ANNOUNCE_HEARTBEAT_SUCCESS; let announceFailedHeartbeats = ANNOUNCE_HEARTBEAT_FAILURE; let fileUploadPublishRetryLimit = FILE_PUBLISH_RETRY_LIMIT; let dedupeOnSubscribe = DEDUPE_ON_SUBSCRIBE; const maximumCacheSize = DEDUPE_CACHE_SIZE; let useRequestId = USE_REQUEST_ID; + // @ts-expect-error Not documented legacy configuration options. if (configurationCopy.dedupeOnSubscribe !== undefined && typeof configurationCopy.dedupeOnSubscribe === 'boolean') { + // @ts-expect-error Not documented legacy configuration options. dedupeOnSubscribe = configurationCopy.dedupeOnSubscribe; } + // @ts-expect-error Not documented legacy configuration options. if (configurationCopy.useRequestId !== undefined && typeof configurationCopy.useRequestId === 'boolean') { + // @ts-expect-error Not documented legacy configuration options. useRequestId = configurationCopy.useRequestId; } - if (configurationCopy.announceSuccessfulHeartbeats !== undefined && + if ( + // @ts-expect-error Not documented legacy configuration options. + configurationCopy.announceSuccessfulHeartbeats !== undefined && + // @ts-expect-error Not documented legacy configuration options. typeof configurationCopy.announceSuccessfulHeartbeats === 'boolean') { + // @ts-expect-error Not documented legacy configuration options. announceSuccessfulHeartbeats = configurationCopy.announceSuccessfulHeartbeats; } - if (configurationCopy.announceFailedHeartbeats !== undefined && + if ( + // @ts-expect-error Not documented legacy configuration options. + configurationCopy.announceFailedHeartbeats !== undefined && + // @ts-expect-error Not documented legacy configuration options. typeof configurationCopy.announceFailedHeartbeats === 'boolean') { + // @ts-expect-error Not documented legacy configuration options. announceFailedHeartbeats = configurationCopy.announceFailedHeartbeats; } - if (configurationCopy.fileUploadPublishRetryLimit !== undefined && + if ( + // @ts-expect-error Not documented legacy configuration options. + configurationCopy.fileUploadPublishRetryLimit !== undefined && + // @ts-expect-error Not documented legacy configuration options. typeof configurationCopy.fileUploadPublishRetryLimit === 'number') { + // @ts-expect-error Not documented legacy configuration options. fileUploadPublishRetryLimit = configurationCopy.fileUploadPublishRetryLimit; } return Object.assign(Object.assign({}, configurationCopy), { keySet, diff --git a/lib/core/interfaces/crypto-module.js b/lib/core/interfaces/crypto-module.js index 72ba0823b..d5efe74f4 100644 --- a/lib/core/interfaces/crypto-module.js +++ b/lib/core/interfaces/crypto-module.js @@ -1,22 +1,64 @@ "use strict"; +/** + * Crypto module. + */ Object.defineProperty(exports, "__esModule", { value: true }); exports.AbstractCryptoModule = void 0; class AbstractCryptoModule { + // -------------------------------------------------------- + // --------------- Convenience functions ------------------ + // -------------------------------------------------------- + // region Convenience functions + /** + * Construct crypto module with legacy cryptor for encryption and both legacy and AES-CBC + * cryptors for decryption. + * + * @param config Cryptors configuration options. + * + * @returns Crypto module which encrypts data using legacy cryptor. + * + * @throws Error if `config.cipherKey` not set. + */ static legacyCryptoModule(config) { throw new Error('Should be implemented by concrete crypto module implementation.'); } + /** + * Construct crypto module with AES-CBC cryptor for encryption and both AES-CBC and legacy + * cryptors for decryption. + * + * @param config Cryptors configuration options. + * + * @returns Crypto module which encrypts data using AES-CBC cryptor. + * + * @throws Error if `config.cipherKey` not set. + */ static aesCbcCryptoModule(config) { throw new Error('Should be implemented by concrete crypto module implementation.'); } + // endregion constructor(configuration) { var _a; this.defaultCryptor = configuration.default; this.cryptors = (_a = configuration.cryptors) !== null && _a !== void 0 ? _a : []; } + // endregion + // -------------------------------------------------------- + // ----------------------- Helpers ------------------------ + // -------------------------------------------------------- + // region Helpers + /** + * Retrieve list of module's cryptors. + */ getAllCryptors() { return [this.defaultCryptor, ...this.cryptors]; } } exports.AbstractCryptoModule = AbstractCryptoModule; +/** + * `String` to {@link ArrayBuffer} response decoder. + */ AbstractCryptoModule.encoder = new TextEncoder(); +/** + * {@link ArrayBuffer} to {@link string} decoder. + */ AbstractCryptoModule.decoder = new TextDecoder(); diff --git a/lib/core/interfaces/cryptography.js b/lib/core/interfaces/cryptography.js index c8ad2e549..23aacc798 100644 --- a/lib/core/interfaces/cryptography.js +++ b/lib/core/interfaces/cryptography.js @@ -1,2 +1,5 @@ "use strict"; +/** + * Legacy Cryptography module interface. + */ Object.defineProperty(exports, "__esModule", { value: true }); diff --git a/lib/core/pubnub-channel-groups.js b/lib/core/pubnub-channel-groups.js index fbab5c9b9..6a15691a5 100644 --- a/lib/core/pubnub-channel-groups.js +++ b/lib/core/pubnub-channel-groups.js @@ -1,4 +1,7 @@ "use strict"; +/** + * PubNub Channel Groups API module. + */ var __awaiter = (this && this.__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) { @@ -15,10 +18,21 @@ const list_channels_1 = require("./endpoints/channel_groups/list_channels"); const delete_group_1 = require("./endpoints/channel_groups/delete_group"); const list_groups_1 = require("./endpoints/channel_groups/list_groups"); class PubnubChannelGroups { - constructor(keySet, sendRequest) { + constructor(keySet, + /* eslint-disable @typescript-eslint/no-explicit-any */ + sendRequest) { this.keySet = keySet; this.sendRequest = sendRequest; } + /** + * Fetch channel group channels. + * + * @param parameters - Request configuration parameters. + * @param [callback] - Request completion handler callback. + * + * @returns Asynchronous get channel group channels response or `void` in case if `callback` + * provided. + */ listChannels(parameters, callback) { return __awaiter(this, void 0, void 0, function* () { const request = new list_channels_1.ListChannelGroupChannels(Object.assign(Object.assign({}, parameters), { keySet: this.keySet })); @@ -27,6 +41,15 @@ class PubnubChannelGroups { return this.sendRequest(request); }); } + /** + * Fetch all channel groups. + * + * @param [callback] - Request completion handler callback. + * + * @returns Asynchronous get all channel groups response or `void` in case if `callback` provided. + * + * @deprecated + */ listGroups(callback) { return __awaiter(this, void 0, void 0, function* () { const request = new list_groups_1.ListChannelGroupsRequest({ keySet: this.keySet }); @@ -35,6 +58,15 @@ class PubnubChannelGroups { return this.sendRequest(request); }); } + /** + * Add channels to the channel group. + * + * @param parameters - Request configuration parameters. + * @param [callback] - Request completion handler callback. + * + * @returns Asynchronous add channels to the channel group response or `void` in case if + * `callback` provided. + */ addChannels(parameters, callback) { return __awaiter(this, void 0, void 0, function* () { const request = new add_channels_1.AddChannelGroupChannelsRequest(Object.assign(Object.assign({}, parameters), { keySet: this.keySet })); @@ -43,6 +75,15 @@ class PubnubChannelGroups { return this.sendRequest(request); }); } + /** + * Remove channels from the channel group. + * + * @param parameters - Request configuration parameters. + * @param [callback] - Request completion handler callback. + * + * @returns Asynchronous remove channels from the channel group response or `void` in + * case if `callback` provided. + */ removeChannels(parameters, callback) { return __awaiter(this, void 0, void 0, function* () { const request = new remove_channels_1.RemoveChannelGroupChannelsRequest(Object.assign(Object.assign({}, parameters), { keySet: this.keySet })); @@ -51,6 +92,14 @@ class PubnubChannelGroups { return this.sendRequest(request); }); } + /** + * Remove channel group. + * + * @param parameters - Request configuration parameters. + * @param [callback] - Request completion handler callback. + * + * @returns Asynchronous remove channel group response or `void` in case if `callback` provided. + */ deleteGroup(parameters, callback) { return __awaiter(this, void 0, void 0, function* () { const request = new delete_group_1.DeleteChannelGroupRequest(Object.assign(Object.assign({}, parameters), { keySet: this.keySet })); diff --git a/lib/core/pubnub-common.js b/lib/core/pubnub-common.js index e0eed71e2..ae929ffc9 100644 --- a/lib/core/pubnub-common.js +++ b/lib/core/pubnub-common.js @@ -36,42 +36,62 @@ var __importDefault = (this && this.__importDefault) || function (mod) { }; Object.defineProperty(exports, "__esModule", { value: true }); exports.PubNubCore = void 0; +// region Imports +// region Components const listener_manager_1 = require("./components/listener_manager"); const subscription_manager_1 = require("./components/subscription-manager"); const push_payload_1 = __importDefault(require("./components/push_payload")); const eventEmitter_1 = __importDefault(require("./components/eventEmitter")); const base64_codec_1 = require("./components/base64_codec"); const uuid_1 = __importDefault(require("./components/uuid")); +// endregion +// region Constants const operations_1 = __importDefault(require("./constants/operations")); const categories_1 = __importDefault(require("./constants/categories")); +// endregion const pubnub_error_1 = require("../errors/pubnub-error"); const pubnub_api_error_1 = require("../errors/pubnub-api-error"); +// region Event Engine const presence_1 = require("../event-engine/presence/presence"); const retryPolicy_1 = require("../event-engine/core/retryPolicy"); const event_engine_1 = require("../event-engine"); +// endregion +// region Publish & Signal const Publish = __importStar(require("./endpoints/publish")); const Signal = __importStar(require("./endpoints/signal")); +// endregion +// region Subscription const subscribe_1 = require("./endpoints/subscribe"); const receiveMessages_1 = require("./endpoints/subscriptionUtils/receiveMessages"); const handshake_1 = require("./endpoints/subscriptionUtils/handshake"); +// endregion +// region Presence const get_state_1 = require("./endpoints/presence/get_state"); const set_state_1 = require("./endpoints/presence/set_state"); const heartbeat_1 = require("./endpoints/presence/heartbeat"); const leave_1 = require("./endpoints/presence/leave"); const where_now_1 = require("./endpoints/presence/where_now"); const here_now_1 = require("./endpoints/presence/here_now"); +// endregion +// region Message Storage const delete_messages_1 = require("./endpoints/history/delete_messages"); const message_counts_1 = require("./endpoints/history/message_counts"); const get_history_1 = require("./endpoints/history/get_history"); const fetch_messages_1 = require("./endpoints/fetch_messages"); +// endregion +// region Message Actions const get_message_actions_1 = require("./endpoints/actions/get_message_actions"); const add_message_action_1 = require("./endpoints/actions/add_message_action"); const remove_message_action_1 = require("./endpoints/actions/remove_message_action"); +// endregion +// region File sharing const publish_file_1 = require("./endpoints/file_upload/publish_file"); const get_file_url_1 = require("./endpoints/file_upload/get_file_url"); const delete_file_1 = require("./endpoints/file_upload/delete_file"); const list_files_1 = require("./endpoints/file_upload/list_files"); const send_file_1 = require("./endpoints/file_upload/send_file"); +// endregion +// region PubNub Access Manager const revoke_token_1 = require("./endpoints/access_manager/revoke_token"); const grant_token_1 = require("./endpoints/access_manager/grant_token"); const grant_1 = require("./endpoints/access_manager/grant"); @@ -81,28 +101,55 @@ const SubscriptionSet_1 = require("../entities/SubscriptionSet"); const ChannelGroup_1 = require("../entities/ChannelGroup"); const UserMetadata_1 = require("../entities/UserMetadata"); const Channel_1 = require("../entities/Channel"); +// endregion +// region Channel Groups const pubnub_channel_groups_1 = __importDefault(require("./pubnub-channel-groups")); +// endregion +// region Push Notifications const pubnub_push_1 = __importDefault(require("./pubnub-push")); const pubnub_objects_1 = __importDefault(require("./pubnub-objects")); +// endregion +// region Time const Time = __importStar(require("./endpoints/time")); +// endregion const utils_1 = require("./utils"); const download_file_1 = require("./endpoints/file_upload/download_file"); +// endregion +/** + * Platform-agnostic PubNub client core. + */ class PubNubCore { + /** + * Construct notification payload which will trigger push notification. + * + * @param title - Title which will be shown on notification. + * @param body - Payload which will be sent as part of notification. + * + * @returns Pre-formatted message payload which will trigger push notification. + */ static notificationPayload(title, body) { return new push_payload_1.default(title, body); } + /** + * Generate unique identifier. + * + * @returns Unique identifier. + */ static generateUUID() { return uuid_1.default.createUUID(); } + // endregion constructor(configuration) { this._configuration = configuration.configuration; this.cryptography = configuration.cryptography; this.tokenManager = configuration.tokenManager; this.transport = configuration.transport; this.crypto = configuration.crypto; + // API group entry points initialization. this._objects = new pubnub_objects_1.default(this._configuration, this.sendRequest.bind(this)); this._channelGroups = new pubnub_channel_groups_1.default(this._configuration.keySet, this.sendRequest.bind(this)); this._push = new pubnub_push_1.default(this._configuration.keySet, this.sendRequest.bind(this)); + // Prepare for real-time events announcement. this.listenerManager = new listener_manager_1.ListenerManager(); this.eventEmitter = new eventEmitter_1.default(this.listenerManager); if (this._configuration.enableEventEngine) { @@ -155,109 +202,319 @@ class PubNubCore { this.subscriptionManager = new subscription_manager_1.SubscriptionManager(this._configuration, this.listenerManager, this.eventEmitter, this.makeSubscribe.bind(this), this.heartbeat.bind(this), this.makeUnsubscribe.bind(this), this.time.bind(this)); } } + // -------------------------------------------------------- + // -------------------- Configuration ---------------------- + // -------------------------------------------------------- + // region Configuration + /** + * PubNub client configuration. + * + * @returns Currently user PubNub client configuration. + */ get configuration() { return this._configuration; } + /** + * Current PubNub client configuration. + * + * @returns Currently user PubNub client configuration. + * + * @deprecated Use {@link configuration} getter instead. + */ get _config() { return this.configuration; } + /** + * REST API endpoint access authorization key. + * + * It is required to have `authorization key` with required permissions to access REST API + * endpoints when `PAM` enabled for user key set. + */ get authKey() { var _a; return (_a = this._configuration.authKey) !== null && _a !== void 0 ? _a : undefined; } + /** + * REST API endpoint access authorization key. + * + * It is required to have `authorization key` with required permissions to access REST API + * endpoints when `PAM` enabled for user key set. + */ getAuthKey() { return this.authKey; } + /** + * Change REST API endpoint access authorization key. + * + * @param authKey - New authorization key which should be used with new requests. + */ setAuthKey(authKey) { this._configuration.setAuthKey(authKey); } + /** + * Get a PubNub client user identifier. + * + * @returns Current PubNub client user identifier. + */ get userId() { return this._configuration.userId; } + /** + * Change the current PubNub client user identifier. + * + * **Important:** Change won't affect ongoing REST API calls. + * + * @param value - New PubNub client user identifier. + * + * @throws Error empty user identifier has been provided. + */ set userId(value) { if (!value || typeof value !== 'string' || value.trim().length === 0) throw new Error('Missing or invalid userId parameter. Provide a valid string userId'); this._configuration.userId = value; } + /** + * Get a PubNub client user identifier. + * + * @returns Current PubNub client user identifier. + */ getUserId() { return this._configuration.userId; } + /** + * Change the current PubNub client user identifier. + * + * **Important:** Change won't affect ongoing REST API calls. + * + * @param value - New PubNub client user identifier. + * + * @throws Error empty user identifier has been provided. + */ setUserId(value) { if (!value || typeof value !== 'string' || value.trim().length === 0) throw new Error('Missing or invalid userId parameter. Provide a valid string userId'); this._configuration.userId = value; } + /** + * Real-time updates filtering expression. + * + * @returns Filtering expression. + */ get filterExpression() { var _a; return (_a = this._configuration.getFilterExpression()) !== null && _a !== void 0 ? _a : undefined; } + /** + * Real-time updates filtering expression. + * + * @returns Filtering expression. + */ getFilterExpression() { return this.filterExpression; } + /** + * Update real-time updates filtering expression. + * + * @param expression - New expression which should be used or `undefined` to disable filtering. + */ set filterExpression(expression) { this._configuration.setFilterExpression(expression); } + /** + * Update real-time updates filtering expression. + * + * @param expression - New expression which should be used or `undefined` to disable filtering. + */ setFilterExpression(expression) { this.filterExpression = expression; } + /** + * Dta encryption / decryption key. + * + * @returns Currently used key for data encryption / decryption. + */ get cipherKey() { return this._configuration.getCipherKey(); } + /** + * Change data encryption / decryption key. + * + * @param key - New key which should be used for data encryption / decryption. + */ set cipherKey(key) { this._configuration.setCipherKey(key); } + /** + * Change data encryption / decryption key. + * + * @param key - New key which should be used for data encryption / decryption. + */ setCipherKey(key) { this.cipherKey = key; } + /** + * Change heartbeat requests interval. + * + * @param interval - New presence request heartbeat intervals. + */ set heartbeatInterval(interval) { this._configuration.setHeartbeatInterval(interval); } + /** + * Change heartbeat requests interval. + * + * @param interval - New presence request heartbeat intervals. + */ setHeartbeatInterval(interval) { this.heartbeatInterval = interval; } + /** + * Get PubNub SDK version. + * + * @returns Current SDK version. + */ getVersion() { return this._configuration.getVersion(); } + /** + * Add framework's prefix. + * + * @param name - Name of the framework which would want to add own data into `pnsdk` suffix. + * @param suffix - Suffix with information about framework. + */ _addPnsdkSuffix(name, suffix) { this._configuration._addPnsdkSuffix(name, suffix); } + // -------------------------------------------------------- + // ---------------------- Deprecated ---------------------- + // -------------------------------------------------------- + // region Deprecated + /** + * Get a PubNub client user identifier. + * + * @returns Current PubNub client user identifier. + * + * @deprecated Use the {@link getUserId} or {@link userId} getter instead. + */ getUUID() { return this.userId; } + /** + * Change the current PubNub client user identifier. + * + * **Important:** Change won't affect ongoing REST API calls. + * + * @param value - New PubNub client user identifier. + * + * @throws Error empty user identifier has been provided. + * + * @deprecated Use the {@link PubNubCore#setUserId} or {@link PubNubCore#userId} setter instead. + */ setUUID(value) { this.userId = value; } + /** + * Custom data encryption method. + * + * @deprecated Instead use {@link cryptoModule} for data encryption. + */ get customEncrypt() { return this._configuration.getCustomEncrypt(); } + /** + * Custom data decryption method. + * + * @deprecated Instead use {@link cryptoModule} for data decryption. + */ get customDecrypt() { return this._configuration.getCustomDecrypt(); } + // endregion + // endregion + // -------------------------------------------------------- + // ---------------------- Entities ------------------------ + // -------------------------------------------------------- + // region Entities + /** + * Create a `Channel` entity. + * + * Entity can be used for the interaction with the following API: + * - `subscribe` + * + * @param name - Unique channel name. + * @returns `Channel` entity. + */ channel(name) { return new Channel_1.Channel(name, this.eventEmitter, this); } + /** + * Create a `ChannelGroup` entity. + * + * Entity can be used for the interaction with the following API: + * - `subscribe` + * + * @param name - Unique channel group name. + * @returns `ChannelGroup` entity. + */ channelGroup(name) { return new ChannelGroup_1.ChannelGroup(name, this.eventEmitter, this); } + /** + * Create a `ChannelMetadata` entity. + * + * Entity can be used for the interaction with the following API: + * - `subscribe` + * + * @param id - Unique channel metadata object identifier. + * @returns `ChannelMetadata` entity. + */ channelMetadata(id) { return new ChannelMetadata_1.ChannelMetadata(id, this.eventEmitter, this); } + /** + * Create a `UserMetadata` entity. + * + * Entity can be used for the interaction with the following API: + * - `subscribe` + * + * @param id - Unique user metadata object identifier. + * @returns `UserMetadata` entity. + */ userMetadata(id) { return new UserMetadata_1.UserMetadata(id, this.eventEmitter, this); } + /** + * Create subscriptions set object. + * + * @param parameters - Subscriptions set configuration parameters. + */ subscriptionSet(parameters) { return new SubscriptionSet_1.SubscriptionSet(Object.assign(Object.assign({}, parameters), { eventEmitter: this.eventEmitter, pubnub: this })); } + /** + * Schedule request execution. + * + * @param request - REST API request. + * @param [callback] - Request completion handler callback. + * + * @returns Asynchronous request execution and response parsing result or `void` in case if + * `callback` provided. + * + * @throws PubNubError in case of request processing error. + */ sendRequest(request, callback) { return __awaiter(this, void 0, void 0, function* () { + // Validate user-input. const validationResult = request.validate(); if (validationResult) { if (callback) return callback((0, pubnub_error_1.createValidationError)(validationResult), null); throw new pubnub_error_1.PubNubError('Validation failed, check status for details', (0, pubnub_error_1.createValidationError)(validationResult)); } + // Complete request configuration. const transportRequest = request.request(); if (transportRequest.formData && transportRequest.formData.length > 0) { + // Set 300 seconds file upload request delay. transportRequest.timeout = 300; } else { @@ -266,6 +523,7 @@ class PubNubCore { else transportRequest.timeout = this._configuration.getTransactionTimeout(); } + // API request processing status. const status = { error: false, operation: request.operation(), @@ -273,10 +531,17 @@ class PubNubCore { statusCode: 0, }; const [sendableRequest, cancellationController] = this.transport.makeSendable(transportRequest); + /** + * **Important:** Because of multiple environments where JS SDK can be used control over + * cancellation had to be inverted to let transport provider solve request cancellation task + * more efficiently. As result, cancellation controller can be retrieved and used only after + * request will be scheduled by transport provider. + */ request.cancellationController = cancellationController ? cancellationController : null; return sendableRequest .then((response) => { status.statusCode = response.status; + // Handle special case when request completed but not fully processed by PubNub service. if (response.status !== 200 && response.status !== 204) { const contentType = response.headers['content-type']; if (contentType || contentType.indexOf('javascript') !== -1 || contentType.indexOf('json') !== -1) { @@ -288,18 +553,25 @@ class PubNubCore { return request.parse(response); }) .then((parsed) => { + // Notify callback (if possible). if (callback) return callback(status, parsed); return parsed; }) .catch((error) => { const apiError = !(error instanceof pubnub_api_error_1.PubNubAPIError) ? pubnub_api_error_1.PubNubAPIError.create(error) : error; + // Notify callback (if possible). if (callback) return callback(apiError.toStatus(request.operation()), null); throw apiError.toPubNubError(request.operation(), 'REST API request processing error, check status for details'); }); }); } + /** + * Unsubscribe from all channels and groups. + * + * @param [isOffline] - Whether `offline` presence should be notified or not. + */ destroy(isOffline) { if (this.subscriptionManager) { this.subscriptionManager.unsubscribeAll(isOffline); @@ -308,18 +580,49 @@ class PubNubCore { else if (this.eventEngine) this.eventEngine.dispose(); } + /** + * Unsubscribe from all channels and groups. + * + * @deprecated Use {@link destroy} method instead. + */ stop() { this.destroy(); } + // endregion + // -------------------------------------------------------- + // ----------------------- Listener ----------------------- + // -------------------------------------------------------- + // region Listener + /** + * Register real-time events listener. + * + * @param listener - Listener with event callbacks to handle different types of events. + */ addListener(listener) { this.listenerManager.addListener(listener); } + /** + * Remove real-time event listener. + * + * @param listener - Event listeners which should be removed. + */ removeListener(listener) { this.listenerManager.removeListener(listener); } + /** + * Clear all real-time event listeners. + */ removeAllListeners() { this.listenerManager.removeAllListeners(); } + /** + * Publish data to a specific channel. + * + * @param parameters - Request configuration parameters. + * @param [callback] - Request completion handler callback. + * + * @returns Asynchronous publish data response or `void` in case if `callback` provided. + */ publish(parameters, callback) { return __awaiter(this, void 0, void 0, function* () { const request = new Publish.PublishRequest(Object.assign(Object.assign({}, parameters), { keySet: this._configuration.keySet, crypto: this._configuration.getCryptoModule() })); @@ -328,6 +631,14 @@ class PubNubCore { return this.sendRequest(request); }); } + /** + * Signal data to a specific channel. + * + * @param parameters - Request configuration parameters. + * @param [callback] - Request completion handler callback. + * + * @returns Asynchronous signal data response or `void` in case if `callback` provided. + */ signal(parameters, callback) { return __awaiter(this, void 0, void 0, function* () { const request = new Signal.SignalRequest(Object.assign(Object.assign({}, parameters), { keySet: this._configuration.keySet })); @@ -336,12 +647,32 @@ class PubNubCore { return this.sendRequest(request); }); } + /** + * `Fire` a data to a specific channel. + * + * @param parameters - Request configuration parameters. + * @param [callback] - Request completion handler callback. + * + * @returns Asynchronous signal data response or `void` in case if `callback` provided. + * + * @deprecated Use {@link publish} method instead. + */ fire(parameters, callback) { return __awaiter(this, void 0, void 0, function* () { callback !== null && callback !== void 0 ? callback : (callback = () => { }); return this.publish(Object.assign(Object.assign({}, parameters), { replicate: false, storeInHistory: false }), callback); }); } + // endregion + // -------------------------------------------------------- + // -------------------- Subscribe API --------------------- + // -------------------------------------------------------- + // region Subscribe API + /** + * Get list of channels on which PubNub client currently subscribed. + * + * @returns List of active channels. + */ getSubscribedChannels() { if (this.subscriptionManager) return this.subscriptionManager.subscribedChannels; @@ -349,6 +680,11 @@ class PubNubCore { return this.eventEngine.getSubscribedChannels(); return []; } + /** + * Get list of channel groups on which PubNub client currently subscribed. + * + * @returns List of active channel groups. + */ getSubscribedChannelGroups() { if (this.subscriptionManager) return this.subscriptionManager.subscribedChannelGroups; @@ -356,12 +692,25 @@ class PubNubCore { return this.eventEngine.getSubscribedChannelGroups(); return []; } + /** + * Subscribe to specified channels and groups real-time events. + * + * @param parameters - Request configuration parameters. + */ subscribe(parameters) { if (this.subscriptionManager) this.subscriptionManager.subscribe(parameters); else if (this.eventEngine) this.eventEngine.subscribe(parameters); } + /** + * Perform subscribe request. + * + * **Note:** Method passed into managers to let them use it when required. + * + * @param parameters - Request configuration parameters. + * @param callback - Request completion handler callback. + */ makeSubscribe(parameters, callback) { const request = new subscribe_1.SubscribeRequest(Object.assign(Object.assign({}, parameters), { keySet: this._configuration.keySet, crypto: this._configuration.getCryptoModule(), getFileUrl: this.getFileUrl.bind(this) })); this.sendRequest(request, (status, result) => { @@ -370,45 +719,88 @@ class PubNubCore { this.subscriptionManager.abort = null; callback(status, result); }); + /** + * Allow subscription cancellation. + * + * **Note:** Had to be done after scheduling because transport provider return cancellation + * controller only when schedule new request. + */ if (this.subscriptionManager) { + // Creating identifiable abort caller. const callableAbort = () => request.abort(); callableAbort.identifier = request.requestIdentifier; this.subscriptionManager.abort = callableAbort; } } + /** + * Unsubscribe from specified channels and groups real-time events. + * + * @param parameters - Request configuration parameters. + */ unsubscribe(parameters) { if (this.subscriptionManager) this.subscriptionManager.unsubscribe(parameters); else if (this.eventEngine) this.eventEngine.unsubscribe(parameters); } + /** + * Perform unsubscribe request. + * + * **Note:** Method passed into managers to let them use it when required. + * + * @param parameters - Request configuration parameters. + * @param callback - Request completion handler callback. + */ makeUnsubscribe(parameters, callback) { this.sendRequest(new leave_1.PresenceLeaveRequest(Object.assign(Object.assign({}, parameters), { keySet: this._configuration.keySet })), callback); } + /** + * Unsubscribe from all channels and groups. + */ unsubscribeAll() { if (this.subscriptionManager) this.subscriptionManager.unsubscribeAll(); else if (this.eventEngine) this.eventEngine.unsubscribeAll(); } + /** + * Temporarily disconnect from real-time events stream. + */ disconnect() { if (this.subscriptionManager) this.subscriptionManager.disconnect(); else if (this.eventEngine) this.eventEngine.disconnect(); } + /** + * Restore connection to the real-time events stream. + * + * @param parameters - Reconnection catch up configuration. **Note:** available only with + * enabled event engine. + */ reconnect(parameters) { if (this.subscriptionManager) this.subscriptionManager.reconnect(); else if (this.eventEngine) this.eventEngine.reconnect(parameters !== null && parameters !== void 0 ? parameters : {}); } + /** + * Event engine handshake subscribe. + * + * @param parameters - Request configuration parameters. + */ subscribeHandshake(parameters) { return __awaiter(this, void 0, void 0, function* () { const request = new handshake_1.HandshakeSubscribeRequest(Object.assign(Object.assign({}, parameters), { keySet: this._configuration.keySet, crypto: this._configuration.getCryptoModule(), getFileUrl: this.getFileUrl.bind(this) })); const abortUnsubscribe = parameters.abortSignal.subscribe((err) => { request.abort(); }); + /** + * Allow subscription cancellation. + * + * **Note:** Had to be done after scheduling because transport provider return cancellation + * controller only when schedule new request. + */ const handshakeResponse = this.sendRequest(request); return handshakeResponse.then((response) => { abortUnsubscribe(); @@ -416,12 +808,23 @@ class PubNubCore { }); }); } + /** + * Event engine receive messages subscribe. + * + * @param parameters - Request configuration parameters. + */ subscribeReceiveMessages(parameters) { return __awaiter(this, void 0, void 0, function* () { const request = new receiveMessages_1.ReceiveMessagesSubscribeRequest(Object.assign(Object.assign({}, parameters), { keySet: this._configuration.keySet, crypto: this._configuration.getCryptoModule(), getFileUrl: this.getFileUrl.bind(this) })); const abortUnsubscribe = parameters.abortSignal.subscribe((err) => { request.abort(); }); + /** + * Allow subscription cancellation. + * + * **Note:** Had to be done after scheduling because transport provider return cancellation + * controller only when schedule new request. + */ const handshakeResponse = this.sendRequest(request); return handshakeResponse.then((response) => { abortUnsubscribe(); @@ -429,6 +832,14 @@ class PubNubCore { }); }); } + /** + * Get reactions to a specific message. + * + * @param parameters - Request configuration parameters. + * @param [callback] - Request completion handler callback. + * + * @returns Asynchronous get reactions response or `void` in case if `callback` provided. + */ getMessageActions(parameters, callback) { return __awaiter(this, void 0, void 0, function* () { const request = new get_message_actions_1.GetMessageActionsRequest(Object.assign(Object.assign({}, parameters), { keySet: this._configuration.keySet })); @@ -437,6 +848,14 @@ class PubNubCore { return this.sendRequest(request); }); } + /** + * Add a reaction to a specific message. + * + * @param parameters - Request configuration parameters. + * @param [callback] - Request completion handler callback. + * + * @returns Asynchronous add a reaction response or `void` in case if `callback` provided. + */ addMessageAction(parameters, callback) { return __awaiter(this, void 0, void 0, function* () { const request = new add_message_action_1.AddMessageActionRequest(Object.assign(Object.assign({}, parameters), { keySet: this._configuration.keySet })); @@ -445,6 +864,14 @@ class PubNubCore { return this.sendRequest(request); }); } + /** + * Remove a reaction from a specific message. + * + * @param parameters - Request configuration parameters. + * @param [callback] - Request completion handler callback. + * + * @returns Asynchronous remove a reaction response or `void` in case if `callback` provided. + */ removeMessageAction(parameters, callback) { return __awaiter(this, void 0, void 0, function* () { const request = new remove_message_action_1.RemoveMessageAction(Object.assign(Object.assign({}, parameters), { keySet: this._configuration.keySet })); @@ -453,6 +880,14 @@ class PubNubCore { return this.sendRequest(request); }); } + /** + * Fetch messages history for channels. + * + * @param parameters - Request configuration parameters. + * @param [callback] - Request completion handler callback. + * + * @returns Asynchronous fetch messages response or `void` in case if `callback` provided. + */ fetchMessages(parameters, callback) { return __awaiter(this, void 0, void 0, function* () { const request = new fetch_messages_1.FetchMessagesRequest(Object.assign(Object.assign({}, parameters), { keySet: this._configuration.keySet, crypto: this._configuration.getCryptoModule(), getFileUrl: this.getFileUrl.bind(this) })); @@ -461,6 +896,16 @@ class PubNubCore { return this.sendRequest(request); }); } + /** + * Delete messages from the channel history. + * + * @param parameters - Request configuration parameters. + * @param [callback] - Request completion handler callback. + * + * @returns Asynchronous delete messages response or `void` in case if `callback` provided. + * + * @deprecated + */ deleteMessages(parameters, callback) { return __awaiter(this, void 0, void 0, function* () { const request = new delete_messages_1.DeleteMessageRequest(Object.assign(Object.assign({}, parameters), { keySet: this._configuration.keySet })); @@ -469,6 +914,14 @@ class PubNubCore { return this.sendRequest(request); }); } + /** + * Count messages from the channels' history. + * + * @param parameters - Request configuration parameters. + * @param [callback] - Request completion handler callback. + * + * @returns Asynchronous count messages response or `void` in case if `callback` provided. + */ messageCounts(parameters, callback) { return __awaiter(this, void 0, void 0, function* () { const request = new message_counts_1.MessageCountRequest(Object.assign(Object.assign({}, parameters), { keySet: this._configuration.keySet })); @@ -477,6 +930,16 @@ class PubNubCore { return this.sendRequest(request); }); } + /** + * Fetch single channel history. + * + * @param parameters - Request configuration parameters. + * @param [callback] - Request completion handler callback. + * + * @returns Asynchronous fetch channel history response or `void` in case if `callback` provided. + * + * @deprecated + */ history(parameters, callback) { return __awaiter(this, void 0, void 0, function* () { const request = new get_history_1.GetHistoryRequest(Object.assign(Object.assign({}, parameters), { keySet: this._configuration.keySet, crypto: this._configuration.getCryptoModule() })); @@ -485,6 +948,14 @@ class PubNubCore { return this.sendRequest(request); }); } + /** + * Get channel's presence information. + * + * @param parameters - Request configuration parameters. + * @param [callback] - Request completion handler callback. + * + * @returns Asynchronous get channel's presence response or `void` in case if `callback` provided. + */ hereNow(parameters, callback) { return __awaiter(this, void 0, void 0, function* () { const request = new here_now_1.HereNowRequest(Object.assign(Object.assign({}, parameters), { keySet: this._configuration.keySet })); @@ -493,6 +964,16 @@ class PubNubCore { return this.sendRequest(request); }); } + /** + * Get user's presence information. + * + * Get list of channels to which `uuid` currently subscribed. + * + * @param parameters - Request configuration parameters. + * @param [callback] - Request completion handler callback. + * + * @returns Asynchronous get user's presence response or `void` in case if `callback` provided. + */ whereNow(parameters, callback) { return __awaiter(this, void 0, void 0, function* () { var _a; @@ -505,6 +986,14 @@ class PubNubCore { return this.sendRequest(request); }); } + /** + * Get associated user's data for channels and groups. + * + * @param parameters - Request configuration parameters. + * @param [callback] - Request completion handler callback. + * + * @returns Asynchronous get user's data response or `void` in case if `callback` provided. + */ getState(parameters, callback) { return __awaiter(this, void 0, void 0, function* () { var _a; @@ -514,12 +1003,21 @@ class PubNubCore { return this.sendRequest(request); }); } + /** + * Set associated user's data for channels and groups. + * + * @param parameters - Request configuration parameters. + * @param [callback] - Request completion handler callback. + * + * @returns Asynchronous set user's data response or `void` in case if `callback` provided. + */ setState(parameters, callback) { return __awaiter(this, void 0, void 0, function* () { var _a, _b; const { keySet, userId: userId } = this._configuration; const heartbeat = this._configuration.getPresenceTimeout(); let request; + // Maintain presence information (if required). if (this._configuration.enableEventEngine && this.presenceState) { const presenceState = this.presenceState; (_a = parameters.channels) === null || _a === void 0 ? void 0 : _a.forEach((channel) => (presenceState[channel] = parameters.state)); @@ -527,12 +1025,14 @@ class PubNubCore { (_b = parameters.channelGroups) === null || _b === void 0 ? void 0 : _b.forEach((group) => (presenceState[group] = parameters.state)); } } + // Check whether state should be set with heartbeat or not. if ('withHeartbeat' in parameters) { request = new heartbeat_1.HeartbeatRequest(Object.assign(Object.assign({}, parameters), { keySet, heartbeat })); } else { request = new set_state_1.SetPresenceStateRequest(Object.assign(Object.assign({}, parameters), { keySet, uuid: userId })); } + // Update state used by subscription manager. if (this.subscriptionManager) this.subscriptionManager.setState(parameters); if (callback) @@ -540,10 +1040,25 @@ class PubNubCore { return this.sendRequest(request); }); } + // endregion + // region Change presence state + /** + * Manual presence management. + * + * @param parameters - Desired presence state for provided list of channels and groups. + */ presence(parameters) { var _a; (_a = this.subscriptionManager) === null || _a === void 0 ? void 0 : _a.changePresence(parameters); } + // endregion + // region Heartbeat + /** + * Announce user presence + * + * @param parameters - Desired presence state for provided list of channels and groups. + * @param callback - Request completion handler callback. + */ heartbeat(parameters, callback) { return __awaiter(this, void 0, void 0, function* () { const request = new heartbeat_1.HeartbeatRequest(Object.assign(Object.assign({}, parameters), { keySet: this._configuration.keySet })); @@ -552,18 +1067,45 @@ class PubNubCore { return this.sendRequest(request); }); } + // endregion + // region Join + /** + * Announce user `join` on specified list of channels and groups. + * + * @param parameters - List of channels and groups where `join` event should be sent. + */ join(parameters) { var _a; (_a = this.presenceEventEngine) === null || _a === void 0 ? void 0 : _a.join(parameters); } + // endregion + // region Leave + /** + * Announce user `leave` on specified list of channels and groups. + * + * @param parameters - List of channels and groups where `leave` event should be sent. + */ leave(parameters) { var _a; (_a = this.presenceEventEngine) === null || _a === void 0 ? void 0 : _a.leave(parameters); } + /** + * Announce user `leave` on all subscribed channels. + */ leaveAll() { var _a; (_a = this.presenceEventEngine) === null || _a === void 0 ? void 0 : _a.leaveAll(); } + /** + * Grant token permission. + * + * Generate access token with requested permissions. + * + * @param parameters - Request configuration parameters. + * @param [callback] - Request completion handler callback. + * + * @returns Asynchronous grant token response or `void` in case if `callback` provided. + */ grantToken(parameters, callback) { return __awaiter(this, void 0, void 0, function* () { const request = new grant_token_1.GrantTokenRequest(Object.assign(Object.assign({}, parameters), { keySet: this._configuration.keySet })); @@ -572,6 +1114,14 @@ class PubNubCore { return this.sendRequest(request); }); } + /** + * Revoke token permission. + * + * @param parameters - Request configuration parameters. + * @param [callback] - Request completion handler callback. + * + * @returns Asynchronous revoke token response or `void` in case if `callback` provided. + */ revokeToken(parameters, callback) { return __awaiter(this, void 0, void 0, function* () { const request = new revoke_token_1.RevokeTokenRequest(Object.assign(Object.assign({}, parameters), { keySet: this._configuration.keySet })); @@ -580,21 +1130,62 @@ class PubNubCore { return this.sendRequest(request); }); } + // endregion + // region Token Manipulation + /** + * Get current access token. + * + * @returns Previously configured access token using {@link setToken} method. + */ get token() { return this.tokenManager.getToken(); } + /** + * Get current access token. + * + * @returns Previously configured access token using {@link setToken} method. + */ getToken() { return this.token; } + /** + * Set current access token. + * + * @param token - New access token which should be used with next REST API endpoint calls. + */ set token(token) { this.tokenManager.setToken(token); } + /** + * Set current access token. + * + * @param token - New access token which should be used with next REST API endpoint calls. + */ setToken(token) { this.token = token; } + /** + * Parse access token. + * + * Parse token to see what permissions token owner has. + * + * @param token - Token which should be parsed. + * + * @returns Token's permissions information for the resources. + */ parseToken(token) { return this.tokenManager.parseToken(token); } + /** + * Grant auth key(s) permission. + * + * @param parameters - Request configuration parameters. + * @param [callback] - Request completion handler callback. + * + * @returns Asynchronous grant auth key(s) permissions or `void` in case if `callback` provided. + * + * @deprecated Use {@link grantToken} and {@link setToken} methods instead. + */ grant(parameters, callback) { return __awaiter(this, void 0, void 0, function* () { const request = new grant_1.GrantRequest(Object.assign(Object.assign({}, parameters), { keySet: this._configuration.keySet })); @@ -603,6 +1194,16 @@ class PubNubCore { return this.sendRequest(request); }); } + /** + * Audit auth key(s) permission. + * + * @param parameters - Request configuration parameters. + * @param [callback] - Request completion handler callback. + * + * @deprecated + * + * @deprecated Use {@link grantToken} and {@link setToken} methods instead. + */ audit(parameters, callback) { return __awaiter(this, void 0, void 0, function* () { const request = new audit_1.AuditRequest(Object.assign(Object.assign({}, parameters), { keySet: this._configuration.keySet })); @@ -611,74 +1212,236 @@ class PubNubCore { return this.sendRequest(request); }); } + // endregion + // endregion + // endregion + // -------------------------------------------------------- + // ------------------- App Context API -------------------- + // -------------------------------------------------------- + // region App Context API + /** + * PubNub App Context API group. + */ get objects() { return this._objects; } + /** + Fetch a paginated list of User objects. + * + * @param [parametersOrCallback] - Request configuration parameters or callback from overload. + * @param [callback] - Request completion handler callback. + * + * @returns Asynchronous get all User objects response or `void` in case if `callback` provided. + * + * @deprecated Use {@link PubNubCore#objects.getAllUUIDMetadata} method instead. + */ fetchUsers(parametersOrCallback, callback) { return __awaiter(this, void 0, void 0, function* () { return this.objects._getAllUUIDMetadata(parametersOrCallback, callback); }); } + /** + * Fetch User object for currently configured PubNub client `uuid`. + * + * @param [parametersOrCallback] - Request configuration parameters or callback from overload. + * @param [callback] - Request completion handler callback. + * + * @returns Asynchronous get User object response or `void` in case if `callback` provided. + * + * @deprecated Use {@link PubNubCore#objects.getUUIDMetadata} method instead. + */ fetchUser(parametersOrCallback, callback) { return __awaiter(this, void 0, void 0, function* () { return this.objects._getUUIDMetadata(parametersOrCallback, callback); }); } + /** + * Create User object. + * + * @param parameters - Request configuration parameters. Will create User object for currently + * configured PubNub client `uuid` if not set. + * @param [callback] - Request completion handler callback. + * + * @returns Asynchronous create User object response or `void` in case if `callback` provided. + * + * @deprecated Use {@link PubNubCore#objects.setUUIDMetadata} method instead. + */ createUser(parameters, callback) { return __awaiter(this, void 0, void 0, function* () { return this.objects._setUUIDMetadata(parameters, callback); }); } + /** + * Update User object. + * + * @param parameters - Request configuration parameters. Will update User object for currently + * configured PubNub client `uuid` if not set. + * @param [callback] - Request completion handler callback. + * + * @returns Asynchronous update User object response or `void` in case if `callback` provided. + * + * @deprecated Use {@link PubNubCore#objects.setUUIDMetadata} method instead. + */ updateUser(parameters, callback) { return __awaiter(this, void 0, void 0, function* () { return this.objects._setUUIDMetadata(parameters, callback); }); } + /** + * Remove a specific User object. + * + * @param [parametersOrCallback] - Request configuration parameters or callback from overload. + * @param [callback] - Request completion handler callback. + * + * @returns Asynchronous User object remove response or `void` in case if `callback` provided. + * + * @deprecated Use {@link PubNubCore#objects.removeUUIDMetadata} method instead. + */ removeUser(parametersOrCallback, callback) { return __awaiter(this, void 0, void 0, function* () { return this.objects._removeUUIDMetadata(parametersOrCallback, callback); }); } + /** + * Fetch a paginated list of Space objects. + * + * @param [parametersOrCallback] - Request configuration parameters or callback from overload. + * @param [callback] - Request completion handler callback. + * + * @returns Asynchronous get all Space objects response or `void` in case if `callback` + * provided. + * + * @deprecated Use {@link PubNubCore#objects.getAllChannelMetadata} method instead. + */ fetchSpaces(parametersOrCallback, callback) { return __awaiter(this, void 0, void 0, function* () { return this.objects._getAllChannelMetadata(parametersOrCallback, callback); }); } + /** + * Fetch a specific Space object. + * + * @param parameters - Request configuration parameters. + * @param [callback] - Request completion handler callback. + * + * @returns Asynchronous get Space object response or `void` in case if `callback` provided. + * + * @deprecated Use {@link PubNubCore#objects.getChannelMetadata} method instead. + */ fetchSpace(parameters, callback) { return __awaiter(this, void 0, void 0, function* () { return this.objects._getChannelMetadata(parameters, callback); }); } + /** + * Create specific Space object. + * + * @param parameters - Request configuration parameters. + * @param [callback] - Request completion handler callback. + * + * @returns Asynchronous create Space object response or `void` in case if `callback` provided. + * + * @deprecated Use {@link PubNubCore#objects.setChannelMetadata} method instead. + */ createSpace(parameters, callback) { return __awaiter(this, void 0, void 0, function* () { return this.objects._setChannelMetadata(parameters, callback); }); } + /** + * Update specific Space object. + * + * @param parameters - Request configuration parameters. + * @param [callback] - Request completion handler callback. + * + * @returns Asynchronous update Space object response or `void` in case if `callback` provided. + * + * @deprecated Use {@link PubNubCore#objects.setChannelMetadata} method instead. + */ updateSpace(parameters, callback) { return __awaiter(this, void 0, void 0, function* () { return this.objects._setChannelMetadata(parameters, callback); }); } + /** + * Remove a specific Space object. + * + * @param parameters - Request configuration parameters. + * @param [callback] - Request completion handler callback. + * + * @returns Asynchronous Space object remove response or `void` in case if `callback` + * provided. + * + * @deprecated Use {@link PubNubCore#objects.removeChannelMetadata} method instead. + */ removeSpace(parameters, callback) { return __awaiter(this, void 0, void 0, function* () { return this.objects._removeChannelMetadata(parameters, callback); }); } + /** + * Fetch paginated list of specific Space members or specific User memberships. + * + * @param parameters - Request configuration parameters. + * @param [callback] - Request completion handler callback. + * + * @returns Asynchronous get specific Space members or specific User memberships response or + * `void` in case if `callback` provided. + * + * @deprecated Use {@link PubNubCore#objects.getChannelMembers} or {@link PubNubCore#objects.getMemberships} + * methods instead. + */ fetchMemberships(parameters, callback) { return __awaiter(this, void 0, void 0, function* () { return this.objects.fetchMemberships(parameters, callback); }); } + /** + * Add members to specific Space or memberships specific User. + * + * @param parameters - Request configuration parameters. + * @param [callback] - Request completion handler callback. + * + * @returns Asynchronous add members to specific Space or memberships specific User response or + * `void` in case if `callback` provided. + * + * @deprecated Use {@link PubNubCore#objects.setChannelMembers} or {@link PubNubCore#objects.setMemberships} + * methods instead. + */ addMemberships(parameters, callback) { return __awaiter(this, void 0, void 0, function* () { return this.objects.addMemberships(parameters, callback); }); } + /** + * Update specific Space members or User memberships. + * + * @param parameters - Request configuration parameters. + * @param [callback] - Request completion handler callback. + * + * @returns Asynchronous update Space members or User memberships response or `void` in case + * if `callback` provided. + * + * @deprecated Use {@link PubNubCore#objects.setChannelMembers} or {@link PubNubCore#objects.setMemberships} + * methods instead. + */ updateMemberships(parameters, callback) { return __awaiter(this, void 0, void 0, function* () { return this.objects.addMemberships(parameters, callback); }); } + /** + * Remove User membership. + * + * @param parameters - Request configuration parameters. + * @param [callback] - Request completion handler callback. + * + * @returns Asynchronous memberships modification response or `void` in case if `callback` provided. + * + * @deprecated Use {@link PubNubCore#objects.removeMemberships} or {@link PubNubCore#objects.removeChannelMembers} + * methods instead + * from `objects` API group.. + */ removeMemberships(parameters, callback) { return __awaiter(this, void 0, void 0, function* () { var _a, _b, _c; @@ -704,12 +1467,37 @@ class PubNubCore { return this.objects.removeMemberships(requestParameters); }); } + // endregion + // endregion + // -------------------------------------------------------- + // ----------------- Channel Groups API ------------------- + // -------------------------------------------------------- + // region Channel Groups API + /** + * PubNub Channel Groups API group. + */ get channelGroups() { return this._channelGroups; } + // endregion + // -------------------------------------------------------- + // ---------------- Push Notifications API ----------------- + // -------------------------------------------------------- + // region Push Notifications API + /** + * PubNub Push Notifications API group. + */ get push() { return this._push; } + /** + * Share file to a specific channel. + * + * @param parameters - Request configuration parameters. + * @param [callback] - Request completion handler callback. + * + * @returns Asynchronous file sharing response or `void` in case if `callback` provided. + */ sendFile(parameters, callback) { return __awaiter(this, void 0, void 0, function* () { if (!this._configuration.PubNubFile) @@ -735,12 +1523,21 @@ class PubNubCore { errorStatus = error.status; else if (error instanceof pubnub_api_error_1.PubNubAPIError) errorStatus = error.toStatus(status.operation); + // Notify callback (if possible). if (callback && errorStatus) callback(errorStatus, null); throw new pubnub_error_1.PubNubError('REST API request processing error, check status for details', errorStatus); }); }); } + /** + * Publish file message to a specific channel. + * + * @param parameters - Request configuration parameters. + * @param [callback] - Request completion handler callback. + * + * @returns Asynchronous publish file message response or `void` in case if `callback` provided. + */ publishFile(parameters, callback) { return __awaiter(this, void 0, void 0, function* () { if (!this._configuration.PubNubFile) @@ -751,6 +1548,14 @@ class PubNubCore { return this.sendRequest(request); }); } + /** + * Retrieve list of shared files in specific channel. + * + * @param parameters - Request configuration parameters. + * @param [callback] - Request completion handler callback. + * + * @returns Asynchronous shared files list response or `void` in case if `callback` provided. + */ listFiles(parameters, callback) { return __awaiter(this, void 0, void 0, function* () { const request = new list_files_1.FilesListRequest(Object.assign(Object.assign({}, parameters), { keySet: this._configuration.keySet })); @@ -759,6 +1564,15 @@ class PubNubCore { return this.sendRequest(request); }); } + // endregion + // region Get Download Url + /** + * Get file download Url. + * + * @param parameters - Request configuration parameters. + * + * @returns File download Url. + */ getFileUrl(parameters) { var _a; const request = this.transport.request(new get_file_url_1.GetFileDownloadUrlRequest(Object.assign(Object.assign({}, parameters), { keySet: this._configuration.keySet })).request()); @@ -773,6 +1587,14 @@ class PubNubCore { .join('&'); return `${request.origin}${request.path}?${queryString}`; } + /** + * Download shared file from specific channel. + * + * @param parameters - Request configuration parameters. + * @param [callback] - Request completion handler callback. + * + * @returns Asynchronous download shared file response or `void` in case if `callback` provided. + */ downloadFile(parameters, callback) { return __awaiter(this, void 0, void 0, function* () { if (!this._configuration.PubNubFile) @@ -783,6 +1605,14 @@ class PubNubCore { return (yield this.sendRequest(request)); }); } + /** + * Delete shared file from specific channel. + * + * @param parameters - Request configuration parameters. + * @param [callback] - Request completion handler callback. + * + * @returns Asynchronous delete shared file response or `void` in case if `callback` provided. + */ deleteFile(parameters, callback) { return __awaiter(this, void 0, void 0, function* () { const request = new delete_file_1.DeleteFileRequest(Object.assign(Object.assign({}, parameters), { keySet: this._configuration.keySet })); @@ -791,6 +1621,13 @@ class PubNubCore { return this.sendRequest(request); }); } + /** + Get current high-precision timetoken. + * + * @param [callback] - Request completion handler callback. + * + * @returns Asynchronous get current timetoken response or `void` in case if `callback` provided. + */ time(callback) { return __awaiter(this, void 0, void 0, function* () { const request = new Time.TimeRequest(); @@ -799,6 +1636,22 @@ class PubNubCore { return this.sendRequest(request); }); } + // endregion + // -------------------------------------------------------- + // ------------------ Cryptography API -------------------- + // -------------------------------------------------------- + // region Cryptography + // region Common + /** + * Encrypt data. + * + * @param data - Stringified data which should be encrypted using `CryptoModule`. + * @deprecated + * @param [customCipherKey] - Cipher key which should be used to encrypt data. **Deprecated:** + * use {@link Configuration#cryptoModule|cryptoModule} instead. + * + * @returns Data encryption result as a string. + */ encrypt(data, customCipherKey) { const cryptoModule = this._configuration.getCryptoModule(); if (!customCipherKey && cryptoModule && typeof data === 'string') { @@ -809,6 +1662,15 @@ class PubNubCore { throw new Error('Encryption error: cypher key not set'); return this.crypto.encrypt(data, customCipherKey); } + /** + * Decrypt data. + * + * @param data - Stringified data which should be encrypted using `CryptoModule`. + * @param [customCipherKey] - Cipher key which should be used to decrypt data. **Deprecated:** + * use {@link Configuration#cryptoModule|cryptoModule} instead. + * + * @returns Data decryption result as an object. + */ decrypt(data, customCipherKey) { const cryptoModule = this._configuration.getCryptoModule(); if (!customCipherKey && cryptoModule) { @@ -819,6 +1681,19 @@ class PubNubCore { throw new Error('Decryption error: cypher key not set'); return this.crypto.decrypt(data, customCipherKey); } + /** + * Encrypt file content. + * + * @param keyOrFile - Cipher key which should be used to encrypt data or file which should be + * encrypted using `CryptoModule`. + * @param [file] - File which should be encrypted using legacy cryptography. + * + * @returns Asynchronous file encryption result. + * + * @throws Error if source file not provided. + * @throws File constructor not provided. + * @throws Crypto module is missing (if non-legacy flow used). + */ encryptFile(keyOrFile, file) { return __awaiter(this, void 0, void 0, function* () { var _a; @@ -838,6 +1713,19 @@ class PubNubCore { return (_a = this._configuration.getCryptoModule()) === null || _a === void 0 ? void 0 : _a.encryptFile(file, this._configuration.PubNubFile); }); } + /** + * Decrypt file content. + * + * @param keyOrFile - Cipher key which should be used to decrypt data or file which should be + * decrypted using `CryptoModule`. + * @param [file] - File which should be decrypted using legacy cryptography. + * + * @returns Asynchronous file decryption result. + * + * @throws Error if source file not provided. + * @throws File constructor not provided. + * @throws Crypto module is missing (if non-legacy flow used). + */ decryptFile(keyOrFile, file) { return __awaiter(this, void 0, void 0, function* () { var _a; @@ -859,8 +1747,29 @@ class PubNubCore { } } exports.PubNubCore = PubNubCore; +/** + * {@link ArrayBuffer} to {@link string} decoder. + * + * @internal + */ PubNubCore.decoder = new TextDecoder(); +// -------------------------------------------------------- +// ----------------------- Static ------------------------- +// -------------------------------------------------------- +// region Static +/** + * Type of REST API endpoint which reported status. + */ PubNubCore.OPERATIONS = operations_1.default; +/** + * API call status category. + */ PubNubCore.CATEGORIES = categories_1.default; +/** + * Exponential retry policy constructor. + */ PubNubCore.ExponentialRetryPolicy = retryPolicy_1.RetryPolicy.ExponentialRetryPolicy; +/** + * Linear retry policy constructor. + */ PubNubCore.LinearRetryPolicy = retryPolicy_1.RetryPolicy.LinearRetryPolicy; diff --git a/lib/core/pubnub-objects.js b/lib/core/pubnub-objects.js index 79b1e885b..9948ee382 100644 --- a/lib/core/pubnub-objects.js +++ b/lib/core/pubnub-objects.js @@ -1,4 +1,7 @@ "use strict"; +/** + * PubNub Objects API module. + */ var __awaiter = (this && this.__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) { @@ -22,18 +25,38 @@ const set_3 = require("./endpoints/objects/member/set"); const get_4 = require("./endpoints/objects/uuid/get"); const set_4 = require("./endpoints/objects/uuid/set"); class PubNubObjects { - constructor(configuration, sendRequest) { + constructor(configuration, + /* eslint-disable @typescript-eslint/no-explicit-any */ + sendRequest) { this.configuration = configuration; this.sendRequest = sendRequest; this.keySet = configuration.keySet; } + /** + * Fetch a paginated list of UUID Metadata objects. + * + * @param [parametersOrCallback] - Request configuration parameters or callback from overload. + * @param [callback] - Request completion handler callback. + * + * @returns Asynchronous get all UUID metadata response or `void` in case if `callback` provided. + */ getAllUUIDMetadata(parametersOrCallback, callback) { return __awaiter(this, void 0, void 0, function* () { return this._getAllUUIDMetadata(parametersOrCallback, callback); }); } + /** + * Fetch a paginated list of UUID Metadata objects. + * + * + * @param [parametersOrCallback] - Request configuration parameters or callback from overload. + * @param [callback] - Request completion handler callback. + * + * @returns Asynchronous get all UUID metadata response or `void` in case if `callback` provided. + */ _getAllUUIDMetadata(parametersOrCallback, callback) { return __awaiter(this, void 0, void 0, function* () { + // Get user request parameters. const parameters = parametersOrCallback && typeof parametersOrCallback !== 'function' ? parametersOrCallback : {}; callback !== null && callback !== void 0 ? callback : (callback = typeof parametersOrCallback === 'function' ? parametersOrCallback : undefined); const request = new get_all_2.GetAllUUIDMetadataRequest(Object.assign(Object.assign({}, parameters), { keySet: this.keySet })); @@ -42,14 +65,31 @@ class PubNubObjects { return this.sendRequest(request); }); } + /** + * Fetch a specific UUID Metadata object. + * + * @param [parametersOrCallback] - Request configuration parameters or callback from overload. + * @param [callback] - Request completion handler callback. + * + * @returns Asynchronous get UUID metadata response or `void` in case if `callback` provided. + */ getUUIDMetadata(parametersOrCallback, callback) { return __awaiter(this, void 0, void 0, function* () { return this._getUUIDMetadata(parametersOrCallback, callback); }); } + /** + * Fetch a specific UUID Metadata object. + * + * @param [parametersOrCallback] - Request configuration parameters or callback from overload. + * @param [callback] - Request completion handler callback. + * + * @returns Asynchronous get UUID metadata response or `void` in case if `callback` provided. + */ _getUUIDMetadata(parametersOrCallback, callback) { return __awaiter(this, void 0, void 0, function* () { var _a; + // Get user request parameters. const parameters = parametersOrCallback && typeof parametersOrCallback !== 'function' ? parametersOrCallback : {}; callback !== null && callback !== void 0 ? callback : (callback = typeof parametersOrCallback === 'function' ? parametersOrCallback : undefined); if (parameters.userId) @@ -61,11 +101,29 @@ class PubNubObjects { return this.sendRequest(request); }); } + /** + * Update specific UUID Metadata object. + * + * @param parameters - Request configuration parameters. Will set UUID metadata for currently + * configured PubNub client `uuid` if not set. + * @param [callback] - Request completion handler callback. + * + * @returns Asynchronous set UUID metadata response or `void` in case if `callback` provided. + */ setUUIDMetadata(parameters, callback) { return __awaiter(this, void 0, void 0, function* () { return this._setUUIDMetadata(parameters, callback); }); } + /** + * Update specific UUID Metadata object. + * + * @param parameters - Request configuration parameters. Will set UUID metadata for currently + * configured PubNub client `uuid` if not set. + * @param [callback] - Request completion handler callback. + * + * @returns Asynchronous set UUID metadata response or `void` in case if `callback` provided. + */ _setUUIDMetadata(parameters, callback) { return __awaiter(this, void 0, void 0, function* () { var _a; @@ -78,14 +136,31 @@ class PubNubObjects { return this.sendRequest(request); }); } + /** + * Remove a specific UUID Metadata object. + * + * @param [parametersOrCallback] - Request configuration parameters or callback from overload. + * @param [callback] - Request completion handler callback. + * + * @returns Asynchronous UUID metadata remove response or `void` in case if `callback` provided. + */ removeUUIDMetadata(parametersOrCallback, callback) { return __awaiter(this, void 0, void 0, function* () { return this._removeUUIDMetadata(parametersOrCallback, callback); }); } + /** + * Remove a specific UUID Metadata object. + * + * @param [parametersOrCallback] - Request configuration parameters or callback from overload. + * @param [callback] - Request completion handler callback. + * + * @returns Asynchronous UUID metadata remove response or `void` in case if `callback` provided. + */ _removeUUIDMetadata(parametersOrCallback, callback) { return __awaiter(this, void 0, void 0, function* () { var _a; + // Get user request parameters. const parameters = parametersOrCallback && typeof parametersOrCallback !== 'function' ? parametersOrCallback : {}; callback !== null && callback !== void 0 ? callback : (callback = typeof parametersOrCallback === 'function' ? parametersOrCallback : undefined); if (parameters.userId) @@ -97,13 +172,32 @@ class PubNubObjects { return this.sendRequest(request); }); } + /** + * Fetch a paginated list of Channel Metadata objects. + * + * @param [parametersOrCallback] - Request configuration parameters or callback from overload. + * @param [callback] - Request completion handler callback. + * + * @returns Asynchronous get all Channel metadata response or `void` in case if `callback` + * provided. + */ getAllChannelMetadata(parametersOrCallback, callback) { return __awaiter(this, void 0, void 0, function* () { return this._getAllChannelMetadata(parametersOrCallback, callback); }); } + /** + * Fetch a paginated list of Channel Metadata objects. + * + * @param [parametersOrCallback] - Request configuration parameters or callback from overload. + * @param [callback] - Request completion handler callback. + * + * @returns Asynchronous get all Channel metadata response or `void` in case if `callback` + * provided. + */ _getAllChannelMetadata(parametersOrCallback, callback) { return __awaiter(this, void 0, void 0, function* () { + // Get user request parameters. const parameters = parametersOrCallback && typeof parametersOrCallback !== 'function' ? parametersOrCallback : {}; callback !== null && callback !== void 0 ? callback : (callback = typeof parametersOrCallback === 'function' ? parametersOrCallback : undefined); const request = new get_all_1.GetAllChannelsMetadataRequest(Object.assign(Object.assign({}, parameters), { keySet: this.keySet })); @@ -112,11 +206,27 @@ class PubNubObjects { return this.sendRequest(request); }); } + /** + * Fetch Channel Metadata object. + * + * @param parameters - Request configuration parameters. + * @param [callback] - Request completion handler callback. + * + * @returns Asynchronous get Channel metadata response or `void` in case if `callback` provided. + */ getChannelMetadata(parameters, callback) { return __awaiter(this, void 0, void 0, function* () { return this._getChannelMetadata(parameters, callback); }); } + /** + * Fetch Channel Metadata object. + * + * @param parameters - Request configuration parameters. + * @param [callback] - Request completion handler callback. + * + * @returns Asynchronous get Channel metadata response or `void` in case if `callback` provided. + */ _getChannelMetadata(parameters, callback) { return __awaiter(this, void 0, void 0, function* () { const request = new get_2.GetChannelMetadataRequest(Object.assign(Object.assign({}, parameters), { keySet: this.keySet })); @@ -125,11 +235,27 @@ class PubNubObjects { return this.sendRequest(request); }); } + /** + * Update specific Channel Metadata object. + * + * @param parameters - Request configuration parameters. + * @param [callback] - Request completion handler callback. + * + * @returns Asynchronous set Channel metadata response or `void` in case if `callback` provided. + */ setChannelMetadata(parameters, callback) { return __awaiter(this, void 0, void 0, function* () { return this._setChannelMetadata(parameters, callback); }); } + /** + * Update specific Channel Metadata object. + * + * @param parameters - Request configuration parameters. + * @param [callback] - Request completion handler callback. + * + * @returns Asynchronous set Channel metadata response or `void` in case if `callback` provided. + */ _setChannelMetadata(parameters, callback) { return __awaiter(this, void 0, void 0, function* () { const request = new set_2.SetChannelMetadataRequest(Object.assign(Object.assign({}, parameters), { keySet: this.keySet })); @@ -138,11 +264,29 @@ class PubNubObjects { return this.sendRequest(request); }); } + /** + * Remove a specific Channel Metadata object. + * + * @param parameters - Request configuration parameters. + * @param [callback] - Request completion handler callback. + * + * @returns Asynchronous Channel metadata remove response or `void` in case if `callback` + * provided. + */ removeChannelMetadata(parameters, callback) { return __awaiter(this, void 0, void 0, function* () { return this._removeChannelMetadata(parameters, callback); }); } + /** + * Remove a specific Channel Metadata object. + * + * @param parameters - Request configuration parameters. + * @param [callback] - Request completion handler callback. + * + * @returns Asynchronous Channel metadata remove response or `void` in case if `callback` + * provided. + */ _removeChannelMetadata(parameters, callback) { return __awaiter(this, void 0, void 0, function* () { const request = new remove_1.RemoveChannelMetadataRequest(Object.assign(Object.assign({}, parameters), { keySet: this.keySet })); @@ -151,6 +295,14 @@ class PubNubObjects { return this.sendRequest(request); }); } + /** + * Fetch a paginated list of Channel Member objects. + * + * @param parameters - Request configuration parameters. + * @param [callback] - Request completion handler callback. + * + * @returns Asynchronous get Channel Members response or `void` in case if `callback` provided. + */ getChannelMembers(parameters, callback) { return __awaiter(this, void 0, void 0, function* () { const request = new get_3.GetChannelMembersRequest(Object.assign(Object.assign({}, parameters), { keySet: this.keySet })); @@ -159,6 +311,15 @@ class PubNubObjects { return this.sendRequest(request); }); } + /** + * Update specific Channel Members list. + * + * @param parameters - Request configuration parameters. + * @param [callback] - Request completion handler callback. + * + * @returns Asynchronous update Channel members list response or `void` in case if `callback` + * provided. + */ setChannelMembers(parameters, callback) { return __awaiter(this, void 0, void 0, function* () { const request = new set_3.SetChannelMembersRequest(Object.assign(Object.assign({}, parameters), { type: 'set', keySet: this.keySet })); @@ -167,6 +328,14 @@ class PubNubObjects { return this.sendRequest(request); }); } + /** + * Remove Members from the Channel. + * + * @param parameters - Request configuration parameters. + * @param [callback] - Request completion handler callback. + * + * @returns Asynchronous Channel Members remove response or `void` in case if `callback` provided. + */ removeChannelMembers(parameters, callback) { return __awaiter(this, void 0, void 0, function* () { const request = new set_3.SetChannelMembersRequest(Object.assign(Object.assign({}, parameters), { type: 'delete', keySet: this.keySet })); @@ -175,9 +344,18 @@ class PubNubObjects { return this.sendRequest(request); }); } + /** + * Fetch a specific UUID Memberships list. + * + * @param [parametersOrCallback] - Request configuration parameters or callback from overload. + * @param [callback] - Request completion handler callback. + * + * @returns Asynchronous get UUID Memberships response or `void` in case if `callback` provided. + */ getMemberships(parametersOrCallback, callback) { return __awaiter(this, void 0, void 0, function* () { var _a; + // Get user request parameters. const parameters = parametersOrCallback && typeof parametersOrCallback !== 'function' ? parametersOrCallback : {}; callback !== null && callback !== void 0 ? callback : (callback = typeof parametersOrCallback === 'function' ? parametersOrCallback : undefined); if (parameters.userId) @@ -189,6 +367,15 @@ class PubNubObjects { return this.sendRequest(request); }); } + /** + * Update specific UUID Memberships list. + * + * @param parameters - Request configuration parameters. + * @param [callback] - Request completion handler callback. + * + * @returns Asynchronous update UUID Memberships list response or `void` in case if `callback` + * provided. + */ setMemberships(parameters, callback) { return __awaiter(this, void 0, void 0, function* () { var _a; @@ -201,6 +388,15 @@ class PubNubObjects { return this.sendRequest(request); }); } + /** + * Remove a specific UUID Memberships. + * + * @param parameters - Request configuration parameters or callback from overload. + * @param [callback] - Request completion handler callback. + * + * @returns Asynchronous UUID Memberships remove response or `void` in case if `callback` + * provided. + */ removeMemberships(parameters, callback) { return __awaiter(this, void 0, void 0, function* () { var _a; @@ -213,6 +409,22 @@ class PubNubObjects { return this.sendRequest(request); }); } + // endregion + // endregion + // -------------------------------------------------------- + // --------------------- Deprecated API ------------------- + // -------------------------------------------------------- + // region Deprecated + /** + * Fetch paginated list of specific Space members or specific User memberships. + * + * @param parameters - Request configuration parameters. + * @param [callback] - Request completion handler callback. + * + * @returns Asynchronous get specific Space members or specific User memberships response. + * + * @deprecated Use {@link PubNubObjects#getChannelMembers} or {@link PubNubObjects#getMemberships} methods instead. + */ fetchMemberships(parameters, callback) { return __awaiter(this, void 0, void 0, function* () { var _a, _b; @@ -228,6 +440,7 @@ class PubNubObjects { ? Object.fromEntries(Object.entries(spaceParameters.sort).map(([key, value]) => [key.replace('user', 'uuid'), value])) : undefined, }; + // Map Members object to the older version. const mapMembers = (response) => ({ status: response.status, data: response.data.map((members) => ({ @@ -257,6 +470,7 @@ class PubNubObjects { ? Object.fromEntries(Object.entries(userParameters.sort).map(([key, value]) => [key.replace('space', 'channel'), value])) : undefined, }; + // Map Memberships object to the older version. const mapMemberships = (response) => ({ status: response.status, data: response.data.map((membership) => ({ @@ -276,6 +490,17 @@ class PubNubObjects { return this.getMemberships(mappedParameters).then(mapMemberships); }); } + /** + * Add members to specific Space or memberships specific User. + * + * @param parameters - Request configuration parameters. + * @param [callback] - Request completion handler callback. + * + * @returns Asynchronous add members to specific Space or memberships specific User response or + * `void` in case if `callback` provided. + * + * @deprecated Use {@link PubNubObjects#setChannelMembers} or {@link PubNubObjects#setMemberships} methods instead. + */ addMemberships(parameters, callback) { return __awaiter(this, void 0, void 0, function* () { var _a, _b, _c, _d, _e, _f; diff --git a/lib/core/pubnub-push.js b/lib/core/pubnub-push.js index 94f135a9c..3fa4911f4 100644 --- a/lib/core/pubnub-push.js +++ b/lib/core/pubnub-push.js @@ -1,4 +1,7 @@ "use strict"; +/** + * PubNub Push Notifications API module. + */ var __awaiter = (this && this.__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) { @@ -14,10 +17,20 @@ const list_push_channels_1 = require("./endpoints/push/list_push_channels"); const add_push_channels_1 = require("./endpoints/push/add_push_channels"); const remove_device_1 = require("./endpoints/push/remove_device"); class PubNubPushNotifications { - constructor(keySet, sendRequest) { + constructor(keySet, + /* eslint-disable @typescript-eslint/no-explicit-any */ + sendRequest) { this.keySet = keySet; this.sendRequest = sendRequest; } + /** + * Fetch device's push notification enabled channels. + * + * @param parameters - Request configuration parameters. + * @param [callback] - Request completion handler callback. + * + * @returns Asynchronous get device channels response or `void` in case if `callback` provided. + */ listChannels(parameters, callback) { return __awaiter(this, void 0, void 0, function* () { const request = new list_push_channels_1.ListDevicePushNotificationChannelsRequest(Object.assign(Object.assign({}, parameters), { keySet: this.keySet })); @@ -26,6 +39,12 @@ class PubNubPushNotifications { return this.sendRequest(request); }); } + /** + * Enable push notifications on channels for device. + * + * @param parameters - Request configuration parameters. + * @param [callback] - Request completion handler callback. + */ addChannels(parameters, callback) { return __awaiter(this, void 0, void 0, function* () { const request = new add_push_channels_1.AddDevicePushNotificationChannelsRequest(Object.assign(Object.assign({}, parameters), { keySet: this.keySet })); @@ -34,6 +53,12 @@ class PubNubPushNotifications { return this.sendRequest(request); }); } + /** + * Disable push notifications on channels for device. + * + * @param parameters - Request configuration parameters. + * @param [callback] - Request completion handler callback. + */ removeChannels(parameters, callback) { return __awaiter(this, void 0, void 0, function* () { const request = new remove_push_channels_1.RemoveDevicePushNotificationChannelsRequest(Object.assign(Object.assign({}, parameters), { keySet: this.keySet })); @@ -42,6 +67,12 @@ class PubNubPushNotifications { return this.sendRequest(request); }); } + /** + * Disable push notifications for device. + * + * @param parameters - Request configuration parameters. + * @param [callback] - Request completion handler callback. + */ deleteDevice(parameters, callback) { return __awaiter(this, void 0, void 0, function* () { const request = new remove_device_1.RemoveDevicePushNotificationRequest(Object.assign(Object.assign({}, parameters), { keySet: this.keySet })); diff --git a/lib/core/types/api/access-panager.js b/lib/core/types/api/access-panager.js index c8ad2e549..5bff3536a 100644 --- a/lib/core/types/api/access-panager.js +++ b/lib/core/types/api/access-panager.js @@ -1,2 +1,4 @@ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); +// endregion +// endregion diff --git a/lib/core/types/api/app-context.js b/lib/core/types/api/app-context.js index c8ad2e549..6c5bae6f7 100644 --- a/lib/core/types/api/app-context.js +++ b/lib/core/types/api/app-context.js @@ -1,2 +1,3 @@ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); +// endregion diff --git a/lib/core/types/api/file-sharing.js b/lib/core/types/api/file-sharing.js index c8ad2e549..35c8b7c01 100644 --- a/lib/core/types/api/file-sharing.js +++ b/lib/core/types/api/file-sharing.js @@ -1,2 +1,6 @@ "use strict"; +/** + * File Sharing REST API module. + */ Object.defineProperty(exports, "__esModule", { value: true }); +// endregion diff --git a/lib/core/types/api/history.js b/lib/core/types/api/history.js index 82e074734..1653ae13f 100644 --- a/lib/core/types/api/history.js +++ b/lib/core/types/api/history.js @@ -1,8 +1,25 @@ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.PubNubMessageType = void 0; +// endregion +// -------------------------------------------------------- +// -------------------- Fetch Messages -------------------- +// -------------------------------------------------------- +// region Fetch Messages +/** + * PubNub-defined message type. + * + * Types of messages which can be retrieved with fetch messages REST API. + */ var PubNubMessageType; (function (PubNubMessageType) { + /** + * Regular message. + */ PubNubMessageType[PubNubMessageType["Message"] = -1] = "Message"; + /** + * File message. + */ PubNubMessageType[PubNubMessageType["Files"] = 4] = "Files"; })(PubNubMessageType || (exports.PubNubMessageType = PubNubMessageType = {})); +// endregion diff --git a/lib/core/types/api/index.js b/lib/core/types/api/index.js index c8ad2e549..91a2a321b 100644 --- a/lib/core/types/api/index.js +++ b/lib/core/types/api/index.js @@ -1,2 +1,3 @@ "use strict"; +// PubNub client API common types. Object.defineProperty(exports, "__esModule", { value: true }); diff --git a/lib/core/types/api/presence.js b/lib/core/types/api/presence.js index c8ad2e549..6c5bae6f7 100644 --- a/lib/core/types/api/presence.js +++ b/lib/core/types/api/presence.js @@ -1,2 +1,3 @@ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); +// endregion diff --git a/lib/core/types/api/push.js b/lib/core/types/api/push.js index c8ad2e549..6c5bae6f7 100644 --- a/lib/core/types/api/push.js +++ b/lib/core/types/api/push.js @@ -1,2 +1,3 @@ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); +// endregion diff --git a/lib/core/types/file.js b/lib/core/types/file.js index c8ad2e549..6e7b7d2bf 100644 --- a/lib/core/types/file.js +++ b/lib/core/types/file.js @@ -1,2 +1,5 @@ "use strict"; +/** + * {@link PubNub} File object interface module. + */ Object.defineProperty(exports, "__esModule", { value: true }); diff --git a/lib/core/types/transport-request.js b/lib/core/types/transport-request.js index d24afce7b..f72b28210 100644 --- a/lib/core/types/transport-request.js +++ b/lib/core/types/transport-request.js @@ -1,11 +1,33 @@ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.TransportMethod = void 0; +/** + * Enum representing possible transport methods for HTTP requests. + * + * @enum {number} + */ var TransportMethod; (function (TransportMethod) { + /** + * Request will be sent using `GET` method. + */ TransportMethod["GET"] = "GET"; + /** + * Request will be sent using `POST` method. + */ TransportMethod["POST"] = "POST"; + /** + * Request will be sent using `PATCH` method. + */ TransportMethod["PATCH"] = "PATCH"; + /** + * Request will be sent using `DELETE` method. + */ TransportMethod["DELETE"] = "DELETE"; + /** + * Local request. + * + * Request won't be sent to the service and probably used to compute URL. + */ TransportMethod["LOCAL"] = "LOCAL"; })(TransportMethod || (exports.TransportMethod = TransportMethod = {})); diff --git a/lib/core/utils.js b/lib/core/utils.js index 512d80040..bb200b5c0 100644 --- a/lib/core/utils.js +++ b/lib/core/utils.js @@ -1,10 +1,28 @@ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.queryStringFromObject = exports.findUniqueCommonElements = exports.removeSingleOccurrence = exports.encodeNames = exports.encodeString = void 0; +/** + * Percent-encode input string. + * + * **Note:** Encode content in accordance of the `PubNub` service requirements. + * + * @param input - Source string or number for encoding. + * + * @returns Percent-encoded string. + */ const encodeString = (input) => { return encodeURIComponent(input).replace(/[!~*'()]/g, (x) => `%${x.charCodeAt(0).toString(16).toUpperCase()}`); }; exports.encodeString = encodeString; +/** + * Percent-encode list of names (channels). + * + * @param names - List of names which should be encoded. + * + * @param [defaultString] - String which should be used in case if {@link names} is empty. + * + * @returns String which contains encoded names joined by non-encoded `,`. + */ const encodeNames = (names, defaultString) => { const encodedNames = names.map((name) => (0, exports.encodeString)(name)); return encodedNames.length ? encodedNames.join(',') : defaultString !== null && defaultString !== void 0 ? defaultString : ''; @@ -25,6 +43,13 @@ const findUniqueCommonElements = (a, b) => { return [...a].filter((value) => b.includes(value) && a.indexOf(value) === a.lastIndexOf(value) && b.indexOf(value) === b.lastIndexOf(value)); }; exports.findUniqueCommonElements = findUniqueCommonElements; +/** + * Transform query key / value pairs to the string. + * + * @param query - Key / value pairs of the request query parameters. + * + * @returns Stringified query key / value pairs. + */ const queryStringFromObject = (query) => { return Object.keys(query) .map((key) => { diff --git a/lib/crypto/index.js b/lib/crypto/index.js index 3918c74e4..1e44d895d 100644 --- a/lib/crypto/index.js +++ b/lib/crypto/index.js @@ -1 +1,2 @@ "use strict"; +/** */ diff --git a/lib/crypto/modules/NodeCryptoModule/ICryptor.js b/lib/crypto/modules/NodeCryptoModule/ICryptor.js index c8ad2e549..e932a515b 100644 --- a/lib/crypto/modules/NodeCryptoModule/ICryptor.js +++ b/lib/crypto/modules/NodeCryptoModule/ICryptor.js @@ -1,2 +1,5 @@ "use strict"; +/** + * Cryptor module. + */ Object.defineProperty(exports, "__esModule", { value: true }); diff --git a/lib/crypto/modules/NodeCryptoModule/ILegacyCryptor.js b/lib/crypto/modules/NodeCryptoModule/ILegacyCryptor.js index c8ad2e549..afefd5492 100644 --- a/lib/crypto/modules/NodeCryptoModule/ILegacyCryptor.js +++ b/lib/crypto/modules/NodeCryptoModule/ILegacyCryptor.js @@ -1,2 +1,5 @@ "use strict"; +/** + * Legacy cryptor module. + */ Object.defineProperty(exports, "__esModule", { value: true }); diff --git a/lib/crypto/modules/NodeCryptoModule/aesCbcCryptor.js b/lib/crypto/modules/NodeCryptoModule/aesCbcCryptor.js index c03ba9b34..b4f71ecd1 100644 --- a/lib/crypto/modules/NodeCryptoModule/aesCbcCryptor.js +++ b/lib/crypto/modules/NodeCryptoModule/aesCbcCryptor.js @@ -1,4 +1,7 @@ "use strict"; +/** + * AES-CBC cryptor module. + */ var __awaiter = (this && this.__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) { @@ -11,10 +14,19 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge Object.defineProperty(exports, "__esModule", { value: true }); const crypto_1 = require("crypto"); const stream_1 = require("stream"); +/** + * AES-CBC cryptor. + * + * AES-CBC cryptor with enhanced cipher strength. + */ class AesCbcCryptor { constructor({ cipherKey }) { this.cipherKey = cipherKey; } + // -------------------------------------------------------- + // --------------------- Encryption ----------------------- + // -------------------------------------------------------- + // region Encryption encrypt(data) { const iv = this.getIv(); const key = this.getKey(); @@ -43,6 +55,11 @@ class AesCbcCryptor { }; }); } + // endregion + // -------------------------------------------------------- + // --------------------- Decryption ----------------------- + // -------------------------------------------------------- + // region Decryption decrypt(input) { const data = typeof input.data === 'string' ? new TextEncoder().encode(input.data) : input.data; if (data.byteLength <= 0) @@ -84,21 +101,47 @@ class AesCbcCryptor { return decryptedStream; }); } + // endregion + // -------------------------------------------------------- + // ----------------------- Helpers ------------------------ + // -------------------------------------------------------- + // region Helpers get identifier() { return 'ACRH'; } + /** + * Cryptor algorithm. + * + * @returns Cryptor module algorithm. + */ get algo() { return 'aes-256-cbc'; } + /** + * Generate random initialization vector. + * + * @returns Random initialization vector. + */ getIv() { return (0, crypto_1.randomBytes)(AesCbcCryptor.BLOCK_SIZE); } + /** + * Convert cipher key to the {@link Buffer}. + * + * @returns SHA256 encoded cipher key {@link Buffer}. + */ getKey() { const sha = (0, crypto_1.createHash)('sha256'); sha.update(Buffer.from(this.cipherKey, 'utf8')); return Buffer.from(sha.digest()); } } +/** + * Cryptor block size. + */ AesCbcCryptor.BLOCK_SIZE = 16; +/** + * {@link string|String} to {@link ArrayBuffer} response decoder. + */ AesCbcCryptor.encoder = new TextEncoder(); exports.default = AesCbcCryptor; diff --git a/lib/crypto/modules/NodeCryptoModule/legacyCryptor.js b/lib/crypto/modules/NodeCryptoModule/legacyCryptor.js index e1c348040..a175eab75 100644 --- a/lib/crypto/modules/NodeCryptoModule/legacyCryptor.js +++ b/lib/crypto/modules/NodeCryptoModule/legacyCryptor.js @@ -1,4 +1,7 @@ "use strict"; +/** + * Legacy cryptor module. + */ var __awaiter = (this && this.__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) { @@ -16,12 +19,19 @@ const index_1 = __importDefault(require("../../../core/components/cryptography/i const base64_codec_1 = require("../../../core/components/base64_codec"); const pubnub_error_1 = require("../../../errors/pubnub-error"); const node_1 = __importDefault(require("../node")); +/** + * Legacy cryptor. + */ class LegacyCryptor { constructor(config) { this.config = config; this.cryptor = new index_1.default(Object.assign({}, config)); this.fileCryptor = new node_1.default(); } + // -------------------------------------------------------- + // --------------------- Encryption ----------------------- + // -------------------------------------------------------- + // region Encryption encrypt(data) { if (data.length === 0) throw new Error('Encryption error: empty content'); @@ -37,6 +47,11 @@ class LegacyCryptor { return this.fileCryptor.encryptFile(this.config.cipherKey, file, File); }); } + // endregion + // -------------------------------------------------------- + // --------------------- Decryption ----------------------- + // -------------------------------------------------------- + // region Decryption decrypt(encryptedData) { const data = typeof encryptedData.data === 'string' ? encryptedData.data : (0, base64_codec_1.encode)(encryptedData.data); return this.cryptor.decrypt(data); @@ -48,6 +63,11 @@ class LegacyCryptor { return this.fileCryptor.decryptFile(this.config.cipherKey, file, File); }); } + // endregion + // -------------------------------------------------------- + // ----------------------- Helpers ------------------------ + // -------------------------------------------------------- + // region Helpers get identifier() { return ''; } diff --git a/lib/crypto/modules/NodeCryptoModule/nodeCryptoModule.js b/lib/crypto/modules/NodeCryptoModule/nodeCryptoModule.js index bebd0de80..90e155a27 100644 --- a/lib/crypto/modules/NodeCryptoModule/nodeCryptoModule.js +++ b/lib/crypto/modules/NodeCryptoModule/nodeCryptoModule.js @@ -1,4 +1,7 @@ "use strict"; +/** + * Node.js crypto module. + */ var __awaiter = (this && this.__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) { @@ -22,7 +25,14 @@ const aesCbcCryptor_1 = __importDefault(require("./aesCbcCryptor")); exports.AesCbcCryptor = aesCbcCryptor_1.default; const legacyCryptor_1 = __importDefault(require("./legacyCryptor")); exports.LegacyCryptor = legacyCryptor_1.default; +/** + * CryptoModule for Node.js platform. + */ class CryptoModule extends crypto_module_1.AbstractCryptoModule { + // -------------------------------------------------------- + // --------------- Convenience functions ------------------ + // ------------------------------------------------------- + // region Convenience functions static legacyCryptoModule(config) { var _a; if (!config.cipherKey) @@ -43,16 +53,30 @@ class CryptoModule extends crypto_module_1.AbstractCryptoModule { ], }); } + /** + * Construct crypto module with `cryptor` as default for data encryption and decryption. + * + * @param defaultCryptor - Default cryptor for data encryption and decryption. + * + * @returns Crypto module with pre-configured default cryptor. + */ static withDefaultCryptor(defaultCryptor) { return new this({ default: defaultCryptor }); } + // endregion + // -------------------------------------------------------- + // --------------------- Encryption ----------------------- + // -------------------------------------------------------- + // region Encryption encrypt(data) { + // Encrypt data. const encrypted = data instanceof ArrayBuffer && this.defaultCryptor.identifier === CryptoModule.LEGACY_IDENTIFIER ? this.defaultCryptor.encrypt(CryptoModule.decoder.decode(data)) : this.defaultCryptor.encrypt(data); if (!encrypted.metadata) return encrypted.data; const headerData = this.getHeaderData(encrypted); + // Write encrypted data payload content. const encryptedData = typeof encrypted.data === 'string' ? CryptoModule.encoder.encode(encrypted.data).buffer : encrypted.data.buffer.slice(encrypted.data.byteOffset, encrypted.data.byteOffset + encrypted.data.length); @@ -60,6 +84,10 @@ class CryptoModule extends crypto_module_1.AbstractCryptoModule { } encryptFile(file, File) { return __awaiter(this, void 0, void 0, function* () { + /** + * Files handled differently in case of Legacy cryptor. + * (as long as we support legacy need to check on instance type) + */ if (this.defaultCryptor.identifier === CryptorHeader.LEGACY_IDENTIFIER) return this.defaultCryptor.encryptFile(file, File); if (file.data instanceof buffer_1.Buffer) { @@ -95,6 +123,11 @@ class CryptoModule extends crypto_module_1.AbstractCryptoModule { } }); } + // endregion + // -------------------------------------------------------- + // --------------------- Decryption ----------------------- + // -------------------------------------------------------- + // region Decryption decrypt(data) { const encryptedData = buffer_1.Buffer.from(typeof data === 'string' ? (0, base64_codec_1.decode)(data) : data); const header = CryptorHeader.tryParse(encryptedData.buffer.slice(encryptedData.byteOffset, encryptedData.byteOffset + encryptedData.length)); @@ -114,6 +147,10 @@ class CryptoModule extends crypto_module_1.AbstractCryptoModule { if (file.data && file.data instanceof buffer_1.Buffer) { const header = CryptorHeader.tryParse(file.data.buffer.slice(file.data.byteOffset, file.data.byteOffset + file.data.length)); const cryptor = this.getCryptor(header); + /** + * If It's legacy one then redirect it. + * (as long as we support legacy need to check on instance type) + */ if ((cryptor === null || cryptor === void 0 ? void 0 : cryptor.identifier) === CryptoModule.LEGACY_IDENTIFIER) return cryptor.decryptFile(file, File); return File.create({ @@ -129,15 +166,43 @@ class CryptoModule extends crypto_module_1.AbstractCryptoModule { } }); } + // endregion + // -------------------------------------------------------- + // ----------------------- Helpers ------------------------ + // -------------------------------------------------------- + // region Helpers + /** + * Retrieve registered legacy cryptor. + * + * @returns Previously registered {@link ILegacyCryptor|legacy} cryptor. + * + * @throws Error if legacy cryptor not registered. + */ getLegacyCryptor() { return this.getCryptorFromId(CryptoModule.LEGACY_IDENTIFIER); } + /** + * Retrieve registered cryptor by its identifier. + * + * @param id - Unique cryptor identifier. + * + * @returns Registered cryptor with specified identifier. + * + * @throws Error if cryptor with specified {@link id} can't be found. + */ getCryptorFromId(id) { const cryptor = this.getAllCryptors().find((cryptor) => id === cryptor.identifier); if (cryptor) return cryptor; throw new Error('Unknown cryptor error'); } + /** + * Retrieve cryptor by its identifier. + * + * @param header - Header with cryptor-defined data or raw cryptor identifier. + * + * @returns Cryptor which correspond to provided {@link header}. + */ getCryptor(header) { if (typeof header === 'string') { const cryptor = this.getAllCryptors().find((c) => c.identifier === header); @@ -149,6 +214,13 @@ class CryptoModule extends crypto_module_1.AbstractCryptoModule { return this.getCryptorFromId(header.identifier); } } + /** + * Create cryptor header data. + * + * @param encrypted - Encryption data object as source for header data. + * + * @returns Binary representation of the cryptor header data. + */ getHeaderData(encrypted) { if (!encrypted.metadata) return; @@ -160,12 +232,31 @@ class CryptoModule extends crypto_module_1.AbstractCryptoModule { headerData.set(new Uint8Array(encrypted.metadata), pos); return headerData.buffer; } + /** + * Merge two {@link ArrayBuffer} instances. + * + * @param ab1 - First {@link ArrayBuffer}. + * @param ab2 - Second {@link ArrayBuffer}. + * + * @returns Merged data as {@link ArrayBuffer}. + */ concatArrayBuffer(ab1, ab2) { const tmp = new Uint8Array(ab1.byteLength + ab2.byteLength); tmp.set(new Uint8Array(ab1), 0); tmp.set(new Uint8Array(ab2), ab1.byteLength); return tmp.buffer; } + /** + * {@link Readable} stream event handler. + * + * @param stream - Stream which can be used to read data for decryption. + * @param file - File object which has been created with {@link stream}. + * @param File - Class constructor for {@link PubNub} File object. + * + * @returns Decrypted data as {@link PubNub} File object. + * + * @throws Error if file is empty or contains unsupported data type. + */ onStreamReadable(stream, file, File) { return __awaiter(this, void 0, void 0, function* () { stream.removeAllListeners('readable'); @@ -193,6 +284,17 @@ class CryptoModule extends crypto_module_1.AbstractCryptoModule { }); }); } + /** + * Decrypt {@link Readable} stream using legacy cryptor. + * + * @param stream - Stream which can be used to read data for decryption. + * @param file - File object which has been created with {@link stream}. + * @param File - Class constructor for {@link PubNub} File object. + * + * @returns Decrypted data as {@link PubNub} File object. + * + * @throws Error if file is empty or contains unsupported data type. + */ decryptLegacyFileStream(stream, file, File) { return __awaiter(this, void 0, void 0, function* () { if (!file.contentLength || file.contentLength <= 16) @@ -210,7 +312,13 @@ class CryptoModule extends crypto_module_1.AbstractCryptoModule { } } exports.CryptoModule = CryptoModule; +/** + * {@link LegacyCryptor|Legacy} cryptor identifier. + */ CryptoModule.LEGACY_IDENTIFIER = ''; +/** + * CryptorHeader Utility + */ class CryptorHeader { static from(id, metadata) { if (id === CryptorHeader.LEGACY_IDENTIFIER) @@ -283,6 +391,9 @@ CryptorHeader.IDENTIFIER_LENGTH = 4; CryptorHeader.VERSION = 1; CryptorHeader.MAX_VERSION = 1; CryptorHeader.MIN_HEADER_LENGTH = 10; +/** + * Cryptor header (v1). + */ class CryptorHeaderV1 { constructor(id, metadataLength) { this._identifier = id; diff --git a/lib/crypto/modules/node.js b/lib/crypto/modules/node.js index 8e7d36a86..55c7865c2 100644 --- a/lib/crypto/modules/node.js +++ b/lib/crypto/modules/node.js @@ -1,4 +1,7 @@ "use strict"; +/** + * Legacy Node.js cryptography module. + */ var __awaiter = (this && this.__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) { @@ -12,7 +15,14 @@ Object.defineProperty(exports, "__esModule", { value: true }); const crypto_1 = require("crypto"); const stream_1 = require("stream"); const buffer_1 = require("buffer"); +/** + * Legacy cryptography implementation for Node.js-based {@link PubNub} client. + */ class NodeCryptography { + // -------------------------------------------------------- + // --------------------- Encryption ----------------------- + // -------------------------------------------------------- + // region Encryption encrypt(key, input) { return __awaiter(this, void 0, void 0, function* () { const bKey = this.getKey(key); @@ -25,11 +35,27 @@ class NodeCryptography { throw new Error('Encryption error: unsupported input format'); }); } + /** + * Encrypt provided source {@link Buffer} using specific encryption {@link key}. + * + * @param key - Data encryption key.
**Note:** Same key should be used to `decrypt` {@link Buffer}. + * @param buffer - Source {@link Buffer} for encryption. + * + * @returns Encrypted data as {@link Buffer} object. + */ encryptBuffer(key, buffer) { const bIv = this.getIv(); const aes = (0, crypto_1.createCipheriv)(this.algo, key, bIv); return buffer_1.Buffer.concat([bIv, aes.update(buffer), aes.final()]); } + /** + * Encrypt provided source {@link Readable} stream using specific encryption {@link key}. + * + * @param key - Data encryption key.
**Note:** Same key should be used to `decrypt` {@link Readable} stream. + * @param stream - Source {@link Readable} stream for encryption. + * + * @returns Encrypted data as {@link Transform} object. + */ encryptStream(key, stream) { return __awaiter(this, void 0, void 0, function* () { const bIv = this.getIv(); @@ -48,6 +74,14 @@ class NodeCryptography { })); }); } + /** + * Encrypt provided source {@link string} using specific encryption {@link key}. + * + * @param key - Data encryption key.
**Note:** Same key should be used to `decrypt` {@link string}. + * @param text - Source {@link string} for encryption. + * + * @returns Encrypted data as byte {@link string}. + */ encryptString(key, text) { const bIv = this.getIv(); const bPlaintext = buffer_1.Buffer.from(text); @@ -57,6 +91,9 @@ class NodeCryptography { encryptFile(key, file, File) { return __awaiter(this, void 0, void 0, function* () { const bKey = this.getKey(key); + /** + * Buffer type check also covers `string` which converted to the `Buffer` during file object creation. + */ if (file.data instanceof buffer_1.Buffer) { if (file.data.byteLength <= 0) throw new Error('Encryption error: empty content.'); @@ -78,6 +115,11 @@ class NodeCryptography { throw new Error('Cannot encrypt this file. In Node.js file encryption supports only string, Buffer or Stream.'); }); } + // endregion + // -------------------------------------------------------- + // --------------------- Decryption ----------------------- + // -------------------------------------------------------- + // region Decryption decrypt(key, input) { return __awaiter(this, void 0, void 0, function* () { const bKey = this.getKey(key); @@ -94,6 +136,14 @@ class NodeCryptography { throw new Error('Decryption error: unsupported input format'); }); } + /** + * Decrypt provided encrypted {@link Buffer} using specific decryption {@link key}. + * + * @param key - Data decryption key.
**Note:** Should be the same as used to `encrypt` {@link Buffer}. + * @param buffer - Encrypted {@link Buffer} for decryption. + * + * @returns Decrypted data as {@link Buffer} object. + */ decryptBuffer(key, buffer) { const bIv = buffer.slice(0, NodeCryptography.IV_LENGTH); const bCiphertext = buffer.slice(NodeCryptography.IV_LENGTH); @@ -102,6 +152,14 @@ class NodeCryptography { const aes = (0, crypto_1.createDecipheriv)(this.algo, key, bIv); return buffer_1.Buffer.concat([aes.update(bCiphertext), aes.final()]); } + /** + * Decrypt provided encrypted {@link Readable} stream using specific decryption {@link key}. + * + * @param key - Data decryption key.
**Note:** Should be the same as used to `encrypt` {@link Readable} stream. + * @param stream - Encrypted {@link Readable} stream for decryption. + * + * @returns Decrypted data as {@link Readable} object. + */ decryptStream(key, stream) { let aes = null; const output = new stream_1.PassThrough(); @@ -132,6 +190,14 @@ class NodeCryptography { }); return output; } + /** + * Decrypt provided encrypted {@link string} using specific decryption {@link key}. + * + * @param key - Data decryption key.
**Note:** Should be the same as used to `encrypt` {@link string}. + * @param text - Encrypted {@link string} for decryption. + * + * @returns Decrypted data as byte {@link string}. + */ decryptString(key, text) { const ciphertext = buffer_1.Buffer.from(text); const bIv = ciphertext.slice(0, NodeCryptography.IV_LENGTH); @@ -142,6 +208,9 @@ class NodeCryptography { decryptFile(key, file, File) { return __awaiter(this, void 0, void 0, function* () { const bKey = this.getKey(key); + /** + * Buffer type check also covers `string` which converted to the `Buffer` during file object creation. + */ if (file.data instanceof buffer_1.Buffer) { return File.create({ name: file.name, @@ -159,17 +228,42 @@ class NodeCryptography { throw new Error('Cannot decrypt this file. In Node.js file decryption supports only string, Buffer or Stream.'); }); } + // endregion + // -------------------------------------------------------- + // ----------------------- Helpers ------------------------ + // -------------------------------------------------------- + // region Helpers + /** + * Cryptography algorithm. + * + * @returns Cryptography module algorithm. + */ get algo() { return 'aes-256-cbc'; } + /** + * Convert cipher key to the {@link Buffer}. + * + * @param key - String cipher key. + * + * @returns SHA256 HEX encoded cipher key {@link Buffer}. + */ getKey(key) { const sha = (0, crypto_1.createHash)('sha256'); sha.update(buffer_1.Buffer.from(key, 'utf8')); return buffer_1.Buffer.from(sha.digest('hex').slice(0, 32), 'utf8'); } + /** + * Generate random initialization vector. + * + * @returns Random initialization vector. + */ getIv() { return (0, crypto_1.randomBytes)(NodeCryptography.IV_LENGTH); } } +/** + * Random initialization vector size. + */ NodeCryptography.IV_LENGTH = 16; exports.default = NodeCryptography; diff --git a/lib/errors/pubnub-api-error.js b/lib/errors/pubnub-api-error.js index 193fd3562..1f09b98b7 100644 --- a/lib/errors/pubnub-api-error.js +++ b/lib/errors/pubnub-api-error.js @@ -1,4 +1,7 @@ "use strict"; +/** + * REST API endpoint use error module. + */ var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; @@ -6,13 +9,34 @@ Object.defineProperty(exports, "__esModule", { value: true }); exports.PubNubAPIError = void 0; const categories_1 = __importDefault(require("../core/constants/categories")); const pubnub_error_1 = require("./pubnub-error"); +/** + * PubNub REST API call error. + */ class PubNubAPIError extends Error { + /** + * Construct API from known error object or {@link PubNub} service error response. + * + * @param errorOrResponse - `Error` or service error response object from which error information + * should be extracted. + * @param data - Preprocessed service error response. + * + * @returns `PubNubAPIError` object with known error category and additional information (if + * available). + */ static create(errorOrResponse, data) { if (errorOrResponse instanceof Error) return PubNubAPIError.createFromError(errorOrResponse); else return PubNubAPIError.createFromServiceResponse(errorOrResponse, data); } + /** + * Create API error instance from other error object. + * + * @param error - `Error` object provided by network provider (mostly) or other {@link PubNub} client components. + * + * @returns `PubNubAPIError` object with known error category and additional information (if + * available). + */ static createFromError(error) { let category = categories_1.default.PNUnknownCategory; let message = 'Unknown error'; @@ -65,6 +89,16 @@ class PubNubAPIError extends Error { category = categories_1.default.PNTimeoutCategory; return new PubNubAPIError(message, category, 0, error); } + /** + * Construct API from known {@link PubNub} service error response. + * + * @param response - Service error response object from which error information should be + * extracted. + * @param data - Preprocessed service error response. + * + * @returns `PubNubAPIError` object with known error category and additional information (if + * available). + */ static createFromServiceResponse(response, data) { let category = categories_1.default.PNUnknownCategory; let errorData; @@ -81,6 +115,7 @@ class PubNubAPIError extends Error { category = categories_1.default.PNAccessDeniedCategory; message = 'Access denied'; } + // Try to get more information about error from service response. if (data && data.byteLength > 0) { const decoded = new TextDecoder().decode(data); if (response.headers['content-type'].indexOf('text/javascript') !== -1 || @@ -117,6 +152,14 @@ class PubNubAPIError extends Error { } return new PubNubAPIError(message, category, status, errorData); } + /** + * Construct PubNub endpoint error. + * + * @param message - Short API call error description. + * @param category - Error category. + * @param statusCode - Response HTTP status code. + * @param errorData - Error information. + */ constructor(message, category, statusCode, errorData) { super(message); this.category = category; @@ -124,6 +167,13 @@ class PubNubAPIError extends Error { this.errorData = errorData; this.name = 'PubNubAPIError'; } + /** + * Convert API error object to API callback status object. + * + * @param operation - Request operation during which error happened. + * + * @returns Pre-formatted API callback status object. + */ toStatus(operation) { return { error: true, @@ -133,6 +183,14 @@ class PubNubAPIError extends Error { errorData: this.errorData, }; } + /** + * Convert API error object to PubNub client error object. + * + * @param operation - Request operation during which error happened. + * @param message - Custom error message. + * + * @returns Client-facing pre-formatted endpoint call error. + */ toPubNubError(operation, message) { return new pubnub_error_1.PubNubError(message !== null && message !== void 0 ? message : this.message, this.toStatus(operation)); } diff --git a/lib/event-engine/core/change.js b/lib/event-engine/core/change.js index c8ad2e549..2b5963b5c 100644 --- a/lib/event-engine/core/change.js +++ b/lib/event-engine/core/change.js @@ -1,2 +1,3 @@ "use strict"; +/* eslint-disable @typescript-eslint/no-explicit-any */ Object.defineProperty(exports, "__esModule", { value: true }); diff --git a/lib/event-engine/core/dispatcher.js b/lib/event-engine/core/dispatcher.js index 4cfc94966..2be9c3fdf 100644 --- a/lib/event-engine/core/dispatcher.js +++ b/lib/event-engine/core/dispatcher.js @@ -1,4 +1,5 @@ "use strict"; +/* eslint-disable @typescript-eslint/no-explicit-any */ Object.defineProperty(exports, "__esModule", { value: true }); exports.Dispatcher = void 0; class Dispatcher { diff --git a/lib/event-engine/core/engine.js b/lib/event-engine/core/engine.js index 351df033f..d94c9c482 100644 --- a/lib/event-engine/core/engine.js +++ b/lib/event-engine/core/engine.js @@ -1,4 +1,5 @@ "use strict"; +/* eslint-disable @typescript-eslint/no-explicit-any */ Object.defineProperty(exports, "__esModule", { value: true }); exports.Engine = void 0; const subject_1 = require("../../core/components/subject"); diff --git a/lib/event-engine/core/handler.js b/lib/event-engine/core/handler.js index 88bead570..de66460b8 100644 --- a/lib/event-engine/core/handler.js +++ b/lib/event-engine/core/handler.js @@ -17,6 +17,8 @@ class AsyncHandler extends Handler { } start() { this.asyncFunction(this.payload, this.abortSignal, this.dependencies).catch((error) => { + // console.log('Unhandled error:', error); + // swallow the error }); } cancel() { diff --git a/lib/event-engine/core/retryPolicy.js b/lib/event-engine/core/retryPolicy.js index a038d25c3..f822b4979 100644 --- a/lib/event-engine/core/retryPolicy.js +++ b/lib/event-engine/core/retryPolicy.js @@ -6,6 +6,7 @@ class RetryPolicy { return { delay: configuration.delay, maximumRetry: configuration.maximumRetry, + /* eslint-disable @typescript-eslint/no-explicit-any */ shouldRetry(error, attempt) { var _a; if (((_a = error === null || error === void 0 ? void 0 : error.status) === null || _a === void 0 ? void 0 : _a.statusCode) === 403) { @@ -18,6 +19,7 @@ class RetryPolicy { const delay = (_a = reason.retryAfter) !== null && _a !== void 0 ? _a : this.delay; return (delay + Math.random()) * 1000; }, + /* eslint-disable @typescript-eslint/no-explicit-any */ getGiveupReason(error, attempt) { var _a; if (this.maximumRetry <= attempt) { diff --git a/lib/event-engine/core/state.js b/lib/event-engine/core/state.js index 88c83cf6a..06d02193c 100644 --- a/lib/event-engine/core/state.js +++ b/lib/event-engine/core/state.js @@ -1,4 +1,5 @@ "use strict"; +/* eslint-disable @typescript-eslint/no-explicit-any */ Object.defineProperty(exports, "__esModule", { value: true }); exports.State = void 0; class State { diff --git a/lib/event-engine/core/types.js b/lib/event-engine/core/types.js index 85dc4a919..8d5546c4b 100644 --- a/lib/event-engine/core/types.js +++ b/lib/event-engine/core/types.js @@ -1,4 +1,5 @@ "use strict"; +/* eslint-disable @typescript-eslint/no-explicit-any */ Object.defineProperty(exports, "__esModule", { value: true }); exports.createManagedEffect = exports.createEffect = exports.createEvent = void 0; function createEvent(type, fn) { diff --git a/lib/event-engine/presence/effects.js b/lib/event-engine/presence/effects.js index beab7cbc6..d6f4d5671 100644 --- a/lib/event-engine/presence/effects.js +++ b/lib/event-engine/presence/effects.js @@ -10,6 +10,7 @@ exports.leave = (0, core_1.createEffect)('LEAVE', (channels, groups) => ({ channels, groups, })); +/* eslint-disable @typescript-eslint/no-explicit-any */ exports.emitStatus = (0, core_1.createEffect)('EMIT_STATUS', (status) => status); exports.wait = (0, core_1.createManagedEffect)('WAIT', () => ({})); exports.delayedHeartbeat = (0, core_1.createManagedEffect)('DELAYED_HEARTBEAT', (context) => context); diff --git a/lib/file/modules/node.js b/lib/file/modules/node.js index 5b0c17841..90f4759e6 100644 --- a/lib/file/modules/node.js +++ b/lib/file/modules/node.js @@ -1,4 +1,7 @@ "use strict"; +/** + * Node.js {@link PubNub} File object module. + */ var __awaiter = (this && this.__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) { @@ -16,7 +19,14 @@ const stream_1 = require("stream"); const buffer_1 = require("buffer"); const path_1 = require("path"); const fs_1 = __importDefault(require("fs")); +// endregion +/** + * Node.js implementation for {@link PubNub} File object. + * + * **Important:** Class should implement constructor and class fields from {@link PubNubFileConstructor}. + */ class PubNubFile { + // endregion static create(file) { return new PubNubFile(file); } @@ -36,6 +46,7 @@ class PubNubFile { } else if (data instanceof buffer_1.Buffer) { contentLength = data.length; + // Copy content of the source Buffer. fileData = buffer_1.Buffer.alloc(contentLength); data.copy(fileData); } @@ -63,6 +74,11 @@ class PubNubFile { this.data = fileData; this.name = fileName; } + /** + * Convert {@link PubNub} File object content to {@link Buffer}. + * + * @returns Asynchronous results of conversion to the {@link Buffer}. + */ toBuffer() { return __awaiter(this, void 0, void 0, function* () { if (this.data instanceof buffer_1.Buffer) @@ -76,20 +92,36 @@ class PubNubFile { stream.on('end', () => { resolve(buffer_1.Buffer.concat(chunks)); }); + // Handle any errors during streaming stream.on('error', (error) => reject(error)); }); }); } + /** + * Convert {@link PubNub} File object content to {@link ArrayBuffer}. + * + * @returns Asynchronous results of conversion to the {@link ArrayBuffer}. + */ toArrayBuffer() { return __awaiter(this, void 0, void 0, function* () { return this.toBuffer().then((buffer) => buffer.buffer.slice(buffer.byteOffset, buffer.byteOffset + buffer.length)); }); } + /** + * Convert {@link PubNub} File object content to {@link string}. + * + * @returns Asynchronous results of conversion to the {@link string}. + */ toString() { return __awaiter(this, arguments, void 0, function* (encoding = 'utf8') { return this.toBuffer().then((buffer) => buffer.toString(encoding)); }); } + /** + * Convert {@link PubNub} File object content to {@link Readable} stream. + * + * @returns Asynchronous results of conversion to the {@link Readable} stream. + */ toStream() { return __awaiter(this, void 0, void 0, function* () { if (this.data instanceof stream_1.Readable) { @@ -105,28 +137,68 @@ class PubNubFile { })); }); } + /** + * Convert {@link PubNub} File object content to {@link File}. + * + * @throws Error because {@link File} not available in Node.js environment. + */ toFile() { return __awaiter(this, void 0, void 0, function* () { throw new Error('This feature is only supported in browser environments.'); }); } + /** + * Convert {@link PubNub} File object content to file `Uri`. + * + * @throws Error because file `Uri` not available in Node.js environment. + */ toFileUri() { return __awaiter(this, void 0, void 0, function* () { throw new Error('This feature is only supported in React Native environments.'); }); } + /** + * Convert {@link PubNub} File object content to {@link Blob}. + * + * @throws Error because {@link Blob} not available in Node.js environment. + */ toBlob() { return __awaiter(this, void 0, void 0, function* () { throw new Error('This feature is only supported in browser environments.'); }); } } +// region Class properties +/** + * Whether {@link Blob} data supported by platform or not. + */ PubNubFile.supportsBlob = false; +/** + * Whether {@link File} data supported by platform or not. + */ PubNubFile.supportsFile = false; +/** + * Whether {@link Buffer} data supported by platform or not. + */ PubNubFile.supportsBuffer = true; +/** + * Whether {@link Stream} data supported by platform or not. + */ PubNubFile.supportsStream = true; +/** + * Whether {@link String} data supported by platform or not. + */ PubNubFile.supportsString = true; +/** + * Whether {@link ArrayBuffer} supported by platform or not. + */ PubNubFile.supportsArrayBuffer = true; +/** + * Whether {@link PubNub} File object encryption supported or not. + */ PubNubFile.supportsEncryptFile = true; +/** + * Whether `File Uri` data supported by platform or not. + */ PubNubFile.supportsFileUri = false; exports.default = PubNubFile; diff --git a/lib/file/modules/react-native.js b/lib/file/modules/react-native.js index b66464e3a..4088586dd 100644 --- a/lib/file/modules/react-native.js +++ b/lib/file/modules/react-native.js @@ -1,4 +1,8 @@ "use strict"; +/* global File, FileReader */ +/** + * React Native {@link PubNub} File object module. + */ var __awaiter = (this && this.__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) { @@ -10,7 +14,9 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge }; Object.defineProperty(exports, "__esModule", { value: true }); exports.PubNubFile = void 0; +// endregion class PubNubFile { + // endregion static create(file) { return new PubNubFile(file); } @@ -53,11 +59,24 @@ class PubNubFile { this.data = fileData; this.name = fileName; } + /** + * Convert {@link PubNub} File object content to {@link Buffer}. + * + * @throws Error because {@link Buffer} not available in React Native environment. + */ toBuffer() { return __awaiter(this, void 0, void 0, function* () { throw new Error('This feature is only supported in Node.js environments.'); }); } + /** + * Convert {@link PubNub} File object content to {@link ArrayBuffer}. + * + * @returns Asynchronous results of conversion to the {@link ArrayBuffer}. + * + * @throws Error if provided {@link PubNub} File object content is not supported for this + * operation. + */ toArrayBuffer() { return __awaiter(this, void 0, void 0, function* () { if (this.data && this.data instanceof File) { @@ -88,6 +107,11 @@ class PubNubFile { throw new Error('Unable convert provided file content type to ArrayBuffer'); }); } + /** + * Convert {@link PubNub} File object content to {@link string}. + * + * @returns Asynchronous results of conversion to the {@link string}. + */ toString() { return __awaiter(this, void 0, void 0, function* () { if (this.data && 'uri' in this.data) @@ -107,11 +131,24 @@ class PubNubFile { return this.data.text(); }); } + /** + * Convert {@link PubNub} File object content to {@link Readable} stream. + * + * @throws Error because {@link Readable} stream not available in React Native environment. + */ toStream() { return __awaiter(this, void 0, void 0, function* () { throw new Error('This feature is only supported in Node.js environments.'); }); } + /** + * Convert {@link PubNub} File object content to {@link File}. + * + * @returns Asynchronous results of conversion to the {@link File}. + * + * @throws Error if provided {@link PubNub} File object content is not supported for this + * operation. + */ toFile() { return __awaiter(this, void 0, void 0, function* () { if (this.data instanceof File) @@ -122,6 +159,14 @@ class PubNubFile { return this.data.blob(); }); } + /** + * Convert {@link PubNub} File object content to file `Uri`. + * + * @returns Asynchronous results of conversion to file `Uri`. + * + * @throws Error if provided {@link PubNub} File object content is not supported for this + * operation. + */ toFileUri() { return __awaiter(this, void 0, void 0, function* () { if (this.data && 'uri' in this.data) @@ -129,6 +174,14 @@ class PubNubFile { throw new Error('This file does not contain a file URI'); }); } + /** + * Convert {@link PubNub} File object content to {@link Blob}. + * + * @returns Asynchronous results of conversion to the {@link Blob}. + * + * @throws Error if provided {@link PubNub} File object content is not supported for this + * operation. + */ toBlob() { return __awaiter(this, void 0, void 0, function* () { if (this.data instanceof File) @@ -141,12 +194,37 @@ class PubNubFile { } } exports.PubNubFile = PubNubFile; +// region Class properties +/** + * Whether {@link Blob} data supported by platform or not. + */ PubNubFile.supportsBlob = typeof Blob !== 'undefined'; +/** + * Whether {@link File} data supported by platform or not. + */ PubNubFile.supportsFile = typeof File !== 'undefined'; +/** + * Whether {@link Buffer} data supported by platform or not. + */ PubNubFile.supportsBuffer = false; +/** + * Whether {@link Stream} data supported by platform or not. + */ PubNubFile.supportsStream = false; +/** + * Whether {@link String} data supported by platform or not. + */ PubNubFile.supportsString = true; +/** + * Whether {@link ArrayBuffer} supported by platform or not. + */ PubNubFile.supportsArrayBuffer = true; +/** + * Whether {@link PubNub} File object encryption supported or not. + */ PubNubFile.supportsEncryptFile = false; +/** + * Whether `File Uri` data supported by platform or not. + */ PubNubFile.supportsFileUri = true; exports.default = PubNubFile; diff --git a/lib/node/configuration.js b/lib/node/configuration.js index 2bdbc0ccc..f0dca5397 100644 --- a/lib/node/configuration.js +++ b/lib/node/configuration.js @@ -1,10 +1,31 @@ "use strict"; +/** + * Node.js specific {@link PubNub} client configuration module. + */ Object.defineProperty(exports, "__esModule", { value: true }); exports.setDefaults = void 0; const configuration_1 = require("../core/interfaces/configuration"); +// -------------------------------------------------------- +// ----------------------- Defaults ----------------------- +// -------------------------------------------------------- +// region Defaults +/** + * Whether PubNub client should try utilize existing TCP connection for new requests or not. + */ const KEEP_ALIVE = false; +/** + * Apply configuration default values. + * + * @param configuration - User-provided configuration. + * + * @returns Extended {@link PubNub} client configuration object pre-filled with default values. + * + * @internal + */ const setDefaults = (configuration) => { var _a; - return Object.assign(Object.assign({}, (0, configuration_1.setDefaults)(configuration)), { keepAlive: (_a = configuration.keepAlive) !== null && _a !== void 0 ? _a : KEEP_ALIVE }); + return Object.assign(Object.assign({}, (0, configuration_1.setDefaults)(configuration)), { + // Set platform-specific options. + keepAlive: (_a = configuration.keepAlive) !== null && _a !== void 0 ? _a : KEEP_ALIVE }); }; exports.setDefaults = setDefaults; diff --git a/lib/node/index.js b/lib/node/index.js index 45fb6690c..eed5fb4a0 100644 --- a/lib/node/index.js +++ b/lib/node/index.js @@ -17,10 +17,14 @@ const cryptography_1 = __importDefault(require("../core/components/cryptography" const pubnub_error_1 = require("../errors/pubnub-error"); const pubnub_common_1 = require("../core/pubnub-common"); const common_1 = __importDefault(require("../cbor/common")); +/** + * PubNub client for Node.js platform. + */ class PubNub extends pubnub_common_1.PubNubCore { constructor(configuration) { const configurationCopy = (0, configuration_2.setDefaults)(configuration); const platformConfiguration = Object.assign(Object.assign({}, configurationCopy), { sdkFamily: 'Nodejs', PubNubFile: node_1.default }); + // Prepare full client configuration. const clientConfiguration = (0, configuration_1.makeConfiguration)(platformConfiguration, (cryptoConfiguration) => { if (!cryptoConfiguration.cipherKey) return undefined; @@ -29,7 +33,9 @@ class PubNub extends pubnub_common_1.PubNubCore { cryptors: [new nodeCryptoModule_1.AesCbcCryptor({ cipherKey: cryptoConfiguration.cipherKey })], }); }); + // Prepare Token manager. const tokenManager = new token_manager_1.TokenManager(new common_1.default((buffer) => cbor_sync_1.default.decode(buffer_1.Buffer.from(buffer)), base64_codec_1.decode)); + // Legacy crypto (legacy data encryption / decryption and request signature support). const crypto = new cryptography_1.default({ secretKey: clientConfiguration.secretKey, cipherKey: clientConfiguration.getCipherKey(), @@ -37,6 +43,7 @@ class PubNub extends pubnub_common_1.PubNubCore { customEncrypt: clientConfiguration.getCustomEncrypt(), customDecrypt: clientConfiguration.getCustomDecrypt(), }); + // Setup transport provider. const transport = new node_transport_1.NodeTransport(configuration.keepAlive, configuration.keepAliveSettings); const transportMiddleware = new middleware_1.PubNubMiddleware({ clientConfiguration, @@ -51,9 +58,20 @@ class PubNub extends pubnub_common_1.PubNubCore { tokenManager, crypto, }); + /** + * PubNub File constructor. + */ this.File = node_1.default; this.nodeTransport = transport; } + /** + * Update request proxy configuration. + * + * @param configuration - Updated request proxy configuration. + * + * @throws An error if {@link PubNub} client already configured to use `keepAlive`. + * `keepAlive` and `proxy` can't be used simultaneously. + */ setProxy(configuration) { var _a; if (configuration && ((_a = this._configuration.keepAlive) !== null && _a !== void 0 ? _a : false)) @@ -62,5 +80,8 @@ class PubNub extends pubnub_common_1.PubNubCore { this.reconnect(); } } +/** + * Data encryption / decryption module constructor. + */ PubNub.CryptoModule = nodeCryptoModule_1.CryptoModule; module.exports = PubNub; diff --git a/lib/react_native/configuration.js b/lib/react_native/configuration.js index 3d4e24615..c88065595 100644 --- a/lib/react_native/configuration.js +++ b/lib/react_native/configuration.js @@ -2,6 +2,13 @@ Object.defineProperty(exports, "__esModule", { value: true }); exports.setDefaults = void 0; const configuration_1 = require("../core/interfaces/configuration"); +/** + * Apply configuration default values. + * + * @param configuration - User-provided configuration. + * + * @internal + */ const setDefaults = (configuration) => { return (0, configuration_1.setDefaults)(configuration); }; diff --git a/lib/react_native/index.js b/lib/react_native/index.js index 7345921f2..606e5d543 100644 --- a/lib/react_native/index.js +++ b/lib/react_native/index.js @@ -18,15 +18,22 @@ const cryptography_1 = __importDefault(require("../core/components/cryptography" const pubnub_common_1 = require("../core/pubnub-common"); const configuration_2 = require("./configuration"); const common_1 = __importDefault(require("../cbor/common")); +// Polyfill global environment global.TextEncoder = global.TextEncoder || text_encoding_1.TextEncoder; global.TextDecoder = global.TextDecoder || text_encoding_1.TextDecoder; global.Buffer = global.Buffer || buffer_1.Buffer; +/** + * PubNub client for React Native platform. + */ class PubNub extends pubnub_common_1.PubNubCore { constructor(configuration) { const configurationCopy = (0, configuration_2.setDefaults)(configuration); const platformConfiguration = Object.assign(Object.assign({}, configurationCopy), { sdkFamily: 'ReactNative', PubNubFile: react_native_1.default }); + // Prepare full client configuration. const clientConfiguration = (0, configuration_1.makeConfiguration)(platformConfiguration); + // Prepare Token manager. const tokenManager = new token_manager_1.TokenManager(new common_1.default((arrayBuffer) => (0, stringify_buffer_keys_1.stringifyBufferKeys)(cbor_js_1.default.decode(arrayBuffer)), base64_codec_1.decode)); + // Legacy crypto (legacy data encryption / decryption and request signature support). let crypto; if (clientConfiguration.getCipherKey() || clientConfiguration.secretKey) { crypto = new cryptography_1.default({ @@ -37,6 +44,7 @@ class PubNub extends pubnub_common_1.PubNubCore { customDecrypt: clientConfiguration.getCustomDecrypt(), }); } + // Setup transport layer. const transportMiddleware = new middleware_1.PubNubMiddleware({ clientConfiguration, tokenManager, diff --git a/lib/transport/middleware.js b/lib/transport/middleware.js index 7433a00a1..61519ad44 100644 --- a/lib/transport/middleware.js +++ b/lib/transport/middleware.js @@ -9,6 +9,12 @@ class RequestSignature { this.secretKey = secretKey; this.hasher = hasher; } + /** + * Compute request signature. + * + * @param req - Request which will be used to compute signature. + * @returns {string} `v2` request signature. + */ signature(req) { const method = req.path.startsWith('/publish') ? transport_request_1.TransportMethod.GET : req.method; let signatureInput = `${method}\n${this.publishKey}\n${req.path}\n${this.queryParameters(req.queryParameters)}\n`; @@ -29,6 +35,12 @@ class RequestSignature { .replace(/\//g, '_') .replace(/=+$/, ''); } + /** + * Prepare request query parameters for signature. + * + * @param query - Key / value pair of the request query parameters. + * @private + */ queryParameters(query) { return Object.keys(query) .sort() @@ -59,9 +71,11 @@ class PubNubMiddleware { request(req) { var _a; const { clientConfiguration } = this.configuration; + // Get request patched by transport provider. req = this.configuration.transport.request(req); if (!req.queryParameters) req.queryParameters = {}; + // Modify request with required information. if (clientConfiguration.useInstanceId) req.queryParameters['instanceid'] = clientConfiguration.instanceId; if (!req.queryParameters['uuid']) @@ -70,12 +84,15 @@ class PubNubMiddleware { req.queryParameters['requestid'] = req.identifier; req.queryParameters['pnsdk'] = this.generatePNSDK(); (_a = req.origin) !== null && _a !== void 0 ? _a : (req.origin = clientConfiguration.origin); + // Authenticate request if required. this.authenticateRequest(req); + // Sign request if it is required. this.signRequest(req); return req; } authenticateRequest(req) { var _a; + // Access management endpoints doesn't need authentication (signature required instead). if (req.path.startsWith('/v2/auth/') || req.path.startsWith('/v3/pam/') || req.path.startsWith('/time')) return; const { clientConfiguration, tokenManager } = this.configuration; @@ -83,12 +100,25 @@ class PubNubMiddleware { if (accessKey) req.queryParameters['auth'] = accessKey; } + /** + * Compute and append request signature. + * + * @param req - Transport request with information which should be used to generate signature. + */ signRequest(req) { if (!this.signatureGenerator || req.path.startsWith('/time')) return; req.queryParameters['timestamp'] = String(Math.floor(new Date().getTime() / 1000)); req.queryParameters['signature'] = this.signatureGenerator.signature(req); } + /** + * Compose `pnsdk` query parameter. + * + * SDK provides ability to set custom name or append vendor information to the `pnsdk` query + * parameter. + * + * @returns Finalized `pnsdk` query parameter value. + */ generatePNSDK() { const { clientConfiguration } = this.configuration; if (clientConfiguration.sdkName) diff --git a/lib/transport/node-transport.js b/lib/transport/node-transport.js index 80418e7c2..95a8b911b 100644 --- a/lib/transport/node-transport.js +++ b/lib/transport/node-transport.js @@ -44,12 +44,29 @@ const form_data_1 = __importDefault(require("form-data")); const buffer_1 = require("buffer"); const pubnub_api_error_1 = require("../errors/pubnub-api-error"); const utils_1 = require("../core/utils"); +/** + * Class representing a fetch-based Node.js transport provider. + */ class NodeTransport { + /** + * Creates a new `fetch`-based transport instance. + * + * @param keepAlive - Indicates whether keep-alive should be enabled. + * @param [keepAliveSettings] - Optional settings for keep-alive. + * @param [logVerbosity] - Whether verbose logging enabled or not. + * + * @returns Transport for performing network requests. + */ constructor(keepAlive = false, keepAliveSettings = { timeout: 30000 }, logVerbosity = false) { this.keepAlive = keepAlive; this.keepAliveSettings = keepAliveSettings; this.logVerbosity = logVerbosity; } + /** + * Update request proxy configuration. + * + * @param configuration - New proxy configuration. + */ setProxy(configuration) { this.proxyConfiguration = configuration; } @@ -59,6 +76,7 @@ class NodeTransport { if (req.cancellable) { abortController = new AbortController(); controller = { + // Storing controller inside to prolong object lifetime. abortController, abort: () => abortController === null || abortController === void 0 ? void 0 : abortController.abort(), }; @@ -76,6 +94,7 @@ class NodeTransport { const responseBody = response[1].byteLength > 0 ? response[1] : undefined; const { status, headers: requestHeaders } = response[0]; const headers = {}; + // Copy Headers object content into plain Record. requestHeaders.forEach((value, key) => (headers[key] = value.toLowerCase())); const transportResponse = { status, @@ -98,12 +117,21 @@ class NodeTransport { request(req) { return req; } + /** + * Creates a Request object from a given {@link TransportRequest} object. + * + * @param req - The {@link TransportRequest} object containing request information. + * + * @returns Request object generated from the {@link TransportRequest} object. + */ requestFromTransportRequest(req) { return __awaiter(this, void 0, void 0, function* () { let headers = req.headers; let body; let path = req.path; + // Create multipart request body. if (req.formData && req.formData.length > 0) { + // Reset query parameters to conform to signed URL req.queryParameters = {}; const file = req.body; const fileData = yield file.toArrayBuffer(); @@ -114,6 +142,7 @@ class NodeTransport { body = formData; headers = formData.getHeaders(headers !== null && headers !== void 0 ? headers : {}); } + // Handle regular body payload (if passed). else if (req.body && (typeof req.body === 'string' || req.body instanceof ArrayBuffer)) body = req.body; if (req.queryParameters && Object.keys(req.queryParameters).length !== 0) @@ -127,11 +156,24 @@ class NodeTransport { }); }); } + /** + * Determines and returns the appropriate agent for a given transport request. + * + * If keep alive is not requested, returns undefined. + * + * @param req - The transport request object. + * + * @returns {HttpAgent | HttpsAgent | undefined} - The appropriate agent for the request, or + * undefined if keep alive or proxy not requested. + */ agentForTransportRequest(req) { + // Don't configure any agents if keep alive not requested. if (!this.keepAlive && !this.proxyConfiguration) return undefined; + // Create proxy agent (if possible). if (this.proxyConfiguration) return this.proxyAgent ? this.proxyAgent : (this.proxyAgent = new proxy_agent_1.ProxyAgent(this.proxyConfiguration)); + // Create keep alive agent. const useSecureAgent = req.origin.startsWith('https:'); if (useSecureAgent && this.httpsAgent === undefined) this.httpsAgent = new https_1.Agent(Object.assign({ keepAlive: true }, this.keepAliveSettings)); @@ -140,6 +182,13 @@ class NodeTransport { } return useSecureAgent ? this.httpsAgent : this.httpAgent; } + /** + * Log out request processing progress and result. + * + * @param request - Platform-specific request object. + * @param [elapsed] - How many times passed since request processing started. + * @param [body] - Service response (if available). + */ logRequestProcessProgress(request, elapsed, body) { if (!this.logVerbosity) return; @@ -159,4 +208,7 @@ class NodeTransport { } } exports.NodeTransport = NodeTransport; +/** + * Service {@link ArrayBuffer} response decoder. + */ NodeTransport.decoder = new TextDecoder(); diff --git a/lib/transport/web-react-native-transport.js b/lib/transport/web-react-native-transport.js index bf09f69d2..9c18341a2 100644 --- a/lib/transport/web-react-native-transport.js +++ b/lib/transport/web-react-native-transport.js @@ -1,4 +1,7 @@ "use strict"; +/** + * Common browser and React Native Transport provider module. + */ var __awaiter = (this && this.__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) { @@ -12,6 +15,9 @@ Object.defineProperty(exports, "__esModule", { value: true }); exports.WebReactNativeTransport = void 0; const pubnub_api_error_1 = require("../errors/pubnub-api-error"); const utils_1 = require("../core/utils"); +/** + * Class representing a `fetch`-based browser and React Native transport provider. + */ class WebReactNativeTransport { constructor(keepAlive = false, logVerbosity) { this.keepAlive = keepAlive; @@ -23,6 +29,7 @@ class WebReactNativeTransport { if (req.cancellable) { abortController = new AbortController(); controller = { + // Storing controller inside to prolong object lifetime. abortController, abort: () => abortController === null || abortController === void 0 ? void 0 : abortController.abort(), }; @@ -31,8 +38,14 @@ class WebReactNativeTransport { this.requestFromTransportRequest(req).then((request) => { const start = new Date().getTime(); this.logRequestProcessProgress(request); + /** + * Setup request timeout promise. + * + * **Note:** Native Fetch API doesn't support `timeout` out-of-box. + */ const requestTimeout = new Promise((_, reject) => { const timeoutId = setTimeout(() => { + // Clean up. clearTimeout(timeoutId); reject(new Error('Request timeout')); }, req.timeout * 1000); @@ -43,6 +56,7 @@ class WebReactNativeTransport { const responseBody = response[1].byteLength > 0 ? response[1] : undefined; const { status, headers: requestHeaders } = response[0]; const headers = {}; + // Copy Headers object content into plain Record. requestHeaders.forEach((value, key) => (headers[key] = value.toLowerCase())); const transportResponse = { status, @@ -65,11 +79,20 @@ class WebReactNativeTransport { request(req) { return req; } + /** + * Creates a Request object from a given {@link TransportRequest} object. + * + * @param req - The {@link TransportRequest} object containing request information. + * + * @returns Request object generated from the {@link TransportRequest} object. + */ requestFromTransportRequest(req) { return __awaiter(this, void 0, void 0, function* () { let body; let path = req.path; + // Create multipart request body. if (req.formData && req.formData.length > 0) { + // Reset query parameters to conform to signed URL req.queryParameters = {}; const file = req.body; const formData = new FormData(); @@ -82,12 +105,14 @@ class WebReactNativeTransport { catch (_) { try { const fileData = yield file.toFileUri(); + // @ts-expect-error React Native File Uri support. formData.append('file', fileData, file.name); } catch (_) { } } body = formData; } + // Handle regular body payload (if passed). else if (req.body && (typeof req.body === 'string' || req.body instanceof ArrayBuffer)) body = req.body; if (req.queryParameters && Object.keys(req.queryParameters).length !== 0) @@ -100,6 +125,13 @@ class WebReactNativeTransport { }); }); } + /** + * Log out request processing progress and result. + * + * @param request - Platform-specific + * @param [elapsed] - How many seconds passed since request processing started. + * @param [body] - Service response (if available). + */ logRequestProcessProgress(request, elapsed, body) { if (!this.logVerbosity) return; @@ -119,4 +151,7 @@ class WebReactNativeTransport { } } exports.WebReactNativeTransport = WebReactNativeTransport; +/** + * Service {@link ArrayBuffer} response decoder. + */ WebReactNativeTransport.decoder = new TextDecoder(); diff --git a/lib/types/cbor/common.d.ts b/lib/types/cbor/common.d.ts index cb0ff5c3b..4ccbdd2ba 100644 --- a/lib/types/cbor/common.d.ts +++ b/lib/types/cbor/common.d.ts @@ -1 +1,4 @@ +/** + * Cbor decoder module. + */ export {}; diff --git a/lib/types/core/components/configuration.d.ts b/lib/types/core/components/configuration.d.ts index cb0ff5c3b..2fb4a5f80 100644 --- a/lib/types/core/components/configuration.d.ts +++ b/lib/types/core/components/configuration.d.ts @@ -1 +1,4 @@ +/** + * {@link PubNub} client configuration module. + */ export {}; diff --git a/lib/types/core/components/cryptography/index.d.ts b/lib/types/core/components/cryptography/index.d.ts index ff88b48b7..b3f187c0b 100644 --- a/lib/types/core/components/cryptography/index.d.ts +++ b/lib/types/core/components/cryptography/index.d.ts @@ -1,5 +1,11 @@ +/** + * Legacy cryptography module. + */ import { CryptorConfiguration } from '../../interfaces/crypto-module'; import { Payload } from '../../types/api'; +/** + * Legacy cryptor configuration options. + */ type CryptoConfiguration = { encryptKey?: boolean; keyEncoding?: 'hex' | 'utf8' | 'base64' | 'binary'; @@ -8,23 +14,130 @@ type CryptoConfiguration = { }; export default class { private readonly configuration; + /** + * Crypto initialization vector. + */ private iv; + /** + * List os allowed cipher key encodings. + */ private allowedKeyEncodings; + /** + * Allowed cipher key lengths. + */ private allowedKeyLengths; + /** + * Allowed crypto modes. + */ private allowedModes; + /** + * Default cryptor configuration options. + */ private readonly defaultOptions; constructor(configuration: CryptorConfiguration); + /** + * Generate HMAC-SHA256 hash from input data. + * + * @param data - Data from which hash should be generated. + * + * @returns HMAC-SHA256 hash from provided `data`. + */ HMACSHA256(data: string): string; + /** + * Generate SHA256 hash from input data. + * + * @param data - Data from which hash should be generated. + * + * @returns SHA256 hash from provided `data`. + */ SHA256(data: string): string; + /** + * Encrypt provided data. + * + * @param data - Source data which should be encrypted. + * @param [customCipherKey] - Custom cipher key (different from defined on client level). + * @param [options] - Specific crypto configuration options. + * + * @returns Encrypted `data`. + */ encrypt(data: string | Payload, customCipherKey?: string, options?: CryptoConfiguration): string; + /** + * Decrypt provided data. + * + * @param data - Encrypted data which should be decrypted. + * @param [customCipherKey] - Custom cipher key (different from defined on client level). + * @param [options] - Specific crypto configuration options. + * + * @returns Decrypted `data`. + */ decrypt(data: string, customCipherKey?: string, options?: CryptoConfiguration): Payload | null; + /** + * Encrypt provided data. + * + * @param data - Source data which should be encrypted. + * @param [customCipherKey] - Custom cipher key (different from defined on client level). + * @param [options] - Specific crypto configuration options. + * + * @returns Encrypted `data` as string. + */ private pnEncrypt; + /** + * Decrypt provided data. + * + * @param data - Encrypted data which should be decrypted. + * @param [customCipherKey] - Custom cipher key (different from defined on client level). + * @param [options] - Specific crypto configuration options. + * + * @returns Decrypted `data`. + */ private pnDecrypt; + /** + * Pre-process provided custom crypto configuration. + * + * @param incomingOptions - Configuration which should be pre-processed before use. + * + * @returns Normalized crypto configuration options. + */ private parseOptions; + /** + * Decode provided cipher key. + * + * @param key - Key in `encoding` provided by `options`. + * @param options - Crypto configuration options with cipher key details. + * + * @returns Array buffer with decoded key. + */ private decodeKey; + /** + * Add padding to the cipher key. + * + * @param key - Key which should be padded. + * @param options - Crypto configuration options with cipher key details. + * + * @returns Properly padded cipher key. + */ private getPaddedKey; + /** + * Cipher mode. + * + * @param options - Crypto configuration with information about cipher mode. + * + * @returns Crypto cipher mode. + */ private getMode; + /** + * Cipher initialization vector. + * + * @param options - Crypto configuration with information about cipher mode. + * + * @returns Initialization vector. + */ private getIV; + /** + * Random initialization vector. + * + * @returns Generated random initialization vector. + */ private getRandomIV; } export {}; diff --git a/lib/types/core/components/deduping_manager.d.ts b/lib/types/core/components/deduping_manager.d.ts index 121ef9cf6..8c072ad6d 100644 --- a/lib/types/core/components/deduping_manager.d.ts +++ b/lib/types/core/components/deduping_manager.d.ts @@ -1,3 +1,8 @@ +/** + * Real-time events deduplication manager. + * + * @internal + */ export default class _default { constructor({ config }: { config: any; diff --git a/lib/types/core/components/listener_manager.d.ts b/lib/types/core/components/listener_manager.d.ts index fec05ebba..054904377 100644 --- a/lib/types/core/components/listener_manager.d.ts +++ b/lib/types/core/components/listener_manager.d.ts @@ -1,14 +1,76 @@ +/** + * Events listener manager module. + */ import * as Subscription from '../types/api/subscription'; import { Status, StatusEvent } from '../types/api'; +/** + * Real-time events listener. + */ export type Listener = { + /** + * Real-time message events listener. + * + * @param message - Received message. + */ message?: (message: Subscription.Message) => void; + /** + * Real-time message signal listener. + * + * @param signal - Received signal. + */ signal?: (signal: Subscription.Signal) => void; + /** + * Real-time presence change events listener. + * + * @param presence - Received presence chane information. + */ presence?: (presence: Subscription.Presence) => void; + /** + * Real-time App Context Objects change events listener. + * + * @param object - Changed App Context Object information. + */ objects?: (object: Subscription.AppContextObject) => void; + /** + * Real-time message actions events listener. + * + * @param action - Message action information. + */ messageAction?: (action: Subscription.MessageAction) => void; + /** + * Real-time file share events listener. + * + * @param file - Shared file information. + */ file?: (file: Subscription.File) => void; + /** + * Real-time PubNub client status change event. + * + * @param status - PubNub client status information + */ status?: (status: Status | StatusEvent) => void; + /** + * Real-time User App Context Objects change events listener. + * + * @param user - User App Context Object information. + * + * @deprecated Use {@link objects} listener callback instead. + */ user?: (user: Subscription.UserAppContextObject) => void; + /** + * Real-time Space App Context Objects change events listener. + * + * @param space - Space App Context Object information. + * + * @deprecated Use {@link objects} listener callback instead. + */ space?: (space: Subscription.SpaceAppContextObject) => void; + /** + * Real-time VSP Membership App Context Objects change events listener. + * + * @param membership - VSP Membership App Context Object information. + * + * @deprecated Use {@link objects} listener callback instead. + */ membership?: (membership: Subscription.VSPMembershipAppContextObject) => void; }; diff --git a/lib/types/core/components/push_payload.d.ts b/lib/types/core/components/push_payload.d.ts index 30be0cc7c..677843f48 100644 --- a/lib/types/core/components/push_payload.d.ts +++ b/lib/types/core/components/push_payload.d.ts @@ -1,152 +1,632 @@ +/** + * Payload for `pn_apns` field in published message. + */ type APNSPayload = { + /** + * Payload for Apple Push Notification Service. + */ aps: { + /** + * Configuration of visual notification representation. + */ alert?: { + /** + * First line title. + * + * Title which is shown in bold on the first line of notification bubble. + */ title?: string; + /** + * Second line title. + * + * Subtitle which is shown under main title with smaller font. + */ subtitle?: string; + /** + * Notification body. + * + * Body which is shown to the user after interaction with notification. + */ body?: string; }; + /** + * Unread notifications count badge value. + */ badge?: number | null; + /** + * Name of the file from resource bundle which should be played when notification received. + */ sound?: string; + /** + * Silent notification flag. + */ 'content-available'?: 1; }; + /** + * APNS2 payload recipients information. + */ pn_push: PubNubAPNS2Configuration[]; }; +/** + * APNS2 configuration type. + */ type APNS2Configuration = { + /** + * Notification group / collapse identifier. Value will be used in APNS POST request as `apns-collapse-id` header + * value. + */ collapseId?: string; + /** + * Date till which APNS will try to deliver notification to target device. Value will be used in APNS POST request as + * `apns-expiration` header value. + */ expirationDate?: Date; + /** + * List of topics which should receive this notification. + */ targets: APNS2Target[]; }; +/** + * Preformatted for PubNub service `APNS2` configuration type. + */ type PubNubAPNS2Configuration = { + /** + * PubNub service authentication method for APNS. + */ auth_method: 'token'; + /** + * Target entities which should receive notification. + */ targets: PubNubAPNS2Target[]; + /** + * Notifications group collapse identifier. + */ collapse_id?: string; + /** + * Notification receive expiration date. + * + * Date after which notification won't be delivered. + */ expiration?: string; + /** + * APNS protocol version. + */ version: 'v2'; }; +/** + * APNS2 configuration target type. + */ type APNS2Target = { + /** + * Notifications topic name (usually it is bundle identifier of application for Apple platform). + * + * **Important:** Required only if `pushGateway` is set to `apns2`. + */ topic: string; + /** + * Environment within which registered devices to which notifications should be delivered. + * + * Available: + * - `development` + * - `production` + * + * @default `development` + */ environment?: 'development' | 'production'; + /** + * List of devices (their push tokens) to which this notification shouldn't be delivered. + */ excludedDevices?: string[]; }; +/** + * Preformatted for PubNub service `APNS2` configuration target type. + */ type PubNubAPNS2Target = Omit & { + /** + * List of devices (their push tokens) to which this notification shouldn't be delivered. + */ excluded_devices?: string[]; }; +/** + * Payload for `pn_gcm` field in published message. + */ type FCMPayload = { + /** + * Configuration of visual notification representation. + */ notification?: { + /** + * First line title. + * + * Title which is shown in bold on the first line of notification bubble. + */ title?: string; + /** + * Notification body. + * + * Body which is shown to the user after interaction with notification. + */ body?: string; + /** + * Name of the icon file from resource bundle which should be shown on notification. + */ icon?: string; + /** + * Name of the file from resource bundle which should be played when notification received. + */ sound?: string; tag?: string; }; + /** + * Configuration of data notification. + * + * Silent notification configuration. + */ data?: { notification?: FCMPayload['notification']; }; }; +/** + * Base notification payload object. + */ declare class BaseNotificationPayload { + /** + * Notification main title. + */ protected _title?: string; + /** + * Notification second-line title. + */ protected _subtitle?: string; + /** + * Name of the sound which should be played for received notification. + */ protected _sound?: string; + /** + * Value which should be placed on application badge (if required). + */ protected _badge?: number | null; + /** + * Notification main body message. + */ protected _body?: string; + /** + * Object in resulting message where notification payload should be added. + */ protected _payload: unknown; constructor(payload: unknown, title?: string, body?: string); + /** + * Retrieve resulting notification payload content for message. + * + * @returns Preformatted push notification payload data. + */ get payload(): unknown; + /** + * Update notification title. + * + * @param value - New notification title. + */ set title(value: string | undefined); + /** + * Update notification subtitle. + * + * @param value - New second-line notification title. + */ set subtitle(value: string | undefined); + /** + * Update notification body. + * + * @param value - Update main notification message (shown when expanded). + */ set body(value: string | undefined); + /** + * Update application badge number. + * + * @param value - Number which should be shown in application badge upon receiving notification. + */ set badge(value: number | null | undefined); + /** + * Update notification sound. + * + * @param value - Name of the sound file which should be played upon notification receive. + */ set sound(value: string | undefined); + /** + * Platform-specific structure initialization. + */ protected setDefaultPayloadStructure(): void; + /** + * Translate data object into PubNub push notification payload object. + * + * @returns Preformatted push notification payload. + */ toObject(): unknown; } +/** + * Message payload for Apple Push Notification Service. + */ export declare class APNSNotificationPayload extends BaseNotificationPayload { + /** + * List with notification receivers information. + */ private _configurations?; + /** + * Type of push notification service for which payload will be created. + */ private _apnsPushType; + /** + * Whether resulting payload should trigger silent notification or not. + */ private _isSilent; get payload(): APNSPayload; + /** + * Update notification receivers configuration. + * + * @param value - New APNS2 configurations. + */ set configurations(value: APNS2Configuration[]); + /** + * Notification payload. + * + * @returns Platform-specific part of PubNub notification payload. + */ get notification(): { + /** + * Configuration of visual notification representation. + */ alert?: { + /** + * First line title. + * + * Title which is shown in bold on the first line of notification bubble. + */ title?: string | undefined; + /** + * Second line title. + * + * Subtitle which is shown under main title with smaller font. + */ subtitle?: string | undefined; + /** + * Notification body. + * + * Body which is shown to the user after interaction with notification. + */ body?: string | undefined; } | undefined; + /** + * Unread notifications count badge value. + */ badge?: number | null | undefined; + /** + * Name of the file from resource bundle which should be played when notification received. + */ sound?: string | undefined; + /** + * Silent notification flag. + */ 'content-available'?: 1 | undefined; }; + /** + * Notification title. + * + * @returns Main notification title. + */ get title(): string | undefined; + /** + * Update notification title. + * + * @param value - New notification title. + */ set title(value: string | undefined); + /** + * Notification subtitle. + * + * @returns Second-line notification title. + */ get subtitle(): string | undefined; + /** + * Update notification subtitle. + * + * @param value - New second-line notification title. + */ set subtitle(value: string | undefined); + /** + * Notification body. + * + * @returns Main notification message (shown when expanded). + */ get body(): string | undefined; + /** + * Update notification body. + * + * @param value - Update main notification message (shown when expanded). + */ set body(value: string | undefined); + /** + * Retrieve unread notifications number. + * + * @returns Number of unread notifications which should be shown on application badge. + */ get badge(): number | null | undefined; + /** + * Update application badge number. + * + * @param value - Number which should be shown in application badge upon receiving notification. + */ set badge(value: number | null | undefined); + /** + * Retrieve notification sound file. + * + * @returns Notification sound file name from resource bundle. + */ get sound(): string | undefined; + /** + * Update notification sound. + * + * @param value - Name of the sound file which should be played upon notification receive. + */ set sound(value: string | undefined); + /** + * Set whether notification should be silent or not. + * + * `content-available` notification type will be used to deliver silent notification if set to `true`. + * + * @param value - Whether notification should be sent as silent or not. + */ set silent(value: boolean); protected setDefaultPayloadStructure(): void; toObject(): APNSPayload | null; + /** + * Create PubNub push notification service APNS2 configuration information object. + * + * @param configuration - Source user-provided APNS2 configuration. + * + * @returns Preformatted for PubNub service APNS2 configuration information. + */ private objectFromAPNS2Configuration; + /** + * Create PubNub push notification service APNS2 target information object. + * + * @param target - Source user-provided data. + * + * @returns Preformatted for PubNub service APNS2 target information. + */ private objectFromAPNSTarget; } +/** + * Message payload for Firebase Clouse Messaging service. + */ export declare class FCMNotificationPayload extends BaseNotificationPayload { + /** + * Whether resulting payload should trigger silent notification or not. + */ private _isSilent?; + /** + * Name of the icon file from resource bundle which should be shown on notification. + */ private _icon?; private _tag?; get payload(): FCMPayload; + /** + * Notification payload. + * + * @returns Platform-specific part of PubNub notification payload. + */ get notification(): { + /** + * First line title. + * + * Title which is shown in bold on the first line of notification bubble. + */ title?: string | undefined; + /** + * Notification body. + * + * Body which is shown to the user after interaction with notification. + */ body?: string | undefined; + /** + * Name of the icon file from resource bundle which should be shown on notification. + */ icon?: string | undefined; + /** + * Name of the file from resource bundle which should be played when notification received. + */ sound?: string | undefined; tag?: string | undefined; } | undefined; + /** + * Silent notification payload. + * + * @returns Silent notification payload (data notification). + */ get data(): { notification?: { + /** + * First line title. + * + * Title which is shown in bold on the first line of notification bubble. + */ title?: string | undefined; + /** + * Notification body. + * + * Body which is shown to the user after interaction with notification. + */ body?: string | undefined; + /** + * Name of the icon file from resource bundle which should be shown on notification. + */ icon?: string | undefined; + /** + * Name of the file from resource bundle which should be played when notification received. + */ sound?: string | undefined; tag?: string | undefined; } | undefined; } | undefined; + /** + * Notification title. + * + * @returns Main notification title. + */ get title(): string | undefined; + /** + * Update notification title. + * + * @param value - New notification title. + */ set title(value: string | undefined); + /** + * Notification body. + * + * @returns Main notification message (shown when expanded). + */ get body(): string | undefined; + /** + * Update notification body. + * + * @param value - Update main notification message (shown when expanded). + */ set body(value: string | undefined); + /** + * Retrieve notification sound file. + * + * @returns Notification sound file name from resource bundle. + */ get sound(): string | undefined; + /** + * Update notification sound. + * + * @param value - Name of the sound file which should be played upon notification receive. + */ set sound(value: string | undefined); + /** + * Retrieve notification icon file. + * + * @returns Notification icon file name from resource bundle. + */ get icon(): string | undefined; + /** + * Update notification icon. + * + * @param value - Name of the icon file which should be shown on notification. + */ set icon(value: string | undefined); get tag(): string | undefined; set tag(value: string | undefined); + /** + * Set whether notification should be silent or not. + * + * All notification data will be sent under `data` field if set to `true`. + * + * @param value - Whether notification should be sent as silent or not. + */ set silent(value: boolean); protected setDefaultPayloadStructure(): void; toObject(): FCMPayload | null; } declare class NotificationsPayload { + /** + * Resulting message payload for notification services. + */ private readonly _payload; + /** + * Whether notifications debugging session should be used or not. + */ private _debugging?; + /** + * First line title. + * + * Title which is shown in bold on the first line of notification bubble. + */ private readonly _title; + /** + * Second line title. + * + * Subtitle which is shown under main title with smaller font. + */ private _subtitle?; + /** + * Notification main body message. + */ private readonly _body; + /** + * Value which should be placed on application badge (if required). + */ private _badge?; + /** + * Name of the file from resource bundle which should be played when notification received. + */ private _sound?; + /** + * APNS-specific message payload. + */ apns: APNSNotificationPayload; + /** + * FCM-specific message payload. + */ fcm: FCMNotificationPayload; constructor(title: string, body: string); set debugging(value: boolean); + /** + * Notification title. + * + * @returns Main notification title. + */ get title(): string; + /** + * Notification subtitle. + * + * @returns Second-line notification title. + */ get subtitle(): string | undefined; + /** + * Update notification subtitle. + * + * @param value - New second-line notification title. + */ set subtitle(value: string | undefined); + /** + * Notification body. + * + * @returns Main notification message (shown when expanded). + */ get body(): string; + /** + * Retrieve unread notifications number. + * + * @returns Number of unread notifications which should be shown on application badge. + */ get badge(): number | undefined; + /** + * Update application badge number. + * + * @param value - Number which should be shown in application badge upon receiving notification. + */ set badge(value: number | undefined); + /** + * Retrieve notification sound file. + * + * @returns Notification sound file name from resource bundle. + */ get sound(): string | undefined; + /** + * Update notification sound. + * + * @param value - Name of the sound file which should be played upon notification receive. + */ set sound(value: string | undefined); + /** + * Build notifications platform for requested platforms. + * + * @param platforms - List of platforms for which payload should be added to final dictionary. Supported values: + * gcm, apns, and apns2. + * + * @returns Object with data, which can be sent with publish method call and trigger remote notifications for + * specified platforms. + */ buildPayload(platforms: string[]): { pn_apns?: APNSPayload | undefined; pn_gcm?: FCMPayload | undefined; diff --git a/lib/types/core/components/reconnection_manager.d.ts b/lib/types/core/components/reconnection_manager.d.ts index cb0ff5c3b..2b32dd6da 100644 --- a/lib/types/core/components/reconnection_manager.d.ts +++ b/lib/types/core/components/reconnection_manager.d.ts @@ -1 +1,6 @@ +/** + * Subscription reconnection-manager. + * + * **Note:** Reconnection manger rely on legacy time-based availability check. + */ export {}; diff --git a/lib/types/core/components/subscription-manager.d.ts b/lib/types/core/components/subscription-manager.d.ts index cb0ff5c3b..6807d1c06 100644 --- a/lib/types/core/components/subscription-manager.d.ts +++ b/lib/types/core/components/subscription-manager.d.ts @@ -1 +1,4 @@ +/** + * Subscription manager module. + */ export {}; diff --git a/lib/types/core/components/token_manager.d.ts b/lib/types/core/components/token_manager.d.ts index cb0ff5c3b..ca862c226 100644 --- a/lib/types/core/components/token_manager.d.ts +++ b/lib/types/core/components/token_manager.d.ts @@ -1 +1,4 @@ +/** + * PubNub Access Token Manager module. + */ export {}; diff --git a/lib/types/core/constants/categories.d.ts b/lib/types/core/constants/categories.d.ts index a56853dae..bc372ba22 100644 --- a/lib/types/core/constants/categories.d.ts +++ b/lib/types/core/constants/categories.d.ts @@ -1,19 +1,75 @@ +/** + * Request processing status categories. + */ declare enum StatusCategory { + /** + * Call failed when network was unable to complete the call. + */ PNNetworkIssuesCategory = "PNNetworkIssuesCategory", + /** + * Network call timed out. + */ PNTimeoutCategory = "PNTimeoutCategory", + /** + * Request has been cancelled. + */ PNCancelledCategory = "PNCancelledCategory", + /** + * Server responded with bad response. + */ PNBadRequestCategory = "PNBadRequestCategory", + /** + * Server responded with access denied. + */ PNAccessDeniedCategory = "PNAccessDeniedCategory", + /** + * Incomplete parameters provided for used endpoint. + */ PNValidationErrorCategory = "PNValidationErrorCategory", + /** + * PubNub request acknowledgment status. + * + * Some API endpoints respond with request processing status w/o useful data. + */ PNAcknowledgmentCategory = "PNAcknowledgmentCategory", + /** + * Something strange happened; please check the logs. + */ PNUnknownCategory = "PNUnknownCategory", + /** + * SDK will announce when the network appears to be connected again. + */ PNNetworkUpCategory = "PNNetworkUpCategory", + /** + * SDK will announce when the network appears to down. + */ PNNetworkDownCategory = "PNNetworkDownCategory", + /** + * PubNub client reconnected to the real-time updates stream. + */ PNReconnectedCategory = "PNReconnectedCategory", + /** + * PubNub client connected to the real-time updates stream. + */ PNConnectedCategory = "PNConnectedCategory", + /** + * Received real-time updates exceed specified threshold. + * + * After temporary disconnection and catchup, this category means that potentially some + * real-time updates have been pushed into `storage` and need to be requested separately. + */ PNRequestMessageCountExceededCategory = "PNRequestMessageCountExceededCategory", + /** + * PubNub client disconnected from the real-time updates streams. + */ PNDisconnectedCategory = "PNDisconnectedCategory", + /** + * PubNub client wasn't able to connect to the real-time updates streams. + */ PNConnectionErrorCategory = "PNConnectionErrorCategory", + /** + * PubNub client unexpectedly disconnected from the real-time updates streams. + */ PNDisconnectedUnexpectedlyCategory = "PNDisconnectedUnexpectedlyCategory" } export default StatusCategory; diff --git a/lib/types/core/constants/operations.d.ts b/lib/types/core/constants/operations.d.ts index c7b7ec87b..2684a4880 100644 --- a/lib/types/core/constants/operations.d.ts +++ b/lib/types/core/constants/operations.d.ts @@ -1,53 +1,201 @@ declare enum RequestOperation { + /** + * Data publish REST API operation. + */ PNPublishOperation = "PNPublishOperation", + /** + * Signal sending REST API operation. + */ PNSignalOperation = "PNSignalOperation", + /** + * Subscribe for real-time updates REST API operation. + * + * User's presence change on specified entities will trigger `join` event. + */ PNSubscribeOperation = "PNSubscribeOperation", + /** + * Unsubscribe from real-time updates REST API operation. + * + * User's presence change on specified entities will trigger `leave` event. + */ PNUnsubscribeOperation = "PNUnsubscribeOperation", + /** + * Fetch user's presence information REST API operation. + */ PNWhereNowOperation = "PNWhereNowOperation", + /** + * Fetch channel's presence information REST API operation. + */ PNHereNowOperation = "PNHereNowOperation", + /** + * Fetch global presence information REST API operation. + */ PNGlobalHereNowOperation = "PNGlobalHereNowOperation", + /** + * Update user's information associated with specified channel REST API operation. + */ PNSetStateOperation = "PNSetStateOperation", + /** + * Fetch user's information associated with the specified channel REST API operation. + */ PNGetStateOperation = "PNGetStateOperation", + /** + * Announce presence on managed channels REST API operation. + */ PNHeartbeatOperation = "PNHeartbeatOperation", + /** + * Add a reaction to the specified message REST API operation. + */ PNAddMessageActionOperation = "PNAddActionOperation", + /** + * Remove reaction from the specified message REST API operation. + */ PNRemoveMessageActionOperation = "PNRemoveMessageActionOperation", + /** + * Fetch reactions for specific message REST API operation. + */ PNGetMessageActionsOperation = "PNGetMessageActionsOperation", PNTimeOperation = "PNTimeOperation", + /** + * Channel history REST API operation. + */ PNHistoryOperation = "PNHistoryOperation", + /** + * Delete messages from channel history REST API operation. + */ PNDeleteMessagesOperation = "PNDeleteMessagesOperation", + /** + * History for channels REST API operation. + */ PNFetchMessagesOperation = "PNFetchMessagesOperation", + /** + * Number of messages for channels in specified time frame REST API operation. + */ PNMessageCounts = "PNMessageCountsOperation", + /** + * Fetch users metadata REST API operation. + */ PNGetAllUUIDMetadataOperation = "PNGetAllUUIDMetadataOperation", + /** + * Fetch user metadata REST API operation. + */ PNGetUUIDMetadataOperation = "PNGetUUIDMetadataOperation", + /** + * Set user metadata REST API operation. + */ PNSetUUIDMetadataOperation = "PNSetUUIDMetadataOperation", + /** + * Remove user metadata REST API operation. + */ PNRemoveUUIDMetadataOperation = "PNRemoveUUIDMetadataOperation", + /** + * Fetch channels metadata REST API operation. + */ PNGetAllChannelMetadataOperation = "PNGetAllChannelMetadataOperation", + /** + * Fetch channel metadata REST API operation. + */ PNGetChannelMetadataOperation = "PNGetChannelMetadataOperation", + /** + * Set channel metadata REST API operation. + */ PNSetChannelMetadataOperation = "PNSetChannelMetadataOperation", + /** + * Remove channel metadata REST API operation. + */ PNRemoveChannelMetadataOperation = "PNRemoveChannelMetadataOperation", + /** + * Fetch channel members REST API operation. + */ PNGetMembersOperation = "PNGetMembersOperation", + /** + * Update channel members REST API operation. + */ PNSetMembersOperation = "PNSetMembersOperation", + /** + * Fetch channel memberships REST API operation. + */ PNGetMembershipsOperation = "PNGetMembershipsOperation", + /** + * Update channel memberships REST API operation. + */ PNSetMembershipsOperation = "PNSetMembershipsOperation", + /** + * Fetch list of files sent to the channel REST API operation. + */ PNListFilesOperation = "PNListFilesOperation", + /** + * Retrieve file upload URL REST API operation. + */ PNGenerateUploadUrlOperation = "PNGenerateUploadUrlOperation", + /** + * Upload file to the channel REST API operation. + */ PNPublishFileOperation = "PNPublishFileOperation", + /** + * Publish File Message to the channel REST API operation. + */ PNPublishFileMessageOperation = "PNPublishFileMessageOperation", + /** + * Retrieve file download URL REST API operation. + */ PNGetFileUrlOperation = "PNGetFileUrlOperation", + /** + * Download file from the channel REST API operation. + */ PNDownloadFileOperation = "PNDownloadFileOperation", + /** + * Delete file sent to the channel REST API operation. + */ PNDeleteFileOperation = "PNDeleteFileOperation", + /** + * Register channels with device push notifications REST API operation. + */ PNAddPushNotificationEnabledChannelsOperation = "PNAddPushNotificationEnabledChannelsOperation", + /** + * Unregister channels with device push notifications REST API operation. + */ PNRemovePushNotificationEnabledChannelsOperation = "PNRemovePushNotificationEnabledChannelsOperation", + /** + * Fetch list of channels with enabled push notifications for device REST API operation. + */ PNPushNotificationEnabledChannelsOperation = "PNPushNotificationEnabledChannelsOperation", + /** + * Disable push notifications for device REST API operation. + */ PNRemoveAllPushNotificationsOperation = "PNRemoveAllPushNotificationsOperation", + /** + * Fetch channels groups list REST API operation. + */ PNChannelGroupsOperation = "PNChannelGroupsOperation", + /** + * Remove specified channel group REST API operation. + */ PNRemoveGroupOperation = "PNRemoveGroupOperation", + /** + * Fetch list of channels for the specified channel group REST API operation. + */ PNChannelsForGroupOperation = "PNChannelsForGroupOperation", + /** + * Add list of channels to the specified channel group REST API operation. + */ PNAddChannelsToGroupOperation = "PNAddChannelsToGroupOperation", + /** + * Remove list of channels from the specified channel group REST API operation. + */ PNRemoveChannelsFromGroupOperation = "PNRemoveChannelsFromGroupOperation", + /** + * Generate authorized token REST API operation. + */ PNAccessManagerGrant = "PNAccessManagerGrant", + /** + * Generate authorized token REST API operation. + */ PNAccessManagerGrantToken = "PNAccessManagerGrantToken", PNAccessManagerAudit = "PNAccessManagerAudit", + /** + * Revoke authorized token REST API operation. + */ PNAccessManagerRevokeToken = "PNAccessManagerRevokeToken", PNHandshakeOperation = "PNHandshakeOperation", PNReceiveMessagesOperation = "PNReceiveMessagesOperation" diff --git a/lib/types/core/endpoints/access_manager/audit.d.ts b/lib/types/core/endpoints/access_manager/audit.d.ts index cb0ff5c3b..78b5769e2 100644 --- a/lib/types/core/endpoints/access_manager/audit.d.ts +++ b/lib/types/core/endpoints/access_manager/audit.d.ts @@ -1 +1,4 @@ +/** + * PAM Audit REST API module. + */ export {}; diff --git a/lib/types/core/endpoints/access_manager/grant.d.ts b/lib/types/core/endpoints/access_manager/grant.d.ts index cb0ff5c3b..0e51654bd 100644 --- a/lib/types/core/endpoints/access_manager/grant.d.ts +++ b/lib/types/core/endpoints/access_manager/grant.d.ts @@ -1 +1,4 @@ +/** + * PAM Grant REST API module. + */ export {}; diff --git a/lib/types/core/endpoints/access_manager/grant_token.d.ts b/lib/types/core/endpoints/access_manager/grant_token.d.ts index cb0ff5c3b..6895635ff 100644 --- a/lib/types/core/endpoints/access_manager/grant_token.d.ts +++ b/lib/types/core/endpoints/access_manager/grant_token.d.ts @@ -1 +1,4 @@ +/** + * PAM Grant Token REST API module. + */ export {}; diff --git a/lib/types/core/endpoints/access_manager/revoke_token.d.ts b/lib/types/core/endpoints/access_manager/revoke_token.d.ts index cb0ff5c3b..207f87cba 100644 --- a/lib/types/core/endpoints/access_manager/revoke_token.d.ts +++ b/lib/types/core/endpoints/access_manager/revoke_token.d.ts @@ -1 +1,4 @@ +/** + * PAM Revoke Token REST API module. + */ export {}; diff --git a/lib/types/core/endpoints/actions/add_message_action.d.ts b/lib/types/core/endpoints/actions/add_message_action.d.ts index cb0ff5c3b..e80c018b0 100644 --- a/lib/types/core/endpoints/actions/add_message_action.d.ts +++ b/lib/types/core/endpoints/actions/add_message_action.d.ts @@ -1 +1,4 @@ +/** + * Add Message Action REST API module. + */ export {}; diff --git a/lib/types/core/endpoints/actions/get_message_actions.d.ts b/lib/types/core/endpoints/actions/get_message_actions.d.ts index cb0ff5c3b..6206ec73f 100644 --- a/lib/types/core/endpoints/actions/get_message_actions.d.ts +++ b/lib/types/core/endpoints/actions/get_message_actions.d.ts @@ -1 +1,4 @@ +/** + * Get Message Actions REST API module. + */ export {}; diff --git a/lib/types/core/endpoints/actions/remove_message_action.d.ts b/lib/types/core/endpoints/actions/remove_message_action.d.ts index cb0ff5c3b..51aa42da6 100644 --- a/lib/types/core/endpoints/actions/remove_message_action.d.ts +++ b/lib/types/core/endpoints/actions/remove_message_action.d.ts @@ -1 +1,4 @@ +/** + * Remove Message Action REST API module. + */ export {}; diff --git a/lib/types/core/endpoints/channel_groups/add_channels.d.ts b/lib/types/core/endpoints/channel_groups/add_channels.d.ts index cb0ff5c3b..4d3dfefd8 100644 --- a/lib/types/core/endpoints/channel_groups/add_channels.d.ts +++ b/lib/types/core/endpoints/channel_groups/add_channels.d.ts @@ -1 +1,4 @@ +/** + * Add channel group channels REST API module. + */ export {}; diff --git a/lib/types/core/endpoints/channel_groups/delete_group.d.ts b/lib/types/core/endpoints/channel_groups/delete_group.d.ts index cb0ff5c3b..873f58775 100644 --- a/lib/types/core/endpoints/channel_groups/delete_group.d.ts +++ b/lib/types/core/endpoints/channel_groups/delete_group.d.ts @@ -1 +1,4 @@ +/** + * Delete channel group REST API module. + */ export {}; diff --git a/lib/types/core/endpoints/channel_groups/list_channels.d.ts b/lib/types/core/endpoints/channel_groups/list_channels.d.ts index cb0ff5c3b..1688a1d49 100644 --- a/lib/types/core/endpoints/channel_groups/list_channels.d.ts +++ b/lib/types/core/endpoints/channel_groups/list_channels.d.ts @@ -1 +1,4 @@ +/** + * List channel group channels REST API module. + */ export {}; diff --git a/lib/types/core/endpoints/channel_groups/list_groups.d.ts b/lib/types/core/endpoints/channel_groups/list_groups.d.ts index cb0ff5c3b..2aa05098f 100644 --- a/lib/types/core/endpoints/channel_groups/list_groups.d.ts +++ b/lib/types/core/endpoints/channel_groups/list_groups.d.ts @@ -1 +1,4 @@ +/** + * List All Channel Groups REST API module. + */ export {}; diff --git a/lib/types/core/endpoints/channel_groups/remove_channels.d.ts b/lib/types/core/endpoints/channel_groups/remove_channels.d.ts index cb0ff5c3b..f46a8e049 100644 --- a/lib/types/core/endpoints/channel_groups/remove_channels.d.ts +++ b/lib/types/core/endpoints/channel_groups/remove_channels.d.ts @@ -1 +1,4 @@ +/** + * Remove channel group channels REST API module. + */ export {}; diff --git a/lib/types/core/endpoints/fetch_messages.d.ts b/lib/types/core/endpoints/fetch_messages.d.ts index cb0ff5c3b..a58cec3cc 100644 --- a/lib/types/core/endpoints/fetch_messages.d.ts +++ b/lib/types/core/endpoints/fetch_messages.d.ts @@ -1 +1,4 @@ +/** + * Fetch messages REST API module. + */ export {}; diff --git a/lib/types/core/endpoints/file_upload/delete_file.d.ts b/lib/types/core/endpoints/file_upload/delete_file.d.ts index cb0ff5c3b..87204dacd 100644 --- a/lib/types/core/endpoints/file_upload/delete_file.d.ts +++ b/lib/types/core/endpoints/file_upload/delete_file.d.ts @@ -1 +1,4 @@ +/** + * Delete file REST API module. + */ export {}; diff --git a/lib/types/core/endpoints/file_upload/download_file.d.ts b/lib/types/core/endpoints/file_upload/download_file.d.ts index cb0ff5c3b..8591c0b12 100644 --- a/lib/types/core/endpoints/file_upload/download_file.d.ts +++ b/lib/types/core/endpoints/file_upload/download_file.d.ts @@ -1 +1,4 @@ +/** + * Download File REST API module. + */ export {}; diff --git a/lib/types/core/endpoints/file_upload/generate_upload_url.d.ts b/lib/types/core/endpoints/file_upload/generate_upload_url.d.ts index cb0ff5c3b..24d09f51a 100644 --- a/lib/types/core/endpoints/file_upload/generate_upload_url.d.ts +++ b/lib/types/core/endpoints/file_upload/generate_upload_url.d.ts @@ -1 +1,4 @@ +/** + * Generate file upload URL REST API request. + */ export {}; diff --git a/lib/types/core/endpoints/file_upload/get_file_url.d.ts b/lib/types/core/endpoints/file_upload/get_file_url.d.ts index cb0ff5c3b..925eee0d8 100644 --- a/lib/types/core/endpoints/file_upload/get_file_url.d.ts +++ b/lib/types/core/endpoints/file_upload/get_file_url.d.ts @@ -1 +1,4 @@ +/** + * File sharing REST API module. + */ export {}; diff --git a/lib/types/core/endpoints/file_upload/list_files.d.ts b/lib/types/core/endpoints/file_upload/list_files.d.ts index cb0ff5c3b..a85d9abf5 100644 --- a/lib/types/core/endpoints/file_upload/list_files.d.ts +++ b/lib/types/core/endpoints/file_upload/list_files.d.ts @@ -1 +1,4 @@ +/** + * List Files REST API module. + */ export {}; diff --git a/lib/types/core/endpoints/file_upload/publish_file.d.ts b/lib/types/core/endpoints/file_upload/publish_file.d.ts index cb0ff5c3b..3bf7b9ebd 100644 --- a/lib/types/core/endpoints/file_upload/publish_file.d.ts +++ b/lib/types/core/endpoints/file_upload/publish_file.d.ts @@ -1 +1,4 @@ +/** + * Publish File Message REST API module. + */ export {}; diff --git a/lib/types/core/endpoints/file_upload/upload-file.d.ts b/lib/types/core/endpoints/file_upload/upload-file.d.ts index cb0ff5c3b..6959033bd 100644 --- a/lib/types/core/endpoints/file_upload/upload-file.d.ts +++ b/lib/types/core/endpoints/file_upload/upload-file.d.ts @@ -1 +1,4 @@ +/** + * Upload file REST API request. + */ export {}; diff --git a/lib/types/core/endpoints/history/delete_messages.d.ts b/lib/types/core/endpoints/history/delete_messages.d.ts index cb0ff5c3b..c189fd470 100644 --- a/lib/types/core/endpoints/history/delete_messages.d.ts +++ b/lib/types/core/endpoints/history/delete_messages.d.ts @@ -1 +1,4 @@ +/** + * Delete messages REST API module. + */ export {}; diff --git a/lib/types/core/endpoints/history/get_history.d.ts b/lib/types/core/endpoints/history/get_history.d.ts index cb0ff5c3b..485ad476b 100644 --- a/lib/types/core/endpoints/history/get_history.d.ts +++ b/lib/types/core/endpoints/history/get_history.d.ts @@ -1 +1,4 @@ +/** + * Get history REST API module. + */ export {}; diff --git a/lib/types/core/endpoints/history/message_counts.d.ts b/lib/types/core/endpoints/history/message_counts.d.ts index cb0ff5c3b..7985a94f9 100644 --- a/lib/types/core/endpoints/history/message_counts.d.ts +++ b/lib/types/core/endpoints/history/message_counts.d.ts @@ -1 +1,4 @@ +/** + * Messages count REST API module. + */ export {}; diff --git a/lib/types/core/endpoints/objects/channel/get.d.ts b/lib/types/core/endpoints/objects/channel/get.d.ts index cb0ff5c3b..c56a41184 100644 --- a/lib/types/core/endpoints/objects/channel/get.d.ts +++ b/lib/types/core/endpoints/objects/channel/get.d.ts @@ -1 +1,4 @@ +/** + * Get Channel Metadata REST API module. + */ export {}; diff --git a/lib/types/core/endpoints/objects/channel/get_all.d.ts b/lib/types/core/endpoints/objects/channel/get_all.d.ts index cb0ff5c3b..777c4ab1c 100644 --- a/lib/types/core/endpoints/objects/channel/get_all.d.ts +++ b/lib/types/core/endpoints/objects/channel/get_all.d.ts @@ -1 +1,4 @@ +/** + * Get All Channel Metadata REST API module. + */ export {}; diff --git a/lib/types/core/endpoints/objects/channel/remove.d.ts b/lib/types/core/endpoints/objects/channel/remove.d.ts index cb0ff5c3b..0779bb2c8 100644 --- a/lib/types/core/endpoints/objects/channel/remove.d.ts +++ b/lib/types/core/endpoints/objects/channel/remove.d.ts @@ -1 +1,4 @@ +/** + * Remove Channel Metadata REST API module. + */ export {}; diff --git a/lib/types/core/endpoints/objects/channel/set.d.ts b/lib/types/core/endpoints/objects/channel/set.d.ts index cb0ff5c3b..e12e2fb2b 100644 --- a/lib/types/core/endpoints/objects/channel/set.d.ts +++ b/lib/types/core/endpoints/objects/channel/set.d.ts @@ -1 +1,4 @@ +/** + * Set Channel Metadata REST API module. + */ export {}; diff --git a/lib/types/core/endpoints/objects/member/get.d.ts b/lib/types/core/endpoints/objects/member/get.d.ts index cb0ff5c3b..db192f3b6 100644 --- a/lib/types/core/endpoints/objects/member/get.d.ts +++ b/lib/types/core/endpoints/objects/member/get.d.ts @@ -1 +1,4 @@ +/** + * Get Channel Members REST API module. + */ export {}; diff --git a/lib/types/core/endpoints/objects/member/set.d.ts b/lib/types/core/endpoints/objects/member/set.d.ts index cb0ff5c3b..67d6a5133 100644 --- a/lib/types/core/endpoints/objects/member/set.d.ts +++ b/lib/types/core/endpoints/objects/member/set.d.ts @@ -1 +1,4 @@ +/** + * Set Channel Members REST API module. + */ export {}; diff --git a/lib/types/core/endpoints/objects/membership/get.d.ts b/lib/types/core/endpoints/objects/membership/get.d.ts index cb0ff5c3b..3db81e283 100644 --- a/lib/types/core/endpoints/objects/membership/get.d.ts +++ b/lib/types/core/endpoints/objects/membership/get.d.ts @@ -1 +1,4 @@ +/** + * Get UUID Memberships REST API module. + */ export {}; diff --git a/lib/types/core/endpoints/objects/membership/set.d.ts b/lib/types/core/endpoints/objects/membership/set.d.ts index cb0ff5c3b..61cb530a7 100644 --- a/lib/types/core/endpoints/objects/membership/set.d.ts +++ b/lib/types/core/endpoints/objects/membership/set.d.ts @@ -1 +1,4 @@ +/** + * Set UUID Memberships REST API module. + */ export {}; diff --git a/lib/types/core/endpoints/objects/uuid/get.d.ts b/lib/types/core/endpoints/objects/uuid/get.d.ts index cb0ff5c3b..40e5f4817 100644 --- a/lib/types/core/endpoints/objects/uuid/get.d.ts +++ b/lib/types/core/endpoints/objects/uuid/get.d.ts @@ -1 +1,4 @@ +/** + * Get UUID Metadata REST API module. + */ export {}; diff --git a/lib/types/core/endpoints/objects/uuid/get_all.d.ts b/lib/types/core/endpoints/objects/uuid/get_all.d.ts index cb0ff5c3b..33e8a18dc 100644 --- a/lib/types/core/endpoints/objects/uuid/get_all.d.ts +++ b/lib/types/core/endpoints/objects/uuid/get_all.d.ts @@ -1 +1,4 @@ +/** + * Get All UUID Metadata REST API module. + */ export {}; diff --git a/lib/types/core/endpoints/objects/uuid/remove.d.ts b/lib/types/core/endpoints/objects/uuid/remove.d.ts index cb0ff5c3b..74edbb159 100644 --- a/lib/types/core/endpoints/objects/uuid/remove.d.ts +++ b/lib/types/core/endpoints/objects/uuid/remove.d.ts @@ -1 +1,4 @@ +/** + * Remove UUID Metadata REST API module. + */ export {}; diff --git a/lib/types/core/endpoints/objects/uuid/set.d.ts b/lib/types/core/endpoints/objects/uuid/set.d.ts index cb0ff5c3b..d4b96bdf7 100644 --- a/lib/types/core/endpoints/objects/uuid/set.d.ts +++ b/lib/types/core/endpoints/objects/uuid/set.d.ts @@ -1 +1,4 @@ +/** + * Set UUID Metadata REST API module. + */ export {}; diff --git a/lib/types/core/endpoints/presence/get_state.d.ts b/lib/types/core/endpoints/presence/get_state.d.ts index cb0ff5c3b..dff42db68 100644 --- a/lib/types/core/endpoints/presence/get_state.d.ts +++ b/lib/types/core/endpoints/presence/get_state.d.ts @@ -1 +1,4 @@ +/** + * Get Presence State REST API module. + */ export {}; diff --git a/lib/types/core/endpoints/presence/heartbeat.d.ts b/lib/types/core/endpoints/presence/heartbeat.d.ts index cb0ff5c3b..52b3c35c2 100644 --- a/lib/types/core/endpoints/presence/heartbeat.d.ts +++ b/lib/types/core/endpoints/presence/heartbeat.d.ts @@ -1 +1,4 @@ +/** + * Announce heartbeat REST API module. + */ export {}; diff --git a/lib/types/core/endpoints/presence/here_now.d.ts b/lib/types/core/endpoints/presence/here_now.d.ts index cb0ff5c3b..7f077a5e2 100644 --- a/lib/types/core/endpoints/presence/here_now.d.ts +++ b/lib/types/core/endpoints/presence/here_now.d.ts @@ -1 +1,4 @@ +/** + * Channels / channel groups presence REST API module. + */ export {}; diff --git a/lib/types/core/endpoints/presence/leave.d.ts b/lib/types/core/endpoints/presence/leave.d.ts index cb0ff5c3b..d6ba4460c 100644 --- a/lib/types/core/endpoints/presence/leave.d.ts +++ b/lib/types/core/endpoints/presence/leave.d.ts @@ -1 +1,4 @@ +/** + * Announce leave REST API module. + */ export {}; diff --git a/lib/types/core/endpoints/presence/set_state.d.ts b/lib/types/core/endpoints/presence/set_state.d.ts index cb0ff5c3b..d18769ae2 100644 --- a/lib/types/core/endpoints/presence/set_state.d.ts +++ b/lib/types/core/endpoints/presence/set_state.d.ts @@ -1 +1,4 @@ +/** + * Set Presence State REST API module. + */ export {}; diff --git a/lib/types/core/endpoints/presence/where_now.d.ts b/lib/types/core/endpoints/presence/where_now.d.ts index cb0ff5c3b..2c4ddd3c0 100644 --- a/lib/types/core/endpoints/presence/where_now.d.ts +++ b/lib/types/core/endpoints/presence/where_now.d.ts @@ -1 +1,4 @@ +/** + * `uuid` presence REST API module. + */ export {}; diff --git a/lib/types/core/endpoints/publish.d.ts b/lib/types/core/endpoints/publish.d.ts index 7b4e99310..f313eb4c5 100644 --- a/lib/types/core/endpoints/publish.d.ts +++ b/lib/types/core/endpoints/publish.d.ts @@ -1,15 +1,69 @@ +/** + * Publish REST API module. + */ import { CryptoModule } from '../interfaces/crypto-module'; import { Payload } from '../types/api'; +/** + * Request configuration parameters. + */ export type PublishParameters = { + /** + * Channel name to publish messages to. + */ channel: string; + /** + * Data which should be sent to the `channel`. + * + * The message may be any valid JSON type including objects, arrays, strings, and numbers. + */ message: Payload; + /** + * Whether published data should be available with `Storage API` later or not. + * + * @default `true` + */ storeInHistory?: boolean; + /** + * Whether message should be sent as part of request POST body or not. + * + * @default `false` + */ sendByPost?: boolean; + /** + * Metadata, which should be associated with published data. + * + * Associated metadata can be utilized by message filtering feature. + */ meta?: Payload; + /** + * Specify duration during which data will be available with `Storage API`. + * + * - If `storeInHistory` = `true`, and `ttl` = `0`, the `message` is stored with no expiry time. + * - If `storeInHistory` = `true` and `ttl` = `X` (`X` is an Integer value), the `message` is + * stored with an expiry time of `X` hours. + * - If `storeInHistory` = `false`, the `ttl` parameter is ignored. + * - If `ttl` is not specified, then expiration of the `message` defaults back to the expiry value + * for the key. + */ ttl?: number; + /** + * Whether published data should be replicated across all data centers or not. + * + * @default `true` + * @deprecated + */ replicate?: boolean; + /** + * Indexed signature for deprecated parameters. + */ [key: string]: string | number | boolean | undefined | Payload | CryptoModule; }; +/** + * Service success response. + */ export type PublishResponse = { + /** + * High-precision time when published data has been received by the PubNub service. + */ timetoken: string; }; diff --git a/lib/types/core/endpoints/push/add_push_channels.d.ts b/lib/types/core/endpoints/push/add_push_channels.d.ts index cb0ff5c3b..ba565c462 100644 --- a/lib/types/core/endpoints/push/add_push_channels.d.ts +++ b/lib/types/core/endpoints/push/add_push_channels.d.ts @@ -1 +1,4 @@ +/** + * Register Channels with Device push REST API module. + */ export {}; diff --git a/lib/types/core/endpoints/push/list_push_channels.d.ts b/lib/types/core/endpoints/push/list_push_channels.d.ts index cb0ff5c3b..cb340e6c5 100644 --- a/lib/types/core/endpoints/push/list_push_channels.d.ts +++ b/lib/types/core/endpoints/push/list_push_channels.d.ts @@ -1 +1,4 @@ +/** + * List Device push enabled channels REST API module. + */ export {}; diff --git a/lib/types/core/endpoints/push/push.d.ts b/lib/types/core/endpoints/push/push.d.ts index cb0ff5c3b..c9f462716 100644 --- a/lib/types/core/endpoints/push/push.d.ts +++ b/lib/types/core/endpoints/push/push.d.ts @@ -1 +1,4 @@ +/** + * Manage channels enabled for device push REST API module. + */ export {}; diff --git a/lib/types/core/endpoints/push/remove_device.d.ts b/lib/types/core/endpoints/push/remove_device.d.ts index cb0ff5c3b..ba3047e70 100644 --- a/lib/types/core/endpoints/push/remove_device.d.ts +++ b/lib/types/core/endpoints/push/remove_device.d.ts @@ -1 +1,4 @@ +/** + * Unregister Device push REST API module. + */ export {}; diff --git a/lib/types/core/endpoints/push/remove_push_channels.d.ts b/lib/types/core/endpoints/push/remove_push_channels.d.ts index cb0ff5c3b..d1343dbc7 100644 --- a/lib/types/core/endpoints/push/remove_push_channels.d.ts +++ b/lib/types/core/endpoints/push/remove_push_channels.d.ts @@ -1 +1,4 @@ +/** + * Unregister Channels from Device push REST API module. + */ export {}; diff --git a/lib/types/core/endpoints/signal.d.ts b/lib/types/core/endpoints/signal.d.ts index 6b739aac8..9238bd206 100644 --- a/lib/types/core/endpoints/signal.d.ts +++ b/lib/types/core/endpoints/signal.d.ts @@ -1,8 +1,28 @@ +/** + * Signal REST API module. + */ import { Payload } from '../types/api'; +/** + * Request configuration parameters. + */ export type SignalParameters = { + /** + * Channel name to publish signal to. + */ channel: string; + /** + * Data which should be sent to the `channel`. + * + * The message may be any valid JSON type including objects, arrays, strings, and numbers. + */ message: Payload; }; +/** + * Service success response. + */ export type SignalResponse = { + /** + * High-precision time when published data has been received by the PubNub service. + */ timetoken: string; }; diff --git a/lib/types/core/endpoints/subscribe.d.ts b/lib/types/core/endpoints/subscribe.d.ts index cb0ff5c3b..a7be65799 100644 --- a/lib/types/core/endpoints/subscribe.d.ts +++ b/lib/types/core/endpoints/subscribe.d.ts @@ -1 +1,4 @@ +/** + * Subscription REST API module. + */ export {}; diff --git a/lib/types/core/endpoints/subscriptionUtils/handshake.d.ts b/lib/types/core/endpoints/subscriptionUtils/handshake.d.ts index cb0ff5c3b..2a942a579 100644 --- a/lib/types/core/endpoints/subscriptionUtils/handshake.d.ts +++ b/lib/types/core/endpoints/subscriptionUtils/handshake.d.ts @@ -1 +1,4 @@ +/** + * Handshake subscribe REST API module. + */ export {}; diff --git a/lib/types/core/endpoints/subscriptionUtils/receiveMessages.d.ts b/lib/types/core/endpoints/subscriptionUtils/receiveMessages.d.ts index cb0ff5c3b..640df8780 100644 --- a/lib/types/core/endpoints/subscriptionUtils/receiveMessages.d.ts +++ b/lib/types/core/endpoints/subscriptionUtils/receiveMessages.d.ts @@ -1 +1,4 @@ +/** + * Receive messages subscribe REST API module. + */ export {}; diff --git a/lib/types/core/endpoints/time.d.ts b/lib/types/core/endpoints/time.d.ts index e02a488b9..cda43e5ea 100644 --- a/lib/types/core/endpoints/time.d.ts +++ b/lib/types/core/endpoints/time.d.ts @@ -1,3 +1,12 @@ +/** + * Time REST API module. + */ +/** + * Service success response. + */ export type TimeResponse = { + /** + * High-precision time when published data has been received by the PubNub service. + */ timetoken: string; }; diff --git a/lib/types/core/interfaces/configuration.d.ts b/lib/types/core/interfaces/configuration.d.ts index b6debb50c..63ce7b036 100644 --- a/lib/types/core/interfaces/configuration.d.ts +++ b/lib/types/core/interfaces/configuration.d.ts @@ -1,74 +1,276 @@ -import { PubNubFileConstructor, PubNubFileInterface } from '../types/file'; +/** + * {@link PubNub} client configuration module. + */ import { RequestRetryPolicy } from '../../event-engine/core/retryPolicy'; -import { CryptoModule } from './crypto-module'; -import { Payload } from '../types/api'; +/** + * Base user-provided PubNub client configuration. + */ export type UserConfiguration = { + /** + * Specifies the `subscribeKey` to be used for subscribing to a channel and message publishing. + */ subscribeKey: string; + /** + * Specifies the `subscribe_key` to be used for subscribing to a channel and message publishing. + * + * @deprecated Use the {@link subscribeKey} instead. + */ subscribe_key?: string; + /** + * Specifies the `publishKey` to be used for publishing messages to a channel. + */ publishKey?: string; + /** + * Specifies the `publish_key` to be used for publishing messages to a channel. + * + * @deprecated Use the {@link publishKey} instead. + */ publish_key?: string; + /** + * Specifies the `secretKey` to be used for request signatures computation. + */ secretKey?: string; + /** + * Specifies the `secret_key` to be used for request signatures computation. + * + * @deprecated Use the {@link secretKey} instead. + */ secret_key?: string; + /** + * Unique PubNub client user identifier. + * + * Unique `userId` to identify the user or the device that connects to PubNub. + * It's a UTF-8 encoded string of up to 64 alphanumeric characters. + * + * If you don't set the `userId`, you won't be able to connect to PubNub. + */ userId?: string; + /** + * If Access Manager enabled, this key will be used on all requests. + */ authKey?: string | null; + /** + * Log HTTP information. + * + * @default `false` + */ logVerbosity?: boolean; + /** + * If set to true, requests will be made over HTTPS. + * + * @default `true` for v4.20.0 onwards, `false` before v4.20.0 + */ ssl?: boolean; + /** + * If a custom domain is required, SDK accepts it here. + * + * @default `ps.pndsn.com` + */ origin?: string | string[]; + /** + * How long the server will consider the client alive for presence.The value is in seconds. + * + * @default `300` + */ presenceTimeout?: number; + /** + * How often the client will announce itself to server.The value is in seconds. + * + * @default `not set` + */ heartbeatInterval?: number; + /** + * Transactional requests timeout in milliseconds. + * + * Maximum duration for which PubNub client should wait for transactional request completion. + * + * @default `15` seconds + */ transactionalRequestTimeout?: number; + /** + * Subscription requests timeout in milliseconds. + * + * Maximum duration for which PubNub client should wait for subscription request completion. + * + * @default `310` seconds + */ subscribeRequestTimeout?: number; + /** + * `true` to allow catch up on the front-end applications. + * + * @default `false` + */ restore?: boolean; + /** + * Whether to include the PubNub object instance ID in outgoing requests. + * + * @default `false` + */ useInstanceId?: boolean; + /** + * When `true` the SDK doesn't send out the leave requests. + * + * @default `false` + */ suppressLeaveEvents?: boolean; + /** + * `PNRequestMessageCountExceededCategory` is thrown when the number of messages into the + * payload is above of `requestMessageCountThreshold`. + * + * @default `100` + */ requestMessageCountThreshold?: number; + /** + * This flag announces when the network is down or up using the states `PNNetworkDownCategory` + * and `PNNetworkUpCategory`. + * + * @default `false` + */ autoNetworkDetection?: boolean; + /** + * Whether to use the standardized workflows for subscribe and presence. + * + * Note that the `maintainPresenceState` parameter is set to true by default, so make sure to + * disable it if you don't need to maintain presence state. For more information, refer to the + * param description in this table. + * + * + * @default `false` + */ enableEventEngine?: boolean; + /** + * Custom reconnection configuration parameters. + * + * `retryConfiguration: policy` is the type of policy to be used. + * + * Available values: + * - `PubNub.LinearRetryPolicy({ delay, maximumRetry })` + * - `PubNub.ExponentialRetryPolicy({ minimumDelay, maximumDelay, maximumRetry })` + * + * For more information, refer to + * {@link /docs/general/setup/connection-management#reconnection-policy|Reconnection Policy}. JavaScript doesn't + * support excluding endpoints. + * + * @default `not set` + */ retryConfiguration?: RequestRetryPolicy; + /** + * Whether the `state` set using `setState()` should be maintained for the current `userId`. + * This option works only when `enableEventEngine` is set to `true`. + * + * @default `true` + */ maintainPresenceState?: boolean; + /** + * `UUID` to use. You should set a unique `UUID` to identify the user or the device that + * connects to PubNub. + * If you don't set the `UUID`, you won't be able to connect to PubNub. + * + * @deprecated Use {@link userId} instead. + */ uuid?: string; + /** + * If set to `true`, SDK will use the same TCP connection for each HTTP request, instead of + * opening a new one for each new request. + * + * @default `false` + */ keepAlive?: boolean; + /** + * If the SDK is running as part of another SDK built atop of it, allow a custom `pnsdk` with + * name and version. + */ sdkName?: string; + /** + * If the SDK is operated by a partner, allow a custom `pnsdk` item for them. + */ partnerId?: string; }; -export type PlatformConfiguration = { - sdkFamily: string; - cryptoModule?: CryptoModule; - PubNubFile?: PubNubFileConstructor; - cipherKey?: string; - useRandomIVs?: boolean; - customEncrypt?: (data: string | Payload) => string; - customDecrypt?: (data: string) => string; -}; +/** + * User-provided configuration object interface. + * + * Interface contains limited set of settings manipulation and access. + */ export interface ClientConfiguration { + /** + * Get a PubNub client user identifier. + * + * @returns Current PubNub client user identifier. + */ getUserId(): string; + /** + * Change the current PubNub client user identifier. + * + * **Important:** Change won't affect ongoing REST API calls. + * + * @param value - New PubNub client user identifier. + * + * @throws Error empty user identifier has been provided. + */ setUserId(value: string): void; + /** + * Change REST API endpoint access authorization key. + * + * @param authKey - New authorization key which should be used with new requests. + */ setAuthKey(authKey: string | null): void; + /** + * Real-time updates filtering expression. + * + * @returns Filtering expression. + */ getFilterExpression(): string | undefined | null; + /** + * Update real-time updates filtering expression. + * + * @param expression - New expression which should be used or `undefined` to disable filtering. + */ setFilterExpression(expression: string | null | undefined): void; + /** + * Change data encryption / decryption key. + * + * @param key - New key which should be used for data encryption / decryption. + */ setCipherKey(key: string | undefined): void; + /** + * Get PubNub SDK version. + * + * @returns Current SDK version. + */ get version(): string; + /** + * Get PubNub SDK version. + * + * @returns Current SDK version. + */ getVersion(): string; + /** + * Add framework's prefix. + * + * @param name - Name of the framework which would want to add own data into `pnsdk` suffix. + * @param suffix - Suffix with information about framework. + */ _addPnsdkSuffix(name: string, suffix: string | number): void; + /** + * Get a PubNub client user identifier. + * + * @returns Current PubNub client user identifier. + * + * @deprecated Use the {@link getUserId} or {@link userId} getter instead. + */ getUUID(): string; + /** + * Change the current PubNub client user identifier. + * + * **Important:** Change won't affect ongoing REST API calls. + * + * @param value - New PubNub client user identifier. + * + * @returns {Configuration} Reference to the configuration instance for easier chaining. + * + * @throws Error empty user identifier has been provided. + * + * @deprecated Use the {@link setUserId} or {@link userId} setter instead. + */ setUUID(value: string): void; } -export interface PrivateClientConfiguration extends ClientConfiguration, Omit { - getAuthKey(): string | undefined | null; - getCryptoModule(): CryptoModule | undefined; - getPresenceTimeout(): number; - setPresenceTimeout(timeout: number): void; - getHeartbeatInterval(): number | undefined; - setHeartbeatInterval(interval: number): void; - getTransactionTimeout(): number; - getSubscribeTimeout(): number; - get PubNubFile(): PubNubFileConstructor | undefined; - get instanceId(): string | undefined; - get sdkFamily(): string; - _getPnsdkSuffix(separator: string): string; - getCipherKey(): string | undefined; - getUseRandomIVs(): boolean | undefined; - getCustomEncrypt(): ((data: string | Payload) => string) | undefined; - getCustomDecrypt(): ((data: string) => string) | undefined; -} -export declare const setDefaults: (configuration: UserConfiguration) => ExtendedConfiguration; diff --git a/lib/types/core/interfaces/crypto-module.d.ts b/lib/types/core/interfaces/crypto-module.d.ts index 8629730da..621df079a 100644 --- a/lib/types/core/interfaces/crypto-module.d.ts +++ b/lib/types/core/interfaces/crypto-module.d.ts @@ -1,33 +1,152 @@ +/** + * Crypto module. + */ import { PubNubFileConstructor, PubNubFileInterface } from '../types/file'; import { Payload } from '../types/api'; +/** + * Crypto module configuration. + */ export type CryptoModuleConfiguration = { default: C; cryptors?: C[]; }; export type CryptorConfiguration = { + /** + * Data encryption / decryption key. + */ cipherKey?: string; + /** + * Request sign secret key. + */ secretKey?: string; + /** + * Whether random initialization vector should be used or not. + * + * @default `true` + */ useRandomIVs?: boolean; + /** + * Custom data encryption method. + * + * @deprecated Instead use {@link cryptoModule} for data encryption. + */ customEncrypt?: (data: string | Payload) => string; + /** + * Custom data decryption method. + * + * @deprecated Instead use {@link cryptoModule} for data decryption. + */ customDecrypt?: (data: string) => string; }; +/** + * Base crypto module interface. + */ export interface CryptoModule { + /** + * Encrypt data. + * + * @param data - Data which should be encrypted using `CryptoModule`. + * + * @returns Data encryption result. + */ encrypt(data: ArrayBuffer | string): ArrayBuffer | string; + /** + * Encrypt file object. + * + * @param file - File object with data for encryption. + * @param File - File object constructor to create instance for encrypted data representation. + * + * @returns Asynchronous file encryption result. + */ encryptFile(file: PubNubFileInterface, File: PubNubFileConstructor): Promise; + /** + * Encrypt data. + * + * @param data - Dta which should be encrypted using `CryptoModule`. + * + * @returns Data decryption result. + */ decrypt(data: ArrayBuffer | string): ArrayBuffer | Payload | null; + /** + * Decrypt file object. + * + * @param file - Encrypted file object with data for decryption. + * @param File - File object constructor to create instance for decrypted data representation. + * + * @returns Asynchronous file decryption result. + */ decryptFile(file: PubNubFileInterface, File: PubNubFileConstructor): Promise; } export declare abstract class AbstractCryptoModule implements CryptoModule { + /** + * `String` to {@link ArrayBuffer} response decoder. + */ protected static encoder: TextEncoder; + /** + * {@link ArrayBuffer} to {@link string} decoder. + */ protected static decoder: TextDecoder; defaultCryptor: C; cryptors: C[]; + /** + * Construct crypto module with legacy cryptor for encryption and both legacy and AES-CBC + * cryptors for decryption. + * + * @param config Cryptors configuration options. + * + * @returns Crypto module which encrypts data using legacy cryptor. + * + * @throws Error if `config.cipherKey` not set. + */ static legacyCryptoModule(config: CryptorConfiguration): CryptoModule; + /** + * Construct crypto module with AES-CBC cryptor for encryption and both AES-CBC and legacy + * cryptors for decryption. + * + * @param config Cryptors configuration options. + * + * @returns Crypto module which encrypts data using AES-CBC cryptor. + * + * @throws Error if `config.cipherKey` not set. + */ static aesCbcCryptoModule(config: CryptorConfiguration): CryptoModule; constructor(configuration: CryptoModuleConfiguration); + /** + * Encrypt data. + * + * @param data - Data which should be encrypted using {@link CryptoModule}. + * + * @returns Data encryption result. + */ abstract encrypt(data: ArrayBuffer | string): ArrayBuffer | string; + /** + * Encrypt file object. + * + * @param file - File object with data for encryption. + * @param File - File object constructor to create instance for encrypted data representation. + * + * @returns Asynchronous file encryption result. + */ abstract encryptFile(file: PubNubFileInterface, File: PubNubFileConstructor): Promise; + /** + * Encrypt data. + * + * @param data - Dta which should be encrypted using `CryptoModule`. + * + * @returns Data decryption result. + */ abstract decrypt(data: ArrayBuffer | string): ArrayBuffer | Payload | null; + /** + * Decrypt file object. + * + * @param file - Encrypted file object with data for decryption. + * @param File - File object constructor to create instance for decrypted data representation. + * + * @returns Asynchronous file decryption result. + */ abstract decryptFile(file: PubNubFileInterface, File: PubNubFileConstructor): Promise; + /** + * Retrieve list of module's cryptors. + */ protected getAllCryptors(): C[]; } diff --git a/lib/types/core/interfaces/cryptography.d.ts b/lib/types/core/interfaces/cryptography.d.ts index cfdfb1a2c..9b73050a5 100644 --- a/lib/types/core/interfaces/cryptography.d.ts +++ b/lib/types/core/interfaces/cryptography.d.ts @@ -1,7 +1,54 @@ +/** + * Legacy Cryptography module interface. + */ import { PubNubFileConstructor, PubNubFileInterface } from '../types/file'; export interface Cryptography { + /** + * Encrypt provided source data using specific encryption {@link key}. + * + * @param key - Data encryption key.
**Note:** Same key should be used to `decrypt` data. + * @param input - Source data for encryption. + * + * @returns Encrypted data as object or stream (depending on from source data type). + * + * @throws Error if unknown data type has been passed. + */ encrypt(key: string, input: Types): Promise; + /** + * Decrypt provided encrypted data using specific decryption {@link key}. + * + * @param key - Data decryption key.
**Note:** Should be the same as used to `encrypt` data. + * @param input - Encrypted data for decryption. + * + * @returns Decrypted data as object or stream (depending on from encrypted data type). + * + * @throws Error if unknown data type has been passed. + */ decrypt(key: string, input: Types): Promise; + /** + * Encrypt provided `PubNub` File object using specific encryption {@link key}. + * + * @param key - Key for `PubNub` File object encryption.
**Note:** Same key should be + * used to `decrypt` data. + * @param file - Source `PubNub` File object for encryption. + * @param File - Class constructor for `PubNub` File object. + * + * @returns Encrypted data as `PubNub` File object. + * + * @throws Error if file is empty or contains unsupported data type. + */ encryptFile(key: string, file: PubNubFileInterface, File: PubNubFileConstructor): Promise; + /** + * Decrypt provided `PubNub` File object using specific decryption {@link key}. + * + * @param key - Key for `PubNub` File object decryption.
**Note:** Should be the same + * as used to `encrypt` data. + * @param file - Encrypted `PubNub` File object for decryption. + * @param File - Class constructor for `PubNub` File object. + * + * @returns Decrypted data as `PubNub` File object. + * + * @throws Error if file is empty or contains unsupported data type. + */ decryptFile(key: string, file: PubNubFileInterface, File: PubNubFileConstructor): Promise; } diff --git a/lib/types/core/interfaces/transport.d.ts b/lib/types/core/interfaces/transport.d.ts index 1b081f700..82ec357eb 100644 --- a/lib/types/core/interfaces/transport.d.ts +++ b/lib/types/core/interfaces/transport.d.ts @@ -1,12 +1,61 @@ import { CancellationController, TransportRequest } from '../types/transport-request'; import { TransportResponse } from '../types/transport-response'; +/** + * Represents the configuration options for keeping the transport connection alive. + */ export type TransportKeepAlive = { + /** + * The time interval in milliseconds for keeping the connection alive. + * + * @default 1000 + */ keepAliveMsecs?: number; + /** + * The maximum number of sockets allowed per host. + * + * @default Infinity + */ maxSockets?: number; + /** + * The maximum number of open and free sockets in the pool per host. + * + * @default 256 + */ maxFreeSockets?: number; + /** + * Timeout in milliseconds, after which the `idle` socket will be closed. + * + * @default 30000 + */ timeout?: number; }; +/** + * This interface is used to send requests to the PubNub API. + * + * You can implement this interface for your types, or use one of the provided modules to use a + * transport library. + * + * @interface + */ export interface Transport { + /** + * Make request sendable. + * + * @param req - The transport request to be processed. + * + * @returns - A promise that resolves to a transport response and request cancellation + * controller (if required). + */ makeSendable(req: TransportRequest): [Promise, CancellationController | undefined]; + /** + * Pre-processed request. + * + * Transport implementation may pre-process original transport requests before making + * platform-specific request objects from it. + * + * @param req - Transport request provided by the PubNub client. + * + * @returns Transport request with updated properties (if it was required). + */ request(req: TransportRequest): TransportRequest; } diff --git a/lib/types/core/pubnub-channel-groups.d.ts b/lib/types/core/pubnub-channel-groups.d.ts index efcecac4d..f9c0dc604 100644 --- a/lib/types/core/pubnub-channel-groups.d.ts +++ b/lib/types/core/pubnub-channel-groups.d.ts @@ -1,17 +1,86 @@ +/** + * PubNub Channel Groups API module. + */ import { KeySet, ResultCallback, SendRequestFunction, StatusCallback } from './types/api'; import * as ChannelGroups from './types/api/channel-groups'; export default class PubnubChannelGroups { private readonly keySet; private readonly sendRequest; constructor(keySet: KeySet, sendRequest: SendRequestFunction); + /** + * Fetch channel group channels. + * + * @param parameters - Request configuration parameters. + * @param callback - Request completion handler callback. + */ listChannels(parameters: ChannelGroups.ListChannelGroupChannelsParameters, callback: ResultCallback): void; + /** + * Fetch channel group channels. + * + * @param parameters - Request configuration parameters. + * + * @returns Asynchronous get channel group channels response. + */ listChannels(parameters: ChannelGroups.ListChannelGroupChannelsParameters): Promise; + /** + * Fetch all channel groups. + * + * @param callback - Request completion handler callback. + * + * @deprecated + */ listGroups(callback: ResultCallback): void; + /** + * Fetch all channel groups. + * + * @returns Asynchronous get all channel groups response. + * + * @deprecated + */ listGroups(): Promise; + /** + * Add channels to the channel group. + * + * @param parameters - Request configuration parameters. + * @param callback - Request completion handler callback. + */ addChannels(parameters: ChannelGroups.ManageChannelGroupChannelsParameters, callback: StatusCallback): void; + /** + * Add channels to the channel group. + * + * @param parameters - Request configuration parameters. + * + * @returns Asynchronous add channels to the channel group response. + */ addChannels(parameters: ChannelGroups.ManageChannelGroupChannelsParameters): Promise>; + /** + * Remove channels from the channel group. + * + * @param parameters - Request configuration parameters. + * @param callback - Request completion handler callback. + */ removeChannels(parameters: ChannelGroups.ManageChannelGroupChannelsParameters, callback: StatusCallback): void; + /** + * Remove channels from the channel group. + * + * @param parameters - Request configuration parameters. + * + * @returns Asynchronous remove channels from the channel group response. + */ removeChannels(parameters: ChannelGroups.ManageChannelGroupChannelsParameters): Promise>; + /** + * Remove channel group. + * + * @param parameters - Request configuration parameters. + * @param callback - Request completion handler callback. + */ deleteGroup(parameters: ChannelGroups.DeleteChannelGroupParameters, callback: StatusCallback): void; + /** + * Remove channel group. + * + * @param parameters - Request configuration parameters. + * + * @returns Asynchronous remove channel group response. + */ deleteGroup(parameters: ChannelGroups.DeleteChannelGroupParameters): Promise>; } diff --git a/lib/types/core/pubnub-common.d.ts b/lib/types/core/pubnub-common.d.ts index 02fea41d4..976ca6564 100644 --- a/lib/types/core/pubnub-common.d.ts +++ b/lib/types/core/pubnub-common.d.ts @@ -30,118 +30,713 @@ import * as AppContext from './types/api/app-context'; import PubNubObjects from './pubnub-objects'; import * as Time from './endpoints/time'; type ClientInstanceConfiguration = { + /** + * Client-provided configuration. + */ configuration: PrivateClientConfiguration; + /** + * Transport provider for requests execution. + */ transport: Transport; + /** + * REST API endpoints access tokens manager. + */ tokenManager: TokenManager; + /** + * Legacy crypto module implementation. + */ cryptography?: Cryptography; + /** + * Legacy crypto (legacy data encryption / decryption and request signature support). + */ crypto?: Crypto; }; +/** + * Platform-agnostic PubNub client core. + */ export declare class PubNubCore = Record> { + /** + * Type of REST API endpoint which reported status. + */ static OPERATIONS: typeof RequestOperation; + /** + * API call status category. + */ static CATEGORIES: typeof StatusCategory; + /** + * Exponential retry policy constructor. + */ static ExponentialRetryPolicy: typeof RetryPolicy.ExponentialRetryPolicy; + /** + * Linear retry policy constructor. + */ static LinearRetryPolicy: typeof RetryPolicy.LinearRetryPolicy; + /** + * Construct notification payload which will trigger push notification. + * + * @param title - Title which will be shown on notification. + * @param body - Payload which will be sent as part of notification. + * + * @returns Pre-formatted message payload which will trigger push notification. + */ static notificationPayload(title: string, body: string): NotificationsPayload; + /** + * Generate unique identifier. + * + * @returns Unique identifier. + */ static generateUUID(): any; constructor(configuration: ClientInstanceConfiguration); + /** + * PubNub client configuration. + * + * @returns Currently user PubNub client configuration. + */ get configuration(): ClientConfiguration; + /** + * Current PubNub client configuration. + * + * @returns Currently user PubNub client configuration. + * + * @deprecated Use {@link configuration} getter instead. + */ get _config(): ClientConfiguration; + /** + * REST API endpoint access authorization key. + * + * It is required to have `authorization key` with required permissions to access REST API + * endpoints when `PAM` enabled for user key set. + */ get authKey(): string | undefined; + /** + * REST API endpoint access authorization key. + * + * It is required to have `authorization key` with required permissions to access REST API + * endpoints when `PAM` enabled for user key set. + */ getAuthKey(): string | undefined; + /** + * Change REST API endpoint access authorization key. + * + * @param authKey - New authorization key which should be used with new requests. + */ setAuthKey(authKey: string): void; + /** + * Get a PubNub client user identifier. + * + * @returns Current PubNub client user identifier. + */ get userId(): string; + /** + * Change the current PubNub client user identifier. + * + * **Important:** Change won't affect ongoing REST API calls. + * + * @param value - New PubNub client user identifier. + * + * @throws Error empty user identifier has been provided. + */ set userId(value: string); + /** + * Get a PubNub client user identifier. + * + * @returns Current PubNub client user identifier. + */ getUserId(): string; + /** + * Change the current PubNub client user identifier. + * + * **Important:** Change won't affect ongoing REST API calls. + * + * @param value - New PubNub client user identifier. + * + * @throws Error empty user identifier has been provided. + */ setUserId(value: string): void; + /** + * Real-time updates filtering expression. + * + * @returns Filtering expression. + */ get filterExpression(): string | undefined; + /** + * Real-time updates filtering expression. + * + * @returns Filtering expression. + */ getFilterExpression(): string | undefined; + /** + * Update real-time updates filtering expression. + * + * @param expression - New expression which should be used or `undefined` to disable filtering. + */ set filterExpression(expression: string | null | undefined); + /** + * Update real-time updates filtering expression. + * + * @param expression - New expression which should be used or `undefined` to disable filtering. + */ setFilterExpression(expression: string | null): void; + /** + * Dta encryption / decryption key. + * + * @returns Currently used key for data encryption / decryption. + */ get cipherKey(): string | undefined; + /** + * Change data encryption / decryption key. + * + * @param key - New key which should be used for data encryption / decryption. + */ set cipherKey(key: string | undefined); + /** + * Change data encryption / decryption key. + * + * @param key - New key which should be used for data encryption / decryption. + */ setCipherKey(key: string): void; + /** + * Change heartbeat requests interval. + * + * @param interval - New presence request heartbeat intervals. + */ set heartbeatInterval(interval: number); + /** + * Change heartbeat requests interval. + * + * @param interval - New presence request heartbeat intervals. + */ setHeartbeatInterval(interval: number): void; + /** + * Get PubNub SDK version. + * + * @returns Current SDK version. + */ getVersion(): string; + /** + * Add framework's prefix. + * + * @param name - Name of the framework which would want to add own data into `pnsdk` suffix. + * @param suffix - Suffix with information about framework. + */ _addPnsdkSuffix(name: string, suffix: string | number): void; + /** + * Get a PubNub client user identifier. + * + * @returns Current PubNub client user identifier. + * + * @deprecated Use the {@link getUserId} or {@link userId} getter instead. + */ getUUID(): string; + /** + * Change the current PubNub client user identifier. + * + * **Important:** Change won't affect ongoing REST API calls. + * + * @param value - New PubNub client user identifier. + * + * @throws Error empty user identifier has been provided. + * + * @deprecated Use the {@link PubNubCore#setUserId} or {@link PubNubCore#userId} setter instead. + */ setUUID(value: string): void; + /** + * Custom data encryption method. + * + * @deprecated Instead use {@link cryptoModule} for data encryption. + */ get customEncrypt(): ((data: string) => string) | undefined; + /** + * Custom data decryption method. + * + * @deprecated Instead use {@link cryptoModule} for data decryption. + */ get customDecrypt(): ((data: string) => string) | undefined; + /** + * Create a `Channel` entity. + * + * Entity can be used for the interaction with the following API: + * - `subscribe` + * + * @param name - Unique channel name. + * @returns `Channel` entity. + */ channel(name: string): Channel; + /** + * Create a `ChannelGroup` entity. + * + * Entity can be used for the interaction with the following API: + * - `subscribe` + * + * @param name - Unique channel group name. + * @returns `ChannelGroup` entity. + */ channelGroup(name: string): ChannelGroup; + /** + * Create a `ChannelMetadata` entity. + * + * Entity can be used for the interaction with the following API: + * - `subscribe` + * + * @param id - Unique channel metadata object identifier. + * @returns `ChannelMetadata` entity. + */ channelMetadata(id: string): ChannelMetadata; + /** + * Create a `UserMetadata` entity. + * + * Entity can be used for the interaction with the following API: + * - `subscribe` + * + * @param id - Unique user metadata object identifier. + * @returns `UserMetadata` entity. + */ userMetadata(id: string): UserMetadata; + /** + * Create subscriptions set object. + * + * @param parameters - Subscriptions set configuration parameters. + */ subscriptionSet(parameters: { channels?: string[]; channelGroups?: string[]; subscriptionOptions?: SubscriptionOptions; }): SubscriptionSet; + /** + * Schedule request execution. + * + * @param request - REST API request. + * @param callback - Request completion handler callback. + * + * @returns Asynchronous request execution and response parsing result. + */ private sendRequest; + /** + * Unsubscribe from all channels and groups. + * + * @param [isOffline] - Whether `offline` presence should be notified or not. + */ destroy(isOffline?: boolean): void; + /** + * Unsubscribe from all channels and groups. + * + * @deprecated Use {@link destroy} method instead. + */ stop(): void; + /** + * Register real-time events listener. + * + * @param listener - Listener with event callbacks to handle different types of events. + */ addListener(listener: Listener): void; + /** + * Remove real-time event listener. + * + * @param listener - Event listeners which should be removed. + */ removeListener(listener: Listener): void; + /** + * Clear all real-time event listeners. + */ removeAllListeners(): void; + /** + * Publish data to a specific channel. + * + * @param parameters - Request configuration parameters. + * @param callback - Request completion handler callback. + */ publish(parameters: Publish.PublishParameters, callback: ResultCallback): void; + /** + * Publish data to a specific channel. + * + * @param parameters - Request configuration parameters. + * + * @returns Asynchronous publish data response. + */ publish(parameters: Publish.PublishParameters): Promise; + /** + * Signal data to a specific channel. + * + * @param parameters - Request configuration parameters. + * @param callback - Request completion handler callback. + */ signal(parameters: Signal.SignalParameters, callback: ResultCallback): void; + /** + * Signal data to a specific channel. + * + * @param parameters - Request configuration parameters. + * + * @returns Asynchronous signal data response. + */ signal(parameters: Signal.SignalParameters): Promise; + /** + * `Fire` a data to a specific channel. + * + * @param parameters - Request configuration parameters. + * @param callback - Request completion handler callback. + * + * @deprecated Use {@link publish} method instead. + */ fire(parameters: Publish.PublishParameters, callback: ResultCallback): void; + /** + * `Fire` a data to a specific channel. + * + * @param parameters - Request configuration parameters. + * + * @returns Asynchronous signal data response. + * + * @deprecated Use {@link publish} method instead. + */ fire(parameters: Publish.PublishParameters): Promise; + /** + * Get list of channels on which PubNub client currently subscribed. + * + * @returns List of active channels. + */ getSubscribedChannels(): string[]; + /** + * Get list of channel groups on which PubNub client currently subscribed. + * + * @returns List of active channel groups. + */ getSubscribedChannelGroups(): string[]; + /** + * Subscribe to specified channels and groups real-time events. + * + * @param parameters - Request configuration parameters. + */ subscribe(parameters: Subscription.SubscribeParameters): void; + /** + * Perform subscribe request. + * + * **Note:** Method passed into managers to let them use it when required. + * + * @param parameters - Request configuration parameters. + * @param callback - Request completion handler callback. + */ private makeSubscribe; + /** + * Unsubscribe from specified channels and groups real-time events. + * + * @param parameters - Request configuration parameters. + */ unsubscribe(parameters: Presence.PresenceLeaveParameters): void; + /** + * Perform unsubscribe request. + * + * **Note:** Method passed into managers to let them use it when required. + * + * @param parameters - Request configuration parameters. + * @param callback - Request completion handler callback. + */ private makeUnsubscribe; + /** + * Unsubscribe from all channels and groups. + */ unsubscribeAll(): void; + /** + * Temporarily disconnect from real-time events stream. + */ disconnect(): void; + /** + * Restore connection to the real-time events stream. + * + * @param parameters - Reconnection catch up configuration. **Note:** available only with + * enabled event engine. + */ reconnect(parameters?: { timetoken?: string; region?: number; }): void; + /** + * Event engine handshake subscribe. + * + * @param parameters - Request configuration parameters. + */ private subscribeHandshake; + /** + * Event engine receive messages subscribe. + * + * @param parameters - Request configuration parameters. + */ private subscribeReceiveMessages; + /** + * Get reactions to a specific message. + * + * @param parameters - Request configuration parameters. + * @param callback - Request completion handler callback. + */ getMessageActions(parameters: MessageAction.GetMessageActionsParameters, callback: ResultCallback): void; + /** + * Get reactions to a specific message. + * + * @param parameters - Request configuration parameters. + * + * @returns Asynchronous get reactions response. + */ getMessageActions(parameters: MessageAction.GetMessageActionsParameters): Promise; + /** + * Add a reaction to a specific message. + * + * @param parameters - Request configuration parameters. + * @param callback - Request completion handler callback. + */ addMessageAction(parameters: MessageAction.AddMessageActionParameters, callback: ResultCallback): void; + /** + * Add a reaction to a specific message. + * + * @param parameters - Request configuration parameters. + * + * @returns Asynchronous add a reaction response. + */ addMessageAction(parameters: MessageAction.AddMessageActionParameters): Promise; + /** + * Remove a reaction from a specific message. + * + * @param parameters - Request configuration parameters. + * @param callback - Request completion handler callback. + */ removeMessageAction(parameters: MessageAction.RemoveMessageActionParameters, callback: ResultCallback): void; + /** + * Remove a reaction from a specific message. + * + * @param parameters - Request configuration parameters. + * + * @returns Asynchronous remove a reaction response. + */ removeMessageAction(parameters: MessageAction.RemoveMessageActionParameters): Promise; + /** + * Fetch messages history for channels. + * + * @param parameters - Request configuration parameters. + * @param callback - Request completion handler callback. + */ fetchMessages(parameters: History.FetchMessagesParameters, callback: ResultCallback): void; + /** + * Fetch messages history for channels. + * + * @param parameters - Request configuration parameters. + * + * @returns Asynchronous fetch messages response. + */ fetchMessages(parameters: History.FetchMessagesParameters): Promise; + /** + * Delete messages from the channel history. + * + * @param parameters - Request configuration parameters. + * @param callback - Request completion handler callback. + * + * @deprecated + */ deleteMessages(parameters: History.DeleteMessagesParameters, callback: ResultCallback): void; + /** + * Delete messages from the channel history. + * + * @param parameters - Request configuration parameters. + * + * @returns Asynchronous delete messages response. + * + * @deprecated + */ deleteMessages(parameters: History.DeleteMessagesParameters): Promise; + /** + * Count messages from the channels' history. + * + * @param parameters - Request configuration parameters. + * @param callback - Request completion handler callback. + */ messageCounts(parameters: History.MessageCountParameters, callback: ResultCallback): void; + /** + * Count messages from the channels' history. + * + * @param parameters - Request configuration parameters. + * + * @returns Asynchronous count messages response. + */ messageCounts(parameters: History.MessageCountParameters): Promise; + /** + * Fetch single channel history. + * + * @param parameters - Request configuration parameters. + * @param callback - Request completion handler callback. + * + * @deprecated + */ history(parameters: History.GetHistoryParameters, callback: ResultCallback): void; + /** + * Fetch single channel history. + * + * @param parameters - Request configuration parameters. + * + * @returns Asynchronous fetch channel history response. + * + * @deprecated + */ history(parameters: History.GetHistoryParameters): Promise; + /** + * Get channel's presence information. + * + * @param parameters - Request configuration parameters. + * @param callback - Request completion handler callback. + */ hereNow(parameters: Presence.HereNowParameters, callback: ResultCallback): void; + /** + * Get channel presence information. + * + * @param parameters - Request configuration parameters. + * + * @returns Asynchronous get channel's presence response. + */ hereNow(parameters: Presence.HereNowParameters): Promise; + /** + * Get user's presence information. + * + * Get list of channels to which `uuid` currently subscribed. + * + * @param parameters - Request configuration parameters. + * @param callback - Request completion handler callback. + */ whereNow(parameters: Presence.WhereNowParameters, callback: ResultCallback): void; + /** + * Get user's presence information. + * + * Get list of channels to which `uuid` currently subscribed. + * + * @param parameters - Request configuration parameters. + * + * @returns Asynchronous get user's presence response. + */ whereNow(parameters: Presence.WhereNowParameters): Promise; + /** + * Get associated user's data for channels and groups. + * + * @param parameters - Request configuration parameters. + * @param callback - Request completion handler callback. + */ getState(parameters: Presence.GetPresenceStateParameters, callback: ResultCallback): void; + /** + * Get associated user's data for channels and groups. + * + * @param parameters - Request configuration parameters. + * + * @returns Asynchronous get associated user's data response. + */ getState(parameters: Presence.GetPresenceStateParameters): Promise; + /** + * Set associated user's data for channels and groups. + * + * @param parameters - Request configuration parameters. + * @param callback - Request completion handler callback. + */ setState(parameters: Presence.SetPresenceStateParameters | Presence.SetPresenceStateWithHeartbeatParameters, callback: ResultCallback): void; + /** + * Set associated user's data for channels and groups. + * + * @param parameters - Request configuration parameters. + * + * @returns Asynchronous set associated user's data response. + */ setState(parameters: Presence.SetPresenceStateParameters | Presence.SetPresenceStateWithHeartbeatParameters): Promise; + /** + * Manual presence management. + * + * @param parameters - Desired presence state for provided list of channels and groups. + */ presence(parameters: { connected: boolean; channels?: string[]; channelGroups?: string[]; }): void; + /** + * Announce user presence + * + * @param parameters - Desired presence state for provided list of channels and groups. + * @param callback - Request completion handler callback. + */ private heartbeat; + /** + * Announce user `join` on specified list of channels and groups. + * + * @param parameters - List of channels and groups where `join` event should be sent. + */ private join; + /** + * Announce user `leave` on specified list of channels and groups. + * + * @param parameters - List of channels and groups where `leave` event should be sent. + */ private leave; + /** + * Announce user `leave` on all subscribed channels. + */ private leaveAll; + /** + * Grant token permission. + * + * Generate access token with requested permissions. + * + * @param parameters - Request configuration parameters. + * @param callback - Request completion handler callback. + */ grantToken(parameters: PAM.GrantTokenParameters, callback: ResultCallback): void; + /** + * Grant token permission. + * + * Generate access token with requested permissions. + * + * @param parameters - Request configuration parameters. + * + * @returns Asynchronous grant token response. + */ grantToken(parameters: PAM.GrantTokenParameters): Promise; + /** + * Revoke token permission. + * + * @param parameters - Request configuration parameters. + * @param callback - Request completion handler callback. + */ revokeToken(parameters: PAM.RevokeParameters, callback: ResultCallback): void; + /** + * Revoke token permission. + * + * @param parameters - Request configuration parameters. + * + * @returns Asynchronous revoke token response. + */ revokeToken(parameters: PAM.RevokeParameters): Promise; + /** + * Get current access token. + * + * @returns Previously configured access token using {@link setToken} method. + */ get token(): string | undefined; + /** + * Get current access token. + * + * @returns Previously configured access token using {@link setToken} method. + */ getToken(): string | undefined; + /** + * Set current access token. + * + * @param token - New access token which should be used with next REST API endpoint calls. + */ set token(token: string | undefined); + /** + * Set current access token. + * + * @param token - New access token which should be used with next REST API endpoint calls. + */ setToken(token: string | undefined): void; + /** + * Parse access token. + * + * Parse token to see what permissions token owner has. + * + * @param token - Token which should be parsed. + * + * @returns Token's permissions information for the resources. + */ parseToken(token: string): { version: number; timestamp: number; @@ -168,63 +763,538 @@ export declare class PubNubCore): void; + /** + * Grant auth key(s) permission. + * + * @param parameters - Request configuration parameters. + * + * @returns Asynchronous grant auth key(s) permissions response. + * + * @deprecated Use {@link grantToken} and {@link setToken} methods instead. + */ grant(parameters: PAM.GrantParameters): Promise; + /** + * Audit auth key(s) permission. + * + * @param parameters - Request configuration parameters. + * @param callback - Request completion handler callback. + * + * @deprecated + */ audit(parameters: PAM.AuditParameters, callback: ResultCallback): void; + /** + * Audit auth key(s) permission. + * + * @param parameters - Request configuration parameters. + * + * @returns Asynchronous audit auth key(s) permissions response. + * + * @deprecated + */ audit(parameters: PAM.AuditParameters): Promise; + /** + * PubNub App Context API group. + */ get objects(): PubNubObjects; + /** + * Fetch a paginated list of User objects. + * + * @param callback - Request completion handler callback. + * + * @deprecated Use {@link PubNubCore#objects.getAllUUIDMetadata} method instead. + */ fetchUsers(callback: ResultCallback>): void; + /** + * Fetch a paginated list of User objects. + * + * @param parameters - Request configuration parameters. + * @param callback - Request completion handler callback. + * + * @deprecated Use {@link PubNubCore#objects.getAllUUIDMetadata} method instead. + */ fetchUsers(parameters: AppContext.GetAllMetadataParameters>, callback: ResultCallback>): void; + /** + * Fetch a paginated list of User objects. + * + * @param [parameters] - Request configuration parameters. + * + * @returns Asynchronous get all User objects response. + * + * @deprecated Use {@link PubNubCore#objects.getAllUUIDMetadata} method instead. + */ fetchUsers(parameters?: AppContext.GetAllMetadataParameters>): Promise>; + /** + * Fetch User object for currently configured PubNub client `uuid`. + * + * @param callback - Request completion handler callback. + * + * @deprecated Use {@link PubNubCore#objects.getUUIDMetadata} method instead. + */ fetchUser(callback: ResultCallback>): void; + /** + * Fetch User object for currently configured PubNub client `uuid`. + * + * @param parameters - Request configuration parameters. Will fetch User object for currently + * configured PubNub client `uuid` if not set. + * @param callback - Request completion handler callback. + * + * @deprecated Use {@link PubNubCore#objects.getUUIDMetadata} method instead. + */ fetchUser(parameters: AppContext.GetUUIDMetadataParameters, callback: ResultCallback>): void; + /** + * Fetch User object for currently configured PubNub client `uuid`. + * + * @param [parameters] - Request configuration parameters. Will fetch User object for currently + * configured PubNub client `uuid` if not set. + * + * @returns Asynchronous get User object response. + * + * @deprecated Use {@link PubNubCore#objects.getUUIDMetadata} method instead. + */ fetchUser(parameters?: AppContext.GetUUIDMetadataParameters): Promise>; + /** + * Create User object. + * + * @param parameters - Request configuration parameters. Will create User object for currently + * configured PubNub client `uuid` if not set. + * @param callback - Request completion handler callback. + * + * @deprecated Use {@link PubNubCore#objects.setUUIDMetadata} method instead. + */ createUser(parameters: AppContext.SetUUIDMetadataParameters, callback: ResultCallback>): void; + /** + * Create User object. + * + * @param parameters - Request configuration parameters. Will create User object for currently + * configured PubNub client `uuid` if not set. + * + * @returns Asynchronous create User object response. + * + * @deprecated Use {@link PubNubCore#objects.setUUIDMetadata} method instead. + */ createUser(parameters: AppContext.SetUUIDMetadataParameters): Promise>; + /** + * Update User object. + * + * @param parameters - Request configuration parameters. Will update User object for currently + * configured PubNub client `uuid` if not set. + * @param callback - Request completion handler callback. + * + * @deprecated Use {@link PubNubCore#objects.setUUIDMetadata} method instead. + */ updateUser(parameters: AppContext.SetUUIDMetadataParameters, callback: ResultCallback>): void; + /** + * Update User object. + * + * @param parameters - Request configuration parameters. Will update User object for currently + * configured PubNub client `uuid` if not set. + * + * @returns Asynchronous update User object response. + * + * @deprecated Use {@link PubNubCore#objects.setUUIDMetadata} method instead. + */ updateUser(parameters: AppContext.SetUUIDMetadataParameters): Promise>; + /** + * Remove a specific User object. + * + * @param callback - Request completion handler callback. Will remove User object for currently + * configured PubNub client `uuid` if not set. + * + * @deprecated Use {@link PubNubCore#objects.removeUUIDMetadata} method instead. + */ removeUser(callback: ResultCallback): void; + /** + * Remove a specific User object. + * + * @param parameters - Request configuration parameters. Will remove User object for currently + * configured PubNub client `uuid` if not set. + * @param callback - Request completion handler callback. + * + * @deprecated Use {@link PubNubCore#objects.removeUUIDMetadata} method instead. + */ removeUser(parameters: AppContext.RemoveUUIDMetadataParameters, callback: ResultCallback): void; + /** + * Remove a specific User object. + * + * @param [parameters] - Request configuration parameters. Will remove User object for currently + * configured PubNub client `uuid` if not set. + * + * @returns Asynchronous User object remove response. + * + * @deprecated Use {@link PubNubCore#objects.removeUUIDMetadata} method instead. + */ removeUser(parameters?: AppContext.RemoveUUIDMetadataParameters): Promise; + /** + * Fetch a paginated list of Space objects. + * + * @param callback - Request completion handler callback. + * + * @deprecated Use {@link PubNubCore#objects.getAllChannelMetadata} method instead. + */ fetchSpaces(callback: ResultCallback>): void; + /** + * Fetch a paginated list of Space objects. + * + * @param parameters - Request configuration parameters. + * @param callback - Request completion handler callback. + * + * @deprecated Use {@link PubNubCore#objects.getAllChannelMetadata} method instead. + */ fetchSpaces(parameters: AppContext.GetAllMetadataParameters>, callback: ResultCallback>): void; + /** + * Fetch a paginated list of Space objects. + * + * @param [parameters] - Request configuration parameters. + * + * @returns Asynchronous get all Space objects response. + * + * @deprecated Use {@link PubNubCore#objects.getAllChannelMetadata} method instead. + */ fetchSpaces(parameters?: AppContext.GetAllMetadataParameters>): Promise>; + /** + * Fetch a specific Space object. + * + * @param parameters - Request configuration parameters. + * @param callback - Request completion handler callback. + * + * @deprecated Use {@link PubNubCore#objects.getChannelMetadata} method instead. + */ fetchSpace(parameters: AppContext.GetChannelMetadataParameters, callback: ResultCallback>): void; + /** + * Fetch a specific Space object. + * + * @param parameters - Request configuration parameters. + * + * @returns Asynchronous get Channel metadata response. + * + * @deprecated Use {@link PubNubCore#objects.getChannelMetadata} method instead. + */ fetchSpace(parameters: AppContext.GetChannelMetadataParameters): Promise>; + /** + * Create specific Space object. + * + * @param parameters - Request configuration parameters. + * @param callback - Request completion handler callback. + * + * @deprecated Use {@link PubNubCore#objects.setChannelMetadata} method instead. + */ createSpace(parameters: AppContext.SetChannelMetadataParameters, callback: ResultCallback>): void; + /** + * Create specific Space object. + * + * @param parameters - Request configuration parameters. + * + * @returns Asynchronous create Space object response. + * + * @deprecated Use {@link PubNubCore#objects.setChannelMetadata} method instead. + */ createSpace(parameters: AppContext.SetChannelMetadataParameters): Promise>; + /** + * Update specific Space object. + * + * @param parameters - Request configuration parameters. + * @param callback - Request completion handler callback. + * + * @deprecated Use {@link PubNubCore#objects.setChannelMetadata} method instead. + */ updateSpace(parameters: AppContext.SetChannelMetadataParameters, callback: ResultCallback>): void; + /** + * Update specific Space object. + * + * @param parameters - Request configuration parameters. + * + * @returns Asynchronous update Space object response. + * + * @deprecated Use {@link PubNubCore#objects.setChannelMetadata} method instead. + */ updateSpace(parameters: AppContext.SetChannelMetadataParameters): Promise>; + /** + * Remove Space object. + * + * @param parameters - Request configuration parameters. + * @param callback - Request completion handler callback. + * + * @deprecated Use {@link PubNubCore#objects.removeChannelMetadata} method instead. + */ removeSpace(parameters: AppContext.RemoveChannelMetadataParameters, callback: ResultCallback): void; + /** + * Remove a specific Space object. + * + * @param parameters - Request configuration parameters. + * + * @returns Asynchronous Space object remove response. + * + * @deprecated Use {@link PubNubCore#objects.removeChannelMetadata} method instead. + */ removeSpace(parameters: AppContext.RemoveChannelMetadataParameters): Promise; + /** + * Fetch paginated list of specific Space members or specific User memberships. + * + * @param parameters - Request configuration parameters. + * @param callback - Request completion handler callback. + * + * @deprecated Use {@link PubNubCore#objects.getChannelMembers} or {@link PubNubCore#objects.getMemberships} + * methods instead. + */ fetchMemberships(parameters: AppContext.GetMembershipsParameters | AppContext.GetMembersParameters, callback: ResultCallback | AppContext.UserMembersResponse>): void; + /** + * Fetch paginated list of specific Space members or specific User memberships. + * + * @param parameters - Request configuration parameters. + * + * @returns Asynchronous get specific Space members or specific User memberships response. + * + * @deprecated Use {@link PubNubCore#objects.getChannelMembers} or {@link PubNubCore#objects.getMemberships} + * methods instead. + */ fetchMemberships(parameters: AppContext.GetMembershipsParameters | AppContext.GetMembersParameters): Promise | AppContext.UserMembersResponse>; + /** + * Add members to specific Space or memberships specific User. + * + * @param parameters - Request configuration parameters. + * @param callback - Request completion handler callback. + * + * @deprecated Use {@link PubNubCore#objects.setChannelMembers} or {@link PubNubCore#objects.setMemberships} + * methods instead. + */ addMemberships(parameters: AppContext.SetMembershipsParameters | AppContext.SetChannelMembersParameters, callback: ResultCallback | AppContext.SetMembersResponse>): void; + /** + * Add members to specific Space or memberships specific User. + * + * @param parameters - Request configuration parameters. + * + * @returns Asynchronous add members to specific Space or memberships specific User response. + * + * @deprecated Use {@link PubNubCore#objects.setChannelMembers} or {@link PubNubCore#objects.setMemberships} + * methods instead. + */ addMemberships(parameters: AppContext.SetMembershipsParameters | AppContext.SetChannelMembersParameters): Promise | AppContext.SetMembersResponse>; + /** + * Update specific Space members or User memberships. + * + * @param parameters - Request configuration parameters. + * @param callback - Request completion handler callback. + * + * @deprecated Use {@link PubNubCore#objects.setChannelMembers} or {@link PubNubCore#objects.setMemberships} + * methods instead. + */ updateMemberships(parameters: AppContext.SetMembershipsParameters | AppContext.SetChannelMembersParameters, callback: ResultCallback | AppContext.SetMembersResponse>): void; + /** + * Update specific Space members or User memberships. + * + * @param parameters - Request configuration parameters. + * + * @returns Asynchronous update Space members or User memberships response. + * + * @deprecated Use {@link PubNubCore#objects.setChannelMembers} or {@link PubNubCore#objects.setMemberships} + * methods instead. + */ updateMemberships(parameters: AppContext.SetMembershipsParameters | AppContext.SetChannelMembersParameters): Promise | AppContext.SetMembersResponse>; + /** + * Remove User membership. + * + * @param parameters - Request configuration parameters. + * @param callback - Request completion handler callback. + * + * @deprecated Use {@link PubNubCore#objects.removeMemberships} or {@link PubNubCore#objects.removeChannelMembers} + * methods instead + * from `objects` API group.. + */ removeMemberships(parameters: AppContext.RemoveMembersParameters | AppContext.RemoveMembershipsParameters, callback: ResultCallback | AppContext.RemoveMembershipsResponse>): void; + /** + * Remove User membership. + * + * @param parameters - Request configuration parameters. + * + * @returns Asynchronous memberships modification response. + * + * @deprecated Use {@link PubNubCore#objects.removeMemberships} or {@link PubNubCore#objects.removeChannelMembers} + * methods instead + * from `objects` API group.. + */ removeMemberships(parameters: AppContext.RemoveMembersParameters | AppContext.RemoveMembershipsParameters): Promise>; + /** + * PubNub Channel Groups API group. + */ get channelGroups(): PubNubChannelGroups; + /** + * PubNub Push Notifications API group. + */ get push(): PubNubPushNotifications; + /** + * Share file to a specific channel. + * + * @param parameters - Request configuration parameters. + * @param callback - Request completion handler callback. + */ sendFile(parameters: FileSharing.SendFileParameters, callback: ResultCallback): void; + /** + * Share file to a specific channel. + * + * @param parameters - Request configuration parameters. + * + * @returns Asynchronous file sharing response. + */ sendFile(parameters: FileSharing.SendFileParameters): Promise; + /** + * Publish file message to a specific channel. + * + * @param parameters - Request configuration parameters. + * @param callback - Request completion handler callback. + */ publishFile(parameters: FileSharing.PublishFileMessageParameters, callback: ResultCallback): void; + /** + * Publish file message to a specific channel. + * + * @param parameters - Request configuration parameters. + * + * @returns Asynchronous publish file message response. + */ publishFile(parameters: FileSharing.PublishFileMessageParameters): Promise; + /** + * Retrieve list of shared files in specific channel. + * + * @param parameters - Request configuration parameters. + * @param callback - Request completion handler callback. + */ listFiles(parameters: FileSharing.ListFilesParameters, callback: ResultCallback): void; + /** + * Retrieve list of shared files in specific channel. + * + * @param parameters - Request configuration parameters. + * + * @returns Asynchronous shared files list response. + */ listFiles(parameters: FileSharing.ListFilesParameters): Promise; + /** + * Get file download Url. + * + * @param parameters - Request configuration parameters. + * + * @returns File download Url. + */ getFileUrl(parameters: FileSharing.FileUrlParameters): FileSharing.FileUrlResponse; + /** + * Download shared file from specific channel. + * + * @param parameters - Request configuration parameters. + * @param callback - Request completion handler callback. + */ downloadFile(parameters: FileSharing.DownloadFileParameters, callback: ResultCallback): void; + /** + * Download shared file from specific channel. + * + * @param parameters - Request configuration parameters. + * + * @returns Asynchronous download shared file response. + */ downloadFile(parameters: FileSharing.DownloadFileParameters): Promise; + /** + * Delete shared file from specific channel. + * + * @param parameters - Request configuration parameters. + * @param callback - Request completion handler callback. + */ deleteFile(parameters: FileSharing.DeleteFileParameters, callback: ResultCallback): void; + /** + * Delete shared file from specific channel. + * + * @param parameters - Request configuration parameters. + * + * @returns Asynchronous delete shared file response. + */ deleteFile(parameters: FileSharing.DeleteFileParameters): Promise; + /** + Get current high-precision timetoken. + * + * @param callback - Request completion handler callback. + */ time(callback: ResultCallback): void; + /** + * Get current high-precision timetoken. + * + * @returns Asynchronous get current timetoken response. + */ time(): Promise; + /** + * Encrypt data. + * + * @param data - Stringified data which should be encrypted using `CryptoModule`. + * @deprecated + * @param [customCipherKey] - Cipher key which should be used to encrypt data. **Deprecated:** + * use {@link Configuration#cryptoModule|cryptoModule} instead. + * + * @returns Data encryption result as a string. + */ encrypt(data: string | Payload, customCipherKey?: string): string; + /** + * Decrypt data. + * + * @param data - Stringified data which should be encrypted using `CryptoModule`. + * @param [customCipherKey] - Cipher key which should be used to decrypt data. **Deprecated:** + * use {@link Configuration#cryptoModule|cryptoModule} instead. + * + * @returns Data decryption result as an object. + */ decrypt(data: string, customCipherKey?: string): Payload | null; + /** + * Encrypt file content. + * + * @param file - File which should be encrypted using `CryptoModule`. + * + * @returns Asynchronous file encryption result. + * + * @throws Error if source file not provided. + * @throws File constructor not provided. + * @throws Crypto module is missing (if non-legacy flow used). + */ encryptFile(file: PubNubFileInterface): Promise; + /** + * Encrypt file content. + * + * @param key - Cipher key which should be used to encrypt data. + * @param file - File which should be encrypted using legacy cryptography. + * + * @returns Asynchronous file encryption result. + * + * @throws Error if source file not provided. + * @throws File constructor not provided. + * @throws Crypto module is missing (if non-legacy flow used). + */ encryptFile(key: string, file: PubNubFileInterface): Promise; + /** + * Decrypt file content. + * + * @param file - File which should be decrypted using legacy cryptography. + * + * @returns Asynchronous file decryption result. + * + * @throws Error if source file not provided. + * @throws File constructor not provided. + * @throws Crypto module is missing (if non-legacy flow used). + */ decryptFile(file: PubNubFileInterface): Promise; + /** + * Decrypt file content. + * + * @param key - Cipher key which should be used to decrypt data. + * @param [file] - File which should be decrypted using legacy cryptography. + * + * @returns Asynchronous file decryption result. + * + * @throws Error if source file not provided. + * @throws File constructor not provided. + * @throws Crypto module is missing (if non-legacy flow used). + */ decryptFile(key: string | PubNubFileInterface, file?: PubNubFileInterface): Promise; } export {}; diff --git a/lib/types/core/pubnub-objects.d.ts b/lib/types/core/pubnub-objects.d.ts index 5dc0b3e44..75f4f1a7b 100644 --- a/lib/types/core/pubnub-objects.d.ts +++ b/lib/types/core/pubnub-objects.d.ts @@ -1,52 +1,364 @@ +/** + * PubNub Objects API module. + */ import { ResultCallback, SendRequestFunction } from './types/api'; import { PrivateClientConfiguration } from './interfaces/configuration'; import * as AppContext from './types/api/app-context'; export default class PubNubObjects { private readonly configuration; private readonly sendRequest; + /** + * REST API endpoints access credentials. + */ private readonly keySet; constructor(configuration: PrivateClientConfiguration, sendRequest: SendRequestFunction); + /** + * Fetch a paginated list of UUID Metadata objects. + * + * @param callback - Request completion handler callback. + */ getAllUUIDMetadata(callback: ResultCallback>): void; + /** + * Fetch a paginated list of UUID Metadata objects. + * + * @param parameters - Request configuration parameters. + * @param callback - Request completion handler callback. + */ getAllUUIDMetadata(parameters: AppContext.GetAllMetadataParameters>, callback: ResultCallback>): void; + /** + * Fetch a paginated list of UUID Metadata objects. + * + * @param [parameters] - Request configuration parameters. + * + * @returns Asynchronous get all UUID metadata response. + */ getAllUUIDMetadata(parameters?: AppContext.GetAllMetadataParameters>): Promise>; + /** + * Fetch a paginated list of UUID Metadata objects. + * + * + * @param [parametersOrCallback] - Request configuration parameters or callback from overload. + * @param [callback] - Request completion handler callback. + * + * @returns Asynchronous get all UUID metadata response or `void` in case if `callback` provided. + */ _getAllUUIDMetadata(parametersOrCallback?: AppContext.GetAllMetadataParameters> | ResultCallback>, callback?: ResultCallback>): Promise | void>; + /** + * Fetch UUID Metadata object for currently configured PubNub client `uuid`. + * + * @param callback - Request completion handler callback. + */ getUUIDMetadata(callback: ResultCallback>): void; + /** + * Fetch a specific UUID Metadata object. + * + * @param parameters - Request configuration parameters. Will fetch UUID metadata object for + * currently configured PubNub client `uuid` if not set. + * @param callback - Request completion handler callback. + */ getUUIDMetadata(parameters: AppContext.GetUUIDMetadataParameters, callback: ResultCallback>): void; + /** + * Fetch a specific UUID Metadata object. + * + * @param [parameters] - Request configuration parameters. Will fetch UUID Metadata object for + * currently configured PubNub client `uuid` if not set. + * + * @returns Asynchronous get UUID metadata response. + */ getUUIDMetadata(parameters?: AppContext.GetUUIDMetadataParameters): Promise>; + /** + * Fetch a specific UUID Metadata object. + * + * @param [parametersOrCallback] - Request configuration parameters or callback from overload. + * @param [callback] - Request completion handler callback. + * + * @returns Asynchronous get UUID metadata response or `void` in case if `callback` provided. + */ _getUUIDMetadata(parametersOrCallback?: AppContext.GetUUIDMetadataParameters | ResultCallback>, callback?: ResultCallback>): Promise | void>; + /** + * Update specific UUID Metadata object. + * + * @param parameters - Request configuration parameters. Will set UUID metadata for currently + * configured PubNub client `uuid` if not set. + * @param callback - Request completion handler callback. + */ setUUIDMetadata(parameters: AppContext.SetUUIDMetadataParameters, callback: ResultCallback>): void; + /** + * Update specific UUID Metadata object. + * + * @param parameters - Request configuration parameters. Will set UUID metadata for currently + * configured PubNub client `uuid` if not set. + * + * @returns Asynchronous set UUID metadata response. + */ setUUIDMetadata(parameters: AppContext.SetUUIDMetadataParameters): Promise>; + /** + * Update specific UUID Metadata object. + * + * @param parameters - Request configuration parameters. Will set UUID metadata for currently + * configured PubNub client `uuid` if not set. + * @param [callback] - Request completion handler callback. + * + * @returns Asynchronous set UUID metadata response or `void` in case if `callback` provided. + */ _setUUIDMetadata(parameters: AppContext.SetUUIDMetadataParameters, callback?: ResultCallback>): Promise | void>; + /** + * Remove UUID Metadata object for currently configured PubNub client `uuid`. + * + * @param callback - Request completion handler callback. + */ removeUUIDMetadata(callback: ResultCallback): void; + /** + * Remove a specific UUID Metadata object. + * + * @param parameters - Request configuration parameters. Will remove UUID metadata for currently + * configured PubNub client `uuid` if not set. + * @param callback - Request completion handler callback. + */ removeUUIDMetadata(parameters: AppContext.RemoveUUIDMetadataParameters, callback: ResultCallback): void; + /** + * Remove a specific UUID Metadata object. + * + * @param [parameters] - Request configuration parameters. Will remove UUID metadata for currently + * configured PubNub client `uuid` if not set. + * + * @returns Asynchronous UUID metadata remove response. + */ removeUUIDMetadata(parameters?: AppContext.RemoveUUIDMetadataParameters): Promise; + /** + * Remove a specific UUID Metadata object. + * + * @param [parametersOrCallback] - Request configuration parameters or callback from overload. + * @param [callback] - Request completion handler callback. + * + * @returns Asynchronous UUID metadata remove response or `void` in case if `callback` provided. + */ _removeUUIDMetadata(parametersOrCallback?: AppContext.RemoveUUIDMetadataParameters | ResultCallback, callback?: ResultCallback): Promise; + /** + * Fetch a paginated list of Channel Metadata objects. + * + * @param callback - Request completion handler callback. + */ getAllChannelMetadata(callback: ResultCallback>): void; + /** + * Fetch a paginated list of Channel Metadata objects. + * + * @param parameters - Request configuration parameters. + * @param callback - Request completion handler callback. + */ getAllChannelMetadata(parameters: AppContext.GetAllMetadataParameters>, callback: ResultCallback>): void; + /** + * Fetch a paginated list of Channel Metadata objects. + * + * @param [parameters] - Request configuration parameters. + * + * @returns Asynchronous get all Channel metadata response. + */ getAllChannelMetadata(parameters?: AppContext.GetAllMetadataParameters>): Promise>; + /** + * Fetch a paginated list of Channel Metadata objects. + * + * @param [parametersOrCallback] - Request configuration parameters or callback from overload. + * @param [callback] - Request completion handler callback. + * + * @returns Asynchronous get all Channel metadata response or `void` in case if `callback` + * provided. + */ _getAllChannelMetadata(parametersOrCallback?: AppContext.GetAllMetadataParameters> | ResultCallback>, callback?: ResultCallback>): Promise | void>; + /** + * Fetch Channel Metadata object. + * + * @param parameters - Request configuration parameters. + * @param callback - Request completion handler callback. + */ getChannelMetadata(parameters: AppContext.GetChannelMetadataParameters, callback: ResultCallback>): void; + /** + * Fetch a specific Channel Metadata object. + * + * @param parameters - Request configuration parameters. + * + * @returns Asynchronous get Channel metadata response. + */ getChannelMetadata(parameters: AppContext.GetChannelMetadataParameters): Promise>; + /** + * Fetch Channel Metadata object. + * + * @param parameters - Request configuration parameters. + * @param [callback] - Request completion handler callback. + * + * @returns Asynchronous get Channel metadata response or `void` in case if `callback` provided. + */ _getChannelMetadata(parameters: AppContext.GetChannelMetadataParameters, callback?: ResultCallback>): Promise | void>; + /** + * Update specific Channel Metadata object. + * + * @param parameters - Request configuration parameters. + * @param callback - Request completion handler callback. + */ setChannelMetadata(parameters: AppContext.SetChannelMetadataParameters, callback: ResultCallback>): void; + /** + * Update specific Channel Metadata object. + * + * @param parameters - Request configuration parameters. + * + * @returns Asynchronous set Channel metadata response. + */ setChannelMetadata(parameters: AppContext.SetChannelMetadataParameters): Promise>; + /** + * Update specific Channel Metadata object. + * + * @param parameters - Request configuration parameters. + * @param [callback] - Request completion handler callback. + * + * @returns Asynchronous set Channel metadata response or `void` in case if `callback` provided. + */ _setChannelMetadata(parameters: AppContext.SetChannelMetadataParameters, callback?: ResultCallback>): Promise | void>; + /** + * Remove Channel Metadata object. + * + * @param parameters - Request configuration parameters. + * @param callback - Request completion handler callback. + */ removeChannelMetadata(parameters: AppContext.RemoveChannelMetadataParameters, callback: ResultCallback): void; + /** + * Remove a specific Channel Metadata object. + * + * @param parameters - Request configuration parameters. + * + * @returns Asynchronous Channel metadata remove response. + */ removeChannelMetadata(parameters: AppContext.RemoveChannelMetadataParameters): Promise; + /** + * Remove a specific Channel Metadata object. + * + * @param parameters - Request configuration parameters. + * @param [callback] - Request completion handler callback. + * + * @returns Asynchronous Channel metadata remove response or `void` in case if `callback` + * provided. + */ _removeChannelMetadata(parameters: AppContext.RemoveChannelMetadataParameters, callback?: ResultCallback): Promise; + /** + * Fetch a paginated list of Channel Member objects. + * + * @param parameters - Request configuration parameters. + * @param callback - Request completion handler callback. + */ getChannelMembers(parameters: AppContext.GetMembersParameters, callback: ResultCallback>): void; + /** + * Fetch a paginated list of Channel Member objects. + * + * @param parameters - Request configuration parameters. + * + * @returns Asynchronous get Channel Members response. + */ getChannelMembers(parameters: AppContext.GetMembersParameters): Promise>; + /** + * Update specific Channel Members list. + * + * @param parameters - Request configuration parameters. + * @param callback - Request completion handler callback. + */ setChannelMembers(parameters: AppContext.SetChannelMembersParameters, callback: ResultCallback>): void; + /** + * Update specific Channel Members list. + * + * @param parameters - Request configuration parameters. + * + * @returns Asynchronous update Channel Members list response. + */ setChannelMembers(parameters: AppContext.SetChannelMembersParameters): Promise>; + /** + * Remove Members from the Channel. + * + * @param parameters - Request configuration parameters. + * @param callback - Request completion handler callback. + */ removeChannelMembers(parameters: AppContext.RemoveMembersParameters, callback: ResultCallback>): void; + /** + * Remove Members from the Channel. + * + * @param parameters - Request configuration parameters. + * + * @returns Asynchronous Channel Members remove response. + */ removeChannelMembers(parameters: AppContext.RemoveMembersParameters): Promise>; + /** + * Fetch a specific UUID Memberships list for currently configured PubNub client `uuid`. + * + * @param callback - Request completion handler callback. + * + * @returns Asynchronous get UUID Memberships list response or `void` in case if `callback` + * provided. + */ getMemberships(callback: ResultCallback>): void; + /** + * Fetch a specific UUID Memberships list. + * + * @param parameters - Request configuration parameters. + * @param callback - Request completion handler callback. + */ getMemberships(parameters: AppContext.GetMembershipsParameters, callback: ResultCallback>): void; + /** + * Fetch a specific UUID Memberships list. + * + * @param [parameters] - Request configuration parameters. Will fetch UUID Memberships list for + * currently configured PubNub client `uuid` if not set. + * + * @returns Asynchronous get UUID Memberships list response. + */ getMemberships(parameters?: AppContext.GetMembershipsParameters): Promise>; + /** + * Update specific UUID Memberships list. + * + * @param parameters - Request configuration parameters. + * @param callback - Request completion handler callback. + */ setMemberships(parameters: AppContext.SetMembershipsParameters, callback: ResultCallback>): void; + /** + * Update specific UUID Memberships list. + * + * @param parameters - Request configuration parameters or callback from overload. + * + * @returns Asynchronous update UUID Memberships list response. + */ setMemberships(parameters: AppContext.SetMembershipsParameters): Promise>; + /** + * Remove a specific UUID Memberships. + * + * @param parameters - Request configuration parameters. + * @param callback - Request completion handler callback. + */ removeMemberships(parameters: AppContext.RemoveMembershipsParameters, callback: ResultCallback>): void; + /** + * Remove a specific UUID Memberships. + * + * @param parameters - Request configuration parameters. + * + * @returns Asynchronous UUID Memberships remove response. + */ removeMemberships(parameters: AppContext.RemoveMembershipsParameters): Promise>; + /** + * Fetch paginated list of specific Space members or specific User memberships. + * + * @param parameters - Request configuration parameters. + * @param [callback] - Request completion handler callback. + * + * @returns Asynchronous get specific Space members or specific User memberships response. + * + * @deprecated Use {@link PubNubObjects#getChannelMembers} or {@link PubNubObjects#getMemberships} methods instead. + */ fetchMemberships(parameters: AppContext.GetMembershipsParameters | AppContext.GetMembersParameters, callback?: ResultCallback | AppContext.UserMembersResponse>): Promise | AppContext.UserMembersResponse | void>; + /** + * Add members to specific Space or memberships specific User. + * + * @param parameters - Request configuration parameters. + * @param [callback] - Request completion handler callback. + * + * @returns Asynchronous add members to specific Space or memberships specific User response or + * `void` in case if `callback` provided. + * + * @deprecated Use {@link PubNubObjects#setChannelMembers} or {@link PubNubObjects#setMemberships} methods instead. + */ addMemberships(parameters: AppContext.SetMembershipsParameters | AppContext.SetChannelMembersParameters, callback?: ResultCallback | AppContext.SetMembersResponse>): Promise | AppContext.SetMembersResponse | void>; } diff --git a/lib/types/core/pubnub-push.d.ts b/lib/types/core/pubnub-push.d.ts index 32bd72558..33d8c02ea 100644 --- a/lib/types/core/pubnub-push.d.ts +++ b/lib/types/core/pubnub-push.d.ts @@ -1,15 +1,64 @@ +/** + * PubNub Push Notifications API module. + */ import { KeySet, ResultCallback, SendRequestFunction, StatusCallback } from './types/api'; import * as Push from './types/api/push'; export default class PubNubPushNotifications { private readonly keySet; private readonly sendRequest; constructor(keySet: KeySet, sendRequest: SendRequestFunction); + /** + * Fetch device's push notification enabled channels. + * + * @param parameters - Request configuration parameters. + * @param callback - Request completion handler callback. + */ listChannels(parameters: Push.ListDeviceChannelsParameters, callback: ResultCallback): void; + /** + * Fetch device's push notification enabled channels. + * + * @param parameters - Request configuration parameters. + * + * @returns Asynchronous get device channels response. + */ listChannels(parameters: Push.ListDeviceChannelsParameters): Promise; + /** + * Enable push notifications on channels for device. + * + * @param parameters - Request configuration parameters. + * @param callback - Request completion handler callback. + */ addChannels(parameters: Push.ManageDeviceChannelsParameters, callback: StatusCallback): void; + /** + * Enable push notifications on channels for device. + * + * @param parameters - Request configuration parameters. + */ addChannels(parameters: Push.ManageDeviceChannelsParameters): Promise; + /** + * Disable push notifications on channels for device. + * + * @param parameters - Request configuration parameters. + * @param callback - Request completion handler callback. + */ removeChannels(parameters: Push.ManageDeviceChannelsParameters, callback: StatusCallback): void; + /** + * Disable push notifications on channels for device. + * + * @param parameters - Request configuration parameters. + */ removeChannels(parameters: Push.ManageDeviceChannelsParameters): Promise; + /** + * Disable push notifications for device. + * + * @param parameters - Request configuration parameters. + * @param callback - Request completion handler callback. + */ deleteDevice(parameters: Push.RemoveDeviceParameters, callback: StatusCallback): void; + /** + * Disable push notifications for device. + * + * @param parameters - Request configuration parameters. + */ deleteDevice(parameters: Push.RemoveDeviceParameters): Promise; } diff --git a/lib/types/core/types/api/access-panager.d.ts b/lib/types/core/types/api/access-panager.d.ts index 70ad4f31e..36f4c5ca4 100644 --- a/lib/types/core/types/api/access-panager.d.ts +++ b/lib/types/core/types/api/access-panager.d.ts @@ -1,124 +1,466 @@ +/** + * Metadata which will be associated with access token. + */ export type Metadata = Record; +/** + * Channel-specific token permissions. + */ export type ChannelTokenPermissions = { + /** + * Whether `read` operations are permitted for corresponding level or not. + */ read?: boolean; + /** + * Whether `write` operations are permitted for corresponding level or not. + */ write?: boolean; + /** + * Whether `get` operations are permitted for corresponding level or not. + */ get?: boolean; + /** + * Whether `manage` operations are permitted for corresponding level or not. + */ manage?: boolean; + /** + * Whether `update` operations are permitted for corresponding level or not. + */ update?: boolean; + /** + * Whether `join` operations are permitted for corresponding level or not. + */ join?: boolean; + /** + * Whether `delete` operations are permitted for corresponding level or not. + */ delete?: boolean; }; +/** + * Space-specific token permissions. + */ type SpaceTokenPermissions = ChannelTokenPermissions; +/** + * Channel group-specific token permissions. + */ export type ChannelGroupTokenPermissions = { + /** + * Whether `read` operations are permitted for corresponding level or not. + */ read?: boolean; + /** + * Whether `manage` operations are permitted for corresponding level or not. + */ manage?: boolean; }; +/** + * Uuid-specific token permissions. + */ export type UuidTokenPermissions = { + /** + * Whether `get` operations are permitted for corresponding level or not. + */ get?: boolean; + /** + * Whether `update` operations are permitted for corresponding level or not. + */ update?: boolean; + /** + * Whether `delete` operations are permitted for corresponding level or not. + */ delete?: boolean; }; +/** + * User-specific token permissions. + */ type UserTokenPermissions = UuidTokenPermissions; +/** + * Generate access token with permissions. + * + * Generate time-limited access token with required permissions for App Context objects. + */ export type ObjectsGrantTokenParameters = { + /** + * Total number of minutes for which the token is valid. + * + * The minimum allowed value is `1`. + * The maximum is `43,200` minutes (`30` days). + */ ttl: number; + /** + * Object containing resource permissions. + */ resources?: { + /** + * Object containing `spaces` metadata permissions. + */ spaces?: Record; + /** + * Object containing `users` permissions. + */ users?: Record; }; + /** + * Object containing permissions to multiple resources specified by a RegEx pattern. + */ patterns?: { + /** + * Object containing `spaces` metadata permissions. + */ spaces?: Record; + /** + * Object containing `users` permissions. + */ users?: Record; }; + /** + * Extra metadata to be published with the request. + * + * **Important:** Values must be scalar only; `arrays` or `objects` aren't supported. + */ meta?: Metadata; + /** + * Single `userId` which is authorized to use the token to make API requests to PubNub. + */ authorizedUserId?: string; }; +/** + * Generate token with permissions. + * + * Generate time-limited access token with required permissions for resources. + */ export type GrantTokenParameters = { + /** + * Total number of minutes for which the token is valid. + * + * The minimum allowed value is `1`. + * The maximum is `43,200` minutes (`30` days). + */ ttl: number; + /** + * Object containing resource permissions. + */ resources?: { + /** + * Object containing `uuid` metadata permissions. + */ uuids?: Record; + /** + * Object containing `channel` permissions. + */ channels?: Record; + /** + * Object containing `channel group` permissions. + */ groups?: Record; }; + /** + * Object containing permissions to multiple resources specified by a RegEx pattern. + */ patterns?: { + /** + * Object containing `uuid` metadata permissions to apply to all `uuids` matching the RegEx + * pattern. + */ uuids?: Record; + /** + * Object containing `channel` permissions to apply to all `channels` matching the RegEx + * pattern. + */ channels?: Record; + /** + * Object containing `channel group` permissions to apply to all `channel groups` matching the + * RegEx pattern. + */ groups?: Record; }; + /** + * Extra metadata to be published with the request. + * + * **Important:** Values must be scalar only; `arrays` or `objects` aren't supported. + */ meta?: Metadata; + /** + * Single `uuid` which is authorized to use the token to make API requests to PubNub. + */ authorized_uuid?: string; }; +/** + * Response with generated access token. + */ export type GrantTokenResponse = string; export type RevokeParameters = { + /** + * Access token for which permissions should be revoked. + */ token: string; }; +/** + * Response with revoked access token. + */ export type RevokeTokenResponse = Record; +/** + * Channel-specific permissions. + * + * Permissions include objects to the App Context Channel object as well. + */ type ChannelPermissions = { + /** + * Whether `read` operations are permitted for corresponding level or not. + */ r?: 0 | 1; + /** + * Whether `write` operations are permitted for corresponding level or not. + */ w?: 0 | 1; + /** + * Whether `delete` operations are permitted for corresponding level or not. + */ d?: 0 | 1; + /** + * Whether `get` operations are permitted for corresponding level or not. + */ g?: 0 | 1; + /** + * Whether `update` operations are permitted for corresponding level or not. + */ u?: 0 | 1; + /** + * Whether `manage` operations are permitted for corresponding level or not. + */ m?: 0 | 1; + /** + * Whether `join` operations are permitted for corresponding level or not. + */ j?: 0 | 1; + /** + * Duration for which permissions has been granted. + */ ttl?: number; }; +/** + * Channel group-specific permissions. + */ type ChannelGroupPermissions = { + /** + * Whether `read` operations are permitted for corresponding level or not. + */ r?: 0 | 1; + /** + * Whether `manage` operations are permitted for corresponding level or not. + */ m?: 0 | 1; + /** + * Duration for which permissions has been granted. + */ ttl?: number; }; +/** + * App Context User-specific permissions. + */ type UserPermissions = { + /** + * Whether `get` operations are permitted for corresponding level or not. + */ g?: 0 | 1; + /** + * Whether `update` operations are permitted for corresponding level or not. + */ u?: 0 | 1; + /** + * Whether `delete` operations are permitted for corresponding level or not. + */ d?: 0 | 1; + /** + * Duration for which permissions has been granted. + */ ttl?: number; }; +/** + * Common permissions audit response content. + */ type BaseAuditResponse = { + /** + * Permissions level. + */ level: Level; + /** + * Subscription key at which permissions has been granted. + */ subscribe_key: string; + /** + * Duration for which permissions has been granted. + */ ttl?: number; }; +/** + * Auth keys permissions for specified `level`. + */ type AuthKeysPermissions = { + /** + * Auth keys-based permissions for specified `level` permission. + */ auths: Record; }; +/** + * Single channel permissions audit result. + */ type ChannelPermissionsResponse = BaseAuditResponse<'channel+auth'> & { + /** + * Name of channel for which permissions audited. + */ channel: string; } & AuthKeysPermissions; +/** + * Multiple channels permissions audit result. + */ type ChannelsPermissionsResponse = BaseAuditResponse<'channel'> & { + /** + * Per-channel permissions. + */ channels: Record>; }; +/** + * Single channel group permissions result. + */ type ChannelGroupPermissionsResponse = BaseAuditResponse<'channel-group+auth'> & { + /** + * Name of channel group for which permissions audited. + */ 'channel-group': string; } & AuthKeysPermissions; +/** + * Multiple channel groups permissions audit result. + */ type ChannelGroupsPermissionsResponse = BaseAuditResponse<'channel'> & { + /** + * Per-channel group permissions. + */ 'channel-groups': Record>; }; +/** + * App Context User permissions audit result. + */ type UserPermissionsResponse = BaseAuditResponse<'user'> & { + /** + * Name of channel for which `user` permissions audited. + */ channel: string; } & AuthKeysPermissions; +/** + * Global sub-key level permissions audit result. + */ type SubKeyPermissionsResponse = BaseAuditResponse<'subkey'> & { + /** + * Per-channel permissions. + */ channels: Record>; + /** + * Per-channel group permissions. + */ 'channel-groups': Record>; + /** + * Per-object permissions. + */ objects: Record>; }; +/** + * Response with permission information. + */ export type PermissionsResponse = ChannelPermissionsResponse | ChannelsPermissionsResponse | ChannelGroupPermissionsResponse | ChannelGroupsPermissionsResponse | UserPermissionsResponse | SubKeyPermissionsResponse; +/** + * Audit permissions for provided auth keys / global permissions. + * + * Audit permissions on specific channel and / or channel group for the set of auth keys. + */ export type AuditParameters = { + /** + * Name of channel for which channel-based permissions should be checked for {@link authKeys}. + */ channel?: string; + /** + * Name of channel group for which channel group-based permissions should be checked for {@link authKeys}. + */ channelGroup?: string; + /** + * List of auth keys for which permissions should be checked. + * + * Leave this empty to check channel / group -based permissions or global permissions. + * + * @default `[]` + */ authKeys?: string[]; }; +/** + * Grant permissions for provided auth keys / global permissions. + * + * Grant permissions on specific channel and / or channel group for the set of auth keys. + */ export type GrantParameters = { + /** + * List of channels for which permissions should be granted. + */ channels?: string[]; + /** + * List of channel groups for which permissions should be granted. + */ channelGroups?: string[]; + /** + * List of App Context UUID for which permissions should be granted. + */ uuids?: string[]; + /** + * List of auth keys for which permissions should be granted on specified objects. + * + * Leave this empty to grant channel / group -based permissions or global permissions. + */ authKeys?: string[]; + /** + * Whether `read` operations are permitted for corresponding level or not. + * + * @default `false` + */ read?: boolean; + /** + * Whether `write` operations are permitted for corresponding level or not. + * + * @default `false` + */ write?: boolean; + /** + * Whether `delete` operations are permitted for corresponding level or not. + * + * @default `false` + */ delete?: boolean; + /** + * Whether `get` operations are permitted for corresponding level or not. + * + * @default `false` + */ get?: boolean; + /** + * Whether `update` operations are permitted for corresponding level or not. + * + * @default `false` + */ update?: boolean; + /** + * Whether `manage` operations are permitted for corresponding level or not. + * + * @default `false` + */ manage?: boolean; + /** + * Whether `join` operations are permitted for corresponding level or not. + * + * @default `false` + */ join?: boolean; + /** + * For how long permissions should be effective (in minutes). + * + * @default `1440` + */ ttl?: number; }; export {}; diff --git a/lib/types/core/types/api/app-context.d.ts b/lib/types/core/types/api/app-context.d.ts index eea32fe4e..2017fdcf7 100644 --- a/lib/types/core/types/api/app-context.d.ts +++ b/lib/types/core/types/api/app-context.d.ts @@ -1,207 +1,875 @@ +/** + * Partial nullability helper type. + */ type PartialNullable = { [P in keyof T]?: T[P] | null; }; +/** + * Custom data which should be associated with metadata objects or their relation. + */ export type CustomData = { [key: string]: string | number | boolean | null; }; +/** + * Type provides shape of App Context parameters which is common to the all objects types to + * be updated. + */ type ObjectParameters = { custom?: Custom; }; +/** + * Type provides shape of App Context object which is common to the all objects types received + * from the PubNub service. + */ export type ObjectData = { + /** + * Unique App Context object identifier. + * + * **Important:** For channel it is different from the channel metadata object name. + */ id: string; + /** + * Last date and time when App Context object has been updated. + * + * String built from date using ISO 8601. + */ updated: string; + /** + * App Context version hash. + */ eTag: string; + /** + * Additional data associated with App Context object. + * + * **Important:** Values must be scalars; only arrays or objects are supported. + * {@link /docs/sdks/javascript/api-reference/objects#app-context-filtering-language-definition|App Context + * filtering language} doesn’t support filtering by custom properties. + */ custom?: Custom | null; }; +/** + * Type provides shape of object which let establish relation between metadata objects. + */ type ObjectsRelation = { + /** + * App Context object unique identifier. + */ id: string; + /** + * App Context objects relation status. + */ status?: string; + /** + * Additional data associated with App Context object relation (membership or members). + * + * **Important:** Values must be scalars; only arrays or objects are supported. + * {@link /docs/sdks/javascript/api-reference/objects#app-context-filtering-language-definition|App Context + * filtering language} doesn’t support filtering by custom properties. + */ custom?: Custom; }; +/** + * Response page cursor. + */ type Page = { + /** + * Random string returned from the server, indicating a specific position in a data set. + * + * Used for forward pagination, it fetches the next page, allowing you to continue from where + * you left off. + */ next?: string; + /** + * Random string returned from the server, indicating a specific position in a data set. + * + * Used for backward pagination, it fetches the previous page, enabling access to earlier + * data. + * + * **Important:** Ignored if the `next` parameter is supplied. + */ prev?: string; }; +/** + * Metadata objects include options. + * + * Allows to configure what additional information should be included into service response. + */ type IncludeOptions = { + /** + * Whether to include total number of App Context objects in the response. + * + * @default `false` + */ totalCount?: boolean; + /** + * Whether to include App Context object `custom` field in the response. + * + * @default `false` + */ customFields?: boolean; }; +/** + * Membership objects include options. + * + * Allows to configure what additional information should be included into service response. + */ type MembershipsIncludeOptions = IncludeOptions & { + /** + * Whether to include all {@link ChannelMetadata} fields in the response. + * + * @default `false` + */ channelFields?: boolean; + /** + * Whether to include {@link ChannelMetadata} `custom` field in the response. + * + * @default `false` + */ customChannelFields?: boolean; + /** + * Whether to include the membership's status field in the response. + * + * @default `false` + */ statusField?: boolean; + /** + * Whether to include the channel's status field in the response. + * + * @default `false` + */ channelStatusField?: boolean; + /** + * Whether to include channel's type fields in the response. + * + * @default `false` + */ channelTypeField?: boolean; }; +/** + * Members objects include options. + * + * Allows to configure what additional information should be included into service response. + */ type MembersIncludeOptions = IncludeOptions & { + /** + * Whether to include all {@link UUIMetadata} fields in the response. + * + * @default `false` + */ UUIDFields?: boolean; + /** + * Whether to include {@link UUIMetadata} `custom` field in the response. + * + * @default `false` + */ customUUIDFields?: boolean; + /** + * Whether to include the members's status field in the response. + * + * @default `false` + */ statusField?: boolean; + /** + * Whether to include the user's status field in the response. + * + * @default `false` + */ UUIDStatusField?: boolean; + /** + * Whether to include user's type fields in the response. + * + * @default `false` + */ UUIDTypeField?: boolean; }; +/** + * Type provides shape of App Context parameters which is common to the all objects types to + * fetch them by pages. + */ type PagedRequestParameters = { + /** + * Fields which can be additionally included into response. + */ include?: Include; + /** + * Expression used to filter the results. + * + * Only objects whose properties satisfy the given expression are returned. The filter language is + * {@link /docs/sdks/javascript/api-reference/objects#app-context-filtering-language-definition|defined here}. + */ filter?: string; + /** + * Fetched App Context objects sorting options. + */ sort?: Sort; + /** + * Number of objects to return in response. + * + * **Important:** Maximum for this API is `100` objects per-response. + * + * @default `100` + */ limit?: number; + /** + * Response pagination configuration. + */ page?: Page; }; +/** + * Type provides shape of App Context object fetch response which is common to the all objects + * types received from the PubNub service. + */ type ObjectResponse = { + /** + * App Context objects list fetch result status code. + */ status: number; + /** + * Received App Context object information. + */ data: ObjectType; }; +/** + * Type provides shape of App Context objects fetch response which is common to the all + * objects types received from the PubNub service. + */ type PagedResponse = ObjectResponse & { + /** + * Total number of App Context objects in the response. + */ totalCount?: number; + /** + * Random string returned from the server, indicating a specific position in a data set. + * + * Used for forward pagination, it fetches the next page, allowing you to continue from where + * you left off. + */ next?: string; + /** + * Random string returned from the server, indicating a specific position in a data set. + * + * Used for backward pagination, it fetches the previous page, enabling access to earlier + * data. + * + * **Important:** Ignored if the `next` parameter is supplied. + */ prev?: string; }; +/** + * Key-value pair of a property to sort by, and a sort direction. + */ type MetadataSortingOptions = keyof Omit | ({ [K in keyof Omit]?: 'asc' | 'desc' | null; } & { [key: `custom.${string}`]: 'asc' | 'desc' | null; }); +/** + * Key-value pair of a property to sort by, and a sort direction. + */ type MembershipsSortingOptions = 'channel.id' | 'channel.name' | 'channel.description' | 'channel.updated' | 'space.id' | 'space.name' | 'space.description' | 'space.updated' | 'updated' | { + /** + * Sort results by channel's `id` in ascending (`asc`) or descending (`desc`) order. + * + * Specify `null` for default sorting direction (ascending). + */ 'channel.id'?: 'asc' | 'desc' | null; + /** + * Sort results by channel's `name` in ascending (`asc`) or descending (`desc`) order. + * + * Specify `null` for default sorting direction (ascending). + */ 'channel.name'?: 'asc' | 'desc' | null; + /** + * Sort results by channel's `description` in ascending (`asc`) or descending (`desc`) order. + * + * Specify `null` for default sorting direction (ascending). + */ 'channel.description'?: 'asc' | 'desc' | null; + /** + * Sort results by channel's `update` in ascending (`asc`) or descending (`desc`) order. + * + * Specify `null` for default sorting direction (ascending). + */ 'channel.updated'?: 'asc' | 'desc' | null; + /** + * Sort results by channel's `id` in ascending (`asc`) or descending (`desc`) order. + * + * Specify `null` for default sorting direction (ascending). + * + * @deprecated Use `channel.id` instead. + */ 'space.id'?: 'asc' | 'desc' | null; + /** + * Sort results by channel's `name` in ascending (`asc`) or descending (`desc`) order. + * + * Specify `null` for default sorting direction (ascending). + * + * @deprecated Use `channel.name` instead. + */ 'space.name'?: 'asc' | 'desc' | null; + /** + * Sort results by channel's `description` in ascending (`asc`) or descending (`desc`) order. + * + * Specify `null` for default sorting direction (ascending). + * + * @deprecated Use `channel.name` instead. + */ 'space.description'?: 'asc' | 'desc' | null; + /** + * Sort results by channel's `update` in ascending (`asc`) or descending (`desc`) order. + * + * Specify `null` for default sorting direction (ascending). + * + * @deprecated Use `channel.updated` instead. + */ 'space.updated'?: 'asc' | 'desc' | null; + /** + * Sort results by `updated` in ascending (`asc`) or descending (`desc`) order. + * + * Specify `null` for default sorting direction (ascending). + */ updated?: 'asc' | 'desc' | null; }; +/** + * Key-value pair of a property to sort by, and a sort direction. + */ type MembersSortingOptions = 'uuid.id' | 'uuid.name' | 'uuid.updated' | 'user.id' | 'user.name' | 'user.updated' | 'updated' | { + /** + * Sort results by user's `id` in ascending (`asc`) or descending (`desc`) order. + * + * Specify `null` for default sorting direction (ascending). + */ 'uuid.id'?: 'asc' | 'desc' | null; + /** + * Sort results by user's `name` in ascending (`asc`) or descending (`desc`) order. + * + * Specify `null` for default sorting direction (ascending). + */ 'uuid.name'?: 'asc' | 'desc' | null; + /** + * Sort results by user's `update` in ascending (`asc`) or descending (`desc`) order. + * + * Specify `null` for default sorting direction (ascending). + */ 'uuid.updated'?: 'asc' | 'desc' | null; + /** + * Sort results by user's `id` in ascending (`asc`) or descending (`desc`) order. + * + * Specify `null` for default sorting direction (ascending). + * + * @deprecated Use `uuid.id` instead. + */ 'user.id'?: 'asc' | 'desc' | null; + /** + * Sort results by user's `name` in ascending (`asc`) or descending (`desc`) order. + * + * Specify `null` for default sorting direction (ascending). + * + * @deprecated Use `uuid.name` instead. + */ 'user.name'?: 'asc' | 'desc' | null; + /** + * Sort results by user's `update` in ascending (`asc`) or descending (`desc`) order. + * + * Specify `null` for default sorting direction (ascending). + * + * @deprecated Use `uuid.updated` instead. + */ 'user.updated'?: 'asc' | 'desc' | null; + /** + * Sort results by `updated` in ascending (`asc`) or descending (`desc`) order. + * + * Specify `null` for default sorting direction (ascending). + */ updated?: 'asc' | 'desc' | null; }; +/** + * Fetch All UUID or Channel Metadata request parameters. + */ export type GetAllMetadataParameters = PagedRequestParameters>; +/** + * Type which describes own UUID metadata object fields. + */ type UUIDMetadataFields = { + /** + * Display name for the user. + */ name?: string; + /** + * The user's email address. + */ email?: string; + /** + * User's identifier in an external system. + */ externalId?: string; + /** + * The URL of the user's profile picture. + */ profileUrl?: string; + /** + * User's object type information. + */ type?: string; + /** + * User's object status. + */ status?: string; }; +/** + * Updated UUID metadata object. + * + * Type represents updated UUID metadata object which will be pushed to the PubNub service. + */ type UUIDMetadata = ObjectParameters & Partial; +/** + * Received UUID metadata object. + * + * Type represents UUID metadata retrieved from the PubNub service. + */ export type UUIDMetadataObject = ObjectData & PartialNullable; +/** + * Response with fetched page of UUID metadata objects. + */ export type GetAllUUIDMetadataResponse = PagedResponse>; +/** + * Fetch UUID Metadata request parameters. + */ export type GetUUIDMetadataParameters = { + /** + * Unique user identifier. + * + * **Important:** If not supplied then current user's uuid is used. + * + * @default Current `uuid`. + */ uuid?: string; + /** + * Unique user identifier. + * + * **Important:** If not supplied then current user's uuid is used. + * + * @default Current `userId`. + * + * @deprecated Use `getUUIDMetadata()` method instead. + */ userId?: string; + /** + * Fields which can be additionally included into response. + */ include?: Omit; }; +/** + * Response with requested UUID metadata object. + */ export type GetUUIDMetadataResponse = ObjectResponse>; +/** + * Update UUID Metadata request parameters. + */ export type SetUUIDMetadataParameters = { + /** + * Unique user identifier. + * + * **Important:** If not supplied then current user's uuid is used. + * + * @default Current `uuid`. + */ uuid?: string; + /** + * Unique user identifier. + * + * **Important:** If not supplied then current user's uuid is used. + * + * @default Current `userId`. + * + * @deprecated Use `setUUIDMetadata()` method instead. + */ userId?: string; + /** + * Metadata, which should be associated with UUID. + */ data: UUIDMetadata; + /** + * Fields which can be additionally included into response. + */ include?: Omit; }; +/** + * Response with result of the UUID metadata object update. + */ export type SetUUIDMetadataResponse = ObjectResponse>; +/** + * Remove UUID Metadata request parameters. + */ export type RemoveUUIDMetadataParameters = { + /** + * Unique user identifier. + * + * **Important:** If not supplied then current user's uuid is used. + * + * @default Current `uuid`. + */ uuid?: string; + /** + * Unique user identifier. + * + * **Important:** If not supplied then current user's uuid is used. + * + * @default Current `userId`. + * + * @deprecated Use `removeUUIDMetadata()` method instead. + */ userId?: string; }; +/** + * Response with result of the UUID metadata removal. + */ export type RemoveUUIDMetadataResponse = ObjectResponse>; +/** + * Type which describes own Channel metadata object fields. + */ type ChannelMetadataFields = { + /** + * Name of a channel. + */ name?: string; + /** + * Description of a channel. + */ description?: string; + /** + * Channel's object type information. + */ type?: string; + /** + * Channel's object status. + */ status?: string; }; +/** + * Updated channel metadata object. + * + * Type represents updated channel metadata object which will be pushed to the PubNub service. + */ type ChannelMetadata = ObjectParameters & Partial; +/** + * Received channel metadata object. + * + * Type represents chanel metadata retrieved from the PubNub service. + */ export type ChannelMetadataObject = ObjectData & PartialNullable; +/** + * Response with fetched page of channel metadata objects. + */ export type GetAllChannelMetadataResponse = PagedResponse>; +/** + * Fetch Channel Metadata request parameters. + */ export type GetChannelMetadataParameters = { + /** + * Channel name. + */ channel: string; + /** + * Space identifier. + * + * @deprecated Use `getChannelMetadata()` method instead. + */ spaceId?: string; + /** + * Fields which can be additionally included into response. + */ include?: Omit; }; +/** + * Response with requested channel metadata object. + */ export type GetChannelMetadataResponse = ObjectResponse>; +/** + * Update Channel Metadata request parameters. + */ export type SetChannelMetadataParameters = { + /** + * Channel name. + */ channel: string; + /** + * Space identifier. + * + * @deprecated Use `setChannelMetadata()` method instead. + */ spaceId?: string; + /** + * Metadata, which should be associated with UUID. + */ data: ChannelMetadata; + /** + * Fields which can be additionally included into response. + */ include?: Omit; }; +/** + * Response with result of the channel metadata object update. + */ export type SetChannelMetadataResponse = ObjectResponse>; +/** + * Remove Channel Metadata request parameters. + */ export type RemoveChannelMetadataParameters = { + /** + * Channel name. + */ channel: string; + /** + * Space identifier. + * + * @deprecated Use `removeChannelMetadata()` method instead. + */ spaceId?: string; }; +/** + * Response with result of the channel metadata removal. + */ export type RemoveChannelMetadataResponse = ObjectResponse>; +/** + * Related channel metadata object. + * + * Type represents chanel metadata which has been used to create membership relation with UUID. + */ type MembershipsObject = Omit, 'id'> & { channel: ChannelMetadataObject | { id: string; }; }; +/** + * Response with fetched page of UUID membership objects. + */ type MembershipsResponse = PagedResponse>; +/** + * Fetch Memberships request parameters. + */ export type GetMembershipsParameters = PagedRequestParameters & { + /** + * Unique user identifier. + * + * **Important:** If not supplied then current user's uuid is used. + * + * @default Current `uuid`. + */ uuid?: string; + /** + * Unique user identifier. + * + * **Important:** If not supplied then current user's uuid is used. + * + * @default Current `uuidId`. + * + * @deprecated Use `uuid` field instead. + */ userId?: string; }; +/** + * Response with requested channel memberships information. + */ export type GetMembershipsResponse = MembershipsResponse; +/** + * Update Memberships request parameters. + */ export type SetMembershipsParameters = PagedRequestParameters, MembershipsSortingOptions> & { + /** + * Unique user identifier. + * + * **Important:** If not supplied then current user's uuid is used. + * + * @default Current `uuid`. + */ uuid?: string; + /** + * Unique user identifier. + * + * **Important:** If not supplied then current user's uuid is used. + * + * @default Current `userId`. + * + * @deprecated Use `uuid` field instead. + */ userId?: string; + /** + * List of channels with which UUID membership should be established. + */ channels: Array>; + /** + * List of channels with which UUID membership should be established. + * + * @deprecated Use `channels` field instead. + */ spaces?: Array, 'id'> & { + /** + * Unique Space object identifier. + */ spaceId: string; })>; }; +/** + * Response with requested channel memberships information change. + */ export type SetMembershipsResponse = MembershipsResponse; +/** + * Remove Memberships request parameters. + */ export type RemoveMembershipsParameters = PagedRequestParameters & { + /** + * Unique user identifier. + * + * **Important:** If not supplied then current user's uuid is used. + * + * @default Current `uuid`. + */ uuid?: string; + /** + * Unique user identifier. + * + * **Important:** If not supplied then current user's uuid is used. + * + * @default Current `userId`. + * + * @deprecated Use {@link uuid} field instead. + */ userId?: string; + /** + * List of channels for which membership which UUID should be removed. + */ channels: string[]; + /** + * List of space names for which membership which UUID should be removed. + * + * @deprecated Use {@link channels} field instead. + */ spaceIds?: string[]; }; +/** + * Response with remaining memberships. + */ export type RemoveMembershipsResponse = MembershipsResponse; +/** + * Related UUID metadata object. + * + * Type represents UUID metadata which has been used to when added members to the channel. + */ type MembersObject = Omit, 'id'> & { uuid: UUIDMetadataObject | { id: string; }; }; +/** + * Response with fetched page of channel member objects. + */ type MembersResponse = PagedResponse>; +/** + * Fetch Members request parameters. + */ export type GetMembersParameters = PagedRequestParameters & { + /** + * Channel name. + */ channel: string; + /** + * Space identifier. + * + * @deprecated Use `channel` field instead. + */ spaceId?: string; }; +/** + * Response with requested channel memberships information. + */ export type GetMembersResponse = MembersResponse; +/** + * Update Members request parameters. + */ export type SetChannelMembersParameters = PagedRequestParameters, MembersSortingOptions> & { + /** + * Channel name. + */ channel: string; + /** + * Space identifier. + * + * @deprecated Use `channel` field instead. + */ spaceId?: string; + /** + * List of UUIDs which should be added as `channel` members. + */ uuids: Array>; + /** + * List of UUIDs which should be added as `channel` members. + * + * @deprecated Use `uuids` field instead. + */ users?: Array, 'id'> & { + /** + * Unique User object identifier. + */ userId: string; })>; }; +/** + * Response with requested channel members information change. + */ export type SetMembersResponse = MembersResponse; +/** + * Remove Members request parameters. + */ export type RemoveMembersParameters = PagedRequestParameters & { + /** + * Channel name. + */ channel: string; + /** + * Space identifier. + * + * @deprecated Use {@link channel} field instead. + */ spaceId?: string; + /** + * List of UUIDs which should be removed from the `channel` members list. + * removed. + */ uuids: string[]; + /** + * List of user identifiers which should be removed from the `channel` members list. + * removed. + * + * @deprecated Use {@link uuids} field instead. + */ userIds?: string[]; }; +/** + * Response with remaining members. + */ export type RemoveMembersResponse = MembersResponse; +/** + * Related User metadata object. + * + * Type represents User metadata which has been used to when added members to the Space. + */ type UserMembersObject = Omit, 'id'> & { user: UUIDMetadataObject | { id: string; }; }; +/** + * Response with fetched page of Space member objects. + */ export type UserMembersResponse = PagedResponse>; type SpaceMembershipObject = Omit, 'id'> & { space: ChannelMetadataObject | { id: string; }; }; +/** + * Response with fetched page of User membership objects. + */ export type SpaceMembershipsResponse = PagedResponse>; export {}; diff --git a/lib/types/core/types/api/channel-groups.d.ts b/lib/types/core/types/api/channel-groups.d.ts index c2408d009..80cd4717a 100644 --- a/lib/types/core/types/api/channel-groups.d.ts +++ b/lib/types/core/types/api/channel-groups.d.ts @@ -1,18 +1,57 @@ +/** + * Add or remove Channels to the channel group request parameters. + */ export type ManageChannelGroupChannelsParameters = { + /** + * Name of the channel group for which channels list should be changed. + */ channelGroup: string; + /** + * List of channels to be added or removed. + */ channels: string[]; }; +/** + * Channel group channels list manage response. + */ export type ManageChannelGroupChannelsResponse = Record; +/** + * Response with result of the all channel groups list. + */ export type ListAllChannelGroupsResponse = { + /** + * All channel groups with channels. + */ groups: string[]; }; +/** + * List Channel Group Channels request parameters. + */ export type ListChannelGroupChannelsParameters = { + /** + * Name of the channel group for which list of channels should be retrieved. + */ channelGroup: string; }; +/** + * Response with result of the list channel group channels. + */ export type ListChannelGroupChannelsResponse = { + /** + * List of the channels registered withing specified channel group. + */ channels: string[]; }; +/** + * Delete Channel Group request parameters. + */ export type DeleteChannelGroupParameters = { + /** + * Name of the channel group which should be removed. + */ channelGroup: string; }; +/** + * Delete channel group response. + */ export type DeleteChannelGroupResponse = Record; diff --git a/lib/types/core/types/api/file-sharing.d.ts b/lib/types/core/types/api/file-sharing.d.ts index dbc5552a4..5bc19beee 100644 --- a/lib/types/core/types/api/file-sharing.d.ts +++ b/lib/types/core/types/api/file-sharing.d.ts @@ -1,85 +1,357 @@ +/** + * File Sharing REST API module. + */ import { PubNubFileInterface } from '../file'; import { Payload } from './index'; +/** + * Shared file object. + */ export type SharedFile = { + /** + * Name with which file has been stored. + */ name: string; + /** + * Unique service-assigned file identifier. + */ id: string; + /** + * Shared file size. + */ size: number; + /** + * ISO 8601 time string when file has been shared. + */ created: string; }; +/** + * List Files request parameters. + */ export type ListFilesParameters = { + /** + * Name of channel for which list of files should be requested. + */ channel: string; + /** + * How many entries return with single response. + */ limit?: number; + /** + * Next files list page token. + */ next?: string; }; +/** + * List Files request response. + */ export type ListFilesResponse = { + /** + * Files list fetch result status code. + */ status: number; + /** + * List of fetched file objects. + */ data: SharedFile[]; + /** + * Next files list page token. + */ next: string; + /** + * Number of retrieved files. + */ count: number; }; +/** + * Send File request parameters. + */ export type SendFileParameters = Omit & { + /** + * Channel to send the file to. + */ channel: string; + /** + * File to send. + */ file: FileParameters; }; +/** + * Send File request response. + */ export type SendFileResponse = PublishFileMessageResponse & { + /** + * Send file request processing status code. + */ status: number; + /** + * Actual file name under which file has been stored. + * + * File name and unique {@link id} can be used to download file from the channel later. + * + * **Important:** Actual file name may be different from the one which has been used during file + * upload. + */ name: string; + /** + * Unique file identifier. + * + * Unique file identifier and it's {@link name} can be used to download file from the channel + * later. + */ id: string; }; +/** + * Upload File request parameters. + */ export type UploadFileParameters = { + /** + * Unique file identifier. + * + * Unique file identifier, and it's {@link fileName} can be used to download file from the channel + * later. + */ fileId: string; + /** + * Actual file name under which file has been stored. + * + * File name and unique {@link fileId} can be used to download file from the channel later. + * + * **Note:** Actual file name may be different from the one which has been used during file + * upload. + */ fileName: string; + /** + * File which should be uploaded. + */ file: PubNubFileInterface; + /** + * Pre-signed file upload Url. + */ uploadUrl: string; + /** + * An array of form fields to be used in the pre-signed POST request. + * + * **Important:** Form data fields should be passed in exact same order as received from + * the PubNub service. + */ formFields: { + /** + * Form data field name. + */ name: string; + /** + * Form data field value. + */ value: string; }[]; }; +/** + * Upload File request response. + */ export type UploadFileResponse = { + /** + * Upload File request processing status code. + */ status: number; + /** + * Service processing result response. + */ message: Payload; }; +/** + * Generate File Upload URL request parameters. + */ export type GenerateFileUploadUrlParameters = { + /** + * Name of channel to which file should be uploaded. + */ channel: string; + /** + * Actual name of the file which should be uploaded. + */ name: string; }; +/** + * Generation File Upload URL request response. + */ export type GenerateFileUploadUrlResponse = { + /** + * Unique file identifier. + * + * Unique file identifier, and it's {@link name} can be used to download file from the channel + * later. + */ id: string; + /** + * Actual file name under which file has been stored. + * + * File name and unique {@link id} can be used to download file from the channel later. + * + * **Note:** Actual file name may be different from the one which has been used during file + * upload. + */ name: string; + /** + * Pre-signed URL for file upload. + */ url: string; + /** + * An array of form fields to be used in the pre-signed POST request. + * + * **Important:** Form data fields should be passed in exact same order as received from + * the PubNub service. + */ formFields: { + /** + * Form data field name. + */ name: string; + /** + * Form data field value. + */ value: string; }[]; }; +/** + * Publish File Message request parameters. + */ export type PublishFileMessageParameters = { + /** + * Name of channel to which file has been sent. + */ channel: string; + /** + * File annotation message. + */ message?: Payload; + /** + * Custom file and message encryption key. + * + * @deprecated Use {@link Configuration#cryptoModule|cryptoModule} configured for PubNub client + * instance or encrypt file prior {@link PubNub#sendFile|sendFile} method call. + */ cipherKey?: string; + /** + * Unique file identifier. + * + * Unique file identifier, and it's {@link fileName} can be used to download file from the channel + * later. + */ fileId: string; + /** + * Actual file name under which file has been stored. + * + * File name and unique {@link fileId} can be used to download file from the channel later. + * + * **Note:** Actual file name may be different from the one which has been used during file + * upload. + */ fileName: string; + /** + * Whether published file messages should be stored in the channel's history. + * + * **Note:** If `storeInHistory` not specified, then the history configuration on the key is + * used. + * + * @default `true` + */ storeInHistory?: boolean; + /** + * How long the message should be stored in the channel's history. + * + * **Note:** If not specified, defaults to the key set's retention value. + * + * @default `0` + */ ttl?: number; + /** + * Metadata, which should be associated with published file. + * + * Associated metadata can be utilized by message filtering feature. + */ meta?: Payload; }; +/** + * Publish File Message request response. + */ export type PublishFileMessageResponse = { + /** + * High-precision time when published file message has been received by the PubNub service. + */ timetoken: string; }; +/** + * Download File request parameters. + */ export type DownloadFileParameters = FileUrlParameters & { + /** + * Custom file and message encryption key. + * + * @deprecated Use {@link Configuration#cryptoModule|cryptoModule} configured for PubNub client + * instance or encrypt file prior {@link PubNub#sendFile|sendFile} method call. + */ cipherKey?: string; }; +/** + * Generate File download Url request parameters. + */ export type FileUrlParameters = { + /** + * Name of channel where file has been sent. + */ channel: string; + /** + * Unique file identifier. + * + * Unique file identifier and it's {@link name} can be used to download file from the channel + * later. + */ id: string; + /** + * Actual file name under which file has been stored. + * + * File name and unique {@link id} can be used to download file from the channel later. + * + * **Important:** Actual file name may be different from the one which has been used during file + * upload. + */ name: string; }; +/** + * Generate File Download Url response. + */ export type FileUrlResponse = string; +/** + * Delete File request parameters. + */ export type DeleteFileParameters = { + /** + * Name of channel where file has been sent. + */ channel: string; + /** + * Unique file identifier. + * + * Unique file identifier and it's {@link name} can be used to download file from the channel + * later. + */ id: string; + /** + * Actual file name under which file has been stored. + * + * File name and unique {@link id} can be used to download file from the channel later. + * + * **Important:** Actual file name may be different from the one which has been used during file + * upload. + */ name: string; }; +/** + * Delete File request response. + */ export type DeleteFileResponse = { + /** + * Delete File request processing status code. + */ status: number; }; diff --git a/lib/types/core/types/api/history.d.ts b/lib/types/core/types/api/history.d.ts index cdb748fc2..9ae00f1c2 100644 --- a/lib/types/core/types/api/history.d.ts +++ b/lib/types/core/types/api/history.d.ts @@ -1,105 +1,395 @@ import { Payload } from './index'; +/** + * Get history request parameters. + */ export type GetHistoryParameters = { + /** + * Channel to return history messages from. + */ channel: string; + /** + * Specifies the number of historical messages to return. + * + * **Note:** Maximum `100` messages can be returned in single response. + * + * @default `100` + */ count?: number; + /** + * Whether message `meta` information should be fetched or not. + * + * @default `false` + */ includeMeta?: boolean; + /** + * Timetoken delimiting the `start` of `time` slice (exclusive) to pull messages from. + */ start?: string; + /** + * Timetoken delimiting the `end` of `time` slice (inclusive) to pull messages from. + */ end?: string; + /** + * Whether timeline should traverse in reverse starting with the oldest message first or not. + * + * If both `start` and `end` arguments are provided, `reverse` is ignored and messages are + * returned starting with the newest message. + */ reverse?: boolean; + /** + * Whether message timetokens should be stringified or not. + * + * @default `false` + */ stringifiedTimeToken?: boolean; }; +/** + * Get history response. + */ export type GetHistoryResponse = { + /** + * List of previously published messages. + */ messages: { + /** + * Message payload (decrypted). + */ entry: Payload; + /** + * When message has been received by PubNub service. + */ timetoken: string | number; + /** + * Additional data which has been published along with message to be used with real-time + * events filter expression. + */ meta?: Payload; + /** + * Message decryption error (if attempt has been done). + */ error?: string; }[]; + /** + * Received messages timeline start. + */ startTimeToken: string | number; + /** + * Received messages timeline end. + */ endTimeToken: string | number; }; +/** + * PubNub-defined message type. + * + * Types of messages which can be retrieved with fetch messages REST API. + */ export declare enum PubNubMessageType { + /** + * Regular message. + */ Message = -1, + /** + * File message. + */ Files = 4 } +/** + * Per-message actions information. + */ export type Actions = { + /** + * Message action type. + */ [t: string]: { + /** + * Message action value. + */ [v: string]: { + /** + * Unique identifier of the user which reacted on message. + */ uuid: string; + /** + * High-precision PubNub timetoken with time when {@link uuid} reacted on message. + */ actionTimetoken: string; }; }; }; +/** + * Additional message actions fetch information. + */ export type MoreActions = { + /** + * Prepared fetch messages with actions REST API URL. + */ url: string; + /** + * Next page time offset. + */ start: string; + /** + * Number of messages to retrieve with next page. + */ max: number; }; +/** + * Common content of the fetched message. + */ type BaseFetchedMessage = { + /** + * Name of channel for which message has been retrieved. + */ channel: string; + /** + * When message has been received by PubNub service. + */ timetoken: string | number; + /** + * Message publisher unique identifier. + */ uuid?: string; + /** + * Additional data which has been published along with message to be used with real-time + * events filter expression. + */ meta?: Payload; + /** + * Message decryption error (if attempt has been done). + */ error?: string; }; +/** + * Regular message published to the channel. + */ export type RegularMessage = BaseFetchedMessage & { + /** + * Message payload (decrypted). + */ message: Payload; + /** + * PubNub-defined message type. + */ messageType?: PubNubMessageType.Message; }; +/** + * File message published to the channel. + */ export type FileMessage = BaseFetchedMessage & { + /** + * Message payload (decrypted). + */ message: { + /** + * File annotation message. + */ message?: Payload; + /** + * File information. + */ file: { + /** + * Unique file identifier. + */ id: string; + /** + * Name with which file has been stored. + */ name: string; + /** + * File's content mime-type. + */ 'mime-type': string; + /** + * Stored file size. + */ size: number; + /** + * Pre-computed file download Url. + */ url: string; }; }; + /** + * PubNub-defined message type. + */ messageType?: PubNubMessageType.Files; }; +/** + * Fetched message entry in channel messages list. + */ export type FetchedMessage = RegularMessage | FileMessage; +/** + * Fetched with actions message entry in channel messages list. + */ export type FetchedMessageWithActions = FetchedMessage & { + /** + * List of message reactions. + */ actions?: Actions; + /** + * List of message reactions. + * + * @deprecated Use {@link actions} field instead. + */ data?: Actions; }; +/** + * Fetch messages request parameters. + */ export type FetchMessagesParameters = { + /** + * Specifies channels to return history messages from. + * + * **Note:** Maximum of `500` channels are allowed. + */ channels: string[]; + /** + * Specifies the number of historical messages to return per channel. + * + * **Note:** Default is `100` per single channel and `25` per multiple channels or per + * single channel if {@link includeMessageActions} is used. + * + * @default `100` or `25` + */ count?: number; + /** + * Whether message type should be returned with each history message or not. + * + * @default `true` + */ includeMessageType?: boolean; + /** + * Whether publisher `uuid` should be returned with each history message or not. + * + * @default `true` + */ includeUUID?: boolean; + /** + * Whether publisher `uuid` should be returned with each history message or not. + * + * @deprecated Use {@link includeUUID} property instead. + */ includeUuid?: boolean; + /** + * Whether message `meta` information should be fetched or not. + * + * @default `false` + */ includeMeta?: boolean; + /** + * Whether message-added message actions should be fetched or not. + * + * If used, the limit of messages retrieved will be `25` per single channel. + * + * Each message can have a maximum of `25000` actions attached to it. Consider the example of + * querying for 10 messages. The first five messages have 5000 actions attached to each of + * them. The API will return the first 5 messages and all their 25000 actions. The response + * will also include a `more` link to get the remaining 5 messages. + * + * **Important:** Truncation will happen if the number of actions on the messages returned + * is > 25000. + * + * @default `false` + * + * @throws Exception if API is called with more than one channel. + */ includeMessageActions?: boolean; + /** + * Timetoken delimiting the `start` of `time` slice (exclusive) to pull messages from. + */ start?: string; + /** + * Timetoken delimiting the `end` of `time` slice (inclusive) to pull messages from. + */ end?: string; + /** + * Whether message timetokens should be stringified or not. + * + * @default `false` + */ stringifiedTimeToken?: boolean; }; +/** + * Fetch messages response. + */ export type FetchMessagesForChannelsResponse = { + /** + * List of previously published messages per requested channel. + */ channels: { [p: string]: FetchedMessage[]; }; }; +/** + * Fetch messages with reactions response. + */ export type FetchMessagesWithActionsResponse = { channels: { [p: string]: FetchedMessageWithActions[]; }; + /** + * Additional message actions fetch information. + */ more: MoreActions; }; +/** + * Fetch messages response. + */ export type FetchMessagesResponse = FetchMessagesForChannelsResponse | FetchMessagesWithActionsResponse; +/** + * Message count request parameters. + */ export type MessageCountParameters = { + /** + * The channels to fetch the message count. + */ channels: string[]; + /** + * List of timetokens, in order of the {@link channels} list. + * + * Specify a single timetoken to apply it to all channels. Otherwise, the list of timetokens + * must be the same length as the list of {@link channels}, or the function returns an error + * flag. + */ channelTimetokens?: string[]; + /** + * High-precision PubNub timetoken starting from which number of messages should be counted. + * + * Same timetoken will be used to count messages for each passed {@link channels}. + * + * @deprecated Use {@link channelTimetokens} field instead. + */ timetoken?: string; }; +/** + * Message count response. + */ export type MessageCountResponse = { + /** + * Map of channel names to the number of counted messages. + */ channels: Record; }; +/** + * Delete messages from channel parameters. + */ export type DeleteMessagesParameters = { + /** + * Specifies channel messages to be deleted from history. + */ channel: string; + /** + * Timetoken delimiting the start of time slice (exclusive) to delete messages from. + */ start?: string; + /** + * Timetoken delimiting the end of time slice (inclusive) to delete messages from. + */ end?: string; }; +/** + * Delete messages from channel response. + */ export type DeleteMessagesResponse = Record; export {}; diff --git a/lib/types/core/types/api/index.d.ts b/lib/types/core/types/api/index.d.ts index a76d7e94e..a27191168 100644 --- a/lib/types/core/types/api/index.d.ts +++ b/lib/types/core/types/api/index.d.ts @@ -1,33 +1,121 @@ import { AbstractRequest } from '../../components/request'; import RequestOperation from '../../constants/operations'; import StatusCategory from '../../constants/categories'; +/** + * PubNub account keyset. + */ export type KeySet = { + /** + * Specifies the `subscribeKey` to be used for subscribing to a channel and message publishing. + */ subscribeKey: string; + /** + * Specifies the `publishKey` to be used for publishing messages to a channel. + */ publishKey?: string; + /** + * Specifies the `secretKey` to be used for request signatures computation. + */ secretKey?: string; }; +/** + * REST API request processing function. + */ export type SendRequestFunction = (request: AbstractRequest, callback?: ResultCallback) => Promise; +/** + * Endpoint call completion block with result. + * + * **Note:** Endpoints which return consumable data use this callback. + */ export type ResultCallback = (status: Status, response: ResponseType | null) => void; +/** + * Endpoint acknowledgment completion block. + * + * **Note:** Endpoints which return only acknowledgment or error status use this callback. + */ export type StatusCallback = (status: Status) => void; +/** + * REST API endpoint processing status. + * + * **Note:** Used as {@link ResultCallback} and {@link StatusCallback} callbacks first argument type and + * {@link PubNubError} instance `status` field value type. + */ export type Status = { + /** + * Whether status represent error or not. + */ error: boolean; + /** + * API call status category. + */ category: StatusCategory; + /** + * Type of REST API endpoint which reported status. + */ operation?: RequestOperation; + /** + * REST API response status code. + */ statusCode: number; + /** + * Error data provided by REST API. + */ errorData?: Error | Payload; + /** + * Additional status information. + */ [p: string]: Payload | Error | undefined; }; +/** + * Real-time PubNub client status change event. + */ export type StatusEvent = { + /** + * API call status category. + */ category: StatusCategory; + /** + * Type of REST API endpoint which reported status. + */ operation?: RequestOperation; + /** + * Information about error. + */ error?: string | boolean; + /** + * List of channels for which status update announced. + */ affectedChannels?: string[]; + /** + * List of currently subscribed channels. + * + * List of channels from which PubNub client receives real-time updates. + */ subscribedChannels?: string[]; + /** + * List of channel groups for which status update announced. + */ affectedChannelGroups?: string[]; + /** + * High-precision timetoken which has been used with previous subscription loop. + */ lastTimetoken?: number | string; + /** + * High-precision timetoken which is used for current subscription loop. + */ currentTimetoken?: number | string; }; +/** + * {@link TransportRequest} query parameter type. + */ export type Query = Record; +/** + * General payload type. + * + * Type should be used for: + * * generic messages and signals content, + * * published message metadata. + */ export type Payload = string | number | boolean | { [key: string]: Payload | null; } | Payload[]; diff --git a/lib/types/core/types/api/message-action.d.ts b/lib/types/core/types/api/message-action.d.ts index aee3c2454..7ad1941a8 100644 --- a/lib/types/core/types/api/message-action.d.ts +++ b/lib/types/core/types/api/message-action.d.ts @@ -1,44 +1,153 @@ +/** + * Message reaction object type. + */ export type MessageAction = { + /** + * What feature this message action represents. + */ type: string; + /** + * Value which should be stored along with message action. + */ value: string; + /** + * Unique identifier of the user which added message action. + */ uuid: string; + /** + * Timetoken of when message reaction has been added. + * + * **Note:** This token required when it will be required to remove raction. + */ actionTimetoken: string; + /** + * Timetoken of message to which `action` has been added. + */ messageTimetoken: string; }; +/** + * More message actions fetch information. + */ export type MoreMessageActions = { + /** + * Prepared REST API url to fetch next page with message actions. + */ url: string; + /** + * Message action timetoken denoting the start of the range requested with next page. + * + * **Note:** Return values will be less than {@link start}. + */ start: string; + /** + * Message action timetoken denoting the end of the range requested with next page. + * + * **Note:** Return values will be greater than or equal to {@link end}. + */ end: string; + /** + * Number of message actions to return in next response. + */ limit: number; }; +/** + * Add Message Action request parameters. + */ export type AddMessageActionParameters = { + /** + * Name of channel which stores the message for which {@link action} should be added. + */ channel: string; + /** + * Timetoken of message for which {@link action} should be added. + */ messageTimetoken: string; + /** + * Message `action` information. + */ action: { + /** + * What feature this message action represents. + */ type: string; + /** + * Value which should be stored along with message action. + */ value: string; }; }; +/** + * Response with added message action object. + */ export type AddMessageActionResponse = { data: MessageAction; }; +/** + * Get Message Actions request parameters. + */ export type GetMessageActionsParameters = { + /** + * Name of channel from which list of messages `actions` should be retrieved. + */ channel: string; + /** + * Message action timetoken denoting the start of the range requested. + * + * **Note:** Return values will be less than {@link start}. + */ start?: string; + /** + * Message action timetoken denoting the end of the range requested. + * + * **Note:** Return values will be greater than or equal to {@link end}. + */ end?: string; + /** + * Number of message actions to return in response. + */ limit?: number; }; +/** + * Response with message actions in specific `channel`. + */ export type GetMessageActionsResponse = { + /** + * Retrieved list of message actions. + */ data: MessageAction[]; + /** + * Received message actions time frame start. + */ start: string | null; + /** + * Received message actions time frame end. + */ end: string | null; + /** + * More message actions fetch information. + */ more?: MoreMessageActions; }; +/** + * Remove Message Action request parameters. + */ export type RemoveMessageActionParameters = { + /** + * Name of channel which store message for which `action` should be removed. + */ channel: string; + /** + * Timetoken of message for which `action` should be removed. + */ messageTimetoken: string; + /** + * Action addition timetoken. + */ actionTimetoken: string; }; +/** + * Response with message remove result. + */ export type RemoveMessageActionResponse = { data: Record; }; diff --git a/lib/types/core/types/api/presence.d.ts b/lib/types/core/types/api/presence.d.ts index ef1fb4b1f..28519378d 100644 --- a/lib/types/core/types/api/presence.d.ts +++ b/lib/types/core/types/api/presence.d.ts @@ -1,61 +1,210 @@ import { Payload } from './index'; +/** + * Associated presence state fetch parameters. + */ export type GetPresenceStateParameters = { + /** + * The subscriber uuid to get the current state. + * + * @default `current uuid` + */ uuid?: string; + /** + * List of channels for which state associated with {@link uuid} should be retrieved. + * + * **Important:** Either {@link channels} or {@link channelGroups} should be provided; + */ channels?: string[]; + /** + * List of channel groups for which state associated with {@link uuid} should be retrieved. + * + * **Important:** Either {@link channels} or {@link channelGroups} should be provided; + */ channelGroups?: string[]; }; +/** + * Associated presence state fetch response. + */ export type GetPresenceStateResponse = { + /** + * Channels map to state which `uuid` has associated with them. + */ channels: Record; }; +/** + * Associate presence state parameters. + */ export type SetPresenceStateParameters = { + /** + * List of channels for which state should be associated with {@link uuid}. + */ channels?: string[]; + /** + * List of channel groups for which state should be associated with {@link uuid}. + */ channelGroups?: string[]; + /** + * State which should be associated with `uuid` on provided list of {@link channels} and {@link channelGroups}. + */ state: Payload; }; +/** + * Associate presence state parameters using heartbeat. + */ export type SetPresenceStateWithHeartbeatParameters = { + /** + * List of channels for which state should be associated with {@link uuid}. + */ channels?: string[]; + /** + * State which should be associated with `uuid` on provided list of {@link channels}. + */ state: Payload; + /** + * Whether `presence/heartbeat` REST API should be used to manage state or not. + * + * @default `false` + */ withHeartbeat: boolean; }; +/** + * Associate presence state response. + */ export type SetPresenceStateResponse = { + /** + * State which has been associated with `uuid` on provided list of channels and groups. + */ state: Payload; }; +/** + * Announce heartbeat parameters. + */ export type PresenceHeartbeatParameters = { + /** + * How long the server will consider the client alive for presence.The value is in seconds. + */ heartbeat: number; + /** + * List of channels for which heartbeat should be announced for {@link uuid}. + */ channels?: string[]; + /** + * List of channel groups for which heartbeat should be announced for {@link uuid}. + */ channelGroups?: string[]; + /** + * State which should be associated with `uuid` on provided list of {@link channels} and {@link channelGroups}. + */ state?: Payload; }; +/** + * Announce heartbeat response. + */ export type PresenceHeartbeatResponse = Record; +/** + * Presence leave parameters. + */ export type PresenceLeaveParameters = { + /** + * List of channels for which `uuid` should be marked as `offline`. + */ channels?: string[]; + /** + /** + * List of channel groups for which `uuid` should be marked as `offline`. + */ channelGroups?: string[]; }; +/** + * Presence leave response. + */ export type PresenceLeaveResponse = Record; +/** + * Channel / channel group presence fetch parameters.. + */ export type HereNowParameters = { + /** + * List of channels for which presence should be retrieved. + */ channels?: string[]; + /** + * List of channel groups for which presence should be retrieved. + */ channelGroups?: string[]; + /** + * Whether `uuid` information should be included in response or not. + * + * **Note:** Only occupancy information will be returned if both {@link includeUUIDs} and {@link includeState} is + * set to `false`. + * + * @default `true` + */ includeUUIDs?: boolean; + /** + * Whether state associated with `uuid` should be included in response or not. + * + * @default `false`. + */ includeState?: boolean; + /** + * Additional query parameters. + */ queryParameters?: Record; }; +/** + * `uuid` where now response. + */ export type HereNowResponse = { + /** + * Total number of channels for which presence information received. + */ totalChannels: number; + /** + * Total occupancy for all retrieved channels. + */ totalOccupancy: number; + /** + * List of channels to which `uuid` currently subscribed. + */ channels: { [p: string]: { + /** + * List of received channel subscribers. + * + * **Note:** Field is missing if `uuid` and `state` not included. + */ occupants: { uuid: string; state?: Payload | null; }[]; + /** + * Name of channel for which presence information retrieved. + */ name: string; + /** + * Total number of active subscribers in single channel. + */ occupancy: number; }; }; }; +/** + * `uuid` where now parameters. + */ export type WhereNowParameters = { + /** + * The subscriber uuid to get the current state. + * + * @default `current uuid` + */ uuid?: string; }; +/** + * `uuid` where now response. + */ export type WhereNowResponse = { + /** + * Channels map to state which `uuid` has associated with them. + */ channels: string[]; }; diff --git a/lib/types/core/types/api/push-notifications.d.ts b/lib/types/core/types/api/push-notifications.d.ts index 8a71a4dee..57ab65076 100644 --- a/lib/types/core/types/api/push-notifications.d.ts +++ b/lib/types/core/types/api/push-notifications.d.ts @@ -1,14 +1,48 @@ +/** + * Type of Push Notifications gateway which should be used with Push Notifications REST API. + */ type PushGateway = 'apns2' | 'gcm'; +/** + * Basic information required by Push Notifications REST API about device. + */ type DevicePush = { + /** + * Device ID for which list of registered channel push notifications will be changed. + */ device: string; + /** + * Push Notifications gateway to use. + * + * **Important:** Depends from the source of `device` token and can be `apns2` (for token + * provided during device registration using Apple's framework) or `gcm` (when used Firebase + * or similar framework to receive token). + */ pushGateway: PushGateway; }; +/** + * Register and unregister push notifications for device request parameters. + */ export type ManageDeviceChannelsParameters = { + /** + * List of channels to be added or removed. + */ channels: string[]; } & DevicePush; +/** + * List Device Channels request parameters. + */ export type ListDeviceChannelsParameters = DevicePush; +/** + * Response with result of the list device channels. + */ export type ListDeviceChannelsResponse = { + /** + * List of the channels for which `device` will receive push notifications. + */ channels: string[]; }; +/** + * Delete Push Notification for device request parameters. + */ export type DeleteDeviceParameters = DevicePush; export {}; diff --git a/lib/types/core/types/api/push.d.ts b/lib/types/core/types/api/push.d.ts index 1b8cf0763..6d67ed8cf 100644 --- a/lib/types/core/types/api/push.d.ts +++ b/lib/types/core/types/api/push.d.ts @@ -1,32 +1,122 @@ +/** + * Common managed channels push notification parameters. + */ type ManagedDeviceChannels = { + /** + * Channels to register or unregister with mobile push notifications. + */ channels: string[]; + /** + * The device ID to associate with mobile push notifications. + */ device: string; + /** + * Starting channel for pagination. + * + * **Note:** Use the last channel from the previous page request. + */ start?: string; + /** + * Number of channels to return for pagination. + * + * **Note:** maximum of 1000 tokens at a time. + * + * @default `500` + */ count?: number; }; +/** + * List all FCM device push notification enabled channels parameters. + */ type ListFCMDeviceChannelsParameters = Omit; +/** + * List all APNS device push notification enabled channels parameters. + * + * @deprecated Use `APNS2`-based endpoints. + */ type ListAPNSDeviceChannelsParameters = Omit; +/** + * List all APNS2 device push notification enabled channels parameters. + */ type ListAPNS2DeviceChannelsParameters = Omit; +/** + * List all device push notification enabled channels parameters. + */ export type ListDeviceChannelsParameters = ListFCMDeviceChannelsParameters | ListAPNSDeviceChannelsParameters | ListAPNS2DeviceChannelsParameters; +/** + * List all device push notification enabled channels response. + */ export type ListDeviceChannelsResponse = { + /** + * List of channels registered for device push notifications. + */ channels: string[]; }; +/** + * Manage FCM device push notification enabled channels parameters. + */ type ManageFCMDeviceChannelsParameters = ManagedDeviceChannels & { + /** + * Push Notifications gateway type. + */ pushGateway: 'gcm'; }; +/** + * Manage APNS device push notification enabled channels parameters. + * + * @deprecated Use `APNS2`-based endpoints. + */ type ManageAPNSDeviceChannelsParameters = ManagedDeviceChannels & { + /** + * Push Notifications gateway type. + */ pushGateway: 'apns'; }; +/** + * Manage APNS2 device push notification enabled channels parameters. + */ type ManageAPNS2DeviceChannelsParameters = ManagedDeviceChannels & { + /** + * Push Notifications gateway type. + */ pushGateway: 'apns2'; + /** + * Environment within which device should manage list of channels with enabled notifications. + */ environment?: 'development' | 'production'; + /** + * Notifications topic name (usually it is bundle identifier of application for Apple platform). + */ topic: string; }; +/** + * Manage device push notification enabled channels parameters. + */ export type ManageDeviceChannelsParameters = ManageFCMDeviceChannelsParameters | ManageAPNSDeviceChannelsParameters | ManageAPNS2DeviceChannelsParameters; +/** + * Manage device push notification enabled channels response. + */ export type ManageDeviceChannelsResponse = Record; +/** + * Remove all FCM device push notification enabled channels parameters. + */ type RemoveFCMDeviceParameters = Omit; +/** + * Manage APNS device push notification enabled channels parameters. + * + * @deprecated Use `APNS2`-based endpoints. + */ type RemoveAPNSDeviceParameters = Omit; +/** + * Manage APNS2 device push notification enabled channels parameters. + */ type RemoveAPNS2DeviceParameters = Omit; +/** + * Remove all device push notification enabled channels parameters. + */ export type RemoveDeviceParameters = RemoveFCMDeviceParameters | RemoveAPNSDeviceParameters | RemoveAPNS2DeviceParameters; +/** + * Remove all device push notification enabled channels response. + */ export type RemoveDeviceResponse = Record; export {}; diff --git a/lib/types/core/types/api/subscription.d.ts b/lib/types/core/types/api/subscription.d.ts index 24b2396ed..0c8e1e19e 100644 --- a/lib/types/core/types/api/subscription.d.ts +++ b/lib/types/core/types/api/subscription.d.ts @@ -1,94 +1,294 @@ import { RequestParameters as SubscribeRequestParameters, VSPMembershipObjectData, AppContextObjectData, MessageActionData, PubNubEventType, SpaceObjectData, UserObjectData, PresenceData, FileData } from '../../endpoints/subscribe'; import { AbortSignal } from '../../components/abort_signal'; import { Payload } from './index'; +/** + * Time cursor. + * + * Cursor used by subscription loop to identify point in time after which updates will be + * delivered. + */ export type SubscriptionCursor = { + /** + * PubNub high-precision timestamp. + * + * Aside of specifying exact time of receiving data / event this token used to catchup / + * follow on real-time updates. + */ timetoken: string | number; + /** + * Data center region for which `timetoken` has been generated. + */ region?: number; }; +/** + * Common real-time event. + */ type Event = { + /** + * Channel to which real-time event has been sent. + */ channel: string; + /** + * Actual subscription at which real-time event has been received. + * + * PubNub client provide various ways to subscribe to the real-time stream: channel groups, + * wildcard subscription, and spaces. + * + * **Note:** Value will be `null` if it is the same as {@link channel}. + */ subscription: string | null; + /** + * High-precision PubNub timetoken with time when event has been received by PubNub services. + */ timetoken: string; }; +/** + * Common legacy real-time event for backward compatibility. + */ type LegacyEvent = Event & { + /** + * Channel to which real-time event has been sent. + * + * @deprecated Use {@link channel} field instead. + */ actualChannel?: string | null; + /** + * Actual subscription at which real-time event has been received. + * + * @deprecated Use {@link subscription} field instead. + */ subscribedChannel?: string; }; +/** + * Presence change real-time event. + */ export type Presence = LegacyEvent & PresenceData; +/** + * Extended presence real-time event. + * + * Type extended for listener manager support. + */ type PresenceEvent = { type: PubNubEventType.Presence; data: Presence; }; +/** + * Common published data information. + */ type PublishedData = { + /** + * Unique identifier of the user which sent data. + */ publisher?: string; + /** + * Additional user-provided metadata which can be used with real-time filtering expression. + */ userMetadata?: { [p: string]: Payload; }; + /** + * Sent data. + */ message: Payload; }; +/** + * Real-time message event. + */ export type Message = LegacyEvent & PublishedData & { + /** + * Decryption error message in case of failure. + */ error?: string; }; +/** + * Extended real-time message event. + * + * Type extended for listener manager support. + */ type MessageEvent = { type: PubNubEventType.Message; data: Message; }; +/** + * Real-time signal event. + */ export type Signal = Event & PublishedData; +/** + * Extended real-time signal event. + * + * Type extended for listener manager support. + */ type SignalEvent = { type: PubNubEventType.Signal; data: Signal; }; +/** + * Message action real-time event. + */ export type MessageAction = Event & Omit & { + /** + * Unique identifier of the user which added message reaction. + * + * @deprecated Use `data.uuid` field instead. + */ publisher?: string; data: MessageActionData['data'] & { + /** + * Unique identifier of the user which added message reaction. + */ uuid: string; }; }; +/** + * Extended message action real-time event. + * + * Type extended for listener manager support. + */ type MessageActionEvent = { type: PubNubEventType.MessageAction; data: MessageAction; }; +/** + * App Context Object change real-time event. + */ export type AppContextObject = Event & { + /** + * Information about App Context object for which event received. + */ message: AppContextObjectData; }; +/** + * `User` App Context Object change real-time event. + */ export type UserAppContextObject = Omit & { + /** + * Space to which real-time event has been sent. + */ spaceId: string; + /** + * Information about User Object for which event received. + */ message: UserObjectData; }; +/** + * `Space` App Context Object change real-time event. + */ export type SpaceAppContextObject = Omit & { + /** + * Space to which real-time event has been sent. + */ spaceId: string; + /** + * Information about `Space` Object for which event received. + */ message: SpaceObjectData; }; +/** + * VSP `Membership` App Context Object change real-time event. + */ export type VSPMembershipAppContextObject = Omit & { + /** + * Space to which real-time event has been sent. + */ spaceId: string; + /** + * Information about `Membership` Object for which event received. + */ message: VSPMembershipObjectData; }; +/** + * Extended App Context Object change real-time event. + * + * Type extended for listener manager support. + */ type AppContextEvent = { type: PubNubEventType.AppContext; data: AppContextObject; }; +/** + * File real-time event. + */ export type File = Event & Omit & Omit & { + /** + * Message which has been associated with uploaded file. + */ message?: Payload; + /** + * Information about uploaded file. + */ file?: FileData['file'] & { + /** + * File download url. + */ url: string; }; + /** + * Decryption error message in case of failure. + */ error?: string; }; +/** + * Extended File real-time event. + * + * Type extended for listener manager support. + */ type FileEvent = { type: PubNubEventType.Files; data: File; }; +/** + * Cancelable subscribe request parameters. + */ export type CancelableSubscribeParameters = Omit & { + /** + * Long-poll request termination signal. + */ abortSignal: AbortSignal; }; +/** + * Subscribe request parameters. + */ export type SubscribeParameters = { + /** + * List of channels from which real-time events should be delivered. + * + * @default `,` if {@link channelGroups} is set. + */ channels?: string[]; + /** + * List of channel groups from which real-time events should be retrieved. + */ channelGroups?: string[]; + /** + * Next subscription loop timetoken. + */ timetoken?: string | number; + /** + * Whether should subscribe to channels / groups presence announcements or not. + * + * @default `false` + */ withPresence?: boolean; + /** + * Presence information which should be associated with `userId`. + * + * `state` information will be associated with `userId` on channels mentioned as keys in + * this object. + * + * @deprecated Use set state methods to specify associated user's data instead of passing to + * subscribe. + */ state?: Record; + /** + * Whether should subscribe to channels / groups presence announcements or not. + * + * @default `false` + */ withHeartbeats?: boolean; }; +/** + * Service success response. + */ export type SubscriptionResponse = { cursor: SubscriptionCursor; messages: (PresenceEvent | MessageEvent | SignalEvent | MessageActionEvent | AppContextEvent | FileEvent)[]; diff --git a/lib/types/core/types/file.d.ts b/lib/types/core/types/file.d.ts index fc6d3d7f4..774a161da 100644 --- a/lib/types/core/types/file.d.ts +++ b/lib/types/core/types/file.d.ts @@ -1,24 +1,104 @@ +/** + * {@link PubNub} File object interface module. + */ +/** + * Base file constructor parameters. + * + * Minimum set of parameters which can be p + */ export type PubNubBasicFileParameters = { data: string | ArrayBuffer; name: string; mimeType?: string; }; +/** + * Platform-agnostic {@link PubNub} File object. + * + * Interface describes share of {@link PubNub} File which is required by {@link PubNub} core to + * perform required actions. + */ export interface PubNubFileInterface { + /** + * Actual file name. + */ name: string; + /** + * File mime-type. + */ mimeType?: string; + /** + * File content length. + */ contentLength?: number; + /** + * Convert {@link PubNub} file object content to {@link ArrayBuffer}. + * + * @returns Asynchronous results of conversion to the {@link ArrayBuffer}. + * + * @throws Error if provided {@link PubNub} File object content is not supported for this + * operation. + */ toArrayBuffer(): Promise; + /** + * Convert {@link PubNub} File object content to file `Uri`. + * + * @returns Asynchronous results of conversion to file `Uri`. + * + * @throws Error if provided {@link PubNub} File object content is not supported for this + * operation. + */ toFileUri(): Promise>; } +/** + * {@link PubNub} File object class interface. + */ export interface PubNubFileConstructor { + /** + * Whether {@link Blob} data supported by platform or not. + */ supportsBlob: boolean; + /** + * Whether {@link File} data supported by platform or not. + */ supportsFile: boolean; + /** + * Whether {@link Buffer} data supported by platform or not. + */ supportsBuffer: boolean; + /** + * Whether {@link Stream} data supported by platform or not. + */ supportsStream: boolean; + /** + * Whether {@link String} data supported by platform or not. + */ supportsString: boolean; + /** + * Whether {@link ArrayBuffer} supported by platform or not. + */ supportsArrayBuffer: boolean; + /** + * Whether {@link PubNub} File object encryption supported or not. + */ supportsEncryptFile: boolean; + /** + * Whether `File Uri` data supported by platform or not. + */ supportsFileUri: boolean; + /** + * {@link PubNub} File object constructor. + * + * @param file - File instantiation parameters (can be raw data or structured object). + * + * @returns Constructed platform-specific {@link PubNub} File object. + */ create(file: ConstructorParameters): File; + /** + * {@link PubNub} File object constructor. + * + * @param file - File instantiation parameters (can be raw data or structured object). + * + * @returns Constructed platform-specific {@link PubNub} File object. + */ new (file: ConstructorParameters): File; } diff --git a/lib/types/core/types/transport-request.d.ts b/lib/types/core/types/transport-request.d.ts index db7da1684..09ddc24f4 100644 --- a/lib/types/core/types/transport-request.d.ts +++ b/lib/types/core/types/transport-request.d.ts @@ -1,24 +1,97 @@ import { PubNubFileInterface } from './file'; import { Query } from './api'; +/** + * Enum representing possible transport methods for HTTP requests. + * + * @enum {number} + */ export declare enum TransportMethod { + /** + * Request will be sent using `GET` method. + */ GET = "GET", + /** + * Request will be sent using `POST` method. + */ POST = "POST", + /** + * Request will be sent using `PATCH` method. + */ PATCH = "PATCH", + /** + * Request will be sent using `DELETE` method. + */ DELETE = "DELETE", + /** + * Local request. + * + * Request won't be sent to the service and probably used to compute URL. + */ LOCAL = "LOCAL" } +/** + * Request cancellation controller. + */ export type CancellationController = { + /** + * Request cancellation / abort function. + */ abort: () => void; }; +/** + * This object represents a request to be sent to the PubNub API. + * + * This struct represents a request to be sent to the PubNub API. It is used by the transport + * provider which implements {@link Transport} interface. + * + * All fields are representing certain parts of the request that can be used to prepare one. + */ export type TransportRequest = { + /** + * Remote host name. + */ origin?: string; + /** + * Remote resource path. + */ path: string; + /** + * Query parameters to be sent with the request. + */ queryParameters?: Query; + /** + * Transport request HTTP method. + */ method: TransportMethod; + /** + * Headers to be sent with the request. + */ headers?: Record; + /** + * Multipart form data fields. + * + * **Important:** `Content-Type` header should be sent the {@link body} data type when + * `multipart/form-data` should request should be sent. + */ formData?: Record[]; + /** + * Body to be sent with the request. + */ body?: ArrayBuffer | PubNubFileInterface | string; + /** + * For how long request should wait response from the server. + * + * @default `10` seconds. + */ timeout: number; + /** + * Whether request can be cancelled or not. + * + * @default `false`. + */ cancellable: boolean; + /** + * Unique request identifier. + */ identifier: string; }; diff --git a/lib/types/core/types/transport-response.d.ts b/lib/types/core/types/transport-response.d.ts index 6c059d060..359aa8712 100644 --- a/lib/types/core/types/transport-response.d.ts +++ b/lib/types/core/types/transport-response.d.ts @@ -1,6 +1,23 @@ +/** + * Represents a transport response from a service. + */ export type TransportResponse = { + /** + * Full remote resource URL used to retrieve response. + */ url: string; + /** + * Service response status code. + */ status: number; + /** + * Service response headers. + * + * **Important:** Header names are in lowercase. + */ headers: Record; + /** + * Service response body. + */ body?: ArrayBuffer; }; diff --git a/lib/types/core/utils.d.ts b/lib/types/core/utils.d.ts index 148db9a49..8f9ab9d64 100644 --- a/lib/types/core/utils.d.ts +++ b/lib/types/core/utils.d.ts @@ -1,6 +1,31 @@ import { Query } from './types/api'; +/** + * Percent-encode input string. + * + * **Note:** Encode content in accordance of the `PubNub` service requirements. + * + * @param input - Source string or number for encoding. + * + * @returns Percent-encoded string. + */ export declare const encodeString: (input: string | number) => string; +/** + * Percent-encode list of names (channels). + * + * @param names - List of names which should be encoded. + * + * @param [defaultString] - String which should be used in case if {@link names} is empty. + * + * @returns String which contains encoded names joined by non-encoded `,`. + */ export declare const encodeNames: (names: string[], defaultString?: string) => string; export declare const removeSingleOccurrence: (source: string[], elementsToRemove: string[]) => string[]; export declare const findUniqueCommonElements: (a: string[], b: string[]) => string[]; +/** + * Transform query key / value pairs to the string. + * + * @param query - Key / value pairs of the request query parameters. + * + * @returns Stringified query key / value pairs. + */ export declare const queryStringFromObject: (query: Query) => string; diff --git a/lib/types/crypto/modules/NodeCryptoModule/ICryptor.d.ts b/lib/types/crypto/modules/NodeCryptoModule/ICryptor.d.ts index 934139069..30a6c7bee 100644 --- a/lib/types/crypto/modules/NodeCryptoModule/ICryptor.d.ts +++ b/lib/types/crypto/modules/NodeCryptoModule/ICryptor.d.ts @@ -1,18 +1,86 @@ +/** + * Cryptor module. + */ /// /// +/** + * Data encrypted by {@link CryptoModule}. + */ export type EncryptedDataType = { + /** + * Encrypted data. + */ data: Buffer | string; + /** + * Used cryptor's metadata. + */ metadata: Buffer | null; }; +/** + * {@link Readable} stream encrypted by {@link CryptoModule}. + */ export type EncryptedStream = { + /** + * Stream with encrypted content. + */ stream: NodeJS.ReadableStream; + /** + * Length of encrypted data in {@link Readable} stream. + */ metadataLength: number; + /** + * Used cryptor's metadata. + */ metadata?: Buffer | undefined; }; +/** + * Cryptor algorithm interface. + */ export interface ICryptor { + /** + * Cryptor unique identifier. + * + * @returns Cryptor identifier. + */ get identifier(): string; + /** + * Encrypt provided source data. + * + * @param data - Source data for encryption. + * + * @returns Encrypted data object. + * + * @throws Error if unknown data type has been passed. + */ encrypt(data: BufferSource | string): EncryptedDataType; + /** + * Encrypt provided source {@link Readable} stream. + * + * @param stream - Stream for encryption. + * + * @returns Encrypted stream object. + * + * @throws Error if unknown data type has been passed. + */ encryptStream(stream: NodeJS.ReadableStream): Promise; + /** + * Decrypt provided encrypted data object. + * + * @param data - Encrypted data object for decryption. + * + * @returns Decrypted data. + * + * @throws Error if unknown data type has been passed. + */ decrypt(data: EncryptedDataType): ArrayBuffer; + /** + * Decrypt provided encrypted stream object. + * + * @param stream - Encrypted stream object for decryption. + * + * @returns Decrypted data as {@link Readable} stream. + * + * @throws Error if unknown data type has been passed. + */ decryptStream(stream: EncryptedStream): Promise; } diff --git a/lib/types/crypto/modules/NodeCryptoModule/ILegacyCryptor.d.ts b/lib/types/crypto/modules/NodeCryptoModule/ILegacyCryptor.d.ts index b41a01098..5b3ea2f2f 100644 --- a/lib/types/crypto/modules/NodeCryptoModule/ILegacyCryptor.d.ts +++ b/lib/types/crypto/modules/NodeCryptoModule/ILegacyCryptor.d.ts @@ -1,11 +1,60 @@ +/** + * Legacy cryptor module. + */ import PubNubFile, { PubNubFileParameters } from '../../../file/modules/node'; import { PubNubFileConstructor } from '../../../core/types/file'; import { Payload } from '../../../core/types/api'; import { EncryptedDataType } from './ICryptor'; +/** + * Legacy cryptor algorithm interface. + */ export interface ILegacyCryptor { + /** + * Cryptor unique identifier. + */ get identifier(): string; + /** + * Encrypt provided source data. + * + * @param data - Source data for encryption. + * + * @returns Encrypted data object. + * + * @throws Error if unknown data type has been passed. + */ encrypt(data: string): EncryptedDataType; + /** + * Encrypt provided source {@link PubNub} File object. + * + * @param file - Source {@link PubNub} File object for encryption. + * @param File - Class constructor for {@link PubNub} File object. + * + * @returns Encrypted data as {@link PubNub} File object. + * + * @throws Error if file is empty or contains unsupported data type. + * @throws Error if cipher key not set. + */ encryptFile(file: PubNubFile, File: PubNubFileConstructor): Promise; + /** + * Decrypt provided encrypted data object. + * + * @param data - Encrypted data object for decryption. + * + * @returns Decrypted data. + * + * @throws Error if unknown data type has been passed. + */ decrypt(data: EncryptedDataType): Payload | null; + /** + * Decrypt provided encrypted {@link PubNub} File object. + * + * @param file - Encrypted {@link PubNub} File object for decryption. + * @param File - Class constructor for {@link PubNub} File object. + * + * @returns Decrypted data as {@link PubNub} File object. + * + * @throws Error if file is empty or contains unsupported data type. + * @throws Error if cipher key not set. + */ decryptFile(file: PubNubFile, File: PubNubFileConstructor): Promise; } diff --git a/lib/types/crypto/modules/NodeCryptoModule/aesCbcCryptor.d.ts b/lib/types/crypto/modules/NodeCryptoModule/aesCbcCryptor.d.ts index ac56f1db9..875bd5d8f 100644 --- a/lib/types/crypto/modules/NodeCryptoModule/aesCbcCryptor.d.ts +++ b/lib/types/crypto/modules/NodeCryptoModule/aesCbcCryptor.d.ts @@ -1,11 +1,28 @@ +/** + * AES-CBC cryptor module. + */ /// /// /// import { PassThrough } from 'stream'; import { ICryptor, EncryptedDataType, EncryptedStream } from './ICryptor'; +/** + * AES-CBC cryptor. + * + * AES-CBC cryptor with enhanced cipher strength. + */ export default class AesCbcCryptor implements ICryptor { + /** + * Cryptor block size. + */ static BLOCK_SIZE: number; + /** + * {@link string|String} to {@link ArrayBuffer} response decoder. + */ static encoder: TextEncoder; + /** + * Data encryption / decryption cipher key. + */ cipherKey: string; constructor({ cipherKey }: { cipherKey: string; @@ -19,7 +36,22 @@ export default class AesCbcCryptor implements ICryptor { decrypt(input: EncryptedDataType): ArrayBuffer; decryptStream(stream: EncryptedStream): Promise; get identifier(): string; + /** + * Cryptor algorithm. + * + * @returns Cryptor module algorithm. + */ private get algo(); + /** + * Generate random initialization vector. + * + * @returns Random initialization vector. + */ private getIv; + /** + * Convert cipher key to the {@link Buffer}. + * + * @returns SHA256 encoded cipher key {@link Buffer}. + */ private getKey; } diff --git a/lib/types/crypto/modules/NodeCryptoModule/legacyCryptor.d.ts b/lib/types/crypto/modules/NodeCryptoModule/legacyCryptor.d.ts index 39bb14f3d..006900d93 100644 --- a/lib/types/crypto/modules/NodeCryptoModule/legacyCryptor.d.ts +++ b/lib/types/crypto/modules/NodeCryptoModule/legacyCryptor.d.ts @@ -1,3 +1,6 @@ +/** + * Legacy cryptor module. + */ import PubNubFile, { PubNubFileParameters } from '../../../file/modules/node'; import { CryptorConfiguration } from '../../../core/interfaces/crypto-module'; import Crypto from '../../../core/components/cryptography/index'; @@ -5,9 +8,21 @@ import { PubNubFileConstructor } from '../../../core/types/file'; import { ILegacyCryptor } from './ILegacyCryptor'; import { EncryptedDataType } from './ICryptor'; import FileCryptor from '../node'; +/** + * Legacy cryptor. + */ export default class LegacyCryptor implements ILegacyCryptor { + /** + * Legacy cryptor configuration. + */ config: CryptorConfiguration; + /** + * Configured file cryptor. + */ fileCryptor: FileCryptor; + /** + * Configured legacy cryptor. + */ cryptor: Crypto; constructor(config: CryptorConfiguration); encrypt(data: string): EncryptedDataType; diff --git a/lib/types/crypto/modules/NodeCryptoModule/nodeCryptoModule.d.ts b/lib/types/crypto/modules/NodeCryptoModule/nodeCryptoModule.d.ts index a55a0ce33..53f627cad 100644 --- a/lib/types/crypto/modules/NodeCryptoModule/nodeCryptoModule.d.ts +++ b/lib/types/crypto/modules/NodeCryptoModule/nodeCryptoModule.d.ts @@ -1,3 +1,6 @@ +/** + * Node.js crypto module. + */ import { AbstractCryptoModule, CryptorConfiguration } from '../../../core/interfaces/crypto-module'; import PubNubFile, { PubNubFileParameters } from '../../../file/modules/node'; import { PubNubFileConstructor } from '../../../core/types/file'; @@ -5,22 +8,101 @@ import { ICryptor } from './ICryptor'; import { ILegacyCryptor } from './ILegacyCryptor'; import AesCbcCryptor from './aesCbcCryptor'; import LegacyCryptor from './legacyCryptor'; +/** + * Re-export bundled cryptors. + */ export { LegacyCryptor, AesCbcCryptor }; +/** + * Crypto module cryptors interface. + */ type CryptorType = ICryptor | ILegacyCryptor; +/** + * CryptoModule for Node.js platform. + */ export declare class CryptoModule extends AbstractCryptoModule { + /** + * {@link LegacyCryptor|Legacy} cryptor identifier. + */ static LEGACY_IDENTIFIER: string; static legacyCryptoModule(config: CryptorConfiguration): CryptoModule; static aesCbcCryptoModule(config: CryptorConfiguration): CryptoModule; + /** + * Construct crypto module with `cryptor` as default for data encryption and decryption. + * + * @param defaultCryptor - Default cryptor for data encryption and decryption. + * + * @returns Crypto module with pre-configured default cryptor. + */ static withDefaultCryptor(defaultCryptor: CryptorType): CryptoModule; encrypt(data: ArrayBuffer | string): string | ArrayBuffer; encryptFile(file: PubNubFile, File: PubNubFileConstructor): Promise; decrypt(data: ArrayBuffer | string): ArrayBuffer | import("../../../core/types/api").Payload | null; decryptFile(file: PubNubFile, File: PubNubFileConstructor): Promise; + /** + * Retrieve registered legacy cryptor. + * + * @returns Previously registered {@link ILegacyCryptor|legacy} cryptor. + * + * @throws Error if legacy cryptor not registered. + */ private getLegacyCryptor; + /** + * Retrieve registered cryptor by its identifier. + * + * @param id - Unique cryptor identifier. + * + * @returns Registered cryptor with specified identifier. + * + * @throws Error if cryptor with specified {@link id} can't be found. + */ private getCryptorFromId; + /** + * Retrieve cryptor by its identifier. + * + * @param header - Header with cryptor-defined data or raw cryptor identifier. + * + * @returns Cryptor which correspond to provided {@link header}. + */ private getCryptor; + /** + * Create cryptor header data. + * + * @param encrypted - Encryption data object as source for header data. + * + * @returns Binary representation of the cryptor header data. + */ private getHeaderData; + /** + * Merge two {@link ArrayBuffer} instances. + * + * @param ab1 - First {@link ArrayBuffer}. + * @param ab2 - Second {@link ArrayBuffer}. + * + * @returns Merged data as {@link ArrayBuffer}. + */ private concatArrayBuffer; + /** + * {@link Readable} stream event handler. + * + * @param stream - Stream which can be used to read data for decryption. + * @param file - File object which has been created with {@link stream}. + * @param File - Class constructor for {@link PubNub} File object. + * + * @returns Decrypted data as {@link PubNub} File object. + * + * @throws Error if file is empty or contains unsupported data type. + */ private onStreamReadable; + /** + * Decrypt {@link Readable} stream using legacy cryptor. + * + * @param stream - Stream which can be used to read data for decryption. + * @param file - File object which has been created with {@link stream}. + * @param File - Class constructor for {@link PubNub} File object. + * + * @returns Decrypted data as {@link PubNub} File object. + * + * @throws Error if file is empty or contains unsupported data type. + */ private decryptLegacyFileStream; } diff --git a/lib/types/crypto/modules/node.d.ts b/lib/types/crypto/modules/node.d.ts index 0a35ba46b..37384f2dc 100644 --- a/lib/types/crypto/modules/node.d.ts +++ b/lib/types/crypto/modules/node.d.ts @@ -1,3 +1,6 @@ +/** + * Legacy Node.js cryptography module. + */ /// /// import { Readable, PassThrough, Transform } from 'stream'; @@ -5,19 +8,90 @@ import { Buffer } from 'buffer'; import PubNubFile, { PubNubFileParameters } from '../../file/modules/node'; import { Cryptography } from '../../core/interfaces/cryptography'; import { PubNubFileConstructor } from '../../core/types/file'; +/** + * Legacy cryptography implementation for Node.js-based {@link PubNub} client. + */ export default class NodeCryptography implements Cryptography { + /** + * Random initialization vector size. + */ static IV_LENGTH: number; encrypt(key: string, input: string | ArrayBuffer | Buffer | Readable): Promise; + /** + * Encrypt provided source {@link Buffer} using specific encryption {@link key}. + * + * @param key - Data encryption key.
**Note:** Same key should be used to `decrypt` {@link Buffer}. + * @param buffer - Source {@link Buffer} for encryption. + * + * @returns Encrypted data as {@link Buffer} object. + */ private encryptBuffer; + /** + * Encrypt provided source {@link Readable} stream using specific encryption {@link key}. + * + * @param key - Data encryption key.
**Note:** Same key should be used to `decrypt` {@link Readable} stream. + * @param stream - Source {@link Readable} stream for encryption. + * + * @returns Encrypted data as {@link Transform} object. + */ private encryptStream; + /** + * Encrypt provided source {@link string} using specific encryption {@link key}. + * + * @param key - Data encryption key.
**Note:** Same key should be used to `decrypt` {@link string}. + * @param text - Source {@link string} for encryption. + * + * @returns Encrypted data as byte {@link string}. + */ private encryptString; encryptFile(key: string, file: PubNubFile, File: PubNubFileConstructor): Promise; decrypt(key: string, input: string | ArrayBuffer | Buffer | Readable): Promise; + /** + * Decrypt provided encrypted {@link Buffer} using specific decryption {@link key}. + * + * @param key - Data decryption key.
**Note:** Should be the same as used to `encrypt` {@link Buffer}. + * @param buffer - Encrypted {@link Buffer} for decryption. + * + * @returns Decrypted data as {@link Buffer} object. + */ private decryptBuffer; + /** + * Decrypt provided encrypted {@link Readable} stream using specific decryption {@link key}. + * + * @param key - Data decryption key.
**Note:** Should be the same as used to `encrypt` {@link Readable} stream. + * @param stream - Encrypted {@link Readable} stream for decryption. + * + * @returns Decrypted data as {@link Readable} object. + */ private decryptStream; + /** + * Decrypt provided encrypted {@link string} using specific decryption {@link key}. + * + * @param key - Data decryption key.
**Note:** Should be the same as used to `encrypt` {@link string}. + * @param text - Encrypted {@link string} for decryption. + * + * @returns Decrypted data as byte {@link string}. + */ private decryptString; decryptFile(key: string, file: PubNubFile, File: PubNubFileConstructor): Promise; + /** + * Cryptography algorithm. + * + * @returns Cryptography module algorithm. + */ private get algo(); + /** + * Convert cipher key to the {@link Buffer}. + * + * @param key - String cipher key. + * + * @returns SHA256 HEX encoded cipher key {@link Buffer}. + */ private getKey; + /** + * Generate random initialization vector. + * + * @returns Random initialization vector. + */ private getIv; } diff --git a/lib/types/errors/pubnub-api-error.d.ts b/lib/types/errors/pubnub-api-error.d.ts index 037db6967..1b75e3be8 100644 --- a/lib/types/errors/pubnub-api-error.d.ts +++ b/lib/types/errors/pubnub-api-error.d.ts @@ -1,16 +1,73 @@ +/** + * REST API endpoint use error module. + */ import { TransportResponse } from '../core/types/transport-response'; import RequestOperation from '../core/constants/operations'; import StatusCategory from '../core/constants/categories'; import { Payload, Status } from '../core/types/api'; import { PubNubError } from './pubnub-error'; +/** + * PubNub REST API call error. + */ export declare class PubNubAPIError extends Error { readonly category: StatusCategory; readonly statusCode: number; readonly errorData?: Error | Payload | undefined; + /** + * Construct API from known error object or {@link PubNub} service error response. + * + * @param errorOrResponse - `Error` or service error response object from which error information + * should be extracted. + * @param data - Preprocessed service error response. + * + * @returns `PubNubAPIError` object with known error category and additional information (if + * available). + */ static create(errorOrResponse: Error | TransportResponse, data?: ArrayBuffer): PubNubAPIError; + /** + * Create API error instance from other error object. + * + * @param error - `Error` object provided by network provider (mostly) or other {@link PubNub} client components. + * + * @returns `PubNubAPIError` object with known error category and additional information (if + * available). + */ private static createFromError; + /** + * Construct API from known {@link PubNub} service error response. + * + * @param response - Service error response object from which error information should be + * extracted. + * @param data - Preprocessed service error response. + * + * @returns `PubNubAPIError` object with known error category and additional information (if + * available). + */ private static createFromServiceResponse; + /** + * Construct PubNub endpoint error. + * + * @param message - Short API call error description. + * @param category - Error category. + * @param statusCode - Response HTTP status code. + * @param errorData - Error information. + */ constructor(message: string, category: StatusCategory, statusCode: number, errorData?: Error | Payload | undefined); + /** + * Convert API error object to API callback status object. + * + * @param operation - Request operation during which error happened. + * + * @returns Pre-formatted API callback status object. + */ toStatus(operation: RequestOperation): Status; + /** + * Convert API error object to PubNub client error object. + * + * @param operation - Request operation during which error happened. + * @param message - Custom error message. + * + * @returns Client-facing pre-formatted endpoint call error. + */ toPubNubError(operation: RequestOperation, message?: string): PubNubError; } diff --git a/lib/types/event-engine/core/retryPolicy.d.ts b/lib/types/event-engine/core/retryPolicy.d.ts index 628c73d13..5aed5de37 100644 --- a/lib/types/event-engine/core/retryPolicy.d.ts +++ b/lib/types/event-engine/core/retryPolicy.d.ts @@ -4,15 +4,47 @@ export declare class RetryPolicy { static ExponentialRetryPolicy(configuration: ExponentialRetryPolicyConfiguration): RequestRetryPolicy & ExponentialRetryPolicyConfiguration; } export type RequestRetryPolicy = { + /** + * Check whether failed request can be retried. + * + * @param reason - Request processing failure reason. + * @param attempt - Number of consequent failure. + * + * @returns `true` if another request retry attempt can be done. + */ shouldRetry(reason: PubNubError & { retryAfter?: number; }, attempt: number): boolean; + /** + * Computed delay for next request retry attempt. + * + * @param attempt - Number of consequent failure. + * @param reason - Request processing failure reason. + * + * @returns Delay before next request retry attempt in milliseconds. + */ getDelay(attempt: number, reason: PubNubError & { retryAfter?: number; }): number; + /** + * Identify reason why another retry attempt can't be made. + * + * @param reason - Request processing failure reason. + * @param attempt - Number of consequent failure. + * + * @returns Give up reason. + */ getGiveupReason(reason: PubNubError & { retryAfter?: number; }, attempt: number): string; + /** + * Validate retry policy parameters. + * + * @throws Error if `minimum` delay is smaller than 2 seconds for `exponential` retry policy. + * @throws Error if `maximum` delay is larger than 150 seconds for `exponential` retry policy. + * @throws Error if `maximumRetry` attempts is larger than 6 for `exponential` retry policy. + * @throws Error if `maximumRetry` attempts is larger than 10 for `linear` retry policy. + */ validate(): void; }; export type LinearRetryPolicyConfiguration = { diff --git a/lib/types/file/modules/node.d.ts b/lib/types/file/modules/node.d.ts index 63ad822b1..344f76fe5 100644 --- a/lib/types/file/modules/node.d.ts +++ b/lib/types/file/modules/node.d.ts @@ -1,35 +1,134 @@ +/** + * Node.js {@link PubNub} File object module. + */ /// /// import { Readable, PassThrough } from 'stream'; import { Buffer } from 'buffer'; import { PubNubFileInterface } from '../../core/types/file'; +/** + * PubNub File instance creation parameters. + */ export type PubNubFileParameters = { + /** + * Readable stream represents file object content. + */ stream?: Readable; + /** + * Buffer or string represents file object content. + */ data?: Buffer | ArrayBuffer | string; + /** + * String {@link PubNubFileParameters#data|data} encoding. + * + * @default `utf8` + */ encoding?: StringEncoding; + /** + * File object name. + */ name: string; + /** + * File object content type. + */ mimeType?: string; }; +/** + * Node.js implementation for {@link PubNub} File object. + * + * **Important:** Class should implement constructor and class fields from {@link PubNubFileConstructor}. + */ export default class PubNubFile implements PubNubFileInterface { + /** + * Whether {@link Blob} data supported by platform or not. + */ static supportsBlob: boolean; + /** + * Whether {@link File} data supported by platform or not. + */ static supportsFile: boolean; + /** + * Whether {@link Buffer} data supported by platform or not. + */ static supportsBuffer: boolean; + /** + * Whether {@link Stream} data supported by platform or not. + */ static supportsStream: boolean; + /** + * Whether {@link String} data supported by platform or not. + */ static supportsString: boolean; + /** + * Whether {@link ArrayBuffer} supported by platform or not. + */ static supportsArrayBuffer: boolean; + /** + * Whether {@link PubNub} File object encryption supported or not. + */ static supportsEncryptFile: boolean; + /** + * Whether `File Uri` data supported by platform or not. + */ static supportsFileUri: boolean; + /** + * File object content source. + */ readonly data: Readable | Buffer; + /** + * File object content length. + */ contentLength?: number; + /** + * File object content type. + */ mimeType: string; + /** + * File object name. + */ name: string; static create(file: PubNubFileParameters): PubNubFile; constructor(file: PubNubFileParameters); + /** + * Convert {@link PubNub} File object content to {@link Buffer}. + * + * @returns Asynchronous results of conversion to the {@link Buffer}. + */ toBuffer(): Promise; + /** + * Convert {@link PubNub} File object content to {@link ArrayBuffer}. + * + * @returns Asynchronous results of conversion to the {@link ArrayBuffer}. + */ toArrayBuffer(): Promise; + /** + * Convert {@link PubNub} File object content to {@link string}. + * + * @returns Asynchronous results of conversion to the {@link string}. + */ toString(encoding?: BufferEncoding): Promise; + /** + * Convert {@link PubNub} File object content to {@link Readable} stream. + * + * @returns Asynchronous results of conversion to the {@link Readable} stream. + */ toStream(): Promise; + /** + * Convert {@link PubNub} File object content to {@link File}. + * + * @throws Error because {@link File} not available in Node.js environment. + */ toFile(): Promise; + /** + * Convert {@link PubNub} File object content to file `Uri`. + * + * @throws Error because file `Uri` not available in Node.js environment. + */ toFileUri(): Promise>; + /** + * Convert {@link PubNub} File object content to {@link Blob}. + * + * @throws Error because {@link Blob} not available in Node.js environment. + */ toBlob(): Promise; } diff --git a/lib/types/file/modules/react-native.d.ts b/lib/types/file/modules/react-native.d.ts index ff707b6bd..51531b6ea 100644 --- a/lib/types/file/modules/react-native.d.ts +++ b/lib/types/file/modules/react-native.d.ts @@ -1,40 +1,135 @@ +/** + * React Native {@link PubNub} File object module. + */ import { PubNubFileInterface } from '../../core/types/file'; +/** + * File path-based file. + */ type FileUri = { uri: string; name: string; mimeType?: string; }; +/** + * Asynchronously fetched file content. + */ type ReadableFile = { arrayBuffer: () => Promise; blob: () => Promise; text: () => Promise; }; +/** + * PubNub File instance creation parameters. + */ export type PubNubFileParameters = File | FileUri | ReadableFile | { data: string | Blob | ArrayBuffer | ArrayBufferView; name: string; mimeType?: string; }; export declare class PubNubFile implements PubNubFileInterface { + /** + * Whether {@link Blob} data supported by platform or not. + */ static supportsBlob: boolean; + /** + * Whether {@link File} data supported by platform or not. + */ static supportsFile: boolean; + /** + * Whether {@link Buffer} data supported by platform or not. + */ static supportsBuffer: boolean; + /** + * Whether {@link Stream} data supported by platform or not. + */ static supportsStream: boolean; + /** + * Whether {@link String} data supported by platform or not. + */ static supportsString: boolean; + /** + * Whether {@link ArrayBuffer} supported by platform or not. + */ static supportsArrayBuffer: boolean; + /** + * Whether {@link PubNub} File object encryption supported or not. + */ static supportsEncryptFile: boolean; + /** + * Whether `File Uri` data supported by platform or not. + */ static supportsFileUri: boolean; + /** + * File object content source. + */ readonly data: File | FileUri | ReadableFile; + /** + * File object content length. + */ contentLength?: number; + /** + * File object content type. + */ mimeType: string; + /** + * File object name. + */ name: string; static create(file: PubNubFileParameters): PubNubFile; constructor(file: PubNubFileParameters); + /** + * Convert {@link PubNub} File object content to {@link Buffer}. + * + * @throws Error because {@link Buffer} not available in React Native environment. + */ toBuffer(): Promise; + /** + * Convert {@link PubNub} File object content to {@link ArrayBuffer}. + * + * @returns Asynchronous results of conversion to the {@link ArrayBuffer}. + * + * @throws Error if provided {@link PubNub} File object content is not supported for this + * operation. + */ toArrayBuffer(): Promise; + /** + * Convert {@link PubNub} File object content to {@link string}. + * + * @returns Asynchronous results of conversion to the {@link string}. + */ toString(): Promise; + /** + * Convert {@link PubNub} File object content to {@link Readable} stream. + * + * @throws Error because {@link Readable} stream not available in React Native environment. + */ toStream(): Promise; + /** + * Convert {@link PubNub} File object content to {@link File}. + * + * @returns Asynchronous results of conversion to the {@link File}. + * + * @throws Error if provided {@link PubNub} File object content is not supported for this + * operation. + */ toFile(): Promise; + /** + * Convert {@link PubNub} File object content to file `Uri`. + * + * @returns Asynchronous results of conversion to file `Uri`. + * + * @throws Error if provided {@link PubNub} File object content is not supported for this + * operation. + */ toFileUri(): Promise; + /** + * Convert {@link PubNub} File object content to {@link Blob}. + * + * @returns Asynchronous results of conversion to the {@link Blob}. + * + * @throws Error if provided {@link PubNub} File object content is not supported for this + * operation. + */ toBlob(): Promise; } export default PubNubFile; diff --git a/lib/types/node/configuration.d.ts b/lib/types/node/configuration.d.ts index 042052553..1d31293bb 100644 --- a/lib/types/node/configuration.d.ts +++ b/lib/types/node/configuration.d.ts @@ -1,13 +1,54 @@ -import { UserConfiguration, ExtendedConfiguration } from '../core/interfaces/configuration'; +/** + * Node.js specific {@link PubNub} client configuration module. + */ +import { UserConfiguration } from '../core/interfaces/configuration'; import { TransportKeepAlive } from '../core/interfaces/transport'; import { Payload } from '../core/types/api'; import { CryptoModule } from '../core/interfaces/crypto-module'; +/** + * NodeJS platform PubNub client configuration. + */ export type PubNubConfiguration = UserConfiguration & { + /** + * Set a custom parameters for setting your connection `keepAlive` if this is set to `true`. + */ keepAliveSettings?: TransportKeepAlive; + /** + * The cryptography module used for encryption and decryption of messages and files. Takes the + * {@link cipherKey} and {@link useRandomIVs} parameters as arguments. + * + * For more information, refer to the + * {@link /docs/sdks/javascript/api-reference/configuration#cryptomodule|cryptoModule} section. + * + * @default `not set` + */ cryptoModule?: CryptoModule; + /** + * If passed, will encrypt the payloads. + * + * @deprecated Pass it to {@link cryptoModule} instead. + */ cipherKey?: string; + /** + * When `true` the initialization vector (IV) is random for all requests (not just for file + * upload). + * When `false` the IV is hard-coded for all requests except for file upload. + * + * @default `true` + * + * @deprecated Pass it to {@link cryptoModule} instead. + */ useRandomIVs?: boolean; + /** + * Custom data encryption method. + * + * @deprecated Instead use {@link cryptoModule} for data encryption. + */ customEncrypt?: (data: string | Payload) => string; + /** + * Custom data decryption method. + * + * @deprecated Instead use {@link cryptoModule} for data decryption. + */ customDecrypt?: (data: string) => string; }; -export declare const setDefaults: (configuration: PubNubConfiguration) => PubNubConfiguration & ExtendedConfiguration; diff --git a/lib/types/node/index.d.ts b/lib/types/node/index.d.ts index f1005d985..71794933a 100644 --- a/lib/types/node/index.d.ts +++ b/lib/types/node/index.d.ts @@ -8,11 +8,31 @@ import PubNubFile, { PubNubFileParameters } from '../file/modules/node'; import { PubNubConfiguration } from './configuration'; import { PubNubFileConstructor } from '../core/types/file'; import { PubNubCore } from '../core/pubnub-common'; +/** + * PubNub client for Node.js platform. + */ declare class PubNub extends PubNubCore { + /** + * Data encryption / decryption module constructor. + */ static CryptoModule: typeof CryptoModule; + /** + * PubNub File constructor. + */ File: PubNubFileConstructor; + /** + * Actual underlying transport provider. + */ private nodeTransport; constructor(configuration: PubNubConfiguration); + /** + * Update request proxy configuration. + * + * @param configuration - Updated request proxy configuration. + * + * @throws An error if {@link PubNub} client already configured to use `keepAlive`. + * `keepAlive` and `proxy` can't be used simultaneously. + */ setProxy(configuration?: ProxyAgentOptions): void; } export = PubNub; diff --git a/lib/types/react_native/configuration.d.ts b/lib/types/react_native/configuration.d.ts index f2f28948b..a17ce3370 100644 --- a/lib/types/react_native/configuration.d.ts +++ b/lib/types/react_native/configuration.d.ts @@ -1,3 +1,5 @@ -import { ExtendedConfiguration, UserConfiguration } from '../core/interfaces/configuration'; +import { UserConfiguration } from '../core/interfaces/configuration'; +/** + * React Native platform PubNub client configuration. + */ export type PubNubConfiguration = UserConfiguration; -export declare const setDefaults: (configuration: PubNubConfiguration) => PubNubConfiguration & ExtendedConfiguration; diff --git a/lib/types/react_native/index.d.ts b/lib/types/react_native/index.d.ts index aff2a70fa..3dcb30caf 100644 --- a/lib/types/react_native/index.d.ts +++ b/lib/types/react_native/index.d.ts @@ -2,6 +2,9 @@ import 'react-native-url-polyfill/auto'; import { PubNubFileParameters } from '../file/modules/react-native'; import { PubNubConfiguration } from './configuration'; import { PubNubCore } from '../core/pubnub-common'; +/** + * PubNub client for React Native platform. + */ export default class PubNub extends PubNubCore { constructor(configuration: PubNubConfiguration); } diff --git a/lib/types/transport/middleware.d.ts b/lib/types/transport/middleware.d.ts index 6d88feba4..ee25da3f9 100644 --- a/lib/types/transport/middleware.d.ts +++ b/lib/types/transport/middleware.d.ts @@ -2,10 +2,25 @@ import { TransportRequest } from '../core/types/transport-request'; import { PrivateClientConfiguration } from '../core/interfaces/configuration'; import { TokenManager } from '../core/components/token_manager'; import { Transport } from '../core/interfaces/transport'; +/** + * Transport middleware configuration options. + */ type PubNubMiddlewareConfiguration = { + /** + * Private client configuration. + */ clientConfiguration: PrivateClientConfiguration; + /** + * REST API endpoints access tokens manager. + */ tokenManager: TokenManager; + /** + * HMAC-SHA256 hash generator from provided `data`. + */ shaHMAC?: (data: string) => string; + /** + * Platform-specific transport for requests processing. + */ transport: Transport; }; export declare class RequestSignature { @@ -14,17 +29,45 @@ export declare class RequestSignature { private hasher; private static textDecoder; constructor(publishKey: string, secretKey: string, hasher: (input: string, secret: string) => string); + /** + * Compute request signature. + * + * @param req - Request which will be used to compute signature. + * @returns {string} `v2` request signature. + */ signature(req: TransportRequest): string; + /** + * Prepare request query parameters for signature. + * + * @param query - Key / value pair of the request query parameters. + * @private + */ private queryParameters; } export declare class PubNubMiddleware implements Transport { private configuration; + /** + * Request signature generator. + */ signatureGenerator?: RequestSignature; constructor(configuration: PubNubMiddlewareConfiguration); makeSendable(req: TransportRequest): [Promise, import("../core/types/transport-request").CancellationController | undefined]; request(req: TransportRequest): TransportRequest; private authenticateRequest; + /** + * Compute and append request signature. + * + * @param req - Transport request with information which should be used to generate signature. + */ private signRequest; + /** + * Compose `pnsdk` query parameter. + * + * SDK provides ability to set custom name or append vendor information to the `pnsdk` query + * parameter. + * + * @returns Finalized `pnsdk` query parameter value. + */ private generatePNSDK; } export {}; diff --git a/lib/types/transport/node-transport.d.ts b/lib/types/transport/node-transport.d.ts index b7af775eb..1e2d7f5b9 100644 --- a/lib/types/transport/node-transport.d.ts +++ b/lib/types/transport/node-transport.d.ts @@ -3,20 +3,67 @@ import { ProxyAgentOptions } from 'proxy-agent'; import { CancellationController, TransportRequest } from '../core/types/transport-request'; import { Transport, TransportKeepAlive } from '../core/interfaces/transport'; import { TransportResponse } from '../core/types/transport-response'; +/** + * Class representing a fetch-based Node.js transport provider. + */ export declare class NodeTransport implements Transport { private readonly keepAlive; private readonly keepAliveSettings; private readonly logVerbosity; + /** + * Service {@link ArrayBuffer} response decoder. + */ protected static decoder: TextDecoder; + /** + * Request proxy configuration. + */ private proxyConfiguration?; private proxyAgent?; private httpsAgent?; private httpAgent?; + /** + * Creates a new `fetch`-based transport instance. + * + * @param keepAlive - Indicates whether keep-alive should be enabled. + * @param [keepAliveSettings] - Optional settings for keep-alive. + * @param [logVerbosity] - Whether verbose logging enabled or not. + * + * @returns Transport for performing network requests. + */ constructor(keepAlive?: boolean, keepAliveSettings?: TransportKeepAlive, logVerbosity?: boolean); + /** + * Update request proxy configuration. + * + * @param configuration - New proxy configuration. + */ setProxy(configuration?: ProxyAgentOptions): void; makeSendable(req: TransportRequest): [Promise, CancellationController | undefined]; request(req: TransportRequest): TransportRequest; + /** + * Creates a Request object from a given {@link TransportRequest} object. + * + * @param req - The {@link TransportRequest} object containing request information. + * + * @returns Request object generated from the {@link TransportRequest} object. + */ private requestFromTransportRequest; + /** + * Determines and returns the appropriate agent for a given transport request. + * + * If keep alive is not requested, returns undefined. + * + * @param req - The transport request object. + * + * @returns {HttpAgent | HttpsAgent | undefined} - The appropriate agent for the request, or + * undefined if keep alive or proxy not requested. + */ private agentForTransportRequest; + /** + * Log out request processing progress and result. + * + * @param request - Platform-specific request object. + * @param [elapsed] - How many times passed since request processing started. + * @param [body] - Service response (if available). + */ protected logRequestProcessProgress(request: Request, elapsed?: number, body?: ArrayBuffer): void; } diff --git a/lib/types/transport/web-react-native-transport.d.ts b/lib/types/transport/web-react-native-transport.d.ts index 2a5f650dd..753788bfd 100644 --- a/lib/types/transport/web-react-native-transport.d.ts +++ b/lib/types/transport/web-react-native-transport.d.ts @@ -1,13 +1,36 @@ +/** + * Common browser and React Native Transport provider module. + */ import { CancellationController, TransportRequest } from '../core/types/transport-request'; import { TransportResponse } from '../core/types/transport-response'; import { Transport } from '../core/interfaces/transport'; +/** + * Class representing a `fetch`-based browser and React Native transport provider. + */ export declare class WebReactNativeTransport implements Transport { private keepAlive; private readonly logVerbosity; + /** + * Service {@link ArrayBuffer} response decoder. + */ protected static decoder: TextDecoder; constructor(keepAlive: boolean, logVerbosity: boolean); makeSendable(req: TransportRequest): [Promise, CancellationController | undefined]; request(req: TransportRequest): TransportRequest; + /** + * Creates a Request object from a given {@link TransportRequest} object. + * + * @param req - The {@link TransportRequest} object containing request information. + * + * @returns Request object generated from the {@link TransportRequest} object. + */ private requestFromTransportRequest; + /** + * Log out request processing progress and result. + * + * @param request - Platform-specific + * @param [elapsed] - How many seconds passed since request processing started. + * @param [body] - Service response (if available). + */ protected logRequestProcessProgress(request: Request, elapsed?: number, body?: ArrayBuffer): void; } diff --git a/src/core/interfaces/configuration.ts b/src/core/interfaces/configuration.ts index dc8409957..f1a0cf3e4 100644 --- a/src/core/interfaces/configuration.ts +++ b/src/core/interfaces/configuration.ts @@ -384,6 +384,8 @@ export type ExtendedConfiguration = UserConfiguration & { * Platform-specific PubNub client configuration. * * Part of configuration which is added by platform-specific PubNub client initialization code. + * + * @internal */ export type PlatformConfiguration = { /** @@ -550,6 +552,8 @@ export interface ClientConfiguration { /** * Internal PubNub client configuration object interface. + * + * @internal */ export interface PrivateClientConfiguration extends ClientConfiguration, @@ -684,6 +688,8 @@ export interface PrivateClientConfiguration * Apply configuration default values. * * @param configuration - User-provided configuration. + * + * @internal */ export const setDefaults = (configuration: UserConfiguration): ExtendedConfiguration => { // Copy configuration. diff --git a/src/node/configuration.ts b/src/node/configuration.ts index e23d744d8..38a2eabc4 100644 --- a/src/node/configuration.ts +++ b/src/node/configuration.ts @@ -83,6 +83,8 @@ export type PubNubConfiguration = UserConfiguration & { * @param configuration - User-provided configuration. * * @returns Extended {@link PubNub} client configuration object pre-filled with default values. + * + * @internal */ export const setDefaults = (configuration: PubNubConfiguration): PubNubConfiguration & ExtendedConfiguration => { return { diff --git a/src/react_native/configuration.ts b/src/react_native/configuration.ts index 1cbfae42f..06fef4e47 100644 --- a/src/react_native/configuration.ts +++ b/src/react_native/configuration.ts @@ -13,6 +13,8 @@ export type PubNubConfiguration = UserConfiguration; * Apply configuration default values. * * @param configuration - User-provided configuration. + * + * @internal */ export const setDefaults = (configuration: PubNubConfiguration): PubNubConfiguration & ExtendedConfiguration => { return setBaseDefaults(configuration); diff --git a/tsconfig.json b/tsconfig.json index 712c2ac6a..2d6f18753 100644 --- a/tsconfig.json +++ b/tsconfig.json @@ -10,7 +10,6 @@ "esModuleInterop": true, "outDir": "./lib", "downlevelIteration": true, - "removeComments": true, "declaration": true, "declarationDir": "./lib/types", "stripInternal": true From 96e7a02d8810670f4787ed718b94b352ef9c166d Mon Sep 17 00:00:00 2001 From: PubNub Release Bot <120067856+pubnub-release-bot@users.noreply.github.com> Date: Thu, 16 May 2024 08:41:32 +0000 Subject: [PATCH 3/3] PubNub SDK v8.1.0 release. --- .pubnub.yml | 15 ++++++++++++--- CHANGELOG.md | 10 ++++++++++ README.md | 4 ++-- dist/web/pubnub.js | 2 +- dist/web/pubnub.min.js | 2 +- lib/core/components/configuration.js | 2 +- package.json | 2 +- src/core/components/configuration.ts | 2 +- 8 files changed, 29 insertions(+), 10 deletions(-) diff --git a/.pubnub.yml b/.pubnub.yml index e84db4641..54e9c5656 100644 --- a/.pubnub.yml +++ b/.pubnub.yml @@ -1,5 +1,14 @@ --- changelog: + - date: 2024-05-16 + version: v8.1.0 + changes: + - type: feature + text: "Use `SharedWorker` instead of `Service Worker` for better PubNub client instances feedback." + - type: feature + text: "Add configuration option to enable debug log output from the subscription `SharedWorker`." + - type: improvement + text: "Create types declaration files." - date: 2024-04-23 version: v8.0.1 changes: @@ -972,7 +981,7 @@ supported-platforms: - 'Ubuntu 14.04 and up' - 'Windows 7 and up' version: 'Pubnub Javascript for Node' -version: '8.0.1' +version: '8.1.0' sdks: - full-name: PubNub Javascript SDK short-name: Javascript @@ -988,7 +997,7 @@ sdks: - distribution-type: source distribution-repository: GitHub release package-name: pubnub.js - location: https://github.com/pubnub/javascript/archive/refs/tags/v8.0.1.zip + location: https://github.com/pubnub/javascript/archive/refs/tags/v8.1.0.zip requires: - name: 'agentkeepalive' min-version: '3.5.2' @@ -1659,7 +1668,7 @@ sdks: - distribution-type: library distribution-repository: GitHub release package-name: pubnub.js - location: https://github.com/pubnub/javascript/releases/download/v8.0.1/pubnub.8.0.1.js + location: https://github.com/pubnub/javascript/releases/download/v8.1.0/pubnub.8.1.0.js requires: - name: 'agentkeepalive' min-version: '3.5.2' diff --git a/CHANGELOG.md b/CHANGELOG.md index 77d7f99c3..e0076703c 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,3 +1,13 @@ +## v8.1.0 +May 16 2024 + +#### Added +- Use `SharedWorker` instead of `Service Worker` for better PubNub client instances feedback. +- Add configuration option to enable debug log output from the subscription `SharedWorker`. + +#### Modified +- Create types declaration files. + ## v8.0.1 April 23 2024 diff --git a/README.md b/README.md index 0aef17301..1a7344234 100644 --- a/README.md +++ b/README.md @@ -28,8 +28,8 @@ Watch [Getting Started with PubNub JS SDK](https://app.dashcam.io/replay/64ee0d2 npm install pubnub ``` * or download one of our builds from our CDN: - * https://cdn.pubnub.com/sdk/javascript/pubnub.8.0.1.js - * https://cdn.pubnub.com/sdk/javascript/pubnub.8.0.1.min.js + * https://cdn.pubnub.com/sdk/javascript/pubnub.8.1.0.js + * https://cdn.pubnub.com/sdk/javascript/pubnub.8.1.0.min.js 2. Configure your keys: diff --git a/dist/web/pubnub.js b/dist/web/pubnub.js index e639ef0e6..b313fae74 100644 --- a/dist/web/pubnub.js +++ b/dist/web/pubnub.js @@ -3810,7 +3810,7 @@ return base.PubNubFile; }, get version() { - return '8.0.1'; + return '8.1.0'; }, getVersion() { return this.version; diff --git a/dist/web/pubnub.min.js b/dist/web/pubnub.min.js index 006cf471a..c8962dd2c 100644 --- a/dist/web/pubnub.min.js +++ b/dist/web/pubnub.min.js @@ -1,2 +1,2 @@ !function(e,t){"object"==typeof exports&&"undefined"!=typeof module?module.exports=t():"function"==typeof define&&define.amd?define(t):(e="undefined"!=typeof globalThis?globalThis:e||self).PubNub=t()}(this,(function(){"use strict";var e="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{};function t(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var s={exports:{}};!function(t){!function(e,s){var n=Math.pow(2,-24),r=Math.pow(2,32),i=Math.pow(2,53);var o={encode:function(e){var t,n=new ArrayBuffer(256),o=new DataView(n),a=0;function c(e){for(var s=n.byteLength,r=a+e;s>2,u=0;u>6),r.push(128|63&o)):o<55296?(r.push(224|o>>12),r.push(128|o>>6&63),r.push(128|63&o)):(o=(1023&o)<<10,o|=1023&t.charCodeAt(++n),o+=65536,r.push(240|o>>18),r.push(128|o>>12&63),r.push(128|o>>6&63),r.push(128|63&o))}return d(3,r.length),h(r);default:var p;if(Array.isArray(t))for(d(4,p=t.length),n=0;n>5!==e)throw"Invalid indefinite length element";return s}function f(e,t){for(var s=0;s>10),e.push(56320|1023&n))}}"function"!=typeof t&&(t=function(e){return e}),"function"!=typeof i&&(i=function(){return s});var m=function e(){var r,d,m=l(),b=m>>5,v=31&m;if(7===b)switch(v){case 25:return function(){var e=new ArrayBuffer(4),t=new DataView(e),s=h(),r=32768&s,i=31744&s,o=1023&s;if(31744===i)i=261120;else if(0!==i)i+=114688;else if(0!==o)return o*n;return t.setUint32(0,r<<16|i<<13|o<<13),t.getFloat32(0)}();case 26:return c(o.getFloat32(a),4);case 27:return c(o.getFloat64(a),8)}if((d=g(v))<0&&(b<2||6=0;)S+=d,w.push(u(d));var k=new Uint8Array(S),E=0;for(r=0;r=0;)f(O,d);else f(O,d);return String.fromCharCode.apply(null,O);case 4:var C;if(d<0)for(C=[];!p();)C.push(e());else for(C=new Array(d),r=0;r{const s=new FileReader;s.addEventListener("load",(()=>{if(s.result instanceof ArrayBuffer)return e(s.result)})),s.addEventListener("error",(()=>t(s.error))),s.readAsArrayBuffer(this.data)}))}))}toString(){return i(this,void 0,void 0,(function*(){return new Promise(((e,t)=>{const s=new FileReader;s.addEventListener("load",(()=>{if("string"==typeof s.result)return e(s.result)})),s.addEventListener("error",(()=>{t(s.error)})),s.readAsBinaryString(this.data)}))}))}toStream(){return i(this,void 0,void 0,(function*(){throw new Error("This feature is only supported in Node.js environments.")}))}toFile(){return i(this,void 0,void 0,(function*(){return this.data}))}toFileUri(){return i(this,void 0,void 0,(function*(){throw new Error("This feature is only supported in React Native environments.")}))}toBlob(){return i(this,void 0,void 0,(function*(){return this.data}))}}a.supportsBlob="undefined"!=typeof Blob,a.supportsFile="undefined"!=typeof File,a.supportsBuffer=!1,a.supportsStream=!1,a.supportsString=!0,a.supportsArrayBuffer=!0,a.supportsEncryptFile=!0,a.supportsFileUri=!1;function c(e){const t=e.replace(/==?$/,""),s=Math.floor(t.length/4*3),n=new ArrayBuffer(s),r=new Uint8Array(n);let i=0;function o(){const e=t.charAt(i++),s="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=".indexOf(e);if(-1===s)throw new Error(`Illegal character at ${i}: ${t.charAt(i-1)}`);return s}for(let e=0;e>4,c=(15&s)<<4|n>>2,u=(3&n)<<6|i;r[e]=a,64!=n&&(r[e+1]=c),64!=i&&(r[e+2]=u)}return n}function u(e){let t="";const s="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",n=new Uint8Array(e),r=n.byteLength,i=r%3,o=r-i;let a,c,u,l,h;for(let e=0;e>18,c=(258048&h)>>12,u=(4032&h)>>6,l=63&h,t+=s[a]+s[c]+s[u]+s[l];return 1==i?(h=n[o],a=(252&h)>>2,c=(3&h)<<4,t+=s[a]+s[c]+"=="):2==i&&(h=n[o]<<8|n[o+1],a=(64512&h)>>10,c=(1008&h)>>4,u=(15&h)<<2,t+=s[a]+s[c]+s[u]+"="),t}var l;!function(e){e.PNNetworkIssuesCategory="PNNetworkIssuesCategory",e.PNTimeoutCategory="PNTimeoutCategory",e.PNCancelledCategory="PNCancelledCategory",e.PNBadRequestCategory="PNBadRequestCategory",e.PNAccessDeniedCategory="PNAccessDeniedCategory",e.PNValidationErrorCategory="PNValidationErrorCategory",e.PNAcknowledgmentCategory="PNAcknowledgmentCategory",e.PNUnknownCategory="PNUnknownCategory",e.PNNetworkUpCategory="PNNetworkUpCategory",e.PNNetworkDownCategory="PNNetworkDownCategory",e.PNReconnectedCategory="PNReconnectedCategory",e.PNConnectedCategory="PNConnectedCategory",e.PNRequestMessageCountExceededCategory="PNRequestMessageCountExceededCategory",e.PNDisconnectedCategory="PNDisconnectedCategory",e.PNConnectionErrorCategory="PNConnectionErrorCategory",e.PNDisconnectedUnexpectedlyCategory="PNDisconnectedUnexpectedlyCategory"}(l||(l={}));var h=l;class d extends Error{constructor(e,t){super(e),this.status=t,this.name="PubNubError",this.message=e,Object.setPrototypeOf(this,new.target.prototype)}}function p(e,t){return s=Object.assign({message:e},void 0!==t?{statusCode:t}:{}),null!==(n=s.statusCode)&&void 0!==n||(s.statusCode=0),Object.assign(Object.assign({},s),{statusCode:s.statusCode,category:h.PNValidationErrorCategory,error:!0});var s,n}var g,y,f,m,b,v=v||function(e,t){var s={},n=s.lib={},r=function(){},i=n.Base={extend:function(e){r.prototype=this;var t=new r;return e&&t.mixIn(e),t.hasOwnProperty("init")||(t.init=function(){t.$super.init.apply(this,arguments)}),t.init.prototype=t,t.$super=this,t},create:function(){var e=this.extend();return e.init.apply(e,arguments),e},init:function(){},mixIn:function(e){for(var t in e)e.hasOwnProperty(t)&&(this[t]=e[t]);e.hasOwnProperty("toString")&&(this.toString=e.toString)},clone:function(){return this.init.prototype.extend(this)}},o=n.WordArray=i.extend({init:function(e,t){e=this.words=e||[],this.sigBytes=null!=t?t:4*e.length},toString:function(e){return(e||c).stringify(this)},concat:function(e){var t=this.words,s=e.words,n=this.sigBytes;if(e=e.sigBytes,this.clamp(),n%4)for(var r=0;r>>2]|=(s[r>>>2]>>>24-r%4*8&255)<<24-(n+r)%4*8;else if(65535>>2]=s[r>>>2];else t.push.apply(t,s);return this.sigBytes+=e,this},clamp:function(){var t=this.words,s=this.sigBytes;t[s>>>2]&=4294967295<<32-s%4*8,t.length=e.ceil(s/4)},clone:function(){var e=i.clone.call(this);return e.words=this.words.slice(0),e},random:function(t){for(var s=[],n=0;n>>2]>>>24-n%4*8&255;s.push((r>>>4).toString(16)),s.push((15&r).toString(16))}return s.join("")},parse:function(e){for(var t=e.length,s=[],n=0;n>>3]|=parseInt(e.substr(n,2),16)<<24-n%8*4;return new o.init(s,t/2)}},u=a.Latin1={stringify:function(e){var t=e.words;e=e.sigBytes;for(var s=[],n=0;n>>2]>>>24-n%4*8&255));return s.join("")},parse:function(e){for(var t=e.length,s=[],n=0;n>>2]|=(255&e.charCodeAt(n))<<24-n%4*8;return new o.init(s,t)}},l=a.Utf8={stringify:function(e){try{return decodeURIComponent(escape(u.stringify(e)))}catch(e){throw Error("Malformed UTF-8 data")}},parse:function(e){return u.parse(unescape(encodeURIComponent(e)))}},h=n.BufferedBlockAlgorithm=i.extend({reset:function(){this._data=new o.init,this._nDataBytes=0},_append:function(e){"string"==typeof e&&(e=l.parse(e)),this._data.concat(e),this._nDataBytes+=e.sigBytes},_process:function(t){var s=this._data,n=s.words,r=s.sigBytes,i=this.blockSize,a=r/(4*i);if(t=(a=t?e.ceil(a):e.max((0|a)-this._minBufferSize,0))*i,r=e.min(4*t,r),t){for(var c=0;cu;){var l;e:{l=c;for(var h=e.sqrt(l),d=2;d<=h;d++)if(!(l%d)){l=!1;break e}l=!0}l&&(8>u&&(i[u]=a(e.pow(c,.5))),o[u]=a(e.pow(c,1/3)),u++),c++}var p=[];r=r.SHA256=n.extend({_doReset:function(){this._hash=new s.init(i.slice(0))},_doProcessBlock:function(e,t){for(var s=this._hash.words,n=s[0],r=s[1],i=s[2],a=s[3],c=s[4],u=s[5],l=s[6],h=s[7],d=0;64>d;d++){if(16>d)p[d]=0|e[t+d];else{var g=p[d-15],y=p[d-2];p[d]=((g<<25|g>>>7)^(g<<14|g>>>18)^g>>>3)+p[d-7]+((y<<15|y>>>17)^(y<<13|y>>>19)^y>>>10)+p[d-16]}g=h+((c<<26|c>>>6)^(c<<21|c>>>11)^(c<<7|c>>>25))+(c&u^~c&l)+o[d]+p[d],y=((n<<30|n>>>2)^(n<<19|n>>>13)^(n<<10|n>>>22))+(n&r^n&i^r&i),h=l,l=u,u=c,c=a+g|0,a=i,i=r,r=n,n=g+y|0}s[0]=s[0]+n|0,s[1]=s[1]+r|0,s[2]=s[2]+i|0,s[3]=s[3]+a|0,s[4]=s[4]+c|0,s[5]=s[5]+u|0,s[6]=s[6]+l|0,s[7]=s[7]+h|0},_doFinalize:function(){var t=this._data,s=t.words,n=8*this._nDataBytes,r=8*t.sigBytes;return s[r>>>5]|=128<<24-r%32,s[14+(r+64>>>9<<4)]=e.floor(n/4294967296),s[15+(r+64>>>9<<4)]=n,t.sigBytes=4*s.length,this._process(),this._hash},clone:function(){var e=n.clone.call(this);return e._hash=this._hash.clone(),e}});t.SHA256=n._createHelper(r),t.HmacSHA256=n._createHmacHelper(r)}(Math),y=(g=v).enc.Utf8,g.algo.HMAC=g.lib.Base.extend({init:function(e,t){e=this._hasher=new e.init,"string"==typeof t&&(t=y.parse(t));var s=e.blockSize,n=4*s;t.sigBytes>n&&(t=e.finalize(t)),t.clamp();for(var r=this._oKey=t.clone(),i=this._iKey=t.clone(),o=r.words,a=i.words,c=0;c>>2]>>>24-r%4*8&255)<<16|(t[r+1>>>2]>>>24-(r+1)%4*8&255)<<8|t[r+2>>>2]>>>24-(r+2)%4*8&255,o=0;4>o&&r+.75*o>>6*(3-o)&63));if(t=n.charAt(64))for(;e.length%4;)e.push(t);return e.join("")},parse:function(e){var t=e.length,s=this._map;(n=s.charAt(64))&&-1!=(n=e.indexOf(n))&&(t=n);for(var n=[],r=0,i=0;i>>6-i%4*2;n[r>>>2]|=(o|a)<<24-r%4*8,r++}return m.create(n,r)},_map:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/="},function(e){function t(e,t,s,n,r,i,o){return((e=e+(t&s|~t&n)+r+o)<>>32-i)+t}function s(e,t,s,n,r,i,o){return((e=e+(t&n|s&~n)+r+o)<>>32-i)+t}function n(e,t,s,n,r,i,o){return((e=e+(t^s^n)+r+o)<>>32-i)+t}function r(e,t,s,n,r,i,o){return((e=e+(s^(t|~n))+r+o)<>>32-i)+t}for(var i=v,o=(c=i.lib).WordArray,a=c.Hasher,c=i.algo,u=[],l=0;64>l;l++)u[l]=4294967296*e.abs(e.sin(l+1))|0;c=c.MD5=a.extend({_doReset:function(){this._hash=new o.init([1732584193,4023233417,2562383102,271733878])},_doProcessBlock:function(e,i){for(var o=0;16>o;o++){var a=e[c=i+o];e[c]=16711935&(a<<8|a>>>24)|4278255360&(a<<24|a>>>8)}o=this._hash.words;var c=e[i+0],l=(a=e[i+1],e[i+2]),h=e[i+3],d=e[i+4],p=e[i+5],g=e[i+6],y=e[i+7],f=e[i+8],m=e[i+9],b=e[i+10],v=e[i+11],w=e[i+12],S=e[i+13],k=e[i+14],E=e[i+15],O=t(O=o[0],P=o[1],N=o[2],C=o[3],c,7,u[0]),C=t(C,O,P,N,a,12,u[1]),N=t(N,C,O,P,l,17,u[2]),P=t(P,N,C,O,h,22,u[3]);O=t(O,P,N,C,d,7,u[4]),C=t(C,O,P,N,p,12,u[5]),N=t(N,C,O,P,g,17,u[6]),P=t(P,N,C,O,y,22,u[7]),O=t(O,P,N,C,f,7,u[8]),C=t(C,O,P,N,m,12,u[9]),N=t(N,C,O,P,b,17,u[10]),P=t(P,N,C,O,v,22,u[11]),O=t(O,P,N,C,w,7,u[12]),C=t(C,O,P,N,S,12,u[13]),N=t(N,C,O,P,k,17,u[14]),O=s(O,P=t(P,N,C,O,E,22,u[15]),N,C,a,5,u[16]),C=s(C,O,P,N,g,9,u[17]),N=s(N,C,O,P,v,14,u[18]),P=s(P,N,C,O,c,20,u[19]),O=s(O,P,N,C,p,5,u[20]),C=s(C,O,P,N,b,9,u[21]),N=s(N,C,O,P,E,14,u[22]),P=s(P,N,C,O,d,20,u[23]),O=s(O,P,N,C,m,5,u[24]),C=s(C,O,P,N,k,9,u[25]),N=s(N,C,O,P,h,14,u[26]),P=s(P,N,C,O,f,20,u[27]),O=s(O,P,N,C,S,5,u[28]),C=s(C,O,P,N,l,9,u[29]),N=s(N,C,O,P,y,14,u[30]),O=n(O,P=s(P,N,C,O,w,20,u[31]),N,C,p,4,u[32]),C=n(C,O,P,N,f,11,u[33]),N=n(N,C,O,P,v,16,u[34]),P=n(P,N,C,O,k,23,u[35]),O=n(O,P,N,C,a,4,u[36]),C=n(C,O,P,N,d,11,u[37]),N=n(N,C,O,P,y,16,u[38]),P=n(P,N,C,O,b,23,u[39]),O=n(O,P,N,C,S,4,u[40]),C=n(C,O,P,N,c,11,u[41]),N=n(N,C,O,P,h,16,u[42]),P=n(P,N,C,O,g,23,u[43]),O=n(O,P,N,C,m,4,u[44]),C=n(C,O,P,N,w,11,u[45]),N=n(N,C,O,P,E,16,u[46]),O=r(O,P=n(P,N,C,O,l,23,u[47]),N,C,c,6,u[48]),C=r(C,O,P,N,y,10,u[49]),N=r(N,C,O,P,k,15,u[50]),P=r(P,N,C,O,p,21,u[51]),O=r(O,P,N,C,w,6,u[52]),C=r(C,O,P,N,h,10,u[53]),N=r(N,C,O,P,b,15,u[54]),P=r(P,N,C,O,a,21,u[55]),O=r(O,P,N,C,f,6,u[56]),C=r(C,O,P,N,E,10,u[57]),N=r(N,C,O,P,g,15,u[58]),P=r(P,N,C,O,S,21,u[59]),O=r(O,P,N,C,d,6,u[60]),C=r(C,O,P,N,v,10,u[61]),N=r(N,C,O,P,l,15,u[62]),P=r(P,N,C,O,m,21,u[63]);o[0]=o[0]+O|0,o[1]=o[1]+P|0,o[2]=o[2]+N|0,o[3]=o[3]+C|0},_doFinalize:function(){var t=this._data,s=t.words,n=8*this._nDataBytes,r=8*t.sigBytes;s[r>>>5]|=128<<24-r%32;var i=e.floor(n/4294967296);for(s[15+(r+64>>>9<<4)]=16711935&(i<<8|i>>>24)|4278255360&(i<<24|i>>>8),s[14+(r+64>>>9<<4)]=16711935&(n<<8|n>>>24)|4278255360&(n<<24|n>>>8),t.sigBytes=4*(s.length+1),this._process(),s=(t=this._hash).words,n=0;4>n;n++)r=s[n],s[n]=16711935&(r<<8|r>>>24)|4278255360&(r<<24|r>>>8);return t},clone:function(){var e=a.clone.call(this);return e._hash=this._hash.clone(),e}}),i.MD5=a._createHelper(c),i.HmacMD5=a._createHmacHelper(c)}(Math),function(){var e,t=v,s=(e=t.lib).Base,n=e.WordArray,r=(e=t.algo).EvpKDF=s.extend({cfg:s.extend({keySize:4,hasher:e.MD5,iterations:1}),init:function(e){this.cfg=this.cfg.extend(e)},compute:function(e,t){for(var s=(a=this.cfg).hasher.create(),r=n.create(),i=r.words,o=a.keySize,a=a.iterations;i.length>>2]}},t.BlockCipher=a.extend({cfg:a.cfg.extend({mode:c,padding:l}),reset:function(){a.reset.call(this);var e=(t=this.cfg).iv,t=t.mode;if(this._xformMode==this._ENC_XFORM_MODE)var s=t.createEncryptor;else s=t.createDecryptor,this._minBufferSize=1;this._mode=s.call(t,this,e&&e.words)},_doProcessBlock:function(e,t){this._mode.processBlock(e,t)},_doFinalize:function(){var e=this.cfg.padding;if(this._xformMode==this._ENC_XFORM_MODE){e.pad(this._data,this.blockSize);var t=this._process(!0)}else t=this._process(!0),e.unpad(t);return t},blockSize:4});var h=t.CipherParams=s.extend({init:function(e){this.mixIn(e)},toString:function(e){return(e||this.formatter).stringify(this)}}),d=(c=(p.format={}).OpenSSL={stringify:function(e){var t=e.ciphertext;return((e=e.salt)?n.create([1398893684,1701076831]).concat(e).concat(t):t).toString(i)},parse:function(e){var t=(e=i.parse(e)).words;if(1398893684==t[0]&&1701076831==t[1]){var s=n.create(t.slice(2,4));t.splice(0,4),e.sigBytes-=16}return h.create({ciphertext:e,salt:s})}},t.SerializableCipher=s.extend({cfg:s.extend({format:c}),encrypt:function(e,t,s,n){n=this.cfg.extend(n);var r=e.createEncryptor(s,n);return t=r.finalize(t),r=r.cfg,h.create({ciphertext:t,key:s,iv:r.iv,algorithm:e,mode:r.mode,padding:r.padding,blockSize:e.blockSize,formatter:n.format})},decrypt:function(e,t,s,n){return n=this.cfg.extend(n),t=this._parse(t,n.format),e.createDecryptor(s,n).finalize(t.ciphertext)},_parse:function(e,t){return"string"==typeof e?t.parse(e,this):e}})),p=(p.kdf={}).OpenSSL={execute:function(e,t,s,r){return r||(r=n.random(8)),e=o.create({keySize:t+s}).compute(e,r),s=n.create(e.words.slice(t),4*s),e.sigBytes=4*t,h.create({key:e,iv:s,salt:r})}},g=t.PasswordBasedCipher=d.extend({cfg:d.cfg.extend({kdf:p}),encrypt:function(e,t,s,n){return s=(n=this.cfg.extend(n)).kdf.execute(s,e.keySize,e.ivSize),n.iv=s.iv,(e=d.encrypt.call(this,e,t,s.key,n)).mixIn(s),e},decrypt:function(e,t,s,n){return n=this.cfg.extend(n),t=this._parse(t,n.format),s=n.kdf.execute(s,e.keySize,e.ivSize,t.salt),n.iv=s.iv,d.decrypt.call(this,e,t,s.key,n)}})}(),function(){for(var e=v,t=e.lib.BlockCipher,s=e.algo,n=[],r=[],i=[],o=[],a=[],c=[],u=[],l=[],h=[],d=[],p=[],g=0;256>g;g++)p[g]=128>g?g<<1:g<<1^283;var y=0,f=0;for(g=0;256>g;g++){var m=(m=f^f<<1^f<<2^f<<3^f<<4)>>>8^255&m^99;n[y]=m,r[m]=y;var b=p[y],w=p[b],S=p[w],k=257*p[m]^16843008*m;i[y]=k<<24|k>>>8,o[y]=k<<16|k>>>16,a[y]=k<<8|k>>>24,c[y]=k,k=16843009*S^65537*w^257*b^16843008*y,u[m]=k<<24|k>>>8,l[m]=k<<16|k>>>16,h[m]=k<<8|k>>>24,d[m]=k,y?(y=b^p[p[p[S^b]]],f^=p[p[f]]):y=f=1}var E=[0,1,2,4,8,16,32,64,128,27,54];s=s.AES=t.extend({_doReset:function(){for(var e=(s=this._key).words,t=s.sigBytes/4,s=4*((this._nRounds=t+6)+1),r=this._keySchedule=[],i=0;i>>24]<<24|n[o>>>16&255]<<16|n[o>>>8&255]<<8|n[255&o]):(o=n[(o=o<<8|o>>>24)>>>24]<<24|n[o>>>16&255]<<16|n[o>>>8&255]<<8|n[255&o],o^=E[i/t|0]<<24),r[i]=r[i-t]^o}for(e=this._invKeySchedule=[],t=0;tt||4>=i?o:u[n[o>>>24]]^l[n[o>>>16&255]]^h[n[o>>>8&255]]^d[n[255&o]]},encryptBlock:function(e,t){this._doCryptBlock(e,t,this._keySchedule,i,o,a,c,n)},decryptBlock:function(e,t){var s=e[t+1];e[t+1]=e[t+3],e[t+3]=s,this._doCryptBlock(e,t,this._invKeySchedule,u,l,h,d,r),s=e[t+1],e[t+1]=e[t+3],e[t+3]=s},_doCryptBlock:function(e,t,s,n,r,i,o,a){for(var c=this._nRounds,u=e[t]^s[0],l=e[t+1]^s[1],h=e[t+2]^s[2],d=e[t+3]^s[3],p=4,g=1;g>>24]^r[l>>>16&255]^i[h>>>8&255]^o[255&d]^s[p++],f=n[l>>>24]^r[h>>>16&255]^i[d>>>8&255]^o[255&u]^s[p++],m=n[h>>>24]^r[d>>>16&255]^i[u>>>8&255]^o[255&l]^s[p++];d=n[d>>>24]^r[u>>>16&255]^i[l>>>8&255]^o[255&h]^s[p++],u=y,l=f,h=m}y=(a[u>>>24]<<24|a[l>>>16&255]<<16|a[h>>>8&255]<<8|a[255&d])^s[p++],f=(a[l>>>24]<<24|a[h>>>16&255]<<16|a[d>>>8&255]<<8|a[255&u])^s[p++],m=(a[h>>>24]<<24|a[d>>>16&255]<<16|a[u>>>8&255]<<8|a[255&l])^s[p++],d=(a[d>>>24]<<24|a[u>>>16&255]<<16|a[l>>>8&255]<<8|a[255&h])^s[p++],e[t]=y,e[t+1]=f,e[t+2]=m,e[t+3]=d},keySize:8});e.AES=t._createHelper(s)}(),v.mode.ECB=((b=v.lib.BlockCipherMode.extend()).Encryptor=b.extend({processBlock:function(e,t){this._cipher.encryptBlock(e,t)}}),b.Decryptor=b.extend({processBlock:function(e,t){this._cipher.decryptBlock(e,t)}}),b);var w=t(v);class S{constructor({cipherKey:e}){this.cipherKey=e,this.CryptoJS=w,this.encryptedKey=this.CryptoJS.SHA256(e)}encrypt(e){if(0===("string"==typeof e?e:S.decoder.decode(e)).length)throw new Error("encryption error. empty content");const t=this.getIv();return{metadata:t,data:c(this.CryptoJS.AES.encrypt(e,this.encryptedKey,{iv:this.bufferToWordArray(t),mode:this.CryptoJS.mode.CBC}).ciphertext.toString(this.CryptoJS.enc.Base64))}}encryptFileData(e){return i(this,void 0,void 0,(function*(){const t=yield this.getKey(),s=this.getIv();return{data:yield crypto.subtle.encrypt({name:this.algo,iv:s},t,e),metadata:s}}))}decrypt(e){if("string"==typeof e.data)throw new Error("Decryption error: data for decryption should be ArrayBuffed.");const t=this.bufferToWordArray(new Uint8ClampedArray(e.metadata)),s=this.bufferToWordArray(new Uint8ClampedArray(e.data));return S.encoder.encode(this.CryptoJS.AES.decrypt({ciphertext:s},this.encryptedKey,{iv:t,mode:this.CryptoJS.mode.CBC}).toString(this.CryptoJS.enc.Utf8)).buffer}decryptFileData(e){return i(this,void 0,void 0,(function*(){if("string"==typeof e.data)throw new Error("Decryption error: data for decryption should be ArrayBuffed.");const t=yield this.getKey();return crypto.subtle.decrypt({name:this.algo,iv:e.metadata},t,e.data)}))}get identifier(){return"ACRH"}get algo(){return"AES-CBC"}getIv(){return crypto.getRandomValues(new Uint8Array(S.BLOCK_SIZE))}getKey(){return i(this,void 0,void 0,(function*(){const e=S.encoder.encode(this.cipherKey),t=yield crypto.subtle.digest("SHA-256",e.buffer);return crypto.subtle.importKey("raw",t,this.algo,!0,["encrypt","decrypt"])}))}bufferToWordArray(e){const t=[];let s;for(s=0;se.toString(16).padStart(2,"0"))).join(""),n=C.encoder.encode(s.slice(0,32)).buffer;return crypto.subtle.importKey("raw",n,"AES-CBC",!0,["encrypt","decrypt"])}))}}C.IV_LENGTH=16,C.encoder=new TextEncoder,C.decoder=new TextDecoder;class N{constructor(e){this.config=e,this.cryptor=new E(Object.assign({},e)),this.fileCryptor=new C}encrypt(e){const t="string"==typeof e?e:N.decoder.decode(e);return{data:this.cryptor.encrypt(t),metadata:null}}encryptFile(e,t){return i(this,void 0,void 0,(function*(){var s;if(!this.config.cipherKey)throw new d("File encryption error: cipher key not set.");return this.fileCryptor.encryptFile(null===(s=this.config)||void 0===s?void 0:s.cipherKey,e,t)}))}decrypt(e){const t="string"==typeof e.data?e.data:u(e.data);return this.cryptor.decrypt(t)}decryptFile(e,t){return i(this,void 0,void 0,(function*(){if(!this.config.cipherKey)throw new d("File encryption error: cipher key not set.");return this.fileCryptor.decryptFile(this.config.cipherKey,e,t)}))}get identifier(){return""}}N.encoder=new TextEncoder,N.decoder=new TextDecoder;class P extends o{static legacyCryptoModule(e){var t;if(!e.cipherKey)throw new d("Crypto module error: cipher key not set.");return new P({default:new N(Object.assign(Object.assign({},e),{useRandomIVs:null===(t=e.useRandomIVs)||void 0===t||t})),cryptors:[new S({cipherKey:e.cipherKey})]})}static aesCbcCryptoModule(e){var t;if(!e.cipherKey)throw new d("Crypto module error: cipher key not set.");return new P({default:new S({cipherKey:e.cipherKey}),cryptors:[new N(Object.assign(Object.assign({},e),{useRandomIVs:null===(t=e.useRandomIVs)||void 0===t||t}))]})}static withDefaultCryptor(e){return new this({default:e})}encrypt(e){const t=e instanceof ArrayBuffer&&this.defaultCryptor.identifier===P.LEGACY_IDENTIFIER?this.defaultCryptor.encrypt(P.decoder.decode(e)):this.defaultCryptor.encrypt(e);if(!t.metadata)return t.data;if("string"==typeof t.data)throw new Error("Encryption error: encrypted data should be ArrayBuffed.");const s=this.getHeaderData(t);return this.concatArrayBuffer(s,t.data)}encryptFile(e,t){return i(this,void 0,void 0,(function*(){if(this.defaultCryptor.identifier===M.LEGACY_IDENTIFIER)return this.defaultCryptor.encryptFile(e,t);const s=yield this.getFileData(e),n=yield this.defaultCryptor.encryptFileData(s);if("string"==typeof n.data)throw new Error("Encryption error: encrypted data should be ArrayBuffed.");return t.create({name:e.name,mimeType:"application/octet-stream",data:this.concatArrayBuffer(this.getHeaderData(n),n.data)})}))}decrypt(e){const t="string"==typeof e?c(e):e,s=M.tryParse(t),n=this.getCryptor(s),r=s.length>0?t.slice(s.length-s.metadataLength,s.length):null;if(t.slice(s.length).byteLength<=0)throw new Error("Decryption error: empty content");return n.decrypt({data:t.slice(s.length),metadata:r})}decryptFile(e,t){return i(this,void 0,void 0,(function*(){const s=yield e.data.arrayBuffer(),n=M.tryParse(s),r=this.getCryptor(n);if((null==r?void 0:r.identifier)===M.LEGACY_IDENTIFIER)return r.decryptFile(e,t);const i=(yield this.getFileData(s)).slice(n.length-n.metadataLength,n.length);return t.create({name:e.name,data:yield this.defaultCryptor.decryptFileData({data:s.slice(n.length),metadata:i})})}))}getCryptorFromId(e){const t=this.getAllCryptors().find((t=>e===t.identifier));if(t)return t;throw Error("Unknown cryptor error")}getCryptor(e){if("string"==typeof e){const t=this.getAllCryptors().find((t=>t.identifier===e));if(t)return t;throw new Error("Unknown cryptor error")}if(e instanceof j)return this.getCryptorFromId(e.identifier)}getHeaderData(e){if(!e.metadata)return;const t=M.from(this.defaultCryptor.identifier,e.metadata),s=new Uint8Array(t.length);let n=0;return s.set(t.data,n),n+=t.length-e.metadata.byteLength,s.set(new Uint8Array(e.metadata),n),s.buffer}concatArrayBuffer(e,t){const s=new Uint8Array(e.byteLength+t.byteLength);return s.set(new Uint8Array(e),0),s.set(new Uint8Array(t),e.byteLength),s.buffer}getFileData(e){return i(this,void 0,void 0,(function*(){if(e instanceof ArrayBuffer)return e;if(e instanceof a)return e.toArrayBuffer();throw new Error("Cannot decrypt/encrypt file. In browsers file encrypt/decrypt supported for string, ArrayBuffer or Blob")}))}}P.LEGACY_IDENTIFIER="";class M{static from(e,t){if(e!==M.LEGACY_IDENTIFIER)return new j(e,t.byteLength)}static tryParse(e){const t=new Uint8Array(e);let s,n,r=null;if(t.byteLength>=4&&(s=t.slice(0,4),this.decoder.decode(s)!==M.SENTINEL))return P.LEGACY_IDENTIFIER;if(!(t.byteLength>=5))throw new Error("Decryption error: invalid header version");if(r=t[4],r>M.MAX_VERSION)throw new Error("Decryption error: Unknown cryptor error");let i=5+M.IDENTIFIER_LENGTH;if(!(t.byteLength>=i))throw new Error("Decryption error: invalid crypto identifier");n=t.slice(5,i);let o=null;if(!(t.byteLength>=i+1))throw new Error("Decryption error: invalid metadata length");return o=t[i],i+=1,255===o&&t.byteLength>=i+2&&(o=new Uint16Array(t.slice(i,i+2)).reduce(((e,t)=>(e<<8)+t),0)),new j(this.decoder.decode(n),o)}}M.SENTINEL="PNED",M.LEGACY_IDENTIFIER="",M.IDENTIFIER_LENGTH=4,M.VERSION=1,M.MAX_VERSION=1,M.decoder=new TextDecoder;class j{constructor(e,t){this._identifier=e,this._metadataLength=t}get identifier(){return this._identifier}set identifier(e){this._identifier=e}get metadataLength(){return this._metadataLength}set metadataLength(e){this._metadataLength=e}get version(){return M.VERSION}get length(){return M.SENTINEL.length+1+M.IDENTIFIER_LENGTH+(this.metadataLength<255?1:3)+this.metadataLength}get data(){let e=0;const t=new Uint8Array(this.length),s=new TextEncoder;t.set(s.encode(M.SENTINEL)),e+=M.SENTINEL.length,t[e]=this.version,e++,this.identifier&&t.set(s.encode(this.identifier),e);const n=this.metadataLength;return e+=M.IDENTIFIER_LENGTH,n<255?t[e]=n:t.set([255,n>>8,255&n],e),t}}j.IDENTIFIER_LENGTH=4,j.SENTINEL="PNED";class _ extends Error{static create(e,t){return e instanceof Error?_.createFromError(e):_.createFromServiceResponse(e,t)}static createFromError(e){let t=h.PNUnknownCategory,s="Unknown error",n="Error";if(!e)return new _(s,t,0);if(e instanceof _)return e;if(e instanceof Error&&(s=e.message,n=e.name),"AbortError"===n||-1!==s.indexOf("Aborted"))t=h.PNCancelledCategory,s="Request cancelled";else if(-1!==s.indexOf("timeout"))t=h.PNTimeoutCategory,s="Request timeout";else if(-1!==s.indexOf("network"))t=h.PNNetworkIssuesCategory,s="Network issues";else if("TypeError"===n)t=h.PNBadRequestCategory;else if("FetchError"===n){const n=e.code;["ECONNREFUSED","ENETUNREACH","ENOTFOUND","ECONNRESET","EAI_AGAIN"].includes(n)&&(t=h.PNNetworkIssuesCategory),"ECONNREFUSED"===n?s="Connection refused":"ENETUNREACH"===n?s="Network not reachable":"ENOTFOUND"===n?s="Server not found":"ECONNRESET"===n?s="Connection reset by peer":"EAI_AGAIN"===n?s="Name resolution error":"ETIMEDOUT"===n?(t=h.PNTimeoutCategory,s="Request timeout"):s=`Unknown system error: ${e}`}else"Request timeout"===s&&(t=h.PNTimeoutCategory);return new _(s,t,0,e)}static createFromServiceResponse(e,t){let s,n=h.PNUnknownCategory,r="Unknown error",{status:i}=e;if(null!=t||(t=e.body),402===i?r="Not available for used key set. Contact support@pubnub.com":400===i?(n=h.PNBadRequestCategory,r="Bad request"):403===i&&(n=h.PNAccessDeniedCategory,r="Access denied"),t&&t.byteLength>0){const n=(new TextDecoder).decode(t);if(-1!==e.headers["content-type"].indexOf("text/javascript")||-1!==e.headers["content-type"].indexOf("application/json"))try{const e=JSON.parse(n);"object"!=typeof e||Array.isArray(e)||("error"in e&&(1===e.error||!0===e.error)&&"status"in e&&"number"==typeof e.status&&"message"in e&&"service"in e?(s=e,i=e.status):s=e,"error"in e&&e.error instanceof Error&&(s=e.error))}catch(e){s=n}else if(-1!==e.headers["content-type"].indexOf("xml")){const e=/(.*)<\/Message>/gi.exec(n);r=e?`Upload to bucket failed: ${e[1]}`:"Upload to bucket failed."}else s=n}return new _(r,n,i,s)}constructor(e,t,s,n){super(e),this.category=t,this.statusCode=s,this.errorData=n,this.name="PubNubAPIError"}toStatus(e){return{error:!0,category:this.category,operation:e,statusCode:this.statusCode,errorData:this.errorData}}toPubNubError(e,t){return new d(null!=t?t:this.message,this.toStatus(e))}}class A{constructor(e){this.configuration=e,this.subscriptionWorkerReady=!1,this.workerEventsQueue=[],this.callbacks=new Map,this.setupSubscriptionWorker()}makeSendable(e){if(!e.path.startsWith("/v2/subscribe")&&!e.path.endsWith("/leave"))return this.configuration.transport.makeSendable(e);let t;const s={type:"send-request",clientIdentifier:this.configuration.clientIdentifier,subscriptionKey:this.configuration.subscriptionKey,logVerbosity:this.configuration.logVerbosity,request:e};return e.cancellable&&(t={abort:()=>{const t={type:"cancel-request",clientIdentifier:this.configuration.clientIdentifier,subscriptionKey:this.configuration.subscriptionKey,logVerbosity:this.configuration.logVerbosity,identifier:e.identifier};this.scheduleEventPost(t)}}),[new Promise(((t,n)=>{this.callbacks.set(e.identifier,{resolve:t,reject:n}),this.scheduleEventPost(s)})),t]}request(e){return e}scheduleEventPost(e,t=!1){const s=this.sharedSubscriptionWorker;s?s.port.postMessage(e):t?this.workerEventsQueue.splice(0,0,e):this.workerEventsQueue.push(e)}flushScheduledEvents(){const e=this.sharedSubscriptionWorker;if(!e||0===this.workerEventsQueue.length)return;const t=[];for(let e=0;e!t.includes(e))),this.workerEventsQueue.forEach((t=>e.port.postMessage(t))),this.workerEventsQueue=[]}get sharedSubscriptionWorker(){return this.subscriptionWorkerReady?this.subscriptionWorker:null}setupSubscriptionWorker(){"undefined"!=typeof SharedWorker&&(this.subscriptionWorker=new SharedWorker(this.configuration.workerUrl,`/pubnub-${this.configuration.sdkVersion}`),this.subscriptionWorker.port.start(),this.scheduleEventPost({type:"client-register",clientIdentifier:this.configuration.clientIdentifier,subscriptionKey:this.configuration.subscriptionKey,userId:this.configuration.userId,logVerbosity:this.configuration.logVerbosity,workerLogVerbosity:this.configuration.workerLogVerbosity},!0),this.subscriptionWorker.port.onmessage=e=>this.handleWorkerEvent(e))}handleWorkerEvent(e){const{data:t}=e;if("shared-worker-ping"===t.type||"shared-worker-connected"===t.type||"shared-worker-console-log"===t.type||"shared-worker-console-dir"===t.type||t.clientIdentifier===this.configuration.clientIdentifier)if("shared-worker-connected"===t.type)this.subscriptionWorkerReady=!0,this.flushScheduledEvents();else if("shared-worker-console-log"===t.type)console.log(`[SharedWorker] ${t.message}`);else if("shared-worker-console-dir"===t.type)t.message&&console.log(`[SharedWorker] ${t.message}`),console.dir(t.data);else if("shared-worker-ping"===t.type){const{logVerbosity:e,subscriptionKey:t,clientIdentifier:s}=this.configuration;this.scheduleEventPost({type:"client-pong",subscriptionKey:t,clientIdentifier:s,logVerbosity:e})}else if("request-progress-start"===t.type||"request-progress-end"===t.type)this.logRequestProgress(t);else if("request-process-success"===t.type||"request-process-error"===t.type){const{resolve:e,reject:s}=this.callbacks.get(t.identifier);if("request-process-success"===t.type)e({status:t.response.status,url:t.url,headers:t.response.headers,body:t.response.body});else{let e=h.PNUnknownCategory,n="Unknown error";if(t.error)"NETWORK_ISSUE"===t.error.type?e=h.PNNetworkIssuesCategory:"TIMEOUT"===t.error.type?e=h.PNTimeoutCategory:"ABORTED"===t.error.type&&(e=h.PNCancelledCategory),n=`${t.error.message} (${t.identifier})`;else if(t.response)return s(_.create({url:t.url,headers:t.response.headers,body:t.response.body,status:t.response.status},t.response.body));s(new _(n,e,0,new Error(n)))}}}logRequestProgress(e){var t,s;"request-progress-start"===e.type?(console.log("<<<<<"),console.log(`[${e.timestamp}] ${e.url}\n${JSON.stringify(null!==(t=e.query)&&void 0!==t?t:{})}`),console.log("-----")):(console.log(">>>>>>"),console.log(`[${e.timestamp} / ${e.duration}] ${e.url}\n${JSON.stringify(null!==(s=e.query)&&void 0!==s?s:{})}\n${e.response}`),console.log("-----"))}}const I=e=>encodeURIComponent(e).replace(/[!~*'()]/g,(e=>`%${e.charCodeAt(0).toString(16).toUpperCase()}`)),R=(e,t)=>{const s=e.map((e=>I(e)));return s.length?s.join(","):null!=t?t:""},U=(e,t)=>{const s=Object.fromEntries(t.map((e=>[e,!1])));return e.filter((e=>!(t.includes(e)&&!s[e])||(s[e]=!0,!1)))},T=(e,t)=>[...e].filter((s=>t.includes(s)&&e.indexOf(s)===e.lastIndexOf(s)&&t.indexOf(s)===t.lastIndexOf(s)));class F{constructor(e=!1,t){this.keepAlive=e,this.logVerbosity=t}makeSendable(e){let t,s;return e.cancellable&&(s=new AbortController,t={abortController:s,abort:()=>null==s?void 0:s.abort()}),[this.requestFromTransportRequest(e).then((t=>{const n=(new Date).getTime();this.logRequestProcessProgress(t);const r=new Promise(((t,s)=>{const n=setTimeout((()=>{clearTimeout(n),s(new Error("Request timeout"))}),1e3*e.timeout)}));return Promise.race([fetch(t,{signal:null==s?void 0:s.signal}),r]).then((e=>e.arrayBuffer().then((t=>[e,t])))).then((e=>{const s=e[1].byteLength>0?e[1]:void 0,{status:r,headers:i}=e[0],o={};i.forEach(((e,t)=>o[t]=e.toLowerCase()));const a={status:r,url:t.url,headers:o,body:s};if(r>=400)throw _.create(a);return this.logRequestProcessProgress(t,(new Date).getTime()-n,s),a})).catch((e=>{throw _.create(e)}))})),t]}request(e){return e}requestFromTransportRequest(e){return i(this,void 0,void 0,(function*(){let t,s=e.path;if(e.formData&&e.formData.length>0){e.queryParameters={};const s=e.body,n=new FormData;for(const{key:t,value:s}of e.formData)n.append(t,s);try{const e=yield s.toArrayBuffer();n.append("file",new Blob([e],{type:"application/octet-stream"}),s.name)}catch(e){try{const e=yield s.toFileUri();n.append("file",e,s.name)}catch(e){}}t=n}else e.body&&("string"==typeof e.body||e.body instanceof ArrayBuffer)&&(t=e.body);var n;return e.queryParameters&&0!==Object.keys(e.queryParameters).length&&(s=`${s}?${n=e.queryParameters,Object.keys(n).map((e=>{const t=n[e];return Array.isArray(t)?t.map((t=>`${e}=${I(t)}`)).join("&"):`${e}=${I(t)}`})).join("&")}`),new Request(`${e.origin}${s}`,{method:e.method,headers:e.headers,redirect:"follow",body:t})}))}logRequestProcessProgress(e,t,s){if(!this.logVerbosity)return;const{protocol:n,host:r,pathname:i,search:o}=new URL(e.url),a=(new Date).toISOString();if(t){const e=s?F.decoder.decode(s):void 0;console.log(">>>>>>"),console.log(`[${a} / ${t}]`,`\n${n}//${r}${i}`,`\n${o}`,`\n${e}`),console.log("-----")}else console.log("<<<<<"),console.log(`[${a}]`,`\n${n}//${r}${i}`,`\n${o}`),console.log("-----")}}function x(e){const t=e=>"object"==typeof e&&null!==e&&e.constructor===Object,s=e=>"number"==typeof e&&isFinite(e);if(!t(e))return e;const n={};return Object.keys(e).forEach((r=>{const i=(e=>"string"==typeof e||e instanceof String)(r);let o=r;const a=e[r];if(i&&r.indexOf(",")>=0){o=r.split(",").map(Number).reduce(((e,t)=>e+String.fromCharCode(t)),"")}else(s(r)||i&&!isNaN(Number(r)))&&(o=String.fromCharCode(s(r)?r:parseInt(r,10)));n[o]=t(a)?x(a):a})),n}F.decoder=new TextDecoder;const D=e=>{var t,s,n;return e.subscriptionWorkerUrl&&"undefined"==typeof SharedWorker&&(e.subscriptionWorkerUrl=null),Object.assign(Object.assign({},(e=>{var t,s,n,r,i,o,a,c,u,l,h,p,g,y,f;const m=Object.assign({},e);if(null!==(t=m.logVerbosity)&&void 0!==t||(m.logVerbosity=!1),null!==(s=m.ssl)&&void 0!==s||(m.ssl=!0),null!==(n=m.transactionalRequestTimeout)&&void 0!==n||(m.transactionalRequestTimeout=15),null!==(r=m.subscribeRequestTimeout)&&void 0!==r||(m.subscribeRequestTimeout=310),null!==(i=m.restore)&&void 0!==i||(m.restore=!1),null!==(o=m.useInstanceId)&&void 0!==o||(m.useInstanceId=!1),null!==(a=m.suppressLeaveEvents)&&void 0!==a||(m.suppressLeaveEvents=!1),null!==(c=m.requestMessageCountThreshold)&&void 0!==c||(m.requestMessageCountThreshold=100),null!==(u=m.autoNetworkDetection)&&void 0!==u||(m.autoNetworkDetection=!1),null!==(l=m.enableEventEngine)&&void 0!==l||(m.enableEventEngine=!1),null!==(h=m.maintainPresenceState)&&void 0!==h||(m.maintainPresenceState=!0),null!==(p=m.keepAlive)&&void 0!==p||(m.keepAlive=!1),m.userId&&m.uuid)throw new d("PubNub client configuration error: use only 'userId'");if(null!==(g=m.userId)&&void 0!==g||(m.userId=m.uuid),!m.userId)throw new d("PubNub client configuration error: 'userId' not set");if(0===(null===(y=m.userId)||void 0===y?void 0:y.trim().length))throw new d("PubNub client configuration error: 'userId' is empty");m.origin||(m.origin=Array.from({length:20},((e,t)=>`ps${t+1}.pndsn.com`)));const b={subscribeKey:m.subscribeKey,publishKey:m.publishKey,secretKey:m.secretKey};void 0!==m.presenceTimeout&&m.presenceTimeout<20&&(m.presenceTimeout=20,console.log("WARNING: Presence timeout is less than the minimum. Using minimum value: ",20)),null!==(f=m.presenceTimeout)&&void 0!==f||(m.presenceTimeout=300);let v=!1,w=!0,S=5,k=!1,E=!0;return void 0!==m.dedupeOnSubscribe&&"boolean"==typeof m.dedupeOnSubscribe&&(k=m.dedupeOnSubscribe),void 0!==m.useRequestId&&"boolean"==typeof m.useRequestId&&(E=m.useRequestId),void 0!==m.announceSuccessfulHeartbeats&&"boolean"==typeof m.announceSuccessfulHeartbeats&&(v=m.announceSuccessfulHeartbeats),void 0!==m.announceFailedHeartbeats&&"boolean"==typeof m.announceFailedHeartbeats&&(w=m.announceFailedHeartbeats),void 0!==m.fileUploadPublishRetryLimit&&"number"==typeof m.fileUploadPublishRetryLimit&&(S=m.fileUploadPublishRetryLimit),Object.assign(Object.assign({},m),{keySet:b,dedupeOnSubscribe:k,maximumCacheSize:100,useRequestId:E,announceSuccessfulHeartbeats:v,announceFailedHeartbeats:w,fileUploadPublishRetryLimit:S})})(e)),{listenToBrowserNetworkEvents:null===(t=e.listenToBrowserNetworkEvents)||void 0===t||t,subscriptionWorkerUrl:e.subscriptionWorkerUrl,subscriptionWorkerLogVerbosity:null!==(s=e.subscriptionWorkerLogVerbosity)&&void 0!==s&&s,keepAlive:null===(n=e.keepAlive)||void 0===n||n})};var K={exports:{}}; -/*! lil-uuid - v0.1 - MIT License - https://github.com/lil-js/uuid */!function(e,t){!function(e){var t="0.1.0",s={3:/^[0-9A-F]{8}-[0-9A-F]{4}-3[0-9A-F]{3}-[0-9A-F]{4}-[0-9A-F]{12}$/i,4:/^[0-9A-F]{8}-[0-9A-F]{4}-4[0-9A-F]{3}-[89AB][0-9A-F]{3}-[0-9A-F]{12}$/i,5:/^[0-9A-F]{8}-[0-9A-F]{4}-5[0-9A-F]{3}-[89AB][0-9A-F]{3}-[0-9A-F]{12}$/i,all:/^[0-9A-F]{8}-[0-9A-F]{4}-[0-9A-F]{4}-[0-9A-F]{4}-[0-9A-F]{12}$/i};function n(){var e,t,s="";for(e=0;e<32;e++)t=16*Math.random()|0,8!==e&&12!==e&&16!==e&&20!==e||(s+="-"),s+=(12===e?4:16===e?3&t|8:t).toString(16);return s}function r(e,t){var n=s[t||"all"];return n&&n.test(e)||!1}n.isUUID=r,n.VERSION=t,e.uuid=n,e.isUUID=r}(t),null!==e&&(e.exports=t.uuid)}(K,K.exports);var q=t(K.exports),G={createUUID:()=>q.uuid?q.uuid():q()};const $=(e,t)=>{var s,n,r;null===(s=e.retryConfiguration)||void 0===s||s.validate(),null!==(n=e.useRandomIVs)&&void 0!==n||(e.useRandomIVs=true),e.origin=L(null!==(r=e.ssl)&&void 0!==r&&r,e.origin);const i=e.cryptoModule;i&&delete e.cryptoModule;const o=Object.assign(Object.assign({},e),{_pnsdkSuffix:{},_instanceId:`pn-${G.createUUID()}`,_cryptoModule:void 0,_cipherKey:void 0,_setupCryptoModule:t,get instanceId(){if(this.useInstanceId)return this._instanceId},getUserId(){return this.userId},setUserId(e){if(!e||"string"!=typeof e||0===e.trim().length)throw new Error("Missing or invalid userId parameter. Provide a valid string userId");this.userId=e},getAuthKey(){return this.authKey},setAuthKey(e){this.authKey=e},getFilterExpression(){return this.filterExpression},setFilterExpression(e){this.filterExpression=e},getCipherKey(){return this._cipherKey},setCipherKey(t){this._cipherKey=t,t||!this._cryptoModule?t&&this._setupCryptoModule&&(this._cryptoModule=this._setupCryptoModule({cipherKey:t,useRandomIVs:e.useRandomIVs,customEncrypt:this.getCustomEncrypt(),customDecrypt:this.getCustomDecrypt()})):this._cryptoModule=void 0},getCryptoModule(){return this._cryptoModule},getUseRandomIVs:()=>e.useRandomIVs,setPresenceTimeout(e){this.heartbeatInterval=e/2-1,this.presenceTimeout=e},getPresenceTimeout(){return this.presenceTimeout},getHeartbeatInterval(){return this.heartbeatInterval},setHeartbeatInterval(e){this.heartbeatInterval=e},getTransactionTimeout(){return this.transactionalRequestTimeout},getSubscribeTimeout(){return this.subscribeRequestTimeout},get PubNubFile(){return e.PubNubFile},get version(){return"8.0.1"},getVersion(){return this.version},_addPnsdkSuffix(e,t){this._pnsdkSuffix[e]=`${t}`},_getPnsdkSuffix(e){const t=Object.values(this._pnsdkSuffix).join(e);return t.length>0?e+t:""},getUUID(){return this.getUserId()},setUUID(e){this.setUserId(e)},getCustomEncrypt:()=>e.customEncrypt,getCustomDecrypt:()=>e.customDecrypt});return e.cipherKey?o.setCipherKey(e.cipherKey):i&&(o._cryptoModule=i),o},L=(e,t)=>{const s=e?"https://":"http://";return"string"==typeof t?`${s}${t}`:`${s}${t[Math.floor(Math.random()*t.length)]}`};class B{constructor(e){this.cbor=e}setToken(e){e&&e.length>0?this.token=e:this.token=void 0}getToken(){return this.token}parseToken(e){const t=this.cbor.decodeToken(e);if(void 0!==t){const e=t.res.uuid?Object.keys(t.res.uuid):[],s=Object.keys(t.res.chan),n=Object.keys(t.res.grp),r=t.pat.uuid?Object.keys(t.pat.uuid):[],i=Object.keys(t.pat.chan),o=Object.keys(t.pat.grp),a={version:t.v,timestamp:t.t,ttl:t.ttl,authorized_uuid:t.uuid,signature:t.sig},c=e.length>0,u=s.length>0,l=n.length>0;if(c||u||l){if(a.resources={},c){const s=a.resources.uuids={};e.forEach((e=>s[e]=this.extractPermissions(t.res.uuid[e])))}if(u){const e=a.resources.channels={};s.forEach((s=>e[s]=this.extractPermissions(t.res.chan[s])))}if(l){const e=a.resources.groups={};n.forEach((s=>e[s]=this.extractPermissions(t.res.grp[s])))}}const h=r.length>0,d=i.length>0,p=o.length>0;if(h||d||p){if(a.patterns={},h){const e=a.patterns.uuids={};r.forEach((s=>e[s]=this.extractPermissions(t.pat.uuid[s])))}if(d){const e=a.patterns.channels={};i.forEach((s=>e[s]=this.extractPermissions(t.pat.chan[s])))}if(p){const e=a.patterns.groups={};o.forEach((s=>e[s]=this.extractPermissions(t.pat.grp[s])))}}return t.meta&&Object.keys(t.meta).length>0&&(a.meta=t.meta),a}}extractPermissions(e){const t={read:!1,write:!1,manage:!1,delete:!1,get:!1,update:!1,join:!1};return 128&~e||(t.join=!0),64&~e||(t.update=!0),32&~e||(t.get=!0),8&~e||(t.delete=!0),4&~e||(t.manage=!0),2&~e||(t.write=!0),1&~e||(t.read=!0),t}}var H;!function(e){e.GET="GET",e.POST="POST",e.PATCH="PATCH",e.DELETE="DELETE",e.LOCAL="LOCAL"}(H||(H={}));class z{constructor(e,t,s){this.publishKey=e,this.secretKey=t,this.hasher=s}signature(e){const t=e.path.startsWith("/publish")?H.GET:e.method;let s=`${t}\n${this.publishKey}\n${e.path}\n${this.queryParameters(e.queryParameters)}\n`;if(t===H.POST||t===H.PATCH){const t=e.body;let n;t&&t instanceof ArrayBuffer?n=z.textDecoder.decode(t):t&&"object"!=typeof t&&(n=t),n&&(s+=n)}return`v2.${this.hasher(s,this.secretKey)}`.replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}queryParameters(e){return Object.keys(e).sort().map((t=>{const s=e[t];return Array.isArray(s)?s.sort().map((e=>`${t}=${I(e)}`)).join("&"):`${t}=${I(s)}`})).join("&")}}z.textDecoder=new TextDecoder("utf-8");class V{constructor(e){this.configuration=e;const{clientConfiguration:{keySet:t},shaHMAC:s}=e;t.secretKey&&s&&(this.signatureGenerator=new z(t.publishKey,t.secretKey,s))}makeSendable(e){return this.configuration.transport.makeSendable(this.request(e))}request(e){var t;const{clientConfiguration:s}=this.configuration;return(e=this.configuration.transport.request(e)).queryParameters||(e.queryParameters={}),s.useInstanceId&&(e.queryParameters.instanceid=s.instanceId),e.queryParameters.uuid||(e.queryParameters.uuid=s.userId),s.useRequestId&&(e.queryParameters.requestid=e.identifier),e.queryParameters.pnsdk=this.generatePNSDK(),null!==(t=e.origin)&&void 0!==t||(e.origin=s.origin),this.authenticateRequest(e),this.signRequest(e),e}authenticateRequest(e){var t;if(e.path.startsWith("/v2/auth/")||e.path.startsWith("/v3/pam/")||e.path.startsWith("/time"))return;const{clientConfiguration:s,tokenManager:n}=this.configuration,r=null!==(t=n.getToken())&&void 0!==t?t:s.authKey;r&&(e.queryParameters.auth=r)}signRequest(e){this.signatureGenerator&&!e.path.startsWith("/time")&&(e.queryParameters.timestamp=String(Math.floor((new Date).getTime()/1e3)),e.queryParameters.signature=this.signatureGenerator.signature(e))}generatePNSDK(){const{clientConfiguration:e}=this.configuration;if(e.sdkName)return e.sdkName;let t=`PubNub-JS-${e.sdkFamily}`;e.partnerId&&(t+=`-${e.partnerId}`),t+=`/${e.getVersion()}`;const s=e._getPnsdkSuffix(" ");return s.length>0&&(t+=s),t}}class W{constructor(){this.listeners=[]}addListener(e){this.listeners.includes(e)||this.listeners.push(e)}removeListener(e){this.listeners=this.listeners.filter((t=>t!==e))}removeAllListeners(){this.listeners=[]}announceStatus(e){this.listeners.forEach((t=>{t.status&&t.status(e)}))}announcePresence(e){this.listeners.forEach((t=>{t.presence&&t.presence(e)}))}announceMessage(e){this.listeners.forEach((t=>{t.message&&t.message(e)}))}announceSignal(e){this.listeners.forEach((t=>{t.signal&&t.signal(e)}))}announceMessageAction(e){this.listeners.forEach((t=>{t.messageAction&&t.messageAction(e)}))}announceFile(e){this.listeners.forEach((t=>{t.file&&t.file(e)}))}announceObjects(e){this.listeners.forEach((t=>{t.objects&&t.objects(e)}))}announceNetworkUp(){this.listeners.forEach((e=>{e.status&&e.status({category:h.PNNetworkUpCategory})}))}announceNetworkDown(){this.listeners.forEach((e=>{e.status&&e.status({category:h.PNNetworkDownCategory})}))}announceUser(e){this.listeners.forEach((t=>{t.user&&t.user(e)}))}announceSpace(e){this.listeners.forEach((t=>{t.space&&t.space(e)}))}announceMembership(e){this.listeners.forEach((t=>{t.membership&&t.membership(e)}))}}class J{constructor(e){this.time=e}onReconnect(e){this.callback=e}startPolling(){this.timeTimer=setInterval((()=>this.callTime()),3e3)}stopPolling(){this.timeTimer&&clearInterval(this.timeTimer),this.timeTimer=null}callTime(){this.time((e=>{e.error||(this.stopPolling(),this.callback&&this.callback())}))}}class Q{_config;hashHistory;constructor({config:e}){this.hashHistory=[],this._config=e}getKey(e){const t=(e=>{let t=0;if(0===e.length)return t;for(let s=0;s=this._config.maximumCacheSize&&this.hashHistory.shift(),this.hashHistory.push(this.getKey(e))}clearHistory(){this.hashHistory=[]}}class Y{constructor(e,t,s,n,r,i,o){this.configuration=e,this.listenerManager=t,this.eventEmitter=s,this.subscribeCall=n,this.heartbeatCall=r,this.leaveCall=i,this.reconnectionManager=new J(o),this.dedupingManager=new Q({config:this.configuration}),this.heartbeatChannelGroups={},this.heartbeatChannels={},this.presenceChannelGroups={},this.presenceChannels={},this.heartbeatTimer=null,this.presenceState={},this.pendingChannelGroupSubscriptions=new Set,this.pendingChannelSubscriptions=new Set,this.channelGroups={},this.channels={},this.currentTimetoken="0",this.lastTimetoken="0",this.storedTimetoken=null,this.subscriptionStatusAnnounced=!1,this.isOnline=!0}get subscribedChannels(){return Object.keys(this.channels)}get subscribedChannelGroups(){return Object.keys(this.channelGroups)}get abort(){return this._subscribeAbort}set abort(e){this._subscribeAbort=e}disconnect(){this.stopSubscribeLoop(),this.stopHeartbeatTimer(),this.reconnectionManager.stopPolling()}reconnect(){this.startSubscribeLoop(),this.startHeartbeatTimer()}subscribe(e){const{channels:t,channelGroups:s,timetoken:n,withPresence:r=!1,withHeartbeats:i=!1}=e;n&&(this.lastTimetoken=this.currentTimetoken,this.currentTimetoken=n),"0"!==this.currentTimetoken&&0!==this.currentTimetoken&&(this.storedTimetoken=this.currentTimetoken,this.currentTimetoken=0),null==t||t.forEach((e=>{this.pendingChannelSubscriptions.add(e),this.channels[e]={},r&&(this.presenceChannels[e]={}),(i||this.configuration.getHeartbeatInterval())&&(this.heartbeatChannels[e]={})})),null==s||s.forEach((e=>{this.pendingChannelGroupSubscriptions.add(e),this.channelGroups[e]={},r&&(this.presenceChannelGroups[e]={}),(i||this.configuration.getHeartbeatInterval())&&(this.heartbeatChannelGroups[e]={})})),this.subscriptionStatusAnnounced=!1,this.reconnect()}unsubscribe(e,t){let{channels:s,channelGroups:n}=e;const i=new Set,o=new Set;null==s||s.forEach((e=>{e in this.channels&&(delete this.channels[e],o.add(e),e in this.heartbeatChannels&&delete this.heartbeatChannels[e]),e in this.presenceState&&delete this.presenceState[e],e in this.presenceChannels&&(delete this.presenceChannels[e],o.add(e))})),null==n||n.forEach((e=>{e in this.channelGroups&&(delete this.channelGroups[e],i.add(e),e in this.heartbeatChannelGroups&&delete this.heartbeatChannelGroups[e]),e in this.presenceState&&delete this.presenceState[e],e in this.presenceChannelGroups&&(delete this.presenceChannelGroups[e],i.add(e))})),0===o.size&&0===i.size||(!1!==this.configuration.suppressLeaveEvents||t||(n=Array.from(i),s=Array.from(o),this.leaveCall({channels:s,channelGroups:n},(e=>{const{error:t}=e,i=r(e,["error"]);let o;t&&(e.errorData&&"object"==typeof e.errorData&&"message"in e.errorData&&"string"==typeof e.errorData.message?o=e.errorData.message:"message"in e&&"string"==typeof e.message&&(o=e.message)),this.listenerManager.announceStatus(Object.assign(Object.assign({},i),{error:null!=o&&o,affectedChannels:s,affectedChannelGroups:n,currentTimetoken:this.currentTimetoken,lastTimetoken:this.lastTimetoken}))}))),0===Object.keys(this.channels).length&&0===Object.keys(this.presenceChannels).length&&0===Object.keys(this.channelGroups).length&&0===Object.keys(this.presenceChannelGroups).length&&(this.lastTimetoken=0,this.currentTimetoken=0,this.storedTimetoken=null,this.region=null,this.reconnectionManager.stopPolling()),this.reconnect())}unsubscribeAll(e){this.unsubscribe({channels:this.subscribedChannels,channelGroups:this.subscribedChannelGroups},e)}startSubscribeLoop(){this.stopSubscribeLoop();const e=[...Object.keys(this.channelGroups)],t=[...Object.keys(this.channels)];Object.keys(this.presenceChannelGroups).forEach((t=>e.push(`${t}-pnpres`))),Object.keys(this.presenceChannels).forEach((e=>t.push(`${e}-pnpres`))),0===t.length&&0===e.length||this.subscribeCall({channels:t,channelGroups:e,state:this.presenceState,heartbeat:this.configuration.getPresenceTimeout(),timetoken:this.currentTimetoken,region:null!==this.region?this.region:void 0,filterExpression:this.configuration.filterExpression},((e,t)=>{this.processSubscribeResponse(e,t)}))}stopSubscribeLoop(){this._subscribeAbort&&(this._subscribeAbort(),this._subscribeAbort=null)}processSubscribeResponse(e,t){if(e.error){if("object"==typeof e.errorData&&"name"in e.errorData&&"AbortError"===e.errorData.name||e.category===h.PNCancelledCategory)return;return void(e.category===h.PNTimeoutCategory?this.startSubscribeLoop():e.category===h.PNNetworkIssuesCategory?(this.disconnect(),e.error&&this.configuration.autoNetworkDetection&&this.isOnline&&(this.isOnline=!1,this.listenerManager.announceNetworkDown()),this.reconnectionManager.onReconnect((()=>{this.configuration.autoNetworkDetection&&!this.isOnline&&(this.isOnline=!0,this.listenerManager.announceNetworkUp()),this.reconnect(),this.subscriptionStatusAnnounced=!0;const t={category:h.PNReconnectedCategory,operation:e.operation,lastTimetoken:this.lastTimetoken,currentTimetoken:this.currentTimetoken};this.listenerManager.announceStatus(t)})),this.reconnectionManager.startPolling(),this.listenerManager.announceStatus(e)):e.category===h.PNBadRequestCategory?(this.stopHeartbeatTimer(),this.listenerManager.announceStatus(e)):this.listenerManager.announceStatus(e))}if(this.storedTimetoken?(this.currentTimetoken=this.storedTimetoken,this.storedTimetoken=null):(this.lastTimetoken=this.currentTimetoken,this.currentTimetoken=t.cursor.timetoken),!this.subscriptionStatusAnnounced){const t={category:h.PNConnectedCategory,operation:e.operation,affectedChannels:Array.from(this.pendingChannelSubscriptions),subscribedChannels:this.subscribedChannels,affectedChannelGroups:Array.from(this.pendingChannelGroupSubscriptions),lastTimetoken:this.lastTimetoken,currentTimetoken:this.currentTimetoken};this.subscriptionStatusAnnounced=!0,this.listenerManager.announceStatus(t),this.pendingChannelGroupSubscriptions.clear(),this.pendingChannelSubscriptions.clear()}const{messages:s}=t,{requestMessageCountThreshold:n,dedupeOnSubscribe:r}=this.configuration;n&&s.length>=n&&this.listenerManager.announceStatus({category:h.PNRequestMessageCountExceededCategory,operation:e.operation});try{s.forEach((e=>{if(r){if(this.dedupingManager.isDuplicate(e.data))return;this.dedupingManager.addEntry(e.data)}this.eventEmitter.emitEvent(e)}))}catch(e){const t={error:!0,category:h.PNUnknownCategory,errorData:e,statusCode:0};this.listenerManager.announceStatus(t)}this.region=t.cursor.region,this.startSubscribeLoop()}setState(e){const{state:t,channels:s,channelGroups:n}=e;null==s||s.forEach((e=>e in this.channels&&(this.presenceState[e]=t))),null==n||n.forEach((e=>e in this.channelGroups&&(this.presenceState[e]=t)))}changePresence(e){const{connected:t,channels:s,channelGroups:n}=e;t?(null==s||s.forEach((e=>this.heartbeatChannels[e]={})),null==n||n.forEach((e=>this.heartbeatChannelGroups[e]={}))):(null==s||s.forEach((e=>{e in this.heartbeatChannels&&delete this.heartbeatChannels[e]})),null==n||n.forEach((e=>{e in this.heartbeatChannelGroups&&delete this.heartbeatChannelGroups[e]})),!1===this.configuration.suppressLeaveEvents&&this.leaveCall({channels:s,channelGroups:n},(e=>this.listenerManager.announceStatus(e)))),this.reconnect()}startHeartbeatTimer(){this.stopHeartbeatTimer();const e=this.configuration.getHeartbeatInterval();e&&0!==e&&(this.sendHeartbeat(),this.heartbeatTimer=setInterval((()=>this.sendHeartbeat()),1e3*e))}stopHeartbeatTimer(){this.heartbeatTimer&&(clearInterval(this.heartbeatTimer),this.heartbeatTimer=null)}sendHeartbeat(){const e=Object.keys(this.heartbeatChannelGroups),t=Object.keys(this.heartbeatChannels);0===t.length&&0===e.length||this.heartbeatCall({channels:t,channelGroups:e,heartbeat:this.configuration.getPresenceTimeout(),state:this.presenceState},(e=>{e.error&&this.configuration.announceFailedHeartbeats&&this.listenerManager.announceStatus(e),e.error&&this.configuration.autoNetworkDetection&&this.isOnline&&(this.isOnline=!1,this.disconnect(),this.listenerManager.announceNetworkDown(),this.reconnect()),!e.error&&this.configuration.announceSuccessfulHeartbeats&&this.listenerManager.announceStatus(e)}))}}class X{constructor(e,t,s){this._payload=e,this.setDefaultPayloadStructure(),this.title=t,this.body=s}get payload(){return this._payload}set title(e){this._title=e}set subtitle(e){this._subtitle=e}set body(e){this._body=e}set badge(e){this._badge=e}set sound(e){this._sound=e}setDefaultPayloadStructure(){}toObject(){return{}}}class Z extends X{constructor(){super(...arguments),this._apnsPushType="apns",this._isSilent=!1}get payload(){return this._payload}set configurations(e){e&&e.length&&(this._configurations=e)}get notification(){return this.payload.aps}get title(){return this._title}set title(e){e&&e.length&&(this.payload.aps.alert.title=e,this._title=e)}get subtitle(){return this._subtitle}set subtitle(e){e&&e.length&&(this.payload.aps.alert.subtitle=e,this._subtitle=e)}get body(){return this._body}set body(e){e&&e.length&&(this.payload.aps.alert.body=e,this._body=e)}get badge(){return this._badge}set badge(e){null!=e&&(this.payload.aps.badge=e,this._badge=e)}get sound(){return this._sound}set sound(e){e&&e.length&&(this.payload.aps.sound=e,this._sound=e)}set silent(e){this._isSilent=e}setDefaultPayloadStructure(){this.payload.aps={alert:{}}}toObject(){const e=Object.assign({},this.payload),{aps:t}=e;let{alert:s}=t;if(this._isSilent&&(t["content-available"]=1),"apns2"===this._apnsPushType){if(!this._configurations||!this._configurations.length)throw new ReferenceError("APNS2 configuration is missing");const t=[];this._configurations.forEach((e=>{t.push(this.objectFromAPNS2Configuration(e))})),t.length&&(e.pn_push=t)}return s&&Object.keys(s).length||delete t.alert,this._isSilent&&(delete t.alert,delete t.badge,delete t.sound,s={}),this._isSilent||s&&Object.keys(s).length?e:null}objectFromAPNS2Configuration(e){if(!e.targets||!e.targets.length)throw new ReferenceError("At least one APNS2 target should be provided");const{collapseId:t,expirationDate:s}=e,n={auth_method:"token",targets:e.targets.map((e=>this.objectFromAPNSTarget(e))),version:"v2"};return t&&t.length&&(n.collapse_id=t),s&&(n.expiration=s.toISOString()),n}objectFromAPNSTarget(e){if(!e.topic||!e.topic.length)throw new TypeError("Target 'topic' undefined.");const{topic:t,environment:s="development",excludedDevices:n=[]}=e,r={topic:t,environment:s};return n.length&&(r.excluded_devices=n),r}}class ee extends X{get payload(){return this._payload}get notification(){return this.payload.notification}get data(){return this.payload.data}get title(){return this._title}set title(e){e&&e.length&&(this.payload.notification.title=e,this._title=e)}get body(){return this._body}set body(e){e&&e.length&&(this.payload.notification.body=e,this._body=e)}get sound(){return this._sound}set sound(e){e&&e.length&&(this.payload.notification.sound=e,this._sound=e)}get icon(){return this._icon}set icon(e){e&&e.length&&(this.payload.notification.icon=e,this._icon=e)}get tag(){return this._tag}set tag(e){e&&e.length&&(this.payload.notification.tag=e,this._tag=e)}set silent(e){this._isSilent=e}setDefaultPayloadStructure(){this.payload.notification={},this.payload.data={}}toObject(){let e=Object.assign({},this.payload.data),t=null;const s={};if(Object.keys(this.payload).length>2){const t=r(this.payload,["notification","data"]);e=Object.assign(Object.assign({},e),t)}return this._isSilent?e.notification=this.payload.notification:t=this.payload.notification,Object.keys(e).length&&(s.data=e),t&&Object.keys(t).length&&(s.notification=t),Object.keys(s).length?s:null}}class te{constructor(e,t){this._payload={apns:{},fcm:{}},this._title=e,this._body=t,this.apns=new Z(this._payload.apns,e,t),this.fcm=new ee(this._payload.fcm,e,t)}set debugging(e){this._debugging=e}get title(){return this._title}get subtitle(){return this._subtitle}set subtitle(e){this._subtitle=e,this.apns.subtitle=e,this.fcm.subtitle=e}get body(){return this._body}get badge(){return this._badge}set badge(e){this._badge=e,this.apns.badge=e,this.fcm.badge=e}get sound(){return this._sound}set sound(e){this._sound=e,this.apns.sound=e,this.fcm.sound=e}buildPayload(e){const t={};if(e.includes("apns")||e.includes("apns2")){this.apns._apnsPushType=e.includes("apns")?"apns":"apns2";const s=this.apns.toObject();s&&Object.keys(s).length&&(t.pn_apns=s)}if(e.includes("fcm")){const e=this.fcm.toObject();e&&Object.keys(e).length&&(t.pn_gcm=e)}return Object.keys(t).length&&this._debugging&&(t.pn_debug=!0),t}}class se{constructor(e){this.params=e,this.requestIdentifier=G.createUUID(),this._cancellationController=null}get cancellationController(){return this._cancellationController}set cancellationController(e){this._cancellationController=e}abort(){this&&this.cancellationController&&this.cancellationController.abort()}operation(){throw Error("Should be implemented by subclass.")}validate(){}parse(e){return i(this,void 0,void 0,(function*(){throw Error("Should be implemented by subclass.")}))}request(){var e,t,s,n;const r={method:null!==(t=null===(e=this.params)||void 0===e?void 0:e.method)&&void 0!==t?t:H.GET,path:this.path,queryParameters:this.queryParameters,cancellable:null!==(n=null===(s=this.params)||void 0===s?void 0:s.cancellable)&&void 0!==n&&n,timeout:1e4,identifier:this.requestIdentifier},i=this.headers;if(i&&(r.headers=i),r.method===H.POST||r.method===H.PATCH){const[e,t]=[this.body,this.formData];t&&(r.formData=t),e&&(r.body=e)}return r}get headers(){}get path(){throw Error("`path` getter should be implemented by subclass.")}get queryParameters(){return{}}get formData(){}get body(){}deserializeResponse(e){const t=e.headers["content-type"];if(!t||-1===t.indexOf("javascript")&&-1===t.indexOf("json"))return;const s=se.decoder.decode(e.body);try{return JSON.parse(s)}catch(e){return void console.error("Error parsing JSON response:",e)}}}var ne;se.decoder=new TextDecoder,function(e){e.PNPublishOperation="PNPublishOperation",e.PNSignalOperation="PNSignalOperation",e.PNSubscribeOperation="PNSubscribeOperation",e.PNUnsubscribeOperation="PNUnsubscribeOperation",e.PNWhereNowOperation="PNWhereNowOperation",e.PNHereNowOperation="PNHereNowOperation",e.PNGlobalHereNowOperation="PNGlobalHereNowOperation",e.PNSetStateOperation="PNSetStateOperation",e.PNGetStateOperation="PNGetStateOperation",e.PNHeartbeatOperation="PNHeartbeatOperation",e.PNAddMessageActionOperation="PNAddActionOperation",e.PNRemoveMessageActionOperation="PNRemoveMessageActionOperation",e.PNGetMessageActionsOperation="PNGetMessageActionsOperation",e.PNTimeOperation="PNTimeOperation",e.PNHistoryOperation="PNHistoryOperation",e.PNDeleteMessagesOperation="PNDeleteMessagesOperation",e.PNFetchMessagesOperation="PNFetchMessagesOperation",e.PNMessageCounts="PNMessageCountsOperation",e.PNGetAllUUIDMetadataOperation="PNGetAllUUIDMetadataOperation",e.PNGetUUIDMetadataOperation="PNGetUUIDMetadataOperation",e.PNSetUUIDMetadataOperation="PNSetUUIDMetadataOperation",e.PNRemoveUUIDMetadataOperation="PNRemoveUUIDMetadataOperation",e.PNGetAllChannelMetadataOperation="PNGetAllChannelMetadataOperation",e.PNGetChannelMetadataOperation="PNGetChannelMetadataOperation",e.PNSetChannelMetadataOperation="PNSetChannelMetadataOperation",e.PNRemoveChannelMetadataOperation="PNRemoveChannelMetadataOperation",e.PNGetMembersOperation="PNGetMembersOperation",e.PNSetMembersOperation="PNSetMembersOperation",e.PNGetMembershipsOperation="PNGetMembershipsOperation",e.PNSetMembershipsOperation="PNSetMembershipsOperation",e.PNListFilesOperation="PNListFilesOperation",e.PNGenerateUploadUrlOperation="PNGenerateUploadUrlOperation",e.PNPublishFileOperation="PNPublishFileOperation",e.PNPublishFileMessageOperation="PNPublishFileMessageOperation",e.PNGetFileUrlOperation="PNGetFileUrlOperation",e.PNDownloadFileOperation="PNDownloadFileOperation",e.PNDeleteFileOperation="PNDeleteFileOperation",e.PNAddPushNotificationEnabledChannelsOperation="PNAddPushNotificationEnabledChannelsOperation",e.PNRemovePushNotificationEnabledChannelsOperation="PNRemovePushNotificationEnabledChannelsOperation",e.PNPushNotificationEnabledChannelsOperation="PNPushNotificationEnabledChannelsOperation",e.PNRemoveAllPushNotificationsOperation="PNRemoveAllPushNotificationsOperation",e.PNChannelGroupsOperation="PNChannelGroupsOperation",e.PNRemoveGroupOperation="PNRemoveGroupOperation",e.PNChannelsForGroupOperation="PNChannelsForGroupOperation",e.PNAddChannelsToGroupOperation="PNAddChannelsToGroupOperation",e.PNRemoveChannelsFromGroupOperation="PNRemoveChannelsFromGroupOperation",e.PNAccessManagerGrant="PNAccessManagerGrant",e.PNAccessManagerGrantToken="PNAccessManagerGrantToken",e.PNAccessManagerAudit="PNAccessManagerAudit",e.PNAccessManagerRevokeToken="PNAccessManagerRevokeToken",e.PNHandshakeOperation="PNHandshakeOperation",e.PNReceiveMessagesOperation="PNReceiveMessagesOperation"}(ne||(ne={}));var re=ne;var ie;!function(e){e[e.Presence=-2]="Presence",e[e.Message=-1]="Message",e[e.Signal=1]="Signal",e[e.AppContext=2]="AppContext",e[e.MessageAction=3]="MessageAction",e[e.Files=4]="Files"}(ie||(ie={}));class oe extends se{constructor(e){var t,s,n,r,i,o;super({cancellable:!0}),this.parameters=e,null!==(t=(r=this.parameters).withPresence)&&void 0!==t||(r.withPresence=false),null!==(s=(i=this.parameters).channelGroups)&&void 0!==s||(i.channelGroups=[]),null!==(n=(o=this.parameters).channels)&&void 0!==n||(o.channels=[])}operation(){return re.PNSubscribeOperation}validate(){const{keySet:{subscribeKey:e},channels:t,channelGroups:s}=this.parameters;return e?t||s?void 0:"`channels` and `channelGroups` both should not be empty":"Missing Subscribe Key"}parse(e){return i(this,void 0,void 0,(function*(){let t;try{const s=se.decoder.decode(e.body);t=JSON.parse(s)}catch(e){console.error("Error parsing JSON response:",e)}if(!t)throw new d("Service response error, check status for details",p("Unable to deserialize service response"));const s=t.m.map((e=>{let{e:t}=e;return null!=t||(t=e.c.endsWith("-pnpres")?ie.Presence:ie.Message),"string"==typeof e.d?t==ie.Message?{type:ie.Message,data:this.messageFromEnvelope(e)}:{type:ie.Files,data:this.fileFromEnvelope(e)}:t==ie.Message?{type:ie.Message,data:this.messageFromEnvelope(e)}:t===ie.Presence?{type:ie.Presence,data:this.presenceEventFromEnvelope(e)}:t==ie.Signal?{type:ie.Signal,data:this.signalFromEnvelope(e)}:t===ie.AppContext?{type:ie.AppContext,data:this.appContextFromEnvelope(e)}:t===ie.MessageAction?{type:ie.MessageAction,data:this.messageActionFromEnvelope(e)}:{type:ie.Files,data:this.fileFromEnvelope(e)}}));return{cursor:{timetoken:t.t.t,region:t.t.r},messages:s}}))}get headers(){return{accept:"text/javascript"}}presenceEventFromEnvelope(e){const{d:t}=e,[s,n]=this.subscriptionChannelFromEnvelope(e),r=s.replace("-pnpres",""),i=null!==n?r:null,o=null!==n?n:r;return"string"!=typeof t&&"data"in t&&(t.state=t.data,delete t.data),Object.assign({channel:r,subscription:n,actualChannel:i,subscribedChannel:o,timetoken:e.p.t},t)}messageFromEnvelope(e){const[t,s]=this.subscriptionChannelFromEnvelope(e),[n,r]=this.decryptedData(e.d),i={channel:t,subscription:s,actualChannel:null!==s?t:null,subscribedChannel:null!==s?s:t,timetoken:e.p.t,publisher:e.i,message:n};return e.u&&(i.userMetadata=e.u),r&&(i.error=r),i}signalFromEnvelope(e){const[t,s]=this.subscriptionChannelFromEnvelope(e),n={channel:t,subscription:s,timetoken:e.p.t,publisher:e.i,message:e.d};return e.u&&(n.userMetadata=e.u),n}messageActionFromEnvelope(e){const[t,s]=this.subscriptionChannelFromEnvelope(e),n=e.d;return{channel:t,subscription:s,timetoken:e.p.t,publisher:e.i,event:n.event,data:Object.assign(Object.assign({},n.data),{uuid:e.i})}}appContextFromEnvelope(e){const[t,s]=this.subscriptionChannelFromEnvelope(e),n=e.d;return{channel:t,subscription:s,timetoken:e.p.t,message:n}}fileFromEnvelope(e){const[t,s]=this.subscriptionChannelFromEnvelope(e),[n,r]=this.decryptedData(e.d);let i=r;const o={channel:t,subscription:s,timetoken:e.p.t,publisher:e.i};return e.u&&(o.userMetadata=e.u),n?"string"==typeof n?null!=i||(i="Unexpected file information payload data type."):(o.message=n.message,n.file&&(o.file={id:n.file.id,name:n.file.name,url:this.parameters.getFileUrl({id:n.file.id,name:n.file.name,channel:t})})):null!=i||(i="File information payload is missing."),i&&(o.error=i),o}subscriptionChannelFromEnvelope(e){return[e.c,void 0===e.b?e.c:e.b]}decryptedData(e){if(!this.parameters.crypto||"string"!=typeof e)return[e,void 0];let t,s;try{const s=this.parameters.crypto.decrypt(e);t=s instanceof ArrayBuffer?JSON.parse(ae.decoder.decode(s)):s}catch(e){t=null,s=`Error while decrypting message content: ${e.message}`}return[null!=t?t:e,s]}}class ae extends oe{get path(){var e;const{keySet:{subscribeKey:t},channels:s}=this.parameters;return`/v2/subscribe/${t}/${R(null!==(e=null==s?void 0:s.sort())&&void 0!==e?e:[],",")}/0`}get queryParameters(){const{channelGroups:e,filterExpression:t,heartbeat:s,state:n,timetoken:r,region:i}=this.parameters,o={};return e&&e.length>0&&(o["channel-group"]=e.sort().join(",")),t&&t.length>0&&(o["filter-expr"]=t),s&&(o.heartbeat=s),n&&Object.keys(n).length>0&&(o.state=JSON.stringify(n)),void 0!==r&&"string"==typeof r?r.length>0&&"0"!==r&&(o.tt=r):void 0!==r&&r>0&&(o.tt=r),i&&(o.tr=i),o}}class ce{constructor(e){this.listenerManager=e,this.channelListenerMap=new Map,this.groupListenerMap=new Map}emitEvent(e){if(e.type===ie.Message)this.listenerManager.announceMessage(e.data),this.announce("message",e.data,e.data.channel,e.data.subscription);else if(e.type===ie.Signal)this.listenerManager.announceSignal(e.data),this.announce("signal",e.data,e.data.channel,e.data.subscription);else if(e.type===ie.Presence)this.listenerManager.announcePresence(e.data),this.announce("presence",e.data,e.data.channel,e.data.subscription);else if(e.type===ie.AppContext){const{data:t}=e,{message:s}=t;if(this.listenerManager.announceObjects(t),this.announce("objects",t,t.channel,t.subscription),"uuid"===s.type){const{message:e,channel:n}=t,i=r(t,["message","channel"]),{event:o,type:a}=s,c=r(s,["event","type"]),u=Object.assign(Object.assign({},i),{spaceId:n,message:Object.assign(Object.assign({},c),{event:"set"===o?"updated":"removed",type:"user"})});this.listenerManager.announceUser(u),this.announce("user",u,u.spaceId,u.subscription)}else if("channel"===s.type){const{message:e,channel:n}=t,i=r(t,["message","channel"]),{event:o,type:a}=s,c=r(s,["event","type"]),u=Object.assign(Object.assign({},i),{spaceId:n,message:Object.assign(Object.assign({},c),{event:"set"===o?"updated":"removed",type:"space"})});this.listenerManager.announceSpace(u),this.announce("space",u,u.spaceId,u.subscription)}else if("membership"===s.type){const{message:e,channel:n}=t,i=r(t,["message","channel"]),{event:o,data:a}=s,c=r(s,["event","data"]),{uuid:u,channel:l}=a,h=r(a,["uuid","channel"]),d=Object.assign(Object.assign({},i),{spaceId:n,message:Object.assign(Object.assign({},c),{event:"set"===o?"updated":"removed",data:Object.assign(Object.assign({},h),{user:u,space:l})})});this.listenerManager.announceMembership(d),this.announce("membership",d,d.spaceId,d.subscription)}}else e.type===ie.MessageAction?(this.listenerManager.announceMessageAction(e.data),this.announce("messageAction",e.data,e.data.channel,e.data.subscription)):e.type===ie.Files&&(this.listenerManager.announceFile(e.data),this.announce("file",e.data,e.data.channel,e.data.subscription))}addListener(e,t,s){t&&s?(null==t||t.forEach((t=>{if(this.channelListenerMap.has(t)){const s=this.channelListenerMap.get(t);s.includes(e)||s.push(e)}else this.channelListenerMap.set(t,[e])})),null==s||s.forEach((t=>{if(this.groupListenerMap.has(t)){const s=this.groupListenerMap.get(t);s.includes(e)||s.push(e)}else this.groupListenerMap.set(t,[e])}))):this.listenerManager.addListener(e)}removeListener(e,t,s){t&&s?(null==t||t.forEach((t=>{this.channelListenerMap.has(t)&&this.channelListenerMap.set(t,this.channelListenerMap.get(t).filter((t=>t!==e)))})),null==s||s.forEach((t=>{this.groupListenerMap.has(t)&&this.groupListenerMap.set(t,this.groupListenerMap.get(t).filter((t=>t!==e)))}))):this.listenerManager.removeListener(e)}removeAllListeners(){this.listenerManager.removeAllListeners(),this.channelListenerMap.clear(),this.groupListenerMap.clear()}announce(e,t,s,n){t&&this.channelListenerMap.has(s)&&this.channelListenerMap.get(s).forEach((s=>{const n=s[e];n&&n(t)})),n&&this.groupListenerMap.has(n)&&this.groupListenerMap.get(n).forEach((s=>{const n=s[e];n&&n(t)}))}}class ue{constructor(e=!1){this.sync=e,this.listeners=new Set}subscribe(e){return this.listeners.add(e),()=>{this.listeners.delete(e)}}notify(e){const t=()=>{this.listeners.forEach((t=>{t(e)}))};this.sync?t():setTimeout(t,0)}}class le{transition(e,t){var s;if(this.transitionMap.has(t.type))return null===(s=this.transitionMap.get(t.type))||void 0===s?void 0:s(e,t)}constructor(e){this.label=e,this.transitionMap=new Map,this.enterEffects=[],this.exitEffects=[]}on(e,t){return this.transitionMap.set(e,t),this}with(e,t){return[this,e,null!=t?t:[]]}onEnter(e){return this.enterEffects.push(e),this}onExit(e){return this.exitEffects.push(e),this}}class he extends ue{describe(e){return new le(e)}start(e,t){this.currentState=e,this.currentContext=t,this.notify({type:"engineStarted",state:e,context:t})}transition(e){if(!this.currentState)throw new Error("Start the engine first");this.notify({type:"eventReceived",event:e});const t=this.currentState.transition(this.currentContext,e);if(t){const[s,n,r]=t;for(const e of this.currentState.exitEffects)this.notify({type:"invocationDispatched",invocation:e(this.currentContext)});const i=this.currentState;this.currentState=s;const o=this.currentContext;this.currentContext=n,this.notify({type:"transitionDone",fromState:i,fromContext:o,toState:s,toContext:n,event:e});for(const e of r)this.notify({type:"invocationDispatched",invocation:e});for(const e of this.currentState.enterEffects)this.notify({type:"invocationDispatched",invocation:e(this.currentContext)})}}}class de{constructor(e){this.dependencies=e,this.instances=new Map,this.handlers=new Map}on(e,t){this.handlers.set(e,t)}dispatch(e){if("CANCEL"===e.type){if(this.instances.has(e.payload)){const t=this.instances.get(e.payload);null==t||t.cancel(),this.instances.delete(e.payload)}return}const t=this.handlers.get(e.type);if(!t)throw new Error(`Unhandled invocation '${e.type}'`);const s=t(e.payload,this.dependencies);e.managed&&this.instances.set(e.type,s),s.start()}dispose(){for(const[e,t]of this.instances.entries())t.cancel(),this.instances.delete(e)}}function pe(e,t){const s=function(...s){return{type:e,payload:null==t?void 0:t(...s)}};return s.type=e,s}function ge(e,t){const s=(...s)=>({type:e,payload:t(...s),managed:!1});return s.type=e,s}function ye(e,t){const s=(...s)=>({type:e,payload:t(...s),managed:!0});return s.type=e,s.cancel={type:"CANCEL",payload:e,managed:!1},s}class fe extends Error{constructor(){super("The operation was aborted."),this.name="AbortError",Object.setPrototypeOf(this,new.target.prototype)}}class me extends ue{constructor(){super(...arguments),this._aborted=!1}get aborted(){return this._aborted}throwIfAborted(){if(this._aborted)throw new fe}abort(){this._aborted=!0,this.notify(new fe)}}class be{constructor(e,t){this.payload=e,this.dependencies=t}}class ve extends be{constructor(e,t,s){super(e,t),this.asyncFunction=s,this.abortSignal=new me}start(){this.asyncFunction(this.payload,this.abortSignal,this.dependencies).catch((e=>{}))}cancel(){this.abortSignal.abort()}}const we=e=>(t,s)=>new ve(t,s,e),Se=pe("RECONNECT",(()=>({}))),ke=pe("DISCONNECT",(()=>({}))),Ee=pe("JOINED",((e,t)=>({channels:e,groups:t}))),Oe=pe("LEFT",((e,t)=>({channels:e,groups:t}))),Ce=pe("LEFT_ALL",(()=>({}))),Ne=pe("HEARTBEAT_SUCCESS",(e=>({statusCode:e}))),Pe=pe("HEARTBEAT_FAILURE",(e=>e)),Me=pe("HEARTBEAT_GIVEUP",(()=>({}))),je=pe("TIMES_UP",(()=>({}))),_e=ge("HEARTBEAT",((e,t)=>({channels:e,groups:t}))),Ae=ge("LEAVE",((e,t)=>({channels:e,groups:t}))),Ie=ge("EMIT_STATUS",(e=>e)),Re=ye("WAIT",(()=>({}))),Ue=ye("DELAYED_HEARTBEAT",(e=>e));class Te extends de{constructor(e,t){super(t),this.on(_e.type,we(((t,s,n)=>i(this,[t,s,n],void 0,(function*(t,s,{heartbeat:n,presenceState:r,config:i}){try{yield n(Object.assign(Object.assign({channels:t.channels,channelGroups:t.groups},i.maintainPresenceState&&{state:r}),{heartbeat:i.presenceTimeout}));e.transition(Ne(200))}catch(t){if(t instanceof d){if(t.status&&t.status.category==h.PNCancelledCategory)return;return e.transition(Pe(t))}}}))))),this.on(Ae.type,we(((e,t,s)=>i(this,[e,t,s],void 0,(function*(e,t,{leave:s,config:n}){if(!n.suppressLeaveEvents)try{s({channels:e.channels,channelGroups:e.groups})}catch(e){}}))))),this.on(Re.type,we(((t,s,n)=>i(this,[t,s,n],void 0,(function*(t,s,{heartbeatDelay:n}){return s.throwIfAborted(),yield n(),s.throwIfAborted(),e.transition(je())}))))),this.on(Ue.type,we(((t,s,n)=>i(this,[t,s,n],void 0,(function*(t,s,{heartbeat:n,retryDelay:r,presenceState:i,config:o}){if(!o.retryConfiguration||!o.retryConfiguration.shouldRetry(t.reason,t.attempts))return e.transition(Me());s.throwIfAborted(),yield r(o.retryConfiguration.getDelay(t.attempts,t.reason)),s.throwIfAborted();try{yield n(Object.assign(Object.assign({channels:t.channels,channelGroups:t.groups},o.maintainPresenceState&&{state:i}),{heartbeat:o.presenceTimeout}));return e.transition(Ne(200))}catch(t){if(t instanceof d){if(t.status&&t.status.category==h.PNCancelledCategory)return;return e.transition(Pe(t))}}}))))),this.on(Ie.type,we(((e,t,s)=>i(this,[e,t,s],void 0,(function*(e,t,{emitStatus:s,config:n}){var r;n.announceFailedHeartbeats&&!0===(null===(r=null==e?void 0:e.status)||void 0===r?void 0:r.error)?s(e.status):n.announceSuccessfulHeartbeats&&200===e.statusCode&&s(Object.assign(Object.assign({},e),{operation:re.PNHeartbeatOperation,error:!1}))})))))}}const Fe=new le("HEARTBEAT_STOPPED");Fe.on(Ee.type,((e,t)=>Fe.with({channels:[...e.channels,...t.payload.channels],groups:[...e.groups,...t.payload.groups]}))),Fe.on(Oe.type,((e,t)=>Fe.with({channels:e.channels.filter((e=>!t.payload.channels.includes(e))),groups:e.groups.filter((e=>!t.payload.groups.includes(e)))}))),Fe.on(Se.type,((e,t)=>qe.with({channels:e.channels,groups:e.groups}))),Fe.on(Ce.type,((e,t)=>Ge.with(void 0)));const xe=new le("HEARTBEAT_COOLDOWN");xe.onEnter((()=>Re())),xe.onExit((()=>Re.cancel)),xe.on(je.type,((e,t)=>qe.with({channels:e.channels,groups:e.groups}))),xe.on(Ee.type,((e,t)=>qe.with({channels:[...e.channels,...t.payload.channels],groups:[...e.groups,...t.payload.groups]}))),xe.on(Oe.type,((e,t)=>qe.with({channels:e.channels.filter((e=>!t.payload.channels.includes(e))),groups:e.groups.filter((e=>!t.payload.groups.includes(e)))},[Ae(t.payload.channels,t.payload.groups)]))),xe.on(ke.type,(e=>Fe.with({channels:e.channels,groups:e.groups},[Ae(e.channels,e.groups)]))),xe.on(Ce.type,((e,t)=>Ge.with(void 0,[Ae(e.channels,e.groups)])));const De=new le("HEARTBEAT_FAILED");De.on(Ee.type,((e,t)=>qe.with({channels:[...e.channels,...t.payload.channels],groups:[...e.groups,...t.payload.groups]}))),De.on(Oe.type,((e,t)=>qe.with({channels:e.channels.filter((e=>!t.payload.channels.includes(e))),groups:e.groups.filter((e=>!t.payload.groups.includes(e)))},[Ae(t.payload.channels,t.payload.groups)]))),De.on(Se.type,((e,t)=>qe.with({channels:e.channels,groups:e.groups}))),De.on(ke.type,((e,t)=>Fe.with({channels:e.channels,groups:e.groups},[Ae(e.channels,e.groups)]))),De.on(Ce.type,((e,t)=>Ge.with(void 0,[Ae(e.channels,e.groups)])));const Ke=new le("HEARBEAT_RECONNECTING");Ke.onEnter((e=>Ue(e))),Ke.onExit((()=>Ue.cancel)),Ke.on(Ee.type,((e,t)=>qe.with({channels:[...e.channels,...t.payload.channels],groups:[...e.groups,...t.payload.groups]}))),Ke.on(Oe.type,((e,t)=>qe.with({channels:e.channels.filter((e=>!t.payload.channels.includes(e))),groups:e.groups.filter((e=>!t.payload.groups.includes(e)))},[Ae(t.payload.channels,t.payload.groups)]))),Ke.on(ke.type,((e,t)=>{Fe.with({channels:e.channels,groups:e.groups},[Ae(e.channels,e.groups)])})),Ke.on(Ne.type,((e,t)=>xe.with({channels:e.channels,groups:e.groups}))),Ke.on(Pe.type,((e,t)=>Ke.with(Object.assign(Object.assign({},e),{attempts:e.attempts+1,reason:t.payload})))),Ke.on(Me.type,((e,t)=>De.with({channels:e.channels,groups:e.groups}))),Ke.on(Ce.type,((e,t)=>Ge.with(void 0,[Ae(e.channels,e.groups)])));const qe=new le("HEARTBEATING");qe.onEnter((e=>_e(e.channels,e.groups))),qe.on(Ne.type,((e,t)=>xe.with({channels:e.channels,groups:e.groups}))),qe.on(Ee.type,((e,t)=>qe.with({channels:[...e.channels,...t.payload.channels],groups:[...e.groups,...t.payload.groups]}))),qe.on(Oe.type,((e,t)=>qe.with({channels:e.channels.filter((e=>!t.payload.channels.includes(e))),groups:e.groups.filter((e=>!t.payload.groups.includes(e)))},[Ae(t.payload.channels,t.payload.groups)]))),qe.on(Pe.type,((e,t)=>Ke.with(Object.assign(Object.assign({},e),{attempts:0,reason:t.payload})))),qe.on(ke.type,(e=>Fe.with({channels:e.channels,groups:e.groups},[Ae(e.channels,e.groups)]))),qe.on(Ce.type,((e,t)=>Ge.with(void 0,[Ae(e.channels,e.groups)])));const Ge=new le("HEARTBEAT_INACTIVE");Ge.on(Ee.type,((e,t)=>qe.with({channels:t.payload.channels,groups:t.payload.groups})));class $e{get _engine(){return this.engine}constructor(e){this.dependencies=e,this.engine=new he,this.channels=[],this.groups=[],this.dispatcher=new Te(this.engine,e),this._unsubscribeEngine=this.engine.subscribe((e=>{"invocationDispatched"===e.type&&this.dispatcher.dispatch(e.invocation)})),this.engine.start(Ge,void 0)}join({channels:e,groups:t}){this.channels=[...this.channels,...null!=e?e:[]],this.groups=[...this.groups,...null!=t?t:[]],this.engine.transition(Ee(this.channels.slice(0),this.groups.slice(0)))}leave({channels:e,groups:t}){this.dependencies.presenceState&&(null==e||e.forEach((e=>delete this.dependencies.presenceState[e])),null==t||t.forEach((e=>delete this.dependencies.presenceState[e]))),this.engine.transition(Oe(null!=e?e:[],null!=t?t:[]))}leaveAll(){this.engine.transition(Ce())}dispose(){this._unsubscribeEngine(),this.dispatcher.dispose()}}class Le{static LinearRetryPolicy(e){return{delay:e.delay,maximumRetry:e.maximumRetry,shouldRetry(e,t){var s;return 403!==(null===(s=null==e?void 0:e.status)||void 0===s?void 0:s.statusCode)&&this.maximumRetry>t},getDelay(e,t){var s;return 1e3*((null!==(s=t.retryAfter)&&void 0!==s?s:this.delay)+Math.random())},getGiveupReason(e,t){var s;return this.maximumRetry<=t?"retry attempts exhaused.":403===(null===(s=null==e?void 0:e.status)||void 0===s?void 0:s.statusCode)?"forbidden operation.":"unknown error"},validate(){if(this.maximumRetry>10)throw new Error("Maximum retry for linear retry policy can not be more than 10")}}}static ExponentialRetryPolicy(e){return{minimumDelay:e.minimumDelay,maximumDelay:e.maximumDelay,maximumRetry:e.maximumRetry,shouldRetry(e,t){var s;return 403!==(null===(s=null==e?void 0:e.status)||void 0===s?void 0:s.statusCode)&&this.maximumRetry>t},getDelay(e,t){var s;return 1e3*((null!==(s=t.retryAfter)&&void 0!==s?s:Math.min(Math.pow(2,e),this.maximumDelay))+Math.random())},getGiveupReason(e,t){var s;return this.maximumRetry<=t?"retry attempts exhausted.":403===(null===(s=null==e?void 0:e.status)||void 0===s?void 0:s.statusCode)?"forbidden operation.":"unknown error"},validate(){if(this.minimumDelay<2)throw new Error("Minimum delay can not be set less than 2 seconds for retry");if(this.maximumDelay)throw new Error("Maximum delay can not be set more than 150 seconds for retry");if(this.maximumRetry>6)throw new Error("Maximum retry for exponential retry policy can not be more than 6")}}}}const Be=ye("HANDSHAKE",((e,t)=>({channels:e,groups:t}))),He=ye("RECEIVE_MESSAGES",((e,t,s)=>({channels:e,groups:t,cursor:s}))),ze=ge("EMIT_MESSAGES",(e=>e)),Ve=ge("EMIT_STATUS",(e=>e)),We=ye("RECEIVE_RECONNECT",(e=>e)),Je=ye("HANDSHAKE_RECONNECT",(e=>e)),Qe=pe("SUBSCRIPTION_CHANGED",((e,t)=>({channels:e,groups:t}))),Ye=pe("SUBSCRIPTION_RESTORED",((e,t,s,n)=>({channels:e,groups:t,cursor:{timetoken:s,region:null!=n?n:0}}))),Xe=pe("HANDSHAKE_SUCCESS",(e=>e)),Ze=pe("HANDSHAKE_FAILURE",(e=>e)),et=pe("HANDSHAKE_RECONNECT_SUCCESS",(e=>({cursor:e}))),tt=pe("HANDSHAKE_RECONNECT_FAILURE",(e=>e)),st=pe("HANDSHAKE_RECONNECT_GIVEUP",(e=>e)),nt=pe("RECEIVE_SUCCESS",((e,t)=>({cursor:e,events:t}))),rt=pe("RECEIVE_FAILURE",(e=>e)),it=pe("RECEIVE_RECONNECT_SUCCESS",((e,t)=>({cursor:e,events:t}))),ot=pe("RECEIVE_RECONNECT_FAILURE",(e=>e)),at=pe("RECEIVING_RECONNECT_GIVEUP",(e=>e)),ct=pe("DISCONNECT",(()=>({}))),ut=pe("RECONNECT",((e,t)=>({cursor:{timetoken:null!=e?e:"",region:null!=t?t:0}}))),lt=pe("UNSUBSCRIBE_ALL",(()=>({})));class ht extends de{constructor(e,t){super(t),this.on(Be.type,we(((t,s,n)=>i(this,[t,s,n],void 0,(function*(t,s,{handshake:n,presenceState:r,config:i}){s.throwIfAborted();try{const o=yield n(Object.assign({abortSignal:s,channels:t.channels,channelGroups:t.groups,filterExpression:i.filterExpression},i.maintainPresenceState&&{state:r}));return e.transition(Xe(o))}catch(t){if(t instanceof d){if(t.status&&t.status.category==h.PNCancelledCategory)return;return e.transition(Ze(t))}}}))))),this.on(He.type,we(((t,s,n)=>i(this,[t,s,n],void 0,(function*(t,s,{receiveMessages:n,config:r}){s.throwIfAborted();try{const i=yield n({abortSignal:s,channels:t.channels,channelGroups:t.groups,timetoken:t.cursor.timetoken,region:t.cursor.region,filterExpression:r.filterExpression});e.transition(nt(i.cursor,i.messages))}catch(t){if(t instanceof d){if(t.status&&t.status.category==h.PNCancelledCategory)return;if(!s.aborted)return e.transition(rt(t))}}}))))),this.on(ze.type,we(((e,t,s)=>i(this,[e,t,s],void 0,(function*(e,t,{emitMessages:s}){e.length>0&&s(e)}))))),this.on(Ve.type,we(((e,t,s)=>i(this,[e,t,s],void 0,(function*(e,t,{emitStatus:s}){s(e)}))))),this.on(We.type,we(((t,s,n)=>i(this,[t,s,n],void 0,(function*(t,s,{receiveMessages:n,delay:r,config:i}){if(!i.retryConfiguration||!i.retryConfiguration.shouldRetry(t.reason,t.attempts))return e.transition(at(new d(i.retryConfiguration?i.retryConfiguration.getGiveupReason(t.reason,t.attempts):"Unable to complete subscribe messages receive.")));s.throwIfAborted(),yield r(i.retryConfiguration.getDelay(t.attempts,t.reason)),s.throwIfAborted();try{const r=yield n({abortSignal:s,channels:t.channels,channelGroups:t.groups,timetoken:t.cursor.timetoken,region:t.cursor.region,filterExpression:i.filterExpression});return e.transition(it(r.cursor,r.messages))}catch(t){if(t instanceof d){if(t.status&&t.status.category==h.PNCancelledCategory)return;return e.transition(ot(t))}}}))))),this.on(Je.type,we(((t,s,n)=>i(this,[t,s,n],void 0,(function*(t,s,{handshake:n,delay:r,presenceState:i,config:o}){if(!o.retryConfiguration||!o.retryConfiguration.shouldRetry(t.reason,t.attempts))return e.transition(st(new d(o.retryConfiguration?o.retryConfiguration.getGiveupReason(t.reason,t.attempts):"Unable to complete subscribe handshake")));s.throwIfAborted(),yield r(o.retryConfiguration.getDelay(t.attempts,t.reason)),s.throwIfAborted();try{const r=yield n(Object.assign({abortSignal:s,channels:t.channels,channelGroups:t.groups,filterExpression:o.filterExpression},o.maintainPresenceState&&{state:i}));return e.transition(et(r))}catch(t){if(t instanceof d){if(t.status&&t.status.category==h.PNCancelledCategory)return;return e.transition(tt(t))}}})))))}}const dt=new le("HANDSHAKE_FAILED");dt.on(Qe.type,((e,t)=>vt.with({channels:t.payload.channels,groups:t.payload.groups,cursor:e.cursor}))),dt.on(ut.type,((e,t)=>vt.with({channels:e.channels,groups:e.groups,cursor:t.payload.cursor||e.cursor}))),dt.on(Ye.type,((e,t)=>{var s,n;return vt.with({channels:t.payload.channels,groups:t.payload.groups,cursor:{timetoken:t.payload.cursor.timetoken,region:t.payload.cursor.region?t.payload.cursor.region:null!==(n=null===(s=null==e?void 0:e.cursor)||void 0===s?void 0:s.region)&&void 0!==n?n:0}})})),dt.on(lt.type,(e=>wt.with()));const pt=new le("HANDSHAKE_STOPPED");pt.on(Qe.type,((e,t)=>pt.with({channels:t.payload.channels,groups:t.payload.groups,cursor:e.cursor}))),pt.on(ut.type,((e,t)=>vt.with(Object.assign(Object.assign({},e),{cursor:t.payload.cursor||e.cursor})))),pt.on(Ye.type,((e,t)=>{var s;return pt.with({channels:t.payload.channels,groups:t.payload.groups,cursor:{timetoken:t.payload.cursor.timetoken,region:t.payload.cursor.region||(null===(s=null==e?void 0:e.cursor)||void 0===s?void 0:s.region)||0}})})),pt.on(lt.type,(e=>wt.with()));const gt=new le("RECEIVE_FAILED");gt.on(ut.type,((e,t)=>{var s;return vt.with({channels:e.channels,groups:e.groups,cursor:{timetoken:t.payload.cursor.timetoken?null===(s=t.payload.cursor)||void 0===s?void 0:s.timetoken:e.cursor.timetoken,region:t.payload.cursor.region||e.cursor.region}})})),gt.on(Qe.type,((e,t)=>vt.with({channels:t.payload.channels,groups:t.payload.groups,cursor:e.cursor}))),gt.on(Ye.type,((e,t)=>vt.with({channels:t.payload.channels,groups:t.payload.groups,cursor:{timetoken:t.payload.cursor.timetoken,region:t.payload.cursor.region||e.cursor.region}}))),gt.on(lt.type,(e=>wt.with(void 0)));const yt=new le("RECEIVE_STOPPED");yt.on(Qe.type,((e,t)=>yt.with({channels:t.payload.channels,groups:t.payload.groups,cursor:e.cursor}))),yt.on(Ye.type,((e,t)=>yt.with({channels:t.payload.channels,groups:t.payload.groups,cursor:{timetoken:t.payload.cursor.timetoken,region:t.payload.cursor.region||e.cursor.region}}))),yt.on(ut.type,((e,t)=>{var s;return vt.with({channels:e.channels,groups:e.groups,cursor:{timetoken:t.payload.cursor.timetoken?null===(s=t.payload.cursor)||void 0===s?void 0:s.timetoken:e.cursor.timetoken,region:t.payload.cursor.region||e.cursor.region}})})),yt.on(lt.type,(()=>wt.with(void 0)));const ft=new le("RECEIVE_RECONNECTING");ft.onEnter((e=>We(e))),ft.onExit((()=>We.cancel)),ft.on(it.type,((e,t)=>mt.with({channels:e.channels,groups:e.groups,cursor:t.payload.cursor},[ze(t.payload.events)]))),ft.on(ot.type,((e,t)=>ft.with(Object.assign(Object.assign({},e),{attempts:e.attempts+1,reason:t.payload})))),ft.on(at.type,((e,t)=>{var s;return gt.with({groups:e.groups,channels:e.channels,cursor:e.cursor,reason:t.payload},[Ve({category:h.PNDisconnectedUnexpectedlyCategory,error:null===(s=t.payload)||void 0===s?void 0:s.message})])})),ft.on(ct.type,(e=>yt.with({channels:e.channels,groups:e.groups,cursor:e.cursor},[Ve({category:h.PNDisconnectedCategory})]))),ft.on(Ye.type,((e,t)=>mt.with({channels:t.payload.channels,groups:t.payload.groups,cursor:{timetoken:t.payload.cursor.timetoken,region:t.payload.cursor.region||e.cursor.region}}))),ft.on(Qe.type,((e,t)=>mt.with({channels:t.payload.channels,groups:t.payload.groups,cursor:e.cursor}))),ft.on(lt.type,(e=>wt.with(void 0,[Ve({category:h.PNDisconnectedCategory})])));const mt=new le("RECEIVING");mt.onEnter((e=>He(e.channels,e.groups,e.cursor))),mt.onExit((()=>He.cancel)),mt.on(nt.type,((e,t)=>mt.with({channels:e.channels,groups:e.groups,cursor:t.payload.cursor},[ze(t.payload.events)]))),mt.on(Qe.type,((e,t)=>0===t.payload.channels.length&&0===t.payload.groups.length?wt.with(void 0):mt.with({cursor:e.cursor,channels:t.payload.channels,groups:t.payload.groups}))),mt.on(Ye.type,((e,t)=>0===t.payload.channels.length&&0===t.payload.groups.length?wt.with(void 0):mt.with({channels:t.payload.channels,groups:t.payload.groups,cursor:{timetoken:t.payload.cursor.timetoken,region:t.payload.cursor.region||e.cursor.region}}))),mt.on(rt.type,((e,t)=>ft.with(Object.assign(Object.assign({},e),{attempts:0,reason:t.payload})))),mt.on(ct.type,(e=>yt.with({channels:e.channels,groups:e.groups,cursor:e.cursor},[Ve({category:h.PNDisconnectedCategory})]))),mt.on(lt.type,(e=>wt.with(void 0,[Ve({category:h.PNDisconnectedCategory})])));const bt=new le("HANDSHAKE_RECONNECTING");bt.onEnter((e=>Je(e))),bt.onExit((()=>Je.cancel)),bt.on(et.type,((e,t)=>{var s,n;const r={timetoken:(null===(s=e.cursor)||void 0===s?void 0:s.timetoken)?null===(n=e.cursor)||void 0===n?void 0:n.timetoken:t.payload.cursor.timetoken,region:t.payload.cursor.region};return mt.with({channels:e.channels,groups:e.groups,cursor:r},[Ve({category:h.PNConnectedCategory})])})),bt.on(tt.type,((e,t)=>bt.with(Object.assign(Object.assign({},e),{attempts:e.attempts+1,reason:t.payload})))),bt.on(st.type,((e,t)=>{var s;return dt.with({groups:e.groups,channels:e.channels,cursor:e.cursor,reason:t.payload},[Ve({category:h.PNConnectionErrorCategory,error:null===(s=t.payload)||void 0===s?void 0:s.message})])})),bt.on(ct.type,(e=>pt.with({channels:e.channels,groups:e.groups,cursor:e.cursor}))),bt.on(Qe.type,((e,t)=>vt.with({channels:t.payload.channels,groups:t.payload.groups,cursor:e.cursor}))),bt.on(Ye.type,((e,t)=>{var s,n;return vt.with({channels:t.payload.channels,groups:t.payload.groups,cursor:{timetoken:t.payload.cursor.timetoken,region:(null===(s=t.payload.cursor)||void 0===s?void 0:s.region)||(null===(n=null==e?void 0:e.cursor)||void 0===n?void 0:n.region)||0}})})),bt.on(lt.type,(e=>wt.with(void 0)));const vt=new le("HANDSHAKING");vt.onEnter((e=>Be(e.channels,e.groups))),vt.onExit((()=>Be.cancel)),vt.on(Qe.type,((e,t)=>0===t.payload.channels.length&&0===t.payload.groups.length?wt.with(void 0):vt.with({channels:t.payload.channels,groups:t.payload.groups,cursor:e.cursor}))),vt.on(Xe.type,((e,t)=>{var s,n;return mt.with({channels:e.channels,groups:e.groups,cursor:{timetoken:(null===(s=null==e?void 0:e.cursor)||void 0===s?void 0:s.timetoken)?null===(n=null==e?void 0:e.cursor)||void 0===n?void 0:n.timetoken:t.payload.timetoken,region:t.payload.region}},[Ve({category:h.PNConnectedCategory})])})),vt.on(Ze.type,((e,t)=>bt.with({channels:e.channels,groups:e.groups,cursor:e.cursor,attempts:0,reason:t.payload}))),vt.on(ct.type,(e=>pt.with({channels:e.channels,groups:e.groups,cursor:e.cursor}))),vt.on(Ye.type,((e,t)=>{var s;return vt.with({channels:t.payload.channels,groups:t.payload.groups,cursor:{timetoken:t.payload.cursor.timetoken,region:t.payload.cursor.region||(null===(s=null==e?void 0:e.cursor)||void 0===s?void 0:s.region)||0}})})),vt.on(lt.type,(e=>wt.with()));const wt=new le("UNSUBSCRIBED");wt.on(Qe.type,((e,t)=>vt.with({channels:t.payload.channels,groups:t.payload.groups}))),wt.on(Ye.type,((e,t)=>vt.with({channels:t.payload.channels,groups:t.payload.groups,cursor:t.payload.cursor})));class St{get _engine(){return this.engine}constructor(e){this.engine=new he,this.channels=[],this.groups=[],this.dependencies=e,this.dispatcher=new ht(this.engine,e),this._unsubscribeEngine=this.engine.subscribe((e=>{"invocationDispatched"===e.type&&this.dispatcher.dispatch(e.invocation)})),this.engine.start(wt,void 0)}subscribe({channels:e,channelGroups:t,timetoken:s,withPresence:n}){this.channels=[...this.channels,...null!=e?e:[]],this.groups=[...this.groups,...null!=t?t:[]],n&&(this.channels.map((e=>this.channels.push(`${e}-pnpres`))),this.groups.map((e=>this.groups.push(`${e}-pnpres`)))),s?this.engine.transition(Ye(Array.from(new Set([...this.channels,...null!=e?e:[]])),Array.from(new Set([...this.groups,...null!=t?t:[]])),s)):this.engine.transition(Qe(Array.from(new Set([...this.channels,...null!=e?e:[]])),Array.from(new Set([...this.groups,...null!=t?t:[]])))),this.dependencies.join&&this.dependencies.join({channels:Array.from(new Set(this.channels.filter((e=>!e.endsWith("-pnpres"))))),groups:Array.from(new Set(this.groups.filter((e=>!e.endsWith("-pnpres")))))})}unsubscribe({channels:e=[],channelGroups:t=[]}){const s=U(this.channels,[...e,...e.map((e=>`${e}-pnpres`))]),n=U(this.groups,[...t,...t.map((e=>`${e}-pnpres`))]);if(new Set(this.channels).size!==new Set(s).size||new Set(this.groups).size!==new Set(n).size){const r=T(this.channels,e),i=T(this.groups,t);this.dependencies.presenceState&&(null==r||r.forEach((e=>delete this.dependencies.presenceState[e])),null==i||i.forEach((e=>delete this.dependencies.presenceState[e]))),this.channels=s,this.groups=n,this.engine.transition(Qe(Array.from(new Set(this.channels.slice(0))),Array.from(new Set(this.groups.slice(0))))),this.dependencies.leave&&this.dependencies.leave({channels:r.slice(0),groups:i.slice(0)})}}unsubscribeAll(){this.channels=[],this.groups=[],this.dependencies.presenceState&&Object.keys(this.dependencies.presenceState).forEach((e=>{delete this.dependencies.presenceState[e]})),this.engine.transition(Qe(this.channels.slice(0),this.groups.slice(0))),this.dependencies.leaveAll&&this.dependencies.leaveAll()}reconnect({timetoken:e,region:t}){this.engine.transition(ut(e,t))}disconnect(){this.engine.transition(ct()),this.dependencies.leaveAll&&this.dependencies.leaveAll()}getSubscribedChannels(){return Array.from(new Set(this.channels.slice(0)))}getSubscribedChannelGroups(){return Array.from(new Set(this.groups.slice(0)))}dispose(){this.disconnect(),this._unsubscribeEngine(),this.dispatcher.dispose()}}class kt extends se{constructor(e){var t,s;super({method:e.sendByPost?H.POST:H.GET}),this.parameters=e,null!==(t=(s=this.parameters).sendByPost)&&void 0!==t||(s.sendByPost=false)}operation(){return re.PNPublishOperation}validate(){const{message:e,channel:t,keySet:{publishKey:s}}=this.parameters;return t?e?s?void 0:"Missing 'publishKey'":"Missing 'message'":"Missing 'channel'"}parse(e){return i(this,void 0,void 0,(function*(){const t=this.deserializeResponse(e);if(!t)throw new d("Service response error, check status for details",p("Unable to deserialize service response"));return{timetoken:t[2]}}))}get path(){const{message:e,channel:t,keySet:s}=this.parameters,n=this.prepareMessagePayload(e);return`/publish/${s.publishKey}/${s.subscribeKey}/0/${I(t)}/0${this.parameters.sendByPost?"":`/${I(n)}`}`}get queryParameters(){const{meta:e,replicate:t,storeInHistory:s,ttl:n}=this.parameters,r={};return void 0!==s&&(r.store=s?"1":"0"),void 0!==n&&(r.ttl=n),void 0===t||t||(r.norep="true"),e&&"object"==typeof e&&(r.meta=JSON.stringify(e)),r}get headers(){return{"Content-Type":"application/json"}}get body(){return this.prepareMessagePayload(this.parameters.message)}prepareMessagePayload(e){const{crypto:t}=this.parameters;if(!t)return JSON.stringify(e)||"";const s=t.encrypt(JSON.stringify(e));return JSON.stringify("string"==typeof s?s:u(s))}}class Et extends se{constructor(e){super(),this.parameters=e}operation(){return re.PNSignalOperation}validate(){const{message:e,channel:t,keySet:{publishKey:s}}=this.parameters;return t?e?s?void 0:"Missing 'publishKey'":"Missing 'message'":"Missing 'channel'"}parse(e){return i(this,void 0,void 0,(function*(){const t=this.deserializeResponse(e);if(!t)throw new d("Service response error, check status for details",p("Unable to deserialize service response"));return{timetoken:t[2]}}))}get path(){const{keySet:{publishKey:e,subscribeKey:t},channel:s,message:n}=this.parameters,r=JSON.stringify(n);return`/signal/${e}/${t}/0/${I(s)}/0/${I(r)}`}}class Ot extends oe{operation(){return re.PNReceiveMessagesOperation}validate(){const e=super.validate();return e||(this.parameters.timetoken?this.parameters.region?void 0:"region can not be empty":"timetoken can not be empty")}get path(){const{keySet:{subscribeKey:e},channels:t=[]}=this.parameters;return`/v2/subscribe/${e}/${R(t.sort(),",")}/0`}get queryParameters(){const{channelGroups:e,filterExpression:t,timetoken:s,region:n}=this.parameters,r={ee:""};return e&&e.length>0&&(r["channel-group"]=e.sort().join(",")),t&&t.length>0&&(r["filter-expr"]=t),"string"==typeof s?s&&s.length>0&&(r.tt=s):s&&s>0&&(r.tt=s),n&&(r.tr=n),r}}class Ct extends oe{operation(){return re.PNHandshakeOperation}get path(){const{keySet:{subscribeKey:e},channels:t=[]}=this.parameters;return`/v2/subscribe/${e}/${R(t.sort(),",")}/0`}get queryParameters(){const{channelGroups:e,filterExpression:t,state:s}=this.parameters,n={tt:0,ee:""};return e&&e.length>0&&(n["channel-group"]=e.sort().join(",")),t&&t.length>0&&(n["filter-expr"]=t),s&&Object.keys(s).length>0&&(n.state=JSON.stringify(s)),n}}class Nt extends se{constructor(e){var t,s,n,r;super(),this.parameters=e,null!==(t=(n=this.parameters).channels)&&void 0!==t||(n.channels=[]),null!==(s=(r=this.parameters).channelGroups)&&void 0!==s||(r.channelGroups=[])}operation(){return re.PNGetStateOperation}validate(){const{keySet:{subscribeKey:e},channels:t,channelGroups:s}=this.parameters;if(!e)return"Missing Subscribe Key"}parse(e){return i(this,void 0,void 0,(function*(){const t=this.deserializeResponse(e);if(!t)throw new d("Service response error, check status for details",p("Unable to deserialize service response"));if(t.status>=400)throw _.create(e);const{channels:s=[],channelGroups:n=[]}=this.parameters,r={channels:{}};return 1===s.length&&0===n.length?r.channels[s[0]]=t.payload:r.channels=t.payload,r}))}get path(){const{keySet:{subscribeKey:e},uuid:t,channels:s}=this.parameters;return`/v2/presence/sub-key/${e}/channel/${R(null!=s?s:[],",")}/uuid/${t}`}get queryParameters(){const{channelGroups:e}=this.parameters;return e&&0!==e.length?{"channel-group":e.join(",")}:{}}}class Pt extends se{constructor(e){super(),this.parameters=e}operation(){return re.PNSetStateOperation}validate(){const{keySet:{subscribeKey:e},state:t,channels:s=[],channelGroups:n=[]}=this.parameters;return e?t?0===(null==s?void 0:s.length)&&0===(null==n?void 0:n.length)?"Please provide a list of channels and/or channel-groups":void 0:"Missing State":"Missing Subscribe Key"}parse(e){return i(this,void 0,void 0,(function*(){const t=this.deserializeResponse(e);if(!t)throw new d("Service response error, check status for details",p("Unable to deserialize service response"));if(t.status>=400)throw _.create(e);return{state:t.payload}}))}get path(){const{keySet:{subscribeKey:e},uuid:t,channels:s}=this.parameters;return`/v2/presence/sub-key/${e}/channel/${R(null!=s?s:[],",")}/uuid/${I(t)}/data`}get queryParameters(){const{channelGroups:e,state:t}=this.parameters,s={state:JSON.stringify(t)};return e&&0!==e.length&&(s["channel-group"]=e.join(",")),s}}class Mt extends se{constructor(e){super(),this.parameters=e}operation(){return re.PNHeartbeatOperation}validate(){const{keySet:{subscribeKey:e},channels:t=[],channelGroups:s=[]}=this.parameters;return e?0===t.length&&0===s.length?"Please provide a list of channels and/or channel-groups":void 0:"Missing Subscribe Key"}parse(e){return i(this,void 0,void 0,(function*(){const t=this.deserializeResponse(e);if(!t)throw new d("Service response error, check status for details",p("Unable to deserialize service response"));if(t.status>=400)throw _.create(e);return{}}))}get path(){const{keySet:{subscribeKey:e},channels:t}=this.parameters;return`/v2/presence/sub-key/${e}/channel/${R(null!=t?t:[],",")}/heartbeat`}get queryParameters(){const{channelGroups:e,state:t,heartbeat:s}=this.parameters,n={heartbeat:`${s}`};return e&&0!==e.length&&(n["channel-group"]=e.join(",")),t&&(n.state=JSON.stringify(t)),n}}class jt extends se{constructor(e){super(),this.parameters=e,this.parameters.channelGroups&&(this.parameters.channelGroups=Array.from(new Set(this.parameters.channelGroups))),this.parameters.channels&&(this.parameters.channels=Array.from(new Set(this.parameters.channels)))}operation(){return re.PNUnsubscribeOperation}validate(){const{keySet:{subscribeKey:e},channels:t=[],channelGroups:s=[]}=this.parameters;return e?0===t.length&&0===s.length?"At least one `channel` or `channel group` should be provided.":void 0:"Missing Subscribe Key"}parse(e){return i(this,void 0,void 0,(function*(){const t=this.deserializeResponse(e);if(!t)throw new d("Service response error, check status for details",p("Unable to deserialize service response"));if(t.status>=400)throw _.create(e);return{}}))}get path(){var e;const{keySet:{subscribeKey:t},channels:s}=this.parameters;return`/v2/presence/sub-key/${t}/channel/${R(null!==(e=null==s?void 0:s.sort())&&void 0!==e?e:[],",")}/leave`}get queryParameters(){const{channelGroups:e}=this.parameters;return e&&0!==e.length?{"channel-group":e.sort().join(",")}:{}}}class _t extends se{constructor(e){super(),this.parameters=e}operation(){return re.PNWhereNowOperation}validate(){if(!this.parameters.keySet.subscribeKey)return"Missing Subscribe Key"}parse(e){return i(this,void 0,void 0,(function*(){const t=this.deserializeResponse(e);if(!t)throw new d("Service response error, check status for details",p("Unable to deserialize service response"));if(t.status>=400)throw _.create(e);return t.payload?{channels:t.payload.channels}:{channels:[]}}))}get path(){const{keySet:{subscribeKey:e},uuid:t}=this.parameters;return`/v2/presence/sub-key/${e}/uuid/${I(t)}`}}class At extends se{constructor(e){var t,s,n,r,i,o;super(),this.parameters=e,null!==(t=(r=this.parameters).queryParameters)&&void 0!==t||(r.queryParameters={}),null!==(s=(i=this.parameters).includeUUIDs)&&void 0!==s||(i.includeUUIDs=true),null!==(n=(o=this.parameters).includeState)&&void 0!==n||(o.includeState=false)}operation(){const{channels:e=[],channelGroups:t=[]}=this.parameters;return 0===e.length&&0===t.length?re.PNGlobalHereNowOperation:re.PNHereNowOperation}validate(){if(!this.parameters.keySet.subscribeKey)return"Missing Subscribe Key"}parse(e){return i(this,void 0,void 0,(function*(){var t,s;const n=this.deserializeResponse(e);if(!n)throw new d("Service response error, check status for details",p("Unable to deserialize service response"));if(n.status>=400)throw _.create(e);const r="occupancy"in n?1:n.payload.total_channels,i="occupancy"in n?n.occupancy:n.payload.total_channels,o={};let a={};if("occupancy"in n){const e=this.parameters.channels[0];a[e]={uuids:null!==(t=n.uuids)&&void 0!==t?t:[],occupancy:i}}else a=null!==(s=n.payload.channels)&&void 0!==s?s:{};return Object.keys(a).forEach((e=>{const t=a[e];o[e]={occupants:this.parameters.includeUUIDs?t.uuids.map((e=>"string"==typeof e?{uuid:e,state:null}:e)):[],name:e,occupancy:t.occupancy}})),{totalChannels:r,totalOccupancy:i,channels:o}}))}get path(){const{keySet:{subscribeKey:e},channels:t,channelGroups:s}=this.parameters;let n=`/v2/presence/sub-key/${e}`;return(t&&t.length>0||s&&s.length>0)&&(n+=`/channel/${R(null!=t?t:[],",")}`),n}get queryParameters(){const{channelGroups:e,includeUUIDs:t,includeState:s,queryParameters:n}=this.parameters;return Object.assign(Object.assign(Object.assign(Object.assign({},t?{}:{disable_uuids:"1"}),null!=s&&s?{state:"1"}:{}),e&&e.length>0?{"channel-group":e.join(",")}:{}),n)}}class It extends se{constructor(e){super({method:H.DELETE}),this.parameters=e}operation(){return re.PNDeleteMessagesOperation}validate(){return this.parameters.keySet.subscribeKey?this.parameters.channel?void 0:"Missing channel":"Missing Subscribe Key"}parse(e){return i(this,void 0,void 0,(function*(){const t=this.deserializeResponse(e);if(!t)throw new d("Service response error, check status for details",p("Unable to deserialize service response"));if(t.status>=400)throw _.create(e);return{}}))}get path(){const{keySet:{subscribeKey:e},channel:t}=this.parameters;return`/v3/history/sub-key/${e}/channel/${I(t)}`}get queryParameters(){const{start:e,end:t}=this.parameters;return Object.assign(Object.assign({},e?{start:e}:{}),t?{end:t}:{})}}class Rt extends se{constructor(e){super(),this.parameters=e}operation(){return re.PNMessageCounts}validate(){const{keySet:{subscribeKey:e},channels:t,timetoken:s,channelTimetokens:n}=this.parameters;return e?t?s&&n?"`timetoken` and `channelTimetokens` are incompatible together":s||n?n&&n.length>1&&n.length!==t.length?"Length of `channelTimetokens` and `channels` do not match":void 0:"`timetoken` or `channelTimetokens` need to be set":"Missing channels":"Missing Subscribe Key"}parse(e){return i(this,void 0,void 0,(function*(){const t=this.deserializeResponse(e);if(!t)throw new d("Service response error, check status for details",p("Unable to deserialize service response"));if(t.status>=400)throw _.create(e);return{channels:t.channels}}))}get path(){return`/v3/history/sub-key/${this.parameters.keySet.subscribeKey}/message-counts/${R(this.parameters.channels)}`}get queryParameters(){let{channelTimetokens:e}=this.parameters;return this.parameters.timetoken&&(e=[this.parameters.timetoken]),Object.assign(Object.assign({},1===e.length?{timetoken:e[0]}:{}),e.length>1?{channelsTimetoken:e.join(",")}:{})}}class Ut extends se{constructor(e){var t,s,n;super(),this.parameters=e,e.count?e.count=Math.min(e.count,100):e.count=100,null!==(t=e.stringifiedTimeToken)&&void 0!==t||(e.stringifiedTimeToken=false),null!==(s=e.includeMeta)&&void 0!==s||(e.includeMeta=false),null!==(n=e.logVerbosity)&&void 0!==n||(e.logVerbosity=false)}operation(){return re.PNHistoryOperation}validate(){return this.parameters.keySet.subscribeKey?this.parameters.channel?void 0:"Missing channel":"Missing Subscribe Key"}parse(e){return i(this,void 0,void 0,(function*(){const t=this.deserializeResponse(e);if(!t)throw new d("Service response error, check status for details",p("Unable to deserialize service response"));const s=t[0],n=t[1],r=t[2];return Array.isArray(s)?{messages:s.map((e=>{const t=this.processPayload(e.message),s={entry:t.payload,timetoken:e.timetoken};return t.error&&(s.error=t.error),e.meta&&(s.meta=e.meta),s})),startTimeToken:n,endTimeToken:r}:{messages:[],startTimeToken:n,endTimeToken:r}}))}get path(){const{keySet:{subscribeKey:e},channel:t}=this.parameters;return`/v2/history/sub-key/${e}/channel/${I(t)}`}get queryParameters(){const{start:e,end:t,reverse:s,count:n,stringifiedTimeToken:r,includeMeta:i}=this.parameters;return Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({count:n,include_token:"true"},e?{start:e}:{}),t?{end:t}:{}),r?{string_message_token:"true"}:{}),null!=s?{reverse:s.toString()}:{}),i?{include_meta:"true"}:{})}processPayload(e){const{crypto:t,logVerbosity:s}=this.parameters;if(!t||"string"!=typeof e)return{payload:e};let n,r;try{const s=t.decrypt(e);n=s instanceof ArrayBuffer?JSON.parse(Ut.decoder.decode(s)):s}catch(t){s&&console.log("decryption error",t.message),n=e,r=`Error while decrypting message content: ${t.message}`}return{payload:n,error:r}}}var Tt;!function(e){e[e.Message=-1]="Message",e[e.Files=4]="Files"}(Tt||(Tt={}));class Ft extends se{constructor(e){var t,s,n,r,i;super(),this.parameters=e;const o=null!==(t=e.includeMessageActions)&&void 0!==t&&t,a=e.channels.length>1||o?25:100;e.count?e.count=Math.min(e.count,a):e.count=a,e.includeUuid?e.includeUUID=e.includeUuid:null!==(s=e.includeUUID)&&void 0!==s||(e.includeUUID=true),null!==(n=e.stringifiedTimeToken)&&void 0!==n||(e.stringifiedTimeToken=false),null!==(r=e.includeMessageType)&&void 0!==r||(e.includeMessageType=true),null!==(i=e.logVerbosity)&&void 0!==i||(e.logVerbosity=false)}operation(){return re.PNFetchMessagesOperation}validate(){const{keySet:{subscribeKey:e},channels:t,includeMessageActions:s}=this.parameters;return e?t?void 0!==s&&s&&t.length>1?"History can return actions data for a single channel only. Either pass a single channel or disable the includeMessageActions flag.":void 0:"Missing channels":"Missing Subscribe Key"}parse(e){return i(this,void 0,void 0,(function*(){var t;const s=this.deserializeResponse(e);if(!s)throw new d("Service response error, check status for details",p("Unable to deserialize service response"));if(s.status>=400)throw _.create(e);const n=null!==(t=s.channels)&&void 0!==t?t:{},r={};return Object.keys(n).forEach((e=>{r[e]=n[e].map((t=>{null===t.message_type&&(t.message_type=Tt.Message);const s=this.processPayload(e,t),n={channel:e,timetoken:t.timetoken,message:s.payload,messageType:t.message_type,uuid:t.uuid};if(t.actions){const e=n;e.actions=t.actions,e.data=t.actions}return t.meta&&(n.meta=t.meta),s.error&&(n.error=s.error),n}))})),s.more?{channels:r,more:s.more}:{channels:r}}))}get path(){const{keySet:{subscribeKey:e},channels:t,includeMessageActions:s}=this.parameters;return`/v3/${s?"history-with-actions":"history"}/sub-key/${e}/channel/${R(t)}`}get queryParameters(){const{start:e,end:t,count:s,includeMessageType:n,includeMeta:r,includeUUID:i,stringifiedTimeToken:o}=this.parameters;return Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({max:s},e?{start:e}:{}),t?{end:t}:{}),o?{string_message_token:"true"}:{}),void 0!==r&&r?{include_meta:"true"}:{}),i?{include_uuid:"true"}:{}),n?{include_message_type:"true"}:{})}processPayload(e,t){const{crypto:s,logVerbosity:n}=this.parameters;if(!s||"string"!=typeof t.message)return{payload:t.message};let r,i;try{const e=s.decrypt(t.message);r=e instanceof ArrayBuffer?JSON.parse(Ft.decoder.decode(e)):e}catch(e){n&&console.log("decryption error",e.message),r=t.message,i=`Error while decrypting message content: ${e.message}`}if(!i&&r&&t.message_type==Tt.Files&&"object"==typeof r&&this.isFileMessage(r)){const t=r;return{payload:{message:t.message,file:Object.assign(Object.assign({},t.file),{url:this.parameters.getFileUrl({channel:e,id:t.file.id,name:t.file.name})})},error:i}}return{payload:r,error:i}}isFileMessage(e){return void 0!==e.file}}class xt extends se{constructor(e){super(),this.parameters=e}operation(){return re.PNGetMessageActionsOperation}validate(){return this.parameters.keySet.subscribeKey?this.parameters.channel?void 0:"Missing message channel":"Missing Subscribe Key"}parse(e){return i(this,void 0,void 0,(function*(){const t=this.deserializeResponse(e);if(!t)throw new d("Service response error, check status for details",p("Unable to deserialize service response"));if(t.status>=400)throw _.create(e);let s=null,n=null;return t.data.length>0&&(s=t.data[0].actionTimetoken,n=t.data[t.data.length-1].actionTimetoken),{data:t.data,more:t.more,start:s,end:n}}))}get path(){const{keySet:{subscribeKey:e},channel:t}=this.parameters;return`/v1/message-actions/${e}/channel/${I(t)}`}get queryParameters(){const{limit:e,start:t,end:s}=this.parameters;return Object.assign(Object.assign(Object.assign({},t?{start:t}:{}),s?{end:s}:{}),e?{limit:e}:{})}}class Dt extends se{constructor(e){super({method:H.POST}),this.parameters=e}operation(){return re.PNAddMessageActionOperation}validate(){const{keySet:{subscribeKey:e},action:t,channel:s,messageTimetoken:n}=this.parameters;return e?s?n?t?t.value?t.type?t.type.length>15?"Action.type value exceed maximum length of 15":void 0:"Missing Action.type":"Missing Action.value":"Missing Action":"Missing message timetoken":"Missing message channel":"Missing Subscribe Key"}parse(e){return i(this,void 0,void 0,(function*(){const t=this.deserializeResponse(e);if(!t)throw new d("Service response error, check status for details",p("Unable to deserialize service response"));if(t.status>=400)throw _.create(e);return{data:t.data}}))}get headers(){return{"Content-Type":"application/json"}}get path(){const{keySet:{subscribeKey:e},channel:t,messageTimetoken:s}=this.parameters;return`/v1/message-actions/${e}/channel/${I(t)}/message/${s}`}get body(){return JSON.stringify(this.parameters.action)}}class Kt extends se{constructor(e){super({method:H.DELETE}),this.parameters=e}operation(){return re.PNRemoveMessageActionOperation}validate(){const{keySet:{subscribeKey:e},channel:t,messageTimetoken:s,actionTimetoken:n}=this.parameters;return e?t?s?n?void 0:"Missing action timetoken":"Missing message timetoken":"Missing message action channel":"Missing Subscribe Key"}parse(e){return i(this,void 0,void 0,(function*(){const t=this.deserializeResponse(e);if(!t)throw new d("Service response error, check status for details",p("Unable to deserialize service response"));if(t.status>=400)throw _.create(e);return{data:t.data}}))}get path(){const{keySet:{subscribeKey:e},channel:t,actionTimetoken:s,messageTimetoken:n}=this.parameters;return`/v1/message-actions/${e}/channel/${I(t)}/message/${n}/action/${s}`}}class qt extends se{constructor(e){var t,s;super(),this.parameters=e,null!==(t=(s=this.parameters).storeInHistory)&&void 0!==t||(s.storeInHistory=true)}operation(){return re.PNPublishFileMessageOperation}validate(){const{channel:e,fileId:t,fileName:s}=this.parameters;return e?t?s?void 0:"file name can't be empty":"file id can't be empty":"channel can't be empty"}parse(e){return i(this,void 0,void 0,(function*(){const t=this.deserializeResponse(e);if(!t)throw new d("Service response error, check status for details",p("Unable to deserialize service response"));return{timetoken:t[2]}}))}get path(){const{message:e,channel:t,keySet:{publishKey:s,subscribeKey:n},fileId:r,fileName:i}=this.parameters,o=Object.assign({file:{name:i,id:r}},e?{message:e}:{});return`/v1/files/publish-file/${s}/${n}/0/${I(t)}/0/${I(this.prepareMessagePayload(o))}`}get queryParameters(){const{storeInHistory:e,ttl:t,meta:s}=this.parameters;return Object.assign(Object.assign({store:e?"1":"0"},t?{ttl:t}:{}),s&&"object"==typeof s?{meta:JSON.stringify(s)}:{})}prepareMessagePayload(e){const{crypto:t}=this.parameters;if(!t)return JSON.stringify(e)||"";const s=t.encrypt(JSON.stringify(e));return JSON.stringify("string"==typeof s?s:u(s))}}class Gt extends se{constructor(e){super({method:H.LOCAL}),this.parameters=e}operation(){return re.PNGetFileUrlOperation}validate(){const{channel:e,id:t,name:s}=this.parameters;return e?t?s?void 0:"file name can't be empty":"file id can't be empty":"channel can't be empty"}parse(e){return i(this,void 0,void 0,(function*(){return e.url}))}get path(){const{channel:e,id:t,name:s,keySet:{subscribeKey:n}}=this.parameters;return`/v1/files/${n}/channels/${I(e)}/files/${t}/${s}`}}class $t extends se{constructor(e){super({method:H.DELETE}),this.parameters=e}operation(){return re.PNDeleteFileOperation}validate(){const{channel:e,id:t,name:s}=this.parameters;return e?t?s?void 0:"file name can't be empty":"file id can't be empty":"channel can't be empty"}parse(e){return i(this,void 0,void 0,(function*(){const t=this.deserializeResponse(e);if(!t)throw new d("Service response error, check status for details",p("Unable to deserialize service response"));if(t.status>=400)throw _.create(e);return t}))}get path(){const{keySet:{subscribeKey:e},id:t,channel:s,name:n}=this.parameters;return`/v1/files/${e}/channels/${I(s)}/files/${t}/${n}`}}class Lt extends se{constructor(e){var t,s;super(),this.parameters=e,null!==(t=(s=this.parameters).limit)&&void 0!==t||(s.limit=100)}operation(){return re.PNListFilesOperation}validate(){if(!this.parameters.channel)return"channel can't be empty"}parse(e){return i(this,void 0,void 0,(function*(){const t=this.deserializeResponse(e);if(!t)throw new d("Service response error, check status for details",p("Unable to deserialize service response"));if(t.status>=400)throw _.create(e);return t}))}get path(){const{keySet:{subscribeKey:e},channel:t}=this.parameters;return`/v1/files/${e}/channels/${I(t)}/files`}get queryParameters(){const{limit:e,next:t}=this.parameters;return Object.assign({limit:e},t?{next:t}:{})}}class Bt extends se{constructor(e){super({method:H.POST}),this.parameters=e}operation(){return re.PNGenerateUploadUrlOperation}validate(){return this.parameters.channel?this.parameters.name?void 0:"'name' can't be empty":"channel can't be empty"}parse(e){return i(this,void 0,void 0,(function*(){const t=this.deserializeResponse(e);if(!t)throw new d("Service response error, check status for details",p("Unable to deserialize service response"));if(t.status>=400)throw _.create(e);return{id:t.data.id,name:t.data.name,url:t.file_upload_request.url,formFields:t.file_upload_request.form_fields}}))}get path(){const{keySet:{subscribeKey:e},channel:t}=this.parameters;return`/v1/files/${e}/channels/${I(t)}/generate-upload-url`}get body(){return JSON.stringify({name:this.parameters.name})}}class Ht extends se{constructor(e){super({method:H.POST}),this.parameters=e;const t=e.file.mimeType;t&&(e.formFields=e.formFields.map((e=>"Content-Type"===e.name?{name:e.name,value:t}:e)))}operation(){return re.PNPublishFileOperation}validate(){const{fileId:e,fileName:t,file:s,uploadUrl:n}=this.parameters;return e?t?s?n?void 0:"Validation failed: file upload 'url' can't be empty":"Validation failed: 'file' can't be empty":"Validation failed: file 'name' can't be empty":"Validation failed: file 'id' can't be empty"}parse(e){return i(this,void 0,void 0,(function*(){return{status:e.status,message:e.body?Ht.decoder.decode(e.body):"OK"}}))}request(){return Object.assign(Object.assign({},super.request()),{origin:new URL(this.parameters.uploadUrl).origin,timeout:300})}get path(){const{pathname:e,search:t}=new URL(this.parameters.uploadUrl);return`${e}${t}`}get body(){return this.parameters.file}get formData(){return this.parameters.formFields}}class zt{constructor(e){var t;if(this.parameters=e,this.file=null===(t=this.parameters.PubNubFile)||void 0===t?void 0:t.create(e.file),!this.file)throw new Error("File upload error: unable to create File object.")}process(){return i(this,void 0,void 0,(function*(){let e,t;return this.generateFileUploadUrl().then((s=>(e=s.name,t=s.id,this.uploadFile(s)))).then((e=>{if(204!==e.status)throw new d("Upload to bucket was unsuccessful",{error:!0,statusCode:e.status,category:h.PNUnknownCategory,operation:re.PNPublishFileOperation,errorData:{message:e.message}})})).then((()=>this.publishFileMessage(t,e))).catch((e=>{if(e instanceof d)throw e;const t=e instanceof _?e:_.create(e);throw new d("File upload error.",t.toStatus(re.PNPublishFileOperation))}))}))}generateFileUploadUrl(){return i(this,void 0,void 0,(function*(){const e=new Bt(Object.assign(Object.assign({},this.parameters),{name:this.file.name,keySet:this.parameters.keySet}));return this.parameters.sendRequest(e)}))}uploadFile(e){return i(this,void 0,void 0,(function*(){const{cipherKey:t,PubNubFile:s,crypto:n,cryptography:r}=this.parameters,{id:i,name:o,url:a,formFields:c}=e;return this.parameters.PubNubFile.supportsEncryptFile&&(!t&&n?this.file=yield n.encryptFile(this.file,s):t&&r&&(this.file=yield r.encryptFile(t,this.file,s))),this.parameters.sendRequest(new Ht({fileId:i,fileName:o,file:this.file,uploadUrl:a,formFields:c}))}))}publishFileMessage(e,t){return i(this,void 0,void 0,(function*(){var s,n,r,i;let o,a={timetoken:"0"},c=this.parameters.fileUploadPublishRetryLimit,u=!1;do{try{a=yield this.parameters.publishFile(Object.assign(Object.assign({},this.parameters),{fileId:e,fileName:t})),u=!0}catch(e){e instanceof d&&(o=e),c-=1}}while(!u&&c>0);if(u)return{status:200,timetoken:a.timetoken,id:e,name:t};throw new d("Publish failed. You may want to execute that operation manually using pubnub.publishFile",{error:!0,category:null!==(n=null===(s=o.status)||void 0===s?void 0:s.category)&&void 0!==n?n:h.PNUnknownCategory,statusCode:null!==(i=null===(r=o.status)||void 0===r?void 0:r.statusCode)&&void 0!==i?i:0,channel:this.parameters.channel,id:e,name:t})}))}}class Vt extends se{constructor(e){super({method:H.DELETE}),this.parameters=e}operation(){return re.PNAccessManagerRevokeToken}validate(){return this.parameters.keySet.secretKey?this.parameters.token?void 0:"token can't be empty":"Missing Secret Key"}parse(e){return i(this,void 0,void 0,(function*(){const t=this.deserializeResponse(e);if(!t)throw new d("Service response error, check status for details",p("Unable to deserialize service response"));if(t.status>=400)throw _.create(e);return{}}))}get path(){const{keySet:{subscribeKey:e},token:t}=this.parameters;return`/v3/pam/${e}/grant/${I(t)}`}}class Wt extends se{constructor(e){var t,s,n,r;super({method:H.POST}),this.parameters=e,null!==(t=(n=this.parameters).resources)&&void 0!==t||(n.resources={}),null!==(s=(r=this.parameters).patterns)&&void 0!==s||(r.patterns={})}operation(){return re.PNAccessManagerGrantToken}validate(){var e,t,s,n,r,i;const{keySet:{subscribeKey:o,publishKey:a,secretKey:c},resources:u,patterns:l}=this.parameters;if(!o)return"Missing Subscribe Key";if(!a)return"Missing Publish Key";if(!c)return"Missing Secret Key";if(!u&&!l)return"Missing either Resources or Patterns";if(this.isVspPermissions(this.parameters)&&("channels"in(null!==(e=this.parameters.resources)&&void 0!==e?e:{})||"uuids"in(null!==(t=this.parameters.resources)&&void 0!==t?t:{})||"groups"in(null!==(s=this.parameters.resources)&&void 0!==s?s:{})||"channels"in(null!==(n=this.parameters.patterns)&&void 0!==n?n:{})||"uuids"in(null!==(r=this.parameters.patterns)&&void 0!==r?r:{})||"groups"in(null!==(i=this.parameters.patterns)&&void 0!==i?i:{})))return"Cannot mix `users`, `spaces` and `authorizedUserId` with `uuids`, `channels`, `groups` and `authorized_uuid`";let h=!0;return[this.parameters.resources,this.parameters.patterns].forEach((e=>{Object.keys(null!=e?e:{}).forEach((t=>{var s;e&&h&&Object.keys(null!==(s=e[t])&&void 0!==s?s:{}).length>0&&(h=!1)}))})),h?"Missing values for either Resources or Patterns":void 0}parse(e){return i(this,void 0,void 0,(function*(){const t=this.deserializeResponse(e);if(!t)throw new d("Service response error, check status for details",p("Unable to deserialize service response"));if(t.status>=400)throw _.create(e);return t.data.token}))}get path(){return`/v3/pam/${this.parameters.keySet.subscribeKey}/grant`}get body(){const{ttl:e,meta:t}=this.parameters,s=Object.assign({},e||0===e?{ttl:e}:{}),n=this.isVspPermissions(this.parameters)?this.parameters.authorizedUserId:this.parameters.authorized_uuid,r={},i={},o={},a=(e,t,s,n)=>{n[s]||(n[s]={}),n[s][e]=t},{resources:c,patterns:u}=this.parameters;return[c,u].forEach(((e,t)=>{var s,n,r,c,u;const l=0===t?i:o;let h={},d={},p={};l.channels||(l.channels={}),l.groups||(l.groups={}),l.uuids||(l.uuids={}),l.users||(l.users={}),l.spaces||(l.spaces={}),e&&("spaces"in e||"users"in e?(h=null!==(s=e.spaces)&&void 0!==s?s:{},p=null!==(n=e.users)&&void 0!==n?n:{}):("channels"in e||"uuids"in e||"groups"in e)&&(h=null!==(r=e.channels)&&void 0!==r?r:{},d=null!==(c=e.groups)&&void 0!==c?c:{},p=null!==(u=e.uuids)&&void 0!==u?u:{})),Object.keys(h).forEach((e=>a(e,this.extractPermissions(h[e]),"channels",l))),Object.keys(d).forEach((e=>a(e,this.extractPermissions(d[e]),"groups",l))),Object.keys(p).forEach((e=>a(e,this.extractPermissions(p[e]),"uuids",l)))})),n&&(r.uuid=`${n}`),r.resources=i,r.patterns=o,r.meta=null!=t?t:{},s.permissions=r,JSON.stringify(s)}extractPermissions(e){let t=0;return"join"in e&&e.join&&(t|=128),"update"in e&&e.update&&(t|=64),"get"in e&&e.get&&(t|=32),"delete"in e&&e.delete&&(t|=8),"manage"in e&&e.manage&&(t|=4),"write"in e&&e.write&&(t|=2),"read"in e&&e.read&&(t|=1),t}isVspPermissions(e){var t,s,n,r;return"authorizedUserId"in e||"spaces"in(null!==(t=e.resources)&&void 0!==t?t:{})||"users"in(null!==(s=e.resources)&&void 0!==s?s:{})||"spaces"in(null!==(n=e.patterns)&&void 0!==n?n:{})||"users"in(null!==(r=e.patterns)&&void 0!==r?r:{})}}class Jt extends se{constructor(e){var t,s,n,r,i,o,a,c,u,l,h,d,p,g,y,f,m,b,v,w;super(),this.parameters=e,null!==(t=(h=this.parameters).channels)&&void 0!==t||(h.channels=[]),null!==(s=(d=this.parameters).channelGroups)&&void 0!==s||(d.channelGroups=[]),null!==(n=(p=this.parameters).uuids)&&void 0!==n||(p.uuids=[]),null!==(r=(g=this.parameters).read)&&void 0!==r||(g.read=false),null!==(i=(y=this.parameters).write)&&void 0!==i||(y.write=false),null!==(o=(f=this.parameters).delete)&&void 0!==o||(f.delete=false),null!==(a=(m=this.parameters).get)&&void 0!==a||(m.get=false),null!==(c=(b=this.parameters).update)&&void 0!==c||(b.update=false),null!==(u=(v=this.parameters).manage)&&void 0!==u||(v.manage=false),null!==(l=(w=this.parameters).join)&&void 0!==l||(w.join=false)}operation(){return re.PNAccessManagerGrant}validate(){const{keySet:{subscribeKey:e,publishKey:t,secretKey:s},uuids:n=[],channels:r=[],channelGroups:i=[],authKeys:o=[]}=this.parameters;return e?t?s?0!==n.length&&0===o.length?"authKeys are required for grant request on uuids":!n.length||0===r.length&&0===i.length?void 0:"Both channel/channel group and uuid cannot be used in the same request":"Missing Secret Key":"Missing Publish Key":"Missing Subscribe Key"}parse(e){return i(this,void 0,void 0,(function*(){const t=this.deserializeResponse(e);if(!t)throw new d("Service response error, check status for details",p("Unable to deserialize service response"));if(t.status>=400)throw _.create(e);return t.payload}))}get path(){return`/v2/auth/grant/sub-key/${this.parameters.keySet.subscribeKey}`}get queryParameters(){const{channels:e,channelGroups:t,authKeys:s,uuids:n,read:r,write:i,manage:o,delete:a,get:c,join:u,update:l,ttl:h}=this.parameters;return Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},e&&(null==e?void 0:e.length)>0?{channel:e.join(",")}:{}),t&&(null==t?void 0:t.length)>0?{"channel-group":t.join(",")}:{}),s&&(null==s?void 0:s.length)>0?{auth:s.join(",")}:{}),n&&(null==n?void 0:n.length)>0?{"target-uuid":n.join(",")}:{}),{r:r?"1":"0",w:i?"1":"0",m:o?"1":"0",d:a?"1":"0",g:c?"1":"0",j:u?"1":"0",u:l?"1":"0"}),h||0===h?{ttl:h}:{})}}const Qt=[];class Yt extends se{constructor(e){var t,s;super(),this.parameters=e,null!==(t=(s=this.parameters).authKeys)&&void 0!==t||(s.authKeys=Qt)}operation(){return re.PNAccessManagerAudit}validate(){if(!this.parameters.keySet.subscribeKey)return"Missing Subscribe Key"}parse(e){return i(this,void 0,void 0,(function*(){const t=this.deserializeResponse(e);if(!t)throw new d("Service response error, check status for details",p("Unable to deserialize service response"));if(t.status>=400)throw _.create(e);return t.payload}))}get path(){return`/v2/auth/audit/sub-key/${this.parameters.keySet.subscribeKey}`}get queryParameters(){const{channel:e,channelGroup:t,authKeys:s}=this.parameters;return Object.assign(Object.assign(Object.assign({},e?{channel:e}:{}),t?{"channel-group":t}:{}),s&&s.length?{auth:s.join(",")}:{})}}class Xt{subscribe(){var e,t;this.pubnub.subscribe(Object.assign({channels:this.channelNames,channelGroups:this.groupNames},(null===(t=null===(e=this.options)||void 0===e?void 0:e.cursor)||void 0===t?void 0:t.timetoken)&&{timetoken:this.options.cursor.timetoken}))}unsubscribe(){this.pubnub.unsubscribe({channels:this.channelNames.filter((e=>!e.endsWith("-pnpres"))),channelGroups:this.groupNames.filter((e=>!e.endsWith("-pnpres")))})}set onMessage(e){this.listener.message=e}set onPresence(e){this.listener.presence=e}set onSignal(e){this.listener.signal=e}set onObjects(e){this.listener.objects=e}set onMessageAction(e){this.listener.messageAction=e}set onFile(e){this.listener.file=e}addListener(e){this.eventEmitter.addListener(e,this.channelNames.filter((e=>!e.endsWith("-pnpres"))),this.groupNames.filter((e=>!e.endsWith("-pnpres"))))}removeListener(e){this.eventEmitter.removeListener(e,this.channelNames,this.groupNames)}get channels(){return this.channelNames.slice(0)}get channelGroups(){return this.groupNames.slice(0)}}class Zt extends Xt{constructor({channels:e=[],channelGroups:t=[],subscriptionOptions:s,eventEmitter:n,pubnub:r}){super(),this.channelNames=[],this.groupNames=[],this.subscriptionList=[],this.options=s,this.eventEmitter=n,this.pubnub=r,e.filter((e=>!e.endsWith("-pnpres"))).forEach((e=>{const t=this.pubnub.channel(e).subscription(this.options);this.channelNames=[...this.channelNames,...t.channels],this.subscriptionList.push(t)})),t.filter((e=>!e.endsWith("-pnpres"))).forEach((e=>{const t=this.pubnub.channelGroup(e).subscription(this.options);this.groupNames=[...this.groupNames,...t.channelGroups],this.subscriptionList.push(t)})),this.listener={},n.addListener(this.listener,this.channelNames.filter((e=>!e.endsWith("-pnpres"))),this.groupNames.filter((e=>!e.endsWith("-pnpres"))))}addSubscription(e){this.subscriptionList.push(e),this.channelNames=[...this.channelNames,...e.channels],this.groupNames=[...this.groupNames,...e.channelGroups],this.eventEmitter.addListener(this.listener,e.channels,e.channelGroups)}removeSubscription(e){const t=e.channels,s=e.channelGroups;this.channelNames=this.channelNames.filter((e=>!t.includes(e))),this.groupNames=this.groupNames.filter((e=>!s.includes(e))),this.subscriptionList=this.subscriptionList.filter((t=>t!==e)),this.eventEmitter.removeListener(this.listener,t,s)}addSubscriptionSet(e){this.subscriptionList=[...this.subscriptionList,...e.subscriptions],this.channelNames=[...this.channelNames,...e.channels],this.groupNames=[...this.groupNames,...e.channelGroups],this.eventEmitter.addListener(this.listener,e.channels,e.channelGroups)}removeSubscriptionSet(e){const t=e.channels,s=e.channelGroups;this.channelNames=this.channelNames.filter((e=>!t.includes(e))),this.groupNames=this.groupNames.filter((e=>!s.includes(e))),this.subscriptionList=this.subscriptionList.filter((t=>!e.subscriptions.includes(t))),this.eventEmitter.removeListener(this.listener,t,s)}get subscriptions(){return this.subscriptionList.slice(0)}}class es extends Xt{constructor({channels:e,channelGroups:t,subscriptionOptions:s,eventEmitter:n,pubnub:r}){super(),this.channelNames=[],this.groupNames=[],this.channelNames=e,this.groupNames=t,this.options=s,this.pubnub=r,this.eventEmitter=n,this.listener={},n.addListener(this.listener,this.channelNames.filter((e=>!e.endsWith("-pnpres"))),this.groupNames.filter((e=>!e.endsWith("-pnpres"))))}addSubscription(e){return new Zt({channels:[...this.channelNames,...e.channels],channelGroups:[...this.groupNames,...e.channelGroups],subscriptionOptions:Object.assign(Object.assign({},this.options),null==e?void 0:e.options),eventEmitter:this.eventEmitter,pubnub:this.pubnub})}}class ts{constructor(e,t,s){this.id=e,this.eventEmitter=t,this.pubnub=s}subscription(e){return new es({channels:[this.id],channelGroups:[],subscriptionOptions:e,eventEmitter:this.eventEmitter,pubnub:this.pubnub})}}class ss{constructor(e,t,s){this.eventEmitter=t,this.pubnub=s,this.name=e}subscription(e){return new es({channels:[],channelGroups:(null==e?void 0:e.receivePresenceEvents)?[this.name,`${this.name}-pnpres`]:[this.name],subscriptionOptions:e,eventEmitter:this.eventEmitter,pubnub:this.pubnub})}}class ns{constructor(e,t,s){this.id=e,this.eventEmitter=t,this.pubnub=s}subscription(e){return new es({channels:[this.id],channelGroups:[],subscriptionOptions:e,eventEmitter:this.eventEmitter,pubnub:this.pubnub})}}class rs{constructor(e,t,s){this.eventEmitter=t,this.pubnub=s,this.name=e}subscription(e){return new es({channels:(null==e?void 0:e.receivePresenceEvents)?[this.name,`${this.name}-pnpres`]:[this.name],channelGroups:[],subscriptionOptions:e,eventEmitter:this.eventEmitter,pubnub:this.pubnub})}}class is extends se{constructor(e){super(),this.parameters=e}operation(){return re.PNRemoveChannelsFromGroupOperation}validate(){const{keySet:{subscribeKey:e},channels:t,channelGroup:s}=this.parameters;return e?s?t?void 0:"Missing channels":"Missing Channel Group":"Missing Subscribe Key"}parse(e){return i(this,void 0,void 0,(function*(){const t=this.deserializeResponse(e);if(!t)throw new d("Service response error, check status for details",p("Unable to deserialize service response"));if(t.status>=400)throw _.create(e);return{}}))}get path(){const{keySet:{subscribeKey:e},channelGroup:t}=this.parameters;return`/v1/channel-registration/sub-key/${e}/channel-group/${I(t)}`}get queryParameters(){return{remove:this.parameters.channels.join(",")}}}class os extends se{constructor(e){super(),this.parameters=e}operation(){return re.PNAddChannelsToGroupOperation}validate(){const{keySet:{subscribeKey:e},channels:t,channelGroup:s}=this.parameters;return e?s?t?void 0:"Missing channels":"Missing Channel Group":"Missing Subscribe Key"}parse(e){return i(this,void 0,void 0,(function*(){const t=this.deserializeResponse(e);if(!t)throw new d("Service response error, check status for details",p("Unable to deserialize service response"));if(t.status>=400)throw _.create(e);return{}}))}get path(){const{keySet:{subscribeKey:e},channelGroup:t}=this.parameters;return`/v1/channel-registration/sub-key/${e}/channel-group/${I(t)}`}get queryParameters(){return{add:this.parameters.channels.join(",")}}}class as extends se{constructor(e){super(),this.parameters=e}operation(){return re.PNChannelsForGroupOperation}validate(){return this.parameters.keySet.subscribeKey?this.parameters.channelGroup?void 0:"Missing Channel Group":"Missing Subscribe Key"}parse(e){return i(this,void 0,void 0,(function*(){const t=this.deserializeResponse(e);if(!t)throw new d("Service response error, check status for details",p("Unable to deserialize service response"));if(t.status>=400)throw _.create(e);return{channels:t.payload.channels}}))}get path(){const{keySet:{subscribeKey:e},channelGroup:t}=this.parameters;return`/v1/channel-registration/sub-key/${e}/channel-group/${I(t)}`}}class cs extends se{constructor(e){super(),this.parameters=e}operation(){return re.PNRemoveGroupOperation}validate(){return this.parameters.keySet.subscribeKey?this.parameters.channelGroup?void 0:"Missing Channel Group":"Missing Subscribe Key"}parse(e){return i(this,void 0,void 0,(function*(){const t=this.deserializeResponse(e);if(!t)throw new d("Service response error, check status for details",p("Unable to deserialize service response"));if(t.status>=400)throw _.create(e);return{}}))}get path(){const{keySet:{subscribeKey:e},channelGroup:t}=this.parameters;return`/v1/channel-registration/sub-key/${e}/channel-group/${I(t)}/remove`}}class us extends se{constructor(e){super(),this.parameters=e}operation(){return re.PNChannelGroupsOperation}validate(){if(!this.parameters.keySet.subscribeKey)return"Missing Subscribe Key"}parse(e){return i(this,void 0,void 0,(function*(){const t=this.deserializeResponse(e);if(!t)throw new d("Service response error, check status for details",p("Unable to deserialize service response"));if(t.status>=400)throw _.create(e);return{groups:t.payload.groups}}))}get path(){return`/v1/channel-registration/sub-key/${this.parameters.keySet.subscribeKey}/channel-group`}}class ls{constructor(e,t){this.keySet=e,this.sendRequest=t}listChannels(e,t){return i(this,void 0,void 0,(function*(){const s=new as(Object.assign(Object.assign({},e),{keySet:this.keySet}));return t?this.sendRequest(s,t):this.sendRequest(s)}))}listGroups(e){return i(this,void 0,void 0,(function*(){const t=new us({keySet:this.keySet});return e?this.sendRequest(t,e):this.sendRequest(t)}))}addChannels(e,t){return i(this,void 0,void 0,(function*(){const s=new os(Object.assign(Object.assign({},e),{keySet:this.keySet}));return t?this.sendRequest(s,t):this.sendRequest(s)}))}removeChannels(e,t){return i(this,void 0,void 0,(function*(){const s=new is(Object.assign(Object.assign({},e),{keySet:this.keySet}));return t?this.sendRequest(s,t):this.sendRequest(s)}))}deleteGroup(e,t){return i(this,void 0,void 0,(function*(){const s=new cs(Object.assign(Object.assign({},e),{keySet:this.keySet}));return t?this.sendRequest(s,t):this.sendRequest(s)}))}}class hs extends se{constructor(e){var t,s;super(),this.parameters=e,"apns2"===this.parameters.pushGateway&&(null!==(t=(s=this.parameters).environment)&&void 0!==t||(s.environment="development")),this.parameters.count&&this.parameters.count>1e3&&(this.parameters.count=1e3)}operation(){throw Error("Should be implemented in subclass.")}validate(){const{keySet:{subscribeKey:e},action:t,device:s,pushGateway:n}=this.parameters;return e?s?"add"!==t&&"remove"!==t||"channels"in this.parameters&&0!==this.parameters.channels.length?n?"apns2"!==this.parameters.pushGateway||this.parameters.topic?void 0:"Missing APNS2 topic":"Missing GW Type (pushGateway: gcm or apns2)":"Missing Channels":"Missing Device ID (device)":"Missing Subscribe Key"}parse(e){return i(this,void 0,void 0,(function*(){throw Error("Should be implemented in subclass.")}))}get path(){const{keySet:{subscribeKey:e},action:t,device:s,pushGateway:n}=this.parameters;let r="apns2"===n?`/v2/push/sub-key/${e}/devices-apns2/${s}`:`/v1/push/sub-key/${e}/devices/${s}`;return"remove-device"===t&&(r=`${r}/remove`),r}get queryParameters(){const{start:e,count:t}=this.parameters;let s=Object.assign(Object.assign({type:this.parameters.pushGateway},e?{start:e}:{}),t&&t>0?{count:t}:{});if("channels"in this.parameters&&(s[this.parameters.action]=this.parameters.channels.join(",")),"apns2"===this.parameters.pushGateway){const{environment:e,topic:t}=this.parameters;s=Object.assign(Object.assign({},s),{environment:e,topic:t})}return s}}class ds extends hs{constructor(e){super(Object.assign(Object.assign({},e),{action:"remove"}))}operation(){return re.PNRemovePushNotificationEnabledChannelsOperation}parse(e){return i(this,void 0,void 0,(function*(){if(!this.deserializeResponse(e))throw new d("Service response error, check status for details",p("Unable to deserialize service response"));return{}}))}}class ps extends hs{constructor(e){super(Object.assign(Object.assign({},e),{action:"list"}))}operation(){return re.PNPushNotificationEnabledChannelsOperation}parse(e){return i(this,void 0,void 0,(function*(){const t=this.deserializeResponse(e);if(!t)throw new d("Service response error, check status for details",p("Unable to deserialize service response"));return{channels:t}}))}}class gs extends hs{constructor(e){super(Object.assign(Object.assign({},e),{action:"add"}))}operation(){return re.PNAddPushNotificationEnabledChannelsOperation}parse(e){return i(this,void 0,void 0,(function*(){if(!this.deserializeResponse(e))throw new d("Service response error, check status for details",p("Unable to deserialize service response"));return{}}))}}class ys extends hs{constructor(e){super(Object.assign(Object.assign({},e),{action:"remove-device"}))}operation(){return re.PNRemoveAllPushNotificationsOperation}parse(e){return i(this,void 0,void 0,(function*(){if(!this.deserializeResponse(e))throw new d("Service response error, check status for details",p("Unable to deserialize service response"));return{}}))}}class fs{constructor(e,t){this.keySet=e,this.sendRequest=t}listChannels(e,t){return i(this,void 0,void 0,(function*(){const s=new ps(Object.assign(Object.assign({},e),{keySet:this.keySet}));return t?this.sendRequest(s,t):this.sendRequest(s)}))}addChannels(e,t){return i(this,void 0,void 0,(function*(){const s=new gs(Object.assign(Object.assign({},e),{keySet:this.keySet}));return t?this.sendRequest(s,t):this.sendRequest(s)}))}removeChannels(e,t){return i(this,void 0,void 0,(function*(){const s=new ds(Object.assign(Object.assign({},e),{keySet:this.keySet}));return t?this.sendRequest(s,t):this.sendRequest(s)}))}deleteDevice(e,t){return i(this,void 0,void 0,(function*(){const s=new ys(Object.assign(Object.assign({},e),{keySet:this.keySet}));return t?this.sendRequest(s,t):this.sendRequest(s)}))}}class ms extends se{constructor(e){var t,s,n,r,i,o;super(),this.parameters=e,null!==(t=e.include)&&void 0!==t||(e.include={}),null!==(s=(i=e.include).customFields)&&void 0!==s||(i.customFields=false),null!==(n=(o=e.include).totalCount)&&void 0!==n||(o.totalCount=false),null!==(r=e.limit)&&void 0!==r||(e.limit=100)}operation(){return re.PNGetAllChannelMetadataOperation}parse(e){return i(this,void 0,void 0,(function*(){const t=this.deserializeResponse(e);if(!t)throw new d("Service response error, check status for details",p("Unable to deserialize service response"));if(t.status>=400)throw _.create(e);return t}))}get path(){return`/v2/objects/${this.parameters.keySet.subscribeKey}/channels`}get queryParameters(){const{include:e,page:t,filter:s,sort:n,limit:r}=this.parameters,i=Object.entries(null!=n?n:{}).map((([e,t])=>null!==t?`${e}:${t}`:e));return Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({include:["status","type",...e.customFields?["custom"]:[]].join(","),count:`${e.totalCount}`},s?{filter:s}:{}),(null==t?void 0:t.next)?{start:t.next}:{}),(null==t?void 0:t.prev)?{end:t.prev}:{}),r?{limit:r}:{}),i.length?{sort:i}:{})}}class bs extends se{constructor(e){super({method:H.DELETE}),this.parameters=e}operation(){return re.PNRemoveChannelMetadataOperation}validate(){if(!this.parameters.channel)return"Channel cannot be empty"}parse(e){return i(this,void 0,void 0,(function*(){const t=this.deserializeResponse(e);if(!t)throw new d("Service response error, check status for details",p("Unable to deserialize service response"));if(t.status>=400)throw _.create(e);return t}))}get path(){const{keySet:{subscribeKey:e},channel:t}=this.parameters;return`/v2/objects/${e}/channels/${I(t)}`}}class vs extends se{constructor(e){var t,s,n,r,i,o,a,c,u,l,h,d,p,g,y,f;super(),this.parameters=e,null!==(t=e.include)&&void 0!==t||(e.include={}),null!==(s=(l=e.include).customFields)&&void 0!==s||(l.customFields=false),null!==(n=(h=e.include).totalCount)&&void 0!==n||(h.totalCount=false),null!==(r=(d=e.include).statusField)&&void 0!==r||(d.statusField=false),null!==(i=(p=e.include).channelFields)&&void 0!==i||(p.channelFields=false),null!==(o=(g=e.include).customChannelFields)&&void 0!==o||(g.customChannelFields=false),null!==(a=(y=e.include).channelStatusField)&&void 0!==a||(y.channelStatusField=false),null!==(c=(f=e.include).channelTypeField)&&void 0!==c||(f.channelTypeField=false),null!==(u=e.limit)&&void 0!==u||(e.limit=100),this.parameters.userId&&(this.parameters.uuid=this.parameters.userId)}operation(){return re.PNGetMembershipsOperation}validate(){if(!this.parameters.uuid)return"'uuid' cannot be empty"}parse(e){return i(this,void 0,void 0,(function*(){const t=this.deserializeResponse(e);if(!t)throw new d("Service response error, check status for details",p("Unable to deserialize service response"));if(t.status>=400)throw _.create(e);return t}))}get path(){const{keySet:{subscribeKey:e},uuid:t}=this.parameters;return`/v2/objects/${e}/uuids/${I(t)}/channels`}get queryParameters(){const{include:e,page:t,filter:s,sort:n,limit:r}=this.parameters,i=Object.entries(null!=n?n:{}).map((([e,t])=>null!==t?`${e}:${t}`:e)),o=[];return e.statusField&&o.push("status"),e.customFields&&o.push("custom"),e.channelFields&&o.push("channel"),e.channelStatusField&&o.push("channel.status"),e.channelTypeField&&o.push("channel.type"),e.customChannelFields&&o.push("channel.custom"),Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({count:`${e.totalCount}`},o.length>0?{include:o.join(",")}:{}),s?{filter:s}:{}),(null==t?void 0:t.next)?{start:t.next}:{}),(null==t?void 0:t.prev)?{end:t.prev}:{}),r?{limit:r}:{}),i.length?{sort:i}:{})}}class ws extends se{constructor(e){var t,s,n,r,i,o,a,c,u,l;super({method:H.PATCH}),this.parameters=e,null!==(t=e.include)&&void 0!==t||(e.include={}),null!==(s=(a=e.include).customFields)&&void 0!==s||(a.customFields=false),null!==(n=(c=e.include).totalCount)&&void 0!==n||(c.totalCount=false),null!==(r=(u=e.include).channelFields)&&void 0!==r||(u.channelFields=false),null!==(i=(l=e.include).customChannelFields)&&void 0!==i||(l.customChannelFields=false),null!==(o=e.limit)&&void 0!==o||(e.limit=100),this.parameters.userId&&(this.parameters.uuid=this.parameters.userId)}operation(){return re.PNSetMembershipsOperation}validate(){const{uuid:e,channels:t}=this.parameters;return e?t&&0!==t.length?void 0:"Channels cannot be empty":"'uuid' cannot be empty"}parse(e){return i(this,void 0,void 0,(function*(){const t=this.deserializeResponse(e);if(!t)throw new d("Service response error, check status for details",p("Unable to deserialize service response"));if(t.status>=400)throw _.create(e);return t}))}get path(){const{keySet:{subscribeKey:e},uuid:t}=this.parameters;return`/v2/objects/${e}/uuids/${I(t)}/channels`}get queryParameters(){const{include:e,page:t,filter:s,sort:n,limit:r}=this.parameters,i=Object.entries(null!=n?n:{}).map((([e,t])=>null!==t?`${e}:${t}`:e)),o=["channel.status","channel.type","status"];return e.customFields&&o.push("custom"),e.channelFields&&o.push("channel"),e.customChannelFields&&o.push("channel.custom"),Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({count:`${e.totalCount}`},o.length>0?{include:o.join(",")}:{}),s?{filter:s}:{}),(null==t?void 0:t.next)?{start:t.next}:{}),(null==t?void 0:t.prev)?{end:t.prev}:{}),r?{limit:r}:{}),i.length?{sort:i}:{})}get body(){const{channels:e,type:t}=this.parameters;return JSON.stringify({[`${t}`]:e.map((e=>"string"==typeof e?{channel:{id:e}}:{channel:{id:e.id},status:e.status,custom:e.custom}))})}}class Ss extends se{constructor(e){var t,s,n,r;super(),this.parameters=e,null!==(t=e.include)&&void 0!==t||(e.include={}),null!==(s=(r=e.include).customFields)&&void 0!==s||(r.customFields=false),null!==(n=e.limit)&&void 0!==n||(e.limit=100)}operation(){return re.PNGetAllUUIDMetadataOperation}parse(e){return i(this,void 0,void 0,(function*(){const t=this.deserializeResponse(e);if(!t)throw new d("Service response error, check status for details",p("Unable to deserialize service response"));if(t.status>=400)throw _.create(e);return t}))}get path(){return`/v2/objects/${this.parameters.keySet.subscribeKey}/uuids`}get queryParameters(){const{include:e,page:t,filter:s,sort:n,limit:r}=this.parameters,i=Object.entries(null!=n?n:{}).map((([e,t])=>null!==t?`${e}:${t}`:e));return Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({include:["status","type",...e.customFields?["custom"]:[]].join(",")},void 0!==e.totalCount?{count:`${e.totalCount}`}:{}),s?{filter:s}:{}),(null==t?void 0:t.next)?{start:t.next}:{}),(null==t?void 0:t.prev)?{end:t.prev}:{}),r?{limit:r}:{}),i.length?{sort:i}:{})}}class ks extends se{constructor(e){var t,s,n;super(),this.parameters=e,null!==(t=e.include)&&void 0!==t||(e.include={}),null!==(s=(n=e.include).customFields)&&void 0!==s||(n.customFields=true)}operation(){return re.PNGetChannelMetadataOperation}validate(){if(!this.parameters.channel)return"Channel cannot be empty"}parse(e){return i(this,void 0,void 0,(function*(){const t=this.deserializeResponse(e);if(!t)throw new d("Service response error, check status for details",p("Unable to deserialize service response"));if(t.status>=400)throw _.create(e);return t}))}get path(){const{keySet:{subscribeKey:e},channel:t}=this.parameters;return`/v2/objects/${e}/channels/${I(t)}`}get queryParameters(){return{include:["status","type",...this.parameters.include.customFields?["custom"]:[]].join(",")}}}class Es extends se{constructor(e){var t,s,n;super({method:H.PATCH}),this.parameters=e,null!==(t=e.include)&&void 0!==t||(e.include={}),null!==(s=(n=e.include).customFields)&&void 0!==s||(n.customFields=true)}operation(){return re.PNSetChannelMetadataOperation}validate(){return this.parameters.channel?this.parameters.data?void 0:"Data cannot be empty":"Channel cannot be empty"}parse(e){return i(this,void 0,void 0,(function*(){const t=this.deserializeResponse(e);if(!t)throw new d("Service response error, check status for details",p("Unable to deserialize service response"));if(t.status>=400)throw _.create(e);return t}))}get path(){const{keySet:{subscribeKey:e},channel:t}=this.parameters;return`/v2/objects/${e}/channels/${I(t)}`}get queryParameters(){return{include:["status","type",...this.parameters.include.customFields?["custom"]:[]].join(",")}}get body(){return JSON.stringify(this.parameters.data)}}class Os extends se{constructor(e){super({method:H.DELETE}),this.parameters=e,this.parameters.userId&&(this.parameters.uuid=this.parameters.userId)}operation(){return re.PNRemoveUUIDMetadataOperation}validate(){if(!this.parameters.uuid)return"'uuid' cannot be empty"}parse(e){return i(this,void 0,void 0,(function*(){const t=this.deserializeResponse(e);if(!t)throw new d("Service response error, check status for details",p("Unable to deserialize service response"));if(t.status>=400)throw _.create(e);return t}))}get path(){const{keySet:{subscribeKey:e},uuid:t}=this.parameters;return`/v2/objects/${e}/uuids/${I(t)}`}}class Cs extends se{constructor(e){var t,s,n,r,i,o,a,c,u,l,h,d,p,g,y,f;super(),this.parameters=e,null!==(t=e.include)&&void 0!==t||(e.include={}),null!==(s=(l=e.include).customFields)&&void 0!==s||(l.customFields=false),null!==(n=(h=e.include).totalCount)&&void 0!==n||(h.totalCount=false),null!==(r=(d=e.include).statusField)&&void 0!==r||(d.statusField=false),null!==(i=(p=e.include).UUIDFields)&&void 0!==i||(p.UUIDFields=false),null!==(o=(g=e.include).customUUIDFields)&&void 0!==o||(g.customUUIDFields=false),null!==(a=(y=e.include).UUIDStatusField)&&void 0!==a||(y.UUIDStatusField=false),null!==(c=(f=e.include).UUIDTypeField)&&void 0!==c||(f.UUIDTypeField=false),null!==(u=e.limit)&&void 0!==u||(e.limit=100)}operation(){return re.PNSetMembersOperation}validate(){if(!this.parameters.channel)return"Channel cannot be empty"}parse(e){return i(this,void 0,void 0,(function*(){const t=this.deserializeResponse(e);if(!t)throw new d("Service response error, check status for details",p("Unable to deserialize service response"));if(t.status>=400)throw _.create(e);return t}))}get path(){const{keySet:{subscribeKey:e},channel:t}=this.parameters;return`/v2/objects/${e}/channels/${I(t)}/uuids`}get queryParameters(){const{include:e,page:t,filter:s,sort:n,limit:r}=this.parameters,i=Object.entries(null!=n?n:{}).map((([e,t])=>null!==t?`${e}:${t}`:e)),o=[];return e.statusField&&o.push("status"),e.customFields&&o.push("custom"),e.UUIDFields&&o.push("uuid"),e.UUIDStatusField&&o.push("uuid.status"),e.UUIDTypeField&&o.push("uuid.type"),e.customUUIDFields&&o.push("uuid.custom"),Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({count:`${e.totalCount}`},o.length>0?{include:o.join(",")}:{}),s?{filter:s}:{}),(null==t?void 0:t.next)?{start:t.next}:{}),(null==t?void 0:t.prev)?{end:t.prev}:{}),r?{limit:r}:{}),i.length?{sort:i}:{})}}class Ns extends se{constructor(e){var t,s,n,r,i,o,a,c,u,l;super({method:H.PATCH}),this.parameters=e,null!==(t=e.include)&&void 0!==t||(e.include={}),null!==(s=(a=e.include).customFields)&&void 0!==s||(a.customFields=false),null!==(n=(c=e.include).totalCount)&&void 0!==n||(c.totalCount=false),null!==(r=(u=e.include).UUIDFields)&&void 0!==r||(u.UUIDFields=false),null!==(i=(l=e.include).customUUIDFields)&&void 0!==i||(l.customUUIDFields=false),null!==(o=e.limit)&&void 0!==o||(e.limit=100)}operation(){return re.PNSetMembersOperation}validate(){const{channel:e,uuids:t}=this.parameters;return e?t&&0!==t.length?void 0:"UUIDs cannot be empty":"Channel cannot be empty"}parse(e){return i(this,void 0,void 0,(function*(){const t=this.deserializeResponse(e);if(!t)throw new d("Service response error, check status for details",p("Unable to deserialize service response"));if(t.status>=400)throw _.create(e);return t}))}get path(){const{keySet:{subscribeKey:e},channel:t}=this.parameters;return`/v2/objects/${e}/channels/${I(t)}/uuids`}get queryParameters(){const{include:e,page:t,filter:s,sort:n,limit:r}=this.parameters,i=Object.entries(null!=n?n:{}).map((([e,t])=>null!==t?`${e}:${t}`:e)),o=["uuid.status","uuid.type","type"];return e.customFields&&o.push("custom"),e.UUIDFields&&o.push("uuid"),e.customUUIDFields&&o.push("uuid.custom"),Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({count:`${e.totalCount}`},o.length>0?{include:o.join(",")}:{}),s?{filter:s}:{}),(null==t?void 0:t.next)?{start:t.next}:{}),(null==t?void 0:t.prev)?{end:t.prev}:{}),r?{limit:r}:{}),i.length?{sort:i}:{})}get body(){const{uuids:e,type:t}=this.parameters;return JSON.stringify({[`${t}`]:e.map((e=>"string"==typeof e?{uuid:{id:e}}:{uuid:{id:e.id},status:e.status,custom:e.custom}))})}}class Ps extends se{constructor(e){var t,s,n;super(),this.parameters=e,null!==(t=e.include)&&void 0!==t||(e.include={}),null!==(s=(n=e.include).customFields)&&void 0!==s||(n.customFields=true),this.parameters.userId&&(this.parameters.uuid=this.parameters.userId)}operation(){return re.PNGetUUIDMetadataOperation}validate(){if(!this.parameters.uuid)return"'uuid' cannot be empty"}parse(e){return i(this,void 0,void 0,(function*(){const t=this.deserializeResponse(e);if(!t)throw new d("Service response error, check status for details",p("Unable to deserialize service response"));if(t.status>=400)throw _.create(e);return t}))}get path(){const{keySet:{subscribeKey:e},uuid:t}=this.parameters;return`/v2/objects/${e}/uuids/${I(t)}`}get queryParameters(){const{include:e}=this.parameters;return{include:["status","type",...e.customFields?["custom"]:[]].join(",")}}}class Ms extends se{constructor(e){var t,s,n;super({method:H.PATCH}),this.parameters=e,null!==(t=e.include)&&void 0!==t||(e.include={}),null!==(s=(n=e.include).customFields)&&void 0!==s||(n.customFields=true),this.parameters.userId&&(this.parameters.uuid=this.parameters.userId)}operation(){return re.PNSetUUIDMetadataOperation}validate(){return this.parameters.uuid?this.parameters.data?void 0:"Data cannot be empty":"'uuid' cannot be empty"}parse(e){return i(this,void 0,void 0,(function*(){const t=this.deserializeResponse(e);if(!t)throw new d("Service response error, check status for details",p("Unable to deserialize service response"));if(t.status>=400)throw _.create(e);return t}))}get path(){const{keySet:{subscribeKey:e},uuid:t}=this.parameters;return`/v2/objects/${e}/uuids/${I(t)}`}get queryParameters(){return{include:["status","type",...this.parameters.include.customFields?["custom"]:[]].join(",")}}get body(){return JSON.stringify(this.parameters.data)}}class js{constructor(e,t){this.configuration=e,this.sendRequest=t,this.keySet=e.keySet}getAllUUIDMetadata(e,t){return i(this,void 0,void 0,(function*(){return this._getAllUUIDMetadata(e,t)}))}_getAllUUIDMetadata(e,t){return i(this,void 0,void 0,(function*(){const s=e&&"function"!=typeof e?e:{};null!=t||(t="function"==typeof e?e:void 0);const n=new Ss(Object.assign(Object.assign({},s),{keySet:this.keySet}));return t?this.sendRequest(n,t):this.sendRequest(n)}))}getUUIDMetadata(e,t){return i(this,void 0,void 0,(function*(){return this._getUUIDMetadata(e,t)}))}_getUUIDMetadata(e,t){return i(this,void 0,void 0,(function*(){var s;const n=e&&"function"!=typeof e?e:{};null!=t||(t="function"==typeof e?e:void 0),n.userId&&(n.uuid=n.userId),null!==(s=n.uuid)&&void 0!==s||(n.uuid=this.configuration.userId);const r=new Ps(Object.assign(Object.assign({},n),{keySet:this.keySet}));return t?this.sendRequest(r,t):this.sendRequest(r)}))}setUUIDMetadata(e,t){return i(this,void 0,void 0,(function*(){return this._setUUIDMetadata(e,t)}))}_setUUIDMetadata(e,t){return i(this,void 0,void 0,(function*(){var s;e.userId&&(e.uuid=e.userId),null!==(s=e.uuid)&&void 0!==s||(e.uuid=this.configuration.userId);const n=new Ms(Object.assign(Object.assign({},e),{keySet:this.keySet}));return t?this.sendRequest(n,t):this.sendRequest(n)}))}removeUUIDMetadata(e,t){return i(this,void 0,void 0,(function*(){return this._removeUUIDMetadata(e,t)}))}_removeUUIDMetadata(e,t){return i(this,void 0,void 0,(function*(){var s;const n=e&&"function"!=typeof e?e:{};null!=t||(t="function"==typeof e?e:void 0),n.userId&&(n.uuid=n.userId),null!==(s=n.uuid)&&void 0!==s||(n.uuid=this.configuration.userId);const r=new Os(Object.assign(Object.assign({},n),{keySet:this.keySet}));return t?this.sendRequest(r,t):this.sendRequest(r)}))}getAllChannelMetadata(e,t){return i(this,void 0,void 0,(function*(){return this._getAllChannelMetadata(e,t)}))}_getAllChannelMetadata(e,t){return i(this,void 0,void 0,(function*(){const s=e&&"function"!=typeof e?e:{};null!=t||(t="function"==typeof e?e:void 0);const n=new ms(Object.assign(Object.assign({},s),{keySet:this.keySet}));return t?this.sendRequest(n,t):this.sendRequest(n)}))}getChannelMetadata(e,t){return i(this,void 0,void 0,(function*(){return this._getChannelMetadata(e,t)}))}_getChannelMetadata(e,t){return i(this,void 0,void 0,(function*(){const s=new ks(Object.assign(Object.assign({},e),{keySet:this.keySet}));return t?this.sendRequest(s,t):this.sendRequest(s)}))}setChannelMetadata(e,t){return i(this,void 0,void 0,(function*(){return this._setChannelMetadata(e,t)}))}_setChannelMetadata(e,t){return i(this,void 0,void 0,(function*(){const s=new Es(Object.assign(Object.assign({},e),{keySet:this.keySet}));return t?this.sendRequest(s,t):this.sendRequest(s)}))}removeChannelMetadata(e,t){return i(this,void 0,void 0,(function*(){return this._removeChannelMetadata(e,t)}))}_removeChannelMetadata(e,t){return i(this,void 0,void 0,(function*(){const s=new bs(Object.assign(Object.assign({},e),{keySet:this.keySet}));return t?this.sendRequest(s,t):this.sendRequest(s)}))}getChannelMembers(e,t){return i(this,void 0,void 0,(function*(){const s=new Cs(Object.assign(Object.assign({},e),{keySet:this.keySet}));return t?this.sendRequest(s,t):this.sendRequest(s)}))}setChannelMembers(e,t){return i(this,void 0,void 0,(function*(){const s=new Ns(Object.assign(Object.assign({},e),{type:"set",keySet:this.keySet}));return t?this.sendRequest(s,t):this.sendRequest(s)}))}removeChannelMembers(e,t){return i(this,void 0,void 0,(function*(){const s=new Ns(Object.assign(Object.assign({},e),{type:"delete",keySet:this.keySet}));return t?this.sendRequest(s,t):this.sendRequest(s)}))}getMemberships(e,t){return i(this,void 0,void 0,(function*(){var s;const n=e&&"function"!=typeof e?e:{};null!=t||(t="function"==typeof e?e:void 0),n.userId&&(n.uuid=n.userId),null!==(s=n.uuid)&&void 0!==s||(n.uuid=this.configuration.userId);const r=new vs(Object.assign(Object.assign({},n),{keySet:this.keySet}));return t?this.sendRequest(r,t):this.sendRequest(r)}))}setMemberships(e,t){return i(this,void 0,void 0,(function*(){var s;e.userId&&(e.uuid=e.userId),null!==(s=e.uuid)&&void 0!==s||(e.uuid=this.configuration.userId);const n=new ws(Object.assign(Object.assign({},e),{type:"set",keySet:this.keySet}));return t?this.sendRequest(n,t):this.sendRequest(n)}))}removeMemberships(e,t){return i(this,void 0,void 0,(function*(){var s;e.userId&&(e.uuid=e.userId),null!==(s=e.uuid)&&void 0!==s||(e.uuid=this.configuration.userId);const n=new ws(Object.assign(Object.assign({},e),{type:"delete",keySet:this.keySet}));return t?this.sendRequest(n,t):this.sendRequest(n)}))}fetchMemberships(e,t){return i(this,void 0,void 0,(function*(){var s,n;if("spaceId"in e){const n=e,r={channel:null!==(s=n.spaceId)&&void 0!==s?s:n.channel,filter:n.filter,limit:n.limit,page:n.page,include:Object.assign({},n.include),sort:n.sort?Object.fromEntries(Object.entries(n.sort).map((([e,t])=>[e.replace("user","uuid"),t]))):void 0},i=e=>({status:e.status,data:e.data.map((e=>({user:e.uuid,custom:e.custom,updated:e.updated,eTag:e.eTag}))),totalCount:e.totalCount,next:e.next,prev:e.prev});return t?this.getChannelMembers(r,((e,s)=>{t(e,s?i(s):s)})):this.getChannelMembers(r).then(i)}const r=e,i={uuid:null!==(n=r.userId)&&void 0!==n?n:r.uuid,filter:r.filter,limit:r.limit,page:r.page,include:Object.assign({},r.include),sort:r.sort?Object.fromEntries(Object.entries(r.sort).map((([e,t])=>[e.replace("space","channel"),t]))):void 0},o=e=>({status:e.status,data:e.data.map((e=>({space:e.channel,custom:e.custom,updated:e.updated,eTag:e.eTag}))),totalCount:e.totalCount,next:e.next,prev:e.prev});return t?this.getMemberships(i,((e,s)=>{t(e,s?o(s):s)})):this.getMemberships(i).then(o)}))}addMemberships(e,t){return i(this,void 0,void 0,(function*(){var s,n,r,i,o,a;if("spaceId"in e){const i=e,o={channel:null!==(s=i.spaceId)&&void 0!==s?s:i.channel,uuids:null!==(r=null===(n=i.users)||void 0===n?void 0:n.map((e=>"string"==typeof e?e:(e.userId,{id:e.userId,custom:e.custom}))))&&void 0!==r?r:i.uuids,limit:0};return t?this.setChannelMembers(o,t):this.setChannelMembers(o)}const c=e,u={uuid:null!==(i=c.userId)&&void 0!==i?i:c.uuid,channels:null!==(a=null===(o=c.spaces)||void 0===o?void 0:o.map((e=>"string"==typeof e?e:{id:e.spaceId,custom:e.custom})))&&void 0!==a?a:c.channels,limit:0};return t?this.setMemberships(u,t):this.setMemberships(u)}))}}class _s extends se{constructor(){super()}operation(){return re.PNTimeOperation}parse(e){return i(this,void 0,void 0,(function*(){const t=this.deserializeResponse(e);if(!t)throw new d("Service response error, check status for details",p("Unable to deserialize service response"));return{timetoken:t[0]}}))}get path(){return"/time/0"}}class As extends se{constructor(e){super(),this.parameters=e}operation(){return re.PNDownloadFileOperation}validate(){const{channel:e,id:t,name:s}=this.parameters;return e?t?s?void 0:"file name can't be empty":"file id can't be empty":"channel can't be empty"}parse(e){return i(this,void 0,void 0,(function*(){const{cipherKey:t,crypto:s,cryptography:n,name:r,PubNubFile:i}=this.parameters,o=e.headers["content-type"];let a,c=e.body;return i.supportsEncryptFile&&(t||s)&&(t&&n?c=yield n.decrypt(t,c):!t&&s&&(a=yield s.decryptFile(i.create({data:c,name:r,mimeType:o}),i))),a||i.create({data:c,name:r,mimeType:o})}))}get path(){const{keySet:{subscribeKey:e},channel:t,id:s,name:n}=this.parameters;return`/v1/files/${e}/channels/${I(t)}/files/${s}/${n}`}}class Is{static notificationPayload(e,t){return new te(e,t)}static generateUUID(){return G.createUUID()}constructor(e){if(this._configuration=e.configuration,this.cryptography=e.cryptography,this.tokenManager=e.tokenManager,this.transport=e.transport,this.crypto=e.crypto,this._objects=new js(this._configuration,this.sendRequest.bind(this)),this._channelGroups=new ls(this._configuration.keySet,this.sendRequest.bind(this)),this._push=new fs(this._configuration.keySet,this.sendRequest.bind(this)),this.listenerManager=new W,this.eventEmitter=new ce(this.listenerManager),this._configuration.enableEventEngine){let e=this._configuration.getHeartbeatInterval();this.presenceState={},e&&(this.presenceEventEngine=new $e({heartbeat:this.heartbeat.bind(this),leave:e=>this.makeUnsubscribe(e,(()=>{})),heartbeatDelay:()=>new Promise(((t,s)=>{e=this._configuration.getHeartbeatInterval(),e?setTimeout(t,1e3*e):s(new d("Heartbeat interval has been reset."))})),retryDelay:e=>new Promise((t=>setTimeout(t,e))),emitStatus:e=>this.listenerManager.announceStatus(e),config:this._configuration,presenceState:this.presenceState})),this.eventEngine=new St({handshake:this.subscribeHandshake.bind(this),receiveMessages:this.subscribeReceiveMessages.bind(this),delay:e=>new Promise((t=>setTimeout(t,e))),join:this.join.bind(this),leave:this.leave.bind(this),leaveAll:this.leaveAll.bind(this),presenceState:this.presenceState,config:this._configuration,emitMessages:e=>{try{e.forEach((e=>this.eventEmitter.emitEvent(e)))}catch(e){const t={error:!0,category:h.PNUnknownCategory,errorData:e,statusCode:0};this.listenerManager.announceStatus(t)}},emitStatus:e=>this.listenerManager.announceStatus(e)})}else this.subscriptionManager=new Y(this._configuration,this.listenerManager,this.eventEmitter,this.makeSubscribe.bind(this),this.heartbeat.bind(this),this.makeUnsubscribe.bind(this),this.time.bind(this))}get configuration(){return this._configuration}get _config(){return this.configuration}get authKey(){var e;return null!==(e=this._configuration.authKey)&&void 0!==e?e:void 0}getAuthKey(){return this.authKey}setAuthKey(e){this._configuration.setAuthKey(e)}get userId(){return this._configuration.userId}set userId(e){if(!e||"string"!=typeof e||0===e.trim().length)throw new Error("Missing or invalid userId parameter. Provide a valid string userId");this._configuration.userId=e}getUserId(){return this._configuration.userId}setUserId(e){if(!e||"string"!=typeof e||0===e.trim().length)throw new Error("Missing or invalid userId parameter. Provide a valid string userId");this._configuration.userId=e}get filterExpression(){var e;return null!==(e=this._configuration.getFilterExpression())&&void 0!==e?e:void 0}getFilterExpression(){return this.filterExpression}set filterExpression(e){this._configuration.setFilterExpression(e)}setFilterExpression(e){this.filterExpression=e}get cipherKey(){return this._configuration.getCipherKey()}set cipherKey(e){this._configuration.setCipherKey(e)}setCipherKey(e){this.cipherKey=e}set heartbeatInterval(e){this._configuration.setHeartbeatInterval(e)}setHeartbeatInterval(e){this.heartbeatInterval=e}getVersion(){return this._configuration.getVersion()}_addPnsdkSuffix(e,t){this._configuration._addPnsdkSuffix(e,t)}getUUID(){return this.userId}setUUID(e){this.userId=e}get customEncrypt(){return this._configuration.getCustomEncrypt()}get customDecrypt(){return this._configuration.getCustomDecrypt()}channel(e){return new rs(e,this.eventEmitter,this)}channelGroup(e){return new ss(e,this.eventEmitter,this)}channelMetadata(e){return new ts(e,this.eventEmitter,this)}userMetadata(e){return new ns(e,this.eventEmitter,this)}subscriptionSet(e){return new Zt(Object.assign(Object.assign({},e),{eventEmitter:this.eventEmitter,pubnub:this}))}sendRequest(e,t){return i(this,void 0,void 0,(function*(){const s=e.validate();if(s){if(t)return t(p(s),null);throw new d("Validation failed, check status for details",p(s))}const n=e.request();n.formData&&n.formData.length>0?n.timeout=300:e.operation()===re.PNSubscribeOperation?n.timeout=this._configuration.getSubscribeTimeout():n.timeout=this._configuration.getTransactionTimeout();const r={error:!1,operation:e.operation(),category:h.PNAcknowledgmentCategory,statusCode:0},[i,o]=this.transport.makeSendable(n);return e.cancellationController=o||null,i.then((t=>{if(r.statusCode=t.status,200!==t.status&&204!==t.status){const e=t.headers["content-type"];if(e||-1!==e.indexOf("javascript")||-1!==e.indexOf("json")){const e=JSON.parse(Is.decoder.decode(t.body));"object"==typeof e&&"error"in e&&e.error&&"object"==typeof e.error&&(r.errorData=e.error)}}return e.parse(t)})).then((e=>t?t(r,e):e)).catch((s=>{const n=s instanceof _?s:_.create(s);if(t)return t(n.toStatus(e.operation()),null);throw n.toPubNubError(e.operation(),"REST API request processing error, check status for details")}))}))}destroy(e){this.subscriptionManager?(this.subscriptionManager.unsubscribeAll(e),this.subscriptionManager.disconnect()):this.eventEngine&&this.eventEngine.dispose()}stop(){this.destroy()}addListener(e){this.listenerManager.addListener(e)}removeListener(e){this.listenerManager.removeListener(e)}removeAllListeners(){this.listenerManager.removeAllListeners()}publish(e,t){return i(this,void 0,void 0,(function*(){const s=new kt(Object.assign(Object.assign({},e),{keySet:this._configuration.keySet,crypto:this._configuration.getCryptoModule()}));return t?this.sendRequest(s,t):this.sendRequest(s)}))}signal(e,t){return i(this,void 0,void 0,(function*(){const s=new Et(Object.assign(Object.assign({},e),{keySet:this._configuration.keySet}));return t?this.sendRequest(s,t):this.sendRequest(s)}))}fire(e,t){return i(this,void 0,void 0,(function*(){return null!=t||(t=()=>{}),this.publish(Object.assign(Object.assign({},e),{replicate:!1,storeInHistory:!1}),t)}))}getSubscribedChannels(){return this.subscriptionManager?this.subscriptionManager.subscribedChannels:this.eventEngine?this.eventEngine.getSubscribedChannels():[]}getSubscribedChannelGroups(){return this.subscriptionManager?this.subscriptionManager.subscribedChannelGroups:this.eventEngine?this.eventEngine.getSubscribedChannelGroups():[]}subscribe(e){this.subscriptionManager?this.subscriptionManager.subscribe(e):this.eventEngine&&this.eventEngine.subscribe(e)}makeSubscribe(e,t){const s=new ae(Object.assign(Object.assign({},e),{keySet:this._configuration.keySet,crypto:this._configuration.getCryptoModule(),getFileUrl:this.getFileUrl.bind(this)}));if(this.sendRequest(s,((e,n)=>{var r;this.subscriptionManager&&(null===(r=this.subscriptionManager.abort)||void 0===r?void 0:r.identifier)===s.requestIdentifier&&(this.subscriptionManager.abort=null),t(e,n)})),this.subscriptionManager){const e=()=>s.abort();e.identifier=s.requestIdentifier,this.subscriptionManager.abort=e}}unsubscribe(e){this.subscriptionManager?this.subscriptionManager.unsubscribe(e):this.eventEngine&&this.eventEngine.unsubscribe(e)}makeUnsubscribe(e,t){this.sendRequest(new jt(Object.assign(Object.assign({},e),{keySet:this._configuration.keySet})),t)}unsubscribeAll(){this.subscriptionManager?this.subscriptionManager.unsubscribeAll():this.eventEngine&&this.eventEngine.unsubscribeAll()}disconnect(){this.subscriptionManager?this.subscriptionManager.disconnect():this.eventEngine&&this.eventEngine.disconnect()}reconnect(e){this.subscriptionManager?this.subscriptionManager.reconnect():this.eventEngine&&this.eventEngine.reconnect(null!=e?e:{})}subscribeHandshake(e){return i(this,void 0,void 0,(function*(){const t=new Ct(Object.assign(Object.assign({},e),{keySet:this._configuration.keySet,crypto:this._configuration.getCryptoModule(),getFileUrl:this.getFileUrl.bind(this)})),s=e.abortSignal.subscribe((e=>{t.abort()}));return this.sendRequest(t).then((e=>(s(),e.cursor)))}))}subscribeReceiveMessages(e){return i(this,void 0,void 0,(function*(){const t=new Ot(Object.assign(Object.assign({},e),{keySet:this._configuration.keySet,crypto:this._configuration.getCryptoModule(),getFileUrl:this.getFileUrl.bind(this)})),s=e.abortSignal.subscribe((e=>{t.abort()}));return this.sendRequest(t).then((e=>(s(),e)))}))}getMessageActions(e,t){return i(this,void 0,void 0,(function*(){const s=new xt(Object.assign(Object.assign({},e),{keySet:this._configuration.keySet}));return t?this.sendRequest(s,t):this.sendRequest(s)}))}addMessageAction(e,t){return i(this,void 0,void 0,(function*(){const s=new Dt(Object.assign(Object.assign({},e),{keySet:this._configuration.keySet}));return t?this.sendRequest(s,t):this.sendRequest(s)}))}removeMessageAction(e,t){return i(this,void 0,void 0,(function*(){const s=new Kt(Object.assign(Object.assign({},e),{keySet:this._configuration.keySet}));return t?this.sendRequest(s,t):this.sendRequest(s)}))}fetchMessages(e,t){return i(this,void 0,void 0,(function*(){const s=new Ft(Object.assign(Object.assign({},e),{keySet:this._configuration.keySet,crypto:this._configuration.getCryptoModule(),getFileUrl:this.getFileUrl.bind(this)}));return t?this.sendRequest(s,t):this.sendRequest(s)}))}deleteMessages(e,t){return i(this,void 0,void 0,(function*(){const s=new It(Object.assign(Object.assign({},e),{keySet:this._configuration.keySet}));return t?this.sendRequest(s,t):this.sendRequest(s)}))}messageCounts(e,t){return i(this,void 0,void 0,(function*(){const s=new Rt(Object.assign(Object.assign({},e),{keySet:this._configuration.keySet}));return t?this.sendRequest(s,t):this.sendRequest(s)}))}history(e,t){return i(this,void 0,void 0,(function*(){const s=new Ut(Object.assign(Object.assign({},e),{keySet:this._configuration.keySet,crypto:this._configuration.getCryptoModule()}));return t?this.sendRequest(s,t):this.sendRequest(s)}))}hereNow(e,t){return i(this,void 0,void 0,(function*(){const s=new At(Object.assign(Object.assign({},e),{keySet:this._configuration.keySet}));return t?this.sendRequest(s,t):this.sendRequest(s)}))}whereNow(e,t){return i(this,void 0,void 0,(function*(){var s;const n=new _t({uuid:null!==(s=e.uuid)&&void 0!==s?s:this._configuration.userId,keySet:this._configuration.keySet});return t?this.sendRequest(n,t):this.sendRequest(n)}))}getState(e,t){return i(this,void 0,void 0,(function*(){var s;const n=new Nt(Object.assign(Object.assign({},e),{uuid:null!==(s=e.uuid)&&void 0!==s?s:this._configuration.userId,keySet:this._configuration.keySet}));return t?this.sendRequest(n,t):this.sendRequest(n)}))}setState(e,t){return i(this,void 0,void 0,(function*(){var s,n;const{keySet:r,userId:i}=this._configuration,o=this._configuration.getPresenceTimeout();let a;if(this._configuration.enableEventEngine&&this.presenceState){const t=this.presenceState;null===(s=e.channels)||void 0===s||s.forEach((s=>t[s]=e.state)),"channelGroups"in e&&(null===(n=e.channelGroups)||void 0===n||n.forEach((s=>t[s]=e.state)))}return a="withHeartbeat"in e?new Mt(Object.assign(Object.assign({},e),{keySet:r,heartbeat:o})):new Pt(Object.assign(Object.assign({},e),{keySet:r,uuid:i})),this.subscriptionManager&&this.subscriptionManager.setState(e),t?this.sendRequest(a,t):this.sendRequest(a)}))}presence(e){var t;null===(t=this.subscriptionManager)||void 0===t||t.changePresence(e)}heartbeat(e,t){return i(this,void 0,void 0,(function*(){const s=new Mt(Object.assign(Object.assign({},e),{keySet:this._configuration.keySet}));return t?this.sendRequest(s,t):this.sendRequest(s)}))}join(e){var t;null===(t=this.presenceEventEngine)||void 0===t||t.join(e)}leave(e){var t;null===(t=this.presenceEventEngine)||void 0===t||t.leave(e)}leaveAll(){var e;null===(e=this.presenceEventEngine)||void 0===e||e.leaveAll()}grantToken(e,t){return i(this,void 0,void 0,(function*(){const s=new Wt(Object.assign(Object.assign({},e),{keySet:this._configuration.keySet}));return t?this.sendRequest(s,t):this.sendRequest(s)}))}revokeToken(e,t){return i(this,void 0,void 0,(function*(){const s=new Vt(Object.assign(Object.assign({},e),{keySet:this._configuration.keySet}));return t?this.sendRequest(s,t):this.sendRequest(s)}))}get token(){return this.tokenManager.getToken()}getToken(){return this.token}set token(e){this.tokenManager.setToken(e)}setToken(e){this.token=e}parseToken(e){return this.tokenManager.parseToken(e)}grant(e,t){return i(this,void 0,void 0,(function*(){const s=new Jt(Object.assign(Object.assign({},e),{keySet:this._configuration.keySet}));return t?this.sendRequest(s,t):this.sendRequest(s)}))}audit(e,t){return i(this,void 0,void 0,(function*(){const s=new Yt(Object.assign(Object.assign({},e),{keySet:this._configuration.keySet}));return t?this.sendRequest(s,t):this.sendRequest(s)}))}get objects(){return this._objects}fetchUsers(e,t){return i(this,void 0,void 0,(function*(){return this.objects._getAllUUIDMetadata(e,t)}))}fetchUser(e,t){return i(this,void 0,void 0,(function*(){return this.objects._getUUIDMetadata(e,t)}))}createUser(e,t){return i(this,void 0,void 0,(function*(){return this.objects._setUUIDMetadata(e,t)}))}updateUser(e,t){return i(this,void 0,void 0,(function*(){return this.objects._setUUIDMetadata(e,t)}))}removeUser(e,t){return i(this,void 0,void 0,(function*(){return this.objects._removeUUIDMetadata(e,t)}))}fetchSpaces(e,t){return i(this,void 0,void 0,(function*(){return this.objects._getAllChannelMetadata(e,t)}))}fetchSpace(e,t){return i(this,void 0,void 0,(function*(){return this.objects._getChannelMetadata(e,t)}))}createSpace(e,t){return i(this,void 0,void 0,(function*(){return this.objects._setChannelMetadata(e,t)}))}updateSpace(e,t){return i(this,void 0,void 0,(function*(){return this.objects._setChannelMetadata(e,t)}))}removeSpace(e,t){return i(this,void 0,void 0,(function*(){return this.objects._removeChannelMetadata(e,t)}))}fetchMemberships(e,t){return i(this,void 0,void 0,(function*(){return this.objects.fetchMemberships(e,t)}))}addMemberships(e,t){return i(this,void 0,void 0,(function*(){return this.objects.addMemberships(e,t)}))}updateMemberships(e,t){return i(this,void 0,void 0,(function*(){return this.objects.addMemberships(e,t)}))}removeMemberships(e,t){return i(this,void 0,void 0,(function*(){var s,n,r;if("spaceId"in e){const r=e,i={channel:null!==(s=r.spaceId)&&void 0!==s?s:r.channel,uuids:null!==(n=r.userIds)&&void 0!==n?n:r.uuids,limit:0};return t?this.objects.removeChannelMembers(i,t):this.objects.removeChannelMembers(i)}const i=e,o={uuid:i.userId,channels:null!==(r=i.spaceIds)&&void 0!==r?r:i.channels,limit:0};return t?this.objects.removeMemberships(o,t):this.objects.removeMemberships(o)}))}get channelGroups(){return this._channelGroups}get push(){return this._push}sendFile(e,t){return i(this,void 0,void 0,(function*(){if(!this._configuration.PubNubFile)throw new Error("Validation failed: 'PubNubFile' not configured or file upload not supported by the platform.");const s=new zt(Object.assign(Object.assign({},e),{keySet:this._configuration.keySet,PubNubFile:this._configuration.PubNubFile,fileUploadPublishRetryLimit:this._configuration.fileUploadPublishRetryLimit,file:e.file,sendRequest:this.sendRequest.bind(this),publishFile:this.publishFile.bind(this),crypto:this._configuration.getCryptoModule(),cryptography:this.cryptography?this.cryptography:void 0})),n={error:!1,operation:re.PNPublishFileOperation,category:h.PNAcknowledgmentCategory,statusCode:0};return s.process().then((e=>(n.statusCode=e.status,t?t(n,e):e))).catch((e=>{let s;throw e instanceof d?s=e.status:e instanceof _&&(s=e.toStatus(n.operation)),t&&s&&t(s,null),new d("REST API request processing error, check status for details",s)}))}))}publishFile(e,t){return i(this,void 0,void 0,(function*(){if(!this._configuration.PubNubFile)throw new Error("Validation failed: 'PubNubFile' not configured or file upload not supported by the platform.");const s=new qt(Object.assign(Object.assign({},e),{keySet:this._configuration.keySet,crypto:this._configuration.getCryptoModule()}));return t?this.sendRequest(s,t):this.sendRequest(s)}))}listFiles(e,t){return i(this,void 0,void 0,(function*(){const s=new Lt(Object.assign(Object.assign({},e),{keySet:this._configuration.keySet}));return t?this.sendRequest(s,t):this.sendRequest(s)}))}getFileUrl(e){var t;const s=this.transport.request(new Gt(Object.assign(Object.assign({},e),{keySet:this._configuration.keySet})).request()),n=null!==(t=s.queryParameters)&&void 0!==t?t:{},r=Object.keys(n).map((e=>{const t=n[e];return Array.isArray(t)?t.map((t=>`${e}=${I(t)}`)).join("&"):`${e}=${I(t)}`})).join("&");return`${s.origin}${s.path}?${r}`}downloadFile(e,t){return i(this,void 0,void 0,(function*(){if(!this._configuration.PubNubFile)throw new Error("Validation failed: 'PubNubFile' not configured or file upload not supported by the platform.");const s=new As(Object.assign(Object.assign({},e),{keySet:this._configuration.keySet,PubNubFile:this._configuration.PubNubFile,cryptography:this.cryptography?this.cryptography:void 0,crypto:this._configuration.getCryptoModule()}));return t?this.sendRequest(s,t):yield this.sendRequest(s)}))}deleteFile(e,t){return i(this,void 0,void 0,(function*(){const s=new $t(Object.assign(Object.assign({},e),{keySet:this._configuration.keySet}));return t?this.sendRequest(s,t):this.sendRequest(s)}))}time(e){return i(this,void 0,void 0,(function*(){const t=new _s;return e?this.sendRequest(t,e):this.sendRequest(t)}))}encrypt(e,t){const s=this._configuration.getCryptoModule();if(!t&&s&&"string"==typeof e){const t=s.encrypt(e);return"string"==typeof t?t:u(t)}if(!this.crypto)throw new Error("Encryption error: cypher key not set");return this.crypto.encrypt(e,t)}decrypt(e,t){const s=this._configuration.getCryptoModule();if(!t&&s){const t=s.decrypt(e);return t instanceof ArrayBuffer?JSON.parse((new TextDecoder).decode(t)):t}if(!this.crypto)throw new Error("Decryption error: cypher key not set");return this.crypto.decrypt(e,t)}encryptFile(e,t){return i(this,void 0,void 0,(function*(){var s;if("string"!=typeof e&&(t=e),!t)throw new Error("File encryption error. Source file is missing.");if(!this._configuration.PubNubFile)throw new Error("File encryption error. File constructor not configured.");if("string"!=typeof e&&!this._configuration.getCryptoModule())throw new Error("File encryption error. Crypto module not configured.");if("string"==typeof e){if(!this.cryptography)throw new Error("File encryption error. File encryption not available");return this.cryptography.encryptFile(e,t,this._configuration.PubNubFile)}return null===(s=this._configuration.getCryptoModule())||void 0===s?void 0:s.encryptFile(t,this._configuration.PubNubFile)}))}decryptFile(e,t){return i(this,void 0,void 0,(function*(){var s;if("string"!=typeof e&&(t=e),!t)throw new Error("File encryption error. Source file is missing.");if(!this._configuration.PubNubFile)throw new Error("File decryption error. File constructor not configured.");if("string"==typeof e&&!this._configuration.getCryptoModule())throw new Error("File decryption error. Crypto module not configured.");if("string"==typeof e){if(!this.cryptography)throw new Error("File decryption error. File decryption not available");return this.cryptography.decryptFile(e,t,this._configuration.PubNubFile)}return null===(s=this._configuration.getCryptoModule())||void 0===s?void 0:s.decryptFile(t,this._configuration.PubNubFile)}))}}Is.decoder=new TextDecoder,Is.OPERATIONS=re,Is.CATEGORIES=h,Is.ExponentialRetryPolicy=Le.ExponentialRetryPolicy,Is.LinearRetryPolicy=Le.LinearRetryPolicy;class Rs{constructor(e,t){this.decode=e,this.base64ToBinary=t}decodeToken(e){let t="";e.length%4==3?t="=":e.length%4==2&&(t="==");const s=e.replace(/-/gi,"+").replace(/_/gi,"/")+t,n=this.decode(this.base64ToBinary(s));return"object"==typeof n?n:void 0}}class Us extends Is{constructor(e){var t;const s=D(e),r=Object.assign(Object.assign({},s),{sdkFamily:"Web",PubNubFile:a}),i=$(r,(e=>{if(e.cipherKey)return new P({default:new N(Object.assign({},e)),cryptors:[new S({cipherKey:e.cipherKey})]})})),o=new B(new Rs((e=>x(n.decode(e))),c));let u;(i.getCipherKey()||i.secretKey)&&(u=new E({secretKey:i.secretKey,cipherKey:i.getCipherKey(),useRandomIVs:i.getUseRandomIVs(),customEncrypt:i.getCustomEncrypt(),customDecrypt:i.getCustomDecrypt()}));let l=new F(i.keepAlive,i.logVerbosity);s.subscriptionWorkerUrl&&(l=new A({clientIdentifier:i._instanceId,subscriptionKey:i.subscribeKey,userId:i.getUserId(),workerUrl:s.subscriptionWorkerUrl,sdkVersion:i.getVersion(),logVerbosity:i.logVerbosity,workerLogVerbosity:r.subscriptionWorkerLogVerbosity,transport:l}));super({configuration:i,transport:new V({clientConfiguration:i,tokenManager:o,transport:l}),cryptography:new C,tokenManager:o,crypto:u}),(null===(t=e.listenToBrowserNetworkEvents)||void 0===t||t)&&(window.addEventListener("offline",(()=>{this.networkDownDetected()})),window.addEventListener("online",(()=>{this.networkUpDetected()})))}networkDownDetected(){this.listenerManager.announceNetworkDown(),this._configuration.restore?this.disconnect():this.destroy(!0)}networkUpDetected(){this.listenerManager.announceNetworkUp(),this.reconnect()}}return Us.CryptoModule=P,Us})); +/*! lil-uuid - v0.1 - MIT License - https://github.com/lil-js/uuid */!function(e,t){!function(e){var t="0.1.0",s={3:/^[0-9A-F]{8}-[0-9A-F]{4}-3[0-9A-F]{3}-[0-9A-F]{4}-[0-9A-F]{12}$/i,4:/^[0-9A-F]{8}-[0-9A-F]{4}-4[0-9A-F]{3}-[89AB][0-9A-F]{3}-[0-9A-F]{12}$/i,5:/^[0-9A-F]{8}-[0-9A-F]{4}-5[0-9A-F]{3}-[89AB][0-9A-F]{3}-[0-9A-F]{12}$/i,all:/^[0-9A-F]{8}-[0-9A-F]{4}-[0-9A-F]{4}-[0-9A-F]{4}-[0-9A-F]{12}$/i};function n(){var e,t,s="";for(e=0;e<32;e++)t=16*Math.random()|0,8!==e&&12!==e&&16!==e&&20!==e||(s+="-"),s+=(12===e?4:16===e?3&t|8:t).toString(16);return s}function r(e,t){var n=s[t||"all"];return n&&n.test(e)||!1}n.isUUID=r,n.VERSION=t,e.uuid=n,e.isUUID=r}(t),null!==e&&(e.exports=t.uuid)}(K,K.exports);var q=t(K.exports),G={createUUID:()=>q.uuid?q.uuid():q()};const $=(e,t)=>{var s,n,r;null===(s=e.retryConfiguration)||void 0===s||s.validate(),null!==(n=e.useRandomIVs)&&void 0!==n||(e.useRandomIVs=true),e.origin=L(null!==(r=e.ssl)&&void 0!==r&&r,e.origin);const i=e.cryptoModule;i&&delete e.cryptoModule;const o=Object.assign(Object.assign({},e),{_pnsdkSuffix:{},_instanceId:`pn-${G.createUUID()}`,_cryptoModule:void 0,_cipherKey:void 0,_setupCryptoModule:t,get instanceId(){if(this.useInstanceId)return this._instanceId},getUserId(){return this.userId},setUserId(e){if(!e||"string"!=typeof e||0===e.trim().length)throw new Error("Missing or invalid userId parameter. Provide a valid string userId");this.userId=e},getAuthKey(){return this.authKey},setAuthKey(e){this.authKey=e},getFilterExpression(){return this.filterExpression},setFilterExpression(e){this.filterExpression=e},getCipherKey(){return this._cipherKey},setCipherKey(t){this._cipherKey=t,t||!this._cryptoModule?t&&this._setupCryptoModule&&(this._cryptoModule=this._setupCryptoModule({cipherKey:t,useRandomIVs:e.useRandomIVs,customEncrypt:this.getCustomEncrypt(),customDecrypt:this.getCustomDecrypt()})):this._cryptoModule=void 0},getCryptoModule(){return this._cryptoModule},getUseRandomIVs:()=>e.useRandomIVs,setPresenceTimeout(e){this.heartbeatInterval=e/2-1,this.presenceTimeout=e},getPresenceTimeout(){return this.presenceTimeout},getHeartbeatInterval(){return this.heartbeatInterval},setHeartbeatInterval(e){this.heartbeatInterval=e},getTransactionTimeout(){return this.transactionalRequestTimeout},getSubscribeTimeout(){return this.subscribeRequestTimeout},get PubNubFile(){return e.PubNubFile},get version(){return"8.1.0"},getVersion(){return this.version},_addPnsdkSuffix(e,t){this._pnsdkSuffix[e]=`${t}`},_getPnsdkSuffix(e){const t=Object.values(this._pnsdkSuffix).join(e);return t.length>0?e+t:""},getUUID(){return this.getUserId()},setUUID(e){this.setUserId(e)},getCustomEncrypt:()=>e.customEncrypt,getCustomDecrypt:()=>e.customDecrypt});return e.cipherKey?o.setCipherKey(e.cipherKey):i&&(o._cryptoModule=i),o},L=(e,t)=>{const s=e?"https://":"http://";return"string"==typeof t?`${s}${t}`:`${s}${t[Math.floor(Math.random()*t.length)]}`};class B{constructor(e){this.cbor=e}setToken(e){e&&e.length>0?this.token=e:this.token=void 0}getToken(){return this.token}parseToken(e){const t=this.cbor.decodeToken(e);if(void 0!==t){const e=t.res.uuid?Object.keys(t.res.uuid):[],s=Object.keys(t.res.chan),n=Object.keys(t.res.grp),r=t.pat.uuid?Object.keys(t.pat.uuid):[],i=Object.keys(t.pat.chan),o=Object.keys(t.pat.grp),a={version:t.v,timestamp:t.t,ttl:t.ttl,authorized_uuid:t.uuid,signature:t.sig},c=e.length>0,u=s.length>0,l=n.length>0;if(c||u||l){if(a.resources={},c){const s=a.resources.uuids={};e.forEach((e=>s[e]=this.extractPermissions(t.res.uuid[e])))}if(u){const e=a.resources.channels={};s.forEach((s=>e[s]=this.extractPermissions(t.res.chan[s])))}if(l){const e=a.resources.groups={};n.forEach((s=>e[s]=this.extractPermissions(t.res.grp[s])))}}const h=r.length>0,d=i.length>0,p=o.length>0;if(h||d||p){if(a.patterns={},h){const e=a.patterns.uuids={};r.forEach((s=>e[s]=this.extractPermissions(t.pat.uuid[s])))}if(d){const e=a.patterns.channels={};i.forEach((s=>e[s]=this.extractPermissions(t.pat.chan[s])))}if(p){const e=a.patterns.groups={};o.forEach((s=>e[s]=this.extractPermissions(t.pat.grp[s])))}}return t.meta&&Object.keys(t.meta).length>0&&(a.meta=t.meta),a}}extractPermissions(e){const t={read:!1,write:!1,manage:!1,delete:!1,get:!1,update:!1,join:!1};return 128&~e||(t.join=!0),64&~e||(t.update=!0),32&~e||(t.get=!0),8&~e||(t.delete=!0),4&~e||(t.manage=!0),2&~e||(t.write=!0),1&~e||(t.read=!0),t}}var H;!function(e){e.GET="GET",e.POST="POST",e.PATCH="PATCH",e.DELETE="DELETE",e.LOCAL="LOCAL"}(H||(H={}));class z{constructor(e,t,s){this.publishKey=e,this.secretKey=t,this.hasher=s}signature(e){const t=e.path.startsWith("/publish")?H.GET:e.method;let s=`${t}\n${this.publishKey}\n${e.path}\n${this.queryParameters(e.queryParameters)}\n`;if(t===H.POST||t===H.PATCH){const t=e.body;let n;t&&t instanceof ArrayBuffer?n=z.textDecoder.decode(t):t&&"object"!=typeof t&&(n=t),n&&(s+=n)}return`v2.${this.hasher(s,this.secretKey)}`.replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}queryParameters(e){return Object.keys(e).sort().map((t=>{const s=e[t];return Array.isArray(s)?s.sort().map((e=>`${t}=${I(e)}`)).join("&"):`${t}=${I(s)}`})).join("&")}}z.textDecoder=new TextDecoder("utf-8");class V{constructor(e){this.configuration=e;const{clientConfiguration:{keySet:t},shaHMAC:s}=e;t.secretKey&&s&&(this.signatureGenerator=new z(t.publishKey,t.secretKey,s))}makeSendable(e){return this.configuration.transport.makeSendable(this.request(e))}request(e){var t;const{clientConfiguration:s}=this.configuration;return(e=this.configuration.transport.request(e)).queryParameters||(e.queryParameters={}),s.useInstanceId&&(e.queryParameters.instanceid=s.instanceId),e.queryParameters.uuid||(e.queryParameters.uuid=s.userId),s.useRequestId&&(e.queryParameters.requestid=e.identifier),e.queryParameters.pnsdk=this.generatePNSDK(),null!==(t=e.origin)&&void 0!==t||(e.origin=s.origin),this.authenticateRequest(e),this.signRequest(e),e}authenticateRequest(e){var t;if(e.path.startsWith("/v2/auth/")||e.path.startsWith("/v3/pam/")||e.path.startsWith("/time"))return;const{clientConfiguration:s,tokenManager:n}=this.configuration,r=null!==(t=n.getToken())&&void 0!==t?t:s.authKey;r&&(e.queryParameters.auth=r)}signRequest(e){this.signatureGenerator&&!e.path.startsWith("/time")&&(e.queryParameters.timestamp=String(Math.floor((new Date).getTime()/1e3)),e.queryParameters.signature=this.signatureGenerator.signature(e))}generatePNSDK(){const{clientConfiguration:e}=this.configuration;if(e.sdkName)return e.sdkName;let t=`PubNub-JS-${e.sdkFamily}`;e.partnerId&&(t+=`-${e.partnerId}`),t+=`/${e.getVersion()}`;const s=e._getPnsdkSuffix(" ");return s.length>0&&(t+=s),t}}class W{constructor(){this.listeners=[]}addListener(e){this.listeners.includes(e)||this.listeners.push(e)}removeListener(e){this.listeners=this.listeners.filter((t=>t!==e))}removeAllListeners(){this.listeners=[]}announceStatus(e){this.listeners.forEach((t=>{t.status&&t.status(e)}))}announcePresence(e){this.listeners.forEach((t=>{t.presence&&t.presence(e)}))}announceMessage(e){this.listeners.forEach((t=>{t.message&&t.message(e)}))}announceSignal(e){this.listeners.forEach((t=>{t.signal&&t.signal(e)}))}announceMessageAction(e){this.listeners.forEach((t=>{t.messageAction&&t.messageAction(e)}))}announceFile(e){this.listeners.forEach((t=>{t.file&&t.file(e)}))}announceObjects(e){this.listeners.forEach((t=>{t.objects&&t.objects(e)}))}announceNetworkUp(){this.listeners.forEach((e=>{e.status&&e.status({category:h.PNNetworkUpCategory})}))}announceNetworkDown(){this.listeners.forEach((e=>{e.status&&e.status({category:h.PNNetworkDownCategory})}))}announceUser(e){this.listeners.forEach((t=>{t.user&&t.user(e)}))}announceSpace(e){this.listeners.forEach((t=>{t.space&&t.space(e)}))}announceMembership(e){this.listeners.forEach((t=>{t.membership&&t.membership(e)}))}}class J{constructor(e){this.time=e}onReconnect(e){this.callback=e}startPolling(){this.timeTimer=setInterval((()=>this.callTime()),3e3)}stopPolling(){this.timeTimer&&clearInterval(this.timeTimer),this.timeTimer=null}callTime(){this.time((e=>{e.error||(this.stopPolling(),this.callback&&this.callback())}))}}class Q{_config;hashHistory;constructor({config:e}){this.hashHistory=[],this._config=e}getKey(e){const t=(e=>{let t=0;if(0===e.length)return t;for(let s=0;s=this._config.maximumCacheSize&&this.hashHistory.shift(),this.hashHistory.push(this.getKey(e))}clearHistory(){this.hashHistory=[]}}class Y{constructor(e,t,s,n,r,i,o){this.configuration=e,this.listenerManager=t,this.eventEmitter=s,this.subscribeCall=n,this.heartbeatCall=r,this.leaveCall=i,this.reconnectionManager=new J(o),this.dedupingManager=new Q({config:this.configuration}),this.heartbeatChannelGroups={},this.heartbeatChannels={},this.presenceChannelGroups={},this.presenceChannels={},this.heartbeatTimer=null,this.presenceState={},this.pendingChannelGroupSubscriptions=new Set,this.pendingChannelSubscriptions=new Set,this.channelGroups={},this.channels={},this.currentTimetoken="0",this.lastTimetoken="0",this.storedTimetoken=null,this.subscriptionStatusAnnounced=!1,this.isOnline=!0}get subscribedChannels(){return Object.keys(this.channels)}get subscribedChannelGroups(){return Object.keys(this.channelGroups)}get abort(){return this._subscribeAbort}set abort(e){this._subscribeAbort=e}disconnect(){this.stopSubscribeLoop(),this.stopHeartbeatTimer(),this.reconnectionManager.stopPolling()}reconnect(){this.startSubscribeLoop(),this.startHeartbeatTimer()}subscribe(e){const{channels:t,channelGroups:s,timetoken:n,withPresence:r=!1,withHeartbeats:i=!1}=e;n&&(this.lastTimetoken=this.currentTimetoken,this.currentTimetoken=n),"0"!==this.currentTimetoken&&0!==this.currentTimetoken&&(this.storedTimetoken=this.currentTimetoken,this.currentTimetoken=0),null==t||t.forEach((e=>{this.pendingChannelSubscriptions.add(e),this.channels[e]={},r&&(this.presenceChannels[e]={}),(i||this.configuration.getHeartbeatInterval())&&(this.heartbeatChannels[e]={})})),null==s||s.forEach((e=>{this.pendingChannelGroupSubscriptions.add(e),this.channelGroups[e]={},r&&(this.presenceChannelGroups[e]={}),(i||this.configuration.getHeartbeatInterval())&&(this.heartbeatChannelGroups[e]={})})),this.subscriptionStatusAnnounced=!1,this.reconnect()}unsubscribe(e,t){let{channels:s,channelGroups:n}=e;const i=new Set,o=new Set;null==s||s.forEach((e=>{e in this.channels&&(delete this.channels[e],o.add(e),e in this.heartbeatChannels&&delete this.heartbeatChannels[e]),e in this.presenceState&&delete this.presenceState[e],e in this.presenceChannels&&(delete this.presenceChannels[e],o.add(e))})),null==n||n.forEach((e=>{e in this.channelGroups&&(delete this.channelGroups[e],i.add(e),e in this.heartbeatChannelGroups&&delete this.heartbeatChannelGroups[e]),e in this.presenceState&&delete this.presenceState[e],e in this.presenceChannelGroups&&(delete this.presenceChannelGroups[e],i.add(e))})),0===o.size&&0===i.size||(!1!==this.configuration.suppressLeaveEvents||t||(n=Array.from(i),s=Array.from(o),this.leaveCall({channels:s,channelGroups:n},(e=>{const{error:t}=e,i=r(e,["error"]);let o;t&&(e.errorData&&"object"==typeof e.errorData&&"message"in e.errorData&&"string"==typeof e.errorData.message?o=e.errorData.message:"message"in e&&"string"==typeof e.message&&(o=e.message)),this.listenerManager.announceStatus(Object.assign(Object.assign({},i),{error:null!=o&&o,affectedChannels:s,affectedChannelGroups:n,currentTimetoken:this.currentTimetoken,lastTimetoken:this.lastTimetoken}))}))),0===Object.keys(this.channels).length&&0===Object.keys(this.presenceChannels).length&&0===Object.keys(this.channelGroups).length&&0===Object.keys(this.presenceChannelGroups).length&&(this.lastTimetoken=0,this.currentTimetoken=0,this.storedTimetoken=null,this.region=null,this.reconnectionManager.stopPolling()),this.reconnect())}unsubscribeAll(e){this.unsubscribe({channels:this.subscribedChannels,channelGroups:this.subscribedChannelGroups},e)}startSubscribeLoop(){this.stopSubscribeLoop();const e=[...Object.keys(this.channelGroups)],t=[...Object.keys(this.channels)];Object.keys(this.presenceChannelGroups).forEach((t=>e.push(`${t}-pnpres`))),Object.keys(this.presenceChannels).forEach((e=>t.push(`${e}-pnpres`))),0===t.length&&0===e.length||this.subscribeCall({channels:t,channelGroups:e,state:this.presenceState,heartbeat:this.configuration.getPresenceTimeout(),timetoken:this.currentTimetoken,region:null!==this.region?this.region:void 0,filterExpression:this.configuration.filterExpression},((e,t)=>{this.processSubscribeResponse(e,t)}))}stopSubscribeLoop(){this._subscribeAbort&&(this._subscribeAbort(),this._subscribeAbort=null)}processSubscribeResponse(e,t){if(e.error){if("object"==typeof e.errorData&&"name"in e.errorData&&"AbortError"===e.errorData.name||e.category===h.PNCancelledCategory)return;return void(e.category===h.PNTimeoutCategory?this.startSubscribeLoop():e.category===h.PNNetworkIssuesCategory?(this.disconnect(),e.error&&this.configuration.autoNetworkDetection&&this.isOnline&&(this.isOnline=!1,this.listenerManager.announceNetworkDown()),this.reconnectionManager.onReconnect((()=>{this.configuration.autoNetworkDetection&&!this.isOnline&&(this.isOnline=!0,this.listenerManager.announceNetworkUp()),this.reconnect(),this.subscriptionStatusAnnounced=!0;const t={category:h.PNReconnectedCategory,operation:e.operation,lastTimetoken:this.lastTimetoken,currentTimetoken:this.currentTimetoken};this.listenerManager.announceStatus(t)})),this.reconnectionManager.startPolling(),this.listenerManager.announceStatus(e)):e.category===h.PNBadRequestCategory?(this.stopHeartbeatTimer(),this.listenerManager.announceStatus(e)):this.listenerManager.announceStatus(e))}if(this.storedTimetoken?(this.currentTimetoken=this.storedTimetoken,this.storedTimetoken=null):(this.lastTimetoken=this.currentTimetoken,this.currentTimetoken=t.cursor.timetoken),!this.subscriptionStatusAnnounced){const t={category:h.PNConnectedCategory,operation:e.operation,affectedChannels:Array.from(this.pendingChannelSubscriptions),subscribedChannels:this.subscribedChannels,affectedChannelGroups:Array.from(this.pendingChannelGroupSubscriptions),lastTimetoken:this.lastTimetoken,currentTimetoken:this.currentTimetoken};this.subscriptionStatusAnnounced=!0,this.listenerManager.announceStatus(t),this.pendingChannelGroupSubscriptions.clear(),this.pendingChannelSubscriptions.clear()}const{messages:s}=t,{requestMessageCountThreshold:n,dedupeOnSubscribe:r}=this.configuration;n&&s.length>=n&&this.listenerManager.announceStatus({category:h.PNRequestMessageCountExceededCategory,operation:e.operation});try{s.forEach((e=>{if(r){if(this.dedupingManager.isDuplicate(e.data))return;this.dedupingManager.addEntry(e.data)}this.eventEmitter.emitEvent(e)}))}catch(e){const t={error:!0,category:h.PNUnknownCategory,errorData:e,statusCode:0};this.listenerManager.announceStatus(t)}this.region=t.cursor.region,this.startSubscribeLoop()}setState(e){const{state:t,channels:s,channelGroups:n}=e;null==s||s.forEach((e=>e in this.channels&&(this.presenceState[e]=t))),null==n||n.forEach((e=>e in this.channelGroups&&(this.presenceState[e]=t)))}changePresence(e){const{connected:t,channels:s,channelGroups:n}=e;t?(null==s||s.forEach((e=>this.heartbeatChannels[e]={})),null==n||n.forEach((e=>this.heartbeatChannelGroups[e]={}))):(null==s||s.forEach((e=>{e in this.heartbeatChannels&&delete this.heartbeatChannels[e]})),null==n||n.forEach((e=>{e in this.heartbeatChannelGroups&&delete this.heartbeatChannelGroups[e]})),!1===this.configuration.suppressLeaveEvents&&this.leaveCall({channels:s,channelGroups:n},(e=>this.listenerManager.announceStatus(e)))),this.reconnect()}startHeartbeatTimer(){this.stopHeartbeatTimer();const e=this.configuration.getHeartbeatInterval();e&&0!==e&&(this.sendHeartbeat(),this.heartbeatTimer=setInterval((()=>this.sendHeartbeat()),1e3*e))}stopHeartbeatTimer(){this.heartbeatTimer&&(clearInterval(this.heartbeatTimer),this.heartbeatTimer=null)}sendHeartbeat(){const e=Object.keys(this.heartbeatChannelGroups),t=Object.keys(this.heartbeatChannels);0===t.length&&0===e.length||this.heartbeatCall({channels:t,channelGroups:e,heartbeat:this.configuration.getPresenceTimeout(),state:this.presenceState},(e=>{e.error&&this.configuration.announceFailedHeartbeats&&this.listenerManager.announceStatus(e),e.error&&this.configuration.autoNetworkDetection&&this.isOnline&&(this.isOnline=!1,this.disconnect(),this.listenerManager.announceNetworkDown(),this.reconnect()),!e.error&&this.configuration.announceSuccessfulHeartbeats&&this.listenerManager.announceStatus(e)}))}}class X{constructor(e,t,s){this._payload=e,this.setDefaultPayloadStructure(),this.title=t,this.body=s}get payload(){return this._payload}set title(e){this._title=e}set subtitle(e){this._subtitle=e}set body(e){this._body=e}set badge(e){this._badge=e}set sound(e){this._sound=e}setDefaultPayloadStructure(){}toObject(){return{}}}class Z extends X{constructor(){super(...arguments),this._apnsPushType="apns",this._isSilent=!1}get payload(){return this._payload}set configurations(e){e&&e.length&&(this._configurations=e)}get notification(){return this.payload.aps}get title(){return this._title}set title(e){e&&e.length&&(this.payload.aps.alert.title=e,this._title=e)}get subtitle(){return this._subtitle}set subtitle(e){e&&e.length&&(this.payload.aps.alert.subtitle=e,this._subtitle=e)}get body(){return this._body}set body(e){e&&e.length&&(this.payload.aps.alert.body=e,this._body=e)}get badge(){return this._badge}set badge(e){null!=e&&(this.payload.aps.badge=e,this._badge=e)}get sound(){return this._sound}set sound(e){e&&e.length&&(this.payload.aps.sound=e,this._sound=e)}set silent(e){this._isSilent=e}setDefaultPayloadStructure(){this.payload.aps={alert:{}}}toObject(){const e=Object.assign({},this.payload),{aps:t}=e;let{alert:s}=t;if(this._isSilent&&(t["content-available"]=1),"apns2"===this._apnsPushType){if(!this._configurations||!this._configurations.length)throw new ReferenceError("APNS2 configuration is missing");const t=[];this._configurations.forEach((e=>{t.push(this.objectFromAPNS2Configuration(e))})),t.length&&(e.pn_push=t)}return s&&Object.keys(s).length||delete t.alert,this._isSilent&&(delete t.alert,delete t.badge,delete t.sound,s={}),this._isSilent||s&&Object.keys(s).length?e:null}objectFromAPNS2Configuration(e){if(!e.targets||!e.targets.length)throw new ReferenceError("At least one APNS2 target should be provided");const{collapseId:t,expirationDate:s}=e,n={auth_method:"token",targets:e.targets.map((e=>this.objectFromAPNSTarget(e))),version:"v2"};return t&&t.length&&(n.collapse_id=t),s&&(n.expiration=s.toISOString()),n}objectFromAPNSTarget(e){if(!e.topic||!e.topic.length)throw new TypeError("Target 'topic' undefined.");const{topic:t,environment:s="development",excludedDevices:n=[]}=e,r={topic:t,environment:s};return n.length&&(r.excluded_devices=n),r}}class ee extends X{get payload(){return this._payload}get notification(){return this.payload.notification}get data(){return this.payload.data}get title(){return this._title}set title(e){e&&e.length&&(this.payload.notification.title=e,this._title=e)}get body(){return this._body}set body(e){e&&e.length&&(this.payload.notification.body=e,this._body=e)}get sound(){return this._sound}set sound(e){e&&e.length&&(this.payload.notification.sound=e,this._sound=e)}get icon(){return this._icon}set icon(e){e&&e.length&&(this.payload.notification.icon=e,this._icon=e)}get tag(){return this._tag}set tag(e){e&&e.length&&(this.payload.notification.tag=e,this._tag=e)}set silent(e){this._isSilent=e}setDefaultPayloadStructure(){this.payload.notification={},this.payload.data={}}toObject(){let e=Object.assign({},this.payload.data),t=null;const s={};if(Object.keys(this.payload).length>2){const t=r(this.payload,["notification","data"]);e=Object.assign(Object.assign({},e),t)}return this._isSilent?e.notification=this.payload.notification:t=this.payload.notification,Object.keys(e).length&&(s.data=e),t&&Object.keys(t).length&&(s.notification=t),Object.keys(s).length?s:null}}class te{constructor(e,t){this._payload={apns:{},fcm:{}},this._title=e,this._body=t,this.apns=new Z(this._payload.apns,e,t),this.fcm=new ee(this._payload.fcm,e,t)}set debugging(e){this._debugging=e}get title(){return this._title}get subtitle(){return this._subtitle}set subtitle(e){this._subtitle=e,this.apns.subtitle=e,this.fcm.subtitle=e}get body(){return this._body}get badge(){return this._badge}set badge(e){this._badge=e,this.apns.badge=e,this.fcm.badge=e}get sound(){return this._sound}set sound(e){this._sound=e,this.apns.sound=e,this.fcm.sound=e}buildPayload(e){const t={};if(e.includes("apns")||e.includes("apns2")){this.apns._apnsPushType=e.includes("apns")?"apns":"apns2";const s=this.apns.toObject();s&&Object.keys(s).length&&(t.pn_apns=s)}if(e.includes("fcm")){const e=this.fcm.toObject();e&&Object.keys(e).length&&(t.pn_gcm=e)}return Object.keys(t).length&&this._debugging&&(t.pn_debug=!0),t}}class se{constructor(e){this.params=e,this.requestIdentifier=G.createUUID(),this._cancellationController=null}get cancellationController(){return this._cancellationController}set cancellationController(e){this._cancellationController=e}abort(){this&&this.cancellationController&&this.cancellationController.abort()}operation(){throw Error("Should be implemented by subclass.")}validate(){}parse(e){return i(this,void 0,void 0,(function*(){throw Error("Should be implemented by subclass.")}))}request(){var e,t,s,n;const r={method:null!==(t=null===(e=this.params)||void 0===e?void 0:e.method)&&void 0!==t?t:H.GET,path:this.path,queryParameters:this.queryParameters,cancellable:null!==(n=null===(s=this.params)||void 0===s?void 0:s.cancellable)&&void 0!==n&&n,timeout:1e4,identifier:this.requestIdentifier},i=this.headers;if(i&&(r.headers=i),r.method===H.POST||r.method===H.PATCH){const[e,t]=[this.body,this.formData];t&&(r.formData=t),e&&(r.body=e)}return r}get headers(){}get path(){throw Error("`path` getter should be implemented by subclass.")}get queryParameters(){return{}}get formData(){}get body(){}deserializeResponse(e){const t=e.headers["content-type"];if(!t||-1===t.indexOf("javascript")&&-1===t.indexOf("json"))return;const s=se.decoder.decode(e.body);try{return JSON.parse(s)}catch(e){return void console.error("Error parsing JSON response:",e)}}}var ne;se.decoder=new TextDecoder,function(e){e.PNPublishOperation="PNPublishOperation",e.PNSignalOperation="PNSignalOperation",e.PNSubscribeOperation="PNSubscribeOperation",e.PNUnsubscribeOperation="PNUnsubscribeOperation",e.PNWhereNowOperation="PNWhereNowOperation",e.PNHereNowOperation="PNHereNowOperation",e.PNGlobalHereNowOperation="PNGlobalHereNowOperation",e.PNSetStateOperation="PNSetStateOperation",e.PNGetStateOperation="PNGetStateOperation",e.PNHeartbeatOperation="PNHeartbeatOperation",e.PNAddMessageActionOperation="PNAddActionOperation",e.PNRemoveMessageActionOperation="PNRemoveMessageActionOperation",e.PNGetMessageActionsOperation="PNGetMessageActionsOperation",e.PNTimeOperation="PNTimeOperation",e.PNHistoryOperation="PNHistoryOperation",e.PNDeleteMessagesOperation="PNDeleteMessagesOperation",e.PNFetchMessagesOperation="PNFetchMessagesOperation",e.PNMessageCounts="PNMessageCountsOperation",e.PNGetAllUUIDMetadataOperation="PNGetAllUUIDMetadataOperation",e.PNGetUUIDMetadataOperation="PNGetUUIDMetadataOperation",e.PNSetUUIDMetadataOperation="PNSetUUIDMetadataOperation",e.PNRemoveUUIDMetadataOperation="PNRemoveUUIDMetadataOperation",e.PNGetAllChannelMetadataOperation="PNGetAllChannelMetadataOperation",e.PNGetChannelMetadataOperation="PNGetChannelMetadataOperation",e.PNSetChannelMetadataOperation="PNSetChannelMetadataOperation",e.PNRemoveChannelMetadataOperation="PNRemoveChannelMetadataOperation",e.PNGetMembersOperation="PNGetMembersOperation",e.PNSetMembersOperation="PNSetMembersOperation",e.PNGetMembershipsOperation="PNGetMembershipsOperation",e.PNSetMembershipsOperation="PNSetMembershipsOperation",e.PNListFilesOperation="PNListFilesOperation",e.PNGenerateUploadUrlOperation="PNGenerateUploadUrlOperation",e.PNPublishFileOperation="PNPublishFileOperation",e.PNPublishFileMessageOperation="PNPublishFileMessageOperation",e.PNGetFileUrlOperation="PNGetFileUrlOperation",e.PNDownloadFileOperation="PNDownloadFileOperation",e.PNDeleteFileOperation="PNDeleteFileOperation",e.PNAddPushNotificationEnabledChannelsOperation="PNAddPushNotificationEnabledChannelsOperation",e.PNRemovePushNotificationEnabledChannelsOperation="PNRemovePushNotificationEnabledChannelsOperation",e.PNPushNotificationEnabledChannelsOperation="PNPushNotificationEnabledChannelsOperation",e.PNRemoveAllPushNotificationsOperation="PNRemoveAllPushNotificationsOperation",e.PNChannelGroupsOperation="PNChannelGroupsOperation",e.PNRemoveGroupOperation="PNRemoveGroupOperation",e.PNChannelsForGroupOperation="PNChannelsForGroupOperation",e.PNAddChannelsToGroupOperation="PNAddChannelsToGroupOperation",e.PNRemoveChannelsFromGroupOperation="PNRemoveChannelsFromGroupOperation",e.PNAccessManagerGrant="PNAccessManagerGrant",e.PNAccessManagerGrantToken="PNAccessManagerGrantToken",e.PNAccessManagerAudit="PNAccessManagerAudit",e.PNAccessManagerRevokeToken="PNAccessManagerRevokeToken",e.PNHandshakeOperation="PNHandshakeOperation",e.PNReceiveMessagesOperation="PNReceiveMessagesOperation"}(ne||(ne={}));var re=ne;var ie;!function(e){e[e.Presence=-2]="Presence",e[e.Message=-1]="Message",e[e.Signal=1]="Signal",e[e.AppContext=2]="AppContext",e[e.MessageAction=3]="MessageAction",e[e.Files=4]="Files"}(ie||(ie={}));class oe extends se{constructor(e){var t,s,n,r,i,o;super({cancellable:!0}),this.parameters=e,null!==(t=(r=this.parameters).withPresence)&&void 0!==t||(r.withPresence=false),null!==(s=(i=this.parameters).channelGroups)&&void 0!==s||(i.channelGroups=[]),null!==(n=(o=this.parameters).channels)&&void 0!==n||(o.channels=[])}operation(){return re.PNSubscribeOperation}validate(){const{keySet:{subscribeKey:e},channels:t,channelGroups:s}=this.parameters;return e?t||s?void 0:"`channels` and `channelGroups` both should not be empty":"Missing Subscribe Key"}parse(e){return i(this,void 0,void 0,(function*(){let t;try{const s=se.decoder.decode(e.body);t=JSON.parse(s)}catch(e){console.error("Error parsing JSON response:",e)}if(!t)throw new d("Service response error, check status for details",p("Unable to deserialize service response"));const s=t.m.map((e=>{let{e:t}=e;return null!=t||(t=e.c.endsWith("-pnpres")?ie.Presence:ie.Message),"string"==typeof e.d?t==ie.Message?{type:ie.Message,data:this.messageFromEnvelope(e)}:{type:ie.Files,data:this.fileFromEnvelope(e)}:t==ie.Message?{type:ie.Message,data:this.messageFromEnvelope(e)}:t===ie.Presence?{type:ie.Presence,data:this.presenceEventFromEnvelope(e)}:t==ie.Signal?{type:ie.Signal,data:this.signalFromEnvelope(e)}:t===ie.AppContext?{type:ie.AppContext,data:this.appContextFromEnvelope(e)}:t===ie.MessageAction?{type:ie.MessageAction,data:this.messageActionFromEnvelope(e)}:{type:ie.Files,data:this.fileFromEnvelope(e)}}));return{cursor:{timetoken:t.t.t,region:t.t.r},messages:s}}))}get headers(){return{accept:"text/javascript"}}presenceEventFromEnvelope(e){const{d:t}=e,[s,n]=this.subscriptionChannelFromEnvelope(e),r=s.replace("-pnpres",""),i=null!==n?r:null,o=null!==n?n:r;return"string"!=typeof t&&"data"in t&&(t.state=t.data,delete t.data),Object.assign({channel:r,subscription:n,actualChannel:i,subscribedChannel:o,timetoken:e.p.t},t)}messageFromEnvelope(e){const[t,s]=this.subscriptionChannelFromEnvelope(e),[n,r]=this.decryptedData(e.d),i={channel:t,subscription:s,actualChannel:null!==s?t:null,subscribedChannel:null!==s?s:t,timetoken:e.p.t,publisher:e.i,message:n};return e.u&&(i.userMetadata=e.u),r&&(i.error=r),i}signalFromEnvelope(e){const[t,s]=this.subscriptionChannelFromEnvelope(e),n={channel:t,subscription:s,timetoken:e.p.t,publisher:e.i,message:e.d};return e.u&&(n.userMetadata=e.u),n}messageActionFromEnvelope(e){const[t,s]=this.subscriptionChannelFromEnvelope(e),n=e.d;return{channel:t,subscription:s,timetoken:e.p.t,publisher:e.i,event:n.event,data:Object.assign(Object.assign({},n.data),{uuid:e.i})}}appContextFromEnvelope(e){const[t,s]=this.subscriptionChannelFromEnvelope(e),n=e.d;return{channel:t,subscription:s,timetoken:e.p.t,message:n}}fileFromEnvelope(e){const[t,s]=this.subscriptionChannelFromEnvelope(e),[n,r]=this.decryptedData(e.d);let i=r;const o={channel:t,subscription:s,timetoken:e.p.t,publisher:e.i};return e.u&&(o.userMetadata=e.u),n?"string"==typeof n?null!=i||(i="Unexpected file information payload data type."):(o.message=n.message,n.file&&(o.file={id:n.file.id,name:n.file.name,url:this.parameters.getFileUrl({id:n.file.id,name:n.file.name,channel:t})})):null!=i||(i="File information payload is missing."),i&&(o.error=i),o}subscriptionChannelFromEnvelope(e){return[e.c,void 0===e.b?e.c:e.b]}decryptedData(e){if(!this.parameters.crypto||"string"!=typeof e)return[e,void 0];let t,s;try{const s=this.parameters.crypto.decrypt(e);t=s instanceof ArrayBuffer?JSON.parse(ae.decoder.decode(s)):s}catch(e){t=null,s=`Error while decrypting message content: ${e.message}`}return[null!=t?t:e,s]}}class ae extends oe{get path(){var e;const{keySet:{subscribeKey:t},channels:s}=this.parameters;return`/v2/subscribe/${t}/${R(null!==(e=null==s?void 0:s.sort())&&void 0!==e?e:[],",")}/0`}get queryParameters(){const{channelGroups:e,filterExpression:t,heartbeat:s,state:n,timetoken:r,region:i}=this.parameters,o={};return e&&e.length>0&&(o["channel-group"]=e.sort().join(",")),t&&t.length>0&&(o["filter-expr"]=t),s&&(o.heartbeat=s),n&&Object.keys(n).length>0&&(o.state=JSON.stringify(n)),void 0!==r&&"string"==typeof r?r.length>0&&"0"!==r&&(o.tt=r):void 0!==r&&r>0&&(o.tt=r),i&&(o.tr=i),o}}class ce{constructor(e){this.listenerManager=e,this.channelListenerMap=new Map,this.groupListenerMap=new Map}emitEvent(e){if(e.type===ie.Message)this.listenerManager.announceMessage(e.data),this.announce("message",e.data,e.data.channel,e.data.subscription);else if(e.type===ie.Signal)this.listenerManager.announceSignal(e.data),this.announce("signal",e.data,e.data.channel,e.data.subscription);else if(e.type===ie.Presence)this.listenerManager.announcePresence(e.data),this.announce("presence",e.data,e.data.channel,e.data.subscription);else if(e.type===ie.AppContext){const{data:t}=e,{message:s}=t;if(this.listenerManager.announceObjects(t),this.announce("objects",t,t.channel,t.subscription),"uuid"===s.type){const{message:e,channel:n}=t,i=r(t,["message","channel"]),{event:o,type:a}=s,c=r(s,["event","type"]),u=Object.assign(Object.assign({},i),{spaceId:n,message:Object.assign(Object.assign({},c),{event:"set"===o?"updated":"removed",type:"user"})});this.listenerManager.announceUser(u),this.announce("user",u,u.spaceId,u.subscription)}else if("channel"===s.type){const{message:e,channel:n}=t,i=r(t,["message","channel"]),{event:o,type:a}=s,c=r(s,["event","type"]),u=Object.assign(Object.assign({},i),{spaceId:n,message:Object.assign(Object.assign({},c),{event:"set"===o?"updated":"removed",type:"space"})});this.listenerManager.announceSpace(u),this.announce("space",u,u.spaceId,u.subscription)}else if("membership"===s.type){const{message:e,channel:n}=t,i=r(t,["message","channel"]),{event:o,data:a}=s,c=r(s,["event","data"]),{uuid:u,channel:l}=a,h=r(a,["uuid","channel"]),d=Object.assign(Object.assign({},i),{spaceId:n,message:Object.assign(Object.assign({},c),{event:"set"===o?"updated":"removed",data:Object.assign(Object.assign({},h),{user:u,space:l})})});this.listenerManager.announceMembership(d),this.announce("membership",d,d.spaceId,d.subscription)}}else e.type===ie.MessageAction?(this.listenerManager.announceMessageAction(e.data),this.announce("messageAction",e.data,e.data.channel,e.data.subscription)):e.type===ie.Files&&(this.listenerManager.announceFile(e.data),this.announce("file",e.data,e.data.channel,e.data.subscription))}addListener(e,t,s){t&&s?(null==t||t.forEach((t=>{if(this.channelListenerMap.has(t)){const s=this.channelListenerMap.get(t);s.includes(e)||s.push(e)}else this.channelListenerMap.set(t,[e])})),null==s||s.forEach((t=>{if(this.groupListenerMap.has(t)){const s=this.groupListenerMap.get(t);s.includes(e)||s.push(e)}else this.groupListenerMap.set(t,[e])}))):this.listenerManager.addListener(e)}removeListener(e,t,s){t&&s?(null==t||t.forEach((t=>{this.channelListenerMap.has(t)&&this.channelListenerMap.set(t,this.channelListenerMap.get(t).filter((t=>t!==e)))})),null==s||s.forEach((t=>{this.groupListenerMap.has(t)&&this.groupListenerMap.set(t,this.groupListenerMap.get(t).filter((t=>t!==e)))}))):this.listenerManager.removeListener(e)}removeAllListeners(){this.listenerManager.removeAllListeners(),this.channelListenerMap.clear(),this.groupListenerMap.clear()}announce(e,t,s,n){t&&this.channelListenerMap.has(s)&&this.channelListenerMap.get(s).forEach((s=>{const n=s[e];n&&n(t)})),n&&this.groupListenerMap.has(n)&&this.groupListenerMap.get(n).forEach((s=>{const n=s[e];n&&n(t)}))}}class ue{constructor(e=!1){this.sync=e,this.listeners=new Set}subscribe(e){return this.listeners.add(e),()=>{this.listeners.delete(e)}}notify(e){const t=()=>{this.listeners.forEach((t=>{t(e)}))};this.sync?t():setTimeout(t,0)}}class le{transition(e,t){var s;if(this.transitionMap.has(t.type))return null===(s=this.transitionMap.get(t.type))||void 0===s?void 0:s(e,t)}constructor(e){this.label=e,this.transitionMap=new Map,this.enterEffects=[],this.exitEffects=[]}on(e,t){return this.transitionMap.set(e,t),this}with(e,t){return[this,e,null!=t?t:[]]}onEnter(e){return this.enterEffects.push(e),this}onExit(e){return this.exitEffects.push(e),this}}class he extends ue{describe(e){return new le(e)}start(e,t){this.currentState=e,this.currentContext=t,this.notify({type:"engineStarted",state:e,context:t})}transition(e){if(!this.currentState)throw new Error("Start the engine first");this.notify({type:"eventReceived",event:e});const t=this.currentState.transition(this.currentContext,e);if(t){const[s,n,r]=t;for(const e of this.currentState.exitEffects)this.notify({type:"invocationDispatched",invocation:e(this.currentContext)});const i=this.currentState;this.currentState=s;const o=this.currentContext;this.currentContext=n,this.notify({type:"transitionDone",fromState:i,fromContext:o,toState:s,toContext:n,event:e});for(const e of r)this.notify({type:"invocationDispatched",invocation:e});for(const e of this.currentState.enterEffects)this.notify({type:"invocationDispatched",invocation:e(this.currentContext)})}}}class de{constructor(e){this.dependencies=e,this.instances=new Map,this.handlers=new Map}on(e,t){this.handlers.set(e,t)}dispatch(e){if("CANCEL"===e.type){if(this.instances.has(e.payload)){const t=this.instances.get(e.payload);null==t||t.cancel(),this.instances.delete(e.payload)}return}const t=this.handlers.get(e.type);if(!t)throw new Error(`Unhandled invocation '${e.type}'`);const s=t(e.payload,this.dependencies);e.managed&&this.instances.set(e.type,s),s.start()}dispose(){for(const[e,t]of this.instances.entries())t.cancel(),this.instances.delete(e)}}function pe(e,t){const s=function(...s){return{type:e,payload:null==t?void 0:t(...s)}};return s.type=e,s}function ge(e,t){const s=(...s)=>({type:e,payload:t(...s),managed:!1});return s.type=e,s}function ye(e,t){const s=(...s)=>({type:e,payload:t(...s),managed:!0});return s.type=e,s.cancel={type:"CANCEL",payload:e,managed:!1},s}class fe extends Error{constructor(){super("The operation was aborted."),this.name="AbortError",Object.setPrototypeOf(this,new.target.prototype)}}class me extends ue{constructor(){super(...arguments),this._aborted=!1}get aborted(){return this._aborted}throwIfAborted(){if(this._aborted)throw new fe}abort(){this._aborted=!0,this.notify(new fe)}}class be{constructor(e,t){this.payload=e,this.dependencies=t}}class ve extends be{constructor(e,t,s){super(e,t),this.asyncFunction=s,this.abortSignal=new me}start(){this.asyncFunction(this.payload,this.abortSignal,this.dependencies).catch((e=>{}))}cancel(){this.abortSignal.abort()}}const we=e=>(t,s)=>new ve(t,s,e),Se=pe("RECONNECT",(()=>({}))),ke=pe("DISCONNECT",(()=>({}))),Ee=pe("JOINED",((e,t)=>({channels:e,groups:t}))),Oe=pe("LEFT",((e,t)=>({channels:e,groups:t}))),Ce=pe("LEFT_ALL",(()=>({}))),Ne=pe("HEARTBEAT_SUCCESS",(e=>({statusCode:e}))),Pe=pe("HEARTBEAT_FAILURE",(e=>e)),Me=pe("HEARTBEAT_GIVEUP",(()=>({}))),je=pe("TIMES_UP",(()=>({}))),_e=ge("HEARTBEAT",((e,t)=>({channels:e,groups:t}))),Ae=ge("LEAVE",((e,t)=>({channels:e,groups:t}))),Ie=ge("EMIT_STATUS",(e=>e)),Re=ye("WAIT",(()=>({}))),Ue=ye("DELAYED_HEARTBEAT",(e=>e));class Te extends de{constructor(e,t){super(t),this.on(_e.type,we(((t,s,n)=>i(this,[t,s,n],void 0,(function*(t,s,{heartbeat:n,presenceState:r,config:i}){try{yield n(Object.assign(Object.assign({channels:t.channels,channelGroups:t.groups},i.maintainPresenceState&&{state:r}),{heartbeat:i.presenceTimeout}));e.transition(Ne(200))}catch(t){if(t instanceof d){if(t.status&&t.status.category==h.PNCancelledCategory)return;return e.transition(Pe(t))}}}))))),this.on(Ae.type,we(((e,t,s)=>i(this,[e,t,s],void 0,(function*(e,t,{leave:s,config:n}){if(!n.suppressLeaveEvents)try{s({channels:e.channels,channelGroups:e.groups})}catch(e){}}))))),this.on(Re.type,we(((t,s,n)=>i(this,[t,s,n],void 0,(function*(t,s,{heartbeatDelay:n}){return s.throwIfAborted(),yield n(),s.throwIfAborted(),e.transition(je())}))))),this.on(Ue.type,we(((t,s,n)=>i(this,[t,s,n],void 0,(function*(t,s,{heartbeat:n,retryDelay:r,presenceState:i,config:o}){if(!o.retryConfiguration||!o.retryConfiguration.shouldRetry(t.reason,t.attempts))return e.transition(Me());s.throwIfAborted(),yield r(o.retryConfiguration.getDelay(t.attempts,t.reason)),s.throwIfAborted();try{yield n(Object.assign(Object.assign({channels:t.channels,channelGroups:t.groups},o.maintainPresenceState&&{state:i}),{heartbeat:o.presenceTimeout}));return e.transition(Ne(200))}catch(t){if(t instanceof d){if(t.status&&t.status.category==h.PNCancelledCategory)return;return e.transition(Pe(t))}}}))))),this.on(Ie.type,we(((e,t,s)=>i(this,[e,t,s],void 0,(function*(e,t,{emitStatus:s,config:n}){var r;n.announceFailedHeartbeats&&!0===(null===(r=null==e?void 0:e.status)||void 0===r?void 0:r.error)?s(e.status):n.announceSuccessfulHeartbeats&&200===e.statusCode&&s(Object.assign(Object.assign({},e),{operation:re.PNHeartbeatOperation,error:!1}))})))))}}const Fe=new le("HEARTBEAT_STOPPED");Fe.on(Ee.type,((e,t)=>Fe.with({channels:[...e.channels,...t.payload.channels],groups:[...e.groups,...t.payload.groups]}))),Fe.on(Oe.type,((e,t)=>Fe.with({channels:e.channels.filter((e=>!t.payload.channels.includes(e))),groups:e.groups.filter((e=>!t.payload.groups.includes(e)))}))),Fe.on(Se.type,((e,t)=>qe.with({channels:e.channels,groups:e.groups}))),Fe.on(Ce.type,((e,t)=>Ge.with(void 0)));const xe=new le("HEARTBEAT_COOLDOWN");xe.onEnter((()=>Re())),xe.onExit((()=>Re.cancel)),xe.on(je.type,((e,t)=>qe.with({channels:e.channels,groups:e.groups}))),xe.on(Ee.type,((e,t)=>qe.with({channels:[...e.channels,...t.payload.channels],groups:[...e.groups,...t.payload.groups]}))),xe.on(Oe.type,((e,t)=>qe.with({channels:e.channels.filter((e=>!t.payload.channels.includes(e))),groups:e.groups.filter((e=>!t.payload.groups.includes(e)))},[Ae(t.payload.channels,t.payload.groups)]))),xe.on(ke.type,(e=>Fe.with({channels:e.channels,groups:e.groups},[Ae(e.channels,e.groups)]))),xe.on(Ce.type,((e,t)=>Ge.with(void 0,[Ae(e.channels,e.groups)])));const De=new le("HEARTBEAT_FAILED");De.on(Ee.type,((e,t)=>qe.with({channels:[...e.channels,...t.payload.channels],groups:[...e.groups,...t.payload.groups]}))),De.on(Oe.type,((e,t)=>qe.with({channels:e.channels.filter((e=>!t.payload.channels.includes(e))),groups:e.groups.filter((e=>!t.payload.groups.includes(e)))},[Ae(t.payload.channels,t.payload.groups)]))),De.on(Se.type,((e,t)=>qe.with({channels:e.channels,groups:e.groups}))),De.on(ke.type,((e,t)=>Fe.with({channels:e.channels,groups:e.groups},[Ae(e.channels,e.groups)]))),De.on(Ce.type,((e,t)=>Ge.with(void 0,[Ae(e.channels,e.groups)])));const Ke=new le("HEARBEAT_RECONNECTING");Ke.onEnter((e=>Ue(e))),Ke.onExit((()=>Ue.cancel)),Ke.on(Ee.type,((e,t)=>qe.with({channels:[...e.channels,...t.payload.channels],groups:[...e.groups,...t.payload.groups]}))),Ke.on(Oe.type,((e,t)=>qe.with({channels:e.channels.filter((e=>!t.payload.channels.includes(e))),groups:e.groups.filter((e=>!t.payload.groups.includes(e)))},[Ae(t.payload.channels,t.payload.groups)]))),Ke.on(ke.type,((e,t)=>{Fe.with({channels:e.channels,groups:e.groups},[Ae(e.channels,e.groups)])})),Ke.on(Ne.type,((e,t)=>xe.with({channels:e.channels,groups:e.groups}))),Ke.on(Pe.type,((e,t)=>Ke.with(Object.assign(Object.assign({},e),{attempts:e.attempts+1,reason:t.payload})))),Ke.on(Me.type,((e,t)=>De.with({channels:e.channels,groups:e.groups}))),Ke.on(Ce.type,((e,t)=>Ge.with(void 0,[Ae(e.channels,e.groups)])));const qe=new le("HEARTBEATING");qe.onEnter((e=>_e(e.channels,e.groups))),qe.on(Ne.type,((e,t)=>xe.with({channels:e.channels,groups:e.groups}))),qe.on(Ee.type,((e,t)=>qe.with({channels:[...e.channels,...t.payload.channels],groups:[...e.groups,...t.payload.groups]}))),qe.on(Oe.type,((e,t)=>qe.with({channels:e.channels.filter((e=>!t.payload.channels.includes(e))),groups:e.groups.filter((e=>!t.payload.groups.includes(e)))},[Ae(t.payload.channels,t.payload.groups)]))),qe.on(Pe.type,((e,t)=>Ke.with(Object.assign(Object.assign({},e),{attempts:0,reason:t.payload})))),qe.on(ke.type,(e=>Fe.with({channels:e.channels,groups:e.groups},[Ae(e.channels,e.groups)]))),qe.on(Ce.type,((e,t)=>Ge.with(void 0,[Ae(e.channels,e.groups)])));const Ge=new le("HEARTBEAT_INACTIVE");Ge.on(Ee.type,((e,t)=>qe.with({channels:t.payload.channels,groups:t.payload.groups})));class $e{get _engine(){return this.engine}constructor(e){this.dependencies=e,this.engine=new he,this.channels=[],this.groups=[],this.dispatcher=new Te(this.engine,e),this._unsubscribeEngine=this.engine.subscribe((e=>{"invocationDispatched"===e.type&&this.dispatcher.dispatch(e.invocation)})),this.engine.start(Ge,void 0)}join({channels:e,groups:t}){this.channels=[...this.channels,...null!=e?e:[]],this.groups=[...this.groups,...null!=t?t:[]],this.engine.transition(Ee(this.channels.slice(0),this.groups.slice(0)))}leave({channels:e,groups:t}){this.dependencies.presenceState&&(null==e||e.forEach((e=>delete this.dependencies.presenceState[e])),null==t||t.forEach((e=>delete this.dependencies.presenceState[e]))),this.engine.transition(Oe(null!=e?e:[],null!=t?t:[]))}leaveAll(){this.engine.transition(Ce())}dispose(){this._unsubscribeEngine(),this.dispatcher.dispose()}}class Le{static LinearRetryPolicy(e){return{delay:e.delay,maximumRetry:e.maximumRetry,shouldRetry(e,t){var s;return 403!==(null===(s=null==e?void 0:e.status)||void 0===s?void 0:s.statusCode)&&this.maximumRetry>t},getDelay(e,t){var s;return 1e3*((null!==(s=t.retryAfter)&&void 0!==s?s:this.delay)+Math.random())},getGiveupReason(e,t){var s;return this.maximumRetry<=t?"retry attempts exhaused.":403===(null===(s=null==e?void 0:e.status)||void 0===s?void 0:s.statusCode)?"forbidden operation.":"unknown error"},validate(){if(this.maximumRetry>10)throw new Error("Maximum retry for linear retry policy can not be more than 10")}}}static ExponentialRetryPolicy(e){return{minimumDelay:e.minimumDelay,maximumDelay:e.maximumDelay,maximumRetry:e.maximumRetry,shouldRetry(e,t){var s;return 403!==(null===(s=null==e?void 0:e.status)||void 0===s?void 0:s.statusCode)&&this.maximumRetry>t},getDelay(e,t){var s;return 1e3*((null!==(s=t.retryAfter)&&void 0!==s?s:Math.min(Math.pow(2,e),this.maximumDelay))+Math.random())},getGiveupReason(e,t){var s;return this.maximumRetry<=t?"retry attempts exhausted.":403===(null===(s=null==e?void 0:e.status)||void 0===s?void 0:s.statusCode)?"forbidden operation.":"unknown error"},validate(){if(this.minimumDelay<2)throw new Error("Minimum delay can not be set less than 2 seconds for retry");if(this.maximumDelay)throw new Error("Maximum delay can not be set more than 150 seconds for retry");if(this.maximumRetry>6)throw new Error("Maximum retry for exponential retry policy can not be more than 6")}}}}const Be=ye("HANDSHAKE",((e,t)=>({channels:e,groups:t}))),He=ye("RECEIVE_MESSAGES",((e,t,s)=>({channels:e,groups:t,cursor:s}))),ze=ge("EMIT_MESSAGES",(e=>e)),Ve=ge("EMIT_STATUS",(e=>e)),We=ye("RECEIVE_RECONNECT",(e=>e)),Je=ye("HANDSHAKE_RECONNECT",(e=>e)),Qe=pe("SUBSCRIPTION_CHANGED",((e,t)=>({channels:e,groups:t}))),Ye=pe("SUBSCRIPTION_RESTORED",((e,t,s,n)=>({channels:e,groups:t,cursor:{timetoken:s,region:null!=n?n:0}}))),Xe=pe("HANDSHAKE_SUCCESS",(e=>e)),Ze=pe("HANDSHAKE_FAILURE",(e=>e)),et=pe("HANDSHAKE_RECONNECT_SUCCESS",(e=>({cursor:e}))),tt=pe("HANDSHAKE_RECONNECT_FAILURE",(e=>e)),st=pe("HANDSHAKE_RECONNECT_GIVEUP",(e=>e)),nt=pe("RECEIVE_SUCCESS",((e,t)=>({cursor:e,events:t}))),rt=pe("RECEIVE_FAILURE",(e=>e)),it=pe("RECEIVE_RECONNECT_SUCCESS",((e,t)=>({cursor:e,events:t}))),ot=pe("RECEIVE_RECONNECT_FAILURE",(e=>e)),at=pe("RECEIVING_RECONNECT_GIVEUP",(e=>e)),ct=pe("DISCONNECT",(()=>({}))),ut=pe("RECONNECT",((e,t)=>({cursor:{timetoken:null!=e?e:"",region:null!=t?t:0}}))),lt=pe("UNSUBSCRIBE_ALL",(()=>({})));class ht extends de{constructor(e,t){super(t),this.on(Be.type,we(((t,s,n)=>i(this,[t,s,n],void 0,(function*(t,s,{handshake:n,presenceState:r,config:i}){s.throwIfAborted();try{const o=yield n(Object.assign({abortSignal:s,channels:t.channels,channelGroups:t.groups,filterExpression:i.filterExpression},i.maintainPresenceState&&{state:r}));return e.transition(Xe(o))}catch(t){if(t instanceof d){if(t.status&&t.status.category==h.PNCancelledCategory)return;return e.transition(Ze(t))}}}))))),this.on(He.type,we(((t,s,n)=>i(this,[t,s,n],void 0,(function*(t,s,{receiveMessages:n,config:r}){s.throwIfAborted();try{const i=yield n({abortSignal:s,channels:t.channels,channelGroups:t.groups,timetoken:t.cursor.timetoken,region:t.cursor.region,filterExpression:r.filterExpression});e.transition(nt(i.cursor,i.messages))}catch(t){if(t instanceof d){if(t.status&&t.status.category==h.PNCancelledCategory)return;if(!s.aborted)return e.transition(rt(t))}}}))))),this.on(ze.type,we(((e,t,s)=>i(this,[e,t,s],void 0,(function*(e,t,{emitMessages:s}){e.length>0&&s(e)}))))),this.on(Ve.type,we(((e,t,s)=>i(this,[e,t,s],void 0,(function*(e,t,{emitStatus:s}){s(e)}))))),this.on(We.type,we(((t,s,n)=>i(this,[t,s,n],void 0,(function*(t,s,{receiveMessages:n,delay:r,config:i}){if(!i.retryConfiguration||!i.retryConfiguration.shouldRetry(t.reason,t.attempts))return e.transition(at(new d(i.retryConfiguration?i.retryConfiguration.getGiveupReason(t.reason,t.attempts):"Unable to complete subscribe messages receive.")));s.throwIfAborted(),yield r(i.retryConfiguration.getDelay(t.attempts,t.reason)),s.throwIfAborted();try{const r=yield n({abortSignal:s,channels:t.channels,channelGroups:t.groups,timetoken:t.cursor.timetoken,region:t.cursor.region,filterExpression:i.filterExpression});return e.transition(it(r.cursor,r.messages))}catch(t){if(t instanceof d){if(t.status&&t.status.category==h.PNCancelledCategory)return;return e.transition(ot(t))}}}))))),this.on(Je.type,we(((t,s,n)=>i(this,[t,s,n],void 0,(function*(t,s,{handshake:n,delay:r,presenceState:i,config:o}){if(!o.retryConfiguration||!o.retryConfiguration.shouldRetry(t.reason,t.attempts))return e.transition(st(new d(o.retryConfiguration?o.retryConfiguration.getGiveupReason(t.reason,t.attempts):"Unable to complete subscribe handshake")));s.throwIfAborted(),yield r(o.retryConfiguration.getDelay(t.attempts,t.reason)),s.throwIfAborted();try{const r=yield n(Object.assign({abortSignal:s,channels:t.channels,channelGroups:t.groups,filterExpression:o.filterExpression},o.maintainPresenceState&&{state:i}));return e.transition(et(r))}catch(t){if(t instanceof d){if(t.status&&t.status.category==h.PNCancelledCategory)return;return e.transition(tt(t))}}})))))}}const dt=new le("HANDSHAKE_FAILED");dt.on(Qe.type,((e,t)=>vt.with({channels:t.payload.channels,groups:t.payload.groups,cursor:e.cursor}))),dt.on(ut.type,((e,t)=>vt.with({channels:e.channels,groups:e.groups,cursor:t.payload.cursor||e.cursor}))),dt.on(Ye.type,((e,t)=>{var s,n;return vt.with({channels:t.payload.channels,groups:t.payload.groups,cursor:{timetoken:t.payload.cursor.timetoken,region:t.payload.cursor.region?t.payload.cursor.region:null!==(n=null===(s=null==e?void 0:e.cursor)||void 0===s?void 0:s.region)&&void 0!==n?n:0}})})),dt.on(lt.type,(e=>wt.with()));const pt=new le("HANDSHAKE_STOPPED");pt.on(Qe.type,((e,t)=>pt.with({channels:t.payload.channels,groups:t.payload.groups,cursor:e.cursor}))),pt.on(ut.type,((e,t)=>vt.with(Object.assign(Object.assign({},e),{cursor:t.payload.cursor||e.cursor})))),pt.on(Ye.type,((e,t)=>{var s;return pt.with({channels:t.payload.channels,groups:t.payload.groups,cursor:{timetoken:t.payload.cursor.timetoken,region:t.payload.cursor.region||(null===(s=null==e?void 0:e.cursor)||void 0===s?void 0:s.region)||0}})})),pt.on(lt.type,(e=>wt.with()));const gt=new le("RECEIVE_FAILED");gt.on(ut.type,((e,t)=>{var s;return vt.with({channels:e.channels,groups:e.groups,cursor:{timetoken:t.payload.cursor.timetoken?null===(s=t.payload.cursor)||void 0===s?void 0:s.timetoken:e.cursor.timetoken,region:t.payload.cursor.region||e.cursor.region}})})),gt.on(Qe.type,((e,t)=>vt.with({channels:t.payload.channels,groups:t.payload.groups,cursor:e.cursor}))),gt.on(Ye.type,((e,t)=>vt.with({channels:t.payload.channels,groups:t.payload.groups,cursor:{timetoken:t.payload.cursor.timetoken,region:t.payload.cursor.region||e.cursor.region}}))),gt.on(lt.type,(e=>wt.with(void 0)));const yt=new le("RECEIVE_STOPPED");yt.on(Qe.type,((e,t)=>yt.with({channels:t.payload.channels,groups:t.payload.groups,cursor:e.cursor}))),yt.on(Ye.type,((e,t)=>yt.with({channels:t.payload.channels,groups:t.payload.groups,cursor:{timetoken:t.payload.cursor.timetoken,region:t.payload.cursor.region||e.cursor.region}}))),yt.on(ut.type,((e,t)=>{var s;return vt.with({channels:e.channels,groups:e.groups,cursor:{timetoken:t.payload.cursor.timetoken?null===(s=t.payload.cursor)||void 0===s?void 0:s.timetoken:e.cursor.timetoken,region:t.payload.cursor.region||e.cursor.region}})})),yt.on(lt.type,(()=>wt.with(void 0)));const ft=new le("RECEIVE_RECONNECTING");ft.onEnter((e=>We(e))),ft.onExit((()=>We.cancel)),ft.on(it.type,((e,t)=>mt.with({channels:e.channels,groups:e.groups,cursor:t.payload.cursor},[ze(t.payload.events)]))),ft.on(ot.type,((e,t)=>ft.with(Object.assign(Object.assign({},e),{attempts:e.attempts+1,reason:t.payload})))),ft.on(at.type,((e,t)=>{var s;return gt.with({groups:e.groups,channels:e.channels,cursor:e.cursor,reason:t.payload},[Ve({category:h.PNDisconnectedUnexpectedlyCategory,error:null===(s=t.payload)||void 0===s?void 0:s.message})])})),ft.on(ct.type,(e=>yt.with({channels:e.channels,groups:e.groups,cursor:e.cursor},[Ve({category:h.PNDisconnectedCategory})]))),ft.on(Ye.type,((e,t)=>mt.with({channels:t.payload.channels,groups:t.payload.groups,cursor:{timetoken:t.payload.cursor.timetoken,region:t.payload.cursor.region||e.cursor.region}}))),ft.on(Qe.type,((e,t)=>mt.with({channels:t.payload.channels,groups:t.payload.groups,cursor:e.cursor}))),ft.on(lt.type,(e=>wt.with(void 0,[Ve({category:h.PNDisconnectedCategory})])));const mt=new le("RECEIVING");mt.onEnter((e=>He(e.channels,e.groups,e.cursor))),mt.onExit((()=>He.cancel)),mt.on(nt.type,((e,t)=>mt.with({channels:e.channels,groups:e.groups,cursor:t.payload.cursor},[ze(t.payload.events)]))),mt.on(Qe.type,((e,t)=>0===t.payload.channels.length&&0===t.payload.groups.length?wt.with(void 0):mt.with({cursor:e.cursor,channels:t.payload.channels,groups:t.payload.groups}))),mt.on(Ye.type,((e,t)=>0===t.payload.channels.length&&0===t.payload.groups.length?wt.with(void 0):mt.with({channels:t.payload.channels,groups:t.payload.groups,cursor:{timetoken:t.payload.cursor.timetoken,region:t.payload.cursor.region||e.cursor.region}}))),mt.on(rt.type,((e,t)=>ft.with(Object.assign(Object.assign({},e),{attempts:0,reason:t.payload})))),mt.on(ct.type,(e=>yt.with({channels:e.channels,groups:e.groups,cursor:e.cursor},[Ve({category:h.PNDisconnectedCategory})]))),mt.on(lt.type,(e=>wt.with(void 0,[Ve({category:h.PNDisconnectedCategory})])));const bt=new le("HANDSHAKE_RECONNECTING");bt.onEnter((e=>Je(e))),bt.onExit((()=>Je.cancel)),bt.on(et.type,((e,t)=>{var s,n;const r={timetoken:(null===(s=e.cursor)||void 0===s?void 0:s.timetoken)?null===(n=e.cursor)||void 0===n?void 0:n.timetoken:t.payload.cursor.timetoken,region:t.payload.cursor.region};return mt.with({channels:e.channels,groups:e.groups,cursor:r},[Ve({category:h.PNConnectedCategory})])})),bt.on(tt.type,((e,t)=>bt.with(Object.assign(Object.assign({},e),{attempts:e.attempts+1,reason:t.payload})))),bt.on(st.type,((e,t)=>{var s;return dt.with({groups:e.groups,channels:e.channels,cursor:e.cursor,reason:t.payload},[Ve({category:h.PNConnectionErrorCategory,error:null===(s=t.payload)||void 0===s?void 0:s.message})])})),bt.on(ct.type,(e=>pt.with({channels:e.channels,groups:e.groups,cursor:e.cursor}))),bt.on(Qe.type,((e,t)=>vt.with({channels:t.payload.channels,groups:t.payload.groups,cursor:e.cursor}))),bt.on(Ye.type,((e,t)=>{var s,n;return vt.with({channels:t.payload.channels,groups:t.payload.groups,cursor:{timetoken:t.payload.cursor.timetoken,region:(null===(s=t.payload.cursor)||void 0===s?void 0:s.region)||(null===(n=null==e?void 0:e.cursor)||void 0===n?void 0:n.region)||0}})})),bt.on(lt.type,(e=>wt.with(void 0)));const vt=new le("HANDSHAKING");vt.onEnter((e=>Be(e.channels,e.groups))),vt.onExit((()=>Be.cancel)),vt.on(Qe.type,((e,t)=>0===t.payload.channels.length&&0===t.payload.groups.length?wt.with(void 0):vt.with({channels:t.payload.channels,groups:t.payload.groups,cursor:e.cursor}))),vt.on(Xe.type,((e,t)=>{var s,n;return mt.with({channels:e.channels,groups:e.groups,cursor:{timetoken:(null===(s=null==e?void 0:e.cursor)||void 0===s?void 0:s.timetoken)?null===(n=null==e?void 0:e.cursor)||void 0===n?void 0:n.timetoken:t.payload.timetoken,region:t.payload.region}},[Ve({category:h.PNConnectedCategory})])})),vt.on(Ze.type,((e,t)=>bt.with({channels:e.channels,groups:e.groups,cursor:e.cursor,attempts:0,reason:t.payload}))),vt.on(ct.type,(e=>pt.with({channels:e.channels,groups:e.groups,cursor:e.cursor}))),vt.on(Ye.type,((e,t)=>{var s;return vt.with({channels:t.payload.channels,groups:t.payload.groups,cursor:{timetoken:t.payload.cursor.timetoken,region:t.payload.cursor.region||(null===(s=null==e?void 0:e.cursor)||void 0===s?void 0:s.region)||0}})})),vt.on(lt.type,(e=>wt.with()));const wt=new le("UNSUBSCRIBED");wt.on(Qe.type,((e,t)=>vt.with({channels:t.payload.channels,groups:t.payload.groups}))),wt.on(Ye.type,((e,t)=>vt.with({channels:t.payload.channels,groups:t.payload.groups,cursor:t.payload.cursor})));class St{get _engine(){return this.engine}constructor(e){this.engine=new he,this.channels=[],this.groups=[],this.dependencies=e,this.dispatcher=new ht(this.engine,e),this._unsubscribeEngine=this.engine.subscribe((e=>{"invocationDispatched"===e.type&&this.dispatcher.dispatch(e.invocation)})),this.engine.start(wt,void 0)}subscribe({channels:e,channelGroups:t,timetoken:s,withPresence:n}){this.channels=[...this.channels,...null!=e?e:[]],this.groups=[...this.groups,...null!=t?t:[]],n&&(this.channels.map((e=>this.channels.push(`${e}-pnpres`))),this.groups.map((e=>this.groups.push(`${e}-pnpres`)))),s?this.engine.transition(Ye(Array.from(new Set([...this.channels,...null!=e?e:[]])),Array.from(new Set([...this.groups,...null!=t?t:[]])),s)):this.engine.transition(Qe(Array.from(new Set([...this.channels,...null!=e?e:[]])),Array.from(new Set([...this.groups,...null!=t?t:[]])))),this.dependencies.join&&this.dependencies.join({channels:Array.from(new Set(this.channels.filter((e=>!e.endsWith("-pnpres"))))),groups:Array.from(new Set(this.groups.filter((e=>!e.endsWith("-pnpres")))))})}unsubscribe({channels:e=[],channelGroups:t=[]}){const s=U(this.channels,[...e,...e.map((e=>`${e}-pnpres`))]),n=U(this.groups,[...t,...t.map((e=>`${e}-pnpres`))]);if(new Set(this.channels).size!==new Set(s).size||new Set(this.groups).size!==new Set(n).size){const r=T(this.channels,e),i=T(this.groups,t);this.dependencies.presenceState&&(null==r||r.forEach((e=>delete this.dependencies.presenceState[e])),null==i||i.forEach((e=>delete this.dependencies.presenceState[e]))),this.channels=s,this.groups=n,this.engine.transition(Qe(Array.from(new Set(this.channels.slice(0))),Array.from(new Set(this.groups.slice(0))))),this.dependencies.leave&&this.dependencies.leave({channels:r.slice(0),groups:i.slice(0)})}}unsubscribeAll(){this.channels=[],this.groups=[],this.dependencies.presenceState&&Object.keys(this.dependencies.presenceState).forEach((e=>{delete this.dependencies.presenceState[e]})),this.engine.transition(Qe(this.channels.slice(0),this.groups.slice(0))),this.dependencies.leaveAll&&this.dependencies.leaveAll()}reconnect({timetoken:e,region:t}){this.engine.transition(ut(e,t))}disconnect(){this.engine.transition(ct()),this.dependencies.leaveAll&&this.dependencies.leaveAll()}getSubscribedChannels(){return Array.from(new Set(this.channels.slice(0)))}getSubscribedChannelGroups(){return Array.from(new Set(this.groups.slice(0)))}dispose(){this.disconnect(),this._unsubscribeEngine(),this.dispatcher.dispose()}}class kt extends se{constructor(e){var t,s;super({method:e.sendByPost?H.POST:H.GET}),this.parameters=e,null!==(t=(s=this.parameters).sendByPost)&&void 0!==t||(s.sendByPost=false)}operation(){return re.PNPublishOperation}validate(){const{message:e,channel:t,keySet:{publishKey:s}}=this.parameters;return t?e?s?void 0:"Missing 'publishKey'":"Missing 'message'":"Missing 'channel'"}parse(e){return i(this,void 0,void 0,(function*(){const t=this.deserializeResponse(e);if(!t)throw new d("Service response error, check status for details",p("Unable to deserialize service response"));return{timetoken:t[2]}}))}get path(){const{message:e,channel:t,keySet:s}=this.parameters,n=this.prepareMessagePayload(e);return`/publish/${s.publishKey}/${s.subscribeKey}/0/${I(t)}/0${this.parameters.sendByPost?"":`/${I(n)}`}`}get queryParameters(){const{meta:e,replicate:t,storeInHistory:s,ttl:n}=this.parameters,r={};return void 0!==s&&(r.store=s?"1":"0"),void 0!==n&&(r.ttl=n),void 0===t||t||(r.norep="true"),e&&"object"==typeof e&&(r.meta=JSON.stringify(e)),r}get headers(){return{"Content-Type":"application/json"}}get body(){return this.prepareMessagePayload(this.parameters.message)}prepareMessagePayload(e){const{crypto:t}=this.parameters;if(!t)return JSON.stringify(e)||"";const s=t.encrypt(JSON.stringify(e));return JSON.stringify("string"==typeof s?s:u(s))}}class Et extends se{constructor(e){super(),this.parameters=e}operation(){return re.PNSignalOperation}validate(){const{message:e,channel:t,keySet:{publishKey:s}}=this.parameters;return t?e?s?void 0:"Missing 'publishKey'":"Missing 'message'":"Missing 'channel'"}parse(e){return i(this,void 0,void 0,(function*(){const t=this.deserializeResponse(e);if(!t)throw new d("Service response error, check status for details",p("Unable to deserialize service response"));return{timetoken:t[2]}}))}get path(){const{keySet:{publishKey:e,subscribeKey:t},channel:s,message:n}=this.parameters,r=JSON.stringify(n);return`/signal/${e}/${t}/0/${I(s)}/0/${I(r)}`}}class Ot extends oe{operation(){return re.PNReceiveMessagesOperation}validate(){const e=super.validate();return e||(this.parameters.timetoken?this.parameters.region?void 0:"region can not be empty":"timetoken can not be empty")}get path(){const{keySet:{subscribeKey:e},channels:t=[]}=this.parameters;return`/v2/subscribe/${e}/${R(t.sort(),",")}/0`}get queryParameters(){const{channelGroups:e,filterExpression:t,timetoken:s,region:n}=this.parameters,r={ee:""};return e&&e.length>0&&(r["channel-group"]=e.sort().join(",")),t&&t.length>0&&(r["filter-expr"]=t),"string"==typeof s?s&&s.length>0&&(r.tt=s):s&&s>0&&(r.tt=s),n&&(r.tr=n),r}}class Ct extends oe{operation(){return re.PNHandshakeOperation}get path(){const{keySet:{subscribeKey:e},channels:t=[]}=this.parameters;return`/v2/subscribe/${e}/${R(t.sort(),",")}/0`}get queryParameters(){const{channelGroups:e,filterExpression:t,state:s}=this.parameters,n={tt:0,ee:""};return e&&e.length>0&&(n["channel-group"]=e.sort().join(",")),t&&t.length>0&&(n["filter-expr"]=t),s&&Object.keys(s).length>0&&(n.state=JSON.stringify(s)),n}}class Nt extends se{constructor(e){var t,s,n,r;super(),this.parameters=e,null!==(t=(n=this.parameters).channels)&&void 0!==t||(n.channels=[]),null!==(s=(r=this.parameters).channelGroups)&&void 0!==s||(r.channelGroups=[])}operation(){return re.PNGetStateOperation}validate(){const{keySet:{subscribeKey:e},channels:t,channelGroups:s}=this.parameters;if(!e)return"Missing Subscribe Key"}parse(e){return i(this,void 0,void 0,(function*(){const t=this.deserializeResponse(e);if(!t)throw new d("Service response error, check status for details",p("Unable to deserialize service response"));if(t.status>=400)throw _.create(e);const{channels:s=[],channelGroups:n=[]}=this.parameters,r={channels:{}};return 1===s.length&&0===n.length?r.channels[s[0]]=t.payload:r.channels=t.payload,r}))}get path(){const{keySet:{subscribeKey:e},uuid:t,channels:s}=this.parameters;return`/v2/presence/sub-key/${e}/channel/${R(null!=s?s:[],",")}/uuid/${t}`}get queryParameters(){const{channelGroups:e}=this.parameters;return e&&0!==e.length?{"channel-group":e.join(",")}:{}}}class Pt extends se{constructor(e){super(),this.parameters=e}operation(){return re.PNSetStateOperation}validate(){const{keySet:{subscribeKey:e},state:t,channels:s=[],channelGroups:n=[]}=this.parameters;return e?t?0===(null==s?void 0:s.length)&&0===(null==n?void 0:n.length)?"Please provide a list of channels and/or channel-groups":void 0:"Missing State":"Missing Subscribe Key"}parse(e){return i(this,void 0,void 0,(function*(){const t=this.deserializeResponse(e);if(!t)throw new d("Service response error, check status for details",p("Unable to deserialize service response"));if(t.status>=400)throw _.create(e);return{state:t.payload}}))}get path(){const{keySet:{subscribeKey:e},uuid:t,channels:s}=this.parameters;return`/v2/presence/sub-key/${e}/channel/${R(null!=s?s:[],",")}/uuid/${I(t)}/data`}get queryParameters(){const{channelGroups:e,state:t}=this.parameters,s={state:JSON.stringify(t)};return e&&0!==e.length&&(s["channel-group"]=e.join(",")),s}}class Mt extends se{constructor(e){super(),this.parameters=e}operation(){return re.PNHeartbeatOperation}validate(){const{keySet:{subscribeKey:e},channels:t=[],channelGroups:s=[]}=this.parameters;return e?0===t.length&&0===s.length?"Please provide a list of channels and/or channel-groups":void 0:"Missing Subscribe Key"}parse(e){return i(this,void 0,void 0,(function*(){const t=this.deserializeResponse(e);if(!t)throw new d("Service response error, check status for details",p("Unable to deserialize service response"));if(t.status>=400)throw _.create(e);return{}}))}get path(){const{keySet:{subscribeKey:e},channels:t}=this.parameters;return`/v2/presence/sub-key/${e}/channel/${R(null!=t?t:[],",")}/heartbeat`}get queryParameters(){const{channelGroups:e,state:t,heartbeat:s}=this.parameters,n={heartbeat:`${s}`};return e&&0!==e.length&&(n["channel-group"]=e.join(",")),t&&(n.state=JSON.stringify(t)),n}}class jt extends se{constructor(e){super(),this.parameters=e,this.parameters.channelGroups&&(this.parameters.channelGroups=Array.from(new Set(this.parameters.channelGroups))),this.parameters.channels&&(this.parameters.channels=Array.from(new Set(this.parameters.channels)))}operation(){return re.PNUnsubscribeOperation}validate(){const{keySet:{subscribeKey:e},channels:t=[],channelGroups:s=[]}=this.parameters;return e?0===t.length&&0===s.length?"At least one `channel` or `channel group` should be provided.":void 0:"Missing Subscribe Key"}parse(e){return i(this,void 0,void 0,(function*(){const t=this.deserializeResponse(e);if(!t)throw new d("Service response error, check status for details",p("Unable to deserialize service response"));if(t.status>=400)throw _.create(e);return{}}))}get path(){var e;const{keySet:{subscribeKey:t},channels:s}=this.parameters;return`/v2/presence/sub-key/${t}/channel/${R(null!==(e=null==s?void 0:s.sort())&&void 0!==e?e:[],",")}/leave`}get queryParameters(){const{channelGroups:e}=this.parameters;return e&&0!==e.length?{"channel-group":e.sort().join(",")}:{}}}class _t extends se{constructor(e){super(),this.parameters=e}operation(){return re.PNWhereNowOperation}validate(){if(!this.parameters.keySet.subscribeKey)return"Missing Subscribe Key"}parse(e){return i(this,void 0,void 0,(function*(){const t=this.deserializeResponse(e);if(!t)throw new d("Service response error, check status for details",p("Unable to deserialize service response"));if(t.status>=400)throw _.create(e);return t.payload?{channels:t.payload.channels}:{channels:[]}}))}get path(){const{keySet:{subscribeKey:e},uuid:t}=this.parameters;return`/v2/presence/sub-key/${e}/uuid/${I(t)}`}}class At extends se{constructor(e){var t,s,n,r,i,o;super(),this.parameters=e,null!==(t=(r=this.parameters).queryParameters)&&void 0!==t||(r.queryParameters={}),null!==(s=(i=this.parameters).includeUUIDs)&&void 0!==s||(i.includeUUIDs=true),null!==(n=(o=this.parameters).includeState)&&void 0!==n||(o.includeState=false)}operation(){const{channels:e=[],channelGroups:t=[]}=this.parameters;return 0===e.length&&0===t.length?re.PNGlobalHereNowOperation:re.PNHereNowOperation}validate(){if(!this.parameters.keySet.subscribeKey)return"Missing Subscribe Key"}parse(e){return i(this,void 0,void 0,(function*(){var t,s;const n=this.deserializeResponse(e);if(!n)throw new d("Service response error, check status for details",p("Unable to deserialize service response"));if(n.status>=400)throw _.create(e);const r="occupancy"in n?1:n.payload.total_channels,i="occupancy"in n?n.occupancy:n.payload.total_channels,o={};let a={};if("occupancy"in n){const e=this.parameters.channels[0];a[e]={uuids:null!==(t=n.uuids)&&void 0!==t?t:[],occupancy:i}}else a=null!==(s=n.payload.channels)&&void 0!==s?s:{};return Object.keys(a).forEach((e=>{const t=a[e];o[e]={occupants:this.parameters.includeUUIDs?t.uuids.map((e=>"string"==typeof e?{uuid:e,state:null}:e)):[],name:e,occupancy:t.occupancy}})),{totalChannels:r,totalOccupancy:i,channels:o}}))}get path(){const{keySet:{subscribeKey:e},channels:t,channelGroups:s}=this.parameters;let n=`/v2/presence/sub-key/${e}`;return(t&&t.length>0||s&&s.length>0)&&(n+=`/channel/${R(null!=t?t:[],",")}`),n}get queryParameters(){const{channelGroups:e,includeUUIDs:t,includeState:s,queryParameters:n}=this.parameters;return Object.assign(Object.assign(Object.assign(Object.assign({},t?{}:{disable_uuids:"1"}),null!=s&&s?{state:"1"}:{}),e&&e.length>0?{"channel-group":e.join(",")}:{}),n)}}class It extends se{constructor(e){super({method:H.DELETE}),this.parameters=e}operation(){return re.PNDeleteMessagesOperation}validate(){return this.parameters.keySet.subscribeKey?this.parameters.channel?void 0:"Missing channel":"Missing Subscribe Key"}parse(e){return i(this,void 0,void 0,(function*(){const t=this.deserializeResponse(e);if(!t)throw new d("Service response error, check status for details",p("Unable to deserialize service response"));if(t.status>=400)throw _.create(e);return{}}))}get path(){const{keySet:{subscribeKey:e},channel:t}=this.parameters;return`/v3/history/sub-key/${e}/channel/${I(t)}`}get queryParameters(){const{start:e,end:t}=this.parameters;return Object.assign(Object.assign({},e?{start:e}:{}),t?{end:t}:{})}}class Rt extends se{constructor(e){super(),this.parameters=e}operation(){return re.PNMessageCounts}validate(){const{keySet:{subscribeKey:e},channels:t,timetoken:s,channelTimetokens:n}=this.parameters;return e?t?s&&n?"`timetoken` and `channelTimetokens` are incompatible together":s||n?n&&n.length>1&&n.length!==t.length?"Length of `channelTimetokens` and `channels` do not match":void 0:"`timetoken` or `channelTimetokens` need to be set":"Missing channels":"Missing Subscribe Key"}parse(e){return i(this,void 0,void 0,(function*(){const t=this.deserializeResponse(e);if(!t)throw new d("Service response error, check status for details",p("Unable to deserialize service response"));if(t.status>=400)throw _.create(e);return{channels:t.channels}}))}get path(){return`/v3/history/sub-key/${this.parameters.keySet.subscribeKey}/message-counts/${R(this.parameters.channels)}`}get queryParameters(){let{channelTimetokens:e}=this.parameters;return this.parameters.timetoken&&(e=[this.parameters.timetoken]),Object.assign(Object.assign({},1===e.length?{timetoken:e[0]}:{}),e.length>1?{channelsTimetoken:e.join(",")}:{})}}class Ut extends se{constructor(e){var t,s,n;super(),this.parameters=e,e.count?e.count=Math.min(e.count,100):e.count=100,null!==(t=e.stringifiedTimeToken)&&void 0!==t||(e.stringifiedTimeToken=false),null!==(s=e.includeMeta)&&void 0!==s||(e.includeMeta=false),null!==(n=e.logVerbosity)&&void 0!==n||(e.logVerbosity=false)}operation(){return re.PNHistoryOperation}validate(){return this.parameters.keySet.subscribeKey?this.parameters.channel?void 0:"Missing channel":"Missing Subscribe Key"}parse(e){return i(this,void 0,void 0,(function*(){const t=this.deserializeResponse(e);if(!t)throw new d("Service response error, check status for details",p("Unable to deserialize service response"));const s=t[0],n=t[1],r=t[2];return Array.isArray(s)?{messages:s.map((e=>{const t=this.processPayload(e.message),s={entry:t.payload,timetoken:e.timetoken};return t.error&&(s.error=t.error),e.meta&&(s.meta=e.meta),s})),startTimeToken:n,endTimeToken:r}:{messages:[],startTimeToken:n,endTimeToken:r}}))}get path(){const{keySet:{subscribeKey:e},channel:t}=this.parameters;return`/v2/history/sub-key/${e}/channel/${I(t)}`}get queryParameters(){const{start:e,end:t,reverse:s,count:n,stringifiedTimeToken:r,includeMeta:i}=this.parameters;return Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({count:n,include_token:"true"},e?{start:e}:{}),t?{end:t}:{}),r?{string_message_token:"true"}:{}),null!=s?{reverse:s.toString()}:{}),i?{include_meta:"true"}:{})}processPayload(e){const{crypto:t,logVerbosity:s}=this.parameters;if(!t||"string"!=typeof e)return{payload:e};let n,r;try{const s=t.decrypt(e);n=s instanceof ArrayBuffer?JSON.parse(Ut.decoder.decode(s)):s}catch(t){s&&console.log("decryption error",t.message),n=e,r=`Error while decrypting message content: ${t.message}`}return{payload:n,error:r}}}var Tt;!function(e){e[e.Message=-1]="Message",e[e.Files=4]="Files"}(Tt||(Tt={}));class Ft extends se{constructor(e){var t,s,n,r,i;super(),this.parameters=e;const o=null!==(t=e.includeMessageActions)&&void 0!==t&&t,a=e.channels.length>1||o?25:100;e.count?e.count=Math.min(e.count,a):e.count=a,e.includeUuid?e.includeUUID=e.includeUuid:null!==(s=e.includeUUID)&&void 0!==s||(e.includeUUID=true),null!==(n=e.stringifiedTimeToken)&&void 0!==n||(e.stringifiedTimeToken=false),null!==(r=e.includeMessageType)&&void 0!==r||(e.includeMessageType=true),null!==(i=e.logVerbosity)&&void 0!==i||(e.logVerbosity=false)}operation(){return re.PNFetchMessagesOperation}validate(){const{keySet:{subscribeKey:e},channels:t,includeMessageActions:s}=this.parameters;return e?t?void 0!==s&&s&&t.length>1?"History can return actions data for a single channel only. Either pass a single channel or disable the includeMessageActions flag.":void 0:"Missing channels":"Missing Subscribe Key"}parse(e){return i(this,void 0,void 0,(function*(){var t;const s=this.deserializeResponse(e);if(!s)throw new d("Service response error, check status for details",p("Unable to deserialize service response"));if(s.status>=400)throw _.create(e);const n=null!==(t=s.channels)&&void 0!==t?t:{},r={};return Object.keys(n).forEach((e=>{r[e]=n[e].map((t=>{null===t.message_type&&(t.message_type=Tt.Message);const s=this.processPayload(e,t),n={channel:e,timetoken:t.timetoken,message:s.payload,messageType:t.message_type,uuid:t.uuid};if(t.actions){const e=n;e.actions=t.actions,e.data=t.actions}return t.meta&&(n.meta=t.meta),s.error&&(n.error=s.error),n}))})),s.more?{channels:r,more:s.more}:{channels:r}}))}get path(){const{keySet:{subscribeKey:e},channels:t,includeMessageActions:s}=this.parameters;return`/v3/${s?"history-with-actions":"history"}/sub-key/${e}/channel/${R(t)}`}get queryParameters(){const{start:e,end:t,count:s,includeMessageType:n,includeMeta:r,includeUUID:i,stringifiedTimeToken:o}=this.parameters;return Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({max:s},e?{start:e}:{}),t?{end:t}:{}),o?{string_message_token:"true"}:{}),void 0!==r&&r?{include_meta:"true"}:{}),i?{include_uuid:"true"}:{}),n?{include_message_type:"true"}:{})}processPayload(e,t){const{crypto:s,logVerbosity:n}=this.parameters;if(!s||"string"!=typeof t.message)return{payload:t.message};let r,i;try{const e=s.decrypt(t.message);r=e instanceof ArrayBuffer?JSON.parse(Ft.decoder.decode(e)):e}catch(e){n&&console.log("decryption error",e.message),r=t.message,i=`Error while decrypting message content: ${e.message}`}if(!i&&r&&t.message_type==Tt.Files&&"object"==typeof r&&this.isFileMessage(r)){const t=r;return{payload:{message:t.message,file:Object.assign(Object.assign({},t.file),{url:this.parameters.getFileUrl({channel:e,id:t.file.id,name:t.file.name})})},error:i}}return{payload:r,error:i}}isFileMessage(e){return void 0!==e.file}}class xt extends se{constructor(e){super(),this.parameters=e}operation(){return re.PNGetMessageActionsOperation}validate(){return this.parameters.keySet.subscribeKey?this.parameters.channel?void 0:"Missing message channel":"Missing Subscribe Key"}parse(e){return i(this,void 0,void 0,(function*(){const t=this.deserializeResponse(e);if(!t)throw new d("Service response error, check status for details",p("Unable to deserialize service response"));if(t.status>=400)throw _.create(e);let s=null,n=null;return t.data.length>0&&(s=t.data[0].actionTimetoken,n=t.data[t.data.length-1].actionTimetoken),{data:t.data,more:t.more,start:s,end:n}}))}get path(){const{keySet:{subscribeKey:e},channel:t}=this.parameters;return`/v1/message-actions/${e}/channel/${I(t)}`}get queryParameters(){const{limit:e,start:t,end:s}=this.parameters;return Object.assign(Object.assign(Object.assign({},t?{start:t}:{}),s?{end:s}:{}),e?{limit:e}:{})}}class Dt extends se{constructor(e){super({method:H.POST}),this.parameters=e}operation(){return re.PNAddMessageActionOperation}validate(){const{keySet:{subscribeKey:e},action:t,channel:s,messageTimetoken:n}=this.parameters;return e?s?n?t?t.value?t.type?t.type.length>15?"Action.type value exceed maximum length of 15":void 0:"Missing Action.type":"Missing Action.value":"Missing Action":"Missing message timetoken":"Missing message channel":"Missing Subscribe Key"}parse(e){return i(this,void 0,void 0,(function*(){const t=this.deserializeResponse(e);if(!t)throw new d("Service response error, check status for details",p("Unable to deserialize service response"));if(t.status>=400)throw _.create(e);return{data:t.data}}))}get headers(){return{"Content-Type":"application/json"}}get path(){const{keySet:{subscribeKey:e},channel:t,messageTimetoken:s}=this.parameters;return`/v1/message-actions/${e}/channel/${I(t)}/message/${s}`}get body(){return JSON.stringify(this.parameters.action)}}class Kt extends se{constructor(e){super({method:H.DELETE}),this.parameters=e}operation(){return re.PNRemoveMessageActionOperation}validate(){const{keySet:{subscribeKey:e},channel:t,messageTimetoken:s,actionTimetoken:n}=this.parameters;return e?t?s?n?void 0:"Missing action timetoken":"Missing message timetoken":"Missing message action channel":"Missing Subscribe Key"}parse(e){return i(this,void 0,void 0,(function*(){const t=this.deserializeResponse(e);if(!t)throw new d("Service response error, check status for details",p("Unable to deserialize service response"));if(t.status>=400)throw _.create(e);return{data:t.data}}))}get path(){const{keySet:{subscribeKey:e},channel:t,actionTimetoken:s,messageTimetoken:n}=this.parameters;return`/v1/message-actions/${e}/channel/${I(t)}/message/${n}/action/${s}`}}class qt extends se{constructor(e){var t,s;super(),this.parameters=e,null!==(t=(s=this.parameters).storeInHistory)&&void 0!==t||(s.storeInHistory=true)}operation(){return re.PNPublishFileMessageOperation}validate(){const{channel:e,fileId:t,fileName:s}=this.parameters;return e?t?s?void 0:"file name can't be empty":"file id can't be empty":"channel can't be empty"}parse(e){return i(this,void 0,void 0,(function*(){const t=this.deserializeResponse(e);if(!t)throw new d("Service response error, check status for details",p("Unable to deserialize service response"));return{timetoken:t[2]}}))}get path(){const{message:e,channel:t,keySet:{publishKey:s,subscribeKey:n},fileId:r,fileName:i}=this.parameters,o=Object.assign({file:{name:i,id:r}},e?{message:e}:{});return`/v1/files/publish-file/${s}/${n}/0/${I(t)}/0/${I(this.prepareMessagePayload(o))}`}get queryParameters(){const{storeInHistory:e,ttl:t,meta:s}=this.parameters;return Object.assign(Object.assign({store:e?"1":"0"},t?{ttl:t}:{}),s&&"object"==typeof s?{meta:JSON.stringify(s)}:{})}prepareMessagePayload(e){const{crypto:t}=this.parameters;if(!t)return JSON.stringify(e)||"";const s=t.encrypt(JSON.stringify(e));return JSON.stringify("string"==typeof s?s:u(s))}}class Gt extends se{constructor(e){super({method:H.LOCAL}),this.parameters=e}operation(){return re.PNGetFileUrlOperation}validate(){const{channel:e,id:t,name:s}=this.parameters;return e?t?s?void 0:"file name can't be empty":"file id can't be empty":"channel can't be empty"}parse(e){return i(this,void 0,void 0,(function*(){return e.url}))}get path(){const{channel:e,id:t,name:s,keySet:{subscribeKey:n}}=this.parameters;return`/v1/files/${n}/channels/${I(e)}/files/${t}/${s}`}}class $t extends se{constructor(e){super({method:H.DELETE}),this.parameters=e}operation(){return re.PNDeleteFileOperation}validate(){const{channel:e,id:t,name:s}=this.parameters;return e?t?s?void 0:"file name can't be empty":"file id can't be empty":"channel can't be empty"}parse(e){return i(this,void 0,void 0,(function*(){const t=this.deserializeResponse(e);if(!t)throw new d("Service response error, check status for details",p("Unable to deserialize service response"));if(t.status>=400)throw _.create(e);return t}))}get path(){const{keySet:{subscribeKey:e},id:t,channel:s,name:n}=this.parameters;return`/v1/files/${e}/channels/${I(s)}/files/${t}/${n}`}}class Lt extends se{constructor(e){var t,s;super(),this.parameters=e,null!==(t=(s=this.parameters).limit)&&void 0!==t||(s.limit=100)}operation(){return re.PNListFilesOperation}validate(){if(!this.parameters.channel)return"channel can't be empty"}parse(e){return i(this,void 0,void 0,(function*(){const t=this.deserializeResponse(e);if(!t)throw new d("Service response error, check status for details",p("Unable to deserialize service response"));if(t.status>=400)throw _.create(e);return t}))}get path(){const{keySet:{subscribeKey:e},channel:t}=this.parameters;return`/v1/files/${e}/channels/${I(t)}/files`}get queryParameters(){const{limit:e,next:t}=this.parameters;return Object.assign({limit:e},t?{next:t}:{})}}class Bt extends se{constructor(e){super({method:H.POST}),this.parameters=e}operation(){return re.PNGenerateUploadUrlOperation}validate(){return this.parameters.channel?this.parameters.name?void 0:"'name' can't be empty":"channel can't be empty"}parse(e){return i(this,void 0,void 0,(function*(){const t=this.deserializeResponse(e);if(!t)throw new d("Service response error, check status for details",p("Unable to deserialize service response"));if(t.status>=400)throw _.create(e);return{id:t.data.id,name:t.data.name,url:t.file_upload_request.url,formFields:t.file_upload_request.form_fields}}))}get path(){const{keySet:{subscribeKey:e},channel:t}=this.parameters;return`/v1/files/${e}/channels/${I(t)}/generate-upload-url`}get body(){return JSON.stringify({name:this.parameters.name})}}class Ht extends se{constructor(e){super({method:H.POST}),this.parameters=e;const t=e.file.mimeType;t&&(e.formFields=e.formFields.map((e=>"Content-Type"===e.name?{name:e.name,value:t}:e)))}operation(){return re.PNPublishFileOperation}validate(){const{fileId:e,fileName:t,file:s,uploadUrl:n}=this.parameters;return e?t?s?n?void 0:"Validation failed: file upload 'url' can't be empty":"Validation failed: 'file' can't be empty":"Validation failed: file 'name' can't be empty":"Validation failed: file 'id' can't be empty"}parse(e){return i(this,void 0,void 0,(function*(){return{status:e.status,message:e.body?Ht.decoder.decode(e.body):"OK"}}))}request(){return Object.assign(Object.assign({},super.request()),{origin:new URL(this.parameters.uploadUrl).origin,timeout:300})}get path(){const{pathname:e,search:t}=new URL(this.parameters.uploadUrl);return`${e}${t}`}get body(){return this.parameters.file}get formData(){return this.parameters.formFields}}class zt{constructor(e){var t;if(this.parameters=e,this.file=null===(t=this.parameters.PubNubFile)||void 0===t?void 0:t.create(e.file),!this.file)throw new Error("File upload error: unable to create File object.")}process(){return i(this,void 0,void 0,(function*(){let e,t;return this.generateFileUploadUrl().then((s=>(e=s.name,t=s.id,this.uploadFile(s)))).then((e=>{if(204!==e.status)throw new d("Upload to bucket was unsuccessful",{error:!0,statusCode:e.status,category:h.PNUnknownCategory,operation:re.PNPublishFileOperation,errorData:{message:e.message}})})).then((()=>this.publishFileMessage(t,e))).catch((e=>{if(e instanceof d)throw e;const t=e instanceof _?e:_.create(e);throw new d("File upload error.",t.toStatus(re.PNPublishFileOperation))}))}))}generateFileUploadUrl(){return i(this,void 0,void 0,(function*(){const e=new Bt(Object.assign(Object.assign({},this.parameters),{name:this.file.name,keySet:this.parameters.keySet}));return this.parameters.sendRequest(e)}))}uploadFile(e){return i(this,void 0,void 0,(function*(){const{cipherKey:t,PubNubFile:s,crypto:n,cryptography:r}=this.parameters,{id:i,name:o,url:a,formFields:c}=e;return this.parameters.PubNubFile.supportsEncryptFile&&(!t&&n?this.file=yield n.encryptFile(this.file,s):t&&r&&(this.file=yield r.encryptFile(t,this.file,s))),this.parameters.sendRequest(new Ht({fileId:i,fileName:o,file:this.file,uploadUrl:a,formFields:c}))}))}publishFileMessage(e,t){return i(this,void 0,void 0,(function*(){var s,n,r,i;let o,a={timetoken:"0"},c=this.parameters.fileUploadPublishRetryLimit,u=!1;do{try{a=yield this.parameters.publishFile(Object.assign(Object.assign({},this.parameters),{fileId:e,fileName:t})),u=!0}catch(e){e instanceof d&&(o=e),c-=1}}while(!u&&c>0);if(u)return{status:200,timetoken:a.timetoken,id:e,name:t};throw new d("Publish failed. You may want to execute that operation manually using pubnub.publishFile",{error:!0,category:null!==(n=null===(s=o.status)||void 0===s?void 0:s.category)&&void 0!==n?n:h.PNUnknownCategory,statusCode:null!==(i=null===(r=o.status)||void 0===r?void 0:r.statusCode)&&void 0!==i?i:0,channel:this.parameters.channel,id:e,name:t})}))}}class Vt extends se{constructor(e){super({method:H.DELETE}),this.parameters=e}operation(){return re.PNAccessManagerRevokeToken}validate(){return this.parameters.keySet.secretKey?this.parameters.token?void 0:"token can't be empty":"Missing Secret Key"}parse(e){return i(this,void 0,void 0,(function*(){const t=this.deserializeResponse(e);if(!t)throw new d("Service response error, check status for details",p("Unable to deserialize service response"));if(t.status>=400)throw _.create(e);return{}}))}get path(){const{keySet:{subscribeKey:e},token:t}=this.parameters;return`/v3/pam/${e}/grant/${I(t)}`}}class Wt extends se{constructor(e){var t,s,n,r;super({method:H.POST}),this.parameters=e,null!==(t=(n=this.parameters).resources)&&void 0!==t||(n.resources={}),null!==(s=(r=this.parameters).patterns)&&void 0!==s||(r.patterns={})}operation(){return re.PNAccessManagerGrantToken}validate(){var e,t,s,n,r,i;const{keySet:{subscribeKey:o,publishKey:a,secretKey:c},resources:u,patterns:l}=this.parameters;if(!o)return"Missing Subscribe Key";if(!a)return"Missing Publish Key";if(!c)return"Missing Secret Key";if(!u&&!l)return"Missing either Resources or Patterns";if(this.isVspPermissions(this.parameters)&&("channels"in(null!==(e=this.parameters.resources)&&void 0!==e?e:{})||"uuids"in(null!==(t=this.parameters.resources)&&void 0!==t?t:{})||"groups"in(null!==(s=this.parameters.resources)&&void 0!==s?s:{})||"channels"in(null!==(n=this.parameters.patterns)&&void 0!==n?n:{})||"uuids"in(null!==(r=this.parameters.patterns)&&void 0!==r?r:{})||"groups"in(null!==(i=this.parameters.patterns)&&void 0!==i?i:{})))return"Cannot mix `users`, `spaces` and `authorizedUserId` with `uuids`, `channels`, `groups` and `authorized_uuid`";let h=!0;return[this.parameters.resources,this.parameters.patterns].forEach((e=>{Object.keys(null!=e?e:{}).forEach((t=>{var s;e&&h&&Object.keys(null!==(s=e[t])&&void 0!==s?s:{}).length>0&&(h=!1)}))})),h?"Missing values for either Resources or Patterns":void 0}parse(e){return i(this,void 0,void 0,(function*(){const t=this.deserializeResponse(e);if(!t)throw new d("Service response error, check status for details",p("Unable to deserialize service response"));if(t.status>=400)throw _.create(e);return t.data.token}))}get path(){return`/v3/pam/${this.parameters.keySet.subscribeKey}/grant`}get body(){const{ttl:e,meta:t}=this.parameters,s=Object.assign({},e||0===e?{ttl:e}:{}),n=this.isVspPermissions(this.parameters)?this.parameters.authorizedUserId:this.parameters.authorized_uuid,r={},i={},o={},a=(e,t,s,n)=>{n[s]||(n[s]={}),n[s][e]=t},{resources:c,patterns:u}=this.parameters;return[c,u].forEach(((e,t)=>{var s,n,r,c,u;const l=0===t?i:o;let h={},d={},p={};l.channels||(l.channels={}),l.groups||(l.groups={}),l.uuids||(l.uuids={}),l.users||(l.users={}),l.spaces||(l.spaces={}),e&&("spaces"in e||"users"in e?(h=null!==(s=e.spaces)&&void 0!==s?s:{},p=null!==(n=e.users)&&void 0!==n?n:{}):("channels"in e||"uuids"in e||"groups"in e)&&(h=null!==(r=e.channels)&&void 0!==r?r:{},d=null!==(c=e.groups)&&void 0!==c?c:{},p=null!==(u=e.uuids)&&void 0!==u?u:{})),Object.keys(h).forEach((e=>a(e,this.extractPermissions(h[e]),"channels",l))),Object.keys(d).forEach((e=>a(e,this.extractPermissions(d[e]),"groups",l))),Object.keys(p).forEach((e=>a(e,this.extractPermissions(p[e]),"uuids",l)))})),n&&(r.uuid=`${n}`),r.resources=i,r.patterns=o,r.meta=null!=t?t:{},s.permissions=r,JSON.stringify(s)}extractPermissions(e){let t=0;return"join"in e&&e.join&&(t|=128),"update"in e&&e.update&&(t|=64),"get"in e&&e.get&&(t|=32),"delete"in e&&e.delete&&(t|=8),"manage"in e&&e.manage&&(t|=4),"write"in e&&e.write&&(t|=2),"read"in e&&e.read&&(t|=1),t}isVspPermissions(e){var t,s,n,r;return"authorizedUserId"in e||"spaces"in(null!==(t=e.resources)&&void 0!==t?t:{})||"users"in(null!==(s=e.resources)&&void 0!==s?s:{})||"spaces"in(null!==(n=e.patterns)&&void 0!==n?n:{})||"users"in(null!==(r=e.patterns)&&void 0!==r?r:{})}}class Jt extends se{constructor(e){var t,s,n,r,i,o,a,c,u,l,h,d,p,g,y,f,m,b,v,w;super(),this.parameters=e,null!==(t=(h=this.parameters).channels)&&void 0!==t||(h.channels=[]),null!==(s=(d=this.parameters).channelGroups)&&void 0!==s||(d.channelGroups=[]),null!==(n=(p=this.parameters).uuids)&&void 0!==n||(p.uuids=[]),null!==(r=(g=this.parameters).read)&&void 0!==r||(g.read=false),null!==(i=(y=this.parameters).write)&&void 0!==i||(y.write=false),null!==(o=(f=this.parameters).delete)&&void 0!==o||(f.delete=false),null!==(a=(m=this.parameters).get)&&void 0!==a||(m.get=false),null!==(c=(b=this.parameters).update)&&void 0!==c||(b.update=false),null!==(u=(v=this.parameters).manage)&&void 0!==u||(v.manage=false),null!==(l=(w=this.parameters).join)&&void 0!==l||(w.join=false)}operation(){return re.PNAccessManagerGrant}validate(){const{keySet:{subscribeKey:e,publishKey:t,secretKey:s},uuids:n=[],channels:r=[],channelGroups:i=[],authKeys:o=[]}=this.parameters;return e?t?s?0!==n.length&&0===o.length?"authKeys are required for grant request on uuids":!n.length||0===r.length&&0===i.length?void 0:"Both channel/channel group and uuid cannot be used in the same request":"Missing Secret Key":"Missing Publish Key":"Missing Subscribe Key"}parse(e){return i(this,void 0,void 0,(function*(){const t=this.deserializeResponse(e);if(!t)throw new d("Service response error, check status for details",p("Unable to deserialize service response"));if(t.status>=400)throw _.create(e);return t.payload}))}get path(){return`/v2/auth/grant/sub-key/${this.parameters.keySet.subscribeKey}`}get queryParameters(){const{channels:e,channelGroups:t,authKeys:s,uuids:n,read:r,write:i,manage:o,delete:a,get:c,join:u,update:l,ttl:h}=this.parameters;return Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},e&&(null==e?void 0:e.length)>0?{channel:e.join(",")}:{}),t&&(null==t?void 0:t.length)>0?{"channel-group":t.join(",")}:{}),s&&(null==s?void 0:s.length)>0?{auth:s.join(",")}:{}),n&&(null==n?void 0:n.length)>0?{"target-uuid":n.join(",")}:{}),{r:r?"1":"0",w:i?"1":"0",m:o?"1":"0",d:a?"1":"0",g:c?"1":"0",j:u?"1":"0",u:l?"1":"0"}),h||0===h?{ttl:h}:{})}}const Qt=[];class Yt extends se{constructor(e){var t,s;super(),this.parameters=e,null!==(t=(s=this.parameters).authKeys)&&void 0!==t||(s.authKeys=Qt)}operation(){return re.PNAccessManagerAudit}validate(){if(!this.parameters.keySet.subscribeKey)return"Missing Subscribe Key"}parse(e){return i(this,void 0,void 0,(function*(){const t=this.deserializeResponse(e);if(!t)throw new d("Service response error, check status for details",p("Unable to deserialize service response"));if(t.status>=400)throw _.create(e);return t.payload}))}get path(){return`/v2/auth/audit/sub-key/${this.parameters.keySet.subscribeKey}`}get queryParameters(){const{channel:e,channelGroup:t,authKeys:s}=this.parameters;return Object.assign(Object.assign(Object.assign({},e?{channel:e}:{}),t?{"channel-group":t}:{}),s&&s.length?{auth:s.join(",")}:{})}}class Xt{subscribe(){var e,t;this.pubnub.subscribe(Object.assign({channels:this.channelNames,channelGroups:this.groupNames},(null===(t=null===(e=this.options)||void 0===e?void 0:e.cursor)||void 0===t?void 0:t.timetoken)&&{timetoken:this.options.cursor.timetoken}))}unsubscribe(){this.pubnub.unsubscribe({channels:this.channelNames.filter((e=>!e.endsWith("-pnpres"))),channelGroups:this.groupNames.filter((e=>!e.endsWith("-pnpres")))})}set onMessage(e){this.listener.message=e}set onPresence(e){this.listener.presence=e}set onSignal(e){this.listener.signal=e}set onObjects(e){this.listener.objects=e}set onMessageAction(e){this.listener.messageAction=e}set onFile(e){this.listener.file=e}addListener(e){this.eventEmitter.addListener(e,this.channelNames.filter((e=>!e.endsWith("-pnpres"))),this.groupNames.filter((e=>!e.endsWith("-pnpres"))))}removeListener(e){this.eventEmitter.removeListener(e,this.channelNames,this.groupNames)}get channels(){return this.channelNames.slice(0)}get channelGroups(){return this.groupNames.slice(0)}}class Zt extends Xt{constructor({channels:e=[],channelGroups:t=[],subscriptionOptions:s,eventEmitter:n,pubnub:r}){super(),this.channelNames=[],this.groupNames=[],this.subscriptionList=[],this.options=s,this.eventEmitter=n,this.pubnub=r,e.filter((e=>!e.endsWith("-pnpres"))).forEach((e=>{const t=this.pubnub.channel(e).subscription(this.options);this.channelNames=[...this.channelNames,...t.channels],this.subscriptionList.push(t)})),t.filter((e=>!e.endsWith("-pnpres"))).forEach((e=>{const t=this.pubnub.channelGroup(e).subscription(this.options);this.groupNames=[...this.groupNames,...t.channelGroups],this.subscriptionList.push(t)})),this.listener={},n.addListener(this.listener,this.channelNames.filter((e=>!e.endsWith("-pnpres"))),this.groupNames.filter((e=>!e.endsWith("-pnpres"))))}addSubscription(e){this.subscriptionList.push(e),this.channelNames=[...this.channelNames,...e.channels],this.groupNames=[...this.groupNames,...e.channelGroups],this.eventEmitter.addListener(this.listener,e.channels,e.channelGroups)}removeSubscription(e){const t=e.channels,s=e.channelGroups;this.channelNames=this.channelNames.filter((e=>!t.includes(e))),this.groupNames=this.groupNames.filter((e=>!s.includes(e))),this.subscriptionList=this.subscriptionList.filter((t=>t!==e)),this.eventEmitter.removeListener(this.listener,t,s)}addSubscriptionSet(e){this.subscriptionList=[...this.subscriptionList,...e.subscriptions],this.channelNames=[...this.channelNames,...e.channels],this.groupNames=[...this.groupNames,...e.channelGroups],this.eventEmitter.addListener(this.listener,e.channels,e.channelGroups)}removeSubscriptionSet(e){const t=e.channels,s=e.channelGroups;this.channelNames=this.channelNames.filter((e=>!t.includes(e))),this.groupNames=this.groupNames.filter((e=>!s.includes(e))),this.subscriptionList=this.subscriptionList.filter((t=>!e.subscriptions.includes(t))),this.eventEmitter.removeListener(this.listener,t,s)}get subscriptions(){return this.subscriptionList.slice(0)}}class es extends Xt{constructor({channels:e,channelGroups:t,subscriptionOptions:s,eventEmitter:n,pubnub:r}){super(),this.channelNames=[],this.groupNames=[],this.channelNames=e,this.groupNames=t,this.options=s,this.pubnub=r,this.eventEmitter=n,this.listener={},n.addListener(this.listener,this.channelNames.filter((e=>!e.endsWith("-pnpres"))),this.groupNames.filter((e=>!e.endsWith("-pnpres"))))}addSubscription(e){return new Zt({channels:[...this.channelNames,...e.channels],channelGroups:[...this.groupNames,...e.channelGroups],subscriptionOptions:Object.assign(Object.assign({},this.options),null==e?void 0:e.options),eventEmitter:this.eventEmitter,pubnub:this.pubnub})}}class ts{constructor(e,t,s){this.id=e,this.eventEmitter=t,this.pubnub=s}subscription(e){return new es({channels:[this.id],channelGroups:[],subscriptionOptions:e,eventEmitter:this.eventEmitter,pubnub:this.pubnub})}}class ss{constructor(e,t,s){this.eventEmitter=t,this.pubnub=s,this.name=e}subscription(e){return new es({channels:[],channelGroups:(null==e?void 0:e.receivePresenceEvents)?[this.name,`${this.name}-pnpres`]:[this.name],subscriptionOptions:e,eventEmitter:this.eventEmitter,pubnub:this.pubnub})}}class ns{constructor(e,t,s){this.id=e,this.eventEmitter=t,this.pubnub=s}subscription(e){return new es({channels:[this.id],channelGroups:[],subscriptionOptions:e,eventEmitter:this.eventEmitter,pubnub:this.pubnub})}}class rs{constructor(e,t,s){this.eventEmitter=t,this.pubnub=s,this.name=e}subscription(e){return new es({channels:(null==e?void 0:e.receivePresenceEvents)?[this.name,`${this.name}-pnpres`]:[this.name],channelGroups:[],subscriptionOptions:e,eventEmitter:this.eventEmitter,pubnub:this.pubnub})}}class is extends se{constructor(e){super(),this.parameters=e}operation(){return re.PNRemoveChannelsFromGroupOperation}validate(){const{keySet:{subscribeKey:e},channels:t,channelGroup:s}=this.parameters;return e?s?t?void 0:"Missing channels":"Missing Channel Group":"Missing Subscribe Key"}parse(e){return i(this,void 0,void 0,(function*(){const t=this.deserializeResponse(e);if(!t)throw new d("Service response error, check status for details",p("Unable to deserialize service response"));if(t.status>=400)throw _.create(e);return{}}))}get path(){const{keySet:{subscribeKey:e},channelGroup:t}=this.parameters;return`/v1/channel-registration/sub-key/${e}/channel-group/${I(t)}`}get queryParameters(){return{remove:this.parameters.channels.join(",")}}}class os extends se{constructor(e){super(),this.parameters=e}operation(){return re.PNAddChannelsToGroupOperation}validate(){const{keySet:{subscribeKey:e},channels:t,channelGroup:s}=this.parameters;return e?s?t?void 0:"Missing channels":"Missing Channel Group":"Missing Subscribe Key"}parse(e){return i(this,void 0,void 0,(function*(){const t=this.deserializeResponse(e);if(!t)throw new d("Service response error, check status for details",p("Unable to deserialize service response"));if(t.status>=400)throw _.create(e);return{}}))}get path(){const{keySet:{subscribeKey:e},channelGroup:t}=this.parameters;return`/v1/channel-registration/sub-key/${e}/channel-group/${I(t)}`}get queryParameters(){return{add:this.parameters.channels.join(",")}}}class as extends se{constructor(e){super(),this.parameters=e}operation(){return re.PNChannelsForGroupOperation}validate(){return this.parameters.keySet.subscribeKey?this.parameters.channelGroup?void 0:"Missing Channel Group":"Missing Subscribe Key"}parse(e){return i(this,void 0,void 0,(function*(){const t=this.deserializeResponse(e);if(!t)throw new d("Service response error, check status for details",p("Unable to deserialize service response"));if(t.status>=400)throw _.create(e);return{channels:t.payload.channels}}))}get path(){const{keySet:{subscribeKey:e},channelGroup:t}=this.parameters;return`/v1/channel-registration/sub-key/${e}/channel-group/${I(t)}`}}class cs extends se{constructor(e){super(),this.parameters=e}operation(){return re.PNRemoveGroupOperation}validate(){return this.parameters.keySet.subscribeKey?this.parameters.channelGroup?void 0:"Missing Channel Group":"Missing Subscribe Key"}parse(e){return i(this,void 0,void 0,(function*(){const t=this.deserializeResponse(e);if(!t)throw new d("Service response error, check status for details",p("Unable to deserialize service response"));if(t.status>=400)throw _.create(e);return{}}))}get path(){const{keySet:{subscribeKey:e},channelGroup:t}=this.parameters;return`/v1/channel-registration/sub-key/${e}/channel-group/${I(t)}/remove`}}class us extends se{constructor(e){super(),this.parameters=e}operation(){return re.PNChannelGroupsOperation}validate(){if(!this.parameters.keySet.subscribeKey)return"Missing Subscribe Key"}parse(e){return i(this,void 0,void 0,(function*(){const t=this.deserializeResponse(e);if(!t)throw new d("Service response error, check status for details",p("Unable to deserialize service response"));if(t.status>=400)throw _.create(e);return{groups:t.payload.groups}}))}get path(){return`/v1/channel-registration/sub-key/${this.parameters.keySet.subscribeKey}/channel-group`}}class ls{constructor(e,t){this.keySet=e,this.sendRequest=t}listChannels(e,t){return i(this,void 0,void 0,(function*(){const s=new as(Object.assign(Object.assign({},e),{keySet:this.keySet}));return t?this.sendRequest(s,t):this.sendRequest(s)}))}listGroups(e){return i(this,void 0,void 0,(function*(){const t=new us({keySet:this.keySet});return e?this.sendRequest(t,e):this.sendRequest(t)}))}addChannels(e,t){return i(this,void 0,void 0,(function*(){const s=new os(Object.assign(Object.assign({},e),{keySet:this.keySet}));return t?this.sendRequest(s,t):this.sendRequest(s)}))}removeChannels(e,t){return i(this,void 0,void 0,(function*(){const s=new is(Object.assign(Object.assign({},e),{keySet:this.keySet}));return t?this.sendRequest(s,t):this.sendRequest(s)}))}deleteGroup(e,t){return i(this,void 0,void 0,(function*(){const s=new cs(Object.assign(Object.assign({},e),{keySet:this.keySet}));return t?this.sendRequest(s,t):this.sendRequest(s)}))}}class hs extends se{constructor(e){var t,s;super(),this.parameters=e,"apns2"===this.parameters.pushGateway&&(null!==(t=(s=this.parameters).environment)&&void 0!==t||(s.environment="development")),this.parameters.count&&this.parameters.count>1e3&&(this.parameters.count=1e3)}operation(){throw Error("Should be implemented in subclass.")}validate(){const{keySet:{subscribeKey:e},action:t,device:s,pushGateway:n}=this.parameters;return e?s?"add"!==t&&"remove"!==t||"channels"in this.parameters&&0!==this.parameters.channels.length?n?"apns2"!==this.parameters.pushGateway||this.parameters.topic?void 0:"Missing APNS2 topic":"Missing GW Type (pushGateway: gcm or apns2)":"Missing Channels":"Missing Device ID (device)":"Missing Subscribe Key"}parse(e){return i(this,void 0,void 0,(function*(){throw Error("Should be implemented in subclass.")}))}get path(){const{keySet:{subscribeKey:e},action:t,device:s,pushGateway:n}=this.parameters;let r="apns2"===n?`/v2/push/sub-key/${e}/devices-apns2/${s}`:`/v1/push/sub-key/${e}/devices/${s}`;return"remove-device"===t&&(r=`${r}/remove`),r}get queryParameters(){const{start:e,count:t}=this.parameters;let s=Object.assign(Object.assign({type:this.parameters.pushGateway},e?{start:e}:{}),t&&t>0?{count:t}:{});if("channels"in this.parameters&&(s[this.parameters.action]=this.parameters.channels.join(",")),"apns2"===this.parameters.pushGateway){const{environment:e,topic:t}=this.parameters;s=Object.assign(Object.assign({},s),{environment:e,topic:t})}return s}}class ds extends hs{constructor(e){super(Object.assign(Object.assign({},e),{action:"remove"}))}operation(){return re.PNRemovePushNotificationEnabledChannelsOperation}parse(e){return i(this,void 0,void 0,(function*(){if(!this.deserializeResponse(e))throw new d("Service response error, check status for details",p("Unable to deserialize service response"));return{}}))}}class ps extends hs{constructor(e){super(Object.assign(Object.assign({},e),{action:"list"}))}operation(){return re.PNPushNotificationEnabledChannelsOperation}parse(e){return i(this,void 0,void 0,(function*(){const t=this.deserializeResponse(e);if(!t)throw new d("Service response error, check status for details",p("Unable to deserialize service response"));return{channels:t}}))}}class gs extends hs{constructor(e){super(Object.assign(Object.assign({},e),{action:"add"}))}operation(){return re.PNAddPushNotificationEnabledChannelsOperation}parse(e){return i(this,void 0,void 0,(function*(){if(!this.deserializeResponse(e))throw new d("Service response error, check status for details",p("Unable to deserialize service response"));return{}}))}}class ys extends hs{constructor(e){super(Object.assign(Object.assign({},e),{action:"remove-device"}))}operation(){return re.PNRemoveAllPushNotificationsOperation}parse(e){return i(this,void 0,void 0,(function*(){if(!this.deserializeResponse(e))throw new d("Service response error, check status for details",p("Unable to deserialize service response"));return{}}))}}class fs{constructor(e,t){this.keySet=e,this.sendRequest=t}listChannels(e,t){return i(this,void 0,void 0,(function*(){const s=new ps(Object.assign(Object.assign({},e),{keySet:this.keySet}));return t?this.sendRequest(s,t):this.sendRequest(s)}))}addChannels(e,t){return i(this,void 0,void 0,(function*(){const s=new gs(Object.assign(Object.assign({},e),{keySet:this.keySet}));return t?this.sendRequest(s,t):this.sendRequest(s)}))}removeChannels(e,t){return i(this,void 0,void 0,(function*(){const s=new ds(Object.assign(Object.assign({},e),{keySet:this.keySet}));return t?this.sendRequest(s,t):this.sendRequest(s)}))}deleteDevice(e,t){return i(this,void 0,void 0,(function*(){const s=new ys(Object.assign(Object.assign({},e),{keySet:this.keySet}));return t?this.sendRequest(s,t):this.sendRequest(s)}))}}class ms extends se{constructor(e){var t,s,n,r,i,o;super(),this.parameters=e,null!==(t=e.include)&&void 0!==t||(e.include={}),null!==(s=(i=e.include).customFields)&&void 0!==s||(i.customFields=false),null!==(n=(o=e.include).totalCount)&&void 0!==n||(o.totalCount=false),null!==(r=e.limit)&&void 0!==r||(e.limit=100)}operation(){return re.PNGetAllChannelMetadataOperation}parse(e){return i(this,void 0,void 0,(function*(){const t=this.deserializeResponse(e);if(!t)throw new d("Service response error, check status for details",p("Unable to deserialize service response"));if(t.status>=400)throw _.create(e);return t}))}get path(){return`/v2/objects/${this.parameters.keySet.subscribeKey}/channels`}get queryParameters(){const{include:e,page:t,filter:s,sort:n,limit:r}=this.parameters,i=Object.entries(null!=n?n:{}).map((([e,t])=>null!==t?`${e}:${t}`:e));return Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({include:["status","type",...e.customFields?["custom"]:[]].join(","),count:`${e.totalCount}`},s?{filter:s}:{}),(null==t?void 0:t.next)?{start:t.next}:{}),(null==t?void 0:t.prev)?{end:t.prev}:{}),r?{limit:r}:{}),i.length?{sort:i}:{})}}class bs extends se{constructor(e){super({method:H.DELETE}),this.parameters=e}operation(){return re.PNRemoveChannelMetadataOperation}validate(){if(!this.parameters.channel)return"Channel cannot be empty"}parse(e){return i(this,void 0,void 0,(function*(){const t=this.deserializeResponse(e);if(!t)throw new d("Service response error, check status for details",p("Unable to deserialize service response"));if(t.status>=400)throw _.create(e);return t}))}get path(){const{keySet:{subscribeKey:e},channel:t}=this.parameters;return`/v2/objects/${e}/channels/${I(t)}`}}class vs extends se{constructor(e){var t,s,n,r,i,o,a,c,u,l,h,d,p,g,y,f;super(),this.parameters=e,null!==(t=e.include)&&void 0!==t||(e.include={}),null!==(s=(l=e.include).customFields)&&void 0!==s||(l.customFields=false),null!==(n=(h=e.include).totalCount)&&void 0!==n||(h.totalCount=false),null!==(r=(d=e.include).statusField)&&void 0!==r||(d.statusField=false),null!==(i=(p=e.include).channelFields)&&void 0!==i||(p.channelFields=false),null!==(o=(g=e.include).customChannelFields)&&void 0!==o||(g.customChannelFields=false),null!==(a=(y=e.include).channelStatusField)&&void 0!==a||(y.channelStatusField=false),null!==(c=(f=e.include).channelTypeField)&&void 0!==c||(f.channelTypeField=false),null!==(u=e.limit)&&void 0!==u||(e.limit=100),this.parameters.userId&&(this.parameters.uuid=this.parameters.userId)}operation(){return re.PNGetMembershipsOperation}validate(){if(!this.parameters.uuid)return"'uuid' cannot be empty"}parse(e){return i(this,void 0,void 0,(function*(){const t=this.deserializeResponse(e);if(!t)throw new d("Service response error, check status for details",p("Unable to deserialize service response"));if(t.status>=400)throw _.create(e);return t}))}get path(){const{keySet:{subscribeKey:e},uuid:t}=this.parameters;return`/v2/objects/${e}/uuids/${I(t)}/channels`}get queryParameters(){const{include:e,page:t,filter:s,sort:n,limit:r}=this.parameters,i=Object.entries(null!=n?n:{}).map((([e,t])=>null!==t?`${e}:${t}`:e)),o=[];return e.statusField&&o.push("status"),e.customFields&&o.push("custom"),e.channelFields&&o.push("channel"),e.channelStatusField&&o.push("channel.status"),e.channelTypeField&&o.push("channel.type"),e.customChannelFields&&o.push("channel.custom"),Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({count:`${e.totalCount}`},o.length>0?{include:o.join(",")}:{}),s?{filter:s}:{}),(null==t?void 0:t.next)?{start:t.next}:{}),(null==t?void 0:t.prev)?{end:t.prev}:{}),r?{limit:r}:{}),i.length?{sort:i}:{})}}class ws extends se{constructor(e){var t,s,n,r,i,o,a,c,u,l;super({method:H.PATCH}),this.parameters=e,null!==(t=e.include)&&void 0!==t||(e.include={}),null!==(s=(a=e.include).customFields)&&void 0!==s||(a.customFields=false),null!==(n=(c=e.include).totalCount)&&void 0!==n||(c.totalCount=false),null!==(r=(u=e.include).channelFields)&&void 0!==r||(u.channelFields=false),null!==(i=(l=e.include).customChannelFields)&&void 0!==i||(l.customChannelFields=false),null!==(o=e.limit)&&void 0!==o||(e.limit=100),this.parameters.userId&&(this.parameters.uuid=this.parameters.userId)}operation(){return re.PNSetMembershipsOperation}validate(){const{uuid:e,channels:t}=this.parameters;return e?t&&0!==t.length?void 0:"Channels cannot be empty":"'uuid' cannot be empty"}parse(e){return i(this,void 0,void 0,(function*(){const t=this.deserializeResponse(e);if(!t)throw new d("Service response error, check status for details",p("Unable to deserialize service response"));if(t.status>=400)throw _.create(e);return t}))}get path(){const{keySet:{subscribeKey:e},uuid:t}=this.parameters;return`/v2/objects/${e}/uuids/${I(t)}/channels`}get queryParameters(){const{include:e,page:t,filter:s,sort:n,limit:r}=this.parameters,i=Object.entries(null!=n?n:{}).map((([e,t])=>null!==t?`${e}:${t}`:e)),o=["channel.status","channel.type","status"];return e.customFields&&o.push("custom"),e.channelFields&&o.push("channel"),e.customChannelFields&&o.push("channel.custom"),Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({count:`${e.totalCount}`},o.length>0?{include:o.join(",")}:{}),s?{filter:s}:{}),(null==t?void 0:t.next)?{start:t.next}:{}),(null==t?void 0:t.prev)?{end:t.prev}:{}),r?{limit:r}:{}),i.length?{sort:i}:{})}get body(){const{channels:e,type:t}=this.parameters;return JSON.stringify({[`${t}`]:e.map((e=>"string"==typeof e?{channel:{id:e}}:{channel:{id:e.id},status:e.status,custom:e.custom}))})}}class Ss extends se{constructor(e){var t,s,n,r;super(),this.parameters=e,null!==(t=e.include)&&void 0!==t||(e.include={}),null!==(s=(r=e.include).customFields)&&void 0!==s||(r.customFields=false),null!==(n=e.limit)&&void 0!==n||(e.limit=100)}operation(){return re.PNGetAllUUIDMetadataOperation}parse(e){return i(this,void 0,void 0,(function*(){const t=this.deserializeResponse(e);if(!t)throw new d("Service response error, check status for details",p("Unable to deserialize service response"));if(t.status>=400)throw _.create(e);return t}))}get path(){return`/v2/objects/${this.parameters.keySet.subscribeKey}/uuids`}get queryParameters(){const{include:e,page:t,filter:s,sort:n,limit:r}=this.parameters,i=Object.entries(null!=n?n:{}).map((([e,t])=>null!==t?`${e}:${t}`:e));return Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({include:["status","type",...e.customFields?["custom"]:[]].join(",")},void 0!==e.totalCount?{count:`${e.totalCount}`}:{}),s?{filter:s}:{}),(null==t?void 0:t.next)?{start:t.next}:{}),(null==t?void 0:t.prev)?{end:t.prev}:{}),r?{limit:r}:{}),i.length?{sort:i}:{})}}class ks extends se{constructor(e){var t,s,n;super(),this.parameters=e,null!==(t=e.include)&&void 0!==t||(e.include={}),null!==(s=(n=e.include).customFields)&&void 0!==s||(n.customFields=true)}operation(){return re.PNGetChannelMetadataOperation}validate(){if(!this.parameters.channel)return"Channel cannot be empty"}parse(e){return i(this,void 0,void 0,(function*(){const t=this.deserializeResponse(e);if(!t)throw new d("Service response error, check status for details",p("Unable to deserialize service response"));if(t.status>=400)throw _.create(e);return t}))}get path(){const{keySet:{subscribeKey:e},channel:t}=this.parameters;return`/v2/objects/${e}/channels/${I(t)}`}get queryParameters(){return{include:["status","type",...this.parameters.include.customFields?["custom"]:[]].join(",")}}}class Es extends se{constructor(e){var t,s,n;super({method:H.PATCH}),this.parameters=e,null!==(t=e.include)&&void 0!==t||(e.include={}),null!==(s=(n=e.include).customFields)&&void 0!==s||(n.customFields=true)}operation(){return re.PNSetChannelMetadataOperation}validate(){return this.parameters.channel?this.parameters.data?void 0:"Data cannot be empty":"Channel cannot be empty"}parse(e){return i(this,void 0,void 0,(function*(){const t=this.deserializeResponse(e);if(!t)throw new d("Service response error, check status for details",p("Unable to deserialize service response"));if(t.status>=400)throw _.create(e);return t}))}get path(){const{keySet:{subscribeKey:e},channel:t}=this.parameters;return`/v2/objects/${e}/channels/${I(t)}`}get queryParameters(){return{include:["status","type",...this.parameters.include.customFields?["custom"]:[]].join(",")}}get body(){return JSON.stringify(this.parameters.data)}}class Os extends se{constructor(e){super({method:H.DELETE}),this.parameters=e,this.parameters.userId&&(this.parameters.uuid=this.parameters.userId)}operation(){return re.PNRemoveUUIDMetadataOperation}validate(){if(!this.parameters.uuid)return"'uuid' cannot be empty"}parse(e){return i(this,void 0,void 0,(function*(){const t=this.deserializeResponse(e);if(!t)throw new d("Service response error, check status for details",p("Unable to deserialize service response"));if(t.status>=400)throw _.create(e);return t}))}get path(){const{keySet:{subscribeKey:e},uuid:t}=this.parameters;return`/v2/objects/${e}/uuids/${I(t)}`}}class Cs extends se{constructor(e){var t,s,n,r,i,o,a,c,u,l,h,d,p,g,y,f;super(),this.parameters=e,null!==(t=e.include)&&void 0!==t||(e.include={}),null!==(s=(l=e.include).customFields)&&void 0!==s||(l.customFields=false),null!==(n=(h=e.include).totalCount)&&void 0!==n||(h.totalCount=false),null!==(r=(d=e.include).statusField)&&void 0!==r||(d.statusField=false),null!==(i=(p=e.include).UUIDFields)&&void 0!==i||(p.UUIDFields=false),null!==(o=(g=e.include).customUUIDFields)&&void 0!==o||(g.customUUIDFields=false),null!==(a=(y=e.include).UUIDStatusField)&&void 0!==a||(y.UUIDStatusField=false),null!==(c=(f=e.include).UUIDTypeField)&&void 0!==c||(f.UUIDTypeField=false),null!==(u=e.limit)&&void 0!==u||(e.limit=100)}operation(){return re.PNSetMembersOperation}validate(){if(!this.parameters.channel)return"Channel cannot be empty"}parse(e){return i(this,void 0,void 0,(function*(){const t=this.deserializeResponse(e);if(!t)throw new d("Service response error, check status for details",p("Unable to deserialize service response"));if(t.status>=400)throw _.create(e);return t}))}get path(){const{keySet:{subscribeKey:e},channel:t}=this.parameters;return`/v2/objects/${e}/channels/${I(t)}/uuids`}get queryParameters(){const{include:e,page:t,filter:s,sort:n,limit:r}=this.parameters,i=Object.entries(null!=n?n:{}).map((([e,t])=>null!==t?`${e}:${t}`:e)),o=[];return e.statusField&&o.push("status"),e.customFields&&o.push("custom"),e.UUIDFields&&o.push("uuid"),e.UUIDStatusField&&o.push("uuid.status"),e.UUIDTypeField&&o.push("uuid.type"),e.customUUIDFields&&o.push("uuid.custom"),Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({count:`${e.totalCount}`},o.length>0?{include:o.join(",")}:{}),s?{filter:s}:{}),(null==t?void 0:t.next)?{start:t.next}:{}),(null==t?void 0:t.prev)?{end:t.prev}:{}),r?{limit:r}:{}),i.length?{sort:i}:{})}}class Ns extends se{constructor(e){var t,s,n,r,i,o,a,c,u,l;super({method:H.PATCH}),this.parameters=e,null!==(t=e.include)&&void 0!==t||(e.include={}),null!==(s=(a=e.include).customFields)&&void 0!==s||(a.customFields=false),null!==(n=(c=e.include).totalCount)&&void 0!==n||(c.totalCount=false),null!==(r=(u=e.include).UUIDFields)&&void 0!==r||(u.UUIDFields=false),null!==(i=(l=e.include).customUUIDFields)&&void 0!==i||(l.customUUIDFields=false),null!==(o=e.limit)&&void 0!==o||(e.limit=100)}operation(){return re.PNSetMembersOperation}validate(){const{channel:e,uuids:t}=this.parameters;return e?t&&0!==t.length?void 0:"UUIDs cannot be empty":"Channel cannot be empty"}parse(e){return i(this,void 0,void 0,(function*(){const t=this.deserializeResponse(e);if(!t)throw new d("Service response error, check status for details",p("Unable to deserialize service response"));if(t.status>=400)throw _.create(e);return t}))}get path(){const{keySet:{subscribeKey:e},channel:t}=this.parameters;return`/v2/objects/${e}/channels/${I(t)}/uuids`}get queryParameters(){const{include:e,page:t,filter:s,sort:n,limit:r}=this.parameters,i=Object.entries(null!=n?n:{}).map((([e,t])=>null!==t?`${e}:${t}`:e)),o=["uuid.status","uuid.type","type"];return e.customFields&&o.push("custom"),e.UUIDFields&&o.push("uuid"),e.customUUIDFields&&o.push("uuid.custom"),Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({count:`${e.totalCount}`},o.length>0?{include:o.join(",")}:{}),s?{filter:s}:{}),(null==t?void 0:t.next)?{start:t.next}:{}),(null==t?void 0:t.prev)?{end:t.prev}:{}),r?{limit:r}:{}),i.length?{sort:i}:{})}get body(){const{uuids:e,type:t}=this.parameters;return JSON.stringify({[`${t}`]:e.map((e=>"string"==typeof e?{uuid:{id:e}}:{uuid:{id:e.id},status:e.status,custom:e.custom}))})}}class Ps extends se{constructor(e){var t,s,n;super(),this.parameters=e,null!==(t=e.include)&&void 0!==t||(e.include={}),null!==(s=(n=e.include).customFields)&&void 0!==s||(n.customFields=true),this.parameters.userId&&(this.parameters.uuid=this.parameters.userId)}operation(){return re.PNGetUUIDMetadataOperation}validate(){if(!this.parameters.uuid)return"'uuid' cannot be empty"}parse(e){return i(this,void 0,void 0,(function*(){const t=this.deserializeResponse(e);if(!t)throw new d("Service response error, check status for details",p("Unable to deserialize service response"));if(t.status>=400)throw _.create(e);return t}))}get path(){const{keySet:{subscribeKey:e},uuid:t}=this.parameters;return`/v2/objects/${e}/uuids/${I(t)}`}get queryParameters(){const{include:e}=this.parameters;return{include:["status","type",...e.customFields?["custom"]:[]].join(",")}}}class Ms extends se{constructor(e){var t,s,n;super({method:H.PATCH}),this.parameters=e,null!==(t=e.include)&&void 0!==t||(e.include={}),null!==(s=(n=e.include).customFields)&&void 0!==s||(n.customFields=true),this.parameters.userId&&(this.parameters.uuid=this.parameters.userId)}operation(){return re.PNSetUUIDMetadataOperation}validate(){return this.parameters.uuid?this.parameters.data?void 0:"Data cannot be empty":"'uuid' cannot be empty"}parse(e){return i(this,void 0,void 0,(function*(){const t=this.deserializeResponse(e);if(!t)throw new d("Service response error, check status for details",p("Unable to deserialize service response"));if(t.status>=400)throw _.create(e);return t}))}get path(){const{keySet:{subscribeKey:e},uuid:t}=this.parameters;return`/v2/objects/${e}/uuids/${I(t)}`}get queryParameters(){return{include:["status","type",...this.parameters.include.customFields?["custom"]:[]].join(",")}}get body(){return JSON.stringify(this.parameters.data)}}class js{constructor(e,t){this.configuration=e,this.sendRequest=t,this.keySet=e.keySet}getAllUUIDMetadata(e,t){return i(this,void 0,void 0,(function*(){return this._getAllUUIDMetadata(e,t)}))}_getAllUUIDMetadata(e,t){return i(this,void 0,void 0,(function*(){const s=e&&"function"!=typeof e?e:{};null!=t||(t="function"==typeof e?e:void 0);const n=new Ss(Object.assign(Object.assign({},s),{keySet:this.keySet}));return t?this.sendRequest(n,t):this.sendRequest(n)}))}getUUIDMetadata(e,t){return i(this,void 0,void 0,(function*(){return this._getUUIDMetadata(e,t)}))}_getUUIDMetadata(e,t){return i(this,void 0,void 0,(function*(){var s;const n=e&&"function"!=typeof e?e:{};null!=t||(t="function"==typeof e?e:void 0),n.userId&&(n.uuid=n.userId),null!==(s=n.uuid)&&void 0!==s||(n.uuid=this.configuration.userId);const r=new Ps(Object.assign(Object.assign({},n),{keySet:this.keySet}));return t?this.sendRequest(r,t):this.sendRequest(r)}))}setUUIDMetadata(e,t){return i(this,void 0,void 0,(function*(){return this._setUUIDMetadata(e,t)}))}_setUUIDMetadata(e,t){return i(this,void 0,void 0,(function*(){var s;e.userId&&(e.uuid=e.userId),null!==(s=e.uuid)&&void 0!==s||(e.uuid=this.configuration.userId);const n=new Ms(Object.assign(Object.assign({},e),{keySet:this.keySet}));return t?this.sendRequest(n,t):this.sendRequest(n)}))}removeUUIDMetadata(e,t){return i(this,void 0,void 0,(function*(){return this._removeUUIDMetadata(e,t)}))}_removeUUIDMetadata(e,t){return i(this,void 0,void 0,(function*(){var s;const n=e&&"function"!=typeof e?e:{};null!=t||(t="function"==typeof e?e:void 0),n.userId&&(n.uuid=n.userId),null!==(s=n.uuid)&&void 0!==s||(n.uuid=this.configuration.userId);const r=new Os(Object.assign(Object.assign({},n),{keySet:this.keySet}));return t?this.sendRequest(r,t):this.sendRequest(r)}))}getAllChannelMetadata(e,t){return i(this,void 0,void 0,(function*(){return this._getAllChannelMetadata(e,t)}))}_getAllChannelMetadata(e,t){return i(this,void 0,void 0,(function*(){const s=e&&"function"!=typeof e?e:{};null!=t||(t="function"==typeof e?e:void 0);const n=new ms(Object.assign(Object.assign({},s),{keySet:this.keySet}));return t?this.sendRequest(n,t):this.sendRequest(n)}))}getChannelMetadata(e,t){return i(this,void 0,void 0,(function*(){return this._getChannelMetadata(e,t)}))}_getChannelMetadata(e,t){return i(this,void 0,void 0,(function*(){const s=new ks(Object.assign(Object.assign({},e),{keySet:this.keySet}));return t?this.sendRequest(s,t):this.sendRequest(s)}))}setChannelMetadata(e,t){return i(this,void 0,void 0,(function*(){return this._setChannelMetadata(e,t)}))}_setChannelMetadata(e,t){return i(this,void 0,void 0,(function*(){const s=new Es(Object.assign(Object.assign({},e),{keySet:this.keySet}));return t?this.sendRequest(s,t):this.sendRequest(s)}))}removeChannelMetadata(e,t){return i(this,void 0,void 0,(function*(){return this._removeChannelMetadata(e,t)}))}_removeChannelMetadata(e,t){return i(this,void 0,void 0,(function*(){const s=new bs(Object.assign(Object.assign({},e),{keySet:this.keySet}));return t?this.sendRequest(s,t):this.sendRequest(s)}))}getChannelMembers(e,t){return i(this,void 0,void 0,(function*(){const s=new Cs(Object.assign(Object.assign({},e),{keySet:this.keySet}));return t?this.sendRequest(s,t):this.sendRequest(s)}))}setChannelMembers(e,t){return i(this,void 0,void 0,(function*(){const s=new Ns(Object.assign(Object.assign({},e),{type:"set",keySet:this.keySet}));return t?this.sendRequest(s,t):this.sendRequest(s)}))}removeChannelMembers(e,t){return i(this,void 0,void 0,(function*(){const s=new Ns(Object.assign(Object.assign({},e),{type:"delete",keySet:this.keySet}));return t?this.sendRequest(s,t):this.sendRequest(s)}))}getMemberships(e,t){return i(this,void 0,void 0,(function*(){var s;const n=e&&"function"!=typeof e?e:{};null!=t||(t="function"==typeof e?e:void 0),n.userId&&(n.uuid=n.userId),null!==(s=n.uuid)&&void 0!==s||(n.uuid=this.configuration.userId);const r=new vs(Object.assign(Object.assign({},n),{keySet:this.keySet}));return t?this.sendRequest(r,t):this.sendRequest(r)}))}setMemberships(e,t){return i(this,void 0,void 0,(function*(){var s;e.userId&&(e.uuid=e.userId),null!==(s=e.uuid)&&void 0!==s||(e.uuid=this.configuration.userId);const n=new ws(Object.assign(Object.assign({},e),{type:"set",keySet:this.keySet}));return t?this.sendRequest(n,t):this.sendRequest(n)}))}removeMemberships(e,t){return i(this,void 0,void 0,(function*(){var s;e.userId&&(e.uuid=e.userId),null!==(s=e.uuid)&&void 0!==s||(e.uuid=this.configuration.userId);const n=new ws(Object.assign(Object.assign({},e),{type:"delete",keySet:this.keySet}));return t?this.sendRequest(n,t):this.sendRequest(n)}))}fetchMemberships(e,t){return i(this,void 0,void 0,(function*(){var s,n;if("spaceId"in e){const n=e,r={channel:null!==(s=n.spaceId)&&void 0!==s?s:n.channel,filter:n.filter,limit:n.limit,page:n.page,include:Object.assign({},n.include),sort:n.sort?Object.fromEntries(Object.entries(n.sort).map((([e,t])=>[e.replace("user","uuid"),t]))):void 0},i=e=>({status:e.status,data:e.data.map((e=>({user:e.uuid,custom:e.custom,updated:e.updated,eTag:e.eTag}))),totalCount:e.totalCount,next:e.next,prev:e.prev});return t?this.getChannelMembers(r,((e,s)=>{t(e,s?i(s):s)})):this.getChannelMembers(r).then(i)}const r=e,i={uuid:null!==(n=r.userId)&&void 0!==n?n:r.uuid,filter:r.filter,limit:r.limit,page:r.page,include:Object.assign({},r.include),sort:r.sort?Object.fromEntries(Object.entries(r.sort).map((([e,t])=>[e.replace("space","channel"),t]))):void 0},o=e=>({status:e.status,data:e.data.map((e=>({space:e.channel,custom:e.custom,updated:e.updated,eTag:e.eTag}))),totalCount:e.totalCount,next:e.next,prev:e.prev});return t?this.getMemberships(i,((e,s)=>{t(e,s?o(s):s)})):this.getMemberships(i).then(o)}))}addMemberships(e,t){return i(this,void 0,void 0,(function*(){var s,n,r,i,o,a;if("spaceId"in e){const i=e,o={channel:null!==(s=i.spaceId)&&void 0!==s?s:i.channel,uuids:null!==(r=null===(n=i.users)||void 0===n?void 0:n.map((e=>"string"==typeof e?e:(e.userId,{id:e.userId,custom:e.custom}))))&&void 0!==r?r:i.uuids,limit:0};return t?this.setChannelMembers(o,t):this.setChannelMembers(o)}const c=e,u={uuid:null!==(i=c.userId)&&void 0!==i?i:c.uuid,channels:null!==(a=null===(o=c.spaces)||void 0===o?void 0:o.map((e=>"string"==typeof e?e:{id:e.spaceId,custom:e.custom})))&&void 0!==a?a:c.channels,limit:0};return t?this.setMemberships(u,t):this.setMemberships(u)}))}}class _s extends se{constructor(){super()}operation(){return re.PNTimeOperation}parse(e){return i(this,void 0,void 0,(function*(){const t=this.deserializeResponse(e);if(!t)throw new d("Service response error, check status for details",p("Unable to deserialize service response"));return{timetoken:t[0]}}))}get path(){return"/time/0"}}class As extends se{constructor(e){super(),this.parameters=e}operation(){return re.PNDownloadFileOperation}validate(){const{channel:e,id:t,name:s}=this.parameters;return e?t?s?void 0:"file name can't be empty":"file id can't be empty":"channel can't be empty"}parse(e){return i(this,void 0,void 0,(function*(){const{cipherKey:t,crypto:s,cryptography:n,name:r,PubNubFile:i}=this.parameters,o=e.headers["content-type"];let a,c=e.body;return i.supportsEncryptFile&&(t||s)&&(t&&n?c=yield n.decrypt(t,c):!t&&s&&(a=yield s.decryptFile(i.create({data:c,name:r,mimeType:o}),i))),a||i.create({data:c,name:r,mimeType:o})}))}get path(){const{keySet:{subscribeKey:e},channel:t,id:s,name:n}=this.parameters;return`/v1/files/${e}/channels/${I(t)}/files/${s}/${n}`}}class Is{static notificationPayload(e,t){return new te(e,t)}static generateUUID(){return G.createUUID()}constructor(e){if(this._configuration=e.configuration,this.cryptography=e.cryptography,this.tokenManager=e.tokenManager,this.transport=e.transport,this.crypto=e.crypto,this._objects=new js(this._configuration,this.sendRequest.bind(this)),this._channelGroups=new ls(this._configuration.keySet,this.sendRequest.bind(this)),this._push=new fs(this._configuration.keySet,this.sendRequest.bind(this)),this.listenerManager=new W,this.eventEmitter=new ce(this.listenerManager),this._configuration.enableEventEngine){let e=this._configuration.getHeartbeatInterval();this.presenceState={},e&&(this.presenceEventEngine=new $e({heartbeat:this.heartbeat.bind(this),leave:e=>this.makeUnsubscribe(e,(()=>{})),heartbeatDelay:()=>new Promise(((t,s)=>{e=this._configuration.getHeartbeatInterval(),e?setTimeout(t,1e3*e):s(new d("Heartbeat interval has been reset."))})),retryDelay:e=>new Promise((t=>setTimeout(t,e))),emitStatus:e=>this.listenerManager.announceStatus(e),config:this._configuration,presenceState:this.presenceState})),this.eventEngine=new St({handshake:this.subscribeHandshake.bind(this),receiveMessages:this.subscribeReceiveMessages.bind(this),delay:e=>new Promise((t=>setTimeout(t,e))),join:this.join.bind(this),leave:this.leave.bind(this),leaveAll:this.leaveAll.bind(this),presenceState:this.presenceState,config:this._configuration,emitMessages:e=>{try{e.forEach((e=>this.eventEmitter.emitEvent(e)))}catch(e){const t={error:!0,category:h.PNUnknownCategory,errorData:e,statusCode:0};this.listenerManager.announceStatus(t)}},emitStatus:e=>this.listenerManager.announceStatus(e)})}else this.subscriptionManager=new Y(this._configuration,this.listenerManager,this.eventEmitter,this.makeSubscribe.bind(this),this.heartbeat.bind(this),this.makeUnsubscribe.bind(this),this.time.bind(this))}get configuration(){return this._configuration}get _config(){return this.configuration}get authKey(){var e;return null!==(e=this._configuration.authKey)&&void 0!==e?e:void 0}getAuthKey(){return this.authKey}setAuthKey(e){this._configuration.setAuthKey(e)}get userId(){return this._configuration.userId}set userId(e){if(!e||"string"!=typeof e||0===e.trim().length)throw new Error("Missing or invalid userId parameter. Provide a valid string userId");this._configuration.userId=e}getUserId(){return this._configuration.userId}setUserId(e){if(!e||"string"!=typeof e||0===e.trim().length)throw new Error("Missing or invalid userId parameter. Provide a valid string userId");this._configuration.userId=e}get filterExpression(){var e;return null!==(e=this._configuration.getFilterExpression())&&void 0!==e?e:void 0}getFilterExpression(){return this.filterExpression}set filterExpression(e){this._configuration.setFilterExpression(e)}setFilterExpression(e){this.filterExpression=e}get cipherKey(){return this._configuration.getCipherKey()}set cipherKey(e){this._configuration.setCipherKey(e)}setCipherKey(e){this.cipherKey=e}set heartbeatInterval(e){this._configuration.setHeartbeatInterval(e)}setHeartbeatInterval(e){this.heartbeatInterval=e}getVersion(){return this._configuration.getVersion()}_addPnsdkSuffix(e,t){this._configuration._addPnsdkSuffix(e,t)}getUUID(){return this.userId}setUUID(e){this.userId=e}get customEncrypt(){return this._configuration.getCustomEncrypt()}get customDecrypt(){return this._configuration.getCustomDecrypt()}channel(e){return new rs(e,this.eventEmitter,this)}channelGroup(e){return new ss(e,this.eventEmitter,this)}channelMetadata(e){return new ts(e,this.eventEmitter,this)}userMetadata(e){return new ns(e,this.eventEmitter,this)}subscriptionSet(e){return new Zt(Object.assign(Object.assign({},e),{eventEmitter:this.eventEmitter,pubnub:this}))}sendRequest(e,t){return i(this,void 0,void 0,(function*(){const s=e.validate();if(s){if(t)return t(p(s),null);throw new d("Validation failed, check status for details",p(s))}const n=e.request();n.formData&&n.formData.length>0?n.timeout=300:e.operation()===re.PNSubscribeOperation?n.timeout=this._configuration.getSubscribeTimeout():n.timeout=this._configuration.getTransactionTimeout();const r={error:!1,operation:e.operation(),category:h.PNAcknowledgmentCategory,statusCode:0},[i,o]=this.transport.makeSendable(n);return e.cancellationController=o||null,i.then((t=>{if(r.statusCode=t.status,200!==t.status&&204!==t.status){const e=t.headers["content-type"];if(e||-1!==e.indexOf("javascript")||-1!==e.indexOf("json")){const e=JSON.parse(Is.decoder.decode(t.body));"object"==typeof e&&"error"in e&&e.error&&"object"==typeof e.error&&(r.errorData=e.error)}}return e.parse(t)})).then((e=>t?t(r,e):e)).catch((s=>{const n=s instanceof _?s:_.create(s);if(t)return t(n.toStatus(e.operation()),null);throw n.toPubNubError(e.operation(),"REST API request processing error, check status for details")}))}))}destroy(e){this.subscriptionManager?(this.subscriptionManager.unsubscribeAll(e),this.subscriptionManager.disconnect()):this.eventEngine&&this.eventEngine.dispose()}stop(){this.destroy()}addListener(e){this.listenerManager.addListener(e)}removeListener(e){this.listenerManager.removeListener(e)}removeAllListeners(){this.listenerManager.removeAllListeners()}publish(e,t){return i(this,void 0,void 0,(function*(){const s=new kt(Object.assign(Object.assign({},e),{keySet:this._configuration.keySet,crypto:this._configuration.getCryptoModule()}));return t?this.sendRequest(s,t):this.sendRequest(s)}))}signal(e,t){return i(this,void 0,void 0,(function*(){const s=new Et(Object.assign(Object.assign({},e),{keySet:this._configuration.keySet}));return t?this.sendRequest(s,t):this.sendRequest(s)}))}fire(e,t){return i(this,void 0,void 0,(function*(){return null!=t||(t=()=>{}),this.publish(Object.assign(Object.assign({},e),{replicate:!1,storeInHistory:!1}),t)}))}getSubscribedChannels(){return this.subscriptionManager?this.subscriptionManager.subscribedChannels:this.eventEngine?this.eventEngine.getSubscribedChannels():[]}getSubscribedChannelGroups(){return this.subscriptionManager?this.subscriptionManager.subscribedChannelGroups:this.eventEngine?this.eventEngine.getSubscribedChannelGroups():[]}subscribe(e){this.subscriptionManager?this.subscriptionManager.subscribe(e):this.eventEngine&&this.eventEngine.subscribe(e)}makeSubscribe(e,t){const s=new ae(Object.assign(Object.assign({},e),{keySet:this._configuration.keySet,crypto:this._configuration.getCryptoModule(),getFileUrl:this.getFileUrl.bind(this)}));if(this.sendRequest(s,((e,n)=>{var r;this.subscriptionManager&&(null===(r=this.subscriptionManager.abort)||void 0===r?void 0:r.identifier)===s.requestIdentifier&&(this.subscriptionManager.abort=null),t(e,n)})),this.subscriptionManager){const e=()=>s.abort();e.identifier=s.requestIdentifier,this.subscriptionManager.abort=e}}unsubscribe(e){this.subscriptionManager?this.subscriptionManager.unsubscribe(e):this.eventEngine&&this.eventEngine.unsubscribe(e)}makeUnsubscribe(e,t){this.sendRequest(new jt(Object.assign(Object.assign({},e),{keySet:this._configuration.keySet})),t)}unsubscribeAll(){this.subscriptionManager?this.subscriptionManager.unsubscribeAll():this.eventEngine&&this.eventEngine.unsubscribeAll()}disconnect(){this.subscriptionManager?this.subscriptionManager.disconnect():this.eventEngine&&this.eventEngine.disconnect()}reconnect(e){this.subscriptionManager?this.subscriptionManager.reconnect():this.eventEngine&&this.eventEngine.reconnect(null!=e?e:{})}subscribeHandshake(e){return i(this,void 0,void 0,(function*(){const t=new Ct(Object.assign(Object.assign({},e),{keySet:this._configuration.keySet,crypto:this._configuration.getCryptoModule(),getFileUrl:this.getFileUrl.bind(this)})),s=e.abortSignal.subscribe((e=>{t.abort()}));return this.sendRequest(t).then((e=>(s(),e.cursor)))}))}subscribeReceiveMessages(e){return i(this,void 0,void 0,(function*(){const t=new Ot(Object.assign(Object.assign({},e),{keySet:this._configuration.keySet,crypto:this._configuration.getCryptoModule(),getFileUrl:this.getFileUrl.bind(this)})),s=e.abortSignal.subscribe((e=>{t.abort()}));return this.sendRequest(t).then((e=>(s(),e)))}))}getMessageActions(e,t){return i(this,void 0,void 0,(function*(){const s=new xt(Object.assign(Object.assign({},e),{keySet:this._configuration.keySet}));return t?this.sendRequest(s,t):this.sendRequest(s)}))}addMessageAction(e,t){return i(this,void 0,void 0,(function*(){const s=new Dt(Object.assign(Object.assign({},e),{keySet:this._configuration.keySet}));return t?this.sendRequest(s,t):this.sendRequest(s)}))}removeMessageAction(e,t){return i(this,void 0,void 0,(function*(){const s=new Kt(Object.assign(Object.assign({},e),{keySet:this._configuration.keySet}));return t?this.sendRequest(s,t):this.sendRequest(s)}))}fetchMessages(e,t){return i(this,void 0,void 0,(function*(){const s=new Ft(Object.assign(Object.assign({},e),{keySet:this._configuration.keySet,crypto:this._configuration.getCryptoModule(),getFileUrl:this.getFileUrl.bind(this)}));return t?this.sendRequest(s,t):this.sendRequest(s)}))}deleteMessages(e,t){return i(this,void 0,void 0,(function*(){const s=new It(Object.assign(Object.assign({},e),{keySet:this._configuration.keySet}));return t?this.sendRequest(s,t):this.sendRequest(s)}))}messageCounts(e,t){return i(this,void 0,void 0,(function*(){const s=new Rt(Object.assign(Object.assign({},e),{keySet:this._configuration.keySet}));return t?this.sendRequest(s,t):this.sendRequest(s)}))}history(e,t){return i(this,void 0,void 0,(function*(){const s=new Ut(Object.assign(Object.assign({},e),{keySet:this._configuration.keySet,crypto:this._configuration.getCryptoModule()}));return t?this.sendRequest(s,t):this.sendRequest(s)}))}hereNow(e,t){return i(this,void 0,void 0,(function*(){const s=new At(Object.assign(Object.assign({},e),{keySet:this._configuration.keySet}));return t?this.sendRequest(s,t):this.sendRequest(s)}))}whereNow(e,t){return i(this,void 0,void 0,(function*(){var s;const n=new _t({uuid:null!==(s=e.uuid)&&void 0!==s?s:this._configuration.userId,keySet:this._configuration.keySet});return t?this.sendRequest(n,t):this.sendRequest(n)}))}getState(e,t){return i(this,void 0,void 0,(function*(){var s;const n=new Nt(Object.assign(Object.assign({},e),{uuid:null!==(s=e.uuid)&&void 0!==s?s:this._configuration.userId,keySet:this._configuration.keySet}));return t?this.sendRequest(n,t):this.sendRequest(n)}))}setState(e,t){return i(this,void 0,void 0,(function*(){var s,n;const{keySet:r,userId:i}=this._configuration,o=this._configuration.getPresenceTimeout();let a;if(this._configuration.enableEventEngine&&this.presenceState){const t=this.presenceState;null===(s=e.channels)||void 0===s||s.forEach((s=>t[s]=e.state)),"channelGroups"in e&&(null===(n=e.channelGroups)||void 0===n||n.forEach((s=>t[s]=e.state)))}return a="withHeartbeat"in e?new Mt(Object.assign(Object.assign({},e),{keySet:r,heartbeat:o})):new Pt(Object.assign(Object.assign({},e),{keySet:r,uuid:i})),this.subscriptionManager&&this.subscriptionManager.setState(e),t?this.sendRequest(a,t):this.sendRequest(a)}))}presence(e){var t;null===(t=this.subscriptionManager)||void 0===t||t.changePresence(e)}heartbeat(e,t){return i(this,void 0,void 0,(function*(){const s=new Mt(Object.assign(Object.assign({},e),{keySet:this._configuration.keySet}));return t?this.sendRequest(s,t):this.sendRequest(s)}))}join(e){var t;null===(t=this.presenceEventEngine)||void 0===t||t.join(e)}leave(e){var t;null===(t=this.presenceEventEngine)||void 0===t||t.leave(e)}leaveAll(){var e;null===(e=this.presenceEventEngine)||void 0===e||e.leaveAll()}grantToken(e,t){return i(this,void 0,void 0,(function*(){const s=new Wt(Object.assign(Object.assign({},e),{keySet:this._configuration.keySet}));return t?this.sendRequest(s,t):this.sendRequest(s)}))}revokeToken(e,t){return i(this,void 0,void 0,(function*(){const s=new Vt(Object.assign(Object.assign({},e),{keySet:this._configuration.keySet}));return t?this.sendRequest(s,t):this.sendRequest(s)}))}get token(){return this.tokenManager.getToken()}getToken(){return this.token}set token(e){this.tokenManager.setToken(e)}setToken(e){this.token=e}parseToken(e){return this.tokenManager.parseToken(e)}grant(e,t){return i(this,void 0,void 0,(function*(){const s=new Jt(Object.assign(Object.assign({},e),{keySet:this._configuration.keySet}));return t?this.sendRequest(s,t):this.sendRequest(s)}))}audit(e,t){return i(this,void 0,void 0,(function*(){const s=new Yt(Object.assign(Object.assign({},e),{keySet:this._configuration.keySet}));return t?this.sendRequest(s,t):this.sendRequest(s)}))}get objects(){return this._objects}fetchUsers(e,t){return i(this,void 0,void 0,(function*(){return this.objects._getAllUUIDMetadata(e,t)}))}fetchUser(e,t){return i(this,void 0,void 0,(function*(){return this.objects._getUUIDMetadata(e,t)}))}createUser(e,t){return i(this,void 0,void 0,(function*(){return this.objects._setUUIDMetadata(e,t)}))}updateUser(e,t){return i(this,void 0,void 0,(function*(){return this.objects._setUUIDMetadata(e,t)}))}removeUser(e,t){return i(this,void 0,void 0,(function*(){return this.objects._removeUUIDMetadata(e,t)}))}fetchSpaces(e,t){return i(this,void 0,void 0,(function*(){return this.objects._getAllChannelMetadata(e,t)}))}fetchSpace(e,t){return i(this,void 0,void 0,(function*(){return this.objects._getChannelMetadata(e,t)}))}createSpace(e,t){return i(this,void 0,void 0,(function*(){return this.objects._setChannelMetadata(e,t)}))}updateSpace(e,t){return i(this,void 0,void 0,(function*(){return this.objects._setChannelMetadata(e,t)}))}removeSpace(e,t){return i(this,void 0,void 0,(function*(){return this.objects._removeChannelMetadata(e,t)}))}fetchMemberships(e,t){return i(this,void 0,void 0,(function*(){return this.objects.fetchMemberships(e,t)}))}addMemberships(e,t){return i(this,void 0,void 0,(function*(){return this.objects.addMemberships(e,t)}))}updateMemberships(e,t){return i(this,void 0,void 0,(function*(){return this.objects.addMemberships(e,t)}))}removeMemberships(e,t){return i(this,void 0,void 0,(function*(){var s,n,r;if("spaceId"in e){const r=e,i={channel:null!==(s=r.spaceId)&&void 0!==s?s:r.channel,uuids:null!==(n=r.userIds)&&void 0!==n?n:r.uuids,limit:0};return t?this.objects.removeChannelMembers(i,t):this.objects.removeChannelMembers(i)}const i=e,o={uuid:i.userId,channels:null!==(r=i.spaceIds)&&void 0!==r?r:i.channels,limit:0};return t?this.objects.removeMemberships(o,t):this.objects.removeMemberships(o)}))}get channelGroups(){return this._channelGroups}get push(){return this._push}sendFile(e,t){return i(this,void 0,void 0,(function*(){if(!this._configuration.PubNubFile)throw new Error("Validation failed: 'PubNubFile' not configured or file upload not supported by the platform.");const s=new zt(Object.assign(Object.assign({},e),{keySet:this._configuration.keySet,PubNubFile:this._configuration.PubNubFile,fileUploadPublishRetryLimit:this._configuration.fileUploadPublishRetryLimit,file:e.file,sendRequest:this.sendRequest.bind(this),publishFile:this.publishFile.bind(this),crypto:this._configuration.getCryptoModule(),cryptography:this.cryptography?this.cryptography:void 0})),n={error:!1,operation:re.PNPublishFileOperation,category:h.PNAcknowledgmentCategory,statusCode:0};return s.process().then((e=>(n.statusCode=e.status,t?t(n,e):e))).catch((e=>{let s;throw e instanceof d?s=e.status:e instanceof _&&(s=e.toStatus(n.operation)),t&&s&&t(s,null),new d("REST API request processing error, check status for details",s)}))}))}publishFile(e,t){return i(this,void 0,void 0,(function*(){if(!this._configuration.PubNubFile)throw new Error("Validation failed: 'PubNubFile' not configured or file upload not supported by the platform.");const s=new qt(Object.assign(Object.assign({},e),{keySet:this._configuration.keySet,crypto:this._configuration.getCryptoModule()}));return t?this.sendRequest(s,t):this.sendRequest(s)}))}listFiles(e,t){return i(this,void 0,void 0,(function*(){const s=new Lt(Object.assign(Object.assign({},e),{keySet:this._configuration.keySet}));return t?this.sendRequest(s,t):this.sendRequest(s)}))}getFileUrl(e){var t;const s=this.transport.request(new Gt(Object.assign(Object.assign({},e),{keySet:this._configuration.keySet})).request()),n=null!==(t=s.queryParameters)&&void 0!==t?t:{},r=Object.keys(n).map((e=>{const t=n[e];return Array.isArray(t)?t.map((t=>`${e}=${I(t)}`)).join("&"):`${e}=${I(t)}`})).join("&");return`${s.origin}${s.path}?${r}`}downloadFile(e,t){return i(this,void 0,void 0,(function*(){if(!this._configuration.PubNubFile)throw new Error("Validation failed: 'PubNubFile' not configured or file upload not supported by the platform.");const s=new As(Object.assign(Object.assign({},e),{keySet:this._configuration.keySet,PubNubFile:this._configuration.PubNubFile,cryptography:this.cryptography?this.cryptography:void 0,crypto:this._configuration.getCryptoModule()}));return t?this.sendRequest(s,t):yield this.sendRequest(s)}))}deleteFile(e,t){return i(this,void 0,void 0,(function*(){const s=new $t(Object.assign(Object.assign({},e),{keySet:this._configuration.keySet}));return t?this.sendRequest(s,t):this.sendRequest(s)}))}time(e){return i(this,void 0,void 0,(function*(){const t=new _s;return e?this.sendRequest(t,e):this.sendRequest(t)}))}encrypt(e,t){const s=this._configuration.getCryptoModule();if(!t&&s&&"string"==typeof e){const t=s.encrypt(e);return"string"==typeof t?t:u(t)}if(!this.crypto)throw new Error("Encryption error: cypher key not set");return this.crypto.encrypt(e,t)}decrypt(e,t){const s=this._configuration.getCryptoModule();if(!t&&s){const t=s.decrypt(e);return t instanceof ArrayBuffer?JSON.parse((new TextDecoder).decode(t)):t}if(!this.crypto)throw new Error("Decryption error: cypher key not set");return this.crypto.decrypt(e,t)}encryptFile(e,t){return i(this,void 0,void 0,(function*(){var s;if("string"!=typeof e&&(t=e),!t)throw new Error("File encryption error. Source file is missing.");if(!this._configuration.PubNubFile)throw new Error("File encryption error. File constructor not configured.");if("string"!=typeof e&&!this._configuration.getCryptoModule())throw new Error("File encryption error. Crypto module not configured.");if("string"==typeof e){if(!this.cryptography)throw new Error("File encryption error. File encryption not available");return this.cryptography.encryptFile(e,t,this._configuration.PubNubFile)}return null===(s=this._configuration.getCryptoModule())||void 0===s?void 0:s.encryptFile(t,this._configuration.PubNubFile)}))}decryptFile(e,t){return i(this,void 0,void 0,(function*(){var s;if("string"!=typeof e&&(t=e),!t)throw new Error("File encryption error. Source file is missing.");if(!this._configuration.PubNubFile)throw new Error("File decryption error. File constructor not configured.");if("string"==typeof e&&!this._configuration.getCryptoModule())throw new Error("File decryption error. Crypto module not configured.");if("string"==typeof e){if(!this.cryptography)throw new Error("File decryption error. File decryption not available");return this.cryptography.decryptFile(e,t,this._configuration.PubNubFile)}return null===(s=this._configuration.getCryptoModule())||void 0===s?void 0:s.decryptFile(t,this._configuration.PubNubFile)}))}}Is.decoder=new TextDecoder,Is.OPERATIONS=re,Is.CATEGORIES=h,Is.ExponentialRetryPolicy=Le.ExponentialRetryPolicy,Is.LinearRetryPolicy=Le.LinearRetryPolicy;class Rs{constructor(e,t){this.decode=e,this.base64ToBinary=t}decodeToken(e){let t="";e.length%4==3?t="=":e.length%4==2&&(t="==");const s=e.replace(/-/gi,"+").replace(/_/gi,"/")+t,n=this.decode(this.base64ToBinary(s));return"object"==typeof n?n:void 0}}class Us extends Is{constructor(e){var t;const s=D(e),r=Object.assign(Object.assign({},s),{sdkFamily:"Web",PubNubFile:a}),i=$(r,(e=>{if(e.cipherKey)return new P({default:new N(Object.assign({},e)),cryptors:[new S({cipherKey:e.cipherKey})]})})),o=new B(new Rs((e=>x(n.decode(e))),c));let u;(i.getCipherKey()||i.secretKey)&&(u=new E({secretKey:i.secretKey,cipherKey:i.getCipherKey(),useRandomIVs:i.getUseRandomIVs(),customEncrypt:i.getCustomEncrypt(),customDecrypt:i.getCustomDecrypt()}));let l=new F(i.keepAlive,i.logVerbosity);s.subscriptionWorkerUrl&&(l=new A({clientIdentifier:i._instanceId,subscriptionKey:i.subscribeKey,userId:i.getUserId(),workerUrl:s.subscriptionWorkerUrl,sdkVersion:i.getVersion(),logVerbosity:i.logVerbosity,workerLogVerbosity:r.subscriptionWorkerLogVerbosity,transport:l}));super({configuration:i,transport:new V({clientConfiguration:i,tokenManager:o,transport:l}),cryptography:new C,tokenManager:o,crypto:u}),(null===(t=e.listenToBrowserNetworkEvents)||void 0===t||t)&&(window.addEventListener("offline",(()=>{this.networkDownDetected()})),window.addEventListener("online",(()=>{this.networkUpDetected()})))}networkDownDetected(){this.listenerManager.announceNetworkDown(),this._configuration.restore?this.disconnect():this.destroy(!0)}networkUpDetected(){this.listenerManager.announceNetworkUp(),this.reconnect()}}return Us.CryptoModule=P,Us})); diff --git a/lib/core/components/configuration.js b/lib/core/components/configuration.js index f70622c7a..ef07c7b3a 100644 --- a/lib/core/components/configuration.js +++ b/lib/core/components/configuration.js @@ -110,7 +110,7 @@ const makeConfiguration = (base, setupCryptoModule) => { return base.PubNubFile; }, get version() { - return '8.0.1'; + return '8.1.0'; }, getVersion() { return this.version; diff --git a/package.json b/package.json index 5c26ca43c..8081417ba 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "pubnub", - "version": "8.0.1", + "version": "8.1.0", "author": "PubNub ", "description": "Publish & Subscribe Real-time Messaging with PubNub", "scripts": { diff --git a/src/core/components/configuration.ts b/src/core/components/configuration.ts index 316a122c6..212f4c07e 100644 --- a/src/core/components/configuration.ts +++ b/src/core/components/configuration.ts @@ -169,7 +169,7 @@ export const makeConfiguration = ( return base.PubNubFile; }, get version(): string { - return '8.0.1'; + return '8.1.0'; }, getVersion(): string { return this.version;