@c8y/client 1018.510.3 → 1019.0.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/NOTICES +6626 -4790
- package/lib/bundles/client.umd.js +241 -506
- package/lib/bundles/client.umd.js.map +1 -1
- package/lib/bundles/client.umd.min.js +1 -1
- package/lib/bundles/client.umd.min.js.map +1 -1
- package/lib/cjs/index.d.ts.map +1 -0
- package/lib/cjs/index.js +2 -15
- package/lib/cjs/index.js.map +1 -1
- package/lib/cjs/src/Client.d.ts.map +1 -0
- package/lib/cjs/src/alarm/AlarmService.d.ts.map +1 -0
- package/lib/cjs/src/alarm/AlarmStatus.d.ts.map +1 -0
- package/lib/cjs/src/alarm/IAlarm.d.ts.map +1 -0
- package/lib/cjs/src/alarm/index.d.ts.map +1 -0
- package/lib/cjs/src/alarm/index.js +4 -17
- package/lib/cjs/src/alarm/index.js.map +1 -1
- package/lib/cjs/src/application/ApplicationAvailability.d.ts.map +1 -0
- package/lib/cjs/src/application/ApplicationBinaryService.d.ts.map +1 -0
- package/lib/cjs/src/application/ApplicationBinaryService.js +2 -4
- package/lib/cjs/src/application/ApplicationBinaryService.js.map +1 -1
- package/lib/cjs/src/application/ApplicationService.d.ts.map +1 -0
- package/lib/cjs/src/application/ApplicationType.d.ts.map +1 -0
- package/lib/cjs/src/application/BillingMode.d.ts.map +1 -0
- package/lib/cjs/src/application/IApplication.d.ts.map +1 -0
- package/lib/cjs/src/application/IApplicationBinary.d.ts.map +1 -0
- package/lib/cjs/src/application/IApplicationInstanceDetails.d.ts.map +1 -0
- package/lib/cjs/src/application/IApplicationReference.d.ts.map +1 -0
- package/lib/cjs/src/application/IApplicationVersion.d.ts.map +1 -0
- package/lib/cjs/src/application/IDeviceRegistrationProvider.d.ts.map +1 -0
- package/lib/cjs/src/application/IManifest.d.ts.map +1 -0
- package/lib/cjs/src/application/IProvider.d.ts.map +1 -0
- package/lib/cjs/src/application/IUploadParamsOverride.d.ts.map +1 -0
- package/lib/cjs/src/application/Isolation.d.ts.map +1 -0
- package/lib/cjs/src/application/index.d.ts.map +1 -0
- package/lib/cjs/src/application/index.js +16 -29
- package/lib/cjs/src/application/index.js.map +1 -1
- package/lib/cjs/src/audit/AuditRecordType.d.ts.map +1 -0
- package/lib/cjs/src/audit/AuditService.d.ts.map +1 -0
- package/lib/cjs/src/audit/ChangeType.d.ts.map +1 -0
- package/lib/cjs/src/audit/IAuditRecord.d.ts.map +1 -0
- package/lib/cjs/src/audit/IChange.d.ts.map +1 -0
- package/lib/cjs/src/audit/index.d.ts.map +1 -0
- package/lib/cjs/src/audit/index.js +6 -19
- package/lib/cjs/src/audit/index.js.map +1 -1
- package/lib/cjs/src/core/BasicAuth.d.ts.map +1 -0
- package/lib/cjs/src/core/BearerAuth.d.ts.map +1 -0
- package/lib/cjs/src/core/CookieAuth.d.ts.map +1 -0
- package/lib/cjs/src/core/FetchClient.d.ts.map +1 -0
- package/lib/cjs/src/core/FetchClient.js +2 -4
- package/lib/cjs/src/core/FetchClient.js.map +1 -1
- package/lib/cjs/src/core/IAuthentication.d.ts.map +1 -0
- package/lib/cjs/src/core/ICustomProperties.d.ts.map +1 -0
- package/lib/cjs/src/core/ICustomPropertiesMap.d.ts.map +1 -0
- package/lib/cjs/src/core/IFetchClient.d.ts.map +1 -0
- package/lib/cjs/src/core/IFetchOptions.d.ts.map +1 -0
- package/lib/cjs/src/core/IFetchResponse.d.ts.map +1 -0
- package/lib/cjs/src/core/IIdentified.d.ts.map +1 -0
- package/lib/cjs/src/core/IMicroserviceSubscriptions.d.ts.map +1 -0
- package/lib/cjs/src/core/INamed.d.ts.map +1 -0
- package/lib/cjs/src/core/IResult.d.ts.map +1 -0
- package/lib/cjs/src/core/IResultBase.d.ts.map +1 -0
- package/lib/cjs/src/core/IResultList.d.ts.map +1 -0
- package/lib/cjs/src/core/ISource.d.ts.map +1 -0
- package/lib/cjs/src/core/MicroserviceClientRequestAuth.d.ts.map +1 -0
- package/lib/cjs/src/core/NodeJSCookieAuth.d.ts.map +1 -0
- package/lib/cjs/src/core/Paging.d.ts.map +1 -0
- package/lib/cjs/src/core/QueriesUtil.d.ts.map +1 -0
- package/lib/cjs/src/core/Service.d.ts.map +1 -0
- package/lib/cjs/src/core/Severity.d.ts.map +1 -0
- package/lib/cjs/src/core/index.d.ts.map +1 -0
- package/lib/cjs/src/core/index.js +23 -36
- package/lib/cjs/src/core/index.js.map +1 -1
- package/lib/cjs/src/device-registration/DeviceRegistrationBulkService.d.ts.map +1 -0
- package/lib/cjs/src/device-registration/DeviceRegistrationBulkService.js +2 -4
- package/lib/cjs/src/device-registration/DeviceRegistrationBulkService.js.map +1 -1
- package/lib/cjs/src/device-registration/DeviceRegistrationSecurityMode.d.ts.map +1 -0
- package/lib/cjs/src/device-registration/DeviceRegistrationService.d.ts.map +1 -0
- package/lib/cjs/src/device-registration/DeviceRegistrationStatus.d.ts.map +1 -0
- package/lib/cjs/src/device-registration/IDeviceCredentials.d.ts.map +1 -0
- package/lib/cjs/src/device-registration/IDeviceRegistration.d.ts.map +1 -0
- package/lib/cjs/src/device-registration/IDeviceRegistrationBulkResult.d.ts.map +1 -0
- package/lib/cjs/src/device-registration/index.d.ts.map +1 -0
- package/lib/cjs/src/device-registration/index.js +8 -21
- package/lib/cjs/src/device-registration/index.js.map +1 -1
- package/lib/cjs/src/event/EventBinaryService.d.ts.map +1 -0
- package/lib/cjs/src/event/EventBinaryService.js +2 -4
- package/lib/cjs/src/event/EventBinaryService.js.map +1 -1
- package/lib/cjs/src/event/EventService.d.ts.map +1 -0
- package/lib/cjs/src/event/IEvent.d.ts.map +1 -0
- package/lib/cjs/src/event/IEventBinary.d.ts.map +1 -0
- package/lib/cjs/src/event/index.d.ts.map +1 -0
- package/lib/cjs/src/event/index.js +5 -18
- package/lib/cjs/src/event/index.js.map +1 -1
- package/lib/cjs/src/gettext.d.ts.map +1 -0
- package/lib/cjs/src/identity/IExternalIdentity.d.ts.map +1 -0
- package/lib/cjs/src/identity/IdentityService.d.ts.map +1 -0
- package/lib/cjs/src/identity/index.d.ts.map +1 -0
- package/lib/cjs/src/identity/index.js +3 -16
- package/lib/cjs/src/identity/index.js.map +1 -1
- package/lib/cjs/src/inventory/IManagedObject.d.ts.map +1 -0
- package/lib/cjs/src/inventory/InventoryBinaryService.d.ts.map +1 -0
- package/lib/cjs/src/inventory/InventoryBinaryService.js +2 -4
- package/lib/cjs/src/inventory/InventoryBinaryService.js.map +1 -1
- package/lib/cjs/src/inventory/InventoryService.d.ts.map +1 -0
- package/lib/cjs/src/inventory/index.d.ts.map +1 -0
- package/lib/cjs/src/inventory/index.js +4 -17
- package/lib/cjs/src/inventory/index.js.map +1 -1
- package/lib/cjs/src/inventory-role/InventoryRoleService.d.ts.map +1 -0
- package/lib/cjs/src/inventory-role/index.d.ts.map +1 -0
- package/lib/cjs/src/inventory-role/index.js +2 -15
- package/lib/cjs/src/inventory-role/index.js.map +1 -1
- package/lib/cjs/src/measurement/IMeasurement.d.ts.map +1 -0
- package/lib/cjs/src/measurement/ISeries.d.ts.map +1 -0
- package/lib/cjs/src/measurement/ISeriesFilter.d.ts.map +1 -0
- package/lib/cjs/src/measurement/MeasurementService.d.ts.map +1 -0
- package/lib/cjs/src/measurement/index.d.ts.map +1 -0
- package/lib/cjs/src/measurement/index.js +5 -18
- package/lib/cjs/src/measurement/index.js.map +1 -1
- package/lib/cjs/src/operation/IOperation.d.ts.map +1 -0
- package/lib/cjs/src/operation/IOperationBulk.d.ts.map +1 -0
- package/lib/cjs/src/operation/IOperationBulkProgress.d.ts.map +1 -0
- package/lib/cjs/src/operation/OperationBulkGeneralStatus.d.ts.map +1 -0
- package/lib/cjs/src/operation/OperationBulkService.d.ts.map +1 -0
- package/lib/cjs/src/operation/OperationBulkStatus.d.ts.map +1 -0
- package/lib/cjs/src/operation/OperationService.d.ts.map +1 -0
- package/lib/cjs/src/operation/OperationStatus.d.ts.map +1 -0
- package/lib/cjs/src/operation/index.d.ts.map +1 -0
- package/lib/cjs/src/operation/index.js +9 -22
- package/lib/cjs/src/operation/index.js.map +1 -1
- package/lib/cjs/src/public_api.d.ts.map +1 -0
- package/lib/cjs/src/public_api.js +25 -38
- package/lib/cjs/src/public_api.js.map +1 -1
- package/lib/cjs/src/realtime/MetaChannel.d.ts.map +1 -0
- package/lib/cjs/src/realtime/Realtime.d.ts.map +1 -0
- package/lib/cjs/src/realtime/index.d.ts.map +1 -0
- package/lib/cjs/src/realtime/index.js +2 -15
- package/lib/cjs/src/realtime/index.js.map +1 -1
- package/lib/cjs/src/services.d.ts.map +1 -0
- package/lib/cjs/src/smart-groups/SmartGroupsService.d.ts.map +1 -0
- package/lib/cjs/src/smart-groups/index.d.ts.map +1 -0
- package/lib/cjs/src/smart-groups/index.js +2 -15
- package/lib/cjs/src/smart-groups/index.js.map +1 -1
- package/lib/cjs/src/smart-rules/IRule.d.ts.map +1 -0
- package/lib/cjs/src/smart-rules/SmartRulesService.d.ts.map +1 -0
- package/lib/cjs/src/smart-rules/SmartRulesService.js +1 -1
- package/lib/cjs/src/smart-rules/SmartRulesService.js.map +1 -1
- package/lib/cjs/src/smart-rules/index.d.ts.map +1 -0
- package/lib/cjs/src/smart-rules/index.js +3 -16
- package/lib/cjs/src/smart-rules/index.js.map +1 -1
- package/lib/cjs/src/system-options/ISystemOption.d.ts.map +1 -0
- package/lib/cjs/src/system-options/SystemOptionsService.d.ts.map +1 -0
- package/lib/cjs/src/system-options/index.d.ts.map +1 -0
- package/lib/cjs/src/system-options/index.js +3 -16
- package/lib/cjs/src/system-options/index.js.map +1 -1
- package/lib/cjs/src/tenant/ICurrentTenant.d.ts.map +1 -0
- package/lib/cjs/src/tenant/ITenant.d.ts.map +1 -0
- package/lib/cjs/src/tenant/ITenantReference.d.ts.map +1 -0
- package/lib/cjs/src/tenant/ITfaSettings.d.ts.map +1 -0
- package/lib/cjs/src/tenant/TenantService.d.ts.map +1 -0
- package/lib/cjs/src/tenant/TenantStatus.d.ts.map +1 -0
- package/lib/cjs/src/tenant/TfaStrategy.d.ts.map +1 -0
- package/lib/cjs/src/tenant/index.d.ts.map +1 -0
- package/lib/cjs/src/tenant/index.js +8 -21
- package/lib/cjs/src/tenant/index.js.map +1 -1
- package/lib/cjs/src/tenant-login-options/ITenantLoginOptions.d.ts.map +1 -0
- package/lib/cjs/src/tenant-login-options/TenantLoginOptionsService.d.ts.map +1 -0
- package/lib/cjs/src/tenant-login-options/index.d.ts.map +1 -0
- package/lib/cjs/src/tenant-login-options/index.js +3 -16
- package/lib/cjs/src/tenant-login-options/index.js.map +1 -1
- package/lib/cjs/src/tenant-options/ITenantOption.d.ts.map +1 -0
- package/lib/cjs/src/tenant-options/ITenantOptionDetailParams.d.ts.map +1 -0
- package/lib/cjs/src/tenant-options/TenantOptionsService.d.ts.map +1 -0
- package/lib/cjs/src/tenant-options/index.d.ts.map +1 -0
- package/lib/cjs/src/tenant-options/index.js +4 -17
- package/lib/cjs/src/tenant-options/index.js.map +1 -1
- package/lib/cjs/src/tenant-security-options/ITenantSecurityOption.d.ts.map +1 -0
- package/lib/cjs/src/tenant-security-options/TenantSecurityOptionsService.d.ts.map +1 -0
- package/lib/cjs/src/tenant-security-options/index.d.ts.map +1 -0
- package/lib/cjs/src/tenant-security-options/index.js +3 -16
- package/lib/cjs/src/tenant-security-options/index.js.map +1 -1
- package/lib/cjs/src/trusted-certificates/CrlService.d.ts.map +1 -0
- package/lib/cjs/src/trusted-certificates/CrlService.js +2 -4
- package/lib/cjs/src/trusted-certificates/CrlService.js.map +1 -1
- package/lib/cjs/src/trusted-certificates/ICertificateRevocation.d.ts.map +1 -0
- package/lib/cjs/src/trusted-certificates/ITrustedCertificate.d.ts.map +1 -0
- package/lib/cjs/src/trusted-certificates/TrustedCertificateService.d.ts.map +1 -0
- package/lib/cjs/src/trusted-certificates/index.d.ts.map +1 -0
- package/lib/cjs/src/trusted-certificates/index.js +5 -18
- package/lib/cjs/src/trusted-certificates/index.js.map +1 -1
- package/lib/cjs/src/user/ICurrentUser.d.ts.map +1 -0
- package/lib/cjs/src/user/IResetPassword.d.ts.map +1 -0
- package/lib/cjs/src/user/ITotp.d.ts.map +1 -0
- package/lib/cjs/src/user/ITotpStatus.d.ts.map +1 -0
- package/lib/cjs/src/user/IUser.d.ts.map +1 -0
- package/lib/cjs/src/user/IUserInventoryRole.d.ts.map +1 -0
- package/lib/cjs/src/user/PasswordStrength.d.ts.map +1 -0
- package/lib/cjs/src/user/UserInventoryRoleService.d.ts.map +1 -0
- package/lib/cjs/src/user/UserService.d.ts.map +1 -0
- package/lib/cjs/src/user/index.d.ts.map +1 -0
- package/lib/cjs/src/user/index.js +10 -23
- package/lib/cjs/src/user/index.js.map +1 -1
- package/lib/cjs/src/user-group/IDevicePermissions.d.ts.map +1 -0
- package/lib/cjs/src/user-group/IUserGroup.d.ts.map +1 -0
- package/lib/cjs/src/user-group/UserGroupService.d.ts.map +1 -0
- package/lib/cjs/src/user-group/index.d.ts.map +1 -0
- package/lib/cjs/src/user-group/index.js +4 -17
- package/lib/cjs/src/user-group/index.js.map +1 -1
- package/lib/cjs/src/user-role/IRole.d.ts.map +1 -0
- package/lib/cjs/src/user-role/IRoleReference.d.ts.map +1 -0
- package/lib/cjs/src/user-role/UserRoleService.d.ts.map +1 -0
- package/lib/cjs/src/user-role/index.d.ts.map +1 -0
- package/lib/cjs/src/user-role/index.js +4 -17
- package/lib/cjs/src/user-role/index.js.map +1 -1
- package/lib/esm2015/index.d.ts.map +1 -0
- package/lib/esm2015/src/Client.d.ts.map +1 -0
- package/lib/esm2015/src/Client.js +1 -9
- package/lib/esm2015/src/Client.js.map +1 -1
- package/lib/esm2015/src/alarm/AlarmService.d.ts.map +1 -0
- package/lib/esm2015/src/alarm/AlarmService.js +1 -9
- package/lib/esm2015/src/alarm/AlarmService.js.map +1 -1
- package/lib/esm2015/src/alarm/AlarmStatus.d.ts.map +1 -0
- package/lib/esm2015/src/alarm/IAlarm.d.ts.map +1 -0
- package/lib/esm2015/src/alarm/index.d.ts.map +1 -0
- package/lib/esm2015/src/application/ApplicationAvailability.d.ts.map +1 -0
- package/lib/esm2015/src/application/ApplicationBinaryService.d.ts.map +1 -0
- package/lib/esm2015/src/application/ApplicationBinaryService.js +1 -9
- package/lib/esm2015/src/application/ApplicationBinaryService.js.map +1 -1
- package/lib/esm2015/src/application/ApplicationService.d.ts.map +1 -0
- package/lib/esm2015/src/application/ApplicationService.js +1 -9
- package/lib/esm2015/src/application/ApplicationService.js.map +1 -1
- package/lib/esm2015/src/application/ApplicationType.d.ts.map +1 -0
- package/lib/esm2015/src/application/BillingMode.d.ts.map +1 -0
- package/lib/esm2015/src/application/IApplication.d.ts.map +1 -0
- package/lib/esm2015/src/application/IApplicationBinary.d.ts.map +1 -0
- package/lib/esm2015/src/application/IApplicationInstanceDetails.d.ts.map +1 -0
- package/lib/esm2015/src/application/IApplicationReference.d.ts.map +1 -0
- package/lib/esm2015/src/application/IApplicationVersion.d.ts.map +1 -0
- package/lib/esm2015/src/application/IDeviceRegistrationProvider.d.ts.map +1 -0
- package/lib/esm2015/src/application/IManifest.d.ts.map +1 -0
- package/lib/esm2015/src/application/IProvider.d.ts.map +1 -0
- package/lib/esm2015/src/application/IUploadParamsOverride.d.ts.map +1 -0
- package/lib/esm2015/src/application/Isolation.d.ts.map +1 -0
- package/lib/esm2015/src/application/index.d.ts.map +1 -0
- package/lib/esm2015/src/audit/AuditRecordType.d.ts.map +1 -0
- package/lib/esm2015/src/audit/AuditService.d.ts.map +1 -0
- package/lib/esm2015/src/audit/AuditService.js +1 -9
- package/lib/esm2015/src/audit/AuditService.js.map +1 -1
- package/lib/esm2015/src/audit/ChangeType.d.ts.map +1 -0
- package/lib/esm2015/src/audit/IAuditRecord.d.ts.map +1 -0
- package/lib/esm2015/src/audit/IChange.d.ts.map +1 -0
- package/lib/esm2015/src/audit/index.d.ts.map +1 -0
- package/lib/esm2015/src/core/BasicAuth.d.ts.map +1 -0
- package/lib/esm2015/src/core/BearerAuth.d.ts.map +1 -0
- package/lib/esm2015/src/core/CookieAuth.d.ts.map +1 -0
- package/lib/esm2015/src/core/CookieAuth.js +1 -9
- package/lib/esm2015/src/core/CookieAuth.js.map +1 -1
- package/lib/esm2015/src/core/FetchClient.d.ts.map +1 -0
- package/lib/esm2015/src/core/FetchClient.js +1 -9
- package/lib/esm2015/src/core/FetchClient.js.map +1 -1
- package/lib/esm2015/src/core/IAuthentication.d.ts.map +1 -0
- package/lib/esm2015/src/core/ICustomProperties.d.ts.map +1 -0
- package/lib/esm2015/src/core/ICustomPropertiesMap.d.ts.map +1 -0
- package/lib/esm2015/src/core/IFetchClient.d.ts.map +1 -0
- package/lib/esm2015/src/core/IFetchOptions.d.ts.map +1 -0
- package/lib/esm2015/src/core/IFetchResponse.d.ts.map +1 -0
- package/lib/esm2015/src/core/IIdentified.d.ts.map +1 -0
- package/lib/esm2015/src/core/IMicroserviceSubscriptions.d.ts.map +1 -0
- package/lib/esm2015/src/core/INamed.d.ts.map +1 -0
- package/lib/esm2015/src/core/IResult.d.ts.map +1 -0
- package/lib/esm2015/src/core/IResultBase.d.ts.map +1 -0
- package/lib/esm2015/src/core/IResultList.d.ts.map +1 -0
- package/lib/esm2015/src/core/ISource.d.ts.map +1 -0
- package/lib/esm2015/src/core/MicroserviceClientRequestAuth.d.ts.map +1 -0
- package/lib/esm2015/src/core/NodeJSCookieAuth.d.ts.map +1 -0
- package/lib/esm2015/src/core/Paging.d.ts.map +1 -0
- package/lib/esm2015/src/core/Paging.js +1 -9
- package/lib/esm2015/src/core/Paging.js.map +1 -1
- package/lib/esm2015/src/core/QueriesUtil.d.ts.map +1 -0
- package/lib/esm2015/src/core/Service.d.ts.map +1 -0
- package/lib/esm2015/src/core/Service.js +1 -9
- package/lib/esm2015/src/core/Service.js.map +1 -1
- package/lib/esm2015/src/core/Severity.d.ts.map +1 -0
- package/lib/esm2015/src/core/index.d.ts.map +1 -0
- package/lib/esm2015/src/device-registration/DeviceRegistrationBulkService.d.ts.map +1 -0
- package/lib/esm2015/src/device-registration/DeviceRegistrationBulkService.js +1 -9
- package/lib/esm2015/src/device-registration/DeviceRegistrationBulkService.js.map +1 -1
- package/lib/esm2015/src/device-registration/DeviceRegistrationSecurityMode.d.ts.map +1 -0
- package/lib/esm2015/src/device-registration/DeviceRegistrationService.d.ts.map +1 -0
- package/lib/esm2015/src/device-registration/DeviceRegistrationService.js +1 -9
- package/lib/esm2015/src/device-registration/DeviceRegistrationService.js.map +1 -1
- package/lib/esm2015/src/device-registration/DeviceRegistrationStatus.d.ts.map +1 -0
- package/lib/esm2015/src/device-registration/IDeviceCredentials.d.ts.map +1 -0
- package/lib/esm2015/src/device-registration/IDeviceRegistration.d.ts.map +1 -0
- package/lib/esm2015/src/device-registration/IDeviceRegistrationBulkResult.d.ts.map +1 -0
- package/lib/esm2015/src/device-registration/index.d.ts.map +1 -0
- package/lib/esm2015/src/event/EventBinaryService.d.ts.map +1 -0
- package/lib/esm2015/src/event/EventBinaryService.js +1 -9
- package/lib/esm2015/src/event/EventBinaryService.js.map +1 -1
- package/lib/esm2015/src/event/EventService.d.ts.map +1 -0
- package/lib/esm2015/src/event/EventService.js +1 -9
- package/lib/esm2015/src/event/EventService.js.map +1 -1
- package/lib/esm2015/src/event/IEvent.d.ts.map +1 -0
- package/lib/esm2015/src/event/IEventBinary.d.ts.map +1 -0
- package/lib/esm2015/src/event/index.d.ts.map +1 -0
- package/lib/esm2015/src/gettext.d.ts.map +1 -0
- package/lib/esm2015/src/identity/IExternalIdentity.d.ts.map +1 -0
- package/lib/esm2015/src/identity/IdentityService.d.ts.map +1 -0
- package/lib/esm2015/src/identity/IdentityService.js +1 -9
- package/lib/esm2015/src/identity/IdentityService.js.map +1 -1
- package/lib/esm2015/src/identity/index.d.ts.map +1 -0
- package/lib/esm2015/src/inventory/IManagedObject.d.ts.map +1 -0
- package/lib/esm2015/src/inventory/InventoryBinaryService.d.ts.map +1 -0
- package/lib/esm2015/src/inventory/InventoryBinaryService.js +1 -9
- package/lib/esm2015/src/inventory/InventoryBinaryService.js.map +1 -1
- package/lib/esm2015/src/inventory/InventoryService.d.ts.map +1 -0
- package/lib/esm2015/src/inventory/InventoryService.js +1 -9
- package/lib/esm2015/src/inventory/InventoryService.js.map +1 -1
- package/lib/esm2015/src/inventory/index.d.ts.map +1 -0
- package/lib/esm2015/src/inventory-role/InventoryRoleService.d.ts.map +1 -0
- package/lib/esm2015/src/inventory-role/InventoryRoleService.js +1 -9
- package/lib/esm2015/src/inventory-role/InventoryRoleService.js.map +1 -1
- package/lib/esm2015/src/inventory-role/index.d.ts.map +1 -0
- package/lib/esm2015/src/measurement/IMeasurement.d.ts.map +1 -0
- package/lib/esm2015/src/measurement/ISeries.d.ts.map +1 -0
- package/lib/esm2015/src/measurement/ISeriesFilter.d.ts.map +1 -0
- package/lib/esm2015/src/measurement/MeasurementService.d.ts.map +1 -0
- package/lib/esm2015/src/measurement/MeasurementService.js +1 -9
- package/lib/esm2015/src/measurement/MeasurementService.js.map +1 -1
- package/lib/esm2015/src/measurement/index.d.ts.map +1 -0
- package/lib/esm2015/src/operation/IOperation.d.ts.map +1 -0
- package/lib/esm2015/src/operation/IOperationBulk.d.ts.map +1 -0
- package/lib/esm2015/src/operation/IOperationBulkProgress.d.ts.map +1 -0
- package/lib/esm2015/src/operation/OperationBulkGeneralStatus.d.ts.map +1 -0
- package/lib/esm2015/src/operation/OperationBulkService.d.ts.map +1 -0
- package/lib/esm2015/src/operation/OperationBulkService.js +1 -9
- package/lib/esm2015/src/operation/OperationBulkService.js.map +1 -1
- package/lib/esm2015/src/operation/OperationBulkStatus.d.ts.map +1 -0
- package/lib/esm2015/src/operation/OperationService.d.ts.map +1 -0
- package/lib/esm2015/src/operation/OperationService.js +1 -9
- package/lib/esm2015/src/operation/OperationService.js.map +1 -1
- package/lib/esm2015/src/operation/OperationStatus.d.ts.map +1 -0
- package/lib/esm2015/src/operation/index.d.ts.map +1 -0
- package/lib/esm2015/src/public_api.d.ts.map +1 -0
- package/lib/esm2015/src/realtime/MetaChannel.d.ts.map +1 -0
- package/lib/esm2015/src/realtime/Realtime.d.ts.map +1 -0
- package/lib/esm2015/src/realtime/index.d.ts.map +1 -0
- package/lib/esm2015/src/services.d.ts.map +1 -0
- package/lib/esm2015/src/smart-groups/SmartGroupsService.d.ts.map +1 -0
- package/lib/esm2015/src/smart-groups/SmartGroupsService.js +1 -9
- package/lib/esm2015/src/smart-groups/SmartGroupsService.js.map +1 -1
- package/lib/esm2015/src/smart-groups/index.d.ts.map +1 -0
- package/lib/esm2015/src/smart-rules/IRule.d.ts.map +1 -0
- package/lib/esm2015/src/smart-rules/SmartRulesService.d.ts.map +1 -0
- package/lib/esm2015/src/smart-rules/SmartRulesService.js +1 -9
- package/lib/esm2015/src/smart-rules/SmartRulesService.js.map +1 -1
- package/lib/esm2015/src/smart-rules/index.d.ts.map +1 -0
- package/lib/esm2015/src/system-options/ISystemOption.d.ts.map +1 -0
- package/lib/esm2015/src/system-options/SystemOptionsService.d.ts.map +1 -0
- package/lib/esm2015/src/system-options/SystemOptionsService.js +1 -9
- package/lib/esm2015/src/system-options/SystemOptionsService.js.map +1 -1
- package/lib/esm2015/src/system-options/index.d.ts.map +1 -0
- package/lib/esm2015/src/tenant/ICurrentTenant.d.ts.map +1 -0
- package/lib/esm2015/src/tenant/ITenant.d.ts.map +1 -0
- package/lib/esm2015/src/tenant/ITenantReference.d.ts.map +1 -0
- package/lib/esm2015/src/tenant/ITfaSettings.d.ts.map +1 -0
- package/lib/esm2015/src/tenant/TenantService.d.ts.map +1 -0
- package/lib/esm2015/src/tenant/TenantService.js +1 -9
- package/lib/esm2015/src/tenant/TenantService.js.map +1 -1
- package/lib/esm2015/src/tenant/TenantStatus.d.ts.map +1 -0
- package/lib/esm2015/src/tenant/TfaStrategy.d.ts.map +1 -0
- package/lib/esm2015/src/tenant/index.d.ts.map +1 -0
- package/lib/esm2015/src/tenant-login-options/ITenantLoginOptions.d.ts.map +1 -0
- package/lib/esm2015/src/tenant-login-options/TenantLoginOptionsService.d.ts.map +1 -0
- package/lib/esm2015/src/tenant-login-options/TenantLoginOptionsService.js +1 -9
- package/lib/esm2015/src/tenant-login-options/TenantLoginOptionsService.js.map +1 -1
- package/lib/esm2015/src/tenant-login-options/index.d.ts.map +1 -0
- package/lib/esm2015/src/tenant-options/ITenantOption.d.ts.map +1 -0
- package/lib/esm2015/src/tenant-options/ITenantOptionDetailParams.d.ts.map +1 -0
- package/lib/esm2015/src/tenant-options/TenantOptionsService.d.ts.map +1 -0
- package/lib/esm2015/src/tenant-options/TenantOptionsService.js +1 -9
- package/lib/esm2015/src/tenant-options/TenantOptionsService.js.map +1 -1
- package/lib/esm2015/src/tenant-options/index.d.ts.map +1 -0
- package/lib/esm2015/src/tenant-security-options/ITenantSecurityOption.d.ts.map +1 -0
- package/lib/esm2015/src/tenant-security-options/TenantSecurityOptionsService.d.ts.map +1 -0
- package/lib/esm2015/src/tenant-security-options/TenantSecurityOptionsService.js +1 -9
- package/lib/esm2015/src/tenant-security-options/TenantSecurityOptionsService.js.map +1 -1
- package/lib/esm2015/src/tenant-security-options/index.d.ts.map +1 -0
- package/lib/esm2015/src/trusted-certificates/CrlService.d.ts.map +1 -0
- package/lib/esm2015/src/trusted-certificates/CrlService.js +1 -9
- package/lib/esm2015/src/trusted-certificates/CrlService.js.map +1 -1
- package/lib/esm2015/src/trusted-certificates/ICertificateRevocation.d.ts.map +1 -0
- package/lib/esm2015/src/trusted-certificates/ITrustedCertificate.d.ts.map +1 -0
- package/lib/esm2015/src/trusted-certificates/TrustedCertificateService.d.ts.map +1 -0
- package/lib/esm2015/src/trusted-certificates/TrustedCertificateService.js +1 -9
- package/lib/esm2015/src/trusted-certificates/TrustedCertificateService.js.map +1 -1
- package/lib/esm2015/src/trusted-certificates/index.d.ts.map +1 -0
- package/lib/esm2015/src/user/ICurrentUser.d.ts.map +1 -0
- package/lib/esm2015/src/user/IResetPassword.d.ts.map +1 -0
- package/lib/esm2015/src/user/ITotp.d.ts.map +1 -0
- package/lib/esm2015/src/user/ITotpStatus.d.ts.map +1 -0
- package/lib/esm2015/src/user/IUser.d.ts.map +1 -0
- package/lib/esm2015/src/user/IUserInventoryRole.d.ts.map +1 -0
- package/lib/esm2015/src/user/PasswordStrength.d.ts.map +1 -0
- package/lib/esm2015/src/user/UserInventoryRoleService.d.ts.map +1 -0
- package/lib/esm2015/src/user/UserInventoryRoleService.js +1 -9
- package/lib/esm2015/src/user/UserInventoryRoleService.js.map +1 -1
- package/lib/esm2015/src/user/UserService.d.ts.map +1 -0
- package/lib/esm2015/src/user/UserService.js +1 -9
- package/lib/esm2015/src/user/UserService.js.map +1 -1
- package/lib/esm2015/src/user/index.d.ts.map +1 -0
- package/lib/esm2015/src/user-group/IDevicePermissions.d.ts.map +1 -0
- package/lib/esm2015/src/user-group/IUserGroup.d.ts.map +1 -0
- package/lib/esm2015/src/user-group/UserGroupService.d.ts.map +1 -0
- package/lib/esm2015/src/user-group/UserGroupService.js +1 -9
- package/lib/esm2015/src/user-group/UserGroupService.js.map +1 -1
- package/lib/esm2015/src/user-group/index.d.ts.map +1 -0
- package/lib/esm2015/src/user-role/IRole.d.ts.map +1 -0
- package/lib/esm2015/src/user-role/IRoleReference.d.ts.map +1 -0
- package/lib/esm2015/src/user-role/UserRoleService.d.ts.map +1 -0
- package/lib/esm2015/src/user-role/UserRoleService.js +1 -9
- package/lib/esm2015/src/user-role/UserRoleService.js.map +1 -1
- package/lib/esm2015/src/user-role/index.d.ts.map +1 -0
- package/lib/index.d.ts.map +1 -0
- package/lib/src/Client.d.ts.map +1 -0
- package/lib/src/alarm/AlarmService.d.ts.map +1 -0
- package/lib/src/alarm/AlarmStatus.d.ts.map +1 -0
- package/lib/src/alarm/IAlarm.d.ts.map +1 -0
- package/lib/src/alarm/index.d.ts.map +1 -0
- package/lib/src/application/ApplicationAvailability.d.ts.map +1 -0
- package/lib/src/application/ApplicationBinaryService.d.ts.map +1 -0
- package/lib/src/application/ApplicationService.d.ts.map +1 -0
- package/lib/src/application/ApplicationType.d.ts.map +1 -0
- package/lib/src/application/BillingMode.d.ts.map +1 -0
- package/lib/src/application/IApplication.d.ts.map +1 -0
- package/lib/src/application/IApplicationBinary.d.ts.map +1 -0
- package/lib/src/application/IApplicationInstanceDetails.d.ts.map +1 -0
- package/lib/src/application/IApplicationReference.d.ts.map +1 -0
- package/lib/src/application/IApplicationVersion.d.ts.map +1 -0
- package/lib/src/application/IDeviceRegistrationProvider.d.ts.map +1 -0
- package/lib/src/application/IManifest.d.ts.map +1 -0
- package/lib/src/application/IProvider.d.ts.map +1 -0
- package/lib/src/application/IUploadParamsOverride.d.ts.map +1 -0
- package/lib/src/application/Isolation.d.ts.map +1 -0
- package/lib/src/application/index.d.ts.map +1 -0
- package/lib/src/audit/AuditRecordType.d.ts.map +1 -0
- package/lib/src/audit/AuditService.d.ts.map +1 -0
- package/lib/src/audit/ChangeType.d.ts.map +1 -0
- package/lib/src/audit/IAuditRecord.d.ts.map +1 -0
- package/lib/src/audit/IChange.d.ts.map +1 -0
- package/lib/src/audit/index.d.ts.map +1 -0
- package/lib/src/core/BasicAuth.d.ts.map +1 -0
- package/lib/src/core/BearerAuth.d.ts.map +1 -0
- package/lib/src/core/CookieAuth.d.ts.map +1 -0
- package/lib/src/core/FetchClient.d.ts.map +1 -0
- package/lib/src/core/IAuthentication.d.ts.map +1 -0
- package/lib/src/core/ICustomProperties.d.ts.map +1 -0
- package/lib/src/core/ICustomPropertiesMap.d.ts.map +1 -0
- package/lib/src/core/IFetchClient.d.ts.map +1 -0
- package/lib/src/core/IFetchOptions.d.ts.map +1 -0
- package/lib/src/core/IFetchResponse.d.ts.map +1 -0
- package/lib/src/core/IIdentified.d.ts.map +1 -0
- package/lib/src/core/IMicroserviceSubscriptions.d.ts.map +1 -0
- package/lib/src/core/INamed.d.ts.map +1 -0
- package/lib/src/core/IResult.d.ts.map +1 -0
- package/lib/src/core/IResultBase.d.ts.map +1 -0
- package/lib/src/core/IResultList.d.ts.map +1 -0
- package/lib/src/core/ISource.d.ts.map +1 -0
- package/lib/src/core/MicroserviceClientRequestAuth.d.ts.map +1 -0
- package/lib/src/core/NodeJSCookieAuth.d.ts.map +1 -0
- package/lib/src/core/Paging.d.ts.map +1 -0
- package/lib/src/core/QueriesUtil.d.ts.map +1 -0
- package/lib/src/core/Service.d.ts.map +1 -0
- package/lib/src/core/Severity.d.ts.map +1 -0
- package/lib/src/core/index.d.ts.map +1 -0
- package/lib/src/device-registration/DeviceRegistrationBulkService.d.ts.map +1 -0
- package/lib/src/device-registration/DeviceRegistrationSecurityMode.d.ts.map +1 -0
- package/lib/src/device-registration/DeviceRegistrationService.d.ts.map +1 -0
- package/lib/src/device-registration/DeviceRegistrationStatus.d.ts.map +1 -0
- package/lib/src/device-registration/IDeviceCredentials.d.ts.map +1 -0
- package/lib/src/device-registration/IDeviceRegistration.d.ts.map +1 -0
- package/lib/src/device-registration/IDeviceRegistrationBulkResult.d.ts.map +1 -0
- package/lib/src/device-registration/index.d.ts.map +1 -0
- package/lib/src/event/EventBinaryService.d.ts.map +1 -0
- package/lib/src/event/EventService.d.ts.map +1 -0
- package/lib/src/event/IEvent.d.ts.map +1 -0
- package/lib/src/event/IEventBinary.d.ts.map +1 -0
- package/lib/src/event/index.d.ts.map +1 -0
- package/lib/src/gettext.d.ts.map +1 -0
- package/lib/src/identity/IExternalIdentity.d.ts.map +1 -0
- package/lib/src/identity/IdentityService.d.ts.map +1 -0
- package/lib/src/identity/index.d.ts.map +1 -0
- package/lib/src/inventory/IManagedObject.d.ts.map +1 -0
- package/lib/src/inventory/InventoryBinaryService.d.ts.map +1 -0
- package/lib/src/inventory/InventoryService.d.ts.map +1 -0
- package/lib/src/inventory/index.d.ts.map +1 -0
- package/lib/src/inventory-role/InventoryRoleService.d.ts.map +1 -0
- package/lib/src/inventory-role/index.d.ts.map +1 -0
- package/lib/src/measurement/IMeasurement.d.ts.map +1 -0
- package/lib/src/measurement/ISeries.d.ts.map +1 -0
- package/lib/src/measurement/ISeriesFilter.d.ts.map +1 -0
- package/lib/src/measurement/MeasurementService.d.ts.map +1 -0
- package/lib/src/measurement/index.d.ts.map +1 -0
- package/lib/src/operation/IOperation.d.ts.map +1 -0
- package/lib/src/operation/IOperationBulk.d.ts.map +1 -0
- package/lib/src/operation/IOperationBulkProgress.d.ts.map +1 -0
- package/lib/src/operation/OperationBulkGeneralStatus.d.ts.map +1 -0
- package/lib/src/operation/OperationBulkService.d.ts.map +1 -0
- package/lib/src/operation/OperationBulkStatus.d.ts.map +1 -0
- package/lib/src/operation/OperationService.d.ts.map +1 -0
- package/lib/src/operation/OperationStatus.d.ts.map +1 -0
- package/lib/src/operation/index.d.ts.map +1 -0
- package/lib/src/public_api.d.ts.map +1 -0
- package/lib/src/realtime/MetaChannel.d.ts.map +1 -0
- package/lib/src/realtime/Realtime.d.ts.map +1 -0
- package/lib/src/realtime/index.d.ts.map +1 -0
- package/lib/src/services.d.ts.map +1 -0
- package/lib/src/smart-groups/SmartGroupsService.d.ts.map +1 -0
- package/lib/src/smart-groups/index.d.ts.map +1 -0
- package/lib/src/smart-rules/IRule.d.ts.map +1 -0
- package/lib/src/smart-rules/SmartRulesService.d.ts.map +1 -0
- package/lib/src/smart-rules/index.d.ts.map +1 -0
- package/lib/src/system-options/ISystemOption.d.ts.map +1 -0
- package/lib/src/system-options/SystemOptionsService.d.ts.map +1 -0
- package/lib/src/system-options/index.d.ts.map +1 -0
- package/lib/src/tenant/ICurrentTenant.d.ts.map +1 -0
- package/lib/src/tenant/ITenant.d.ts.map +1 -0
- package/lib/src/tenant/ITenantReference.d.ts.map +1 -0
- package/lib/src/tenant/ITfaSettings.d.ts.map +1 -0
- package/lib/src/tenant/TenantService.d.ts.map +1 -0
- package/lib/src/tenant/TenantStatus.d.ts.map +1 -0
- package/lib/src/tenant/TfaStrategy.d.ts.map +1 -0
- package/lib/src/tenant/index.d.ts.map +1 -0
- package/lib/src/tenant-login-options/ITenantLoginOptions.d.ts.map +1 -0
- package/lib/src/tenant-login-options/TenantLoginOptionsService.d.ts.map +1 -0
- package/lib/src/tenant-login-options/index.d.ts.map +1 -0
- package/lib/src/tenant-options/ITenantOption.d.ts.map +1 -0
- package/lib/src/tenant-options/ITenantOptionDetailParams.d.ts.map +1 -0
- package/lib/src/tenant-options/TenantOptionsService.d.ts.map +1 -0
- package/lib/src/tenant-options/index.d.ts.map +1 -0
- package/lib/src/tenant-security-options/ITenantSecurityOption.d.ts.map +1 -0
- package/lib/src/tenant-security-options/TenantSecurityOptionsService.d.ts.map +1 -0
- package/lib/src/tenant-security-options/index.d.ts.map +1 -0
- package/lib/src/trusted-certificates/CrlService.d.ts.map +1 -0
- package/lib/src/trusted-certificates/ICertificateRevocation.d.ts.map +1 -0
- package/lib/src/trusted-certificates/ITrustedCertificate.d.ts.map +1 -0
- package/lib/src/trusted-certificates/TrustedCertificateService.d.ts.map +1 -0
- package/lib/src/trusted-certificates/index.d.ts.map +1 -0
- package/lib/src/user/ICurrentUser.d.ts.map +1 -0
- package/lib/src/user/IResetPassword.d.ts.map +1 -0
- package/lib/src/user/ITotp.d.ts.map +1 -0
- package/lib/src/user/ITotpStatus.d.ts.map +1 -0
- package/lib/src/user/IUser.d.ts.map +1 -0
- package/lib/src/user/IUserInventoryRole.d.ts.map +1 -0
- package/lib/src/user/PasswordStrength.d.ts.map +1 -0
- package/lib/src/user/UserInventoryRoleService.d.ts.map +1 -0
- package/lib/src/user/UserService.d.ts.map +1 -0
- package/lib/src/user/index.d.ts.map +1 -0
- package/lib/src/user-group/IDevicePermissions.d.ts.map +1 -0
- package/lib/src/user-group/IUserGroup.d.ts.map +1 -0
- package/lib/src/user-group/UserGroupService.d.ts.map +1 -0
- package/lib/src/user-group/index.d.ts.map +1 -0
- package/lib/src/user-role/IRole.d.ts.map +1 -0
- package/lib/src/user-role/IRoleReference.d.ts.map +1 -0
- package/lib/src/user-role/UserRoleService.d.ts.map +1 -0
- package/lib/src/user-role/index.d.ts.map +1 -0
- package/package.json +9 -3
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"client.umd.min.js","sources":["../../src/core/Paging.ts","../../src/core/Service.ts","../../../../node_modules/cross-fetch/dist/browser-ponyfill.js","../../src/core/FetchClient.ts","../../../../node_modules/b2a/es/common.js","../../../../node_modules/b2a/es/btoa.js","../../src/core/BasicAuth.ts","../../../../node_modules/b2a/es/atob.js","../../src/core/BearerAuth.ts","../../src/core/CookieAuth.ts","../../src/core/MicroserviceClientRequestAuth.ts","../../src/core/NodeJSCookieAuth.ts","../../src/core/Severity.ts","../../src/core/QueriesUtil.ts","../../src/realtime/MetaChannel.ts","../../../../node_modules/cometd/cometd.js","../../../../node_modules/isomorphic-cometd/browser.js","../../src/realtime/Realtime.ts","../../src/event/EventService.ts","../../../../node_modules/form-data/lib/browser.js","../../src/event/EventBinaryService.ts","../../src/inventory/InventoryBinaryService.ts","../../src/inventory/InventoryService.ts","../../src/measurement/MeasurementService.ts","../../src/measurement/ISeriesFilter.ts","../../src/alarm/AlarmService.ts","../../src/alarm/AlarmStatus.ts","../../src/operation/OperationService.ts","../../src/operation/OperationBulkService.ts","../../src/operation/OperationBulkStatus.ts","../../src/operation/OperationBulkGeneralStatus.ts","../../src/operation/OperationStatus.ts","../../src/tenant/TenantService.ts","../../src/tenant/TenantStatus.ts","../../src/tenant/TfaStrategy.ts","../../src/user/UserInventoryRoleService.ts","../../src/user/UserService.ts","../../src/user/PasswordStrength.ts","../../src/application/ApplicationBinaryService.ts","../../src/application/ApplicationType.ts","../../src/application/ApplicationService.ts","../../src/application/IApplicationInstanceDetails.ts","../../src/application/BillingMode.ts","../../src/application/Isolation.ts","../../src/application/ApplicationAvailability.ts","../../src/system-options/SystemOptionsService.ts","../../src/tenant-options/TenantOptionsService.ts","../../src/tenant-security-options/TenantSecurityOptionsService.ts","../../src/tenant-login-options/TenantLoginOptionsService.ts","../../src/tenant-login-options/ITenantLoginOptions.ts","../../src/audit/AuditService.ts","../../src/audit/AuditRecordType.ts","../../src/audit/ChangeType.ts","../../src/inventory-role/InventoryRoleService.ts","../../src/device-registration/DeviceRegistrationStatus.ts","../../src/device-registration/DeviceRegistrationService.ts","../../src/device-registration/DeviceRegistrationBulkService.ts","../../src/device-registration/DeviceRegistrationSecurityMode.ts","../../src/user-role/UserRoleService.ts","../../src/user-group/UserGroupService.ts","../../src/identity/IdentityService.ts","../../src/trusted-certificates/TrustedCertificateService.ts","../../src/trusted-certificates/CrlService.ts","../../src/smart-groups/SmartGroupsService.ts","../../src/smart-rules/SmartRulesService.ts","../../src/Client.ts"],"sourcesContent":["import { Service } from './Service';\nimport { IResultList } from './IResultList';\n\n/**\n * Paging allows you to query the next and previous data chunks\n * in a convenient way. You can also go to a specific page or just read\n * page information about the current data chunk.\n * Note that page numbers are generated by backend\n * and may be used as offset rather than a continuous range of positive numbers\n * (e.g. in case of users with restricted permissions).\n */\nexport class Paging<TData> {\n /**\n * Holds the number of the current page, so in fact\n * the data chunk you are looking at.\n */\n currentPage: number;\n /**\n * Holds the number of the next page.\n */\n nextPage: number;\n /**\n * Holds the number of the previous page.\n */\n prevPage: number;\n /**\n * Holds the number of the maximum data that you will\n * get with the response.\n */\n pageSize: number;\n /**\n * Holds the number of total pages regarding to the\n * given page size.\n */\n totalPages: number;\n\n private service: Service<TData>;\n private filter: object;\n\n constructor(service: Service<TData>, statistics: any, filter: object) {\n this.filter = filter;\n this.service = service;\n this.currentPage = statistics.currentPage;\n this.nextPage = statistics.nextPage;\n this.prevPage = statistics.prevPage;\n this.pageSize = statistics.pageSize;\n this.totalPages = statistics.totalPages;\n }\n\n /**\n * Gets the next page of available data from the server.\n * @param filter\n */\n async next(filter: object = {}): Promise<IResultList<TData>> {\n return this.list(this.getFilter(filter, this.nextPage));\n }\n\n /**\n * Gets the previous page of available data from server.\n * @param filter\n */\n async prev(filter: object = {}): Promise<IResultList<TData>> {\n return this.list(this.getFilter(filter, this.prevPage));\n }\n\n /**\n * Method used by next(), prev() and goto() to call the service.list method.\n * It is public so it can be overriden in special cases (like children objects\n * in inventory).\n * @param filter\n */\n async list(filter: object = {}): Promise<IResultList<TData>> {\n return this.service.list(filter);\n }\n\n /**\n * Goes to the page that you define as page parameter.\n * @param page\n * @param filter\n */\n async goto(page: number, filter: object = {}): Promise<IResultList<TData>> {\n return this.list(this.getFilter(filter, page));\n }\n\n private getFilter(filter: object, page: number) {\n return Object.assign(filter, this.filter, { currentPage: page });\n }\n}\n","import { IFetchClient } from './IFetchClient';\nimport { IFetchOptions } from './IFetchOptions';\nimport { IFetchResponse } from './IFetchResponse';\nimport { IIdentified } from './IIdentified';\nimport { IResult } from './IResult';\nimport { IResultList } from './IResultList';\nimport { Paging } from './Paging';\n\nimport { Realtime } from '../realtime/index';\n\nexport abstract class Service<TData extends IIdentified> {\n protected propertyName: string;\n protected abstract baseUrl: string;\n protected abstract listUrl: string;\n protected channel: string;\n private cache = new Map();\n\n constructor(protected client: IFetchClient, protected realtime?: Realtime) {\n const methodsToHide = ['list', 'create', 'update', 'detail', 'delete'];\n const prototype = Object.getPrototypeOf(this);\n methodsToHide.forEach(method => {\n if (!prototype.hasOwnProperty(method)) {\n Object.defineProperty(this, method, {\n get() {\n return undefined;\n }\n });\n }\n });\n }\n\n async list(filter: object = {}): Promise<IResultList<TData>> {\n const headers = { accept: 'application/json' };\n const url = this.listUrl;\n const res = await this.fetch(url, this.changeFetchOptions({ headers, params: filter }, url));\n const json = await res.json();\n const data = this.propertyName ? json[this.propertyName] : json;\n const paging = this.getPaging(json, filter);\n return { res, data, paging };\n }\n\n protected async detail(\n entityOrId: string | number | IIdentified,\n filter: object = {}\n ): Promise<IResult<TData>> {\n const headers = { accept: 'application/json' };\n const url = this.getDetailUrl(entityOrId);\n const res = await this.fetch(\n url,\n this.changeFetchOptions({ headers, params: { ...filter } }, url)\n );\n const data = await res.json();\n return { res, data };\n }\n\n protected async create(entity: Partial<TData>): Promise<IResult<TData>> {\n const url = this.listUrl;\n const method = 'POST';\n const body = JSON.stringify(this.onBeforeCreate(entity));\n const headers = { 'content-type': 'application/json', accept: 'application/json' };\n const res = await this.fetch(url, this.changeFetchOptions({ method, body, headers }, url));\n const data = await res.json();\n return { res, data };\n }\n\n protected async update(entity: Partial<TData>): Promise<IResult<TData>> {\n const url = this.getDetailUrl(entity);\n const method = 'PUT';\n const body = JSON.stringify(this.onBeforeUpdate(entity));\n const headers = { 'content-type': 'application/json', accept: 'application/json' };\n const res = await this.fetch(url, this.changeFetchOptions({ method, body, headers }, url));\n const data = await res.json();\n return { res, data };\n }\n\n protected async delete(\n entityOrId: string | number | IIdentified,\n params?: any\n ): Promise<IResult<null>> {\n const method = 'DELETE';\n const url = this.getDetailUrl(entityOrId);\n const res = await this.fetch(url, this.changeFetchOptions({ method, params }, url));\n return { res, data: null };\n }\n\n protected onBeforeCreate(obj: Partial<TData>): Partial<TData> {\n delete obj.id;\n return obj;\n }\n\n protected onBeforeUpdate(objWithId: Partial<TData>): Partial<TData> {\n return objWithId;\n }\n\n protected changeFetchOptions(options: any, _url = '') {\n return options;\n }\n\n protected getUrl(url = ''): string {\n const baseUrl = this.baseUrl.replace(/\\/+$/, '');\n const partialUrl = url.replace(/^\\/+/, '');\n return `${baseUrl}/${partialUrl}`;\n }\n\n protected getEntityId(entityOrId: string | number | IIdentified): string {\n if (entityOrId === undefined || entityOrId === null) {\n return '';\n }\n\n if (typeof entityOrId === 'object') {\n return this.getEntityId(entityOrId.id);\n }\n\n return `${entityOrId}`;\n }\n\n protected getDetailUrl(entityOrId: string | number | IIdentified): string {\n const id = this.getEntityId(entityOrId);\n return `${this.listUrl}/${id}`;\n }\n\n protected async fetch(url: string, init?: IFetchOptions): Promise<IFetchResponse> {\n const fullUrl = this.getUrl(url);\n const res: IFetchResponse = await this.client.fetch(fullUrl, init);\n return await this.handleErrorStatusCodes(res);\n }\n\n /**\n * Checks the response for errors and throws exceptions, otherwise returns the response as is.\n *\n * @param response The response from server.\n *\n * @returns If no errors are detected, it returns the same response.\n *\n * @throws If an error is detected, it throws `{ res, data }`, where `data` contains error details from server.\n */\n protected async handleErrorStatusCodes(response: IFetchResponse): Promise<IFetchResponse> {\n if (response.status >= 400) {\n let data = null;\n try {\n data = await response.json();\n } catch (ex) {\n try {\n data = await response.text();\n } catch (ex) {\n // do nothing\n }\n }\n throw { res: response, data };\n }\n return response;\n }\n\n protected mimeType(type: string): string {\n return `application/vnd.com.nsn.cumulocity.${type}+json`;\n }\n\n protected getIdString(reference: number | string | IIdentified): string {\n let id;\n if (typeof reference === 'object') {\n id = reference.id;\n } else {\n id = reference;\n }\n return String(id);\n }\n\n protected getPaging(json: any, filter: object): Paging<TData> {\n if (json.statistics) {\n const statistics = {\n ...json.statistics,\n nextPage: this.getCurrentPageFromLink(json.next),\n prevPage: this.getCurrentPageFromLink(json.prev)\n };\n return new Paging<TData>(this, statistics, filter);\n }\n return null;\n }\n\n protected getCurrentPageFromLink(link = '') {\n const matches = link.match(/currentPage=(-{0,1}\\d+)/);\n return matches && parseInt(matches[1], 10);\n }\n}\n","var global = typeof self !== 'undefined' ? self : this;\nvar __self__ = (function () {\nfunction F() {\nthis.fetch = false;\nthis.DOMException = global.DOMException\n}\nF.prototype = global;\nreturn new F();\n})();\n(function(self) {\n\nvar irrelevant = (function (exports) {\n\n var support = {\n searchParams: 'URLSearchParams' in self,\n iterable: 'Symbol' in self && 'iterator' in Symbol,\n blob:\n 'FileReader' in self &&\n 'Blob' in self &&\n (function() {\n try {\n new Blob();\n return true\n } catch (e) {\n return false\n }\n })(),\n formData: 'FormData' in self,\n arrayBuffer: 'ArrayBuffer' in self\n };\n\n function isDataView(obj) {\n return obj && DataView.prototype.isPrototypeOf(obj)\n }\n\n if (support.arrayBuffer) {\n var viewClasses = [\n '[object Int8Array]',\n '[object Uint8Array]',\n '[object Uint8ClampedArray]',\n '[object Int16Array]',\n '[object Uint16Array]',\n '[object Int32Array]',\n '[object Uint32Array]',\n '[object Float32Array]',\n '[object Float64Array]'\n ];\n\n var isArrayBufferView =\n ArrayBuffer.isView ||\n function(obj) {\n return obj && viewClasses.indexOf(Object.prototype.toString.call(obj)) > -1\n };\n }\n\n function normalizeName(name) {\n if (typeof name !== 'string') {\n name = String(name);\n }\n if (/[^a-z0-9\\-#$%&'*+.^_`|~]/i.test(name)) {\n throw new TypeError('Invalid character in header field name')\n }\n return name.toLowerCase()\n }\n\n function normalizeValue(value) {\n if (typeof value !== 'string') {\n value = String(value);\n }\n return value\n }\n\n // Build a destructive iterator for the value list\n function iteratorFor(items) {\n var iterator = {\n next: function() {\n var value = items.shift();\n return {done: value === undefined, value: value}\n }\n };\n\n if (support.iterable) {\n iterator[Symbol.iterator] = function() {\n return iterator\n };\n }\n\n return iterator\n }\n\n function Headers(headers) {\n this.map = {};\n\n if (headers instanceof Headers) {\n headers.forEach(function(value, name) {\n this.append(name, value);\n }, this);\n } else if (Array.isArray(headers)) {\n headers.forEach(function(header) {\n this.append(header[0], header[1]);\n }, this);\n } else if (headers) {\n Object.getOwnPropertyNames(headers).forEach(function(name) {\n this.append(name, headers[name]);\n }, this);\n }\n }\n\n Headers.prototype.append = function(name, value) {\n name = normalizeName(name);\n value = normalizeValue(value);\n var oldValue = this.map[name];\n this.map[name] = oldValue ? oldValue + ', ' + value : value;\n };\n\n Headers.prototype['delete'] = function(name) {\n delete this.map[normalizeName(name)];\n };\n\n Headers.prototype.get = function(name) {\n name = normalizeName(name);\n return this.has(name) ? this.map[name] : null\n };\n\n Headers.prototype.has = function(name) {\n return this.map.hasOwnProperty(normalizeName(name))\n };\n\n Headers.prototype.set = function(name, value) {\n this.map[normalizeName(name)] = normalizeValue(value);\n };\n\n Headers.prototype.forEach = function(callback, thisArg) {\n for (var name in this.map) {\n if (this.map.hasOwnProperty(name)) {\n callback.call(thisArg, this.map[name], name, this);\n }\n }\n };\n\n Headers.prototype.keys = function() {\n var items = [];\n this.forEach(function(value, name) {\n items.push(name);\n });\n return iteratorFor(items)\n };\n\n Headers.prototype.values = function() {\n var items = [];\n this.forEach(function(value) {\n items.push(value);\n });\n return iteratorFor(items)\n };\n\n Headers.prototype.entries = function() {\n var items = [];\n this.forEach(function(value, name) {\n items.push([name, value]);\n });\n return iteratorFor(items)\n };\n\n if (support.iterable) {\n Headers.prototype[Symbol.iterator] = Headers.prototype.entries;\n }\n\n function consumed(body) {\n if (body.bodyUsed) {\n return Promise.reject(new TypeError('Already read'))\n }\n body.bodyUsed = true;\n }\n\n function fileReaderReady(reader) {\n return new Promise(function(resolve, reject) {\n reader.onload = function() {\n resolve(reader.result);\n };\n reader.onerror = function() {\n reject(reader.error);\n };\n })\n }\n\n function readBlobAsArrayBuffer(blob) {\n var reader = new FileReader();\n var promise = fileReaderReady(reader);\n reader.readAsArrayBuffer(blob);\n return promise\n }\n\n function readBlobAsText(blob) {\n var reader = new FileReader();\n var promise = fileReaderReady(reader);\n reader.readAsText(blob);\n return promise\n }\n\n function readArrayBufferAsText(buf) {\n var view = new Uint8Array(buf);\n var chars = new Array(view.length);\n\n for (var i = 0; i < view.length; i++) {\n chars[i] = String.fromCharCode(view[i]);\n }\n return chars.join('')\n }\n\n function bufferClone(buf) {\n if (buf.slice) {\n return buf.slice(0)\n } else {\n var view = new Uint8Array(buf.byteLength);\n view.set(new Uint8Array(buf));\n return view.buffer\n }\n }\n\n function Body() {\n this.bodyUsed = false;\n\n this._initBody = function(body) {\n this._bodyInit = body;\n if (!body) {\n this._bodyText = '';\n } else if (typeof body === 'string') {\n this._bodyText = body;\n } else if (support.blob && Blob.prototype.isPrototypeOf(body)) {\n this._bodyBlob = body;\n } else if (support.formData && FormData.prototype.isPrototypeOf(body)) {\n this._bodyFormData = body;\n } else if (support.searchParams && URLSearchParams.prototype.isPrototypeOf(body)) {\n this._bodyText = body.toString();\n } else if (support.arrayBuffer && support.blob && isDataView(body)) {\n this._bodyArrayBuffer = bufferClone(body.buffer);\n // IE 10-11 can't handle a DataView body.\n this._bodyInit = new Blob([this._bodyArrayBuffer]);\n } else if (support.arrayBuffer && (ArrayBuffer.prototype.isPrototypeOf(body) || isArrayBufferView(body))) {\n this._bodyArrayBuffer = bufferClone(body);\n } else {\n this._bodyText = body = Object.prototype.toString.call(body);\n }\n\n if (!this.headers.get('content-type')) {\n if (typeof body === 'string') {\n this.headers.set('content-type', 'text/plain;charset=UTF-8');\n } else if (this._bodyBlob && this._bodyBlob.type) {\n this.headers.set('content-type', this._bodyBlob.type);\n } else if (support.searchParams && URLSearchParams.prototype.isPrototypeOf(body)) {\n this.headers.set('content-type', 'application/x-www-form-urlencoded;charset=UTF-8');\n }\n }\n };\n\n if (support.blob) {\n this.blob = function() {\n var rejected = consumed(this);\n if (rejected) {\n return rejected\n }\n\n if (this._bodyBlob) {\n return Promise.resolve(this._bodyBlob)\n } else if (this._bodyArrayBuffer) {\n return Promise.resolve(new Blob([this._bodyArrayBuffer]))\n } else if (this._bodyFormData) {\n throw new Error('could not read FormData body as blob')\n } else {\n return Promise.resolve(new Blob([this._bodyText]))\n }\n };\n\n this.arrayBuffer = function() {\n if (this._bodyArrayBuffer) {\n return consumed(this) || Promise.resolve(this._bodyArrayBuffer)\n } else {\n return this.blob().then(readBlobAsArrayBuffer)\n }\n };\n }\n\n this.text = function() {\n var rejected = consumed(this);\n if (rejected) {\n return rejected\n }\n\n if (this._bodyBlob) {\n return readBlobAsText(this._bodyBlob)\n } else if (this._bodyArrayBuffer) {\n return Promise.resolve(readArrayBufferAsText(this._bodyArrayBuffer))\n } else if (this._bodyFormData) {\n throw new Error('could not read FormData body as text')\n } else {\n return Promise.resolve(this._bodyText)\n }\n };\n\n if (support.formData) {\n this.formData = function() {\n return this.text().then(decode)\n };\n }\n\n this.json = function() {\n return this.text().then(JSON.parse)\n };\n\n return this\n }\n\n // HTTP methods whose capitalization should be normalized\n var methods = ['DELETE', 'GET', 'HEAD', 'OPTIONS', 'POST', 'PUT'];\n\n function normalizeMethod(method) {\n var upcased = method.toUpperCase();\n return methods.indexOf(upcased) > -1 ? upcased : method\n }\n\n function Request(input, options) {\n options = options || {};\n var body = options.body;\n\n if (input instanceof Request) {\n if (input.bodyUsed) {\n throw new TypeError('Already read')\n }\n this.url = input.url;\n this.credentials = input.credentials;\n if (!options.headers) {\n this.headers = new Headers(input.headers);\n }\n this.method = input.method;\n this.mode = input.mode;\n this.signal = input.signal;\n if (!body && input._bodyInit != null) {\n body = input._bodyInit;\n input.bodyUsed = true;\n }\n } else {\n this.url = String(input);\n }\n\n this.credentials = options.credentials || this.credentials || 'same-origin';\n if (options.headers || !this.headers) {\n this.headers = new Headers(options.headers);\n }\n this.method = normalizeMethod(options.method || this.method || 'GET');\n this.mode = options.mode || this.mode || null;\n this.signal = options.signal || this.signal;\n this.referrer = null;\n\n if ((this.method === 'GET' || this.method === 'HEAD') && body) {\n throw new TypeError('Body not allowed for GET or HEAD requests')\n }\n this._initBody(body);\n }\n\n Request.prototype.clone = function() {\n return new Request(this, {body: this._bodyInit})\n };\n\n function decode(body) {\n var form = new FormData();\n body\n .trim()\n .split('&')\n .forEach(function(bytes) {\n if (bytes) {\n var split = bytes.split('=');\n var name = split.shift().replace(/\\+/g, ' ');\n var value = split.join('=').replace(/\\+/g, ' ');\n form.append(decodeURIComponent(name), decodeURIComponent(value));\n }\n });\n return form\n }\n\n function parseHeaders(rawHeaders) {\n var headers = new Headers();\n // Replace instances of \\r\\n and \\n followed by at least one space or horizontal tab with a space\n // https://tools.ietf.org/html/rfc7230#section-3.2\n var preProcessedHeaders = rawHeaders.replace(/\\r?\\n[\\t ]+/g, ' ');\n preProcessedHeaders.split(/\\r?\\n/).forEach(function(line) {\n var parts = line.split(':');\n var key = parts.shift().trim();\n if (key) {\n var value = parts.join(':').trim();\n headers.append(key, value);\n }\n });\n return headers\n }\n\n Body.call(Request.prototype);\n\n function Response(bodyInit, options) {\n if (!options) {\n options = {};\n }\n\n this.type = 'default';\n this.status = options.status === undefined ? 200 : options.status;\n this.ok = this.status >= 200 && this.status < 300;\n this.statusText = 'statusText' in options ? options.statusText : 'OK';\n this.headers = new Headers(options.headers);\n this.url = options.url || '';\n this._initBody(bodyInit);\n }\n\n Body.call(Response.prototype);\n\n Response.prototype.clone = function() {\n return new Response(this._bodyInit, {\n status: this.status,\n statusText: this.statusText,\n headers: new Headers(this.headers),\n url: this.url\n })\n };\n\n Response.error = function() {\n var response = new Response(null, {status: 0, statusText: ''});\n response.type = 'error';\n return response\n };\n\n var redirectStatuses = [301, 302, 303, 307, 308];\n\n Response.redirect = function(url, status) {\n if (redirectStatuses.indexOf(status) === -1) {\n throw new RangeError('Invalid status code')\n }\n\n return new Response(null, {status: status, headers: {location: url}})\n };\n\n exports.DOMException = self.DOMException;\n try {\n new exports.DOMException();\n } catch (err) {\n exports.DOMException = function(message, name) {\n this.message = message;\n this.name = name;\n var error = Error(message);\n this.stack = error.stack;\n };\n exports.DOMException.prototype = Object.create(Error.prototype);\n exports.DOMException.prototype.constructor = exports.DOMException;\n }\n\n function fetch(input, init) {\n return new Promise(function(resolve, reject) {\n var request = new Request(input, init);\n\n if (request.signal && request.signal.aborted) {\n return reject(new exports.DOMException('Aborted', 'AbortError'))\n }\n\n var xhr = new XMLHttpRequest();\n\n function abortXhr() {\n xhr.abort();\n }\n\n xhr.onload = function() {\n var options = {\n status: xhr.status,\n statusText: xhr.statusText,\n headers: parseHeaders(xhr.getAllResponseHeaders() || '')\n };\n options.url = 'responseURL' in xhr ? xhr.responseURL : options.headers.get('X-Request-URL');\n var body = 'response' in xhr ? xhr.response : xhr.responseText;\n resolve(new Response(body, options));\n };\n\n xhr.onerror = function() {\n reject(new TypeError('Network request failed'));\n };\n\n xhr.ontimeout = function() {\n reject(new TypeError('Network request failed'));\n };\n\n xhr.onabort = function() {\n reject(new exports.DOMException('Aborted', 'AbortError'));\n };\n\n xhr.open(request.method, request.url, true);\n\n if (request.credentials === 'include') {\n xhr.withCredentials = true;\n } else if (request.credentials === 'omit') {\n xhr.withCredentials = false;\n }\n\n if ('responseType' in xhr && support.blob) {\n xhr.responseType = 'blob';\n }\n\n request.headers.forEach(function(value, name) {\n xhr.setRequestHeader(name, value);\n });\n\n if (request.signal) {\n request.signal.addEventListener('abort', abortXhr);\n\n xhr.onreadystatechange = function() {\n // DONE (success or failure)\n if (xhr.readyState === 4) {\n request.signal.removeEventListener('abort', abortXhr);\n }\n };\n }\n\n xhr.send(typeof request._bodyInit === 'undefined' ? null : request._bodyInit);\n })\n }\n\n fetch.polyfill = true;\n\n if (!self.fetch) {\n self.fetch = fetch;\n self.Headers = Headers;\n self.Request = Request;\n self.Response = Response;\n }\n\n exports.Headers = Headers;\n exports.Request = Request;\n exports.Response = Response;\n exports.fetch = fetch;\n\n Object.defineProperty(exports, '__esModule', { value: true });\n\n return exports;\n\n})({});\n})(__self__);\n__self__.fetch.ponyfill = true;\n// Remove \"polyfill\" property added by whatwg-fetch\ndelete __self__.fetch.polyfill;\n// Choose between native implementation (global) or custom implementation (__self__)\n// var ctx = global.fetch ? global : __self__;\nvar ctx = __self__; // this line disable service worker support temporarily\nexports = ctx.fetch // To enable: import fetch from 'cross-fetch'\nexports.default = ctx.fetch // For TypeScript consumers without esModuleInterop.\nexports.fetch = ctx.fetch // To enable: import {fetch} from 'cross-fetch'\nexports.Headers = ctx.Headers\nexports.Request = ctx.Request\nexports.Response = ctx.Response\nmodule.exports = exports\n","import fetch from 'cross-fetch';\n\nimport { IFetchClient } from './IFetchClient';\nimport { IFetchOptions } from './IFetchOptions';\nimport { IFetchResponse } from './IFetchResponse';\nimport { IAuthentication } from './IAuthentication';\n\n// eslint-disable-next-line prefer-const\nlet auths = new WeakMap();\n\nexport class FetchClient implements IFetchClient {\n tenant = '';\n defaultHeaders = {};\n constructor(authOrBaseUrl?: IAuthentication | string, public baseUrl?: string) {\n if (typeof authOrBaseUrl === 'string') {\n baseUrl = authOrBaseUrl;\n } else {\n this.setAuth(authOrBaseUrl);\n }\n this.baseUrl = this.resolveServerUrl(baseUrl);\n }\n\n setAuth(auth: IAuthentication) {\n auths.set(this, auth);\n }\n\n async fetch(url: string, init?: IFetchOptions): Promise<IFetchResponse> {\n let fetchFn = fetch;\n try {\n fetchFn = window.fetch || fetchFn;\n } catch (e) {\n /* do nothing */\n }\n const fullUrl: string = this.getUrl(url, init);\n const options: IFetchOptions = this.getFetchOptions(init);\n const optionsWithAdjustedBody = this.adjustOptionsForFormData(options);\n return fetchFn(fullUrl, optionsWithAdjustedBody);\n }\n\n getUrl(url = '', options?: IFetchOptions): string {\n const params = options && options.params;\n let paramPart = '';\n if (params && Object.keys(params).length) {\n paramPart = Object.keys(params)\n .map(k => {\n let vals = params[k];\n const encodedKey = encodeURIComponent(k);\n if (!Array.isArray(vals)) {\n vals = [vals];\n }\n return vals.map(v => `${encodedKey}=${encodeURIComponent(v)}`).join('&');\n })\n .join('&');\n paramPart = `?${paramPart}`;\n }\n const baseUrl = this.baseUrl.replace(/\\/+$/, '').replace(/^\\/+/, '');\n const partialUrl = url.replace(/\\/+$/, '').replace(/^\\/+/, '');\n return `${baseUrl}/${partialUrl}${paramPart}`;\n }\n\n getFetchOptions(options: IFetchOptions = {}): IFetchOptions {\n let clonedOptions = { ...options };\n const auth = auths.get(this);\n clonedOptions.headers = Object.assign({}, this.defaultHeaders, clonedOptions.headers, {\n UseXBasic: true\n });\n delete clonedOptions.params;\n clonedOptions = auth ? auth.getFetchOptions(clonedOptions) : clonedOptions;\n return clonedOptions;\n }\n\n getCometdHandshake(config: any = {}) {\n const auth = auths.get(this);\n return auth ? auth.getCometdHandshake(config) : config;\n }\n\n private resolveServerUrl(baseUrl = ''): any {\n if (baseUrl && baseUrl.startsWith('http')) {\n return baseUrl.replace(/\\/+$/, '');\n }\n try {\n const location = window.location;\n return `${location.protocol}//${location.host}/${baseUrl.replace(/\\/+$/, '')}`;\n } catch (ex) {\n throw Error('Your environment does not support relative URLs. Please provide a base URL.');\n }\n }\n\n private adjustOptionsForFormData(options: IFetchOptions): RequestInit {\n const newOptions = Object.assign(options, { body: options.body as RequestInit['body'] });\n return newOptions;\n }\n}\n","export var error = function (message) {\n function E() {\n this.message = message;\n }\n\n E.prototype = new Error();\n E.prototype.name = 'InvalidCharacterError';\n E.prototype.code = 5;\n return E;\n};\nexport var chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=';","import { chars, error } from './common'; // btoa polyfill for IE<10 courtesy https://gist.github.com/nignag/999166\n\nvar E = error('The string to be encoded contains characters out of range');\nexport var _btoa = typeof btoa !== 'undefined'\n/* istanbul ignore next */\n? function (input) {\n return btoa(input);\n} : function (input) {\n var str = String(input);\n var output = '';\n\n for ( // initialize result and counter\n var block, charCode, idx = 0, map = chars; // if the next str index does not exist:\n // change the mapping table to \"=\"\n // check if d has no fractional digits\n str.charAt(idx | 0) || (map = '=', idx % 1); // \"8 - idx % 1 * 8\" generates the sequence 2, 4, 6, 8\n output += map.charAt(63 & block >> 8 - idx % 1 * 8)) {\n charCode = str.charCodeAt(idx += 3 / 4);\n\n if (charCode > 0xFF) {\n throw new E();\n }\n\n block = block << 8 | charCode;\n }\n\n return output;\n};\n\nvar utf8 = function (input) {\n return encodeURIComponent(input).replace(/%([0-9A-F]{2})/g, function (match, p1) {\n return String.fromCharCode('0x' + p1);\n });\n};\n\nexport default (function (input) {\n return _btoa(utf8(input));\n});","import { IAuthentication, ICredentials } from './IAuthentication';\nimport { btoa } from 'b2a';\n\n// this is var and not const to please typedoc https://github.com/TypeStrong/typedoc/issues/691\n// eslint-disable-next-line no-var\nvar secrets = new WeakMap();\n\n/**\n * Allows to use Basic-Auth for Authorization to the\n * Cumulocity API.\n */\nexport class BasicAuth implements IAuthentication {\n user: string;\n /**\n * Authenticates the given user against the given tenant.\n * @param name\n * @param password\n * @param tenant\n */\n constructor(credentials?: ICredentials) {\n this.updateCredentials(credentials);\n }\n\n updateCredentials({ tenant, user, password, token, tfa }: ICredentials = {}) {\n const secret = secrets.get(this) || {};\n if (user && tenant) {\n user = `${tenant}/${user}`;\n }\n user = user || this.user;\n password = password || secret.password;\n if (!token && user && password) {\n token = btoa(`${user}:${password}`);\n }\n if (user) {\n this.user = user;\n }\n token = token || secret.token;\n tfa = tfa || secret.tfa;\n secrets.set(this, { tfa, token, password });\n return token;\n }\n\n getFetchOptions(options) {\n const secret = secrets.get(this);\n const { token, tfa } = secret;\n const xsrfToken = this.getCookieValue('XSRF-TOKEN');\n const headers: any = {\n Authorization: `Basic ${token || ''}`,\n ...(xsrfToken ? { 'X-XSRF-TOKEN': xsrfToken } : undefined)\n };\n\n if (tfa) {\n headers.tfatoken = tfa;\n }\n options.headers = Object.assign(headers, options.headers);\n return options;\n }\n\n getCometdHandshake(config: { ext?: object } = {}) {\n const secret = secrets.get(this);\n const { token, tfa } = secret;\n const KEY = 'com.cumulocity.authn';\n const ext = (config.ext = config.ext || {});\n ext[KEY] = Object.assign(ext[KEY] || {}, { token, tfa });\n return config;\n }\n\n logout() {\n delete this.user;\n secrets.set(this, {});\n }\n\n private getCookieValue(name) {\n try {\n const value = document.cookie.match('(^|;)\\\\s*' + name + '\\\\s*=\\\\s*([^;]+)');\n return value ? value.pop() : undefined;\n } catch (ex) {\n return undefined;\n }\n }\n}\n","import { chars, error } from './common';\nvar E = error('The string to be decoded is not correctly encoded');\nexport var _atob = typeof atob !== 'undefined'\n/* istanbul ignore next */\n? function (input) {\n return atob(input);\n} : function (input) {\n var str = String(input).replace(/[=]+$/, '');\n\n if (str.length % 4 == 1) {\n throw new E();\n }\n\n var output = '';\n\n for ( // initialize result and counters\n var bc = 0, bs, buffer, idx = 0; // get next character\n buffer = str.charAt(idx++); // character found in table? initialize bit storage and add its ascii value;\n ~buffer && (bs = bc % 4 ? bs * 64 + buffer : buffer, // and if not first of each 4 characters,\n // convert the first 8 bits to one ascii character\n bc++ % 4) ? output += String.fromCharCode(255 & bs >> (-2 * bc & 6)) : 0) {\n // try to find character in table (0-63, not found => -1)\n buffer = chars.indexOf(buffer);\n }\n\n return output;\n};\n\nvar utf16 = function (input) {\n return decodeURIComponent(input.split('').map(function (c) {\n return '%' + ('00' + c.charCodeAt(0).toString(16)).slice(-2);\n }).join(''));\n};\n\nexport default (function (input) {\n return utf16(_atob(input));\n});","import { IAuthentication, ICredentials } from './IAuthentication';\n\nconst secrets = new WeakMap();\n\nexport class BearerAuth implements IAuthentication {\n constructor(token?: string) {\n secrets.set(this, { token });\n }\n getFetchOptions(options: any): any {\n const secret = secrets.get(this);\n const { token } = secret;\n options.headers = Object.assign({ Authorization: `Bearer ${token}` }, options.headers);\n return options;\n }\n\n updateCredentials({ token }: ICredentials): undefined {\n secrets.set(this, { token });\n return;\n }\n\n getCometdHandshake(config: { ext?: any } = {}) {\n const secret = secrets.get(this);\n const { token, tfa } = secret;\n const KEY = 'com.cumulocity.authn';\n const ext = (config.ext = config.ext || {});\n ext[KEY] = Object.assign(ext[KEY] || {}, { token, tfa });\n return config;\n }\n\n logout(): void {\n secrets.set(this, {});\n }\n}\n","import { IAuthentication, ICredentials } from './IAuthentication';\nimport { FetchClient } from './FetchClient';\n\n/**\n * Allows to use Cookies for Authorization to the\n * Cumulocity API.\n */\nexport class CookieAuth implements IAuthentication {\n user: string;\n private logoutUrl = 'user/logout';\n\n updateCredentials({ user }: ICredentials = {}): string {\n this.user = user;\n return undefined;\n }\n\n getFetchOptions(options) {\n const xsrfToken = this.getCookieValue('XSRF-TOKEN');\n const headers: any = { 'X-XSRF-TOKEN': xsrfToken };\n options.headers = Object.assign(headers, options.headers);\n return options;\n }\n\n getCometdHandshake(config: { ext?: object } = {}) {\n const KEY = 'com.cumulocity.authn';\n const xsrfToken = this.getCookieValue('XSRF-TOKEN');\n const ext = (config.ext = config.ext || {});\n ext[KEY] = Object.assign(ext[KEY] || {}, { xsrfToken });\n return config;\n }\n\n async logout() {\n if (this.user) {\n delete this.user;\n }\n const client = new FetchClient();\n client.setAuth(this);\n const method = 'POST';\n const body = JSON.stringify({});\n const headers = { 'content-type': 'application/json', accept: 'application/json' };\n return client.fetch(this.logoutUrl, { headers, body, method });\n }\n\n private getCookieValue(name) {\n const value = document.cookie.match('(^|;)\\\\s*' + name + '\\\\s*=\\\\s*([^;]+)');\n return value ? value.pop() : '';\n }\n}\n","import { IAuthentication, IMicroserviceClientRequestHeaders } from './IAuthentication';\n\n/**\n * Allows to use either Cookie-Auth or Basic-Auth\n * of a microservice client request header\n * for Authorization to the Cumulocity API.\n */\nexport class MicroserviceClientRequestAuth implements IAuthentication {\n // Bearer token read from cookie from header\n protected authTokenFromCookie: string | undefined;\n // Bearer/Basic auth token read from header\n protected authTokenFromHeader: string | undefined;\n protected xsrfToken: string | undefined;\n\n /**\n * Authenticates using the credentials which were\n * provided within the request headers of the\n * client call to the microservice.\n * @param headers\n */\n constructor(headers: IMicroserviceClientRequestHeaders = {}) {\n this.xsrfToken = this.getCookieValue(headers, 'XSRF-TOKEN');\n this.authTokenFromCookie = this.getCookieValue(headers, 'authorization');\n this.authTokenFromHeader = headers.authorization;\n }\n\n updateCredentials(): string {\n return undefined;\n }\n\n getFetchOptions(options: any) {\n const headers: any = {\n Authorization: this.authTokenFromCookie\n ? `Bearer ${this.authTokenFromCookie}`\n : this.authTokenFromHeader,\n ...(this.xsrfToken ? { 'X-XSRF-TOKEN': this.xsrfToken } : undefined)\n };\n options.headers = Object.assign(headers, options.headers);\n return options;\n }\n\n getCometdHandshake(config: { ext?: { [key: string]: any } } = {}) {\n const KEY = 'com.cumulocity.authn';\n const xsrfToken = this.xsrfToken;\n let token = this.authTokenFromCookie;\n if (!token && this.authTokenFromHeader) {\n token = this.authTokenFromHeader.replace('Basic ', '').replace('Bearer ', '');\n }\n const ext = (config.ext = config.ext || {});\n ext[KEY] = Object.assign(ext[KEY] || {}, { token, ...(xsrfToken ? { xsrfToken } : undefined) });\n return config;\n }\n\n logout() {\n if (this.authTokenFromCookie) {\n delete this.authTokenFromCookie;\n }\n if (this.authTokenFromHeader) {\n delete this.authTokenFromHeader;\n }\n if (this.xsrfToken) {\n delete this.xsrfToken;\n }\n }\n\n protected getCookieValue(headers: IMicroserviceClientRequestHeaders, name: string) {\n try {\n const value =\n headers && headers.cookie && headers.cookie.match('(^|;)\\\\s*' + name + '\\\\s*=\\\\s*([^;]+)');\n return value ? value.pop() : undefined;\n } catch (ex) {\n return undefined;\n }\n }\n}\n","import { IFetchResponse } from './IFetchResponse';\nimport { MicroserviceClientRequestAuth } from './MicroserviceClientRequestAuth';\n\n/**\n * Extracts the `authorization` cookie from the `set-cookie` header of a response.\n *\n * Meant to be used in none browser environments like nodejs which don't deal with cookies.\n */\nexport class NodeJSCookieAuth extends MicroserviceClientRequestAuth {\n constructor(cookieResponse: IFetchResponse) {\n super();\n\n const setCookiesHeader = cookieResponse.headers.get('set-cookie');\n if (!setCookiesHeader) {\n throw Error('No Cookie set');\n }\n this.authTokenFromCookie = this.getCookieValue({ cookie: setCookiesHeader }, 'authorization');\n }\n}\n","import { gettext } from '../gettext';\n\n/**\n * Severity can be one of the following states.\n * It is used in [[AlarmService]] for example.\n */\nexport enum Severity {\n CRITICAL = gettext('CRITICAL'),\n MAJOR = gettext('MAJOR'),\n MINOR = gettext('MINOR'),\n WARNING = gettext('WARNING')\n}\n","export class QueriesUtil {\n protected operatorFns = {\n __not: operand => {\n return `not(${this.buildQueryFilter(operand, null)})`;\n },\n __and: operand => {\n return this.buildQueryFilter(operand, null, 'and');\n },\n __or: operand => {\n return this.buildQueryFilter(operand, null, 'or');\n },\n __eq: (operand, contextKey) => {\n if (typeof operand === 'object' && operand !== null) {\n return this.buildQueryFilter(operand, contextKey);\n }\n return `${contextKey} eq ${this.quoteString(operand)}`;\n },\n __gt: (operand, contextKey) => {\n return `${contextKey} gt ${this.quoteString(operand)}`;\n },\n __ge: (operand, contextKey) => {\n return `${contextKey} ge ${this.quoteString(operand)}`;\n },\n __lt: (operand, contextKey) => {\n return `${contextKey} lt ${this.quoteString(operand)}`;\n },\n __le: (operand, contextKey) => {\n return `${contextKey} le ${this.quoteString(operand)}`;\n },\n __in: (operand, contextKey) => {\n const stmts = operand\n .filter(op => !!op)\n .map(op => {\n return `${contextKey} eq ${this.quoteString(op)}`;\n });\n return this.glue(stmts, 'or');\n },\n __bygroupid: operand => {\n return `bygroupid(${operand})`;\n },\n __has: operand => {\n return `has(${operand})`;\n },\n __useFilterQueryString: (queryString: string) => {\n // match everything inside the most exterior parentheses, including them\n const query = queryString.match(/\\(.*\\)/)?.[0];\n // get rid of the most exterior parentheses\n return query?.substring(1, query.length - 1);\n }\n };\n\n /**\n * Builds query string from provided query object.\n *\n * @param query Object containing filters and sort order for querying managed objects. Supported filters are:\n * - **__and** - Specifies conditions, e.g. `{__and: [{__has: 'c8y_IsDevice'}, {'count': {__gt: 0}}]}`.\n * - **__or** - Specifies alternative conditions, e.g. `{__or: [{__bygroupid: 10300}, {__bygroupid: 10400}]}`.\n * - **__eq** - Specified fragment must be equal to given value, e.g. `{'status': 'AVAILABLE'}` (no nested object required).\n * - **__lt** - Specified fragment must be less then given value, e.g. `{'count': {__lt: 10}}`.\n * - **__gt** - Specified fragment must be greater then given value, e.g. `{'count': {__gt: 0}}`.\n * - **__in** - Specified fragment must be equal to one of values in the list, e.g. `{'status': {__in: ['AVAILABLE', 'UNAVAILABLE']}}`.\n * - **__not** - Negates condition, e.g. `{__not: {'status': 'AVAILABLE'}}`.\n * - **__bygroupid** - True if filtered managed object is assigned to given group, e.g. `{__bygroupid: 10300}`.\n * - **__has** - Specified fragment must have a value defined, e.g. `{__has: 'c8y_IsDevice'}`.\n * - **__useFilterQueryString** - Gets rid of the `$filter=()… $orderby=…` parts of a query and keeps only what's between the most\n * exterior parentheses of the $filter.\n * EXAMPLE: takes a query of the form\n * `$filter=(name eq 'RaspPi*') $orderby=name asc`\n * and turns it into\n * `name eq 'RaspPi*'`\n * This is necessary for searching for smart groups, which are identified by their own query\n * that needs to be passed through.\n *\n * Note: if you want to specify the order, you need to wrap your filters within `__filter` property and then add `__orderby` with the array of field paths and sort directions (1 for ascending, -1 for descending), for example:\n * - `{ __filter: { ... }, __orderby: [{ 'creationTime': -1 }, { 'name': 1 }] }`\n *\n * @returns {string} Returns a query string ready to be sent in request params to backend.\n *\n * **Example**\n * ```typescript\n * const query = {\n * __filter: {\n * 'name': 'My Device*',\n * 'c8y_Availability.status': {\n * __in: ['AVAILABLE', 'UNAVAILABLE']\n * },\n * 'creationTime': {\n * __lt: '2015-11-30T13:28:123Z'\n * },\n * 'c8y_ActiveAlarmsStatus.critical': {\n * __gt: 0\n * },\n * __or: [\n * {__not: {__has: 'c8y_ActiveAlarmsStatus.major'}},\n * {\n * __or: [\n * {__bygroupid: 10300},\n * {__bygroupid: 10400}\n * ]\n * }\n * ]\n * },\n * __orderby: [\n * {'name': 1},\n * {'creationTime': -1},\n * {'c8y_ActiveAlarmsStatus.critical': -1}\n * ]\n * };\n *\n * const params = {\n * query: queriesUtil.buildQuery(query)\n * };\n * ```\n */\n buildQuery(query): string {\n const q = [];\n const filter = this.buildQueryFilter(query.__filter || query);\n const orderBy = this.buildQueryOrderby(query.__orderby);\n if (filter) {\n q.push(`$filter=(${filter})`);\n }\n if (orderBy) {\n q.push(`$orderby=${orderBy}`);\n }\n return q.join(' ');\n }\n\n buildQueryFilter(queryFilter, _queryKey?, _glueType?): string {\n const queryKey = _queryKey || null;\n const glueType = _glueType || 'and';\n\n const q = [];\n\n if (Array.isArray(queryFilter)) {\n queryFilter.forEach(qFilter => {\n const _q = this.buildQueryFilter(qFilter, null, glueType);\n if (_q) {\n q.push(_q);\n }\n });\n } else {\n let _q;\n Object.keys(queryFilter).forEach(k => {\n if (this.operatorFns[k] !== undefined) {\n _q = this.operatorFns[k](queryFilter[k], queryKey);\n if (_q) {\n q.push(_q);\n }\n } else {\n _q = this.operatorFns.__eq(queryFilter[k], k);\n if (_q) {\n q.push(_q);\n }\n }\n });\n }\n\n return this.glue(q, glueType);\n }\n\n buildQueryOrderby(queryOrderbys): string {\n const o = [];\n if (queryOrderbys) {\n queryOrderbys.forEach(q => {\n Object.keys(q).forEach(k => {\n if (q[k] !== 0) {\n o.push(`${k} ${q[k] > 0 ? 'asc' : 'desc'}`);\n }\n });\n });\n }\n return o.join(',');\n }\n\n addAndFilter(query, filter) {\n return this.addFilter(query, filter, 'and');\n }\n\n addOrFilter(query, filter) {\n return this.addFilter(query, filter, 'or');\n }\n\n addFilter(query, filter, operator: 'and' | 'or') {\n const oldFilter = query.__orderby ? query.__filter || {} : query.__filter || query;\n const newFilter = { [`__${operator}`]: this.skipEmptyObjects([oldFilter, filter]) };\n if (!query.__filter && !query.__orderby) {\n return newFilter;\n }\n query.__filter = newFilter;\n return query;\n }\n\n prependOrderbys(query, orderbys) {\n return this.addOrderbys(query, orderbys, 'prepend');\n }\n\n appendOrderbys(query, orderbys) {\n return this.addOrderbys(query, orderbys, 'append');\n }\n\n addOrderbys(query, orderbys, how: 'prepend' | 'append') {\n const oldFilter = query.__orderby ? query.__filter || {} : query.__filter || query;\n const oldOrderbys = query.__orderby || [];\n const newOrderbys =\n how === 'prepend' ? [...orderbys, ...oldOrderbys] : [...oldOrderbys, ...orderbys];\n const newQuery: any = {\n __orderby: this.skipEmptyObjects(newOrderbys)\n };\n if (!this.isEmptyObject(oldFilter)) {\n newQuery.__filter = oldFilter;\n }\n return newQuery;\n }\n\n extractAndMergeOrderBys(queries: string[]): string {\n if (queries?.length > 0) {\n const orderByQuery = queries\n .map(query => query.match(/\\$orderby=(.*)$/)?.[1])\n .filter(orderBy => !!orderBy)\n .join(',');\n return orderByQuery ? `$orderby=${orderByQuery}` : '';\n }\n }\n\n protected glue(stmts: any[], type: string) {\n return stmts.length > 1 ? `(${stmts.join(`) ${type} (`)})` : stmts[0];\n }\n\n protected quoteString(s: any) {\n return typeof s === 'string' ? `'${this.escapeSingleQuote(s)}'` : s;\n }\n\n protected skipEmptyObjects(objs: any[]) {\n return objs.filter(obj => !this.isEmptyObject(obj));\n }\n\n protected isEmptyObject(obj: object) {\n return Object.keys(obj).length === 0;\n }\n\n // OData does not support single quotes in the query. We need to replace all single quotes with double quotes.\n // http://docs.oasis-open.org/odata/odata/v4.01/cs01/part2-url-conventions/odata-v4.01-cs01-part2-url-conventions.html#sec_URLComponents\n private escapeSingleQuote(s: string): string {\n if (typeof s !== 'string') {\n return s;\n }\n return s.replace(/\\'/g, \"''\");\n }\n}\n","export enum MetaChannel {\n HANDSHAKE = '/meta/handshake',\n CONNECT = '/meta/connect',\n SUBSCRIBE = '/meta/subscribe',\n UNSUBSCRIBE = '/meta/unsubscribe'\n}\n","/*\n * Copyright (c) 2008-2020 the original author or authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/* CometD Version 4.0.8 */\n\n(function(root, factory) {\n if (typeof exports === 'object') {\n // CommonJS.\n module.exports = factory();\n } else if (typeof define === 'function' && define.amd) {\n // AMD.\n define([], factory);\n } else {\n // Globals.\n root.org = root.org || {};\n root.org.cometd = factory();\n }\n}(this, function() {\n /**\n * Browsers may throttle the Window scheduler,\n * so we may replace it with a Worker scheduler.\n */\n var Scheduler = function() {\n var _ids = 0;\n var _tasks = {};\n this.register = function(funktion) {\n var id = ++_ids;\n _tasks[id] = funktion;\n return id;\n };\n this.unregister = function(id) {\n var funktion = _tasks[id];\n delete _tasks[id];\n return funktion;\n };\n this.setTimeout = function(funktion, delay) {\n return window.setTimeout(funktion, delay);\n };\n this.clearTimeout = function(id) {\n window.clearTimeout(id);\n };\n };\n\n /**\n * The scheduler code that will run in the Worker.\n * Workers have a built-in `self` variable similar to `window`.\n */\n function WorkerScheduler() {\n var _tasks = {};\n self.onmessage = function(e) {\n var cmd = e.data;\n var id = _tasks[cmd.id];\n switch (cmd.type) {\n case 'setTimeout':\n _tasks[cmd.id] = self.setTimeout(function() {\n delete _tasks[cmd.id];\n self.postMessage({\n id: cmd.id\n });\n }, cmd.delay);\n break;\n case 'clearTimeout':\n delete _tasks[cmd.id];\n if (id) {\n self.clearTimeout(id);\n }\n break;\n default:\n throw 'Unknown command ' + cmd.type;\n }\n };\n }\n\n\n /**\n * Utility functions.\n */\n var Utils = {\n isString: function(value) {\n if (value === undefined || value === null) {\n return false;\n }\n return typeof value === 'string' || value instanceof String;\n },\n isArray: function(value) {\n if (value === undefined || value === null) {\n return false;\n }\n return value instanceof Array;\n },\n /**\n * Returns whether the given element is contained into the given array.\n * @param element the element to check presence for\n * @param array the array to check for the element presence\n * @return the index of the element, if present, or a negative index if the element is not present\n */\n inArray: function(element, array) {\n for (var i = 0; i < array.length; ++i) {\n if (element === array[i]) {\n return i;\n }\n }\n return -1;\n }\n };\n\n\n /**\n * A registry for transports used by the CometD object.\n */\n var TransportRegistry = function() {\n var _types = [];\n var _transports = {};\n\n this.getTransportTypes = function() {\n return _types.slice(0);\n };\n\n this.findTransportTypes = function(version, crossDomain, url) {\n var result = [];\n for (var i = 0; i < _types.length; ++i) {\n var type = _types[i];\n if (_transports[type].accept(version, crossDomain, url) === true) {\n result.push(type);\n }\n }\n return result;\n };\n\n this.negotiateTransport = function(types, version, crossDomain, url) {\n for (var i = 0; i < _types.length; ++i) {\n var type = _types[i];\n for (var j = 0; j < types.length; ++j) {\n if (type === types[j]) {\n var transport = _transports[type];\n if (transport.accept(version, crossDomain, url) === true) {\n return transport;\n }\n }\n }\n }\n return null;\n };\n\n this.add = function(type, transport, index) {\n var existing = false;\n for (var i = 0; i < _types.length; ++i) {\n if (_types[i] === type) {\n existing = true;\n break;\n }\n }\n\n if (!existing) {\n if (typeof index !== 'number') {\n _types.push(type);\n } else {\n _types.splice(index, 0, type);\n }\n _transports[type] = transport;\n }\n\n return !existing;\n };\n\n this.find = function(type) {\n for (var i = 0; i < _types.length; ++i) {\n if (_types[i] === type) {\n return _transports[type];\n }\n }\n return null;\n };\n\n this.remove = function(type) {\n for (var i = 0; i < _types.length; ++i) {\n if (_types[i] === type) {\n _types.splice(i, 1);\n var transport = _transports[type];\n delete _transports[type];\n return transport;\n }\n }\n return null;\n };\n\n this.clear = function() {\n _types = [];\n _transports = {};\n };\n\n this.reset = function(init) {\n for (var i = 0; i < _types.length; ++i) {\n _transports[_types[i]].reset(init);\n }\n };\n };\n\n\n /**\n * Base object with the common functionality for transports.\n */\n var Transport = function() {\n var _type;\n var _cometd;\n var _url;\n\n /**\n * Function invoked just after a transport has been successfully registered.\n * @param type the type of transport (for example 'long-polling')\n * @param cometd the cometd object this transport has been registered to\n * @see #unregistered()\n */\n this.registered = function(type, cometd) {\n _type = type;\n _cometd = cometd;\n };\n\n /**\n * Function invoked just after a transport has been successfully unregistered.\n * @see #registered(type, cometd)\n */\n this.unregistered = function() {\n _type = null;\n _cometd = null;\n };\n\n this._debug = function() {\n _cometd._debug.apply(_cometd, arguments);\n };\n\n this._mixin = function() {\n return _cometd._mixin.apply(_cometd, arguments);\n };\n\n this.getConfiguration = function() {\n return _cometd.getConfiguration();\n };\n\n this.getAdvice = function() {\n return _cometd.getAdvice();\n };\n\n this.setTimeout = function(funktion, delay) {\n return _cometd.setTimeout(funktion, delay);\n };\n\n this.clearTimeout = function(id) {\n _cometd.clearTimeout(id);\n };\n\n /**\n * Converts the given response into an array of bayeux messages\n * @param response the response to convert\n * @return an array of bayeux messages obtained by converting the response\n */\n this.convertToMessages = function(response) {\n if (Utils.isString(response)) {\n try {\n return JSON.parse(response);\n } catch (x) {\n this._debug('Could not convert to JSON the following string', '\"' + response + '\"');\n throw x;\n }\n }\n if (Utils.isArray(response)) {\n return response;\n }\n if (response === undefined || response === null) {\n return [];\n }\n if (response instanceof Object) {\n return [response];\n }\n throw 'Conversion Error ' + response + ', typeof ' + (typeof response);\n };\n\n /**\n * Returns whether this transport can work for the given version and cross domain communication case.\n * @param version a string indicating the transport version\n * @param crossDomain a boolean indicating whether the communication is cross domain\n * @param url the URL to connect to\n * @return true if this transport can work for the given version and cross domain communication case,\n * false otherwise\n */\n this.accept = function(version, crossDomain, url) {\n throw 'Abstract';\n };\n\n /**\n * Returns the type of this transport.\n * @see #registered(type, cometd)\n */\n this.getType = function() {\n return _type;\n };\n\n this.getURL = function() {\n return _url;\n };\n\n this.setURL = function(url) {\n _url = url;\n };\n\n this.send = function(envelope, metaConnect) {\n throw 'Abstract';\n };\n\n this.reset = function(init) {\n this._debug('Transport', _type, 'reset', init ? 'initial' : 'retry');\n };\n\n this.abort = function() {\n this._debug('Transport', _type, 'aborted');\n };\n\n this.toString = function() {\n return this.getType();\n };\n };\n\n Transport.derive = function(baseObject) {\n function F() {\n }\n\n F.prototype = baseObject;\n return new F();\n };\n\n\n /**\n * Base object with the common functionality for transports based on requests.\n * The key responsibility is to allow at most 2 outstanding requests to the server,\n * to avoid that requests are sent behind a long poll.\n * To achieve this, we have one reserved request for the long poll, and all other\n * requests are serialized one after the other.\n */\n var RequestTransport = function() {\n var _super = new Transport();\n var _self = Transport.derive(_super);\n var _requestIds = 0;\n var _metaConnectRequest = null;\n var _requests = [];\n var _envelopes = [];\n\n function _coalesceEnvelopes(envelope) {\n while (_envelopes.length > 0) {\n var envelopeAndRequest = _envelopes[0];\n var newEnvelope = envelopeAndRequest[0];\n var newRequest = envelopeAndRequest[1];\n if (newEnvelope.url === envelope.url &&\n newEnvelope.sync === envelope.sync) {\n _envelopes.shift();\n envelope.messages = envelope.messages.concat(newEnvelope.messages);\n this._debug('Coalesced', newEnvelope.messages.length, 'messages from request', newRequest.id);\n continue;\n }\n break;\n }\n }\n\n function _transportSend(envelope, request) {\n this.transportSend(envelope, request);\n request.expired = false;\n\n if (!envelope.sync) {\n var maxDelay = this.getConfiguration().maxNetworkDelay;\n var delay = maxDelay;\n if (request.metaConnect === true) {\n delay += this.getAdvice().timeout;\n }\n\n this._debug('Transport', this.getType(), 'waiting at most', delay, 'ms for the response, maxNetworkDelay', maxDelay);\n\n var self = this;\n request.timeout = this.setTimeout(function() {\n request.expired = true;\n var errorMessage = 'Request ' + request.id + ' of transport ' + self.getType() + ' exceeded ' + delay + ' ms max network delay';\n var failure = {\n reason: errorMessage\n };\n var xhr = request.xhr;\n failure.httpCode = self.xhrStatus(xhr);\n self.abortXHR(xhr);\n self._debug(errorMessage);\n self.complete(request, false, request.metaConnect);\n envelope.onFailure(xhr, envelope.messages, failure);\n }, delay);\n }\n }\n\n function _queueSend(envelope) {\n var requestId = ++_requestIds;\n var request = {\n id: requestId,\n metaConnect: false,\n envelope: envelope\n };\n\n // Consider the /meta/connect requests which should always be present.\n if (_requests.length < this.getConfiguration().maxConnections - 1) {\n _requests.push(request);\n _transportSend.call(this, envelope, request);\n } else {\n this._debug('Transport', this.getType(), 'queueing request', requestId, 'envelope', envelope);\n _envelopes.push([envelope, request]);\n }\n }\n\n function _metaConnectComplete(request) {\n var requestId = request.id;\n this._debug('Transport', this.getType(), '/meta/connect complete, request', requestId);\n if (_metaConnectRequest !== null && _metaConnectRequest.id !== requestId) {\n throw '/meta/connect request mismatch, completing request ' + requestId;\n }\n _metaConnectRequest = null;\n }\n\n function _complete(request, success) {\n var index = Utils.inArray(request, _requests);\n // The index can be negative if the request has been aborted\n if (index >= 0) {\n _requests.splice(index, 1);\n }\n\n if (_envelopes.length > 0) {\n var envelopeAndRequest = _envelopes.shift();\n var nextEnvelope = envelopeAndRequest[0];\n var nextRequest = envelopeAndRequest[1];\n this._debug('Transport dequeued request', nextRequest.id);\n if (success) {\n if (this.getConfiguration().autoBatch) {\n _coalesceEnvelopes.call(this, nextEnvelope);\n }\n _queueSend.call(this, nextEnvelope);\n this._debug('Transport completed request', request.id, nextEnvelope);\n } else {\n // Keep the semantic of calling response callbacks asynchronously after the request\n var self = this;\n this.setTimeout(function() {\n self.complete(nextRequest, false, nextRequest.metaConnect);\n var failure = {\n reason: 'Previous request failed'\n };\n var xhr = nextRequest.xhr;\n failure.httpCode = self.xhrStatus(xhr);\n nextEnvelope.onFailure(xhr, nextEnvelope.messages, failure);\n }, 0);\n }\n }\n }\n\n _self.complete = function(request, success, metaConnect) {\n if (metaConnect) {\n _metaConnectComplete.call(this, request);\n } else {\n _complete.call(this, request, success);\n }\n };\n\n /**\n * Performs the actual send depending on the transport type details.\n * @param envelope the envelope to send\n * @param request the request information\n */\n _self.transportSend = function(envelope, request) {\n throw 'Abstract';\n };\n\n _self.transportSuccess = function(envelope, request, responses) {\n if (!request.expired) {\n this.clearTimeout(request.timeout);\n this.complete(request, true, request.metaConnect);\n if (responses && responses.length > 0) {\n envelope.onSuccess(responses);\n } else {\n envelope.onFailure(request.xhr, envelope.messages, {\n httpCode: 204\n });\n }\n }\n };\n\n _self.transportFailure = function(envelope, request, failure) {\n if (!request.expired) {\n this.clearTimeout(request.timeout);\n this.complete(request, false, request.metaConnect);\n envelope.onFailure(request.xhr, envelope.messages, failure);\n }\n };\n\n function _metaConnectSend(envelope) {\n if (_metaConnectRequest !== null) {\n throw 'Concurrent /meta/connect requests not allowed, request id=' + _metaConnectRequest.id + ' not yet completed';\n }\n\n var requestId = ++_requestIds;\n this._debug('Transport', this.getType(), '/meta/connect send, request', requestId, 'envelope', envelope);\n var request = {\n id: requestId,\n metaConnect: true,\n envelope: envelope\n };\n _transportSend.call(this, envelope, request);\n _metaConnectRequest = request;\n }\n\n _self.send = function(envelope, metaConnect) {\n if (metaConnect) {\n _metaConnectSend.call(this, envelope);\n } else {\n _queueSend.call(this, envelope);\n }\n };\n\n _self.abort = function() {\n _super.abort();\n for (var i = 0; i < _requests.length; ++i) {\n var request = _requests[i];\n if (request) {\n this._debug('Aborting request', request);\n if (!this.abortXHR(request.xhr)) {\n this.transportFailure(request.envelope, request, {reason: 'abort'});\n }\n }\n }\n var metaConnectRequest = _metaConnectRequest;\n if (metaConnectRequest) {\n this._debug('Aborting /meta/connect request', metaConnectRequest);\n if (!this.abortXHR(metaConnectRequest.xhr)) {\n this.transportFailure(metaConnectRequest.envelope, metaConnectRequest, {reason: 'abort'});\n }\n }\n this.reset(true);\n };\n\n _self.reset = function(init) {\n _super.reset(init);\n _metaConnectRequest = null;\n _requests = [];\n _envelopes = [];\n };\n\n _self.abortXHR = function(xhr) {\n if (xhr) {\n try {\n var state = xhr.readyState;\n xhr.abort();\n return state !== window.XMLHttpRequest.UNSENT;\n } catch (x) {\n this._debug(x);\n }\n }\n return false;\n };\n\n _self.xhrStatus = function(xhr) {\n if (xhr) {\n try {\n return xhr.status;\n } catch (x) {\n this._debug(x);\n }\n }\n return -1;\n };\n\n return _self;\n };\n\n\n var LongPollingTransport = function() {\n var _super = new RequestTransport();\n var _self = Transport.derive(_super);\n // By default, support cross domain\n var _supportsCrossDomain = true;\n\n _self.accept = function(version, crossDomain, url) {\n return _supportsCrossDomain || !crossDomain;\n };\n\n _self.newXMLHttpRequest = function() {\n return new window.XMLHttpRequest();\n };\n\n function _copyContext(xhr) {\n try {\n // Copy external context, to be used in other environments.\n xhr.context = _self.context;\n } catch (e) {\n // May happen if XHR is wrapped by Object.seal(),\n // Object.freeze(), or Object.preventExtensions().\n this._debug('Could not copy transport context into XHR', e);\n }\n }\n\n _self.xhrSend = function(packet) {\n var xhr = _self.newXMLHttpRequest();\n _copyContext(xhr);\n xhr.withCredentials = true;\n xhr.open('POST', packet.url, packet.sync !== true);\n var headers = packet.headers;\n if (headers) {\n for (var headerName in headers) {\n if (headers.hasOwnProperty(headerName)) {\n xhr.setRequestHeader(headerName, headers[headerName]);\n }\n }\n }\n xhr.setRequestHeader('Content-Type', 'application/json;charset=UTF-8');\n xhr.onload = function() {\n if (xhr.status === 200) {\n packet.onSuccess(xhr.responseText);\n } else {\n packet.onError(xhr.statusText);\n }\n };\n xhr.onabort = xhr.onerror = function() {\n packet.onError(xhr.statusText);\n };\n xhr.send(packet.body);\n return xhr;\n };\n\n _self.transportSend = function(envelope, request) {\n this._debug('Transport', this.getType(), 'sending request', request.id, 'envelope', envelope);\n\n var self = this;\n try {\n var sameStack = true;\n request.xhr = this.xhrSend({\n transport: this,\n url: envelope.url,\n sync: envelope.sync,\n headers: this.getConfiguration().requestHeaders,\n body: JSON.stringify(envelope.messages),\n onSuccess: function(response) {\n self._debug('Transport', self.getType(), 'received response', response);\n var success = false;\n try {\n var received = self.convertToMessages(response);\n if (received.length === 0) {\n _supportsCrossDomain = false;\n self.transportFailure(envelope, request, {\n httpCode: 204\n });\n } else {\n success = true;\n self.transportSuccess(envelope, request, received);\n }\n } catch (x) {\n self._debug(x);\n if (!success) {\n _supportsCrossDomain = false;\n var failure = {\n exception: x\n };\n failure.httpCode = self.xhrStatus(request.xhr);\n self.transportFailure(envelope, request, failure);\n }\n }\n },\n onError: function(reason, exception) {\n self._debug('Transport', self.getType(), 'received error', reason, exception);\n _supportsCrossDomain = false;\n var failure = {\n reason: reason,\n exception: exception\n };\n failure.httpCode = self.xhrStatus(request.xhr);\n if (sameStack) {\n // Keep the semantic of calling response callbacks asynchronously after the request\n self.setTimeout(function() {\n self.transportFailure(envelope, request, failure);\n }, 0);\n } else {\n self.transportFailure(envelope, request, failure);\n }\n }\n });\n sameStack = false;\n } catch (x) {\n _supportsCrossDomain = false;\n // Keep the semantic of calling response callbacks asynchronously after the request\n this.setTimeout(function() {\n self.transportFailure(envelope, request, {\n exception: x\n });\n }, 0);\n }\n };\n\n _self.reset = function(init) {\n _super.reset(init);\n _supportsCrossDomain = true;\n };\n\n return _self;\n };\n\n\n var CallbackPollingTransport = function() {\n var _super = new RequestTransport();\n var _self = Transport.derive(_super);\n var jsonp = 0;\n\n _self.accept = function(version, crossDomain, url) {\n return true;\n };\n\n _self.jsonpSend = function(packet) {\n var head = document.getElementsByTagName('head')[0];\n var script = document.createElement('script');\n\n var callbackName = '_cometd_jsonp_' + jsonp++;\n window[callbackName] = function(responseText) {\n head.removeChild(script);\n delete window[callbackName];\n packet.onSuccess(responseText);\n };\n\n var url = packet.url;\n url += url.indexOf('?') < 0 ? '?' : '&';\n url += 'jsonp=' + callbackName;\n url += '&message=' + encodeURIComponent(packet.body);\n script.src = url;\n script.async = packet.sync !== true;\n script.type = 'application/javascript';\n script.onerror = function(e) {\n packet.onError('jsonp ' + e.type);\n };\n head.appendChild(script);\n };\n\n function _failTransportFn(envelope, request, x) {\n var self = this;\n return function() {\n self.transportFailure(envelope, request, 'error', x);\n };\n }\n\n _self.transportSend = function(envelope, request) {\n var self = this;\n\n // Microsoft Internet Explorer has a 2083 URL max length\n // We must ensure that we stay within that length\n var start = 0;\n var length = envelope.messages.length;\n var lengths = [];\n while (length > 0) {\n // Encode the messages because all brackets, quotes, commas, colons, etc\n // present in the JSON will be URL encoded, taking many more characters\n var json = JSON.stringify(envelope.messages.slice(start, start + length));\n var urlLength = envelope.url.length + encodeURI(json).length;\n\n var maxLength = this.getConfiguration().maxURILength;\n if (urlLength > maxLength) {\n if (length === 1) {\n var x = 'Bayeux message too big (' + urlLength + ' bytes, max is ' + maxLength + ') ' +\n 'for transport ' + this.getType();\n // Keep the semantic of calling response callbacks asynchronously after the request\n this.setTimeout(_failTransportFn.call(this, envelope, request, x), 0);\n return;\n }\n\n --length;\n continue;\n }\n\n lengths.push(length);\n start += length;\n length = envelope.messages.length - start;\n }\n\n // Here we are sure that the messages can be sent within the URL limit\n\n var envelopeToSend = envelope;\n if (lengths.length > 1) {\n var begin = 0;\n var end = lengths[0];\n this._debug('Transport', this.getType(), 'split', envelope.messages.length, 'messages into', lengths.join(' + '));\n envelopeToSend = this._mixin(false, {}, envelope);\n envelopeToSend.messages = envelope.messages.slice(begin, end);\n envelopeToSend.onSuccess = envelope.onSuccess;\n envelopeToSend.onFailure = envelope.onFailure;\n\n for (var i = 1; i < lengths.length; ++i) {\n var nextEnvelope = this._mixin(false, {}, envelope);\n begin = end;\n end += lengths[i];\n nextEnvelope.messages = envelope.messages.slice(begin, end);\n nextEnvelope.onSuccess = envelope.onSuccess;\n nextEnvelope.onFailure = envelope.onFailure;\n this.send(nextEnvelope, request.metaConnect);\n }\n }\n\n this._debug('Transport', this.getType(), 'sending request', request.id, 'envelope', envelopeToSend);\n\n try {\n var sameStack = true;\n this.jsonpSend({\n transport: this,\n url: envelopeToSend.url,\n sync: envelopeToSend.sync,\n headers: this.getConfiguration().requestHeaders,\n body: JSON.stringify(envelopeToSend.messages),\n onSuccess: function(responses) {\n var success = false;\n try {\n var received = self.convertToMessages(responses);\n if (received.length === 0) {\n self.transportFailure(envelopeToSend, request, {\n httpCode: 204\n });\n } else {\n success = true;\n self.transportSuccess(envelopeToSend, request, received);\n }\n } catch (x) {\n self._debug(x);\n if (!success) {\n self.transportFailure(envelopeToSend, request, {\n exception: x\n });\n }\n }\n },\n onError: function(reason, exception) {\n var failure = {\n reason: reason,\n exception: exception\n };\n if (sameStack) {\n // Keep the semantic of calling response callbacks asynchronously after the request\n self.setTimeout(function() {\n self.transportFailure(envelopeToSend, request, failure);\n }, 0);\n } else {\n self.transportFailure(envelopeToSend, request, failure);\n }\n }\n });\n sameStack = false;\n } catch (xx) {\n // Keep the semantic of calling response callbacks asynchronously after the request\n this.setTimeout(function() {\n self.transportFailure(envelopeToSend, request, {\n exception: xx\n });\n }, 0);\n }\n };\n\n return _self;\n };\n\n\n var WebSocketTransport = function() {\n var _super = new Transport();\n var _self = Transport.derive(_super);\n var _cometd;\n // By default WebSocket is supported\n var _webSocketSupported = true;\n // Whether we were able to establish a WebSocket connection\n var _webSocketConnected = false;\n var _stickyReconnect = true;\n // The context contains the envelopes that have been sent\n // and the timeouts for the messages that have been sent.\n var _context = null;\n var _connecting = null;\n var _connected = false;\n var _successCallback = null;\n\n _self.reset = function(init) {\n _super.reset(init);\n _webSocketSupported = true;\n if (init) {\n _webSocketConnected = false;\n }\n _stickyReconnect = true;\n _context = null;\n _connecting = null;\n _connected = false;\n };\n\n function _forceClose(context, event) {\n if (context) {\n this.webSocketClose(context, event.code, event.reason);\n // Force immediate failure of pending messages to trigger reconnect.\n // This is needed because the server may not reply to our close()\n // and therefore the onclose function is never called.\n this.onClose(context, event);\n }\n }\n\n function _sameContext(context) {\n return context === _connecting || context === _context;\n }\n\n function _storeEnvelope(context, envelope, metaConnect) {\n var messageIds = [];\n for (var i = 0; i < envelope.messages.length; ++i) {\n var message = envelope.messages[i];\n if (message.id) {\n messageIds.push(message.id);\n }\n }\n context.envelopes[messageIds.join(',')] = [envelope, metaConnect];\n this._debug('Transport', this.getType(), 'stored envelope, envelopes', context.envelopes);\n }\n\n function _websocketConnect(context) {\n // We may have multiple attempts to open a WebSocket\n // connection, for example a /meta/connect request that\n // may take time, along with a user-triggered publish.\n // Early return if we are already connecting.\n if (_connecting) {\n return;\n }\n\n // Mangle the URL, changing the scheme from 'http' to 'ws'.\n var url = _cometd.getURL().replace(/^http/, 'ws');\n this._debug('Transport', this.getType(), 'connecting to URL', url);\n\n try {\n var protocol = _cometd.getConfiguration().protocol;\n context.webSocket = protocol ? new window.WebSocket(url, protocol) : new window.WebSocket(url);\n _connecting = context;\n } catch (x) {\n _webSocketSupported = false;\n this._debug('Exception while creating WebSocket object', x);\n throw x;\n }\n\n // By default use sticky reconnects.\n _stickyReconnect = _cometd.getConfiguration().stickyReconnect !== false;\n\n var self = this;\n var connectTimeout = _cometd.getConfiguration().connectTimeout;\n if (connectTimeout > 0) {\n context.connectTimer = this.setTimeout(function() {\n _cometd._debug('Transport', self.getType(), 'timed out while connecting to URL', url, ':', connectTimeout, 'ms');\n // The connection was not opened, close anyway.\n _forceClose.call(self, context, {code: 1000, reason: 'Connect Timeout'});\n }, connectTimeout);\n }\n\n var onopen = function() {\n _cometd._debug('WebSocket onopen', context);\n if (context.connectTimer) {\n self.clearTimeout(context.connectTimer);\n }\n\n if (_sameContext(context)) {\n _connecting = null;\n _context = context;\n _webSocketConnected = true;\n self.onOpen(context);\n } else {\n // We have a valid connection already, close this one.\n _cometd._warn('Closing extra WebSocket connection', this, 'active connection', _context);\n _forceClose.call(self, context, {code: 1000, reason: 'Extra Connection'});\n }\n };\n\n // This callback is invoked when the server sends the close frame.\n // The close frame for a connection may arrive *after* another\n // connection has been opened, so we must make sure that actions\n // are performed only if it's the same connection.\n var onclose = function(event) {\n event = event || {code: 1000};\n _cometd._debug('WebSocket onclose', context, event, 'connecting', _connecting, 'current', _context);\n\n if (context.connectTimer) {\n self.clearTimeout(context.connectTimer);\n }\n\n self.onClose(context, event);\n };\n\n var onmessage = function(wsMessage) {\n _cometd._debug('WebSocket onmessage', wsMessage, context);\n self.onMessage(context, wsMessage);\n };\n\n context.webSocket.onopen = onopen;\n context.webSocket.onclose = onclose;\n context.webSocket.onerror = function() {\n // Clients should call onclose(), but if they do not we do it here for safety.\n onclose({code: 1000, reason: 'Error'});\n };\n context.webSocket.onmessage = onmessage;\n\n this._debug('Transport', this.getType(), 'configured callbacks on', context);\n }\n\n function _webSocketSend(context, envelope, metaConnect) {\n var json = JSON.stringify(envelope.messages);\n context.webSocket.send(json);\n this._debug('Transport', this.getType(), 'sent', envelope, '/meta/connect =', metaConnect);\n\n // Manage the timeout waiting for the response.\n var maxDelay = this.getConfiguration().maxNetworkDelay;\n var delay = maxDelay;\n if (metaConnect) {\n delay += this.getAdvice().timeout;\n _connected = true;\n }\n\n var self = this;\n var messageIds = [];\n for (var i = 0; i < envelope.messages.length; ++i) {\n (function() {\n var message = envelope.messages[i];\n if (message.id) {\n messageIds.push(message.id);\n context.timeouts[message.id] = self.setTimeout(function() {\n _cometd._debug('Transport', self.getType(), 'timing out message', message.id, 'after', delay, 'on', context);\n _forceClose.call(self, context, {code: 1000, reason: 'Message Timeout'});\n }, delay);\n }\n })();\n }\n\n this._debug('Transport', this.getType(), 'waiting at most', delay, 'ms for messages', messageIds, 'maxNetworkDelay', maxDelay, ', timeouts:', context.timeouts);\n }\n\n _self._notifySuccess = function(fn, messages) {\n fn.call(this, messages);\n };\n\n _self._notifyFailure = function(fn, context, messages, failure) {\n fn.call(this, context, messages, failure);\n };\n\n function _send(context, envelope, metaConnect) {\n try {\n if (context === null) {\n context = _connecting || {\n envelopes: {},\n timeouts: {}\n };\n _storeEnvelope.call(this, context, envelope, metaConnect);\n _websocketConnect.call(this, context);\n } else {\n _storeEnvelope.call(this, context, envelope, metaConnect);\n _webSocketSend.call(this, context, envelope, metaConnect);\n }\n } catch (x) {\n // Keep the semantic of calling response callbacks asynchronously after the request.\n var self = this;\n this.setTimeout(function() {\n _forceClose.call(self, context, {\n code: 1000,\n reason: 'Exception',\n exception: x\n });\n }, 0);\n }\n }\n\n _self.onOpen = function(context) {\n var envelopes = context.envelopes;\n this._debug('Transport', this.getType(), 'opened', context, 'pending messages', envelopes);\n for (var key in envelopes) {\n if (envelopes.hasOwnProperty(key)) {\n var element = envelopes[key];\n var envelope = element[0];\n var metaConnect = element[1];\n // Store the success callback, which is independent from the envelope,\n // so that it can be used to notify arrival of messages.\n _successCallback = envelope.onSuccess;\n _webSocketSend.call(this, context, envelope, metaConnect);\n }\n }\n };\n\n _self.onMessage = function(context, wsMessage) {\n this._debug('Transport', this.getType(), 'received websocket message', wsMessage, context);\n\n var close = false;\n var messages = this.convertToMessages(wsMessage.data);\n var messageIds = [];\n for (var i = 0; i < messages.length; ++i) {\n var message = messages[i];\n\n // Detect if the message is a response to a request we made.\n // If it's a meta message, for sure it's a response; otherwise it's\n // a publish message and publish responses don't have the data field.\n if (/^\\/meta\\//.test(message.channel) || message.data === undefined) {\n if (message.id) {\n messageIds.push(message.id);\n\n var timeout = context.timeouts[message.id];\n if (timeout) {\n this.clearTimeout(timeout);\n delete context.timeouts[message.id];\n this._debug('Transport', this.getType(), 'removed timeout for message', message.id, ', timeouts', context.timeouts);\n }\n }\n }\n\n if ('/meta/connect' === message.channel) {\n _connected = false;\n }\n if ('/meta/disconnect' === message.channel && !_connected) {\n close = true;\n }\n }\n\n // Remove the envelope corresponding to the messages.\n var removed = false;\n var envelopes = context.envelopes;\n for (var j = 0; j < messageIds.length; ++j) {\n var id = messageIds[j];\n for (var key in envelopes) {\n if (envelopes.hasOwnProperty(key)) {\n var ids = key.split(',');\n var index = Utils.inArray(id, ids);\n if (index >= 0) {\n removed = true;\n ids.splice(index, 1);\n var envelope = envelopes[key][0];\n var metaConnect = envelopes[key][1];\n delete envelopes[key];\n if (ids.length > 0) {\n envelopes[ids.join(',')] = [envelope, metaConnect];\n }\n break;\n }\n }\n }\n }\n if (removed) {\n this._debug('Transport', this.getType(), 'removed envelope, envelopes', envelopes);\n }\n\n this._notifySuccess(_successCallback, messages);\n\n if (close) {\n this.webSocketClose(context, 1000, 'Disconnect');\n }\n };\n\n _self.onClose = function(context, event) {\n this._debug('Transport', this.getType(), 'closed', context, event);\n\n if (_sameContext(context)) {\n // Remember if we were able to connect.\n // This close event could be due to server shutdown,\n // and if it restarts we want to try websocket again.\n _webSocketSupported = _stickyReconnect && _webSocketConnected;\n _connecting = null;\n _context = null;\n }\n\n var timeouts = context.timeouts;\n context.timeouts = {};\n for (var id in timeouts) {\n if (timeouts.hasOwnProperty(id)) {\n this.clearTimeout(timeouts[id]);\n }\n }\n\n var envelopes = context.envelopes;\n context.envelopes = {};\n for (var key in envelopes) {\n if (envelopes.hasOwnProperty(key)) {\n var envelope = envelopes[key][0];\n var metaConnect = envelopes[key][1];\n if (metaConnect) {\n _connected = false;\n }\n var failure = {\n websocketCode: event.code,\n reason: event.reason\n };\n if (event.exception) {\n failure.exception = event.exception;\n }\n this._notifyFailure(envelope.onFailure, context, envelope.messages, failure);\n }\n }\n };\n\n _self.registered = function(type, cometd) {\n _super.registered(type, cometd);\n _cometd = cometd;\n };\n\n _self.accept = function(version, crossDomain, url) {\n this._debug('Transport', this.getType(), 'accept, supported:', _webSocketSupported);\n // Using !! to return a boolean (and not the WebSocket object).\n return _webSocketSupported && !!window.WebSocket && _cometd.websocketEnabled !== false;\n };\n\n _self.send = function(envelope, metaConnect) {\n this._debug('Transport', this.getType(), 'sending', envelope, '/meta/connect =', metaConnect);\n _send.call(this, _context, envelope, metaConnect);\n };\n\n _self.webSocketClose = function(context, code, reason) {\n try {\n if (context.webSocket) {\n context.webSocket.close(code, reason);\n }\n } catch (x) {\n this._debug(x);\n }\n };\n\n _self.abort = function() {\n _super.abort();\n _forceClose.call(this, _context, {code: 1000, reason: 'Abort'});\n this.reset(true);\n };\n\n return _self;\n };\n\n\n /**\n * The constructor for a CometD object, identified by an optional name.\n * The default name is the string 'default'.\n * @param name the optional name of this cometd object\n */\n var CometD = function(name) {\n var _scheduler = new Scheduler();\n var _cometd = this;\n var _name = name || 'default';\n var _crossDomain = false;\n var _transports = new TransportRegistry();\n var _transport;\n var _status = 'disconnected';\n var _messageId = 0;\n var _clientId = null;\n var _batch = 0;\n var _messageQueue = [];\n var _internalBatch = false;\n var _listenerId = 0;\n var _listeners = {};\n var _backoff = 0;\n var _scheduledSend = null;\n var _extensions = [];\n var _advice = {};\n var _handshakeProps;\n var _handshakeCallback;\n var _callbacks = {};\n var _remoteCalls = {};\n var _reestablish = false;\n var _connected = false;\n var _unconnectTime = 0;\n var _handshakeMessages = 0;\n var _metaConnect = null;\n var _config = {\n useWorkerScheduler: true,\n protocol: null,\n stickyReconnect: true,\n connectTimeout: 0,\n maxConnections: 2,\n backoffIncrement: 1000,\n maxBackoff: 60000,\n logLevel: 'info',\n maxNetworkDelay: 10000,\n requestHeaders: {},\n appendMessageTypeToURL: true,\n autoBatch: false,\n urls: {},\n maxURILength: 2000,\n advice: {\n timeout: 60000,\n interval: 0,\n reconnect: undefined,\n maxInterval: 0\n }\n };\n\n function _fieldValue(object, name) {\n try {\n return object[name];\n } catch (x) {\n return undefined;\n }\n }\n\n /**\n * Mixes in the given objects into the target object by copying the properties.\n * @param deep if the copy must be deep\n * @param target the target object\n * @param objects the objects whose properties are copied into the target\n */\n this._mixin = function(deep, target, objects) {\n var result = target || {};\n\n // Skip first 2 parameters (deep and target), and loop over the others\n for (var i = 2; i < arguments.length; ++i) {\n var object = arguments[i];\n\n if (object === undefined || object === null) {\n continue;\n }\n\n for (var propName in object) {\n if (object.hasOwnProperty(propName)) {\n var prop = _fieldValue(object, propName);\n var targ = _fieldValue(result, propName);\n\n // Avoid infinite loops\n if (prop === target) {\n continue;\n }\n // Do not mixin undefined values\n if (prop === undefined) {\n continue;\n }\n\n if (deep && typeof prop === 'object' && prop !== null) {\n if (prop instanceof Array) {\n result[propName] = this._mixin(deep, targ instanceof Array ? targ : [], prop);\n } else {\n var source = typeof targ === 'object' && !(targ instanceof Array) ? targ : {};\n result[propName] = this._mixin(deep, source, prop);\n }\n } else {\n result[propName] = prop;\n }\n }\n }\n }\n\n return result;\n };\n\n function _isString(value) {\n return Utils.isString(value);\n }\n\n function _isFunction(value) {\n if (value === undefined || value === null) {\n return false;\n }\n return typeof value === 'function';\n }\n\n function _zeroPad(value, length) {\n var result = '';\n while (--length > 0) {\n if (value >= Math.pow(10, length)) {\n break;\n }\n result += '0';\n }\n result += value;\n return result;\n }\n\n function _log(level, args) {\n if (window.console) {\n var logger = window.console[level];\n if (_isFunction(logger)) {\n var now = new Date();\n [].splice.call(args, 0, 0, _zeroPad(now.getHours(), 2) + ':' + _zeroPad(now.getMinutes(), 2) + ':' +\n _zeroPad(now.getSeconds(), 2) + '.' + _zeroPad(now.getMilliseconds(), 3));\n logger.apply(window.console, args);\n }\n }\n }\n\n this._warn = function() {\n _log('warn', arguments);\n };\n\n this._info = function() {\n if (_config.logLevel !== 'warn') {\n _log('info', arguments);\n }\n };\n\n this._debug = function() {\n if (_config.logLevel === 'debug') {\n _log('debug', arguments);\n }\n };\n\n function _splitURL(url) {\n // [1] = protocol://,\n // [2] = host:port,\n // [3] = host,\n // [4] = IPv6_host,\n // [5] = IPv4_host,\n // [6] = :port,\n // [7] = port,\n // [8] = uri,\n // [9] = rest (query / fragment)\n return new RegExp('(^https?://)?(((\\\\[[^\\\\]]+])|([^:/?#]+))(:(\\\\d+))?)?([^?#]*)(.*)?').exec(url);\n }\n\n /**\n * Returns whether the given hostAndPort is cross domain.\n * The default implementation checks against window.location.host\n * but this function can be overridden to make it work in non-browser\n * environments.\n *\n * @param hostAndPort the host and port in format host:port\n * @return whether the given hostAndPort is cross domain\n */\n this._isCrossDomain = function(hostAndPort) {\n if (window.location && window.location.host) {\n if (hostAndPort) {\n return hostAndPort !== window.location.host;\n }\n }\n return false;\n };\n\n function _configure(configuration) {\n _cometd._debug('Configuring cometd object with', configuration);\n // Support old style param, where only the Bayeux server URL was passed.\n if (_isString(configuration)) {\n configuration = {\n url: configuration\n };\n }\n if (!configuration) {\n configuration = {};\n }\n\n _config = _cometd._mixin(false, _config, configuration);\n\n var url = _cometd.getURL();\n if (!url) {\n throw 'Missing required configuration parameter \\'url\\' specifying the Bayeux server URL';\n }\n\n // Check if we're cross domain.\n var urlParts = _splitURL(url);\n var hostAndPort = urlParts[2];\n var uri = urlParts[8];\n var afterURI = urlParts[9];\n _crossDomain = _cometd._isCrossDomain(hostAndPort);\n\n // Check if appending extra path is supported.\n if (_config.appendMessageTypeToURL) {\n if (afterURI !== undefined && afterURI.length > 0) {\n _cometd._info('Appending message type to URI ' + uri + afterURI + ' is not supported, disabling \\'appendMessageTypeToURL\\' configuration');\n _config.appendMessageTypeToURL = false;\n } else {\n var uriSegments = uri.split('/');\n var lastSegmentIndex = uriSegments.length - 1;\n if (uri.match(/\\/$/)) {\n lastSegmentIndex -= 1;\n }\n if (uriSegments[lastSegmentIndex].indexOf('.') >= 0) {\n // Very likely the CometD servlet's URL pattern is mapped to an extension, such as *.cometd\n // It will be difficult to add the extra path in this case\n _cometd._info('Appending message type to URI ' + uri + ' is not supported, disabling \\'appendMessageTypeToURL\\' configuration');\n _config.appendMessageTypeToURL = false;\n }\n }\n }\n\n if (window.Worker && window.Blob && window.URL && _config.useWorkerScheduler) {\n var code = WorkerScheduler.toString();\n // Remove the function declaration, the opening brace and the closing brace.\n code = code.substring(code.indexOf('{') + 1, code.lastIndexOf('}'));\n var blob = new window.Blob([code], {\n type: 'application/json'\n });\n var blobURL = window.URL.createObjectURL(blob);\n var worker = new window.Worker(blobURL);\n _scheduler.setTimeout = function(funktion, delay) {\n var id = _scheduler.register(funktion);\n worker.postMessage({\n id: id,\n type: 'setTimeout',\n delay: delay\n });\n return id;\n };\n _scheduler.clearTimeout = function(id) {\n _scheduler.unregister(id);\n worker.postMessage({\n id: id,\n type: 'clearTimeout'\n });\n };\n worker.onmessage = function(e) {\n var id = e.data.id;\n var funktion = _scheduler.unregister(id);\n if (funktion) {\n funktion();\n }\n };\n }\n }\n\n function _removeListener(subscription) {\n if (subscription) {\n var subscriptions = _listeners[subscription.channel];\n if (subscriptions && subscriptions[subscription.id]) {\n delete subscriptions[subscription.id];\n _cometd._debug('Removed', subscription.listener ? 'listener' : 'subscription', subscription);\n }\n }\n }\n\n function _removeSubscription(subscription) {\n if (subscription && !subscription.listener) {\n _removeListener(subscription);\n }\n }\n\n function _clearSubscriptions() {\n for (var channel in _listeners) {\n if (_listeners.hasOwnProperty(channel)) {\n var subscriptions = _listeners[channel];\n if (subscriptions) {\n for (var id in subscriptions) {\n if (subscriptions.hasOwnProperty(id)) {\n _removeSubscription(subscriptions[id]);\n }\n }\n }\n }\n }\n }\n\n function _setStatus(newStatus) {\n if (_status !== newStatus) {\n _cometd._debug('Status', _status, '->', newStatus);\n _status = newStatus;\n }\n }\n\n function _isDisconnected() {\n return _status === 'disconnecting' || _status === 'disconnected';\n }\n\n function _nextMessageId() {\n var result = ++_messageId;\n return '' + result;\n }\n\n function _applyExtension(scope, callback, name, message, outgoing) {\n try {\n return callback.call(scope, message);\n } catch (x) {\n var handler = _cometd.onExtensionException;\n if (_isFunction(handler)) {\n _cometd._debug('Invoking extension exception handler', name, x);\n try {\n handler.call(_cometd, x, name, outgoing, message);\n } catch (xx) {\n _cometd._info('Exception during execution of extension exception handler', name, xx);\n }\n } else {\n _cometd._info('Exception during execution of extension', name, x);\n }\n return message;\n }\n }\n\n function _applyIncomingExtensions(message) {\n for (var i = 0; i < _extensions.length; ++i) {\n if (message === undefined || message === null) {\n break;\n }\n\n var extension = _extensions[i];\n var callback = extension.extension.incoming;\n if (_isFunction(callback)) {\n var result = _applyExtension(extension.extension, callback, extension.name, message, false);\n message = result === undefined ? message : result;\n }\n }\n return message;\n }\n\n function _applyOutgoingExtensions(message) {\n for (var i = _extensions.length - 1; i >= 0; --i) {\n if (message === undefined || message === null) {\n break;\n }\n\n var extension = _extensions[i];\n var callback = extension.extension.outgoing;\n if (_isFunction(callback)) {\n var result = _applyExtension(extension.extension, callback, extension.name, message, true);\n message = result === undefined ? message : result;\n }\n }\n return message;\n }\n\n function _notify(channel, message) {\n var subscriptions = _listeners[channel];\n if (subscriptions) {\n for (var id in subscriptions) {\n if (subscriptions.hasOwnProperty(id)) {\n var subscription = subscriptions[id];\n // Subscriptions may come and go, so the array may have 'holes'\n if (subscription) {\n try {\n subscription.callback.call(subscription.scope, message);\n } catch (x) {\n var handler = _cometd.onListenerException;\n if (_isFunction(handler)) {\n _cometd._debug('Invoking listener exception handler', subscription, x);\n try {\n handler.call(_cometd, x, subscription, subscription.listener, message);\n } catch (xx) {\n _cometd._info('Exception during execution of listener exception handler', subscription, xx);\n }\n } else {\n _cometd._info('Exception during execution of listener', subscription, message, x);\n }\n }\n }\n }\n }\n }\n }\n\n function _notifyListeners(channel, message) {\n // Notify direct listeners\n _notify(channel, message);\n\n // Notify the globbing listeners\n var channelParts = channel.split('/');\n var last = channelParts.length - 1;\n for (var i = last; i > 0; --i) {\n var channelPart = channelParts.slice(0, i).join('/') + '/*';\n // We don't want to notify /foo/* if the channel is /foo/bar/baz,\n // so we stop at the first non recursive globbing\n if (i === last) {\n _notify(channelPart, message);\n }\n // Add the recursive globber and notify\n channelPart += '*';\n _notify(channelPart, message);\n }\n }\n\n function _cancelDelayedSend() {\n if (_scheduledSend !== null) {\n _cometd.clearTimeout(_scheduledSend);\n }\n _scheduledSend = null;\n }\n\n function _delayedSend(operation, delay) {\n _cancelDelayedSend();\n var time = _advice.interval + delay;\n _cometd._debug('Function scheduled in', time, 'ms, interval =', _advice.interval, 'backoff =', _backoff, operation);\n _scheduledSend = _cometd.setTimeout(operation, time);\n }\n\n // Needed to break cyclic dependencies between function definitions\n var _handleMessages;\n var _handleFailure;\n\n /**\n * Delivers the messages to the CometD server\n * @param messages the array of messages to send\n * @param metaConnect true if this send is on /meta/connect\n * @param extraPath an extra path to append to the Bayeux server URL\n */\n function _send(messages, metaConnect, extraPath) {\n // We must be sure that the messages have a clientId.\n // This is not guaranteed since the handshake may take time to return\n // (and hence the clientId is not known yet) and the application\n // may create other messages.\n for (var i = 0; i < messages.length; ++i) {\n var message = messages[i];\n var messageId = message.id;\n\n if (_clientId) {\n message.clientId = _clientId;\n }\n\n message = _applyOutgoingExtensions(message);\n if (message !== undefined && message !== null) {\n // Extensions may have modified the message id, but we need to own it.\n message.id = messageId;\n messages[i] = message;\n } else {\n delete _callbacks[messageId];\n messages.splice(i--, 1);\n }\n }\n\n if (messages.length === 0) {\n return;\n }\n\n if (metaConnect) {\n _metaConnect = messages[0];\n }\n\n var url = _cometd.getURL();\n if (_config.appendMessageTypeToURL) {\n // If url does not end with '/', then append it\n if (!url.match(/\\/$/)) {\n url = url + '/';\n }\n if (extraPath) {\n url = url + extraPath;\n }\n }\n\n var envelope = {\n url: url,\n sync: false,\n messages: messages,\n onSuccess: function(rcvdMessages) {\n try {\n _handleMessages.call(_cometd, rcvdMessages);\n } catch (x) {\n _cometd._info('Exception during handling of messages', x);\n }\n },\n onFailure: function(conduit, messages, failure) {\n try {\n var transport = _cometd.getTransport();\n failure.connectionType = transport ? transport.getType() : \"unknown\";\n _handleFailure.call(_cometd, conduit, messages, failure);\n } catch (x) {\n _cometd._info('Exception during handling of failure', x);\n }\n }\n };\n _cometd._debug('Send', envelope);\n _transport.send(envelope, metaConnect);\n }\n\n function _queueSend(message) {\n if (_batch > 0 || _internalBatch === true) {\n _messageQueue.push(message);\n } else {\n _send([message], false);\n }\n }\n\n /**\n * Sends a complete bayeux message.\n * This method is exposed as a public so that extensions may use it\n * to send bayeux message directly, for example in case of re-sending\n * messages that have already been sent but that for some reason must\n * be resent.\n */\n this.send = _queueSend;\n\n function _resetBackoff() {\n _backoff = 0;\n }\n\n function _increaseBackoff() {\n if (_backoff < _config.maxBackoff) {\n _backoff += _config.backoffIncrement;\n }\n return _backoff;\n }\n\n /**\n * Starts a the batch of messages to be sent in a single request.\n * @see #_endBatch(sendMessages)\n */\n function _startBatch() {\n ++_batch;\n _cometd._debug('Starting batch, depth', _batch);\n }\n\n function _flushBatch() {\n var messages = _messageQueue;\n _messageQueue = [];\n if (messages.length > 0) {\n _send(messages, false);\n }\n }\n\n /**\n * Ends the batch of messages to be sent in a single request,\n * optionally sending messages present in the message queue depending\n * on the given argument.\n * @see #_startBatch()\n */\n function _endBatch() {\n --_batch;\n _cometd._debug('Ending batch, depth', _batch);\n if (_batch < 0) {\n throw 'Calls to startBatch() and endBatch() are not paired';\n }\n\n if (_batch === 0 && !_isDisconnected() && !_internalBatch) {\n _flushBatch();\n }\n }\n\n /**\n * Sends the connect message\n */\n function _connect() {\n if (!_isDisconnected()) {\n var bayeuxMessage = {\n id: _nextMessageId(),\n channel: '/meta/connect',\n connectionType: _transport.getType()\n };\n\n // In case of reload or temporary loss of connection\n // we want the next successful connect to return immediately\n // instead of being held by the server, so that connect listeners\n // can be notified that the connection has been re-established\n if (!_connected) {\n bayeuxMessage.advice = {\n timeout: 0\n };\n }\n\n _setStatus('connecting');\n _cometd._debug('Connect sent', bayeuxMessage);\n _send([bayeuxMessage], true, 'connect');\n _setStatus('connected');\n }\n }\n\n function _delayedConnect(delay) {\n _setStatus('connecting');\n _delayedSend(function() {\n _connect();\n }, delay);\n }\n\n function _updateAdvice(newAdvice) {\n if (newAdvice) {\n _advice = _cometd._mixin(false, {}, _config.advice, newAdvice);\n _cometd._debug('New advice', _advice);\n }\n }\n\n function _disconnect(abort) {\n _cancelDelayedSend();\n if (abort && _transport) {\n _transport.abort();\n }\n _crossDomain = false;\n _transport = null;\n _setStatus('disconnected');\n _clientId = null;\n _batch = 0;\n _resetBackoff();\n _reestablish = false;\n _connected = false;\n _unconnectTime = 0;\n _metaConnect = null;\n\n // Fail any existing queued message\n if (_messageQueue.length > 0) {\n var messages = _messageQueue;\n _messageQueue = [];\n _handleFailure.call(_cometd, undefined, messages, {\n reason: 'Disconnected'\n });\n }\n }\n\n function _notifyTransportException(oldTransport, newTransport, failure) {\n var handler = _cometd.onTransportException;\n if (_isFunction(handler)) {\n _cometd._debug('Invoking transport exception handler', oldTransport, newTransport, failure);\n try {\n handler.call(_cometd, failure, oldTransport, newTransport);\n } catch (x) {\n _cometd._info('Exception during execution of transport exception handler', x);\n }\n }\n }\n\n /**\n * Sends the initial handshake message\n */\n function _handshake(handshakeProps, handshakeCallback) {\n if (_isFunction(handshakeProps)) {\n handshakeCallback = handshakeProps;\n handshakeProps = undefined;\n }\n\n _clientId = null;\n\n _clearSubscriptions();\n\n // Reset the transports if we're not retrying the handshake\n if (_isDisconnected()) {\n _transports.reset(true);\n }\n\n // Reset the advice.\n _updateAdvice({});\n\n _batch = 0;\n\n // Mark the start of an internal batch.\n // This is needed because handshake and connect are async.\n // It may happen that the application calls init() then subscribe()\n // and the subscribe message is sent before the connect message, if\n // the subscribe message is not held until the connect message is sent.\n // So here we start a batch to hold temporarily any message until\n // the connection is fully established.\n _internalBatch = true;\n\n // Save the properties provided by the user, so that\n // we can reuse them during automatic re-handshake\n _handshakeProps = handshakeProps;\n _handshakeCallback = handshakeCallback;\n\n var version = '1.0';\n\n // Figure out the transports to send to the server\n var url = _cometd.getURL();\n var transportTypes = _transports.findTransportTypes(version, _crossDomain, url);\n\n var bayeuxMessage = {\n id: _nextMessageId(),\n version: version,\n minimumVersion: version,\n channel: '/meta/handshake',\n supportedConnectionTypes: transportTypes,\n advice: {\n timeout: _advice.timeout,\n interval: _advice.interval\n }\n };\n // Do not allow the user to override important fields.\n var message = _cometd._mixin(false, {}, _handshakeProps, bayeuxMessage);\n\n // Save the callback.\n _cometd._putCallback(message.id, handshakeCallback);\n\n // Pick up the first available transport as initial transport\n // since we don't know if the server supports it\n if (!_transport) {\n _transport = _transports.negotiateTransport(transportTypes, version, _crossDomain, url);\n if (!_transport) {\n var failure = 'Could not find initial transport among: ' + _transports.getTransportTypes();\n _cometd._warn(failure);\n throw failure;\n }\n }\n\n _cometd._debug('Initial transport is', _transport.getType());\n\n // We started a batch to hold the application messages,\n // so here we must bypass it and send immediately.\n _setStatus('handshaking');\n _cometd._debug('Handshake sent', message);\n _send([message], false, 'handshake');\n }\n\n function _delayedHandshake(delay) {\n _setStatus('handshaking');\n\n // We will call _handshake() which will reset _clientId, but we want to avoid\n // that between the end of this method and the call to _handshake() someone may\n // call publish() (or other methods that call _queueSend()).\n _internalBatch = true;\n\n _delayedSend(function() {\n _handshake(_handshakeProps, _handshakeCallback);\n }, delay);\n }\n\n function _notifyCallback(callback, message) {\n try {\n callback.call(_cometd, message);\n } catch (x) {\n var handler = _cometd.onCallbackException;\n if (_isFunction(handler)) {\n _cometd._debug('Invoking callback exception handler', x);\n try {\n handler.call(_cometd, x, message);\n } catch (xx) {\n _cometd._info('Exception during execution of callback exception handler', xx);\n }\n } else {\n _cometd._info('Exception during execution of message callback', x);\n }\n }\n }\n\n this._getCallback = function(messageId) {\n return _callbacks[messageId];\n };\n\n this._putCallback = function(messageId, callback) {\n var result = this._getCallback(messageId);\n if (_isFunction(callback)) {\n _callbacks[messageId] = callback;\n }\n return result;\n };\n\n function _handleCallback(message) {\n var callback = _cometd._getCallback([message.id]);\n if (_isFunction(callback)) {\n delete _callbacks[message.id];\n _notifyCallback(callback, message);\n }\n }\n\n function _handleRemoteCall(message) {\n var context = _remoteCalls[message.id];\n delete _remoteCalls[message.id];\n if (context) {\n _cometd._debug('Handling remote call response for', message, 'with context', context);\n\n // Clear the timeout, if present.\n var timeout = context.timeout;\n if (timeout) {\n _cometd.clearTimeout(timeout);\n }\n\n var callback = context.callback;\n if (_isFunction(callback)) {\n _notifyCallback(callback, message);\n return true;\n }\n }\n return false;\n }\n\n this.onTransportFailure = function(message, failureInfo, failureHandler) {\n this._debug('Transport failure', failureInfo, 'for', message);\n\n var transports = this.getTransportRegistry();\n var url = this.getURL();\n var crossDomain = this._isCrossDomain(_splitURL(url)[2]);\n var version = '1.0';\n var transportTypes = transports.findTransportTypes(version, crossDomain, url);\n\n if (failureInfo.action === 'none') {\n if (message.channel === '/meta/handshake') {\n if (!failureInfo.transport) {\n var failure = 'Could not negotiate transport, client=[' + transportTypes + '], server=[' + message.supportedConnectionTypes + ']';\n this._warn(failure);\n _notifyTransportException(_transport.getType(), null, {\n reason: failure,\n connectionType: _transport.getType(),\n transport: _transport\n });\n }\n }\n } else {\n failureInfo.delay = this.getBackoffPeriod();\n // Different logic depending on whether we are handshaking or connecting.\n if (message.channel === '/meta/handshake') {\n if (!failureInfo.transport) {\n // The transport is invalid, try to negotiate again.\n var oldTransportType = _transport ? _transport.getType() : null;\n var newTransport = transports.negotiateTransport(transportTypes, version, crossDomain, url);\n if (!newTransport) {\n this._warn('Could not negotiate transport, client=[' + transportTypes + ']');\n _notifyTransportException(oldTransportType, null, message.failure);\n failureInfo.action = 'none';\n } else {\n var newTransportType = newTransport.getType();\n this._debug('Transport', oldTransportType, '->', newTransportType);\n _notifyTransportException(oldTransportType, newTransportType, message.failure);\n failureInfo.action = 'handshake';\n failureInfo.transport = newTransport;\n }\n }\n\n if (failureInfo.action !== 'none') {\n this.increaseBackoffPeriod();\n }\n } else {\n var now = new Date().getTime();\n\n if (_unconnectTime === 0) {\n _unconnectTime = now;\n }\n\n if (failureInfo.action === 'retry') {\n failureInfo.delay = this.increaseBackoffPeriod();\n // Check whether we may switch to handshaking.\n var maxInterval = _advice.maxInterval;\n if (maxInterval > 0) {\n var expiration = _advice.timeout + _advice.interval + maxInterval;\n var unconnected = now - _unconnectTime;\n if (unconnected + _backoff > expiration) {\n failureInfo.action = 'handshake';\n }\n }\n }\n\n if (failureInfo.action === 'handshake') {\n failureInfo.delay = 0;\n transports.reset(false);\n this.resetBackoffPeriod();\n }\n }\n }\n\n failureHandler.call(_cometd, failureInfo);\n };\n\n function _handleTransportFailure(failureInfo) {\n _cometd._debug('Transport failure handling', failureInfo);\n\n if (failureInfo.transport) {\n _transport = failureInfo.transport;\n }\n\n if (failureInfo.url) {\n _transport.setURL(failureInfo.url);\n }\n\n var action = failureInfo.action;\n var delay = failureInfo.delay || 0;\n switch (action) {\n case 'handshake':\n _delayedHandshake(delay);\n break;\n case 'retry':\n _delayedConnect(delay);\n break;\n case 'none':\n _disconnect(true);\n break;\n default:\n throw 'Unknown action ' + action;\n }\n }\n\n function _failHandshake(message, failureInfo) {\n _handleCallback(message);\n _notifyListeners('/meta/handshake', message);\n _notifyListeners('/meta/unsuccessful', message);\n\n // The listeners may have disconnected.\n if (_isDisconnected()) {\n failureInfo.action = 'none';\n }\n\n _cometd.onTransportFailure.call(_cometd, message, failureInfo, _handleTransportFailure);\n }\n\n function _handshakeResponse(message) {\n var url = _cometd.getURL();\n if (message.successful) {\n var crossDomain = _cometd._isCrossDomain(_splitURL(url)[2]);\n var newTransport = _transports.negotiateTransport(message.supportedConnectionTypes, message.version, crossDomain, url);\n if (newTransport === null) {\n message.successful = false;\n _failHandshake(message, {\n cause: 'negotiation',\n action: 'none',\n transport: null\n });\n return;\n } else if (_transport !== newTransport) {\n _cometd._debug('Transport', _transport.getType(), '->', newTransport.getType());\n _transport = newTransport;\n }\n\n _clientId = message.clientId;\n\n // End the internal batch and allow held messages from the application\n // to go to the server (see _handshake() where we start the internal batch).\n _internalBatch = false;\n _flushBatch();\n\n // Here the new transport is in place, as well as the clientId, so\n // the listeners can perform a publish() if they want.\n // Notify the listeners before the connect below.\n message.reestablish = _reestablish;\n _reestablish = true;\n\n _handleCallback(message);\n _notifyListeners('/meta/handshake', message);\n\n _handshakeMessages = message['x-messages'] || 0;\n\n var action = _isDisconnected() ? 'none' : _advice.reconnect || 'retry';\n switch (action) {\n case 'retry':\n _resetBackoff();\n if (_handshakeMessages === 0) {\n _delayedConnect(0);\n } else {\n _cometd._debug('Processing', _handshakeMessages, 'handshake-delivered messages');\n }\n break;\n case 'none':\n _disconnect(true);\n break;\n default:\n throw 'Unrecognized advice action ' + action;\n }\n } else {\n _failHandshake(message, {\n cause: 'unsuccessful',\n action: _advice.reconnect || 'handshake',\n transport: _transport\n });\n }\n }\n\n function _handshakeFailure(message) {\n _failHandshake(message, {\n cause: 'failure',\n action: 'handshake',\n transport: null\n });\n }\n\n function _matchMetaConnect(connect) {\n if (_status === 'disconnected') {\n return true;\n }\n if (_metaConnect && _metaConnect.id === connect.id) {\n _metaConnect = null;\n return true;\n }\n return false;\n }\n\n function _failConnect(message, failureInfo) {\n // Notify the listeners after the status change but before the next action.\n _notifyListeners('/meta/connect', message);\n _notifyListeners('/meta/unsuccessful', message);\n\n // The listeners may have disconnected.\n if (_isDisconnected()) {\n failureInfo.action = 'none';\n }\n\n _cometd.onTransportFailure.call(_cometd, message, failureInfo, _handleTransportFailure);\n }\n\n function _connectResponse(message) {\n if (_matchMetaConnect(message)) {\n _connected = message.successful;\n if (_connected) {\n _notifyListeners('/meta/connect', message);\n\n // Normally, the advice will say \"reconnect: 'retry', interval: 0\"\n // and the server will hold the request, so when a response returns\n // we immediately call the server again (long polling).\n // Listeners can call disconnect(), so check the state after they run.\n var action = _isDisconnected() ? 'none' : _advice.reconnect || 'retry';\n switch (action) {\n case 'retry':\n _resetBackoff();\n _delayedConnect(_backoff);\n break;\n case 'none':\n _disconnect(false);\n break;\n default:\n throw 'Unrecognized advice action ' + action;\n }\n } else {\n _failConnect(message, {\n cause: 'unsuccessful',\n action: _advice.reconnect || 'retry',\n transport: _transport\n });\n }\n } else {\n _cometd._debug('Mismatched /meta/connect reply', message);\n }\n }\n\n function _connectFailure(message) {\n if (_matchMetaConnect(message)) {\n _connected = false;\n _failConnect(message, {\n cause: 'failure',\n action: 'retry',\n transport: null\n });\n } else {\n _cometd._debug('Mismatched /meta/connect failure', message);\n }\n }\n\n function _failDisconnect(message) {\n _disconnect(true);\n _handleCallback(message);\n _notifyListeners('/meta/disconnect', message);\n _notifyListeners('/meta/unsuccessful', message);\n }\n\n function _disconnectResponse(message) {\n if (message.successful) {\n // Wait for the /meta/connect to arrive.\n _disconnect(false);\n _handleCallback(message);\n _notifyListeners('/meta/disconnect', message);\n } else {\n _failDisconnect(message);\n }\n }\n\n function _disconnectFailure(message) {\n _failDisconnect(message);\n }\n\n function _failSubscribe(message) {\n var subscriptions = _listeners[message.subscription];\n if (subscriptions) {\n for (var id in subscriptions) {\n if (subscriptions.hasOwnProperty(id)) {\n var subscription = subscriptions[id];\n if (subscription && !subscription.listener) {\n delete subscriptions[id];\n _cometd._debug('Removed failed subscription', subscription);\n }\n }\n }\n }\n _handleCallback(message);\n _notifyListeners('/meta/subscribe', message);\n _notifyListeners('/meta/unsuccessful', message);\n }\n\n function _subscribeResponse(message) {\n if (message.successful) {\n _handleCallback(message);\n _notifyListeners('/meta/subscribe', message);\n } else {\n _failSubscribe(message);\n }\n }\n\n function _subscribeFailure(message) {\n _failSubscribe(message);\n }\n\n function _failUnsubscribe(message) {\n _handleCallback(message);\n _notifyListeners('/meta/unsubscribe', message);\n _notifyListeners('/meta/unsuccessful', message);\n }\n\n function _unsubscribeResponse(message) {\n if (message.successful) {\n _handleCallback(message);\n _notifyListeners('/meta/unsubscribe', message);\n } else {\n _failUnsubscribe(message);\n }\n }\n\n function _unsubscribeFailure(message) {\n _failUnsubscribe(message);\n }\n\n function _failMessage(message) {\n if (!_handleRemoteCall(message)) {\n _handleCallback(message);\n _notifyListeners('/meta/publish', message);\n _notifyListeners('/meta/unsuccessful', message);\n }\n }\n\n function _messageResponse(message) {\n if (message.data !== undefined) {\n if (!_handleRemoteCall(message)) {\n _notifyListeners(message.channel, message);\n if (_handshakeMessages > 0) {\n --_handshakeMessages;\n if (_handshakeMessages === 0) {\n _cometd._debug('Processed last handshake-delivered message');\n _delayedConnect(0);\n }\n }\n }\n } else {\n if (message.successful === undefined) {\n _cometd._warn('Unknown Bayeux Message', message);\n } else {\n if (message.successful) {\n _handleCallback(message);\n _notifyListeners('/meta/publish', message);\n } else {\n _failMessage(message);\n }\n }\n }\n }\n\n function _messageFailure(failure) {\n _failMessage(failure);\n }\n\n function _receive(message) {\n _unconnectTime = 0;\n\n message = _applyIncomingExtensions(message);\n if (message === undefined || message === null) {\n return;\n }\n\n _updateAdvice(message.advice);\n\n var channel = message.channel;\n switch (channel) {\n case '/meta/handshake':\n _handshakeResponse(message);\n break;\n case '/meta/connect':\n _connectResponse(message);\n break;\n case '/meta/disconnect':\n _disconnectResponse(message);\n break;\n case '/meta/subscribe':\n _subscribeResponse(message);\n break;\n case '/meta/unsubscribe':\n _unsubscribeResponse(message);\n break;\n default:\n _messageResponse(message);\n break;\n }\n }\n\n /**\n * Receives a message.\n * This method is exposed as a public so that extensions may inject\n * messages simulating that they had been received.\n */\n this.receive = _receive;\n\n _handleMessages = function(rcvdMessages) {\n _cometd._debug('Received', rcvdMessages);\n\n for (var i = 0; i < rcvdMessages.length; ++i) {\n var message = rcvdMessages[i];\n _receive(message);\n }\n };\n\n _handleFailure = function(conduit, messages, failure) {\n _cometd._debug('handleFailure', conduit, messages, failure);\n\n failure.transport = conduit;\n for (var i = 0; i < messages.length; ++i) {\n var message = messages[i];\n var failureMessage = {\n id: message.id,\n successful: false,\n channel: message.channel,\n failure: failure\n };\n failure.message = message;\n switch (message.channel) {\n case '/meta/handshake':\n _handshakeFailure(failureMessage);\n break;\n case '/meta/connect':\n _connectFailure(failureMessage);\n break;\n case '/meta/disconnect':\n _disconnectFailure(failureMessage);\n break;\n case '/meta/subscribe':\n failureMessage.subscription = message.subscription;\n _subscribeFailure(failureMessage);\n break;\n case '/meta/unsubscribe':\n failureMessage.subscription = message.subscription;\n _unsubscribeFailure(failureMessage);\n break;\n default:\n _messageFailure(failureMessage);\n break;\n }\n }\n };\n\n function _hasSubscriptions(channel) {\n var subscriptions = _listeners[channel];\n if (subscriptions) {\n for (var id in subscriptions) {\n if (subscriptions.hasOwnProperty(id)) {\n if (subscriptions[id]) {\n return true;\n }\n }\n }\n }\n return false;\n }\n\n function _resolveScopedCallback(scope, callback) {\n var delegate = {\n scope: scope,\n method: callback\n };\n if (_isFunction(scope)) {\n delegate.scope = undefined;\n delegate.method = scope;\n } else {\n if (_isString(callback)) {\n if (!scope) {\n throw 'Invalid scope ' + scope;\n }\n delegate.method = scope[callback];\n if (!_isFunction(delegate.method)) {\n throw 'Invalid callback ' + callback + ' for scope ' + scope;\n }\n } else if (!_isFunction(callback)) {\n throw 'Invalid callback ' + callback;\n }\n }\n return delegate;\n }\n\n function _addListener(channel, scope, callback, isListener) {\n // The data structure is a map<channel, subscription[]>, where each subscription\n // holds the callback to be called and its scope.\n\n var delegate = _resolveScopedCallback(scope, callback);\n _cometd._debug('Adding', isListener ? 'listener' : 'subscription', 'on', channel, 'with scope', delegate.scope, 'and callback', delegate.method);\n\n var id = ++_listenerId;\n var subscription = {\n id: id,\n channel: channel,\n scope: delegate.scope,\n callback: delegate.method,\n listener: isListener\n };\n\n var subscriptions = _listeners[channel];\n if (!subscriptions) {\n subscriptions = {};\n _listeners[channel] = subscriptions;\n }\n\n subscriptions[id] = subscription;\n\n _cometd._debug('Added', isListener ? 'listener' : 'subscription', subscription);\n\n return subscription;\n }\n\n //\n // PUBLIC API\n //\n\n /**\n * Registers the given transport under the given transport type.\n * The optional index parameter specifies the \"priority\" at which the\n * transport is registered (where 0 is the max priority).\n * If a transport with the same type is already registered, this function\n * does nothing and returns false.\n * @param type the transport type\n * @param transport the transport object\n * @param index the index at which this transport is to be registered\n * @return true if the transport has been registered, false otherwise\n * @see #unregisterTransport(type)\n */\n this.registerTransport = function(type, transport, index) {\n var result = _transports.add(type, transport, index);\n if (result) {\n this._debug('Registered transport', type);\n\n if (_isFunction(transport.registered)) {\n transport.registered(type, this);\n }\n }\n return result;\n };\n\n /**\n * Unregisters the transport with the given transport type.\n * @param type the transport type to unregister\n * @return the transport that has been unregistered,\n * or null if no transport was previously registered under the given transport type\n */\n this.unregisterTransport = function(type) {\n var transport = _transports.remove(type);\n if (transport !== null) {\n this._debug('Unregistered transport', type);\n\n if (_isFunction(transport.unregistered)) {\n transport.unregistered();\n }\n }\n return transport;\n };\n\n this.unregisterTransports = function() {\n _transports.clear();\n };\n\n /**\n * @return an array of all registered transport types\n */\n this.getTransportTypes = function() {\n return _transports.getTransportTypes();\n };\n\n this.findTransport = function(name) {\n return _transports.find(name);\n };\n\n /**\n * @returns the TransportRegistry object\n */\n this.getTransportRegistry = function() {\n return _transports;\n };\n\n /**\n * Configures the initial Bayeux communication with the Bayeux server.\n * Configuration is passed via an object that must contain a mandatory field <code>url</code>\n * of type string containing the URL of the Bayeux server.\n * @param configuration the configuration object\n */\n this.configure = function(configuration) {\n _configure.call(this, configuration);\n };\n\n /**\n * Configures and establishes the Bayeux communication with the Bayeux server\n * via a handshake and a subsequent connect.\n * @param configuration the configuration object\n * @param handshakeProps an object to be merged with the handshake message\n * @see #configure(configuration)\n * @see #handshake(handshakeProps)\n */\n this.init = function(configuration, handshakeProps) {\n this.configure(configuration);\n this.handshake(handshakeProps);\n };\n\n /**\n * Establishes the Bayeux communication with the Bayeux server\n * via a handshake and a subsequent connect.\n * @param handshakeProps an object to be merged with the handshake message\n * @param handshakeCallback a function to be invoked when the handshake is acknowledged\n */\n this.handshake = function(handshakeProps, handshakeCallback) {\n if (_status !== 'disconnected') {\n throw 'Illegal state: handshaken';\n }\n _handshake(handshakeProps, handshakeCallback);\n };\n\n /**\n * Disconnects from the Bayeux server.\n * @param disconnectProps an object to be merged with the disconnect message\n * @param disconnectCallback a function to be invoked when the disconnect is acknowledged\n */\n this.disconnect = function(disconnectProps, disconnectCallback) {\n if (_isDisconnected()) {\n return;\n }\n\n if (_isFunction(disconnectProps)) {\n disconnectCallback = disconnectProps;\n disconnectProps = undefined;\n }\n\n var bayeuxMessage = {\n id: _nextMessageId(),\n channel: '/meta/disconnect'\n };\n // Do not allow the user to override important fields.\n var message = this._mixin(false, {}, disconnectProps, bayeuxMessage);\n\n // Save the callback.\n _cometd._putCallback(message.id, disconnectCallback);\n\n _setStatus('disconnecting');\n _send([message], false, 'disconnect');\n };\n\n /**\n * Marks the start of a batch of application messages to be sent to the server\n * in a single request, obtaining a single response containing (possibly) many\n * application reply messages.\n * Messages are held in a queue and not sent until {@link #endBatch()} is called.\n * If startBatch() is called multiple times, then an equal number of endBatch()\n * calls must be made to close and send the batch of messages.\n * @see #endBatch()\n */\n this.startBatch = function() {\n _startBatch();\n };\n\n /**\n * Marks the end of a batch of application messages to be sent to the server\n * in a single request.\n * @see #startBatch()\n */\n this.endBatch = function() {\n _endBatch();\n };\n\n /**\n * Executes the given callback in the given scope, surrounded by a {@link #startBatch()}\n * and {@link #endBatch()} calls.\n * @param scope the scope of the callback, may be omitted\n * @param callback the callback to be executed within {@link #startBatch()} and {@link #endBatch()} calls\n */\n this.batch = function(scope, callback) {\n var delegate = _resolveScopedCallback(scope, callback);\n this.startBatch();\n try {\n delegate.method.call(delegate.scope);\n this.endBatch();\n } catch (x) {\n this._info('Exception during execution of batch', x);\n this.endBatch();\n throw x;\n }\n };\n\n /**\n * Adds a listener for bayeux messages, performing the given callback in the given scope\n * when a message for the given channel arrives.\n * @param channel the channel the listener is interested to\n * @param scope the scope of the callback, may be omitted\n * @param callback the callback to call when a message is sent to the channel\n * @returns the subscription handle to be passed to {@link #removeListener(object)}\n * @see #removeListener(subscription)\n */\n this.addListener = function(channel, scope, callback) {\n if (arguments.length < 2) {\n throw 'Illegal arguments number: required 2, got ' + arguments.length;\n }\n if (!_isString(channel)) {\n throw 'Illegal argument type: channel must be a string';\n }\n\n return _addListener(channel, scope, callback, true);\n };\n\n /**\n * Removes the subscription obtained with a call to {@link #addListener(string, object, function)}.\n * @param subscription the subscription to unsubscribe.\n * @see #addListener(channel, scope, callback)\n */\n this.removeListener = function(subscription) {\n // Beware of subscription.id == 0, which is falsy => cannot use !subscription.id\n if (!subscription || !subscription.channel || !(\"id\" in subscription)) {\n throw 'Invalid argument: expected subscription, not ' + subscription;\n }\n\n _removeListener(subscription);\n };\n\n /**\n * Removes all listeners registered with {@link #addListener(channel, scope, callback)} or\n * {@link #subscribe(channel, scope, callback)}.\n */\n this.clearListeners = function() {\n _listeners = {};\n };\n\n /**\n * Subscribes to the given channel, performing the given callback in the given scope\n * when a message for the channel arrives.\n * @param channel the channel to subscribe to\n * @param scope the scope of the callback, may be omitted\n * @param callback the callback to call when a message is sent to the channel\n * @param subscribeProps an object to be merged with the subscribe message\n * @param subscribeCallback a function to be invoked when the subscription is acknowledged\n * @return the subscription handle to be passed to {@link #unsubscribe(object)}\n */\n this.subscribe = function(channel, scope, callback, subscribeProps, subscribeCallback) {\n if (arguments.length < 2) {\n throw 'Illegal arguments number: required 2, got ' + arguments.length;\n }\n if (!_isString(channel)) {\n throw 'Illegal argument type: channel must be a string';\n }\n if (_isDisconnected()) {\n throw 'Illegal state: disconnected';\n }\n\n // Normalize arguments\n if (_isFunction(scope)) {\n subscribeCallback = subscribeProps;\n subscribeProps = callback;\n callback = scope;\n scope = undefined;\n }\n if (_isFunction(subscribeProps)) {\n subscribeCallback = subscribeProps;\n subscribeProps = undefined;\n }\n\n // Only send the message to the server if this client has not yet subscribed to the channel\n var send = !_hasSubscriptions(channel);\n\n var subscription = _addListener(channel, scope, callback, false);\n\n if (send) {\n // Send the subscription message after the subscription registration to avoid\n // races where the server would send a message to the subscribers, but here\n // on the client the subscription has not been added yet to the data structures\n var bayeuxMessage = {\n id: _nextMessageId(),\n channel: '/meta/subscribe',\n subscription: channel\n };\n // Do not allow the user to override important fields.\n var message = this._mixin(false, {}, subscribeProps, bayeuxMessage);\n\n // Save the callback.\n _cometd._putCallback(message.id, subscribeCallback);\n\n _queueSend(message);\n }\n\n return subscription;\n };\n\n /**\n * Unsubscribes the subscription obtained with a call to {@link #subscribe(string, object, function)}.\n * @param subscription the subscription to unsubscribe.\n * @param unsubscribeProps an object to be merged with the unsubscribe message\n * @param unsubscribeCallback a function to be invoked when the unsubscription is acknowledged\n */\n this.unsubscribe = function(subscription, unsubscribeProps, unsubscribeCallback) {\n if (arguments.length < 1) {\n throw 'Illegal arguments number: required 1, got ' + arguments.length;\n }\n if (_isDisconnected()) {\n throw 'Illegal state: disconnected';\n }\n\n if (_isFunction(unsubscribeProps)) {\n unsubscribeCallback = unsubscribeProps;\n unsubscribeProps = undefined;\n }\n\n // Remove the local listener before sending the message\n // This ensures that if the server fails, this client does not get notifications\n this.removeListener(subscription);\n\n var channel = subscription.channel;\n // Only send the message to the server if this client unsubscribes the last subscription\n if (!_hasSubscriptions(channel)) {\n var bayeuxMessage = {\n id: _nextMessageId(),\n channel: '/meta/unsubscribe',\n subscription: channel\n };\n // Do not allow the user to override important fields.\n var message = this._mixin(false, {}, unsubscribeProps, bayeuxMessage);\n\n // Save the callback.\n _cometd._putCallback(message.id, unsubscribeCallback);\n\n _queueSend(message);\n }\n };\n\n this.resubscribe = function(subscription, subscribeProps) {\n _removeSubscription(subscription);\n if (subscription) {\n return this.subscribe(subscription.channel, subscription.scope, subscription.callback, subscribeProps);\n }\n return undefined;\n };\n\n /**\n * Removes all subscriptions added via {@link #subscribe(channel, scope, callback, subscribeProps)},\n * but does not remove the listeners added via {@link addListener(channel, scope, callback)}.\n */\n this.clearSubscriptions = function() {\n _clearSubscriptions();\n };\n\n /**\n * Publishes a message on the given channel, containing the given content.\n * @param channel the channel to publish the message to\n * @param content the content of the message\n * @param publishProps an object to be merged with the publish message\n * @param publishCallback a function to be invoked when the publish is acknowledged by the server\n */\n this.publish = function(channel, content, publishProps, publishCallback) {\n if (arguments.length < 1) {\n throw 'Illegal arguments number: required 1, got ' + arguments.length;\n }\n if (!_isString(channel)) {\n throw 'Illegal argument type: channel must be a string';\n }\n if (/^\\/meta\\//.test(channel)) {\n throw 'Illegal argument: cannot publish to meta channels';\n }\n if (_isDisconnected()) {\n throw 'Illegal state: disconnected';\n }\n\n if (_isFunction(content)) {\n publishCallback = content;\n content = {};\n publishProps = undefined;\n } else if (_isFunction(publishProps)) {\n publishCallback = publishProps;\n publishProps = undefined;\n }\n\n var bayeuxMessage = {\n id: _nextMessageId(),\n channel: channel,\n data: content\n };\n // Do not allow the user to override important fields.\n var message = this._mixin(false, {}, publishProps, bayeuxMessage);\n\n // Save the callback.\n _cometd._putCallback(message.id, publishCallback);\n\n _queueSend(message);\n };\n\n /**\n * Publishes a message with binary data on the given channel.\n * The binary data chunk may be an ArrayBuffer, a DataView, a TypedArray\n * (such as Uint8Array) or a plain integer array.\n * The meta data object may contain additional application data such as\n * a file name, a mime type, etc.\n * @param channel the channel to publish the message to\n * @param data the binary data to publish\n * @param last whether the binary data chunk is the last\n * @param meta an object containing meta data associated to the binary chunk\n * @param callback a function to be invoked when the publish is acknowledged by the server\n */\n this.publishBinary = function(channel, data, last, meta, callback) {\n if (_isFunction(data)) {\n callback = data;\n data = new ArrayBuffer(0);\n last = true;\n meta = undefined;\n } else if (_isFunction(last)) {\n callback = last;\n last = true;\n meta = undefined;\n } else if (_isFunction(meta)) {\n callback = meta;\n meta = undefined;\n }\n var content = {\n meta: meta,\n data: data,\n last: last\n };\n var ext = {\n ext: {\n binary: {}\n }\n };\n this.publish(channel, content, ext, callback);\n };\n\n this.remoteCall = function(target, content, timeout, callProps, callback) {\n if (arguments.length < 1) {\n throw 'Illegal arguments number: required 1, got ' + arguments.length;\n }\n if (!_isString(target)) {\n throw 'Illegal argument type: target must be a string';\n }\n if (_isDisconnected()) {\n throw 'Illegal state: disconnected';\n }\n\n if (_isFunction(content)) {\n callback = content;\n content = {};\n timeout = _config.maxNetworkDelay;\n callProps = undefined;\n } else if (_isFunction(timeout)) {\n callback = timeout;\n timeout = _config.maxNetworkDelay;\n callProps = undefined;\n } else if (_isFunction(callProps)) {\n callback = callProps;\n callProps = undefined;\n }\n\n if (typeof timeout !== 'number') {\n throw 'Illegal argument type: timeout must be a number';\n }\n\n if (!target.match(/^\\//)) {\n target = '/' + target;\n }\n var channel = '/service' + target;\n\n var bayeuxMessage = {\n id: _nextMessageId(),\n channel: channel,\n data: content\n };\n var message = this._mixin(false, {}, callProps, bayeuxMessage);\n\n var context = {\n callback: callback\n };\n if (timeout > 0) {\n context.timeout = _cometd.setTimeout(function() {\n _cometd._debug('Timing out remote call', message, 'after', timeout, 'ms');\n _failMessage({\n id: message.id,\n error: '406::timeout',\n successful: false,\n failure: {\n message: message,\n reason: 'Remote Call Timeout'\n }\n });\n }, timeout);\n _cometd._debug('Scheduled remote call timeout', message, 'in', timeout, 'ms');\n }\n _remoteCalls[message.id] = context;\n\n _queueSend(message);\n };\n\n this.remoteCallBinary = function(target, data, last, meta, timeout, callback) {\n if (_isFunction(data)) {\n callback = data;\n data = new ArrayBuffer(0);\n last = true;\n meta = undefined;\n timeout = _config.maxNetworkDelay;\n } else if (_isFunction(last)) {\n callback = last;\n last = true;\n meta = undefined;\n timeout = _config.maxNetworkDelay;\n } else if (_isFunction(meta)) {\n callback = meta;\n meta = undefined;\n timeout = _config.maxNetworkDelay;\n } else if (_isFunction(timeout)) {\n callback = timeout;\n timeout = _config.maxNetworkDelay;\n }\n\n var content = {\n meta: meta,\n data: data,\n last: last\n };\n var ext = {\n ext: {\n binary: {}\n }\n };\n\n this.remoteCall(target, content, timeout, ext, callback);\n };\n\n /**\n * Returns a string representing the status of the bayeux communication with the Bayeux server.\n */\n this.getStatus = function() {\n return _status;\n };\n\n /**\n * Returns whether this instance has been disconnected.\n */\n this.isDisconnected = _isDisconnected;\n\n /**\n * Sets the backoff period used to increase the backoff time when retrying an unsuccessful or failed message.\n * Default value is 1 second, which means if there is a persistent failure the retries will happen\n * after 1 second, then after 2 seconds, then after 3 seconds, etc. So for example with 15 seconds of\n * elapsed time, there will be 5 retries (at 1, 3, 6, 10 and 15 seconds elapsed).\n * @param period the backoff period to set\n * @see #getBackoffIncrement()\n */\n this.setBackoffIncrement = function(period) {\n _config.backoffIncrement = period;\n };\n\n /**\n * Returns the backoff period used to increase the backoff time when retrying an unsuccessful or failed message.\n * @see #setBackoffIncrement(period)\n */\n this.getBackoffIncrement = function() {\n return _config.backoffIncrement;\n };\n\n /**\n * Returns the backoff period to wait before retrying an unsuccessful or failed message.\n */\n this.getBackoffPeriod = function() {\n return _backoff;\n };\n\n /**\n * Increases the backoff period up to the maximum value configured.\n * @returns the backoff period after increment\n * @see getBackoffIncrement\n */\n this.increaseBackoffPeriod = function() {\n return _increaseBackoff();\n };\n\n /**\n * Resets the backoff period to zero.\n */\n this.resetBackoffPeriod = function() {\n _resetBackoff();\n };\n\n /**\n * Sets the log level for console logging.\n * Valid values are the strings 'error', 'warn', 'info' and 'debug', from\n * less verbose to more verbose.\n * @param level the log level string\n */\n this.setLogLevel = function(level) {\n _config.logLevel = level;\n };\n\n /**\n * Registers an extension whose callbacks are called for every incoming message\n * (that comes from the server to this client implementation) and for every\n * outgoing message (that originates from this client implementation for the\n * server).\n * The format of the extension object is the following:\n * <pre>\n * {\n * incoming: function(message) { ... },\n * outgoing: function(message) { ... }\n * }\n * </pre>\n * Both properties are optional, but if they are present they will be called\n * respectively for each incoming message and for each outgoing message.\n * @param name the name of the extension\n * @param extension the extension to register\n * @return true if the extension was registered, false otherwise\n * @see #unregisterExtension(name)\n */\n this.registerExtension = function(name, extension) {\n if (arguments.length < 2) {\n throw 'Illegal arguments number: required 2, got ' + arguments.length;\n }\n if (!_isString(name)) {\n throw 'Illegal argument type: extension name must be a string';\n }\n\n var existing = false;\n for (var i = 0; i < _extensions.length; ++i) {\n var existingExtension = _extensions[i];\n if (existingExtension.name === name) {\n existing = true;\n break;\n }\n }\n if (!existing) {\n _extensions.push({\n name: name,\n extension: extension\n });\n this._debug('Registered extension', name);\n\n // Callback for extensions\n if (_isFunction(extension.registered)) {\n extension.registered(name, this);\n }\n\n return true;\n } else {\n this._info('Could not register extension with name', name, 'since another extension with the same name already exists');\n return false;\n }\n };\n\n /**\n * Unregister an extension previously registered with\n * {@link #registerExtension(name, extension)}.\n * @param name the name of the extension to unregister.\n * @return true if the extension was unregistered, false otherwise\n */\n this.unregisterExtension = function(name) {\n if (!_isString(name)) {\n throw 'Illegal argument type: extension name must be a string';\n }\n\n var unregistered = false;\n for (var i = 0; i < _extensions.length; ++i) {\n var extension = _extensions[i];\n if (extension.name === name) {\n _extensions.splice(i, 1);\n unregistered = true;\n this._debug('Unregistered extension', name);\n\n // Callback for extensions\n var ext = extension.extension;\n if (_isFunction(ext.unregistered)) {\n ext.unregistered();\n }\n\n break;\n }\n }\n return unregistered;\n };\n\n /**\n * Find the extension registered with the given name.\n * @param name the name of the extension to find\n * @return the extension found or null if no extension with the given name has been registered\n */\n this.getExtension = function(name) {\n for (var i = 0; i < _extensions.length; ++i) {\n var extension = _extensions[i];\n if (extension.name === name) {\n return extension.extension;\n }\n }\n return null;\n };\n\n /**\n * Returns the name assigned to this CometD object, or the string 'default'\n * if no name has been explicitly passed as parameter to the constructor.\n */\n this.getName = function() {\n return _name;\n };\n\n /**\n * Returns the clientId assigned by the Bayeux server during handshake.\n */\n this.getClientId = function() {\n return _clientId;\n };\n\n /**\n * Returns the URL of the Bayeux server.\n */\n this.getURL = function() {\n if (_transport) {\n var url = _transport.getURL();\n if (url) {\n return url;\n }\n url = _config.urls[_transport.getType()];\n if (url) {\n return url;\n }\n }\n return _config.url;\n };\n\n this.getTransport = function() {\n return _transport;\n };\n\n this.getConfiguration = function() {\n return this._mixin(true, {}, _config);\n };\n\n this.getAdvice = function() {\n return this._mixin(true, {}, _advice);\n };\n\n this.setTimeout = function(funktion, delay) {\n return _scheduler.setTimeout(function() {\n try {\n _cometd._debug('Invoking timed function', funktion);\n funktion();\n } catch (x) {\n _cometd._debug('Exception invoking timed function', funktion, x);\n }\n }, delay);\n };\n\n this.clearTimeout = function(id) {\n _scheduler.clearTimeout(id);\n };\n\n // Initialize transports.\n if (window.WebSocket) {\n this.registerTransport('websocket', new WebSocketTransport());\n }\n this.registerTransport('long-polling', new LongPollingTransport());\n this.registerTransport('callback-polling', new CallbackPollingTransport());\n };\n\n var _z85EncodeTable = [\n '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',\n 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j',\n 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't',\n 'u', 'v', 'w', 'x', 'y', 'z', 'A', 'B', 'C', 'D',\n 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N',\n 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X',\n 'Y', 'Z', '.', '-', ':', '+', '=', '^', '!', '/',\n '*', '?', '&', '<', '>', '(', ')', '[', ']', '{',\n '}', '@', '%', '$', '#'\n ];\n var _z85DecodeTable = [\n 0x00, 0x44, 0x00, 0x54, 0x53, 0x52, 0x48, 0x00,\n 0x4B, 0x4C, 0x46, 0x41, 0x00, 0x3F, 0x3E, 0x45,\n 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,\n 0x08, 0x09, 0x40, 0x00, 0x49, 0x42, 0x4A, 0x47,\n 0x51, 0x24, 0x25, 0x26, 0x27, 0x28, 0x29, 0x2A,\n 0x2B, 0x2C, 0x2D, 0x2E, 0x2F, 0x30, 0x31, 0x32,\n 0x33, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39, 0x3A,\n 0x3B, 0x3C, 0x3D, 0x4D, 0x00, 0x4E, 0x43, 0x00,\n 0x00, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F, 0x10,\n 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18,\n 0x19, 0x1A, 0x1B, 0x1C, 0x1D, 0x1E, 0x1F, 0x20,\n 0x21, 0x22, 0x23, 0x4F, 0x00, 0x50, 0x00, 0x00\n ];\n var Z85 = {\n encode: function(bytes) {\n var buffer = null;\n if (bytes instanceof ArrayBuffer) {\n buffer = bytes;\n } else if (bytes.buffer instanceof ArrayBuffer) {\n buffer = bytes.buffer;\n } else if (Array.isArray(bytes)) {\n buffer = new Uint8Array(bytes).buffer;\n }\n if (buffer == null) {\n throw 'Cannot Z85 encode ' + bytes;\n }\n\n var length = buffer.byteLength;\n var remainder = length % 4;\n var padding = 4 - (remainder === 0 ? 4 : remainder);\n var view = new DataView(buffer);\n var result = '';\n var value = 0;\n for (var i = 0; i < length + padding; ++i) {\n var isPadding = i >= length;\n value = value * 256 + (isPadding ? 0 : view.getUint8(i));\n if ((i + 1) % 4 === 0) {\n var divisor = 85 * 85 * 85 * 85;\n for (var j = 5; j > 0; --j) {\n if (!isPadding || j > padding) {\n var code = Math.floor(value / divisor) % 85;\n result += _z85EncodeTable[code];\n }\n divisor /= 85;\n }\n value = 0;\n }\n }\n\n return result;\n },\n decode: function(string) {\n var remainder = string.length % 5;\n var padding = 5 - (remainder === 0 ? 5 : remainder);\n for (var p = 0; p < padding; ++p) {\n string += _z85EncodeTable[_z85EncodeTable.length - 1];\n }\n var length = string.length;\n\n var buffer = new ArrayBuffer((length * 4 / 5) - padding);\n var view = new DataView(buffer);\n var value = 0;\n var charIdx = 0;\n var byteIdx = 0;\n for (var i = 0; i < length; ++i) {\n var code = string.charCodeAt(charIdx++) - 32;\n value = value * 85 + _z85DecodeTable[code];\n if (charIdx % 5 === 0) {\n var divisor = 256 * 256 * 256;\n while (divisor >= 1) {\n if (byteIdx < view.byteLength) {\n view.setUint8(byteIdx++, Math.floor(value / divisor) % 256);\n }\n divisor /= 256;\n }\n value = 0;\n }\n }\n\n return buffer;\n }\n };\n\n return {\n CometD: CometD,\n Transport: Transport,\n RequestTransport: RequestTransport,\n LongPollingTransport: LongPollingTransport,\n CallbackPollingTransport: CallbackPollingTransport,\n WebSocketTransport: WebSocketTransport,\n Utils: Utils,\n Z85: Z85\n };\n}));\n","const lib = require('cometd');\nmodule.exports = {\n CometD: lib.CometD,\n default: lib\n};\n","import { CometD as IsoCometD } from 'isomorphic-cometd';\nimport type {\n CometD,\n Configuration as CometDConfiguration,\n SubscriptionHandle,\n Listener as CometDListener,\n Callback as CometDCallback,\n HandshakeMessage as CometDHandshakeMessage,\n Message as CometDMessage\n} from 'cometd';\nimport { IFetchClient } from '../core';\nimport { MetaChannel } from './MetaChannel';\n\nexport interface ICometdConfig {\n url: string;\n logLevel?: string;\n requestHeaders?: any;\n appendMessageTypeToURL?: boolean;\n stickyReconnect?: boolean;\n}\n\nexport class Realtime {\n protected cometd: CometD;\n\n /**\n * Allows to set up a realtime (websocket or long-polling) connection to the platform.\n * @param client The fetch client instance to use\n * @param url The URL to connect to\n * @param handshakeCallback A function which is called on succeeded or failed handshake\n */\n constructor(\n private client: IFetchClient,\n private url: string = '/notification/realtime',\n handshakeCallback?\n ) {\n this.cometd = new IsoCometD({} as CometDConfiguration);\n // does not actually seem to be needed/supported? Just keeping to satisfy unit test snapshots\n (this.cometd as any).websocketEnabled = true;\n this.cometd.addListener(MetaChannel.HANDSHAKE, handshakeCallback || this.metaHandshake);\n }\n\n /**\n * Subscribes to a realtime channel to listen for data.\n * @param channel The channel to connect to\n * @param callback A function to call when data is received\n */\n subscribe(channel: string, callback: CometDCallback): SubscriptionHandle {\n this.checkConnection();\n return this.cometd.subscribe(channel, callback);\n }\n\n /**\n * Cancels the listening to a channel.\n * @param subscription The subscription object returned by subscribe()\n */\n unsubscribe(subscription: SubscriptionHandle): void {\n return this.cometd.unsubscribe(subscription);\n }\n\n /**\n * Allows to listen to Cometd handshake to find out if e.g. the connection was reestablished.\n */\n addHandshakeListener(callback: (msg: CometDHandshakeMessage) => void): SubscriptionHandle {\n return this.cometd.addListener(MetaChannel.HANDSHAKE, callback);\n }\n\n /**\n * Allows to listen to Cometd connection to e.g. detect when connection was lost.\n */\n addConnectListener(callback: (msg: CometDMessage) => void): SubscriptionHandle {\n return this.cometd.addListener(MetaChannel.CONNECT, callback);\n }\n\n /**\n * Removes the subscription obtained with a call to `addHandshakeListener` or `addConnectListener`.\n */\n removeListener(subscriptionHandle: SubscriptionHandle): void {\n return this.cometd.removeListener(subscriptionHandle);\n }\n\n /**\n * Resubscribes as necessary in case of a re-handshake.\n */\n resubscribe(subscriptionHandle: SubscriptionHandle): SubscriptionHandle {\n return this.cometd.resubscribe(subscriptionHandle);\n }\n\n /**\n * Disconnects the current connection.\n */\n disconnect(disconnectCallback: CometDListener = undefined): void {\n this.cometd.disconnect(disconnectCallback);\n }\n\n /**\n * Returns true if the CometD instance is disconnected or disconnecting.\n */\n isDisconnected(): boolean {\n return this.cometd.isDisconnected();\n }\n\n private checkConnection() {\n const { cometd, client, url } = this;\n if (cometd.isDisconnected()) {\n const { headers } = client.getFetchOptions();\n const config = {\n url: client.getUrl(url),\n requestHeaders: headers\n };\n cometd.configure(config);\n this.handshake(client.getCometdHandshake());\n }\n }\n\n private handshake(config: object) {\n this.cometd.handshake(config, undefined);\n }\n\n private metaHandshake = msg => {\n if (!msg.successful) {\n throw new Error('Handshake failed');\n }\n };\n}\n","import { IIdentified, Service, IResult, IResultList } from '../core';\nimport { IEvent } from './IEvent';\n\n/**\n * This class allows managing for events.\n */\nexport class EventService extends Service<IEvent> {\n protected baseUrl = 'event';\n protected listUrl = 'events';\n protected propertyName = 'events';\n protected channel = '/events/*';\n\n /**\n * Gets the details of a specific event.\n *\n * @param {string|number|IIdentified} entityOrId Entity or Id of the entity.\n *\n * @returns Response wrapped in [[IResult]]\n *\n * **Example**\n * ```typescript\n *\n * const eventId: number = 1;\n *\n * (async () => {\n * const {data, res} = await eventService.detail(eventId);\n * })();\n * ```\n */\n async detail(entityOrId: string | number | IIdentified): Promise<IResult<IEvent>> {\n return super.detail(entityOrId);\n }\n\n /**\n * Creates a new event.\n *\n * @param {IEvent} entity Event object with mandantory fragments.\n *\n * @returns Response wrapped in [[IResult]]\n *\n * **Example**\n * ```typescript\n *\n * const mandantoryObject: IEvent = {\n * source: device,\n * text: 'I am an Event!',\n * time: '2018-05-02T10:08:00Z',\n * type: 'device-type-here',\n * };\n *\n * (async () => {\n * const {data, res} = await eventService.create(mandantoryObject);\n * })();\n * ```\n */\n async create(entity: IEvent): Promise<IResult<IEvent>> {\n return super.create(entity);\n }\n\n /**\n * Updates event data.\n *\n * @param {Partial<IEvent>} entity Event is partially updatable.\n *\n * @returns Response wrapped in [[IResult]]\n *\n * **Example**\n * ```typescript\n *\n * const partialUpdateObject: Partial<IEvent> = {\n * source: device,\n * text: 'Changed Event!'\n * };\n *\n * (async () => {\n * const {data, res} = await eventService.update(partialUpdateObject);\n * })();\n * ```\n */\n async update(entity: Partial<IEvent>): Promise<IResult<IEvent>> {\n return super.update(entity);\n }\n\n /**\n * Gets the list of events filtered by parameters.\n *\n * @returns Response wrapped in [[IResultList]]\n *\n * @param {object} filter Object containing filters for querying events.\n *\n * **Example**\n * ```typescript\n *\n * const filter: object = {\n * pageSize: 100,\n * withTotalPages: true\n * };\n *\n * (async () => {\n * const {data, res, paging} = await eventService.list(filter);\n * })();\n * ```\n */\n async list(filter: object = {}): Promise<IResultList<IEvent>> {\n return super.list(filter);\n }\n\n /**\n * Removes an event with given id.\n *\n * @returns Response wrapped in [[IResult]]\n *\n * @param {string | number | IIdentified} entityOrId entity or id of the event.\n *\n * **Example**\n * ```typescript\n *\n * const eventId: number = 1;\n *\n * (async () => {\n * const {data, res} = await eventService.delete(eventId);\n * // data will be null\n * })();\n * ```\n */\n async delete(entityOrId: string | number | IIdentified): Promise<IResult<null>> {\n return super.delete(entityOrId);\n }\n}\n","/* eslint-env browser */\nmodule.exports = typeof self == 'object' ? self.FormData : window.FormData;\n","import FormData from 'form-data';\nimport { Stream } from 'stream';\nimport { Service, IResult, IFetchResponse } from '../core';\nimport { IEvent } from './IEvent';\nimport { IEventBinary } from './IEventBinary';\n\nexport class EventBinaryService extends Service<IEventBinary> {\n protected baseUrl = 'event';\n protected listUrl = 'events';\n\n /**\n * Uploads an event binary.\n * @returns Response wrapped in [[IResult]]\n *\n * @param {Stream | Buffer | File | Blob} file file to upload.\n * @param {string | number | IEvent} eventOrId Event or Id of the Event.\n *\n * **Example**\n * ```typescript\n *\n * const file = Buffer.from('aaa');\n * const eventId: string | number = 123;\n *\n * (async () => {\n * const {data, res} = await eventBinaryService.upload(file, eventId);\n * })();\n * ```\n */\n async upload(\n file: Stream | Buffer | File | Blob,\n entityOrId: string | number | IEvent\n ): Promise<IResult<IEventBinary>> {\n const method = 'POST';\n const url = this.getDetailUrl(entityOrId);\n const body = new FormData();\n\n body.append('file', file);\n const headers = {\n accept: 'application/json'\n };\n const res = await this.fetch(url, { method, body, headers });\n const data = await res.json();\n return { res, data };\n }\n\n /**\n * Downloads the binary for a given event.\n * @returns Response wrapped in [[IFetchResponse]]\n *\n * @param {string | number | IEvent} eventOrId Event or Id of the Event.\n *\n * **Example**\n * ```typescript\n *\n * const eventId: string | number = 123;\n *\n * (async () => {\n * const res = await eventBinaryService.download(eventId);\n * })();\n */\n async download(entityOrId: string | number | IEvent): Promise<IFetchResponse> {\n const url = this.getDetailUrl(entityOrId);\n return await this.fetch(url);\n }\n\n /**\n * Removes the binary for a given event.\n * @returns Response wrapped in [[IResult]]\n *\n * @param {string | number | IEvent} eventOrId Event or Id of the Event.\n *\n * **Example**\n * ```typescript\n *\n * const eventId: string | number = 123;\n *\n * (async () => {\n * const {data, res} = await eventBinaryService.delete(eventId);\n * })();\n * ```\n */\n async delete(entityOrId: string | number | IEvent) {\n return super.delete(entityOrId);\n }\n\n protected getDetailUrl(entityOrId: string | number | IEvent): string {\n let id: string | number;\n if (typeof entityOrId === 'object' && entityOrId.id) {\n id = entityOrId.id;\n } else {\n id = entityOrId as string;\n }\n return `${this.listUrl}/${id}/binaries`;\n }\n}\n","import FormData from 'form-data';\nimport { Stream } from 'stream';\nimport { Service, IResult, IFetchResponse, IFetchOptions } from '../core';\nimport { IdReference } from './InventoryService';\nimport { IManagedObject, IManagedObjectBinary } from './IManagedObject';\n\nexport class InventoryBinaryService extends Service<IManagedObjectBinary> {\n protected baseUrl = 'inventory';\n protected listUrl = 'binaries';\n protected propertyName = 'managedObjects';\n\n /**\n * Uploads a file and creates a managed object with its metadata.\n * @param file A file to be uploaded.\n * @param managedObject An object containing metadata about the file.\n * Note that you can specify `fileType` and `fileName` in case `file` does not define them\n * but these two properties will be removed from `managedObject` before saving.\n */\n async create(\n file: Stream | Buffer | File | Blob,\n managedObject: Partial<IManagedObject> = {}\n ): Promise<IResult<IManagedObjectBinary>> {\n const method = 'POST';\n const url = this.listUrl;\n const body = new FormData();\n let fileName;\n let fileType;\n if (managedObject.fileName) {\n fileName = managedObject.fileName;\n delete managedObject.fileName;\n }\n if (managedObject.fileType) {\n fileType = managedObject.fileType;\n delete managedObject.fileType;\n }\n if (!fileName) {\n fileName = 'bin';\n }\n if (typeof File !== 'undefined' && file instanceof File) {\n fileName = file.name;\n fileType = file.type;\n }\n if (!managedObject.name) {\n managedObject.name = fileName;\n }\n if (!managedObject.type) {\n managedObject.type = fileType || 'c8y_upload';\n }\n body.append('file', file, fileName);\n body.append('object', JSON.stringify(managedObject));\n const headers = {\n accept: 'application/json'\n };\n const res = await this.fetch(url, { method, body, headers });\n const data = await res.json();\n return { res, data };\n }\n\n async list(filter: object = {}) {\n return super.list(filter);\n }\n\n async delete(managedObjectOrId: IdReference) {\n return super.delete(managedObjectOrId);\n }\n\n async download(managedObjectOrId: IdReference, init?: IFetchOptions): Promise<IFetchResponse> {\n const url = this.getDetailUrl(managedObjectOrId);\n return await this.fetch(url, init);\n }\n\n /**\n * Uploads a file and creates a managed object with its metadata. What's more, it invokes an upload progress callback.\n * @param file A file to be uploaded.\n * @param managedObject An object containing metadata about the file.\n * @param onProgress Event handler for progress update, invoked while the browser is uploading the file.\n */\n createWithProgress(\n file: Stream | Buffer | File | Blob,\n onProgress: EventListener,\n managedObject: Partial<IManagedObject> = {}\n ): XMLHttpRequest {\n const url = `/${this.baseUrl}/${this.listUrl}`;\n const method = 'POST';\n const body = new FormData();\n let fileName;\n let fileType;\n if (managedObject.fileName) {\n fileName = managedObject.fileName;\n delete managedObject.fileName;\n }\n if (managedObject.fileType) {\n fileType = managedObject.fileType;\n delete managedObject.fileType;\n }\n if (!fileName) {\n fileName = 'bin';\n }\n if (typeof File !== 'undefined' && file instanceof File) {\n fileName = file.name;\n fileType = file.type;\n }\n if (!managedObject.name) {\n managedObject.name = fileName;\n }\n if (!managedObject.type) {\n managedObject.type = fileType || 'c8y_upload';\n }\n body.append('file', file, fileName);\n body.append('object', JSON.stringify(managedObject));\n let bodyHeaders;\n\n if (typeof body.getHeaders === 'function') {\n bodyHeaders = body.getHeaders();\n }\n const headers = this.client.getFetchOptions().headers;\n Object.assign(\n headers,\n {\n accept: 'application/json'\n },\n bodyHeaders\n );\n\n const xhr = new XMLHttpRequest();\n xhr.open(method, url, true);\n for (const key in headers) {\n if (headers.hasOwnProperty(key)) {\n xhr.setRequestHeader(key, headers[key]);\n }\n }\n xhr.upload.addEventListener('progress', onProgress);\n\n let xhrBody: XMLHttpRequestBodyInit;\n if (typeof body.getBuffer === 'function') {\n xhrBody = body.getBuffer();\n } else {\n xhrBody = body as any;\n }\n xhr.send(xhrBody);\n\n return xhr;\n }\n\n getXMLHttpResponse(xhr): Promise<IResult<IManagedObjectBinary>> {\n return new Promise((res, rej) => {\n xhr.addEventListener('loadend', () => {\n xhr.readyState === 4 && (xhr.status === 200 || xhr.status === 201)\n ? res(JSON.parse(xhr.responseText))\n : rej(\n xhr.responseText ? { data: JSON.parse(xhr.responseText) } : 'Could not upload file.'\n );\n });\n });\n }\n\n /**\n * Gets binary managed object's id from its download or self URL.\n *\n * @param {string} url URL string.\n *\n * @returns {number} Binary managed object's id.\n *\n * **Example**\n * ```typescript\n *\n * const id = InventoryBinaryService.getIdFromUrl('http://mytenant.cumulocity.com/inventory/binaries/12345');\n * ```\n */\n getIdFromUrl(url: string): string {\n if (!!url) {\n const regexp = new RegExp(\n '\\\\/inventory\\\\/binaries\\\\/(\\\\d+)|\\\\/inventory\\\\/managedObjects\\\\/(\\\\d+)'\n );\n const matches = url.match(regexp);\n return matches && (matches[1] || matches[2]);\n }\n }\n}\n","import { IIdentified, Service, IResult, IResultList, IFetchClient, QueriesUtil } from '../core';\nimport { IManagedObject } from './IManagedObject';\nimport { InventoryBinaryService } from './InventoryBinaryService';\n\nimport { Realtime } from '../realtime';\n\n/**\n * Possible types of a child.\n */\nexport enum ChildType {\n ASSETS = 'childAssets',\n DEVICES = 'childDevices',\n ADDITIONS = 'childAdditions'\n}\n\n/**\n * IdReference is only a combined type of string | number | IIdentified\n */\nexport type IdReference = string | number | IIdentified;\n\n/**\n * This class allows for managing managed objects and different child types, see [[ChildType]].\n */\nexport class InventoryService extends Service<IManagedObject> {\n binary: InventoryBinaryService;\n queriesUtil: QueriesUtil;\n protected baseUrl = 'inventory';\n protected listUrl = 'managedObjects';\n protected propertyName = 'managedObjects';\n protected channel = '/managedobjects/*';\n protected inventoriesQueryParamName = 'query';\n protected devicesQueryParamName = 'q';\n\n constructor(client: IFetchClient, realtime?: Realtime) {\n super(client, realtime);\n this.queriesUtil = new QueriesUtil();\n this.binary = new InventoryBinaryService(client);\n }\n\n /**\n * Gets the details of managed object\n *\n * @param {IdReference} managedObjectOrId ManagedObject or Id of the ManagedObject.\n * @param {object} filter Filter object.\n *\n * @returns Response wrapped in [[IResult]]\n *\n * **Example**\n * ```typescript\n *\n * const managedObjId: number = 1;\n * const filter = { withChildren: false };\n *\n * (async () => {\n * const {data, res} = await inventoryService.detail(managedObjId, filter);\n * })();\n * ```\n */\n async detail(managedObjectOrId: IdReference, filter: object = {}) {\n return super.detail(managedObjectOrId, filter);\n }\n\n /**\n * Creates a new managed object.\n *\n * @param {Partial<IManagedObject>} managedObject\n *\n * @returns Response wrapped in [[IResult]]\n *\n * **Example**\n * ```typescript\n *\n * const partialManagedObj: Partial<IManagedObject> = {\n * customFragment: 'yourData'\n * };\n *\n * (async () => {\n * const {data, res} = await inventoryService.create(partialManagedObj);\n * })();\n * ```\n */\n async create(managedObject: Partial<IManagedObject>) {\n return super.create(managedObject);\n }\n\n /**\n * Updates managed object data.\n *\n * @param {Partial<IManagedObject>} managedObject Managed object is partially updatable.\n *\n * @returns Response wrapped in [[IResult]]\n *\n * **Example**\n * ```typescript\n *\n * const partialUpdateObject: Partial<IManagedObject> = {\n * customFragment: 'Changed data',\n * name: 'Name'\n * };\n *\n * (async () => {\n * const {data, res} = await inventoryService.update(partialUpdateObject);\n * })();\n * ```\n */\n async update(managedObject: Partial<IManagedObject>) {\n return super.update(managedObject);\n }\n\n /**\n * Gets the list of managed objects filtered by parameters.\n *\n * @returns Response wrapped in [[IResultList]]\n *\n * @param {object} filter Object containing filters for querying managed objects.\n *\n * **Example**\n * ```typescript\n *\n * const filter: object = {\n * pageSize: 100,\n * withTotalPages: true\n * };\n *\n * (async () => {\n * const {data, res, paging} = await inventoryService.list(filter);\n * })();\n * ```\n */\n async list(filter: object = {}) {\n return super.list(filter);\n }\n\n /**\n * Gets the list of all managed objects filtered and sorted by given query.\n *\n * @returns Response wrapped in [[IResultList]]\n *\n * @param {object} filter Object containing filters for querying managed objects.\n *\n * **Example**\n * ```typescript\n *\n * const filter: object = {\n * pageSize: 100,\n * withTotalPages: true\n * };\n *\n * const query = {\n * name: 'MY-NAM*'\n * }\n *\n * (async () => {\n * const {data, res, paging} = await inventoryService.listQuery(query, filter);\n * })();\n * ```\n */\n async listQuery(query, filter: object = {}) {\n filter[this.inventoriesQueryParamName] = this.queriesUtil.buildQuery(query);\n return super.list(filter);\n }\n\n /**\n * Gets the list of all devices filtered and sorted by given query.\n *\n * @returns Response wrapped in [[IResultList]]\n *\n * @param {object} filter Object containing filters for querying devices.\n *\n * **Example**\n * ```typescript\n *\n * const filter: object = {\n * pageSize: 100,\n * withTotalPages: true\n * };\n *\n * const query = {\n * name: 'MY-NAM*'\n * }\n *\n * (async () => {\n * const {data, res, paging} = await inventoryService.listQueryDevices(query, filter);\n * })();\n * ```\n */\n async listQueryDevices(query, filter: object = {}) {\n filter[this.devicesQueryParamName] = this.queriesUtil.buildQuery(query);\n return super.list(filter);\n }\n\n /**\n * Removes managed object with given id.\n *\n * @returns Response wrapped in [[IResult]]\n *\n * @param {IdReference} managedObjectOrId ManagedObject or Id of the ManagedObject.\n * @param {object} params Additional query params.\n *\n * **Example**\n * ```typescript\n *\n * const managedObjectId: number = 1;\n * const params: any = {\n * cascade: true\n * }\n *\n * (async () => {\n * const {data, res} = await inventoryService.delete(managedObjectId, params);\n * })();\n * ```\n */\n async delete(managedObjectOrId: IdReference, params: any = {}) {\n return super.delete(managedObjectOrId, params);\n }\n\n /**\n * Gets a list of child additions from a given managed object (parent)\n *\n * @returns Response wrapped in [[IResultList]]\n *\n * @param {IdReference} parentReference\n * @param {object} filter\n *\n * **Example**\n * ```typescript\n * const parentReferenceId: IdReference = 1;\n *\n * const filter: object = {\n * pageSize: 100,\n * withTotalPages: true\n * };\n *\n * (async () => {\n * const {data, res, paging} = await inventoryService.childAdditionsList(parentReferenceId, filter);\n * })();\n * ```\n */\n async childAdditionsList(parentReference: IdReference, filter: object = {}) {\n return this.listChildren(ChildType.ADDITIONS, parentReference, filter);\n }\n\n /**\n * Creates a new managed object as child addition to another managed object (parent)\n *\n * @returns Response wrapped in [[IResult]]\n *\n * @param {Partial<IManagedObject>} managedObject\n * @param {IdReference} parentReference\n *\n * **Example**\n * ```typescript\n *\n * const mOAsChildAddition: Partial<IManagedObject> = {\n * name: 'Child addition MO',\n * type: 'new type',\n * ...\n * };\n *\n * // This is the identifier of the managed object which should be the parent of\n * // mOAsChildAddition, see above.\n * const parentReferenceId: number = 1;\n *\n * (async () => {\n * const {data, res} = await inventoryService.childAdditionsCreate(mOAsChildAddition, parentReferenceId);\n * })();\n * ```\n */\n async childAdditionsCreate(managedObject: Partial<IManagedObject>, parentReference: IdReference) {\n return this.createChild(ChildType.ADDITIONS, managedObject, parentReference);\n }\n\n /**\n * Adds an existing managed object as child addition to another managed object (parent)\n *\n * @returns Response wrapped in [[IResult]]\n *\n * @param {IdReference} childReference\n * @param {IdReference} parentReference\n *\n * **Example**\n * ```typescript\n *\n * const childRef: number = 2;\n * const parentReferenceId: number = 1;\n *\n * (async () => {\n * const {data, res} = await inventoryService.childAdditionsCreate(childRef, parentReferenceId);\n * })();\n * ```\n */\n async childAdditionsAdd(childReference: IdReference, parentReference: IdReference) {\n return this.addChild(ChildType.ADDITIONS, childReference, parentReference);\n }\n\n /**\n * Removes an existing managed object as child addition from another managed object (parent)\n *\n * @returns Response wrapped in [[IResult]]\n *\n * @param {IdReference} childReference\n * @param {IdReference} parentReference\n *\n * **Example**\n * ```typescript\n *\n * const childRef: number = 2;\n * const parentReferenceId: number = 1;\n *\n * (async () => {\n * const {data, res} = await inventoryService.childAdditionsRemove(childRef, parentReferenceId);\n * })();\n * ```\n */\n async childAdditionsRemove(childReference: IdReference, parentReference: IdReference) {\n return this.removeChild(ChildType.ADDITIONS, childReference, parentReference);\n }\n\n /**\n * Gets a list of child assets from a given managed object (parent)\n *\n * @returns Response wrapped in [[IResultList]]\n *\n * @param {IdReference} parentReference\n * @param {object} filter\n *\n * **Example**\n * ```typescript\n *\n * const parentReferenceId: IdReference = 1;\n *\n * const filter: object = {\n * pageSize: 100,\n * withTotalPages: true\n * };\n *\n * (async () => {\n * const {data, res, paging} = await inventoryService.childAssetsList(parentReferenceId, filter);\n * })();\n * ```\n */\n async childAssetsList(parentReference: IdReference, filter: object = {}) {\n return this.listChildren(ChildType.ASSETS, parentReference, filter);\n }\n\n /**\n * Creates a new managed object as child asset to another managed object (parent)\n *\n * @returns Response wrapped in [[IResult]]\n *\n * @param {Partial<IManagedObject>} managedObject\n * @param {IdReference} parentReference\n *\n * **Example**\n * ```typescript\n *\n * const mOAsChildAsset: Partial<IManagedObject> = {\n * name: 'Child asset MO',\n * type: 'new type',\n * ...\n * };\n *\n * // This is the identifier of the managed object which should be the parent of\n * // mOAsChildAsset, see above.\n * const parentReferenceId: number = 1;\n *\n * (async () => {\n * const {data, res} = await inventoryService.childAdditionsCreate(mOAsChildAddition, parentReferenceId);\n * })();\n * ```\n */\n async childAssetsCreate(managedObject: Partial<IManagedObject>, parentReference: IdReference) {\n return this.createChild(ChildType.ASSETS, managedObject, parentReference);\n }\n\n /**\n * Adds an existing managed object as child asset to another managed object (parent)\n *\n * @returns Response wrapped in [[IResult]]\n *\n * @param {IdReference} childReference\n * @param {IdReference} parentReference\n *\n * **Example**\n * ```typescript\n *\n * const childRef: number = 2;\n * const parentReferenceId: number = 1;\n *\n * (async () => {\n * const {data, res} = await inventoryService.childAssetsAdd(childRef, parentReferenceId);\n * })();\n * ```\n */\n async childAssetsAdd(childReference: IdReference, parentReference: IdReference) {\n return this.addChild(ChildType.ASSETS, childReference, parentReference);\n }\n /**\n * Adds bulk of existing managed objects as child assets to another managed object (parent).\n *\n * @returns Response wrapped in array of [[IResult]]\n *\n * @param {IdReference[]} childReference List of existing managed objects IDs that should be added to another managed object (parent).\n * @param {IdReference} parentReference\n *\n * **Example**\n * ```typescript\n *\n * const childAssetsRefIds: string[] = ['2', '3'];\n * const parentReferenceId: number = 1;\n *\n * (async () => {\n * const {data, res} = await inventoryService.childAssetsBulkAdd(childAssetsRefIds, parentReferenceId);\n * })();\n * ```\n */\n async childAssetsBulkAdd(childReference: IdReference[], parentReference: IdReference) {\n return this.addChildBulk(ChildType.ASSETS, childReference, parentReference);\n }\n\n /**\n * Removes an existing managed object as child asset from another managed object (parent)\n *\n * @returns Response wrapped in [[IResult]]\n *\n * @param {IdReference} childReference\n * @param {IdReference} parentReference\n *\n * **Example**\n * ```typescript\n *\n * const childRef: number = 2;\n * const parentReferenceId: number = 1;\n *\n * (async () => {\n * const {data, res} = await inventoryService.childAssetsRemove(childRef, parentReferenceId);\n * })();\n * ```\n */\n async childAssetsRemove(childReference: IdReference, parentReference: IdReference) {\n return this.removeChild(ChildType.ASSETS, childReference, parentReference);\n }\n\n /**\n * Gets a list of child devices from a given managed object (parent)\n *\n * @returns Response wrapped in [[IResultList]]\n *\n * @param {IdReference} parentReference\n * @param {object} filter\n *\n * **Example**\n * ```typescript\n *\n * const parentReferenceId: IdReference = 1;\n *\n * const filter: object = {\n * pageSize: 100,\n * withTotalPages: true\n * };\n *\n * (async () => {\n * const {data, res, paging} = await inventoryService.childDevicesList(parentReferenceId, filter);\n * })();\n * ```\n */\n async childDevicesList(parentReference: IdReference, filter: object = {}) {\n return this.listChildren(ChildType.DEVICES, parentReference, filter);\n }\n\n /**\n * Creates a new managed object as child device to another managed object (parent)\n *\n * @returns Response wrapped in [[IResult]]\n *\n * @param {Partial<IManagedObject>} managedObject\n * @param {IdReference} parentReference\n *\n * **Example**\n * ```typescript\n *\n * const mOAsChildDevice: Partial<IManagedObject> = {\n * name: 'Child device MO',\n * type: 'new type',\n * ...\n * };\n *\n * // This is the identifier of the managed object which should be the parent of\n * // mOAsChildDevice, see above.\n * const parentReferenceId: number = 1;\n *\n * (async () => {\n * const {data, res} = await inventoryService.childDevicesCreate(mOAsChildDevice, parentReferenceId);\n * })();\n * ```\n */\n async childDevicesCreate(managedObject: Partial<IManagedObject>, parentReference: IdReference) {\n return this.createChild(ChildType.DEVICES, managedObject, parentReference);\n }\n\n /**\n * Adds an existing managed object as child device to another managed object (parent)\n *\n * @returns Response wrapped in [[IResult]]\n *\n * @param {IdReference} childReference\n * @param {IdReference} parentReference\n *\n * **Example**\n * ```typescript\n *\n * const childRef: number = 2;\n * const parentReferenceId: number = 1;\n *\n * (async () => {\n * const {data, res} = await inventoryService.childDevicesAdd(childRef, parentReferenceId);\n * })();\n * ```\n */\n async childDevicesAdd(childReference: IdReference, parentReference: IdReference) {\n return this.addChild(ChildType.DEVICES, childReference, parentReference);\n }\n\n /**\n * Removes an existing managed object as child device from another managed object (parent)\n *\n * @returns Response wrapped in [[IResult]]\n *\n * @param {IdReference} childReference\n * @param {IdReference} parentReference\n *\n * **Example**\n * ```typescript\n *\n * const childRef: number = 2;\n * const parentReferenceId: number = 1;\n *\n * (async () => {\n * const {data, res} = await inventoryService.childDevicesRemove(childRef, parentReferenceId);\n * })();\n * ```\n */\n async childDevicesRemove(childReference: IdReference, parentReference: IdReference) {\n return this.removeChild(ChildType.DEVICES, childReference, parentReference);\n }\n\n /**\n * Gets an array of measurement fragments supported by the specified managedObject.\n * e.g. [\"c8y_Temperature\", \"c8y_Humidity\"]\n *\n * @returns array of supported measurement fragments\n *\n * @param {IdReference} managedObjectOrId\n */\n async getSupportedMeasurements(managedObjectOrId: IdReference): Promise<string[]> {\n return this.getSupportedMeasurementDetails(managedObjectOrId, 'supportedMeasurements');\n }\n\n /**\n * Gets an array of measurement series supported by the specified managedObject.\n * e.g. [\"c8y_Temperature.T\", \"c8y_Humidity.H\"]\n *\n * @returns array of supported measurement series\n *\n * @param {IdReference} managedObjectOrId\n */\n async getSupportedSeries(managedObjectOrId: IdReference): Promise<string[]> {\n return this.getSupportedMeasurementDetails(managedObjectOrId, 'supportedSeries');\n }\n\n /**\n * Gets an array of measurement series and fragments supported by the specified managedObject.\n *\n * @returns array of supported measurement series and fragments\n *\n * @param {IdReference} managedObjectOrId\n */\n async getMeasurementsAndSeries(managedObjectOrId: IdReference): Promise<\n Array<{\n fragment: string;\n series: string;\n }>\n > {\n const [supportedMeasurements, supportedSeries] = await Promise.all([\n this.getSupportedMeasurements(managedObjectOrId),\n this.getSupportedSeries(managedObjectOrId)\n ]);\n\n // sort by longest measurement fragment first\n const sortedSupportedMeasurements = supportedMeasurements.sort((a, b) => b.length - a.length);\n\n return supportedSeries\n .map(s => {\n const fragment = sortedSupportedMeasurements.find(m => s.indexOf(`${m}.`) === 0);\n const series = s.replace(`${fragment}.`, '');\n return {\n fragment,\n series\n };\n })\n .filter(obj => !!obj.fragment);\n }\n\n /**\n * Gets a list of KPIs (data point library entries) matching a given managed object\n *\n * @returns Response wrapped in [[IResultList]]\n *\n * @param {IdReference} parentReference\n * @param {object} filter\n */\n async assetKPIsList(parentReference: IdReference, filter: object = {}) {\n return this.listKPIs(parentReference, filter);\n }\n\n protected async listKPIs(\n parentReference: IdReference,\n filter: object = {}\n ): Promise<IResultList<IManagedObject>> {\n const headers = { accept: 'application/json' };\n const url = this.getChildrenUrl('kpis', parentReference);\n const res = await this.fetch(url, this.changeFetchOptions({ headers, params: filter }, url));\n const json = await res.json();\n const data = json[this.propertyName];\n const paging = this.getPaging(json, filter);\n return { res, data, paging };\n }\n\n protected onBeforeUpdate(objWithId: Partial<IManagedObject>): Partial<IManagedObject> {\n delete objWithId.lastUpdated;\n return objWithId;\n }\n\n protected onBeforeCreate(managedObject: Partial<IManagedObject>): Partial<IManagedObject> {\n delete managedObject.id;\n delete managedObject.lastUpdated;\n return managedObject;\n }\n\n private getChildrenUrl(type: ChildType | string, parentReference: IdReference): string {\n return `${this.getDetailUrl(parentReference)}/${type}`;\n }\n\n private getChildUrl(\n type: ChildType,\n childReference: IdReference,\n parentReference: IdReference\n ): string {\n const childId = this.getIdString(childReference);\n return `${this.getChildrenUrl(type, parentReference)}/${childId}`;\n }\n\n private async listChildren(\n type: ChildType,\n parentReference: IdReference,\n filter: object = {}\n ): Promise<IResultList<IManagedObject>> {\n const headers = { 'content-type': 'application/json' };\n const url = this.getChildrenUrl(type, parentReference);\n const res = await this.fetch(url, { headers, params: filter });\n const json = await res.json();\n const data = json.references.map(ref => ref.managedObject);\n const paging = this.getPaging(json, filter);\n paging.list = pagingFilter => this.listChildren(type, parentReference, pagingFilter);\n return { res, data, paging };\n }\n\n private async createChild(\n type: ChildType,\n managedObject: Partial<IManagedObject>,\n parentReference: IdReference\n ): Promise<IResult<IIdentified>> {\n const url = this.getChildrenUrl(type, parentReference);\n const method = 'POST';\n const body = JSON.stringify(this.onBeforeCreate(managedObject));\n const headers = { 'content-type': this.mimeType('managedObject'), accept: 'application/json' };\n const res = await this.fetch(url, { method, body, headers });\n const data = await res.json();\n return { res, data };\n }\n\n private async addChild(\n type: ChildType,\n childReference: IdReference,\n parentReference: IdReference\n ): Promise<IResult<IIdentified>> {\n const url = this.getChildrenUrl(type, parentReference);\n const method = 'POST';\n const childId = this.getIdString(childReference);\n const body = JSON.stringify({ managedObject: { id: String(childId) } });\n const headers = {\n accept: 'application/json',\n 'content-type': this.mimeType('managedObjectReference')\n };\n const res = await this.fetch(url, { method, body, headers });\n let data = await res.json();\n data = data.managedObject;\n return { res, data };\n }\n\n private async addChildBulk(\n type: ChildType,\n childReferenceArray: IdReference[],\n parentReference: IdReference\n ): Promise<IResultList<IIdentified>> {\n const url = this.getChildrenUrl(type, parentReference);\n const method = 'POST';\n const references = childReferenceArray.map(childId => ({\n managedObject: {\n id: this.getIdString(childId)\n }\n }));\n const body = JSON.stringify({\n references\n });\n const headers = {\n accept: 'application/json',\n 'content-type': this.mimeType('managedObjectReferenceCollection')\n };\n const res = await this.fetch(url, { method, body, headers });\n const data = (await res.json()).references;\n return { res, data: data.map(obj => obj.managedObject) };\n }\n\n private async removeChild(\n type: ChildType,\n childReference: IdReference,\n parentReference: IdReference\n ): Promise<IResult<null>> {\n const childId = this.getIdString(childReference);\n const url = `${this.getChildrenUrl(type, parentReference)}/${childId}`;\n const method = 'DELETE';\n const headers = { accept: 'application/json' };\n const res = await this.fetch(url, { method, headers });\n const data = null;\n return { res, data };\n }\n\n private async getSupportedMeasurementDetails(\n managedObjectOrId: IdReference,\n type: 'supportedMeasurements' | 'supportedSeries' = 'supportedSeries'\n ): Promise<string[]> {\n const url = `${this.getDetailUrl(managedObjectOrId)}/${type}`;\n this.getIdString(managedObjectOrId);\n const headers = { accept: 'application/json' };\n const res = await this.fetch(url, { headers });\n const data = await res.json();\n return data.c8y_SupportedMeasurements || data.c8y_SupportedSeries;\n }\n}\n","import { IIdentified, Service, IResult } from '../core';\nimport { IMeasurement, IMeasurementCreate } from './IMeasurement';\nimport { ISeriesFilter } from './ISeriesFilter';\nimport { ISeries } from './ISeries';\n\n/**\n * This class allows for managing measurements.\n */\nexport class MeasurementService extends Service<IMeasurement> {\n protected baseUrl = 'measurement';\n protected listUrl = 'measurements';\n protected propertyName = 'measurements';\n protected channel = '/measurements/*';\n\n /**\n * Gets the details of selected measurement.\n *\n * @param {string|number|IIdentified} entityOrId Entity or Id of the entity.\n *\n * @returns Response wrapped in [[IResult]]\n *\n * @deprecated As of version 10.16.0.0 and the usage of the time series database,\n * reading a single measurement via id is not supported any more.\n *\n * **Example**\n * ```typescript\n *\n * const measurementId: number = 1;\n *\n * (async () => {\n * const {data, res} = await measurementService.detail(measurementId);\n * })();\n * ```\n */\n async detail(entityOrId: string | number | IIdentified) {\n return super.detail(entityOrId);\n }\n\n /**\n * Creates a new measurement.\n *\n * @param {Partial<IMeasurementCreate>} entity At least sourceId is mandantory.\n *\n * @returns Response wrapped in [[IResult]]\n *\n * **Example**\n * ```typescript\n *\n * const mandantoryObject: Partial<IMeasurementCreate> = {\n * sourceId: device.id,\n * fragment: { series: { unit: '%', value: 51 } },\n * };\n *\n * (async () => {\n * const {data, res} = await measurementService.create(mandantoryObject);\n * })();\n * ```\n */\n async create(entity: Partial<IMeasurementCreate>) {\n return super.create(this.onBeforeCreate(entity));\n }\n\n /**\n * Gets the list of measurements filtered by parameters.\n *\n * @returns Response wrapped in [[IResultList]]\n *\n * @param {object} filter Object containing filters for querying measurements.\n *\n * **Example**\n * ```typescript\n *\n * const filter: object = {\n * pageSize: 100,\n * withTotalPages: true\n * };\n *\n * (async () => {\n * const {data, res, paging} = await measurementService.list(filter);\n * })();\n * ```\n */\n async list(filter: object = {}) {\n return super.list(filter);\n }\n\n /**\n * Removes a measurement with given id.\n *\n * @returns Response wrapped in [[IResult]]\n *\n * @param {string | number | IIdentified} entityOrId\n *\n * @deprecated As of version 10.16.0.0 and the usage of the time series database,\n * deleting a single measurement via id is not supported any more.\n *\n * **Example**\n * ```typescript\n *\n * const id: number = 1;\n *\n * (async () => {\n * const {data, res} = await measurementService.delete(id);\n * })();\n * ```\n */\n async delete(entityOrId: string | number | IIdentified) {\n return super.delete(entityOrId);\n }\n\n /**\n * Gets the list of series in a measurement filtered by parameters.\n *\n * @returns Response wrapped in [[IResult]]\n *\n * @param {object} filter Object containing filters for querying measurements.\n *\n * **Example**\n * ```typescript\n *\n * const filter: object = {\n * dateFrom: '2018-02-06T10:43:55.077Z',\n * dateTo: '2018-02-06T10:50:55.077Z',\n * source: device.id\n * };\n *\n * (async () => {\n * const {data, res} = await measurementService.listSeries(filter);\n * })();\n * ```\n */\n async listSeries(params: ISeriesFilter): Promise<IResult<ISeries>> {\n const url = `${this.baseUrl}/${this.listUrl}/series`;\n const res = await this.client.fetch(url, { params });\n const data = await res.json();\n return { res, data };\n }\n\n protected onBeforeCreate(entity: Partial<IMeasurementCreate>) {\n if (!entity.time) {\n entity.time = new Date().toISOString();\n }\n if (!entity.type) {\n entity.type = 'c8y_Measurement';\n }\n if (entity.sourceId) {\n const { sourceId } = entity;\n delete entity.sourceId;\n if (!entity.source) {\n entity.source = {\n id: String(sourceId)\n };\n }\n }\n return entity;\n }\n}\n","export enum aggregationType {\n MINUTELY = 'MINUTELY',\n HOURLY = 'HOURLY',\n DAILY = 'DAILY'\n}\n\n/**\n * This interface specifies all fragments which can be used\n * to filter for specific series.\n */\nexport interface ISeriesFilter {\n /**\n * The ManagedObject which is the source of these series\n */\n source: number | string;\n /**\n * From which date the series should be gathered\n */\n dateFrom: string | Date;\n /**\n * To which date the series should be gathered\n */\n dateTo: string | Date;\n /**\n * For which aggregation it should filter, see [[aggregationType]]\n */\n aggregationType?: aggregationType;\n /**\n * The series type and name\n *\n * **Example**\n * ```typescript\n *\n * const series: string[] = ['c8y_AccelerationMeasurement.acceleration', '...'];\n * ```\n */\n series?: string | string[];\n}\n","import { IIdentified, Service, IResult, IResultList } from '../core';\nimport { IAlarm } from './IAlarm';\n\n/**\n * This class allows for managing alarms.\n */\nexport class AlarmService extends Service<IAlarm> {\n protected baseUrl = 'alarm';\n protected listUrl = 'alarms';\n protected propertyName = 'alarms';\n protected channel = '/alarms/*';\n\n /**\n * Gets the details of selected alarms.\n *\n * @param {string|number|IIdentified} entityOrId Entity or Id of the entity.\n *\n * @returns Response wrapped in [[IResult]]\n *\n * **Example**\n * ```typescript\n *\n * const alarmId: number = 1;\n *\n * (async () => {\n * const {data, res} = await alarmService.detail(alarmId);\n * })();\n * ```\n */\n async detail(entityOrId: string | number | IIdentified): Promise<IResult<IAlarm>> {\n return super.detail(entityOrId);\n }\n\n /**\n * Creates a new alarm.\n *\n * @param {IAlarm} entity Alarm object with mandantory fragments.\n *\n * @returns Response wrapped in [[IResult]]\n *\n * **Example**\n * ```typescript\n *\n * const mandantoryObject: IAlarm = {\n * severity: Severity.CRITICAL,\n * source: device,\n * text: 'I am an Alarm!',\n * time: '2018-05-02T10:08:00Z',\n * type: 'device-type-here',\n * };\n *\n * (async () => {\n * const {data, res} = await alarmService.create(mandantoryObject);\n * })();\n * ```\n */\n async create(entity: IAlarm): Promise<IResult<IAlarm>> {\n return super.create(entity);\n }\n\n /**\n * Updates alarm data.\n *\n * @param {Partial<IAlarm>} entity Alarm is partially updatable.\n *\n * @returns Response wrapped in [[IResult]]\n *\n * **Example**\n * ```typescript\n *\n * const partialUpdateObject: Partial<IAlarm> = {\n * severity: Severity.MINOR,\n * source: device,\n * text: 'Changed Alarm!'\n * };\n *\n * (async () => {\n * const {data, res} = await alarmService.update(partialUpdateObject);\n * })();\n * ```\n */\n async update(entity: Partial<IAlarm>): Promise<IResult<IAlarm>> {\n return super.update(entity);\n }\n\n /**\n * Gets the list of alarms filtered by parameters.\n *\n * @returns Response wrapped in [[IResultList]]\n *\n * @param {object} filter Object containing filters for querying alarms.\n *\n * **Example**\n * ```typescript\n *\n * const filter: object = {\n * severity: Severity.MAJOR,\n * pageSize: 100,\n * withTotalPages: true\n * };\n *\n * (async () => {\n * const {data, res, paging} = await alarmService.list(filter);\n * })();\n * ```\n */\n async list(filter: object = {}): Promise<IResultList<IAlarm>> {\n return super.list(filter);\n }\n}\n","import { gettext } from '../gettext';\n\n/**\n * A specific alarm can have one of the following states\n */\nexport enum AlarmStatus {\n ACKNOWLEDGED = gettext('ACKNOWLEDGED'),\n CLEARED = gettext('CLEARED'),\n ACTIVE = gettext('ACTIVE')\n}\n","import { IIdentified, Service, IResult, IResultList } from '../core';\nimport { IOperation } from './IOperation';\n\n/**\n * This class allows for managing operations on a device.\n */\nexport class OperationService extends Service<IOperation> {\n protected baseUrl = 'devicecontrol';\n protected listUrl = 'operations';\n protected propertyName = 'operations';\n\n /**\n * Gets the details of selected operation.\n *\n * @param {string|number|IIdentified} entityOrId Entity or Id of the entitytabs.service.ts.\n *\n * @returns Response wrapped in [[IResult]]\n *\n * **Example**\n * ```typescript\n *\n * const operationId: number = 1;\n *\n * (async () => {\n * const {data, res} = await operationService.detail(operationId);\n * })();\n * ```\n */\n async detail(entityOrId: string | number | IIdentified): Promise<IResult<IOperation>> {\n return super.detail(entityOrId);\n }\n\n /**\n * Creates a new operation.\n *\n * @param {IOperation} entity Operation object with mandantory fragments.\n *\n * @returns Response wrapped in [[IResult]]\n *\n * **Example**\n * ```typescript\n *\n * const mandantoryObject: IOperation = {\n * com_cumulocity_model_WebCamDevice: {\n * name: 'take picture',\n * parameters: {\n * duration: '5s',\n * quality: 'HD'\n * }\n * },\n * deviceId: device.id,\n * };\n *\n * (async () => {\n * const {data, res} = await operationService.create(mandantoryObject);\n * })();\n * ```\n */\n async create(entity: IOperation): Promise<IResult<IOperation>> {\n return super.create(entity);\n }\n\n /**\n * Updates operation data.\n *\n * @param {Partial<IOperation>} entity Operation is partially updatable.\n *\n * @returns Response wrapped in [[IResult]]\n *\n * **Example**\n * ```typescript\n *\n * const partialUpdateObject: Partial<IOperation> = {\n * com_cumulocity_model_WebCamDevice: {\n * name: 'take picture',\n * parameters: {\n * duration: '2s',\n * quality: 'HD',\n * ratio: '16:9'\n * }\n * },\n * deviceId: device.id,\n * };\n *\n * (async () => {\n * const {data, res} = await operationService.update(partialUpdateObject);\n * })();\n * ```\n */\n async update(entity: Partial<IOperation>): Promise<IResult<IOperation>> {\n return super.update(entity);\n }\n\n /**\n * Gets the list of operations filtered by parameters.\n *\n * @returns Response wrapped in [[IResultList]]\n *\n * @param {object} filter Object containing filters for querying operations.\n *\n * **Example**\n * ```typescript\n *\n * const filter: object = {\n * pageSize: 100,\n * withTotalPages: true\n * };\n *\n * (async () => {\n * const {data, res, paging} = await operationService.list(filter);\n * })();\n * ```\n */\n async list(filter: object = {}): Promise<IResultList<IOperation>> {\n return super.list(filter);\n }\n}\n","import { IIdentified, Service, IResult } from '../core';\nimport { IOperationBulk } from './IOperationBulk';\n\n/**\n * This class allows for managing bulk operations.\n */\nexport class OperationBulkService extends Service<IOperationBulk> {\n protected baseUrl = 'devicecontrol';\n protected listUrl = 'bulkoperations';\n protected propertyName = 'bulkOperations';\n\n /**\n * Gets the details of selected bulk operation.\n *\n * @param {string|number|IIdentified} entityOrId Entity or Id of the entity.\n *\n * @returns Response wrapped in [[IResult]]\n *\n * **Example**\n * ```typescript\n *\n * const bulkOperationId: number = 1;\n *\n * (async () => {\n * const {data, res} = await operationBulkService.detail(bulkOperationId);\n * })();\n * ```\n */\n async detail(operationOrId: string | number | IIdentified) {\n return super.detail(operationOrId);\n }\n\n /**\n * Creates a new operation.\n *\n * @param {Partial<IOperationBulk>} operation Operation object with mandantory fragments.\n *\n * @returns Response wrapped in [[IResult]]\n *\n * **Example**\n * ```typescript\n *\n * const mandantoryObject: Partial<IOperationBulk> = {\n * creationRamp: 15,\n * groupId: '149044',\n * operationPrototype: {\n * c8y_Restart: {},\n * description: 'Restart device',\n * deviceId: device.id,\n * status: 'PENDING'\n * },\n * startDate: '2018-02-15T16:01:00.000Z'\n * };\n *\n * (async () => {\n * const {data, res} = await operationBulkService.create(mandantoryObject);\n * })();\n * ```\n */\n async create(operation: Partial<IOperationBulk>) {\n return super.create(operation);\n }\n\n /**\n * Updates a new operation.\n *\n * @param {Partial<IOperationBulk>} operation Operation object.\n *\n * @returns Response wrapped in [[IResult]]\n *\n * **Example**\n * ```typescript\n *\n * const updateObject: Partial<IOperationBulk> = {\n * creationRamp: 15,\n * groupId: '149044',\n * operationPrototype: {\n * c8y_Restart: {},\n * description: 'Restart device',\n * deviceId: device.id,\n * status: 'PENDING'\n * },\n * startDate: '2018-02-15T16:01:00.000Z'\n * };\n *\n * (async () => {\n * const {data, res} = await operationBulkService.update(updateObject);\n * })();\n * ```\n */\n async update(entity: Partial<IOperationBulk>) {\n return super.update(entity);\n }\n\n /**\n * Gets the list of bulk operations filtered by parameters.\n *\n * @returns Response wrapped in [[IResultList]]\n *\n * @param {object} filter Object containing filters for querying alarms.\n *\n * **Example**\n * ```typescript\n *\n * const filter: object = {\n * pageSize: 100,\n * withTotalPages: true\n * };\n *\n * (async () => {\n * const {data, res, paging} = await operationBulkService.list(filter);\n * })();\n * ```\n */\n async list(filter: object = {}) {\n return super.list(filter);\n }\n\n /**\n * Removes an bulk operation with given id.\n *\n * @returns Response wrapped in [[IResult]]\n *\n * @param {string | number | IIdentified):} operationOrId Operation object or id.\n *\n * **Example**\n * ```typescript\n *\n * const id: number = 1;\n *\n * (async () => {\n * const {data, res} = await operationBulkService.delete(id);\n * })();\n * ```\n */\n async delete(operationOrId: string | number | IIdentified): Promise<IResult<null>> {\n return super.delete(operationOrId);\n }\n}\n","import { gettext } from '../gettext';\r\n\r\n/**\r\n * A bulk operation can have one of the following states.\r\n */\r\nexport enum OperationBulkStatus {\r\n ACTIVE = gettext('ACTIVE'),\r\n IN_PROGRESS = gettext('IN_PROGRESS'),\r\n COMPLETED = gettext('COMPLETED'),\r\n DELETED = gettext('DELETED')\r\n}\r\n","import { gettext } from '../gettext';\r\n\r\n/**\r\n * A bulk operation can have one of the following general statuses.\r\n */\r\nexport enum OperationBulkGeneralStatus {\r\n SCHEDULED = gettext('SCHEDULED'),\r\n EXECUTING = gettext('EXECUTING'),\r\n EXECUTING_WITH_ERROR = gettext('EXECUTING_WITH_ERROR'),\r\n CANCELED = gettext('CANCELED'),\r\n FAILED = gettext('FAILED'),\r\n SUCCESSFUL = gettext('SUCCESSFUL'),\r\n DELETED = gettext('DELETED'),\r\n INCORRECT = gettext('INCORRECT')\r\n}\r\n","import { gettext } from '../gettext';\n\n/**\n * An Operation can have one of the following states.\n */\nexport enum OperationStatus {\n PENDING = gettext('PENDING'),\n EXECUTING = gettext('EXECUTING'),\n SUCCESSFUL = gettext('SUCCESSFUL'),\n FAILED = gettext('FAILED')\n}\n","import { Service, IResult, IResultList } from '../core';\nimport { ITenant } from './ITenant';\nimport { ICurrentTenant } from './ICurrentTenant';\nimport { ITfaSettings } from './ITfaSettings';\nimport { IApplication } from '../application';\n\n/**\n * @description\n * This service allows for managing tenants.\n */\nexport class TenantService extends Service<ITenant> {\n protected baseUrl = 'tenant';\n protected listUrl = 'tenants';\n protected currentTenantUrl = 'currentTenant';\n protected propertyName = 'tenants';\n protected fetchOptions = {\n method: 'PUT',\n body: '{}',\n headers: { 'content-type': 'application/json', accept: 'application/json' }\n };\n\n /**\n * Get a representation of a tenant.\n *\n * @param {string|number|IIdentified} entityOrId Tenant's id or tenant object.\n *\n * @returns Returns promise object that is resolved with the IIdentified wrapped by IResult.\n *\n * **Example**\n * ```typescript\n *\n * const tenantId: number = 1;\n *\n * (async () => {\n * const {data, res} = await tenantService.detail(tenantId);\n * })();\n * ```\n *\n * Required role: ROLE_TENANT_MANAGEMENT_READ<br><br>\n * User password is never returned in GET response. Authentication mechanism is provided by another interface.\n */\n async detail(entityOrId: string | number | ITenant): Promise<IResult<ITenant>> {\n return super.detail(entityOrId);\n }\n\n /**\n * Creates a new tenant.\n *\n * @param {IIdentified} entity Tenant object.\n *\n * @returns {IResult<IIdentified>} Returns promise object that is resolved with the details of newly created tenant.\n *\n * **Example**\n * ```typescript\n *\n * const tenantObject = {\n * id: \"sample_tenant\",\n * company: \"sample_company\",\n * domain: \"sample_domain.com\",\n * contactName: \"Mr. Doe\",\n * ...\n * };\n *\n * (async () => {\n * const {data, res} = await tenantService.create(tenantObject);\n * })();\n * ```\n *\n * Required role: ROLE_TENANT_MANAGEMENT_ADMIN or ROLE_TENANT_MANAGEMENT_CREATE<br><br>\n * Note that creating a tenant with adminName, adminPass and adminEmail, creates an admin user with these settings.\n * For the tenant id SQL keywords (e.g., select, cross, where) are not allowed.\n */\n async create(entity: ITenant): Promise<IResult<ITenant>> {\n return super.create(entity);\n }\n\n /**\n * Updates tenant data.\n *\n * @param {IIdentified} entity Tenant is partially updatable.\n *\n * @returns {IResult<IIdentified>} Returns promise object that is resolved with the saved tenant object.\n *\n * **Example**\n * ```typescript\n *\n * const partialUpdateObject: IIdentified = {\n * adminName : \"newAdmin\"\n * ...\n * }\n *\n * (async () => {\n * const {data, res} = await tenantService.update(partialUpdateObject);\n * })();\n * ```\n *\n * Required role: ROLE_TENANT_MANAGEMENT_ADMIN or ROLE_TENANT_MANAGEMENT_UPDATE<br><br>\n * Note that updating adminPass and adminEmail updates these settings in the admin user of the tenant.\n * Updating adminName has no effect.\n */\n async update(entity: ITenant): Promise<IResult<ITenant>> {\n return super.update(entity);\n }\n\n /**\n * Gets the list of tenants filtered by parameters.\n *\n * @param {object} filter Object containing filters for querying tenants.\n *\n * @returns Returns promise object that is resolved with the IIdentified wrapped by IResultList.\n *\n * **Example**\n * ```typescript\n *\n * const filter: object = {\n * severity: Severity.MAJOR,\n * pageSize: 100,\n * withTotalPages: true\n * };\n *\n * (async () => {\n * const {data, res, paging} = await tenantService.list(filter);\n * })();\n * ```\n *\n * Required role: ROLE_TENANT_MANAGEMENT_READ\n */\n async list(filter: object = {}): Promise<IResultList<ITenant>> {\n return super.list(filter);\n }\n\n /**\n * Delete a representation of a tenant.\n *\n * @param {string|number|IIdentified} entityOrId Tenant's id or tenant object.\n *\n * @returns Returns promise object that is resolved with the IResult.\n *\n * **Example**\n * ```typescript\n *\n * const tenantId: string = \"uniqueTenantId\";\n *\n * (async () => {\n * const {data, res} = await tenantService.delete(tenantId);\n * })();\n * ```\n *\n * Required role: ROLE_TENANT_MANAGEMENT_ADMIN\n */\n async delete(entityOrId: string | number | ITenant): Promise<IResult<null>> {\n return super.delete(entityOrId);\n }\n\n async current(): Promise<IResult<ICurrentTenant>> {\n const headers = { 'content-type': 'application/json' };\n const res = await this.fetch(this.currentTenantUrl, { headers });\n const data = await res.json();\n return { res, data };\n }\n\n /**\n * enable support user for current tenant.\n *\n * @returns Returns promise object that is resolved with the IResult.\n *\n * **Example**\n * ```typescript\n * (async () => {\n * const {res} = await tenantService.enableSupportUser();\n * })();\n * ```\n */\n async enableSupportUser(): Promise<IResult<null>> {\n const url = 'support-user/enable';\n const res = await this.fetch(url, this.fetchOptions);\n return { res, data: null };\n }\n\n /**\n * disable support user for current tenant.\n *\n * @returns Returns promise object that is resolved with the IResult.\n *\n * **Example**\n * ```typescript\n * (async () => {\n * const {res} = await tenantService.disableSupportUser();\n * })();\n * ```\n */\n async disableSupportUser(): Promise<IResult<null>> {\n const url = 'support-user/disable';\n const res = await this.fetch(url, this.fetchOptions);\n return { res, data: null };\n }\n\n async currentTenantType() {\n const tenantData = await this.current();\n if (\n tenantData.data.customProperties &&\n tenantData.data.customProperties.tenantType === 'TRIAL'\n ) {\n return 'TRIAL';\n }\n return 'REGULAR';\n }\n\n /**\n * Returns two factor-authentication settings for given tenant.\n *\n * @param tenant The tenant object.\n *\n * @returns Promise which resolves with the object with TFA settings.\n *\n * **Example**\n * ```typescript\n * (async () => {\n * const currentTenant = (await tenantService.current()).data;\n * const currentTenantTfaSettings = await tenantService.getTfaSettings(currentTenant);\n *\n * const subtenant = (await tenantService.detail('t12345')).data;\n * const subtenantTfaSettings = await tenantService.getTfaSettings(subtenant);\n * })();\n * ```\n */\n async getTfaSettings(tenant: ICurrentTenant | ITenant): Promise<ITfaSettings> {\n const entityOrId: string = this.getIdString(tenant);\n const url = `tenants/${entityOrId}/tfa`;\n const res = await this.fetch(url);\n const tfaSettings = await res.json();\n\n return tfaSettings;\n }\n\n /**\n * Subscribes a given application to a given tenant.\n *\n * @param tenant The tenant object.\n * @param application The application object.\n *\n * @returns Returns promise object that is resolved with the IResult.\n *\n * **Example**\n * ```typescript\n * const newApp = {\n * name: 'New application',\n * type: 'HOSTED',\n * key: 'new-app'\n * };\n *\n * const application = (await applicationService.create(newApp)).data;\n * const currentTenant = (await tenantService.current()).data;\n *\n * const {data, res} = await tenantService.subscribeApplication(currentTenant, application);\n * })();\n * ```\n */\n async subscribeApplication(\n tenant: ICurrentTenant | ITenant,\n application: IApplication\n ): Promise<IResult<null>> {\n const entityOrId: string = this.getIdString(tenant);\n const applicationId = application.id;\n const url = `tenants/${entityOrId}/applications`;\n const method = 'POST';\n const body = JSON.stringify({\n application: {\n id: applicationId,\n self: application.self\n }\n });\n const headers = { 'content-type': this.mimeType('applicationReference') };\n const res = await this.fetch(url, this.changeFetchOptions({ method, body, headers }, url));\n return { res, data: null };\n }\n\n /**\n * Unsubscribes a given application from a given tenant.\n *\n * @param tenant The tenant object.\n * @param application The application object.\n *\n * @returns Returns promise object that is resolved with the IResult.\n *\n * **Example**\n * ```typescript\n * const newApp = {\n * name: 'New application',\n * type: 'HOSTED',\n * key: 'new-app'\n * };\n *\n * const application = (await applicationService.create(newApp)).data;\n * const currentTenant = (await tenantService.current()).data;\n * await tenantService.addApplication(currentTenant, application);\n *\n * await tenantService.unsubscribeApplication(currentTenant, application);\n * })();\n * ```\n */\n async unsubscribeApplication(\n tenant: ICurrentTenant | ITenant,\n application: IApplication\n ): Promise<IResult<null>> {\n const entityOrId: string = this.getIdString(tenant);\n const url = `tenants/${entityOrId}/applications/${application.id}`;\n const method = 'DELETE';\n const res = await this.fetch(url, this.changeFetchOptions({ method }, url));\n return { res, data: null };\n }\n\n protected getIdString(tenant: ITenant | ICurrentTenant): string {\n return (tenant as ITenant).id || (tenant as ICurrentTenant).name;\n }\n\n protected onBeforeCreate(obj: ITenant): any {\n return obj;\n }\n}\n","import { gettext } from '../gettext';\r\n\r\nexport enum TenantStatus {\r\n ACTIVE = gettext('ACTIVE'),\r\n SUSPENDED = gettext('SUSPENDED')\r\n}\r\n","/**\n * Represents a strategy used for two-factor authentication.\n */\nexport enum TfaStrategy {\n /** Two-factor authentication with Time-Based One Time Passwords. */\n TOTP = 'TOTP',\n /** Two-factor authentication with codes sent via SMSes. */\n SMS = 'SMS'\n}\n","import { IFetchClient, IIdentified, Service } from '../core';\nimport { IUserInventoryRole } from './IUserInventoryRole';\n\n/**\n * @description\n * This service allows for managing current user's inventory roles.\n */\nexport class UserInventoryRoleService extends Service<IUserInventoryRole> {\n protected baseUrl;\n protected listUrl = `inventory`;\n protected currenUserUrl = `currentUser`;\n protected propertyName = 'inventoryAssignments';\n\n constructor(userUrl: string, client: IFetchClient) {\n super(client);\n this.baseUrl = `user/${userUrl}/roles`;\n }\n\n /**\n * Get a representation of a concrete current user's inventory role.\n *\n * @param {string|number|IUserInventoryRole} entityOrId inventory role id or inventory role object.\n *\n * @returns Returns promise object that is resolved with the IUserInventoryRole wrapped by IResult.\n *\n * **Example**\n * ```typescript\n *\n * const inventoryRoleId: number = 1;\n *\n * (async () => {\n * const {data, res} = await userInventoryRoleService.detail(inventoryRoleId);\n * })();\n * ```\n *\n * Required role: ROLE_TENANT_MANAGEMENT_READ<br><br>\n * User password is never returned in GET response. Authentication mechanism is provided by another interface.\n */\n async detail(entityOrId: string | number | IUserInventoryRole) {\n return super.detail(entityOrId);\n }\n\n /**\n * Assign inventory role to current user.\n *\n * @param {IUserInventoryRole} entity Inventory Role object.\n *\n * @returns Returns promise object that is resolved with the details of newly assigned inventory role.\n *\n * **Example**\n * ```typescript\n *\n * const inventoryRoleObject: IUserInventoryRole = {\n * ...\n * };\n *\n * (async () => {\n * const {data, res} = await userInventoryRoleService.create(inventoryRoleObject);\n * })();\n * ```\n */\n async create(entity: IUserInventoryRole) {\n return super.create(entity);\n }\n\n /**\n * Updates an inventory role.\n *\n * @param {Partial<IUserInventoryRole>} entity Inventory Role object.\n */\n async update(entity: Partial<IUserInventoryRole>) {\n return super.update(entity);\n }\n\n /**\n * Gets the list the inventory roles applied to a current user.\n *\n * @param {object} filter Object containing filters for querying inventory roles.\n *\n * @returns Returns promise object that is resolved with the IUserInventoryRole wrapped by IResultList.\n *\n * **Example**\n * ```typescript\n *\n * const filter: object = {\n * severity: Severity.MAJOR,\n * pageSize: 100,\n * withTotalPages: true\n * };\n *\n * (async () => {\n * const {data, res, paging} = await userInventoryRoleService.list(filter);\n * })();\n * ```\n */\n async list(filter: object = {}) {\n return super.list(filter);\n }\n\n /**\n * Unassign inventory role from current user\n *\n * @param {string|number|IIdentified} entityOrId Inventory Role id or Inventory Role object.\n *\n * @returns Returns promise object that is resolved with the IResult.\n *\n * **Example**\n * ```typescript\n *\n * const inventoryRoleId: number = 1;\n *\n * (async () => {\n * const {data, res} = await userInventoryRoleService.delete(inventoryRoleId);\n * })();\n * ```\n */\n async delete(entityOrId: string | number | IIdentified) {\n return super.delete(entityOrId);\n }\n}\n","import { IIdentified, Service, IResult, IFetchOptions } from '../core';\nimport { IUser } from './IUser';\nimport { ICurrentUser } from './ICurrentUser';\nimport { UserInventoryRoleService } from './UserInventoryRoleService';\nimport { IResetPassword } from './IResetPassword';\nimport { ITotp } from './ITotp';\nimport { ITotpStatus } from './ITotpStatus';\n\n/**\n * @description\n * This service allows for managing users.\n */\nexport class UserService extends Service<IUser> {\n protected get listUrl() {\n return `${this.client.tenant}/users`;\n }\n protected baseUrl = 'user';\n protected currentUserUrl = 'currentUser';\n protected passwordResetUrl = 'passwordReset';\n protected currentUserPhoneUrl = 'currentUserPhone';\n protected verifyTFACodeUrl = 'pin';\n protected totpCurrentUserURL = `${this.currentUserUrl}/totpSecret`;\n protected verifyTOTPCodeUrl = `${this.totpCurrentUserURL}/verify`;\n protected activateTOTPCodeUrl = `${this.totpCurrentUserURL}/activity`;\n protected revokeTOTPSecretUrl = 'totpSecret/revoke';\n protected get newsletterEmailsUrl() {\n return `${this.client.tenant}/users/newsletterEmails`;\n }\n protected get currentUserPasswordUrl() {\n return `${this.currentUserUrl}/password`;\n }\n protected get revokeAllTokensUrl() {\n return `/logout/${this.client.tenant}/allUsers`;\n }\n protected propertyName = 'users';\n\n /**\n * Gets the details of given user.\n *\n * @param {string | number | IUser} entityOrId User's id or user object.\n *\n * @returns Returns promise object that is resolved with the IUser wrapped by IResult.\n *\n * **Example**\n * ```typescript\n *\n * const userId: number = 1;\n *\n * (async () => {\n * const {data, res} = await userService.detail(userId);\n * })();\n * ```\n * User password is never returned in GET response. Authentication mechanism is provided by another interface.\n */\n async detail(entityOrId: string | number | IUser) {\n return super.detail(entityOrId);\n }\n\n /**\n * Creates a new user.\n *\n * @param {IUser} entity User object.\n *\n * @returns {IResult<IUser>} Returns promise object that is resolved with the details of newly created user.\n *\n * **Example**\n * ```typescript\n *\n * const userObject: IUser = {\n * userName: \"newUser\",\n * password: \"userPassword12!@\"\n * };\n *\n * (async () => {\n * const {data, res} = await userService.create(userObject);\n * })();\n * ```\n */\n async create(entity: IUser) {\n return super.create(entity);\n }\n\n /**\n * Updates user data.\n *\n * @param {Partial<IUser>} entity User is partially updatable.\n *\n * @returns {IResult<IUserGroup>} Returns promise object that is resolved with the saved user object.\n *\n * **Example**\n * ```typescript\n *\n * const partialUpdateObject: Partial<IUser> = {\n * \"id\" : \"myuser\",\n * \"userName\" : \"newUserName\",\n * \"email\": \"newUserEmail@example.com\"\n * ...\n * }\n *\n * (async () => {\n * const {data, res} = await userService.update(partialUpdateObject);\n * })();\n * ```\n * When user is updated with changed permissions or groups, suitable audit record is created with type\n * 'User' and activity 'User updated'.\n */\n async update(entity: Partial<IUser>) {\n return super.update(entity);\n }\n\n /**\n * Gets the list of users filtered by parameters.\n *\n * @param {object} filter Object containing filters for querying users.\n *\n * @returns Returns promise object that is resolved with the IUser wrapped by IResultList.\n *\n * **Example**\n * ```typescript\n *\n * const filter: object = {\n * pageSize: 100,\n * withTotalPages: true\n * };\n *\n * (async () => {\n * const {data, res, paging} = await userService.list(filter);\n * })();\n * ```\n */\n async list(filter: object = {}) {\n return super.list(filter);\n }\n\n /**\n * Removes user.\n *\n * @param {number|IIdentified} entityOrId User's id or user object.\n *\n * @returns Returns promise object that is resolved with the IResult of null.\n *\n * **Example**\n * ```typescript\n *\n * const userId: string = \"uniqueUserId\";\n *\n * (async () => {\n * const {data, res} = await userService.delete(userGroupId);\n * })();\n * ```\n */\n async delete(entityOrId: string | number | IIdentified) {\n return super.delete(entityOrId);\n }\n\n /**\n * Create instance of User Inventory Role Service related with given User.\n *\n * @param {string|number|IUser} entityOrId User's id or user object.\n *\n * @returns Returns UserInventoryRoleService object that is related with given User.\n *\n * **Example**\n * ```typescript\n *\n * const userId: string = \"uniqueUserId\";\n *\n * const userInventoryRoleService = userService.inventoryAssignment(userGroupId);\n * (async () => {\n * const {data, res} = await userInventoryRoleService.create(...);\n * })();\n * ```\n */\n inventoryAssignment(entityOrId: string | number | IUser) {\n return new UserInventoryRoleService(this.getDetailUrl(entityOrId), this.client);\n }\n\n /**\n * Gets user that is currently logged in.\n *\n * @returns Returns promise object that is resolved with the IUser wrapped by IResult.\n *\n * **Example**\n * ```typescript\n *\n * (async () => {\n * const {data, res} = await userService.current();\n * })();\n * ```\n */\n async current(): Promise<IResult<IUser>> {\n const headers = {\n 'content-type': 'application/json',\n Accept: 'application/vnd.com.nsn.cumulocity.user+json;'\n };\n const res = await this.fetch(this.currentUserUrl, { headers });\n const data = await res.json();\n return { res, data };\n }\n\n /**\n * Gets user that is currently logged in with the list of all roles assigned.\n *\n * @returns Returns promise object that is resolved with the ICurrenUser wrapped by IResult.\n *\n * **Example**\n * ```typescript\n *\n * (async () => {\n * const {data, res} = await userService.currentWithEffectiveRoles();\n * })();\n * ```\n */\n async currentWithEffectiveRoles(): Promise<IResult<ICurrentUser>> {\n const headers = {\n 'content-type': 'application/json',\n Accept: 'application/vnd.com.nsn.cumulocity.currentUser+json;'\n };\n const res = await this.fetch(this.currentUserUrl, { headers });\n const data = await res.json();\n return { res, data };\n }\n\n /**\n * Updates the current user\n *\n * @param {IUser} user The user object with the properties to be updated\n *\n * @return Returns promise object resolved with the IUser wrapped by IResult\n */\n async updateCurrent(user: IUser): Promise<IResult<IUser>> {\n const mimeType = 'application/vnd.com.nsn.cumulocity.user+json';\n const headers = { 'content-type': mimeType, Accept: mimeType };\n const body = JSON.stringify(this.onBeforeUpdate(user));\n const res = await this.fetch(this.currentUserUrl, { headers, body, method: 'PUT' });\n const data = await res.json();\n return { res, data };\n }\n\n /**\n * Sends an email message with a link allowing user to reset their password.\n *\n * @param {string} email The email address to send the message to.\n * @param {string} tenantId The id of user's tenant (if cannot be inferred from URL).\n *\n * @returns Returns a request result object.\n *\n * **Example**\n * ```typescript\n * const email = 'user@example.com';\n * const tenantId = 't123456';\n *\n * (async () => {\n * const { res, data } = await userService.sendPasswordResetMail(email, tenantId);\n * })();\n * ```\n */\n async sendPasswordResetMail(email: string, tenantId?: string): Promise<IResult<null>> {\n const headers = { 'content-type': 'application/json', accept: 'application/json' };\n const method = 'POST';\n const url = this.passwordResetUrl;\n const params = tenantId ? { tenantId } : {};\n const body = JSON.stringify({ email });\n const res = await this.fetch(url, { headers, method, params, body });\n return { res, data: null };\n }\n\n /**\n * Resets user's password to a new one.\n *\n * @param {IResetPassword} newPassword Object with token, user's email, new password and its strength indicator.\n * @param {string} tenantId The id of user's tenant (if cannot be inferred from URL).\n *\n * @returns Returns a request result object.\n *\n * **Example**\n * ```typescript\n * const newPassword: IResetPassword = {\n * token: '123123ASDAWERER@#!WEDS$@#!WADA#A#EA#EA#EA',\n * email: 'user@example.com',\n * newPassword: 'myNewPassword',\n * passwordStrength: PasswordStrength.GREEN\n * };\n * const tenantId = 't123456';\n *\n * (async () => {\n * const { res, data } = await userService.resetPassword(newPassword, tenantId);\n * })();\n * ```\n */\n async resetPassword(newPassword: IResetPassword, tenantId?: string): Promise<IResult<null>> {\n const headers = { 'content-type': 'application/json', accept: 'application/json' };\n const method = 'PUT';\n const url = this.passwordResetUrl;\n const params = tenantId ? { tenantId } : {};\n const body = JSON.stringify(newPassword);\n const res = await this.fetch(url, { headers, method, params, body });\n return { res, data: null };\n }\n\n /**\n * Verifies TFA code which is sent via SMS. If invoked with string '0', new TFA code will be sent.\n *\n * @param {string} pin The code to verify.\n *\n * @returns Returns a status object.\n *\n * **Example**\n * ```typescript\n *\n * (async () => {\n * const {data, res} = await userService.verifyTFACode('123123');\n * })();\n * ```\n */\n async verifyTFACode(pin: string): Promise<IResult<null>> {\n const method = 'POST';\n const body = JSON.stringify({ pin });\n const headers = { 'content-type': 'application/json', accept: 'application/json' };\n const res = await this.fetch(this.verifyTFACodeUrl, { headers, body, method });\n return { res, data: null };\n }\n\n /**\n * Verifies TFA code which is generated by a TOTP app.\n *\n * @param {string} code The code to verify.\n *\n * @returns Returns a status object.\n *\n * **Example**\n * ```typescript\n *\n * (async () => {\n * const {data, res} = await userService.verifyTotpCode('123123');\n * })();\n * ```\n */\n async verifyTotpCode(code): Promise<IResult<null>> {\n const method = 'POST';\n const headers = { 'content-type': 'application/json' };\n const body = JSON.stringify({ code });\n const res = await this.fetch(this.verifyTOTPCodeUrl, { headers, body, method });\n return { res, data: null };\n }\n\n /**\n * Verifies TFA code which is generated by a TOTP app.\n *\n * @returns Returns a status object.\n *\n * **Example**\n * ```typescript\n *\n * (async () => {\n * const {data, res} = await userService.activateTotp();\n * })();\n * ```\n */\n async activateTotp(): Promise<IResult<null>> {\n const method = 'POST';\n const headers = { 'content-type': 'application/json' };\n const body = JSON.stringify({ isActive: true });\n const res = await this.fetch(this.activateTOTPCodeUrl, { headers, body, method });\n return { res, data: null };\n }\n\n /**\n * Checks if TOTP is activated and enforced.\n *\n * @returns Returns an object of ITotpStatus if it is active.\n *\n * **Example**\n * ```typescript\n *\n * (async () => {\n * const {data, res} = await userService.getActivityTotp();\n * console.log(data.isActive);\n * })();\n * ```\n */\n async getActivityTotp(): Promise<IResult<ITotpStatus>> {\n const method = 'GET';\n const headers = { 'content-type': 'application/json' };\n const res = await this.fetch(this.activateTOTPCodeUrl, { headers, method });\n const data = await res.json();\n return { res, data };\n }\n\n /**\n * Generates a secret which can be used to setup two-factor authentication with TOTP.\n *\n * @returns Returns the secret and an URL to a QR Code.\n *\n * **Example**\n * ```typescript\n *\n * (async () => {\n * const {data, res} = await userService.generateTotpSecret();\n * console.log(secret);\n * })();\n * ```\n */\n async generateTotpSecret(): Promise<IResult<ITotp>> {\n const method = 'POST';\n const headers = { 'content-type': 'application/json', accept: 'application/json' };\n const res = await this.fetch(this.totpCurrentUserURL, { headers, method });\n const data = await res.json();\n return { res, data };\n }\n\n /**\n * Revokes a specific user's TOTP secret.\n *\n * @param {IUser} user User whose TOTP secret to revoke.\n *\n * @returns Status object\n */\n async totpRevokeSecret(user: IUser): Promise<IResult<null>> {\n const url = `${this.getDetailUrl(user)}/${this.revokeTOTPSecretUrl}`;\n const method = 'DELETE';\n const headers = { accept: 'application/json' };\n const res = await this.fetch(url, { headers, method });\n return { res, data: null };\n }\n\n /**\n * Saves phone number for the current user.\n * @param phoneNumber Phone number to save.\n * @returns Server response and data with updated current user object.\n */\n async savePhoneNumber(phoneNumber: string): Promise<IResult<ICurrentUser>> {\n const url = this.currentUserPhoneUrl;\n const options: IFetchOptions = {\n method: 'PUT',\n headers: { 'content-type': 'application/json', accept: 'application/json' },\n body: JSON.stringify({\n phone: phoneNumber\n })\n };\n const res = await this.fetch(url, options);\n const data = await res.json();\n return { res, data };\n }\n\n /**\n * Gets the list of emails of users subscribed for newsletter\n * on the current tenant and its subtenants.\n * @returns Server response and data with email addresses as plain text.\n */\n async getNewsletterEmails(): Promise<IResult<string>> {\n const url = this.newsletterEmailsUrl;\n const options: IFetchOptions = {\n method: 'GET',\n headers: { accept: 'text/plain' }\n };\n const res = await this.fetch(url, options);\n const data = await res.text();\n return { res, data };\n }\n\n /**\n * Changes password for user.\n *\n * @param {string | number | IUser} entityOrId User's id or user object.\n * @param {string} newPassword New user password.\n * @param {string} currentUserPassword The password of the currently logged user.\n *\n * @returns Returns a result object.\n */\n async changeUserPassword(\n entityOrId: string | number | IUser,\n newPassword: string,\n currentUserPassword: string\n ): Promise<IResult<null>> {\n const method = 'PUT';\n const headers = { 'content-type': 'application/json' };\n const body = JSON.stringify({ newPassword, currentUserPassword });\n const res = await this.fetch(this.changeUserPasswordUrl(entityOrId), { headers, body, method });\n return { res, data: null };\n }\n\n /**\n * Changes password for current user.\n *\n * @param {string} newPassword New password for current user.\n * @param {string} currentUserPassword The password of the currently logged user.\n *\n * @returns Returns a result object. During this action if preferred login mode is OAI_SECURE new jwt cookie will be set.\n */\n async changeCurrentUserPassword(\n newPassword: string,\n currentUserPassword: string\n ): Promise<IResult<null>> {\n const method = 'PUT';\n const headers = { 'content-type': 'application/json' };\n const body = JSON.stringify({ newPassword, currentUserPassword });\n const res = await this.fetch(this.currentUserPasswordUrl, { headers, body, method });\n return { res, data: null };\n }\n\n /**\n * Revoke tokens for all users. All users logged with \"OAI-Secure\" or \"Single sign-on redirect\" will be logged out.\n *\n * @returns Returns a result object.\n */\n async revokeTokens(): Promise<IResult<null>> {\n const method = 'POST';\n const headers = { 'content-type': 'application/json' };\n const res = await this.fetch(this.revokeAllTokensUrl, { headers, method });\n return { res, data: null };\n }\n\n hasRole(user: IUser, roleId: string): boolean {\n return this.hasRoleInUser(user, roleId) || this.hasRoleInGroups(user, roleId);\n }\n\n hasAllRoles(user: IUser, roleIds: string[]): boolean {\n return roleIds.every(roleId => this.hasRole(user, roleId));\n }\n\n hasAnyRole(user: IUser, roleIds: string[]): boolean {\n return roleIds.some(roleId => this.hasRole(user, roleId));\n }\n\n hasAnyGlobalRole(user: IUser, globalRoleIds: number[]): boolean {\n return globalRoleIds.some(globalRoleId => this.hasGlobalRoleInUser(user, globalRoleId));\n }\n\n isDeviceUser(user: IUser) {\n return user.id.match(/^device_/);\n }\n\n protected onBeforeUpdate(user: IUser): any {\n const obj = Object.assign({}, user);\n delete obj.id;\n delete obj.userName;\n return obj;\n }\n\n protected getDetailUrl(entityOrId: string | number | IUser): string {\n return `${this.listUrl}/${encodeURIComponent(this.getId(entityOrId))}`;\n }\n\n protected getId(entityOrId: string | number | IUser): string {\n let id: string | number;\n if (typeof entityOrId === 'object' && entityOrId.id) {\n id = entityOrId.id;\n } else if (typeof entityOrId === 'object' && entityOrId.userName) {\n id = entityOrId.userName;\n } else {\n id = entityOrId as string | number;\n }\n return String(id);\n }\n\n protected hasRoleInUser(user, roleId) {\n const effectiveRoles = user.effectiveRoles || [];\n return (\n this.hasRoleInReferences((user && user.roles && user.roles.references) || [], roleId) ||\n effectiveRoles.some(({ id }) => roleId === id)\n );\n }\n\n protected hasRoleInGroups(user, roleId) {\n const groupReferences = (user && user.groups && user.groups.references) || [];\n return groupReferences.some(groupRef =>\n this.hasRoleInReferences(groupRef.group.roles.references, roleId)\n );\n }\n\n protected hasRoleInReferences(references, roleId) {\n return references.some(ref => ref.role.id === roleId);\n }\n\n protected changeUserPasswordUrl(entityOrId: string | number | IUser) {\n return `${this.client.tenant}/users/${this.getId(entityOrId)}/password`;\n }\n\n protected hasGlobalRoleInUser(user: IUser, globalRoleId: number) {\n const groupReferencesIds = (user?.groups?.references || []).map(gR => gR?.group?.id);\n return groupReferencesIds.some(id => id === globalRoleId);\n }\n}\n","export enum PasswordStrength {\n GREEN = 'GREEN',\n RED = 'RED',\n YELLOW = 'YELLOW'\n}\n","import { IFetchClient, Service, IResult, IFetchResponse } from '../core';\nimport { IApplication } from './IApplication';\nimport { IApplicationBinary } from './IApplicationBinary';\nimport { Stream } from 'stream';\nimport FormData from 'form-data';\nimport { IUploadParamsOverride } from './IUploadParamsOverride';\n\nexport class ApplicationBinaryService extends Service<IApplicationBinary> {\n protected baseUrl;\n protected listUrl = 'binaries';\n protected propertyName = 'attachments';\n\n constructor(client: IFetchClient, applicationOrId: string | number | IApplication) {\n super(client);\n this.baseUrl = `application/applications/${this.getIdString(applicationOrId)}`;\n }\n\n async upload(\n binary: ArrayBuffer | Stream | Buffer | File | Blob,\n fileName?: string,\n uploadParamsOverride?: IUploadParamsOverride\n ): Promise<IResult<IApplicationBinary>> {\n const url = uploadParamsOverride?.listUrl || this.listUrl;\n const method = 'POST';\n const body = this.createBinaryRequestBody(binary, fileName, uploadParamsOverride);\n let bodyHeaders;\n if (typeof body.getHeaders === 'function') {\n bodyHeaders = body.getHeaders();\n }\n const headers = Object.assign(\n uploadParamsOverride?.headers || {\n Accept: 'application/json'\n },\n bodyHeaders\n );\n const res = await this.fetch(url, { method, body, headers });\n const data = await res.json();\n return { res, data };\n }\n\n uploadWithProgressXhr(\n binary: ArrayBuffer | Stream | Buffer | File | Blob,\n onProgress,\n fileName?: string,\n uploadParamsOverride?: IUploadParamsOverride\n ): XMLHttpRequest {\n const url = `/${this.baseUrl}/${uploadParamsOverride?.listUrl || this.listUrl}`;\n const method = 'POST';\n const body = this.createBinaryRequestBody(binary, fileName, uploadParamsOverride);\n let bodyHeaders;\n if (typeof body.getHeaders === 'function') {\n bodyHeaders = body.getHeaders();\n }\n const headers = this.client.getFetchOptions().headers;\n Object.assign(\n headers,\n uploadParamsOverride?.headers || {\n Accept: 'application/json'\n }\n );\n Object.assign(headers, bodyHeaders);\n const xhr = new XMLHttpRequest();\n xhr.open(method, url, true);\n for (const key in headers) {\n if (headers.hasOwnProperty(key)) {\n xhr.setRequestHeader(key, headers[key]);\n }\n }\n\n xhr.upload.addEventListener('progress', onProgress);\n\n let xhrBody: XMLHttpRequestBodyInit;\n if (typeof body.getBuffer === 'function') {\n xhrBody = body.getBuffer();\n } else {\n xhrBody = body as any;\n }\n xhr.send(xhrBody);\n return xhr;\n }\n\n getXMLHttpResponse(xhr): Promise<IApplication> {\n return new Promise((res, rej) => {\n xhr.addEventListener('loadend', () => {\n xhr.readyState === 4 && (xhr.status === 200 || xhr.status === 201)\n ? res(JSON.parse(xhr.responseText))\n : rej(\n xhr.responseText ? { data: JSON.parse(xhr.responseText) } : 'Could not upload file.'\n );\n });\n });\n }\n\n async list(filter?) {\n return super.list(filter);\n }\n\n async delete(binaryOrId: string | number | IApplicationBinary) {\n return super.delete(binaryOrId);\n }\n\n async listPlugins() {\n const headers = { accept: 'application/json' };\n const url = `${this.listUrl}/plugins`;\n const res = await this.fetch(url, { headers });\n const data = await res.json();\n return { res, data };\n }\n\n async addPlugin(pluginName: string, pluginFile: Stream | Buffer | ArrayBuffer) {\n const url = `${this.listUrl}/plugins/${encodeURIComponent(pluginName)}`;\n const method = 'POST';\n const body = new FormData();\n const bufferOrStream = pluginFile instanceof ArrayBuffer ? Buffer.from(pluginFile) : pluginFile;\n body.append('file', bufferOrStream);\n\n const headers = {\n accept: 'application/json'\n };\n\n const res = await this.fetch(url, { method, body, headers });\n const data = await res.json();\n return { res, data };\n }\n\n async removePlugin(pluginName: string) {\n const method = 'DELETE';\n const headers = { accept: 'application/json' };\n const url = `${this.listUrl}/plugins/${pluginName}`;\n const res = await this.fetch(url, { method, headers });\n const data = await res.json();\n return { res, data };\n }\n\n async updateFiles(files: Array<{ path: string; contents: Stream | Buffer | ArrayBuffer }>) {\n const url = `${this.listUrl}/files`;\n const method = 'POST';\n const body = new FormData();\n files.forEach(file => {\n const bufferOrStream =\n file.contents instanceof ArrayBuffer ? Buffer.from(file.contents) : file.contents;\n body.append(file.path, bufferOrStream);\n });\n const headers = {\n accept: 'application/json'\n };\n const res = await this.fetch(url, { method, body, headers });\n const data = await res.json();\n return { res, data };\n }\n\n async downloadArchive(binaryId: number | string): Promise<IFetchResponse> {\n const url = `${this.listUrl}/${binaryId}`;\n return await this.fetch(url);\n }\n\n private createBinaryRequestBody(\n binary: ArrayBuffer | Stream | Buffer | File | Blob,\n fileName?: string,\n uploadParamsOverride?: IUploadParamsOverride\n ) {\n const body = new FormData();\n const bufferOrStream = binary instanceof ArrayBuffer ? Buffer.from(binary) : binary;\n let uploadFileName = fileName;\n if (typeof File !== 'undefined' && binary instanceof File) {\n uploadFileName = binary.name;\n }\n body.append(uploadParamsOverride?.bodyFileProperty || 'file', bufferOrStream, uploadFileName);\n body.append('fileName', uploadFileName);\n if (uploadParamsOverride?.requestBody) {\n for (const key in uploadParamsOverride.requestBody) {\n if (uploadParamsOverride.requestBody.hasOwnProperty(key)) {\n body.append(key, JSON.stringify(uploadParamsOverride.requestBody[key]));\n }\n }\n }\n return body;\n }\n}\n","export enum ApplicationType {\n EXTERNAL = 'EXTERNAL',\n HOSTED = 'HOSTED',\n MICROSERVICE = 'MICROSERVICE',\n FEATURE = 'FEATURE'\n}\n","import {\n IApplicationInstanceLog,\n IApplicationInstanceLogRequestParams,\n IApplicationManagedObject\n} from './IApplicationInstanceDetails';\nimport { IFetchResponse, IResult, IResultList, Service } from '../core';\nimport { InventoryService } from '../inventory';\nimport { ITenant, TenantService } from '../tenant';\nimport { IUser, UserService } from '../user';\nimport { ApplicationBinaryService } from './ApplicationBinaryService';\nimport { ApplicationType } from './ApplicationType';\nimport { IApplication } from './IApplication';\nimport { gettext } from '../gettext';\nimport { IApplicationVersionDeleteParams, IApplicationVersion } from './IApplicationVersion';\nimport { IManifest } from './IManifest';\nimport { ApplicationAvailability } from './ApplicationAvailability';\n\nexport class ApplicationService extends Service<IApplication> {\n protected baseUrl = 'application';\n protected listUrl = 'applications';\n protected propertyName = 'applications';\n protected channel = '/applications/*';\n\n /**\n * Creates a new application.\n *\n * @param {IIdentified} entity Application object.\n *\n * @returns Response wrapped in [[IResult]]\n *\n * **Example**\n * ```typescript\n *\n * const newApp = {\n * name: 'New application',\n * type: 'EXTERNAL',\n * key: 'new-app'\n * };\n *\n * (async () => {\n * const {data, res} = await applicationService.create(newApp);\n * })();\n * ```\n */\n async create(entity: IApplication): Promise<IResult<IApplication>> {\n return super.create(entity);\n }\n\n /**\n * Clones a given application. The application name, key, and context-path will be\n * prefixed with `clone` and if necessary a number.\n * @param entity The application to clone.\n * @param version If a blueprint, you can define which version to clone. If not provided, it will always clone the latest version.\n * @returns The application entity.\n */\n async clone(entity: IApplication, version?: string): Promise<IResult<IApplication>> {\n const url = `${this.getDetailUrl(entity)}/clone`;\n const method = 'POST';\n const body = '';\n const headers = { 'content-type': 'application/json', accept: 'application/json' };\n let params = undefined;\n if (version) {\n params = { version };\n }\n const res = await this.fetch(url, { method, body, headers, params });\n const data = await res.json();\n return { res, data };\n }\n\n /**\n * Gets the list of existing applications filtered by parameters.\n *\n * @returns Response wrapped in [[IResultList]]\n *\n * @param {object} filter Object containing filters for querying applications.\n *\n * **Example**\n * ```typescript\n *\n * const filter: object = {\n * pageSize: 100,\n * withTotalPages: true\n * };\n *\n * (async () => {\n * const {data, res, paging} = await applicationService.list(filter);\n * })();\n * ```\n */\n async list(filter: object = {}): Promise<IResultList<IApplication>> {\n return super.list(filter);\n }\n\n /**\n * Gets the list of all application versions.\n *\n * @param {string|number|IIdentified} entityOrId Entity or Id of the entity.\n *\n * @param {object} params Additional request parameters.\n *\n * @returns Returns list of all application versions.\n *\n * **Example**\n * ```typescript\n *\n * const applicationId: number = 1;\n *\n * (async () => {\n * const {res, data} = await applicationService.listVersions(applicationId);\n * })();\n * ```\n */\n async listVersions(\n entityOrId: string | number | IApplication,\n params: object = {}\n ): Promise<IResultList<IApplicationVersion>> {\n const id = this.getEntityId(entityOrId);\n const url = `${this.listUrl}/${id}/versions`;\n const headers = { 'content-type': 'application/json' };\n try {\n const res = await this.fetch(url, { headers, params });\n const data = (await res.json())?.applicationVersions;\n return { res, data };\n } catch (ex) {\n if (ex.res.status === 404) {\n const { data: appDetail, res } = await this.detail(entityOrId);\n return { res, data: appDetail.applicationVersions };\n }\n throw ex;\n }\n }\n\n /**\n * Gets the details of selected application.\n *\n * @param {string|number|IIdentified} entityOrId Entity or Id of the entity.\n *\n * @returns Response wrapped in [[IResult]]\n *\n * **Example**\n * ```typescript\n *\n * const applicationId: number = 1;\n *\n * (async () => {\n * const {data, res} = await applicationService.detail(applicationId);\n * })();\n * ```\n */\n async detail(entityOrId: string | number | IApplication): Promise<IResult<IApplication>> {\n return super.detail(entityOrId);\n }\n\n /**\n * Updates existing application.\n * Make sure that you specifiy the application id within the update object.\n *\n * @param {IIdentified} entity Application object.\n *\n * @returns Response wrapped in [[IResult]]\n *\n * **Example**\n * ```typescript\n *\n * const updateApp = {\n * id: 38\n * name: 'Updated application'\n * };\n *\n * (async () => {\n * const {data, res} = await applicationService.update(updateApp);\n * })();\n * ```\n */\n async update(entity: IApplication): Promise<IResult<IApplication>> {\n return super.update(entity);\n }\n\n /**\n * Removes an application with given id.\n *\n * @returns Response wrapped in [[IResult]]\n *\n * @param {string | number | IIdentified} entityOrId entity or id of the application.\n *\n * **Example**\n * ```typescript\n *\n * const removeApp: object = {\n * id: 38\n * };\n *\n * (async () => {\n * const {data, res} = await applicationService.delete(removeApp);\n * // data will be null\n * })();\n * ```\n */\n async delete(entityOrId: string | number | IApplication): Promise<IResult<null>> {\n return super.delete(entityOrId);\n }\n\n async listByName(name: string): Promise<IResultList<IApplication>> {\n const headers = { 'content-type': 'application/json' };\n const url = `applicationsByName/${encodeURIComponent(name)}`;\n const res = await this.fetch(url, { headers });\n const json = await res.json();\n const data = json[this.propertyName];\n return { res, data };\n }\n\n async listByTenant(\n tenantOrName?: string | ITenant,\n params: object = {}\n ): Promise<IResultList<IApplication>> {\n const headers = { 'content-type': 'application/json' };\n const tenantService = new TenantService(this.client);\n const tenantName = this.getIdString(tenantOrName || (await tenantService.current()).data.name);\n const url = `applicationsByTenant/${encodeURIComponent(tenantName)}`;\n const res = await this.fetch(url, { headers, params });\n const json = await res.json();\n const data = json[this.propertyName];\n return { res, data };\n }\n\n async listByOwner(\n tenantOrName?: string | ITenant,\n params: object = {}\n ): Promise<IResultList<IApplication>> {\n const headers = { 'content-type': 'application/json' };\n const tenantService = new TenantService(this.client);\n const tenantName = this.getIdString(tenantOrName || (await tenantService.current()).data.name);\n const url = `applicationsByOwner/${encodeURIComponent(tenantName)}`;\n const res = await this.fetch(url, { headers, params });\n const json = await res.json();\n const data = json[this.propertyName];\n return { res, data };\n }\n\n async listByUser(\n userOrId?: string | number | IUser,\n params: object = {}\n ): Promise<IResultList<IApplication>> {\n const headers = { 'content-type': 'application/json' };\n const userService = new UserService(this.client);\n const userId = this.getIdString(userOrId || (await userService.current()).data);\n const url = `applicationsByUser/${encodeURIComponent(userId)}`;\n const res = await this.fetch(url, { headers, params });\n const json = await res.json();\n const data = json[this.propertyName];\n return { res, data };\n }\n\n async reactivateArchive(appId: number | string): Promise<IResult<null>> {\n const url = `${this.listUrl}/${appId}/refresh`;\n const method = 'POST';\n const body = '';\n const headers = { 'content-type': 'application/json', accept: 'application/json' };\n const res = await this.fetch(url, { method, body, headers });\n return { res, data: null };\n }\n\n binary(application: string | number | IApplication): ApplicationBinaryService {\n return new ApplicationBinaryService(this.client, application);\n }\n\n getHref(application: IApplication): string {\n if (application.type === ApplicationType.EXTERNAL) {\n return application.externalUrl;\n }\n return `/apps/${application.public ? 'public/' : ''}${application.contextPath}`;\n }\n\n /**\n * Checks if current user can access specified application.\n *\n * @returns Response wrapped in [[IResult]]\n *\n * @param {string | IApplication} application Application name or contextPath as a\n * string or Application object.\n *\n * **Example**\n * ```typescript\n *\n * const checkApp: object = {\n * name: 'myApplication'\n * };\n *\n * (async () => {\n * const {data, res} = await applicationService.isAvailable(checkApp);\n * })();\n * ```\n */\n async isAvailable(application: string | Partial<IApplication>): Promise<IResult<boolean>> {\n const { res, data } = await this.listByUser(undefined, {\n dropOverwrittenApps: true,\n noPaging: true\n });\n\n const available: boolean = (data || []).some((availableApp: IApplication) =>\n typeof application === 'string'\n ? availableApp.name === application || availableApp.contextPath === application\n : this.isMatch(availableApp, application)\n );\n\n return { data: available, res };\n }\n\n /**\n * Gets instance details of the specified application (microservice).\n *\n * @param {string|number|IApplication} entityOrId Entity or Id of the application.\n *\n * @returns Response wrapped in [[IResultList]]\n *\n * **Example**\n * ```typescript\n *\n * const applicationId: number = 1;\n *\n * (async () => {\n * const {data, res} = await applicationService.getStatusDetails(applicationId);\n * })();\n * ```\n */\n async getStatusDetails(\n entityOrId: string | number | IApplication\n ): Promise<IResultList<IApplicationManagedObject>> {\n const appId = this.getEntityId(entityOrId);\n const inventory = new InventoryService(this.client, this.realtime);\n return inventory.list({ type: `c8y_Application_${appId}` });\n }\n\n /**\n * Extracts instance names of the provided IApplicationManagedObject.\n *\n * @param {IApplicationManagedObject} appStatusDetails Application details managedObject.\n *\n * @returns instance names\n *\n * **Example**\n * ```typescript\n *\n * const applicationId: number = 1;\n *\n * (async () => {\n * const {data, res} = await applicationService.getStatusDetails(applicationId);\n * const instances = data.map((appMO) => applicationService.getInstanceNames(appMO));\n * })();\n * ```\n */\n getInstanceNames(appStatusDetails: IApplicationManagedObject): string[] {\n let instanceNames = new Array<string>();\n if (appStatusDetails && appStatusDetails.c8y_Status && appStatusDetails.c8y_Status.instances) {\n instanceNames = Object.keys(appStatusDetails.c8y_Status.instances);\n }\n return instanceNames;\n }\n\n /**\n * Get log for a specific application instance.\n *\n * @param {string|number|IApplication} entityOrId Entity or Id of the application.\n *\n * @param {string} instanceName instance name of the application.\n *\n * @param {IApplicationInstanceLogRequestParams} params Object containing parameters for querying the log file.\n *\n * @returns Response wrapped in [[IResult]]\n *\n * **Example**\n * ```typescript\n *\n * const applicationId: number = 1;\n * const applicationInstanceName: string = 'apama-ctrl-1c-4g-scope-t123456789-deployment-abcdefghij-abcde';\n *\n * (async () => {\n * const {data, res} = await applicationService.getInstanceLog(applicationId, applicationInstanceName);\n * })();\n * ```\n */\n async getInstanceLog(\n entityOrId: string | number | IApplication,\n instanceName: string,\n params?: IApplicationInstanceLogRequestParams\n ): Promise<IResult<IApplicationInstanceLog>> {\n const url = `${this.getDetailUrl(entityOrId)}/logs/${instanceName}`;\n const headers = { accept: this.mimeType('applicationLogs') };\n const res = await this.fetch(url, { headers, params });\n const data = await res.json();\n return { res, data };\n }\n\n /**\n * Dynamic options are stored on the API in a specific `config: {}` object. They can\n * be used to configure the app dynamically.\n *\n * Note: To avoids conflicts with the default Config, it is recommended\n * to use a certain namespace.\n * @param entityOrId Entity or Id of the application.\n * @param config Configuration to be updated.\n * @returns Returns updated configuration.\n */\n async updateApplicationConfig<T>(\n entityOrId: string | number | IApplication,\n config: T\n ): Promise<IApplication & { config: T }> {\n const id = this.getEntityId(entityOrId);\n const { data: app } = await this.detail(id);\n const currentConfig = app?.config || {};\n const newConfig = { ...currentConfig, ...config };\n const updatedConfigApp = await this.update({\n id,\n config: newConfig\n });\n return (await updatedConfigApp)?.data as any;\n }\n\n /**\n * Gets manifest (cumulocity.json file) of a given application.\n *\n * @param {IApplication} app Application entity.\n *\n * @param {string} app version\n *\n * @returns Application manifest object.\n */\n async getAppManifest(app: IApplication, version?: string): Promise<IManifest> {\n const date = new Date();\n let result: IFetchResponse;\n if (!version) {\n result = await this.client.fetch(\n `/apps/${app.contextPath}/cumulocity.json?nocache=${date.getTime()}`\n );\n } else {\n result = await this.client.fetch(\n `/apps/${app.contextPath}@${version}/cumulocity.json?nocache=${date.getTime()}`\n );\n }\n if (result.status >= 400) {\n throw new Error(gettext('No Cumulocity IoT manifest found.'));\n }\n const c8yJson = await result.json();\n return c8yJson;\n }\n\n /**\n * Updates manifest (cumulocity.json file) of a given application.\n *\n * @param {string|number|IApplication} entityOrId Entity or Id of the application.\n *\n * @param {any} manifestJSON Application manifest object to be stored.\n *\n * @returns Application manifest object.\n */\n async storeAppManifest(entityOrId: string | number | IApplication, manifestJSON: any) {\n return await this.binary(entityOrId).updateFiles([\n { path: 'cumulocity.json', contents: JSON.stringify(manifestJSON) as any }\n ]);\n }\n\n /**\n * Sets tags for specific application package version.\n *\n * @param {IApplication} app Application entity.\n *\n * @param {string} version Application package version which tags will be set.\n *\n * @param {string[]} tags Tags array to set on package version\n *\n * @returns Application version object.\n */\n async setPackageVersionTag(app: IApplication, version: string, tags: string[]) {\n const url = `${this.getDetailUrl(app)}/versions/${version}`;\n const method = 'PUT';\n const body = JSON.stringify({ tags });\n const headers = {\n accept: 'application/vnd.com.nsn.cumulocity.applicationVersion+json;charset=UTF-8;ver=0.9',\n 'content-type': 'application/json'\n };\n const res = await this.fetch(url, { method, body, headers });\n const data = await res.json();\n return { res, data };\n }\n\n /**\n * Retrieves the manifest of the application behind the given context path.\n * @param contextPath\n */\n async getManifestOfContextPath(contextPath: string): Promise<IResult<Partial<IApplication>>> {\n const url = `${this.getDetailUrl(contextPath)}/manifest`;\n const res = await this.fetch(url);\n const { application } = await res.json();\n return {\n res,\n data: application\n };\n }\n\n /**\n * Removes package version.\n *\n * @param {IApplication} app Application entity.\n *\n * @param {IApplicationVersionDeleteParams} params Version or tag indication package to remove.\n *\n * @returns Request response.\n *\n * **Example**\n * ```typescript\n *\n * const { res } = await applicationService.deleteVersionPackage(app, {version: '1.0.0'});\n *\n * const { res } = await applicationService.deleteVersionPackage(app, {tag: 'next'});\n *\n * ```\n */\n async deleteVersionPackage(app: IApplication, params: IApplicationVersionDeleteParams) {\n const url = `${this.getDetailUrl(app)}/versions/`;\n const method = 'DELETE';\n const res = await this.fetch(url, this.changeFetchOptions({ method, params }, url));\n return { res, data: null };\n }\n\n /**\n * Updates the availability of the given application to the provided value.\n *\n * @param {string|number|IApplication} entityOrId Entity or Id of the application.\n *\n * @param {any} availability The new application availability.\n *\n * @returns Updated application.\n */\n async updateApplicationAvailability(\n entityOrId: string | number | IApplication,\n availability: ApplicationAvailability\n ): Promise<IResult<IApplication>> {\n const id = this.getEntityId(entityOrId);\n return await this.update({\n id,\n availability\n });\n }\n\n private isMatch(object, source): boolean {\n return Object.keys(source).every(key => {\n if (Array.isArray(object[key]) && Array.isArray(source[key])) {\n return source[key].every(el => object[key].includes(el));\n } else if (\n typeof object[key] === 'object' &&\n object[key] !== null &&\n typeof source[key] === 'object' &&\n source[key] !== null\n ) {\n return this.isMatch(object[key], source[key]);\n } else {\n return object[key] === source[key];\n }\n });\n }\n}\n","import { IManagedObject } from '../inventory';\n\nexport enum InstanceStatus {\n Up = 'Up',\n Unhealthy = 'Unhealthy',\n Down = 'Down',\n Unknown = 'Unknown'\n}\n\nexport interface ILastUpdated {\n date: {\n $date: string;\n };\n offset: number;\n [key: string]: any;\n}\n\nexport interface IInstanceDetails {\n lastUpdated: ILastUpdated;\n memoryInBytes: number;\n scheduled: boolean;\n restarts: number;\n cpuInMillis: number;\n [key: string]: any;\n}\n\nexport interface IApplicationStatus {\n lastUpdated: ILastUpdated;\n instances: {\n [instanceName: string]: IInstanceDetails;\n };\n details: {\n desired: number;\n aggregatedResources: {\n memory: string;\n cpu: string;\n };\n active: number;\n restarts: number;\n };\n status: InstanceStatus;\n [key: string]: any;\n}\n\nexport interface IApplicationManagedObjectAdditions {\n c8y_Status?: IApplicationStatus;\n applicationOwner?: string;\n c8y_Subscriptions?: {\n [tenantId: string]: IApplicationStatus;\n };\n applicationId?: string;\n name?: string;\n c8y_SupportedLogs?: string[];\n [key: string]: any;\n}\n\nexport type IApplicationManagedObject = IManagedObject & IApplicationManagedObjectAdditions;\n\nexport interface IApplicationInstanceLog {\n dateFrom: string;\n dateTo: string;\n logs: string;\n truncated: boolean;\n [key: string]: any;\n}\n\nexport interface IApplicationInstanceLogRequestParams {\n dateFrom?: string;\n dateTo?: string;\n /**\n * Limits the maximum number of lines to be returned by the backend.\n */\n limit?: number;\n [key: string]: any;\n}\n","export enum BillingMode {\n SUBSCRIPTION = 'SUBSCRIPTION',\n RESOURCES = 'RESOURCES'\n}\n","export enum Isolation {\n PER_TENANT = 'PER_TENANT',\n MULTI_TENANT = 'MULTI_TENANT'\n}\n","import { gettext } from '../gettext';\n\nexport enum ApplicationAvailability {\n MARKET = gettext('MARKET'),\n PRIVATE = gettext('PRIVATE'),\n SHARED = gettext('SHARED')\n}\n","import { Service, IResult, IResultList } from '../core';\r\nimport { ISystemOption } from './ISystemOption';\r\n\r\nexport class SystemOptionsService extends Service<ISystemOption> {\r\n protected baseUrl = 'tenant/system';\r\n protected listUrl = 'options';\r\n protected propertyName = 'options';\r\n\r\n /**\r\n * Gets the details of given system option.\r\n *\r\n * @param {string|number|IIdentified} option System option object with mandantory fragments.\r\n *\r\n * @returns Response wrapped in [[IResult]]\r\n *\r\n * **Example**\r\n * ```typescript\r\n *\r\n * const option: ISystemOption = {\r\n * category: 'alarm.type.mapping',\r\n * key: 'temp_to_high'\r\n * };\r\n *\r\n * (async () => {\r\n * const {data, res} = await systemOptionsService.detail(option);\r\n * })();\r\n * ```\r\n */\r\n async detail(option: ISystemOption): Promise<IResult<ISystemOption>> {\r\n return super.detail(option);\r\n }\r\n\r\n /**\r\n * Gets the list of system options filtered by parameters.\r\n *\r\n * @returns Response wrapped in [[IResultList]]\r\n *\r\n * @param {object} filter Object containing filters for querying system options.\r\n *\r\n * **Example**\r\n * ```typescript\r\n *\r\n * const filter: object = {\r\n * pageSize: 100,\r\n * withTotalPages: true\r\n * };\r\n *\r\n * (async () => {\r\n * const {data, res, paging} = await systemOptionsService.list(filter);\r\n * })();\r\n * ```\r\n */\r\n async list(filter: object = {}): Promise<IResultList<ISystemOption>> {\r\n const headers = { 'content-type': 'application/json' };\r\n const url = this.listUrl;\r\n const res = await this.fetch(url, { headers, params: filter });\r\n const json = await res.json();\r\n const data = json[this.propertyName];\r\n\r\n return { res, data };\r\n }\r\n\r\n protected getDetailUrl(option: ISystemOption): string {\r\n return `${this.listUrl}/${option.category}/${option.key}`;\r\n }\r\n\r\n protected onBeforeCreate(obj: ISystemOption): any {\r\n return obj;\r\n }\r\n}\r\n","import { Service, IResultList, IResult, IIdentified } from '../core';\nimport { ITenantOption } from './ITenantOption';\nimport { ITenantOptionDetailParams } from './ITenantOptionDetailParams';\n\n/**\n * @description\n * This service allows for managing tenant's options.\n */\nexport class TenantOptionsService extends Service<ITenantOption> {\n protected baseUrl = 'tenant';\n protected listUrl = 'options';\n protected propertyName = 'options';\n\n private securityOptionsCategories = ['password'];\n private securityOptionsListUrl = 'security-options';\n private systemOptions = 'system';\n\n /**\n * Get a representation of a tenant's option.\n *\n * @param entity Tenant option object.\n * @param params Additional query parameters.\n *\n * @returns Returns promise object that is resolved with\n * the ITenantOption wrapped by IResult.\n *\n * **Example**\n * ```typescript\n * const option: ITenantOption = {\n * category: 'access.control',\n * key: 'allow.origin'\n * };\n * const params: ITenantOptionDetailParams = {\n * evaluate: 'inherited'\n * };\n * (async () => {\n * const { data, res } = await tenantService.detail(option);\n * console.log('value inherited from parent tenant:', data.value);\n * })();\n * ```\n *\n * Required role: ROLE_OPTION_MANAGEMENT_READ\n */\n async detail(\n entity: ITenantOption,\n params: ITenantOptionDetailParams = {}\n ): Promise<IResult<ITenantOption>> {\n return super.detail(entity, params);\n }\n\n /**\n * Creates a new tenant's option.\n *\n * @param {ITenantOption} entity Tenant's Option object.\n *\n * @returns {IResult<IIdentified>} Returns promise object that is resolved with\n * the details of newly created tenant option.\n *\n * **Example**\n * ```typescript\n *\n * const tenantObject = {\n * id: \"sample_tenant\",\n * company: \"sample_company\",\n * domain: \"sample_domain.com\",\n * contactName: \"Mr. Doe\",\n * ...\n * };\n *\n * (async () => {\n * const {data, res} = await tenantService.create(tenantObject);\n * })();\n * ```\n *\n * Required role: ROLE_OPTION_MANAGEMENT_ADMIN<br><br>\n * Options are category-key-value tuples, storing tenant configuration.Some categories of options\n * allow creation of new one, other are limited to predefined set of keys.<br><br>\n * Any option of any tenant can be defined as \"non-editable\" by \"management\" tenant. Afterwards, any PUT or DELETE\n * requests made on that option by the owner tenant, will result in 403 error (Unauthorized).\n */\n async create(entity: ITenantOption): Promise<IResult<ITenantOption>> {\n return super.create(entity);\n }\n\n /**\n * Updates tenant's option data.\n *\n * @param {ITenantOption} entity Tenant option is partially updatable.\n *\n * @returns {IResult<ITenantOption>} Returns promise object that is resolved with the saved tenant option object.\n *\n * **Example**\n * ```typescript\n *\n * const partialUpdateObject: IIdentified = {\n * value : \"http://developer.cumulocity.com\"\n * ...\n * }\n *\n * (async () => {\n * const {data, res} = await tenantOptionsService.update(partialUpdateObject);\n * })();\n * ```\n *\n * Required role: ROLE_OPTION_MANAGEMENT_ADMIN\n */\n async update(entity: ITenantOption): Promise<IResult<ITenantOption>> {\n return super.update(entity);\n }\n\n /**\n * Gets the list of tenant's options filtered by parameters.\n *\n * @param {object} filter Object containing filters for querying tenant options.\n *\n * @returns {IResultList<ITenantOption>} Returns promise object that is resolved\n * with the ITenantOption wrapped by IResultList.\n *\n * **Example**\n * ```typescript\n *\n * const filter: object = {\n * severity: Severity.MAJOR,\n * pageSize: 100,\n * withTotalPages: true\n * };\n *\n * (async () => {\n * const {data, res, paging} = await tenantOptionsService.list(filter);\n * })();\n * ```\n *\n * Required role: ROLE_OPTION_MANAGEMENT_READ\n */\n async list(filter: object = {}): Promise<IResultList<ITenantOption>> {\n return super.list(filter);\n }\n\n /**\n * Delete a representation of a tenant's option.\n *\n * @param {string|number|IIdentified} entityOrId Tenant's option id or tenant's option object.\n *\n * @returns Returns promise object that is resolved with the IResult.\n *\n * **Example**\n * ```typescript\n *\n * const tenantOptionId: string = \"uniqueTenantId\";\n *\n * (async () => {\n * const {data, res} = await tenantOptionsService.delete(tenantOptionId);\n * })();\n * ```\n *\n * Required role: ROLE_TENANT_MANAGEMENT_ADMIN\n */\n async delete(entityOrId: string | number | IIdentified): Promise<IResult<null>> {\n return super.delete(entityOrId);\n }\n\n protected getDetailUrl(entity: ITenantOption): string {\n const encodedCategory = encodeURIComponent(entity.category);\n const encodedKey = encodeURIComponent(entity.key);\n if (this.securityOptionsCategories.indexOf(entity.category) > -1) {\n return `${this.securityOptionsListUrl}/${encodedCategory}/${encodedKey}`;\n } else {\n return `${this.listUrl}/${encodedCategory}/${encodedKey}`;\n }\n }\n\n protected onBeforeCreate(obj: ITenantOption): any {\n return obj;\n }\n}\n","import { Service, IResult } from '../core';\nimport { ITenantSecurityOption } from './ITenantSecurityOption';\n\n/**\n * @description\n * This service allows to get tenant security option.\n */\nexport class TenantSecurityOptionsService extends Service<ITenantSecurityOption> {\n protected baseUrl = 'tenant';\n protected listUrl = 'security-options';\n protected category = 'password';\n protected propertyName = 'options';\n\n /**\n * Get a specific tenant's security option.\n *\n * @param {ITenantSecurityOption} Tenant's security option object with key value.\n *\n * @returns Returns promise object that is resolved with the ITenantSecurityOption wrapped by IResult.\n *\n * **Example**\n * ```typescript\n *\n * const option: ITenantSecurityOption = {\n * key: 'limit.validity'\n * };\n *\n * (async () => {\n * const {data, res} = await tenantSecurityOptionsService.detail(option);\n * })();\n * ```\n */\n async detail(\n tenantSecurityOption: ITenantSecurityOption\n ): Promise<IResult<ITenantSecurityOption>> {\n return super.detail(tenantSecurityOption);\n }\n\n protected getDetailUrl(tenantSecurityOption: ITenantSecurityOption): string {\n return `${this.listUrl}/${this.category}/${tenantSecurityOption.key}`;\n }\n\n protected onBeforeCreate(obj: ITenantSecurityOption): any {\n return obj;\n }\n}\n","import { IIdentified, IResult, IResultList, Service } from '../core';\nimport { ITenantLoginOption } from './ITenantLoginOptions';\n\n/**\n * @description\n * This service allows to get tenant login options.\n */\nexport class TenantLoginOptionsService extends Service<ITenantLoginOption> {\n protected baseUrl = 'tenant';\n protected listUrl = 'loginOptions';\n protected propertyName = 'loginOptions';\n\n /**\n * Gets the details of login option.\n *\n * @param entityIdentityOrId Login option's id or login option object.\n *\n * @returns Returns promise object that is resolved with the ITenantLoginOption wrapped by IResult.\n *\n * **Example**\n * ```typescript\n *\n * const tenantLoginOptionId: string = 'uniqueTenantLoginOptionId';\n *\n * (async () => {\n * const {data, res} = await tenantLoginOptionsService.detail(tenantLoginOptionId);\n * })();\n * ```\n */\n async detail(entityIdentityOrId: string | IIdentified): Promise<IResult<ITenantLoginOption>> {\n return super.detail(entityIdentityOrId);\n }\n\n /**\n * Gets the list of tenant's login options filtered by parameters.\n *\n * @param filter Object containing filters for querying tenant's login options.\n *\n * @returns Returns promise object that is resolved with the ITenantLoginOption wrapped by IResultList.\n *\n * **Example**\n * ```typescript\n *\n * const filter: object = {\n * tenantId: '1111111'\n * };\n *\n * (async () => {\n * const {data, res, paging} = await tenantLoginOptionsService.list(filter);\n * })();\n * ```\n */\n async list(filter: object = {}): Promise<IResultList<ITenantLoginOption>> {\n return super.list(filter);\n }\n\n /**\n * Gets the list of all tenant's login options for current tenant.\n *\n * @returns Returns promise object that is resolved with the ITenantLoginOption wrapped by IResultList.\n *\n * **Example**\n * ```typescript\n *\n * (async () => {\n * const {data, res, paging} = await tenantLoginOptionsService.listForCurrentTenant();\n * })();\n * ```\n */\n async listForCurrentTenant(): Promise<IResultList<ITenantLoginOption>> {\n return super.list({ tenantId: this.client.tenant });\n }\n\n /**\n * Gets the list of all tenant's login options for management tenant.\n *\n * @returns Returns promise object that is resolved with the ITenantLoginOption wrapped by IResultList.\n *\n * **Example**\n * ```typescript\n *\n * (async () => {\n * const {data, res, paging} = await tenantLoginOptionsService.listForManagement();\n * })();\n * ```\n */\n async listForManagement(): Promise<IResultList<ITenantLoginOption>> {\n return super.list({ management: true });\n }\n\n /**\n * Creates a new tenant login option.\n *\n * @param entity ITenantLoginOption object.\n *\n * @returns Returns promise object that is resolved with the details of newly created tenant login option.\n *\n * **Example**\n * ```typescript\n *\n * const tenantLoginOption: ITenantLoginOption = {\n * grantType: \"PASSWORD\",\n * providerName: \"Cumulocity\",\n * type: \"BASIC\",\n * userManagementSource: \"INTERNAL\",\n * visibleOnLoginPage: true\n * };\n *\n * (async () => {\n * const {data, res} = await tenantLoginOptionsService.create(tenantLoginOption);\n * })();\n * ```\n */\n async create(entity: ITenantLoginOption): Promise<IResult<ITenantLoginOption>> {\n return super.create(entity);\n }\n\n /**\n * Updates tenant's login option data.\n *\n * @param entity ITenantLoginOption object.\n *\n * @returns Returns promise object that is resolved with the saved tenant's login option object.\n *\n * **Example**\n * ```typescript\n *\n * const tenantLoginOption: ITenantLoginOption = {\n * grantType: \"PASSWORD\",\n * id: \"2eff9a0b-e376-4ce8-a0f1-0a07cef8a8a1\",\n * providerName: \"Cumulocity\",\n * type: \"BASIC\",\n * userManagementSource: \"INTERNAL\",\n * visibleOnLoginPage: true\n * };\n *\n * (async () => {\n * const {data, res} = await tenantLoginOptionsService.update(tenantLoginOption);\n * })();\n * ```\n */\n async update(entity: ITenantLoginOption): Promise<IResult<ITenantLoginOption>> {\n return super.update(entity);\n }\n\n /**\n * Update tenant's login option data if id exists in object, otherwise create new entity.\n *\n * @param entity ITenantLoginOption object.\n *\n * @returns Returns promise object that is resolved with the saved tenant's login option object.\n *\n * **Example**\n * ```typescript\n *\n * const tenantLoginOption: ITenantLoginOption = {\n * grantType: \"PASSWORD\",\n * id: \"2eff9a0b-e376-4ce8-a0f1-0a07cef8a8a1\",\n * providerName: \"Cumulocity\",\n * type: \"BASIC\",\n * userManagementSource: \"INTERNAL\",\n * visibleOnLoginPage: true\n * };\n *\n * (async () => {\n * const {data, res} = await tenantLoginOptionsService.save(tenantLoginOption);\n * })();\n * ```\n */\n async save(entity: ITenantLoginOption): Promise<IResult<ITenantLoginOption>> {\n return entity.id ? this.update(entity) : this.create(entity);\n }\n\n /**\n * Removes tenant's login option.\n *\n * @param entityOrId Tenant's login option's id or tenant's login option object.\n *\n * @returns Returns promise object that is resolved with the IResult of null.\n *\n * **Example**\n * ```typescript\n *\n * const tenantLoginOptionId: string = 'uniqueTenantLoginOptionId';\n *\n * (async () => {\n * const {data, res} = await tenantLoginOptionsService.delete(tenantLoginOptionId);\n * })();\n * ```\n */\n async delete(entityOrId: string | IIdentified): Promise<IResult<null>> {\n return super.delete(entityOrId);\n }\n}\n","/**\n * A list of supported [[ITenantLoginOption]] which\n * describe the way a user can login to the Platform.\n */\nimport { TfaStrategy } from '../tenant';\n\nexport interface ITenantLoginOptions {\n /**\n * Link to the resource\n */\n self?: string;\n /**\n * The list of tenant login options\n */\n loginOptions: ITenantLoginOption[];\n}\n\n/**\n * Describes the login option which can be requested by any\n * application on startup without login. It describes which kind\n * of login mechanism (e.g. Basic, SSO or OAI-Secure) is\n * supported by the current Platform.\n */\nexport interface ITenantLoginOption {\n /**\n * Identifies the login option\n */\n id?: string;\n /**\n * Login option type\n */\n type?: TenantLoginOptionType;\n /**\n * Grant type\n */\n grantType?: GrantType;\n /**\n * The origin of the users REMOTE or INTERNAL\n */\n userManagementSource: UserManagementSource;\n /**\n * Link to the resource\n */\n self?: string;\n /**\n * The strategy for Two Factor Authentication\n */\n tfaStrategy?: TfaStrategy;\n /**\n * Indicates whether the login option should be visible on the login page of UI applications.\n * If set to `true` for more than one login option, then the preferred one will be selected according to priority:\n * 1. OAI-Secure: authentication information is stored in a HttpOnly cookie\n * 2. Basic Auth: authentication information is stored in a session storage\n * 3. SSO redirect: allows a user to login with a single 3rd-party authorization server using the OAuth2 protocol.\n * If no login option has `visibleOnLoginPage` set to `true`, the preferred login option will be Basic Auth.\n */\n visibleOnLoginPage?: boolean;\n /**\n * The label which is shown on the login button\n */\n buttonName?: string;\n /**\n * The request which is used to initialize an oauth flow\n */\n initRequest?: string;\n /**\n * Determines if password strength is enforced on system level\n */\n enforceStrength?: boolean;\n /**\n * Minimum length of a password to be considered as a “green” strong one\n */\n greenMinLength?: number;\n /**\n * Determines if password strength is enforced on tenant level\n */\n strengthValidity?: boolean;\n /**\n * Organizations name which provides login option\n */\n providerName?: string;\n /**\n * Basic authentication restrictions.\n */\n authenticationRestrictions?: IAuthenticationRestrictions;\n /**\n * Configuration for OAI-Secure sessions.\n */\n sessionConfiguration?: ISessionConfiguration;\n /**\n * Tenant correct domain for OAI-Secure login option.\n * UI will redirect to this domain if OAI-Secure is\n * set as preferred login mode and domain in browser is wrong.\n */\n loginRedirectDomain?: string;\n}\n\nexport interface IAuthenticationRestrictions {\n /**\n * The list of user agents which are allowed to use the platform's REST API.\n * The values are compared with `User-Agent` HTTP header.\n */\n trustedUserAgents: string[];\n\n /**\n * The list of user agents which are forbidden to use the platform's REST API.\n * The values are compared with `User-Agent` HTTP header.\n */\n forbiddenUserAgents: string[];\n\n /**\n * The list of clients which are forbidden to use the platform's REST API.\n * For now, the only value supported in the array is `'WEB_BROWSERS'` (which blocks all web browsers).\n */\n forbiddenClients: string[];\n}\n\nexport interface ISessionConfiguration {\n /**\n * The maximum amount of time a session can be active.\n */\n absoluteTimeoutMillis: number;\n /**\n * The maximum amount of sessions per user.\n */\n maximumNumberOfParallelSessions: number;\n /**\n * The timeout after which the session id is automatically renewed. If there is no activity after renewal timeout and before absolute session timeout, the session will not be renewed.\n */\n renewalTimeoutMillis: number;\n /**\n * If `true`, then every request needs to use the same `User-Agent` header as the first request which initiated the session.\n */\n userAgentValidationRequired: boolean;\n}\n\nexport enum TenantLoginOptionType {\n /**\n * OAI-Secure: authentication information is stored in a HttpOnly cookie\n */\n OAUTH2_INTERNAL = 'OAUTH2_INTERNAL',\n /**\n * SSO redirect: allows a user to login with a single 3rd-party authorization server using the OAuth2 protocol.\n */\n OAUTH2 = 'OAUTH2',\n /**\n * Basic Auth: authentication information is stored in a session storage\n */\n BASIC = 'BASIC'\n}\n\nexport enum GrantType {\n AUTHORIZATION_CODE = 'AUTHORIZATION_CODE',\n PASSWORD = 'PASSWORD'\n}\n\nexport enum UserManagementSource {\n REMOTE = 'REMOTE',\n INTERNAL = 'INTERNAL'\n}\n","import { Service, IResult, IResultList } from '../core';\nimport { IAuditRecord } from './IAuditRecord';\n\nexport class AuditService extends Service<IAuditRecord> {\n protected baseUrl = 'audit';\n protected listUrl = 'auditRecords';\n protected propertyName = 'auditRecords';\n\n /**\n * Gets the details of selected audit record.\n *\n * @param {string|number|IAuditRecord} entityOrId Entity or Id of the entity.\n *\n * @returns Response wrapped in [[IResult]]\n *\n * **Example**\n * ```typescript\n *\n * const auditId: number = 1;\n *\n * (async () => {\n * const {data, res} = await auditService.detail(auditId);\n * })();\n * ```\n */\n async detail(entityOrId: string | number | IAuditRecord): Promise<IResult<IAuditRecord>> {\n return super.detail(entityOrId);\n }\n\n /**\n * Creates a new audit record for a given source.\n *\n * @param {IAuditRecord} entity Audit record object with mandantory fragments.\n * IAuditRecord implements the [[IEvent]] interface.\n *\n * @returns Response wrapped in [[IResult]]\n *\n * **Example**\n * ```typescript\n *\n * const mandantoryObject: IAuditRecord = {\n * type: AuditRecordType.ALARM,\n * time: '2018-05-02T10:08:00Z',\n * severity: Severity.MAJOR,\n * source: {id: 1}\n * };\n *\n * (async () => {\n * const {data, res} = await auditService.create(mandantoryObject);\n * })();\n * ```\n */\n async create(entity: IAuditRecord): Promise<IResult<IAuditRecord>> {\n return super.create(entity);\n }\n\n /**\n * Gets the list of audit records filtered by parameters.\n *\n * @returns Response wrapped in [[IResultList]]\n *\n * @param {object} filter Object containing filters for querying audit records.\n *\n * **Example**\n * ```typescript\n *\n * const filter: object = {\n * severity: Severity.MAJOR,\n * pageSize: 100,\n * withTotalPages: true\n * };\n *\n * (async () => {\n * const {data, res, paging} = await auditService.list(filter);\n * })();\n * ```\n */\n async list(filter: object = {}): Promise<IResultList<IAuditRecord>> {\n return super.list(filter);\n }\n}\n","/**\n * A specific audit record can have one of the following types\n */\nexport enum AuditRecordType {\n ALARM = 'Alarm',\n BULK_OPERATION = 'BulkOperation',\n CEP_MODULE = 'CepModule', // FIXME: legacy type. Remains because there might be audits from before migration to apama.\n EVENT = 'Event',\n INVENTORY = 'Inventory',\n INVENTORY_ROLE = 'InventoryRole',\n OPERATION = 'Operation',\n OPTION = 'Option',\n GROUP = 'Group',\n SMART_RULE = 'SmartRule',\n SYSTEM = 'SYSTEM',\n TENANT = 'Tenant',\n USER = 'User'\n}\n","import { gettext } from '../gettext';\r\n\r\n/**\r\n * An audit record can have one of the following change type\r\n */\r\nexport enum ChangeType {\r\n ADDED = gettext('ADDED'),\r\n REPLACED = gettext('REPLACED'),\r\n REMOVED = gettext('REMOVED')\r\n}\r\n","import { IIdentified, Service, IResult, IResultList } from '../core';\n\nexport class InventoryRoleService extends Service<IIdentified> {\n protected baseUrl = 'user';\n protected listUrl = 'inventoryroles';\n protected propertyName = 'roles';\n\n /**\n * Gets the details of inventory role.\n *\n * @param {string|number|IIdentified} entityOrId Entity or Id of the entity.\n *\n * @returns Response wrapped in [[IResult]]\n *\n * **Example**\n * ```typescript\n *\n * const inventoryRoleId: number = 1;\n *\n * (async () => {\n * const {data, res} = await inventoryRoleService.detail(inventoryRoleId);\n * })();\n * ```\n */\n async detail(entityOrId: string | number | IIdentified): Promise<IResult<IIdentified>> {\n return super.detail(entityOrId);\n }\n\n /**\n * Creates a new inventory role.\n *\n * @param {IIdentified} entity\n *\n * @returns Response wrapped in [[IResult]]\n *\n * **Example**\n * ```typescript\n *\n * const newRole: IIdentified = {\n * name: 'Custom role'\n * };\n *\n * (async () => {\n * const {data, res} = await inventoryRoleService.create(newRole);\n * })();\n * ```\n */\n async create(entity: IIdentified): Promise<IResult<IIdentified>> {\n return super.create(entity);\n }\n\n /**\n * Updates inventory role data.\n *\n * @param {IIdentified} entity\n *\n * @returns Response wrapped in [[IResult]]\n *\n * **Example**\n * ```typescript\n *\n * const updateObject: IIdentified = {\n * id: 1,\n * name: 'changed role'\n * };\n *\n * (async () => {\n * const {data, res} = await inventoryRoleService.update(updateObject);\n * })();\n * ```\n */\n async update(entity: IIdentified): Promise<IResult<IIdentified>> {\n return super.update(entity);\n }\n\n /**\n * Gets the list of inventory roles filtered by parameters.\n *\n * @returns Response wrapped in [[IResultList]]\n *\n * @param {object} filter Object containing filters for querying alarms.\n *\n * **Example**\n * ```typescript\n *\n * const filter: object = {\n * pageSize: 100,\n * withTotalPages: true\n * };\n *\n * (async () => {\n * const {data, res, paging} = await inventoryRoleService.list(filter);\n * })();\n * ```\n */\n async list(filter: object = {}): Promise<IResultList<IIdentified>> {\n return super.list(filter);\n }\n\n /**\n * Removes an inventory role with given id.\n *\n * @returns Response wrapped in [[IResult]]\n *\n * @param {IExternalIdentity} identity Identity object with mandantory fragments.\n *\n * **Example**\n * ```typescript\n *\n * const id: number = 1;\n *\n * (async () => {\n * const {data, res} = await identityService.delete(id);\n * })();\n * ```\n */\n async delete(entityOrId: string | number | IIdentified): Promise<IResult<null>> {\n return super.delete(entityOrId);\n }\n}\n","import { gettext } from '../gettext';\n\n/**\n * Device registration can have one of the following states.\n */\nexport enum DeviceRegistrationStatus {\n WAITING_FOR_CONNECTION = gettext('WAITING_FOR_CONNECTION'),\n PENDING_ACCEPTANCE = gettext('PENDING_ACCEPTANCE'),\n ACCEPTED = gettext('ACCEPTED'),\n BLOCKED = gettext('BLOCKED')\n}\n","import { btoa } from 'b2a';\nimport { IIdentified, Service, IResult, IResultList } from '../core';\nimport {\n IDeviceRegistration,\n IDeviceRegistrationAccept,\n IDeviceRegistrationCreate,\n IDeviceRegistrationLimit\n} from './IDeviceRegistration';\nimport { DeviceRegistrationStatus } from './DeviceRegistrationStatus';\nimport { IDeviceCredentials } from './IDeviceCredentials';\n\n/**\n * Interface to use as options parameter\n * to bootstrap a new device.\n */\nexport interface IDeviceBootstrapOptions {\n /**\n * If already logged in it is accessible via\n * client.auth.getFetchOptions, see [[BasicAuth.getFetchOptions]]\n *\n * **Example**\n * ``` typescript\n *\n * // tenant/username:password\n * const basicAuthToken = 'Basic dGVuYW50L3VzZXJuYW1lOnBhc3N3b3Jk';\n * ```\n */\n basicAuthToken?: string;\n /**\n * Object to define username and password\n * as string.\n *\n * **Example**\n * ``` typescript\n *\n * const basicAuth = {\n * user: 'username',\n * pass: 'password'\n * }\n * ```\n */\n basicAuth?: {\n user: string;\n pass: string;\n };\n}\n\n/**\n * This class allows registration of a new device.\n */\nexport class DeviceRegistrationService extends Service<IDeviceRegistration> {\n protected baseUrl = 'devicecontrol';\n protected listUrl = 'newDeviceRequests';\n protected propertyName = 'newDeviceRequests';\n\n /**\n * Gets the details of device registration.\n *\n * @param {string|number|IIdentified} entityOrId Entity or Id of the entity.\n *\n * @returns Response wrapped in [[IResult]]\n *\n * **Example**\n * ```typescript\n *\n * const entityId: number = 1;\n *\n * (async () => {\n * const {data, res} = await deviceRegistrationService.detail(entityId);\n * })();\n * ```\n */\n async detail(entityOrId: string | number | IIdentified) {\n return super.detail(entityOrId);\n }\n\n /**\n * Creates a new device registration.\n *\n * @param {IDeviceRegistrationCreate} entity Device registration object with mandantory fragments.\n *\n * @returns Response wrapped in [[IResult]]\n *\n * **Example**\n * ```typescript\n *\n * const mandantoryObject: IDeviceRegistrationCreate = {\n * id: 1,\n * };\n *\n * (async () => {\n * const {data, res} = await deviceRegistrationService.create(mandantoryObject);\n * })();\n * ```\n */\n async create(entity: IDeviceRegistrationCreate) {\n return super.create(entity);\n }\n\n /**\n * Gets the list of device registrations by parameters.\n *\n * @returns Response wrapped in [[IResultList]]\n *\n * @param {object} filter Object containing filters for querying registrations.\n *\n * **Example**\n * ```typescript\n *\n * const filter: object = {\n * pageSize: 100,\n * withTotalPages: true\n * };\n *\n * (async () => {\n * const {data, res, paging} = await deviceRegistrationService.list(filter);\n * })();\n * ```\n */\n async list(filter: object = {}) {\n return super.list(filter);\n }\n\n /**\n * Removes an registration with given id.\n *\n * @returns Response wrapped in [[IResult]]\n *\n * @param {string | number | IIdentified} entityOrId entity or id of the registration.\n *\n * **Example**\n * ```typescript\n *\n * const id = 'abc';\n *\n * (async () => {\n * const {data, res} = await deviceRegistrationService.delete(id);\n * // data will be null\n * })();\n * ```\n */\n async delete(entityOrId: string | number | IIdentified) {\n return super.delete(entityOrId);\n }\n\n /**\n * Accepts the device registration for given id.\n *\n * @returns Response wrapped in [[IResult]]\n *\n * @param {string | number | IIdentified} entityOrId entity or id of registration.\n *\n * **Example**\n * ```typescript\n *\n * const id = 'abc';\n *\n * (async () => {\n * const {data, res} = await deviceRegistrationService.accept(id);\n * })();\n * ```\n */\n async accept(entityOrId: string | number | IIdentified): Promise<IResult<IDeviceRegistration>> {\n const securityToken: string = this.getSecurityToken(entityOrId);\n let payload: Partial<IDeviceRegistration> = {\n id: this.getIdString(entityOrId),\n status: DeviceRegistrationStatus.ACCEPTED\n };\n\n if (securityToken) {\n payload = {\n ...payload,\n securityToken\n };\n }\n return super.update(payload);\n }\n\n /**\n * Accepts the device registration for all registrations in pending acceptance.\n *\n * @returns Response wrapped in [[IResultList]]\n *\n * **Example**\n * ```typescript\n *\n * (async () => {\n * const {data, res} = await deviceRegistrationService.acceptAll();\n * })();\n * ```\n */\n async acceptAll(): Promise<IResultList<IDeviceRegistrationAccept>> {\n const res = await super.fetch(`${this.listUrl}/acceptAll`, { method: 'POST' });\n const data = (await res.json()) as IDeviceRegistrationAccept[];\n return { res, data };\n }\n\n /**\n * Gets limitation information for registering devices to the platform\n *\n * @returns Response wrapped in [[IResult]]\n *\n * **Example**\n * ```typescript\n *\n * (async () => {\n * const {data, res} = await deviceRegistrationService.limit();\n * })();\n * ```\n */\n async limit(): Promise<IResult<IDeviceRegistrationLimit>> {\n const res = await super.fetch(`${this.listUrl}/limit`);\n const data = (await res.json()) as IDeviceRegistrationLimit;\n return { res, data };\n }\n\n /**\n * Bootstraps the device with given id.\n *\n * @param entityOrId entity or id of registration.\n * @param options for details see [[IDeviceBootstrapOptions]]\n *\n * **Example**\n * ```typescript\n *\n * const id: 'abc';\n * const options: IDeviceBootstrapOptions = {\n * basicAuthToken: 'Basic dGVuYW50L3VzZXJuYW1lOnBhc3N3b3Jk',\n * basicAuth: {\n * user: 'username',\n * pass: 'password'\n * }\n * };\n *\n * (async () => {\n * const {data, res} = await deviceRegistrationService.bootstrap(id, options);\n * })();\n * ```\n */\n async bootstrap(\n entityOrId: string | number | IIdentified,\n options: IDeviceBootstrapOptions\n ): Promise<IResult<IDeviceCredentials>> {\n const id = this.getIdString(entityOrId);\n const securityToken = this.getSecurityToken(entityOrId);\n const body = securityToken ? JSON.stringify({ id, securityToken }) : JSON.stringify({ id });\n const url = `${this.baseUrl}/deviceCredentials`;\n const { basicAuth } = options;\n let { basicAuthToken } = options;\n if (basicAuth) {\n const { user, pass } = basicAuth;\n basicAuthToken = btoa(`${user}:${pass}`);\n }\n const headers = {\n Authorization: `Basic ${basicAuthToken}`,\n accept: 'application/json',\n 'content-type': 'application/json'\n };\n const method = 'POST';\n const res = await this.client.fetch(url, { body, headers, method });\n const data = await res.json();\n if (res.status > 400) {\n throw { res, data };\n }\n return { res, data };\n }\n\n protected onBeforeCreate(entity: IDeviceRegistrationCreate): IDeviceRegistrationCreate {\n return entity;\n }\n\n protected onBeforeUpdate(entity: IDeviceRegistrationCreate): IDeviceRegistrationCreate {\n const noIdEntity = Object.assign({}, entity);\n delete noIdEntity.id;\n return noIdEntity;\n }\n\n protected getDetailUrl(entityOrId: string | number | IIdentified): string {\n const id = encodeURIComponent(this.getEntityId(entityOrId));\n return `${this.listUrl}/${id}`;\n }\n\n private getSecurityToken(entity: string | number | IIdentified): string {\n let securityToken: string;\n if (typeof entity === 'object') {\n securityToken = entity.securityToken ? String(entity.securityToken) : undefined;\n }\n return securityToken;\n }\n}\n","import FormData from 'form-data';\nimport { Stream } from 'stream';\nimport { IFetchClient, IResult } from '../core';\nimport { IDeviceRegistrationBulkResult } from './IDeviceRegistrationBulkResult';\n\n/**\n * This class allows for bulk registering devices.\n */\nexport class DeviceRegistrationBulkService {\n protected client: IFetchClient;\n\n /**\n * Instantiate class and assign client\n * @param {IFetchClient} client\n */\n constructor(client: IFetchClient) {\n this.client = client;\n }\n\n /**\n * A new device registration as bulk.\n *\n * @param {Stream | Buffer} csv\n *\n * @returns Response wrapped in [[IResult]]\n *\n * **Example**\n * ```typescript\n *\n * const csvString = `\n * ID,CREDENTIALS,TENANT,TYPE,NAME,ICCID,IDTYPE,PATH,SHELL\n * e2eDeviceRegistrationId,e2epassword123!,e2edocker,c8y_e2eDevice,e2eDevice,123456789,89456,e2eDeviceGroup,1\n * 900001,e2epassword123!,e2edocker,c8y_e2eDevice1,e2eDevice1,123456789,89456,e2eDeviceGroup,1\n * 900002,e2epassword123!,e2edocker,c8y_e2eDevice2,e2eDevice2,123456789,89456,e2eDeviceGroup,1`.trim();\n *\n * const csvBuffer = Buffer.from(csvString):\n *\n * (async () => {\n * const {data, res} = await deviceRegistrationBulkService.create(csvBuffer);\n * })();\n * ```\n */\n async create(\n inputFile: Stream | Buffer | File | Blob\n ): Promise<IResult<IDeviceRegistrationBulkResult>> {\n let csv = inputFile;\n const url = '/devicecontrol/bulkNewDeviceRequests';\n const method = 'POST';\n const body = new FormData();\n let fileName = 'bulk-registration.csv';\n if (typeof File !== 'undefined' && csv instanceof File) {\n fileName = csv.name;\n const checkPattern = /\\.csv$/;\n if (csv.name.match(checkPattern)) {\n csv = new File([csv], csv.name, { type: 'text/csv' });\n }\n }\n body.append('file', csv, fileName);\n const headers = {\n accept: 'application/json'\n };\n const res = await this.client.fetch(url, { method, body, headers });\n const data = await res.json();\n return { res, data };\n }\n}\n","/**\n * Device registration can have one of the following security modes.\n */\nexport enum DeviceRegistrationSecurityMode {\n REQUIRED = 'REQUIRED',\n OPTIONAL = 'OPTIONAL',\n IGNORED = 'IGNORED'\n}\n","import { Service } from '../core';\nimport { IRole } from './IRole';\n\n/**\n * @description\n * This service allows for fetch user roles.\n */\nexport class UserRoleService extends Service<IRole> {\n protected baseUrl = 'user';\n protected listUrl = 'roles';\n protected propertyName = 'roles';\n\n /**\n * Gets the details of given role.\n *\n * @param {string|number|IRole} entityOrId Roles's id or role object.\n *\n * @returns Returns promise object that is resolved with the IRole wrapped by IResult.\n *\n * **Example**\n * ```typescript\n *\n * const roleId: number = 1;\n *\n * (async () => {\n * const {data, res} = await userRoleService.detail(roleId);\n * })();\n * ```\n */\n async detail(entityOrId: string | number | IRole) {\n return super.detail(entityOrId);\n }\n\n /**\n * Gets the list of user roles filtered by parameters.\n *\n * @param {object} filter Object containing filters for querying roles.\n *\n * @returns Returns promise object that is resolved with the IRole wrapped by IResultList.\n *\n * **Example**\n * ```typescript\n *\n * const filter: object = {\n * severity: Severity.MAJOR,\n * pageSize: 100,\n * withTotalPages: true\n * };\n *\n * (async () => {\n * const {data, res, paging} = await userRoleService.list(filter);\n * })();\n * ```\n */\n async list(filter: object = {}) {\n return super.list(filter);\n }\n}\n","import { Service, IIdentified, IResult, ISource, IResultList } from '../core';\nimport { IUserGroup } from './IUserGroup';\nimport { IRoleReference } from '../user-role';\nimport { IUserReference } from '../user';\n\nenum ChildType {\n ROLES = 'roles',\n USERS = 'users'\n}\n\n/**\n * @description\n * This service allows for managing user groups.\n */\nexport class UserGroupService extends Service<IUserGroup> {\n protected baseUrl = 'user';\n protected propertyName = 'groups';\n\n protected get listUrl() {\n return `${this.client.tenant}/groups`;\n }\n\n /**\n * Gets the details of given user group.\n *\n * @param {string|number|IUserGroup} entityOrId Group's id or role object.\n *\n * @returns Returns promise object that is resolved with the IUserGroup wrapped by IResult.\n *\n * **Example**\n * ```typescript\n *\n * const groupId: number = 1;\n *\n * (async () => {\n * const {data, res} = await userGroupService.detail(roleId);\n * })();\n * ```\n */\n async detail(entityOrId: string | number | IUserGroup): Promise<IResult<IUserGroup>> {\n return super.detail(entityOrId);\n }\n\n /**\n * Creates a new user group.\n *\n * @param {IUserGroup} entity User Group object.\n *\n * @returns {IResult<IUserGroup>} Returns promise object that is resolved with\n * the details of newly created user group.\n *\n * **Example**\n * ```typescript\n *\n * const userGroupObject: IUserGroup = {\n * name: \"new user group\"\n * };\n *\n * (async () => {\n * const {data, res} = await userGroupService.create(userGroupObject);\n * })();\n * ```\n */\n async create(entity: Partial<IUserGroup>): Promise<IResult<IUserGroup>> {\n return super.create(entity);\n }\n\n /**\n * Updates user group data.\n *\n * @param {Partial<IUserGroup>} entity User group is partially updatable.\n *\n * @returns {IResult<IUserGroup>} Returns promise object that is resolved with the saved user group object.\n *\n * **Example**\n * ```typescript\n *\n * const partialUpdateObject: Partial<IUserGroup> = {\n * \"id\" : 1,\n * \"self\" : \"[URL to this resource]\",\n * \"name\" : \"PlatformAdministrators\",\n * ...\n * }\n *\n * (async () => {\n * const {data, res} = await userGroupService.update(partialUpdateObject);\n * })();\n * ```\n */\n async update(entity: Partial<IUserGroup>): Promise<IResult<IUserGroup>> {\n return super.update(entity);\n }\n\n /**\n * Gets the list of user groups filtered by parameters.\n *\n * @param {object} filter Object containing filters for querying User Groups.\n *\n * @returns Returns promise object that is resolved with the IUserGroup wrapped by IResultList.\n *\n * **Example**\n * ```typescript\n *\n * const filter: object = {\n * severity: Severity.MAJOR,\n * pageSize: 100,\n * withTotalPages: true\n * };\n *\n * (async () => {\n * const {data, res, paging} = await userGroupService.list(filter);\n * })();\n * ```\n */\n async list(filter: object = {}): Promise<IResultList<IUserGroup>> {\n return super.list(filter);\n }\n\n /**\n * Removes user group.\n *\n * @param {number | IIdentified} entityOrId User group's id or user group object.\n *\n * @returns Returns promise object that is resolved with the IResult of null.\n *\n * **Example**\n * ```typescript\n *\n * const userGroupId: number = 1;\n *\n * (async () => {\n * const {data, res} = await userGroupService.delete(userGroupId);\n * })();\n * ```\n * When group is removed, suitable audit records are created with type 'User'\n * and activity 'User updated' with information that user has been removed from group.\n *\n * Please, note that the ADMINS and DEVICES groups can not be deleted.\n */\n async delete(entityOrId: number | IIdentified): Promise<IResult<null>> {\n return super.delete(entityOrId);\n }\n\n /**\n * Assign role to user group.\n *\n * @param {string | number | Partial<IUserGroup>} entityOrId User group's id or user group object.\n * @param {string | Partial<ISource>} childEntityOrSelf Url to role resource or IRoleReference object.\n *\n * @returns Returns promise object that is resolved with the IRoleReference wrapped by IResult.\n *\n * **Example**\n * ```typescript\n *\n * const userGroupId: number = 1;\n * const roleResource: string = \"[URL to the Role resource]\";\n *\n * (async () => {\n * const {data, res} = await userGroupService.addRoleToGroup(userGroupId, roleResource);\n * })();\n * ```\n * When role is assigned to user, suitable audit record is created with type 'User' and activity 'User updated'.\n */\n async addRoleToGroup(\n entityOrId: string | number | Partial<IUserGroup>,\n childEntityOrSelf: string | Partial<ISource>\n ): Promise<IResult<IRoleReference>> {\n return this.addChild(ChildType.ROLES, entityOrId, childEntityOrSelf) as Promise<\n IResult<IRoleReference>\n >;\n }\n\n /**\n * Unassign role from user\n *\n * @param {string | number | Partial<IUserGroup>} entityOrId User group's id or user group object.\n * @param {string | Partial<ISource>} childEntityOrSelf Url to user resource or IRoleReference object.\n *\n * @returns Returns promise object that is resolved with the IResult of null.\n *\n * **Example**\n * ```typescript\n *\n * const userGroupId: number = 1;\n * const userResource: string = \"[URL to the Role resource]\";\n *\n * (async () => {\n * const {data, res} = await userGroupService.removeRoleFromGroup(userGroupId, userResource);\n * })();\n * ```\n */\n async removeRoleFromGroup(\n entityOrId: string | number | Partial<IUserGroup>,\n childEntityOrSelf: string | Partial<ISource>\n ): Promise<IResult<null>> {\n return this.removeChild(ChildType.ROLES, entityOrId, childEntityOrSelf);\n }\n\n /**\n * Assign user to user group.\n *\n * @param {string | number | Partial<IUserGroup>} entityOrId User group's id or user group object.\n * @param {string | Partial<ISource>} childEntityOrSelf Url to user resource or IUserReference object.\n *\n * @returns Returns promise object that is resolved with the IUserReference wrapped by IResult.\n *\n * **Example**\n * ```typescript\n *\n * const userGroupId: number = 1;\n * const userResource: string = \"[URL to the User resource]\";\n *\n * (async () => {\n * const {data, res} = await userGroupService.addUserToGroup(userGroupId, userResource);\n * })();\n * ```\n * When user is added to group, suitable audit record is created with type 'User' and activity 'User updated'.\n */\n async addUserToGroup(\n entityOrId: string | number | Partial<IUserGroup>,\n childEntityOrSelf: string | Partial<ISource>\n ): Promise<IResult<IUserReference>> {\n return this.addChild(ChildType.USERS, entityOrId, childEntityOrSelf) as Promise<\n IResult<IUserReference>\n >;\n }\n\n /**\n * Remove user from a group\n *\n * @param {string | number | Partial<IUserGroup>} entityOrId User group's id or user group object.\n * @param {string | Partial<ISource>} childEntityOrSelf Url to user resource or IUserReference object.\n *\n * @returns Returns promise object that is resolved with the IResult of null.\n *\n * **Example**\n * ```typescript\n *\n * const userGroupId: number = 1;\n * const userResource: string = \"[URL to the User resource]\";\n *\n * (async () => {\n * const {data, res} = await userGroupService.removeUserFromGroup(userGroupId, userResource);\n * })();\n * ```\n * When user is removed from group, suitable audit record is created with type 'User' and activity 'User updated'.\n */\n async removeUserFromGroup(\n entityOrId: string | number | Partial<IUserGroup>,\n childEntityOrSelf: string | Partial<ISource>\n ): Promise<IResult<null>> {\n return this.removeChild(ChildType.USERS, entityOrId, childEntityOrSelf);\n }\n\n protected getSelf(childReference: string | Partial<ISource>): string {\n if (typeof childReference === 'object' && childReference.self) {\n return childReference.self;\n } else {\n return childReference as string;\n }\n }\n\n private getChildUrl(\n type: ChildType,\n userGroupOrId: string | number | Partial<IUserGroup>\n ): string {\n return `${this.getDetailUrl(userGroupOrId)}/${type}`;\n }\n\n private getChildReferenceAsBody(type: ChildType, childReference: string | Partial<ISource>) {\n const childSelf = this.getSelf(childReference);\n switch (type) {\n case ChildType.ROLES:\n return JSON.stringify({ role: { self: String(childSelf) } });\n case ChildType.USERS:\n return JSON.stringify({ user: { self: String(childSelf) } });\n }\n throw new Error('UserGroupService -> getChild -> unsupported child type');\n }\n\n private async addChild(\n type: ChildType,\n userGroupOrId: string | number | Partial<IUserGroup>,\n childReference: string | Partial<ISource>\n ): Promise<IResult<IUserReference | IRoleReference>> {\n const url = this.getChildUrl(type, userGroupOrId);\n const method = 'POST';\n const body = this.getChildReferenceAsBody(type, childReference);\n const headers = {\n accept: 'application/json',\n 'content-type': 'application/json'\n };\n const res = await this.fetch(url, { method, body, headers });\n let data = await res.json();\n data = data.managedObject;\n return { res, data };\n }\n\n private async removeChild(\n type: ChildType,\n userGroupOrId: string | number | Partial<IUserGroup>,\n childReference: string | IIdentified\n ): Promise<IResult<null>> {\n const childId = this.getIdString(childReference);\n const url = `${this.getChildUrl(type, userGroupOrId)}/${encodeURIComponent(String(childId))}`;\n const method = 'DELETE';\n const headers = { accept: 'application/json' };\n const res = await this.fetch(url, { method, headers });\n const data = null;\n return { res, data };\n }\n}\n","import { IResult, IResultList, IFetchClient, IFetchOptions, IFetchResponse } from '../core';\nimport { IExternalIdentity } from './IExternalIdentity';\n\n/**\n * This class allwos for managing external identifiers.\n */\nexport class IdentityService {\n private baseUrl = 'identity';\n private propertyName = 'externalIds';\n private client: IFetchClient;\n\n constructor(client: IFetchClient) {\n this.client = client;\n }\n\n /**\n * Gets the list of identities filtered by parameters.\n *\n * @returns Response wrapped in [[IResultList]]\n *\n * @param {object} filter Object containing filters for querying identity.\n *\n * **Example**\n * ```typescript\n *\n * const filter: object = {\n * pageSize: 100,\n * withTotalPages: true\n * };\n *\n * (async () => {\n * const {data, res, paging} = await identityService.list(filter);\n * })();\n * ```\n */\n async list(managedObjectId: string): Promise<IResultList<IExternalIdentity>> {\n const headers = { accept: 'application/json' };\n const url = this.getExternalIdsOfGlobalIdUrl(managedObjectId);\n const res = await this.fetch(url, { headers });\n const json = await res.json();\n const data = json[this.propertyName];\n return { res, data };\n }\n\n /**\n * Creates a new identity.\n *\n * @param {IExternalIdentity} identity Identity object with mandantory fragments.\n *\n * @returns Response wrapped in [[IResult]]\n *\n * **Example**\n * ```typescript\n * const linkedManagedObjectId = '123';\n * const identity: IExternalIdentity = {\n * type: 'type',\n * externalId: '1',\n * managedObject: {\n * id: linkedManagedObjectId\n * }\n * };\n *\n * (async () => {\n * const {data, res} = await identityService.create(identity);\n * })();\n * ```\n */\n async create(identity: IExternalIdentity): Promise<IResult<IExternalIdentity>> {\n const headers = { 'content-type': 'application/json', accept: 'application/json' };\n const method = 'POST';\n const body = JSON.stringify(identity);\n const url = this.getExternalIdsOfGlobalIdUrl(identity.managedObject.id);\n const res = await this.fetch(url, { headers, method, body });\n const data = await res.json();\n return { res, data };\n }\n\n /**\n * Gets the details of an identity.\n *\n * @param {IExternalIdentity} identity Identity object with mandantory fragments.\n *\n * @returns Response wrapped in [[IResult]]\n *\n * **Example**\n * ```typescript\n *\n * const identity: IExternalIdentity = {\n * type: 'type',\n * externalId: '1'\n * };\n *\n * (async () => {\n * const {data, res} = await identityService.detail(identity);\n * })();\n * ```\n */\n async detail(identity: IExternalIdentity): Promise<IResult<IExternalIdentity>> {\n const headers = { accept: 'application/json' };\n const url = this.getExternalIdUrl(identity);\n const res = await this.fetch(url, { headers });\n const data = await res.json();\n return { res, data };\n }\n\n /**\n * Removes an identity with given id.\n *\n * @returns Response wrapped in [[IResult]]\n *\n * @param {IExternalIdentity} identity Identity object with mandantory fragments.\n *\n * **Example**\n * ```typescript\n *\n * const identity: IExternalIdentity = {\n * type: 'type',\n * externalId: '1'\n * };\n *\n * (async () => {\n * const {data, res} = await identityService.delete(identity);\n * })();\n * ```\n */\n async delete(identity: IExternalIdentity): Promise<IResult<IExternalIdentity>> {\n const headers = { accept: 'application/json' };\n const method = 'DELETE';\n const url = this.getExternalIdUrl(identity);\n const res = await this.fetch(url, { headers, method });\n return { res, data: null };\n }\n\n private async fetch(url: string, init?: IFetchOptions): Promise<IFetchResponse> {\n const res: IFetchResponse = await this.client.fetch(url, init);\n if (res.status >= 400) {\n let data = null;\n try {\n data = await res.json();\n } catch (ex) {\n try {\n data = await res.text();\n } catch (ex) {\n // do nothing\n }\n }\n throw { res, data };\n }\n return res;\n }\n\n private getExternalIdsOfGlobalIdUrl(managedObjectId: string | number): string {\n return `/${this.baseUrl}/globalIds/${managedObjectId}/externalIds`;\n }\n\n private getExternalIdUrl(identity: IExternalIdentity): string {\n return `/${this.baseUrl}/externalIds/${identity.type}/${identity.externalId}`;\n }\n}\n","import { IResult, Service } from '../core';\nimport { ITrustedCertificate } from './ITrustedCertificate';\n\n/**\n * This class allows for managing trusted certificates.\n */\nexport class TrustedCertificateService extends Service<ITrustedCertificate> {\n protected get baseUrl() {\n return `/tenant/tenants/${this.client.tenant}`;\n }\n protected listUrl = 'trusted-certificates';\n protected proofOfPossessionUrl = 'trusted-certificates-pop';\n protected propertyName = 'certificates';\n\n /**\n * Gets a list of trusted certificates.\n *\n * @returns Response wrapped in [[IResultList]].\n *\n * **Example**\n * ```typescript\n *\n * (async () => {\n * const {data, res} = await trustedCertificateService.list();\n * })();\n * ```\n */\n async list(filter: object = {}) {\n return super.list(filter);\n }\n\n /**\n * Gets the details of trusted certificate\n *\n * @param entityOrId Trusted certificate object or trusted certificate fingerprint.\n *\n * @returns Response wrapped in [[IResult]]\n *\n * **Example**\n * ```typescript\n *\n * const fingerprint: string = 'abc';\n *\n * (async () => {\n * const {data, res} = await trustedCertificateService.detail(fingerprint);\n * })();\n * ```\n */\n async detail(entityOrId: string | ITrustedCertificate) {\n return super.detail(entityOrId);\n }\n\n /**\n * Removes a trusted certificate with given fingerprint.\n *\n * @returns Response wrapped in [[IResult]]\n *\n * @param entityOrId Trusted certificate object or trusted certificate fingerprint.\n *\n * **Example**\n * ```typescript\n *\n * const fingerprint: string = 'abc';\n *\n * (async () => {\n * const {data, res} = await trustedCertificateService.delete(fingerprint);\n * })();\n * ```\n */\n async delete(entityOrId: string | ITrustedCertificate) {\n return super.delete(entityOrId);\n }\n\n /**\n * Updates trusted certificate data.\n *\n * @param entity Trusted certificate partial object.\n *\n * @returns Response wrapped in [[IResult]]\n *\n * **Example**\n * ```typescript\n *\n * const certificate: Partial<ITrustedCertificate> = {\n * name: 'Name'\n * };\n *\n * (async () => {\n * const {data, res} = await trustedCertificateService.update(certificate);\n * })();\n * ```\n */\n async update(entity: Partial<ITrustedCertificate>) {\n return super.update(entity);\n }\n\n /**\n * Creates a new trusted certificate.\n *\n * @param entity Trusted certificate object.\n *\n * @returns Response wrapped in [[IResult]]\n *\n * **Example**\n * ```typescript\n *\n * const certificate: Partial<ITrustedCertificate> = {\n * name: 'Name',\n * certInPemFormat: 'MIID+DCCAuCgAwIBAgIJAO1Q9t/M9gYlMA0GC...',\n * status: 'ENABLED'\n * };\n *\n * (async () => {\n * const {data, res} = await trustedCertificateService.create(certificate);\n * })();\n * ```\n */\n async create(entity: Partial<ITrustedCertificate>) {\n return super.create(entity);\n }\n\n /**\n * Regenerates unsigned verification code for trusted certificate.\n *\n *\n * @param entityOrId Trusted certificate object or finger print.\n *\n * @returns Certificate object with new verification code (wrapped in [[IResult]])\n *\n * **Example**\n * ```typescript\n *\n * (async () => {\n * const fingerPrint = '00a360973e3e8d61e05aedb32c72438e2442279e';\n * const {data, res} = await trustedCertificateService.regeneratePoPVerificationCode(fingerPrint);\n * const newProofOfPossessionUnsignedVerificationCode = data.proofOfPossessionUnsignedVerificationCode;\n * })();\n * ```\n */\n async regeneratePoPVerificationCode(\n entityOrId: string | ITrustedCertificate\n ): Promise<IResult<ITrustedCertificate>> {\n const method = 'POST';\n const headers = { 'content-type': 'application/json', Accept: 'application/json' };\n const url = `${this.proofOfPossessionUrl}/${this.getEntityId(entityOrId)}/verification-code`;\n const res = await this.fetch(url, { headers, method });\n const data = await res.json();\n return { res, data };\n }\n\n /**\n * Verifies signed verification code for trusted certificate.\n *\n *\n * @param entityOrId Trusted certificate object or finger print.\n * @param proofOfPossessionSignedVerificationCode Unsigned verification code encrypted by the private key.\n *\n * @returns Certificate object with the result of verification (wrapped in [[IResult]]).\n *\n * **Example**\n * ```typescript\n *\n * (async () => {\n * const fingerPrint = '00a360973e3e8d61e05aedb32c72438e2442279e';\n * const encryptedVerificationCode ='fuvlVWLfXG3V3bJWAdEhPD0HFCrYo5';\n * const {data, res} = await trustedCertificateService.verifySignedVerificationCode(fingerPrint, encryptedVerificationCode);\n * const isCertificateVerified = data.proofOfPossessionValid;\n * })();\n * ```\n */\n async verifySignedVerificationCode(\n entityOrId: string | ITrustedCertificate,\n proofOfPossessionSignedVerificationCode: string\n ): Promise<IResult<ITrustedCertificate>> {\n const method = 'POST';\n const headers = { 'content-type': 'application/json', Accept: 'application/json' };\n const url = `${this.proofOfPossessionUrl}/${this.getEntityId(entityOrId)}/pop`;\n const body = JSON.stringify({ proofOfPossessionSignedVerificationCode });\n const res = await this.fetch(url, { method, body, headers });\n const data = await res.json();\n return { res, data };\n }\n\n protected getDetailUrl(entityOrId: string | ITrustedCertificate): string {\n const id = this.getEntityId(entityOrId);\n return `${this.listUrl}/${id}`;\n }\n\n protected getEntityId(entityOrId: string | ITrustedCertificate): string {\n let id: string;\n if (typeof entityOrId === 'object' && entityOrId.fingerprint) {\n id = entityOrId.fingerprint;\n } else {\n id = entityOrId as string;\n }\n return id;\n }\n}\n","import FormData from 'form-data';\nimport { IFetchOptions, IFetchResponse, IResult, Service } from '../core';\nimport { ICertificateRevocation } from './ICertificateRevocation';\nimport { Stream } from 'stream';\n\n/**\n * This class allows for managing a list of certificate revocations.\n */\nexport class CrlService extends Service<ICertificateRevocation> {\n protected get baseUrl() {\n return `/tenant/trusted-certificates/settings/crl`;\n }\n protected readonly listUrl: string;\n\n /**\n * Uploads a list of certificate revocations.\n * Adds new entries to the certificate revocation list,\n * the ones that already exist are updated.\n * No entries are removed from the certificate revocation list.\n *\n * @returns Returns a status object.\n *\n * **Example**\n * ```typescript\n *\n * const crls: ICertificateRevocation[] = [\n * { serialNumberInHex: '24234', revocationDate: '2023-01-13T23:00:00.000Z' }\n * ];\n *\n * (async () => {\n * const { res } = await crlService.uploadCrls(crls);\n * })();\n * ```\n */\n async uploadCrls(crls: ICertificateRevocation[]): Promise<IResult<null>> {\n const method = 'PUT';\n const headers = { 'content-type': 'application/json', Accept: 'application/json' };\n const body = JSON.stringify({ crls });\n const res = await this.fetch('', { method, body, headers });\n return { res, data: null };\n }\n\n /**\n * Uploads a csv file containing a list of certificate revocations.\n * Adds new entries to the certificate revocation list,\n * the ones that already exist are updated.\n * No entries are removed from the certificate revocation list.\n *\n * File format:\n * SERIALNO,DATE\n * 1234567890abcdef,2023-01-01T00:00:00.000Z\n *\n * @returns Returns a status object.\n *\n * **Example**\n * ```typescript\n *\n * (async () => {\n * const { res } = await crlService.uploadCrlFile( file );\n * })();\n * ```\n */\n async uploadCrlFile(file: Stream | Buffer | File | Blob): Promise<IResult<null>> {\n const method = 'PUT';\n const body = new FormData();\n\n body.append('file', file);\n const headers = {\n accept: 'application/json'\n };\n const res = await this.fetch('', { method, body, headers });\n return { res, data: null };\n }\n\n /**\n * Downloads a certificate revocation list file.\n * To open the downloaded file please use command: openssl crl -inform DER -text -noout -in fileName.crl\n *\n * @returns Returns a arrayBuffer wrapped in [[IFetchResponse]].\n *\n * **Example**\n * ```typescript\n *\n * (async () => {\n * const res = await this.crlService.downloadCrlFile();\n * const arrayBuffer = await res.arrayBuffer();\n * })();\n * ```\n */\n async downloadCrlFile(init?: IFetchOptions): Promise<IFetchResponse> {\n return await this.fetch('', init);\n }\n}\n","import { IFetchClient, IResult } from '../core';\nimport { Service } from '../core/Service';\nimport { IManagedObject, IdReference } from '../inventory';\nexport class SmartGroupsService extends Service<IManagedObject> {\n protected baseUrl = 'inventory';\n protected listUrl = 'managedObjects';\n private readonly SMART_GROUP_TYPE = 'c8y_DynamicGroup';\n private readonly SMART_GROUP_FRAGMENT_TYPE = 'c8y_IsDynamicGroup';\n private readonly COLUMNS_CONFIG_FRAGMENT = 'c8y_DeviceColumnsConfig';\n private readonly FILTER_CONFIG_FRAGMENT = 'c8y_DeviceFilterConfig';\n private readonly QUERY_STRING_FRAGMENT = 'c8y_DeviceQueryString';\n\n constructor(client: IFetchClient) {\n super(client);\n }\n\n /**\n * Gets the details of managed object\n *\n * @param {IdReference} entityOrId Entity or Id of the ManagedObject.\n * @param {object} filter Filter object.\n *\n * @returns Response wrapped in [[IResult]]\n *\n * @example\n * ```typescript\n *\n * const id: string = '1';\n * const filter: any = { withChildren: false };\n *\n * (async () => {\n * const {data, res} = await smartGroupsService.detail(id, filter);\n * })();\n * ```\n */\n async detail(entityOrId: IdReference, filter: object = {}): Promise<IResult<IManagedObject>> {\n return super.detail(entityOrId, filter);\n }\n\n /**\n * Creates a smart group managed object with columns configuration.\n *\n * @param {object} smartGroup Dynamic group managed object.\n * @param {object} deviceQueryString Columns configuration query string to filter the new group.\n * @param {object} configurableColumns Configurable columns definitions.\n * @param {object} filterConfig Columns filter configuration for the new group.\n *\n * @returns Response wrapped in [[IResult]]\n *\n * **Example**\n * ```typescript\n *\n * const smartGroup = { name: 'newName', type: 'c8y_DynamicGroup', c8y_IsDynamicGroup: {} };\n * const deviceQueryString = 'c8y_DeviceQueryString: \"$filter=(name eq 'test*') $orderby=c8y_Hardware.model asc';\n * const configurableColumns = [\n * {headerName: 'Status', active: false, key: 'status'},\n * {headerName: 'Name', active: true, key: 'name', filter: { externalFilterQuery: { name: { names: ['test*'] } } }},\n * {headerName: 'Model', active: true, key: 'model'}\n * ];\n *\n * (async () => {\n * await smartGroupsService.create({ smartGroup, deviceQueryString, configurableColumns });\n * })();\n *\n * Note: filterConfig has been removed as a default property to the input object.\n * Now it is part of the configurable columns properties as it is shown above.\n * You can still pass it as an optional parameter.\n * ( const filterConfig = [{ name: { names: ['test*'] } }] )\n * ```\n */\n async create(obj: Partial<IManagedObject>): Promise<IResult<IManagedObject>> {\n const entity = {\n ...obj.smartGroup,\n [this.QUERY_STRING_FRAGMENT]: obj.deviceQueryString,\n [this.COLUMNS_CONFIG_FRAGMENT]: obj.configurableColumns,\n ...(obj.filterConfig && { [this.FILTER_CONFIG_FRAGMENT]: obj.filterConfig })\n };\n\n return super.create(entity);\n }\n\n /**\n * Updates smart group managed object with given id.\n *\n * @param {Partial<IManagedObject>} mo Partial managed object of the smart group.\n *\n * @returns Response wrapped in [[IResult]]\n *\n * @example\n * ```typescript\n *\n * const smartGroup = { id: '1', name: 'newName' };\n *\n * (async () => {\n * await smartGroupsService.update(smartGroup);\n * })();\n * ```\n */\n async update(mo: Partial<IManagedObject>): Promise<IResult<IManagedObject>> {\n return super.update(mo);\n }\n\n /**\n * Removes managed object with given id.\n *\n * @param {IManagedObject} group Managed object of the group.\n * @param {object} params Additional query params.\n *\n * @returns Response wrapped in [[IResult]]\n *\n * @example\n * ```typescript\n *\n * const group = { id: '1' } as IManagedObject;\n * const params: any = {\n * withChildren: false\n * }\n *\n * (async () => {\n * await smartGroupsService.delete(group, params);\n * })();\n * ```\n */\n async delete(entityOrId: IdReference, params: any = {}): Promise<IResult<null>> {\n const data = (await this.detail(entityOrId, { withChildren: false })).data;\n\n return await super.delete(data, params);\n }\n\n /**\n * Checks whether a given managed object is a smart group\n *\n * @param {IManagedObject} mo Managed object to check.\n *\n * @returns boolean\n *\n * @example\n * ```typescript\n *\n * const mo: IManagedObject = {id: 1, type: \"c8y_DeviceGroup\", c8y_IsDeviceGroup: {}} as IManagedObject;\n *\n * (() => {\n * const isSmartGroup = smartGroupsService.isSmartGroup(mo);\n * })();\n * ```\n */\n isSmartGroup(mo: Partial<IManagedObject>): boolean {\n const hasSmartGroupFragmentType = mo.hasOwnProperty(this.SMART_GROUP_FRAGMENT_TYPE);\n const isSmartGroupType = mo && mo.type === this.SMART_GROUP_TYPE;\n\n return hasSmartGroupFragmentType || isSmartGroupType;\n }\n\n protected getUrl(url = ''): string {\n const partialUrl = url.replace(/^\\/+/, '');\n const baseUrl = this.baseUrl.replace(/\\/+$/, '');\n\n return `${baseUrl}/${partialUrl}`;\n }\n}\n","import { ApplicationService } from '../application';\nimport { IResult } from '../core';\nimport { IFetchClient } from '../core/IFetchClient';\nimport { Service } from '../core/Service';\nimport { IdReference } from '../inventory';\nimport { IRule } from './IRule';\n\nexport class SmartRulesService extends Service<IRule> {\n private static readonly microserviceName = 'smartrule';\n protected readonly baseUrl = 'service/smartrule';\n protected readonly listUrl;\n private readonly rulesUrl = 'smartrules';\n private readonly unupdatableFields = ['type', 'cepModuleId', 'creationTime', 'lastUpdated'];\n private microserviceAvailable: boolean;\n private applicationService: ApplicationService;\n\n constructor(client: IFetchClient) {\n super(client);\n this.applicationService = new ApplicationService(client);\n }\n\n /**\n * Checks if the smart rules microservice is subscribed and available to user.\n *\n * **Example**\n * ```typescript\n *\n * (async () => {\n * const isAvailable = await smartRulesService.isMicroserviceAvailable();\n * })();\n * ```\n */\n async isMicroserviceAvailable(): Promise<boolean> {\n if (this.microserviceAvailable === undefined) {\n this.microserviceAvailable = (\n await this.applicationService.isAvailable(SmartRulesService.microserviceName)\n ).data;\n }\n return this.microserviceAvailable;\n }\n\n /**\n * Gets a list of smart rules for given managed object.\n *\n * @param {IdReference} entityOrId Entity or Id of the ManagedObject.\n *\n * @returns Response wrapped in [[IResult]]\n *\n * **Example**\n * ```typescript\n *\n * const id: string = '1';\n *\n * (async () => {\n * const {data, res} = await smartRulesService.listByContext(id);\n * })();\n * ```\n */\n async listByContext(entityOrId: IdReference): Promise<IResult<IRule[]>> {\n const url = this.contextRulesUrl(entityOrId);\n const res = await this.fetch(url, { method: 'GET' });\n const rules = (await res.json()).rules;\n return { res, data: rules };\n }\n\n /**\n * Deactivates smart rule for given entities list.\n *\n * @param {Partial<IRule>} rule Smart rule managed object.\n * @param {IdReference[]} entitiesOrIdsList List of entities or Id of the ManagedObjects.\n *\n * @returns Response wrapped in [[IResult]]\n *\n * **Example**\n * ```typescript\n *\n * const rule: IRule = {id: '1', enabledSources: ['2', '3'],...};\n * const entityOrIdList: IdReference[] = ['2'];\n * (async () => {\n * const {data, res} = await smartRulesService.bulkDeactivateEnabledSources(rule, entityOrIdList);\n * })();\n * ```\n */\n bulkDeactivateEnabledSources(\n rule: Partial<IRule>,\n entitiesOrIdsList: IdReference[]\n ): Promise<IResult<IRule>> {\n if (entitiesOrIdsList.length === 0) {\n return Promise.resolve({ res: null, data: null });\n }\n const { enabledSources } = rule;\n const newEnabledSources = this.disableEnabledSources(enabledSources, entitiesOrIdsList);\n const ruleCopy = { ...rule };\n\n Object.assign(ruleCopy, { enabledSources: newEnabledSources });\n return this.update(ruleCopy);\n }\n\n /**\n * Updates smart rule.\n *\n * @param {Parial<IRule>} rule Smart rule managed object.\n *\n * @returns Response wrapped in [[IResult]]\n *\n * **Example**\n * ```typescript\n *\n * const rule: IRule = {id: '1', enabledSources: ['2', '3'],...};\n * (async () => {\n * const {data, res} = await smartRulesService.updateSmartRule(rule);\n * })();\n * ```\n */\n async update(rule: Partial<IRule>): Promise<IResult<IRule>> {\n const url = this.getSmartRulesUrl(rule);\n const method = 'PUT';\n const body = JSON.stringify(this.removeUnclonableFields(rule, this.unupdatableFields));\n const headers = { 'content-type': 'application/json', accept: 'application/json' };\n const res = await this.fetch(url, { method, body, headers });\n const data = await res.json();\n\n return { res, data };\n }\n\n private disableEnabledSources(\n enabledSources: string[] = [],\n entityOrIdList: IdReference[]\n ): string[] {\n return enabledSources.filter(id => !this.getListOfStringIds(entityOrIdList).includes(id));\n }\n\n private getListOfStringIds(entityOrIdList: IdReference[]): string[] {\n return entityOrIdList.map(entityOrId => {\n if (typeof entityOrId === 'object' && entityOrId.id) {\n return entityOrId.id.toString();\n }\n return entityOrId.toString();\n });\n }\n\n private getSmartRulesUrl(rule: Partial<IRule>): string {\n const contextMoId = rule && rule.c8y_Context && rule.c8y_Context.id;\n let url = !!contextMoId ? this.contextRulesUrl(contextMoId) : this.rulesUrl;\n\n if (rule.id) {\n url = `${url}/${rule.id}`;\n }\n return url;\n }\n\n private removeUnclonableFields(rule: Partial<IRule>, fieldsToRemove: string[]): Partial<IRule> {\n const ruleCopy = { ...rule };\n fieldsToRemove.forEach(f => {\n delete ruleCopy[f];\n });\n return ruleCopy;\n }\n\n private contextRulesUrl(entityOrId: IdReference = {}): string {\n if (typeof entityOrId === 'object' && entityOrId.id) {\n return `managedObjects/${entityOrId.id}/smartrules`;\n }\n return `managedObjects/${entityOrId}/smartrules`;\n }\n}\n","import {\n BearerAuth,\n CookieAuth,\n IAuthentication,\n ICredentials,\n IFetchResponse,\n IMicroserviceSubscriptionsResponse,\n NodeJSCookieAuth\n} from './core';\nimport { Realtime } from './realtime';\nimport {\n FetchClient,\n BasicAuth,\n AlarmService,\n ApplicationService,\n AuditService,\n DeviceRegistrationBulkService,\n DeviceRegistrationService,\n EventService,\n InventoryBinaryService,\n InventoryRoleService,\n InventoryService,\n MeasurementService,\n OperationBulkService,\n OperationService,\n SystemOptionsService,\n TenantOptionsService,\n TenantSecurityOptionsService,\n TenantLoginOptionsService,\n TenantService,\n UserGroupService,\n UserRoleService,\n UserService,\n IdentityService,\n SmartGroupsService,\n SmartRulesService\n} from './services';\n\nexport interface IBootstrapOptions {\n deviceId: string;\n basicAuthToken: string;\n timeout?: number;\n expire?: number;\n baseUrl?: string;\n}\n\nexport class Client {\n /**\n * Authenticates the given user. Determines the tenant by itself via a call to tenant/currentTenant.\n *\n * **Example**\n * ```typescript\n *\n * let client: Client;\n * (async () => {\n * client = await Client.authenticate({\n * user: 'testuser',\n * password: 'password1337!'\n * }, 'https://acme.cumulocity.com');\n *\n * //you have access to the client api now\n * const { data, paging, res }); = await client.inventory.list({ pageSize: 100 });\n * })();\n * ```\n */\n static async authenticate(credentials: ICredentials, baseUrl?: string): Promise<Client> {\n const auth = new BasicAuth(credentials);\n const clientCore = new FetchClient(auth, baseUrl);\n const tenantName = await this.getCurrentTenant(clientCore);\n const client = new Client(auth, baseUrl);\n client.core.tenant = tenantName;\n return client;\n }\n\n /**\n * Authenticates the given user via OAuth Internal. Determines the tenant by itself via a call to tenant/currentTenant.\n * Login call goes to `/tenant/oauth/token` and the retrieved token will be added in the `Authorization` header to subsequent requests.\n *\n * **Example**\n * ```typescript\n *\n * let client: Client;\n * (async () => {\n * client = await Client.authenticateViaOAuthInternal({\n * user: 'testuser',\n * password: 'password1337!'\n * }, 'https://acme.cumulocity.com');\n *\n * //you have access to the client api now\n * const { data, paging, res }); = await client.inventory.list({ pageSize: 100 });\n * })();\n * ```\n */\n static async authenticateViaOAuthInternal(credentials: ICredentials, baseUrl?: string) {\n const token = await this.loginViaOAuthInternal(credentials, true, baseUrl);\n const auth = new BearerAuth(token);\n const clientCore = new FetchClient(auth, baseUrl);\n const tenantName = credentials.tenant || (await this.getCurrentTenant(clientCore));\n const client = new Client(auth, baseUrl);\n client.core.tenant = tenantName;\n return client;\n }\n\n /**\n * Authenticates the given user via OAuth Internal. Determines the tenant by itself via a call to tenant/currentTenant.\n * Login call goes to `/tenant/oauth` and the retrieved token will be attached as a Cookie in browser environments to subsequent requests (using 'CookieAuth').\n * In none browser environments (e.g. nodejs) the retrieved token will be added in the `Authorization` header to subsequent requests (using 'NodeJSCookieAuth').\n *\n * **Example**\n * ```typescript\n *\n * let client: Client;\n * (async () => {\n * client = await Client.authenticateViaOAuthInternalCookie({\n * user: 'testuser',\n * password: 'password1337!'\n * }, 'https://acme.cumulocity.com');\n *\n * //you have access to the client api now\n * const { data, paging, res }); = await client.inventory.list({ pageSize: 100 });\n * })();\n * ```\n */\n static async authenticateViaOAuthInternalCookie(credentials: ICredentials, baseUrl?: string) {\n const response = await this.loginViaOAuthInternal(credentials, false, baseUrl);\n let auth: NodeJSCookieAuth | CookieAuth;\n if (typeof document === 'undefined') {\n auth = new NodeJSCookieAuth(response);\n } else {\n auth = new CookieAuth();\n }\n const clientCore = new FetchClient(auth, baseUrl);\n const tenantName = credentials.tenant || (await this.getCurrentTenant(clientCore));\n const client = new Client(auth, baseUrl);\n client.core.tenant = tenantName;\n return client;\n }\n\n /**\n * Allows to use http to register a device on the platform.\n *\n * **Deprecated** Please use MQTT to bootstrap a device.\n */\n static async deviceBootstrap(options: IBootstrapOptions): Promise<Client> {\n const { deviceId, timeout, baseUrl, basicAuthToken } = options;\n let { expire } = options;\n if (timeout && !expire) {\n expire = Date.now() + timeout;\n }\n const clientCore = new FetchClient(undefined, baseUrl);\n const deviceRegistration = new DeviceRegistrationService(clientCore);\n let client;\n try {\n const { data } = await deviceRegistration.bootstrap(deviceId, { basicAuthToken });\n const { username, password, tenantId } = data;\n const auth = new BasicAuth({ user: username, tenant: tenantId, password });\n client = new Client(auth, baseUrl);\n client.core.tenant = tenantId;\n } catch (error) {\n const retry = (!expire || Date.now() < expire) && error.res.status === 404;\n if (retry) {\n return Client.deviceBootstrap(Object.assign({ expire }, options));\n } else {\n throw error;\n }\n }\n return client;\n }\n\n /**\n * Retrieves microservice credentials for the subscribed tenants\n * using provided bootstrap credentials\n *\n * **Example**\n * ```typescript\n *\n * (async () => {\n * const subscriptions = await Client.getMicroserviceSubscriptions({\n * tenant: process.env.C8Y_BOOTSTRAP_TENANT,\n * user: process.env.C8Y_BOOTSTRAP_USER,\n * password: process.env.C8Y_BOOTSTRAP_PASSWORD\n * }, process.env.C8Y_BASEURL);\n *\n * const clients = subscriptions.map(subscription => new Client(new BasicAuth(subscription), process.env.C8Y_BASEURL));\n * // you have access to the client api now\n * const promiseArray = clients.map(client => client.options.tenant.detail({\n * category: process.env.APPLICATION_KEY,\n * key: 'someSetting'\n * }));\n * })();\n * ```\n */\n static async getMicroserviceSubscriptions(\n bootstrapCredentials: ICredentials,\n baseUrl: string\n ): Promise<ICredentials[]> {\n const microserviceSubscriptionsEndpoint = '/application/currentApplication/subscriptions';\n const clientCore = new FetchClient(new BasicAuth(bootstrapCredentials), baseUrl);\n const res = await clientCore.fetch(microserviceSubscriptionsEndpoint);\n const { users }: IMicroserviceSubscriptionsResponse = await res.json();\n return users.map(({ tenant, name, password }) => {\n return {\n tenant,\n user: name,\n password\n } as ICredentials;\n });\n }\n\n /**\n * Performs the OAuth Internal login.\n *\n * If the parameter `bearerAuth` is set to true (default), the `/tenant/oauth/token` endpoint is called and a string containing the token returned.\n *\n * If the parameter `bearerAuth` is set to false, the `/tenant/oauth` endpoint is called and a Cookie should be set and the response returned.\n * The response can be used in none browser environments to extract the `set-cookie` header from it.\n *\n * **Example**\n * ```typescript\n *\n * (async () => {\n * const client = await Client.loginViaOAuthInternal({\n * tenant: process.env.C8Y_BOOTSTRAP_TENANT,\n * user: process.env.C8Y_BOOTSTRAP_USER,\n * password: process.env.C8Y_BOOTSTRAP_PASSWORD\n * }, true, process.env.C8Y_BASEURL);\n *\n * // you have access to the client api now\n * const option = client.options.tenant.detail({\n * category: process.env.APPLICATION_KEY,\n * key: 'someSetting'\n * });\n * })();\n * ```\n */\n static async loginViaOAuthInternal(\n credentials: ICredentials,\n bearerAuth?: true,\n baseUrl?: string\n ): Promise<string>;\n static async loginViaOAuthInternal(\n credentials: ICredentials,\n bearerAuth: false,\n baseUrl?: string\n ): Promise<IFetchResponse>;\n static async loginViaOAuthInternal(\n credentials: ICredentials,\n bearerAuth = true,\n baseUrl?: string\n ): Promise<string | IFetchResponse> {\n const auth = new BasicAuth(credentials);\n const clientCore = new FetchClient(auth, baseUrl);\n let url = '/tenant/oauth';\n if (bearerAuth) {\n url += `/token`;\n }\n if (credentials.tenant) {\n url += `?tenant_id=${credentials.tenant}`;\n }\n const params = new URLSearchParams({\n grant_type: 'PASSWORD',\n username: credentials.user,\n password: credentials.password,\n tfa_code: credentials.tfa\n });\n const res = await clientCore.fetch(url, {\n method: 'POST',\n body: params.toString(),\n headers: {\n 'content-type': 'application/x-www-form-urlencoded;charset=UTF-8'\n }\n });\n if (res.status !== 200) {\n throw { res };\n }\n\n if (bearerAuth) {\n const body = await res.json();\n\n return body['access_token'];\n }\n\n return res;\n }\n\n private static async getCurrentTenant(fetchClient: FetchClient): Promise<string> {\n const tenantService = new TenantService(fetchClient);\n const { data: tenant } = await tenantService.current();\n return tenant.name;\n }\n\n alarm: AlarmService;\n application: ApplicationService;\n audit: AuditService;\n core: FetchClient;\n deviceRegistration: DeviceRegistrationService;\n deviceRegistrationBulk: DeviceRegistrationBulkService;\n event: EventService;\n inventory: InventoryService;\n inventoryRole: InventoryRoleService;\n inventoryBinary: InventoryBinaryService;\n measurement: MeasurementService;\n operation: OperationService;\n operationBulk: OperationBulkService;\n options: {\n security: TenantSecurityOptionsService;\n system: SystemOptionsService;\n login: TenantLoginOptionsService;\n tenant: TenantOptionsService;\n };\n realtime: Realtime;\n role: InventoryRoleService;\n tenant: TenantService;\n user: UserService;\n userGroup: UserGroupService;\n userRole: UserRoleService;\n identity: IdentityService;\n smartGroups: SmartGroupsService;\n smartRules: SmartRulesService;\n\n /**\n * Initializes a new Client, which allows to request data from the API. Differently\n * to Client.authenticate([...]) it needs a tenant given and does not verify if the\n * login is correct.\n *\n * **Example**\n * ```typescript\n *\n * const auth = new BasicAuth({\n * user: 'youruser',\n * password: 'yourpassword',\n * tenant: 'acme'\n * }); // use CookieAuth() if your platform uses oauth (only in browser!)\n *\n * const baseUrl = 'https://acme.cumulocity.com';\n * const client = new Client(auth, baseUrl);\n * (async () => {\n * const { data, paging, res }); = await client.inventory.list({ pageSize: 100 });\n * })();\n * ```\n *\n * @param auth The Authentication strategy to use (e.g. new BasicAuth())\n * @param baseUrl The URL to request (optional in browser, mandatory in node)\n */\n constructor(auth: IAuthentication, baseUrl?: string) {\n const client = new FetchClient(auth, baseUrl);\n this.realtime = new Realtime(client);\n this.alarm = new AlarmService(client, this.realtime);\n this.application = new ApplicationService(client, this.realtime);\n this.audit = new AuditService(client);\n this.core = client;\n this.deviceRegistration = new DeviceRegistrationService(client);\n this.deviceRegistrationBulk = new DeviceRegistrationBulkService(client);\n this.event = new EventService(client, this.realtime);\n this.inventory = new InventoryService(client, this.realtime);\n this.inventoryBinary = new InventoryBinaryService(client);\n this.inventoryRole = new InventoryRoleService(client);\n this.measurement = new MeasurementService(client, this.realtime);\n this.operation = new OperationService(client);\n this.operationBulk = new OperationBulkService(client);\n this.options = {\n security: new TenantSecurityOptionsService(client),\n system: new SystemOptionsService(client),\n login: new TenantLoginOptionsService(client),\n tenant: new TenantOptionsService(client)\n };\n this.role = new InventoryRoleService(client);\n this.tenant = new TenantService(client);\n this.user = new UserService(client);\n this.userGroup = new UserGroupService(client);\n this.userRole = new UserRoleService(client);\n this.identity = new IdentityService(client);\n this.smartGroups = new SmartGroupsService(client);\n this.smartRules = new SmartRulesService(client);\n }\n\n /**\n * Allows to change the current Authentication\n * @param auth The new Authentication information.\n */\n setAuth(auth: IAuthentication) {\n this.core.setAuth(auth);\n this.realtime.disconnect();\n }\n}\n"],"names":["Paging","constructor","service","statistics","filter","this","currentPage","nextPage","prevPage","pageSize","totalPages","next","list","getFilter","prev","goto","page","Object","assign","Service","client","realtime","cache","Map","prototype","getPrototypeOf","forEach","method","hasOwnProperty","defineProperty","get","url","listUrl","res","yield","fetch","changeFetchOptions","headers","accept","params","json","data","propertyName","paging","getPaging","detail","entityOrId","getDetailUrl","create","entity","body","JSON","stringify","onBeforeCreate","content-type","update","onBeforeUpdate","delete","obj","id","objWithId","options","_url","getUrl","baseUrl","replace","getEntityId","init","fullUrl","handleErrorStatusCodes","response","status","let","ex","text","mimeType","type","getIdString","reference","String","getCurrentPageFromLink","link","matches","match","parseInt","global","self","__self__","F","DOMException","viewClasses","isArrayBufferView","exports","support","Symbol","Blob","e","normalizeName","name","test","TypeError","toLowerCase","normalizeValue","value","iteratorFor","items","iterator","shift","done","undefined","Headers","map","append","Array","isArray","header","getOwnPropertyNames","consumed","bodyUsed","Promise","reject","fileReaderReady","reader","resolve","onload","result","onerror","error","readBlobAsArrayBuffer","blob","FileReader","promise","readAsArrayBuffer","bufferClone","buf","view","slice","Uint8Array","byteLength","set","buffer","Body","_initBody","_bodyInit","_bodyText","isPrototypeOf","_bodyBlob","FormData","_bodyFormData","URLSearchParams","toString","DataView","_bodyArrayBuffer","ArrayBuffer","call","rejected","Error","arrayBuffer","then","readAsText","chars","length","i","fromCharCode","join","formData","decode","parse","isView","indexOf","oldValue","has","callback","thisArg","keys","push","values","entries","methods","Request","input","upcased","credentials","mode","signal","toUpperCase","referrer","form","trim","split","bytes","decodeURIComponent","Response","bodyInit","ok","statusText","clone","redirectStatuses","redirect","RangeError","location","err","message","stack","request","aborted","xhr","XMLHttpRequest","abortXhr","abort","rawHeaders","getAllResponseHeaders","line","parts","key","responseURL","responseText","ontimeout","onabort","open","withCredentials","responseType","setRequestHeader","addEventListener","onreadystatechange","readyState","removeEventListener","send","polyfill","ponyfill","ctx","default","module","auths","WeakMap","FetchClient","authOrBaseUrl","tenant","defaultHeaders","setAuth","resolveServerUrl","auth","fetchFn","window","getFetchOptions","optionsWithAdjustedBody","adjustOptionsForFormData","paramPart","k","vals","encodedKey","encodeURIComponent","v","clonedOptions","UseXBasic","getCometdHandshake","config","startsWith","protocol","host","E","code","btoa$1","_btoa","p1","btoa","block","charCode","str","output","idx","charAt","charCodeAt","secrets","BasicAuth","updateCredentials","user","password","token","tfa","secret","xsrfToken","getCookieValue","Authorization","X-XSRF-TOKEN","tfatoken","KEY","ext","logout","document","cookie","pop","BearerAuth","CookieAuth","logoutUrl","MicroserviceClientRequestAuth","authTokenFromCookie","authTokenFromHeader","authorization","NodeJSCookieAuth","cookieResponse","super","setCookiesHeader","Severity","QueriesUtil","operatorFns","__not","operand","buildQueryFilter","__and","__or","__eq","contextKey","quoteString","__gt","__ge","__lt","__le","__in","stmts","op","glue","__bygroupid","__has","__useFilterQueryString","query","_a","queryString","substring","buildQuery","q","__filter","orderBy","buildQueryOrderby","__orderby","queryFilter","_queryKey","_glueType","queryKey","glueType","qFilter","_q","queryOrderbys","o","addAndFilter","addFilter","addOrFilter","operator","oldFilter","newFilter","skipEmptyObjects","prependOrderbys","orderbys","addOrderbys","appendOrderbys","how","oldOrderbys","newOrderbys","newQuery","isEmptyObject","extractAndMergeOrderBys","queries","orderByQuery","s","escapeSingleQuote","objs","MetaChannel","Scheduler","Utils","TransportRegistry","Transport","RequestTransport","LongPollingTransport","CallbackPollingTransport","WebSocketTransport","_z85EncodeTable","_z85DecodeTable","_ids","_tasks","register","funktion","unregister","setTimeout","delay","clearTimeout","isString","inArray","element","array","_types","_transports","getTransportTypes","findTransportTypes","version","crossDomain","negotiateTransport","types","j","transport","add","index","existing","splice","find","remove","clear","reset","_type","_cometd","registered","cometd","unregistered","_debug","apply","arguments","_mixin","getConfiguration","getAdvice","convertToMessages","x","getType","getURL","setURL","envelope","metaConnect","derive","baseObject","CometD","_transport","_handshakeProps","_handshakeCallback","_handleMessages","_handleFailure","_scheduler","_name","_crossDomain","_status","_messageId","_clientId","_batch","_messageQueue","_internalBatch","_listenerId","_listeners","_backoff","_scheduledSend","_extensions","_advice","_callbacks","_remoteCalls","_reestablish","_connected","_unconnectTime","_handshakeMessages","_metaConnect","_config","useWorkerScheduler","stickyReconnect","connectTimeout","maxConnections","backoffIncrement","maxBackoff","logLevel","maxNetworkDelay","requestHeaders","appendMessageTypeToURL","autoBatch","urls","maxURILength","advice","timeout","interval","reconnect","maxInterval","_fieldValue","object","_isString","_isFunction","_zeroPad","Math","pow","_log","level","args","now","console","logger","Date","getHours","getMinutes","getSeconds","getMilliseconds","_splitURL","RegExp","exec","_configure","configuration","worker","urlParts","hostAndPort","uri","afterURI","_isCrossDomain","_info","lastSegmentIndex","uriSegments","Worker","URL","onmessage","cmd","postMessage","lastIndexOf","blobURL","createObjectURL","_removeListener","subscription","subscriptions","channel","listener","_removeSubscription","_clearSubscriptions","_setStatus","newStatus","_isDisconnected","_nextMessageId","_applyExtension","scope","outgoing","handler","onExtensionException","xx","_notify","onListenerException","_notifyListeners","channelParts","last","channelPart","_cancelDelayedSend","_delayedSend","operation","time","_send","messages","extraPath","messageId","clientId","extension","sync","onSuccess","rcvdMessages","onFailure","conduit","failure","getTransport","connectionType","_queueSend","_resetBackoff","_flushBatch","_delayedConnect","bayeuxMessage","_updateAdvice","newAdvice","_disconnect","reason","_notifyTransportException","oldTransport","newTransport","onTransportException","_handshake","handshakeProps","handshakeCallback","transportTypes","minimumVersion","supportedConnectionTypes","_putCallback","_warn","_notifyCallback","onCallbackException","_handleCallback","_getCallback","_handleRemoteCall","context","_handleTransportFailure","failureInfo","action","_failHandshake","onTransportFailure","_matchMetaConnect","connect","_failConnect","_failDisconnect","_failSubscribe","_failUnsubscribe","_failMessage","_receive","incoming","_handshakeResponse","successful","cause","reestablish","_hasSubscriptions","_resolveScopedCallback","delegate","_addListener","isListener","deep","target","objects","prop","source","propName","targ","failureHandler","oldTransportType","transports","getTransportRegistry","getBackoffPeriod","newTransportType","increaseBackoffPeriod","getTime","resetBackoffPeriod","receive","failureMessage","registerTransport","unregisterTransport","unregisterTransports","findTransport","configure","handshake","disconnect","disconnectProps","disconnectCallback","startBatch","endBatch","batch","addListener","removeListener","clearListeners","subscribe","subscribeProps","subscribeCallback","unsubscribe","unsubscribeProps","unsubscribeCallback","resubscribe","clearSubscriptions","publish","content","publishProps","publishCallback","publishBinary","meta","binary","remoteCall","callProps","remoteCallBinary","getStatus","isDisconnected","setBackoffIncrement","period","getBackoffIncrement","setLogLevel","registerExtension","unregisterExtension","getExtension","getName","getClientId","WebSocket","_super","_self","_requestIds","_metaConnectRequest","_requests","_envelopes","_transportSend","maxDelay","transportSend","expired","errorMessage","httpCode","xhrStatus","abortXHR","complete","requestId","_complete","success","nextEnvelope","nextRequest","envelopeAndRequest","newEnvelope","newRequest","concat","transportSuccess","responses","transportFailure","metaConnectRequest","state","UNSENT","_supportsCrossDomain","newXMLHttpRequest","xhrSend","packet","_copyContext","headerName","onError","sameStack","received","exception","jsonp","_failTransportFn","jsonpSend","head","getElementsByTagName","script","createElement","callbackName","removeChild","src","async","appendChild","start","lengths","urlLength","encodeURI","maxLength","envelopeToSend","end","begin","_webSocketSupported","_webSocketConnected","_stickyReconnect","_context","_connecting","_successCallback","_forceClose","event","webSocketClose","onClose","_sameContext","_storeEnvelope","messageIds","envelopes","_webSocketSend","webSocket","timeouts","onclose","connectTimer","onopen","onOpen","wsMessage","onMessage","_notifySuccess","fn","_notifyFailure","close","removed","ids","websocketCode","websocketEnabled","Z85","encode","remainder","padding","isPadding","getUint8","divisor","floor","string","p","charIdx","byteIdx","setUint8","lib","Realtime","metaHandshake","msg","IsoCometD","HANDSHAKE","checkConnection","addHandshakeListener","addConnectListener","CONNECT","subscriptionHandle","EventService","browser","EventBinaryService","upload","file","download","InventoryBinaryService","managedObject","fileName","fileType","File","managedObjectOrId","createWithProgress","onProgress","bodyHeaders","getHeaders","xhrBody","getBuffer","getXMLHttpResponse","rej","getIdFromUrl","regexp","ChildType","InventoryService","inventoriesQueryParamName","devicesQueryParamName","queriesUtil","listQuery","listQueryDevices","childAdditionsList","parentReference","listChildren","ADDITIONS","childAdditionsCreate","createChild","childAdditionsAdd","childReference","addChild","childAdditionsRemove","childAssetsList","ASSETS","childAssetsCreate","childAssetsAdd","childAssetsBulkAdd","addChildBulk","childAssetsRemove","childDevicesList","DEVICES","childDevicesCreate","childDevicesAdd","childDevicesRemove","getSupportedMeasurements","getSupportedMeasurementDetails","getSupportedSeries","getMeasurementsAndSeries","supportedMeasurements","supportedSeries","all","sortedSupportedMeasurements","sort","a","b","fragment","m","series","assetKPIsList","listKPIs","getChildrenUrl","lastUpdated","getChildUrl","childId","references","ref","pagingFilter","childReferenceArray","c8y_SupportedMeasurements","c8y_SupportedSeries","MeasurementService","listSeries","sourceId","toISOString","aggregationType","AlarmService","AlarmStatus","OperationService","OperationBulkService","operationOrId","OperationBulkStatus","OperationBulkGeneralStatus","OperationStatus","TenantService","currentTenantUrl","fetchOptions","current","enableSupportUser","disableSupportUser","currentTenantType","tenantData","customProperties","tenantType","getTfaSettings","subscribeApplication","application","applicationId","unsubscribeApplication","TenantStatus","TfaStrategy","UserInventoryRoleService","userUrl","currenUserUrl","UserService","currentUserUrl","passwordResetUrl","currentUserPhoneUrl","verifyTFACodeUrl","totpCurrentUserURL","verifyTOTPCodeUrl","activateTOTPCodeUrl","revokeTOTPSecretUrl","newsletterEmailsUrl","currentUserPasswordUrl","revokeAllTokensUrl","inventoryAssignment","Accept","currentWithEffectiveRoles","updateCurrent","sendPasswordResetMail","email","tenantId","resetPassword","newPassword","verifyTFACode","pin","verifyTotpCode","activateTotp","isActive","getActivityTotp","generateTotpSecret","totpRevokeSecret","savePhoneNumber","phoneNumber","phone","getNewsletterEmails","changeUserPassword","currentUserPassword","changeUserPasswordUrl","changeCurrentUserPassword","revokeTokens","hasRole","roleId","hasRoleInUser","hasRoleInGroups","hasAllRoles","roleIds","every","hasAnyRole","some","hasAnyGlobalRole","globalRoleIds","globalRoleId","hasGlobalRoleInUser","isDeviceUser","userName","getId","effectiveRoles","hasRoleInReferences","roles","groups","groupRef","group","role","gR","PasswordStrength","ApplicationBinaryService","applicationOrId","uploadParamsOverride","createBinaryRequestBody","uploadWithProgressXhr","binaryOrId","listPlugins","addPlugin","pluginName","pluginFile","bufferOrStream","Buffer","from","removePlugin","updateFiles","files","contents","path","downloadArchive","binaryId","uploadFileName","bodyFileProperty","requestBody","ApplicationType","ApplicationService","listVersions","applicationVersions","appDetail","listByName","listByTenant","tenantOrName","tenantService","tenantName","listByOwner","listByUser","userOrId","userService","userId","reactivateArchive","appId","getHref","EXTERNAL","externalUrl","public","contextPath","isAvailable","dropOverwrittenApps","noPaging","availableApp","isMatch","getStatusDetails","getInstanceNames","appStatusDetails","instanceNames","c8y_Status","instances","getInstanceLog","instanceName","updateApplicationConfig","app","currentConfig","newConfig","updatedConfigApp","getAppManifest","date","storeAppManifest","manifestJSON","setPackageVersionTag","tags","getManifestOfContextPath","deleteVersionPackage","updateApplicationAvailability","availability","el","includes","InstanceStatus","BillingMode","Isolation","ApplicationAvailability","SystemOptionsService","option","category","TenantOptionsService","securityOptionsCategories","securityOptionsListUrl","systemOptions","encodedCategory","TenantSecurityOptionsService","tenantSecurityOption","TenantLoginOptionsService","entityIdentityOrId","listForCurrentTenant","listForManagement","management","save","TenantLoginOptionType","GrantType","UserManagementSource","AuditService","AuditRecordType","ChangeType","InventoryRoleService","DeviceRegistrationStatus","DeviceRegistrationService","securityToken","getSecurityToken","payload","ACCEPTED","acceptAll","limit","bootstrap","basicAuth","basicAuthToken","pass","noIdEntity","DeviceRegistrationBulkService","inputFile","csv","DeviceRegistrationSecurityMode","UserRoleService","UserGroupService","addRoleToGroup","childEntityOrSelf","ROLES","removeRoleFromGroup","addUserToGroup","USERS","removeUserFromGroup","getSelf","userGroupOrId","getChildReferenceAsBody","childSelf","IdentityService","managedObjectId","getExternalIdsOfGlobalIdUrl","identity","getExternalIdUrl","externalId","TrustedCertificateService","proofOfPossessionUrl","regeneratePoPVerificationCode","verifySignedVerificationCode","proofOfPossessionSignedVerificationCode","fingerprint","CrlService","uploadCrls","crls","uploadCrlFile","downloadCrlFile","SmartGroupsService","SMART_GROUP_TYPE","SMART_GROUP_FRAGMENT_TYPE","COLUMNS_CONFIG_FRAGMENT","FILTER_CONFIG_FRAGMENT","QUERY_STRING_FRAGMENT","smartGroup","deviceQueryString","configurableColumns","filterConfig","mo","withChildren","isSmartGroup","hasSmartGroupFragmentType","isSmartGroupType","partialUrl","SmartRulesService","rulesUrl","unupdatableFields","applicationService","isMicroserviceAvailable","microserviceAvailable","microserviceName","listByContext","contextRulesUrl","rules","bulkDeactivateEnabledSources","rule","entitiesOrIdsList","newEnabledSources","enabledSources","disableEnabledSources","ruleCopy","getSmartRulesUrl","removeUnclonableFields","entityOrIdList","getListOfStringIds","contextMoId","c8y_Context","fieldsToRemove","f","Client","authenticate","clientCore","getCurrentTenant","core","authenticateViaOAuthInternal","loginViaOAuthInternal","authenticateViaOAuthInternalCookie","deviceBootstrap","deviceId","expire","deviceRegistration","username","getMicroserviceSubscriptions","bootstrapCredentials","users","bearerAuth","grant_type","tfa_code","fetchClient","alarm","audit","deviceRegistrationBulk","inventory","inventoryBinary","inventoryRole","measurement","operationBulk","security","system","login","userGroup","userRole","smartGroups","smartRules"],"mappings":"0hBAWaA,EA4BXC,YAAYC,EAAyBC,EAAiBC,GACpDC,KAAKD,OAASA,EACdC,KAAKH,QAAUA,EACfG,KAAKC,YAAcH,EAAWG,YAC9BD,KAAKE,SAAWJ,EAAWI,SAC3BF,KAAKG,SAAWL,EAAWK,SAC3BH,KAAKI,SAAWN,EAAWM,SAC3BJ,KAAKK,WAAaP,EAAWO,UAC9B,CAMKC,KAAKP,EAAiB,4CAC1B,OAAOC,KAAKO,KAAKP,KAAKQ,UAAUT,EAAQC,KAAKE,QAAQ,CAAC,EACvD,CAAA,CAMKO,KAAKV,EAAiB,4CAC1B,OAAOC,KAAKO,KAAKP,KAAKQ,UAAUT,EAAQC,KAAKG,QAAQ,CAAC,EACvD,CAAA,CAQKI,KAAKR,EAAiB,4CAC1B,OAAOC,KAAKH,Q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B,IAAIlH,GAAqB7gC,CAAM,EACpDf,KAAK+oC,YAAc,IAAIxT,GAAmBx0B,EAAQf,KAAKgB,QAAQ,EAC/DhB,KAAKshB,UAAY,IAAIwU,GAAiB/0B,CAAM,EAC5Cf,KAAKgpC,cAAgB,IAAIjT,GAAqBh1B,CAAM,EACpDf,KAAKwD,QAAU,CACbylC,SAAU,IAAInI,GAA6B//B,CAAM,EACjDmoC,OAAQ,IAAI5I,GAAqBv/B,CAAM,EACvCooC,MAAO,IAAInI,GAA0BjgC,CAAM,EAC3CyN,OAAQ,IAAIiyB,GAAqB1/B,CAAM,GAEzCf,KAAKo7B,KAAO,IAAIwG,GAAqB7gC,CAAM,EAC3Cf,KAAKwO,OAAS,IAAI4nB,EAAcr1B,CAAM,EACtCf,KAAK+Q,KAAO,IAAIymB,GAAYz2B,CAAM,EAClCf,KAAKopC,UAAY,IAAIrG,GAAiBhiC,CAAM,EAC5Cf,KAAKqpC,SAAW,IAAIvG,GAAgB/hC,CAAM,EAC1Cf,KAAK8jC,SAAW,IAAIH,GAAgB5iC,CAAM,EAC1Cf,KAAKspC,YAAc,IAAI1E,GAAmB7jC,CAAM,EAChDf,KAAKupC,WAAa,IAAI3D,GAAkB7kC,CAAM,CAC/C,CAMD2N,QAAQE,GACN5O,KAAKynC,KAAK/4B,QAAQE,CAAI,EACtB5O,KAAKgB,SAASgmB,YACf,CACF","x_google_ignoreList":[2,4,5,7,15,16,19]}
|
|
1
|
+
{"version":3,"file":"client.umd.min.js","sources":["../../../../node_modules/tslib/tslib.es6.js","../../src/core/Paging.ts","../../src/core/Service.ts","../../../../node_modules/cross-fetch/dist/browser-ponyfill.js","../../src/core/FetchClient.ts","../../../../node_modules/b2a/es/common.js","../../../../node_modules/b2a/es/btoa.js","../../src/core/BasicAuth.ts","../../../../node_modules/b2a/es/atob.js","../../src/core/BearerAuth.ts","../../src/core/CookieAuth.ts","../../src/core/MicroserviceClientRequestAuth.ts","../../src/core/NodeJSCookieAuth.ts","../../src/core/Severity.ts","../../src/core/QueriesUtil.ts","../../src/realtime/MetaChannel.ts","../../../../node_modules/cometd/cometd.js","../../../../node_modules/isomorphic-cometd/browser.js","../../src/realtime/Realtime.ts","../../src/event/EventService.ts","../../../../node_modules/form-data/lib/browser.js","../../src/user-group/UserGroupService.ts","../../src/event/EventBinaryService.ts","../../src/inventory/InventoryBinaryService.ts","../../src/inventory/InventoryService.ts","../../src/measurement/MeasurementService.ts","../../src/measurement/ISeriesFilter.ts","../../src/alarm/AlarmService.ts","../../src/alarm/AlarmStatus.ts","../../src/operation/OperationService.ts","../../src/operation/OperationBulkService.ts","../../src/operation/OperationBulkStatus.ts","../../src/operation/OperationBulkGeneralStatus.ts","../../src/operation/OperationStatus.ts","../../src/tenant/TenantService.ts","../../src/tenant/TenantStatus.ts","../../src/tenant/TfaStrategy.ts","../../src/user/UserInventoryRoleService.ts","../../src/user/UserService.ts","../../src/user/PasswordStrength.ts","../../src/application/ApplicationBinaryService.ts","../../src/application/ApplicationType.ts","../../src/application/ApplicationService.ts","../../src/application/IApplicationInstanceDetails.ts","../../src/application/BillingMode.ts","../../src/application/Isolation.ts","../../src/application/ApplicationAvailability.ts","../../src/system-options/SystemOptionsService.ts","../../src/tenant-options/TenantOptionsService.ts","../../src/tenant-security-options/TenantSecurityOptionsService.ts","../../src/tenant-login-options/TenantLoginOptionsService.ts","../../src/tenant-login-options/ITenantLoginOptions.ts","../../src/audit/AuditService.ts","../../src/audit/AuditRecordType.ts","../../src/audit/ChangeType.ts","../../src/inventory-role/InventoryRoleService.ts","../../src/device-registration/DeviceRegistrationStatus.ts","../../src/device-registration/DeviceRegistrationService.ts","../../src/device-registration/DeviceRegistrationBulkService.ts","../../src/device-registration/DeviceRegistrationSecurityMode.ts","../../src/user-role/UserRoleService.ts","../../src/identity/IdentityService.ts","../../src/trusted-certificates/TrustedCertificateService.ts","../../src/trusted-certificates/CrlService.ts","../../src/smart-groups/SmartGroupsService.ts","../../src/smart-rules/SmartRulesService.ts","../../src/Client.ts"],"sourcesContent":["/******************************************************************************\r\nCopyright (c) Microsoft Corporation.\r\n\r\nPermission to use, copy, modify, and/or distribute this software for any\r\npurpose with or without fee is hereby granted.\r\n\r\nTHE SOFTWARE IS PROVIDED \"AS IS\" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH\r\nREGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY\r\nAND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,\r\nINDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM\r\nLOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR\r\nOTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR\r\nPERFORMANCE OF THIS SOFTWARE.\r\n***************************************************************************** */\r\n/* global Reflect, Promise, SuppressedError, Symbol */\r\n\r\nvar extendStatics = function(d, b) {\r\n extendStatics = Object.setPrototypeOf ||\r\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\r\n function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };\r\n return extendStatics(d, b);\r\n};\r\n\r\nexport function __extends(d, b) {\r\n if (typeof b !== \"function\" && b !== null)\r\n throw new TypeError(\"Class extends value \" + String(b) + \" is not a constructor or null\");\r\n extendStatics(d, b);\r\n function __() { this.constructor = d; }\r\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\r\n}\r\n\r\nexport var __assign = function() {\r\n __assign = Object.assign || function __assign(t) {\r\n for (var s, i = 1, n = arguments.length; i < n; i++) {\r\n s = arguments[i];\r\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p];\r\n }\r\n return t;\r\n }\r\n return __assign.apply(this, arguments);\r\n}\r\n\r\nexport function __rest(s, e) {\r\n var t = {};\r\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)\r\n t[p] = s[p];\r\n if (s != null && typeof Object.getOwnPropertySymbols === \"function\")\r\n for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {\r\n if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))\r\n t[p[i]] = s[p[i]];\r\n }\r\n return t;\r\n}\r\n\r\nexport function __decorate(decorators, target, key, desc) {\r\n var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;\r\n if (typeof Reflect === \"object\" && typeof Reflect.decorate === \"function\") r = Reflect.decorate(decorators, target, key, desc);\r\n else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;\r\n return c > 3 && r && Object.defineProperty(target, key, r), r;\r\n}\r\n\r\nexport function __param(paramIndex, decorator) {\r\n return function (target, key) { decorator(target, key, paramIndex); }\r\n}\r\n\r\nexport function __esDecorate(ctor, descriptorIn, decorators, contextIn, initializers, extraInitializers) {\r\n function accept(f) { if (f !== void 0 && typeof f !== \"function\") throw new TypeError(\"Function expected\"); return f; }\r\n var kind = contextIn.kind, key = kind === \"getter\" ? \"get\" : kind === \"setter\" ? \"set\" : \"value\";\r\n var target = !descriptorIn && ctor ? contextIn[\"static\"] ? ctor : ctor.prototype : null;\r\n var descriptor = descriptorIn || (target ? Object.getOwnPropertyDescriptor(target, contextIn.name) : {});\r\n var _, done = false;\r\n for (var i = decorators.length - 1; i >= 0; i--) {\r\n var context = {};\r\n for (var p in contextIn) context[p] = p === \"access\" ? {} : contextIn[p];\r\n for (var p in contextIn.access) context.access[p] = contextIn.access[p];\r\n context.addInitializer = function (f) { if (done) throw new TypeError(\"Cannot add initializers after decoration has completed\"); extraInitializers.push(accept(f || null)); };\r\n var result = (0, decorators[i])(kind === \"accessor\" ? { get: descriptor.get, set: descriptor.set } : descriptor[key], context);\r\n if (kind === \"accessor\") {\r\n if (result === void 0) continue;\r\n if (result === null || typeof result !== \"object\") throw new TypeError(\"Object expected\");\r\n if (_ = accept(result.get)) descriptor.get = _;\r\n if (_ = accept(result.set)) descriptor.set = _;\r\n if (_ = accept(result.init)) initializers.unshift(_);\r\n }\r\n else if (_ = accept(result)) {\r\n if (kind === \"field\") initializers.unshift(_);\r\n else descriptor[key] = _;\r\n }\r\n }\r\n if (target) Object.defineProperty(target, contextIn.name, descriptor);\r\n done = true;\r\n};\r\n\r\nexport function __runInitializers(thisArg, initializers, value) {\r\n var useValue = arguments.length > 2;\r\n for (var i = 0; i < initializers.length; i++) {\r\n value = useValue ? initializers[i].call(thisArg, value) : initializers[i].call(thisArg);\r\n }\r\n return useValue ? value : void 0;\r\n};\r\n\r\nexport function __propKey(x) {\r\n return typeof x === \"symbol\" ? x : \"\".concat(x);\r\n};\r\n\r\nexport function __setFunctionName(f, name, prefix) {\r\n if (typeof name === \"symbol\") name = name.description ? \"[\".concat(name.description, \"]\") : \"\";\r\n return Object.defineProperty(f, \"name\", { configurable: true, value: prefix ? \"\".concat(prefix, \" \", name) : name });\r\n};\r\n\r\nexport function __metadata(metadataKey, metadataValue) {\r\n if (typeof Reflect === \"object\" && typeof Reflect.metadata === \"function\") return Reflect.metadata(metadataKey, metadataValue);\r\n}\r\n\r\nexport function __awaiter(thisArg, _arguments, P, generator) {\r\n function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }\r\n return new (P || (P = Promise))(function (resolve, reject) {\r\n function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }\r\n function rejected(value) { try { step(generator[\"throw\"](value)); } catch (e) { reject(e); } }\r\n function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }\r\n step((generator = generator.apply(thisArg, _arguments || [])).next());\r\n });\r\n}\r\n\r\nexport function __generator(thisArg, body) {\r\n var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;\r\n return g = { next: verb(0), \"throw\": verb(1), \"return\": verb(2) }, typeof Symbol === \"function\" && (g[Symbol.iterator] = function() { return this; }), g;\r\n function verb(n) { return function (v) { return step([n, v]); }; }\r\n function step(op) {\r\n if (f) throw new TypeError(\"Generator is already executing.\");\r\n while (g && (g = 0, op[0] && (_ = 0)), _) try {\r\n if (f = 1, y && (t = op[0] & 2 ? y[\"return\"] : op[0] ? y[\"throw\"] || ((t = y[\"return\"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;\r\n if (y = 0, t) op = [op[0] & 2, t.value];\r\n switch (op[0]) {\r\n case 0: case 1: t = op; break;\r\n case 4: _.label++; return { value: op[1], done: false };\r\n case 5: _.label++; y = op[1]; op = [0]; continue;\r\n case 7: op = _.ops.pop(); _.trys.pop(); continue;\r\n default:\r\n if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }\r\n if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }\r\n if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }\r\n if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }\r\n if (t[2]) _.ops.pop();\r\n _.trys.pop(); continue;\r\n }\r\n op = body.call(thisArg, _);\r\n } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }\r\n if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };\r\n }\r\n}\r\n\r\nexport var __createBinding = Object.create ? (function(o, m, k, k2) {\r\n if (k2 === undefined) k2 = k;\r\n var desc = Object.getOwnPropertyDescriptor(m, k);\r\n if (!desc || (\"get\" in desc ? !m.__esModule : desc.writable || desc.configurable)) {\r\n desc = { enumerable: true, get: function() { return m[k]; } };\r\n }\r\n Object.defineProperty(o, k2, desc);\r\n}) : (function(o, m, k, k2) {\r\n if (k2 === undefined) k2 = k;\r\n o[k2] = m[k];\r\n});\r\n\r\nexport function __exportStar(m, o) {\r\n for (var p in m) if (p !== \"default\" && !Object.prototype.hasOwnProperty.call(o, p)) __createBinding(o, m, p);\r\n}\r\n\r\nexport function __values(o) {\r\n var s = typeof Symbol === \"function\" && Symbol.iterator, m = s && o[s], i = 0;\r\n if (m) return m.call(o);\r\n if (o && typeof o.length === \"number\") return {\r\n next: function () {\r\n if (o && i >= o.length) o = void 0;\r\n return { value: o && o[i++], done: !o };\r\n }\r\n };\r\n throw new TypeError(s ? \"Object is not iterable.\" : \"Symbol.iterator is not defined.\");\r\n}\r\n\r\nexport function __read(o, n) {\r\n var m = typeof Symbol === \"function\" && o[Symbol.iterator];\r\n if (!m) return o;\r\n var i = m.call(o), r, ar = [], e;\r\n try {\r\n while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);\r\n }\r\n catch (error) { e = { error: error }; }\r\n finally {\r\n try {\r\n if (r && !r.done && (m = i[\"return\"])) m.call(i);\r\n }\r\n finally { if (e) throw e.error; }\r\n }\r\n return ar;\r\n}\r\n\r\n/** @deprecated */\r\nexport function __spread() {\r\n for (var ar = [], i = 0; i < arguments.length; i++)\r\n ar = ar.concat(__read(arguments[i]));\r\n return ar;\r\n}\r\n\r\n/** @deprecated */\r\nexport function __spreadArrays() {\r\n for (var s = 0, i = 0, il = arguments.length; i < il; i++) s += arguments[i].length;\r\n for (var r = Array(s), k = 0, i = 0; i < il; i++)\r\n for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++)\r\n r[k] = a[j];\r\n return r;\r\n}\r\n\r\nexport function __spreadArray(to, from, pack) {\r\n if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {\r\n if (ar || !(i in from)) {\r\n if (!ar) ar = Array.prototype.slice.call(from, 0, i);\r\n ar[i] = from[i];\r\n }\r\n }\r\n return to.concat(ar || Array.prototype.slice.call(from));\r\n}\r\n\r\nexport function __await(v) {\r\n return this instanceof __await ? (this.v = v, this) : new __await(v);\r\n}\r\n\r\nexport function __asyncGenerator(thisArg, _arguments, generator) {\r\n if (!Symbol.asyncIterator) throw new TypeError(\"Symbol.asyncIterator is not defined.\");\r\n var g = generator.apply(thisArg, _arguments || []), i, q = [];\r\n return i = {}, verb(\"next\"), verb(\"throw\"), verb(\"return\"), i[Symbol.asyncIterator] = function () { return this; }, i;\r\n function verb(n) { if (g[n]) i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; }\r\n function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } }\r\n function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); }\r\n function fulfill(value) { resume(\"next\", value); }\r\n function reject(value) { resume(\"throw\", value); }\r\n function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); }\r\n}\r\n\r\nexport function __asyncDelegator(o) {\r\n var i, p;\r\n return i = {}, verb(\"next\"), verb(\"throw\", function (e) { throw e; }), verb(\"return\"), i[Symbol.iterator] = function () { return this; }, i;\r\n function verb(n, f) { i[n] = o[n] ? function (v) { return (p = !p) ? { value: __await(o[n](v)), done: false } : f ? f(v) : v; } : f; }\r\n}\r\n\r\nexport function __asyncValues(o) {\r\n if (!Symbol.asyncIterator) throw new TypeError(\"Symbol.asyncIterator is not defined.\");\r\n var m = o[Symbol.asyncIterator], i;\r\n return m ? m.call(o) : (o = typeof __values === \"function\" ? __values(o) : o[Symbol.iterator](), i = {}, verb(\"next\"), verb(\"throw\"), verb(\"return\"), i[Symbol.asyncIterator] = function () { return this; }, i);\r\n function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; }\r\n function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); }\r\n}\r\n\r\nexport function __makeTemplateObject(cooked, raw) {\r\n if (Object.defineProperty) { Object.defineProperty(cooked, \"raw\", { value: raw }); } else { cooked.raw = raw; }\r\n return cooked;\r\n};\r\n\r\nvar __setModuleDefault = Object.create ? (function(o, v) {\r\n Object.defineProperty(o, \"default\", { enumerable: true, value: v });\r\n}) : function(o, v) {\r\n o[\"default\"] = v;\r\n};\r\n\r\nexport function __importStar(mod) {\r\n if (mod && mod.__esModule) return mod;\r\n var result = {};\r\n if (mod != null) for (var k in mod) if (k !== \"default\" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);\r\n __setModuleDefault(result, mod);\r\n return result;\r\n}\r\n\r\nexport function __importDefault(mod) {\r\n return (mod && mod.__esModule) ? mod : { default: mod };\r\n}\r\n\r\nexport function __classPrivateFieldGet(receiver, state, kind, f) {\r\n if (kind === \"a\" && !f) throw new TypeError(\"Private accessor was defined without a getter\");\r\n if (typeof state === \"function\" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError(\"Cannot read private member from an object whose class did not declare it\");\r\n return kind === \"m\" ? f : kind === \"a\" ? f.call(receiver) : f ? f.value : state.get(receiver);\r\n}\r\n\r\nexport function __classPrivateFieldSet(receiver, state, value, kind, f) {\r\n if (kind === \"m\") throw new TypeError(\"Private method is not writable\");\r\n if (kind === \"a\" && !f) throw new TypeError(\"Private accessor was defined without a setter\");\r\n if (typeof state === \"function\" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError(\"Cannot write private member to an object whose class did not declare it\");\r\n return (kind === \"a\" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;\r\n}\r\n\r\nexport function __classPrivateFieldIn(state, receiver) {\r\n if (receiver === null || (typeof receiver !== \"object\" && typeof receiver !== \"function\")) throw new TypeError(\"Cannot use 'in' operator on non-object\");\r\n return typeof state === \"function\" ? receiver === state : state.has(receiver);\r\n}\r\n\r\nexport function __addDisposableResource(env, value, async) {\r\n if (value !== null && value !== void 0) {\r\n if (typeof value !== \"object\" && typeof value !== \"function\") throw new TypeError(\"Object expected.\");\r\n var dispose;\r\n if (async) {\r\n if (!Symbol.asyncDispose) throw new TypeError(\"Symbol.asyncDispose is not defined.\");\r\n dispose = value[Symbol.asyncDispose];\r\n }\r\n if (dispose === void 0) {\r\n if (!Symbol.dispose) throw new TypeError(\"Symbol.dispose is not defined.\");\r\n dispose = value[Symbol.dispose];\r\n }\r\n if (typeof dispose !== \"function\") throw new TypeError(\"Object not disposable.\");\r\n env.stack.push({ value: value, dispose: dispose, async: async });\r\n }\r\n else if (async) {\r\n env.stack.push({ async: true });\r\n }\r\n return value;\r\n}\r\n\r\nvar _SuppressedError = typeof SuppressedError === \"function\" ? SuppressedError : function (error, suppressed, message) {\r\n var e = new Error(message);\r\n return e.name = \"SuppressedError\", e.error = error, e.suppressed = suppressed, e;\r\n};\r\n\r\nexport function __disposeResources(env) {\r\n function fail(e) {\r\n env.error = env.hasError ? new _SuppressedError(e, env.error, \"An error was suppressed during disposal.\") : e;\r\n env.hasError = true;\r\n }\r\n function next() {\r\n while (env.stack.length) {\r\n var rec = env.stack.pop();\r\n try {\r\n var result = rec.dispose && rec.dispose.call(rec.value);\r\n if (rec.async) return Promise.resolve(result).then(next, function(e) { fail(e); return next(); });\r\n }\r\n catch (e) {\r\n fail(e);\r\n }\r\n }\r\n if (env.hasError) throw env.error;\r\n }\r\n return next();\r\n}\r\n\r\nexport default {\r\n __extends: __extends,\r\n __assign: __assign,\r\n __rest: __rest,\r\n __decorate: __decorate,\r\n __param: __param,\r\n __metadata: __metadata,\r\n __awaiter: __awaiter,\r\n __generator: __generator,\r\n __createBinding: __createBinding,\r\n __exportStar: __exportStar,\r\n __values: __values,\r\n __read: __read,\r\n __spread: __spread,\r\n __spreadArrays: __spreadArrays,\r\n __spreadArray: __spreadArray,\r\n __await: __await,\r\n __asyncGenerator: __asyncGenerator,\r\n __asyncDelegator: __asyncDelegator,\r\n __asyncValues: __asyncValues,\r\n __makeTemplateObject: __makeTemplateObject,\r\n __importStar: __importStar,\r\n __importDefault: __importDefault,\r\n __classPrivateFieldGet: __classPrivateFieldGet,\r\n __classPrivateFieldSet: __classPrivateFieldSet,\r\n __classPrivateFieldIn: __classPrivateFieldIn,\r\n __addDisposableResource: __addDisposableResource,\r\n __disposeResources: __disposeResources,\r\n};\r\n","import { Service } from './Service';\nimport { IResultList } from './IResultList';\n\n/**\n * Paging allows you to query the next and previous data chunks\n * in a convenient way. You can also go to a specific page or just read\n * page information about the current data chunk.\n * Note that page numbers are generated by backend\n * and may be used as offset rather than a continuous range of positive numbers\n * (e.g. in case of users with restricted permissions).\n */\nexport class Paging<TData> {\n /**\n * Holds the number of the current page, so in fact\n * the data chunk you are looking at.\n */\n currentPage: number;\n /**\n * Holds the number of the next page.\n */\n nextPage: number;\n /**\n * Holds the number of the previous page.\n */\n prevPage: number;\n /**\n * Holds the number of the maximum data that you will\n * get with the response.\n */\n pageSize: number;\n /**\n * Holds the number of total pages regarding to the\n * given page size.\n */\n totalPages: number;\n\n private service: Service<TData>;\n private filter: object;\n\n constructor(service: Service<TData>, statistics: any, filter: object) {\n this.filter = filter;\n this.service = service;\n this.currentPage = statistics.currentPage;\n this.nextPage = statistics.nextPage;\n this.prevPage = statistics.prevPage;\n this.pageSize = statistics.pageSize;\n this.totalPages = statistics.totalPages;\n }\n\n /**\n * Gets the next page of available data from the server.\n * @param filter\n */\n async next(filter: object = {}): Promise<IResultList<TData>> {\n return this.list(this.getFilter(filter, this.nextPage));\n }\n\n /**\n * Gets the previous page of available data from server.\n * @param filter\n */\n async prev(filter: object = {}): Promise<IResultList<TData>> {\n return this.list(this.getFilter(filter, this.prevPage));\n }\n\n /**\n * Method used by next(), prev() and goto() to call the service.list method.\n * It is public so it can be overriden in special cases (like children objects\n * in inventory).\n * @param filter\n */\n async list(filter: object = {}): Promise<IResultList<TData>> {\n return this.service.list(filter);\n }\n\n /**\n * Goes to the page that you define as page parameter.\n * @param page\n * @param filter\n */\n async goto(page: number, filter: object = {}): Promise<IResultList<TData>> {\n return this.list(this.getFilter(filter, page));\n }\n\n private getFilter(filter: object, page: number) {\n return Object.assign(filter, this.filter, { currentPage: page });\n }\n}\n","import { IFetchClient } from './IFetchClient';\nimport { IFetchOptions } from './IFetchOptions';\nimport { IFetchResponse } from './IFetchResponse';\nimport { IIdentified } from './IIdentified';\nimport { IResult } from './IResult';\nimport { IResultList } from './IResultList';\nimport { Paging } from './Paging';\n\nimport { Realtime } from '../realtime/index';\n\nexport abstract class Service<TData extends IIdentified> {\n protected propertyName: string;\n protected abstract baseUrl: string;\n protected abstract listUrl: string;\n protected channel: string;\n private cache = new Map();\n\n constructor(protected client: IFetchClient, protected realtime?: Realtime) {\n const methodsToHide = ['list', 'create', 'update', 'detail', 'delete'];\n const prototype = Object.getPrototypeOf(this);\n methodsToHide.forEach(method => {\n if (!prototype.hasOwnProperty(method)) {\n Object.defineProperty(this, method, {\n get() {\n return undefined;\n }\n });\n }\n });\n }\n\n async list(filter: object = {}): Promise<IResultList<TData>> {\n const headers = { accept: 'application/json' };\n const url = this.listUrl;\n const res = await this.fetch(url, this.changeFetchOptions({ headers, params: filter }, url));\n const json = await res.json();\n const data = this.propertyName ? json[this.propertyName] : json;\n const paging = this.getPaging(json, filter);\n return { res, data, paging };\n }\n\n protected async detail(\n entityOrId: string | number | IIdentified,\n filter: object = {}\n ): Promise<IResult<TData>> {\n const headers = { accept: 'application/json' };\n const url = this.getDetailUrl(entityOrId);\n const res = await this.fetch(\n url,\n this.changeFetchOptions({ headers, params: { ...filter } }, url)\n );\n const data = await res.json();\n return { res, data };\n }\n\n protected async create(entity: Partial<TData>): Promise<IResult<TData>> {\n const url = this.listUrl;\n const method = 'POST';\n const body = JSON.stringify(this.onBeforeCreate(entity));\n const headers = { 'content-type': 'application/json', accept: 'application/json' };\n const res = await this.fetch(url, this.changeFetchOptions({ method, body, headers }, url));\n const data = await res.json();\n return { res, data };\n }\n\n protected async update(entity: Partial<TData>): Promise<IResult<TData>> {\n const url = this.getDetailUrl(entity);\n const method = 'PUT';\n const body = JSON.stringify(this.onBeforeUpdate(entity));\n const headers = { 'content-type': 'application/json', accept: 'application/json' };\n const res = await this.fetch(url, this.changeFetchOptions({ method, body, headers }, url));\n const data = await res.json();\n return { res, data };\n }\n\n protected async delete(\n entityOrId: string | number | IIdentified,\n params?: any\n ): Promise<IResult<null>> {\n const method = 'DELETE';\n const url = this.getDetailUrl(entityOrId);\n const res = await this.fetch(url, this.changeFetchOptions({ method, params }, url));\n return { res, data: null };\n }\n\n protected onBeforeCreate(obj: Partial<TData>): Partial<TData> {\n delete obj.id;\n return obj;\n }\n\n protected onBeforeUpdate(objWithId: Partial<TData>): Partial<TData> {\n return objWithId;\n }\n\n protected changeFetchOptions(options: any, _url = '') {\n return options;\n }\n\n protected getUrl(url = ''): string {\n const baseUrl = this.baseUrl.replace(/\\/+$/, '');\n const partialUrl = url.replace(/^\\/+/, '');\n return `${baseUrl}/${partialUrl}`;\n }\n\n protected getEntityId(entityOrId: string | number | IIdentified): string {\n if (entityOrId === undefined || entityOrId === null) {\n return '';\n }\n\n if (typeof entityOrId === 'object') {\n return this.getEntityId(entityOrId.id);\n }\n\n return `${entityOrId}`;\n }\n\n protected getDetailUrl(entityOrId: string | number | IIdentified): string {\n const id = this.getEntityId(entityOrId);\n return `${this.listUrl}/${id}`;\n }\n\n protected async fetch(url: string, init?: IFetchOptions): Promise<IFetchResponse> {\n const fullUrl = this.getUrl(url);\n const res: IFetchResponse = await this.client.fetch(fullUrl, init);\n return await this.handleErrorStatusCodes(res);\n }\n\n /**\n * Checks the response for errors and throws exceptions, otherwise returns the response as is.\n *\n * @param response The response from server.\n *\n * @returns If no errors are detected, it returns the same response.\n *\n * @throws If an error is detected, it throws `{ res, data }`, where `data` contains error details from server.\n */\n protected async handleErrorStatusCodes(response: IFetchResponse): Promise<IFetchResponse> {\n if (response.status >= 400) {\n let data = null;\n try {\n data = await response.json();\n } catch (ex) {\n try {\n data = await response.text();\n } catch (ex) {\n // do nothing\n }\n }\n throw { res: response, data };\n }\n return response;\n }\n\n protected mimeType(type: string): string {\n return `application/vnd.com.nsn.cumulocity.${type}+json`;\n }\n\n protected getIdString(reference: number | string | IIdentified): string {\n let id;\n if (typeof reference === 'object') {\n id = reference.id;\n } else {\n id = reference;\n }\n return String(id);\n }\n\n protected getPaging(json: any, filter: object): Paging<TData> {\n if (json.statistics) {\n const statistics = {\n ...json.statistics,\n nextPage: this.getCurrentPageFromLink(json.next),\n prevPage: this.getCurrentPageFromLink(json.prev)\n };\n return new Paging<TData>(this, statistics, filter);\n }\n return null;\n }\n\n protected getCurrentPageFromLink(link = '') {\n const matches = link.match(/currentPage=(-{0,1}\\d+)/);\n return matches && parseInt(matches[1], 10);\n }\n}\n","var global = typeof self !== 'undefined' ? self : this;\nvar __self__ = (function () {\nfunction F() {\nthis.fetch = false;\nthis.DOMException = global.DOMException\n}\nF.prototype = global;\nreturn new F();\n})();\n(function(self) {\n\nvar irrelevant = (function (exports) {\n\n var support = {\n searchParams: 'URLSearchParams' in self,\n iterable: 'Symbol' in self && 'iterator' in Symbol,\n blob:\n 'FileReader' in self &&\n 'Blob' in self &&\n (function() {\n try {\n new Blob();\n return true\n } catch (e) {\n return false\n }\n })(),\n formData: 'FormData' in self,\n arrayBuffer: 'ArrayBuffer' in self\n };\n\n function isDataView(obj) {\n return obj && DataView.prototype.isPrototypeOf(obj)\n }\n\n if (support.arrayBuffer) {\n var viewClasses = [\n '[object Int8Array]',\n '[object Uint8Array]',\n '[object Uint8ClampedArray]',\n '[object Int16Array]',\n '[object Uint16Array]',\n '[object Int32Array]',\n '[object Uint32Array]',\n '[object Float32Array]',\n '[object Float64Array]'\n ];\n\n var isArrayBufferView =\n ArrayBuffer.isView ||\n function(obj) {\n return obj && viewClasses.indexOf(Object.prototype.toString.call(obj)) > -1\n };\n }\n\n function normalizeName(name) {\n if (typeof name !== 'string') {\n name = String(name);\n }\n if (/[^a-z0-9\\-#$%&'*+.^_`|~]/i.test(name)) {\n throw new TypeError('Invalid character in header field name')\n }\n return name.toLowerCase()\n }\n\n function normalizeValue(value) {\n if (typeof value !== 'string') {\n value = String(value);\n }\n return value\n }\n\n // Build a destructive iterator for the value list\n function iteratorFor(items) {\n var iterator = {\n next: function() {\n var value = items.shift();\n return {done: value === undefined, value: value}\n }\n };\n\n if (support.iterable) {\n iterator[Symbol.iterator] = function() {\n return iterator\n };\n }\n\n return iterator\n }\n\n function Headers(headers) {\n this.map = {};\n\n if (headers instanceof Headers) {\n headers.forEach(function(value, name) {\n this.append(name, value);\n }, this);\n } else if (Array.isArray(headers)) {\n headers.forEach(function(header) {\n this.append(header[0], header[1]);\n }, this);\n } else if (headers) {\n Object.getOwnPropertyNames(headers).forEach(function(name) {\n this.append(name, headers[name]);\n }, this);\n }\n }\n\n Headers.prototype.append = function(name, value) {\n name = normalizeName(name);\n value = normalizeValue(value);\n var oldValue = this.map[name];\n this.map[name] = oldValue ? oldValue + ', ' + value : value;\n };\n\n Headers.prototype['delete'] = function(name) {\n delete this.map[normalizeName(name)];\n };\n\n Headers.prototype.get = function(name) {\n name = normalizeName(name);\n return this.has(name) ? this.map[name] : null\n };\n\n Headers.prototype.has = function(name) {\n return this.map.hasOwnProperty(normalizeName(name))\n };\n\n Headers.prototype.set = function(name, value) {\n this.map[normalizeName(name)] = normalizeValue(value);\n };\n\n Headers.prototype.forEach = function(callback, thisArg) {\n for (var name in this.map) {\n if (this.map.hasOwnProperty(name)) {\n callback.call(thisArg, this.map[name], name, this);\n }\n }\n };\n\n Headers.prototype.keys = function() {\n var items = [];\n this.forEach(function(value, name) {\n items.push(name);\n });\n return iteratorFor(items)\n };\n\n Headers.prototype.values = function() {\n var items = [];\n this.forEach(function(value) {\n items.push(value);\n });\n return iteratorFor(items)\n };\n\n Headers.prototype.entries = function() {\n var items = [];\n this.forEach(function(value, name) {\n items.push([name, value]);\n });\n return iteratorFor(items)\n };\n\n if (support.iterable) {\n Headers.prototype[Symbol.iterator] = Headers.prototype.entries;\n }\n\n function consumed(body) {\n if (body.bodyUsed) {\n return Promise.reject(new TypeError('Already read'))\n }\n body.bodyUsed = true;\n }\n\n function fileReaderReady(reader) {\n return new Promise(function(resolve, reject) {\n reader.onload = function() {\n resolve(reader.result);\n };\n reader.onerror = function() {\n reject(reader.error);\n };\n })\n }\n\n function readBlobAsArrayBuffer(blob) {\n var reader = new FileReader();\n var promise = fileReaderReady(reader);\n reader.readAsArrayBuffer(blob);\n return promise\n }\n\n function readBlobAsText(blob) {\n var reader = new FileReader();\n var promise = fileReaderReady(reader);\n reader.readAsText(blob);\n return promise\n }\n\n function readArrayBufferAsText(buf) {\n var view = new Uint8Array(buf);\n var chars = new Array(view.length);\n\n for (var i = 0; i < view.length; i++) {\n chars[i] = String.fromCharCode(view[i]);\n }\n return chars.join('')\n }\n\n function bufferClone(buf) {\n if (buf.slice) {\n return buf.slice(0)\n } else {\n var view = new Uint8Array(buf.byteLength);\n view.set(new Uint8Array(buf));\n return view.buffer\n }\n }\n\n function Body() {\n this.bodyUsed = false;\n\n this._initBody = function(body) {\n this._bodyInit = body;\n if (!body) {\n this._bodyText = '';\n } else if (typeof body === 'string') {\n this._bodyText = body;\n } else if (support.blob && Blob.prototype.isPrototypeOf(body)) {\n this._bodyBlob = body;\n } else if (support.formData && FormData.prototype.isPrototypeOf(body)) {\n this._bodyFormData = body;\n } else if (support.searchParams && URLSearchParams.prototype.isPrototypeOf(body)) {\n this._bodyText = body.toString();\n } else if (support.arrayBuffer && support.blob && isDataView(body)) {\n this._bodyArrayBuffer = bufferClone(body.buffer);\n // IE 10-11 can't handle a DataView body.\n this._bodyInit = new Blob([this._bodyArrayBuffer]);\n } else if (support.arrayBuffer && (ArrayBuffer.prototype.isPrototypeOf(body) || isArrayBufferView(body))) {\n this._bodyArrayBuffer = bufferClone(body);\n } else {\n this._bodyText = body = Object.prototype.toString.call(body);\n }\n\n if (!this.headers.get('content-type')) {\n if (typeof body === 'string') {\n this.headers.set('content-type', 'text/plain;charset=UTF-8');\n } else if (this._bodyBlob && this._bodyBlob.type) {\n this.headers.set('content-type', this._bodyBlob.type);\n } else if (support.searchParams && URLSearchParams.prototype.isPrototypeOf(body)) {\n this.headers.set('content-type', 'application/x-www-form-urlencoded;charset=UTF-8');\n }\n }\n };\n\n if (support.blob) {\n this.blob = function() {\n var rejected = consumed(this);\n if (rejected) {\n return rejected\n }\n\n if (this._bodyBlob) {\n return Promise.resolve(this._bodyBlob)\n } else if (this._bodyArrayBuffer) {\n return Promise.resolve(new Blob([this._bodyArrayBuffer]))\n } else if (this._bodyFormData) {\n throw new Error('could not read FormData body as blob')\n } else {\n return Promise.resolve(new Blob([this._bodyText]))\n }\n };\n\n this.arrayBuffer = function() {\n if (this._bodyArrayBuffer) {\n return consumed(this) || Promise.resolve(this._bodyArrayBuffer)\n } else {\n return this.blob().then(readBlobAsArrayBuffer)\n }\n };\n }\n\n this.text = function() {\n var rejected = consumed(this);\n if (rejected) {\n return rejected\n }\n\n if (this._bodyBlob) {\n return readBlobAsText(this._bodyBlob)\n } else if (this._bodyArrayBuffer) {\n return Promise.resolve(readArrayBufferAsText(this._bodyArrayBuffer))\n } else if (this._bodyFormData) {\n throw new Error('could not read FormData body as text')\n } else {\n return Promise.resolve(this._bodyText)\n }\n };\n\n if (support.formData) {\n this.formData = function() {\n return this.text().then(decode)\n };\n }\n\n this.json = function() {\n return this.text().then(JSON.parse)\n };\n\n return this\n }\n\n // HTTP methods whose capitalization should be normalized\n var methods = ['DELETE', 'GET', 'HEAD', 'OPTIONS', 'POST', 'PUT'];\n\n function normalizeMethod(method) {\n var upcased = method.toUpperCase();\n return methods.indexOf(upcased) > -1 ? upcased : method\n }\n\n function Request(input, options) {\n options = options || {};\n var body = options.body;\n\n if (input instanceof Request) {\n if (input.bodyUsed) {\n throw new TypeError('Already read')\n }\n this.url = input.url;\n this.credentials = input.credentials;\n if (!options.headers) {\n this.headers = new Headers(input.headers);\n }\n this.method = input.method;\n this.mode = input.mode;\n this.signal = input.signal;\n if (!body && input._bodyInit != null) {\n body = input._bodyInit;\n input.bodyUsed = true;\n }\n } else {\n this.url = String(input);\n }\n\n this.credentials = options.credentials || this.credentials || 'same-origin';\n if (options.headers || !this.headers) {\n this.headers = new Headers(options.headers);\n }\n this.method = normalizeMethod(options.method || this.method || 'GET');\n this.mode = options.mode || this.mode || null;\n this.signal = options.signal || this.signal;\n this.referrer = null;\n\n if ((this.method === 'GET' || this.method === 'HEAD') && body) {\n throw new TypeError('Body not allowed for GET or HEAD requests')\n }\n this._initBody(body);\n }\n\n Request.prototype.clone = function() {\n return new Request(this, {body: this._bodyInit})\n };\n\n function decode(body) {\n var form = new FormData();\n body\n .trim()\n .split('&')\n .forEach(function(bytes) {\n if (bytes) {\n var split = bytes.split('=');\n var name = split.shift().replace(/\\+/g, ' ');\n var value = split.join('=').replace(/\\+/g, ' ');\n form.append(decodeURIComponent(name), decodeURIComponent(value));\n }\n });\n return form\n }\n\n function parseHeaders(rawHeaders) {\n var headers = new Headers();\n // Replace instances of \\r\\n and \\n followed by at least one space or horizontal tab with a space\n // https://tools.ietf.org/html/rfc7230#section-3.2\n var preProcessedHeaders = rawHeaders.replace(/\\r?\\n[\\t ]+/g, ' ');\n preProcessedHeaders.split(/\\r?\\n/).forEach(function(line) {\n var parts = line.split(':');\n var key = parts.shift().trim();\n if (key) {\n var value = parts.join(':').trim();\n headers.append(key, value);\n }\n });\n return headers\n }\n\n Body.call(Request.prototype);\n\n function Response(bodyInit, options) {\n if (!options) {\n options = {};\n }\n\n this.type = 'default';\n this.status = options.status === undefined ? 200 : options.status;\n this.ok = this.status >= 200 && this.status < 300;\n this.statusText = 'statusText' in options ? options.statusText : 'OK';\n this.headers = new Headers(options.headers);\n this.url = options.url || '';\n this._initBody(bodyInit);\n }\n\n Body.call(Response.prototype);\n\n Response.prototype.clone = function() {\n return new Response(this._bodyInit, {\n status: this.status,\n statusText: this.statusText,\n headers: new Headers(this.headers),\n url: this.url\n })\n };\n\n Response.error = function() {\n var response = new Response(null, {status: 0, statusText: ''});\n response.type = 'error';\n return response\n };\n\n var redirectStatuses = [301, 302, 303, 307, 308];\n\n Response.redirect = function(url, status) {\n if (redirectStatuses.indexOf(status) === -1) {\n throw new RangeError('Invalid status code')\n }\n\n return new Response(null, {status: status, headers: {location: url}})\n };\n\n exports.DOMException = self.DOMException;\n try {\n new exports.DOMException();\n } catch (err) {\n exports.DOMException = function(message, name) {\n this.message = message;\n this.name = name;\n var error = Error(message);\n this.stack = error.stack;\n };\n exports.DOMException.prototype = Object.create(Error.prototype);\n exports.DOMException.prototype.constructor = exports.DOMException;\n }\n\n function fetch(input, init) {\n return new Promise(function(resolve, reject) {\n var request = new Request(input, init);\n\n if (request.signal && request.signal.aborted) {\n return reject(new exports.DOMException('Aborted', 'AbortError'))\n }\n\n var xhr = new XMLHttpRequest();\n\n function abortXhr() {\n xhr.abort();\n }\n\n xhr.onload = function() {\n var options = {\n status: xhr.status,\n statusText: xhr.statusText,\n headers: parseHeaders(xhr.getAllResponseHeaders() || '')\n };\n options.url = 'responseURL' in xhr ? xhr.responseURL : options.headers.get('X-Request-URL');\n var body = 'response' in xhr ? xhr.response : xhr.responseText;\n resolve(new Response(body, options));\n };\n\n xhr.onerror = function() {\n reject(new TypeError('Network request failed'));\n };\n\n xhr.ontimeout = function() {\n reject(new TypeError('Network request failed'));\n };\n\n xhr.onabort = function() {\n reject(new exports.DOMException('Aborted', 'AbortError'));\n };\n\n xhr.open(request.method, request.url, true);\n\n if (request.credentials === 'include') {\n xhr.withCredentials = true;\n } else if (request.credentials === 'omit') {\n xhr.withCredentials = false;\n }\n\n if ('responseType' in xhr && support.blob) {\n xhr.responseType = 'blob';\n }\n\n request.headers.forEach(function(value, name) {\n xhr.setRequestHeader(name, value);\n });\n\n if (request.signal) {\n request.signal.addEventListener('abort', abortXhr);\n\n xhr.onreadystatechange = function() {\n // DONE (success or failure)\n if (xhr.readyState === 4) {\n request.signal.removeEventListener('abort', abortXhr);\n }\n };\n }\n\n xhr.send(typeof request._bodyInit === 'undefined' ? null : request._bodyInit);\n })\n }\n\n fetch.polyfill = true;\n\n if (!self.fetch) {\n self.fetch = fetch;\n self.Headers = Headers;\n self.Request = Request;\n self.Response = Response;\n }\n\n exports.Headers = Headers;\n exports.Request = Request;\n exports.Response = Response;\n exports.fetch = fetch;\n\n Object.defineProperty(exports, '__esModule', { value: true });\n\n return exports;\n\n})({});\n})(__self__);\n__self__.fetch.ponyfill = true;\n// Remove \"polyfill\" property added by whatwg-fetch\ndelete __self__.fetch.polyfill;\n// Choose between native implementation (global) or custom implementation (__self__)\n// var ctx = global.fetch ? global : __self__;\nvar ctx = __self__; // this line disable service worker support temporarily\nexports = ctx.fetch // To enable: import fetch from 'cross-fetch'\nexports.default = ctx.fetch // For TypeScript consumers without esModuleInterop.\nexports.fetch = ctx.fetch // To enable: import {fetch} from 'cross-fetch'\nexports.Headers = ctx.Headers\nexports.Request = ctx.Request\nexports.Response = ctx.Response\nmodule.exports = exports\n","import fetch from 'cross-fetch';\n\nimport { IFetchClient } from './IFetchClient';\nimport { IFetchOptions } from './IFetchOptions';\nimport { IFetchResponse } from './IFetchResponse';\nimport { IAuthentication } from './IAuthentication';\n\n// eslint-disable-next-line prefer-const\nlet auths = new WeakMap();\n\nexport class FetchClient implements IFetchClient {\n tenant = '';\n defaultHeaders = {};\n constructor(authOrBaseUrl?: IAuthentication | string, public baseUrl?: string) {\n if (typeof authOrBaseUrl === 'string') {\n baseUrl = authOrBaseUrl;\n } else {\n this.setAuth(authOrBaseUrl);\n }\n this.baseUrl = this.resolveServerUrl(baseUrl);\n }\n\n setAuth(auth: IAuthentication) {\n auths.set(this, auth);\n }\n\n async fetch(url: string, init?: IFetchOptions): Promise<IFetchResponse> {\n let fetchFn = fetch;\n try {\n fetchFn = window.fetch || fetchFn;\n } catch (e) {\n /* do nothing */\n }\n const fullUrl: string = this.getUrl(url, init);\n const options: IFetchOptions = this.getFetchOptions(init);\n const optionsWithAdjustedBody = this.adjustOptionsForFormData(options);\n return fetchFn(fullUrl, optionsWithAdjustedBody);\n }\n\n getUrl(url = '', options?: IFetchOptions): string {\n const params = options && options.params;\n let paramPart = '';\n if (params && Object.keys(params).length) {\n paramPart = Object.keys(params)\n .map(k => {\n let vals = params[k];\n const encodedKey = encodeURIComponent(k);\n if (!Array.isArray(vals)) {\n vals = [vals];\n }\n return vals.map(v => `${encodedKey}=${encodeURIComponent(v)}`).join('&');\n })\n .join('&');\n paramPart = `?${paramPart}`;\n }\n const baseUrl = this.baseUrl.replace(/\\/+$/, '').replace(/^\\/+/, '');\n const partialUrl = url.replace(/\\/+$/, '').replace(/^\\/+/, '');\n return `${baseUrl}/${partialUrl}${paramPart}`;\n }\n\n getFetchOptions(options: IFetchOptions = {}): IFetchOptions {\n let clonedOptions = { ...options };\n const auth = auths.get(this);\n clonedOptions.headers = Object.assign({}, this.defaultHeaders, clonedOptions.headers, {\n UseXBasic: true\n });\n delete clonedOptions.params;\n clonedOptions = auth ? auth.getFetchOptions(clonedOptions) : clonedOptions;\n return clonedOptions;\n }\n\n getCometdHandshake(config: any = {}) {\n const auth = auths.get(this);\n return auth ? auth.getCometdHandshake(config) : config;\n }\n\n private resolveServerUrl(baseUrl = ''): any {\n if (baseUrl && baseUrl.startsWith('http')) {\n return baseUrl.replace(/\\/+$/, '');\n }\n try {\n const location = window.location;\n return `${location.protocol}//${location.host}/${baseUrl.replace(/\\/+$/, '')}`;\n } catch (ex) {\n throw Error('Your environment does not support relative URLs. Please provide a base URL.');\n }\n }\n\n private adjustOptionsForFormData(options: IFetchOptions): RequestInit {\n const newOptions = Object.assign(options, { body: options.body as RequestInit['body'] });\n return newOptions;\n }\n}\n","export var error = function (message) {\n function E() {\n this.message = message;\n }\n\n E.prototype = new Error();\n E.prototype.name = 'InvalidCharacterError';\n E.prototype.code = 5;\n return E;\n};\nexport var chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=';","import { chars, error } from './common'; // btoa polyfill for IE<10 courtesy https://gist.github.com/nignag/999166\n\nvar E = error('The string to be encoded contains characters out of range');\nexport var _btoa = typeof btoa !== 'undefined'\n/* istanbul ignore next */\n? function (input) {\n return btoa(input);\n} : function (input) {\n var str = String(input);\n var output = '';\n\n for ( // initialize result and counter\n var block, charCode, idx = 0, map = chars; // if the next str index does not exist:\n // change the mapping table to \"=\"\n // check if d has no fractional digits\n str.charAt(idx | 0) || (map = '=', idx % 1); // \"8 - idx % 1 * 8\" generates the sequence 2, 4, 6, 8\n output += map.charAt(63 & block >> 8 - idx % 1 * 8)) {\n charCode = str.charCodeAt(idx += 3 / 4);\n\n if (charCode > 0xFF) {\n throw new E();\n }\n\n block = block << 8 | charCode;\n }\n\n return output;\n};\n\nvar utf8 = function (input) {\n return encodeURIComponent(input).replace(/%([0-9A-F]{2})/g, function (match, p1) {\n return String.fromCharCode('0x' + p1);\n });\n};\n\nexport default (function (input) {\n return _btoa(utf8(input));\n});","import { IAuthentication, ICredentials } from './IAuthentication';\nimport { btoa } from 'b2a';\n\n// this is var and not const to please typedoc https://github.com/TypeStrong/typedoc/issues/691\n// eslint-disable-next-line no-var\nvar secrets = new WeakMap();\n\n/**\n * Allows to use Basic-Auth for Authorization to the\n * Cumulocity API.\n */\nexport class BasicAuth implements IAuthentication {\n user: string;\n /**\n * Authenticates the given user against the given tenant.\n * @param name\n * @param password\n * @param tenant\n */\n constructor(credentials?: ICredentials) {\n this.updateCredentials(credentials);\n }\n\n updateCredentials({ tenant, user, password, token, tfa }: ICredentials = {}) {\n const secret = secrets.get(this) || {};\n if (user && tenant) {\n user = `${tenant}/${user}`;\n }\n user = user || this.user;\n password = password || secret.password;\n if (!token && user && password) {\n token = btoa(`${user}:${password}`);\n }\n if (user) {\n this.user = user;\n }\n token = token || secret.token;\n tfa = tfa || secret.tfa;\n secrets.set(this, { tfa, token, password });\n return token;\n }\n\n getFetchOptions(options) {\n const secret = secrets.get(this);\n const { token, tfa } = secret;\n const xsrfToken = this.getCookieValue('XSRF-TOKEN');\n const headers: any = {\n Authorization: `Basic ${token || ''}`,\n ...(xsrfToken ? { 'X-XSRF-TOKEN': xsrfToken } : undefined)\n };\n\n if (tfa) {\n headers.tfatoken = tfa;\n }\n options.headers = Object.assign(headers, options.headers);\n return options;\n }\n\n getCometdHandshake(config: { ext?: object } = {}) {\n const secret = secrets.get(this);\n const { token, tfa } = secret;\n const KEY = 'com.cumulocity.authn';\n const ext = (config.ext = config.ext || {});\n ext[KEY] = Object.assign(ext[KEY] || {}, { token, tfa });\n return config;\n }\n\n logout() {\n delete this.user;\n secrets.set(this, {});\n }\n\n private getCookieValue(name) {\n try {\n const value = document.cookie.match('(^|;)\\\\s*' + name + '\\\\s*=\\\\s*([^;]+)');\n return value ? value.pop() : undefined;\n } catch (ex) {\n return undefined;\n }\n }\n}\n","import { chars, error } from './common';\nvar E = error('The string to be decoded is not correctly encoded');\nexport var _atob = typeof atob !== 'undefined'\n/* istanbul ignore next */\n? function (input) {\n return atob(input);\n} : function (input) {\n var str = String(input).replace(/[=]+$/, '');\n\n if (str.length % 4 == 1) {\n throw new E();\n }\n\n var output = '';\n\n for ( // initialize result and counters\n var bc = 0, bs, buffer, idx = 0; // get next character\n buffer = str.charAt(idx++); // character found in table? initialize bit storage and add its ascii value;\n ~buffer && (bs = bc % 4 ? bs * 64 + buffer : buffer, // and if not first of each 4 characters,\n // convert the first 8 bits to one ascii character\n bc++ % 4) ? output += String.fromCharCode(255 & bs >> (-2 * bc & 6)) : 0) {\n // try to find character in table (0-63, not found => -1)\n buffer = chars.indexOf(buffer);\n }\n\n return output;\n};\n\nvar utf16 = function (input) {\n return decodeURIComponent(input.split('').map(function (c) {\n return '%' + ('00' + c.charCodeAt(0).toString(16)).slice(-2);\n }).join(''));\n};\n\nexport default (function (input) {\n return utf16(_atob(input));\n});","import { IAuthentication, ICredentials } from './IAuthentication';\n\nconst secrets = new WeakMap();\n\nexport class BearerAuth implements IAuthentication {\n constructor(token?: string) {\n secrets.set(this, { token });\n }\n getFetchOptions(options: any): any {\n const secret = secrets.get(this);\n const { token } = secret;\n options.headers = Object.assign({ Authorization: `Bearer ${token}` }, options.headers);\n return options;\n }\n\n updateCredentials({ token }: ICredentials): undefined {\n secrets.set(this, { token });\n return;\n }\n\n getCometdHandshake(config: { ext?: any } = {}) {\n const secret = secrets.get(this);\n const { token, tfa } = secret;\n const KEY = 'com.cumulocity.authn';\n const ext = (config.ext = config.ext || {});\n ext[KEY] = Object.assign(ext[KEY] || {}, { token, tfa });\n return config;\n }\n\n logout(): void {\n secrets.set(this, {});\n }\n}\n","import { IAuthentication, ICredentials } from './IAuthentication';\nimport { FetchClient } from './FetchClient';\n\n/**\n * Allows to use Cookies for Authorization to the\n * Cumulocity API.\n */\nexport class CookieAuth implements IAuthentication {\n user: string;\n private logoutUrl = 'user/logout';\n\n updateCredentials({ user }: ICredentials = {}): string {\n this.user = user;\n return undefined;\n }\n\n getFetchOptions(options) {\n const xsrfToken = this.getCookieValue('XSRF-TOKEN');\n const headers: any = { 'X-XSRF-TOKEN': xsrfToken };\n options.headers = Object.assign(headers, options.headers);\n return options;\n }\n\n getCometdHandshake(config: { ext?: object } = {}) {\n const KEY = 'com.cumulocity.authn';\n const xsrfToken = this.getCookieValue('XSRF-TOKEN');\n const ext = (config.ext = config.ext || {});\n ext[KEY] = Object.assign(ext[KEY] || {}, { xsrfToken });\n return config;\n }\n\n async logout() {\n if (this.user) {\n delete this.user;\n }\n const client = new FetchClient();\n client.setAuth(this);\n const method = 'POST';\n const body = JSON.stringify({});\n const headers = { 'content-type': 'application/json', accept: 'application/json' };\n return client.fetch(this.logoutUrl, { headers, body, method });\n }\n\n private getCookieValue(name) {\n const value = document.cookie.match('(^|;)\\\\s*' + name + '\\\\s*=\\\\s*([^;]+)');\n return value ? value.pop() : '';\n }\n}\n","import { IAuthentication, IMicroserviceClientRequestHeaders } from './IAuthentication';\n\n/**\n * Allows to use either Cookie-Auth or Basic-Auth\n * of a microservice client request header\n * for Authorization to the Cumulocity API.\n */\nexport class MicroserviceClientRequestAuth implements IAuthentication {\n // Bearer token read from cookie from header\n protected authTokenFromCookie: string | undefined;\n // Bearer/Basic auth token read from header\n protected authTokenFromHeader: string | undefined;\n protected xsrfToken: string | undefined;\n\n /**\n * Authenticates using the credentials which were\n * provided within the request headers of the\n * client call to the microservice.\n * @param headers\n */\n constructor(headers: IMicroserviceClientRequestHeaders = {}) {\n this.xsrfToken = this.getCookieValue(headers, 'XSRF-TOKEN');\n this.authTokenFromCookie = this.getCookieValue(headers, 'authorization');\n this.authTokenFromHeader = headers.authorization;\n }\n\n updateCredentials(): string {\n return undefined;\n }\n\n getFetchOptions(options: any) {\n const headers: any = {\n Authorization: this.authTokenFromCookie\n ? `Bearer ${this.authTokenFromCookie}`\n : this.authTokenFromHeader,\n ...(this.xsrfToken ? { 'X-XSRF-TOKEN': this.xsrfToken } : undefined)\n };\n options.headers = Object.assign(headers, options.headers);\n return options;\n }\n\n getCometdHandshake(config: { ext?: { [key: string]: any } } = {}) {\n const KEY = 'com.cumulocity.authn';\n const xsrfToken = this.xsrfToken;\n let token = this.authTokenFromCookie;\n if (!token && this.authTokenFromHeader) {\n token = this.authTokenFromHeader.replace('Basic ', '').replace('Bearer ', '');\n }\n const ext = (config.ext = config.ext || {});\n ext[KEY] = Object.assign(ext[KEY] || {}, { token, ...(xsrfToken ? { xsrfToken } : undefined) });\n return config;\n }\n\n logout() {\n if (this.authTokenFromCookie) {\n delete this.authTokenFromCookie;\n }\n if (this.authTokenFromHeader) {\n delete this.authTokenFromHeader;\n }\n if (this.xsrfToken) {\n delete this.xsrfToken;\n }\n }\n\n protected getCookieValue(headers: IMicroserviceClientRequestHeaders, name: string) {\n try {\n const value =\n headers && headers.cookie && headers.cookie.match('(^|;)\\\\s*' + name + '\\\\s*=\\\\s*([^;]+)');\n return value ? value.pop() : undefined;\n } catch (ex) {\n return undefined;\n }\n }\n}\n","import { IFetchResponse } from './IFetchResponse';\nimport { MicroserviceClientRequestAuth } from './MicroserviceClientRequestAuth';\n\n/**\n * Extracts the `authorization` cookie from the `set-cookie` header of a response.\n *\n * Meant to be used in none browser environments like nodejs which don't deal with cookies.\n */\nexport class NodeJSCookieAuth extends MicroserviceClientRequestAuth {\n constructor(cookieResponse: IFetchResponse) {\n super();\n\n const setCookiesHeader = cookieResponse.headers.get('set-cookie');\n if (!setCookiesHeader) {\n throw Error('No Cookie set');\n }\n this.authTokenFromCookie = this.getCookieValue({ cookie: setCookiesHeader }, 'authorization');\n }\n}\n","import { gettext } from '../gettext';\n\n/**\n * Severity can be one of the following states.\n * It is used in [[AlarmService]] for example.\n */\nexport enum Severity {\n CRITICAL = gettext('CRITICAL'),\n MAJOR = gettext('MAJOR'),\n MINOR = gettext('MINOR'),\n WARNING = gettext('WARNING')\n}\n","export class QueriesUtil {\n protected operatorFns = {\n __not: operand => {\n return `not(${this.buildQueryFilter(operand, null)})`;\n },\n __and: operand => {\n return this.buildQueryFilter(operand, null, 'and');\n },\n __or: operand => {\n return this.buildQueryFilter(operand, null, 'or');\n },\n __eq: (operand, contextKey) => {\n if (typeof operand === 'object' && operand !== null) {\n return this.buildQueryFilter(operand, contextKey);\n }\n return `${contextKey} eq ${this.quoteString(operand)}`;\n },\n __gt: (operand, contextKey) => {\n return `${contextKey} gt ${this.quoteString(operand)}`;\n },\n __ge: (operand, contextKey) => {\n return `${contextKey} ge ${this.quoteString(operand)}`;\n },\n __lt: (operand, contextKey) => {\n return `${contextKey} lt ${this.quoteString(operand)}`;\n },\n __le: (operand, contextKey) => {\n return `${contextKey} le ${this.quoteString(operand)}`;\n },\n __in: (operand, contextKey) => {\n const stmts = operand\n .filter(op => !!op)\n .map(op => {\n return `${contextKey} eq ${this.quoteString(op)}`;\n });\n return this.glue(stmts, 'or');\n },\n __bygroupid: operand => {\n return `bygroupid(${operand})`;\n },\n __has: operand => {\n return `has(${operand})`;\n },\n __useFilterQueryString: (queryString: string) => {\n // match everything inside the most exterior parentheses, including them\n const query = queryString.match(/\\(.*\\)/)?.[0];\n // get rid of the most exterior parentheses\n return query?.substring(1, query.length - 1);\n }\n };\n\n /**\n * Builds query string from provided query object.\n *\n * @param query Object containing filters and sort order for querying managed objects. Supported filters are:\n * - **__and** - Specifies conditions, e.g. `{__and: [{__has: 'c8y_IsDevice'}, {'count': {__gt: 0}}]}`.\n * - **__or** - Specifies alternative conditions, e.g. `{__or: [{__bygroupid: 10300}, {__bygroupid: 10400}]}`.\n * - **__eq** - Specified fragment must be equal to given value, e.g. `{'status': 'AVAILABLE'}` (no nested object required).\n * - **__lt** - Specified fragment must be less then given value, e.g. `{'count': {__lt: 10}}`.\n * - **__gt** - Specified fragment must be greater then given value, e.g. `{'count': {__gt: 0}}`.\n * - **__in** - Specified fragment must be equal to one of values in the list, e.g. `{'status': {__in: ['AVAILABLE', 'UNAVAILABLE']}}`.\n * - **__not** - Negates condition, e.g. `{__not: {'status': 'AVAILABLE'}}`.\n * - **__bygroupid** - True if filtered managed object is assigned to given group, e.g. `{__bygroupid: 10300}`.\n * - **__has** - Specified fragment must have a value defined, e.g. `{__has: 'c8y_IsDevice'}`.\n * - **__useFilterQueryString** - Gets rid of the `$filter=()… $orderby=…` parts of a query and keeps only what's between the most\n * exterior parentheses of the $filter.\n * EXAMPLE: takes a query of the form\n * `$filter=(name eq 'RaspPi*') $orderby=name asc`\n * and turns it into\n * `name eq 'RaspPi*'`\n * This is necessary for searching for smart groups, which are identified by their own query\n * that needs to be passed through.\n *\n * Note: if you want to specify the order, you need to wrap your filters within `__filter` property and then add `__orderby` with the array of field paths and sort directions (1 for ascending, -1 for descending), for example:\n * - `{ __filter: { ... }, __orderby: [{ 'creationTime': -1 }, { 'name': 1 }] }`\n *\n * @returns {string} Returns a query string ready to be sent in request params to backend.\n *\n * **Example**\n * ```typescript\n * const query = {\n * __filter: {\n * 'name': 'My Device*',\n * 'c8y_Availability.status': {\n * __in: ['AVAILABLE', 'UNAVAILABLE']\n * },\n * 'creationTime': {\n * __lt: '2015-11-30T13:28:123Z'\n * },\n * 'c8y_ActiveAlarmsStatus.critical': {\n * __gt: 0\n * },\n * __or: [\n * {__not: {__has: 'c8y_ActiveAlarmsStatus.major'}},\n * {\n * __or: [\n * {__bygroupid: 10300},\n * {__bygroupid: 10400}\n * ]\n * }\n * ]\n * },\n * __orderby: [\n * {'name': 1},\n * {'creationTime': -1},\n * {'c8y_ActiveAlarmsStatus.critical': -1}\n * ]\n * };\n *\n * const params = {\n * query: queriesUtil.buildQuery(query)\n * };\n * ```\n */\n buildQuery(query): string {\n const q = [];\n const filter = this.buildQueryFilter(query.__filter || query);\n const orderBy = this.buildQueryOrderby(query.__orderby);\n if (filter) {\n q.push(`$filter=(${filter})`);\n }\n if (orderBy) {\n q.push(`$orderby=${orderBy}`);\n }\n return q.join(' ');\n }\n\n buildQueryFilter(queryFilter, _queryKey?, _glueType?): string {\n const queryKey = _queryKey || null;\n const glueType = _glueType || 'and';\n\n const q = [];\n\n if (Array.isArray(queryFilter)) {\n queryFilter.forEach(qFilter => {\n const _q = this.buildQueryFilter(qFilter, null, glueType);\n if (_q) {\n q.push(_q);\n }\n });\n } else {\n let _q;\n Object.keys(queryFilter).forEach(k => {\n if (this.operatorFns[k] !== undefined) {\n _q = this.operatorFns[k](queryFilter[k], queryKey);\n if (_q) {\n q.push(_q);\n }\n } else {\n _q = this.operatorFns.__eq(queryFilter[k], k);\n if (_q) {\n q.push(_q);\n }\n }\n });\n }\n\n return this.glue(q, glueType);\n }\n\n buildQueryOrderby(queryOrderbys): string {\n const o = [];\n if (queryOrderbys) {\n queryOrderbys.forEach(q => {\n Object.keys(q).forEach(k => {\n if (q[k] !== 0) {\n o.push(`${k} ${q[k] > 0 ? 'asc' : 'desc'}`);\n }\n });\n });\n }\n return o.join(',');\n }\n\n addAndFilter(query, filter) {\n return this.addFilter(query, filter, 'and');\n }\n\n addOrFilter(query, filter) {\n return this.addFilter(query, filter, 'or');\n }\n\n addFilter(query, filter, operator: 'and' | 'or') {\n const oldFilter = query.__orderby ? query.__filter || {} : query.__filter || query;\n const newFilter = { [`__${operator}`]: this.skipEmptyObjects([oldFilter, filter]) };\n if (!query.__filter && !query.__orderby) {\n return newFilter;\n }\n query.__filter = newFilter;\n return query;\n }\n\n prependOrderbys(query, orderbys) {\n return this.addOrderbys(query, orderbys, 'prepend');\n }\n\n appendOrderbys(query, orderbys) {\n return this.addOrderbys(query, orderbys, 'append');\n }\n\n addOrderbys(query, orderbys, how: 'prepend' | 'append') {\n const oldFilter = query.__orderby ? query.__filter || {} : query.__filter || query;\n const oldOrderbys = query.__orderby || [];\n const newOrderbys =\n how === 'prepend' ? [...orderbys, ...oldOrderbys] : [...oldOrderbys, ...orderbys];\n const newQuery: any = {\n __orderby: this.skipEmptyObjects(newOrderbys)\n };\n if (!this.isEmptyObject(oldFilter)) {\n newQuery.__filter = oldFilter;\n }\n return newQuery;\n }\n\n extractAndMergeOrderBys(queries: string[]): string {\n if (queries?.length > 0) {\n const orderByQuery = queries\n .map(query => query.match(/\\$orderby=(.*)$/)?.[1])\n .filter(orderBy => !!orderBy)\n .join(',');\n return orderByQuery ? `$orderby=${orderByQuery}` : '';\n }\n }\n\n protected glue(stmts: any[], type: string) {\n return stmts.length > 1 ? `(${stmts.join(`) ${type} (`)})` : stmts[0];\n }\n\n protected quoteString(s: any) {\n return typeof s === 'string' ? `'${this.escapeSingleQuote(s)}'` : s;\n }\n\n protected skipEmptyObjects(objs: any[]) {\n return objs.filter(obj => !this.isEmptyObject(obj));\n }\n\n protected isEmptyObject(obj: object) {\n return Object.keys(obj).length === 0;\n }\n\n // OData does not support single quotes in the query. We need to replace all single quotes with double quotes.\n // http://docs.oasis-open.org/odata/odata/v4.01/cs01/part2-url-conventions/odata-v4.01-cs01-part2-url-conventions.html#sec_URLComponents\n private escapeSingleQuote(s: string): string {\n if (typeof s !== 'string') {\n return s;\n }\n return s.replace(/\\'/g, \"''\");\n }\n}\n","export enum MetaChannel {\n HANDSHAKE = '/meta/handshake',\n CONNECT = '/meta/connect',\n SUBSCRIBE = '/meta/subscribe',\n UNSUBSCRIBE = '/meta/unsubscribe'\n}\n","/*\n * Copyright (c) 2008-2020 the original author or authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/* CometD Version 4.0.8 */\n\n(function(root, factory) {\n if (typeof exports === 'object') {\n // CommonJS.\n module.exports = factory();\n } else if (typeof define === 'function' && define.amd) {\n // AMD.\n define([], factory);\n } else {\n // Globals.\n root.org = root.org || {};\n root.org.cometd = factory();\n }\n}(this, function() {\n /**\n * Browsers may throttle the Window scheduler,\n * so we may replace it with a Worker scheduler.\n */\n var Scheduler = function() {\n var _ids = 0;\n var _tasks = {};\n this.register = function(funktion) {\n var id = ++_ids;\n _tasks[id] = funktion;\n return id;\n };\n this.unregister = function(id) {\n var funktion = _tasks[id];\n delete _tasks[id];\n return funktion;\n };\n this.setTimeout = function(funktion, delay) {\n return window.setTimeout(funktion, delay);\n };\n this.clearTimeout = function(id) {\n window.clearTimeout(id);\n };\n };\n\n /**\n * The scheduler code that will run in the Worker.\n * Workers have a built-in `self` variable similar to `window`.\n */\n function WorkerScheduler() {\n var _tasks = {};\n self.onmessage = function(e) {\n var cmd = e.data;\n var id = _tasks[cmd.id];\n switch (cmd.type) {\n case 'setTimeout':\n _tasks[cmd.id] = self.setTimeout(function() {\n delete _tasks[cmd.id];\n self.postMessage({\n id: cmd.id\n });\n }, cmd.delay);\n break;\n case 'clearTimeout':\n delete _tasks[cmd.id];\n if (id) {\n self.clearTimeout(id);\n }\n break;\n default:\n throw 'Unknown command ' + cmd.type;\n }\n };\n }\n\n\n /**\n * Utility functions.\n */\n var Utils = {\n isString: function(value) {\n if (value === undefined || value === null) {\n return false;\n }\n return typeof value === 'string' || value instanceof String;\n },\n isArray: function(value) {\n if (value === undefined || value === null) {\n return false;\n }\n return value instanceof Array;\n },\n /**\n * Returns whether the given element is contained into the given array.\n * @param element the element to check presence for\n * @param array the array to check for the element presence\n * @return the index of the element, if present, or a negative index if the element is not present\n */\n inArray: function(element, array) {\n for (var i = 0; i < array.length; ++i) {\n if (element === array[i]) {\n return i;\n }\n }\n return -1;\n }\n };\n\n\n /**\n * A registry for transports used by the CometD object.\n */\n var TransportRegistry = function() {\n var _types = [];\n var _transports = {};\n\n this.getTransportTypes = function() {\n return _types.slice(0);\n };\n\n this.findTransportTypes = function(version, crossDomain, url) {\n var result = [];\n for (var i = 0; i < _types.length; ++i) {\n var type = _types[i];\n if (_transports[type].accept(version, crossDomain, url) === true) {\n result.push(type);\n }\n }\n return result;\n };\n\n this.negotiateTransport = function(types, version, crossDomain, url) {\n for (var i = 0; i < _types.length; ++i) {\n var type = _types[i];\n for (var j = 0; j < types.length; ++j) {\n if (type === types[j]) {\n var transport = _transports[type];\n if (transport.accept(version, crossDomain, url) === true) {\n return transport;\n }\n }\n }\n }\n return null;\n };\n\n this.add = function(type, transport, index) {\n var existing = false;\n for (var i = 0; i < _types.length; ++i) {\n if (_types[i] === type) {\n existing = true;\n break;\n }\n }\n\n if (!existing) {\n if (typeof index !== 'number') {\n _types.push(type);\n } else {\n _types.splice(index, 0, type);\n }\n _transports[type] = transport;\n }\n\n return !existing;\n };\n\n this.find = function(type) {\n for (var i = 0; i < _types.length; ++i) {\n if (_types[i] === type) {\n return _transports[type];\n }\n }\n return null;\n };\n\n this.remove = function(type) {\n for (var i = 0; i < _types.length; ++i) {\n if (_types[i] === type) {\n _types.splice(i, 1);\n var transport = _transports[type];\n delete _transports[type];\n return transport;\n }\n }\n return null;\n };\n\n this.clear = function() {\n _types = [];\n _transports = {};\n };\n\n this.reset = function(init) {\n for (var i = 0; i < _types.length; ++i) {\n _transports[_types[i]].reset(init);\n }\n };\n };\n\n\n /**\n * Base object with the common functionality for transports.\n */\n var Transport = function() {\n var _type;\n var _cometd;\n var _url;\n\n /**\n * Function invoked just after a transport has been successfully registered.\n * @param type the type of transport (for example 'long-polling')\n * @param cometd the cometd object this transport has been registered to\n * @see #unregistered()\n */\n this.registered = function(type, cometd) {\n _type = type;\n _cometd = cometd;\n };\n\n /**\n * Function invoked just after a transport has been successfully unregistered.\n * @see #registered(type, cometd)\n */\n this.unregistered = function() {\n _type = null;\n _cometd = null;\n };\n\n this._debug = function() {\n _cometd._debug.apply(_cometd, arguments);\n };\n\n this._mixin = function() {\n return _cometd._mixin.apply(_cometd, arguments);\n };\n\n this.getConfiguration = function() {\n return _cometd.getConfiguration();\n };\n\n this.getAdvice = function() {\n return _cometd.getAdvice();\n };\n\n this.setTimeout = function(funktion, delay) {\n return _cometd.setTimeout(funktion, delay);\n };\n\n this.clearTimeout = function(id) {\n _cometd.clearTimeout(id);\n };\n\n /**\n * Converts the given response into an array of bayeux messages\n * @param response the response to convert\n * @return an array of bayeux messages obtained by converting the response\n */\n this.convertToMessages = function(response) {\n if (Utils.isString(response)) {\n try {\n return JSON.parse(response);\n } catch (x) {\n this._debug('Could not convert to JSON the following string', '\"' + response + '\"');\n throw x;\n }\n }\n if (Utils.isArray(response)) {\n return response;\n }\n if (response === undefined || response === null) {\n return [];\n }\n if (response instanceof Object) {\n return [response];\n }\n throw 'Conversion Error ' + response + ', typeof ' + (typeof response);\n };\n\n /**\n * Returns whether this transport can work for the given version and cross domain communication case.\n * @param version a string indicating the transport version\n * @param crossDomain a boolean indicating whether the communication is cross domain\n * @param url the URL to connect to\n * @return true if this transport can work for the given version and cross domain communication case,\n * false otherwise\n */\n this.accept = function(version, crossDomain, url) {\n throw 'Abstract';\n };\n\n /**\n * Returns the type of this transport.\n * @see #registered(type, cometd)\n */\n this.getType = function() {\n return _type;\n };\n\n this.getURL = function() {\n return _url;\n };\n\n this.setURL = function(url) {\n _url = url;\n };\n\n this.send = function(envelope, metaConnect) {\n throw 'Abstract';\n };\n\n this.reset = function(init) {\n this._debug('Transport', _type, 'reset', init ? 'initial' : 'retry');\n };\n\n this.abort = function() {\n this._debug('Transport', _type, 'aborted');\n };\n\n this.toString = function() {\n return this.getType();\n };\n };\n\n Transport.derive = function(baseObject) {\n function F() {\n }\n\n F.prototype = baseObject;\n return new F();\n };\n\n\n /**\n * Base object with the common functionality for transports based on requests.\n * The key responsibility is to allow at most 2 outstanding requests to the server,\n * to avoid that requests are sent behind a long poll.\n * To achieve this, we have one reserved request for the long poll, and all other\n * requests are serialized one after the other.\n */\n var RequestTransport = function() {\n var _super = new Transport();\n var _self = Transport.derive(_super);\n var _requestIds = 0;\n var _metaConnectRequest = null;\n var _requests = [];\n var _envelopes = [];\n\n function _coalesceEnvelopes(envelope) {\n while (_envelopes.length > 0) {\n var envelopeAndRequest = _envelopes[0];\n var newEnvelope = envelopeAndRequest[0];\n var newRequest = envelopeAndRequest[1];\n if (newEnvelope.url === envelope.url &&\n newEnvelope.sync === envelope.sync) {\n _envelopes.shift();\n envelope.messages = envelope.messages.concat(newEnvelope.messages);\n this._debug('Coalesced', newEnvelope.messages.length, 'messages from request', newRequest.id);\n continue;\n }\n break;\n }\n }\n\n function _transportSend(envelope, request) {\n this.transportSend(envelope, request);\n request.expired = false;\n\n if (!envelope.sync) {\n var maxDelay = this.getConfiguration().maxNetworkDelay;\n var delay = maxDelay;\n if (request.metaConnect === true) {\n delay += this.getAdvice().timeout;\n }\n\n this._debug('Transport', this.getType(), 'waiting at most', delay, 'ms for the response, maxNetworkDelay', maxDelay);\n\n var self = this;\n request.timeout = this.setTimeout(function() {\n request.expired = true;\n var errorMessage = 'Request ' + request.id + ' of transport ' + self.getType() + ' exceeded ' + delay + ' ms max network delay';\n var failure = {\n reason: errorMessage\n };\n var xhr = request.xhr;\n failure.httpCode = self.xhrStatus(xhr);\n self.abortXHR(xhr);\n self._debug(errorMessage);\n self.complete(request, false, request.metaConnect);\n envelope.onFailure(xhr, envelope.messages, failure);\n }, delay);\n }\n }\n\n function _queueSend(envelope) {\n var requestId = ++_requestIds;\n var request = {\n id: requestId,\n metaConnect: false,\n envelope: envelope\n };\n\n // Consider the /meta/connect requests which should always be present.\n if (_requests.length < this.getConfiguration().maxConnections - 1) {\n _requests.push(request);\n _transportSend.call(this, envelope, request);\n } else {\n this._debug('Transport', this.getType(), 'queueing request', requestId, 'envelope', envelope);\n _envelopes.push([envelope, request]);\n }\n }\n\n function _metaConnectComplete(request) {\n var requestId = request.id;\n this._debug('Transport', this.getType(), '/meta/connect complete, request', requestId);\n if (_metaConnectRequest !== null && _metaConnectRequest.id !== requestId) {\n throw '/meta/connect request mismatch, completing request ' + requestId;\n }\n _metaConnectRequest = null;\n }\n\n function _complete(request, success) {\n var index = Utils.inArray(request, _requests);\n // The index can be negative if the request has been aborted\n if (index >= 0) {\n _requests.splice(index, 1);\n }\n\n if (_envelopes.length > 0) {\n var envelopeAndRequest = _envelopes.shift();\n var nextEnvelope = envelopeAndRequest[0];\n var nextRequest = envelopeAndRequest[1];\n this._debug('Transport dequeued request', nextRequest.id);\n if (success) {\n if (this.getConfiguration().autoBatch) {\n _coalesceEnvelopes.call(this, nextEnvelope);\n }\n _queueSend.call(this, nextEnvelope);\n this._debug('Transport completed request', request.id, nextEnvelope);\n } else {\n // Keep the semantic of calling response callbacks asynchronously after the request\n var self = this;\n this.setTimeout(function() {\n self.complete(nextRequest, false, nextRequest.metaConnect);\n var failure = {\n reason: 'Previous request failed'\n };\n var xhr = nextRequest.xhr;\n failure.httpCode = self.xhrStatus(xhr);\n nextEnvelope.onFailure(xhr, nextEnvelope.messages, failure);\n }, 0);\n }\n }\n }\n\n _self.complete = function(request, success, metaConnect) {\n if (metaConnect) {\n _metaConnectComplete.call(this, request);\n } else {\n _complete.call(this, request, success);\n }\n };\n\n /**\n * Performs the actual send depending on the transport type details.\n * @param envelope the envelope to send\n * @param request the request information\n */\n _self.transportSend = function(envelope, request) {\n throw 'Abstract';\n };\n\n _self.transportSuccess = function(envelope, request, responses) {\n if (!request.expired) {\n this.clearTimeout(request.timeout);\n this.complete(request, true, request.metaConnect);\n if (responses && responses.length > 0) {\n envelope.onSuccess(responses);\n } else {\n envelope.onFailure(request.xhr, envelope.messages, {\n httpCode: 204\n });\n }\n }\n };\n\n _self.transportFailure = function(envelope, request, failure) {\n if (!request.expired) {\n this.clearTimeout(request.timeout);\n this.complete(request, false, request.metaConnect);\n envelope.onFailure(request.xhr, envelope.messages, failure);\n }\n };\n\n function _metaConnectSend(envelope) {\n if (_metaConnectRequest !== null) {\n throw 'Concurrent /meta/connect requests not allowed, request id=' + _metaConnectRequest.id + ' not yet completed';\n }\n\n var requestId = ++_requestIds;\n this._debug('Transport', this.getType(), '/meta/connect send, request', requestId, 'envelope', envelope);\n var request = {\n id: requestId,\n metaConnect: true,\n envelope: envelope\n };\n _transportSend.call(this, envelope, request);\n _metaConnectRequest = request;\n }\n\n _self.send = function(envelope, metaConnect) {\n if (metaConnect) {\n _metaConnectSend.call(this, envelope);\n } else {\n _queueSend.call(this, envelope);\n }\n };\n\n _self.abort = function() {\n _super.abort();\n for (var i = 0; i < _requests.length; ++i) {\n var request = _requests[i];\n if (request) {\n this._debug('Aborting request', request);\n if (!this.abortXHR(request.xhr)) {\n this.transportFailure(request.envelope, request, {reason: 'abort'});\n }\n }\n }\n var metaConnectRequest = _metaConnectRequest;\n if (metaConnectRequest) {\n this._debug('Aborting /meta/connect request', metaConnectRequest);\n if (!this.abortXHR(metaConnectRequest.xhr)) {\n this.transportFailure(metaConnectRequest.envelope, metaConnectRequest, {reason: 'abort'});\n }\n }\n this.reset(true);\n };\n\n _self.reset = function(init) {\n _super.reset(init);\n _metaConnectRequest = null;\n _requests = [];\n _envelopes = [];\n };\n\n _self.abortXHR = function(xhr) {\n if (xhr) {\n try {\n var state = xhr.readyState;\n xhr.abort();\n return state !== window.XMLHttpRequest.UNSENT;\n } catch (x) {\n this._debug(x);\n }\n }\n return false;\n };\n\n _self.xhrStatus = function(xhr) {\n if (xhr) {\n try {\n return xhr.status;\n } catch (x) {\n this._debug(x);\n }\n }\n return -1;\n };\n\n return _self;\n };\n\n\n var LongPollingTransport = function() {\n var _super = new RequestTransport();\n var _self = Transport.derive(_super);\n // By default, support cross domain\n var _supportsCrossDomain = true;\n\n _self.accept = function(version, crossDomain, url) {\n return _supportsCrossDomain || !crossDomain;\n };\n\n _self.newXMLHttpRequest = function() {\n return new window.XMLHttpRequest();\n };\n\n function _copyContext(xhr) {\n try {\n // Copy external context, to be used in other environments.\n xhr.context = _self.context;\n } catch (e) {\n // May happen if XHR is wrapped by Object.seal(),\n // Object.freeze(), or Object.preventExtensions().\n this._debug('Could not copy transport context into XHR', e);\n }\n }\n\n _self.xhrSend = function(packet) {\n var xhr = _self.newXMLHttpRequest();\n _copyContext(xhr);\n xhr.withCredentials = true;\n xhr.open('POST', packet.url, packet.sync !== true);\n var headers = packet.headers;\n if (headers) {\n for (var headerName in headers) {\n if (headers.hasOwnProperty(headerName)) {\n xhr.setRequestHeader(headerName, headers[headerName]);\n }\n }\n }\n xhr.setRequestHeader('Content-Type', 'application/json;charset=UTF-8');\n xhr.onload = function() {\n if (xhr.status === 200) {\n packet.onSuccess(xhr.responseText);\n } else {\n packet.onError(xhr.statusText);\n }\n };\n xhr.onabort = xhr.onerror = function() {\n packet.onError(xhr.statusText);\n };\n xhr.send(packet.body);\n return xhr;\n };\n\n _self.transportSend = function(envelope, request) {\n this._debug('Transport', this.getType(), 'sending request', request.id, 'envelope', envelope);\n\n var self = this;\n try {\n var sameStack = true;\n request.xhr = this.xhrSend({\n transport: this,\n url: envelope.url,\n sync: envelope.sync,\n headers: this.getConfiguration().requestHeaders,\n body: JSON.stringify(envelope.messages),\n onSuccess: function(response) {\n self._debug('Transport', self.getType(), 'received response', response);\n var success = false;\n try {\n var received = self.convertToMessages(response);\n if (received.length === 0) {\n _supportsCrossDomain = false;\n self.transportFailure(envelope, request, {\n httpCode: 204\n });\n } else {\n success = true;\n self.transportSuccess(envelope, request, received);\n }\n } catch (x) {\n self._debug(x);\n if (!success) {\n _supportsCrossDomain = false;\n var failure = {\n exception: x\n };\n failure.httpCode = self.xhrStatus(request.xhr);\n self.transportFailure(envelope, request, failure);\n }\n }\n },\n onError: function(reason, exception) {\n self._debug('Transport', self.getType(), 'received error', reason, exception);\n _supportsCrossDomain = false;\n var failure = {\n reason: reason,\n exception: exception\n };\n failure.httpCode = self.xhrStatus(request.xhr);\n if (sameStack) {\n // Keep the semantic of calling response callbacks asynchronously after the request\n self.setTimeout(function() {\n self.transportFailure(envelope, request, failure);\n }, 0);\n } else {\n self.transportFailure(envelope, request, failure);\n }\n }\n });\n sameStack = false;\n } catch (x) {\n _supportsCrossDomain = false;\n // Keep the semantic of calling response callbacks asynchronously after the request\n this.setTimeout(function() {\n self.transportFailure(envelope, request, {\n exception: x\n });\n }, 0);\n }\n };\n\n _self.reset = function(init) {\n _super.reset(init);\n _supportsCrossDomain = true;\n };\n\n return _self;\n };\n\n\n var CallbackPollingTransport = function() {\n var _super = new RequestTransport();\n var _self = Transport.derive(_super);\n var jsonp = 0;\n\n _self.accept = function(version, crossDomain, url) {\n return true;\n };\n\n _self.jsonpSend = function(packet) {\n var head = document.getElementsByTagName('head')[0];\n var script = document.createElement('script');\n\n var callbackName = '_cometd_jsonp_' + jsonp++;\n window[callbackName] = function(responseText) {\n head.removeChild(script);\n delete window[callbackName];\n packet.onSuccess(responseText);\n };\n\n var url = packet.url;\n url += url.indexOf('?') < 0 ? '?' : '&';\n url += 'jsonp=' + callbackName;\n url += '&message=' + encodeURIComponent(packet.body);\n script.src = url;\n script.async = packet.sync !== true;\n script.type = 'application/javascript';\n script.onerror = function(e) {\n packet.onError('jsonp ' + e.type);\n };\n head.appendChild(script);\n };\n\n function _failTransportFn(envelope, request, x) {\n var self = this;\n return function() {\n self.transportFailure(envelope, request, 'error', x);\n };\n }\n\n _self.transportSend = function(envelope, request) {\n var self = this;\n\n // Microsoft Internet Explorer has a 2083 URL max length\n // We must ensure that we stay within that length\n var start = 0;\n var length = envelope.messages.length;\n var lengths = [];\n while (length > 0) {\n // Encode the messages because all brackets, quotes, commas, colons, etc\n // present in the JSON will be URL encoded, taking many more characters\n var json = JSON.stringify(envelope.messages.slice(start, start + length));\n var urlLength = envelope.url.length + encodeURI(json).length;\n\n var maxLength = this.getConfiguration().maxURILength;\n if (urlLength > maxLength) {\n if (length === 1) {\n var x = 'Bayeux message too big (' + urlLength + ' bytes, max is ' + maxLength + ') ' +\n 'for transport ' + this.getType();\n // Keep the semantic of calling response callbacks asynchronously after the request\n this.setTimeout(_failTransportFn.call(this, envelope, request, x), 0);\n return;\n }\n\n --length;\n continue;\n }\n\n lengths.push(length);\n start += length;\n length = envelope.messages.length - start;\n }\n\n // Here we are sure that the messages can be sent within the URL limit\n\n var envelopeToSend = envelope;\n if (lengths.length > 1) {\n var begin = 0;\n var end = lengths[0];\n this._debug('Transport', this.getType(), 'split', envelope.messages.length, 'messages into', lengths.join(' + '));\n envelopeToSend = this._mixin(false, {}, envelope);\n envelopeToSend.messages = envelope.messages.slice(begin, end);\n envelopeToSend.onSuccess = envelope.onSuccess;\n envelopeToSend.onFailure = envelope.onFailure;\n\n for (var i = 1; i < lengths.length; ++i) {\n var nextEnvelope = this._mixin(false, {}, envelope);\n begin = end;\n end += lengths[i];\n nextEnvelope.messages = envelope.messages.slice(begin, end);\n nextEnvelope.onSuccess = envelope.onSuccess;\n nextEnvelope.onFailure = envelope.onFailure;\n this.send(nextEnvelope, request.metaConnect);\n }\n }\n\n this._debug('Transport', this.getType(), 'sending request', request.id, 'envelope', envelopeToSend);\n\n try {\n var sameStack = true;\n this.jsonpSend({\n transport: this,\n url: envelopeToSend.url,\n sync: envelopeToSend.sync,\n headers: this.getConfiguration().requestHeaders,\n body: JSON.stringify(envelopeToSend.messages),\n onSuccess: function(responses) {\n var success = false;\n try {\n var received = self.convertToMessages(responses);\n if (received.length === 0) {\n self.transportFailure(envelopeToSend, request, {\n httpCode: 204\n });\n } else {\n success = true;\n self.transportSuccess(envelopeToSend, request, received);\n }\n } catch (x) {\n self._debug(x);\n if (!success) {\n self.transportFailure(envelopeToSend, request, {\n exception: x\n });\n }\n }\n },\n onError: function(reason, exception) {\n var failure = {\n reason: reason,\n exception: exception\n };\n if (sameStack) {\n // Keep the semantic of calling response callbacks asynchronously after the request\n self.setTimeout(function() {\n self.transportFailure(envelopeToSend, request, failure);\n }, 0);\n } else {\n self.transportFailure(envelopeToSend, request, failure);\n }\n }\n });\n sameStack = false;\n } catch (xx) {\n // Keep the semantic of calling response callbacks asynchronously after the request\n this.setTimeout(function() {\n self.transportFailure(envelopeToSend, request, {\n exception: xx\n });\n }, 0);\n }\n };\n\n return _self;\n };\n\n\n var WebSocketTransport = function() {\n var _super = new Transport();\n var _self = Transport.derive(_super);\n var _cometd;\n // By default WebSocket is supported\n var _webSocketSupported = true;\n // Whether we were able to establish a WebSocket connection\n var _webSocketConnected = false;\n var _stickyReconnect = true;\n // The context contains the envelopes that have been sent\n // and the timeouts for the messages that have been sent.\n var _context = null;\n var _connecting = null;\n var _connected = false;\n var _successCallback = null;\n\n _self.reset = function(init) {\n _super.reset(init);\n _webSocketSupported = true;\n if (init) {\n _webSocketConnected = false;\n }\n _stickyReconnect = true;\n _context = null;\n _connecting = null;\n _connected = false;\n };\n\n function _forceClose(context, event) {\n if (context) {\n this.webSocketClose(context, event.code, event.reason);\n // Force immediate failure of pending messages to trigger reconnect.\n // This is needed because the server may not reply to our close()\n // and therefore the onclose function is never called.\n this.onClose(context, event);\n }\n }\n\n function _sameContext(context) {\n return context === _connecting || context === _context;\n }\n\n function _storeEnvelope(context, envelope, metaConnect) {\n var messageIds = [];\n for (var i = 0; i < envelope.messages.length; ++i) {\n var message = envelope.messages[i];\n if (message.id) {\n messageIds.push(message.id);\n }\n }\n context.envelopes[messageIds.join(',')] = [envelope, metaConnect];\n this._debug('Transport', this.getType(), 'stored envelope, envelopes', context.envelopes);\n }\n\n function _websocketConnect(context) {\n // We may have multiple attempts to open a WebSocket\n // connection, for example a /meta/connect request that\n // may take time, along with a user-triggered publish.\n // Early return if we are already connecting.\n if (_connecting) {\n return;\n }\n\n // Mangle the URL, changing the scheme from 'http' to 'ws'.\n var url = _cometd.getURL().replace(/^http/, 'ws');\n this._debug('Transport', this.getType(), 'connecting to URL', url);\n\n try {\n var protocol = _cometd.getConfiguration().protocol;\n context.webSocket = protocol ? new window.WebSocket(url, protocol) : new window.WebSocket(url);\n _connecting = context;\n } catch (x) {\n _webSocketSupported = false;\n this._debug('Exception while creating WebSocket object', x);\n throw x;\n }\n\n // By default use sticky reconnects.\n _stickyReconnect = _cometd.getConfiguration().stickyReconnect !== false;\n\n var self = this;\n var connectTimeout = _cometd.getConfiguration().connectTimeout;\n if (connectTimeout > 0) {\n context.connectTimer = this.setTimeout(function() {\n _cometd._debug('Transport', self.getType(), 'timed out while connecting to URL', url, ':', connectTimeout, 'ms');\n // The connection was not opened, close anyway.\n _forceClose.call(self, context, {code: 1000, reason: 'Connect Timeout'});\n }, connectTimeout);\n }\n\n var onopen = function() {\n _cometd._debug('WebSocket onopen', context);\n if (context.connectTimer) {\n self.clearTimeout(context.connectTimer);\n }\n\n if (_sameContext(context)) {\n _connecting = null;\n _context = context;\n _webSocketConnected = true;\n self.onOpen(context);\n } else {\n // We have a valid connection already, close this one.\n _cometd._warn('Closing extra WebSocket connection', this, 'active connection', _context);\n _forceClose.call(self, context, {code: 1000, reason: 'Extra Connection'});\n }\n };\n\n // This callback is invoked when the server sends the close frame.\n // The close frame for a connection may arrive *after* another\n // connection has been opened, so we must make sure that actions\n // are performed only if it's the same connection.\n var onclose = function(event) {\n event = event || {code: 1000};\n _cometd._debug('WebSocket onclose', context, event, 'connecting', _connecting, 'current', _context);\n\n if (context.connectTimer) {\n self.clearTimeout(context.connectTimer);\n }\n\n self.onClose(context, event);\n };\n\n var onmessage = function(wsMessage) {\n _cometd._debug('WebSocket onmessage', wsMessage, context);\n self.onMessage(context, wsMessage);\n };\n\n context.webSocket.onopen = onopen;\n context.webSocket.onclose = onclose;\n context.webSocket.onerror = function() {\n // Clients should call onclose(), but if they do not we do it here for safety.\n onclose({code: 1000, reason: 'Error'});\n };\n context.webSocket.onmessage = onmessage;\n\n this._debug('Transport', this.getType(), 'configured callbacks on', context);\n }\n\n function _webSocketSend(context, envelope, metaConnect) {\n var json = JSON.stringify(envelope.messages);\n context.webSocket.send(json);\n this._debug('Transport', this.getType(), 'sent', envelope, '/meta/connect =', metaConnect);\n\n // Manage the timeout waiting for the response.\n var maxDelay = this.getConfiguration().maxNetworkDelay;\n var delay = maxDelay;\n if (metaConnect) {\n delay += this.getAdvice().timeout;\n _connected = true;\n }\n\n var self = this;\n var messageIds = [];\n for (var i = 0; i < envelope.messages.length; ++i) {\n (function() {\n var message = envelope.messages[i];\n if (message.id) {\n messageIds.push(message.id);\n context.timeouts[message.id] = self.setTimeout(function() {\n _cometd._debug('Transport', self.getType(), 'timing out message', message.id, 'after', delay, 'on', context);\n _forceClose.call(self, context, {code: 1000, reason: 'Message Timeout'});\n }, delay);\n }\n })();\n }\n\n this._debug('Transport', this.getType(), 'waiting at most', delay, 'ms for messages', messageIds, 'maxNetworkDelay', maxDelay, ', timeouts:', context.timeouts);\n }\n\n _self._notifySuccess = function(fn, messages) {\n fn.call(this, messages);\n };\n\n _self._notifyFailure = function(fn, context, messages, failure) {\n fn.call(this, context, messages, failure);\n };\n\n function _send(context, envelope, metaConnect) {\n try {\n if (context === null) {\n context = _connecting || {\n envelopes: {},\n timeouts: {}\n };\n _storeEnvelope.call(this, context, envelope, metaConnect);\n _websocketConnect.call(this, context);\n } else {\n _storeEnvelope.call(this, context, envelope, metaConnect);\n _webSocketSend.call(this, context, envelope, metaConnect);\n }\n } catch (x) {\n // Keep the semantic of calling response callbacks asynchronously after the request.\n var self = this;\n this.setTimeout(function() {\n _forceClose.call(self, context, {\n code: 1000,\n reason: 'Exception',\n exception: x\n });\n }, 0);\n }\n }\n\n _self.onOpen = function(context) {\n var envelopes = context.envelopes;\n this._debug('Transport', this.getType(), 'opened', context, 'pending messages', envelopes);\n for (var key in envelopes) {\n if (envelopes.hasOwnProperty(key)) {\n var element = envelopes[key];\n var envelope = element[0];\n var metaConnect = element[1];\n // Store the success callback, which is independent from the envelope,\n // so that it can be used to notify arrival of messages.\n _successCallback = envelope.onSuccess;\n _webSocketSend.call(this, context, envelope, metaConnect);\n }\n }\n };\n\n _self.onMessage = function(context, wsMessage) {\n this._debug('Transport', this.getType(), 'received websocket message', wsMessage, context);\n\n var close = false;\n var messages = this.convertToMessages(wsMessage.data);\n var messageIds = [];\n for (var i = 0; i < messages.length; ++i) {\n var message = messages[i];\n\n // Detect if the message is a response to a request we made.\n // If it's a meta message, for sure it's a response; otherwise it's\n // a publish message and publish responses don't have the data field.\n if (/^\\/meta\\//.test(message.channel) || message.data === undefined) {\n if (message.id) {\n messageIds.push(message.id);\n\n var timeout = context.timeouts[message.id];\n if (timeout) {\n this.clearTimeout(timeout);\n delete context.timeouts[message.id];\n this._debug('Transport', this.getType(), 'removed timeout for message', message.id, ', timeouts', context.timeouts);\n }\n }\n }\n\n if ('/meta/connect' === message.channel) {\n _connected = false;\n }\n if ('/meta/disconnect' === message.channel && !_connected) {\n close = true;\n }\n }\n\n // Remove the envelope corresponding to the messages.\n var removed = false;\n var envelopes = context.envelopes;\n for (var j = 0; j < messageIds.length; ++j) {\n var id = messageIds[j];\n for (var key in envelopes) {\n if (envelopes.hasOwnProperty(key)) {\n var ids = key.split(',');\n var index = Utils.inArray(id, ids);\n if (index >= 0) {\n removed = true;\n ids.splice(index, 1);\n var envelope = envelopes[key][0];\n var metaConnect = envelopes[key][1];\n delete envelopes[key];\n if (ids.length > 0) {\n envelopes[ids.join(',')] = [envelope, metaConnect];\n }\n break;\n }\n }\n }\n }\n if (removed) {\n this._debug('Transport', this.getType(), 'removed envelope, envelopes', envelopes);\n }\n\n this._notifySuccess(_successCallback, messages);\n\n if (close) {\n this.webSocketClose(context, 1000, 'Disconnect');\n }\n };\n\n _self.onClose = function(context, event) {\n this._debug('Transport', this.getType(), 'closed', context, event);\n\n if (_sameContext(context)) {\n // Remember if we were able to connect.\n // This close event could be due to server shutdown,\n // and if it restarts we want to try websocket again.\n _webSocketSupported = _stickyReconnect && _webSocketConnected;\n _connecting = null;\n _context = null;\n }\n\n var timeouts = context.timeouts;\n context.timeouts = {};\n for (var id in timeouts) {\n if (timeouts.hasOwnProperty(id)) {\n this.clearTimeout(timeouts[id]);\n }\n }\n\n var envelopes = context.envelopes;\n context.envelopes = {};\n for (var key in envelopes) {\n if (envelopes.hasOwnProperty(key)) {\n var envelope = envelopes[key][0];\n var metaConnect = envelopes[key][1];\n if (metaConnect) {\n _connected = false;\n }\n var failure = {\n websocketCode: event.code,\n reason: event.reason\n };\n if (event.exception) {\n failure.exception = event.exception;\n }\n this._notifyFailure(envelope.onFailure, context, envelope.messages, failure);\n }\n }\n };\n\n _self.registered = function(type, cometd) {\n _super.registered(type, cometd);\n _cometd = cometd;\n };\n\n _self.accept = function(version, crossDomain, url) {\n this._debug('Transport', this.getType(), 'accept, supported:', _webSocketSupported);\n // Using !! to return a boolean (and not the WebSocket object).\n return _webSocketSupported && !!window.WebSocket && _cometd.websocketEnabled !== false;\n };\n\n _self.send = function(envelope, metaConnect) {\n this._debug('Transport', this.getType(), 'sending', envelope, '/meta/connect =', metaConnect);\n _send.call(this, _context, envelope, metaConnect);\n };\n\n _self.webSocketClose = function(context, code, reason) {\n try {\n if (context.webSocket) {\n context.webSocket.close(code, reason);\n }\n } catch (x) {\n this._debug(x);\n }\n };\n\n _self.abort = function() {\n _super.abort();\n _forceClose.call(this, _context, {code: 1000, reason: 'Abort'});\n this.reset(true);\n };\n\n return _self;\n };\n\n\n /**\n * The constructor for a CometD object, identified by an optional name.\n * The default name is the string 'default'.\n * @param name the optional name of this cometd object\n */\n var CometD = function(name) {\n var _scheduler = new Scheduler();\n var _cometd = this;\n var _name = name || 'default';\n var _crossDomain = false;\n var _transports = new TransportRegistry();\n var _transport;\n var _status = 'disconnected';\n var _messageId = 0;\n var _clientId = null;\n var _batch = 0;\n var _messageQueue = [];\n var _internalBatch = false;\n var _listenerId = 0;\n var _listeners = {};\n var _backoff = 0;\n var _scheduledSend = null;\n var _extensions = [];\n var _advice = {};\n var _handshakeProps;\n var _handshakeCallback;\n var _callbacks = {};\n var _remoteCalls = {};\n var _reestablish = false;\n var _connected = false;\n var _unconnectTime = 0;\n var _handshakeMessages = 0;\n var _metaConnect = null;\n var _config = {\n useWorkerScheduler: true,\n protocol: null,\n stickyReconnect: true,\n connectTimeout: 0,\n maxConnections: 2,\n backoffIncrement: 1000,\n maxBackoff: 60000,\n logLevel: 'info',\n maxNetworkDelay: 10000,\n requestHeaders: {},\n appendMessageTypeToURL: true,\n autoBatch: false,\n urls: {},\n maxURILength: 2000,\n advice: {\n timeout: 60000,\n interval: 0,\n reconnect: undefined,\n maxInterval: 0\n }\n };\n\n function _fieldValue(object, name) {\n try {\n return object[name];\n } catch (x) {\n return undefined;\n }\n }\n\n /**\n * Mixes in the given objects into the target object by copying the properties.\n * @param deep if the copy must be deep\n * @param target the target object\n * @param objects the objects whose properties are copied into the target\n */\n this._mixin = function(deep, target, objects) {\n var result = target || {};\n\n // Skip first 2 parameters (deep and target), and loop over the others\n for (var i = 2; i < arguments.length; ++i) {\n var object = arguments[i];\n\n if (object === undefined || object === null) {\n continue;\n }\n\n for (var propName in object) {\n if (object.hasOwnProperty(propName)) {\n var prop = _fieldValue(object, propName);\n var targ = _fieldValue(result, propName);\n\n // Avoid infinite loops\n if (prop === target) {\n continue;\n }\n // Do not mixin undefined values\n if (prop === undefined) {\n continue;\n }\n\n if (deep && typeof prop === 'object' && prop !== null) {\n if (prop instanceof Array) {\n result[propName] = this._mixin(deep, targ instanceof Array ? targ : [], prop);\n } else {\n var source = typeof targ === 'object' && !(targ instanceof Array) ? targ : {};\n result[propName] = this._mixin(deep, source, prop);\n }\n } else {\n result[propName] = prop;\n }\n }\n }\n }\n\n return result;\n };\n\n function _isString(value) {\n return Utils.isString(value);\n }\n\n function _isFunction(value) {\n if (value === undefined || value === null) {\n return false;\n }\n return typeof value === 'function';\n }\n\n function _zeroPad(value, length) {\n var result = '';\n while (--length > 0) {\n if (value >= Math.pow(10, length)) {\n break;\n }\n result += '0';\n }\n result += value;\n return result;\n }\n\n function _log(level, args) {\n if (window.console) {\n var logger = window.console[level];\n if (_isFunction(logger)) {\n var now = new Date();\n [].splice.call(args, 0, 0, _zeroPad(now.getHours(), 2) + ':' + _zeroPad(now.getMinutes(), 2) + ':' +\n _zeroPad(now.getSeconds(), 2) + '.' + _zeroPad(now.getMilliseconds(), 3));\n logger.apply(window.console, args);\n }\n }\n }\n\n this._warn = function() {\n _log('warn', arguments);\n };\n\n this._info = function() {\n if (_config.logLevel !== 'warn') {\n _log('info', arguments);\n }\n };\n\n this._debug = function() {\n if (_config.logLevel === 'debug') {\n _log('debug', arguments);\n }\n };\n\n function _splitURL(url) {\n // [1] = protocol://,\n // [2] = host:port,\n // [3] = host,\n // [4] = IPv6_host,\n // [5] = IPv4_host,\n // [6] = :port,\n // [7] = port,\n // [8] = uri,\n // [9] = rest (query / fragment)\n return new RegExp('(^https?://)?(((\\\\[[^\\\\]]+])|([^:/?#]+))(:(\\\\d+))?)?([^?#]*)(.*)?').exec(url);\n }\n\n /**\n * Returns whether the given hostAndPort is cross domain.\n * The default implementation checks against window.location.host\n * but this function can be overridden to make it work in non-browser\n * environments.\n *\n * @param hostAndPort the host and port in format host:port\n * @return whether the given hostAndPort is cross domain\n */\n this._isCrossDomain = function(hostAndPort) {\n if (window.location && window.location.host) {\n if (hostAndPort) {\n return hostAndPort !== window.location.host;\n }\n }\n return false;\n };\n\n function _configure(configuration) {\n _cometd._debug('Configuring cometd object with', configuration);\n // Support old style param, where only the Bayeux server URL was passed.\n if (_isString(configuration)) {\n configuration = {\n url: configuration\n };\n }\n if (!configuration) {\n configuration = {};\n }\n\n _config = _cometd._mixin(false, _config, configuration);\n\n var url = _cometd.getURL();\n if (!url) {\n throw 'Missing required configuration parameter \\'url\\' specifying the Bayeux server URL';\n }\n\n // Check if we're cross domain.\n var urlParts = _splitURL(url);\n var hostAndPort = urlParts[2];\n var uri = urlParts[8];\n var afterURI = urlParts[9];\n _crossDomain = _cometd._isCrossDomain(hostAndPort);\n\n // Check if appending extra path is supported.\n if (_config.appendMessageTypeToURL) {\n if (afterURI !== undefined && afterURI.length > 0) {\n _cometd._info('Appending message type to URI ' + uri + afterURI + ' is not supported, disabling \\'appendMessageTypeToURL\\' configuration');\n _config.appendMessageTypeToURL = false;\n } else {\n var uriSegments = uri.split('/');\n var lastSegmentIndex = uriSegments.length - 1;\n if (uri.match(/\\/$/)) {\n lastSegmentIndex -= 1;\n }\n if (uriSegments[lastSegmentIndex].indexOf('.') >= 0) {\n // Very likely the CometD servlet's URL pattern is mapped to an extension, such as *.cometd\n // It will be difficult to add the extra path in this case\n _cometd._info('Appending message type to URI ' + uri + ' is not supported, disabling \\'appendMessageTypeToURL\\' configuration');\n _config.appendMessageTypeToURL = false;\n }\n }\n }\n\n if (window.Worker && window.Blob && window.URL && _config.useWorkerScheduler) {\n var code = WorkerScheduler.toString();\n // Remove the function declaration, the opening brace and the closing brace.\n code = code.substring(code.indexOf('{') + 1, code.lastIndexOf('}'));\n var blob = new window.Blob([code], {\n type: 'application/json'\n });\n var blobURL = window.URL.createObjectURL(blob);\n var worker = new window.Worker(blobURL);\n _scheduler.setTimeout = function(funktion, delay) {\n var id = _scheduler.register(funktion);\n worker.postMessage({\n id: id,\n type: 'setTimeout',\n delay: delay\n });\n return id;\n };\n _scheduler.clearTimeout = function(id) {\n _scheduler.unregister(id);\n worker.postMessage({\n id: id,\n type: 'clearTimeout'\n });\n };\n worker.onmessage = function(e) {\n var id = e.data.id;\n var funktion = _scheduler.unregister(id);\n if (funktion) {\n funktion();\n }\n };\n }\n }\n\n function _removeListener(subscription) {\n if (subscription) {\n var subscriptions = _listeners[subscription.channel];\n if (subscriptions && subscriptions[subscription.id]) {\n delete subscriptions[subscription.id];\n _cometd._debug('Removed', subscription.listener ? 'listener' : 'subscription', subscription);\n }\n }\n }\n\n function _removeSubscription(subscription) {\n if (subscription && !subscription.listener) {\n _removeListener(subscription);\n }\n }\n\n function _clearSubscriptions() {\n for (var channel in _listeners) {\n if (_listeners.hasOwnProperty(channel)) {\n var subscriptions = _listeners[channel];\n if (subscriptions) {\n for (var id in subscriptions) {\n if (subscriptions.hasOwnProperty(id)) {\n _removeSubscription(subscriptions[id]);\n }\n }\n }\n }\n }\n }\n\n function _setStatus(newStatus) {\n if (_status !== newStatus) {\n _cometd._debug('Status', _status, '->', newStatus);\n _status = newStatus;\n }\n }\n\n function _isDisconnected() {\n return _status === 'disconnecting' || _status === 'disconnected';\n }\n\n function _nextMessageId() {\n var result = ++_messageId;\n return '' + result;\n }\n\n function _applyExtension(scope, callback, name, message, outgoing) {\n try {\n return callback.call(scope, message);\n } catch (x) {\n var handler = _cometd.onExtensionException;\n if (_isFunction(handler)) {\n _cometd._debug('Invoking extension exception handler', name, x);\n try {\n handler.call(_cometd, x, name, outgoing, message);\n } catch (xx) {\n _cometd._info('Exception during execution of extension exception handler', name, xx);\n }\n } else {\n _cometd._info('Exception during execution of extension', name, x);\n }\n return message;\n }\n }\n\n function _applyIncomingExtensions(message) {\n for (var i = 0; i < _extensions.length; ++i) {\n if (message === undefined || message === null) {\n break;\n }\n\n var extension = _extensions[i];\n var callback = extension.extension.incoming;\n if (_isFunction(callback)) {\n var result = _applyExtension(extension.extension, callback, extension.name, message, false);\n message = result === undefined ? message : result;\n }\n }\n return message;\n }\n\n function _applyOutgoingExtensions(message) {\n for (var i = _extensions.length - 1; i >= 0; --i) {\n if (message === undefined || message === null) {\n break;\n }\n\n var extension = _extensions[i];\n var callback = extension.extension.outgoing;\n if (_isFunction(callback)) {\n var result = _applyExtension(extension.extension, callback, extension.name, message, true);\n message = result === undefined ? message : result;\n }\n }\n return message;\n }\n\n function _notify(channel, message) {\n var subscriptions = _listeners[channel];\n if (subscriptions) {\n for (var id in subscriptions) {\n if (subscriptions.hasOwnProperty(id)) {\n var subscription = subscriptions[id];\n // Subscriptions may come and go, so the array may have 'holes'\n if (subscription) {\n try {\n subscription.callback.call(subscription.scope, message);\n } catch (x) {\n var handler = _cometd.onListenerException;\n if (_isFunction(handler)) {\n _cometd._debug('Invoking listener exception handler', subscription, x);\n try {\n handler.call(_cometd, x, subscription, subscription.listener, message);\n } catch (xx) {\n _cometd._info('Exception during execution of listener exception handler', subscription, xx);\n }\n } else {\n _cometd._info('Exception during execution of listener', subscription, message, x);\n }\n }\n }\n }\n }\n }\n }\n\n function _notifyListeners(channel, message) {\n // Notify direct listeners\n _notify(channel, message);\n\n // Notify the globbing listeners\n var channelParts = channel.split('/');\n var last = channelParts.length - 1;\n for (var i = last; i > 0; --i) {\n var channelPart = channelParts.slice(0, i).join('/') + '/*';\n // We don't want to notify /foo/* if the channel is /foo/bar/baz,\n // so we stop at the first non recursive globbing\n if (i === last) {\n _notify(channelPart, message);\n }\n // Add the recursive globber and notify\n channelPart += '*';\n _notify(channelPart, message);\n }\n }\n\n function _cancelDelayedSend() {\n if (_scheduledSend !== null) {\n _cometd.clearTimeout(_scheduledSend);\n }\n _scheduledSend = null;\n }\n\n function _delayedSend(operation, delay) {\n _cancelDelayedSend();\n var time = _advice.interval + delay;\n _cometd._debug('Function scheduled in', time, 'ms, interval =', _advice.interval, 'backoff =', _backoff, operation);\n _scheduledSend = _cometd.setTimeout(operation, time);\n }\n\n // Needed to break cyclic dependencies between function definitions\n var _handleMessages;\n var _handleFailure;\n\n /**\n * Delivers the messages to the CometD server\n * @param messages the array of messages to send\n * @param metaConnect true if this send is on /meta/connect\n * @param extraPath an extra path to append to the Bayeux server URL\n */\n function _send(messages, metaConnect, extraPath) {\n // We must be sure that the messages have a clientId.\n // This is not guaranteed since the handshake may take time to return\n // (and hence the clientId is not known yet) and the application\n // may create other messages.\n for (var i = 0; i < messages.length; ++i) {\n var message = messages[i];\n var messageId = message.id;\n\n if (_clientId) {\n message.clientId = _clientId;\n }\n\n message = _applyOutgoingExtensions(message);\n if (message !== undefined && message !== null) {\n // Extensions may have modified the message id, but we need to own it.\n message.id = messageId;\n messages[i] = message;\n } else {\n delete _callbacks[messageId];\n messages.splice(i--, 1);\n }\n }\n\n if (messages.length === 0) {\n return;\n }\n\n if (metaConnect) {\n _metaConnect = messages[0];\n }\n\n var url = _cometd.getURL();\n if (_config.appendMessageTypeToURL) {\n // If url does not end with '/', then append it\n if (!url.match(/\\/$/)) {\n url = url + '/';\n }\n if (extraPath) {\n url = url + extraPath;\n }\n }\n\n var envelope = {\n url: url,\n sync: false,\n messages: messages,\n onSuccess: function(rcvdMessages) {\n try {\n _handleMessages.call(_cometd, rcvdMessages);\n } catch (x) {\n _cometd._info('Exception during handling of messages', x);\n }\n },\n onFailure: function(conduit, messages, failure) {\n try {\n var transport = _cometd.getTransport();\n failure.connectionType = transport ? transport.getType() : \"unknown\";\n _handleFailure.call(_cometd, conduit, messages, failure);\n } catch (x) {\n _cometd._info('Exception during handling of failure', x);\n }\n }\n };\n _cometd._debug('Send', envelope);\n _transport.send(envelope, metaConnect);\n }\n\n function _queueSend(message) {\n if (_batch > 0 || _internalBatch === true) {\n _messageQueue.push(message);\n } else {\n _send([message], false);\n }\n }\n\n /**\n * Sends a complete bayeux message.\n * This method is exposed as a public so that extensions may use it\n * to send bayeux message directly, for example in case of re-sending\n * messages that have already been sent but that for some reason must\n * be resent.\n */\n this.send = _queueSend;\n\n function _resetBackoff() {\n _backoff = 0;\n }\n\n function _increaseBackoff() {\n if (_backoff < _config.maxBackoff) {\n _backoff += _config.backoffIncrement;\n }\n return _backoff;\n }\n\n /**\n * Starts a the batch of messages to be sent in a single request.\n * @see #_endBatch(sendMessages)\n */\n function _startBatch() {\n ++_batch;\n _cometd._debug('Starting batch, depth', _batch);\n }\n\n function _flushBatch() {\n var messages = _messageQueue;\n _messageQueue = [];\n if (messages.length > 0) {\n _send(messages, false);\n }\n }\n\n /**\n * Ends the batch of messages to be sent in a single request,\n * optionally sending messages present in the message queue depending\n * on the given argument.\n * @see #_startBatch()\n */\n function _endBatch() {\n --_batch;\n _cometd._debug('Ending batch, depth', _batch);\n if (_batch < 0) {\n throw 'Calls to startBatch() and endBatch() are not paired';\n }\n\n if (_batch === 0 && !_isDisconnected() && !_internalBatch) {\n _flushBatch();\n }\n }\n\n /**\n * Sends the connect message\n */\n function _connect() {\n if (!_isDisconnected()) {\n var bayeuxMessage = {\n id: _nextMessageId(),\n channel: '/meta/connect',\n connectionType: _transport.getType()\n };\n\n // In case of reload or temporary loss of connection\n // we want the next successful connect to return immediately\n // instead of being held by the server, so that connect listeners\n // can be notified that the connection has been re-established\n if (!_connected) {\n bayeuxMessage.advice = {\n timeout: 0\n };\n }\n\n _setStatus('connecting');\n _cometd._debug('Connect sent', bayeuxMessage);\n _send([bayeuxMessage], true, 'connect');\n _setStatus('connected');\n }\n }\n\n function _delayedConnect(delay) {\n _setStatus('connecting');\n _delayedSend(function() {\n _connect();\n }, delay);\n }\n\n function _updateAdvice(newAdvice) {\n if (newAdvice) {\n _advice = _cometd._mixin(false, {}, _config.advice, newAdvice);\n _cometd._debug('New advice', _advice);\n }\n }\n\n function _disconnect(abort) {\n _cancelDelayedSend();\n if (abort && _transport) {\n _transport.abort();\n }\n _crossDomain = false;\n _transport = null;\n _setStatus('disconnected');\n _clientId = null;\n _batch = 0;\n _resetBackoff();\n _reestablish = false;\n _connected = false;\n _unconnectTime = 0;\n _metaConnect = null;\n\n // Fail any existing queued message\n if (_messageQueue.length > 0) {\n var messages = _messageQueue;\n _messageQueue = [];\n _handleFailure.call(_cometd, undefined, messages, {\n reason: 'Disconnected'\n });\n }\n }\n\n function _notifyTransportException(oldTransport, newTransport, failure) {\n var handler = _cometd.onTransportException;\n if (_isFunction(handler)) {\n _cometd._debug('Invoking transport exception handler', oldTransport, newTransport, failure);\n try {\n handler.call(_cometd, failure, oldTransport, newTransport);\n } catch (x) {\n _cometd._info('Exception during execution of transport exception handler', x);\n }\n }\n }\n\n /**\n * Sends the initial handshake message\n */\n function _handshake(handshakeProps, handshakeCallback) {\n if (_isFunction(handshakeProps)) {\n handshakeCallback = handshakeProps;\n handshakeProps = undefined;\n }\n\n _clientId = null;\n\n _clearSubscriptions();\n\n // Reset the transports if we're not retrying the handshake\n if (_isDisconnected()) {\n _transports.reset(true);\n }\n\n // Reset the advice.\n _updateAdvice({});\n\n _batch = 0;\n\n // Mark the start of an internal batch.\n // This is needed because handshake and connect are async.\n // It may happen that the application calls init() then subscribe()\n // and the subscribe message is sent before the connect message, if\n // the subscribe message is not held until the connect message is sent.\n // So here we start a batch to hold temporarily any message until\n // the connection is fully established.\n _internalBatch = true;\n\n // Save the properties provided by the user, so that\n // we can reuse them during automatic re-handshake\n _handshakeProps = handshakeProps;\n _handshakeCallback = handshakeCallback;\n\n var version = '1.0';\n\n // Figure out the transports to send to the server\n var url = _cometd.getURL();\n var transportTypes = _transports.findTransportTypes(version, _crossDomain, url);\n\n var bayeuxMessage = {\n id: _nextMessageId(),\n version: version,\n minimumVersion: version,\n channel: '/meta/handshake',\n supportedConnectionTypes: transportTypes,\n advice: {\n timeout: _advice.timeout,\n interval: _advice.interval\n }\n };\n // Do not allow the user to override important fields.\n var message = _cometd._mixin(false, {}, _handshakeProps, bayeuxMessage);\n\n // Save the callback.\n _cometd._putCallback(message.id, handshakeCallback);\n\n // Pick up the first available transport as initial transport\n // since we don't know if the server supports it\n if (!_transport) {\n _transport = _transports.negotiateTransport(transportTypes, version, _crossDomain, url);\n if (!_transport) {\n var failure = 'Could not find initial transport among: ' + _transports.getTransportTypes();\n _cometd._warn(failure);\n throw failure;\n }\n }\n\n _cometd._debug('Initial transport is', _transport.getType());\n\n // We started a batch to hold the application messages,\n // so here we must bypass it and send immediately.\n _setStatus('handshaking');\n _cometd._debug('Handshake sent', message);\n _send([message], false, 'handshake');\n }\n\n function _delayedHandshake(delay) {\n _setStatus('handshaking');\n\n // We will call _handshake() which will reset _clientId, but we want to avoid\n // that between the end of this method and the call to _handshake() someone may\n // call publish() (or other methods that call _queueSend()).\n _internalBatch = true;\n\n _delayedSend(function() {\n _handshake(_handshakeProps, _handshakeCallback);\n }, delay);\n }\n\n function _notifyCallback(callback, message) {\n try {\n callback.call(_cometd, message);\n } catch (x) {\n var handler = _cometd.onCallbackException;\n if (_isFunction(handler)) {\n _cometd._debug('Invoking callback exception handler', x);\n try {\n handler.call(_cometd, x, message);\n } catch (xx) {\n _cometd._info('Exception during execution of callback exception handler', xx);\n }\n } else {\n _cometd._info('Exception during execution of message callback', x);\n }\n }\n }\n\n this._getCallback = function(messageId) {\n return _callbacks[messageId];\n };\n\n this._putCallback = function(messageId, callback) {\n var result = this._getCallback(messageId);\n if (_isFunction(callback)) {\n _callbacks[messageId] = callback;\n }\n return result;\n };\n\n function _handleCallback(message) {\n var callback = _cometd._getCallback([message.id]);\n if (_isFunction(callback)) {\n delete _callbacks[message.id];\n _notifyCallback(callback, message);\n }\n }\n\n function _handleRemoteCall(message) {\n var context = _remoteCalls[message.id];\n delete _remoteCalls[message.id];\n if (context) {\n _cometd._debug('Handling remote call response for', message, 'with context', context);\n\n // Clear the timeout, if present.\n var timeout = context.timeout;\n if (timeout) {\n _cometd.clearTimeout(timeout);\n }\n\n var callback = context.callback;\n if (_isFunction(callback)) {\n _notifyCallback(callback, message);\n return true;\n }\n }\n return false;\n }\n\n this.onTransportFailure = function(message, failureInfo, failureHandler) {\n this._debug('Transport failure', failureInfo, 'for', message);\n\n var transports = this.getTransportRegistry();\n var url = this.getURL();\n var crossDomain = this._isCrossDomain(_splitURL(url)[2]);\n var version = '1.0';\n var transportTypes = transports.findTransportTypes(version, crossDomain, url);\n\n if (failureInfo.action === 'none') {\n if (message.channel === '/meta/handshake') {\n if (!failureInfo.transport) {\n var failure = 'Could not negotiate transport, client=[' + transportTypes + '], server=[' + message.supportedConnectionTypes + ']';\n this._warn(failure);\n _notifyTransportException(_transport.getType(), null, {\n reason: failure,\n connectionType: _transport.getType(),\n transport: _transport\n });\n }\n }\n } else {\n failureInfo.delay = this.getBackoffPeriod();\n // Different logic depending on whether we are handshaking or connecting.\n if (message.channel === '/meta/handshake') {\n if (!failureInfo.transport) {\n // The transport is invalid, try to negotiate again.\n var oldTransportType = _transport ? _transport.getType() : null;\n var newTransport = transports.negotiateTransport(transportTypes, version, crossDomain, url);\n if (!newTransport) {\n this._warn('Could not negotiate transport, client=[' + transportTypes + ']');\n _notifyTransportException(oldTransportType, null, message.failure);\n failureInfo.action = 'none';\n } else {\n var newTransportType = newTransport.getType();\n this._debug('Transport', oldTransportType, '->', newTransportType);\n _notifyTransportException(oldTransportType, newTransportType, message.failure);\n failureInfo.action = 'handshake';\n failureInfo.transport = newTransport;\n }\n }\n\n if (failureInfo.action !== 'none') {\n this.increaseBackoffPeriod();\n }\n } else {\n var now = new Date().getTime();\n\n if (_unconnectTime === 0) {\n _unconnectTime = now;\n }\n\n if (failureInfo.action === 'retry') {\n failureInfo.delay = this.increaseBackoffPeriod();\n // Check whether we may switch to handshaking.\n var maxInterval = _advice.maxInterval;\n if (maxInterval > 0) {\n var expiration = _advice.timeout + _advice.interval + maxInterval;\n var unconnected = now - _unconnectTime;\n if (unconnected + _backoff > expiration) {\n failureInfo.action = 'handshake';\n }\n }\n }\n\n if (failureInfo.action === 'handshake') {\n failureInfo.delay = 0;\n transports.reset(false);\n this.resetBackoffPeriod();\n }\n }\n }\n\n failureHandler.call(_cometd, failureInfo);\n };\n\n function _handleTransportFailure(failureInfo) {\n _cometd._debug('Transport failure handling', failureInfo);\n\n if (failureInfo.transport) {\n _transport = failureInfo.transport;\n }\n\n if (failureInfo.url) {\n _transport.setURL(failureInfo.url);\n }\n\n var action = failureInfo.action;\n var delay = failureInfo.delay || 0;\n switch (action) {\n case 'handshake':\n _delayedHandshake(delay);\n break;\n case 'retry':\n _delayedConnect(delay);\n break;\n case 'none':\n _disconnect(true);\n break;\n default:\n throw 'Unknown action ' + action;\n }\n }\n\n function _failHandshake(message, failureInfo) {\n _handleCallback(message);\n _notifyListeners('/meta/handshake', message);\n _notifyListeners('/meta/unsuccessful', message);\n\n // The listeners may have disconnected.\n if (_isDisconnected()) {\n failureInfo.action = 'none';\n }\n\n _cometd.onTransportFailure.call(_cometd, message, failureInfo, _handleTransportFailure);\n }\n\n function _handshakeResponse(message) {\n var url = _cometd.getURL();\n if (message.successful) {\n var crossDomain = _cometd._isCrossDomain(_splitURL(url)[2]);\n var newTransport = _transports.negotiateTransport(message.supportedConnectionTypes, message.version, crossDomain, url);\n if (newTransport === null) {\n message.successful = false;\n _failHandshake(message, {\n cause: 'negotiation',\n action: 'none',\n transport: null\n });\n return;\n } else if (_transport !== newTransport) {\n _cometd._debug('Transport', _transport.getType(), '->', newTransport.getType());\n _transport = newTransport;\n }\n\n _clientId = message.clientId;\n\n // End the internal batch and allow held messages from the application\n // to go to the server (see _handshake() where we start the internal batch).\n _internalBatch = false;\n _flushBatch();\n\n // Here the new transport is in place, as well as the clientId, so\n // the listeners can perform a publish() if they want.\n // Notify the listeners before the connect below.\n message.reestablish = _reestablish;\n _reestablish = true;\n\n _handleCallback(message);\n _notifyListeners('/meta/handshake', message);\n\n _handshakeMessages = message['x-messages'] || 0;\n\n var action = _isDisconnected() ? 'none' : _advice.reconnect || 'retry';\n switch (action) {\n case 'retry':\n _resetBackoff();\n if (_handshakeMessages === 0) {\n _delayedConnect(0);\n } else {\n _cometd._debug('Processing', _handshakeMessages, 'handshake-delivered messages');\n }\n break;\n case 'none':\n _disconnect(true);\n break;\n default:\n throw 'Unrecognized advice action ' + action;\n }\n } else {\n _failHandshake(message, {\n cause: 'unsuccessful',\n action: _advice.reconnect || 'handshake',\n transport: _transport\n });\n }\n }\n\n function _handshakeFailure(message) {\n _failHandshake(message, {\n cause: 'failure',\n action: 'handshake',\n transport: null\n });\n }\n\n function _matchMetaConnect(connect) {\n if (_status === 'disconnected') {\n return true;\n }\n if (_metaConnect && _metaConnect.id === connect.id) {\n _metaConnect = null;\n return true;\n }\n return false;\n }\n\n function _failConnect(message, failureInfo) {\n // Notify the listeners after the status change but before the next action.\n _notifyListeners('/meta/connect', message);\n _notifyListeners('/meta/unsuccessful', message);\n\n // The listeners may have disconnected.\n if (_isDisconnected()) {\n failureInfo.action = 'none';\n }\n\n _cometd.onTransportFailure.call(_cometd, message, failureInfo, _handleTransportFailure);\n }\n\n function _connectResponse(message) {\n if (_matchMetaConnect(message)) {\n _connected = message.successful;\n if (_connected) {\n _notifyListeners('/meta/connect', message);\n\n // Normally, the advice will say \"reconnect: 'retry', interval: 0\"\n // and the server will hold the request, so when a response returns\n // we immediately call the server again (long polling).\n // Listeners can call disconnect(), so check the state after they run.\n var action = _isDisconnected() ? 'none' : _advice.reconnect || 'retry';\n switch (action) {\n case 'retry':\n _resetBackoff();\n _delayedConnect(_backoff);\n break;\n case 'none':\n _disconnect(false);\n break;\n default:\n throw 'Unrecognized advice action ' + action;\n }\n } else {\n _failConnect(message, {\n cause: 'unsuccessful',\n action: _advice.reconnect || 'retry',\n transport: _transport\n });\n }\n } else {\n _cometd._debug('Mismatched /meta/connect reply', message);\n }\n }\n\n function _connectFailure(message) {\n if (_matchMetaConnect(message)) {\n _connected = false;\n _failConnect(message, {\n cause: 'failure',\n action: 'retry',\n transport: null\n });\n } else {\n _cometd._debug('Mismatched /meta/connect failure', message);\n }\n }\n\n function _failDisconnect(message) {\n _disconnect(true);\n _handleCallback(message);\n _notifyListeners('/meta/disconnect', message);\n _notifyListeners('/meta/unsuccessful', message);\n }\n\n function _disconnectResponse(message) {\n if (message.successful) {\n // Wait for the /meta/connect to arrive.\n _disconnect(false);\n _handleCallback(message);\n _notifyListeners('/meta/disconnect', message);\n } else {\n _failDisconnect(message);\n }\n }\n\n function _disconnectFailure(message) {\n _failDisconnect(message);\n }\n\n function _failSubscribe(message) {\n var subscriptions = _listeners[message.subscription];\n if (subscriptions) {\n for (var id in subscriptions) {\n if (subscriptions.hasOwnProperty(id)) {\n var subscription = subscriptions[id];\n if (subscription && !subscription.listener) {\n delete subscriptions[id];\n _cometd._debug('Removed failed subscription', subscription);\n }\n }\n }\n }\n _handleCallback(message);\n _notifyListeners('/meta/subscribe', message);\n _notifyListeners('/meta/unsuccessful', message);\n }\n\n function _subscribeResponse(message) {\n if (message.successful) {\n _handleCallback(message);\n _notifyListeners('/meta/subscribe', message);\n } else {\n _failSubscribe(message);\n }\n }\n\n function _subscribeFailure(message) {\n _failSubscribe(message);\n }\n\n function _failUnsubscribe(message) {\n _handleCallback(message);\n _notifyListeners('/meta/unsubscribe', message);\n _notifyListeners('/meta/unsuccessful', message);\n }\n\n function _unsubscribeResponse(message) {\n if (message.successful) {\n _handleCallback(message);\n _notifyListeners('/meta/unsubscribe', message);\n } else {\n _failUnsubscribe(message);\n }\n }\n\n function _unsubscribeFailure(message) {\n _failUnsubscribe(message);\n }\n\n function _failMessage(message) {\n if (!_handleRemoteCall(message)) {\n _handleCallback(message);\n _notifyListeners('/meta/publish', message);\n _notifyListeners('/meta/unsuccessful', message);\n }\n }\n\n function _messageResponse(message) {\n if (message.data !== undefined) {\n if (!_handleRemoteCall(message)) {\n _notifyListeners(message.channel, message);\n if (_handshakeMessages > 0) {\n --_handshakeMessages;\n if (_handshakeMessages === 0) {\n _cometd._debug('Processed last handshake-delivered message');\n _delayedConnect(0);\n }\n }\n }\n } else {\n if (message.successful === undefined) {\n _cometd._warn('Unknown Bayeux Message', message);\n } else {\n if (message.successful) {\n _handleCallback(message);\n _notifyListeners('/meta/publish', message);\n } else {\n _failMessage(message);\n }\n }\n }\n }\n\n function _messageFailure(failure) {\n _failMessage(failure);\n }\n\n function _receive(message) {\n _unconnectTime = 0;\n\n message = _applyIncomingExtensions(message);\n if (message === undefined || message === null) {\n return;\n }\n\n _updateAdvice(message.advice);\n\n var channel = message.channel;\n switch (channel) {\n case '/meta/handshake':\n _handshakeResponse(message);\n break;\n case '/meta/connect':\n _connectResponse(message);\n break;\n case '/meta/disconnect':\n _disconnectResponse(message);\n break;\n case '/meta/subscribe':\n _subscribeResponse(message);\n break;\n case '/meta/unsubscribe':\n _unsubscribeResponse(message);\n break;\n default:\n _messageResponse(message);\n break;\n }\n }\n\n /**\n * Receives a message.\n * This method is exposed as a public so that extensions may inject\n * messages simulating that they had been received.\n */\n this.receive = _receive;\n\n _handleMessages = function(rcvdMessages) {\n _cometd._debug('Received', rcvdMessages);\n\n for (var i = 0; i < rcvdMessages.length; ++i) {\n var message = rcvdMessages[i];\n _receive(message);\n }\n };\n\n _handleFailure = function(conduit, messages, failure) {\n _cometd._debug('handleFailure', conduit, messages, failure);\n\n failure.transport = conduit;\n for (var i = 0; i < messages.length; ++i) {\n var message = messages[i];\n var failureMessage = {\n id: message.id,\n successful: false,\n channel: message.channel,\n failure: failure\n };\n failure.message = message;\n switch (message.channel) {\n case '/meta/handshake':\n _handshakeFailure(failureMessage);\n break;\n case '/meta/connect':\n _connectFailure(failureMessage);\n break;\n case '/meta/disconnect':\n _disconnectFailure(failureMessage);\n break;\n case '/meta/subscribe':\n failureMessage.subscription = message.subscription;\n _subscribeFailure(failureMessage);\n break;\n case '/meta/unsubscribe':\n failureMessage.subscription = message.subscription;\n _unsubscribeFailure(failureMessage);\n break;\n default:\n _messageFailure(failureMessage);\n break;\n }\n }\n };\n\n function _hasSubscriptions(channel) {\n var subscriptions = _listeners[channel];\n if (subscriptions) {\n for (var id in subscriptions) {\n if (subscriptions.hasOwnProperty(id)) {\n if (subscriptions[id]) {\n return true;\n }\n }\n }\n }\n return false;\n }\n\n function _resolveScopedCallback(scope, callback) {\n var delegate = {\n scope: scope,\n method: callback\n };\n if (_isFunction(scope)) {\n delegate.scope = undefined;\n delegate.method = scope;\n } else {\n if (_isString(callback)) {\n if (!scope) {\n throw 'Invalid scope ' + scope;\n }\n delegate.method = scope[callback];\n if (!_isFunction(delegate.method)) {\n throw 'Invalid callback ' + callback + ' for scope ' + scope;\n }\n } else if (!_isFunction(callback)) {\n throw 'Invalid callback ' + callback;\n }\n }\n return delegate;\n }\n\n function _addListener(channel, scope, callback, isListener) {\n // The data structure is a map<channel, subscription[]>, where each subscription\n // holds the callback to be called and its scope.\n\n var delegate = _resolveScopedCallback(scope, callback);\n _cometd._debug('Adding', isListener ? 'listener' : 'subscription', 'on', channel, 'with scope', delegate.scope, 'and callback', delegate.method);\n\n var id = ++_listenerId;\n var subscription = {\n id: id,\n channel: channel,\n scope: delegate.scope,\n callback: delegate.method,\n listener: isListener\n };\n\n var subscriptions = _listeners[channel];\n if (!subscriptions) {\n subscriptions = {};\n _listeners[channel] = subscriptions;\n }\n\n subscriptions[id] = subscription;\n\n _cometd._debug('Added', isListener ? 'listener' : 'subscription', subscription);\n\n return subscription;\n }\n\n //\n // PUBLIC API\n //\n\n /**\n * Registers the given transport under the given transport type.\n * The optional index parameter specifies the \"priority\" at which the\n * transport is registered (where 0 is the max priority).\n * If a transport with the same type is already registered, this function\n * does nothing and returns false.\n * @param type the transport type\n * @param transport the transport object\n * @param index the index at which this transport is to be registered\n * @return true if the transport has been registered, false otherwise\n * @see #unregisterTransport(type)\n */\n this.registerTransport = function(type, transport, index) {\n var result = _transports.add(type, transport, index);\n if (result) {\n this._debug('Registered transport', type);\n\n if (_isFunction(transport.registered)) {\n transport.registered(type, this);\n }\n }\n return result;\n };\n\n /**\n * Unregisters the transport with the given transport type.\n * @param type the transport type to unregister\n * @return the transport that has been unregistered,\n * or null if no transport was previously registered under the given transport type\n */\n this.unregisterTransport = function(type) {\n var transport = _transports.remove(type);\n if (transport !== null) {\n this._debug('Unregistered transport', type);\n\n if (_isFunction(transport.unregistered)) {\n transport.unregistered();\n }\n }\n return transport;\n };\n\n this.unregisterTransports = function() {\n _transports.clear();\n };\n\n /**\n * @return an array of all registered transport types\n */\n this.getTransportTypes = function() {\n return _transports.getTransportTypes();\n };\n\n this.findTransport = function(name) {\n return _transports.find(name);\n };\n\n /**\n * @returns the TransportRegistry object\n */\n this.getTransportRegistry = function() {\n return _transports;\n };\n\n /**\n * Configures the initial Bayeux communication with the Bayeux server.\n * Configuration is passed via an object that must contain a mandatory field <code>url</code>\n * of type string containing the URL of the Bayeux server.\n * @param configuration the configuration object\n */\n this.configure = function(configuration) {\n _configure.call(this, configuration);\n };\n\n /**\n * Configures and establishes the Bayeux communication with the Bayeux server\n * via a handshake and a subsequent connect.\n * @param configuration the configuration object\n * @param handshakeProps an object to be merged with the handshake message\n * @see #configure(configuration)\n * @see #handshake(handshakeProps)\n */\n this.init = function(configuration, handshakeProps) {\n this.configure(configuration);\n this.handshake(handshakeProps);\n };\n\n /**\n * Establishes the Bayeux communication with the Bayeux server\n * via a handshake and a subsequent connect.\n * @param handshakeProps an object to be merged with the handshake message\n * @param handshakeCallback a function to be invoked when the handshake is acknowledged\n */\n this.handshake = function(handshakeProps, handshakeCallback) {\n if (_status !== 'disconnected') {\n throw 'Illegal state: handshaken';\n }\n _handshake(handshakeProps, handshakeCallback);\n };\n\n /**\n * Disconnects from the Bayeux server.\n * @param disconnectProps an object to be merged with the disconnect message\n * @param disconnectCallback a function to be invoked when the disconnect is acknowledged\n */\n this.disconnect = function(disconnectProps, disconnectCallback) {\n if (_isDisconnected()) {\n return;\n }\n\n if (_isFunction(disconnectProps)) {\n disconnectCallback = disconnectProps;\n disconnectProps = undefined;\n }\n\n var bayeuxMessage = {\n id: _nextMessageId(),\n channel: '/meta/disconnect'\n };\n // Do not allow the user to override important fields.\n var message = this._mixin(false, {}, disconnectProps, bayeuxMessage);\n\n // Save the callback.\n _cometd._putCallback(message.id, disconnectCallback);\n\n _setStatus('disconnecting');\n _send([message], false, 'disconnect');\n };\n\n /**\n * Marks the start of a batch of application messages to be sent to the server\n * in a single request, obtaining a single response containing (possibly) many\n * application reply messages.\n * Messages are held in a queue and not sent until {@link #endBatch()} is called.\n * If startBatch() is called multiple times, then an equal number of endBatch()\n * calls must be made to close and send the batch of messages.\n * @see #endBatch()\n */\n this.startBatch = function() {\n _startBatch();\n };\n\n /**\n * Marks the end of a batch of application messages to be sent to the server\n * in a single request.\n * @see #startBatch()\n */\n this.endBatch = function() {\n _endBatch();\n };\n\n /**\n * Executes the given callback in the given scope, surrounded by a {@link #startBatch()}\n * and {@link #endBatch()} calls.\n * @param scope the scope of the callback, may be omitted\n * @param callback the callback to be executed within {@link #startBatch()} and {@link #endBatch()} calls\n */\n this.batch = function(scope, callback) {\n var delegate = _resolveScopedCallback(scope, callback);\n this.startBatch();\n try {\n delegate.method.call(delegate.scope);\n this.endBatch();\n } catch (x) {\n this._info('Exception during execution of batch', x);\n this.endBatch();\n throw x;\n }\n };\n\n /**\n * Adds a listener for bayeux messages, performing the given callback in the given scope\n * when a message for the given channel arrives.\n * @param channel the channel the listener is interested to\n * @param scope the scope of the callback, may be omitted\n * @param callback the callback to call when a message is sent to the channel\n * @returns the subscription handle to be passed to {@link #removeListener(object)}\n * @see #removeListener(subscription)\n */\n this.addListener = function(channel, scope, callback) {\n if (arguments.length < 2) {\n throw 'Illegal arguments number: required 2, got ' + arguments.length;\n }\n if (!_isString(channel)) {\n throw 'Illegal argument type: channel must be a string';\n }\n\n return _addListener(channel, scope, callback, true);\n };\n\n /**\n * Removes the subscription obtained with a call to {@link #addListener(string, object, function)}.\n * @param subscription the subscription to unsubscribe.\n * @see #addListener(channel, scope, callback)\n */\n this.removeListener = function(subscription) {\n // Beware of subscription.id == 0, which is falsy => cannot use !subscription.id\n if (!subscription || !subscription.channel || !(\"id\" in subscription)) {\n throw 'Invalid argument: expected subscription, not ' + subscription;\n }\n\n _removeListener(subscription);\n };\n\n /**\n * Removes all listeners registered with {@link #addListener(channel, scope, callback)} or\n * {@link #subscribe(channel, scope, callback)}.\n */\n this.clearListeners = function() {\n _listeners = {};\n };\n\n /**\n * Subscribes to the given channel, performing the given callback in the given scope\n * when a message for the channel arrives.\n * @param channel the channel to subscribe to\n * @param scope the scope of the callback, may be omitted\n * @param callback the callback to call when a message is sent to the channel\n * @param subscribeProps an object to be merged with the subscribe message\n * @param subscribeCallback a function to be invoked when the subscription is acknowledged\n * @return the subscription handle to be passed to {@link #unsubscribe(object)}\n */\n this.subscribe = function(channel, scope, callback, subscribeProps, subscribeCallback) {\n if (arguments.length < 2) {\n throw 'Illegal arguments number: required 2, got ' + arguments.length;\n }\n if (!_isString(channel)) {\n throw 'Illegal argument type: channel must be a string';\n }\n if (_isDisconnected()) {\n throw 'Illegal state: disconnected';\n }\n\n // Normalize arguments\n if (_isFunction(scope)) {\n subscribeCallback = subscribeProps;\n subscribeProps = callback;\n callback = scope;\n scope = undefined;\n }\n if (_isFunction(subscribeProps)) {\n subscribeCallback = subscribeProps;\n subscribeProps = undefined;\n }\n\n // Only send the message to the server if this client has not yet subscribed to the channel\n var send = !_hasSubscriptions(channel);\n\n var subscription = _addListener(channel, scope, callback, false);\n\n if (send) {\n // Send the subscription message after the subscription registration to avoid\n // races where the server would send a message to the subscribers, but here\n // on the client the subscription has not been added yet to the data structures\n var bayeuxMessage = {\n id: _nextMessageId(),\n channel: '/meta/subscribe',\n subscription: channel\n };\n // Do not allow the user to override important fields.\n var message = this._mixin(false, {}, subscribeProps, bayeuxMessage);\n\n // Save the callback.\n _cometd._putCallback(message.id, subscribeCallback);\n\n _queueSend(message);\n }\n\n return subscription;\n };\n\n /**\n * Unsubscribes the subscription obtained with a call to {@link #subscribe(string, object, function)}.\n * @param subscription the subscription to unsubscribe.\n * @param unsubscribeProps an object to be merged with the unsubscribe message\n * @param unsubscribeCallback a function to be invoked when the unsubscription is acknowledged\n */\n this.unsubscribe = function(subscription, unsubscribeProps, unsubscribeCallback) {\n if (arguments.length < 1) {\n throw 'Illegal arguments number: required 1, got ' + arguments.length;\n }\n if (_isDisconnected()) {\n throw 'Illegal state: disconnected';\n }\n\n if (_isFunction(unsubscribeProps)) {\n unsubscribeCallback = unsubscribeProps;\n unsubscribeProps = undefined;\n }\n\n // Remove the local listener before sending the message\n // This ensures that if the server fails, this client does not get notifications\n this.removeListener(subscription);\n\n var channel = subscription.channel;\n // Only send the message to the server if this client unsubscribes the last subscription\n if (!_hasSubscriptions(channel)) {\n var bayeuxMessage = {\n id: _nextMessageId(),\n channel: '/meta/unsubscribe',\n subscription: channel\n };\n // Do not allow the user to override important fields.\n var message = this._mixin(false, {}, unsubscribeProps, bayeuxMessage);\n\n // Save the callback.\n _cometd._putCallback(message.id, unsubscribeCallback);\n\n _queueSend(message);\n }\n };\n\n this.resubscribe = function(subscription, subscribeProps) {\n _removeSubscription(subscription);\n if (subscription) {\n return this.subscribe(subscription.channel, subscription.scope, subscription.callback, subscribeProps);\n }\n return undefined;\n };\n\n /**\n * Removes all subscriptions added via {@link #subscribe(channel, scope, callback, subscribeProps)},\n * but does not remove the listeners added via {@link addListener(channel, scope, callback)}.\n */\n this.clearSubscriptions = function() {\n _clearSubscriptions();\n };\n\n /**\n * Publishes a message on the given channel, containing the given content.\n * @param channel the channel to publish the message to\n * @param content the content of the message\n * @param publishProps an object to be merged with the publish message\n * @param publishCallback a function to be invoked when the publish is acknowledged by the server\n */\n this.publish = function(channel, content, publishProps, publishCallback) {\n if (arguments.length < 1) {\n throw 'Illegal arguments number: required 1, got ' + arguments.length;\n }\n if (!_isString(channel)) {\n throw 'Illegal argument type: channel must be a string';\n }\n if (/^\\/meta\\//.test(channel)) {\n throw 'Illegal argument: cannot publish to meta channels';\n }\n if (_isDisconnected()) {\n throw 'Illegal state: disconnected';\n }\n\n if (_isFunction(content)) {\n publishCallback = content;\n content = {};\n publishProps = undefined;\n } else if (_isFunction(publishProps)) {\n publishCallback = publishProps;\n publishProps = undefined;\n }\n\n var bayeuxMessage = {\n id: _nextMessageId(),\n channel: channel,\n data: content\n };\n // Do not allow the user to override important fields.\n var message = this._mixin(false, {}, publishProps, bayeuxMessage);\n\n // Save the callback.\n _cometd._putCallback(message.id, publishCallback);\n\n _queueSend(message);\n };\n\n /**\n * Publishes a message with binary data on the given channel.\n * The binary data chunk may be an ArrayBuffer, a DataView, a TypedArray\n * (such as Uint8Array) or a plain integer array.\n * The meta data object may contain additional application data such as\n * a file name, a mime type, etc.\n * @param channel the channel to publish the message to\n * @param data the binary data to publish\n * @param last whether the binary data chunk is the last\n * @param meta an object containing meta data associated to the binary chunk\n * @param callback a function to be invoked when the publish is acknowledged by the server\n */\n this.publishBinary = function(channel, data, last, meta, callback) {\n if (_isFunction(data)) {\n callback = data;\n data = new ArrayBuffer(0);\n last = true;\n meta = undefined;\n } else if (_isFunction(last)) {\n callback = last;\n last = true;\n meta = undefined;\n } else if (_isFunction(meta)) {\n callback = meta;\n meta = undefined;\n }\n var content = {\n meta: meta,\n data: data,\n last: last\n };\n var ext = {\n ext: {\n binary: {}\n }\n };\n this.publish(channel, content, ext, callback);\n };\n\n this.remoteCall = function(target, content, timeout, callProps, callback) {\n if (arguments.length < 1) {\n throw 'Illegal arguments number: required 1, got ' + arguments.length;\n }\n if (!_isString(target)) {\n throw 'Illegal argument type: target must be a string';\n }\n if (_isDisconnected()) {\n throw 'Illegal state: disconnected';\n }\n\n if (_isFunction(content)) {\n callback = content;\n content = {};\n timeout = _config.maxNetworkDelay;\n callProps = undefined;\n } else if (_isFunction(timeout)) {\n callback = timeout;\n timeout = _config.maxNetworkDelay;\n callProps = undefined;\n } else if (_isFunction(callProps)) {\n callback = callProps;\n callProps = undefined;\n }\n\n if (typeof timeout !== 'number') {\n throw 'Illegal argument type: timeout must be a number';\n }\n\n if (!target.match(/^\\//)) {\n target = '/' + target;\n }\n var channel = '/service' + target;\n\n var bayeuxMessage = {\n id: _nextMessageId(),\n channel: channel,\n data: content\n };\n var message = this._mixin(false, {}, callProps, bayeuxMessage);\n\n var context = {\n callback: callback\n };\n if (timeout > 0) {\n context.timeout = _cometd.setTimeout(function() {\n _cometd._debug('Timing out remote call', message, 'after', timeout, 'ms');\n _failMessage({\n id: message.id,\n error: '406::timeout',\n successful: false,\n failure: {\n message: message,\n reason: 'Remote Call Timeout'\n }\n });\n }, timeout);\n _cometd._debug('Scheduled remote call timeout', message, 'in', timeout, 'ms');\n }\n _remoteCalls[message.id] = context;\n\n _queueSend(message);\n };\n\n this.remoteCallBinary = function(target, data, last, meta, timeout, callback) {\n if (_isFunction(data)) {\n callback = data;\n data = new ArrayBuffer(0);\n last = true;\n meta = undefined;\n timeout = _config.maxNetworkDelay;\n } else if (_isFunction(last)) {\n callback = last;\n last = true;\n meta = undefined;\n timeout = _config.maxNetworkDelay;\n } else if (_isFunction(meta)) {\n callback = meta;\n meta = undefined;\n timeout = _config.maxNetworkDelay;\n } else if (_isFunction(timeout)) {\n callback = timeout;\n timeout = _config.maxNetworkDelay;\n }\n\n var content = {\n meta: meta,\n data: data,\n last: last\n };\n var ext = {\n ext: {\n binary: {}\n }\n };\n\n this.remoteCall(target, content, timeout, ext, callback);\n };\n\n /**\n * Returns a string representing the status of the bayeux communication with the Bayeux server.\n */\n this.getStatus = function() {\n return _status;\n };\n\n /**\n * Returns whether this instance has been disconnected.\n */\n this.isDisconnected = _isDisconnected;\n\n /**\n * Sets the backoff period used to increase the backoff time when retrying an unsuccessful or failed message.\n * Default value is 1 second, which means if there is a persistent failure the retries will happen\n * after 1 second, then after 2 seconds, then after 3 seconds, etc. So for example with 15 seconds of\n * elapsed time, there will be 5 retries (at 1, 3, 6, 10 and 15 seconds elapsed).\n * @param period the backoff period to set\n * @see #getBackoffIncrement()\n */\n this.setBackoffIncrement = function(period) {\n _config.backoffIncrement = period;\n };\n\n /**\n * Returns the backoff period used to increase the backoff time when retrying an unsuccessful or failed message.\n * @see #setBackoffIncrement(period)\n */\n this.getBackoffIncrement = function() {\n return _config.backoffIncrement;\n };\n\n /**\n * Returns the backoff period to wait before retrying an unsuccessful or failed message.\n */\n this.getBackoffPeriod = function() {\n return _backoff;\n };\n\n /**\n * Increases the backoff period up to the maximum value configured.\n * @returns the backoff period after increment\n * @see getBackoffIncrement\n */\n this.increaseBackoffPeriod = function() {\n return _increaseBackoff();\n };\n\n /**\n * Resets the backoff period to zero.\n */\n this.resetBackoffPeriod = function() {\n _resetBackoff();\n };\n\n /**\n * Sets the log level for console logging.\n * Valid values are the strings 'error', 'warn', 'info' and 'debug', from\n * less verbose to more verbose.\n * @param level the log level string\n */\n this.setLogLevel = function(level) {\n _config.logLevel = level;\n };\n\n /**\n * Registers an extension whose callbacks are called for every incoming message\n * (that comes from the server to this client implementation) and for every\n * outgoing message (that originates from this client implementation for the\n * server).\n * The format of the extension object is the following:\n * <pre>\n * {\n * incoming: function(message) { ... },\n * outgoing: function(message) { ... }\n * }\n * </pre>\n * Both properties are optional, but if they are present they will be called\n * respectively for each incoming message and for each outgoing message.\n * @param name the name of the extension\n * @param extension the extension to register\n * @return true if the extension was registered, false otherwise\n * @see #unregisterExtension(name)\n */\n this.registerExtension = function(name, extension) {\n if (arguments.length < 2) {\n throw 'Illegal arguments number: required 2, got ' + arguments.length;\n }\n if (!_isString(name)) {\n throw 'Illegal argument type: extension name must be a string';\n }\n\n var existing = false;\n for (var i = 0; i < _extensions.length; ++i) {\n var existingExtension = _extensions[i];\n if (existingExtension.name === name) {\n existing = true;\n break;\n }\n }\n if (!existing) {\n _extensions.push({\n name: name,\n extension: extension\n });\n this._debug('Registered extension', name);\n\n // Callback for extensions\n if (_isFunction(extension.registered)) {\n extension.registered(name, this);\n }\n\n return true;\n } else {\n this._info('Could not register extension with name', name, 'since another extension with the same name already exists');\n return false;\n }\n };\n\n /**\n * Unregister an extension previously registered with\n * {@link #registerExtension(name, extension)}.\n * @param name the name of the extension to unregister.\n * @return true if the extension was unregistered, false otherwise\n */\n this.unregisterExtension = function(name) {\n if (!_isString(name)) {\n throw 'Illegal argument type: extension name must be a string';\n }\n\n var unregistered = false;\n for (var i = 0; i < _extensions.length; ++i) {\n var extension = _extensions[i];\n if (extension.name === name) {\n _extensions.splice(i, 1);\n unregistered = true;\n this._debug('Unregistered extension', name);\n\n // Callback for extensions\n var ext = extension.extension;\n if (_isFunction(ext.unregistered)) {\n ext.unregistered();\n }\n\n break;\n }\n }\n return unregistered;\n };\n\n /**\n * Find the extension registered with the given name.\n * @param name the name of the extension to find\n * @return the extension found or null if no extension with the given name has been registered\n */\n this.getExtension = function(name) {\n for (var i = 0; i < _extensions.length; ++i) {\n var extension = _extensions[i];\n if (extension.name === name) {\n return extension.extension;\n }\n }\n return null;\n };\n\n /**\n * Returns the name assigned to this CometD object, or the string 'default'\n * if no name has been explicitly passed as parameter to the constructor.\n */\n this.getName = function() {\n return _name;\n };\n\n /**\n * Returns the clientId assigned by the Bayeux server during handshake.\n */\n this.getClientId = function() {\n return _clientId;\n };\n\n /**\n * Returns the URL of the Bayeux server.\n */\n this.getURL = function() {\n if (_transport) {\n var url = _transport.getURL();\n if (url) {\n return url;\n }\n url = _config.urls[_transport.getType()];\n if (url) {\n return url;\n }\n }\n return _config.url;\n };\n\n this.getTransport = function() {\n return _transport;\n };\n\n this.getConfiguration = function() {\n return this._mixin(true, {}, _config);\n };\n\n this.getAdvice = function() {\n return this._mixin(true, {}, _advice);\n };\n\n this.setTimeout = function(funktion, delay) {\n return _scheduler.setTimeout(function() {\n try {\n _cometd._debug('Invoking timed function', funktion);\n funktion();\n } catch (x) {\n _cometd._debug('Exception invoking timed function', funktion, x);\n }\n }, delay);\n };\n\n this.clearTimeout = function(id) {\n _scheduler.clearTimeout(id);\n };\n\n // Initialize transports.\n if (window.WebSocket) {\n this.registerTransport('websocket', new WebSocketTransport());\n }\n this.registerTransport('long-polling', new LongPollingTransport());\n this.registerTransport('callback-polling', new CallbackPollingTransport());\n };\n\n var _z85EncodeTable = [\n '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',\n 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j',\n 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't',\n 'u', 'v', 'w', 'x', 'y', 'z', 'A', 'B', 'C', 'D',\n 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N',\n 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X',\n 'Y', 'Z', '.', '-', ':', '+', '=', '^', '!', '/',\n '*', '?', '&', '<', '>', '(', ')', '[', ']', '{',\n '}', '@', '%', '$', '#'\n ];\n var _z85DecodeTable = [\n 0x00, 0x44, 0x00, 0x54, 0x53, 0x52, 0x48, 0x00,\n 0x4B, 0x4C, 0x46, 0x41, 0x00, 0x3F, 0x3E, 0x45,\n 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,\n 0x08, 0x09, 0x40, 0x00, 0x49, 0x42, 0x4A, 0x47,\n 0x51, 0x24, 0x25, 0x26, 0x27, 0x28, 0x29, 0x2A,\n 0x2B, 0x2C, 0x2D, 0x2E, 0x2F, 0x30, 0x31, 0x32,\n 0x33, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39, 0x3A,\n 0x3B, 0x3C, 0x3D, 0x4D, 0x00, 0x4E, 0x43, 0x00,\n 0x00, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F, 0x10,\n 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18,\n 0x19, 0x1A, 0x1B, 0x1C, 0x1D, 0x1E, 0x1F, 0x20,\n 0x21, 0x22, 0x23, 0x4F, 0x00, 0x50, 0x00, 0x00\n ];\n var Z85 = {\n encode: function(bytes) {\n var buffer = null;\n if (bytes instanceof ArrayBuffer) {\n buffer = bytes;\n } else if (bytes.buffer instanceof ArrayBuffer) {\n buffer = bytes.buffer;\n } else if (Array.isArray(bytes)) {\n buffer = new Uint8Array(bytes).buffer;\n }\n if (buffer == null) {\n throw 'Cannot Z85 encode ' + bytes;\n }\n\n var length = buffer.byteLength;\n var remainder = length % 4;\n var padding = 4 - (remainder === 0 ? 4 : remainder);\n var view = new DataView(buffer);\n var result = '';\n var value = 0;\n for (var i = 0; i < length + padding; ++i) {\n var isPadding = i >= length;\n value = value * 256 + (isPadding ? 0 : view.getUint8(i));\n if ((i + 1) % 4 === 0) {\n var divisor = 85 * 85 * 85 * 85;\n for (var j = 5; j > 0; --j) {\n if (!isPadding || j > padding) {\n var code = Math.floor(value / divisor) % 85;\n result += _z85EncodeTable[code];\n }\n divisor /= 85;\n }\n value = 0;\n }\n }\n\n return result;\n },\n decode: function(string) {\n var remainder = string.length % 5;\n var padding = 5 - (remainder === 0 ? 5 : remainder);\n for (var p = 0; p < padding; ++p) {\n string += _z85EncodeTable[_z85EncodeTable.length - 1];\n }\n var length = string.length;\n\n var buffer = new ArrayBuffer((length * 4 / 5) - padding);\n var view = new DataView(buffer);\n var value = 0;\n var charIdx = 0;\n var byteIdx = 0;\n for (var i = 0; i < length; ++i) {\n var code = string.charCodeAt(charIdx++) - 32;\n value = value * 85 + _z85DecodeTable[code];\n if (charIdx % 5 === 0) {\n var divisor = 256 * 256 * 256;\n while (divisor >= 1) {\n if (byteIdx < view.byteLength) {\n view.setUint8(byteIdx++, Math.floor(value / divisor) % 256);\n }\n divisor /= 256;\n }\n value = 0;\n }\n }\n\n return buffer;\n }\n };\n\n return {\n CometD: CometD,\n Transport: Transport,\n RequestTransport: RequestTransport,\n LongPollingTransport: LongPollingTransport,\n CallbackPollingTransport: CallbackPollingTransport,\n WebSocketTransport: WebSocketTransport,\n Utils: Utils,\n Z85: Z85\n };\n}));\n","const lib = require('cometd');\nmodule.exports = {\n CometD: lib.CometD,\n default: lib\n};\n","import { CometD as IsoCometD } from 'isomorphic-cometd';\nimport type {\n CometD,\n Configuration as CometDConfiguration,\n SubscriptionHandle,\n Listener as CometDListener,\n Callback as CometDCallback,\n HandshakeMessage as CometDHandshakeMessage,\n Message as CometDMessage\n} from 'cometd';\nimport { IFetchClient } from '../core';\nimport { MetaChannel } from './MetaChannel';\n\nexport interface ICometdConfig {\n url: string;\n logLevel?: string;\n requestHeaders?: any;\n appendMessageTypeToURL?: boolean;\n stickyReconnect?: boolean;\n}\n\nexport class Realtime {\n protected cometd: CometD;\n\n /**\n * Allows to set up a realtime (websocket or long-polling) connection to the platform.\n * @param client The fetch client instance to use\n * @param url The URL to connect to\n * @param handshakeCallback A function which is called on succeeded or failed handshake\n */\n constructor(\n private client: IFetchClient,\n private url: string = '/notification/realtime',\n handshakeCallback?\n ) {\n this.cometd = new IsoCometD({} as CometDConfiguration);\n // does not actually seem to be needed/supported? Just keeping to satisfy unit test snapshots\n (this.cometd as any).websocketEnabled = true;\n this.cometd.addListener(MetaChannel.HANDSHAKE, handshakeCallback || this.metaHandshake);\n }\n\n /**\n * Subscribes to a realtime channel to listen for data.\n * @param channel The channel to connect to\n * @param callback A function to call when data is received\n */\n subscribe(channel: string, callback: CometDCallback): SubscriptionHandle {\n this.checkConnection();\n return this.cometd.subscribe(channel, callback);\n }\n\n /**\n * Cancels the listening to a channel.\n * @param subscription The subscription object returned by subscribe()\n */\n unsubscribe(subscription: SubscriptionHandle): void {\n return this.cometd.unsubscribe(subscription);\n }\n\n /**\n * Allows to listen to Cometd handshake to find out if e.g. the connection was reestablished.\n */\n addHandshakeListener(callback: (msg: CometDHandshakeMessage) => void): SubscriptionHandle {\n return this.cometd.addListener(MetaChannel.HANDSHAKE, callback);\n }\n\n /**\n * Allows to listen to Cometd connection to e.g. detect when connection was lost.\n */\n addConnectListener(callback: (msg: CometDMessage) => void): SubscriptionHandle {\n return this.cometd.addListener(MetaChannel.CONNECT, callback);\n }\n\n /**\n * Removes the subscription obtained with a call to `addHandshakeListener` or `addConnectListener`.\n */\n removeListener(subscriptionHandle: SubscriptionHandle): void {\n return this.cometd.removeListener(subscriptionHandle);\n }\n\n /**\n * Resubscribes as necessary in case of a re-handshake.\n */\n resubscribe(subscriptionHandle: SubscriptionHandle): SubscriptionHandle {\n return this.cometd.resubscribe(subscriptionHandle);\n }\n\n /**\n * Disconnects the current connection.\n */\n disconnect(disconnectCallback: CometDListener = undefined): void {\n this.cometd.disconnect(disconnectCallback);\n }\n\n /**\n * Returns true if the CometD instance is disconnected or disconnecting.\n */\n isDisconnected(): boolean {\n return this.cometd.isDisconnected();\n }\n\n private checkConnection() {\n const { cometd, client, url } = this;\n if (cometd.isDisconnected()) {\n const { headers } = client.getFetchOptions();\n const config = {\n url: client.getUrl(url),\n requestHeaders: headers\n };\n cometd.configure(config);\n this.handshake(client.getCometdHandshake());\n }\n }\n\n private handshake(config: object) {\n this.cometd.handshake(config, undefined);\n }\n\n private metaHandshake = msg => {\n if (!msg.successful) {\n throw new Error('Handshake failed');\n }\n };\n}\n","import { IIdentified, Service, IResult, IResultList } from '../core';\nimport { IEvent } from './IEvent';\n\n/**\n * This class allows managing for events.\n */\nexport class EventService extends Service<IEvent> {\n protected baseUrl = 'event';\n protected listUrl = 'events';\n protected propertyName = 'events';\n protected channel = '/events/*';\n\n /**\n * Gets the details of a specific event.\n *\n * @param {string|number|IIdentified} entityOrId Entity or Id of the entity.\n *\n * @returns Response wrapped in [[IResult]]\n *\n * **Example**\n * ```typescript\n *\n * const eventId: number = 1;\n *\n * (async () => {\n * const {data, res} = await eventService.detail(eventId);\n * })();\n * ```\n */\n async detail(entityOrId: string | number | IIdentified): Promise<IResult<IEvent>> {\n return super.detail(entityOrId);\n }\n\n /**\n * Creates a new event.\n *\n * @param {IEvent} entity Event object with mandantory fragments.\n *\n * @returns Response wrapped in [[IResult]]\n *\n * **Example**\n * ```typescript\n *\n * const mandantoryObject: IEvent = {\n * source: device,\n * text: 'I am an Event!',\n * time: '2018-05-02T10:08:00Z',\n * type: 'device-type-here',\n * };\n *\n * (async () => {\n * const {data, res} = await eventService.create(mandantoryObject);\n * })();\n * ```\n */\n async create(entity: IEvent): Promise<IResult<IEvent>> {\n return super.create(entity);\n }\n\n /**\n * Updates event data.\n *\n * @param {Partial<IEvent>} entity Event is partially updatable.\n *\n * @returns Response wrapped in [[IResult]]\n *\n * **Example**\n * ```typescript\n *\n * const partialUpdateObject: Partial<IEvent> = {\n * source: device,\n * text: 'Changed Event!'\n * };\n *\n * (async () => {\n * const {data, res} = await eventService.update(partialUpdateObject);\n * })();\n * ```\n */\n async update(entity: Partial<IEvent>): Promise<IResult<IEvent>> {\n return super.update(entity);\n }\n\n /**\n * Gets the list of events filtered by parameters.\n *\n * @returns Response wrapped in [[IResultList]]\n *\n * @param {object} filter Object containing filters for querying events.\n *\n * **Example**\n * ```typescript\n *\n * const filter: object = {\n * pageSize: 100,\n * withTotalPages: true\n * };\n *\n * (async () => {\n * const {data, res, paging} = await eventService.list(filter);\n * })();\n * ```\n */\n async list(filter: object = {}): Promise<IResultList<IEvent>> {\n return super.list(filter);\n }\n\n /**\n * Removes an event with given id.\n *\n * @returns Response wrapped in [[IResult]]\n *\n * @param {string | number | IIdentified} entityOrId entity or id of the event.\n *\n * **Example**\n * ```typescript\n *\n * const eventId: number = 1;\n *\n * (async () => {\n * const {data, res} = await eventService.delete(eventId);\n * // data will be null\n * })();\n * ```\n */\n async delete(entityOrId: string | number | IIdentified): Promise<IResult<null>> {\n return super.delete(entityOrId);\n }\n}\n","/* eslint-env browser */\nmodule.exports = typeof self == 'object' ? self.FormData : window.FormData;\n","import { Service, IIdentified, IResult, ISource, IResultList } from '../core';\nimport { IUserGroup } from './IUserGroup';\nimport { IRoleReference } from '../user-role';\nimport { IUserReference } from '../user';\n\nenum ChildType {\n ROLES = 'roles',\n USERS = 'users'\n}\n\n/**\n * @description\n * This service allows for managing user groups.\n */\nexport class UserGroupService extends Service<IUserGroup> {\n protected baseUrl = 'user';\n protected propertyName = 'groups';\n\n protected get listUrl() {\n return `${this.client.tenant}/groups`;\n }\n\n /**\n * Gets the details of given user group.\n *\n * @param {string|number|IUserGroup} entityOrId Group's id or role object.\n *\n * @returns Returns promise object that is resolved with the IUserGroup wrapped by IResult.\n *\n * **Example**\n * ```typescript\n *\n * const groupId: number = 1;\n *\n * (async () => {\n * const {data, res} = await userGroupService.detail(roleId);\n * })();\n * ```\n */\n async detail(entityOrId: string | number | IUserGroup): Promise<IResult<IUserGroup>> {\n return super.detail(entityOrId);\n }\n\n /**\n * Creates a new user group.\n *\n * @param {IUserGroup} entity User Group object.\n *\n * @returns {IResult<IUserGroup>} Returns promise object that is resolved with\n * the details of newly created user group.\n *\n * **Example**\n * ```typescript\n *\n * const userGroupObject: IUserGroup = {\n * name: \"new user group\"\n * };\n *\n * (async () => {\n * const {data, res} = await userGroupService.create(userGroupObject);\n * })();\n * ```\n */\n async create(entity: Partial<IUserGroup>): Promise<IResult<IUserGroup>> {\n return super.create(entity);\n }\n\n /**\n * Updates user group data.\n *\n * @param {Partial<IUserGroup>} entity User group is partially updatable.\n *\n * @returns {IResult<IUserGroup>} Returns promise object that is resolved with the saved user group object.\n *\n * **Example**\n * ```typescript\n *\n * const partialUpdateObject: Partial<IUserGroup> = {\n * \"id\" : 1,\n * \"self\" : \"[URL to this resource]\",\n * \"name\" : \"PlatformAdministrators\",\n * ...\n * }\n *\n * (async () => {\n * const {data, res} = await userGroupService.update(partialUpdateObject);\n * })();\n * ```\n */\n async update(entity: Partial<IUserGroup>): Promise<IResult<IUserGroup>> {\n return super.update(entity);\n }\n\n /**\n * Gets the list of user groups filtered by parameters.\n *\n * @param {object} filter Object containing filters for querying User Groups.\n *\n * @returns Returns promise object that is resolved with the IUserGroup wrapped by IResultList.\n *\n * **Example**\n * ```typescript\n *\n * const filter: object = {\n * severity: Severity.MAJOR,\n * pageSize: 100,\n * withTotalPages: true\n * };\n *\n * (async () => {\n * const {data, res, paging} = await userGroupService.list(filter);\n * })();\n * ```\n */\n async list(filter: object = {}): Promise<IResultList<IUserGroup>> {\n return super.list(filter);\n }\n\n /**\n * Removes user group.\n *\n * @param {number | IIdentified} entityOrId User group's id or user group object.\n *\n * @returns Returns promise object that is resolved with the IResult of null.\n *\n * **Example**\n * ```typescript\n *\n * const userGroupId: number = 1;\n *\n * (async () => {\n * const {data, res} = await userGroupService.delete(userGroupId);\n * })();\n * ```\n * When group is removed, suitable audit records are created with type 'User'\n * and activity 'User updated' with information that user has been removed from group.\n *\n * Please, note that the ADMINS and DEVICES groups can not be deleted.\n */\n async delete(entityOrId: number | IIdentified): Promise<IResult<null>> {\n return super.delete(entityOrId);\n }\n\n /**\n * Assign role to user group.\n *\n * @param {string | number | Partial<IUserGroup>} entityOrId User group's id or user group object.\n * @param {string | Partial<ISource>} childEntityOrSelf Url to role resource or IRoleReference object.\n *\n * @returns Returns promise object that is resolved with the IRoleReference wrapped by IResult.\n *\n * **Example**\n * ```typescript\n *\n * const userGroupId: number = 1;\n * const roleResource: string = \"[URL to the Role resource]\";\n *\n * (async () => {\n * const {data, res} = await userGroupService.addRoleToGroup(userGroupId, roleResource);\n * })();\n * ```\n * When role is assigned to user, suitable audit record is created with type 'User' and activity 'User updated'.\n */\n async addRoleToGroup(\n entityOrId: string | number | Partial<IUserGroup>,\n childEntityOrSelf: string | Partial<ISource>\n ): Promise<IResult<IRoleReference>> {\n return this.addChild(ChildType.ROLES, entityOrId, childEntityOrSelf) as Promise<\n IResult<IRoleReference>\n >;\n }\n\n /**\n * Unassign role from user\n *\n * @param {string | number | Partial<IUserGroup>} entityOrId User group's id or user group object.\n * @param {string | Partial<ISource>} childEntityOrSelf Url to user resource or IRoleReference object.\n *\n * @returns Returns promise object that is resolved with the IResult of null.\n *\n * **Example**\n * ```typescript\n *\n * const userGroupId: number = 1;\n * const userResource: string = \"[URL to the Role resource]\";\n *\n * (async () => {\n * const {data, res} = await userGroupService.removeRoleFromGroup(userGroupId, userResource);\n * })();\n * ```\n */\n async removeRoleFromGroup(\n entityOrId: string | number | Partial<IUserGroup>,\n childEntityOrSelf: string | Partial<ISource>\n ): Promise<IResult<null>> {\n return this.removeChild(ChildType.ROLES, entityOrId, childEntityOrSelf);\n }\n\n /**\n * Assign user to user group.\n *\n * @param {string | number | Partial<IUserGroup>} entityOrId User group's id or user group object.\n * @param {string | Partial<ISource>} childEntityOrSelf Url to user resource or IUserReference object.\n *\n * @returns Returns promise object that is resolved with the IUserReference wrapped by IResult.\n *\n * **Example**\n * ```typescript\n *\n * const userGroupId: number = 1;\n * const userResource: string = \"[URL to the User resource]\";\n *\n * (async () => {\n * const {data, res} = await userGroupService.addUserToGroup(userGroupId, userResource);\n * })();\n * ```\n * When user is added to group, suitable audit record is created with type 'User' and activity 'User updated'.\n */\n async addUserToGroup(\n entityOrId: string | number | Partial<IUserGroup>,\n childEntityOrSelf: string | Partial<ISource>\n ): Promise<IResult<IUserReference>> {\n return this.addChild(ChildType.USERS, entityOrId, childEntityOrSelf) as Promise<\n IResult<IUserReference>\n >;\n }\n\n /**\n * Remove user from a group\n *\n * @param {string | number | Partial<IUserGroup>} entityOrId User group's id or user group object.\n * @param {string | Partial<ISource>} childEntityOrSelf Url to user resource or IUserReference object.\n *\n * @returns Returns promise object that is resolved with the IResult of null.\n *\n * **Example**\n * ```typescript\n *\n * const userGroupId: number = 1;\n * const userResource: string = \"[URL to the User resource]\";\n *\n * (async () => {\n * const {data, res} = await userGroupService.removeUserFromGroup(userGroupId, userResource);\n * })();\n * ```\n * When user is removed from group, suitable audit record is created with type 'User' and activity 'User updated'.\n */\n async removeUserFromGroup(\n entityOrId: string | number | Partial<IUserGroup>,\n childEntityOrSelf: string | Partial<ISource>\n ): Promise<IResult<null>> {\n return this.removeChild(ChildType.USERS, entityOrId, childEntityOrSelf);\n }\n\n protected getSelf(childReference: string | Partial<ISource>): string {\n if (typeof childReference === 'object' && childReference.self) {\n return childReference.self;\n } else {\n return childReference as string;\n }\n }\n\n private getChildUrl(\n type: ChildType,\n userGroupOrId: string | number | Partial<IUserGroup>\n ): string {\n return `${this.getDetailUrl(userGroupOrId)}/${type}`;\n }\n\n private getChildReferenceAsBody(type: ChildType, childReference: string | Partial<ISource>) {\n const childSelf = this.getSelf(childReference);\n switch (type) {\n case ChildType.ROLES:\n return JSON.stringify({ role: { self: String(childSelf) } });\n case ChildType.USERS:\n return JSON.stringify({ user: { self: String(childSelf) } });\n }\n throw new Error('UserGroupService -> getChild -> unsupported child type');\n }\n\n private async addChild(\n type: ChildType,\n userGroupOrId: string | number | Partial<IUserGroup>,\n childReference: string | Partial<ISource>\n ): Promise<IResult<IUserReference | IRoleReference>> {\n const url = this.getChildUrl(type, userGroupOrId);\n const method = 'POST';\n const body = this.getChildReferenceAsBody(type, childReference);\n const headers = {\n accept: 'application/json',\n 'content-type': 'application/json'\n };\n const res = await this.fetch(url, { method, body, headers });\n let data = await res.json();\n data = data.managedObject;\n return { res, data };\n }\n\n private async removeChild(\n type: ChildType,\n userGroupOrId: string | number | Partial<IUserGroup>,\n childReference: string | IIdentified\n ): Promise<IResult<null>> {\n const childId = this.getIdString(childReference);\n const url = `${this.getChildUrl(type, userGroupOrId)}/${encodeURIComponent(String(childId))}`;\n const method = 'DELETE';\n const headers = { accept: 'application/json' };\n const res = await this.fetch(url, { method, headers });\n const data = null;\n return { res, data };\n }\n}\n","import FormData from 'form-data';\nimport { Stream } from 'stream';\nimport { Service, IResult, IFetchResponse } from '../core';\nimport { IEvent } from './IEvent';\nimport { IEventBinary } from './IEventBinary';\n\nexport class EventBinaryService extends Service<IEventBinary> {\n protected baseUrl = 'event';\n protected listUrl = 'events';\n\n /**\n * Uploads an event binary.\n * @returns Response wrapped in [[IResult]]\n *\n * @param {Stream | Buffer | File | Blob} file file to upload.\n * @param {string | number | IEvent} eventOrId Event or Id of the Event.\n *\n * **Example**\n * ```typescript\n *\n * const file = Buffer.from('aaa');\n * const eventId: string | number = 123;\n *\n * (async () => {\n * const {data, res} = await eventBinaryService.upload(file, eventId);\n * })();\n * ```\n */\n async upload(\n file: Stream | Buffer | File | Blob,\n entityOrId: string | number | IEvent\n ): Promise<IResult<IEventBinary>> {\n const method = 'POST';\n const url = this.getDetailUrl(entityOrId);\n const body = new FormData();\n\n body.append('file', file);\n const headers = {\n accept: 'application/json'\n };\n const res = await this.fetch(url, { method, body, headers });\n const data = await res.json();\n return { res, data };\n }\n\n /**\n * Downloads the binary for a given event.\n * @returns Response wrapped in [[IFetchResponse]]\n *\n * @param {string | number | IEvent} eventOrId Event or Id of the Event.\n *\n * **Example**\n * ```typescript\n *\n * const eventId: string | number = 123;\n *\n * (async () => {\n * const res = await eventBinaryService.download(eventId);\n * })();\n */\n async download(entityOrId: string | number | IEvent): Promise<IFetchResponse> {\n const url = this.getDetailUrl(entityOrId);\n return await this.fetch(url);\n }\n\n /**\n * Removes the binary for a given event.\n * @returns Response wrapped in [[IResult]]\n *\n * @param {string | number | IEvent} eventOrId Event or Id of the Event.\n *\n * **Example**\n * ```typescript\n *\n * const eventId: string | number = 123;\n *\n * (async () => {\n * const {data, res} = await eventBinaryService.delete(eventId);\n * })();\n * ```\n */\n async delete(entityOrId: string | number | IEvent) {\n return super.delete(entityOrId);\n }\n\n protected getDetailUrl(entityOrId: string | number | IEvent): string {\n let id: string | number;\n if (typeof entityOrId === 'object' && entityOrId.id) {\n id = entityOrId.id;\n } else {\n id = entityOrId as string;\n }\n return `${this.listUrl}/${id}/binaries`;\n }\n}\n","import FormData from 'form-data';\nimport { Stream } from 'stream';\nimport { Service, IResult, IFetchResponse, IFetchOptions } from '../core';\nimport { IdReference } from './InventoryService';\nimport { IManagedObject, IManagedObjectBinary } from './IManagedObject';\n\nexport class InventoryBinaryService extends Service<IManagedObjectBinary> {\n protected baseUrl = 'inventory';\n protected listUrl = 'binaries';\n protected propertyName = 'managedObjects';\n\n /**\n * Uploads a file and creates a managed object with its metadata.\n * @param file A file to be uploaded.\n * @param managedObject An object containing metadata about the file.\n * Note that you can specify `fileType` and `fileName` in case `file` does not define them\n * but these two properties will be removed from `managedObject` before saving.\n */\n async create(\n file: Stream | Buffer | File | Blob,\n managedObject: Partial<IManagedObject> = {}\n ): Promise<IResult<IManagedObjectBinary>> {\n const method = 'POST';\n const url = this.listUrl;\n const body = new FormData();\n let fileName;\n let fileType;\n if (managedObject.fileName) {\n fileName = managedObject.fileName;\n delete managedObject.fileName;\n }\n if (managedObject.fileType) {\n fileType = managedObject.fileType;\n delete managedObject.fileType;\n }\n if (!fileName) {\n fileName = 'bin';\n }\n if (typeof File !== 'undefined' && file instanceof File) {\n fileName = file.name;\n fileType = file.type;\n }\n if (!managedObject.name) {\n managedObject.name = fileName;\n }\n if (!managedObject.type) {\n managedObject.type = fileType || 'c8y_upload';\n }\n body.append('file', file, fileName);\n body.append('object', JSON.stringify(managedObject));\n const headers = {\n accept: 'application/json'\n };\n const res = await this.fetch(url, { method, body, headers });\n const data = await res.json();\n return { res, data };\n }\n\n async list(filter: object = {}) {\n return super.list(filter);\n }\n\n async delete(managedObjectOrId: IdReference) {\n return super.delete(managedObjectOrId);\n }\n\n async download(managedObjectOrId: IdReference, init?: IFetchOptions): Promise<IFetchResponse> {\n const url = this.getDetailUrl(managedObjectOrId);\n return await this.fetch(url, init);\n }\n\n /**\n * Uploads a file and creates a managed object with its metadata. What's more, it invokes an upload progress callback.\n * @param file A file to be uploaded.\n * @param managedObject An object containing metadata about the file.\n * @param onProgress Event handler for progress update, invoked while the browser is uploading the file.\n */\n createWithProgress(\n file: Stream | Buffer | File | Blob,\n onProgress: EventListener,\n managedObject: Partial<IManagedObject> = {}\n ): XMLHttpRequest {\n const url = `/${this.baseUrl}/${this.listUrl}`;\n const method = 'POST';\n const body = new FormData();\n let fileName;\n let fileType;\n if (managedObject.fileName) {\n fileName = managedObject.fileName;\n delete managedObject.fileName;\n }\n if (managedObject.fileType) {\n fileType = managedObject.fileType;\n delete managedObject.fileType;\n }\n if (!fileName) {\n fileName = 'bin';\n }\n if (typeof File !== 'undefined' && file instanceof File) {\n fileName = file.name;\n fileType = file.type;\n }\n if (!managedObject.name) {\n managedObject.name = fileName;\n }\n if (!managedObject.type) {\n managedObject.type = fileType || 'c8y_upload';\n }\n body.append('file', file, fileName);\n body.append('object', JSON.stringify(managedObject));\n let bodyHeaders;\n\n if (typeof body.getHeaders === 'function') {\n bodyHeaders = body.getHeaders();\n }\n const headers = this.client.getFetchOptions().headers;\n Object.assign(\n headers,\n {\n accept: 'application/json'\n },\n bodyHeaders\n );\n\n const xhr = new XMLHttpRequest();\n xhr.open(method, url, true);\n for (const key in headers) {\n if (headers.hasOwnProperty(key)) {\n xhr.setRequestHeader(key, headers[key]);\n }\n }\n xhr.upload.addEventListener('progress', onProgress);\n\n let xhrBody: XMLHttpRequestBodyInit;\n if (typeof body.getBuffer === 'function') {\n xhrBody = body.getBuffer();\n } else {\n xhrBody = body as any;\n }\n xhr.send(xhrBody);\n\n return xhr;\n }\n\n getXMLHttpResponse(xhr): Promise<IResult<IManagedObjectBinary>> {\n return new Promise((res, rej) => {\n xhr.addEventListener('loadend', () => {\n xhr.readyState === 4 && (xhr.status === 200 || xhr.status === 201)\n ? res(JSON.parse(xhr.responseText))\n : rej(\n xhr.responseText ? { data: JSON.parse(xhr.responseText) } : 'Could not upload file.'\n );\n });\n });\n }\n\n /**\n * Gets binary managed object's id from its download or self URL.\n *\n * @param {string} url URL string.\n *\n * @returns {number} Binary managed object's id.\n *\n * **Example**\n * ```typescript\n *\n * const id = InventoryBinaryService.getIdFromUrl('http://mytenant.cumulocity.com/inventory/binaries/12345');\n * ```\n */\n getIdFromUrl(url: string): string {\n if (!!url) {\n const regexp = new RegExp(\n '\\\\/inventory\\\\/binaries\\\\/(\\\\d+)|\\\\/inventory\\\\/managedObjects\\\\/(\\\\d+)'\n );\n const matches = url.match(regexp);\n return matches && (matches[1] || matches[2]);\n }\n }\n}\n","import { IIdentified, Service, IResult, IResultList, IFetchClient, QueriesUtil } from '../core';\nimport { IManagedObject } from './IManagedObject';\nimport { InventoryBinaryService } from './InventoryBinaryService';\n\nimport { Realtime } from '../realtime';\n\n/**\n * Possible types of a child.\n */\nexport enum ChildType {\n ASSETS = 'childAssets',\n DEVICES = 'childDevices',\n ADDITIONS = 'childAdditions'\n}\n\n/**\n * IdReference is only a combined type of string | number | IIdentified\n */\nexport type IdReference = string | number | IIdentified;\n\n/**\n * This class allows for managing managed objects and different child types, see [[ChildType]].\n */\nexport class InventoryService extends Service<IManagedObject> {\n binary: InventoryBinaryService;\n queriesUtil: QueriesUtil;\n protected baseUrl = 'inventory';\n protected listUrl = 'managedObjects';\n protected propertyName = 'managedObjects';\n protected channel = '/managedobjects/*';\n protected inventoriesQueryParamName = 'query';\n protected devicesQueryParamName = 'q';\n\n constructor(client: IFetchClient, realtime?: Realtime) {\n super(client, realtime);\n this.queriesUtil = new QueriesUtil();\n this.binary = new InventoryBinaryService(client);\n }\n\n /**\n * Gets the details of managed object\n *\n * @param {IdReference} managedObjectOrId ManagedObject or Id of the ManagedObject.\n * @param {object} filter Filter object.\n *\n * @returns Response wrapped in [[IResult]]\n *\n * **Example**\n * ```typescript\n *\n * const managedObjId: number = 1;\n * const filter = { withChildren: false };\n *\n * (async () => {\n * const {data, res} = await inventoryService.detail(managedObjId, filter);\n * })();\n * ```\n */\n async detail(managedObjectOrId: IdReference, filter: object = {}) {\n return super.detail(managedObjectOrId, filter);\n }\n\n /**\n * Creates a new managed object.\n *\n * @param {Partial<IManagedObject>} managedObject\n *\n * @returns Response wrapped in [[IResult]]\n *\n * **Example**\n * ```typescript\n *\n * const partialManagedObj: Partial<IManagedObject> = {\n * customFragment: 'yourData'\n * };\n *\n * (async () => {\n * const {data, res} = await inventoryService.create(partialManagedObj);\n * })();\n * ```\n */\n async create(managedObject: Partial<IManagedObject>) {\n return super.create(managedObject);\n }\n\n /**\n * Updates managed object data.\n *\n * @param {Partial<IManagedObject>} managedObject Managed object is partially updatable.\n *\n * @returns Response wrapped in [[IResult]]\n *\n * **Example**\n * ```typescript\n *\n * const partialUpdateObject: Partial<IManagedObject> = {\n * customFragment: 'Changed data',\n * name: 'Name'\n * };\n *\n * (async () => {\n * const {data, res} = await inventoryService.update(partialUpdateObject);\n * })();\n * ```\n */\n async update(managedObject: Partial<IManagedObject>) {\n return super.update(managedObject);\n }\n\n /**\n * Gets the list of managed objects filtered by parameters.\n *\n * @returns Response wrapped in [[IResultList]]\n *\n * @param {object} filter Object containing filters for querying managed objects.\n *\n * **Example**\n * ```typescript\n *\n * const filter: object = {\n * pageSize: 100,\n * withTotalPages: true\n * };\n *\n * (async () => {\n * const {data, res, paging} = await inventoryService.list(filter);\n * })();\n * ```\n */\n async list(filter: object = {}) {\n return super.list(filter);\n }\n\n /**\n * Gets the list of all managed objects filtered and sorted by given query.\n *\n * @returns Response wrapped in [[IResultList]]\n *\n * @param {object} filter Object containing filters for querying managed objects.\n *\n * **Example**\n * ```typescript\n *\n * const filter: object = {\n * pageSize: 100,\n * withTotalPages: true\n * };\n *\n * const query = {\n * name: 'MY-NAM*'\n * }\n *\n * (async () => {\n * const {data, res, paging} = await inventoryService.listQuery(query, filter);\n * })();\n * ```\n */\n async listQuery(query, filter: object = {}) {\n filter[this.inventoriesQueryParamName] = this.queriesUtil.buildQuery(query);\n return super.list(filter);\n }\n\n /**\n * Gets the list of all devices filtered and sorted by given query.\n *\n * @returns Response wrapped in [[IResultList]]\n *\n * @param {object} filter Object containing filters for querying devices.\n *\n * **Example**\n * ```typescript\n *\n * const filter: object = {\n * pageSize: 100,\n * withTotalPages: true\n * };\n *\n * const query = {\n * name: 'MY-NAM*'\n * }\n *\n * (async () => {\n * const {data, res, paging} = await inventoryService.listQueryDevices(query, filter);\n * })();\n * ```\n */\n async listQueryDevices(query, filter: object = {}) {\n filter[this.devicesQueryParamName] = this.queriesUtil.buildQuery(query);\n return super.list(filter);\n }\n\n /**\n * Removes managed object with given id.\n *\n * @returns Response wrapped in [[IResult]]\n *\n * @param {IdReference} managedObjectOrId ManagedObject or Id of the ManagedObject.\n * @param {object} params Additional query params.\n *\n * **Example**\n * ```typescript\n *\n * const managedObjectId: number = 1;\n * const params: any = {\n * cascade: true\n * }\n *\n * (async () => {\n * const {data, res} = await inventoryService.delete(managedObjectId, params);\n * })();\n * ```\n */\n async delete(managedObjectOrId: IdReference, params: any = {}) {\n return super.delete(managedObjectOrId, params);\n }\n\n /**\n * Gets a list of child additions from a given managed object (parent)\n *\n * @returns Response wrapped in [[IResultList]]\n *\n * @param {IdReference} parentReference\n * @param {object} filter\n *\n * **Example**\n * ```typescript\n * const parentReferenceId: IdReference = 1;\n *\n * const filter: object = {\n * pageSize: 100,\n * withTotalPages: true\n * };\n *\n * (async () => {\n * const {data, res, paging} = await inventoryService.childAdditionsList(parentReferenceId, filter);\n * })();\n * ```\n */\n async childAdditionsList(parentReference: IdReference, filter: object = {}) {\n return this.listChildren(ChildType.ADDITIONS, parentReference, filter);\n }\n\n /**\n * Creates a new managed object as child addition to another managed object (parent)\n *\n * @returns Response wrapped in [[IResult]]\n *\n * @param {Partial<IManagedObject>} managedObject\n * @param {IdReference} parentReference\n *\n * **Example**\n * ```typescript\n *\n * const mOAsChildAddition: Partial<IManagedObject> = {\n * name: 'Child addition MO',\n * type: 'new type',\n * ...\n * };\n *\n * // This is the identifier of the managed object which should be the parent of\n * // mOAsChildAddition, see above.\n * const parentReferenceId: number = 1;\n *\n * (async () => {\n * const {data, res} = await inventoryService.childAdditionsCreate(mOAsChildAddition, parentReferenceId);\n * })();\n * ```\n */\n async childAdditionsCreate(managedObject: Partial<IManagedObject>, parentReference: IdReference) {\n return this.createChild(ChildType.ADDITIONS, managedObject, parentReference);\n }\n\n /**\n * Adds an existing managed object as child addition to another managed object (parent)\n *\n * @returns Response wrapped in [[IResult]]\n *\n * @param {IdReference} childReference\n * @param {IdReference} parentReference\n *\n * **Example**\n * ```typescript\n *\n * const childRef: number = 2;\n * const parentReferenceId: number = 1;\n *\n * (async () => {\n * const {data, res} = await inventoryService.childAdditionsCreate(childRef, parentReferenceId);\n * })();\n * ```\n */\n async childAdditionsAdd(childReference: IdReference, parentReference: IdReference) {\n return this.addChild(ChildType.ADDITIONS, childReference, parentReference);\n }\n\n /**\n * Removes an existing managed object as child addition from another managed object (parent)\n *\n * @returns Response wrapped in [[IResult]]\n *\n * @param {IdReference} childReference\n * @param {IdReference} parentReference\n *\n * **Example**\n * ```typescript\n *\n * const childRef: number = 2;\n * const parentReferenceId: number = 1;\n *\n * (async () => {\n * const {data, res} = await inventoryService.childAdditionsRemove(childRef, parentReferenceId);\n * })();\n * ```\n */\n async childAdditionsRemove(childReference: IdReference, parentReference: IdReference) {\n return this.removeChild(ChildType.ADDITIONS, childReference, parentReference);\n }\n\n /**\n * Gets a list of child assets from a given managed object (parent)\n *\n * @returns Response wrapped in [[IResultList]]\n *\n * @param {IdReference} parentReference\n * @param {object} filter\n *\n * **Example**\n * ```typescript\n *\n * const parentReferenceId: IdReference = 1;\n *\n * const filter: object = {\n * pageSize: 100,\n * withTotalPages: true\n * };\n *\n * (async () => {\n * const {data, res, paging} = await inventoryService.childAssetsList(parentReferenceId, filter);\n * })();\n * ```\n */\n async childAssetsList(parentReference: IdReference, filter: object = {}) {\n return this.listChildren(ChildType.ASSETS, parentReference, filter);\n }\n\n /**\n * Creates a new managed object as child asset to another managed object (parent)\n *\n * @returns Response wrapped in [[IResult]]\n *\n * @param {Partial<IManagedObject>} managedObject\n * @param {IdReference} parentReference\n *\n * **Example**\n * ```typescript\n *\n * const mOAsChildAsset: Partial<IManagedObject> = {\n * name: 'Child asset MO',\n * type: 'new type',\n * ...\n * };\n *\n * // This is the identifier of the managed object which should be the parent of\n * // mOAsChildAsset, see above.\n * const parentReferenceId: number = 1;\n *\n * (async () => {\n * const {data, res} = await inventoryService.childAdditionsCreate(mOAsChildAddition, parentReferenceId);\n * })();\n * ```\n */\n async childAssetsCreate(managedObject: Partial<IManagedObject>, parentReference: IdReference) {\n return this.createChild(ChildType.ASSETS, managedObject, parentReference);\n }\n\n /**\n * Adds an existing managed object as child asset to another managed object (parent)\n *\n * @returns Response wrapped in [[IResult]]\n *\n * @param {IdReference} childReference\n * @param {IdReference} parentReference\n *\n * **Example**\n * ```typescript\n *\n * const childRef: number = 2;\n * const parentReferenceId: number = 1;\n *\n * (async () => {\n * const {data, res} = await inventoryService.childAssetsAdd(childRef, parentReferenceId);\n * })();\n * ```\n */\n async childAssetsAdd(childReference: IdReference, parentReference: IdReference) {\n return this.addChild(ChildType.ASSETS, childReference, parentReference);\n }\n /**\n * Adds bulk of existing managed objects as child assets to another managed object (parent).\n *\n * @returns Response wrapped in array of [[IResult]]\n *\n * @param {IdReference[]} childReference List of existing managed objects IDs that should be added to another managed object (parent).\n * @param {IdReference} parentReference\n *\n * **Example**\n * ```typescript\n *\n * const childAssetsRefIds: string[] = ['2', '3'];\n * const parentReferenceId: number = 1;\n *\n * (async () => {\n * const {data, res} = await inventoryService.childAssetsBulkAdd(childAssetsRefIds, parentReferenceId);\n * })();\n * ```\n */\n async childAssetsBulkAdd(childReference: IdReference[], parentReference: IdReference) {\n return this.addChildBulk(ChildType.ASSETS, childReference, parentReference);\n }\n\n /**\n * Removes an existing managed object as child asset from another managed object (parent)\n *\n * @returns Response wrapped in [[IResult]]\n *\n * @param {IdReference} childReference\n * @param {IdReference} parentReference\n *\n * **Example**\n * ```typescript\n *\n * const childRef: number = 2;\n * const parentReferenceId: number = 1;\n *\n * (async () => {\n * const {data, res} = await inventoryService.childAssetsRemove(childRef, parentReferenceId);\n * })();\n * ```\n */\n async childAssetsRemove(childReference: IdReference, parentReference: IdReference) {\n return this.removeChild(ChildType.ASSETS, childReference, parentReference);\n }\n\n /**\n * Gets a list of child devices from a given managed object (parent)\n *\n * @returns Response wrapped in [[IResultList]]\n *\n * @param {IdReference} parentReference\n * @param {object} filter\n *\n * **Example**\n * ```typescript\n *\n * const parentReferenceId: IdReference = 1;\n *\n * const filter: object = {\n * pageSize: 100,\n * withTotalPages: true\n * };\n *\n * (async () => {\n * const {data, res, paging} = await inventoryService.childDevicesList(parentReferenceId, filter);\n * })();\n * ```\n */\n async childDevicesList(parentReference: IdReference, filter: object = {}) {\n return this.listChildren(ChildType.DEVICES, parentReference, filter);\n }\n\n /**\n * Creates a new managed object as child device to another managed object (parent)\n *\n * @returns Response wrapped in [[IResult]]\n *\n * @param {Partial<IManagedObject>} managedObject\n * @param {IdReference} parentReference\n *\n * **Example**\n * ```typescript\n *\n * const mOAsChildDevice: Partial<IManagedObject> = {\n * name: 'Child device MO',\n * type: 'new type',\n * ...\n * };\n *\n * // This is the identifier of the managed object which should be the parent of\n * // mOAsChildDevice, see above.\n * const parentReferenceId: number = 1;\n *\n * (async () => {\n * const {data, res} = await inventoryService.childDevicesCreate(mOAsChildDevice, parentReferenceId);\n * })();\n * ```\n */\n async childDevicesCreate(managedObject: Partial<IManagedObject>, parentReference: IdReference) {\n return this.createChild(ChildType.DEVICES, managedObject, parentReference);\n }\n\n /**\n * Adds an existing managed object as child device to another managed object (parent)\n *\n * @returns Response wrapped in [[IResult]]\n *\n * @param {IdReference} childReference\n * @param {IdReference} parentReference\n *\n * **Example**\n * ```typescript\n *\n * const childRef: number = 2;\n * const parentReferenceId: number = 1;\n *\n * (async () => {\n * const {data, res} = await inventoryService.childDevicesAdd(childRef, parentReferenceId);\n * })();\n * ```\n */\n async childDevicesAdd(childReference: IdReference, parentReference: IdReference) {\n return this.addChild(ChildType.DEVICES, childReference, parentReference);\n }\n\n /**\n * Removes an existing managed object as child device from another managed object (parent)\n *\n * @returns Response wrapped in [[IResult]]\n *\n * @param {IdReference} childReference\n * @param {IdReference} parentReference\n *\n * **Example**\n * ```typescript\n *\n * const childRef: number = 2;\n * const parentReferenceId: number = 1;\n *\n * (async () => {\n * const {data, res} = await inventoryService.childDevicesRemove(childRef, parentReferenceId);\n * })();\n * ```\n */\n async childDevicesRemove(childReference: IdReference, parentReference: IdReference) {\n return this.removeChild(ChildType.DEVICES, childReference, parentReference);\n }\n\n /**\n * Gets an array of measurement fragments supported by the specified managedObject.\n * e.g. [\"c8y_Temperature\", \"c8y_Humidity\"]\n *\n * @returns array of supported measurement fragments\n *\n * @param {IdReference} managedObjectOrId\n */\n async getSupportedMeasurements(managedObjectOrId: IdReference): Promise<string[]> {\n return this.getSupportedMeasurementDetails(managedObjectOrId, 'supportedMeasurements');\n }\n\n /**\n * Gets an array of measurement series supported by the specified managedObject.\n * e.g. [\"c8y_Temperature.T\", \"c8y_Humidity.H\"]\n *\n * @returns array of supported measurement series\n *\n * @param {IdReference} managedObjectOrId\n */\n async getSupportedSeries(managedObjectOrId: IdReference): Promise<string[]> {\n return this.getSupportedMeasurementDetails(managedObjectOrId, 'supportedSeries');\n }\n\n /**\n * Gets an array of measurement series and fragments supported by the specified managedObject.\n *\n * @returns array of supported measurement series and fragments\n *\n * @param {IdReference} managedObjectOrId\n */\n async getMeasurementsAndSeries(managedObjectOrId: IdReference): Promise<\n Array<{\n fragment: string;\n series: string;\n }>\n > {\n const [supportedMeasurements, supportedSeries] = await Promise.all([\n this.getSupportedMeasurements(managedObjectOrId),\n this.getSupportedSeries(managedObjectOrId)\n ]);\n\n // sort by longest measurement fragment first\n const sortedSupportedMeasurements = supportedMeasurements.sort((a, b) => b.length - a.length);\n\n return supportedSeries\n .map(s => {\n const fragment = sortedSupportedMeasurements.find(m => s.indexOf(`${m}.`) === 0);\n const series = s.replace(`${fragment}.`, '');\n return {\n fragment,\n series\n };\n })\n .filter(obj => !!obj.fragment);\n }\n\n /**\n * Gets a list of KPIs (data point library entries) matching a given managed object\n *\n * @returns Response wrapped in [[IResultList]]\n *\n * @param {IdReference} parentReference\n * @param {object} filter\n */\n async assetKPIsList(parentReference: IdReference, filter: object = {}) {\n return this.listKPIs(parentReference, filter);\n }\n\n protected async listKPIs(\n parentReference: IdReference,\n filter: object = {}\n ): Promise<IResultList<IManagedObject>> {\n const headers = { accept: 'application/json' };\n const url = this.getChildrenUrl('kpis', parentReference);\n const res = await this.fetch(url, this.changeFetchOptions({ headers, params: filter }, url));\n const json = await res.json();\n const data = json[this.propertyName];\n const paging = this.getPaging(json, filter);\n return { res, data, paging };\n }\n\n protected onBeforeUpdate(objWithId: Partial<IManagedObject>): Partial<IManagedObject> {\n delete objWithId.lastUpdated;\n return objWithId;\n }\n\n protected onBeforeCreate(managedObject: Partial<IManagedObject>): Partial<IManagedObject> {\n delete managedObject.id;\n delete managedObject.lastUpdated;\n return managedObject;\n }\n\n private getChildrenUrl(type: ChildType | string, parentReference: IdReference): string {\n return `${this.getDetailUrl(parentReference)}/${type}`;\n }\n\n private getChildUrl(\n type: ChildType,\n childReference: IdReference,\n parentReference: IdReference\n ): string {\n const childId = this.getIdString(childReference);\n return `${this.getChildrenUrl(type, parentReference)}/${childId}`;\n }\n\n private async listChildren(\n type: ChildType,\n parentReference: IdReference,\n filter: object = {}\n ): Promise<IResultList<IManagedObject>> {\n const headers = { 'content-type': 'application/json' };\n const url = this.getChildrenUrl(type, parentReference);\n const res = await this.fetch(url, { headers, params: filter });\n const json = await res.json();\n const data = json.references.map(ref => ref.managedObject);\n const paging = this.getPaging(json, filter);\n paging.list = pagingFilter => this.listChildren(type, parentReference, pagingFilter);\n return { res, data, paging };\n }\n\n private async createChild(\n type: ChildType,\n managedObject: Partial<IManagedObject>,\n parentReference: IdReference\n ): Promise<IResult<IIdentified>> {\n const url = this.getChildrenUrl(type, parentReference);\n const method = 'POST';\n const body = JSON.stringify(this.onBeforeCreate(managedObject));\n const headers = { 'content-type': this.mimeType('managedObject'), accept: 'application/json' };\n const res = await this.fetch(url, { method, body, headers });\n const data = await res.json();\n return { res, data };\n }\n\n private async addChild(\n type: ChildType,\n childReference: IdReference,\n parentReference: IdReference\n ): Promise<IResult<IIdentified>> {\n const url = this.getChildrenUrl(type, parentReference);\n const method = 'POST';\n const childId = this.getIdString(childReference);\n const body = JSON.stringify({ managedObject: { id: String(childId) } });\n const headers = {\n accept: 'application/json',\n 'content-type': this.mimeType('managedObjectReference')\n };\n const res = await this.fetch(url, { method, body, headers });\n let data = await res.json();\n data = data.managedObject;\n return { res, data };\n }\n\n private async addChildBulk(\n type: ChildType,\n childReferenceArray: IdReference[],\n parentReference: IdReference\n ): Promise<IResultList<IIdentified>> {\n const url = this.getChildrenUrl(type, parentReference);\n const method = 'POST';\n const references = childReferenceArray.map(childId => ({\n managedObject: {\n id: this.getIdString(childId)\n }\n }));\n const body = JSON.stringify({\n references\n });\n const headers = {\n accept: 'application/json',\n 'content-type': this.mimeType('managedObjectReferenceCollection')\n };\n const res = await this.fetch(url, { method, body, headers });\n const data = (await res.json()).references;\n return { res, data: data.map(obj => obj.managedObject) };\n }\n\n private async removeChild(\n type: ChildType,\n childReference: IdReference,\n parentReference: IdReference\n ): Promise<IResult<null>> {\n const childId = this.getIdString(childReference);\n const url = `${this.getChildrenUrl(type, parentReference)}/${childId}`;\n const method = 'DELETE';\n const headers = { accept: 'application/json' };\n const res = await this.fetch(url, { method, headers });\n const data = null;\n return { res, data };\n }\n\n private async getSupportedMeasurementDetails(\n managedObjectOrId: IdReference,\n type: 'supportedMeasurements' | 'supportedSeries' = 'supportedSeries'\n ): Promise<string[]> {\n const url = `${this.getDetailUrl(managedObjectOrId)}/${type}`;\n this.getIdString(managedObjectOrId);\n const headers = { accept: 'application/json' };\n const res = await this.fetch(url, { headers });\n const data = await res.json();\n return data.c8y_SupportedMeasurements || data.c8y_SupportedSeries;\n }\n}\n","import { IIdentified, Service, IResult } from '../core';\nimport { IMeasurement, IMeasurementCreate } from './IMeasurement';\nimport { ISeriesFilter } from './ISeriesFilter';\nimport { ISeries } from './ISeries';\n\n/**\n * This class allows for managing measurements.\n */\nexport class MeasurementService extends Service<IMeasurement> {\n protected baseUrl = 'measurement';\n protected listUrl = 'measurements';\n protected propertyName = 'measurements';\n protected channel = '/measurements/*';\n\n /**\n * Gets the details of selected measurement.\n *\n * @param {string|number|IIdentified} entityOrId Entity or Id of the entity.\n *\n * @returns Response wrapped in [[IResult]]\n *\n * @deprecated As of version 10.16.0.0 and the usage of the time series database,\n * reading a single measurement via id is not supported any more.\n *\n * **Example**\n * ```typescript\n *\n * const measurementId: number = 1;\n *\n * (async () => {\n * const {data, res} = await measurementService.detail(measurementId);\n * })();\n * ```\n */\n async detail(entityOrId: string | number | IIdentified) {\n return super.detail(entityOrId);\n }\n\n /**\n * Creates a new measurement.\n *\n * @param {Partial<IMeasurementCreate>} entity At least sourceId is mandantory.\n *\n * @returns Response wrapped in [[IResult]]\n *\n * **Example**\n * ```typescript\n *\n * const mandantoryObject: Partial<IMeasurementCreate> = {\n * sourceId: device.id,\n * fragment: { series: { unit: '%', value: 51 } },\n * };\n *\n * (async () => {\n * const {data, res} = await measurementService.create(mandantoryObject);\n * })();\n * ```\n */\n async create(entity: Partial<IMeasurementCreate>) {\n return super.create(this.onBeforeCreate(entity));\n }\n\n /**\n * Gets the list of measurements filtered by parameters.\n *\n * @returns Response wrapped in [[IResultList]]\n *\n * @param {object} filter Object containing filters for querying measurements.\n *\n * **Example**\n * ```typescript\n *\n * const filter: object = {\n * pageSize: 100,\n * withTotalPages: true\n * };\n *\n * (async () => {\n * const {data, res, paging} = await measurementService.list(filter);\n * })();\n * ```\n */\n async list(filter: object = {}) {\n return super.list(filter);\n }\n\n /**\n * Removes a measurement with given id.\n *\n * @returns Response wrapped in [[IResult]]\n *\n * @param {string | number | IIdentified} entityOrId\n *\n * @deprecated As of version 10.16.0.0 and the usage of the time series database,\n * deleting a single measurement via id is not supported any more.\n *\n * **Example**\n * ```typescript\n *\n * const id: number = 1;\n *\n * (async () => {\n * const {data, res} = await measurementService.delete(id);\n * })();\n * ```\n */\n async delete(entityOrId: string | number | IIdentified) {\n return super.delete(entityOrId);\n }\n\n /**\n * Gets the list of series in a measurement filtered by parameters.\n *\n * @returns Response wrapped in [[IResult]]\n *\n * @param {object} filter Object containing filters for querying measurements.\n *\n * **Example**\n * ```typescript\n *\n * const filter: object = {\n * dateFrom: '2018-02-06T10:43:55.077Z',\n * dateTo: '2018-02-06T10:50:55.077Z',\n * source: device.id\n * };\n *\n * (async () => {\n * const {data, res} = await measurementService.listSeries(filter);\n * })();\n * ```\n */\n async listSeries(params: ISeriesFilter): Promise<IResult<ISeries>> {\n const url = `${this.baseUrl}/${this.listUrl}/series`;\n const res = await this.client.fetch(url, { params });\n const data = await res.json();\n return { res, data };\n }\n\n protected onBeforeCreate(entity: Partial<IMeasurementCreate>) {\n if (!entity.time) {\n entity.time = new Date().toISOString();\n }\n if (!entity.type) {\n entity.type = 'c8y_Measurement';\n }\n if (entity.sourceId) {\n const { sourceId } = entity;\n delete entity.sourceId;\n if (!entity.source) {\n entity.source = {\n id: String(sourceId)\n };\n }\n }\n return entity;\n }\n}\n","export enum aggregationType {\n MINUTELY = 'MINUTELY',\n HOURLY = 'HOURLY',\n DAILY = 'DAILY'\n}\n\n/**\n * This interface specifies all fragments which can be used\n * to filter for specific series.\n */\nexport interface ISeriesFilter {\n /**\n * The ManagedObject which is the source of these series\n */\n source: number | string;\n /**\n * From which date the series should be gathered\n */\n dateFrom: string | Date;\n /**\n * To which date the series should be gathered\n */\n dateTo: string | Date;\n /**\n * For which aggregation it should filter, see [[aggregationType]]\n */\n aggregationType?: aggregationType;\n /**\n * The series type and name\n *\n * **Example**\n * ```typescript\n *\n * const series: string[] = ['c8y_AccelerationMeasurement.acceleration', '...'];\n * ```\n */\n series?: string | string[];\n}\n","import { IIdentified, Service, IResult, IResultList } from '../core';\nimport { IAlarm } from './IAlarm';\n\n/**\n * This class allows for managing alarms.\n */\nexport class AlarmService extends Service<IAlarm> {\n protected baseUrl = 'alarm';\n protected listUrl = 'alarms';\n protected propertyName = 'alarms';\n protected channel = '/alarms/*';\n\n /**\n * Gets the details of selected alarms.\n *\n * @param {string|number|IIdentified} entityOrId Entity or Id of the entity.\n *\n * @returns Response wrapped in [[IResult]]\n *\n * **Example**\n * ```typescript\n *\n * const alarmId: number = 1;\n *\n * (async () => {\n * const {data, res} = await alarmService.detail(alarmId);\n * })();\n * ```\n */\n async detail(entityOrId: string | number | IIdentified): Promise<IResult<IAlarm>> {\n return super.detail(entityOrId);\n }\n\n /**\n * Creates a new alarm.\n *\n * @param {IAlarm} entity Alarm object with mandantory fragments.\n *\n * @returns Response wrapped in [[IResult]]\n *\n * **Example**\n * ```typescript\n *\n * const mandantoryObject: IAlarm = {\n * severity: Severity.CRITICAL,\n * source: device,\n * text: 'I am an Alarm!',\n * time: '2018-05-02T10:08:00Z',\n * type: 'device-type-here',\n * };\n *\n * (async () => {\n * const {data, res} = await alarmService.create(mandantoryObject);\n * })();\n * ```\n */\n async create(entity: IAlarm): Promise<IResult<IAlarm>> {\n return super.create(entity);\n }\n\n /**\n * Updates alarm data.\n *\n * @param {Partial<IAlarm>} entity Alarm is partially updatable.\n *\n * @returns Response wrapped in [[IResult]]\n *\n * **Example**\n * ```typescript\n *\n * const partialUpdateObject: Partial<IAlarm> = {\n * severity: Severity.MINOR,\n * source: device,\n * text: 'Changed Alarm!'\n * };\n *\n * (async () => {\n * const {data, res} = await alarmService.update(partialUpdateObject);\n * })();\n * ```\n */\n async update(entity: Partial<IAlarm>): Promise<IResult<IAlarm>> {\n return super.update(entity);\n }\n\n /**\n * Gets the list of alarms filtered by parameters.\n *\n * @returns Response wrapped in [[IResultList]]\n *\n * @param {object} filter Object containing filters for querying alarms.\n *\n * **Example**\n * ```typescript\n *\n * const filter: object = {\n * severity: Severity.MAJOR,\n * pageSize: 100,\n * withTotalPages: true\n * };\n *\n * (async () => {\n * const {data, res, paging} = await alarmService.list(filter);\n * })();\n * ```\n */\n async list(filter: object = {}): Promise<IResultList<IAlarm>> {\n return super.list(filter);\n }\n}\n","import { gettext } from '../gettext';\n\n/**\n * A specific alarm can have one of the following states\n */\nexport enum AlarmStatus {\n ACKNOWLEDGED = gettext('ACKNOWLEDGED'),\n CLEARED = gettext('CLEARED'),\n ACTIVE = gettext('ACTIVE')\n}\n","import { IIdentified, Service, IResult, IResultList } from '../core';\nimport { IOperation } from './IOperation';\n\n/**\n * This class allows for managing operations on a device.\n */\nexport class OperationService extends Service<IOperation> {\n protected baseUrl = 'devicecontrol';\n protected listUrl = 'operations';\n protected propertyName = 'operations';\n\n /**\n * Gets the details of selected operation.\n *\n * @param {string|number|IIdentified} entityOrId Entity or Id of the entitytabs.service.ts.\n *\n * @returns Response wrapped in [[IResult]]\n *\n * **Example**\n * ```typescript\n *\n * const operationId: number = 1;\n *\n * (async () => {\n * const {data, res} = await operationService.detail(operationId);\n * })();\n * ```\n */\n async detail(entityOrId: string | number | IIdentified): Promise<IResult<IOperation>> {\n return super.detail(entityOrId);\n }\n\n /**\n * Creates a new operation.\n *\n * @param {IOperation} entity Operation object with mandantory fragments.\n *\n * @returns Response wrapped in [[IResult]]\n *\n * **Example**\n * ```typescript\n *\n * const mandantoryObject: IOperation = {\n * com_cumulocity_model_WebCamDevice: {\n * name: 'take picture',\n * parameters: {\n * duration: '5s',\n * quality: 'HD'\n * }\n * },\n * deviceId: device.id,\n * };\n *\n * (async () => {\n * const {data, res} = await operationService.create(mandantoryObject);\n * })();\n * ```\n */\n async create(entity: IOperation): Promise<IResult<IOperation>> {\n return super.create(entity);\n }\n\n /**\n * Updates operation data.\n *\n * @param {Partial<IOperation>} entity Operation is partially updatable.\n *\n * @returns Response wrapped in [[IResult]]\n *\n * **Example**\n * ```typescript\n *\n * const partialUpdateObject: Partial<IOperation> = {\n * com_cumulocity_model_WebCamDevice: {\n * name: 'take picture',\n * parameters: {\n * duration: '2s',\n * quality: 'HD',\n * ratio: '16:9'\n * }\n * },\n * deviceId: device.id,\n * };\n *\n * (async () => {\n * const {data, res} = await operationService.update(partialUpdateObject);\n * })();\n * ```\n */\n async update(entity: Partial<IOperation>): Promise<IResult<IOperation>> {\n return super.update(entity);\n }\n\n /**\n * Gets the list of operations filtered by parameters.\n *\n * @returns Response wrapped in [[IResultList]]\n *\n * @param {object} filter Object containing filters for querying operations.\n *\n * **Example**\n * ```typescript\n *\n * const filter: object = {\n * pageSize: 100,\n * withTotalPages: true\n * };\n *\n * (async () => {\n * const {data, res, paging} = await operationService.list(filter);\n * })();\n * ```\n */\n async list(filter: object = {}): Promise<IResultList<IOperation>> {\n return super.list(filter);\n }\n}\n","import { IIdentified, Service, IResult } from '../core';\nimport { IOperationBulk } from './IOperationBulk';\n\n/**\n * This class allows for managing bulk operations.\n */\nexport class OperationBulkService extends Service<IOperationBulk> {\n protected baseUrl = 'devicecontrol';\n protected listUrl = 'bulkoperations';\n protected propertyName = 'bulkOperations';\n\n /**\n * Gets the details of selected bulk operation.\n *\n * @param {string|number|IIdentified} entityOrId Entity or Id of the entity.\n *\n * @returns Response wrapped in [[IResult]]\n *\n * **Example**\n * ```typescript\n *\n * const bulkOperationId: number = 1;\n *\n * (async () => {\n * const {data, res} = await operationBulkService.detail(bulkOperationId);\n * })();\n * ```\n */\n async detail(operationOrId: string | number | IIdentified) {\n return super.detail(operationOrId);\n }\n\n /**\n * Creates a new operation.\n *\n * @param {Partial<IOperationBulk>} operation Operation object with mandantory fragments.\n *\n * @returns Response wrapped in [[IResult]]\n *\n * **Example**\n * ```typescript\n *\n * const mandantoryObject: Partial<IOperationBulk> = {\n * creationRamp: 15,\n * groupId: '149044',\n * operationPrototype: {\n * c8y_Restart: {},\n * description: 'Restart device',\n * deviceId: device.id,\n * status: 'PENDING'\n * },\n * startDate: '2018-02-15T16:01:00.000Z'\n * };\n *\n * (async () => {\n * const {data, res} = await operationBulkService.create(mandantoryObject);\n * })();\n * ```\n */\n async create(operation: Partial<IOperationBulk>) {\n return super.create(operation);\n }\n\n /**\n * Updates a new operation.\n *\n * @param {Partial<IOperationBulk>} operation Operation object.\n *\n * @returns Response wrapped in [[IResult]]\n *\n * **Example**\n * ```typescript\n *\n * const updateObject: Partial<IOperationBulk> = {\n * creationRamp: 15,\n * groupId: '149044',\n * operationPrototype: {\n * c8y_Restart: {},\n * description: 'Restart device',\n * deviceId: device.id,\n * status: 'PENDING'\n * },\n * startDate: '2018-02-15T16:01:00.000Z'\n * };\n *\n * (async () => {\n * const {data, res} = await operationBulkService.update(updateObject);\n * })();\n * ```\n */\n async update(entity: Partial<IOperationBulk>) {\n return super.update(entity);\n }\n\n /**\n * Gets the list of bulk operations filtered by parameters.\n *\n * @returns Response wrapped in [[IResultList]]\n *\n * @param {object} filter Object containing filters for querying alarms.\n *\n * **Example**\n * ```typescript\n *\n * const filter: object = {\n * pageSize: 100,\n * withTotalPages: true\n * };\n *\n * (async () => {\n * const {data, res, paging} = await operationBulkService.list(filter);\n * })();\n * ```\n */\n async list(filter: object = {}) {\n return super.list(filter);\n }\n\n /**\n * Removes an bulk operation with given id.\n *\n * @returns Response wrapped in [[IResult]]\n *\n * @param {string | number | IIdentified):} operationOrId Operation object or id.\n *\n * **Example**\n * ```typescript\n *\n * const id: number = 1;\n *\n * (async () => {\n * const {data, res} = await operationBulkService.delete(id);\n * })();\n * ```\n */\n async delete(operationOrId: string | number | IIdentified): Promise<IResult<null>> {\n return super.delete(operationOrId);\n }\n}\n","import { gettext } from '../gettext';\r\n\r\n/**\r\n * A bulk operation can have one of the following states.\r\n */\r\nexport enum OperationBulkStatus {\r\n ACTIVE = gettext('ACTIVE'),\r\n IN_PROGRESS = gettext('IN_PROGRESS'),\r\n COMPLETED = gettext('COMPLETED'),\r\n DELETED = gettext('DELETED')\r\n}\r\n","import { gettext } from '../gettext';\r\n\r\n/**\r\n * A bulk operation can have one of the following general statuses.\r\n */\r\nexport enum OperationBulkGeneralStatus {\r\n SCHEDULED = gettext('SCHEDULED'),\r\n EXECUTING = gettext('EXECUTING'),\r\n EXECUTING_WITH_ERROR = gettext('EXECUTING_WITH_ERROR'),\r\n CANCELED = gettext('CANCELED'),\r\n FAILED = gettext('FAILED'),\r\n SUCCESSFUL = gettext('SUCCESSFUL'),\r\n DELETED = gettext('DELETED'),\r\n INCORRECT = gettext('INCORRECT')\r\n}\r\n","import { gettext } from '../gettext';\n\n/**\n * An Operation can have one of the following states.\n */\nexport enum OperationStatus {\n PENDING = gettext('PENDING'),\n EXECUTING = gettext('EXECUTING'),\n SUCCESSFUL = gettext('SUCCESSFUL'),\n FAILED = gettext('FAILED')\n}\n","import { Service, IResult, IResultList } from '../core';\nimport { ITenant } from './ITenant';\nimport { ICurrentTenant } from './ICurrentTenant';\nimport { ITfaSettings } from './ITfaSettings';\nimport { IApplication } from '../application';\n\n/**\n * @description\n * This service allows for managing tenants.\n */\nexport class TenantService extends Service<ITenant> {\n protected baseUrl = 'tenant';\n protected listUrl = 'tenants';\n protected currentTenantUrl = 'currentTenant';\n protected propertyName = 'tenants';\n protected fetchOptions = {\n method: 'PUT',\n body: '{}',\n headers: { 'content-type': 'application/json', accept: 'application/json' }\n };\n\n /**\n * Get a representation of a tenant.\n *\n * @param {string|number|IIdentified} entityOrId Tenant's id or tenant object.\n *\n * @returns Returns promise object that is resolved with the IIdentified wrapped by IResult.\n *\n * **Example**\n * ```typescript\n *\n * const tenantId: number = 1;\n *\n * (async () => {\n * const {data, res} = await tenantService.detail(tenantId);\n * })();\n * ```\n *\n * Required role: ROLE_TENANT_MANAGEMENT_READ<br><br>\n * User password is never returned in GET response. Authentication mechanism is provided by another interface.\n */\n async detail(entityOrId: string | number | ITenant): Promise<IResult<ITenant>> {\n return super.detail(entityOrId);\n }\n\n /**\n * Creates a new tenant.\n *\n * @param {IIdentified} entity Tenant object.\n *\n * @returns {IResult<IIdentified>} Returns promise object that is resolved with the details of newly created tenant.\n *\n * **Example**\n * ```typescript\n *\n * const tenantObject = {\n * id: \"sample_tenant\",\n * company: \"sample_company\",\n * domain: \"sample_domain.com\",\n * contactName: \"Mr. Doe\",\n * ...\n * };\n *\n * (async () => {\n * const {data, res} = await tenantService.create(tenantObject);\n * })();\n * ```\n *\n * Required role: ROLE_TENANT_MANAGEMENT_ADMIN or ROLE_TENANT_MANAGEMENT_CREATE<br><br>\n * Note that creating a tenant with adminName, adminPass and adminEmail, creates an admin user with these settings.\n * For the tenant id SQL keywords (e.g., select, cross, where) are not allowed.\n */\n async create(entity: ITenant): Promise<IResult<ITenant>> {\n return super.create(entity);\n }\n\n /**\n * Updates tenant data.\n *\n * @param {IIdentified} entity Tenant is partially updatable.\n *\n * @returns {IResult<IIdentified>} Returns promise object that is resolved with the saved tenant object.\n *\n * **Example**\n * ```typescript\n *\n * const partialUpdateObject: IIdentified = {\n * adminName : \"newAdmin\"\n * ...\n * }\n *\n * (async () => {\n * const {data, res} = await tenantService.update(partialUpdateObject);\n * })();\n * ```\n *\n * Required role: ROLE_TENANT_MANAGEMENT_ADMIN or ROLE_TENANT_MANAGEMENT_UPDATE<br><br>\n * Note that updating adminPass and adminEmail updates these settings in the admin user of the tenant.\n * Updating adminName has no effect.\n */\n async update(entity: ITenant): Promise<IResult<ITenant>> {\n return super.update(entity);\n }\n\n /**\n * Gets the list of tenants filtered by parameters.\n *\n * @param {object} filter Object containing filters for querying tenants.\n *\n * @returns Returns promise object that is resolved with the IIdentified wrapped by IResultList.\n *\n * **Example**\n * ```typescript\n *\n * const filter: object = {\n * severity: Severity.MAJOR,\n * pageSize: 100,\n * withTotalPages: true\n * };\n *\n * (async () => {\n * const {data, res, paging} = await tenantService.list(filter);\n * })();\n * ```\n *\n * Required role: ROLE_TENANT_MANAGEMENT_READ\n */\n async list(filter: object = {}): Promise<IResultList<ITenant>> {\n return super.list(filter);\n }\n\n /**\n * Delete a representation of a tenant.\n *\n * @param {string|number|IIdentified} entityOrId Tenant's id or tenant object.\n *\n * @returns Returns promise object that is resolved with the IResult.\n *\n * **Example**\n * ```typescript\n *\n * const tenantId: string = \"uniqueTenantId\";\n *\n * (async () => {\n * const {data, res} = await tenantService.delete(tenantId);\n * })();\n * ```\n *\n * Required role: ROLE_TENANT_MANAGEMENT_ADMIN\n */\n async delete(entityOrId: string | number | ITenant): Promise<IResult<null>> {\n return super.delete(entityOrId);\n }\n\n async current(): Promise<IResult<ICurrentTenant>> {\n const headers = { 'content-type': 'application/json' };\n const res = await this.fetch(this.currentTenantUrl, { headers });\n const data = await res.json();\n return { res, data };\n }\n\n /**\n * enable support user for current tenant.\n *\n * @returns Returns promise object that is resolved with the IResult.\n *\n * **Example**\n * ```typescript\n * (async () => {\n * const {res} = await tenantService.enableSupportUser();\n * })();\n * ```\n */\n async enableSupportUser(): Promise<IResult<null>> {\n const url = 'support-user/enable';\n const res = await this.fetch(url, this.fetchOptions);\n return { res, data: null };\n }\n\n /**\n * disable support user for current tenant.\n *\n * @returns Returns promise object that is resolved with the IResult.\n *\n * **Example**\n * ```typescript\n * (async () => {\n * const {res} = await tenantService.disableSupportUser();\n * })();\n * ```\n */\n async disableSupportUser(): Promise<IResult<null>> {\n const url = 'support-user/disable';\n const res = await this.fetch(url, this.fetchOptions);\n return { res, data: null };\n }\n\n async currentTenantType() {\n const tenantData = await this.current();\n if (\n tenantData.data.customProperties &&\n tenantData.data.customProperties.tenantType === 'TRIAL'\n ) {\n return 'TRIAL';\n }\n return 'REGULAR';\n }\n\n /**\n * Returns two factor-authentication settings for given tenant.\n *\n * @param tenant The tenant object.\n *\n * @returns Promise which resolves with the object with TFA settings.\n *\n * **Example**\n * ```typescript\n * (async () => {\n * const currentTenant = (await tenantService.current()).data;\n * const currentTenantTfaSettings = await tenantService.getTfaSettings(currentTenant);\n *\n * const subtenant = (await tenantService.detail('t12345')).data;\n * const subtenantTfaSettings = await tenantService.getTfaSettings(subtenant);\n * })();\n * ```\n */\n async getTfaSettings(tenant: ICurrentTenant | ITenant): Promise<ITfaSettings> {\n const entityOrId: string = this.getIdString(tenant);\n const url = `tenants/${entityOrId}/tfa`;\n const res = await this.fetch(url);\n const tfaSettings = await res.json();\n\n return tfaSettings;\n }\n\n /**\n * Subscribes a given application to a given tenant.\n *\n * @param tenant The tenant object.\n * @param application The application object.\n *\n * @returns Returns promise object that is resolved with the IResult.\n *\n * **Example**\n * ```typescript\n * const newApp = {\n * name: 'New application',\n * type: 'HOSTED',\n * key: 'new-app'\n * };\n *\n * const application = (await applicationService.create(newApp)).data;\n * const currentTenant = (await tenantService.current()).data;\n *\n * const {data, res} = await tenantService.subscribeApplication(currentTenant, application);\n * })();\n * ```\n */\n async subscribeApplication(\n tenant: ICurrentTenant | ITenant,\n application: IApplication\n ): Promise<IResult<null>> {\n const entityOrId: string = this.getIdString(tenant);\n const applicationId = application.id;\n const url = `tenants/${entityOrId}/applications`;\n const method = 'POST';\n const body = JSON.stringify({\n application: {\n id: applicationId,\n self: application.self\n }\n });\n const headers = { 'content-type': this.mimeType('applicationReference') };\n const res = await this.fetch(url, this.changeFetchOptions({ method, body, headers }, url));\n return { res, data: null };\n }\n\n /**\n * Unsubscribes a given application from a given tenant.\n *\n * @param tenant The tenant object.\n * @param application The application object.\n *\n * @returns Returns promise object that is resolved with the IResult.\n *\n * **Example**\n * ```typescript\n * const newApp = {\n * name: 'New application',\n * type: 'HOSTED',\n * key: 'new-app'\n * };\n *\n * const application = (await applicationService.create(newApp)).data;\n * const currentTenant = (await tenantService.current()).data;\n * await tenantService.addApplication(currentTenant, application);\n *\n * await tenantService.unsubscribeApplication(currentTenant, application);\n * })();\n * ```\n */\n async unsubscribeApplication(\n tenant: ICurrentTenant | ITenant,\n application: IApplication\n ): Promise<IResult<null>> {\n const entityOrId: string = this.getIdString(tenant);\n const url = `tenants/${entityOrId}/applications/${application.id}`;\n const method = 'DELETE';\n const res = await this.fetch(url, this.changeFetchOptions({ method }, url));\n return { res, data: null };\n }\n\n protected getIdString(tenant: ITenant | ICurrentTenant): string {\n return (tenant as ITenant).id || (tenant as ICurrentTenant).name;\n }\n\n protected onBeforeCreate(obj: ITenant): any {\n return obj;\n }\n}\n","import { gettext } from '../gettext';\r\n\r\nexport enum TenantStatus {\r\n ACTIVE = gettext('ACTIVE'),\r\n SUSPENDED = gettext('SUSPENDED')\r\n}\r\n","/**\n * Represents a strategy used for two-factor authentication.\n */\nexport enum TfaStrategy {\n /** Two-factor authentication with Time-Based One Time Passwords. */\n TOTP = 'TOTP',\n /** Two-factor authentication with codes sent via SMSes. */\n SMS = 'SMS'\n}\n","import { IFetchClient, IIdentified, Service } from '../core';\nimport { IUserInventoryRole } from './IUserInventoryRole';\n\n/**\n * @description\n * This service allows for managing current user's inventory roles.\n */\nexport class UserInventoryRoleService extends Service<IUserInventoryRole> {\n protected baseUrl;\n protected listUrl = `inventory`;\n protected currenUserUrl = `currentUser`;\n protected propertyName = 'inventoryAssignments';\n\n constructor(userUrl: string, client: IFetchClient) {\n super(client);\n this.baseUrl = `user/${userUrl}/roles`;\n }\n\n /**\n * Get a representation of a concrete current user's inventory role.\n *\n * @param {string|number|IUserInventoryRole} entityOrId inventory role id or inventory role object.\n *\n * @returns Returns promise object that is resolved with the IUserInventoryRole wrapped by IResult.\n *\n * **Example**\n * ```typescript\n *\n * const inventoryRoleId: number = 1;\n *\n * (async () => {\n * const {data, res} = await userInventoryRoleService.detail(inventoryRoleId);\n * })();\n * ```\n *\n * Required role: ROLE_TENANT_MANAGEMENT_READ<br><br>\n * User password is never returned in GET response. Authentication mechanism is provided by another interface.\n */\n async detail(entityOrId: string | number | IUserInventoryRole) {\n return super.detail(entityOrId);\n }\n\n /**\n * Assign inventory role to current user.\n *\n * @param {IUserInventoryRole} entity Inventory Role object.\n *\n * @returns Returns promise object that is resolved with the details of newly assigned inventory role.\n *\n * **Example**\n * ```typescript\n *\n * const inventoryRoleObject: IUserInventoryRole = {\n * ...\n * };\n *\n * (async () => {\n * const {data, res} = await userInventoryRoleService.create(inventoryRoleObject);\n * })();\n * ```\n */\n async create(entity: IUserInventoryRole) {\n return super.create(entity);\n }\n\n /**\n * Updates an inventory role.\n *\n * @param {Partial<IUserInventoryRole>} entity Inventory Role object.\n */\n async update(entity: Partial<IUserInventoryRole>) {\n return super.update(entity);\n }\n\n /**\n * Gets the list the inventory roles applied to a current user.\n *\n * @param {object} filter Object containing filters for querying inventory roles.\n *\n * @returns Returns promise object that is resolved with the IUserInventoryRole wrapped by IResultList.\n *\n * **Example**\n * ```typescript\n *\n * const filter: object = {\n * severity: Severity.MAJOR,\n * pageSize: 100,\n * withTotalPages: true\n * };\n *\n * (async () => {\n * const {data, res, paging} = await userInventoryRoleService.list(filter);\n * })();\n * ```\n */\n async list(filter: object = {}) {\n return super.list(filter);\n }\n\n /**\n * Unassign inventory role from current user\n *\n * @param {string|number|IIdentified} entityOrId Inventory Role id or Inventory Role object.\n *\n * @returns Returns promise object that is resolved with the IResult.\n *\n * **Example**\n * ```typescript\n *\n * const inventoryRoleId: number = 1;\n *\n * (async () => {\n * const {data, res} = await userInventoryRoleService.delete(inventoryRoleId);\n * })();\n * ```\n */\n async delete(entityOrId: string | number | IIdentified) {\n return super.delete(entityOrId);\n }\n}\n","import { IIdentified, Service, IResult, IFetchOptions } from '../core';\nimport { IUser } from './IUser';\nimport { ICurrentUser } from './ICurrentUser';\nimport { UserInventoryRoleService } from './UserInventoryRoleService';\nimport { IResetPassword } from './IResetPassword';\nimport { ITotp } from './ITotp';\nimport { ITotpStatus } from './ITotpStatus';\n\n/**\n * @description\n * This service allows for managing users.\n */\nexport class UserService extends Service<IUser> {\n protected get listUrl() {\n return `${this.client.tenant}/users`;\n }\n protected baseUrl = 'user';\n protected currentUserUrl = 'currentUser';\n protected passwordResetUrl = 'passwordReset';\n protected currentUserPhoneUrl = 'currentUserPhone';\n protected verifyTFACodeUrl = 'pin';\n protected totpCurrentUserURL = `${this.currentUserUrl}/totpSecret`;\n protected verifyTOTPCodeUrl = `${this.totpCurrentUserURL}/verify`;\n protected activateTOTPCodeUrl = `${this.totpCurrentUserURL}/activity`;\n protected revokeTOTPSecretUrl = 'totpSecret/revoke';\n protected get newsletterEmailsUrl() {\n return `${this.client.tenant}/users/newsletterEmails`;\n }\n protected get currentUserPasswordUrl() {\n return `${this.currentUserUrl}/password`;\n }\n protected get revokeAllTokensUrl() {\n return `/logout/${this.client.tenant}/allUsers`;\n }\n protected propertyName = 'users';\n\n /**\n * Gets the details of given user.\n *\n * @param {string | number | IUser} entityOrId User's id or user object.\n *\n * @returns Returns promise object that is resolved with the IUser wrapped by IResult.\n *\n * **Example**\n * ```typescript\n *\n * const userId: number = 1;\n *\n * (async () => {\n * const {data, res} = await userService.detail(userId);\n * })();\n * ```\n * User password is never returned in GET response. Authentication mechanism is provided by another interface.\n */\n async detail(entityOrId: string | number | IUser) {\n return super.detail(entityOrId);\n }\n\n /**\n * Creates a new user.\n *\n * @param {IUser} entity User object.\n *\n * @returns {IResult<IUser>} Returns promise object that is resolved with the details of newly created user.\n *\n * **Example**\n * ```typescript\n *\n * const userObject: IUser = {\n * userName: \"newUser\",\n * password: \"userPassword12!@\"\n * };\n *\n * (async () => {\n * const {data, res} = await userService.create(userObject);\n * })();\n * ```\n */\n async create(entity: IUser) {\n return super.create(entity);\n }\n\n /**\n * Updates user data.\n *\n * @param {Partial<IUser>} entity User is partially updatable.\n *\n * @returns {IResult<IUserGroup>} Returns promise object that is resolved with the saved user object.\n *\n * **Example**\n * ```typescript\n *\n * const partialUpdateObject: Partial<IUser> = {\n * \"id\" : \"myuser\",\n * \"userName\" : \"newUserName\",\n * \"email\": \"newUserEmail@example.com\"\n * ...\n * }\n *\n * (async () => {\n * const {data, res} = await userService.update(partialUpdateObject);\n * })();\n * ```\n * When user is updated with changed permissions or groups, suitable audit record is created with type\n * 'User' and activity 'User updated'.\n */\n async update(entity: Partial<IUser>) {\n return super.update(entity);\n }\n\n /**\n * Gets the list of users filtered by parameters.\n *\n * @param {object} filter Object containing filters for querying users.\n *\n * @returns Returns promise object that is resolved with the IUser wrapped by IResultList.\n *\n * **Example**\n * ```typescript\n *\n * const filter: object = {\n * pageSize: 100,\n * withTotalPages: true\n * };\n *\n * (async () => {\n * const {data, res, paging} = await userService.list(filter);\n * })();\n * ```\n */\n async list(filter: object = {}) {\n return super.list(filter);\n }\n\n /**\n * Removes user.\n *\n * @param {number|IIdentified} entityOrId User's id or user object.\n *\n * @returns Returns promise object that is resolved with the IResult of null.\n *\n * **Example**\n * ```typescript\n *\n * const userId: string = \"uniqueUserId\";\n *\n * (async () => {\n * const {data, res} = await userService.delete(userGroupId);\n * })();\n * ```\n */\n async delete(entityOrId: string | number | IIdentified) {\n return super.delete(entityOrId);\n }\n\n /**\n * Create instance of User Inventory Role Service related with given User.\n *\n * @param {string|number|IUser} entityOrId User's id or user object.\n *\n * @returns Returns UserInventoryRoleService object that is related with given User.\n *\n * **Example**\n * ```typescript\n *\n * const userId: string = \"uniqueUserId\";\n *\n * const userInventoryRoleService = userService.inventoryAssignment(userGroupId);\n * (async () => {\n * const {data, res} = await userInventoryRoleService.create(...);\n * })();\n * ```\n */\n inventoryAssignment(entityOrId: string | number | IUser) {\n return new UserInventoryRoleService(this.getDetailUrl(entityOrId), this.client);\n }\n\n /**\n * Gets user that is currently logged in.\n *\n * @returns Returns promise object that is resolved with the IUser wrapped by IResult.\n *\n * **Example**\n * ```typescript\n *\n * (async () => {\n * const {data, res} = await userService.current();\n * })();\n * ```\n */\n async current(): Promise<IResult<IUser>> {\n const headers = {\n 'content-type': 'application/json',\n Accept: 'application/vnd.com.nsn.cumulocity.user+json;'\n };\n const res = await this.fetch(this.currentUserUrl, { headers });\n const data = await res.json();\n return { res, data };\n }\n\n /**\n * Gets user that is currently logged in with the list of all roles assigned.\n *\n * @returns Returns promise object that is resolved with the ICurrenUser wrapped by IResult.\n *\n * **Example**\n * ```typescript\n *\n * (async () => {\n * const {data, res} = await userService.currentWithEffectiveRoles();\n * })();\n * ```\n */\n async currentWithEffectiveRoles(): Promise<IResult<ICurrentUser>> {\n const headers = {\n 'content-type': 'application/json',\n Accept: 'application/vnd.com.nsn.cumulocity.currentUser+json;'\n };\n const res = await this.fetch(this.currentUserUrl, { headers });\n const data = await res.json();\n return { res, data };\n }\n\n /**\n * Updates the current user\n *\n * @param {IUser} user The user object with the properties to be updated\n *\n * @return Returns promise object resolved with the IUser wrapped by IResult\n */\n async updateCurrent(user: IUser): Promise<IResult<IUser>> {\n const mimeType = 'application/vnd.com.nsn.cumulocity.user+json';\n const headers = { 'content-type': mimeType, Accept: mimeType };\n const body = JSON.stringify(this.onBeforeUpdate(user));\n const res = await this.fetch(this.currentUserUrl, { headers, body, method: 'PUT' });\n const data = await res.json();\n return { res, data };\n }\n\n /**\n * Sends an email message with a link allowing user to reset their password.\n *\n * @param {string} email The email address to send the message to.\n * @param {string} tenantId The id of user's tenant (if cannot be inferred from URL).\n *\n * @returns Returns a request result object.\n *\n * **Example**\n * ```typescript\n * const email = 'user@example.com';\n * const tenantId = 't123456';\n *\n * (async () => {\n * const { res, data } = await userService.sendPasswordResetMail(email, tenantId);\n * })();\n * ```\n */\n async sendPasswordResetMail(email: string, tenantId?: string): Promise<IResult<null>> {\n const headers = { 'content-type': 'application/json', accept: 'application/json' };\n const method = 'POST';\n const url = this.passwordResetUrl;\n const params = tenantId ? { tenantId } : {};\n const body = JSON.stringify({ email });\n const res = await this.fetch(url, { headers, method, params, body });\n return { res, data: null };\n }\n\n /**\n * Resets user's password to a new one.\n *\n * @param {IResetPassword} newPassword Object with token, user's email, new password and its strength indicator.\n * @param {string} tenantId The id of user's tenant (if cannot be inferred from URL).\n *\n * @returns Returns a request result object.\n *\n * **Example**\n * ```typescript\n * const newPassword: IResetPassword = {\n * token: '123123ASDAWERER@#!WEDS$@#!WADA#A#EA#EA#EA',\n * email: 'user@example.com',\n * newPassword: 'myNewPassword',\n * passwordStrength: PasswordStrength.GREEN\n * };\n * const tenantId = 't123456';\n *\n * (async () => {\n * const { res, data } = await userService.resetPassword(newPassword, tenantId);\n * })();\n * ```\n */\n async resetPassword(newPassword: IResetPassword, tenantId?: string): Promise<IResult<null>> {\n const headers = { 'content-type': 'application/json', accept: 'application/json' };\n const method = 'PUT';\n const url = this.passwordResetUrl;\n const params = tenantId ? { tenantId } : {};\n const body = JSON.stringify(newPassword);\n const res = await this.fetch(url, { headers, method, params, body });\n return { res, data: null };\n }\n\n /**\n * Verifies TFA code which is sent via SMS. If invoked with string '0', new TFA code will be sent.\n *\n * @param {string} pin The code to verify.\n *\n * @returns Returns a status object.\n *\n * **Example**\n * ```typescript\n *\n * (async () => {\n * const {data, res} = await userService.verifyTFACode('123123');\n * })();\n * ```\n */\n async verifyTFACode(pin: string): Promise<IResult<null>> {\n const method = 'POST';\n const body = JSON.stringify({ pin });\n const headers = { 'content-type': 'application/json', accept: 'application/json' };\n const res = await this.fetch(this.verifyTFACodeUrl, { headers, body, method });\n return { res, data: null };\n }\n\n /**\n * Verifies TFA code which is generated by a TOTP app.\n *\n * @param {string} code The code to verify.\n *\n * @returns Returns a status object.\n *\n * **Example**\n * ```typescript\n *\n * (async () => {\n * const {data, res} = await userService.verifyTotpCode('123123');\n * })();\n * ```\n */\n async verifyTotpCode(code): Promise<IResult<null>> {\n const method = 'POST';\n const headers = { 'content-type': 'application/json' };\n const body = JSON.stringify({ code });\n const res = await this.fetch(this.verifyTOTPCodeUrl, { headers, body, method });\n return { res, data: null };\n }\n\n /**\n * Verifies TFA code which is generated by a TOTP app.\n *\n * @returns Returns a status object.\n *\n * **Example**\n * ```typescript\n *\n * (async () => {\n * const {data, res} = await userService.activateTotp();\n * })();\n * ```\n */\n async activateTotp(): Promise<IResult<null>> {\n const method = 'POST';\n const headers = { 'content-type': 'application/json' };\n const body = JSON.stringify({ isActive: true });\n const res = await this.fetch(this.activateTOTPCodeUrl, { headers, body, method });\n return { res, data: null };\n }\n\n /**\n * Checks if TOTP is activated and enforced.\n *\n * @returns Returns an object of ITotpStatus if it is active.\n *\n * **Example**\n * ```typescript\n *\n * (async () => {\n * const {data, res} = await userService.getActivityTotp();\n * console.log(data.isActive);\n * })();\n * ```\n */\n async getActivityTotp(): Promise<IResult<ITotpStatus>> {\n const method = 'GET';\n const headers = { 'content-type': 'application/json' };\n const res = await this.fetch(this.activateTOTPCodeUrl, { headers, method });\n const data = await res.json();\n return { res, data };\n }\n\n /**\n * Generates a secret which can be used to setup two-factor authentication with TOTP.\n *\n * @returns Returns the secret and an URL to a QR Code.\n *\n * **Example**\n * ```typescript\n *\n * (async () => {\n * const {data, res} = await userService.generateTotpSecret();\n * console.log(secret);\n * })();\n * ```\n */\n async generateTotpSecret(): Promise<IResult<ITotp>> {\n const method = 'POST';\n const headers = { 'content-type': 'application/json', accept: 'application/json' };\n const res = await this.fetch(this.totpCurrentUserURL, { headers, method });\n const data = await res.json();\n return { res, data };\n }\n\n /**\n * Revokes a specific user's TOTP secret.\n *\n * @param {IUser} user User whose TOTP secret to revoke.\n *\n * @returns Status object\n */\n async totpRevokeSecret(user: IUser): Promise<IResult<null>> {\n const url = `${this.getDetailUrl(user)}/${this.revokeTOTPSecretUrl}`;\n const method = 'DELETE';\n const headers = { accept: 'application/json' };\n const res = await this.fetch(url, { headers, method });\n return { res, data: null };\n }\n\n /**\n * Saves phone number for the current user.\n * @param phoneNumber Phone number to save.\n * @returns Server response and data with updated current user object.\n */\n async savePhoneNumber(phoneNumber: string): Promise<IResult<ICurrentUser>> {\n const url = this.currentUserPhoneUrl;\n const options: IFetchOptions = {\n method: 'PUT',\n headers: { 'content-type': 'application/json', accept: 'application/json' },\n body: JSON.stringify({\n phone: phoneNumber\n })\n };\n const res = await this.fetch(url, options);\n const data = await res.json();\n return { res, data };\n }\n\n /**\n * Gets the list of emails of users subscribed for newsletter\n * on the current tenant and its subtenants.\n * @returns Server response and data with email addresses as plain text.\n */\n async getNewsletterEmails(): Promise<IResult<string>> {\n const url = this.newsletterEmailsUrl;\n const options: IFetchOptions = {\n method: 'GET',\n headers: { accept: 'text/plain' }\n };\n const res = await this.fetch(url, options);\n const data = await res.text();\n return { res, data };\n }\n\n /**\n * Changes password for user.\n *\n * @param {string | number | IUser} entityOrId User's id or user object.\n * @param {string} newPassword New user password.\n * @param {string} currentUserPassword The password of the currently logged user.\n *\n * @returns Returns a result object.\n */\n async changeUserPassword(\n entityOrId: string | number | IUser,\n newPassword: string,\n currentUserPassword: string\n ): Promise<IResult<null>> {\n const method = 'PUT';\n const headers = { 'content-type': 'application/json' };\n const body = JSON.stringify({ newPassword, currentUserPassword });\n const res = await this.fetch(this.changeUserPasswordUrl(entityOrId), { headers, body, method });\n return { res, data: null };\n }\n\n /**\n * Changes password for current user.\n *\n * @param {string} newPassword New password for current user.\n * @param {string} currentUserPassword The password of the currently logged user.\n *\n * @returns Returns a result object. During this action if preferred login mode is OAI_SECURE new jwt cookie will be set.\n */\n async changeCurrentUserPassword(\n newPassword: string,\n currentUserPassword: string\n ): Promise<IResult<null>> {\n const method = 'PUT';\n const headers = { 'content-type': 'application/json' };\n const body = JSON.stringify({ newPassword, currentUserPassword });\n const res = await this.fetch(this.currentUserPasswordUrl, { headers, body, method });\n return { res, data: null };\n }\n\n /**\n * Revoke tokens for all users. All users logged with \"OAI-Secure\" or \"Single sign-on redirect\" will be logged out.\n *\n * @returns Returns a result object.\n */\n async revokeTokens(): Promise<IResult<null>> {\n const method = 'POST';\n const headers = { 'content-type': 'application/json' };\n const res = await this.fetch(this.revokeAllTokensUrl, { headers, method });\n return { res, data: null };\n }\n\n hasRole(user: IUser, roleId: string): boolean {\n return this.hasRoleInUser(user, roleId) || this.hasRoleInGroups(user, roleId);\n }\n\n hasAllRoles(user: IUser, roleIds: string[]): boolean {\n return roleIds.every(roleId => this.hasRole(user, roleId));\n }\n\n hasAnyRole(user: IUser, roleIds: string[]): boolean {\n return roleIds.some(roleId => this.hasRole(user, roleId));\n }\n\n hasAnyGlobalRole(user: IUser, globalRoleIds: number[]): boolean {\n return globalRoleIds.some(globalRoleId => this.hasGlobalRoleInUser(user, globalRoleId));\n }\n\n isDeviceUser(user: IUser) {\n return user.id.match(/^device_/);\n }\n\n protected onBeforeUpdate(user: IUser): any {\n const obj = Object.assign({}, user);\n delete obj.id;\n delete obj.userName;\n return obj;\n }\n\n protected getDetailUrl(entityOrId: string | number | IUser): string {\n return `${this.listUrl}/${encodeURIComponent(this.getId(entityOrId))}`;\n }\n\n protected getId(entityOrId: string | number | IUser): string {\n let id: string | number;\n if (typeof entityOrId === 'object' && entityOrId.id) {\n id = entityOrId.id;\n } else if (typeof entityOrId === 'object' && entityOrId.userName) {\n id = entityOrId.userName;\n } else {\n id = entityOrId as string | number;\n }\n return String(id);\n }\n\n protected hasRoleInUser(user, roleId) {\n const effectiveRoles = user.effectiveRoles || [];\n return (\n this.hasRoleInReferences((user && user.roles && user.roles.references) || [], roleId) ||\n effectiveRoles.some(({ id }) => roleId === id)\n );\n }\n\n protected hasRoleInGroups(user, roleId) {\n const groupReferences = (user && user.groups && user.groups.references) || [];\n return groupReferences.some(groupRef =>\n this.hasRoleInReferences(groupRef.group.roles.references, roleId)\n );\n }\n\n protected hasRoleInReferences(references, roleId) {\n return references.some(ref => ref.role.id === roleId);\n }\n\n protected changeUserPasswordUrl(entityOrId: string | number | IUser) {\n return `${this.client.tenant}/users/${this.getId(entityOrId)}/password`;\n }\n\n protected hasGlobalRoleInUser(user: IUser, globalRoleId: number) {\n const groupReferencesIds = (user?.groups?.references || []).map(gR => gR?.group?.id);\n return groupReferencesIds.some(id => id === globalRoleId);\n }\n}\n","export enum PasswordStrength {\n GREEN = 'GREEN',\n RED = 'RED',\n YELLOW = 'YELLOW'\n}\n","import { IFetchClient, Service, IResult, IFetchResponse } from '../core';\nimport { IApplication } from './IApplication';\nimport { IApplicationBinary } from './IApplicationBinary';\nimport { Stream } from 'stream';\nimport FormData from 'form-data';\nimport { IUploadParamsOverride } from './IUploadParamsOverride';\n\nexport class ApplicationBinaryService extends Service<IApplicationBinary> {\n protected baseUrl;\n protected listUrl = 'binaries';\n protected propertyName = 'attachments';\n\n constructor(client: IFetchClient, applicationOrId: string | number | IApplication) {\n super(client);\n this.baseUrl = `application/applications/${this.getIdString(applicationOrId)}`;\n }\n\n async upload(\n binary: ArrayBuffer | Stream | Buffer | File | Blob,\n fileName?: string,\n uploadParamsOverride?: IUploadParamsOverride\n ): Promise<IResult<IApplicationBinary>> {\n const url = uploadParamsOverride?.listUrl || this.listUrl;\n const method = 'POST';\n const body = this.createBinaryRequestBody(binary, fileName, uploadParamsOverride);\n let bodyHeaders;\n if (typeof body.getHeaders === 'function') {\n bodyHeaders = body.getHeaders();\n }\n const headers = Object.assign(\n uploadParamsOverride?.headers || {\n Accept: 'application/json'\n },\n bodyHeaders\n );\n const res = await this.fetch(url, { method, body, headers });\n const data = await res.json();\n return { res, data };\n }\n\n uploadWithProgressXhr(\n binary: ArrayBuffer | Stream | Buffer | File | Blob,\n onProgress,\n fileName?: string,\n uploadParamsOverride?: IUploadParamsOverride\n ): XMLHttpRequest {\n const url = `/${this.baseUrl}/${uploadParamsOverride?.listUrl || this.listUrl}`;\n const method = 'POST';\n const body = this.createBinaryRequestBody(binary, fileName, uploadParamsOverride);\n let bodyHeaders;\n if (typeof body.getHeaders === 'function') {\n bodyHeaders = body.getHeaders();\n }\n const headers = this.client.getFetchOptions().headers;\n Object.assign(\n headers,\n uploadParamsOverride?.headers || {\n Accept: 'application/json'\n }\n );\n Object.assign(headers, bodyHeaders);\n const xhr = new XMLHttpRequest();\n xhr.open(method, url, true);\n for (const key in headers) {\n if (headers.hasOwnProperty(key)) {\n xhr.setRequestHeader(key, headers[key]);\n }\n }\n\n xhr.upload.addEventListener('progress', onProgress);\n\n let xhrBody: XMLHttpRequestBodyInit;\n if (typeof body.getBuffer === 'function') {\n xhrBody = body.getBuffer();\n } else {\n xhrBody = body as any;\n }\n xhr.send(xhrBody);\n return xhr;\n }\n\n getXMLHttpResponse(xhr): Promise<IApplication> {\n return new Promise((res, rej) => {\n xhr.addEventListener('loadend', () => {\n xhr.readyState === 4 && (xhr.status === 200 || xhr.status === 201)\n ? res(JSON.parse(xhr.responseText))\n : rej(\n xhr.responseText ? { data: JSON.parse(xhr.responseText) } : 'Could not upload file.'\n );\n });\n });\n }\n\n async list(filter?) {\n return super.list(filter);\n }\n\n async delete(binaryOrId: string | number | IApplicationBinary) {\n return super.delete(binaryOrId);\n }\n\n async listPlugins() {\n const headers = { accept: 'application/json' };\n const url = `${this.listUrl}/plugins`;\n const res = await this.fetch(url, { headers });\n const data = await res.json();\n return { res, data };\n }\n\n async addPlugin(pluginName: string, pluginFile: Stream | Buffer | ArrayBuffer) {\n const url = `${this.listUrl}/plugins/${encodeURIComponent(pluginName)}`;\n const method = 'POST';\n const body = new FormData();\n const bufferOrStream = pluginFile instanceof ArrayBuffer ? Buffer.from(pluginFile) : pluginFile;\n body.append('file', bufferOrStream);\n\n const headers = {\n accept: 'application/json'\n };\n\n const res = await this.fetch(url, { method, body, headers });\n const data = await res.json();\n return { res, data };\n }\n\n async removePlugin(pluginName: string) {\n const method = 'DELETE';\n const headers = { accept: 'application/json' };\n const url = `${this.listUrl}/plugins/${pluginName}`;\n const res = await this.fetch(url, { method, headers });\n const data = await res.json();\n return { res, data };\n }\n\n async updateFiles(files: Array<{ path: string; contents: Stream | Buffer | ArrayBuffer }>) {\n const url = `${this.listUrl}/files`;\n const method = 'POST';\n const body = new FormData();\n files.forEach(file => {\n const bufferOrStream =\n file.contents instanceof ArrayBuffer ? Buffer.from(file.contents) : file.contents;\n body.append(file.path, bufferOrStream);\n });\n const headers = {\n accept: 'application/json'\n };\n const res = await this.fetch(url, { method, body, headers });\n const data = await res.json();\n return { res, data };\n }\n\n async downloadArchive(binaryId: number | string): Promise<IFetchResponse> {\n const url = `${this.listUrl}/${binaryId}`;\n return await this.fetch(url);\n }\n\n private createBinaryRequestBody(\n binary: ArrayBuffer | Stream | Buffer | File | Blob,\n fileName?: string,\n uploadParamsOverride?: IUploadParamsOverride\n ) {\n const body = new FormData();\n const bufferOrStream = binary instanceof ArrayBuffer ? Buffer.from(binary) : binary;\n let uploadFileName = fileName;\n if (typeof File !== 'undefined' && binary instanceof File) {\n uploadFileName = binary.name;\n }\n body.append(uploadParamsOverride?.bodyFileProperty || 'file', bufferOrStream, uploadFileName);\n body.append('fileName', uploadFileName);\n if (uploadParamsOverride?.requestBody) {\n for (const key in uploadParamsOverride.requestBody) {\n if (uploadParamsOverride.requestBody.hasOwnProperty(key)) {\n body.append(key, JSON.stringify(uploadParamsOverride.requestBody[key]));\n }\n }\n }\n return body;\n }\n}\n","export enum ApplicationType {\n EXTERNAL = 'EXTERNAL',\n HOSTED = 'HOSTED',\n MICROSERVICE = 'MICROSERVICE',\n FEATURE = 'FEATURE'\n}\n","import {\n IApplicationInstanceLog,\n IApplicationInstanceLogRequestParams,\n IApplicationManagedObject\n} from './IApplicationInstanceDetails';\nimport { IFetchResponse, IResult, IResultList, Service } from '../core';\nimport { InventoryService } from '../inventory';\nimport { ITenant, TenantService } from '../tenant';\nimport { IUser, UserService } from '../user';\nimport { ApplicationBinaryService } from './ApplicationBinaryService';\nimport { ApplicationType } from './ApplicationType';\nimport { IApplication } from './IApplication';\nimport { gettext } from '../gettext';\nimport { IApplicationVersionDeleteParams, IApplicationVersion } from './IApplicationVersion';\nimport { IManifest } from './IManifest';\nimport { ApplicationAvailability } from './ApplicationAvailability';\n\nexport class ApplicationService extends Service<IApplication> {\n protected baseUrl = 'application';\n protected listUrl = 'applications';\n protected propertyName = 'applications';\n protected channel = '/applications/*';\n\n /**\n * Creates a new application.\n *\n * @param {IIdentified} entity Application object.\n *\n * @returns Response wrapped in [[IResult]]\n *\n * **Example**\n * ```typescript\n *\n * const newApp = {\n * name: 'New application',\n * type: 'EXTERNAL',\n * key: 'new-app'\n * };\n *\n * (async () => {\n * const {data, res} = await applicationService.create(newApp);\n * })();\n * ```\n */\n async create(entity: IApplication): Promise<IResult<IApplication>> {\n return super.create(entity);\n }\n\n /**\n * Clones a given application. The application name, key, and context-path will be\n * prefixed with `clone` and if necessary a number.\n * @param entity The application to clone.\n * @param version If a blueprint, you can define which version to clone. If not provided, it will always clone the latest version.\n * @returns The application entity.\n */\n async clone(entity: IApplication, version?: string): Promise<IResult<IApplication>> {\n const url = `${this.getDetailUrl(entity)}/clone`;\n const method = 'POST';\n const body = '';\n const headers = { 'content-type': 'application/json', accept: 'application/json' };\n let params = undefined;\n if (version) {\n params = { version };\n }\n const res = await this.fetch(url, { method, body, headers, params });\n const data = await res.json();\n return { res, data };\n }\n\n /**\n * Gets the list of existing applications filtered by parameters.\n *\n * @returns Response wrapped in [[IResultList]]\n *\n * @param {object} filter Object containing filters for querying applications.\n *\n * **Example**\n * ```typescript\n *\n * const filter: object = {\n * pageSize: 100,\n * withTotalPages: true\n * };\n *\n * (async () => {\n * const {data, res, paging} = await applicationService.list(filter);\n * })();\n * ```\n */\n async list(filter: object = {}): Promise<IResultList<IApplication>> {\n return super.list(filter);\n }\n\n /**\n * Gets the list of all application versions.\n *\n * @param {string|number|IIdentified} entityOrId Entity or Id of the entity.\n *\n * @param {object} params Additional request parameters.\n *\n * @returns Returns list of all application versions.\n *\n * **Example**\n * ```typescript\n *\n * const applicationId: number = 1;\n *\n * (async () => {\n * const {res, data} = await applicationService.listVersions(applicationId);\n * })();\n * ```\n */\n async listVersions(\n entityOrId: string | number | IApplication,\n params: object = {}\n ): Promise<IResultList<IApplicationVersion>> {\n const id = this.getEntityId(entityOrId);\n const url = `${this.listUrl}/${id}/versions`;\n const headers = { 'content-type': 'application/json' };\n try {\n const res = await this.fetch(url, { headers, params });\n const data = (await res.json())?.applicationVersions;\n return { res, data };\n } catch (ex) {\n if (ex.res.status === 404) {\n const { data: appDetail, res } = await this.detail(entityOrId);\n return { res, data: appDetail.applicationVersions };\n }\n throw ex;\n }\n }\n\n /**\n * Gets the details of selected application.\n *\n * @param {string|number|IIdentified} entityOrId Entity or Id of the entity.\n *\n * @returns Response wrapped in [[IResult]]\n *\n * **Example**\n * ```typescript\n *\n * const applicationId: number = 1;\n *\n * (async () => {\n * const {data, res} = await applicationService.detail(applicationId);\n * })();\n * ```\n */\n async detail(entityOrId: string | number | IApplication): Promise<IResult<IApplication>> {\n return super.detail(entityOrId);\n }\n\n /**\n * Updates existing application.\n * Make sure that you specifiy the application id within the update object.\n *\n * @param {IIdentified} entity Application object.\n *\n * @returns Response wrapped in [[IResult]]\n *\n * **Example**\n * ```typescript\n *\n * const updateApp = {\n * id: 38\n * name: 'Updated application'\n * };\n *\n * (async () => {\n * const {data, res} = await applicationService.update(updateApp);\n * })();\n * ```\n */\n async update(entity: IApplication): Promise<IResult<IApplication>> {\n return super.update(entity);\n }\n\n /**\n * Removes an application with given id.\n *\n * @returns Response wrapped in [[IResult]]\n *\n * @param {string | number | IIdentified} entityOrId entity or id of the application.\n *\n * **Example**\n * ```typescript\n *\n * const removeApp: object = {\n * id: 38\n * };\n *\n * (async () => {\n * const {data, res} = await applicationService.delete(removeApp);\n * // data will be null\n * })();\n * ```\n */\n async delete(entityOrId: string | number | IApplication): Promise<IResult<null>> {\n return super.delete(entityOrId);\n }\n\n async listByName(name: string): Promise<IResultList<IApplication>> {\n const headers = { 'content-type': 'application/json' };\n const url = `applicationsByName/${encodeURIComponent(name)}`;\n const res = await this.fetch(url, { headers });\n const json = await res.json();\n const data = json[this.propertyName];\n return { res, data };\n }\n\n async listByTenant(\n tenantOrName?: string | ITenant,\n params: object = {}\n ): Promise<IResultList<IApplication>> {\n const headers = { 'content-type': 'application/json' };\n const tenantService = new TenantService(this.client);\n const tenantName = this.getIdString(tenantOrName || (await tenantService.current()).data.name);\n const url = `applicationsByTenant/${encodeURIComponent(tenantName)}`;\n const res = await this.fetch(url, { headers, params });\n const json = await res.json();\n const data = json[this.propertyName];\n return { res, data };\n }\n\n async listByOwner(\n tenantOrName?: string | ITenant,\n params: object = {}\n ): Promise<IResultList<IApplication>> {\n const headers = { 'content-type': 'application/json' };\n const tenantService = new TenantService(this.client);\n const tenantName = this.getIdString(tenantOrName || (await tenantService.current()).data.name);\n const url = `applicationsByOwner/${encodeURIComponent(tenantName)}`;\n const res = await this.fetch(url, { headers, params });\n const json = await res.json();\n const data = json[this.propertyName];\n return { res, data };\n }\n\n async listByUser(\n userOrId?: string | number | IUser,\n params: object = {}\n ): Promise<IResultList<IApplication>> {\n const headers = { 'content-type': 'application/json' };\n const userService = new UserService(this.client);\n const userId = this.getIdString(userOrId || (await userService.current()).data);\n const url = `applicationsByUser/${encodeURIComponent(userId)}`;\n const res = await this.fetch(url, { headers, params });\n const json = await res.json();\n const data = json[this.propertyName];\n return { res, data };\n }\n\n async reactivateArchive(appId: number | string): Promise<IResult<null>> {\n const url = `${this.listUrl}/${appId}/refresh`;\n const method = 'POST';\n const body = '';\n const headers = { 'content-type': 'application/json', accept: 'application/json' };\n const res = await this.fetch(url, { method, body, headers });\n return { res, data: null };\n }\n\n binary(application: string | number | IApplication): ApplicationBinaryService {\n return new ApplicationBinaryService(this.client, application);\n }\n\n getHref(application: IApplication): string {\n if (application.type === ApplicationType.EXTERNAL) {\n return application.externalUrl;\n }\n return `/apps/${application.public ? 'public/' : ''}${application.contextPath}`;\n }\n\n /**\n * Checks if current user can access specified application.\n *\n * @returns Response wrapped in [[IResult]]\n *\n * @param {string | IApplication} application Application name or contextPath as a\n * string or Application object.\n *\n * **Example**\n * ```typescript\n *\n * const checkApp: object = {\n * name: 'myApplication'\n * };\n *\n * (async () => {\n * const {data, res} = await applicationService.isAvailable(checkApp);\n * })();\n * ```\n */\n async isAvailable(application: string | Partial<IApplication>): Promise<IResult<boolean>> {\n const { res, data } = await this.listByUser(undefined, {\n dropOverwrittenApps: true,\n noPaging: true\n });\n\n const available: boolean = (data || []).some((availableApp: IApplication) =>\n typeof application === 'string'\n ? availableApp.name === application || availableApp.contextPath === application\n : this.isMatch(availableApp, application)\n );\n\n return { data: available, res };\n }\n\n /**\n * Gets instance details of the specified application (microservice).\n *\n * @param {string|number|IApplication} entityOrId Entity or Id of the application.\n *\n * @returns Response wrapped in [[IResultList]]\n *\n * **Example**\n * ```typescript\n *\n * const applicationId: number = 1;\n *\n * (async () => {\n * const {data, res} = await applicationService.getStatusDetails(applicationId);\n * })();\n * ```\n */\n async getStatusDetails(\n entityOrId: string | number | IApplication\n ): Promise<IResultList<IApplicationManagedObject>> {\n const appId = this.getEntityId(entityOrId);\n const inventory = new InventoryService(this.client, this.realtime);\n return inventory.list({ type: `c8y_Application_${appId}` });\n }\n\n /**\n * Extracts instance names of the provided IApplicationManagedObject.\n *\n * @param {IApplicationManagedObject} appStatusDetails Application details managedObject.\n *\n * @returns instance names\n *\n * **Example**\n * ```typescript\n *\n * const applicationId: number = 1;\n *\n * (async () => {\n * const {data, res} = await applicationService.getStatusDetails(applicationId);\n * const instances = data.map((appMO) => applicationService.getInstanceNames(appMO));\n * })();\n * ```\n */\n getInstanceNames(appStatusDetails: IApplicationManagedObject): string[] {\n let instanceNames = new Array<string>();\n if (appStatusDetails && appStatusDetails.c8y_Status && appStatusDetails.c8y_Status.instances) {\n instanceNames = Object.keys(appStatusDetails.c8y_Status.instances);\n }\n return instanceNames;\n }\n\n /**\n * Get log for a specific application instance.\n *\n * @param {string|number|IApplication} entityOrId Entity or Id of the application.\n *\n * @param {string} instanceName instance name of the application.\n *\n * @param {IApplicationInstanceLogRequestParams} params Object containing parameters for querying the log file.\n *\n * @returns Response wrapped in [[IResult]]\n *\n * **Example**\n * ```typescript\n *\n * const applicationId: number = 1;\n * const applicationInstanceName: string = 'apama-ctrl-1c-4g-scope-t123456789-deployment-abcdefghij-abcde';\n *\n * (async () => {\n * const {data, res} = await applicationService.getInstanceLog(applicationId, applicationInstanceName);\n * })();\n * ```\n */\n async getInstanceLog(\n entityOrId: string | number | IApplication,\n instanceName: string,\n params?: IApplicationInstanceLogRequestParams\n ): Promise<IResult<IApplicationInstanceLog>> {\n const url = `${this.getDetailUrl(entityOrId)}/logs/${instanceName}`;\n const headers = { accept: this.mimeType('applicationLogs') };\n const res = await this.fetch(url, { headers, params });\n const data = await res.json();\n return { res, data };\n }\n\n /**\n * Dynamic options are stored on the API in a specific `config: {}` object. They can\n * be used to configure the app dynamically.\n *\n * Note: To avoids conflicts with the default Config, it is recommended\n * to use a certain namespace.\n * @param entityOrId Entity or Id of the application.\n * @param config Configuration to be updated.\n * @returns Returns updated configuration.\n */\n async updateApplicationConfig<T>(\n entityOrId: string | number | IApplication,\n config: T\n ): Promise<IApplication & { config: T }> {\n const id = this.getEntityId(entityOrId);\n const { data: app } = await this.detail(id);\n const currentConfig = app?.config || {};\n const newConfig = { ...currentConfig, ...config };\n const updatedConfigApp = await this.update({\n id,\n config: newConfig\n });\n return (await updatedConfigApp)?.data as any;\n }\n\n /**\n * Gets manifest (cumulocity.json file) of a given application.\n *\n * @param {IApplication} app Application entity.\n *\n * @param {string} app version\n *\n * @returns Application manifest object.\n */\n async getAppManifest(app: IApplication, version?: string): Promise<IManifest> {\n const date = new Date();\n let result: IFetchResponse;\n if (!version) {\n result = await this.client.fetch(\n `/apps/${app.contextPath}/cumulocity.json?nocache=${date.getTime()}`\n );\n } else {\n result = await this.client.fetch(\n `/apps/${app.contextPath}@${version}/cumulocity.json?nocache=${date.getTime()}`\n );\n }\n if (result.status >= 400) {\n throw new Error(gettext('No Cumulocity IoT manifest found.'));\n }\n const c8yJson = await result.json();\n return c8yJson;\n }\n\n /**\n * Updates manifest (cumulocity.json file) of a given application.\n *\n * @param {string|number|IApplication} entityOrId Entity or Id of the application.\n *\n * @param {any} manifestJSON Application manifest object to be stored.\n *\n * @returns Application manifest object.\n */\n async storeAppManifest(entityOrId: string | number | IApplication, manifestJSON: any) {\n return await this.binary(entityOrId).updateFiles([\n { path: 'cumulocity.json', contents: JSON.stringify(manifestJSON) as any }\n ]);\n }\n\n /**\n * Sets tags for specific application package version.\n *\n * @param {IApplication} app Application entity.\n *\n * @param {string} version Application package version which tags will be set.\n *\n * @param {string[]} tags Tags array to set on package version\n *\n * @returns Application version object.\n */\n async setPackageVersionTag(app: IApplication, version: string, tags: string[]) {\n const url = `${this.getDetailUrl(app)}/versions/${version}`;\n const method = 'PUT';\n const body = JSON.stringify({ tags });\n const headers = {\n accept: 'application/vnd.com.nsn.cumulocity.applicationVersion+json;charset=UTF-8;ver=0.9',\n 'content-type': 'application/json'\n };\n const res = await this.fetch(url, { method, body, headers });\n const data = await res.json();\n return { res, data };\n }\n\n /**\n * Retrieves the manifest of the application behind the given context path.\n * @param contextPath\n */\n async getManifestOfContextPath(contextPath: string): Promise<IResult<Partial<IApplication>>> {\n const url = `${this.getDetailUrl(contextPath)}/manifest`;\n const res = await this.fetch(url);\n const { application } = await res.json();\n return {\n res,\n data: application\n };\n }\n\n /**\n * Removes package version.\n *\n * @param {IApplication} app Application entity.\n *\n * @param {IApplicationVersionDeleteParams} params Version or tag indication package to remove.\n *\n * @returns Request response.\n *\n * **Example**\n * ```typescript\n *\n * const { res } = await applicationService.deleteVersionPackage(app, {version: '1.0.0'});\n *\n * const { res } = await applicationService.deleteVersionPackage(app, {tag: 'next'});\n *\n * ```\n */\n async deleteVersionPackage(app: IApplication, params: IApplicationVersionDeleteParams) {\n const url = `${this.getDetailUrl(app)}/versions/`;\n const method = 'DELETE';\n const res = await this.fetch(url, this.changeFetchOptions({ method, params }, url));\n return { res, data: null };\n }\n\n /**\n * Updates the availability of the given application to the provided value.\n *\n * @param {string|number|IApplication} entityOrId Entity or Id of the application.\n *\n * @param {any} availability The new application availability.\n *\n * @returns Updated application.\n */\n async updateApplicationAvailability(\n entityOrId: string | number | IApplication,\n availability: ApplicationAvailability\n ): Promise<IResult<IApplication>> {\n const id = this.getEntityId(entityOrId);\n return await this.update({\n id,\n availability\n });\n }\n\n private isMatch(object, source): boolean {\n return Object.keys(source).every(key => {\n if (Array.isArray(object[key]) && Array.isArray(source[key])) {\n return source[key].every(el => object[key].includes(el));\n } else if (\n typeof object[key] === 'object' &&\n object[key] !== null &&\n typeof source[key] === 'object' &&\n source[key] !== null\n ) {\n return this.isMatch(object[key], source[key]);\n } else {\n return object[key] === source[key];\n }\n });\n }\n}\n","import { IManagedObject } from '../inventory';\n\nexport enum InstanceStatus {\n Up = 'Up',\n Unhealthy = 'Unhealthy',\n Down = 'Down',\n Unknown = 'Unknown'\n}\n\nexport interface ILastUpdated {\n date: {\n $date: string;\n };\n offset: number;\n [key: string]: any;\n}\n\nexport interface IInstanceDetails {\n lastUpdated: ILastUpdated;\n memoryInBytes: number;\n scheduled: boolean;\n restarts: number;\n cpuInMillis: number;\n [key: string]: any;\n}\n\nexport interface IApplicationStatus {\n lastUpdated: ILastUpdated;\n instances: {\n [instanceName: string]: IInstanceDetails;\n };\n details: {\n desired: number;\n aggregatedResources: {\n memory: string;\n cpu: string;\n };\n active: number;\n restarts: number;\n };\n status: InstanceStatus;\n [key: string]: any;\n}\n\nexport interface IApplicationManagedObjectAdditions {\n c8y_Status?: IApplicationStatus;\n applicationOwner?: string;\n c8y_Subscriptions?: {\n [tenantId: string]: IApplicationStatus;\n };\n applicationId?: string;\n name?: string;\n c8y_SupportedLogs?: string[];\n [key: string]: any;\n}\n\nexport type IApplicationManagedObject = IManagedObject & IApplicationManagedObjectAdditions;\n\nexport interface IApplicationInstanceLog {\n dateFrom: string;\n dateTo: string;\n logs: string;\n truncated: boolean;\n [key: string]: any;\n}\n\nexport interface IApplicationInstanceLogRequestParams {\n dateFrom?: string;\n dateTo?: string;\n /**\n * Limits the maximum number of lines to be returned by the backend.\n */\n limit?: number;\n [key: string]: any;\n}\n","export enum BillingMode {\n SUBSCRIPTION = 'SUBSCRIPTION',\n RESOURCES = 'RESOURCES'\n}\n","export enum Isolation {\n PER_TENANT = 'PER_TENANT',\n MULTI_TENANT = 'MULTI_TENANT'\n}\n","import { gettext } from '../gettext';\n\nexport enum ApplicationAvailability {\n MARKET = gettext('MARKET'),\n PRIVATE = gettext('PRIVATE'),\n SHARED = gettext('SHARED')\n}\n","import { Service, IResult, IResultList } from '../core';\r\nimport { ISystemOption } from './ISystemOption';\r\n\r\nexport class SystemOptionsService extends Service<ISystemOption> {\r\n protected baseUrl = 'tenant/system';\r\n protected listUrl = 'options';\r\n protected propertyName = 'options';\r\n\r\n /**\r\n * Gets the details of given system option.\r\n *\r\n * @param {string|number|IIdentified} option System option object with mandantory fragments.\r\n *\r\n * @returns Response wrapped in [[IResult]]\r\n *\r\n * **Example**\r\n * ```typescript\r\n *\r\n * const option: ISystemOption = {\r\n * category: 'alarm.type.mapping',\r\n * key: 'temp_to_high'\r\n * };\r\n *\r\n * (async () => {\r\n * const {data, res} = await systemOptionsService.detail(option);\r\n * })();\r\n * ```\r\n */\r\n async detail(option: ISystemOption): Promise<IResult<ISystemOption>> {\r\n return super.detail(option);\r\n }\r\n\r\n /**\r\n * Gets the list of system options filtered by parameters.\r\n *\r\n * @returns Response wrapped in [[IResultList]]\r\n *\r\n * @param {object} filter Object containing filters for querying system options.\r\n *\r\n * **Example**\r\n * ```typescript\r\n *\r\n * const filter: object = {\r\n * pageSize: 100,\r\n * withTotalPages: true\r\n * };\r\n *\r\n * (async () => {\r\n * const {data, res, paging} = await systemOptionsService.list(filter);\r\n * })();\r\n * ```\r\n */\r\n async list(filter: object = {}): Promise<IResultList<ISystemOption>> {\r\n const headers = { 'content-type': 'application/json' };\r\n const url = this.listUrl;\r\n const res = await this.fetch(url, { headers, params: filter });\r\n const json = await res.json();\r\n const data = json[this.propertyName];\r\n\r\n return { res, data };\r\n }\r\n\r\n protected getDetailUrl(option: ISystemOption): string {\r\n return `${this.listUrl}/${option.category}/${option.key}`;\r\n }\r\n\r\n protected onBeforeCreate(obj: ISystemOption): any {\r\n return obj;\r\n }\r\n}\r\n","import { Service, IResultList, IResult, IIdentified } from '../core';\nimport { ITenantOption } from './ITenantOption';\nimport { ITenantOptionDetailParams } from './ITenantOptionDetailParams';\n\n/**\n * @description\n * This service allows for managing tenant's options.\n */\nexport class TenantOptionsService extends Service<ITenantOption> {\n protected baseUrl = 'tenant';\n protected listUrl = 'options';\n protected propertyName = 'options';\n\n private securityOptionsCategories = ['password'];\n private securityOptionsListUrl = 'security-options';\n private systemOptions = 'system';\n\n /**\n * Get a representation of a tenant's option.\n *\n * @param entity Tenant option object.\n * @param params Additional query parameters.\n *\n * @returns Returns promise object that is resolved with\n * the ITenantOption wrapped by IResult.\n *\n * **Example**\n * ```typescript\n * const option: ITenantOption = {\n * category: 'access.control',\n * key: 'allow.origin'\n * };\n * const params: ITenantOptionDetailParams = {\n * evaluate: 'inherited'\n * };\n * (async () => {\n * const { data, res } = await tenantService.detail(option);\n * console.log('value inherited from parent tenant:', data.value);\n * })();\n * ```\n *\n * Required role: ROLE_OPTION_MANAGEMENT_READ\n */\n async detail(\n entity: ITenantOption,\n params: ITenantOptionDetailParams = {}\n ): Promise<IResult<ITenantOption>> {\n return super.detail(entity, params);\n }\n\n /**\n * Creates a new tenant's option.\n *\n * @param {ITenantOption} entity Tenant's Option object.\n *\n * @returns {IResult<IIdentified>} Returns promise object that is resolved with\n * the details of newly created tenant option.\n *\n * **Example**\n * ```typescript\n *\n * const tenantObject = {\n * id: \"sample_tenant\",\n * company: \"sample_company\",\n * domain: \"sample_domain.com\",\n * contactName: \"Mr. Doe\",\n * ...\n * };\n *\n * (async () => {\n * const {data, res} = await tenantService.create(tenantObject);\n * })();\n * ```\n *\n * Required role: ROLE_OPTION_MANAGEMENT_ADMIN<br><br>\n * Options are category-key-value tuples, storing tenant configuration.Some categories of options\n * allow creation of new one, other are limited to predefined set of keys.<br><br>\n * Any option of any tenant can be defined as \"non-editable\" by \"management\" tenant. Afterwards, any PUT or DELETE\n * requests made on that option by the owner tenant, will result in 403 error (Unauthorized).\n */\n async create(entity: ITenantOption): Promise<IResult<ITenantOption>> {\n return super.create(entity);\n }\n\n /**\n * Updates tenant's option data.\n *\n * @param {ITenantOption} entity Tenant option is partially updatable.\n *\n * @returns {IResult<ITenantOption>} Returns promise object that is resolved with the saved tenant option object.\n *\n * **Example**\n * ```typescript\n *\n * const partialUpdateObject: IIdentified = {\n * value : \"http://developer.cumulocity.com\"\n * ...\n * }\n *\n * (async () => {\n * const {data, res} = await tenantOptionsService.update(partialUpdateObject);\n * })();\n * ```\n *\n * Required role: ROLE_OPTION_MANAGEMENT_ADMIN\n */\n async update(entity: ITenantOption): Promise<IResult<ITenantOption>> {\n return super.update(entity);\n }\n\n /**\n * Gets the list of tenant's options filtered by parameters.\n *\n * @param {object} filter Object containing filters for querying tenant options.\n *\n * @returns {IResultList<ITenantOption>} Returns promise object that is resolved\n * with the ITenantOption wrapped by IResultList.\n *\n * **Example**\n * ```typescript\n *\n * const filter: object = {\n * severity: Severity.MAJOR,\n * pageSize: 100,\n * withTotalPages: true\n * };\n *\n * (async () => {\n * const {data, res, paging} = await tenantOptionsService.list(filter);\n * })();\n * ```\n *\n * Required role: ROLE_OPTION_MANAGEMENT_READ\n */\n async list(filter: object = {}): Promise<IResultList<ITenantOption>> {\n return super.list(filter);\n }\n\n /**\n * Delete a representation of a tenant's option.\n *\n * @param {string|number|IIdentified} entityOrId Tenant's option id or tenant's option object.\n *\n * @returns Returns promise object that is resolved with the IResult.\n *\n * **Example**\n * ```typescript\n *\n * const tenantOptionId: string = \"uniqueTenantId\";\n *\n * (async () => {\n * const {data, res} = await tenantOptionsService.delete(tenantOptionId);\n * })();\n * ```\n *\n * Required role: ROLE_TENANT_MANAGEMENT_ADMIN\n */\n async delete(entityOrId: string | number | IIdentified): Promise<IResult<null>> {\n return super.delete(entityOrId);\n }\n\n protected getDetailUrl(entity: ITenantOption): string {\n const encodedCategory = encodeURIComponent(entity.category);\n const encodedKey = encodeURIComponent(entity.key);\n if (this.securityOptionsCategories.indexOf(entity.category) > -1) {\n return `${this.securityOptionsListUrl}/${encodedCategory}/${encodedKey}`;\n } else {\n return `${this.listUrl}/${encodedCategory}/${encodedKey}`;\n }\n }\n\n protected onBeforeCreate(obj: ITenantOption): any {\n return obj;\n }\n}\n","import { Service, IResult } from '../core';\nimport { ITenantSecurityOption } from './ITenantSecurityOption';\n\n/**\n * @description\n * This service allows to get tenant security option.\n */\nexport class TenantSecurityOptionsService extends Service<ITenantSecurityOption> {\n protected baseUrl = 'tenant';\n protected listUrl = 'security-options';\n protected category = 'password';\n protected propertyName = 'options';\n\n /**\n * Get a specific tenant's security option.\n *\n * @param {ITenantSecurityOption} Tenant's security option object with key value.\n *\n * @returns Returns promise object that is resolved with the ITenantSecurityOption wrapped by IResult.\n *\n * **Example**\n * ```typescript\n *\n * const option: ITenantSecurityOption = {\n * key: 'limit.validity'\n * };\n *\n * (async () => {\n * const {data, res} = await tenantSecurityOptionsService.detail(option);\n * })();\n * ```\n */\n async detail(\n tenantSecurityOption: ITenantSecurityOption\n ): Promise<IResult<ITenantSecurityOption>> {\n return super.detail(tenantSecurityOption);\n }\n\n protected getDetailUrl(tenantSecurityOption: ITenantSecurityOption): string {\n return `${this.listUrl}/${this.category}/${tenantSecurityOption.key}`;\n }\n\n protected onBeforeCreate(obj: ITenantSecurityOption): any {\n return obj;\n }\n}\n","import { IIdentified, IResult, IResultList, Service } from '../core';\nimport { ITenantLoginOption } from './ITenantLoginOptions';\n\n/**\n * @description\n * This service allows to get tenant login options.\n */\nexport class TenantLoginOptionsService extends Service<ITenantLoginOption> {\n protected baseUrl = 'tenant';\n protected listUrl = 'loginOptions';\n protected propertyName = 'loginOptions';\n\n /**\n * Gets the details of login option.\n *\n * @param entityIdentityOrId Login option's id or login option object.\n *\n * @returns Returns promise object that is resolved with the ITenantLoginOption wrapped by IResult.\n *\n * **Example**\n * ```typescript\n *\n * const tenantLoginOptionId: string = 'uniqueTenantLoginOptionId';\n *\n * (async () => {\n * const {data, res} = await tenantLoginOptionsService.detail(tenantLoginOptionId);\n * })();\n * ```\n */\n async detail(entityIdentityOrId: string | IIdentified): Promise<IResult<ITenantLoginOption>> {\n return super.detail(entityIdentityOrId);\n }\n\n /**\n * Gets the list of tenant's login options filtered by parameters.\n *\n * @param filter Object containing filters for querying tenant's login options.\n *\n * @returns Returns promise object that is resolved with the ITenantLoginOption wrapped by IResultList.\n *\n * **Example**\n * ```typescript\n *\n * const filter: object = {\n * tenantId: '1111111'\n * };\n *\n * (async () => {\n * const {data, res, paging} = await tenantLoginOptionsService.list(filter);\n * })();\n * ```\n */\n async list(filter: object = {}): Promise<IResultList<ITenantLoginOption>> {\n return super.list(filter);\n }\n\n /**\n * Gets the list of all tenant's login options for current tenant.\n *\n * @returns Returns promise object that is resolved with the ITenantLoginOption wrapped by IResultList.\n *\n * **Example**\n * ```typescript\n *\n * (async () => {\n * const {data, res, paging} = await tenantLoginOptionsService.listForCurrentTenant();\n * })();\n * ```\n */\n async listForCurrentTenant(): Promise<IResultList<ITenantLoginOption>> {\n return super.list({ tenantId: this.client.tenant });\n }\n\n /**\n * Gets the list of all tenant's login options for management tenant.\n *\n * @returns Returns promise object that is resolved with the ITenantLoginOption wrapped by IResultList.\n *\n * **Example**\n * ```typescript\n *\n * (async () => {\n * const {data, res, paging} = await tenantLoginOptionsService.listForManagement();\n * })();\n * ```\n */\n async listForManagement(): Promise<IResultList<ITenantLoginOption>> {\n return super.list({ management: true });\n }\n\n /**\n * Creates a new tenant login option.\n *\n * @param entity ITenantLoginOption object.\n *\n * @returns Returns promise object that is resolved with the details of newly created tenant login option.\n *\n * **Example**\n * ```typescript\n *\n * const tenantLoginOption: ITenantLoginOption = {\n * grantType: \"PASSWORD\",\n * providerName: \"Cumulocity\",\n * type: \"BASIC\",\n * userManagementSource: \"INTERNAL\",\n * visibleOnLoginPage: true\n * };\n *\n * (async () => {\n * const {data, res} = await tenantLoginOptionsService.create(tenantLoginOption);\n * })();\n * ```\n */\n async create(entity: ITenantLoginOption): Promise<IResult<ITenantLoginOption>> {\n return super.create(entity);\n }\n\n /**\n * Updates tenant's login option data.\n *\n * @param entity ITenantLoginOption object.\n *\n * @returns Returns promise object that is resolved with the saved tenant's login option object.\n *\n * **Example**\n * ```typescript\n *\n * const tenantLoginOption: ITenantLoginOption = {\n * grantType: \"PASSWORD\",\n * id: \"2eff9a0b-e376-4ce8-a0f1-0a07cef8a8a1\",\n * providerName: \"Cumulocity\",\n * type: \"BASIC\",\n * userManagementSource: \"INTERNAL\",\n * visibleOnLoginPage: true\n * };\n *\n * (async () => {\n * const {data, res} = await tenantLoginOptionsService.update(tenantLoginOption);\n * })();\n * ```\n */\n async update(entity: ITenantLoginOption): Promise<IResult<ITenantLoginOption>> {\n return super.update(entity);\n }\n\n /**\n * Update tenant's login option data if id exists in object, otherwise create new entity.\n *\n * @param entity ITenantLoginOption object.\n *\n * @returns Returns promise object that is resolved with the saved tenant's login option object.\n *\n * **Example**\n * ```typescript\n *\n * const tenantLoginOption: ITenantLoginOption = {\n * grantType: \"PASSWORD\",\n * id: \"2eff9a0b-e376-4ce8-a0f1-0a07cef8a8a1\",\n * providerName: \"Cumulocity\",\n * type: \"BASIC\",\n * userManagementSource: \"INTERNAL\",\n * visibleOnLoginPage: true\n * };\n *\n * (async () => {\n * const {data, res} = await tenantLoginOptionsService.save(tenantLoginOption);\n * })();\n * ```\n */\n async save(entity: ITenantLoginOption): Promise<IResult<ITenantLoginOption>> {\n return entity.id ? this.update(entity) : this.create(entity);\n }\n\n /**\n * Removes tenant's login option.\n *\n * @param entityOrId Tenant's login option's id or tenant's login option object.\n *\n * @returns Returns promise object that is resolved with the IResult of null.\n *\n * **Example**\n * ```typescript\n *\n * const tenantLoginOptionId: string = 'uniqueTenantLoginOptionId';\n *\n * (async () => {\n * const {data, res} = await tenantLoginOptionsService.delete(tenantLoginOptionId);\n * })();\n * ```\n */\n async delete(entityOrId: string | IIdentified): Promise<IResult<null>> {\n return super.delete(entityOrId);\n }\n}\n","/**\n * A list of supported [[ITenantLoginOption]] which\n * describe the way a user can login to the Platform.\n */\nimport { TfaStrategy } from '../tenant';\n\nexport interface ITenantLoginOptions {\n /**\n * Link to the resource\n */\n self?: string;\n /**\n * The list of tenant login options\n */\n loginOptions: ITenantLoginOption[];\n}\n\n/**\n * Describes the login option which can be requested by any\n * application on startup without login. It describes which kind\n * of login mechanism (e.g. Basic, SSO or OAI-Secure) is\n * supported by the current Platform.\n */\nexport interface ITenantLoginOption {\n /**\n * Identifies the login option\n */\n id?: string;\n /**\n * Login option type\n */\n type?: TenantLoginOptionType;\n /**\n * Grant type\n */\n grantType?: GrantType;\n /**\n * The origin of the users REMOTE or INTERNAL\n */\n userManagementSource: UserManagementSource;\n /**\n * Link to the resource\n */\n self?: string;\n /**\n * The strategy for Two Factor Authentication\n */\n tfaStrategy?: TfaStrategy;\n /**\n * Indicates whether the login option should be visible on the login page of UI applications.\n * If set to `true` for more than one login option, then the preferred one will be selected according to priority:\n * 1. OAI-Secure: authentication information is stored in a HttpOnly cookie\n * 2. Basic Auth: authentication information is stored in a session storage\n * 3. SSO redirect: allows a user to login with a single 3rd-party authorization server using the OAuth2 protocol.\n * If no login option has `visibleOnLoginPage` set to `true`, the preferred login option will be Basic Auth.\n */\n visibleOnLoginPage?: boolean;\n /**\n * The label which is shown on the login button\n */\n buttonName?: string;\n /**\n * The request which is used to initialize an oauth flow\n */\n initRequest?: string;\n /**\n * Determines if password strength is enforced on system level\n */\n enforceStrength?: boolean;\n /**\n * Minimum length of a password to be considered as a “green” strong one\n */\n greenMinLength?: number;\n /**\n * Determines if password strength is enforced on tenant level\n */\n strengthValidity?: boolean;\n /**\n * Organizations name which provides login option\n */\n providerName?: string;\n /**\n * Basic authentication restrictions.\n */\n authenticationRestrictions?: IAuthenticationRestrictions;\n /**\n * Configuration for OAI-Secure sessions.\n */\n sessionConfiguration?: ISessionConfiguration;\n /**\n * Tenant correct domain for OAI-Secure login option.\n * UI will redirect to this domain if OAI-Secure is\n * set as preferred login mode and domain in browser is wrong.\n */\n loginRedirectDomain?: string;\n}\n\nexport interface IAuthenticationRestrictions {\n /**\n * The list of user agents which are allowed to use the platform's REST API.\n * The values are compared with `User-Agent` HTTP header.\n */\n trustedUserAgents: string[];\n\n /**\n * The list of user agents which are forbidden to use the platform's REST API.\n * The values are compared with `User-Agent` HTTP header.\n */\n forbiddenUserAgents: string[];\n\n /**\n * The list of clients which are forbidden to use the platform's REST API.\n * For now, the only value supported in the array is `'WEB_BROWSERS'` (which blocks all web browsers).\n */\n forbiddenClients: string[];\n}\n\nexport interface ISessionConfiguration {\n /**\n * The maximum amount of time a session can be active.\n */\n absoluteTimeoutMillis: number;\n /**\n * The maximum amount of sessions per user.\n */\n maximumNumberOfParallelSessions: number;\n /**\n * The timeout after which the session id is automatically renewed. If there is no activity after renewal timeout and before absolute session timeout, the session will not be renewed.\n */\n renewalTimeoutMillis: number;\n /**\n * If `true`, then every request needs to use the same `User-Agent` header as the first request which initiated the session.\n */\n userAgentValidationRequired: boolean;\n}\n\nexport enum TenantLoginOptionType {\n /**\n * OAI-Secure: authentication information is stored in a HttpOnly cookie\n */\n OAUTH2_INTERNAL = 'OAUTH2_INTERNAL',\n /**\n * SSO redirect: allows a user to login with a single 3rd-party authorization server using the OAuth2 protocol.\n */\n OAUTH2 = 'OAUTH2',\n /**\n * Basic Auth: authentication information is stored in a session storage\n */\n BASIC = 'BASIC'\n}\n\nexport enum GrantType {\n AUTHORIZATION_CODE = 'AUTHORIZATION_CODE',\n PASSWORD = 'PASSWORD'\n}\n\nexport enum UserManagementSource {\n REMOTE = 'REMOTE',\n INTERNAL = 'INTERNAL'\n}\n","import { Service, IResult, IResultList } from '../core';\nimport { IAuditRecord } from './IAuditRecord';\n\nexport class AuditService extends Service<IAuditRecord> {\n protected baseUrl = 'audit';\n protected listUrl = 'auditRecords';\n protected propertyName = 'auditRecords';\n\n /**\n * Gets the details of selected audit record.\n *\n * @param {string|number|IAuditRecord} entityOrId Entity or Id of the entity.\n *\n * @returns Response wrapped in [[IResult]]\n *\n * **Example**\n * ```typescript\n *\n * const auditId: number = 1;\n *\n * (async () => {\n * const {data, res} = await auditService.detail(auditId);\n * })();\n * ```\n */\n async detail(entityOrId: string | number | IAuditRecord): Promise<IResult<IAuditRecord>> {\n return super.detail(entityOrId);\n }\n\n /**\n * Creates a new audit record for a given source.\n *\n * @param {IAuditRecord} entity Audit record object with mandantory fragments.\n * IAuditRecord implements the [[IEvent]] interface.\n *\n * @returns Response wrapped in [[IResult]]\n *\n * **Example**\n * ```typescript\n *\n * const mandantoryObject: IAuditRecord = {\n * type: AuditRecordType.ALARM,\n * time: '2018-05-02T10:08:00Z',\n * severity: Severity.MAJOR,\n * source: {id: 1}\n * };\n *\n * (async () => {\n * const {data, res} = await auditService.create(mandantoryObject);\n * })();\n * ```\n */\n async create(entity: IAuditRecord): Promise<IResult<IAuditRecord>> {\n return super.create(entity);\n }\n\n /**\n * Gets the list of audit records filtered by parameters.\n *\n * @returns Response wrapped in [[IResultList]]\n *\n * @param {object} filter Object containing filters for querying audit records.\n *\n * **Example**\n * ```typescript\n *\n * const filter: object = {\n * severity: Severity.MAJOR,\n * pageSize: 100,\n * withTotalPages: true\n * };\n *\n * (async () => {\n * const {data, res, paging} = await auditService.list(filter);\n * })();\n * ```\n */\n async list(filter: object = {}): Promise<IResultList<IAuditRecord>> {\n return super.list(filter);\n }\n}\n","/**\n * A specific audit record can have one of the following types\n */\nexport enum AuditRecordType {\n ALARM = 'Alarm',\n BULK_OPERATION = 'BulkOperation',\n CEP_MODULE = 'CepModule', // FIXME: legacy type. Remains because there might be audits from before migration to apama.\n EVENT = 'Event',\n INVENTORY = 'Inventory',\n INVENTORY_ROLE = 'InventoryRole',\n OPERATION = 'Operation',\n OPTION = 'Option',\n GROUP = 'Group',\n SMART_RULE = 'SmartRule',\n SYSTEM = 'SYSTEM',\n TENANT = 'Tenant',\n USER = 'User'\n}\n","import { gettext } from '../gettext';\r\n\r\n/**\r\n * An audit record can have one of the following change type\r\n */\r\nexport enum ChangeType {\r\n ADDED = gettext('ADDED'),\r\n REPLACED = gettext('REPLACED'),\r\n REMOVED = gettext('REMOVED')\r\n}\r\n","import { IIdentified, Service, IResult, IResultList } from '../core';\n\nexport class InventoryRoleService extends Service<IIdentified> {\n protected baseUrl = 'user';\n protected listUrl = 'inventoryroles';\n protected propertyName = 'roles';\n\n /**\n * Gets the details of inventory role.\n *\n * @param {string|number|IIdentified} entityOrId Entity or Id of the entity.\n *\n * @returns Response wrapped in [[IResult]]\n *\n * **Example**\n * ```typescript\n *\n * const inventoryRoleId: number = 1;\n *\n * (async () => {\n * const {data, res} = await inventoryRoleService.detail(inventoryRoleId);\n * })();\n * ```\n */\n async detail(entityOrId: string | number | IIdentified): Promise<IResult<IIdentified>> {\n return super.detail(entityOrId);\n }\n\n /**\n * Creates a new inventory role.\n *\n * @param {IIdentified} entity\n *\n * @returns Response wrapped in [[IResult]]\n *\n * **Example**\n * ```typescript\n *\n * const newRole: IIdentified = {\n * name: 'Custom role'\n * };\n *\n * (async () => {\n * const {data, res} = await inventoryRoleService.create(newRole);\n * })();\n * ```\n */\n async create(entity: IIdentified): Promise<IResult<IIdentified>> {\n return super.create(entity);\n }\n\n /**\n * Updates inventory role data.\n *\n * @param {IIdentified} entity\n *\n * @returns Response wrapped in [[IResult]]\n *\n * **Example**\n * ```typescript\n *\n * const updateObject: IIdentified = {\n * id: 1,\n * name: 'changed role'\n * };\n *\n * (async () => {\n * const {data, res} = await inventoryRoleService.update(updateObject);\n * })();\n * ```\n */\n async update(entity: IIdentified): Promise<IResult<IIdentified>> {\n return super.update(entity);\n }\n\n /**\n * Gets the list of inventory roles filtered by parameters.\n *\n * @returns Response wrapped in [[IResultList]]\n *\n * @param {object} filter Object containing filters for querying alarms.\n *\n * **Example**\n * ```typescript\n *\n * const filter: object = {\n * pageSize: 100,\n * withTotalPages: true\n * };\n *\n * (async () => {\n * const {data, res, paging} = await inventoryRoleService.list(filter);\n * })();\n * ```\n */\n async list(filter: object = {}): Promise<IResultList<IIdentified>> {\n return super.list(filter);\n }\n\n /**\n * Removes an inventory role with given id.\n *\n * @returns Response wrapped in [[IResult]]\n *\n * @param {IExternalIdentity} identity Identity object with mandantory fragments.\n *\n * **Example**\n * ```typescript\n *\n * const id: number = 1;\n *\n * (async () => {\n * const {data, res} = await identityService.delete(id);\n * })();\n * ```\n */\n async delete(entityOrId: string | number | IIdentified): Promise<IResult<null>> {\n return super.delete(entityOrId);\n }\n}\n","import { gettext } from '../gettext';\n\n/**\n * Device registration can have one of the following states.\n */\nexport enum DeviceRegistrationStatus {\n WAITING_FOR_CONNECTION = gettext('WAITING_FOR_CONNECTION'),\n PENDING_ACCEPTANCE = gettext('PENDING_ACCEPTANCE'),\n ACCEPTED = gettext('ACCEPTED'),\n BLOCKED = gettext('BLOCKED')\n}\n","import { btoa } from 'b2a';\nimport { IIdentified, Service, IResult, IResultList } from '../core';\nimport {\n IDeviceRegistration,\n IDeviceRegistrationAccept,\n IDeviceRegistrationCreate,\n IDeviceRegistrationLimit\n} from './IDeviceRegistration';\nimport { DeviceRegistrationStatus } from './DeviceRegistrationStatus';\nimport { IDeviceCredentials } from './IDeviceCredentials';\n\n/**\n * Interface to use as options parameter\n * to bootstrap a new device.\n */\nexport interface IDeviceBootstrapOptions {\n /**\n * If already logged in it is accessible via\n * client.auth.getFetchOptions, see [[BasicAuth.getFetchOptions]]\n *\n * **Example**\n * ``` typescript\n *\n * // tenant/username:password\n * const basicAuthToken = 'Basic dGVuYW50L3VzZXJuYW1lOnBhc3N3b3Jk';\n * ```\n */\n basicAuthToken?: string;\n /**\n * Object to define username and password\n * as string.\n *\n * **Example**\n * ``` typescript\n *\n * const basicAuth = {\n * user: 'username',\n * pass: 'password'\n * }\n * ```\n */\n basicAuth?: {\n user: string;\n pass: string;\n };\n}\n\n/**\n * This class allows registration of a new device.\n */\nexport class DeviceRegistrationService extends Service<IDeviceRegistration> {\n protected baseUrl = 'devicecontrol';\n protected listUrl = 'newDeviceRequests';\n protected propertyName = 'newDeviceRequests';\n\n /**\n * Gets the details of device registration.\n *\n * @param {string|number|IIdentified} entityOrId Entity or Id of the entity.\n *\n * @returns Response wrapped in [[IResult]]\n *\n * **Example**\n * ```typescript\n *\n * const entityId: number = 1;\n *\n * (async () => {\n * const {data, res} = await deviceRegistrationService.detail(entityId);\n * })();\n * ```\n */\n async detail(entityOrId: string | number | IIdentified) {\n return super.detail(entityOrId);\n }\n\n /**\n * Creates a new device registration.\n *\n * @param {IDeviceRegistrationCreate} entity Device registration object with mandantory fragments.\n *\n * @returns Response wrapped in [[IResult]]\n *\n * **Example**\n * ```typescript\n *\n * const mandantoryObject: IDeviceRegistrationCreate = {\n * id: 1,\n * };\n *\n * (async () => {\n * const {data, res} = await deviceRegistrationService.create(mandantoryObject);\n * })();\n * ```\n */\n async create(entity: IDeviceRegistrationCreate) {\n return super.create(entity);\n }\n\n /**\n * Gets the list of device registrations by parameters.\n *\n * @returns Response wrapped in [[IResultList]]\n *\n * @param {object} filter Object containing filters for querying registrations.\n *\n * **Example**\n * ```typescript\n *\n * const filter: object = {\n * pageSize: 100,\n * withTotalPages: true\n * };\n *\n * (async () => {\n * const {data, res, paging} = await deviceRegistrationService.list(filter);\n * })();\n * ```\n */\n async list(filter: object = {}) {\n return super.list(filter);\n }\n\n /**\n * Removes an registration with given id.\n *\n * @returns Response wrapped in [[IResult]]\n *\n * @param {string | number | IIdentified} entityOrId entity or id of the registration.\n *\n * **Example**\n * ```typescript\n *\n * const id = 'abc';\n *\n * (async () => {\n * const {data, res} = await deviceRegistrationService.delete(id);\n * // data will be null\n * })();\n * ```\n */\n async delete(entityOrId: string | number | IIdentified) {\n return super.delete(entityOrId);\n }\n\n /**\n * Accepts the device registration for given id.\n *\n * @returns Response wrapped in [[IResult]]\n *\n * @param {string | number | IIdentified} entityOrId entity or id of registration.\n *\n * **Example**\n * ```typescript\n *\n * const id = 'abc';\n *\n * (async () => {\n * const {data, res} = await deviceRegistrationService.accept(id);\n * })();\n * ```\n */\n async accept(entityOrId: string | number | IIdentified): Promise<IResult<IDeviceRegistration>> {\n const securityToken: string = this.getSecurityToken(entityOrId);\n let payload: Partial<IDeviceRegistration> = {\n id: this.getIdString(entityOrId),\n status: DeviceRegistrationStatus.ACCEPTED\n };\n\n if (securityToken) {\n payload = {\n ...payload,\n securityToken\n };\n }\n return super.update(payload);\n }\n\n /**\n * Accepts the device registration for all registrations in pending acceptance.\n *\n * @returns Response wrapped in [[IResultList]]\n *\n * **Example**\n * ```typescript\n *\n * (async () => {\n * const {data, res} = await deviceRegistrationService.acceptAll();\n * })();\n * ```\n */\n async acceptAll(): Promise<IResultList<IDeviceRegistrationAccept>> {\n const res = await super.fetch(`${this.listUrl}/acceptAll`, { method: 'POST' });\n const data = (await res.json()) as IDeviceRegistrationAccept[];\n return { res, data };\n }\n\n /**\n * Gets limitation information for registering devices to the platform\n *\n * @returns Response wrapped in [[IResult]]\n *\n * **Example**\n * ```typescript\n *\n * (async () => {\n * const {data, res} = await deviceRegistrationService.limit();\n * })();\n * ```\n */\n async limit(): Promise<IResult<IDeviceRegistrationLimit>> {\n const res = await super.fetch(`${this.listUrl}/limit`);\n const data = (await res.json()) as IDeviceRegistrationLimit;\n return { res, data };\n }\n\n /**\n * Bootstraps the device with given id.\n *\n * @param entityOrId entity or id of registration.\n * @param options for details see [[IDeviceBootstrapOptions]]\n *\n * **Example**\n * ```typescript\n *\n * const id: 'abc';\n * const options: IDeviceBootstrapOptions = {\n * basicAuthToken: 'Basic dGVuYW50L3VzZXJuYW1lOnBhc3N3b3Jk',\n * basicAuth: {\n * user: 'username',\n * pass: 'password'\n * }\n * };\n *\n * (async () => {\n * const {data, res} = await deviceRegistrationService.bootstrap(id, options);\n * })();\n * ```\n */\n async bootstrap(\n entityOrId: string | number | IIdentified,\n options: IDeviceBootstrapOptions\n ): Promise<IResult<IDeviceCredentials>> {\n const id = this.getIdString(entityOrId);\n const securityToken = this.getSecurityToken(entityOrId);\n const body = securityToken ? JSON.stringify({ id, securityToken }) : JSON.stringify({ id });\n const url = `${this.baseUrl}/deviceCredentials`;\n const { basicAuth } = options;\n let { basicAuthToken } = options;\n if (basicAuth) {\n const { user, pass } = basicAuth;\n basicAuthToken = btoa(`${user}:${pass}`);\n }\n const headers = {\n Authorization: `Basic ${basicAuthToken}`,\n accept: 'application/json',\n 'content-type': 'application/json'\n };\n const method = 'POST';\n const res = await this.client.fetch(url, { body, headers, method });\n const data = await res.json();\n if (res.status > 400) {\n throw { res, data };\n }\n return { res, data };\n }\n\n protected onBeforeCreate(entity: IDeviceRegistrationCreate): IDeviceRegistrationCreate {\n return entity;\n }\n\n protected onBeforeUpdate(entity: IDeviceRegistrationCreate): IDeviceRegistrationCreate {\n const noIdEntity = Object.assign({}, entity);\n delete noIdEntity.id;\n return noIdEntity;\n }\n\n protected getDetailUrl(entityOrId: string | number | IIdentified): string {\n const id = encodeURIComponent(this.getEntityId(entityOrId));\n return `${this.listUrl}/${id}`;\n }\n\n private getSecurityToken(entity: string | number | IIdentified): string {\n let securityToken: string;\n if (typeof entity === 'object') {\n securityToken = entity.securityToken ? String(entity.securityToken) : undefined;\n }\n return securityToken;\n }\n}\n","import FormData from 'form-data';\nimport { Stream } from 'stream';\nimport { IFetchClient, IResult } from '../core';\nimport { IDeviceRegistrationBulkResult } from './IDeviceRegistrationBulkResult';\n\n/**\n * This class allows for bulk registering devices.\n */\nexport class DeviceRegistrationBulkService {\n protected client: IFetchClient;\n\n /**\n * Instantiate class and assign client\n * @param {IFetchClient} client\n */\n constructor(client: IFetchClient) {\n this.client = client;\n }\n\n /**\n * A new device registration as bulk.\n *\n * @param {Stream | Buffer} csv\n *\n * @returns Response wrapped in [[IResult]]\n *\n * **Example**\n * ```typescript\n *\n * const csvString = `\n * ID,CREDENTIALS,TENANT,TYPE,NAME,ICCID,IDTYPE,PATH,SHELL\n * e2eDeviceRegistrationId,e2epassword123!,e2edocker,c8y_e2eDevice,e2eDevice,123456789,89456,e2eDeviceGroup,1\n * 900001,e2epassword123!,e2edocker,c8y_e2eDevice1,e2eDevice1,123456789,89456,e2eDeviceGroup,1\n * 900002,e2epassword123!,e2edocker,c8y_e2eDevice2,e2eDevice2,123456789,89456,e2eDeviceGroup,1`.trim();\n *\n * const csvBuffer = Buffer.from(csvString):\n *\n * (async () => {\n * const {data, res} = await deviceRegistrationBulkService.create(csvBuffer);\n * })();\n * ```\n */\n async create(\n inputFile: Stream | Buffer | File | Blob\n ): Promise<IResult<IDeviceRegistrationBulkResult>> {\n let csv = inputFile;\n const url = '/devicecontrol/bulkNewDeviceRequests';\n const method = 'POST';\n const body = new FormData();\n let fileName = 'bulk-registration.csv';\n if (typeof File !== 'undefined' && csv instanceof File) {\n fileName = csv.name;\n const checkPattern = /\\.csv$/;\n if (csv.name.match(checkPattern)) {\n csv = new File([csv], csv.name, { type: 'text/csv' });\n }\n }\n body.append('file', csv, fileName);\n const headers = {\n accept: 'application/json'\n };\n const res = await this.client.fetch(url, { method, body, headers });\n const data = await res.json();\n return { res, data };\n }\n}\n","/**\n * Device registration can have one of the following security modes.\n */\nexport enum DeviceRegistrationSecurityMode {\n REQUIRED = 'REQUIRED',\n OPTIONAL = 'OPTIONAL',\n IGNORED = 'IGNORED'\n}\n","import { Service } from '../core';\nimport { IRole } from './IRole';\n\n/**\n * @description\n * This service allows for fetch user roles.\n */\nexport class UserRoleService extends Service<IRole> {\n protected baseUrl = 'user';\n protected listUrl = 'roles';\n protected propertyName = 'roles';\n\n /**\n * Gets the details of given role.\n *\n * @param {string|number|IRole} entityOrId Roles's id or role object.\n *\n * @returns Returns promise object that is resolved with the IRole wrapped by IResult.\n *\n * **Example**\n * ```typescript\n *\n * const roleId: number = 1;\n *\n * (async () => {\n * const {data, res} = await userRoleService.detail(roleId);\n * })();\n * ```\n */\n async detail(entityOrId: string | number | IRole) {\n return super.detail(entityOrId);\n }\n\n /**\n * Gets the list of user roles filtered by parameters.\n *\n * @param {object} filter Object containing filters for querying roles.\n *\n * @returns Returns promise object that is resolved with the IRole wrapped by IResultList.\n *\n * **Example**\n * ```typescript\n *\n * const filter: object = {\n * severity: Severity.MAJOR,\n * pageSize: 100,\n * withTotalPages: true\n * };\n *\n * (async () => {\n * const {data, res, paging} = await userRoleService.list(filter);\n * })();\n * ```\n */\n async list(filter: object = {}) {\n return super.list(filter);\n }\n}\n","import { IResult, IResultList, IFetchClient, IFetchOptions, IFetchResponse } from '../core';\nimport { IExternalIdentity } from './IExternalIdentity';\n\n/**\n * This class allwos for managing external identifiers.\n */\nexport class IdentityService {\n private baseUrl = 'identity';\n private propertyName = 'externalIds';\n private client: IFetchClient;\n\n constructor(client: IFetchClient) {\n this.client = client;\n }\n\n /**\n * Gets the list of identities filtered by parameters.\n *\n * @returns Response wrapped in [[IResultList]]\n *\n * @param {object} filter Object containing filters for querying identity.\n *\n * **Example**\n * ```typescript\n *\n * const filter: object = {\n * pageSize: 100,\n * withTotalPages: true\n * };\n *\n * (async () => {\n * const {data, res, paging} = await identityService.list(filter);\n * })();\n * ```\n */\n async list(managedObjectId: string): Promise<IResultList<IExternalIdentity>> {\n const headers = { accept: 'application/json' };\n const url = this.getExternalIdsOfGlobalIdUrl(managedObjectId);\n const res = await this.fetch(url, { headers });\n const json = await res.json();\n const data = json[this.propertyName];\n return { res, data };\n }\n\n /**\n * Creates a new identity.\n *\n * @param {IExternalIdentity} identity Identity object with mandantory fragments.\n *\n * @returns Response wrapped in [[IResult]]\n *\n * **Example**\n * ```typescript\n * const linkedManagedObjectId = '123';\n * const identity: IExternalIdentity = {\n * type: 'type',\n * externalId: '1',\n * managedObject: {\n * id: linkedManagedObjectId\n * }\n * };\n *\n * (async () => {\n * const {data, res} = await identityService.create(identity);\n * })();\n * ```\n */\n async create(identity: IExternalIdentity): Promise<IResult<IExternalIdentity>> {\n const headers = { 'content-type': 'application/json', accept: 'application/json' };\n const method = 'POST';\n const body = JSON.stringify(identity);\n const url = this.getExternalIdsOfGlobalIdUrl(identity.managedObject.id);\n const res = await this.fetch(url, { headers, method, body });\n const data = await res.json();\n return { res, data };\n }\n\n /**\n * Gets the details of an identity.\n *\n * @param {IExternalIdentity} identity Identity object with mandantory fragments.\n *\n * @returns Response wrapped in [[IResult]]\n *\n * **Example**\n * ```typescript\n *\n * const identity: IExternalIdentity = {\n * type: 'type',\n * externalId: '1'\n * };\n *\n * (async () => {\n * const {data, res} = await identityService.detail(identity);\n * })();\n * ```\n */\n async detail(identity: IExternalIdentity): Promise<IResult<IExternalIdentity>> {\n const headers = { accept: 'application/json' };\n const url = this.getExternalIdUrl(identity);\n const res = await this.fetch(url, { headers });\n const data = await res.json();\n return { res, data };\n }\n\n /**\n * Removes an identity with given id.\n *\n * @returns Response wrapped in [[IResult]]\n *\n * @param {IExternalIdentity} identity Identity object with mandantory fragments.\n *\n * **Example**\n * ```typescript\n *\n * const identity: IExternalIdentity = {\n * type: 'type',\n * externalId: '1'\n * };\n *\n * (async () => {\n * const {data, res} = await identityService.delete(identity);\n * })();\n * ```\n */\n async delete(identity: IExternalIdentity): Promise<IResult<IExternalIdentity>> {\n const headers = { accept: 'application/json' };\n const method = 'DELETE';\n const url = this.getExternalIdUrl(identity);\n const res = await this.fetch(url, { headers, method });\n return { res, data: null };\n }\n\n private async fetch(url: string, init?: IFetchOptions): Promise<IFetchResponse> {\n const res: IFetchResponse = await this.client.fetch(url, init);\n if (res.status >= 400) {\n let data = null;\n try {\n data = await res.json();\n } catch (ex) {\n try {\n data = await res.text();\n } catch (ex) {\n // do nothing\n }\n }\n throw { res, data };\n }\n return res;\n }\n\n private getExternalIdsOfGlobalIdUrl(managedObjectId: string | number): string {\n return `/${this.baseUrl}/globalIds/${managedObjectId}/externalIds`;\n }\n\n private getExternalIdUrl(identity: IExternalIdentity): string {\n return `/${this.baseUrl}/externalIds/${identity.type}/${identity.externalId}`;\n }\n}\n","import { IResult, Service } from '../core';\nimport { ITrustedCertificate } from './ITrustedCertificate';\n\n/**\n * This class allows for managing trusted certificates.\n */\nexport class TrustedCertificateService extends Service<ITrustedCertificate> {\n protected get baseUrl() {\n return `/tenant/tenants/${this.client.tenant}`;\n }\n protected listUrl = 'trusted-certificates';\n protected proofOfPossessionUrl = 'trusted-certificates-pop';\n protected propertyName = 'certificates';\n\n /**\n * Gets a list of trusted certificates.\n *\n * @returns Response wrapped in [[IResultList]].\n *\n * **Example**\n * ```typescript\n *\n * (async () => {\n * const {data, res} = await trustedCertificateService.list();\n * })();\n * ```\n */\n async list(filter: object = {}) {\n return super.list(filter);\n }\n\n /**\n * Gets the details of trusted certificate\n *\n * @param entityOrId Trusted certificate object or trusted certificate fingerprint.\n *\n * @returns Response wrapped in [[IResult]]\n *\n * **Example**\n * ```typescript\n *\n * const fingerprint: string = 'abc';\n *\n * (async () => {\n * const {data, res} = await trustedCertificateService.detail(fingerprint);\n * })();\n * ```\n */\n async detail(entityOrId: string | ITrustedCertificate) {\n return super.detail(entityOrId);\n }\n\n /**\n * Removes a trusted certificate with given fingerprint.\n *\n * @returns Response wrapped in [[IResult]]\n *\n * @param entityOrId Trusted certificate object or trusted certificate fingerprint.\n *\n * **Example**\n * ```typescript\n *\n * const fingerprint: string = 'abc';\n *\n * (async () => {\n * const {data, res} = await trustedCertificateService.delete(fingerprint);\n * })();\n * ```\n */\n async delete(entityOrId: string | ITrustedCertificate) {\n return super.delete(entityOrId);\n }\n\n /**\n * Updates trusted certificate data.\n *\n * @param entity Trusted certificate partial object.\n *\n * @returns Response wrapped in [[IResult]]\n *\n * **Example**\n * ```typescript\n *\n * const certificate: Partial<ITrustedCertificate> = {\n * name: 'Name'\n * };\n *\n * (async () => {\n * const {data, res} = await trustedCertificateService.update(certificate);\n * })();\n * ```\n */\n async update(entity: Partial<ITrustedCertificate>) {\n return super.update(entity);\n }\n\n /**\n * Creates a new trusted certificate.\n *\n * @param entity Trusted certificate object.\n *\n * @returns Response wrapped in [[IResult]]\n *\n * **Example**\n * ```typescript\n *\n * const certificate: Partial<ITrustedCertificate> = {\n * name: 'Name',\n * certInPemFormat: 'MIID+DCCAuCgAwIBAgIJAO1Q9t/M9gYlMA0GC...',\n * status: 'ENABLED'\n * };\n *\n * (async () => {\n * const {data, res} = await trustedCertificateService.create(certificate);\n * })();\n * ```\n */\n async create(entity: Partial<ITrustedCertificate>) {\n return super.create(entity);\n }\n\n /**\n * Regenerates unsigned verification code for trusted certificate.\n *\n *\n * @param entityOrId Trusted certificate object or finger print.\n *\n * @returns Certificate object with new verification code (wrapped in [[IResult]])\n *\n * **Example**\n * ```typescript\n *\n * (async () => {\n * const fingerPrint = '00a360973e3e8d61e05aedb32c72438e2442279e';\n * const {data, res} = await trustedCertificateService.regeneratePoPVerificationCode(fingerPrint);\n * const newProofOfPossessionUnsignedVerificationCode = data.proofOfPossessionUnsignedVerificationCode;\n * })();\n * ```\n */\n async regeneratePoPVerificationCode(\n entityOrId: string | ITrustedCertificate\n ): Promise<IResult<ITrustedCertificate>> {\n const method = 'POST';\n const headers = { 'content-type': 'application/json', Accept: 'application/json' };\n const url = `${this.proofOfPossessionUrl}/${this.getEntityId(entityOrId)}/verification-code`;\n const res = await this.fetch(url, { headers, method });\n const data = await res.json();\n return { res, data };\n }\n\n /**\n * Verifies signed verification code for trusted certificate.\n *\n *\n * @param entityOrId Trusted certificate object or finger print.\n * @param proofOfPossessionSignedVerificationCode Unsigned verification code encrypted by the private key.\n *\n * @returns Certificate object with the result of verification (wrapped in [[IResult]]).\n *\n * **Example**\n * ```typescript\n *\n * (async () => {\n * const fingerPrint = '00a360973e3e8d61e05aedb32c72438e2442279e';\n * const encryptedVerificationCode ='fuvlVWLfXG3V3bJWAdEhPD0HFCrYo5';\n * const {data, res} = await trustedCertificateService.verifySignedVerificationCode(fingerPrint, encryptedVerificationCode);\n * const isCertificateVerified = data.proofOfPossessionValid;\n * })();\n * ```\n */\n async verifySignedVerificationCode(\n entityOrId: string | ITrustedCertificate,\n proofOfPossessionSignedVerificationCode: string\n ): Promise<IResult<ITrustedCertificate>> {\n const method = 'POST';\n const headers = { 'content-type': 'application/json', Accept: 'application/json' };\n const url = `${this.proofOfPossessionUrl}/${this.getEntityId(entityOrId)}/pop`;\n const body = JSON.stringify({ proofOfPossessionSignedVerificationCode });\n const res = await this.fetch(url, { method, body, headers });\n const data = await res.json();\n return { res, data };\n }\n\n protected getDetailUrl(entityOrId: string | ITrustedCertificate): string {\n const id = this.getEntityId(entityOrId);\n return `${this.listUrl}/${id}`;\n }\n\n protected getEntityId(entityOrId: string | ITrustedCertificate): string {\n let id: string;\n if (typeof entityOrId === 'object' && entityOrId.fingerprint) {\n id = entityOrId.fingerprint;\n } else {\n id = entityOrId as string;\n }\n return id;\n }\n}\n","import FormData from 'form-data';\nimport { IFetchOptions, IFetchResponse, IResult, Service } from '../core';\nimport { ICertificateRevocation } from './ICertificateRevocation';\nimport { Stream } from 'stream';\n\n/**\n * This class allows for managing a list of certificate revocations.\n */\nexport class CrlService extends Service<ICertificateRevocation> {\n protected get baseUrl() {\n return `/tenant/trusted-certificates/settings/crl`;\n }\n protected readonly listUrl: string;\n\n /**\n * Uploads a list of certificate revocations.\n * Adds new entries to the certificate revocation list,\n * the ones that already exist are updated.\n * No entries are removed from the certificate revocation list.\n *\n * @returns Returns a status object.\n *\n * **Example**\n * ```typescript\n *\n * const crls: ICertificateRevocation[] = [\n * { serialNumberInHex: '24234', revocationDate: '2023-01-13T23:00:00.000Z' }\n * ];\n *\n * (async () => {\n * const { res } = await crlService.uploadCrls(crls);\n * })();\n * ```\n */\n async uploadCrls(crls: ICertificateRevocation[]): Promise<IResult<null>> {\n const method = 'PUT';\n const headers = { 'content-type': 'application/json', Accept: 'application/json' };\n const body = JSON.stringify({ crls });\n const res = await this.fetch('', { method, body, headers });\n return { res, data: null };\n }\n\n /**\n * Uploads a csv file containing a list of certificate revocations.\n * Adds new entries to the certificate revocation list,\n * the ones that already exist are updated.\n * No entries are removed from the certificate revocation list.\n *\n * File format:\n * SERIALNO,DATE\n * 1234567890abcdef,2023-01-01T00:00:00.000Z\n *\n * @returns Returns a status object.\n *\n * **Example**\n * ```typescript\n *\n * (async () => {\n * const { res } = await crlService.uploadCrlFile( file );\n * })();\n * ```\n */\n async uploadCrlFile(file: Stream | Buffer | File | Blob): Promise<IResult<null>> {\n const method = 'PUT';\n const body = new FormData();\n\n body.append('file', file);\n const headers = {\n accept: 'application/json'\n };\n const res = await this.fetch('', { method, body, headers });\n return { res, data: null };\n }\n\n /**\n * Downloads a certificate revocation list file.\n * To open the downloaded file please use command: openssl crl -inform DER -text -noout -in fileName.crl\n *\n * @returns Returns a arrayBuffer wrapped in [[IFetchResponse]].\n *\n * **Example**\n * ```typescript\n *\n * (async () => {\n * const res = await this.crlService.downloadCrlFile();\n * const arrayBuffer = await res.arrayBuffer();\n * })();\n * ```\n */\n async downloadCrlFile(init?: IFetchOptions): Promise<IFetchResponse> {\n return await this.fetch('', init);\n }\n}\n","import { IFetchClient, IResult } from '../core';\nimport { Service } from '../core/Service';\nimport { IManagedObject, IdReference } from '../inventory';\nexport class SmartGroupsService extends Service<IManagedObject> {\n protected baseUrl = 'inventory';\n protected listUrl = 'managedObjects';\n private readonly SMART_GROUP_TYPE = 'c8y_DynamicGroup';\n private readonly SMART_GROUP_FRAGMENT_TYPE = 'c8y_IsDynamicGroup';\n private readonly COLUMNS_CONFIG_FRAGMENT = 'c8y_DeviceColumnsConfig';\n private readonly FILTER_CONFIG_FRAGMENT = 'c8y_DeviceFilterConfig';\n private readonly QUERY_STRING_FRAGMENT = 'c8y_DeviceQueryString';\n\n constructor(client: IFetchClient) {\n super(client);\n }\n\n /**\n * Gets the details of managed object\n *\n * @param {IdReference} entityOrId Entity or Id of the ManagedObject.\n * @param {object} filter Filter object.\n *\n * @returns Response wrapped in [[IResult]]\n *\n * @example\n * ```typescript\n *\n * const id: string = '1';\n * const filter: any = { withChildren: false };\n *\n * (async () => {\n * const {data, res} = await smartGroupsService.detail(id, filter);\n * })();\n * ```\n */\n async detail(entityOrId: IdReference, filter: object = {}): Promise<IResult<IManagedObject>> {\n return super.detail(entityOrId, filter);\n }\n\n /**\n * Creates a smart group managed object with columns configuration.\n *\n * @param {object} smartGroup Dynamic group managed object.\n * @param {object} deviceQueryString Columns configuration query string to filter the new group.\n * @param {object} configurableColumns Configurable columns definitions.\n * @param {object} filterConfig Columns filter configuration for the new group.\n *\n * @returns Response wrapped in [[IResult]]\n *\n * **Example**\n * ```typescript\n *\n * const smartGroup = { name: 'newName', type: 'c8y_DynamicGroup', c8y_IsDynamicGroup: {} };\n * const deviceQueryString = 'c8y_DeviceQueryString: \"$filter=(name eq 'test*') $orderby=c8y_Hardware.model asc';\n * const configurableColumns = [\n * {headerName: 'Status', active: false, key: 'status'},\n * {headerName: 'Name', active: true, key: 'name', filter: { externalFilterQuery: { name: { names: ['test*'] } } }},\n * {headerName: 'Model', active: true, key: 'model'}\n * ];\n *\n * (async () => {\n * await smartGroupsService.create({ smartGroup, deviceQueryString, configurableColumns });\n * })();\n *\n * Note: filterConfig has been removed as a default property to the input object.\n * Now it is part of the configurable columns properties as it is shown above.\n * You can still pass it as an optional parameter.\n * ( const filterConfig = [{ name: { names: ['test*'] } }] )\n * ```\n */\n async create(obj: Partial<IManagedObject>): Promise<IResult<IManagedObject>> {\n const entity = {\n ...obj.smartGroup,\n [this.QUERY_STRING_FRAGMENT]: obj.deviceQueryString,\n [this.COLUMNS_CONFIG_FRAGMENT]: obj.configurableColumns,\n ...(obj.filterConfig && { [this.FILTER_CONFIG_FRAGMENT]: obj.filterConfig })\n };\n\n return super.create(entity);\n }\n\n /**\n * Updates smart group managed object with given id.\n *\n * @param {Partial<IManagedObject>} mo Partial managed object of the smart group.\n *\n * @returns Response wrapped in [[IResult]]\n *\n * @example\n * ```typescript\n *\n * const smartGroup = { id: '1', name: 'newName' };\n *\n * (async () => {\n * await smartGroupsService.update(smartGroup);\n * })();\n * ```\n */\n async update(mo: Partial<IManagedObject>): Promise<IResult<IManagedObject>> {\n return super.update(mo);\n }\n\n /**\n * Removes managed object with given id.\n *\n * @param {IManagedObject} group Managed object of the group.\n * @param {object} params Additional query params.\n *\n * @returns Response wrapped in [[IResult]]\n *\n * @example\n * ```typescript\n *\n * const group = { id: '1' } as IManagedObject;\n * const params: any = {\n * withChildren: false\n * }\n *\n * (async () => {\n * await smartGroupsService.delete(group, params);\n * })();\n * ```\n */\n async delete(entityOrId: IdReference, params: any = {}): Promise<IResult<null>> {\n const data = (await this.detail(entityOrId, { withChildren: false })).data;\n\n return await super.delete(data, params);\n }\n\n /**\n * Checks whether a given managed object is a smart group\n *\n * @param {IManagedObject} mo Managed object to check.\n *\n * @returns boolean\n *\n * @example\n * ```typescript\n *\n * const mo: IManagedObject = {id: 1, type: \"c8y_DeviceGroup\", c8y_IsDeviceGroup: {}} as IManagedObject;\n *\n * (() => {\n * const isSmartGroup = smartGroupsService.isSmartGroup(mo);\n * })();\n * ```\n */\n isSmartGroup(mo: Partial<IManagedObject>): boolean {\n const hasSmartGroupFragmentType = mo.hasOwnProperty(this.SMART_GROUP_FRAGMENT_TYPE);\n const isSmartGroupType = mo && mo.type === this.SMART_GROUP_TYPE;\n\n return hasSmartGroupFragmentType || isSmartGroupType;\n }\n\n protected getUrl(url = ''): string {\n const partialUrl = url.replace(/^\\/+/, '');\n const baseUrl = this.baseUrl.replace(/\\/+$/, '');\n\n return `${baseUrl}/${partialUrl}`;\n }\n}\n","import { ApplicationService } from '../application';\nimport { IResult } from '../core';\nimport { IFetchClient } from '../core/IFetchClient';\nimport { Service } from '../core/Service';\nimport { IdReference } from '../inventory';\nimport { IRule } from './IRule';\n\nexport class SmartRulesService extends Service<IRule> {\n private static readonly microserviceName = 'smartrule';\n protected readonly baseUrl = 'service/smartrule';\n protected readonly listUrl;\n private readonly rulesUrl = 'smartrules';\n private readonly unupdatableFields = ['type', 'cepModuleId', 'creationTime', 'lastUpdated'];\n private microserviceAvailable: boolean;\n private applicationService: ApplicationService;\n\n constructor(client: IFetchClient) {\n super(client);\n this.applicationService = new ApplicationService(client);\n }\n\n /**\n * Checks if the smart rules microservice is subscribed and available to user.\n *\n * **Example**\n * ```typescript\n *\n * (async () => {\n * const isAvailable = await smartRulesService.isMicroserviceAvailable();\n * })();\n * ```\n */\n async isMicroserviceAvailable(): Promise<boolean> {\n if (this.microserviceAvailable === undefined) {\n this.microserviceAvailable = (\n await this.applicationService.isAvailable(SmartRulesService.microserviceName)\n ).data;\n }\n return this.microserviceAvailable;\n }\n\n /**\n * Gets a list of smart rules for given managed object.\n *\n * @param {IdReference} entityOrId Entity or Id of the ManagedObject.\n *\n * @returns Response wrapped in [[IResult]]\n *\n * **Example**\n * ```typescript\n *\n * const id: string = '1';\n *\n * (async () => {\n * const {data, res} = await smartRulesService.listByContext(id);\n * })();\n * ```\n */\n async listByContext(entityOrId: IdReference): Promise<IResult<IRule[]>> {\n const url = this.contextRulesUrl(entityOrId);\n const res = await this.fetch(url, { method: 'GET' });\n const rules = (await res.json()).rules;\n return { res, data: rules };\n }\n\n /**\n * Deactivates smart rule for given entities list.\n *\n * @param {Partial<IRule>} rule Smart rule managed object.\n * @param {IdReference[]} entitiesOrIdsList List of entities or Id of the ManagedObjects.\n *\n * @returns Response wrapped in [[IResult]]\n *\n * **Example**\n * ```typescript\n *\n * const rule: IRule = {id: '1', enabledSources: ['2', '3'],...};\n * const entityOrIdList: IdReference[] = ['2'];\n * (async () => {\n * const {data, res} = await smartRulesService.bulkDeactivateEnabledSources(rule, entityOrIdList);\n * })();\n * ```\n */\n bulkDeactivateEnabledSources(\n rule: Partial<IRule>,\n entitiesOrIdsList: IdReference[]\n ): Promise<IResult<IRule>> {\n if (entitiesOrIdsList.length === 0) {\n return Promise.resolve({ res: null, data: null });\n }\n const { enabledSources } = rule;\n const newEnabledSources = this.disableEnabledSources(enabledSources, entitiesOrIdsList);\n const ruleCopy = { ...rule };\n\n Object.assign(ruleCopy, { enabledSources: newEnabledSources });\n return this.update(ruleCopy);\n }\n\n /**\n * Updates smart rule.\n *\n * @param {Parial<IRule>} rule Smart rule managed object.\n *\n * @returns Response wrapped in [[IResult]]\n *\n * **Example**\n * ```typescript\n *\n * const rule: IRule = {id: '1', enabledSources: ['2', '3'],...};\n * (async () => {\n * const {data, res} = await smartRulesService.updateSmartRule(rule);\n * })();\n * ```\n */\n async update(rule: Partial<IRule>): Promise<IResult<IRule>> {\n const url = this.getSmartRulesUrl(rule);\n const method = 'PUT';\n const body = JSON.stringify(this.removeUnclonableFields(rule, this.unupdatableFields));\n const headers = { 'content-type': 'application/json', accept: 'application/json' };\n const res = await this.fetch(url, { method, body, headers });\n const data = await res.json();\n\n return { res, data };\n }\n\n private disableEnabledSources(\n enabledSources: string[] = [],\n entityOrIdList: IdReference[]\n ): string[] {\n return enabledSources.filter(id => !this.getListOfStringIds(entityOrIdList).includes(id));\n }\n\n private getListOfStringIds(entityOrIdList: IdReference[]): string[] {\n return entityOrIdList.map(entityOrId => {\n if (typeof entityOrId === 'object' && entityOrId.id) {\n return entityOrId.id.toString();\n }\n return entityOrId.toString();\n });\n }\n\n private getSmartRulesUrl(rule: Partial<IRule>): string {\n const contextMoId = rule && rule.c8y_Context && rule.c8y_Context.id;\n let url = !!contextMoId ? this.contextRulesUrl(contextMoId) : this.rulesUrl;\n\n if (rule.id) {\n url = `${url}/${rule.id}`;\n }\n return url;\n }\n\n private removeUnclonableFields(rule: Partial<IRule>, fieldsToRemove: string[]): Partial<IRule> {\n const ruleCopy = { ...rule };\n fieldsToRemove.forEach(f => {\n delete ruleCopy[f];\n });\n return ruleCopy;\n }\n\n private contextRulesUrl(entityOrId: IdReference = {}): string {\n if (typeof entityOrId === 'object' && entityOrId.id) {\n return `managedObjects/${entityOrId.id}/smartrules`;\n }\n return `managedObjects/${entityOrId}/smartrules`;\n }\n}\n","import {\n BearerAuth,\n CookieAuth,\n IAuthentication,\n ICredentials,\n IFetchResponse,\n IMicroserviceSubscriptionsResponse,\n NodeJSCookieAuth\n} from './core';\nimport { Realtime } from './realtime';\nimport {\n FetchClient,\n BasicAuth,\n AlarmService,\n ApplicationService,\n AuditService,\n DeviceRegistrationBulkService,\n DeviceRegistrationService,\n EventService,\n InventoryBinaryService,\n InventoryRoleService,\n InventoryService,\n MeasurementService,\n OperationBulkService,\n OperationService,\n SystemOptionsService,\n TenantOptionsService,\n TenantSecurityOptionsService,\n TenantLoginOptionsService,\n TenantService,\n UserGroupService,\n UserRoleService,\n UserService,\n IdentityService,\n SmartGroupsService,\n SmartRulesService\n} from './services';\n\nexport interface IBootstrapOptions {\n deviceId: string;\n basicAuthToken: string;\n timeout?: number;\n expire?: number;\n baseUrl?: string;\n}\n\nexport class Client {\n /**\n * Authenticates the given user. Determines the tenant by itself via a call to tenant/currentTenant.\n *\n * **Example**\n * ```typescript\n *\n * let client: Client;\n * (async () => {\n * client = await Client.authenticate({\n * user: 'testuser',\n * password: 'password1337!'\n * }, 'https://acme.cumulocity.com');\n *\n * //you have access to the client api now\n * const { data, paging, res }); = await client.inventory.list({ pageSize: 100 });\n * })();\n * ```\n */\n static async authenticate(credentials: ICredentials, baseUrl?: string): Promise<Client> {\n const auth = new BasicAuth(credentials);\n const clientCore = new FetchClient(auth, baseUrl);\n const tenantName = await this.getCurrentTenant(clientCore);\n const client = new Client(auth, baseUrl);\n client.core.tenant = tenantName;\n return client;\n }\n\n /**\n * Authenticates the given user via OAuth Internal. Determines the tenant by itself via a call to tenant/currentTenant.\n * Login call goes to `/tenant/oauth/token` and the retrieved token will be added in the `Authorization` header to subsequent requests.\n *\n * **Example**\n * ```typescript\n *\n * let client: Client;\n * (async () => {\n * client = await Client.authenticateViaOAuthInternal({\n * user: 'testuser',\n * password: 'password1337!'\n * }, 'https://acme.cumulocity.com');\n *\n * //you have access to the client api now\n * const { data, paging, res }); = await client.inventory.list({ pageSize: 100 });\n * })();\n * ```\n */\n static async authenticateViaOAuthInternal(credentials: ICredentials, baseUrl?: string) {\n const token = await this.loginViaOAuthInternal(credentials, true, baseUrl);\n const auth = new BearerAuth(token);\n const clientCore = new FetchClient(auth, baseUrl);\n const tenantName = credentials.tenant || (await this.getCurrentTenant(clientCore));\n const client = new Client(auth, baseUrl);\n client.core.tenant = tenantName;\n return client;\n }\n\n /**\n * Authenticates the given user via OAuth Internal. Determines the tenant by itself via a call to tenant/currentTenant.\n * Login call goes to `/tenant/oauth` and the retrieved token will be attached as a Cookie in browser environments to subsequent requests (using 'CookieAuth').\n * In none browser environments (e.g. nodejs) the retrieved token will be added in the `Authorization` header to subsequent requests (using 'NodeJSCookieAuth').\n *\n * **Example**\n * ```typescript\n *\n * let client: Client;\n * (async () => {\n * client = await Client.authenticateViaOAuthInternalCookie({\n * user: 'testuser',\n * password: 'password1337!'\n * }, 'https://acme.cumulocity.com');\n *\n * //you have access to the client api now\n * const { data, paging, res }); = await client.inventory.list({ pageSize: 100 });\n * })();\n * ```\n */\n static async authenticateViaOAuthInternalCookie(credentials: ICredentials, baseUrl?: string) {\n const response = await this.loginViaOAuthInternal(credentials, false, baseUrl);\n let auth: NodeJSCookieAuth | CookieAuth;\n if (typeof document === 'undefined') {\n auth = new NodeJSCookieAuth(response);\n } else {\n auth = new CookieAuth();\n }\n const clientCore = new FetchClient(auth, baseUrl);\n const tenantName = credentials.tenant || (await this.getCurrentTenant(clientCore));\n const client = new Client(auth, baseUrl);\n client.core.tenant = tenantName;\n return client;\n }\n\n /**\n * Allows to use http to register a device on the platform.\n *\n * **Deprecated** Please use MQTT to bootstrap a device.\n */\n static async deviceBootstrap(options: IBootstrapOptions): Promise<Client> {\n const { deviceId, timeout, baseUrl, basicAuthToken } = options;\n let { expire } = options;\n if (timeout && !expire) {\n expire = Date.now() + timeout;\n }\n const clientCore = new FetchClient(undefined, baseUrl);\n const deviceRegistration = new DeviceRegistrationService(clientCore);\n let client;\n try {\n const { data } = await deviceRegistration.bootstrap(deviceId, { basicAuthToken });\n const { username, password, tenantId } = data;\n const auth = new BasicAuth({ user: username, tenant: tenantId, password });\n client = new Client(auth, baseUrl);\n client.core.tenant = tenantId;\n } catch (error) {\n const retry = (!expire || Date.now() < expire) && error.res.status === 404;\n if (retry) {\n return Client.deviceBootstrap(Object.assign({ expire }, options));\n } else {\n throw error;\n }\n }\n return client;\n }\n\n /**\n * Retrieves microservice credentials for the subscribed tenants\n * using provided bootstrap credentials\n *\n * **Example**\n * ```typescript\n *\n * (async () => {\n * const subscriptions = await Client.getMicroserviceSubscriptions({\n * tenant: process.env.C8Y_BOOTSTRAP_TENANT,\n * user: process.env.C8Y_BOOTSTRAP_USER,\n * password: process.env.C8Y_BOOTSTRAP_PASSWORD\n * }, process.env.C8Y_BASEURL);\n *\n * const clients = subscriptions.map(subscription => new Client(new BasicAuth(subscription), process.env.C8Y_BASEURL));\n * // you have access to the client api now\n * const promiseArray = clients.map(client => client.options.tenant.detail({\n * category: process.env.APPLICATION_KEY,\n * key: 'someSetting'\n * }));\n * })();\n * ```\n */\n static async getMicroserviceSubscriptions(\n bootstrapCredentials: ICredentials,\n baseUrl: string\n ): Promise<ICredentials[]> {\n const microserviceSubscriptionsEndpoint = '/application/currentApplication/subscriptions';\n const clientCore = new FetchClient(new BasicAuth(bootstrapCredentials), baseUrl);\n const res = await clientCore.fetch(microserviceSubscriptionsEndpoint);\n const { users }: IMicroserviceSubscriptionsResponse = await res.json();\n return users.map(({ tenant, name, password }) => {\n return {\n tenant,\n user: name,\n password\n } as ICredentials;\n });\n }\n\n /**\n * Performs the OAuth Internal login.\n *\n * If the parameter `bearerAuth` is set to true (default), the `/tenant/oauth/token` endpoint is called and a string containing the token returned.\n *\n * If the parameter `bearerAuth` is set to false, the `/tenant/oauth` endpoint is called and a Cookie should be set and the response returned.\n * The response can be used in none browser environments to extract the `set-cookie` header from it.\n *\n * **Example**\n * ```typescript\n *\n * (async () => {\n * const client = await Client.loginViaOAuthInternal({\n * tenant: process.env.C8Y_BOOTSTRAP_TENANT,\n * user: process.env.C8Y_BOOTSTRAP_USER,\n * password: process.env.C8Y_BOOTSTRAP_PASSWORD\n * }, true, process.env.C8Y_BASEURL);\n *\n * // you have access to the client api now\n * const option = client.options.tenant.detail({\n * category: process.env.APPLICATION_KEY,\n * key: 'someSetting'\n * });\n * })();\n * ```\n */\n static async loginViaOAuthInternal(\n credentials: ICredentials,\n bearerAuth?: true,\n baseUrl?: string\n ): Promise<string>;\n static async loginViaOAuthInternal(\n credentials: ICredentials,\n bearerAuth: false,\n baseUrl?: string\n ): Promise<IFetchResponse>;\n static async loginViaOAuthInternal(\n credentials: ICredentials,\n bearerAuth = true,\n baseUrl?: string\n ): Promise<string | IFetchResponse> {\n const auth = new BasicAuth(credentials);\n const clientCore = new FetchClient(auth, baseUrl);\n let url = '/tenant/oauth';\n if (bearerAuth) {\n url += `/token`;\n }\n if (credentials.tenant) {\n url += `?tenant_id=${credentials.tenant}`;\n }\n const params = new URLSearchParams({\n grant_type: 'PASSWORD',\n username: credentials.user,\n password: credentials.password,\n tfa_code: credentials.tfa\n });\n const res = await clientCore.fetch(url, {\n method: 'POST',\n body: params.toString(),\n headers: {\n 'content-type': 'application/x-www-form-urlencoded;charset=UTF-8'\n }\n });\n if (res.status !== 200) {\n throw { res };\n }\n\n if (bearerAuth) {\n const body = await res.json();\n\n return body['access_token'];\n }\n\n return res;\n }\n\n private static async getCurrentTenant(fetchClient: FetchClient): Promise<string> {\n const tenantService = new TenantService(fetchClient);\n const { data: tenant } = await tenantService.current();\n return tenant.name;\n }\n\n alarm: AlarmService;\n application: ApplicationService;\n audit: AuditService;\n core: FetchClient;\n deviceRegistration: DeviceRegistrationService;\n deviceRegistrationBulk: DeviceRegistrationBulkService;\n event: EventService;\n inventory: InventoryService;\n inventoryRole: InventoryRoleService;\n inventoryBinary: InventoryBinaryService;\n measurement: MeasurementService;\n operation: OperationService;\n operationBulk: OperationBulkService;\n options: {\n security: TenantSecurityOptionsService;\n system: SystemOptionsService;\n login: TenantLoginOptionsService;\n tenant: TenantOptionsService;\n };\n realtime: Realtime;\n role: InventoryRoleService;\n tenant: TenantService;\n user: UserService;\n userGroup: UserGroupService;\n userRole: UserRoleService;\n identity: IdentityService;\n smartGroups: SmartGroupsService;\n smartRules: SmartRulesService;\n\n /**\n * Initializes a new Client, which allows to request data from the API. Differently\n * to Client.authenticate([...]) it needs a tenant given and does not verify if the\n * login is correct.\n *\n * **Example**\n * ```typescript\n *\n * const auth = new BasicAuth({\n * user: 'youruser',\n * password: 'yourpassword',\n * tenant: 'acme'\n * }); // use CookieAuth() if your platform uses oauth (only in browser!)\n *\n * const baseUrl = 'https://acme.cumulocity.com';\n * const client = new Client(auth, baseUrl);\n * (async () => {\n * const { data, paging, res }); = await client.inventory.list({ pageSize: 100 });\n * })();\n * ```\n *\n * @param auth The Authentication strategy to use (e.g. new BasicAuth())\n * @param baseUrl The URL to request (optional in browser, mandatory in node)\n */\n constructor(auth: IAuthentication, baseUrl?: string) {\n const client = new FetchClient(auth, baseUrl);\n this.realtime = new Realtime(client);\n this.alarm = new AlarmService(client, this.realtime);\n this.application = new ApplicationService(client, this.realtime);\n this.audit = new AuditService(client);\n this.core = client;\n this.deviceRegistration = new DeviceRegistrationService(client);\n this.deviceRegistrationBulk = new DeviceRegistrationBulkService(client);\n this.event = new EventService(client, this.realtime);\n this.inventory = new InventoryService(client, this.realtime);\n this.inventoryBinary = new InventoryBinaryService(client);\n this.inventoryRole = new InventoryRoleService(client);\n this.measurement = new MeasurementService(client, this.realtime);\n this.operation = new OperationService(client);\n this.operationBulk = new OperationBulkService(client);\n this.options = {\n security: new TenantSecurityOptionsService(client),\n system: new SystemOptionsService(client),\n login: new TenantLoginOptionsService(client),\n tenant: new TenantOptionsService(client)\n };\n this.role = new InventoryRoleService(client);\n this.tenant = new TenantService(client);\n this.user = new UserService(client);\n this.userGroup = new UserGroupService(client);\n this.userRole = new UserRoleService(client);\n this.identity = new IdentityService(client);\n this.smartGroups = new SmartGroupsService(client);\n this.smartRules = new SmartRulesService(client);\n }\n\n /**\n * Allows to change the current Authentication\n * @param auth The new Authentication information.\n */\n setAuth(auth: IAuthentication) {\n this.core.setAuth(auth);\n this.realtime.disconnect();\n }\n}\n"],"names":["__awaiter","thisArg","_arguments","P","generator","Promise","resolve","reject","fulfilled","value","step","next","e","rejected","result","done","then","apply","Paging","constructor","service","statistics","filter","this","currentPage","nextPage","prevPage","pageSize","totalPages","list","getFilter","prev","goto","page","Object","assign","Service","client","realtime","cache","Map","prototype","getPrototypeOf","forEach","method","hasOwnProperty","defineProperty","get","url","listUrl","res","yield","fetch","changeFetchOptions","headers","accept","params","json","data","propertyName","paging","getPaging","detail","entityOrId","getDetailUrl","create","entity","body","JSON","stringify","onBeforeCreate","content-type","update","onBeforeUpdate","delete","obj","id","objWithId","options","_url","getUrl","baseUrl","replace","getEntityId","init","fullUrl","handleErrorStatusCodes","response","status","let","ex","text","mimeType","type","getIdString","reference","String","getCurrentPageFromLink","link","matches","match","parseInt","global","self","__self__","F","DOMException","viewClasses","isArrayBufferView","exports","support","Symbol","Blob","normalizeName","name","test","TypeError","toLowerCase","normalizeValue","iteratorFor","items","iterator","shift","undefined","Headers","map","append","Array","isArray","header","getOwnPropertyNames","consumed","bodyUsed","fileReaderReady","reader","onload","onerror","error","readBlobAsArrayBuffer","blob","FileReader","promise","readAsArrayBuffer","bufferClone","buf","view","slice","Uint8Array","byteLength","set","buffer","Body","_initBody","_bodyInit","_bodyText","isPrototypeOf","_bodyBlob","FormData","_bodyFormData","URLSearchParams","toString","DataView","_bodyArrayBuffer","ArrayBuffer","call","Error","arrayBuffer","readAsText","chars","length","i","fromCharCode","join","formData","decode","parse","isView","indexOf","oldValue","has","callback","keys","push","values","entries","methods","Request","input","upcased","credentials","mode","signal","toUpperCase","referrer","form","trim","split","bytes","decodeURIComponent","Response","bodyInit","ok","statusText","clone","redirectStatuses","redirect","RangeError","location","err","message","stack","request","aborted","xhr","XMLHttpRequest","abortXhr","abort","rawHeaders","getAllResponseHeaders","line","parts","key","responseURL","responseText","ontimeout","onabort","open","withCredentials","responseType","setRequestHeader","addEventListener","onreadystatechange","readyState","removeEventListener","send","polyfill","ponyfill","ctx","default","module","auths","WeakMap","FetchClient","authOrBaseUrl","tenant","defaultHeaders","setAuth","resolveServerUrl","auth","fetchFn","window","getFetchOptions","optionsWithAdjustedBody","adjustOptionsForFormData","paramPart","k","vals","encodedKey","encodeURIComponent","v","clonedOptions","UseXBasic","getCometdHandshake","config","startsWith","protocol","host","E","code","btoa$1","_btoa","p1","btoa","block","charCode","str","output","idx","charAt","charCodeAt","secrets","BasicAuth","updateCredentials","user","password","token","tfa","secret","xsrfToken","getCookieValue","Authorization","X-XSRF-TOKEN","tfatoken","KEY","ext","logout","document","cookie","pop","BearerAuth","CookieAuth","logoutUrl","MicroserviceClientRequestAuth","authTokenFromCookie","authTokenFromHeader","authorization","NodeJSCookieAuth","cookieResponse","super","setCookiesHeader","Severity","QueriesUtil","operatorFns","__not","operand","buildQueryFilter","__and","__or","__eq","contextKey","quoteString","__gt","__ge","__lt","__le","__in","stmts","op","glue","__bygroupid","__has","__useFilterQueryString","query","_a","queryString","substring","buildQuery","q","__filter","orderBy","buildQueryOrderby","__orderby","queryFilter","_queryKey","_glueType","queryKey","glueType","qFilter","_q","queryOrderbys","o","addAndFilter","addFilter","addOrFilter","operator","oldFilter","newFilter","skipEmptyObjects","prependOrderbys","orderbys","addOrderbys","appendOrderbys","how","oldOrderbys","newOrderbys","newQuery","isEmptyObject","extractAndMergeOrderBys","queries","orderByQuery","s","escapeSingleQuote","objs","MetaChannel","Scheduler","Utils","TransportRegistry","Transport","RequestTransport","LongPollingTransport","CallbackPollingTransport","WebSocketTransport","_z85EncodeTable","_z85DecodeTable","_ids","_tasks","register","funktion","unregister","setTimeout","delay","clearTimeout","isString","inArray","element","array","_types","_transports","getTransportTypes","findTransportTypes","version","crossDomain","negotiateTransport","types","j","transport","add","index","existing","splice","find","remove","clear","reset","_type","_cometd","registered","cometd","unregistered","_debug","arguments","_mixin","getConfiguration","getAdvice","convertToMessages","x","getType","getURL","setURL","envelope","metaConnect","derive","baseObject","CometD","_transport","_handshakeProps","_handshakeCallback","_handleMessages","_handleFailure","_scheduler","_name","_crossDomain","_status","_messageId","_clientId","_batch","_messageQueue","_internalBatch","_listenerId","_listeners","_backoff","_scheduledSend","_extensions","_advice","_callbacks","_remoteCalls","_reestablish","_connected","_unconnectTime","_handshakeMessages","_metaConnect","_config","useWorkerScheduler","stickyReconnect","connectTimeout","maxConnections","backoffIncrement","maxBackoff","logLevel","maxNetworkDelay","requestHeaders","appendMessageTypeToURL","autoBatch","urls","maxURILength","advice","timeout","interval","reconnect","maxInterval","_fieldValue","object","_isString","_isFunction","_zeroPad","Math","pow","_log","level","args","now","console","logger","Date","getHours","getMinutes","getSeconds","getMilliseconds","_splitURL","RegExp","exec","_configure","configuration","worker","urlParts","hostAndPort","uri","afterURI","_isCrossDomain","_info","lastSegmentIndex","uriSegments","Worker","URL","onmessage","cmd","postMessage","lastIndexOf","blobURL","createObjectURL","_removeListener","subscription","subscriptions","channel","listener","_removeSubscription","_clearSubscriptions","_setStatus","newStatus","_isDisconnected","_nextMessageId","_applyExtension","scope","outgoing","handler","onExtensionException","xx","_notify","onListenerException","_notifyListeners","channelParts","last","channelPart","_cancelDelayedSend","_delayedSend","operation","time","_send","messages","extraPath","messageId","clientId","extension","sync","onSuccess","rcvdMessages","onFailure","conduit","failure","getTransport","connectionType","_queueSend","_resetBackoff","_flushBatch","_delayedConnect","bayeuxMessage","_updateAdvice","newAdvice","_disconnect","reason","_notifyTransportException","oldTransport","newTransport","onTransportException","_handshake","handshakeProps","handshakeCallback","transportTypes","minimumVersion","supportedConnectionTypes","_putCallback","_warn","_notifyCallback","onCallbackException","_handleCallback","_getCallback","_handleRemoteCall","context","_handleTransportFailure","failureInfo","action","_failHandshake","onTransportFailure","_matchMetaConnect","connect","_failConnect","_failDisconnect","_failSubscribe","_failUnsubscribe","_failMessage","_receive","incoming","_handshakeResponse","successful","cause","reestablish","_hasSubscriptions","_resolveScopedCallback","delegate","_addListener","isListener","deep","target","objects","prop","source","propName","targ","failureHandler","oldTransportType","transports","getTransportRegistry","getBackoffPeriod","newTransportType","increaseBackoffPeriod","getTime","resetBackoffPeriod","receive","failureMessage","registerTransport","unregisterTransport","unregisterTransports","findTransport","configure","handshake","disconnect","disconnectProps","disconnectCallback","startBatch","endBatch","batch","addListener","removeListener","clearListeners","subscribe","subscribeProps","subscribeCallback","unsubscribe","unsubscribeProps","unsubscribeCallback","resubscribe","clearSubscriptions","publish","content","publishProps","publishCallback","publishBinary","meta","binary","remoteCall","callProps","remoteCallBinary","getStatus","isDisconnected","setBackoffIncrement","period","getBackoffIncrement","setLogLevel","registerExtension","unregisterExtension","getExtension","getName","getClientId","WebSocket","_super","_self","_requestIds","_metaConnectRequest","_requests","_envelopes","_transportSend","maxDelay","transportSend","expired","errorMessage","httpCode","xhrStatus","abortXHR","complete","requestId","_complete","success","nextEnvelope","nextRequest","envelopeAndRequest","newEnvelope","newRequest","concat","transportSuccess","responses","transportFailure","metaConnectRequest","state","UNSENT","_supportsCrossDomain","newXMLHttpRequest","xhrSend","packet","_copyContext","headerName","onError","sameStack","received","exception","jsonp","_failTransportFn","jsonpSend","head","getElementsByTagName","script","createElement","callbackName","removeChild","src","async","appendChild","start","lengths","urlLength","encodeURI","maxLength","envelopeToSend","end","begin","_webSocketSupported","_webSocketConnected","_stickyReconnect","_context","_connecting","_successCallback","_forceClose","event","webSocketClose","onClose","_sameContext","_storeEnvelope","messageIds","envelopes","_webSocketSend","webSocket","timeouts","onclose","connectTimer","onopen","onOpen","wsMessage","onMessage","_notifySuccess","fn","_notifyFailure","close","removed","ids","websocketCode","websocketEnabled","Z85","encode","remainder","padding","isPadding","getUint8","divisor","floor","string","p","charIdx","byteIdx","setUint8","lib","Realtime","metaHandshake","msg","IsoCometD","HANDSHAKE","checkConnection","addHandshakeListener","addConnectListener","CONNECT","subscriptionHandle","EventService","ChildType","browser","EventBinaryService","upload","file","download","InventoryBinaryService","managedObject","fileName","fileType","File","managedObjectOrId","createWithProgress","onProgress","bodyHeaders","getHeaders","xhrBody","getBuffer","getXMLHttpResponse","rej","getIdFromUrl","regexp","InventoryService","inventoriesQueryParamName","devicesQueryParamName","queriesUtil","listQuery","listQueryDevices","childAdditionsList","parentReference","listChildren","ADDITIONS","childAdditionsCreate","createChild","childAdditionsAdd","childReference","addChild","childAdditionsRemove","childAssetsList","ASSETS","childAssetsCreate","childAssetsAdd","childAssetsBulkAdd","addChildBulk","childAssetsRemove","childDevicesList","DEVICES","childDevicesCreate","childDevicesAdd","childDevicesRemove","getSupportedMeasurements","getSupportedMeasurementDetails","getSupportedSeries","getMeasurementsAndSeries","supportedMeasurements","supportedSeries","all","sortedSupportedMeasurements","sort","a","b","fragment","m","series","assetKPIsList","listKPIs","getChildrenUrl","lastUpdated","getChildUrl","childId","references","ref","pagingFilter","childReferenceArray","c8y_SupportedMeasurements","c8y_SupportedSeries","MeasurementService","listSeries","sourceId","toISOString","aggregationType","AlarmService","AlarmStatus","OperationService","OperationBulkService","operationOrId","OperationBulkStatus","OperationBulkGeneralStatus","OperationStatus","TenantService","currentTenantUrl","fetchOptions","current","enableSupportUser","disableSupportUser","currentTenantType","tenantData","customProperties","tenantType","getTfaSettings","subscribeApplication","application","applicationId","unsubscribeApplication","TenantStatus","TfaStrategy","UserInventoryRoleService","userUrl","currenUserUrl","UserService","currentUserUrl","passwordResetUrl","currentUserPhoneUrl","verifyTFACodeUrl","totpCurrentUserURL","verifyTOTPCodeUrl","activateTOTPCodeUrl","revokeTOTPSecretUrl","newsletterEmailsUrl","currentUserPasswordUrl","revokeAllTokensUrl","inventoryAssignment","Accept","currentWithEffectiveRoles","updateCurrent","sendPasswordResetMail","email","tenantId","resetPassword","newPassword","verifyTFACode","pin","verifyTotpCode","activateTotp","isActive","getActivityTotp","generateTotpSecret","totpRevokeSecret","savePhoneNumber","phoneNumber","phone","getNewsletterEmails","changeUserPassword","currentUserPassword","changeUserPasswordUrl","changeCurrentUserPassword","revokeTokens","hasRole","roleId","hasRoleInUser","hasRoleInGroups","hasAllRoles","roleIds","every","hasAnyRole","some","hasAnyGlobalRole","globalRoleIds","globalRoleId","hasGlobalRoleInUser","isDeviceUser","userName","getId","effectiveRoles","hasRoleInReferences","roles","groups","groupRef","group","role","gR","PasswordStrength","ApplicationBinaryService","applicationOrId","uploadParamsOverride","createBinaryRequestBody","uploadWithProgressXhr","binaryOrId","listPlugins","addPlugin","pluginName","pluginFile","bufferOrStream","Buffer","from","removePlugin","updateFiles","files","contents","path","downloadArchive","binaryId","uploadFileName","bodyFileProperty","requestBody","ApplicationType","ApplicationService","listVersions","applicationVersions","appDetail","listByName","listByTenant","tenantOrName","tenantService","tenantName","listByOwner","listByUser","userOrId","userService","userId","reactivateArchive","appId","getHref","EXTERNAL","externalUrl","public","contextPath","isAvailable","dropOverwrittenApps","noPaging","availableApp","isMatch","getStatusDetails","getInstanceNames","appStatusDetails","instanceNames","c8y_Status","instances","getInstanceLog","instanceName","updateApplicationConfig","app","currentConfig","newConfig","updatedConfigApp","getAppManifest","date","storeAppManifest","manifestJSON","setPackageVersionTag","tags","getManifestOfContextPath","deleteVersionPackage","updateApplicationAvailability","availability","el","includes","InstanceStatus","BillingMode","Isolation","ApplicationAvailability","SystemOptionsService","option","category","TenantOptionsService","securityOptionsCategories","securityOptionsListUrl","systemOptions","encodedCategory","TenantSecurityOptionsService","tenantSecurityOption","TenantLoginOptionsService","entityIdentityOrId","listForCurrentTenant","listForManagement","management","save","TenantLoginOptionType","GrantType","UserManagementSource","AuditService","AuditRecordType","ChangeType","InventoryRoleService","DeviceRegistrationStatus","DeviceRegistrationService","securityToken","getSecurityToken","payload","ACCEPTED","acceptAll","limit","bootstrap","basicAuth","basicAuthToken","pass","noIdEntity","DeviceRegistrationBulkService","inputFile","csv","DeviceRegistrationSecurityMode","UserRoleService","UserGroupService","addRoleToGroup","childEntityOrSelf","ROLES","removeRoleFromGroup","addUserToGroup","USERS","removeUserFromGroup","getSelf","userGroupOrId","getChildReferenceAsBody","childSelf","IdentityService","managedObjectId","getExternalIdsOfGlobalIdUrl","identity","getExternalIdUrl","externalId","TrustedCertificateService","proofOfPossessionUrl","regeneratePoPVerificationCode","verifySignedVerificationCode","proofOfPossessionSignedVerificationCode","fingerprint","CrlService","uploadCrls","crls","uploadCrlFile","downloadCrlFile","SmartGroupsService","SMART_GROUP_TYPE","SMART_GROUP_FRAGMENT_TYPE","COLUMNS_CONFIG_FRAGMENT","FILTER_CONFIG_FRAGMENT","QUERY_STRING_FRAGMENT","smartGroup","deviceQueryString","configurableColumns","filterConfig","mo","withChildren","isSmartGroup","hasSmartGroupFragmentType","isSmartGroupType","partialUrl","SmartRulesService","rulesUrl","unupdatableFields","applicationService","isMicroserviceAvailable","microserviceAvailable","microserviceName","listByContext","contextRulesUrl","rules","bulkDeactivateEnabledSources","rule","entitiesOrIdsList","newEnabledSources","enabledSources","disableEnabledSources","ruleCopy","getSmartRulesUrl","removeUnclonableFields","entityOrIdList","getListOfStringIds","contextMoId","c8y_Context","fieldsToRemove","f","Client","authenticate","clientCore","getCurrentTenant","core","authenticateViaOAuthInternal","loginViaOAuthInternal","authenticateViaOAuthInternalCookie","deviceBootstrap","deviceId","expire","deviceRegistration","username","getMicroserviceSubscriptions","bootstrapCredentials","users","bearerAuth","grant_type","tfa_code","fetchClient","alarm","audit","deviceRegistrationBulk","inventory","inventoryBinary","inventoryRole","measurement","operationBulk","security","system","login","userGroup","userRole","smartGroups","smartRules"],"mappings":"iPAkHO,SAASA,EAAUC,EAASC,EAAYC,EAAGC,GAE9C,OAAO,IAAKD,EAAAA,GAAUE,SAAU,SAAUC,EAASC,GAC/C,SAASC,EAAUC,GAAS,IAAMC,EAAKN,EAAUO,KAAKF,CAAK,CAAC,EAAK,MAAOG,GAAKL,EAAOK,CAAC,EAAM,CAC3F,SAASC,EAASJ,GAAS,IAAMC,EAAKN,EAAiB,MAAEK,CAAK,CAAC,EAAK,MAAOG,GAAKL,EAAOK,CAAC,EAAM,CAC9F,SAASF,EAAKI,GAJlB,IAAeL,EAIaK,EAAOC,KAAOT,EAAQQ,EAAOL,KAAK,IAJ/CA,EAIyDK,EAAOL,iBAJ/BN,EAAIM,EAAQ,IAAIN,EAAE,SAAUG,GAAWA,EAAQG,CAAK,CAAE,CAAE,GAIlBO,KAAKR,EAAWK,CAAQ,CAAI,CAC9GH,GAAMN,EAAYA,EAAUa,MAAMhB,EAASC,GAAc,EAAE,GAAGS,KAAI,CAAE,CAC5E,CAAK,CACL,OC/GaO,EA4BXC,YAAYC,EAAyBC,EAAiBC,G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