text
stringlengths
2.5k
6.39M
kind
stringclasses
3 values
import {Request} from '../lib/request'; import {Response} from '../lib/response'; import {AWSError} from '../lib/error'; import {Service} from '../lib/service'; import {ServiceConfigurationOptions} from '../lib/service'; import {ConfigBase as Config} from '../lib/config-base'; interface Blob {} declare class MQ extends Service { /** * Constructs a service object. This object has one method for each API operation. */ constructor(options?: MQ.Types.ClientConfiguration) config: Config & MQ.Types.ClientConfiguration; /** * Creates a broker. Note: This API is asynchronous. To create a broker, you must either use the AmazonMQFullAccess IAM policy or include the following EC2 permissions in your IAM policy. ec2:CreateNetworkInterface This permission is required to allow Amazon MQ to create an elastic network interface (ENI) on behalf of your account. ec2:CreateNetworkInterfacePermission This permission is required to attach the ENI to the broker instance. ec2:DeleteNetworkInterface ec2:DeleteNetworkInterfacePermission ec2:DetachNetworkInterface ec2:DescribeInternetGateways ec2:DescribeNetworkInterfaces ec2:DescribeNetworkInterfacePermissions ec2:DescribeRouteTables ec2:DescribeSecurityGroups ec2:DescribeSubnets ec2:DescribeVpcs For more information, see Create an IAM User and Get Your AWS Credentials and Never Modify or Delete the Amazon MQ Elastic Network Interface in the Amazon MQ Developer Guide. */ createBroker(params: MQ.Types.CreateBrokerRequest, callback?: (err: AWSError, data: MQ.Types.CreateBrokerResponse) => void): Request<MQ.Types.CreateBrokerResponse, AWSError>; /** * Creates a broker. Note: This API is asynchronous. To create a broker, you must either use the AmazonMQFullAccess IAM policy or include the following EC2 permissions in your IAM policy. ec2:CreateNetworkInterface This permission is required to allow Amazon MQ to create an elastic network interface (ENI) on behalf of your account. ec2:CreateNetworkInterfacePermission This permission is required to attach the ENI to the broker instance. ec2:DeleteNetworkInterface ec2:DeleteNetworkInterfacePermission ec2:DetachNetworkInterface ec2:DescribeInternetGateways ec2:DescribeNetworkInterfaces ec2:DescribeNetworkInterfacePermissions ec2:DescribeRouteTables ec2:DescribeSecurityGroups ec2:DescribeSubnets ec2:DescribeVpcs For more information, see Create an IAM User and Get Your AWS Credentials and Never Modify or Delete the Amazon MQ Elastic Network Interface in the Amazon MQ Developer Guide. */ createBroker(callback?: (err: AWSError, data: MQ.Types.CreateBrokerResponse) => void): Request<MQ.Types.CreateBrokerResponse, AWSError>; /** * Creates a new configuration for the specified configuration name. Amazon MQ uses the default configuration (the engine type and version). */ createConfiguration(params: MQ.Types.CreateConfigurationRequest, callback?: (err: AWSError, data: MQ.Types.CreateConfigurationResponse) => void): Request<MQ.Types.CreateConfigurationResponse, AWSError>; /** * Creates a new configuration for the specified configuration name. Amazon MQ uses the default configuration (the engine type and version). */ createConfiguration(callback?: (err: AWSError, data: MQ.Types.CreateConfigurationResponse) => void): Request<MQ.Types.CreateConfigurationResponse, AWSError>; /** * Add a tag to a resource. */ createTags(params: MQ.Types.CreateTagsRequest, callback?: (err: AWSError, data: {}) => void): Request<{}, AWSError>; /** * Add a tag to a resource. */ createTags(callback?: (err: AWSError, data: {}) => void): Request<{}, AWSError>; /** * Creates an ActiveMQ user. */ createUser(params: MQ.Types.CreateUserRequest, callback?: (err: AWSError, data: MQ.Types.CreateUserResponse) => void): Request<MQ.Types.CreateUserResponse, AWSError>; /** * Creates an ActiveMQ user. */ createUser(callback?: (err: AWSError, data: MQ.Types.CreateUserResponse) => void): Request<MQ.Types.CreateUserResponse, AWSError>; /** * Deletes a broker. Note: This API is asynchronous. */ deleteBroker(params: MQ.Types.DeleteBrokerRequest, callback?: (err: AWSError, data: MQ.Types.DeleteBrokerResponse) => void): Request<MQ.Types.DeleteBrokerResponse, AWSError>; /** * Deletes a broker. Note: This API is asynchronous. */ deleteBroker(callback?: (err: AWSError, data: MQ.Types.DeleteBrokerResponse) => void): Request<MQ.Types.DeleteBrokerResponse, AWSError>; /** * Removes a tag from a resource. */ deleteTags(params: MQ.Types.DeleteTagsRequest, callback?: (err: AWSError, data: {}) => void): Request<{}, AWSError>; /** * Removes a tag from a resource. */ deleteTags(callback?: (err: AWSError, data: {}) => void): Request<{}, AWSError>; /** * Deletes an ActiveMQ user. */ deleteUser(params: MQ.Types.DeleteUserRequest, callback?: (err: AWSError, data: MQ.Types.DeleteUserResponse) => void): Request<MQ.Types.DeleteUserResponse, AWSError>; /** * Deletes an ActiveMQ user. */ deleteUser(callback?: (err: AWSError, data: MQ.Types.DeleteUserResponse) => void): Request<MQ.Types.DeleteUserResponse, AWSError>; /** * Returns information about the specified broker. */ describeBroker(params: MQ.Types.DescribeBrokerRequest, callback?: (err: AWSError, data: MQ.Types.DescribeBrokerResponse) => void): Request<MQ.Types.DescribeBrokerResponse, AWSError>; /** * Returns information about the specified broker. */ describeBroker(callback?: (err: AWSError, data: MQ.Types.DescribeBrokerResponse) => void): Request<MQ.Types.DescribeBrokerResponse, AWSError>; /** * Describe available engine types and versions. */ describeBrokerEngineTypes(params: MQ.Types.DescribeBrokerEngineTypesRequest, callback?: (err: AWSError, data: MQ.Types.DescribeBrokerEngineTypesResponse) => void): Request<MQ.Types.DescribeBrokerEngineTypesResponse, AWSError>; /** * Describe available engine types and versions. */ describeBrokerEngineTypes(callback?: (err: AWSError, data: MQ.Types.DescribeBrokerEngineTypesResponse) => void): Request<MQ.Types.DescribeBrokerEngineTypesResponse, AWSError>; /** * Describe available broker instance options. */ describeBrokerInstanceOptions(params: MQ.Types.DescribeBrokerInstanceOptionsRequest, callback?: (err: AWSError, data: MQ.Types.DescribeBrokerInstanceOptionsResponse) => void): Request<MQ.Types.DescribeBrokerInstanceOptionsResponse, AWSError>; /** * Describe available broker instance options. */ describeBrokerInstanceOptions(callback?: (err: AWSError, data: MQ.Types.DescribeBrokerInstanceOptionsResponse) => void): Request<MQ.Types.DescribeBrokerInstanceOptionsResponse, AWSError>; /** * Returns information about the specified configuration. */ describeConfiguration(params: MQ.Types.DescribeConfigurationRequest, callback?: (err: AWSError, data: MQ.Types.DescribeConfigurationResponse) => void): Request<MQ.Types.DescribeConfigurationResponse, AWSError>; /** * Returns information about the specified configuration. */ describeConfiguration(callback?: (err: AWSError, data: MQ.Types.DescribeConfigurationResponse) => void): Request<MQ.Types.DescribeConfigurationResponse, AWSError>; /** * Returns the specified configuration revision for the specified configuration. */ describeConfigurationRevision(params: MQ.Types.DescribeConfigurationRevisionRequest, callback?: (err: AWSError, data: MQ.Types.DescribeConfigurationRevisionResponse) => void): Request<MQ.Types.DescribeConfigurationRevisionResponse, AWSError>; /** * Returns the specified configuration revision for the specified configuration. */ describeConfigurationRevision(callback?: (err: AWSError, data: MQ.Types.DescribeConfigurationRevisionResponse) => void): Request<MQ.Types.DescribeConfigurationRevisionResponse, AWSError>; /** * Returns information about an ActiveMQ user. */ describeUser(params: MQ.Types.DescribeUserRequest, callback?: (err: AWSError, data: MQ.Types.DescribeUserResponse) => void): Request<MQ.Types.DescribeUserResponse, AWSError>; /** * Returns information about an ActiveMQ user. */ describeUser(callback?: (err: AWSError, data: MQ.Types.DescribeUserResponse) => void): Request<MQ.Types.DescribeUserResponse, AWSError>; /** * Returns a list of all brokers. */ listBrokers(params: MQ.Types.ListBrokersRequest, callback?: (err: AWSError, data: MQ.Types.ListBrokersResponse) => void): Request<MQ.Types.ListBrokersResponse, AWSError>; /** * Returns a list of all brokers. */ listBrokers(callback?: (err: AWSError, data: MQ.Types.ListBrokersResponse) => void): Request<MQ.Types.ListBrokersResponse, AWSError>; /** * Returns a list of all revisions for the specified configuration. */ listConfigurationRevisions(params: MQ.Types.ListConfigurationRevisionsRequest, callback?: (err: AWSError, data: MQ.Types.ListConfigurationRevisionsResponse) => void): Request<MQ.Types.ListConfigurationRevisionsResponse, AWSError>; /** * Returns a list of all revisions for the specified configuration. */ listConfigurationRevisions(callback?: (err: AWSError, data: MQ.Types.ListConfigurationRevisionsResponse) => void): Request<MQ.Types.ListConfigurationRevisionsResponse, AWSError>; /** * Returns a list of all configurations. */ listConfigurations(params: MQ.Types.ListConfigurationsRequest, callback?: (err: AWSError, data: MQ.Types.ListConfigurationsResponse) => void): Request<MQ.Types.ListConfigurationsResponse, AWSError>; /** * Returns a list of all configurations. */ listConfigurations(callback?: (err: AWSError, data: MQ.Types.ListConfigurationsResponse) => void): Request<MQ.Types.ListConfigurationsResponse, AWSError>; /** * Lists tags for a resource. */ listTags(params: MQ.Types.ListTagsRequest, callback?: (err: AWSError, data: MQ.Types.ListTagsResponse) => void): Request<MQ.Types.ListTagsResponse, AWSError>; /** * Lists tags for a resource. */ listTags(callback?: (err: AWSError, data: MQ.Types.ListTagsResponse) => void): Request<MQ.Types.ListTagsResponse, AWSError>; /** * Returns a list of all ActiveMQ users. */ listUsers(params: MQ.Types.ListUsersRequest, callback?: (err: AWSError, data: MQ.Types.ListUsersResponse) => void): Request<MQ.Types.ListUsersResponse, AWSError>; /** * Returns a list of all ActiveMQ users. */ listUsers(callback?: (err: AWSError, data: MQ.Types.ListUsersResponse) => void): Request<MQ.Types.ListUsersResponse, AWSError>; /** * Reboots a broker. Note: This API is asynchronous. */ rebootBroker(params: MQ.Types.RebootBrokerRequest, callback?: (err: AWSError, data: MQ.Types.RebootBrokerResponse) => void): Request<MQ.Types.RebootBrokerResponse, AWSError>; /** * Reboots a broker. Note: This API is asynchronous. */ rebootBroker(callback?: (err: AWSError, data: MQ.Types.RebootBrokerResponse) => void): Request<MQ.Types.RebootBrokerResponse, AWSError>; /** * Adds a pending configuration change to a broker. */ updateBroker(params: MQ.Types.UpdateBrokerRequest, callback?: (err: AWSError, data: MQ.Types.UpdateBrokerResponse) => void): Request<MQ.Types.UpdateBrokerResponse, AWSError>; /** * Adds a pending configuration change to a broker. */ updateBroker(callback?: (err: AWSError, data: MQ.Types.UpdateBrokerResponse) => void): Request<MQ.Types.UpdateBrokerResponse, AWSError>; /** * Updates the specified configuration. */ updateConfiguration(params: MQ.Types.UpdateConfigurationRequest, callback?: (err: AWSError, data: MQ.Types.UpdateConfigurationResponse) => void): Request<MQ.Types.UpdateConfigurationResponse, AWSError>; /** * Updates the specified configuration. */ updateConfiguration(callback?: (err: AWSError, data: MQ.Types.UpdateConfigurationResponse) => void): Request<MQ.Types.UpdateConfigurationResponse, AWSError>; /** * Updates the information for an ActiveMQ user. */ updateUser(params: MQ.Types.UpdateUserRequest, callback?: (err: AWSError, data: MQ.Types.UpdateUserResponse) => void): Request<MQ.Types.UpdateUserResponse, AWSError>; /** * Updates the information for an ActiveMQ user. */ updateUser(callback?: (err: AWSError, data: MQ.Types.UpdateUserResponse) => void): Request<MQ.Types.UpdateUserResponse, AWSError>; } declare namespace MQ { export type AuthenticationStrategy = "SIMPLE"|"LDAP"|string; export interface AvailabilityZone { /** * Id for the availability zone. */ Name?: __string; } export interface BrokerEngineType { /** * The broker's engine type. */ EngineType?: EngineType; /** * The list of engine versions. */ EngineVersions?: __listOfEngineVersion; } export interface BrokerInstance { /** * The brokers web console URL. */ ConsoleURL?: __string; /** * The broker's wire-level protocol endpoints. */ Endpoints?: __listOf__string; /** * The IP address of the Elastic Network Interface (ENI) attached to the broker. Does not apply to RabbitMQ brokers. */ IpAddress?: __string; } export interface BrokerInstanceOption { /** * The list of available az. */ AvailabilityZones?: __listOfAvailabilityZone; /** * The broker's engine type. */ EngineType?: EngineType; /** * The broker's instance type. */ HostInstanceType?: __string; /** * The broker's storage type. */ StorageType?: BrokerStorageType; /** * The list of supported deployment modes. */ SupportedDeploymentModes?: __listOfDeploymentMode; /** * The list of supported engine versions. */ SupportedEngineVersions?: __listOf__string; } export type BrokerState = "CREATION_IN_PROGRESS"|"CREATION_FAILED"|"DELETION_IN_PROGRESS"|"RUNNING"|"REBOOT_IN_PROGRESS"|string; export type BrokerStorageType = "EBS"|"EFS"|string; export interface BrokerSummary { /** * The broker's Amazon Resource Name (ARN). */ BrokerArn?: __string; /** * The unique ID that Amazon MQ generates for the broker. */ BrokerId?: __string; /** * The broker's name. This value is unique in your AWS account, 1-50 characters long, and containing only letters, numbers, dashes, and underscores, and must not contain white spaces, brackets, wildcard characters, or special characters. */ BrokerName?: __string; /** * The broker's status. */ BrokerState?: BrokerState; /** * The time when the broker was created. */ Created?: __timestampIso8601; /** * The broker's deployment mode. */ DeploymentMode: DeploymentMode; /** * The type of broker engine. */ EngineType: EngineType; /** * The broker's instance type. */ HostInstanceType?: __string; } export type ChangeType = "CREATE"|"UPDATE"|"DELETE"|string; export interface Configuration { /** * Required. The ARN of the configuration. */ Arn: __string; /** * Optional. The authentication strategy associated with the configuration. The default is SIMPLE. */ AuthenticationStrategy: AuthenticationStrategy; /** * Required. The date and time of the configuration revision. */ Created: __timestampIso8601; /** * Required. The description of the configuration. */ Description: __string; /** * Required. The type of broker engine. Currently, Amazon MQ supports ACTIVEMQ and RABBITMQ. */ EngineType: EngineType; /** * Required. The broker engine's version. For a list of supported engine versions, see, Supported engines. */ EngineVersion: __string; /** * Required. The unique ID that Amazon MQ generates for the configuration. */ Id: __string; /** * Required. The latest revision of the configuration. */ LatestRevision: ConfigurationRevision; /** * Required. The name of the configuration. This value can contain only alphanumeric characters, dashes, periods, underscores, and tildes (- . _ ~). This value must be 1-150 characters long. */ Name: __string; /** * The list of all tags associated with this configuration. */ Tags?: __mapOf__string; } export interface ConfigurationId { /** * Required. The unique ID that Amazon MQ generates for the configuration. */ Id: __string; /** * The revision number of the configuration. */ Revision?: __integer; } export interface ConfigurationRevision { /** * Required. The date and time of the configuration revision. */ Created: __timestampIso8601; /** * The description of the configuration revision. */ Description?: __string; /** * Required. The revision number of the configuration. */ Revision: __integer; } export interface Configurations { /** * The broker's current configuration. */ Current?: ConfigurationId; /** * The history of configurations applied to the broker. */ History?: __listOfConfigurationId; /** * The broker's pending configuration. */ Pending?: ConfigurationId; } export interface CreateBrokerRequest { /** * Optional. The authentication strategy used to secure the broker. The default is SIMPLE. */ AuthenticationStrategy?: AuthenticationStrategy; /** * Enables automatic upgrades to new minor versions for brokers, as new versions are released and supported by Amazon MQ. Automatic upgrades occur during the scheduled maintenance window of the broker or after a manual broker reboot. Set to true by default, if no value is specified. */ AutoMinorVersionUpgrade: __boolean; /** * Required. The broker's name. This value must be unique in your AWS account, 1-50 characters long, must contain only letters, numbers, dashes, and underscores, and must not contain white spaces, brackets, wildcard characters, or special characters. */ BrokerName: __string; /** * A list of information about the configuration. */ Configuration?: ConfigurationId; /** * The unique ID that the requester receives for the created broker. Amazon MQ passes your ID with the API action. Note: We recommend using a Universally Unique Identifier (UUID) for the creatorRequestId. You may omit the creatorRequestId if your application doesn't require idempotency. */ CreatorRequestId?: __string; /** * Required. The broker's deployment mode. */ DeploymentMode: DeploymentMode; /** * Encryption options for the broker. Does not apply to RabbitMQ brokers. */ EncryptionOptions?: EncryptionOptions; /** * Required. The type of broker engine. Currently, Amazon MQ supports ACTIVEMQ and RABBITMQ. */ EngineType: EngineType; /** * Required. The broker engine's version. For a list of supported engine versions, see Supported engines. */ EngineVersion: __string; /** * Required. The broker's instance type. */ HostInstanceType: __string; /** * Optional. The metadata of the LDAP server used to authenticate and authorize connections to the broker. Does not apply to RabbitMQ brokers. */ LdapServerMetadata?: LdapServerMetadataInput; /** * Enables Amazon CloudWatch logging for brokers. */ Logs?: Logs; /** * The parameters that determine the WeeklyStartTime. */ MaintenanceWindowStartTime?: WeeklyStartTime; /** * Enables connections from applications outside of the VPC that hosts the broker's subnets. Set to false by default, if no value is provided. */ PubliclyAccessible: __boolean; /** * The list of rules (1 minimum, 125 maximum) that authorize connections to brokers. */ SecurityGroups?: __listOf__string; /** * The broker's storage type. */ StorageType?: BrokerStorageType; /** * The list of groups that define which subnets and IP ranges the broker can use from different Availability Zones. If you specify more than one subnet, the subnets must be in different Availability Zones. Amazon MQ will not be able to create VPC endpoints for your broker with multiple subnets in the same Availability Zone. A SINGLE_INSTANCE deployment requires one subnet (for example, the default subnet). An ACTIVE_STANDBY_MULTI_AZ Amazon MQ for ActiveMQ deployment requires two subnets. A CLUSTER_MULTI_AZ Amazon MQ for RabbitMQ deployment has no subnet requirements when deployed with public accessibility. Deployment without public accessibility requires at least one subnet. If you specify subnets in a shared VPC for a RabbitMQ broker, the associated VPC to which the specified subnets belong must be owned by your AWS account. Amazon MQ will not be able to create VPC endpoints in VPCs that are not owned by your AWS account. */ SubnetIds?: __listOf__string; /** * Create tags when creating the broker. */ Tags?: __mapOf__string; /** * Required. The list of broker users (persons or applications) who can access queues and topics. This value can contain only alphanumeric characters, dashes, periods, underscores, and tildes (- . _ ~). This value must be 2-100 characters long. Amazon MQ for RabbitMQ When you create an Amazon MQ for RabbitMQ broker, one and only one administrative user is accepted and created when a broker is first provisioned. All subsequent broker users are created by making RabbitMQ API calls directly to brokers or via the RabbitMQ web console. */ Users: __listOfUser; } export interface CreateBrokerResponse { /** * The broker's Amazon Resource Name (ARN). */ BrokerArn?: __string; /** * The unique ID that Amazon MQ generates for the broker. */ BrokerId?: __string; } export interface CreateConfigurationRequest { /** * Optional. The authentication strategy associated with the configuration. The default is SIMPLE. */ AuthenticationStrategy?: AuthenticationStrategy; /** * Required. The type of broker engine. Currently, Amazon MQ supports ACTIVEMQ and RABBITMQ. */ EngineType: EngineType; /** * Required. The broker engine's version. For a list of supported engine versions, see Supported engines. */ EngineVersion: __string; /** * Required. The name of the configuration. This value can contain only alphanumeric characters, dashes, periods, underscores, and tildes (- . _ ~). This value must be 1-150 characters long. */ Name: __string; /** * Create tags when creating the configuration. */ Tags?: __mapOf__string; } export interface CreateConfigurationResponse { /** * Required. The Amazon Resource Name (ARN) of the configuration. */ Arn?: __string; /** * Optional. The authentication strategy associated with the configuration. The default is SIMPLE. */ AuthenticationStrategy?: AuthenticationStrategy; /** * Required. The date and time of the configuration. */ Created?: __timestampIso8601; /** * Required. The unique ID that Amazon MQ generates for the configuration. */ Id?: __string; /** * The latest revision of the configuration. */ LatestRevision?: ConfigurationRevision; /** * Required. The name of the configuration. This value can contain only alphanumeric characters, dashes, periods, underscores, and tildes (- . _ ~). This value must be 1-150 characters long. */ Name?: __string; } export interface CreateTagsRequest { /** * The Amazon Resource Name (ARN) of the resource tag. */ ResourceArn: __string; /** * The key-value pair for the resource tag. */ Tags?: __mapOf__string; } export interface CreateUserRequest { /** * The unique ID that Amazon MQ generates for the broker. */ BrokerId: __string; /** * Enables access to the ActiveMQ Web Console for the ActiveMQ user. */ ConsoleAccess?: __boolean; /** * The list of groups (20 maximum) to which the ActiveMQ user belongs. This value can contain only alphanumeric characters, dashes, periods, underscores, and tildes (- . _ ~). This value must be 2-100 characters long. */ Groups?: __listOf__string; /** * Required. The password of the user. This value must be at least 12 characters long, must contain at least 4 unique characters, and must not contain commas, colons, or equal signs (,:=). */ Password: __string; /** * The username of the ActiveMQ user. This value can contain only alphanumeric characters, dashes, periods, underscores, and tildes (- . _ ~). This value must be 2-100 characters long. */ Username: __string; } export interface CreateUserResponse { } export type DayOfWeek = "MONDAY"|"TUESDAY"|"WEDNESDAY"|"THURSDAY"|"FRIDAY"|"SATURDAY"|"SUNDAY"|string; export interface DeleteBrokerRequest { /** * The unique ID that Amazon MQ generates for the broker. */ BrokerId: __string; } export interface DeleteBrokerResponse { /** * The unique ID that Amazon MQ generates for the broker. */ BrokerId?: __string; } export interface DeleteTagsRequest { /** * The Amazon Resource Name (ARN) of the resource tag. */ ResourceArn: __string; /** * An array of tag keys to delete */ TagKeys: __listOf__string; } export interface DeleteUserRequest { /** * The unique ID that Amazon MQ generates for the broker. */ BrokerId: __string; /** * The username of the ActiveMQ user. This value can contain only alphanumeric characters, dashes, periods, underscores, and tildes (- . _ ~). This value must be 2-100 characters long. */ Username: __string; } export interface DeleteUserResponse { } export type DeploymentMode = "SINGLE_INSTANCE"|"ACTIVE_STANDBY_MULTI_AZ"|"CLUSTER_MULTI_AZ"|string; export interface DescribeBrokerEngineTypesRequest { /** * Filter response by engine type. */ EngineType?: __string; /** * The maximum number of brokers that Amazon MQ can return per page (20 by default). This value must be an integer from 5 to 100. */ MaxResults?: MaxResults; /** * The token that specifies the next page of results Amazon MQ should return. To request the first page, leave nextToken empty. */ NextToken?: __string; } export interface DescribeBrokerEngineTypesResponse { /** * List of available engine types and versions. */ BrokerEngineTypes?: __listOfBrokerEngineType; /** * Required. The maximum number of engine types that can be returned per page (20 by default). This value must be an integer from 5 to 100. */ MaxResults?: __integerMin5Max100; /** * The token that specifies the next page of results Amazon MQ should return. To request the first page, leave nextToken empty. */ NextToken?: __string; } export interface DescribeBrokerInstanceOptionsRequest { /** * Filter response by engine type. */ EngineType?: __string; /** * Filter response by host instance type. */ HostInstanceType?: __string; /** * The maximum number of brokers that Amazon MQ can return per page (20 by default). This value must be an integer from 5 to 100. */ MaxResults?: MaxResults; /** * The token that specifies the next page of results Amazon MQ should return. To request the first page, leave nextToken empty. */ NextToken?: __string; /** * Filter response by storage type. */ StorageType?: __string; } export interface DescribeBrokerInstanceOptionsResponse { /** * List of available broker instance options. */ BrokerInstanceOptions?: __listOfBrokerInstanceOption; /** * Required. The maximum number of instance options that can be returned per page (20 by default). This value must be an integer from 5 to 100. */ MaxResults?: __integerMin5Max100; /** * The token that specifies the next page of results Amazon MQ should return. To request the first page, leave nextToken empty. */ NextToken?: __string; } export interface DescribeBrokerRequest { /** * The unique ID that Amazon MQ generates for the broker. */ BrokerId: __string; } export interface DescribeBrokerResponse { /** * The authentication strategy used to secure the broker. The default is SIMPLE. */ AuthenticationStrategy?: AuthenticationStrategy; /** * Enables automatic upgrades to new minor versions for brokers, as new versions are released and supported by Amazon MQ. Automatic upgrades occur during the scheduled maintenance window of the broker or after a manual broker reboot. */ AutoMinorVersionUpgrade?: __boolean; /** * The broker's Amazon Resource Name (ARN). */ BrokerArn?: __string; /** * The unique ID that Amazon MQ generates for the broker. */ BrokerId?: __string; /** * A list of information about allocated brokers. */ BrokerInstances?: __listOfBrokerInstance; /** * The broker's name. This value must be unique in your AWS account, 1-50 characters long, must contain only letters, numbers, dashes, and underscores, and must not contain white spaces, brackets, wildcard characters, or special characters. */ BrokerName?: __string; /** * The broker's status. */ BrokerState?: BrokerState; /** * The list of all revisions for the specified configuration. */ Configurations?: Configurations; /** * The time when the broker was created. */ Created?: __timestampIso8601; /** * The broker's deployment mode. */ DeploymentMode?: DeploymentMode; /** * Encryption options for the broker. Does not apply to RabbitMQ brokers. */ EncryptionOptions?: EncryptionOptions; /** * The type of broker engine. Currently, Amazon MQ supports ACTIVEMQ and RABBITMQ. */ EngineType?: EngineType; /** * The broker engine's version. For a list of supported engine versions, see Supported engines. */ EngineVersion?: __string; /** * The broker's instance type. */ HostInstanceType?: __string; /** * The metadata of the LDAP server used to authenticate and authorize connections to the broker. */ LdapServerMetadata?: LdapServerMetadataOutput; /** * The list of information about logs currently enabled and pending to be deployed for the specified broker. */ Logs?: LogsSummary; /** * The parameters that determine the WeeklyStartTime. */ MaintenanceWindowStartTime?: WeeklyStartTime; /** * The authentication strategy that will be applied when the broker is rebooted. The default is SIMPLE. */ PendingAuthenticationStrategy?: AuthenticationStrategy; /** * The broker engine version to upgrade to. For a list of supported engine versions, see Supported engines. */ PendingEngineVersion?: __string; /** * The broker's host instance type to upgrade to. For a list of supported instance types, see Broker instance types. */ PendingHostInstanceType?: __string; /** * The metadata of the LDAP server that will be used to authenticate and authorize connections to the broker after it is rebooted. */ PendingLdapServerMetadata?: LdapServerMetadataOutput; /** * The list of pending security groups to authorize connections to brokers. */ PendingSecurityGroups?: __listOf__string; /** * Enables connections from applications outside of the VPC that hosts the broker's subnets. */ PubliclyAccessible?: __boolean; /** * The list of rules (1 minimum, 125 maximum) that authorize connections to brokers. */ SecurityGroups?: __listOf__string; /** * The broker's storage type. */ StorageType?: BrokerStorageType; /** * The list of groups that define which subnets and IP ranges the broker can use from different Availability Zones. */ SubnetIds?: __listOf__string; /** * The list of all tags associated with this broker. */ Tags?: __mapOf__string; /** * The list of all broker usernames for the specified broker. */ Users?: __listOfUserSummary; } export interface DescribeConfigurationRequest { /** * The unique ID that Amazon MQ generates for the configuration. */ ConfigurationId: __string; } export interface DescribeConfigurationResponse { /** * Required. The ARN of the configuration. */ Arn?: __string; /** * Optional. The authentication strategy associated with the configuration. The default is SIMPLE. */ AuthenticationStrategy?: AuthenticationStrategy; /** * Required. The date and time of the configuration revision. */ Created?: __timestampIso8601; /** * Required. The description of the configuration. */ Description?: __string; /** * Required. The type of broker engine. Currently, Amazon MQ supports ACTIVEMQ and RABBITMQ. */ EngineType?: EngineType; /** * Required. The broker engine's version. For a list of supported engine versions, see, Supported engines. */ EngineVersion?: __string; /** * Required. The unique ID that Amazon MQ generates for the configuration. */ Id?: __string; /** * Required. The latest revision of the configuration. */ LatestRevision?: ConfigurationRevision; /** * Required. The name of the configuration. This value can contain only alphanumeric characters, dashes, periods, underscores, and tildes (- . _ ~). This value must be 1-150 characters long. */ Name?: __string; /** * The list of all tags associated with this configuration. */ Tags?: __mapOf__string; } export interface DescribeConfigurationRevisionRequest { /** * The unique ID that Amazon MQ generates for the configuration. */ ConfigurationId: __string; /** * The revision of the configuration. */ ConfigurationRevision: __string; } export interface DescribeConfigurationRevisionResponse { /** * Required. The unique ID that Amazon MQ generates for the configuration. */ ConfigurationId?: __string; /** * Required. The date and time of the configuration. */ Created?: __timestampIso8601; /** * Required. The base64-encoded XML configuration. */ Data?: __string; /** * The description of the configuration. */ Description?: __string; } export interface DescribeUserRequest { /** * The unique ID that Amazon MQ generates for the broker. */ BrokerId: __string; /** * The username of the ActiveMQ user. This value can contain only alphanumeric characters, dashes, periods, underscores, and tildes (- . _ ~). This value must be 2-100 characters long. */ Username: __string; } export interface DescribeUserResponse { /** * Required. The unique ID that Amazon MQ generates for the broker. */ BrokerId?: __string; /** * Enables access to the the ActiveMQ Web Console for the ActiveMQ user. */ ConsoleAccess?: __boolean; /** * The list of groups (20 maximum) to which the ActiveMQ user belongs. This value can contain only alphanumeric characters, dashes, periods, underscores, and tildes (- . _ ~). This value must be 2-100 characters long. */ Groups?: __listOf__string; /** * The status of the changes pending for the ActiveMQ user. */ Pending?: UserPendingChanges; /** * Required. The username of the ActiveMQ user. This value can contain only alphanumeric characters, dashes, periods, underscores, and tildes (- . _ ~). This value must be 2-100 characters long. */ Username?: __string; } export interface EncryptionOptions { /** * The customer master key (CMK) to use for the AWS Key Management Service (KMS). This key is used to encrypt your data at rest. If not provided, Amazon MQ will use a default CMK to encrypt your data. */ KmsKeyId?: __string; /** * Enables the use of an AWS owned CMK using AWS Key Management Service (KMS). Set to true by default, if no value is provided, for example, for RabbitMQ brokers. */ UseAwsOwnedKey: __boolean; } export type EngineType = "ACTIVEMQ"|"RABBITMQ"|string; export interface EngineVersion { /** * Id for the version. */ Name?: __string; } export interface LdapServerMetadataInput { /** * Specifies the location of the LDAP server such as AWS Directory Service for Microsoft Active Directory . Optional failover server. */ Hosts: __listOf__string; /** * The distinguished name of the node in the directory information tree (DIT) to search for roles or groups. For example, ou=group, ou=corp, dc=corp, dc=example, dc=com. */ RoleBase: __string; /** * Specifies the LDAP attribute that identifies the group name attribute in the object returned from the group membership query. */ RoleName?: __string; /** * The LDAP search filter used to find roles within the roleBase. The distinguished name of the user matched by userSearchMatching is substituted into the {0} placeholder in the search filter. The client's username is substituted into the {1} placeholder. For example, if you set this option to (member=uid={1})for the user janedoe, the search filter becomes (member=uid=janedoe) after string substitution. It matches all role entries that have a member attribute equal to uid=janedoe under the subtree selected by the roleBase. */ RoleSearchMatching: __string; /** * The directory search scope for the role. If set to true, scope is to search the entire subtree. */ RoleSearchSubtree?: __boolean; /** * Service account password. A service account is an account in your LDAP server that has access to initiate a connection. For example, cn=admin,dc=corp, dc=example, dc=com. */ ServiceAccountPassword: __string; /** * Service account username. A service account is an account in your LDAP server that has access to initiate a connection. For example, cn=admin,dc=corp, dc=example, dc=com. */ ServiceAccountUsername: __string; /** * Select a particular subtree of the directory information tree (DIT) to search for user entries. The subtree is specified by a DN, which specifies the base node of the subtree. For example, by setting this option to ou=Users,ou=corp, dc=corp, dc=example, dc=com, the search for user entries is restricted to the subtree beneath ou=Users, ou=corp, dc=corp, dc=example, dc=com. */ UserBase: __string; /** * Specifies the name of the LDAP attribute for the user group membership. */ UserRoleName?: __string; /** * The LDAP search filter used to find users within the userBase. The client's username is substituted into the {0} placeholder in the search filter. For example, if this option is set to (uid={0}) and the received username is janedoe, the search filter becomes (uid=janedoe) after string substitution. It will result in matching an entry like uid=janedoe, ou=Users,ou=corp, dc=corp, dc=example, dc=com. */ UserSearchMatching: __string; /** * The directory search scope for the user. If set to true, scope is to search the entire subtree. */ UserSearchSubtree?: __boolean; } export interface LdapServerMetadataOutput { /** * Specifies the location of the LDAP server such as AWS Directory Service for Microsoft Active Directory . Optional failover server. */ Hosts: __listOf__string; /** * The distinguished name of the node in the directory information tree (DIT) to search for roles or groups. For example, ou=group, ou=corp, dc=corp, dc=example, dc=com. */ RoleBase: __string; /** * Specifies the LDAP attribute that identifies the group name attribute in the object returned from the group membership query. */ RoleName?: __string; /** * The LDAP search filter used to find roles within the roleBase. The distinguished name of the user matched by userSearchMatching is substituted into the {0} placeholder in the search filter. The client's username is substituted into the {1} placeholder. For example, if you set this option to (member=uid={1})for the user janedoe, the search filter becomes (member=uid=janedoe) after string substitution. It matches all role entries that have a member attribute equal to uid=janedoe under the subtree selected by the roleBase. */ RoleSearchMatching: __string; /** * The directory search scope for the role. If set to true, scope is to search the entire subtree. */ RoleSearchSubtree?: __boolean; /** * Service account username. A service account is an account in your LDAP server that has access to initiate a connection. For example, cn=admin,dc=corp, dc=example, dc=com. */ ServiceAccountUsername: __string; /** * Select a particular subtree of the directory information tree (DIT) to search for user entries. The subtree is specified by a DN, which specifies the base node of the subtree. For example, by setting this option to ou=Users,ou=corp, dc=corp, dc=example, dc=com, the search for user entries is restricted to the subtree beneath ou=Users, ou=corp, dc=corp, dc=example, dc=com. */ UserBase: __string; /** * Specifies the name of the LDAP attribute for the user group membership. */ UserRoleName?: __string; /** * The LDAP search filter used to find users within the userBase. The client's username is substituted into the {0} placeholder in the search filter. For example, if this option is set to (uid={0}) and the received username is janedoe, the search filter becomes (uid=janedoe) after string substitution. It will result in matching an entry like uid=janedoe, ou=Users,ou=corp, dc=corp, dc=example, dc=com. */ UserSearchMatching: __string; /** * The directory search scope for the user. If set to true, scope is to search the entire subtree. */ UserSearchSubtree?: __boolean; } export interface ListBrokersRequest { /** * The maximum number of brokers that Amazon MQ can return per page (20 by default). This value must be an integer from 5 to 100. */ MaxResults?: MaxResults; /** * The token that specifies the next page of results Amazon MQ should return. To request the first page, leave nextToken empty. */ NextToken?: __string; } export interface ListBrokersResponse { /** * A list of information about all brokers. */ BrokerSummaries?: __listOfBrokerSummary; /** * The token that specifies the next page of results Amazon MQ should return. To request the first page, leave nextToken empty. */ NextToken?: __string; } export interface ListConfigurationRevisionsRequest { /** * The unique ID that Amazon MQ generates for the configuration. */ ConfigurationId: __string; /** * The maximum number of brokers that Amazon MQ can return per page (20 by default). This value must be an integer from 5 to 100. */ MaxResults?: MaxResults; /** * The token that specifies the next page of results Amazon MQ should return. To request the first page, leave nextToken empty. */ NextToken?: __string; } export interface ListConfigurationRevisionsResponse { /** * The unique ID that Amazon MQ generates for the configuration. */ ConfigurationId?: __string; /** * The maximum number of configuration revisions that can be returned per page (20 by default). This value must be an integer from 5 to 100. */ MaxResults?: __integer; /** * The token that specifies the next page of results Amazon MQ should return. To request the first page, leave nextToken empty. */ NextToken?: __string; /** * The list of all revisions for the specified configuration. */ Revisions?: __listOfConfigurationRevision; } export interface ListConfigurationsRequest { /** * The maximum number of brokers that Amazon MQ can return per page (20 by default). This value must be an integer from 5 to 100. */ MaxResults?: MaxResults; /** * The token that specifies the next page of results Amazon MQ should return. To request the first page, leave nextToken empty. */ NextToken?: __string; } export interface ListConfigurationsResponse { /** * The list of all revisions for the specified configuration. */ Configurations?: __listOfConfiguration; /** * The maximum number of configurations that Amazon MQ can return per page (20 by default). This value must be an integer from 5 to 100. */ MaxResults?: __integer; /** * The token that specifies the next page of results Amazon MQ should return. To request the first page, leave nextToken empty. */ NextToken?: __string; } export interface ListTagsRequest { /** * The Amazon Resource Name (ARN) of the resource tag. */ ResourceArn: __string; } export interface ListTagsResponse { /** * The key-value pair for the resource tag. */ Tags?: __mapOf__string; } export interface ListUsersRequest { /** * The unique ID that Amazon MQ generates for the broker. */ BrokerId: __string; /** * The maximum number of brokers that Amazon MQ can return per page (20 by default). This value must be an integer from 5 to 100. */ MaxResults?: MaxResults; /** * The token that specifies the next page of results Amazon MQ should return. To request the first page, leave nextToken empty. */ NextToken?: __string; } export interface ListUsersResponse { /** * Required. The unique ID that Amazon MQ generates for the broker. */ BrokerId?: __string; /** * Required. The maximum number of ActiveMQ users that can be returned per page (20 by default). This value must be an integer from 5 to 100. */ MaxResults?: __integerMin5Max100; /** * The token that specifies the next page of results Amazon MQ should return. To request the first page, leave nextToken empty. */ NextToken?: __string; /** * Required. The list of all ActiveMQ usernames for the specified broker. Does not apply to RabbitMQ brokers. */ Users?: __listOfUserSummary; } export interface Logs { /** * Enables audit logging. Every user management action made using JMX or the ActiveMQ Web Console is logged. Does not apply to RabbitMQ brokers. */ Audit?: __boolean; /** * Enables general logging. */ General?: __boolean; } export interface LogsSummary { /** * Enables audit logging. Every user management action made using JMX or the ActiveMQ Web Console is logged. */ Audit?: __boolean; /** * The location of the CloudWatch Logs log group where audit logs are sent. */ AuditLogGroup?: __string; /** * Enables general logging. */ General: __boolean; /** * The location of the CloudWatch Logs log group where general logs are sent. */ GeneralLogGroup: __string; /** * The list of information about logs pending to be deployed for the specified broker. */ Pending?: PendingLogs; } export type MaxResults = number; export interface PendingLogs { /** * Enables audit logging. Every user management action made using JMX or the ActiveMQ Web Console is logged. */ Audit?: __boolean; /** * Enables general logging. */ General?: __boolean; } export interface RebootBrokerRequest { /** * The unique ID that Amazon MQ generates for the broker. */ BrokerId: __string; } export interface RebootBrokerResponse { } export interface SanitizationWarning { /** * The name of the XML attribute that has been sanitized. */ AttributeName?: __string; /** * The name of the XML element that has been sanitized. */ ElementName?: __string; /** * Required. The reason for which the XML elements or attributes were sanitized. */ Reason: SanitizationWarningReason; } export type SanitizationWarningReason = "DISALLOWED_ELEMENT_REMOVED"|"DISALLOWED_ATTRIBUTE_REMOVED"|"INVALID_ATTRIBUTE_VALUE_REMOVED"|string; export interface UpdateBrokerRequest { /** * Optional. The authentication strategy used to secure the broker. The default is SIMPLE. */ AuthenticationStrategy?: AuthenticationStrategy; /** * Enables automatic upgrades to new minor versions for brokers, as new versions are released and supported by Amazon MQ. Automatic upgrades occur during the scheduled maintenance window of the broker or after a manual broker reboot. */ AutoMinorVersionUpgrade?: __boolean; /** * The unique ID that Amazon MQ generates for the broker. */ BrokerId: __string; /** * A list of information about the configuration. */ Configuration?: ConfigurationId; /** * The broker engine version. For a list of supported engine versions, see Supported engines. */ EngineVersion?: __string; /** * The broker's host instance type to upgrade to. For a list of supported instance types, see Broker instance types. */ HostInstanceType?: __string; /** * Optional. The metadata of the LDAP server used to authenticate and authorize connections to the broker. Does not apply to RabbitMQ brokers. */ LdapServerMetadata?: LdapServerMetadataInput; /** * Enables Amazon CloudWatch logging for brokers. */ Logs?: Logs; /** * The parameters that determine the WeeklyStartTime. */ MaintenanceWindowStartTime?: WeeklyStartTime; /** * The list of security groups (1 minimum, 5 maximum) that authorizes connections to brokers. */ SecurityGroups?: __listOf__string; } export interface UpdateBrokerResponse { /** * Optional. The authentication strategy used to secure the broker. The default is SIMPLE. */ AuthenticationStrategy?: AuthenticationStrategy; /** * The new boolean value that specifies whether broker engines automatically upgrade to new minor versions as new versions are released and supported by Amazon MQ. */ AutoMinorVersionUpgrade?: __boolean; /** * Required. The unique ID that Amazon MQ generates for the broker. */ BrokerId?: __string; /** * The ID of the updated configuration. */ Configuration?: ConfigurationId; /** * The broker engine version to upgrade to. For a list of supported engine versions, see Supported engines. */ EngineVersion?: __string; /** * The broker's host instance type to upgrade to. For a list of supported instance types, see Broker instance types. */ HostInstanceType?: __string; /** * Optional. The metadata of the LDAP server used to authenticate and authorize connections to the broker. Does not apply to RabbitMQ brokers. */ LdapServerMetadata?: LdapServerMetadataOutput; /** * The list of information about logs to be enabled for the specified broker. */ Logs?: Logs; /** * The parameters that determine the WeeklyStartTime. */ MaintenanceWindowStartTime?: WeeklyStartTime; /** * The list of security groups (1 minimum, 5 maximum) that authorizes connections to brokers. */ SecurityGroups?: __listOf__string; } export interface UpdateConfigurationRequest { /** * The unique ID that Amazon MQ generates for the configuration. */ ConfigurationId: __string; /** * Required. The base64-encoded XML configuration. */ Data: __string; /** * The description of the configuration. */ Description?: __string; } export interface UpdateConfigurationResponse { /** * Required. The Amazon Resource Name (ARN) of the configuration. */ Arn?: __string; /** * Required. The date and time of the configuration. */ Created?: __timestampIso8601; /** * Required. The unique ID that Amazon MQ generates for the configuration. */ Id?: __string; /** * The latest revision of the configuration. */ LatestRevision?: ConfigurationRevision; /** * Required. The name of the configuration. This value can contain only alphanumeric characters, dashes, periods, underscores, and tildes (- . _ ~). This value must be 1-150 characters long. */ Name?: __string; /** * The list of the first 20 warnings about the configuration XML elements or attributes that were sanitized. */ Warnings?: __listOfSanitizationWarning; } export interface UpdateUserRequest { /** * The unique ID that Amazon MQ generates for the broker. */ BrokerId: __string; /** * Enables access to the the ActiveMQ Web Console for the ActiveMQ user. */ ConsoleAccess?: __boolean; /** * The list of groups (20 maximum) to which the ActiveMQ user belongs. This value can contain only alphanumeric characters, dashes, periods, underscores, and tildes (- . _ ~). This value must be 2-100 characters long. */ Groups?: __listOf__string; /** * The password of the user. This value must be at least 12 characters long, must contain at least 4 unique characters, and must not contain commas, colons, or equal signs (,:=). */ Password?: __string; /** * The username of the ActiveMQ user. This value can contain only alphanumeric characters, dashes, periods, underscores, and tildes (- . _ ~). This value must be 2-100 characters long. */ Username: __string; } export interface UpdateUserResponse { } export interface User { /** * Enables access to the ActiveMQ Web Console for the ActiveMQ user. Does not apply to RabbitMQ brokers. */ ConsoleAccess?: __boolean; /** * The list of groups (20 maximum) to which the ActiveMQ user belongs. This value can contain only alphanumeric characters, dashes, periods, underscores, and tildes (- . _ ~). This value must be 2-100 characters long. Does not apply to RabbitMQ brokers. */ Groups?: __listOf__string; /** * Required. The password of the user. This value must be at least 12 characters long, must contain at least 4 unique characters, and must not contain commas, colons, or equal signs (,:=). */ Password: __string; /** * important>Amazon MQ for ActiveMQ For ActiveMQ brokers, this value can contain only alphanumeric characters, dashes, periods, underscores, and tildes (- . _ ~). This value must be 2-100 characters long./important> Amazon MQ for RabbitMQ For RabbitMQ brokers, this value can contain only alphanumeric characters, dashes, periods, underscores (- . _). This value must not contain a tilde (~) character. Amazon MQ prohibts using guest as a valid usename. This value must be 2-100 characters long. */ Username: __string; } export interface UserPendingChanges { /** * Enables access to the the ActiveMQ Web Console for the ActiveMQ user. */ ConsoleAccess?: __boolean; /** * The list of groups (20 maximum) to which the ActiveMQ user belongs. This value can contain only alphanumeric characters, dashes, periods, underscores, and tildes (- . _ ~). This value must be 2-100 characters long. */ Groups?: __listOf__string; /** * Required. The type of change pending for the ActiveMQ user. */ PendingChange: ChangeType; } export interface UserSummary { /** * The type of change pending for the broker user. */ PendingChange?: ChangeType; /** * Required. The username of the broker user. This value can contain only alphanumeric characters, dashes, periods, underscores, and tildes (- . _ ~). This value must be 2-100 characters long. */ Username: __string; } export interface WeeklyStartTime { /** * Required. The day of the week. */ DayOfWeek: DayOfWeek; /** * Required. The time, in 24-hour format. */ TimeOfDay: __string; /** * The time zone, UTC by default, in either the Country/City format, or the UTC offset format. */ TimeZone?: __string; } export type __boolean = boolean; export type __integer = number; export type __integerMin5Max100 = number; export type __listOfAvailabilityZone = AvailabilityZone[]; export type __listOfBrokerEngineType = BrokerEngineType[]; export type __listOfBrokerInstance = BrokerInstance[]; export type __listOfBrokerInstanceOption = BrokerInstanceOption[]; export type __listOfBrokerSummary = BrokerSummary[]; export type __listOfConfiguration = Configuration[]; export type __listOfConfigurationId = ConfigurationId[]; export type __listOfConfigurationRevision = ConfigurationRevision[]; export type __listOfDeploymentMode = DeploymentMode[]; export type __listOfEngineVersion = EngineVersion[]; export type __listOfSanitizationWarning = SanitizationWarning[]; export type __listOfUser = User[]; export type __listOfUserSummary = UserSummary[]; export type __listOf__string = __string[]; export type __mapOf__string = {[key: string]: __string}; export type __string = string; export type __timestampIso8601 = Date; /** * A string in YYYY-MM-DD format that represents the latest possible API version that can be used in this service. Specify 'latest' to use the latest possible version. */ export type apiVersion = "2017-11-27"|"latest"|string; export interface ClientApiVersions { /** * A string in YYYY-MM-DD format that represents the latest possible API version that can be used in this service. Specify 'latest' to use the latest possible version. */ apiVersion?: apiVersion; } export type ClientConfiguration = ServiceConfigurationOptions & ClientApiVersions; /** * Contains interfaces for use with the MQ client. */ export import Types = MQ; } export = MQ;
the_stack
import {Injectable, isDevMode, Inject} from '@angular/core'; import { HttpClient, HttpParams } from '@angular/common/http'; import 'rxjs/add/operator/map'; import 'rxjs/add/operator/map'; import 'rxjs/add/operator/catch'; import 'rxjs/add/observable/throw'; import { THEMES_CONFIG } from '../themes'; import { Router, CanActivate } from '@angular/router'; import { DOCUMENT } from '@angular/common'; import { BehaviorSubject } from 'rxjs'; import { MatSnackBar } from '@angular/material/snack-bar'; import * as Fingerprint2 from 'fingerprintjs2'; import { ChangeRolePermissionsRequest, ChangeUserPermissionsRequest, ConfigResponse, CreatePlaylistRequest, CreatePlaylistResponse, CropFileSettings, DeleteMp3Mp4Request, DeletePlaylistRequest, DeleteSubscriptionFileRequest, DeleteUserRequest, DownloadArchiveRequest, DownloadFileRequest, FileType, GenerateNewApiKeyResponse, GetAllDownloadsResponse, GetAllFilesResponse, GetAllSubscriptionsResponse, GetDownloadResponse, GetDownloadRequest, GetFileRequest, GetFileResponse, GetMp3sResponse, GetMp4sResponse, GetPlaylistRequest, GetPlaylistResponse, GetRolesResponse, GetSubscriptionRequest, GetSubscriptionResponse, GetUsersResponse, LoginRequest, LoginResponse, DownloadRequest, DownloadResponse, Playlist, RegisterRequest, RegisterResponse, SetConfigRequest, SharingToggle, SubscribeRequest, SubscribeResponse, SubscriptionRequestData, SuccessObject, UpdaterStatus, UnsubscribeRequest, UnsubscribeResponse, UpdatePlaylistRequest, UpdateServerRequest, UpdateUserRequest, UserPermission, YesNo, GenerateArgsResponse, GetPlaylistsRequest, UpdateCategoryRequest, UpdateCategoriesRequest, DeleteCategoryRequest, CreateCategoryRequest, CreateCategoryResponse, GetAllCategoriesResponse, AddFileToPlaylistRequest, IncrementViewCountRequest, GetLogsRequest, GetLogsResponse, UpdateConcurrentStreamResponse, UpdateConcurrentStreamRequest, CheckConcurrentStreamRequest, CheckConcurrentStreamResponse, DownloadTwitchChatByVODIDRequest, DownloadTwitchChatByVODIDResponse, GetFullTwitchChatRequest, GetFullTwitchChatResponse, GetAllDownloadsRequest, TestConnectionStringRequest, TestConnectionStringResponse, TransferDBRequest, TransferDBResponse, VersionInfoResponse, DBInfoResponse, GetFileFormatsRequest, GetFileFormatsResponse, } from '../api-types'; import { isoLangs } from './settings/locales_list'; import { Title } from '@angular/platform-browser'; @Injectable() export class PostsService implements CanActivate { path = ''; // local settings THEMES_CONFIG = THEMES_CONFIG; theme; card_size = 'medium'; sidepanel_mode = 'over'; // auth auth_token = '4241b401-7236-493e-92b5-b72696b9d853'; session_id = null; httpOptions: { params: HttpParams }; http_params: string = null; unauthorized = false; debugMode = false; // must be reset after logout isLoggedIn = false; token = null; user = null; permissions = null; available_permissions = null; // behavior subjects reload_config = new BehaviorSubject<boolean>(false); config_reloaded = new BehaviorSubject<boolean>(false); service_initialized = new BehaviorSubject<boolean>(false); settings_changed = new BehaviorSubject<boolean>(false); open_create_default_admin_dialog = new BehaviorSubject<boolean>(false); files_changed = new BehaviorSubject<boolean>(false); playlists_changed = new BehaviorSubject<boolean>(false); // app status initialized = false; // global vars config = null; subscriptions = null; categories = null; sidenav = null; locale = isoLangs['en']; version_info = null; constructor(private http: HttpClient, private router: Router, @Inject(DOCUMENT) private document: Document, public snackBar: MatSnackBar, private titleService: Title) { console.log('PostsService Initialized...'); this.path = this.document.location.origin + '/api/'; if (isDevMode()) { this.debugMode = true; this.path = 'http://localhost:17442/api/'; } this.http_params = `apiKey=${this.auth_token}` this.httpOptions = { params: new HttpParams({ fromString: this.http_params }) }; Fingerprint2.get(components => { // set identity as user id doesn't necessarily exist this.session_id = Fingerprint2.x64hash128(components.map(function (pair) { return pair.value; }).join(), 31); this.httpOptions.params = this.httpOptions.params.set('sessionID', this.session_id); }); const redirect_not_required = window.location.href.includes('/player') || window.location.href.includes('/login'); // get config this.loadNavItems().subscribe(res => { const result = !this.debugMode ? res['config_file'] : res; if (result) { this.config = result['YoutubeDLMaterial']; this.titleService.setTitle(this.config['Extra']['title_top']); if (this.config['Advanced']['multi_user_mode']) { this.checkAdminCreationStatus(); // login stuff if (localStorage.getItem('jwt_token') && localStorage.getItem('jwt_token') !== 'null') { this.token = localStorage.getItem('jwt_token'); this.httpOptions.params = this.httpOptions.params.set('jwt', this.token); this.jwtAuth(); } else if (redirect_not_required) { this.setInitialized(); } else { this.sendToLogin(); } } else { this.setInitialized(); } } }); this.reload_config.subscribe(yes_reload => { if (yes_reload) { this.reloadConfig(); } }); if (localStorage.getItem('sidepanel_mode')) { this.sidepanel_mode = localStorage.getItem('sidepanel_mode'); } if (localStorage.getItem('card_size')) { this.card_size = localStorage.getItem('card_size'); } // localization const locale = localStorage.getItem('locale'); if (!locale) { localStorage.setItem('locale', 'en'); } if (isoLangs[locale]) { this.locale = isoLangs[locale]; } } canActivate(route, state): Promise<boolean> { return new Promise(resolve => { resolve(true); }) console.log(route); throw new Error('Method not implemented.'); } setTheme(theme) { this.theme = this.THEMES_CONFIG[theme]; } getSubscriptionByID(sub_id) { for (let i = 0; i < this.subscriptions.length; i++) { if (this.subscriptions[i]['id'] === sub_id) { return this.subscriptions[i]; } } return null; } startHandshake(url: string) { return this.http.get(url + 'geturl'); } startHandshakeSSL(url: string) { return this.http.get(url + 'geturl'); } reloadConfig() { this.loadNavItems().subscribe(res => { const result = !this.debugMode ? res['config_file'] : res; if (result) { this.config = result['YoutubeDLMaterial']; this.config_reloaded.next(true); } }); } // tslint:disable-next-line: max-line-length // tslint:disable-next-line: max-line-length downloadFile(url: string, type: FileType, selectedQuality: string, customQualityConfiguration: string, customArgs: string = null, additionalArgs: string = null, customOutput: string = null, youtubeUsername: string = null, youtubePassword: string = null, cropFileSettings: CropFileSettings = null) { const body: DownloadRequest = {url: url, selectedHeight: selectedQuality, customQualityConfiguration: customQualityConfiguration, customArgs: customArgs, additionalArgs: additionalArgs, customOutput: customOutput, youtubeUsername: youtubeUsername, youtubePassword: youtubePassword, type: type, cropFileSettings: cropFileSettings} return this.http.post<DownloadResponse>(this.path + 'downloadFile', body, this.httpOptions); } generateArgs(url: string, type: FileType, selectedQuality: string, customQualityConfiguration: string, customArgs: string = null, additionalArgs: string = null, customOutput: string = null, youtubeUsername: string = null, youtubePassword: string = null, cropFileSettings = null) { const body: DownloadRequest = {url: url, selectedHeight: selectedQuality, customQualityConfiguration: customQualityConfiguration, customArgs: customArgs, additionalArgs: additionalArgs, customOutput: customOutput, youtubeUsername: youtubeUsername, youtubePassword: youtubePassword, type: type, cropFileSettings: cropFileSettings} return this.http.post<GenerateArgsResponse>(this.path + 'generateArgs', body, this.httpOptions); } getDBInfo() { return this.http.get<DBInfoResponse>(this.path + 'getDBInfo', this.httpOptions); } transferDB(local_to_remote) { const body: TransferDBRequest = {local_to_remote: local_to_remote}; return this.http.post<TransferDBResponse>(this.path + 'transferDB', body, this.httpOptions); } testConnectionString(connection_string: string) { const body: TestConnectionStringRequest = {connection_string: connection_string}; return this.http.post<TestConnectionStringResponse>(this.path + 'testConnectionString', body, this.httpOptions); } killAllDownloads() { return this.http.post<SuccessObject>(this.path + 'killAllDownloads', {}, this.httpOptions); } restartServer() { return this.http.post<SuccessObject>(this.path + 'restartServer', {}, this.httpOptions); } loadNavItems() { if (isDevMode()) { return this.http.get('./assets/default.json'); } else { return this.http.get<ConfigResponse>(this.path + 'config', this.httpOptions); } } loadAsset(name) { return this.http.get(`./assets/${name}`); } getSupportedLocales() { return this.http.get('./assets/i18n/supported_locales.json'); } setConfig(config) { const body: SetConfigRequest = {new_config_file: config}; return this.http.post<SuccessObject>(this.path + 'setConfig', body, this.httpOptions); } deleteFile(uid: string, blacklistMode = false) { const body: DeleteMp3Mp4Request = {uid: uid, blacklistMode: blacklistMode} return this.http.post(this.path + 'deleteFile', body, this.httpOptions); } getMp3s() { return this.http.get<GetMp3sResponse>(this.path + 'getMp3s', this.httpOptions); } getMp4s() { return this.http.get<GetMp4sResponse>(this.path + 'getMp4s', this.httpOptions); } getFile(uid: string, type: FileType, uuid: string = null) { const body: GetFileRequest = {uid: uid, type: type, uuid: uuid}; return this.http.post<GetFileResponse>(this.path + 'getFile', body, this.httpOptions); } getAllFiles(sort, range, text_search, file_type_filter) { return this.http.post<GetAllFilesResponse>(this.path + 'getAllFiles', {sort: sort, range: range, text_search: text_search, file_type_filter: file_type_filter}, this.httpOptions); } downloadFileFromServer(uid: string, uuid: string = null, sub_id: string = null) { const body: DownloadFileRequest = { uid: uid, uuid: uuid, sub_id: sub_id }; return this.http.post(this.path + 'downloadFile', body, {responseType: 'blob', params: this.httpOptions.params}); } getFullTwitchChat(id, type, uuid = null, sub = null) { const body: GetFullTwitchChatRequest = {id: id, type: type, uuid: uuid, sub: sub}; return this.http.post<GetFullTwitchChatResponse>(this.path + 'getFullTwitchChat', body, this.httpOptions); } downloadTwitchChat(id, type, vodId, uuid = null, sub = null) { const body: DownloadTwitchChatByVODIDRequest = {id: id, type: type, vodId: vodId, uuid: uuid, sub: sub}; return this.http.post<DownloadTwitchChatByVODIDResponse>(this.path + 'downloadTwitchChatByVODID', body, this.httpOptions); } downloadPlaylistFromServer(playlist_id, uuid = null) { const body: DownloadFileRequest = {uuid: uuid, playlist_id: playlist_id}; return this.http.post(this.path + 'downloadFileFromServer', body, {responseType: 'blob', params: this.httpOptions.params}); } downloadSubFromServer(sub_id, uuid = null) { const body: DownloadFileRequest = {uuid: uuid, sub_id: sub_id}; return this.http.post(this.path + 'downloadFileFromServer', body, {responseType: 'blob', params: this.httpOptions.params}); } checkConcurrentStream(uid) { const body: CheckConcurrentStreamRequest = {uid: uid}; return this.http.post<CheckConcurrentStreamResponse>(this.path + 'checkConcurrentStream', body, this.httpOptions); } updateConcurrentStream(uid, playback_timestamp, unix_timestamp, playing) { const body: UpdateConcurrentStreamRequest = {uid: uid, playback_timestamp: playback_timestamp, unix_timestamp: unix_timestamp, playing: playing}; return this.http.post<UpdateConcurrentStreamResponse>(this.path + 'updateConcurrentStream', body, this.httpOptions); } uploadCookiesFile(fileFormData) { return this.http.post<SuccessObject>(this.path + 'uploadCookies', fileFormData, this.httpOptions); } downloadArchive(sub) { const body: DownloadArchiveRequest = {sub: sub}; return this.http.post(this.path + 'downloadArchive', body, {responseType: 'blob', params: this.httpOptions.params}); } getFileFormats(url) { const body: GetFileFormatsRequest = {url: url}; return this.http.post<GetFileFormatsResponse>(this.path + 'getFileFormats', body, this.httpOptions); } getLogs(lines = 50) { const body: GetLogsRequest = {lines: lines}; return this.http.post<GetLogsResponse>(this.path + 'logs', body, this.httpOptions); } clearAllLogs() { return this.http.post<SuccessObject>(this.path + 'clearAllLogs', {}, this.httpOptions); } generateNewAPIKey() { return this.http.post<GenerateNewApiKeyResponse>(this.path + 'generateNewAPIKey', {}, this.httpOptions); } enableSharing(uid: string, is_playlist: boolean) { const body: SharingToggle = {uid: uid, is_playlist: is_playlist}; return this.http.post<SuccessObject>(this.path + 'enableSharing', body, this.httpOptions); } disableSharing(uid: string, is_playlist: boolean) { const body: SharingToggle = {uid: uid, is_playlist: is_playlist}; return this.http.post<SuccessObject>(this.path + 'disableSharing', body, this.httpOptions); } createPlaylist(playlistName: string, uids: string[], type: FileType, thumbnailURL: string) { const body: CreatePlaylistRequest = {playlistName: playlistName, uids: uids, type: type, thumbnailURL: thumbnailURL}; return this.http.post<CreatePlaylistResponse>(this.path + 'createPlaylist', body, this.httpOptions); } getPlaylist(playlist_id: string, uuid: string = null, include_file_metadata: boolean = false) { const body: GetPlaylistRequest = {playlist_id: playlist_id, include_file_metadata: include_file_metadata, uuid: uuid}; return this.http.post<GetPlaylistResponse>(this.path + 'getPlaylist', body, this.httpOptions); } incrementViewCount(file_uid, sub_id, uuid) { const body: IncrementViewCountRequest = {file_uid: file_uid, sub_id: sub_id, uuid: uuid}; return this.http.post<SuccessObject>(this.path + 'incrementViewCount', body, this.httpOptions); } getPlaylists() { return this.http.post<GetPlaylistsRequest>(this.path + 'getPlaylists', {}, this.httpOptions); } updatePlaylist(playlist: Playlist) { const body: UpdatePlaylistRequest = {playlist: playlist}; return this.http.post<SuccessObject>(this.path + 'updatePlaylist', body, this.httpOptions); } removePlaylist(playlist_id: string, type: FileType) { const body: DeletePlaylistRequest = {playlist_id: playlist_id, type: type}; return this.http.post<SuccessObject>(this.path + 'deletePlaylist', body, this.httpOptions); } createSubscription(url, name, timerange = null, maxQuality = 'best', audioOnly = false, customArgs: string = null, customFileOutput: string = null) { const body: SubscribeRequest = {url: url, name: name, timerange: timerange, maxQuality: maxQuality, audioOnly: audioOnly, customArgs: customArgs, customFileOutput: customFileOutput}; return this.http.post<SubscribeResponse>(this.path + 'subscribe', body, this.httpOptions); } addFileToPlaylist(playlist_id, file_uid) { const body: AddFileToPlaylistRequest = {playlist_id: playlist_id, file_uid: file_uid} return this.http.post<SuccessObject>(this.path + 'addFileToPlaylist', body, this.httpOptions); } // categories getAllCategories() { return this.http.post<GetAllCategoriesResponse>(this.path + 'getAllCategories', {}, this.httpOptions); } createCategory(name) { const body: CreateCategoryRequest = {name: name}; return this.http.post<CreateCategoryResponse>(this.path + 'createCategory', body, this.httpOptions); } deleteCategory(category_uid) { const body: DeleteCategoryRequest = {category_uid: category_uid}; return this.http.post<SuccessObject>(this.path + 'deleteCategory', body, this.httpOptions); } updateCategory(category) { const body: UpdateCategoryRequest = {category: category}; return this.http.post<SuccessObject>(this.path + 'updateCategory', body, this.httpOptions); } updateCategories(categories) { const body: UpdateCategoriesRequest = {categories: categories}; return this.http.post<SuccessObject>(this.path + 'updateCategories', body, this.httpOptions); } reloadCategories() { this.getAllCategories().subscribe(res => { this.categories = res['categories']; }); } updateSubscription(subscription) { delete subscription['videos']; return this.http.post<SuccessObject>(this.path + 'updateSubscription', {subscription: subscription}, this.httpOptions); } unsubscribe(sub: SubscriptionRequestData, deleteMode = false) { const body: UnsubscribeRequest = {sub: sub, deleteMode: deleteMode}; return this.http.post<UnsubscribeResponse>(this.path + 'unsubscribe', body, this.httpOptions) } deleteSubscriptionFile(sub: SubscriptionRequestData, file: string, deleteForever: boolean, file_uid: string) { const body: DeleteSubscriptionFileRequest = {sub: sub, file: file, deleteForever: deleteForever, file_uid: file_uid}; return this.http.post<SuccessObject>(this.path + 'deleteSubscriptionFile', body, this.httpOptions) } getSubscription(id: string, name: string = null) { const body: GetSubscriptionRequest = {id: id, name: name}; return this.http.post<GetSubscriptionResponse>(this.path + 'getSubscription', body, this.httpOptions); } getAllSubscriptions() { return this.http.post<GetAllSubscriptionsResponse>(this.path + 'getSubscriptions', {}, this.httpOptions); } getCurrentDownloads(uids: Array<string> = null) { const body: GetAllDownloadsRequest = {uids: uids}; return this.http.post<GetAllDownloadsResponse>(this.path + 'downloads', body, this.httpOptions); } getCurrentDownload(download_uid: string) { const body: GetDownloadRequest = {download_uid: download_uid}; return this.http.post<GetDownloadResponse>(this.path + 'download', body, this.httpOptions); } pauseDownload(download_uid) { return this.http.post<SuccessObject>(this.path + 'pauseDownload', {download_uid: download_uid}, this.httpOptions); } pauseAllDownloads() { return this.http.post<SuccessObject>(this.path + 'pauseAllDownloads', {}, this.httpOptions); } resumeDownload(download_uid) { return this.http.post<SuccessObject>(this.path + 'resumeDownload', {download_uid: download_uid}, this.httpOptions); } resumeAllDownloads() { return this.http.post<SuccessObject>(this.path + 'resumeAllDownloads', {}, this.httpOptions); } restartDownload(download_uid) { return this.http.post<SuccessObject>(this.path + 'restartDownload', {download_uid: download_uid}, this.httpOptions); } cancelDownload(download_uid) { return this.http.post<SuccessObject>(this.path + 'cancelDownload', {download_uid: download_uid}, this.httpOptions); } clearDownload(download_uid) { return this.http.post<SuccessObject>(this.path + 'clearDownload', {download_uid: download_uid}, this.httpOptions); } clearFinishedDownloads() { return this.http.post<SuccessObject>(this.path + 'clearFinishedDownloads', {}, this.httpOptions); } getVersionInfo() { return this.http.get<VersionInfoResponse>(this.path + 'versionInfo', this.httpOptions); } updateServer(tag: string) { const body: UpdateServerRequest = {tag: tag}; return this.http.post<SuccessObject>(this.path + 'updateServer', body, this.httpOptions); } getUpdaterStatus() { return this.http.get<UpdaterStatus>(this.path + 'updaterStatus', this.httpOptions); } // gets tag of the latest version of youtubedl-material getLatestGithubRelease() { return this.http.get('https://api.github.com/repos/tzahi12345/youtubedl-material/releases/latest'); } getAvailableRelease() { return this.http.get('https://api.github.com/repos/tzahi12345/youtubedl-material/releases'); } afterLogin(user, token, permissions, available_permissions) { this.isLoggedIn = true; this.user = user; this.permissions = permissions; this.available_permissions = available_permissions; this.token = token; localStorage.setItem('jwt_token', this.token); this.httpOptions.params = this.httpOptions.params.set('jwt', this.token); this.setInitialized(); // needed to re-initialize parts of app after login this.config_reloaded.next(true); if (this.router.url === '/login') { this.router.navigate(['/home']); } } // user methods login(username: string, password: string) { const body: LoginRequest = {username: username, password: password}; return this.http.post<LoginResponse>(this.path + 'auth/login', body, this.httpOptions); } // user methods jwtAuth() { const call = this.http.post(this.path + 'auth/jwtAuth', {}, this.httpOptions); call.subscribe(res => { if (res['token']) { this.afterLogin(res['user'], res['token'], res['permissions'], res['available_permissions']); } }, err => { if (err.status === 401) { this.sendToLogin(); this.token = null; this.resetHttpParams(); } console.log(err); }); return call; } logout() { this.user = null; this.permissions = null; this.isLoggedIn = false; this.token = null; localStorage.setItem('jwt_token', null); if (this.router.url !== '/login') { this.router.navigate(['/login']); } this.resetHttpParams(); } hasPermission(permission) { // assume not logged in users never have permission if (this.config.Advanced.multi_user_mode && !this.isLoggedIn) return false; return this.config.Advanced.multi_user_mode ? this.permissions.includes(permission) : true; } // user methods register(username: string, password: string) { const body: RegisterRequest = {userid: username, username: username, password: password} const call = this.http.post<RegisterResponse>(this.path + 'auth/register', body, this.httpOptions); return call; } sendToLogin() { if (!this.initialized) { this.setInitialized(); } if (this.router.url === '/login') { return; } this.router.navigate(['/login']); // send login notification this.openSnackBar('You must log in to access this page!'); } resetHttpParams() { // resets http params this.http_params = `apiKey=${this.auth_token}&sessionID=${this.session_id}` this.httpOptions = { params: new HttpParams({ fromString: this.http_params }), }; } setInitialized() { this.service_initialized.next(true); this.initialized = true; this.config_reloaded.next(true); } reloadSubscriptions() { this.getAllSubscriptions().subscribe(res => { this.subscriptions = res['subscriptions']; }); } adminExists() { return this.http.post(this.path + 'auth/adminExists', {}, this.httpOptions); } createAdminAccount(password: string) { const body: RegisterRequest = {userid: 'admin', username: 'admin', password: password}; return this.http.post<RegisterResponse>(this.path + 'auth/register', body, this.httpOptions); } checkAdminCreationStatus(force_show = false) { if (!force_show && !this.config['Advanced']['multi_user_mode']) { return; } this.adminExists().subscribe(res => { if (!res['exists']) { // must create admin account this.open_create_default_admin_dialog.next(true); } }); } changeUser(change_obj: UpdateUserRequest['change_object']) { const body: UpdateUserRequest = {change_object: change_obj}; return this.http.post<SuccessObject>(this.path + 'updateUser', body, this.httpOptions); } deleteUser(uid: string) { const body: DeleteUserRequest = {uid: uid}; return this.http.post<SuccessObject>(this.path + 'deleteUser', body, this.httpOptions); } changeUserPassword(user_uid, new_password) { return this.http.post(this.path + 'auth/changePassword', {user_uid: user_uid, new_password: new_password}, this.httpOptions); } getUsers() { return this.http.post<GetUsersResponse>(this.path + 'getUsers', {}, this.httpOptions); } getRoles() { return this.http.post<GetRolesResponse>(this.path + 'getRoles', {}, this.httpOptions); } setUserPermission(user_uid: string, permission: UserPermission, new_value: YesNo) { const body: ChangeUserPermissionsRequest = {user_uid: user_uid, permission: permission, new_value: new_value}; return this.http.post<SuccessObject>(this.path + 'changeUserPermissions', body, this.httpOptions); } setRolePermission(role_name: string, permission: UserPermission, new_value: YesNo) { const body: ChangeRolePermissionsRequest = {role: role_name, permission: permission, new_value: new_value}; return this.http.post<SuccessObject>(this.path + 'changeRolePermissions', body, this.httpOptions); } getSponsorBlockDataForVideo(id_hash) { const sponsor_block_api_path = 'https://sponsor.ajay.app/api/'; return this.http.get(sponsor_block_api_path + `skipSegments/${id_hash}`); } public openSnackBar(message: string, action: string = '') { this.snackBar.open(message, action, { duration: 2000, }); } }
the_stack
export namespace apis { export namespace alarms { export type Alarm = chrome.alarms.Alarm; export type _CreateAlarmInfo = chrome.alarms.AlarmCreateInfo; export function clear(name: string): Promise<boolean> { return new Promise<boolean>((resolve, reject) => { chrome.alarms.clear(name, wasCleared => { if (chrome.runtime.lastError) { reject(new Error(chrome.runtime.lastError.message)); } else { resolve(wasCleared); } }); }); } export function create(name: string, alarmInfo: _CreateAlarmInfo): void { chrome.alarms.create(name, alarmInfo); } export function get(name: string): Promise<Alarm | undefined> { return new Promise<Alarm | undefined>((resolve, reject) => { chrome.alarms.get(name, alarm => { if (chrome.runtime.lastError) { reject(new Error(chrome.runtime.lastError.message)); } else { resolve(alarm); } }); }); } export const onAlarm = { addListener(callback: (alarm: Alarm) => void): void { chrome.alarms.onAlarm.addListener(callback); }, }; } export namespace extensionTypes { export type InjectDetails = chrome.tabs.InjectDetails; } export namespace i18n { export function getMessage(messageName: string, substitutions?: unknown): string { return chrome.i18n.getMessage(messageName, substitutions); } } export namespace identity { export type _LaunchWebAuthFlowDetails = chrome.identity.WebAuthFlowOptions; export function getRedirectURL(path?: string): string { return chrome.identity.getRedirectURL(path); } export function launchWebAuthFlow(details: _LaunchWebAuthFlowDetails): Promise<string> { return new Promise<string>((resolve, reject) => { chrome.identity.launchWebAuthFlow(details, responseUrl => { if (chrome.runtime.lastError) { reject(new Error(chrome.runtime.lastError.message)); } else { // eslint-disable-next-line @typescript-eslint/no-non-null-assertion resolve(responseUrl!); } }); }); } } export namespace permissions { export type AnyPermissions = chrome.permissions.Permissions; export type Permissions = chrome.permissions.Permissions; export function contains(permissions: AnyPermissions): Promise<boolean> { return new Promise<boolean>((resolve, reject) => { chrome.permissions.contains(permissions, result => { if (chrome.runtime.lastError) { reject(new Error(chrome.runtime.lastError.message)); } else { resolve(result); } }); }); } export function request(permissions: Permissions): Promise<boolean> { return new Promise<boolean>((resolve, reject) => { chrome.permissions.request(permissions, granted => { if (chrome.runtime.lastError) { reject(new Error(chrome.runtime.lastError.message)); } else { resolve(granted); } }); }); } } export namespace runtime { export type MessageSender = chrome.runtime.MessageSender; export type PlatformInfo = chrome.runtime.PlatformInfo; export type _OnInstalledDetails = chrome.runtime.InstalledDetails; export function getPlatformInfo(): Promise<PlatformInfo> { return new Promise<PlatformInfo>((resolve, reject) => { chrome.runtime.getPlatformInfo(platformInfo => { if (chrome.runtime.lastError) { reject(new Error(chrome.runtime.lastError.message)); } else { resolve(platformInfo); } }); }); } export function openOptionsPage(): Promise<void> { return new Promise<void>((resolve, reject) => { chrome.runtime.openOptionsPage(() => { if (chrome.runtime.lastError) { reject(new Error(chrome.runtime.lastError.message)); } else { resolve(); } }); }); } export function sendMessage(message: unknown): Promise<unknown> { return new Promise<unknown>((resolve, reject) => { chrome.runtime.sendMessage(message, response => { if (chrome.runtime.lastError) { reject(new Error(chrome.runtime.lastError.message)); } else { resolve(response); } }); }); } export const onInstalled = { addListener(callback: (details: _OnInstalledDetails) => void): void { chrome.runtime.onInstalled.addListener(callback); }, }; export const onMessage = { addListener( callback: ( message: unknown, sender: MessageSender, sendResponse: (response: unknown) => void | boolean, ) => void, ): void { chrome.runtime.onMessage.addListener(callback); }, removeListener( callback: ( message: unknown, sender: MessageSender, sendResponse: (response: unknown) => void | boolean, ) => void, ): void { chrome.runtime.onMessage.removeListener(callback); }, }; export const onStartup = { addListener(callback: () => void): void { chrome.runtime.onStartup.addListener(callback); }, }; } export namespace storage { export const local = { get( keys: string | string[] | Record<string, unknown> | null, ): Promise<Record<string, unknown>> { return new Promise<Record<string, unknown>>((resolve, reject) => { chrome.storage.local.get(keys, items => { if (chrome.runtime.lastError) { reject(new Error(chrome.runtime.lastError.message)); } else { resolve(items); } }); }); }, set(items: Record<string, unknown>): Promise<void> { return new Promise<void>((resolve, reject) => { chrome.storage.local.set(items, () => { if (chrome.runtime.lastError) { reject(new Error(chrome.runtime.lastError.message)); } else { resolve(); } }); }); }, }; } export namespace tabs { export type Tab = chrome.tabs.Tab; export type _CreateCreateProperties = chrome.tabs.CreateProperties; export type _QueryQueryInfo = chrome.tabs.QueryInfo; export type _UpdateUpdateProperties = chrome.tabs.UpdateProperties; export type _OnRemovedRemoveInfo = chrome.tabs.TabRemoveInfo; export type _OnUpdatedChangeInfo = chrome.tabs.TabChangeInfo; export function create(createProperties: _CreateCreateProperties): Promise<Tab> { return new Promise<Tab>((resolve, reject) => { chrome.tabs.create(createProperties, tab => { if (chrome.runtime.lastError) { reject(new Error(chrome.runtime.lastError.message)); } else { resolve(tab); } }); }); } export function executeScript( tabId: number, details: extensionTypes.InjectDetails, ): Promise<unknown[]> { return new Promise<unknown[]>((resolve, reject) => { chrome.tabs.executeScript(tabId, details, result => { if (chrome.runtime.lastError) { reject(new Error(chrome.runtime.lastError.message)); } else { resolve(result); } }); }); } export function get(tabId: number): Promise<Tab> { return new Promise<Tab>((resolve, reject) => { chrome.tabs.get(tabId, tab => { if (chrome.runtime.lastError) { reject(new Error(chrome.runtime.lastError.message)); } else { resolve(tab); } }); }); } export function insertCSS(tabId: number, details: extensionTypes.InjectDetails): Promise<void> { return new Promise<void>((resolve, reject) => { chrome.tabs.insertCSS(tabId, details, () => { if (chrome.runtime.lastError) { reject(new Error(chrome.runtime.lastError.message)); } else { resolve(); } }); }); } export function query(queryInfo: _QueryQueryInfo): Promise<Tab[]> { return new Promise<Tab[]>((resolve, reject) => { chrome.tabs.query(queryInfo, result => { if (chrome.runtime.lastError) { reject(new Error(chrome.runtime.lastError.message)); } else { resolve(result); } }); }); } export function remove(tabIds: number | number[]): Promise<void> { return new Promise<void>((resolve, reject) => { chrome.tabs.remove(tabIds as number, () => { if (chrome.runtime.lastError) { reject(new Error(chrome.runtime.lastError.message)); } else { resolve(); } }); }); } export function update(tabId: number, updateProperties: _UpdateUpdateProperties): Promise<Tab> { return new Promise<Tab>((resolve, reject) => { chrome.tabs.update(tabId, updateProperties, tab => { if (chrome.runtime.lastError) { reject(new Error(chrome.runtime.lastError.message)); } else { // eslint-disable-next-line @typescript-eslint/no-non-null-assertion resolve(tab!); } }); }); } export const onRemoved = { addListener(callback: (tabId: number, removeInfo: _OnRemovedRemoveInfo) => void): void { chrome.tabs.onRemoved.addListener(callback); }, removeListener(callback: (tabId: number, removeInfo: _OnRemovedRemoveInfo) => void): void { chrome.tabs.onRemoved.removeListener(callback); }, }; export const onUpdated = { addListener( callback: (tabId: number, changeInfo: _OnUpdatedChangeInfo, tab: Tab) => void, ): void { chrome.tabs.onUpdated.addListener(callback); }, removeListener( callback: (tabId: number, changeInfo: _OnUpdatedChangeInfo, tab: Tab) => void, ): void { chrome.tabs.onUpdated.removeListener(callback); }, }; } export namespace windows { export const WINDOW_ID_NONE = -1; // chrome.windows.WINDOW_ID_NONE export const onFocusChanged = { addListener(callback: (windowId: number) => void): void { chrome.windows.onFocusChanged.addListener(callback); }, }; } } /* #else export import apis = browser; */ // #endif
the_stack
import { Component, OnDestroy, OnInit, ViewChild, ViewEncapsulation } from '@angular/core'; import { HttpErrorResponse, HttpResponse } from '@angular/common/http'; import { Subscription } from 'rxjs'; import { ActivatedRoute, Router } from '@angular/router'; import { Observable, of, Subject } from 'rxjs'; import { User } from 'app/core/user/user.model'; import { ActionType } from 'app/shared/delete-dialog/delete-dialog.model'; import { catchError, map, switchMap, tap } from 'rxjs/operators'; import { UserService } from 'app/core/user/user.service'; import { DataTableComponent } from 'app/shared/data-table/data-table.component'; import { iconsAsHTML } from 'app/utils/icons.utils'; import { Exam } from 'app/entities/exam.model'; import { ExamManagementService } from 'app/exam/manage/exam-management.service'; import { ButtonSize, ButtonType } from 'app/shared/components/button.component'; import { AccountService } from 'app/core/auth/account.service'; import { AlertService } from 'app/core/util/alert.service'; import { EventManager } from 'app/core/util/event-manager.service'; const cssClasses = { alreadyRegistered: 'already-registered', newlyRegistered: 'newly-registered', }; @Component({ selector: 'jhi-exam-students', templateUrl: './exam-students.component.html', styleUrls: ['./exam-students.component.scss'], encapsulation: ViewEncapsulation.None, }) export class ExamStudentsComponent implements OnInit, OnDestroy { @ViewChild(DataTableComponent) dataTable: DataTableComponent; readonly ButtonType = ButtonType; readonly ButtonSize = ButtonSize; readonly ActionType = ActionType; courseId: number; exam: Exam; allRegisteredUsers: User[] = []; filteredUsersSize = 0; paramSub: Subscription; private dialogErrorSource = new Subject<string>(); dialogError$ = this.dialogErrorSource.asObservable(); isLoading = false; isSearching = false; searchFailed = false; searchNoResults = false; isTransitioning = false; rowClass: string | undefined = undefined; isAdmin = false; constructor( private router: Router, private route: ActivatedRoute, private alertService: AlertService, private eventManager: EventManager, private examManagementService: ExamManagementService, private userService: UserService, private accountService: AccountService, ) {} ngOnInit() { this.isLoading = true; this.courseId = Number(this.route.snapshot.paramMap.get('courseId')); this.isAdmin = this.accountService.isAdmin(); this.route.data.subscribe(({ exam }: { exam: Exam }) => { this.exam = exam; this.allRegisteredUsers = exam.registeredUsers! || []; this.isLoading = false; }); } reloadExamWithRegisteredUsers() { this.isLoading = true; this.examManagementService.find(this.courseId, this.exam.id!, true).subscribe((examResponse: HttpResponse<Exam>) => { this.exam = examResponse.body!; this.allRegisteredUsers = this.exam.registeredUsers! || []; this.isLoading = false; }); } ngOnDestroy() { this.dialogErrorSource.unsubscribe(); } /** * Receives the search text and filter results from DataTableComponent, modifies them and returns the result which will be used by ngbTypeahead. * * @param stream$ stream of searches of the format {text, entities} where entities are the results * @return stream of users for the autocomplete */ searchAllUsers = (stream$: Observable<{ text: string; entities: User[] }>): Observable<User[]> => { return stream$.pipe( switchMap(({ text: loginOrName }) => { this.searchFailed = false; this.searchNoResults = false; if (loginOrName.length < 3) { return of([]); } this.isSearching = true; return this.userService .search(loginOrName) .pipe(map((usersResponse) => usersResponse.body!)) .pipe( tap((users) => { if (users.length === 0) { this.searchNoResults = true; } }), catchError(() => { this.searchFailed = true; return of([]); }), ); }), tap(() => { this.isSearching = false; }), tap((users) => { setTimeout(() => { for (let i = 0; i < this.dataTable.typeaheadButtons.length; i++) { const isAlreadyInCourseGroup = this.allRegisteredUsers.map((user) => user.id).includes(users[i].id); this.dataTable.typeaheadButtons[i].insertAdjacentHTML('beforeend', iconsAsHTML[isAlreadyInCourseGroup ? 'users' : 'users-plus']); if (isAlreadyInCourseGroup) { this.dataTable.typeaheadButtons[i].classList.add(cssClasses.alreadyRegistered); } } }); }), ); }; /** * Receives the user that was selected in the autocomplete and the callback from DataTableComponent. * The callback inserts the search term of the selected entity into the search field and updates the displayed users. * * @param user The selected user from the autocomplete suggestions * @param callback Function that can be called with the selected user to trigger the DataTableComponent default behavior */ onAutocompleteSelect = (user: User, callback: (user: User) => void): void => { // If the user is not registered for this exam yet, perform the server call to add them if (!this.allRegisteredUsers.map((u) => u.id).includes(user.id) && user.login) { this.isTransitioning = true; this.examManagementService.addStudentToExam(this.courseId, this.exam.id!, user.login).subscribe( (student) => { this.isTransitioning = false; // make sure the registration number is set in the user object user.visibleRegistrationNumber = student.body!.registrationNumber; // Add newly registered user to the list of all registered users for the exam this.allRegisteredUsers.push(user); // Hand back over to the data table for updating callback(user); // Flash green background color to signal to the user that this student was registered this.flashRowClass(cssClasses.newlyRegistered); }, (error: HttpErrorResponse) => { this.onError(`artemisApp.exam.${error.headers.get('x-null-error')}`); }, ); } else { // Hand back over to the data table callback(user); } }; /** * Unregister student from exam * * @param user User that should be removed from the exam * @param event generated by the jhiDeleteButton. Has the property deleteParticipationsAndSubmission, reflecting the checkbox choice of the user */ removeFromExam(user: User, event: { [key: string]: boolean }) { this.examManagementService.removeStudentFromExam(this.courseId, this.exam.id!, user.login!, event.deleteParticipationsAndSubmission).subscribe( () => { this.allRegisteredUsers = this.allRegisteredUsers.filter((u) => u.login !== user.login); this.dialogErrorSource.next(''); }, (error: HttpErrorResponse) => this.dialogErrorSource.next(error.message), ); } /** * Unregister all students from the exam */ removeAllStudents(event: { [key: string]: boolean }) { this.examManagementService.removeAllStudentsFromExam(this.courseId, this.exam.id!, event.deleteParticipationsAndSubmission).subscribe( () => { this.allRegisteredUsers = []; this.dialogErrorSource.next(''); }, (error: HttpErrorResponse) => this.dialogErrorSource.next(error.message), ); } /** * Update the number of filtered users * * @param filteredUsersSize Total number of users after filters have been applied */ handleUsersSizeChange = (filteredUsersSize: number) => { this.filteredUsersSize = filteredUsersSize; }; /** * Formats the results in the autocomplete overlay. * * @param user */ searchResultFormatter = (user: User) => { const { name, login } = user; return `${name} (${login})`; }; /** * Converts a user object to a string that can be searched for. This is * used by the autocomplete select inside the data table. * * @param user User */ searchTextFromUser = (user: User): string => { return user.login || ''; }; /** * Computes the row class that is being added to all rows of the datatable */ dataTableRowClass = () => { return this.rowClass; }; /** * Can be used to highlight rows temporarily by flashing a certain css class * * @param className Name of the class to be applied to all rows */ flashRowClass = (className: string) => { this.rowClass = className; setTimeout(() => (this.rowClass = undefined)); }; /** * Show an error as an alert in the top of the editor html. * Used by other components to display errors. * The error must already be provided translated by the emitting component. */ onError(error: string) { this.alertService.error(error); this.isTransitioning = false; } /** * Registers all students who are enrolled in the course for the exam */ registerAllStudentsFromCourse() { if (this.exam?.id) { this.examManagementService.addAllStudentsOfCourseToExam(this.courseId, this.exam.id).subscribe( () => { this.reloadExamWithRegisteredUsers(); }, (error: HttpErrorResponse) => this.dialogErrorSource.next(error.message), ); } } }
the_stack
import assert from "assert" import { Event, EventTarget } from "../src/index" import { Global } from "../src/lib/global" import { FalsyWasAssignedToCancelBubble, InitEventWasCalledWhileDispatching, NonCancelableEventWasCanceled, TruthyWasAssignedToReturnValue, } from "../src/lib/warnings" import { setupErrorCheck } from "./lib/setup-error-check" const NativeEvent: typeof Event = Global.Event describe("'Event' class", () => { const { assertWarning } = setupErrorCheck() describe("constructor", () => { it("should return an Event object", () => { assert(new Event("") instanceof Event) }) it("should throw a TypeError if called as a function", () => { assert.throws(() => { // @ts-expect-error Event("") // eslint-disable-line new-cap }) }) const nativeDescribe = NativeEvent ? describe : xdescribe nativeDescribe("if native Event class is present", () => { it("`event instanceof window.Event` should be true", () => { const event = new Event("") assert(event instanceof NativeEvent) }) }) }) describe("'type' property", () => { it("should be the value of the constructor's first argument", () => { const event = new Event("foo") assert.strictEqual(event.type, "foo") }) it("should be the string representation of the constructor's first argument", () => { // @ts-expect-error assert.strictEqual(new Event().type, "undefined") // @ts-expect-error assert.strictEqual(new Event(null).type, "null") // @ts-expect-error assert.strictEqual(new Event(1e3).type, "1000") }) it("should be readonly", () => { const event = new Event("foo") assert.throws(() => { // @ts-expect-error event.type = "bar" }) }) }) describe("'target' property", () => { it("should be null", () => { const event = new Event("foo") assert.strictEqual(event.target, null) }) it("should be readonly", () => { const event = new Event("foo") assert.throws(() => { // @ts-expect-error event.target = null }) }) it("should be the event target under dispatching", () => { const target = new EventTarget() const event = new Event("foo") let ok = false target.addEventListener("foo", () => { assert.strictEqual(event.target, target) ok = true }) target.dispatchEvent(event) assert.strictEqual(event.target, null) assert(ok) }) }) describe("'srcElement' property", () => { it("should be null", () => { const event = new Event("foo") assert.strictEqual(event.srcElement, null) }) it("should be readonly", () => { const event = new Event("foo") assert.throws(() => { // @ts-expect-error event.srcElement = null }) }) it("should be the event target under dispatching", () => { const target = new EventTarget() const event = new Event("foo") let ok = false target.addEventListener("foo", () => { assert.strictEqual(event.srcElement, target) ok = true }) target.dispatchEvent(event) assert.strictEqual(event.srcElement, null) assert(ok) }) }) describe("'currentTarget' property", () => { it("should be null", () => { const event = new Event("foo") assert.strictEqual(event.currentTarget, null) }) it("should be readonly", () => { const event = new Event("foo") assert.throws(() => { // @ts-expect-error event.currentTarget = null }) }) it("should be the event target under dispatching", () => { const target = new EventTarget() const event = new Event("foo") let ok = false target.addEventListener("foo", () => { assert.strictEqual(event.currentTarget, target) ok = true }) target.dispatchEvent(event) assert.strictEqual(event.currentTarget, null) assert(ok) }) }) describe("'composedPath' method", () => { it("should return an empty array", () => { const event = new Event("foo") assert.deepStrictEqual(event.composedPath(), []) }) it("should return the event target under dispatching", () => { const target = new EventTarget() const event = new Event("foo") let ok = false target.addEventListener("foo", () => { assert.deepStrictEqual(event.composedPath(), [target]) ok = true }) target.dispatchEvent(event) assert.deepStrictEqual(event.composedPath(), []) assert(ok) }) }) describe("'NONE' property", () => { it("should be 0", () => { const event = new Event("foo") assert.strictEqual(event.NONE, 0) }) it("should be readonly", () => { const event = new Event("foo") assert.throws(() => { // @ts-expect-error event.NONE = -1 }) }) }) describe("'NONE' static property", () => { it("should be 0", () => { assert.strictEqual(Event.NONE, 0) }) it("should be readonly", () => { assert.throws(() => { // @ts-expect-error Event.NONE = -1 }) }) }) describe("'CAPTURING_PHASE' property", () => { it("should be 1", () => { const event = new Event("foo") assert.strictEqual(event.CAPTURING_PHASE, 1) }) it("should be readonly", () => { const event = new Event("foo") assert.throws(() => { // @ts-expect-error event.CAPTURING_PHASE = -1 }) }) }) describe("'CAPTURING_PHASE' static property", () => { it("should be 1", () => { assert.strictEqual(Event.CAPTURING_PHASE, 1) }) it("should be readonly", () => { assert.throws(() => { // @ts-expect-error Event.CAPTURING_PHASE = -1 }) }) }) describe("'AT_TARGET' property", () => { it("should be 2", () => { const event = new Event("foo") assert.strictEqual(event.AT_TARGET, 2) }) it("should be readonly", () => { const event = new Event("foo") assert.throws(() => { // @ts-expect-error event.AT_TARGET = -1 }) }) }) describe("'AT_TARGET' static property", () => { it("should be 2", () => { assert.strictEqual(Event.AT_TARGET, 2) }) it("should be readonly", () => { assert.throws(() => { // @ts-expect-error Event.AT_TARGET = -1 }) }) }) describe("'BUBBLING_PHASE' property", () => { it("should be 3", () => { const event = new Event("foo") assert.strictEqual(event.BUBBLING_PHASE, 3) }) it("should be readonly", () => { const event = new Event("foo") assert.throws(() => { // @ts-expect-error event.BUBBLING_PHASE = -1 }) }) }) describe("'BUBBLING_PHASE' static property", () => { it("should be 3", () => { assert.strictEqual(Event.BUBBLING_PHASE, 3) }) it("should be readonly", () => { assert.throws(() => { // @ts-expect-error Event.BUBBLING_PHASE = -1 }) }) }) describe("'eventPhase' property", () => { it("should be 0", () => { const event = new Event("foo") assert.strictEqual(event.eventPhase, 0) }) it("should be readonly", () => { const event = new Event("foo") assert.throws(() => { // @ts-expect-error event.eventPhase = -1 }) }) it("should be 2 under dispatching", () => { const target = new EventTarget() const event = new Event("foo") let ok = false target.addEventListener("foo", () => { assert.strictEqual(event.eventPhase, 2) ok = true }) target.dispatchEvent(event) assert.strictEqual(event.eventPhase, 0) assert(ok) }) }) describe("'stopPropagation' method", () => { it("should return undefined", () => { const event = new Event("foo") assert.strictEqual(event.stopPropagation(), undefined) }) }) describe("'cancelBubble' property", () => { it("should be false", () => { const event = new Event("foo") assert.strictEqual(event.cancelBubble, false) }) it("should be true after 'stopPropagation' method was called", () => { const event = new Event("foo") event.stopPropagation() assert.strictEqual(event.cancelBubble, true) }) it("should be true after 'stopImmediatePropagation' method was called", () => { const event = new Event("foo") event.stopImmediatePropagation() assert.strictEqual(event.cancelBubble, true) }) it("should be writable", () => { const event = new Event("foo") event.cancelBubble = true assert.strictEqual(event.cancelBubble, true) }) it("should NOT be changed by the assignment of false after 'stopPropagation' method was called", () => { const event = new Event("foo") event.stopPropagation() event.cancelBubble = false assert.strictEqual(event.cancelBubble, true) assertWarning(FalsyWasAssignedToCancelBubble) }) it("should NOT be changed by the assignment of false after 'stopImmediatePropagation' method was called", () => { const event = new Event("foo") event.stopImmediatePropagation() event.cancelBubble = false assert.strictEqual(event.cancelBubble, true) assertWarning(FalsyWasAssignedToCancelBubble) }) it("should NOT be changed by the assignment of false after the assignment of true", () => { const event = new Event("foo") event.cancelBubble = true event.cancelBubble = false assert.strictEqual(event.cancelBubble, true) assertWarning(FalsyWasAssignedToCancelBubble) }) }) describe("'stopImmediatePropagation' method", () => { it("should return undefined", () => { const event = new Event("foo") assert.strictEqual(event.stopImmediatePropagation(), undefined) }) }) describe("'bubbles' property", () => { it("should be false if the constructor option was not present", () => { const event = new Event("foo") assert.strictEqual(event.bubbles, false) }) it("should be false if the constructor option was false", () => { const event = new Event("foo", { bubbles: false }) assert.strictEqual(event.bubbles, false) }) it("should be true if the constructor option was true", () => { const event = new Event("foo", { bubbles: true }) assert.strictEqual(event.bubbles, true) }) it("should be readonly", () => { const event = new Event("foo") assert.throws(() => { // @ts-expect-error event.bubbles = true }) }) }) describe("'cancelable' property", () => { it("should be false if the constructor option was not present", () => { const event = new Event("foo") assert.strictEqual(event.cancelable, false) }) it("should be false if the constructor option was false", () => { const event = new Event("foo", { cancelable: false }) assert.strictEqual(event.cancelable, false) }) it("should be true if the constructor option was true", () => { const event = new Event("foo", { cancelable: true }) assert.strictEqual(event.cancelable, true) }) it("should be readonly", () => { const event = new Event("foo") assert.throws(() => { // @ts-expect-error event.cancelable = true }) }) }) describe("'returnValue' property", () => { it("should be true", () => { const event = new Event("foo") assert.strictEqual(event.returnValue, true) }) it("should be true after 'preventDefault' method was called if 'cancelable' is false", () => { const event = new Event("foo") event.preventDefault() assert.strictEqual(event.returnValue, true) assertWarning(NonCancelableEventWasCanceled) }) it("should be false after 'preventDefault' method was called if 'cancelable' is true", () => { const event = new Event("foo", { cancelable: true }) event.preventDefault() assert.strictEqual(event.returnValue, false) }) it("should NOT be changed by assignment if 'cancelable' is false", () => { const event = new Event("foo") event.returnValue = false assert.strictEqual(event.returnValue, true) assertWarning(NonCancelableEventWasCanceled) }) it("should be changed by assignment if 'cancelable' is true", () => { const event = new Event("foo", { cancelable: true }) event.returnValue = false assert.strictEqual(event.returnValue, false) }) it("should NOT be changed by the assignment of true after 'preventDefault' method was called", () => { const event = new Event("foo", { cancelable: true }) event.preventDefault() event.returnValue = true assert.strictEqual(event.returnValue, false) assertWarning(TruthyWasAssignedToReturnValue) }) it("should NOT be changed by the assignment of true after the assginment of false", () => { const event = new Event("foo", { cancelable: true }) event.returnValue = false event.returnValue = true assert.strictEqual(event.returnValue, false) assertWarning(TruthyWasAssignedToReturnValue) }) }) describe("'preventDefault' method", () => { it("should return undefined", () => { const event = new Event("foo", { cancelable: true }) assert.strictEqual(event.preventDefault(), undefined) }) it("should return undefined", () => { const event = new Event("foo") assert.strictEqual(event.preventDefault(), undefined) assertWarning(NonCancelableEventWasCanceled) }) }) describe("'defaultPrevented' property", () => { it("should be false", () => { const event = new Event("foo") assert.strictEqual(event.defaultPrevented, false) }) it("should be false after 'preventDefault' method was called if 'cancelable' is false", () => { const event = new Event("foo") event.preventDefault() assert.strictEqual(event.defaultPrevented, false) assertWarning(NonCancelableEventWasCanceled) }) it("should be false after 'preventDefault' method was called if 'cancelable' is true", () => { const event = new Event("foo", { cancelable: true }) event.preventDefault() assert.strictEqual(event.defaultPrevented, true) }) it("should be readonly", () => { const event = new Event("foo") assert.throws(() => { // @ts-expect-error event.defaultPrevented = true }) }) }) describe("'composed' property", () => { it("should be false if the constructor option was not present", () => { const event = new Event("foo") assert.strictEqual(event.composed, false) }) it("should be false if the constructor option was false", () => { const event = new Event("foo", { composed: false }) assert.strictEqual(event.composed, false) }) it("should be true if the constructor option was true", () => { const event = new Event("foo", { composed: true }) assert.strictEqual(event.composed, true) }) it("should be readonly", () => { const event = new Event("foo") assert.throws(() => { // @ts-expect-error event.composed = true }) }) }) describe("'isTrusted' property", () => { it("should be false", () => { const event = new Event("foo") assert.strictEqual(event.isTrusted, false) }) it("should be readonly", () => { const event = new Event("foo") assert.throws(() => { // @ts-expect-error event.isTrusted = true }) }) it("should NOT be configurable", () => { const event = new Event("foo") assert.throws(() => { Object.defineProperty(event, "isTrusted", { value: true }) }) }) it("should NOT be overridable", () => { class CustomEvent extends Event { // eslint-disable-next-line class-methods-use-this public get isTrusted(): boolean { return true } } const event = new CustomEvent("foo") assert.strictEqual(event.isTrusted, false) }) }) describe("'timeStamp' property", () => { it("should be a number", () => { const event = new Event("foo") assert.strictEqual(typeof event.timeStamp, "number") }) it("should be readonly", () => { const event = new Event("foo") assert.throws(() => { // @ts-expect-error event.timeStamp = 0 }) }) }) describe("'initEvent' method", () => { it("should return undefined", () => { const event = new Event("foo") assert.strictEqual(event.initEvent("bar"), undefined) }) it("should set type", () => { const event = new Event("foo") event.initEvent("bar") assert.strictEqual(event.type, "bar") }) it("should set type (string representation)", () => { const event = new Event("foo") // @ts-expect-error event.initEvent(1e3) assert.strictEqual(event.type, "1000") }) it("should set bubbles", () => { const event = new Event("foo") event.initEvent("foo", true) assert.strictEqual(event.bubbles, true) assert.strictEqual(event.cancelable, false) assert.strictEqual(event.composed, false) }) it("should set cancelable", () => { const event = new Event("foo", { bubbles: true }) event.initEvent("foo", undefined, true) assert.strictEqual(event.bubbles, false) assert.strictEqual(event.cancelable, true) assert.strictEqual(event.composed, false) }) it("should not change composed", () => { const event = new Event("foo", { bubbles: true, cancelable: true, composed: true, }) event.initEvent("foo") assert.strictEqual(event.bubbles, false) assert.strictEqual(event.cancelable, false) assert.strictEqual(event.composed, true) }) it("should reset 'stopPropagation' flag", () => { const event = new Event("foo") event.stopPropagation() assert.strictEqual(event.cancelBubble, true) event.initEvent("foo") assert.strictEqual(event.cancelBubble, false) }) it("should reset 'canceled' flag", () => { const event = new Event("foo", { cancelable: true }) event.preventDefault() assert.strictEqual(event.defaultPrevented, true) event.initEvent("foo") assert.strictEqual(event.defaultPrevented, false) }) it("should do nothing under dispatching", () => { const target = new EventTarget() const event = new Event("foo") target.addEventListener("foo", () => { event.initEvent("bar") }) target.dispatchEvent(event) assert.strictEqual(event.type, "foo") assertWarning(InitEventWasCalledWhileDispatching) }) }) describe("for-in", () => { it("should enumerate 22 property names", () => { const event = new Event("foo") const actualKeys = new Set<string>() // eslint-disable-next-line @mysticatea/prefer-for-of for (const key in event) { actualKeys.add(key) } for (const expectedKey of [ "type", "target", "srcElement", "currentTarget", "composedPath", "NONE", "CAPTURING_PHASE", "AT_TARGET", "BUBBLING_PHASE", "eventPhase", "stopPropagation", "cancelBubble", "stopImmediatePropagation", "bubbles", "cancelable", "returnValue", "preventDefault", "defaultPrevented", "composed", "isTrusted", "timeStamp", "initEvent", ]) { assert( actualKeys.has(expectedKey), `for-in loop should iterate '${expectedKey}' key`, ) } }) it("should enumerate 4 property names in static", () => { const actualKeys = [] const expectedKeys = [ "AT_TARGET", "BUBBLING_PHASE", "CAPTURING_PHASE", "NONE", ] // eslint-disable-next-line @mysticatea/prefer-for-of for (const key in Event) { actualKeys.push(key) } assert.deepStrictEqual( actualKeys.sort(undefined), expectedKeys.sort(undefined), ) }) }) })
the_stack
import App from "../app"; import {gql, withFilter} from "apollo-server-express"; import {pubsub} from "../helpers/subscriptionManager"; import uuid from "uuid"; const mutationHelper = require("../helpers/mutationHelper").default; // We define a schema that encompasses all of the types // necessary for the functionality in this file. const schema = gql` type ProcessedData { value: String! time: String! } type Sensors implements SystemInterface { id: ID! simulatorId: ID type: String name: String displayName: String upgradeName: String upgraded: Boolean stealthFactor: Float domain: String! pings: Boolean timeSincePing: Int pingMode: PING_MODES scanResults: String scanRequest: String processedData: [ProcessedData!] presetAnswers: [PresetAnswer] scanning: Boolean power: Power contacts: [SensorContact] armyContacts: [SensorContact] damage: Damage scans: [SensorScan] history: Boolean autoTarget: Boolean frozen: Boolean autoThrusters: Boolean interference: Float movement: Coordinates segments: [SensorsSegment] locations: [Room] defaultHitpoints: Int defaultSpeed: Float missPercent: Float } type SensorScan { id: ID! timestamp: String mode: String location: String request: String response: String scanning: Boolean cancelled: Boolean } input SensorScanInput { id: ID timestamp: String mode: String location: String request: String response: String scanning: Boolean cancelled: Boolean } type SensorContact { id: ID! name: String type: String size: Float icon: String picture: String color: String rotation: Float speed: Float location: Coordinates destination: Coordinates position: Coordinates startTime: Float endTime: Float movementTime: Int infrared: Boolean cloaked: Boolean destroyed: Boolean forceUpdate: Boolean targeted: Boolean selected: Boolean locked: Boolean disabled: Boolean hostile: Boolean hitpoints: Int autoFire: Boolean particle: ParticleTypes } enum ParticleTypes { Dilithium Tachyon Neutrino AntiMatter Anomaly #Also use this for Science Probe bursts Resonance Graviton Lithium Magnetic Helium Hydrogen Oxygen Carbon Radiation } type SensorsSegment { ring: Int line: Int state: Boolean } type PresetAnswer { label: String! value: String! } input PresetAnswerInput { label: String value: String } input SensorContactInput { sensorId: ID id: ID name: String type: String size: Float icon: String picture: String color: String speed: Float rotation: Float location: CoordinatesInput destination: CoordinatesInput infrared: Boolean cloaked: Boolean destroyed: Boolean locked: Boolean disabled: Boolean hostile: Boolean hitpoints: Int autoFire: Boolean particle: ParticleTypes } enum PING_MODES { active passive manual } extend type Query { sensors(simulatorId: ID, domain: String): [Sensors!]! sensor(id: ID!): Sensors sensorContacts( simulatorId: ID sensorsId: ID hostile: Boolean type: String ): [SensorContact] } extend type Mutation { sensorScanRequest(id: ID!, request: String!): String """ Macro: Sensors: Send Scan Result Requires: - Cards:SecurityScans, SensorScans, Sensors, JrSensors - Systems:Sensors """ sensorScanResult(id: ID!, domain: String, result: String!): String """ Macro: Sensors: Processed Data Requires: - Cards:Sensors, JrSensors - Systems:Sensors """ processedData( id: ID simulatorId: ID domain: String data: String! flash: Boolean ): String removeProcessedData( id: ID simulatorId: ID domain: String time: String! ): String sensorScanCancel(id: ID!): String """ Macro: Sensors: Scan Answers Requires: - Cards:SecurityScans, SensorScans, Sensors, JrSensors - Systems:Sensors """ setPresetAnswers( simulatorId: ID! domain: String! presetAnswers: [PresetAnswerInput]! ): String # Sensor Contacts createSensorContact(id: ID!, contact: SensorContactInput!): String createSensorContacts(id: ID!, contacts: [SensorContactInput!]!): String moveSensorContact(id: ID!, contact: SensorContactInput!): String removeSensorContact(id: ID!, contact: SensorContactInput!): String removeAllSensorContacts(id: ID!, type: [String]): String stopAllSensorContacts(id: ID!): String updateSensorContact( id: ID simulatorId: ID contact: SensorContactInput! ): String """ Macro: Sensors: Set Army Sensor Contacts Requires: - Cards:Sensors, JrSensors - Systems:Sensors """ setArmyContacts( simulatorId: ID! domain: String! armyContacts: [SensorContactInput]! ): String createSensorArmyContact(id: ID!, contact: SensorContactInput!): String removeSensorArmyContact(id: ID!, contact: ID!): String updateSensorArmyContact(id: ID!, contact: SensorContactInput!): String nudgeSensorContacts( id: ID! amount: CoordinatesInput speed: Float! yaw: Float ): String sensorsSetHasPing(id: ID!, ping: Boolean!): String setSensorPingMode(id: ID!, mode: PING_MODES): String pingSensors(id: ID!): String animateSensorContacact: String setSensorsHistory(id: ID!, history: Boolean!): String # For scan history newSensorScan(id: ID!, scan: SensorScanInput!): String # For scan history updateSensorScan(id: ID!, scan: SensorScanInput!): String # For scan history cancelSensorScan(id: ID!, scan: ID!): String toggleSensorsAutoTarget(id: ID!, target: Boolean!): String toggleSensorsAutoThrusters(id: ID!, thrusters: Boolean!): String setSensorsInterference(id: ID!, interference: Float!): String setSensorsSegment(id: ID!, ring: Int!, line: Int!, state: Boolean!): String setAutoMovement(id: ID!, movement: CoordinatesInput!): String updateSensorContacts(id: ID!, contacts: [SensorContactInput]!): String """ Macro: Sensors: Update Sensor Grid Requires: - Cards:Sensors, JrSensors - Systems:Sensors """ updateSensorGrid(simulatorId: ID!, contacts: [SensorContactInput]!): String destroySensorContact(id: ID!, contact: ID, contacts: [ID]): String sensorsFireProjectile( simulatorId: ID! contactId: ID! speed: Float! hitpoints: Int! miss: Boolean ): String setSensorsDefaultHitpoints(id: ID, simulatorId: ID, hp: Int!): String setSensorsDefaultSpeed(id: ID, simulatorId: ID, speed: Float!): String setSensorsMissPercent(id: ID!, miss: Float!): String } extend type Subscription { sensorsUpdate(simulatorId: ID, domain: String): [Sensors!]! sensorContactUpdate( simulatorId: ID sensorId: ID hostile: Boolean type: String ): [SensorContact!]! sensorsPing(sensorId: ID): String } `; const resolver = { Sensors: { locations(rootValue) { return rootValue.locations.map(r => App.rooms.find(room => room.id === r), ); }, interference(rootValue) { const signalJammer = App.systems.find( s => s.simulatorId === rootValue.simulatorId && s.class === "SignalJammer", ); if ( !signalJammer || !signalJammer.addsSensorsInterference || !signalJammer.active ) { return rootValue.interference; } return Math.max(signalJammer.strength / 3 + 0.05, rootValue.interference); }, movement(rootValue) { return { x: rootValue.movement.x + rootValue.thrusterMovement.x, y: rootValue.movement.y + rootValue.thrusterMovement.y, z: rootValue.movement.z + rootValue.thrusterMovement.z, }; }, }, SensorContact: { /*startTime() { return 0; }, endTime() { return 0; },*/ movementTime({startTime, endTime}) { return endTime - startTime; }, targeted({id, sensorId}) { const sensor = App.systems.find(s => s.id === sensorId); const targeting = App.systems.find( s => s.simulatorId === sensor.simulatorId && s.class === "Targeting", ); const targetedContact = targeting.contacts.find(t => t.targeted === true); if (targetedContact && targetedContact.class === id) return true; return false; }, selected({id, sensorId}) { const sensor = App.systems.find(s => s.id === sensorId); const targeting = App.systems.find( s => s.simulatorId === sensor.simulatorId && s.class === "Targeting", ); return id === targeting.targetedSensorContact; }, }, Query: { sensors(root, {simulatorId, domain}) { let returnVal = App.systems.filter(s => s.type === "Sensors"); if (domain) { returnVal = returnVal.filter(s => s.domain === domain); } if (simulatorId) { returnVal = returnVal.filter(s => s.simulatorId === simulatorId); } return returnVal; }, sensor(root, {id}) { return App.systems.find(s => s.id === id); }, sensorContacts(root, {simulatorId, sensorsId, hostile, type}) { let contacts = []; if (sensorsId) { const sensors = App.systems.find(system => { return system.type === "Sensors" && system.id === sensorsId; }); contacts = sensors ? sensors.contacts : []; } if (simulatorId) { const sensors = App.systems.filter(system => { return ( system.type === "Sensors" && system.simulatorId === simulatorId ); }); contacts = sensors.reduce( (prev, next) => prev.concat(next.contacts), [], ); } if (hostile || hostile === false) contacts = contacts.filter(c => c.hostile === hostile); if (type) { contacts = contacts.filter(c => c.type === type); } return contacts; }, }, Mutation: mutationHelper(schema), Subscription: { sensorsUpdate: { resolve(root, {simulatorId, domain}) { let returnRes = root; if (simulatorId) returnRes = returnRes.filter(s => s.simulatorId === simulatorId); if (domain) returnRes = returnRes.filter(s => s.domain === domain); return returnRes; }, subscribe: withFilter( (rootValue, {simulatorId, domain}) => { const id = uuid.v4(); process.nextTick(() => { let returnVal = App.systems.filter(s => s.class === "Sensors"); if (simulatorId) returnVal = returnVal.filter(s => s.simulatorId === simulatorId); if (domain) returnVal = returnVal.filter(s => s.domain === domain); pubsub.publish(id, returnVal); }); return pubsub.asyncIterator([id, "sensorsUpdate"]); }, rootValue => !!(rootValue && rootValue.length), ), }, sensorContactUpdate: { resolve(root, {simulatorId, sensorId, hostile, type}) { if (root.id !== sensorId && root.simulatorId !== simulatorId) return null; let contacts = root.contacts; if (hostile || hostile === false) contacts = root.contacts.filter(c => c.hostile === hostile); if (type) { contacts = contacts.filter(c => c.type === type); } return contacts; }, subscribe: withFilter( () => pubsub.asyncIterator("sensorContactUpdate"), (rootValue, {simulatorId, sensorId}) => { let returnVal = false; if (sensorId) returnVal = rootValue.id === sensorId; if (simulatorId) returnVal = rootValue.simulatorId === simulatorId; return returnVal; }, ), }, sensorsPing: { resolve(root, args) { return root; }, subscribe: withFilter( () => pubsub.asyncIterator("sensorsPing"), (rootValue, {sensorId}) => { if (rootValue !== sensorId) return false; return true; }, ), }, }, }; export default {schema, resolver};
the_stack
import React from 'react' import { gql, useQuery } from '@apollo/client' import DatasetQueryContext from '../../datalad/dataset/dataset-query-context.js' import Markdown from 'markdown-to-jsx' import { Link, useLocation } from 'react-router-dom' import pluralize from 'pluralize' import formatDistanceToNow from 'date-fns/formatDistanceToNow' import parseISO from 'date-fns/parseISO' import Files from './files' import Validation from '../validation/validation.jsx' import { config } from '../../config' import Comments from './comments/comments.jsx' import DatasetCitation from './fragments/dataset-citation.jsx' import { ModalitiesMetaDataBlock, MetaDataBlock, BrainLifeButton, ValidationBlock, CloneDropdown, DatasetHeader, DatasetHeaderMeta, DatasetPage, DatasetGitAccess, VersionList, DatasetTools, } from '@openneuro/components/dataset' import { Loading } from '@openneuro/components/loading' import { getUnexpiredProfile, hasEditPermissions, } from '../authentication/profile' import { useCookies } from 'react-cookie' import { Modal } from '@openneuro/components/modal' import { ReadMore } from '@openneuro/components/read-more' import { FollowDataset } from './mutations/follow' import { StarDataset } from './mutations/star' import { SNAPSHOT_FIELDS } from './queries/dataset-query-fragments.js' const formatDate = dateObject => new Date(dateObject).toISOString().split('T')[0] // Helper function for getting version from URL const snapshotVersion = location => { const matches = location.pathname.match(/versions\/(.*?)(\/|$)/) return matches && matches[1] } type SnapshotContainerProps = { dataset tag: string snapshot } const SnapshotContainer: React.FC<SnapshotContainerProps> = ({ dataset, tag, snapshot, }) => { const location = useLocation() const activeDataset = snapshotVersion(location) || 'draft' const [selectedVersion, setSelectedVersion] = React.useState(activeDataset) const [deprecatedmodalIsOpen, setDeprecatedModalIsOpen] = React.useState(false) const summary = snapshot.summary const description = snapshot.description const datasetId = dataset.id const numSessions = summary && summary.sessions.length > 0 ? summary.sessions.length : 1 const dateAdded = formatDate(dataset.created) const dateAddedDifference = formatDistanceToNow(parseISO(dataset.created)) const dateModified = formatDate(snapshot.created) const dateUpdatedDifference = formatDistanceToNow(parseISO(snapshot.created)) const rootPath = `/datasets/${datasetId}/versions/${activeDataset}` //TODO deprecated needs to be added to the dataset snapshot obj and an admin needs to be able to say a version is deprecated somehow. const [cookies] = useCookies() const profile = getUnexpiredProfile(cookies) const isAdmin = profile?.admin const hasEdit = hasEditPermissions(dataset.permissions, profile?.sub) || isAdmin const hasDraftChanges = dataset.snapshots.length === 0 || dataset.draft.head !== dataset.snapshots[dataset.snapshots.length - 1].hexsha return ( <> <DatasetPage modality={summary?.modalities[0]} renderHeader={() => ( <> {summary && ( <DatasetHeader pageHeading={description.Name} modality={summary?.modalities[0]} /> )} </> )} renderHeaderMeta={() => ( <> {summary && ( <DatasetHeaderMeta size={summary.size} totalFiles={summary.totalFiles} datasetId={datasetId} /> )} </> )} renderFollowBookmark={() => ( <> <FollowDataset profile={profile} datasetId={dataset.id} following={dataset.following} followers={dataset.followers.length} /> <StarDataset profile={profile} datasetId={dataset.id} starred={dataset.starred} stars={dataset.stars.length} /> </> )} renderBrainLifeButton={() => ( <BrainLifeButton datasetId={datasetId} onBrainlife={dataset.onBrainlife} /> )} renderValidationBlock={() => ( <ValidationBlock> <Validation datasetId={dataset.id} issues={snapshot.issues} /> </ValidationBlock> )} renderCloneDropdown={() => ( <CloneDropdown gitAccess={ <DatasetGitAccess configUrl={config.url} worker={dataset.worker} datasetId={datasetId} gitHash={snapshot.hexsha} /> } /> )} renderToolButtons={() => ( <DatasetTools hasEdit={hasEdit} isPublic={dataset.public} datasetId={datasetId} isSnapshot={true} isAdmin={isAdmin} /> )} renderFiles={() => ( <ReadMore fileTree={true} id="collapse-tree" expandLabel="Read More" collapseabel="Collapse" > <Files datasetId={datasetId} snapshotTag={snapshot.tag} datasetName={description.Name} files={snapshot.files} editMode={false} datasetPermissions={dataset.permissions} /> </ReadMore> )} renderReadMe={() => ( <MetaDataBlock heading="README" item={ <ReadMore id="readme" expandLabel="Read More" collapseabel="Collapse" > <Markdown> {snapshot.readme == null ? 'N/A' : snapshot.readme} </Markdown> </ReadMore> } className="dataset-readme markdown-body" /> )} renderSidebar={() => ( <> <MetaDataBlock heading="Authors" item={ description.Authors.length ? description.Authors.join(', ') : 'N/A' } className="dmb-inline-list" /> <> {summary && ( <ModalitiesMetaDataBlock items={summary?.modalities} className="dmb-modalities" /> )} </> <MetaDataBlock heading="Versions" item={ <div className="version-block"> <VersionList hasEdit={hasEdit} datasetId={datasetId} items={dataset.snapshots} className="version-dropdown" activeDataset={activeDataset} dateModified={dateModified} selected={selectedVersion} setSelected={setSelectedVersion} setDeprecatedModalIsOpen={setDeprecatedModalIsOpen} /> </div> } /> {summary && ( <MetaDataBlock heading="Tasks" item={summary.tasks.length ? summary.tasks.join(', ') : 'N/A'} className="dmb-inline-list" /> )} {summary?.modalities.includes('pet') || summary?.modalities.includes('Pet') || (summary?.modalities.includes('PET') && ( <> <MetaDataBlock heading={pluralize('Target', summary.pet?.BodyPart)} item={summary.pet?.BodyPart} /> <MetaDataBlock heading={pluralize( 'Scanner Manufacturer', summary.pet?.ScannerManufacturer, )} item={ summary.pet?.ScannerManufacturer ? summary.pet?.ScannerManufacturer : 'N/A' } /> <MetaDataBlock heading={pluralize( 'Scanner Model', summary.pet?.ScannerManufacturersModelName, )} item={ summary.pet?.ScannerManufacturersModelName ? summary.pet?.ScannerManufacturersModelName : 'N/A' } /> <MetaDataBlock heading={pluralize( 'Radionuclide', summary.pet?.TracerRadionuclide, )} item={ summary.pet?.TracerRadionuclide ? summary.pet?.TracerRadionuclide : 'N/A' } /> <MetaDataBlock heading={pluralize('Radiotracer', summary.pet?.TracerName)} item={ summary.pet?.TracerName ? summary.pet?.TracerName : 'N/A' } /> </> ))} <MetaDataBlock heading="Uploaded by" item={ <> {dataset.uploader.name} on {dateAdded} - {dateAddedDifference}{' '} ago </> } /> {dataset.snapshots.length && ( <MetaDataBlock heading="Last Updated" item={ <> {dateModified} - {dateUpdatedDifference} ago </> } /> )} <MetaDataBlock heading="Sessions" item={numSessions} /> <> {summary && ( <MetaDataBlock heading="Participants" item={summary.subjects.length} /> )} </> <MetaDataBlock heading="Dataset DOI" item={ description.DatasetDOI || 'Create a new snapshot to obtain a DOI for the snapshot.' } /> <MetaDataBlock heading="License" item={description.License} /> <MetaDataBlock heading="How To Cite" item={ <> <DatasetCitation snapshot={snapshot} /> <h5> <Link to="/cite">More citation info</Link> </h5> </> } /> <MetaDataBlock heading="Acknowledgements" item={description.Acknowledgements} /> <MetaDataBlock heading="How to Acknowledge" item={description.HowToAcknowledge} /> <MetaDataBlock heading="Funding" item={description.Funding} className="dmb-list" /> <MetaDataBlock heading="References and Links" item={description.ReferencesAndLinks} className="dmb-list" /> <MetaDataBlock heading="Ethics Approvals" item={description.EthicsApprovals} className="dmb-list" /> </> )} renderDeprecatedModal={() => ( <Modal isOpen={deprecatedmodalIsOpen} toggle={() => setDeprecatedModalIsOpen(prevIsOpen => !prevIsOpen)} closeText={'close'} className="deprecated-modal" > <p> You have selected a deprecated version. The author of the dataset does not recommend this specific version. </p> </Modal> )} renderComments={() => ( <Comments datasetId={dataset.id} uploader={dataset.uploader} comments={dataset.comments} /> )} /> </> ) } const getSnapshotDetails = gql` query snapshot($datasetId: ID!, $tag: String!) { snapshot(datasetId: $datasetId, tag: $tag) { id ...SnapshotFields } } ${SNAPSHOT_FIELDS} ` export interface SnapshotLoaderProps { dataset tag: string } const SnapshotLoader: React.FC<SnapshotLoaderProps> = ({ dataset, tag }) => { const { loading, error, data, fetchMore } = useQuery(getSnapshotDetails, { variables: { datasetId: dataset.id, tag, }, errorPolicy: 'all', }) if (loading) { return ( <div className="loading-dataset"> <Loading /> Loading Dataset </div> ) } else if (error) { throw new Error(error.toString()) } else { return ( <DatasetQueryContext.Provider value={{ datasetId: dataset.id, fetchMore, error: null, }} > <SnapshotContainer dataset={dataset} tag={tag} snapshot={data.snapshot} /> </DatasetQueryContext.Provider> ) } } export default SnapshotLoader
the_stack
import { TransactionRequest, TransactionReceipt, TransactionResponse, BlockTag, EventType, Listener, Provider, Block } from "@ethersproject/abstract-provider"; import { BaseProvider, Web3Provider } from "@ethersproject/providers"; import { Networkish } from "@ethersproject/networks"; import { Deferrable } from "@ethersproject/properties"; import { hexDataLength } from "@ethersproject/bytes"; import { WebSocketProvider } from "./WebSocketProvider"; export interface WebSocketAugmentedProvider extends BaseProvider { openWebSocket(url: string, network: Networkish): void; closeWebSocket(): void; } const webSocketAugmentedProviders: any[] = []; export const isWebSocketAugmentedProvider = ( provider: Provider ): provider is WebSocketAugmentedProvider => webSocketAugmentedProviders.some( webSocketAugmentedProvider => provider instanceof webSocketAugmentedProvider ); const isHeaderNotFoundError = (error: any) => typeof error === "object" && typeof error.message === "string" && (error.message.includes( // geth "header not found" ) || error.message.includes( // openethereum "request is not supported because your node is running with state pruning" )); const isTransactionHash = (eventName: EventType): eventName is string => typeof eventName === "string" && hexDataLength(eventName) === 32; const loadBalancingGlitchRetryIntervalMs = 200; const delay = (ms: number) => new Promise(resolve => setTimeout(resolve, ms)); type BlockListenerContext = { isActive: () => boolean; removeMe: () => void; }; const waitFor = <T, U>(f: (t: T) => Promise<U | null>) => (g: (u: U) => void) => ( t: T, { isActive }: BlockListenerContext ) => { f(t).then(u => { if (u !== null && isActive()) { g(u); } }); }; const pass = <T>(f: (t: T) => void) => (t: T, _: BlockListenerContext) => { f(t); }; const passOnce = <T>(f: (t: T) => void) => (t: T, { removeMe }: BlockListenerContext) => { f(t); removeMe(); }; const sequence = <T, U, V>( f: (_: (_: U) => void) => (_: T, context: BlockListenerContext) => void, g: (_: (_: V) => void) => (_: U, context: BlockListenerContext) => void ) => (h: (_: V) => void) => (t: T, context: BlockListenerContext) => { f(u => g(h)(u, context))(t, context); }; const defer = <T>(f: (t: T) => void) => (t: T) => { setTimeout(() => { f(t); }, 0); }; export const WebSocketAugmented = <T extends new (...args: any[]) => BaseProvider>(Base: T) => { let webSocketAugmentedProvider = class extends Base implements WebSocketAugmentedProvider { _wsProvider?: WebSocketProvider; _wsParams?: [string, Networkish]; _reconnectTimerId: any; _seenBlock = 0; _blockListenerScheduled = false; readonly _blockListeners = new Map<(_: never) => void, (blockNumber: number) => void>(); readonly _blockListener = this._onBlock.bind(this); openWebSocket(url: string, network: Networkish) { this._wsProvider = new WebSocketProvider(url, network); this._wsProvider.onClose = this._onWebSocketClose.bind(this); this._wsParams = [url, network]; this._switchover(); } _onWebSocketClose() { this.closeWebSocket(); console.warn("WebSocketProvider disconnected. Retrying in 10 seconds."); this._reconnectTimerId = setTimeout(() => this.openWebSocket(...this._wsParams!), 10000); } closeWebSocket() { if (this._wsProvider) { this._wsProvider.onClose = null; this._wsProvider.close(1000); // normal closure this._wsProvider = undefined; this._switchover(); if (this._reconnectTimerId !== undefined) { clearTimeout(this._reconnectTimerId); this._reconnectTimerId = undefined; } } } _switchover() { if (this._blockListeners.size > 0) { if (this._wsProvider) { super.off("block", this._blockListener); } this._startBlockEvents(); } } _onBlock(blockNumber: number) { this._seenBlock = blockNumber; if (!this._blockListenerScheduled) { this._blockListenerScheduled = true; setTimeout(() => { this._blockListenerScheduled = false; [...this._blockListeners].forEach(([, listener]) => listener(this._seenBlock)); }, 50); } } async _retrySeenBlock<T>(perform: () => Promise<T>, startingBlock: number) { for (let retries = 0; ; ++retries) { try { const ret = await perform(); if (retries) { // console.log(`Glitch resolved after ${retries} ${retries === 1 ? "retry" : "retries"}.`); } return ret; } catch (error) { if (this._seenBlock !== startingBlock || !isHeaderNotFoundError(error)) { throw error; } } // console.warn("Load balancing glitch. Retrying..."); await delay(loadBalancingGlitchRetryIntervalMs); } } async call( transaction: Deferrable<TransactionRequest>, blockTag?: BlockTag | Promise<BlockTag> ) { const resolvedBlockTag = await blockTag; const perform = () => this._wsProvider?.isReady ? this._wsProvider.call(transaction, resolvedBlockTag) : super.call(transaction, resolvedBlockTag); return resolvedBlockTag === this._seenBlock ? this._retrySeenBlock(perform, this._seenBlock) : perform(); } async getBalance( addressOrName: string | Promise<string>, blockTag?: BlockTag | Promise<BlockTag> ) { const resolvedBlockTag = await blockTag; const perform = () => this._wsProvider?.isReady ? this._wsProvider.getBalance(addressOrName, resolvedBlockTag) : super.getBalance(addressOrName, resolvedBlockTag); return resolvedBlockTag === this._seenBlock ? this._retrySeenBlock(perform, this._seenBlock) : perform(); } _startBlockEvents() { if (this._wsProvider) { console.log("Listening for new blocks on WebSocketProvider"); this._wsProvider.on("block", this._blockListener); } else { console.log("Listening for new blocks on basic Provider"); super.on("block", this._blockListener); } } _stopBlockEvents() { if (this._wsProvider) { this._wsProvider.off("block", this._blockListener); } else { super.off("block", this._blockListener); } } _wrap<T, U>( f: (t: T) => void, g: (f: (t: T) => void) => (u: U, { removeMe }: BlockListenerContext) => void ): [(t: T) => void, (u: U) => void] { return [ f, (u: U) => g(defer(f))(u, { isActive: () => this._blockListeners.has(f), removeMe: () => this._blockListeners.delete(f) }) ]; } on(eventName: EventType, listener: Listener) { if (isTransactionHash(eventName)) { const fetchReceipt = this._getTransactionReceiptFromLatest.bind(this, eventName); const [, passReceipt] = this._wrap(listener, waitFor(fetchReceipt)); passReceipt(undefined); return this._addBlockListener(listener, passReceipt); } else if (eventName === "block") { return this._addBlockListener(...this._wrap(listener, pass)); } else { return super.on(eventName, listener); } } _addBlockListener(key: (_: never) => void, blockListener: (blockNumber: number) => void) { if (!this._blockListeners.has(key)) { this._blockListeners.set(key, blockListener); if (this._blockListeners.size === 1) { this._startBlockEvents(); } } return this; } once(eventName: EventType, listener: Listener) { if (isTransactionHash(eventName)) { const fetchReceipt = this._getTransactionReceiptFromLatest.bind(this, eventName); const [, passReceiptOnce] = this._wrap(listener, sequence(waitFor(fetchReceipt), passOnce)); passReceiptOnce(undefined); return this._addBlockListener(listener, passReceiptOnce); } else if (eventName === "block") { return this._addBlockListener(...this._wrap(listener, passOnce)); } else { return super.once(eventName, listener); } } off(eventName: EventType, listener: Listener) { if (isTransactionHash(eventName) || eventName === "block") { return this._removeBlockListener(listener); } else { return super.off(eventName, listener); } } _removeBlockListener(key: (_: never) => void) { if (this._blockListeners.has(key)) { this._blockListeners.delete(key); if (this._blockListeners.size === 0) { this._stopBlockEvents(); } } return this; } async getTransaction(transactionHash: string | Promise<string>) { const txPromises: Promise<TransactionResponse | null>[] = [ super.getTransaction(transactionHash), ...(this._wsProvider?.isReady ? [this._wsProvider.getTransaction(transactionHash)] : []) ]; const first = await Promise.race(txPromises); const tx = first ?? (await Promise.all(txPromises)).find(tx => tx !== null) ?? null; return tx as TransactionResponse; } getTransactionReceipt(transactionHash: string | Promise<string>) { return this._wsProvider?.isReady ? this._wsProvider.getTransactionReceipt(transactionHash) : super.getTransactionReceipt(transactionHash); } getTransactionCount( addressOrName: string | Promise<string>, blockTag?: BlockTag | Promise<BlockTag> ) { return this._wsProvider?.isReady ? this._wsProvider.getTransactionCount(addressOrName, blockTag) : super.getTransactionCount(addressOrName, blockTag); } getBlock(blockHashOrBlockTag: BlockTag | string | Promise<BlockTag | string>) { return this._wsProvider?.isReady ? this._wsProvider.getBlock(blockHashOrBlockTag) : super.getBlock(blockHashOrBlockTag); } getBlockWithTransactions(blockHashOrBlockTag: BlockTag | string | Promise<BlockTag | string>) { return this._wsProvider?.isReady ? this._wsProvider.getBlockWithTransactions(blockHashOrBlockTag) : super.getBlockWithTransactions(blockHashOrBlockTag); } async _blockContainsTx(blockNumber: number, txHash: string) { let block: Block | null; for (block = null; !block; block = await this.getBlock(blockNumber)) { await delay(loadBalancingGlitchRetryIntervalMs); } return block.transactions.some(txHashInBlock => txHashInBlock === txHash); } async _getTransactionReceiptFromLatest(txHash: string | Promise<string>, latestBlock?: number) { txHash = await txHash; for (let retries = 0; ; ++retries) { const receipt = (await this.getTransactionReceipt(txHash)) as TransactionReceipt | null; if ( latestBlock === undefined || (receipt === null && !(await this._blockContainsTx(latestBlock, txHash))) || (receipt !== null && receipt.blockNumber + receipt.confirmations - 1 >= latestBlock) ) { if (retries) { // console.log(`Glitch resolved after ${retries} ${retries === 1 ? "retry" : "retries"}.`); } return receipt; } // console.warn("Load balancing glitch. Retrying..."); await delay(loadBalancingGlitchRetryIntervalMs); } } async waitForTransaction(txHash: string, confirmations?: number, timeout?: number) { if (timeout !== undefined) { // We don't use timeout, don't implement it return super.waitForTransaction(txHash, confirmations, timeout); } let latestBlock: number | undefined = undefined; for (;;) { const receipt = await this._getTransactionReceiptFromLatest(txHash, latestBlock); if ( receipt !== null && (confirmations === undefined || receipt.confirmations >= confirmations) ) { return receipt; } latestBlock = await new Promise<number>(resolve => this.once("block", resolve)); } } }; webSocketAugmentedProviders.push(webSocketAugmentedProvider); return webSocketAugmentedProvider; }; export const WebSocketAugmentedWeb3Provider = WebSocketAugmented(Web3Provider);
the_stack
import { Card, CardOutput } from 'neuron-ipe-types'; import * as path from "path"; import * as fs from "fs"; import * as vscode from 'vscode'; import { Event, EventEmitter } from "vscode"; import { JSONObject, JSONArray } from '@phosphor/coreutils'; import { ContentHelpers } from './contentHelpers'; /** * Class maintaining an array of the exising cards in the backend. * Member functions allow the reordering and modification of cards. * It includes utilities to import and export to a Jupyter Notebook file. */ export class CardManager { /** * Event triggared when a Jupyter Notebook file (.ipynb) is imported by the user. */ private _onOpenNotebook : EventEmitter<string> = new EventEmitter(); get onOpenNotebook(): Event<string> { return this._onOpenNotebook.event; } /** * Array of existing cards. */ private cards: Card[] = []; /** * Array containing the previously deleted cards. * Allows restore if the user decides to undo the deletion. */ public lastDeletedCards: Card[] = []; /** * Holds the metadata required for python3 Jupyter Notebooks. */ private metadataPy = { "kernelspec": { "display_name": "Python 3", "language": "python", "name": "python3" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.6.4" } }; /** * Holds the metadata required for r Jupyter Notebooks. */ private metadataR = { "kernelspec": { "display_name": "R", "language": "R", "name": "ir" }, "language_info": { "codemirror_mode": "r", "file_extension": ".r", "mimetype": "text/x-r-source", "name": "R", "pygments_lexer": "r", "version": "3.5.0" } }; // Add additional metadata here to support more kernels. /** * Write the Jupyter Notebook exported in json format to file. * After export is completed ask the user to open the exported file in the browser * through the exising Jupyter Notebook instance. * @param jupyterFileData Json object containing the jupyter data exported. * @param kernelName The name of the kernel for the current file being exported (python3 and r supported). * @param fileName */ private writeToFile(jupyterFileData: JSONObject, kernelName: string, fileName: string) { if (!vscode.workspace.workspaceFolders) throw "You must have a workspace open to export the files"; let fullPath = vscode.workspace.workspaceFolders[0].uri.fsPath; let filePath = ''; if (!fileName) { filePath = path.join(fullPath, 'output_' + kernelName + '.ipynb'); } else { filePath = path.join(fullPath, fileName) } if((jupyterFileData['cells'] as JSONArray).length > 0) { try { fs.writeFileSync(filePath, JSON.stringify(jupyterFileData), {encoding: 'utf8', flag: 'w'}); vscode.window.showInformationMessage(`Exported ${kernelName} cards to ${filePath}`, 'Open in browser') .then(selection => { if (selection === 'Open in browser') { this._onOpenNotebook.fire(path.basename(filePath)); } }); } catch { throw "Unable to save exported Jupyter file"; } } } /** * Export cards to a Jupyter file (.ipynb). * @param indexes Array containing the indexes of the cards to export. * @param fileName Filename of the Jupyter file (does not include the extension) to which the cards are exported. */ exportToJupyter(indexes: number[] = null, fileName: string = null) { let cardsToExport: Card[]; if (indexes) { cardsToExport = indexes.map(index => this.cards[index]); } else { cardsToExport = this.cards; } // Process python cards let pythonData: JSONObject = { "nbformat": 4, "nbformat_minor": 2, "metadata": this.metadataPy, "cells": cardsToExport .filter(card => card.kernel === 'python3') .map(card => card.jupyterData as JSONObject) }; // Process r cards let rData: JSONObject = { "nbformat": 4, "nbformat_minor": 2, "metadata": this.metadataR, "cells": cardsToExport .filter(card => card.kernel === 'ir') .map(card => card.jupyterData as JSONObject) }; // If a new kernel is added, add export processing here // Write cards to file try { this.writeToFile(pythonData, 'python3', fileName); this.writeToFile(rData, 'r', fileName); } catch (err) { vscode.window.showErrorMessage(err); } } /** * Get the id of the card from its index. * @param index Index of the card. */ getCardId(index: number) { return this.cards[index].id; } /** * Add a card to the backend array. * @param card Card to add. */ addCard(card: Card) { this.cards.push(card); } /** * Move a card up in the backend array. * @param index Index of the card to move up. */ moveCardUp(index: number) { if (index > 0 && index < this.cards.length) { const tmp: Card = this.cards[index - 1]; this.cards[index - 1] = this.cards[index]; this.cards[index] = tmp; } } /** * Move a card down in the backend array. * @param index Index of the card to move down. */ moveCardDown(index: number) { if (index > -1 && index < this.cards.length - 1) { const tmp: Card = this.cards[index + 1]; this.cards[index + 1] = this.cards[index]; this.cards[index] = tmp; } } /** * Delete a card from the backend array. * @param index Index of the card to delete. */ deleteCard(index: number) { if (index > -1 && index < this.cards.length) { this.lastDeletedCards = [this.cards[index]]; this.cards.splice(index, 1); } } /** * Delete multiple cards from the backend array. * @param indexes Array containing the indexes of the cards to delete. */ deleteSelectedCards(indexes: number[]){ this.lastDeletedCards = indexes .filter(index => index > -1) .map(index => { let card = this.cards[index]; this.cards.splice(index, 1); return card; }); } /** * Change the title of a card in the backend array. * @param index Index of the card whose title is changed. * @param newTitle New title set for the card. */ changeTitle(index: number, newTitle: string) { if (index > -1 && index < this.cards.length) { this.cards[index].title = newTitle; } } /** * Collpase or expand the code of card in the backend array. * @param index Index of the card whose code is collapsed or expanded. * @param value Boolean, true for collapse, false for expand. */ collapseCode(index: number, value: boolean) { if (index > -1 && index < this.cards.length) { this.cards[index].codeCollapsed = value; } } /** * Collpase or expand the output of card in the backend array. * @param index Index of the card whose code is collapsed or expanded. * @param value Boolean, true for collapse, false for expand. */ collapseOutput(index: number, value: boolean) { if (index > -1 && index < this.cards.length) { this.cards[index].outputCollapsed = value; } } /** * Collapse or expand a card in the backend array. * @param index Index of the card to collapse or expand. * @param value Boolean, true for collapse, false for expand. */ collapseCard(index: number, value: boolean) { if (index > -1 && index < this.cards.length) { this.cards[index].collapsed = value; } } /** * Add custom card to the backend array. * Called when a card is added in the frontend. * This includes custom markdown cards in the * current implementation. * @param card Card that was added from the frontend. */ addCustomCard(card: Card) { let cardToAdd = card; cardToAdd.id = ContentHelpers.assignId(); if(cardToAdd.isCustomMarkdown) { cardToAdd.kernel = 'python3'; // Add relevant jupyter data cardToAdd.jupyterData = { "cell_type": "markdown", "metadata": {}, "source": cardToAdd.sourceCode }; } this.cards.push(cardToAdd); } /** * Edit a custom card in the backend array. * Called when a custom card is modified in the frontend. * E.g. the markdown content is changed. * @param index Index of the card whose content is changed. * @param card New version of the card. */ editCustomCard(index: number, card: Card) { if (index > -1 && index < this.cards.length) { let cardEdited = card; if(cardEdited.isCustomMarkdown){ cardEdited.kernel = 'python3'; // Add relevant jupyter data cardEdited.jupyterData = { "cell_type": "markdown", "metadata": {}, "source": cardEdited.sourceCode }; } this.cards[index] = cardEdited; } } /** * Import a Jupyter Notebook in json format. * @param jsonContent The content of the Jupyter Notebook to import in json format. */ importJupyter(jsonContent: JSONObject) { try{ /** * Convert every cell in the Jupyter Notebook imported to a card * and add it to the backend and frontend arrays. */ (jsonContent['cells'] as JSONArray) .map(cell => { let source = cell['source']; if(Array.isArray(source)){ source = source.join(''); } let cardId = ContentHelpers.assignId(); let newCard = new Card( cardId, ContentHelpers.makeCardTitle(cardId), source, this.processJupyterOutputs(cell['outputs'] as JSONArray), cell as object, jsonContent['metadata']['kernelspec']['name'] as string ); if(cell['cell_type'] == 'markdown') { newCard.isCustomMarkdown = true; } return newCard; }) .map(newCard => ContentHelpers.addNewCard(newCard)); let language: string; switch(jsonContent['metadata']['kernelspec']['name']) { case 'python3': language = 'python'; break case 'ir': language = 'r'; } /** * Generate a source file from the source fields of the * Jupyter Notebook imported. */ let content = (jsonContent['cells'] as JSONArray) .map(cell => { let source = ''; source = cell['source']; if(Array.isArray(source)) { if(cell['cell_type'] == 'markdown') { source = source.map(el => `# ${el}`).join(''); } else { source = source.join(''); } } else { if(cell['cell_type'] == 'markdown') { source = `# ${source}`; } } return source; }) .join('\n'); /** * Show the source file reconstructed to the user in a new pane. */ vscode.workspace.openTextDocument({language: language, content: content}) .then(textDocument => vscode.window.showTextDocument(textDocument)); } catch(err){ vscode.window.showInformationMessage('The Jupyter notebook file entered is in an unknown format'); } } /** * Convert the outputs of the Jupyter Notebook imported * to CardOutput objects. * @param outputs Jupyter Notebook outputs to convert. */ processJupyterOutputs(outputs: JSONArray): CardOutput[] { if (!outputs) { return []; } else { return outputs.map(output => { let keys = Object.keys(output); if(keys.indexOf('name') > -1) { let value = ''; if(typeof output['text'] === 'string') { value = output['text']; } else { value = output['text'].join(''); } return new CardOutput( 'stdout', value ); } else if(keys.indexOf('traceback') > -1) { return new CardOutput( 'error', (output['traceback'] as string[]).join('\n') ); } else { let type = ContentHelpers.chooseTypeFromComplexData(output['data']); return new CardOutput( type, output['data'][type] ); } }) } } /** * Reset the state of the backend array and of the id assignment. * Called when the webview is closed by the user. */ resetState() { this.cards = []; ContentHelpers.resetId(); } }
the_stack
import { expect } from "chai"; import { BeDuration, Id64, Id64Arg, Id64Set, Id64String } from "@itwin/core-bentley"; import { IModelConnection, SnapshotConnection, SubCategoriesCache } from "@itwin/core-frontend"; import { TestUtility } from "../TestUtility"; describe("SubCategoriesCache", () => { // test.bim: // 3d views: // view: 34 // model selector: 35 // models: 1c 1f 22 23 24 (all spatial models in file) // All but 1 category has one subcategory (id = catId + 1) // 4 spatial categories: // 17 // 2d // 2f: 2 subcategories: 30, 33 // 31 // 1 drawing category: 19 let imodel: IModelConnection; before(async () => { await TestUtility.startFrontend(undefined, true); imodel = await SnapshotConnection.openFile("test.bim"); // relative path resolved by BackendTestAssetResolver }); after(async () => { if (undefined !== imodel) await imodel.close(); await TestUtility.shutdownFrontend(); }); it("should not repeatedly request same categories", async () => { const catIds = new Set<string>(); catIds.add("0x2f"); // contains 2 subcategories: 0x33 and 0x30 catIds.add("0x17"); // contains 1 subcategory: 0x18 // Request the categories and await the result const subcats = new SubCategoriesCache(imodel); const req1 = subcats.load(catIds); expect(req1).not.to.be.undefined; expect(req1!.missingCategoryIds.size).to.equal(catIds.size); for (const catId of catIds) expect(req1!.missingCategoryIds.has(catId)).to.be.true; const res1 = await req1!.promise; expect(res1).to.be.true; // indicates all info loaded // Request the same categories again - should be a no-op as they are already loaded. const req2 = subcats.load(catIds); expect(req2).to.be.undefined; // Now request some "categories" using Ids that do not identify category elements catIds.clear(); catIds.add("0x1a"); // is a subcategory Id, not a category Id catIds.add("0x12345678"); // does not identify an existent element catIds.add("lalala"); // is an invalid Id64String const req3 = subcats.load(catIds); expect(req3).not.to.be.undefined; expect(req3!.missingCategoryIds.size).to.equal(catIds.size); for (const catId of catIds) expect(req3!.missingCategoryIds.has(catId)).to.be.true; const res3 = await req3!.promise; expect(res3).to.be.true; // Repeat the request - should be a no-op - we should cache the result even if the query returned no subcategory info const req4 = subcats.load(catIds); expect(req4).to.be.undefined; }); function expectEqualIdSets(idSet: Id64Set, ids: Id64Arg): void { expect(idSet.size).to.equal(Id64.sizeOf(ids)); for (const id of Id64.iterable(ids)) expect(idSet.has(id)).to.be.true; } class Queue extends SubCategoriesCache.Queue { // Note: it doesn't use IModelConnection's cache, so it always starts out empty. public readonly cache: SubCategoriesCache; public constructor(iModel: IModelConnection) { super(); this.cache = new SubCategoriesCache(iModel); } public q(catIds: Id64Arg, func: SubCategoriesCache.QueueFunc = () => undefined): void { this.push(this.cache, catIds, func); } public expectMembers(current: boolean, next: boolean, request: boolean, disposed = false): void { expect(this.current !== undefined).to.equal(current); expect(this.next !== undefined).to.equal(next); expect(this.request !== undefined).to.equal(request); expect(this.disposed).to.equal(disposed); } public expectNotLoaded(catIds: Id64Arg): void { for (const catId of Id64.iterable(catIds)) expect(this.cache.getSubCategories(catId)).to.be.undefined; } public expectLoaded(catId: Id64String, subcatIds: Id64Arg): void { const subcats = this.cache.getSubCategories(catId); expect(subcats).not.to.be.undefined; expectEqualIdSets(subcats!, subcatIds); } public get current() { return this._current; } public get next() { return this._next; } public get request() { return this._request; } public get disposed() { return this._disposed; } public async waitUntilEmpty(): Promise<void> { while (!this.isEmpty) await BeDuration.wait(1); } public expectEmpty(disposed = false): void { this.expectMembers(false, false, false, disposed); expect(this.isEmpty).to.be.true; } public expectFull(): void { this.expectMembers(true, true, true); expect(this.isEmpty).to.be.false; } } it("should have expected members", () => { const q = new Queue(imodel); q.expectEmpty(); q.dispose(); q.expectEmpty(true); }); it("should execute empty request immediately", () => { const q = new Queue(imodel); let proc = 0; q.q(new Set<string>(), () => ++proc); expect(proc).to.equal(1); expect(q.request).to.be.undefined; q.expectEmpty(); }); it("should execute request for unloaded categories asynchronously", async () => { const q = new Queue(imodel); q.expectNotLoaded("0x2f"); q.q("0x2f"); q.expectNotLoaded("02f"); await q.waitUntilEmpty(); q.expectLoaded("0x2f", ["0x30", "0x33"]); }); it("should process category asynchronously, then same category synchronously", async () => { const q = new Queue(imodel); q.expectNotLoaded("0x17"); let processedFirst = 0; let processedSecond = 0; q.q("0x17", () => ++processedFirst); // becomes current q.q("0x17", () => ++processedSecond); // becomes next q.expectFull(); expectEqualIdSets(q.current!.categoryIds, q.request!.missingCategoryIds); expectEqualIdSets(q.current!.categoryIds, "0x17"); expectEqualIdSets(q.current!.categoryIds, q.next!.categoryIds); // First request will load 0x17 asynchronously. As soon as that occurs, it will process second request immediately and the queue will become empty again. q.expectNotLoaded("0x17"); await q.waitUntilEmpty(); q.expectLoaded("0x17", "0x18"); q.expectEmpty(); expect(processedFirst).to.equal(1); expect(processedSecond).to.equal(1); }); it("should process consecutive requests asynchronously", async () => { const q = new Queue(imodel); q.expectNotLoaded(["0x17", "0x2f", "0x2d"]); let lastProcessed = 0; // becomes current q.q("0x17", () => { expect(lastProcessed++).to.equal(0); // Only the first request has been processed so far. q.expectLoaded("0x17", "0x18"); q.expectNotLoaded(["0x2f", "0x2d"]); }); // becomes next q.q("0x2f", () => { expect(lastProcessed++).to.equal(1); // The second and third requests were processed together q.expectLoaded("0x2f", ["0x30", "0x33"]); q.expectLoaded("0x2d", "0x2e"); }); // categories are merged with next; function is appended to next q.q("0x2d", () => { expect(lastProcessed++).to.equal(2); }); q.expectFull(); expectEqualIdSets(q.current!.categoryIds, q.request!.missingCategoryIds); expectEqualIdSets(q.current!.categoryIds, "0x17"); expectEqualIdSets(q.next!.categoryIds, ["0x2f", "0x2d"]); // First request will load 0x17 asynchronously. Second will load 0x2f and 0x2d asynchronously. q.expectNotLoaded(["0x17", "0x2f", "0x2d"]); await q.waitUntilEmpty(); // Requesting already-loaded categories should be processed immediately q.q(["0x17", "0x2f", "0x2d"], () => { expect(lastProcessed++).to.equal(3); }); q.expectEmpty(); expect(lastProcessed).to.equal(4); // Requesting same 3 categories individually also processes immediately, in order. lastProcessed = 0; q.q("0x17", () => { expect(lastProcessed++).to.equal(0); }); q.q("0x2f", () => { expect(lastProcessed++).to.equal(1); }); q.q("0x2d", () => { expect(lastProcessed++).to.equal(2); }); q.expectEmpty(); expect(lastProcessed).to.equal(3); }); it("should process loaded categories immediately, then unloaded categories asynchronously", async () => { const q = new Queue(imodel); const load = q.cache.load("0x17"); expect(load).not.to.be.undefined; await load!.promise; q.expectLoaded("0x17", "0x18"); // Request a loaded category, then an unloaded category. let lastProcessed = 0; q.q("0x17", () => { expect(lastProcessed++).to.equal(0); q.expectNotLoaded("0x2d"); }); q.q("0x2d", () => { expect(lastProcessed++).to.equal(1); q.expectLoaded("0x2d", "0x2e"); }); q.expectMembers(true, false, true); expect(lastProcessed).to.equal(1); q.expectNotLoaded("0x2d"); await q.waitUntilEmpty(); expect(lastProcessed).to.equal(2); q.expectLoaded("0x2d", "0x2e"); }); it("should not process requests fulfilled after disposal", async () => { const q = new Queue(imodel); // Request a category that is not yet loaded. let processed = false; q.q("0x17", () => processed = true); expect(q.request).not.to.be.undefined; const promise = q.request!.promise; let promiseFulfilled = false; // I'm going to handle it further down the function, geez... promise.then(() => promiseFulfilled = true); // eslint-disable-line @typescript-eslint/no-floating-promises q.expectMembers(true, false, true); q.dispose(); q.expectEmpty(true); // The promise will fulfill. The results will be added to the cache, but our processing function will not execute. await promise; expect(promiseFulfilled).to.be.true; expect(processed).to.be.false; q.expectNotLoaded("0x17"); }); it("should not process synchronous requests after disposal", async () => { // Load a category const q = new Queue(imodel); q.q("0x17"); await q.waitUntilEmpty(); q.expectLoaded("0x17", "0x18"); // Dispose, then request same category. Should be ignored. let processed = false; q.dispose(); q.q("0x17", () => processed = true); q.expectEmpty(true); expect(processed).to.be.false; }); it("should not process pending asynchronous requests after disposal", async () => { const q = new Queue(imodel); q.q("0x17", () => q.dispose()); let processedPending = false; q.q("0x2d", () => processedPending = true); await q.waitUntilEmpty(); expect(processedPending).to.be.false; q.expectLoaded("0x17", "0x18"); q.expectNotLoaded("0x2d"); }); it("should not process pending synchronous requests after disposal", async () => { const q = new Queue(imodel); // Asynchronous request to load category. q.q("0x17", () => q.dispose()); // Request same category, which would normally be processed synchronously as soon as first request completes. let processedPending = false; q.q("0x17", () => processedPending = true); await q.waitUntilEmpty(); // Should not process second request after disposal. expect(processedPending).to.be.false; q.expectLoaded("0x17", "0x18"); }); it("should not create requests after disposal", () => { const q = new Queue(imodel); q.dispose(); q.q("0x17"); q.expectEmpty(true); }); });
the_stack
import { ENTER, ESCAPE, SPACE } from '@angular/cdk/keycodes'; import { OverlayContainer } from '@angular/cdk/overlay'; import { Component } from '@angular/core'; import { ComponentFixture, TestBed, fakeAsync, inject, tick, } from '@angular/core/testing'; import { By } from '@angular/platform-browser'; import { NoopAnimationsModule } from '@angular/platform-browser/animations'; import { DtOverlayModule } from './overlay-module'; import { DT_OVERLAY_DEFAULT_OFFSET } from './overlay'; import { DtOverlayConfig } from './overlay-config'; import { createComponent, dispatchKeyboardEvent, dispatchMouseEvent, } from '@dynatrace/testing/browser'; describe('DtOverlayTrigger', () => { let overlayContainer: OverlayContainer; let overlayContainerElement: HTMLElement; let trigger: HTMLElement; let fixture: ComponentFixture<TestComponent>; beforeEach(fakeAsync(() => { TestBed.configureTestingModule({ imports: [DtOverlayModule, NoopAnimationsModule], declarations: [TestComponent], }).compileComponents(); })); beforeEach(inject([OverlayContainer], (oc: OverlayContainer) => { overlayContainer = oc; overlayContainerElement = oc.getContainerElement(); })); beforeEach(() => { fixture = createComponent(TestComponent); trigger = fixture.debugElement.query( By.css('.dt-overlay-trigger'), ).nativeElement; }); afterEach(() => { overlayContainer.ngOnDestroy(); (overlayContainer as any) = null; (overlayContainerElement as any) = null; }); it('should create an overlay on mouseenter and move and dismiss on mouseleave', fakeAsync(() => { initOverlay(fixture, trigger); let overlay = getContainerElement(overlayContainerElement); expect(overlay).toBeDefined(); expect(overlay.textContent).toContain('overlayfocusme'); dispatchMouseEvent(trigger, 'mouseleave'); fixture.detectChanges(); tick(); overlay = getContainerElement(overlayContainerElement); expect(overlay).toBeNull(); })); it('should set the offset to the mouseposition and deal with initial offset', fakeAsync(() => { const offset = 1; initOverlay(fixture, trigger); dispatchMouseEvent( trigger, 'mousemove', trigger.getBoundingClientRect().left + offset, trigger.getBoundingClientRect().top + offset, ); fixture.detectChanges(); tick(); const overlayPane = overlayContainerElement.querySelector( '.cdk-overlay-pane', ) as HTMLElement; expect(overlayPane).toBeDefined(); // TODO: [e2e] computed style is not available in jsdom move to e2e test // expect(overlayPane.style.transform).toEqual( // `translateX(${DT_OVERLAY_DEFAULT_OFFSET + // 1}px) translateY(${DT_OVERLAY_DEFAULT_OFFSET + offset}px)` // ); })); // TODO: Test is flaky since the change to JEST. // it('should not be pinnable by default', fakeAsync(() => { // initOverlay(fixture, trigger); // dispatchMouseEvent(trigger, 'click'); // flush(); // fixture.detectChanges(); // dispatchMouseEvent(trigger, 'mouseleave'); // flush(); // fixture.detectChanges(); // const overlay = getContainerElement(overlayContainerElement); // expect(overlay).toBeNull(); // })); it('should be pinnable if configured', fakeAsync(() => { fixture.componentInstance.config = { pinnable: true }; fixture.detectChanges(); initOverlay(fixture, trigger); dispatchMouseEvent(trigger, 'click'); fixture.detectChanges(); tick(); dispatchMouseEvent(trigger, 'mouseleave'); tick(); const overlay = getContainerElement(overlayContainerElement); expect(overlay).not.toBeNull(); })); it('should fire pinnedChanged when pinned', fakeAsync(() => { fixture.componentInstance.config = { pinnable: true }; fixture.detectChanges(); initOverlay(fixture, trigger); dispatchMouseEvent(trigger, 'click'); fixture.detectChanges(); tick(); expect(fixture.componentInstance.pinned).toBeTruthy(); })); it('should not fire pinnedChanged on subsequent mouseenter', fakeAsync(() => { fixture.componentInstance.config = { pinnable: true }; fixture.detectChanges(); initOverlay(fixture, trigger); dispatchMouseEvent(trigger, 'click'); fixture.detectChanges(); tick(); expect(fixture.componentInstance.pinned).toBeTruthy(); dispatchMouseEvent(trigger, 'mouseleave'); dispatchMouseEvent(trigger, 'mouseenter'); dispatchMouseEvent(trigger, 'mousemove'); fixture.detectChanges(); tick(); expect(fixture.componentInstance.pinned).toBeTruthy(); })); it('should fire pinnedChanged when pinned then overlay is dismissed', fakeAsync(() => { fixture.componentInstance.config = { pinnable: true }; fixture.detectChanges(); initOverlay(fixture, trigger); dispatchMouseEvent(trigger, 'click'); fixture.detectChanges(); tick(); expect(fixture.componentInstance.pinned).toBeTruthy(); fixture.componentInstance.showTrigger = false; fixture.detectChanges(); tick(); expect(fixture.componentInstance.pinned).toBeFalsy(); })); it('should stay pinned on subsequent mouseenter', fakeAsync(() => { fixture.componentInstance.config = { pinnable: true }; fixture.detectChanges(); initOverlay(fixture, trigger); dispatchMouseEvent(trigger, 'click'); fixture.detectChanges(); tick(); dispatchMouseEvent(trigger, 'mouseleave'); fixture.detectChanges(); tick(); let overlay = getOverlayPane(overlayContainerElement); expect(overlay).not.toBeNull(); dispatchMouseEvent(trigger, 'mouseenter'); dispatchMouseEvent(trigger, 'mousemove'); fixture.detectChanges(); tick(); overlay = getOverlayPane(overlayContainerElement); expect(overlay).not.toBeNull(); })); // tslint:disable-next-line: dt-no-focused-tests it.skip('should lock movement to xAxis', fakeAsync(() => { const offset = 1; fixture.componentInstance.config = { movementConstraint: 'xAxis' }; fixture.detectChanges(); initOverlay(fixture, trigger); dispatchMouseEvent( trigger, 'mousemove', trigger.getBoundingClientRect().left + offset, trigger.getBoundingClientRect().top + offset, ); fixture.detectChanges(); tick(); const overlayPane = overlayContainerElement.querySelector( '.cdk-overlay-pane', ) as HTMLElement; // TODO: [e2e] computed style is not available in jsdom move to e2e test expect(overlayPane.style.transform).toEqual( `translateX(${ DT_OVERLAY_DEFAULT_OFFSET + offset }px) translateY(${DT_OVERLAY_DEFAULT_OFFSET}px)`, ); })); // tslint:disable-next-line: dt-no-focused-tests it.skip('should lock movement to yAxis', fakeAsync(() => { const offset = 1; fixture.componentInstance.config = { movementConstraint: 'yAxis' }; fixture.detectChanges(); initOverlay(fixture, trigger); dispatchMouseEvent( trigger, 'mousemove', trigger.getBoundingClientRect().left + offset, trigger.getBoundingClientRect().top + offset, ); fixture.detectChanges(); tick(); const overlayPane = overlayContainerElement.querySelector( '.cdk-overlay-pane', ) as HTMLElement; // TODO: [e2e] computed style is not available in jsdom move to e2e test expect(overlayPane.style.transform).toEqual( `translateX(${DT_OVERLAY_DEFAULT_OFFSET}px) translateY(${ DT_OVERLAY_DEFAULT_OFFSET + offset }px)`, ); })); it('should focus the trigger', () => { expect(document.activeElement).not.toBe(trigger); trigger.focus(); fixture.detectChanges(); expect(document.activeElement).toBe(trigger); }); it('should not change the focus if the overlay is not pinned', fakeAsync(() => { const previouslyFocused = document.activeElement; initOverlay(fixture, trigger); expect(document.activeElement).toBe(previouslyFocused); })); // tslint:disable-next-line: dt-no-focused-tests it.skip('should change the focus if the overlay pinned', fakeAsync(() => { const previouslyFocused = document.activeElement; fixture.componentInstance.config = { pinnable: true }; fixture.detectChanges(); initOverlay(fixture, trigger); dispatchMouseEvent(trigger, 'click'); fixture.detectChanges(); tick(); expect(document.activeElement).not.toBe(previouslyFocused); })); it('should open the overlay with space', () => { dispatchKeyboardEvent(trigger, 'keydown', SPACE); fixture.detectChanges(); const overlay = getContainerElement(overlayContainerElement); expect(overlay).not.toBeNull(); }); it('should open the overlay with enter', () => { dispatchKeyboardEvent(trigger, 'keydown', ENTER); fixture.detectChanges(); const overlay = getContainerElement(overlayContainerElement); expect(overlay).not.toBeNull(); }); it('should close the overlay on escape', fakeAsync(() => { initOverlay(fixture, trigger); let overlay = getContainerElement(overlayContainerElement); expect(overlay).not.toBeNull(); dispatchKeyboardEvent(trigger, 'keydown', ESCAPE); fixture.detectChanges(); tick(); overlay = getContainerElement(overlayContainerElement); expect(overlay).toBeNull(); })); it('should not open an overlay when disabled', fakeAsync(() => { fixture.componentInstance.disabled = true; fixture.detectChanges(); initOverlay(fixture, trigger); const overlay = getContainerElement(overlayContainerElement); expect(overlay).toBeNull(); })); it('should destroy the overlay when trigger is destroyed', fakeAsync(() => { initOverlay(fixture, trigger); fixture.detectChanges(); let overlay = getContainerElement(overlayContainerElement); expect(overlay).not.toBeNull(); fixture.componentInstance.showTrigger = false; fixture.detectChanges(); tick(); overlay = getContainerElement(overlayContainerElement); expect(overlay).toBeNull(); })); }); function initOverlay( fixture: ComponentFixture<TestComponent>, trigger: HTMLElement, ): void { dispatchMouseEvent(trigger, 'mouseenter'); dispatchMouseEvent(trigger, 'mousemove'); fixture.detectChanges(); tick(); } function getContainerElement( overlayContainerElement: HTMLElement, ): HTMLElement { return overlayContainerElement.querySelector( '.dt-overlay-container', ) as HTMLElement; } function getOverlayPane(overlayContainerElement: HTMLElement): HTMLElement { return overlayContainerElement.querySelector( '.cdk-overlay-pane', ) as HTMLElement; } /** Test component */ @Component({ selector: 'dt-test-component', template: ` <div *ngIf="showTrigger" [dtOverlay]="overlay" [dtOverlayConfig]="config" [disabled]="disabled" (pinnedChanged)="handlePinnedChanged($event)" > trigger </div> <!-- prettier-ignore --> <ng-template #overlay>overlay<button>focusme</button></ng-template> `, }) class TestComponent { config: DtOverlayConfig = {}; disabled = false; showTrigger = true; pinned: boolean = false; handlePinnedChanged(event: boolean): void { this.pinned = event; } }
the_stack
import beetle = require("beetle.js"); declare module "beetle" { namespace querying { interface ArrayQuery<T> { /** Automatically executed before enumeration (like LINQ). */ length: number; /** * Applies an accumulator function over an array. The specified seed value is used as the initial accumulator value. * @param func A function to test each element for a condition. * @param seed The initial accumulator value. */ aggregate<TAggregate>(func: (aggregate: TAggregate, entity: T) => TAggregate, seed?: TAggregate): beetle.querying.ArrayQuery<TAggregate>; /** * Concatenates two arrays. * @param other The array to concatenate to the query's array. */ concat(other: Array<T>): beetle.querying.ArrayQuery<T>; /** * Determines whether a array contains a specified element. * @param item The value to locate in the array. * @returns true if the source array contains an element that has the specified value; otherwise, false. */ contains(item: T): boolean; /** * Produces the set difference of two arrays. * @param other An array whose elements that also occur in the first array will cause those elements to be removed from the returned array. */ except(other: Array<T>): beetle.querying.ArrayQuery<T>; /** * Correlates the elements of two arrays based on equality of keys and groups the results. * @param other The array to join to the query array. * @param thisKey Key selector for query's array. * @param otherKey Key selector for other array. * @param selector A function to create a result element from an element from the first array and a collection of matching elements from the other array. */ groupJoin<TOther>(other: Array<TOther>, thisKey: string, otherKey: string, selector: (entity: T, other: Array<TOther>) => any): beetle.querying.ArrayQuery<any>; groupJoin<TOther, TKey>(other: Array<TOther>, thisKey: (entity: T) => TKey, otherKey: (entity: TOther) => TKey, selector: (entity: T, other: Array<TOther>) => any): beetle.querying.ArrayQuery<any>; groupJoin<TOther, TResult>(other: Array<TOther>, thisKey: string, otherKey: string, selector: (entity: T, other: Array<TOther>) => TResult): beetle.querying.ArrayQuery<TResult>; groupJoin<TOther, TKey, TResult>(other: Array<TOther>, thisKey: (entity: T) => TKey, otherKey: (entity: TOther) => TKey, selector: (entity: T, other: Array<TOther>) => TResult): beetle.querying.ArrayQuery<TResult>; /** * Correlates the elements of two arrays based on matching keys. * @param other The array to join to the query array. * @param thisKey Key selector for query's array. * @param otherKey Key selector for other array. * @param selector A function to create a result element from two matching elements. */ join<TOther>(other: Array<TOther>, thisKey: string, otherKey: string, selector: (entity: T, other: TOther) => any): beetle.querying.ArrayQuery<any>; join<TOther, TKey>(other: Array<TOther>, thisKey: (entity: T) => TKey, otherKey: (entity: TOther) => TKey, selector: (entity: T, other: TOther) => any): beetle.querying.ArrayQuery<any>; join<TOther, TResult>(other: Array<TOther>, thisKey: string, otherKey: string, selector: (entity: T, other: TOther) => TResult): beetle.querying.ArrayQuery<TResult>; join<TOther, TKey, TResult>(other: Array<TOther>, thisKey: (entity: T) => TKey, otherKey: (entity: TOther) => TKey, selector: (entity: T, other: TOther) => TResult): beetle.querying.ArrayQuery<TResult>; /** * Correlates the elements of two arrays based on matching keys. * @param other The array to join to the query array. * @param thisKey Key selector for query's array. * @param otherKey Key selector for other array. * @param selector A function to create a result element from two matching elements. */ innerJoin<TOther>(other: Array<TOther>, thisKey: string, otherKey: string, selector: (entity: T, other: TOther) => any): beetle.querying.ArrayQuery<any>; innerJoin<TOther, TKey>(other: Array<TOther>, thisKey: (entity: T) => TKey, otherKey: (entity: TOther) => TKey, selector: (entity: T, other: TOther) => any): beetle.querying.ArrayQuery<any>; innerJoin<TOther, TResult>(other: Array<TOther>, thisKey: string, otherKey: string, selector: (entity: T, other: TOther) => TResult): beetle.querying.ArrayQuery<TResult>; innerJoin<TOther, TKey, TResult>(other: Array<TOther>, thisKey: (entity: T) => TKey, otherKey: (entity: TOther) => TKey, selector: (entity: T, other: TOther) => TResult): beetle.querying.ArrayQuery<TResult>; /** * Correlates the elements of two arrays based on matching keys (query array items are taken even they do not have matching item on other array). * @param other The array to join to the query array. * @param thisKey Key selector for query's array. * @param otherKey Key selector for other array. * @param selector A function to create a result element from two matching elements. */ leftJoin<TOther>(other: Array<TOther>, thisKey: string, otherKey: string, selector: (entity: T, other: TOther) => any): beetle.querying.ArrayQuery<any>; leftJoin<TOther, TKey>(other: Array<TOther>, thisKey: (entity: T) => TKey, otherKey: (entity: TOther) => TKey, selector: (entity: T, other: TOther) => any): beetle.querying.ArrayQuery<any>; leftJoin<TOther, TResult>(other: Array<TOther>, thisKey: string, otherKey: string, selector: (entity: T, other: TOther) => TResult): beetle.querying.ArrayQuery<TResult>; leftJoin<TOther, TKey, TResult>(other: Array<TOther>, thisKey: (entity: T) => TKey, otherKey: (entity: TOther) => TKey, selector: (entiy: T, other: TOther) => TResult): beetle.querying.ArrayQuery<TResult>; /** * Correlates the elements of two arrays based on matching keys (other array items are taken even they do not have matching item on query array). * @param other The array to join to the query array. * @param thisKey Key selector for query's array. * @param otherKey Key selector for other array. * @param selector A function to create a result element from two matching elements. */ rightJoin<TOther>(other: Array<TOther>, thisKey: string, otherKey: string, selector: (entity: T, other: TOther) => any): beetle.querying.ArrayQuery<any>; rightJoin<TOther, TKey>(other: Array<TOther>, thisKey: (entity: T) => TKey, otherKey: (entity: TOther) => TKey, selector: (entity: T, other: TOther) => any): beetle.querying.ArrayQuery<any>; rightJoin<TOther, TResult>(other: Array<TOther>, thisKey: string, otherKey: string, selector: (entity: T, other: TOther) => TResult): beetle.querying.ArrayQuery<TResult>; rightJoin<TOther, TKey, TResult>(other: Array<TOther>, thisKey: (entity: T) => TKey, otherKey: (entity: TOther) => TKey, selector: (entity: T, other: TOther) => TResult): beetle.querying.ArrayQuery<TResult>; /** * Correlates the elements of two arrays based on matching keys (all items are taken cross-multiplied). * @param other The array to join to the query array. * @param thisKey Key selector for query's array. * @param otherKey Key selector for other array. * @param selector A function to create a result element from two matching elements. */ fullJoin<TOther>(other: Array<TOther>, thisKey: string, otherKey: string, selector: (entity: T, other: TOther) => any): beetle.querying.ArrayQuery<any>; fullJoin<TOther, TKey>(other: Array<TOther>, thisKey: (entity: T) => TKey, otherKey: (entity: TOther) => TKey, selector: (entity: T, other: TOther) => any): beetle.querying.ArrayQuery<any>; fullJoin<TOther, TResult>(other: Array<TOther>, thisKey: string, otherKey: string, selector: (entity: T, other: TOther) => TResult): beetle.querying.ArrayQuery<TResult>; fullJoin<TOther, TKey, TResult>(other: Array<TOther>, thisKey: (entity: T) => TKey, otherKey: (entity: TOther) => TKey, selector: (entity: T, other: TOther) => TResult): beetle.querying.ArrayQuery<TResult>; /** * Correlates the elements of two arrays based on matching keys (all items are taken cross-multiplied). * @param other The array to join to the query array. * @param thisKey Key selector for query's array. * @param otherKey Key selector for other array. * @param selector A function to create a result element from two matching elements. */ crossJoin<TOther>(other: Array<TOther>, selector: (entity: T, other: TOther) => any): beetle.querying.ArrayQuery<any>; crossJoin<TOther, TResult>(other: Array<TOther>, selector: (entity: T, other: TOther) => TResult): beetle.querying.ArrayQuery<TResult>; /** * Produces the set intersection of two arrays. * @param other The array whose distinct elements that also appear in the first array will be returned. */ intersect(other: Array<T>): beetle.querying.ArrayQuery<T>; /** * Determines whether two arrays are equal by comparing the elements. * @param other An array to compare to the query array. */ sequenceEqual(other: Array<T>): boolean; /** * Creates a array from query array according to specified key selector and element selector functions. * @param keySelector A function to extract a key from each element. * @param elementSelector An array to compare to the query array. */ toLookup(keySelector: (entity: T) => any, elementSelector: (group: beetle.interfaces.Grouping<T, any>) => any): beetle.querying.ArrayQuery<any>; toLookup<TKey>(keySelector: (entity: T) => TKey, elementSelector: (group: beetle.interfaces.Grouping<T, any>) => any): beetle.querying.ArrayQuery<any>; toLookup<TKey, TResult>(keySelector: (entity: T) => TKey, elementSelector: (group: beetle.interfaces.Grouping<T, TKey>) => any): beetle.querying.ArrayQuery<TResult>; /** * Produces the set union of two arrays' distinct elements. * @param other An array whose distinct elements form the second set for the union. */ union(other: Array<T>): beetle.querying.ArrayQuery<T>; /** * Applies a specified function to the corresponding elements of two arrays, producing a array of the results. * @param other The second array to merge. * @param selector A function that specifies how to merge the elements from the two arrays. */ zip<TOther>(other: Array<TOther>, selector: (entity: T, other: TOther) => any): beetle.querying.ArrayQuery<any>; zip<TOther, TResult>(other: Array<TOther>, selector: (entity: T, other: TOther) => TResult): beetle.querying.ArrayQuery<TResult>; /** Automatically executes before enumeration. */ forEach(callback: (item: T) => void); } } } declare global { interface Array<T> { /** * Indicates wheter or not include total count in result. * @param isEnabled When true, total count will be included in result. Default value: true. */ inlineCount(isEnabled?: boolean): beetle.querying.ArrayQuery<T>; /** * If model has inheritance, when querying base type we can tell which derived type we want to load. * @param typeName Derived type name. */ ofType<TResult extends T>(type: string | (new () => TResult)): beetle.querying.ArrayQuery<TResult>; /** * Filter query based on given expression. * @param predicate A function to test each element for a condition (can be string expression). * @param varContext Variable context for the expression. */ where(predicate: string | ((entity: T) => boolean), varContext?: any): beetle.querying.ArrayQuery<T>; /** * Sorts results based on given properties. * @param properties The properties to sort by. * @param isDesc Indicates if sorting will be descending. Default value is false. */ orderBy(keySelector?: string | ((entity: T) => any) | ((entity1: T, entity2: T) => number)): beetle.querying.ArrayQuery<T>; /** * Sorts results based on given properties descendingly. * @param properties The properties to sort by. */ orderByDesc(keySelector?: string | ((entity: T) => any) | ((entity1: T, entity2: T) => number)): beetle.querying.ArrayQuery<T>; /** * Selects only given properties using projection. * @param properties Properties or PropertyPaths to select (project). */ select<TResult>(selector: string | string[] | ((entity: T) => TResult)): beetle.querying.ArrayQuery<TResult>; select<TResult>(...selectors: string[]): beetle.querying.ArrayQuery<TResult>; select(selector: string | string[] | ((entity: T) => any)): beetle.querying.ArrayQuery<any>; select(...selectors: string[]): beetle.querying.ArrayQuery<any>; /** * Skips given count records and start reading. * @paramcount The number of items to skip. */ skip(count: number): beetle.querying.ArrayQuery<T>; /** * Takes only given count records. * @param count The number of items to take. */ take(count: number): beetle.querying.ArrayQuery<T>; /** * Takes only given count records . * @param count The number of items to take. */ top(count: number): beetle.querying.ArrayQuery<T>; /** * Groups query by given keys (projects them into a new type) and returns values (projecting into new type). * @param keySelector A projection to extract the key for each element. * @param valueSelector A projection to create a result value from each group. */ groupBy<TKey, TResult>(keySelector: (entity: T) => TKey, valueSelector: (group: beetle.interfaces.Grouping<T, TKey>) => TResult): beetle.querying.ArrayQuery<TResult>; groupBy<TKey>(keySelector: (entity: T) => TKey): beetle.querying.ArrayQuery<beetle.interfaces.Grouped<T, TKey>>; groupBy<TResult>(keySelector: string | ((entity: T) => any), valueSelector: string | ((group: beetle.interfaces.Grouping<T, any>) => TResult)): beetle.querying.ArrayQuery<TResult>; groupBy(keySelector: string | ((entity: T) => any)): beetle.querying.ArrayQuery<beetle.interfaces.Grouped<T, any>>; groupBy(keySelector: string | ((entity: T) => any), valueSelector: string | ((group: beetle.interfaces.Grouping<T, any>) => any)): beetle.querying.ArrayQuery<any>; /** * Gets only distinct items, when selector is given it will be used as comparer (project and compares projected objects). * @param selector A projection to extract the key for each element. */ distinct(): beetle.querying.ArrayQuery<T>; distinct<TResult>(selector: string | ((entity: T) => TResult)): beetle.querying.ArrayQuery<TResult>; distinct(selector: string | ((entity: T) => any)): beetle.querying.ArrayQuery<any>; /** Reverse the collection. */ reverse(): beetle.querying.ArrayQuery<T>; /** * Selects given collection property for each element and returns all in a new array. * @param properties Properties or PropertyPaths to select (project). */ selectMany<TResult>(selector: string | ((entity: T) => Array<TResult>)): beetle.querying.ArrayQuery<TResult>; selectMany(selector: string | ((entity: T) => any)): beetle.querying.ArrayQuery<any>; /** * Gets all the items after first succesful predicate. * @param predicate A function to test each element for a condition (can be string expression). * @param varContext Variable context for the expression. */ skipWhile(predicate: string | ((entity: T) => boolean), varContext?: any): beetle.querying.ArrayQuery<T>; /** * Gets all the items before first succesful predicate. * @param predicate A function to test each element for a condition (can be string expression). * @param varContext Variable context for the expression. */ takeWhile(predicate: string | ((entity: T) => boolean), varContext?: any): beetle.querying.ArrayQuery<T>; /** * If all items suits given predication returns true, otherwise false. * @param predicate A function to test each element for a condition (can be string expression). * @param varContext Variable context for the expression. */ all(predicate?: string | ((entity: T) => boolean), varContext?: any): boolean; /** * If there is at least one item in query result (or any item suits given predication) returns true, otherwise false. * @param predicate A function to test each element for a condition (can be string expression). * @param varContext Variable context for the expression. */ any(predicate?: string | ((entity: T) => boolean), varContext?: any): boolean; /** * Calculates average of items of query (or from given projection result). * @param selector Property path to use on calculation. */ avg(selector?: string | ((entity: T) => number)): number; /** * Finds maximum value from items of query (or from given projection result). * @param selector Property path to use on calculation. */ max(selector?: string | ((entity: T) => number)): number; /** * Finds minimum value from items of query (or from given projection result). * @param selector Property path to use on calculation. */ min(selector?: string | ((entity: T) => number)): number; /** * Finds summary value from items of query (or from given projection result). * @param selector Property path to use on calculation. */ sum(selector?: string | ((entity: T) => number)): number; /** * Gets the count of items of query. * @param predicate A function to test each element for a condition (can be string expression). * @param varContext Variable context for the expression. */ count(predicate?: string | ((entity: T) => boolean), varContext?: any): number; /** * Gets the first value from items of query (or from given predication result). When there is no item, throws exception. * @param predicate A function to test each element for a condition (can be string expression). * @param varContext Variable context for the expression. */ first(predicate?: string | ((entity: T) => boolean), varContext?: any): T; /** * Gets the first value (or null when there is no items) from items of query (or from given predication result). * @param predicate A function to test each element for a condition (can be string expression). * @param varContext Variable context for the expression. */ firstOrDefault(predicate?: string | ((entity: T) => boolean), varContext?: any): T; /** * Gets the single value from items (or from given predication result). Where zero or more than one item exists throws exception. * @param predicate A function to test each element for a condition (can be string expression). * @param varContext Variable context for the expression. */ single(predicate?: string | ((entity: T) => boolean), varContext?: any): T; /** * Gets the single value (or null when there is no items) from items (or from given predication result). Where more than one item exists throws exception. * @param predicate A function to test each element for a condition (can be string expression). * @param varContext Variable context for the expression. */ singleOrDefault(predicate?: string | ((entity: T) => boolean), varContext?: any): T; /** * Gets the last value from items of query (or from given predication result). When there is no item, throws exception. * @param predicate A function to test each element for a condition (can be string expression). * @param varContext Variable context for the expression. */ last(predicate?: string | ((entity: T) => boolean), varContext?: any): T; /** * Gets the last value (or null when there is no items) from items of query (or from given predication result). * @param predicate A function to test each element for a condition (can be string expression). * @param varContext Variable context for the expression. */ lastOrDefault(predicate?: string | ((entity: T) => boolean), varContext?: any): T; /** * Applies an accumulator function over an array. The specified seed value is used as the initial accumulator value. * @param func A function to test each element for a condition. * @param seed The initial accumulator value. */ aggregate<TAggregate>(func: (aggregate: TAggregate, entity: T) => TAggregate, seed?: TAggregate): beetle.querying.ArrayQuery<TAggregate>; /** * Concatenates two arrays. * @param other The array to concatenate to the query's array. */ concat(other: Array<T>): beetle.querying.ArrayQuery<T>; /** * Determines whether a array contains a specified element. * @param item The value to locate in the array. * @returns true if the source array contains an element that has the specified value; otherwise, false. */ contains(item: T): boolean; /** * Produces the set difference of two arrays. * @param other An array whose elements that also occur in the first array will cause those elements to be removed from the returned array. */ except(other: Array<T>): beetle.querying.ArrayQuery<T>; /** * Correlates the elements of two arrays based on equality of keys and groups the results. * @param other The array to join to the query array. * @param thisKey Key selector for query's array. * @param otherKey Key selector for other array. * @param selector A function to create a result element from an element from the first array and a collection of matching elements from the other array. */ groupJoin<TOther>(other: Array<TOther>, thisKey: string, otherKey: string, selector: (entity: T, other: Array<TOther>) => any): beetle.querying.ArrayQuery<any>; groupJoin<TOther, TKey>(other: Array<TOther>, thisKey: (entity: T) => TKey, otherKey: (entity: TOther) => TKey, selector: (entity: T, other: Array<TOther>) => any): beetle.querying.ArrayQuery<any>; groupJoin<TOther, TResult>(other: Array<TOther>, thisKey: string, otherKey: string, selector: (entity: T, other: Array<TOther>) => TResult): beetle.querying.ArrayQuery<TResult>; groupJoin<TOther, TKey, TResult>(other: Array<TOther>, thisKey: (entity: T) => TKey, otherKey: (entity: TOther) => TKey, selector: (entity: T, other: Array<TOther>) => TResult): beetle.querying.ArrayQuery<TResult>; /** * Correlates the elements of two arrays based on matching keys. * @param other The array to join to the query array. * @param thisKey Key selector for query's array. * @param otherKey Key selector for other array. * @param selector A function to create a result element from two matching elements. */ join<TOther>(other: Array<TOther>, thisKey: string, otherKey: string, selector: (entity: T, other: TOther) => any): beetle.querying.ArrayQuery<any>; join<TOther, TKey>(other: Array<TOther>, thisKey: (entity: T) => TKey, otherKey: (entity: TOther) => TKey, selector: (entity: T, other: TOther) => any): beetle.querying.ArrayQuery<any>; join<TOther, TResult>(other: Array<TOther>, thisKey: string, otherKey: string, selector: (entity: T, other: TOther) => TResult): beetle.querying.ArrayQuery<TResult>; join<TOther, TKey, TResult>(other: Array<TOther>, thisKey: (entity: T) => TKey, otherKey: (entity: TOther) => TKey, selector: (entity: T, other: TOther) => TResult): beetle.querying.ArrayQuery<TResult>; /** * Correlates the elements of two arrays based on matching keys. * @param other The array to join to the query array. * @param thisKey Key selector for query's array. * @param otherKey Key selector for other array. * @param selector A function to create a result element from two matching elements. */ innerJoin<TOther>(other: Array<TOther>, thisKey: string, otherKey: string, selector: (entity: T, other: TOther) => any): beetle.querying.ArrayQuery<any>; innerJoin<TOther, TKey>(other: Array<TOther>, thisKey: (entity: T) => TKey, otherKey: (entity: TOther) => TKey, selector: (entity: T, other: TOther) => any): beetle.querying.ArrayQuery<any>; innerJoin<TOther, TResult>(other: Array<TOther>, thisKey: string, otherKey: string, selector: (entity: T, other: TOther) => TResult): beetle.querying.ArrayQuery<TResult>; innerJoin<TOther, TKey, TResult>(other: Array<TOther>, thisKey: (entity: T) => TKey, otherKey: (entity: TOther) => TKey, selector: (entity: T, other: TOther) => TResult): beetle.querying.ArrayQuery<TResult>; /** * Correlates the elements of two arrays based on matching keys (query array items are taken even they do not have matching item on other array). * @param other The array to join to the query array. * @param thisKey Key selector for query's array. * @param otherKey Key selector for other array. * @param selector A function to create a result element from two matching elements. */ leftJoin<TOther>(other: Array<TOther>, thisKey: string, otherKey: string, selector: (entity: T, other: TOther) => any): beetle.querying.ArrayQuery<any>; leftJoin<TOther, TKey>(other: Array<TOther>, thisKey: (entity: T) => TKey, otherKey: (entity: TOther) => TKey, selector: (entity: T, other: TOther) => any): beetle.querying.ArrayQuery<any>; leftJoin<TOther, TResult>(other: Array<TOther>, thisKey: string, otherKey: string, selector: (entity: T, other: TOther) => TResult): beetle.querying.ArrayQuery<TResult>; leftJoin<TOther, TKey, TResult>(other: Array<TOther>, thisKey: (entity: T) => TKey, otherKey: (entity: TOther) => TKey, selector: (entiy: T, other: TOther) => TResult): beetle.querying.ArrayQuery<TResult>; /** * Correlates the elements of two arrays based on matching keys (other array items are taken even they do not have matching item on query array). * @param other The array to join to the query array. * @param thisKey Key selector for query's array. * @param otherKey Key selector for other array. * @param selector A function to create a result element from two matching elements. */ rightJoin<TOther>(other: Array<TOther>, thisKey: string, otherKey: string, selector: (entity: T, other: TOther) => any): beetle.querying.ArrayQuery<any>; rightJoin<TOther, TKey>(other: Array<TOther>, thisKey: (entity: T) => TKey, otherKey: (entity: TOther) => TKey, selector: (entity: T, other: TOther) => any): beetle.querying.ArrayQuery<any>; rightJoin<TOther, TResult>(other: Array<TOther>, thisKey: string, otherKey: string, selector: (entity: T, other: TOther) => TResult): beetle.querying.ArrayQuery<TResult>; rightJoin<TOther, TKey, TResult>(other: Array<TOther>, thisKey: (entity: T) => TKey, otherKey: (entity: TOther) => TKey, selector: (entity: T, other: TOther) => TResult): beetle.querying.ArrayQuery<TResult>; /** * Correlates the elements of two arrays based on matching keys (all items are taken cross-multiplied). * @param other The array to join to the query array. * @param thisKey Key selector for query's array. * @param otherKey Key selector for other array. * @param selector A function to create a result element from two matching elements. */ fullJoin<TOther>(other: Array<TOther>, thisKey: string, otherKey: string, selector: (entity: T, other: TOther) => any): beetle.querying.ArrayQuery<any>; fullJoin<TOther, TKey>(other: Array<TOther>, thisKey: (entity: T) => TKey, otherKey: (entity: TOther) => TKey, selector: (entity: T, other: TOther) => any): beetle.querying.ArrayQuery<any>; fullJoin<TOther, TResult>(other: Array<TOther>, thisKey: string, otherKey: string, selector: (entity: T, other: TOther) => TResult): beetle.querying.ArrayQuery<TResult>; fullJoin<TOther, TKey, TResult>(other: Array<TOther>, thisKey: (entity: T) => TKey, otherKey: (entity: TOther) => TKey, selector: (entity: T, other: TOther) => TResult): beetle.querying.ArrayQuery<TResult>; /** * Correlates the elements of two arrays based on matching keys (all items are taken cross-multiplied). * @param other The array to join to the query array. * @param thisKey Key selector for query's array. * @param otherKey Key selector for other array. * @param selector A function to create a result element from two matching elements. */ crossJoin<TOther>(other: Array<TOther>, selector: (entity: T, other: TOther) => any): beetle.querying.ArrayQuery<any>; crossJoin<TOther, TResult>(other: Array<TOther>, selector: (entity: T, other: TOther) => TResult): beetle.querying.ArrayQuery<TResult>; /** * Produces the set intersection of two arrays. * @param other The array whose distinct elements that also appear in the first array will be returned. */ intersect(other: Array<T>): beetle.querying.ArrayQuery<T>; /** * Determines whether two arrays are equal by comparing the elements. * @param other An array to compare to the query array. */ sequenceEqual(other: Array<T>): boolean; /** * Creates a array from query array according to specified key selector and element selector functions. * @param keySelector A function to extract a key from each element. * @param elementSelector An array to compare to the query array. */ toLookup(keySelector: (entity: T) => any, elementSelector: (group: beetle.interfaces.Grouping<T, any>) => any): beetle.querying.ArrayQuery<any>; toLookup<TKey>(keySelector: (entity: T) => TKey, elementSelector: (group: beetle.interfaces.Grouping<T, any>) => any): beetle.querying.ArrayQuery<any>; toLookup<TKey, TResult>(keySelector: (entity: T) => TKey, elementSelector: (group: beetle.interfaces.Grouping<T, TKey>) => any): beetle.querying.ArrayQuery<TResult>; /** * Produces the set union of two arrays' distinct elements. * @param other An array whose distinct elements form the second set for the union. */ union(other: Array<T>): beetle.querying.ArrayQuery<T>; /** * Applies a specified function to the corresponding elements of two arrays, producing a array of the results. * @param other The second array to merge. * @param selector A function that specifies how to merge the elements from the two arrays. */ zip<TOther>(other: Array<TOther>, selector: (entity: T, other: TOther) => any): beetle.querying.ArrayQuery<any>; zip<TOther, TResult>(other: Array<TOther>, selector: (entity: T, other: TOther) => TResult): beetle.querying.ArrayQuery<TResult>; /** Register forEach method to Array */ forEach(callback: (item: T) => void); } interface ArrayConstructor { /** Register static range method to Array */ range(start: number, count: number): Array<number>; /** Register static repeat method to Array */ repeat(item: any, count: number): Array<number>; } } /** Re-export all beetle module. */ export = beetle; /** Also re-export as namespace to support UMD. */ export as namespace beetle;
the_stack
import { ErrorConstant } from '@remirror/core-constants'; import { invariant, isFunction, isNullOrUndefined, isString } from '@remirror/core-helpers'; import type { EditorState, EditorStateProps, GetAttributesProps, Mark, MarkType, MarkTypeProps, NodeTypeProps, RegExpProps, TransactionProps, } from '@remirror/core-types'; import { InputRule } from '@remirror/pm/inputrules'; import { NodeType } from '@remirror/pm/model'; import { markActiveInRange } from '@remirror/pm/suggest'; export interface BeforeDispatchProps extends TransactionProps { /** * The matches returned by the regex. */ match: string[]; /** * The start position of the most recently typed character. */ start: number; /** * The end position of the most recently typed character. */ end: number; } export interface BaseInputRuleProps extends ShouldSkip { /** * A method which can be used to add more steps to the transaction after the * input rule update but before the editor has dispatched to update to a new * state. * * ```ts * import { nodeInputRule } from 'remirror'; * * nodeInputRule({ * type, * regexp: /abc/, * beforeDispatch?: (props: BeforeDispatchProps) => void; : (tr) * => tr.insertText('hello') * }); * ``` */ beforeDispatch?: (props: BeforeDispatchProps) => void; /** * Ignore the match when all characters in the capture group are whitespace. * * This helps stop situations from occurring where the a capture group matches * but you don't want an update if it's all whitespace. * * @default false */ ignoreWhitespace?: boolean; /** * Update the capture group. This is needed sometimes because lookbehind regex * don't work in some browsers and can't be transpiled or polyfilled. This * method allows the developer to update the details of the matching input * rule details before it is acted on. * * The capture group refers to the first match within the matching bracket. * * ```ts * abc.match(/ab(c)/) => ['abc', 'a'] * ``` * * In the above example the capture group is the first index so in this case * the captured text would be `a`. * * @param captured - All the details about the capture to allow for full * customisation. * @returns updated details or undefined to leave unchanged. * * See https://github.com/remirror/remirror/issues/574#issuecomment-678700121 * for more context. */ updateCaptured?: UpdateCaptured; } type UpdateCaptured = (captured: UpdateCaptureTextProps) => Partial<UpdateCaptureTextProps>; export interface NodeInputRuleProps extends Partial<GetAttributesProps>, RegExpProps, NodeTypeProps, BaseInputRuleProps {} export interface PlainInputRuleProps extends RegExpProps, BaseInputRuleProps { /** * A function that transforms the match into the desired value. * * Return `null` or `undefined` to invalidate the match. */ transformMatch: (match: string[]) => string | null | undefined; } export interface UpdateCaptureTextProps { /** * The first capture group from the matching input rule. */ captureGroup: string | undefined; /** * The text of the full match which was received. */ fullMatch: string; /** * The starting position of the match relative to the `doc`. */ start: number; /** * The end position of the match relative to the `doc`. */ end: number; } interface MarkInputRuleProps extends Partial<GetAttributesProps>, RegExpProps, MarkTypeProps, BaseInputRuleProps {} /** * Creates an input rule based on the provided regex for the provided mark type. */ export function markInputRule(props: MarkInputRuleProps): SkippableInputRule { const { regexp, type, getAttributes, ignoreWhitespace = false, beforeDispatch, updateCaptured, shouldSkip, invalidMarks, } = props; let markType: MarkType | undefined; const rule: SkippableInputRule = new InputRule(regexp, (state, match, start, end) => { const { tr, schema } = state; if (!markType) { markType = isString(type) ? schema.marks[type] : type; invariant(markType, { code: ErrorConstant.SCHEMA, message: `Mark type: ${type} does not exist on the current schema.`, }); } let captureGroup = match[1]; let fullMatch = match[0]; // These are the attributes which are added to the mark and they can be // obtained from the match if a function is provided. const details = gatherDetails({ captureGroup, fullMatch, end, start, rule, state, ignoreWhitespace, invalidMarks, shouldSkip, updateCaptured, }); if (!details) { return null; } ({ start, end, captureGroup, fullMatch } = details); const attributes = isFunction(getAttributes) ? getAttributes(match) : getAttributes; let markEnd = end; let initialStoredMarks: Mark[] = []; if (captureGroup) { const startSpaces = fullMatch.search(/\S/); const textStart = start + fullMatch.indexOf(captureGroup); const textEnd = textStart + captureGroup.length; initialStoredMarks = tr.storedMarks ?? []; if (textEnd < end) { tr.delete(textEnd, end); } if (textStart > start) { tr.delete(start + startSpaces, textStart); } markEnd = start + startSpaces + captureGroup.length; } tr.addMark(start, markEnd, markType.create(attributes)); // Make sure not to reactivate any marks which had previously been // deactivated. By keeping track of the initial stored marks we are able to // discard any unintended consequences of deleting text and adding it again. tr.setStoredMarks(initialStoredMarks); // Allow the caller of this method to update the transaction before it is // returned and dispatched by ProseMirror. beforeDispatch?.({ tr, match, start, end }); return tr; }); return rule; } /** * Creates a node input rule based on the provided regex for the provided node * type. * * Input rules transform content as the user types based on whether a match is * found with a sequence of characters. */ export function nodeInputRule(props: NodeInputRuleProps): SkippableInputRule { const { regexp, type, getAttributes, beforeDispatch, shouldSkip, ignoreWhitespace = false, updateCaptured, invalidMarks, } = props; const rule: SkippableInputRule = new InputRule(regexp, (state, match, start, end) => { const attributes = isFunction(getAttributes) ? getAttributes(match) : getAttributes; const { tr, schema } = state; const nodeType: NodeType = isString(type) ? schema.nodes[type] : type; let captureGroup = match[1]; let fullMatch = match[0]; // These are the attributes which are added to the mark and they can be // obtained from the match if a function is provided. const details = gatherDetails({ captureGroup, fullMatch, end, start, rule, state, ignoreWhitespace, invalidMarks, shouldSkip, updateCaptured, }); if (!details) { return null; } ({ start, end, captureGroup, fullMatch } = details); invariant(nodeType, { code: ErrorConstant.SCHEMA, message: `No node exists for ${type} in the schema.`, }); const content = nodeType.createAndFill(attributes); if (content) { tr.replaceRangeWith(nodeType.isBlock ? tr.doc.resolve(start).before() : start, end, content); beforeDispatch?.({ tr, match: [fullMatch, captureGroup ?? ''], start, end }); } return tr; }); return rule; } /** * Creates a plain rule based on the provided regex. You can see this being used * in the `@remirror/extension-emoji` when it is setup to use plain text. */ export function plainInputRule(props: PlainInputRuleProps): SkippableInputRule { const { regexp, transformMatch, beforeDispatch, shouldSkip, ignoreWhitespace = false, updateCaptured, invalidMarks, } = props; const rule: SkippableInputRule = new InputRule(regexp, (state, match, start, end) => { const value = transformMatch(match); if (isNullOrUndefined(value)) { return null; } const { tr, schema } = state; let captureGroup = match[1]; let fullMatch = match[0]; // These are the attributes which are added to the mark and they can be // obtained from the match if a function is provided. const details = gatherDetails({ captureGroup, fullMatch, end, start, rule, state, ignoreWhitespace, invalidMarks, shouldSkip, updateCaptured, }); if (!details) { return null; } ({ start, end, captureGroup, fullMatch } = details); if (value === '') { tr.delete(start, end); } else { tr.replaceWith(start, end, schema.text(value)); } beforeDispatch?.({ tr, match, start, end }); return tr; }); return rule; } export interface ShouldSkipProps extends EditorStateProps, UpdateCaptureTextProps { /** The type of input rule that has been activated */ ruleType: 'mark' | 'node' | 'plain'; } interface ShouldSkip { /** * Every input rule calls this function before deciding whether or not to run. * * This is run for every successful input rule match to check if there are any * reasons to prevent it from running. * * In particular it is so that the input rule only runs when there are no * active checks that prevent it from doing so. * * - Other extension can register a `shouldSkip` handler * - Every time the input rule is running it makes sure it isn't blocked. */ shouldSkip?: ShouldSkipFunction; /** * A list of marks which if existing in the provided range should invalidate * the range. */ invalidMarks?: string[]; } /** * A function which is called to check whether an input rule should be skipped. * * - When it returns false then it won't be skipped. * - When it returns true then it will be skipped. */ export type ShouldSkipFunction = (props: ShouldSkipProps) => boolean; /** * An input rule which can have a `shouldSkip` property that returns true when * the input rule should be skipped. */ export type SkippableInputRule = ShouldSkip & InputRule; interface GatherDetailsProps extends Omit<BaseInputRuleProps, 'beforeDispatch'> { /** * The first capture group from the matching input rule. */ captureGroup: string | undefined; /** * The text of the full match which was received. */ fullMatch: string | undefined; /** * The starting position of the match relative to the `doc`. */ start: number; /** * The end position of the match relative to the `doc`. */ end: number; /** * The current editor state. */ state: EditorState; /** * The input rule being run. This can have global skip handlers attached. */ rule: SkippableInputRule; } /** * This is a monster of a function. * * TODO make it make sense. */ function gatherDetails({ captureGroup, fullMatch, end, start, rule, ignoreWhitespace, shouldSkip, updateCaptured, state, invalidMarks, }: GatherDetailsProps): UpdateCaptureTextProps | null { if (fullMatch == null) { return null; } // Update the internal values with the user provided method. const details = updateCaptured?.({ captureGroup, fullMatch, start, end }) ?? {}; // Store the updated values or the original. captureGroup = details.captureGroup ?? captureGroup; fullMatch = details.fullMatch ?? fullMatch; start = details.start ?? start; end = details.end ?? end; const $from = state.doc.resolve(start); const $to = state.doc.resolve(end); if ( // Skip when the range contains an excluded mark. (invalidMarks && markActiveInRange({ $from, $to }, invalidMarks)) || (rule.invalidMarks && markActiveInRange({ $from, $to }, rule.invalidMarks)) || // Skip pure whitespace updates (ignoreWhitespace && captureGroup?.trim() === '') || // Skip when configured to do shouldSkip?.({ state, captureGroup, fullMatch, start, end, ruleType: 'mark' }) || rule.shouldSkip?.({ state, captureGroup, fullMatch, start, end, ruleType: 'mark' }) ) { return null; } return { captureGroup, end, fullMatch, start }; }
the_stack
import { Tabs } from "./tabs"; import { Events } from "./events"; export namespace Windows { /** * The type of browser window this is. Under some circumstances a Window may not be assigned type property, * for example when querying closed windows from the $(ref:sessions) API. */ type WindowType = "normal" | "popup" | "panel" | "app" | "devtools"; /** * The state of this browser window. Under some circumstances a Window may not be assigned state property, * for example when querying closed windows from the $(ref:sessions) API. */ type WindowState = "normal" | "minimized" | "maximized" | "fullscreen" | "docked"; interface Window { /** * The ID of the window. Window IDs are unique within a browser session. Under some circumstances a Window may not be * assigned an ID, for example when querying windows using the $(ref:sessions) API, in which case a session ID may be * present. * Optional. */ id?: number; /** * Whether the window is currently the focused window. */ focused: boolean; /** * The offset of the window from the top edge of the screen in pixels. Under some circumstances a Window may not be * assigned top property, for example when querying closed windows from the $(ref:sessions) API. * Optional. */ top?: number; /** * The offset of the window from the left edge of the screen in pixels. Under some circumstances a Window may not be * assigned left property, for example when querying closed windows from the $(ref:sessions) API. * Optional. */ left?: number; /** * The width of the window, including the frame, in pixels. Under some circumstances a Window may not be assigned width * property, for example when querying closed windows from the $(ref:sessions) API. * Optional. */ width?: number; /** * The height of the window, including the frame, in pixels. Under some circumstances a Window may not be assigned height * property, for example when querying closed windows from the $(ref:sessions) API. * Optional. */ height?: number; /** * Array of $(ref:tabs.Tab) objects representing the current tabs in the window. * Optional. */ tabs?: Tabs.Tab[]; /** * Whether the window is incognito. */ incognito: boolean; /** * The type of browser window this is. * Optional. */ type?: WindowType; /** * The state of this browser window. * Optional. */ state?: WindowState; /** * Whether the window is set to be always on top. */ alwaysOnTop: boolean; /** * The session ID used to uniquely identify a Window obtained from the $(ref:sessions) API. * Optional. */ sessionId?: string; /** * The title of the window. Read-only. * Optional. */ title?: string; } /** * Specifies what type of browser window to create. The 'panel' and 'detached_panel' types create a popup unless the * '--enable-panels' flag is set. */ type CreateType = "normal" | "popup" | "panel" | "detached_panel"; /** * Specifies whether the $(ref:windows.Window) returned should contain a list of the $(ref:tabs.Tab) objects. */ interface GetInfo { /** * If true, the $(ref:windows.Window) returned will have a <var>tabs</var> property that contains a list of the $(ref:tabs. * Tab) objects. The <code>Tab</code> objects only contain the <code>url</code>, <code>title</code> and <code> * favIconUrl</code> properties if the extension's manifest file includes the <code>"tabs"</code> permission. * Optional. */ populate?: boolean; } /** * Specifies properties used to filter the $(ref:windows.Window) returned and to determine whether they should contain a * list of the $(ref:tabs.Tab) objects. */ interface GetAllGetInfoType extends GetInfo { /** * If set, the $(ref:windows.Window) returned will be filtered based on its type. If unset the default filter is set to * <code>['app', 'normal', 'panel', 'popup']</code>, with <code>'app'</code> and <code>'panel'</code> * window types limited to the extension's own windows. * Optional. */ windowTypes?: WindowType[]; } interface CreateCreateDataType { /** * A URL or array of URLs to open as tabs in the window. Fully-qualified URLs must include a scheme (i.e. 'http://www. * google.com', not 'www.google.com'). Relative URLs will be relative to the current page within the extension. * Defaults to the New Tab Page. * Optional. */ url?: string | string[]; /** * The id of the tab for which you want to adopt to the new window. * Optional. */ tabId?: number; /** * The number of pixels to position the new window from the left edge of the screen. If not specified, * the new window is offset naturally from the last focused window. This value is ignored for panels. * Optional. */ left?: number; /** * The number of pixels to position the new window from the top edge of the screen. If not specified, * the new window is offset naturally from the last focused window. This value is ignored for panels. * Optional. */ top?: number; /** * The width in pixels of the new window, including the frame. If not specified defaults to a natural width. * Optional. */ width?: number; /** * The height in pixels of the new window, including the frame. If not specified defaults to a natural height. * Optional. */ height?: number; /** * If true, the new window will be focused. If false, the new window will be opened in the background and the currently * focused window will stay focused. Defaults to true. * Optional. */ focused?: boolean; /** * Whether the new window should be an incognito window. * Optional. */ incognito?: boolean; /** * Specifies what type of browser window to create. The 'panel' and 'detached_panel' types create a popup unless the * '--enable-panels' flag is set. * Optional. */ type?: CreateType; /** * The initial state of the window. The 'minimized', 'maximized' and 'fullscreen' states cannot be combined with 'left', * 'top', 'width' or 'height'. * Optional. */ state?: WindowState; /** * Allow scripts to close the window. * Optional. */ allowScriptsToClose?: boolean; /** * The CookieStoreId to use for all tabs that were created when the window is opened. * Optional. */ cookieStoreId?: string; /** * A string to add to the beginning of the window title. * Optional. */ titlePreface?: string; } interface UpdateUpdateInfoType { /** * The offset from the left edge of the screen to move the window to in pixels. This value is ignored for panels. * Optional. */ left?: number; /** * The offset from the top edge of the screen to move the window to in pixels. This value is ignored for panels. * Optional. */ top?: number; /** * The width to resize the window to in pixels. This value is ignored for panels. * Optional. */ width?: number; /** * The height to resize the window to in pixels. This value is ignored for panels. * Optional. */ height?: number; /** * If true, brings the window to the front. If false, brings the next window in the z-order to the front. * Optional. */ focused?: boolean; /** * If true, causes the window to be displayed in a manner that draws the user's attention to the window, * without changing the focused window. The effect lasts until the user changes focus to the window. * This option has no effect if the window already has focus. Set to false to cancel a previous draw attention request. * Optional. */ drawAttention?: boolean; /** * The new state of the window. The 'minimized', 'maximized' and 'fullscreen' states cannot be combined with 'left', 'top', * 'width' or 'height'. * Optional. */ state?: WindowState; /** * A string to add to the beginning of the window title. * Optional. */ titlePreface?: string; } interface Static { /** * Gets details about a window. * * @param windowId * @param getInfo Optional. */ get(windowId: number, getInfo?: GetInfo): Promise<Window>; /** * Gets the $(topic:current-window)[current window]. * * @param getInfo Optional. */ getCurrent(getInfo?: GetInfo): Promise<Window>; /** * Gets the window that was most recently focused &mdash; typically the window 'on top'. * * @param getInfo Optional. */ getLastFocused(getInfo?: GetInfo): Promise<Window>; /** * Gets all windows. * * @param getInfo Optional. Specifies properties used to filter the $(ref:windows.Window) * returned and to determine whether they should contain a list of the $(ref:tabs.Tab) objects. */ getAll(getInfo?: GetAllGetInfoType): Promise<Window[]>; /** * Creates (opens) a new browser with any optional sizing, position or default URL provided. * * @param createData Optional. */ create(createData?: CreateCreateDataType): Promise<Window>; /** * Updates the properties of a window. Specify only the properties that you want to change; unspecified properties will be * left unchanged. * * @param windowId * @param updateInfo */ update(windowId: number, updateInfo: UpdateUpdateInfoType): Promise<Window>; /** * Removes (closes) a window, and all the tabs inside it. * * @param windowId */ remove(windowId: number): Promise<void>; /** * Fired when a window is created. * * @param window Details of the window that was created. */ onCreated: Events.Event<(window: Window) => void>; /** * Fired when a window is removed (closed). * * @param windowId ID of the removed window. */ onRemoved: Events.Event<(windowId: number) => void>; /** * Fired when the currently focused window changes. Will be $(ref:windows.WINDOW_ID_NONE) * if all browser windows have lost focus. Note: On some Linux window managers, WINDOW_ID_NONE will always be sent * immediately preceding a switch from one browser window to another. * * @param windowId ID of the newly focused window. */ onFocusChanged: Events.Event<(windowId: number) => void>; /** * The windowId value that represents the absence of a browser window. */ WINDOW_ID_NONE: -1; /** * The windowId value that represents the $(topic:current-window)[current window]. */ WINDOW_ID_CURRENT: -2; } }
the_stack
import * as msRest from "@azure/ms-rest-js"; import * as Mappers from "./mappers"; import { Operation } from "./operation"; import * as Parameters from "./parameters"; const serializer = new msRest.Serializer(Mappers, true); // specifications for new method group start const tableQueryOperationSpec: msRest.OperationSpec = { httpMethod: "GET", path: "Tables", urlParameters: [Parameters.url], queryParameters: [ Parameters.nextTableName, Parameters.format, Parameters.top, Parameters.select, Parameters.filter ], headerParameters: [ Parameters.version, Parameters.requestId, Parameters.dataServiceVersion ], responses: { 200: { bodyMapper: Mappers.TableQueryResponse, headersMapper: Mappers.TableQueryHeaders }, default: {} }, isXML: true, serializer }; const tableCreateOperationSpec: msRest.OperationSpec = { httpMethod: "POST", path: "Tables", urlParameters: [Parameters.url], queryParameters: [Parameters.format], headerParameters: [ Parameters.version, Parameters.requestId, Parameters.dataServiceVersion, Parameters.responsePreference ], requestBody: { parameterPath: "tableProperties", mapper: { ...Mappers.TableProperties, required: true } }, contentType: "application/json;odata=nometadata; charset=utf-8", responses: { 201: { bodyMapper: Mappers.TableResponse, headersMapper: Mappers.TableCreateHeaders }, 204: { headersMapper: Mappers.TableCreateHeaders }, default: { bodyMapper: Mappers.TableServiceError } }, isXML: true, serializer }; const tableBatchOperationSpec: msRest.OperationSpec = { httpMethod: "POST", path: "$batch", urlParameters: [Parameters.url], headerParameters: [ Parameters.version, Parameters.requestId, Parameters.dataServiceVersion, Parameters.multipartContentType, Parameters.contentLength ], requestBody: { parameterPath: "body", mapper: { required: true, serializedName: "body", type: { name: "Stream" } } }, contentType: "application/json;odata=nometadata; charset=utf-8", responses: { 202: { bodyMapper: { serializedName: "Stream", type: { name: "Stream" } }, headersMapper: Mappers.TableBatchHeaders }, default: { bodyMapper: Mappers.TableServiceError } }, isXML: true, serializer }; const tableDeleteOperationSpec: msRest.OperationSpec = { httpMethod: "DELETE", path: "Tables('{table}')", urlParameters: [Parameters.url, Parameters.table], headerParameters: [Parameters.version, Parameters.requestId], responses: { 204: { headersMapper: Mappers.TableDeleteHeaders }, default: { bodyMapper: Mappers.TableServiceError } }, isXML: true, serializer }; const tableQueryEntitiesOperationSpec: msRest.OperationSpec = { httpMethod: "GET", path: "{table}()", urlParameters: [Parameters.url, Parameters.table], queryParameters: [ Parameters.timeout, Parameters.nextPartitionKey, Parameters.nextRowKey, Parameters.format, Parameters.top, Parameters.select, Parameters.filter ], headerParameters: [ Parameters.version, Parameters.requestId, Parameters.dataServiceVersion ], responses: { 200: { bodyMapper: { serializedName: "Stream", type: { name: "Stream" } }, headersMapper: Mappers.TableQueryEntitiesHeaders }, default: { bodyMapper: Mappers.TableServiceError } }, isXML: true, serializer }; const tableQueryEntitiesWithPartitionAndRowKeyOperationSpec: msRest.OperationSpec = { httpMethod: "GET", path: "{table}(PartitionKey='{partitionKey}',RowKey='{rowKey}')", urlParameters: [ Parameters.url, Parameters.table, Parameters.partitionKey, Parameters.rowKey ], queryParameters: [ Parameters.timeout, Parameters.format, Parameters.select, Parameters.filter ], headerParameters: [ Parameters.version, Parameters.requestId, Parameters.dataServiceVersion ], responses: { 200: { bodyMapper: { serializedName: "Stream", type: { name: "Stream" } }, headersMapper: Mappers.TableQueryEntitiesWithPartitionAndRowKeyHeaders }, default: { bodyMapper: Mappers.TableServiceError } }, isXML: true, serializer }; const tableUpdateEntityOperationSpec: msRest.OperationSpec = { httpMethod: "PUT", path: "{table}(PartitionKey='{partitionKey}',RowKey='{rowKey}')", urlParameters: [ Parameters.url, Parameters.table, Parameters.partitionKey, Parameters.rowKey ], queryParameters: [Parameters.timeout, Parameters.format], headerParameters: [ Parameters.version, Parameters.requestId, Parameters.dataServiceVersion, Parameters.ifMatch0 ], requestBody: { parameterPath: ["options", "tableEntityProperties"], mapper: { serializedName: "tableEntityProperties", type: { name: "Dictionary", value: { type: { name: "Object" } } } } }, responses: { 204: { headersMapper: Mappers.TableUpdateEntityHeaders }, default: { bodyMapper: Mappers.TableServiceError } }, isXML: true, serializer }; const tableMergeEntityOperationSpec: msRest.OperationSpec = { httpMethod: "PATCH", path: "{table}(PartitionKey='{partitionKey}',RowKey='{rowKey}')", urlParameters: [ Parameters.url, Parameters.table, Parameters.partitionKey, Parameters.rowKey ], queryParameters: [Parameters.timeout, Parameters.format], headerParameters: [ Parameters.version, Parameters.requestId, Parameters.dataServiceVersion, Parameters.ifMatch0 ], requestBody: { parameterPath: ["options", "tableEntityProperties"], mapper: { serializedName: "tableEntityProperties", type: { name: "Dictionary", value: { type: { name: "Object" } } } } }, responses: { 204: { headersMapper: Mappers.TableMergeEntityHeaders }, default: { bodyMapper: Mappers.TableServiceError } }, isXML: true, serializer }; const tableDeleteEntityOperationSpec: msRest.OperationSpec = { httpMethod: "DELETE", path: "{table}(PartitionKey='{partitionKey}',RowKey='{rowKey}')", urlParameters: [ Parameters.url, Parameters.table, Parameters.partitionKey, Parameters.rowKey ], queryParameters: [Parameters.timeout, Parameters.format], headerParameters: [ Parameters.version, Parameters.requestId, Parameters.dataServiceVersion, Parameters.ifMatch1 ], responses: { 204: { headersMapper: Mappers.TableDeleteEntityHeaders }, default: { bodyMapper: Mappers.TableServiceError } }, isXML: true, serializer }; const tableMergeEntityWithMergeOperationSpec: msRest.OperationSpec = { httpMethod: "POST", path: "{table}(PartitionKey='{partitionKey}',RowKey='{rowKey}')", urlParameters: [ Parameters.url, Parameters.table, Parameters.partitionKey, Parameters.rowKey ], queryParameters: [Parameters.timeout, Parameters.format], headerParameters: [ Parameters.version, Parameters.requestId, Parameters.dataServiceVersion, Parameters.ifMatch0 ], requestBody: { parameterPath: ["options", "tableEntityProperties"], mapper: { serializedName: "tableEntityProperties", type: { name: "Dictionary", value: { type: { name: "Object" } } } } }, responses: { 204: { headersMapper: Mappers.TableMergeEntityWithMergeHeaders }, default: { bodyMapper: Mappers.TableServiceError } }, isXML: true, serializer }; const tableInsertEntityOperationSpec: msRest.OperationSpec = { httpMethod: "POST", path: "{table}", urlParameters: [Parameters.url, Parameters.table], queryParameters: [Parameters.timeout, Parameters.format], headerParameters: [ Parameters.version, Parameters.requestId, Parameters.dataServiceVersion, Parameters.responsePreference ], requestBody: { parameterPath: ["options", "tableEntityProperties"], mapper: { serializedName: "tableEntityProperties", type: { name: "Dictionary", value: { type: { name: "Object" } } } } }, contentType: "application/json;odata=nometadata; charset=utf-8", responses: { 201: { bodyMapper: { serializedName: "Stream", type: { name: "Stream" } }, headersMapper: Mappers.TableInsertEntityHeaders }, 204: { headersMapper: Mappers.TableInsertEntityHeaders }, default: { bodyMapper: Mappers.TableServiceError } }, isXML: true, serializer }; const tableGetAccessPolicyOperationSpec: msRest.OperationSpec = { httpMethod: "GET", path: "{table}", urlParameters: [Parameters.url, Parameters.table], queryParameters: [Parameters.timeout, Parameters.comp0], headerParameters: [Parameters.version, Parameters.requestId], responses: { 200: { bodyMapper: { xmlElementName: "SignedIdentifier", serializedName: "SignedIdentifiers", type: { name: "Sequence", element: { type: { name: "Composite", className: "SignedIdentifier" } } } }, headersMapper: Mappers.TableGetAccessPolicyHeaders }, default: { bodyMapper: Mappers.TableServiceError } }, isXML: true, serializer }; const tableSetAccessPolicyOperationSpec: msRest.OperationSpec = { httpMethod: "PUT", path: "{table}", urlParameters: [Parameters.url, Parameters.table], queryParameters: [Parameters.timeout, Parameters.comp0], headerParameters: [Parameters.version, Parameters.requestId], requestBody: { parameterPath: ["options", "tableAcl"], mapper: { xmlName: "SignedIdentifiers", xmlElementName: "SignedIdentifier", serializedName: "tableAcl", type: { name: "Sequence", element: { type: { name: "Composite", className: "SignedIdentifier" } } } } }, contentType: "application/xml; charset=utf-8", responses: { 204: { headersMapper: Mappers.TableSetAccessPolicyHeaders }, default: { bodyMapper: Mappers.TableServiceError } }, isXML: true, serializer }; // specifications for new method group start const serviceSetPropertiesOperationSpec: msRest.OperationSpec = { httpMethod: "PUT", urlParameters: [Parameters.url], queryParameters: [Parameters.timeout, Parameters.restype, Parameters.comp1], headerParameters: [Parameters.version, Parameters.requestId], requestBody: { parameterPath: "tableServiceProperties", mapper: { ...Mappers.TableServiceProperties, required: true } }, contentType: "application/xml; charset=utf-8", responses: { 202: { headersMapper: Mappers.ServiceSetPropertiesHeaders }, default: { bodyMapper: Mappers.TableServiceError } }, isXML: true, serializer }; const serviceGetPropertiesOperationSpec: msRest.OperationSpec = { httpMethod: "GET", urlParameters: [Parameters.url], queryParameters: [Parameters.restype, Parameters.comp1, Parameters.timeout], headerParameters: [Parameters.version, Parameters.requestId], responses: { 200: { bodyMapper: Mappers.TableServiceProperties, headersMapper: Mappers.ServiceGetPropertiesHeaders }, default: { bodyMapper: Mappers.TableServiceError } }, isXML: true, serializer }; const serviceGetStatisticsOperationSpec: msRest.OperationSpec = { httpMethod: "GET", urlParameters: [Parameters.url], queryParameters: [Parameters.timeout, Parameters.restype, Parameters.comp2], headerParameters: [Parameters.version, Parameters.requestId], responses: { 200: { bodyMapper: Mappers.TableServiceStats, headersMapper: Mappers.ServiceGetStatisticsHeaders }, default: { bodyMapper: Mappers.TableServiceError } }, isXML: true, serializer }; const Specifications: { [key: number]: msRest.OperationSpec } = {}; Specifications[Operation.Table_Query] = tableQueryOperationSpec; Specifications[Operation.Table_Create] = tableCreateOperationSpec; Specifications[Operation.Table_Batch] = tableBatchOperationSpec; Specifications[Operation.Table_Delete] = tableDeleteOperationSpec; Specifications[Operation.Table_QueryEntities] = tableQueryEntitiesOperationSpec; Specifications[ Operation.Table_QueryEntitiesWithPartitionAndRowKey ] = tableQueryEntitiesWithPartitionAndRowKeyOperationSpec; Specifications[Operation.Table_UpdateEntity] = tableUpdateEntityOperationSpec; Specifications[Operation.Table_MergeEntity] = tableMergeEntityOperationSpec; Specifications[Operation.Table_DeleteEntity] = tableDeleteEntityOperationSpec; Specifications[ Operation.Table_MergeEntityWithMerge ] = tableMergeEntityWithMergeOperationSpec; Specifications[Operation.Table_InsertEntity] = tableInsertEntityOperationSpec; Specifications[ Operation.Table_GetAccessPolicy ] = tableGetAccessPolicyOperationSpec; Specifications[ Operation.Table_SetAccessPolicy ] = tableSetAccessPolicyOperationSpec; Specifications[ Operation.Service_SetProperties ] = serviceSetPropertiesOperationSpec; Specifications[ Operation.Service_GetProperties ] = serviceGetPropertiesOperationSpec; Specifications[ Operation.Service_GetStatistics ] = serviceGetStatisticsOperationSpec; export default Specifications;
the_stack
import { MetricsPanelCtrl } from 'grafana/app/plugins/sdk'; import _ from 'lodash'; import angular from 'angular'; import kbn from 'grafana/app/core/utils/kbn'; import * as FileExport from './file_export'; import 'datatables.net/js/jquery.dataTables.min'; import { panelDefaults, dateFormats, columnTypes, columnStyleDefaults, colorModes, fontSizes } from './Defaults'; import { transformDataToTable, transformers } from './transformers'; import { DatatableRenderer } from './DatatableRenderer'; import { PanelEvents } from '@grafana/data'; // See this for styling https://datatables.net/manual/styling/theme-creator /* Dark Theme Basic uses these values table section border: #242222 rgb(36,34,34) row/cell border: #141414 rgb(20,20,20) row background: #1F1D1D rgb(31,29,29) row selected color: #242222 rgb(36,34,34) control text: #1FB2E5 rgb(31,178,229) control text: white (dataTables_paginate) paging active button: #242222 rgb(36,34,34) paging button hover: #111111 rgb(17,17,17) with these modifications: .dataTables_wrapper .dataTables_paginate .paginate_button { color: white } table.dataTable tfoot th { color: #1FB2E5; font-weight: bold; } Light Theme Basic uses these values table section border: #ECECEC rgb(236,236,236) row/cell border: #FFFFFF rgb(255,255,255) row background: #FBFBFB rgb(251,251,251) row selected color: #ECECEC rgb(236,236,236) control text: black paging active button: #BEBEBE paging button hover: #C0C0C0 with these modifications: .dataTables_wrapper .dataTables_paginate .paginate_button.current, .dataTables_wrapper .dataTables_paginate .paginate_button.current:hover { color: #1fb2e5 !important; table.dataTable tfoot th { color: #1FB2E5; font-weight: bold; } */ export class DatatablePanelCtrl extends MetricsPanelCtrl { static templateUrl = 'partials/template.html'; dataLoaded: boolean; pageIndex: number; table: any; dataRaw: any[]; transformers: any; annotationsSrv: any; uiSegmentSrv: any; addColumnSegment: any; mappingTypes: any; columnSortMethods: any; fontSizes: any; colorModes: any; columnTypes: any; unitFormats: any; dateFormats: any; $q: any; http: any; getColumnNames: () => any[]; /** @ngInject */ constructor( $scope: any, $injector: any, $http: any, $location: any, $q: any, uiSegmentSrv: any, annotationsSrv: any, private $sanitize: any, timeSrv: any ) { super($scope, $injector); this.pageIndex = 0; this.table = null; this.dataRaw = []; this.$q = $q; this.transformers = transformers; this.annotationsSrv = annotationsSrv; this.uiSegmentSrv = uiSegmentSrv; // editor this.addColumnSegment = uiSegmentSrv.newPlusButton(); this.mappingTypes = [ { text: 'Value to text', value: 1 }, { text: 'Range to text', value: 2 }, ]; this.columnSortMethods = [ { text: 'Ascending', value: 'asc', }, { text: 'Descending', value: 'desc', }, ]; this.fontSizes = fontSizes; this.colorModes = colorModes; this.columnTypes = columnTypes; this.unitFormats = kbn.getUnitFormats(); this.dateFormats = dateFormats; // this is used from bs-typeahead and needs to be instance bound this.getColumnNames = () => { if (!this.table) { return []; } return _.map(this.table.columns, col => { return col.text; }); }; if (this.panel.styles === void 0) { this.panel.styles = this.panel.columns; this.panel.columns = this.panel.fields; delete this.panel.columns; delete this.panel.fields; } _.defaults(this.panel, panelDefaults); this.dataLoaded = true; this.http = $http; // v6 compat if (typeof PanelEvents === 'undefined') { this.events.on('data-received', this.onDataReceived.bind(this)); this.events.on('data-error', this.onDataError.bind(this)); this.events.on('data-snapshot-load', this.onDataReceived.bind(this)); this.events.on('init-edit-mode', this.onInitEditMode.bind(this)); this.events.on('init-panel-actions', this.onInitPanelActions.bind(this)); } else { // v7+ compat this.events.on(PanelEvents.dataReceived, this.onDataReceived.bind(this)); this.events.on(PanelEvents.dataError, this.onDataError.bind(this)); this.events.on(PanelEvents.dataSnapshotLoad, this.onDataReceived.bind(this)); this.events.on(PanelEvents.editModeInitialized, this.onInitEditMode.bind(this)); this.events.on(PanelEvents.initPanelActions, this.onInitPanelActions.bind(this)); } } onInitPanelActions(actions: any) { actions.push({ text: 'Export CSV', click: 'ctrl.exportCsv()', }); } // setup the editor onInitEditMode() { // determine the path to this plugin const thisPanelPath = 'public/plugins/' + this.panel.type + '/'; // add the relative path to the partial const optionsPath = thisPanelPath + 'partials/editor.options.html'; this.addEditorTab('Options', optionsPath, 2); const datatableOptionsPath = thisPanelPath + 'partials/datatables.options.html'; this.addEditorTab('Datatable Options', datatableOptionsPath, 3); } issueQueries(datasource: any) { this.pageIndex = 0; if (this.panel.transform === 'annotations') { this.setTimeQueryStart(); return this.annotationsSrv .getAnnotations({ dashboard: this.dashboard, panel: this.panel, range: this.range, }) .then((annotations: any) => { return { data: annotations, }; }); } return super.issueQueries(datasource); } onDataError(err: any) { this.dataRaw = []; this.render(); } onDataReceived(dataList: any) { this.dataRaw = dataList; this.pageIndex = 0; // automatically correct transform mode based on data if (this.dataRaw && this.dataRaw.length) { if (this.dataRaw[0].type === 'table') { this.panel.transform = 'table'; } else { if (this.dataRaw[0].type === 'docs') { this.panel.transform = 'json'; } else { if (this.panel.transform === 'table' || this.panel.transform === 'json') { this.panel.transform = 'timeseries_to_rows'; } } } } this.render(); } render() { this.table = transformDataToTable(this.dataRaw, this.panel); this.table.sort(this.panel.sort); this.panel.emptyData = this.table.rows.length === 0 || this.table.columns.length === 0; return super.render(this.table); } changeRowNumbersEnabled() { this.panel.sortByColumnsData.map((sortData: any) => [ this.panel.rowNumbersEnabled ? sortData[0]++ : sortData[0]--, sortData[1], ]); this.render(); } getPanelHeight() { // panel can have a fixed height set via "General" tab in panel editor let tmpPanelHeight = this.panel.height; if (typeof tmpPanelHeight === 'undefined' || tmpPanelHeight === '') { // grafana also supplies the height, try to use that if the panel does not have a height tmpPanelHeight = String(this.height); // v4 and earlier define this height, detect span for pre-v5 if (typeof this.panel.span !== 'undefined') { // if there is no header, adjust height to use all space available let panelTitleOffset = 20; if (this.panel.title !== '') { panelTitleOffset = 42; } tmpPanelHeight = String(this.containerHeight - panelTitleOffset); // offset for header } if (typeof tmpPanelHeight === 'undefined') { // height still cannot be determined, get it from the row instead tmpPanelHeight = this.row.height; if (typeof tmpPanelHeight === 'undefined') { // last resort - default to 250px (this should never happen) tmpPanelHeight = '250'; } } } // replace px tmpPanelHeight = tmpPanelHeight.replace('px', ''); // convert to numeric value const actualHeight = parseInt(tmpPanelHeight, 10); return actualHeight; } exportCsv() { let isInUTC = false; if (this.dashboard && this.dashboard.hasOwnProperty('isTimezoneUtc')) { isInUTC = this.dashboard.isTimezoneUtc(); } const renderer = new DatatableRenderer(this.panel, this.table, isInUTC, this.$sanitize, this.timeSrv); FileExport.exportTableDataToCsv(renderer.render_values()); } link(scope: any, elem: any, attrs: any, ctrl: any) { let data: any[]; const panel = ctrl.panel; const _this = this; /** * [renderPanel description] * @return {[type]} [description] */ function renderPanel() { // v7 has removed this let isInUTC = false; if (ctrl.dashboard && ctrl.dashboard.hasOwnProperty('isTimezoneUtc')) { isInUTC = ctrl.dashboard.isTimezoneUtc(); } const renderer = new DatatableRenderer(panel, ctrl.table, isInUTC, ctrl.$sanitize, _this.timeSrv); renderer.render(); _this.dataLoaded = true; } ctrl.panel.panelHeight = this.getPanelHeight(); ctrl.events.on('render', (renderData: any) => { data = renderData || data; if (data) { renderPanel(); } ctrl.renderingCompleted(); }); } // editor methods // // cell and row borders cannot both be set at the same time showCellBordersChanged() { if (this.panel.showCellBorders) { this.panel.showRowBorders = false; } this.render(); } themeChanged() { //console.log(this.panel.datatableTheme); this.render(); } transformChanged() { this.panel.columns = []; this.render(); } removeColumn(column: any) { this.panel.columns = _.without(this.panel.columns, column); this.render(); } getColumnOptions() { if (!this.dataRaw) { return this.$q.when([]); } const columns = this.transformers[this.panel.transform].getColumns(this.dataRaw); const segments = _.map(columns, c => this.uiSegmentSrv.newSegment({ value: c.text, }) ); return this.$q.when(segments); } addColumn() { const columns = transformers[this.panel.transform].getColumns(this.dataRaw); const column = _.find(columns, { text: this.addColumnSegment.value, }); if (column) { this.panel.columns.push(column); this.render(); } const plusButton = this.uiSegmentSrv.newPlusButton(); this.addColumnSegment.html = plusButton.html; this.addColumnSegment.value = plusButton.value; } addColumnStyle() { this.panel.styles.push(angular.copy(columnStyleDefaults)); } removeColumnStyle(style: any) { this.panel.styles = _.without(this.panel.styles, style); } setUnitFormat(column: any, subItem: any) { column.unit = subItem.value; this.render(); } invertColorOrder(index: any) { const ref = this.panel.styles[index].colors; const copy = ref[0]; ref[0] = ref[2]; ref[2] = copy; this.render(); } addColumnSortingRule() { const defaultRule = { columnData: 0, sortMethod: 'desc', }; // check if this column already exists this.panel.sortByColumns.push(angular.copy(defaultRule)); this.columnSortChanged(); } removeSortByColumn(column: any) { this.panel.sortByColumns = _.without(this.panel.sortByColumns, column); this.columnSortChanged(); } columnSortChanged() { // take the values in sortByColumns and convert them into datatables format const data = []; if (this.panel.sortByColumns.length > 0) { for (let i = 0; i < this.panel.sortByColumns.length; i++) { // allow numbers and column names const columnData = this.panel.sortByColumns[i].columnData; let columnNumber = 0; columnNumber = parseInt(columnData, 10); if (Number.isNaN(columnNumber)) { columnNumber = 0; // find the matching column index for (let j = 0; j < this.table.columns.length; j++) { if (this.table.columns[j].text === columnData) { columnNumber = j; break; } } } const sortDirection = this.panel.sortByColumns[i].sortMethod; data.push([columnNumber, sortDirection]); } } else { // default to column 0, descending data.push([0, 'desc']); } if (this.panel.rowNumbersEnabled) { data.map((sortData: any) => [sortData[0]++, sortData[1]]); } this.panel.sortByColumnsData = data; this.render(); } addColumnAlias() { const defaultAlias = { name: '', alias: '', }; // check if this column already exists this.panel.columnAliases.push(angular.copy(defaultAlias)); this.columnAliasChanged(); } removeColumnAlias(column: any) { this.panel.columnAliases = _.without(this.panel.columnAliases, column); this.columnAliasChanged(); } columnAliasChanged() { this.render(); } addColumnWidthHint() { const defaultHint = { name: '', width: '80px', }; // check if this column already exists this.panel.columnWidthHints.push(angular.copy(defaultHint)); this.columnWidthHintsChanged(); } removeColumnWidthHint(column: any) { this.panel.columnWidthHints = _.without(this.panel.columnWidthHints, column); this.columnWidthHintsChanged(); } columnWidthHintsChanged() { this.render(); } addValueMap(style: any) { if (!style.valueMaps) { style.valueMaps = []; } style.valueMaps.push({ value: '', text: '' }); this.render(); } removeValueMap(style: any, index: any) { style.valueMaps.splice(index, 1); this.render(); } addRangeMap(style: any) { if (!style.rangeMaps) { style.rangeMaps = []; } style.rangeMaps.push({ from: '', to: '', text: '' }); this.render(); } removeRangeMap(style: any, index: any) { style.rangeMaps.splice(index, 1); this.render(); } }
the_stack
import assert from 'assert' import { handleActions } from 'redux-actions' import mapValues from 'lodash/mapValues' import cloneDeep from 'lodash/cloneDeep' import merge from 'lodash/merge' import omit from 'lodash/omit' import omitBy from 'lodash/omitBy' import reduce from 'lodash/reduce' import { getLabwareDefaultEngageHeight, getLabwareDefURI, getModuleType, MAGNETIC_MODULE_TYPE, MAGNETIC_MODULE_V1, THERMOCYCLER_MODULE_TYPE, } from '@opentrons/shared-data' import type { RootState as LabwareDefsRootState } from '../../labware-defs' import { rootReducer as labwareDefsRootReducer } from '../../labware-defs' import { uuid } from '../../utils' import { INITIAL_DECK_SETUP_STEP_ID, FIXED_TRASH_ID, SPAN7_8_10_11_SLOT, } from '../../constants' import { getPDMetadata } from '../../file-types' import { getDefaultsForStepType, handleFormChange, } from '../../steplist/formLevel' import { PRESAVED_STEP_ID } from '../../steplist/types' import { _getPipetteEntitiesRootState, _getLabwareEntitiesRootState, _getInitialDeckSetupRootState, } from '../selectors' import { getLabwareIsCompatible } from '../../utils/labwareModuleCompatibility' import { createPresavedStepForm, getDeckItemIdInSlot, getIdsInRange, } from '../utils' import { createInitialProfileCycle, createInitialProfileStep, } from '../utils/createInitialProfileItems' import { getLabwareOnModule } from '../../ui/modules/utils' import { nestedCombineReducers } from './nestedCombineReducers' import { PROFILE_CYCLE, PROFILE_STEP } from '../../form-types' import { Reducer } from 'redux' import { NormalizedPipetteById } from '@opentrons/step-generation' import { LoadFileAction } from '../../load-file' import { CreateContainerAction, DeleteContainerAction, DuplicateLabwareAction, SwapSlotContentsAction, } from '../../labware-ingred/actions' import { ReplaceCustomLabwareDef } from '../../labware-defs/actions' import type { FormData, StepIdType, StepType, ProfileItem, ProfileCycleItem, ProfileStepItem, } from '../../form-types' import { FileLabware, FilePipette, FileModule, } from '@opentrons/shared-data/protocol/types/schemaV4' import { CancelStepFormAction, ChangeFormInputAction, ChangeSavedStepFormAction, DeleteStepAction, DeleteMultipleStepsAction, PopulateFormAction, ReorderStepsAction, AddProfileCycleAction, AddProfileStepAction, DeleteProfileCycleAction, DeleteProfileStepAction, EditProfileCycleAction, EditProfileStepAction, FormPatch, } from '../../steplist/actions' import { AddStepAction, DuplicateStepAction, DuplicateMultipleStepsAction, ReorderSelectedStepAction, SelectStepAction, SelectTerminalItemAction, SelectMultipleStepsAction, } from '../../ui/steps/actions/types' import { SaveStepFormAction } from '../../ui/steps/actions/thunks' import { NormalizedLabware, NormalizedLabwareById, ModuleEntities, } from '../types' import { CreateModuleAction, CreatePipettesAction, DeleteModuleAction, DeletePipettesAction, EditModuleAction, SubstituteStepFormPipettesAction, ChangeBatchEditFieldAction, ResetBatchEditFieldChangesAction, SaveStepFormsMultiAction, } from '../actions' type FormState = FormData | null const unsavedFormInitialState = null // the `unsavedForm` state holds temporary form info that is saved or thrown away with "cancel". export type UnsavedFormActions = | AddProfileCycleAction | AddStepAction | ChangeFormInputAction | PopulateFormAction | CancelStepFormAction | SaveStepFormAction | DeleteStepAction | DeleteMultipleStepsAction | CreateModuleAction | DeleteModuleAction | SelectTerminalItemAction | EditModuleAction | SubstituteStepFormPipettesAction | AddProfileStepAction | DeleteProfileStepAction | DeleteProfileCycleAction | EditProfileCycleAction | EditProfileStepAction | SelectMultipleStepsAction export const unsavedForm = ( rootState: RootState, action: UnsavedFormActions ): FormState => { const unsavedFormState = rootState ? rootState.unsavedForm : unsavedFormInitialState switch (action.type) { case 'ADD_PROFILE_CYCLE': { if (unsavedFormState?.stepType !== 'thermocycler') { console.error( 'ADD_PROFILE_CYCLE should only be dispatched when unsaved form is "thermocycler" form' ) return unsavedFormState } const cycleId = uuid() const profileStepId = uuid() return { ...unsavedFormState, orderedProfileItems: [...unsavedFormState.orderedProfileItems, cycleId], profileItemsById: { ...unsavedFormState.profileItemsById, [cycleId]: createInitialProfileCycle(cycleId, profileStepId), }, } } case 'ADD_STEP': { return createPresavedStepForm({ stepType: action.payload.stepType, stepId: action.payload.id, pipetteEntities: _getPipetteEntitiesRootState(rootState), labwareEntities: _getLabwareEntitiesRootState(rootState), savedStepForms: rootState.savedStepForms, orderedStepIds: rootState.orderedStepIds, initialDeckSetup: _getInitialDeckSetupRootState(rootState), robotStateTimeline: action.meta.robotStateTimeline, }) } case 'CHANGE_FORM_INPUT': { const fieldUpdate = handleFormChange( action.payload.update, unsavedFormState, _getPipetteEntitiesRootState(rootState), _getLabwareEntitiesRootState(rootState) ) // @ts-expect-error (IL, 2020-02-24): address in #3161, underspecified form fields may be overwritten in type-unsafe manner return { ...unsavedFormState, ...fieldUpdate } } case 'POPULATE_FORM': return action.payload case 'CANCEL_STEP_FORM': case 'CREATE_MODULE': case 'DELETE_MODULE': case 'DELETE_STEP': case 'DELETE_MULTIPLE_STEPS': case 'SELECT_MULTIPLE_STEPS': case 'EDIT_MODULE': case 'SAVE_STEP_FORM': case 'SELECT_TERMINAL_ITEM': return unsavedFormInitialState case 'SUBSTITUTE_STEP_FORM_PIPETTES': { // only substitute unsaved step form if its ID is in the start-end range const { substitutionMap, startStepId, endStepId } = action.payload const stepIdsToUpdate = getIdsInRange( rootState.orderedStepIds, startStepId, endStepId ) if ( unsavedFormState && unsavedFormState?.pipette && // TODO(IL, 2020-06-02): Flow should know unsavedFormState is not null here (so keys are safe to access), but it's being dumb unsavedFormState.pipette in substitutionMap && unsavedFormState.id && stepIdsToUpdate.includes(unsavedFormState.id) ) { // TODO(IL, 2020-02-24): address in #3161, underspecified form fields may be overwritten in type-unsafe manner return { ...unsavedFormState, ...handleFormChange( { pipette: substitutionMap[unsavedFormState.pipette], }, unsavedFormState, _getPipetteEntitiesRootState(rootState), _getLabwareEntitiesRootState(rootState) ), } } return unsavedFormState } case 'ADD_PROFILE_STEP': { if (unsavedFormState?.stepType !== 'thermocycler') { console.error( 'ADD_PROFILE_STEP should only be dispatched when unsaved form is "thermocycler" form' ) return unsavedFormState } const id = uuid() const newStep = createInitialProfileStep(id) if (action.payload !== null) { const { cycleId } = action.payload const targetCycle = unsavedFormState.profileItemsById[cycleId] // add to cycle return { ...unsavedFormState, profileItemsById: { ...unsavedFormState.profileItemsById, [cycleId]: { ...targetCycle, steps: [...targetCycle.steps, newStep], }, }, } } // TODO factor this createInitialProfileStep out somewhere return { ...unsavedFormState, orderedProfileItems: [...unsavedFormState.orderedProfileItems, id], profileItemsById: { ...unsavedFormState.profileItemsById, [id]: newStep, }, } } case 'DELETE_PROFILE_CYCLE': { if (unsavedFormState?.stepType !== 'thermocycler') { console.error( 'DELETE_PROFILE_CYCLE should only be dispatched when unsaved form is "thermocycler" form' ) return unsavedFormState } const { id } = action.payload const isCycle = unsavedFormState.profileItemsById[id].type === PROFILE_CYCLE if (!isCycle) { return unsavedFormState } return { ...unsavedFormState, orderedProfileItems: unsavedFormState.orderedProfileItems.filter( (itemId: string) => itemId !== id ), profileItemsById: omit(unsavedFormState.profileItemsById, id), } } case 'DELETE_PROFILE_STEP': { if (unsavedFormState?.stepType !== 'thermocycler') { console.error( 'DELETE_PROFILE_STEP should only be dispatched when unsaved form is "thermocycler" form' ) return unsavedFormState } const { id } = action.payload const omitTopLevelSteps = ( profileItemsById: Record<string, ProfileItem> ): Record<string, ProfileItem> => omitBy( profileItemsById, (item: ProfileItem, itemId: string): boolean => { return item.type === PROFILE_STEP && itemId === id } ) // not top-level, must be nested inside a cycle const omitCycleSteps = ( profileItemsById: Record<string, ProfileItem> ): Record<string, ProfileItem> => mapValues( profileItemsById, (item: ProfileItem): ProfileItem => { if (item.type === PROFILE_CYCLE) { return { ...item, steps: item.steps.filter( (stepItem: ProfileStepItem) => stepItem.id !== id ), } } return item } ) const isTopLevelProfileStep = unsavedFormState.orderedProfileItems.includes(id) && unsavedFormState.profileItemsById[id].type === PROFILE_STEP const filteredItemsById = isTopLevelProfileStep ? omitTopLevelSteps(unsavedFormState.profileItemsById) : omitCycleSteps(unsavedFormState.profileItemsById) const filteredOrderedProfileItems = isTopLevelProfileStep ? unsavedFormState.orderedProfileItems.filter( (itemId: string) => itemId !== id ) : unsavedFormState.orderedProfileItems return { ...unsavedFormState, orderedProfileItems: filteredOrderedProfileItems, profileItemsById: filteredItemsById, } } case 'EDIT_PROFILE_CYCLE': { if (unsavedFormState?.stepType !== 'thermocycler') { console.error( 'EDIT_PROFILE_CYCLE should only be dispatched when unsaved form is "thermocycler" form' ) return unsavedFormState } const { id, fields } = action.payload const cycle = unsavedFormState.profileItemsById[id] if (cycle.type !== PROFILE_CYCLE) { console.warn( `EDIT_PROFILE_CYCLE got non-cycle profile item ${cycle.id}` ) return unsavedFormState } return { ...unsavedFormState, profileItemsById: { ...unsavedFormState.profileItemsById, [id]: { ...cycle, ...fields }, }, } } case 'EDIT_PROFILE_STEP': { if (unsavedFormState?.stepType !== 'thermocycler') { console.error( 'EDIT_PROFILE_STEP should only be dispatched when unsaved form is "thermocycler" form' ) return unsavedFormState } const { id, fields } = action.payload const isTopLevelStep = unsavedFormState.orderedProfileItems.includes(id) && unsavedFormState.profileItemsById[id].type === PROFILE_STEP if (isTopLevelStep) { return { ...unsavedFormState, profileItemsById: { ...unsavedFormState.profileItemsById, [id]: { ...unsavedFormState.profileItemsById[id], ...fields }, }, } } else { // it's a step in a cycle. Get the cycle id, and the index of our edited step in that cycle's `steps` array let editedStepIndex = -1 const cycleId: string | undefined = Object.keys( unsavedFormState.profileItemsById ).find((itemId: string): boolean => { const item: ProfileItem = unsavedFormState.profileItemsById[itemId] if (item.type === PROFILE_CYCLE) { const stepIndex = item.steps.findIndex(step => step.id === id) if (stepIndex !== -1) { editedStepIndex = stepIndex return true } } return false }) if (cycleId == null || editedStepIndex === -1) { console.warn(`EDIT_PROFILE_STEP: step does not exist ${id}`) return unsavedFormState } let newCycle: ProfileCycleItem = { ...unsavedFormState.profileItemsById[cycleId], } const newSteps = [...newCycle.steps] newSteps[editedStepIndex] = { ...newCycle.steps[editedStepIndex], ...fields, } newCycle = { ...newCycle, steps: newSteps } const newProfileItems = { ...unsavedFormState.profileItemsById, [cycleId]: newCycle, } return { ...unsavedFormState, profileItemsById: newProfileItems } } } default: return unsavedFormState } } export type SavedStepFormState = Record<StepIdType, FormData> export const initialDeckSetupStepForm: FormData = { stepType: 'manualIntervention', id: INITIAL_DECK_SETUP_STEP_ID, labwareLocationUpdate: { [FIXED_TRASH_ID]: '12', }, pipetteLocationUpdate: {}, moduleLocationUpdate: {}, } export const initialSavedStepFormsState: SavedStepFormState = { [INITIAL_DECK_SETUP_STEP_ID]: initialDeckSetupStepForm, } export type SavedStepFormsActions = | SaveStepFormAction | SaveStepFormsMultiAction | DeleteStepAction | DeleteMultipleStepsAction | LoadFileAction | CreateContainerAction | DeleteContainerAction | SubstituteStepFormPipettesAction | DeletePipettesAction | CreateModuleAction | DeleteModuleAction | DuplicateStepAction | DuplicateMultipleStepsAction | ChangeSavedStepFormAction | DuplicateLabwareAction | SwapSlotContentsAction | ReplaceCustomLabwareDef | EditModuleAction export const _editModuleFormUpdate = ({ savedForm, moduleId, formId, rootState, nextModuleModel, }: { savedForm: FormData moduleId: string formId: string rootState: RootState nextModuleModel: string }): FormData => { if ( savedForm.stepType === 'magnet' && savedForm.moduleId === moduleId && savedForm.magnetAction === 'engage' ) { const prevEngageHeight = parseFloat(savedForm.engageHeight) if (Number.isFinite(prevEngageHeight)) { const initialDeckSetup = _getInitialDeckSetupRootState(rootState) const labwareEntity = getLabwareOnModule(initialDeckSetup, moduleId) const labwareDefaultEngageHeight = labwareEntity ? getLabwareDefaultEngageHeight(labwareEntity.def) : null const moduleEntity = initialDeckSetup.modules[moduleId] assert( moduleEntity, `editModuleFormUpdate expected moduleEntity for module ${moduleId}` ) const prevModuleModel = moduleEntity?.model if (labwareDefaultEngageHeight != null) { // compensate for fact that V1 mag module uses 'short mm' const shortMMDefault = labwareDefaultEngageHeight * 2 const prevModelSpecificDefault = prevModuleModel === MAGNETIC_MODULE_V1 ? shortMMDefault : labwareDefaultEngageHeight const nextModelSpecificDefault = nextModuleModel === MAGNETIC_MODULE_V1 ? shortMMDefault : labwareDefaultEngageHeight if (prevEngageHeight === prevModelSpecificDefault) { return { ...savedForm, engageHeight: String(nextModelSpecificDefault), } } } } // default case: null out engageHeight if magnet step's module has been edited const blankEngageHeight = getDefaultsForStepType('magnet').engageHeight return { ...savedForm, engageHeight: blankEngageHeight } } // not a Magnet > Engage step for the edited moduleId, no change return savedForm } export const savedStepForms = ( rootState: RootState, action: SavedStepFormsActions ): SavedStepFormState => { const savedStepForms = rootState ? rootState.savedStepForms : initialSavedStepFormsState switch (action.type) { case 'SAVE_STEP_FORM': { return { ...savedStepForms, [action.payload.id]: action.payload } } case 'SAVE_STEP_FORMS_MULTI': { const { editedFields, stepIds } = action.payload return stepIds.reduce( (acc, stepId) => ({ ...acc, [stepId]: { ...savedStepForms[stepId], ...editedFields }, }), { ...savedStepForms } ) } case 'DELETE_STEP': { return omit(savedStepForms, action.payload) } case 'DELETE_MULTIPLE_STEPS': { return omit(savedStepForms, action.payload) } case 'LOAD_FILE': { const { file } = action.payload const stepFormsFromFile = getPDMetadata(file).savedStepForms return mapValues(stepFormsFromFile, stepForm => ({ ...getDefaultsForStepType(stepForm.stepType), ...stepForm, })) } case 'DUPLICATE_LABWARE': case 'CREATE_CONTAINER': { // auto-update initial deck setup state. const prevInitialDeckSetupStep = savedStepForms[INITIAL_DECK_SETUP_STEP_ID] const labwareId: string = action.type === 'CREATE_CONTAINER' ? action.payload.id : action.payload.duplicateLabwareId assert( prevInitialDeckSetupStep, 'expected initial deck setup step to exist, could not handle CREATE_CONTAINER' ) const slot = action.payload.slot if (!slot) { console.warn('no slots available, ignoring action:', action) return savedStepForms } return { ...savedStepForms, [INITIAL_DECK_SETUP_STEP_ID]: { ...prevInitialDeckSetupStep, labwareLocationUpdate: { ...prevInitialDeckSetupStep.labwareLocationUpdate, [labwareId]: slot, }, }, } } case 'CREATE_MODULE': { const prevInitialDeckSetupStep = savedStepForms[INITIAL_DECK_SETUP_STEP_ID] const labwareOccupyingDestination = getDeckItemIdInSlot( prevInitialDeckSetupStep.labwareLocationUpdate, action.payload.slot ) const moduleId = action.payload.id // If module is going into a slot occupied by a labware, // move the labware on top of the new module const labwareLocationUpdate = labwareOccupyingDestination == null ? prevInitialDeckSetupStep.labwareLocationUpdate : { ...prevInitialDeckSetupStep.labwareLocationUpdate, [labwareOccupyingDestination]: moduleId, } return mapValues(savedStepForms, (savedForm: FormData, formId) => { if (formId === INITIAL_DECK_SETUP_STEP_ID) { return { ...prevInitialDeckSetupStep, labwareLocationUpdate, moduleLocationUpdate: { ...prevInitialDeckSetupStep.moduleLocationUpdate, [action.payload.id]: action.payload.slot, }, } } // NOTE: since users can only have 1 magnetic module at a time, // and since the Magnet step form doesn't allow users to select a dropdown, // we auto-select a newly-added magnetic module for all of them // to handle the case where users delete and re-add a magnetic module if ( savedForm.stepType === 'magnet' && action.payload.type === MAGNETIC_MODULE_TYPE ) { return { ...savedForm, moduleId } } // same logic applies to Thermocycler if ( savedForm.stepType === 'thermocycler' && action.payload.type === THERMOCYCLER_MODULE_TYPE ) { return { ...savedForm, moduleId } } return savedForm }) } case 'EDIT_MODULE': { const moduleId = action.payload.id return mapValues(savedStepForms, (savedForm: FormData, formId) => _editModuleFormUpdate({ moduleId, savedForm, formId, rootState, nextModuleModel: action.payload.model, }) ) } case 'MOVE_DECK_ITEM': { const { sourceSlot, destSlot } = action.payload return mapValues( savedStepForms, (savedForm: FormData): FormData => { if (savedForm.stepType === 'manualIntervention') { // swap labware/module slots from all manualIntervention steps // (or place compatible labware in dest slot onto module) const sourceLabwareId = getDeckItemIdInSlot( savedForm.labwareLocationUpdate, sourceSlot ) const destLabwareId = getDeckItemIdInSlot( savedForm.labwareLocationUpdate, destSlot ) const sourceModuleId = getDeckItemIdInSlot( savedForm.moduleLocationUpdate, sourceSlot ) const destModuleId = getDeckItemIdInSlot( savedForm.moduleLocationUpdate, destSlot ) if (sourceModuleId && destLabwareId) { // moving module to a destination slot with labware const prevInitialDeckSetup = _getInitialDeckSetupRootState( rootState ) const moduleEntity = prevInitialDeckSetup.modules[sourceModuleId] const labwareEntity = prevInitialDeckSetup.labware[destLabwareId] const isCompat = getLabwareIsCompatible( labwareEntity.def, moduleEntity.type ) const moduleIsOccupied = getDeckItemIdInSlot( savedForm.labwareLocationUpdate, sourceModuleId ) != null if (isCompat && !moduleIsOccupied) { // only in this special case, we put module under the labware return { ...savedForm, labwareLocationUpdate: { ...savedForm.labwareLocationUpdate, [destLabwareId]: sourceModuleId, }, moduleLocationUpdate: { ...savedForm.moduleLocationUpdate, [sourceModuleId]: destSlot, }, } } } const labwareLocationUpdate: Record<string, string> = { ...savedForm.labwareLocationUpdate, } if (sourceLabwareId != null) { labwareLocationUpdate[sourceLabwareId] = destSlot } if (destLabwareId != null) { labwareLocationUpdate[destLabwareId] = sourceSlot } const moduleLocationUpdate: Record<string, string> = { ...savedForm.moduleLocationUpdate, } if (sourceModuleId != null) { moduleLocationUpdate[sourceModuleId] = destSlot } if (destModuleId != null) { moduleLocationUpdate[destModuleId] = sourceSlot } return { ...savedForm, labwareLocationUpdate, moduleLocationUpdate } } return savedForm } ) } case 'DELETE_CONTAINER': { const labwareIdToDelete = action.payload.labwareId return mapValues(savedStepForms, (savedForm: FormData) => { if (savedForm.stepType === 'manualIntervention') { // remove instances of labware from all manualIntervention steps return { ...savedForm, labwareLocationUpdate: omit( savedForm.labwareLocationUpdate, labwareIdToDelete ), } } const deleteLabwareUpdate = reduce<FormData, FormData>( savedForm, (acc, value, fieldName) => { if (value === labwareIdToDelete) { // TODO(IL, 2020-02-24): address in #3161, underspecified form fields may be overwritten in type-unsafe manner return { ...acc, ...handleFormChange( { [fieldName]: null, }, acc, _getPipetteEntitiesRootState(rootState), _getLabwareEntitiesRootState(rootState) ), } } else { return acc } }, savedForm ) // TODO(IL, 2020-02-24): address in #3161, underspecified form fields may be overwritten in type-unsafe manner return { ...savedForm, ...deleteLabwareUpdate } }) } case 'DELETE_PIPETTES': { // remove references to pipettes that have been deleted const deletedPipetteIds = action.payload return mapValues( savedStepForms, (form: FormData): FormData => { if (form.stepType === 'manualIntervention') { return { ...form, pipetteLocationUpdate: omit( form.pipetteLocationUpdate, deletedPipetteIds ), } } else if (deletedPipetteIds.includes(form.pipette)) { // TODO(IL, 2020-02-24): address in #3161, underspecified form fields may be overwritten in type-unsafe manner return { ...form, ...handleFormChange( { pipette: null, }, form, _getPipetteEntitiesRootState(rootState), _getLabwareEntitiesRootState(rootState) ), } } return form } ) } case 'DELETE_MODULE': { const moduleId = action.payload.id return mapValues(savedStepForms, (form: FormData) => { if (form.stepType === 'manualIntervention') { // TODO: Ian 2019-10-28 when we have multiple manualIntervention steps, this should look backwards // for the latest location update for the module, not just the initial deck setup const _deletedModuleSlot = savedStepForms[INITIAL_DECK_SETUP_STEP_ID].moduleLocationUpdate[ moduleId ] // handle special spanning slots that are intended for modules & not for labware const labwareFallbackSlot = _deletedModuleSlot === SPAN7_8_10_11_SLOT ? '7' : _deletedModuleSlot return { ...form, moduleLocationUpdate: omit(form.moduleLocationUpdate, moduleId), labwareLocationUpdate: mapValues( form.labwareLocationUpdate, labwareSlot => labwareSlot === moduleId ? labwareFallbackSlot : labwareSlot ), } } else if ( (form.stepType === 'magnet' || form.stepType === 'temperature' || form.stepType === 'pause') && form.moduleId === moduleId ) { return { ...form, moduleId: null } } else { return form } }) } case 'SUBSTITUTE_STEP_FORM_PIPETTES': { const { startStepId, endStepId, substitutionMap } = action.payload const stepIdsToUpdate = getIdsInRange( rootState.orderedStepIds, startStepId, endStepId ) const savedStepsUpdate = stepIdsToUpdate.reduce((acc, stepId) => { const prevStepForm = savedStepForms[stepId] const shouldSubstitute = Boolean( prevStepForm && // pristine forms will not exist in savedStepForms prevStepForm.pipette && prevStepForm.pipette in substitutionMap ) if (!shouldSubstitute) return acc const updatedFields = handleFormChange( { pipette: substitutionMap[prevStepForm.pipette], }, prevStepForm, _getPipetteEntitiesRootState(rootState), _getLabwareEntitiesRootState(rootState) ) return { ...acc, // TODO(IL, 2020-02-24): address in #3161, underspecified form fields may be overwritten in type-unsafe manner [stepId]: { ...prevStepForm, ...updatedFields }, } }, {}) // TODO(IL, 2020-02-24): address in #3161, underspecified form fields may be overwritten in type-unsafe manner return { ...savedStepForms, ...savedStepsUpdate } } case 'CHANGE_SAVED_STEP_FORM': { const { stepId } = action.payload if (stepId == null) { assert( false, `savedStepForms got CHANGE_SAVED_STEP_FORM action without a stepId` ) return savedStepForms } const previousForm = savedStepForms[stepId] if (previousForm.stepType === 'manualIntervention') { // since manualIntervention steps are nested, use a recursive merge return { ...savedStepForms, [stepId]: merge({}, previousForm, action.payload.update), } } // other step form types are not designed to be deeply merged // (eg `wells` arrays should be reset, not appended to) return { ...savedStepForms, // TODO(IL, 2020-02-24): address in #3161, underspecified form fields may be overwritten in type-unsafe manner [stepId]: { ...previousForm, ...handleFormChange( action.payload.update, previousForm, _getPipetteEntitiesRootState(rootState), _getLabwareEntitiesRootState(rootState) ), }, } } case 'DUPLICATE_STEP': { // @ts-expect-error(sa, 2021-6-10): if stepId is null, we will end up in situation where the entry for duplicateStepId // will be {[duplicateStepId]: {id: duplicateStepId}}, which will be missing the rest of the properties from FormData return { ...savedStepForms, [action.payload.duplicateStepId]: { ...cloneDeep( action.payload.stepId != null ? savedStepForms[action.payload.stepId] : {} ), id: action.payload.duplicateStepId, }, } } case 'DUPLICATE_MULTIPLE_STEPS': { return action.payload.steps.reduce( (acc, { stepId, duplicateStepId }) => ({ ...acc, [duplicateStepId]: { ...cloneDeep(savedStepForms[stepId]), id: duplicateStepId, }, }), { ...savedStepForms } ) } case 'REPLACE_CUSTOM_LABWARE_DEF': { // no mismatch, it's safe to keep all steps as they are if (!action.payload.isOverwriteMismatched) return savedStepForms // Reset all well-selection fields of any steps, where the labware of those selected wells is having its def replaced // (otherwise, a mismatched definition with different wells or different multi-channel arrangement can break the step forms) const stepIds = Object.keys(savedStepForms) const labwareEntities = _getLabwareEntitiesRootState(rootState) const labwareIdsToDeselect = Object.keys(labwareEntities).filter( labwareId => labwareEntities[labwareId].labwareDefURI === action.payload.defURIToOverwrite ) const savedStepsUpdate = stepIds.reduce<SavedStepFormState>( (acc, stepId) => { const prevStepForm = savedStepForms[stepId] const defaults = getDefaultsForStepType(prevStepForm.stepType) if (!prevStepForm) { assert(false, `expected stepForm for id ${stepId}`) return acc } let fieldsToUpdate = {} if (prevStepForm.stepType === 'moveLiquid') { if (labwareIdsToDeselect.includes(prevStepForm.aspirate_labware)) { fieldsToUpdate = { ...fieldsToUpdate, aspirate_wells: defaults.aspirate_wells, } } if (labwareIdsToDeselect.includes(prevStepForm.dispense_labware)) { fieldsToUpdate = { ...fieldsToUpdate, dispense_wells: defaults.dispense_wells, } } } else if ( prevStepForm.stepType === 'mix' && labwareIdsToDeselect.includes(prevStepForm.labware) ) { fieldsToUpdate = { wells: defaults.wells, } } if (Object.keys(fieldsToUpdate).length === 0) { return acc } const updatedFields = handleFormChange( fieldsToUpdate, prevStepForm, _getPipetteEntitiesRootState(rootState), _getLabwareEntitiesRootState(rootState) ) return { ...acc, // TODO(IL, 2020-02-24): address in #3161, underspecified form fields may be overwritten in type-unsafe manner [stepId]: { ...prevStepForm, ...updatedFields }, } }, {} ) return { ...savedStepForms, ...savedStepsUpdate } } default: return savedStepForms } } export type BatchEditFormChangesState = FormPatch type BatchEditFormActions = | ChangeBatchEditFieldAction | ResetBatchEditFieldChangesAction | SaveStepFormsMultiAction | SelectStepAction | SelectMultipleStepsAction | DuplicateMultipleStepsAction | DeleteMultipleStepsAction export const batchEditFormChanges = ( state: BatchEditFormChangesState = {}, action: BatchEditFormActions ): BatchEditFormChangesState => { switch (action.type) { case 'CHANGE_BATCH_EDIT_FIELD': { return { ...state, ...action.payload } } case 'SELECT_STEP': case 'SAVE_STEP_FORMS_MULTI': case 'SELECT_MULTIPLE_STEPS': case 'DUPLICATE_MULTIPLE_STEPS': case 'DELETE_MULTIPLE_STEPS': case 'RESET_BATCH_EDIT_FIELD_CHANGES': { return {} } default: { return state } } } const initialLabwareState: NormalizedLabwareById = { [FIXED_TRASH_ID]: { labwareDefURI: 'opentrons/opentrons_1_trash_1100ml_fixed/1', }, } // MIGRATION NOTE: copied from `containers` reducer. Slot + UI stuff stripped out. export const labwareInvariantProperties: Reducer< NormalizedLabwareById, any // @ts-expect-error(sa, 2021-6-10): cannot use string literals as action type // TODO IMMEDIATELY: refactor this to the old fashioned way if we cannot have type safety: https://github.com/redux-utilities/redux-actions/issues/282#issuecomment-595163081 > = handleActions( { CREATE_CONTAINER: ( state: NormalizedLabwareById, action: CreateContainerAction ) => { return { ...state, [action.payload.id]: { labwareDefURI: action.payload.labwareDefURI, }, } }, DUPLICATE_LABWARE: ( state: NormalizedLabwareById, action: DuplicateLabwareAction ) => { return { ...state, [action.payload.duplicateLabwareId]: { labwareDefURI: state[action.payload.templateLabwareId].labwareDefURI, }, } }, DELETE_CONTAINER: ( state: NormalizedLabwareById, action: DeleteContainerAction ): NormalizedLabwareById => { return omit(state, action.payload.labwareId) }, LOAD_FILE: ( state: NormalizedLabwareById, action: LoadFileAction ): NormalizedLabwareById => { const { file } = action.payload return mapValues( file.labware, (fileLabware: FileLabware, id: string) => ({ labwareDefURI: fileLabware.definitionId, }) ) }, REPLACE_CUSTOM_LABWARE_DEF: ( state: NormalizedLabwareById, action: ReplaceCustomLabwareDef ): NormalizedLabwareById => mapValues( state, (prev: NormalizedLabware): NormalizedLabware => action.payload.defURIToOverwrite === prev.labwareDefURI ? { ...prev, labwareDefURI: getLabwareDefURI(action.payload.newDef), } : prev ), }, initialLabwareState ) export const moduleInvariantProperties: Reducer< ModuleEntities, any // @ts-expect-error(sa, 2021-6-10): cannot use string literals as action type // TODO IMMEDIATELY: refactor this to the old fashioned way if we cannot have type safety: https://github.com/redux-utilities/redux-actions/issues/282#issuecomment-595163081 > = handleActions( { CREATE_MODULE: ( state: ModuleEntities, action: CreateModuleAction ): ModuleEntities => ({ ...state, [action.payload.id]: { id: action.payload.id, type: action.payload.type, model: action.payload.model, }, }), EDIT_MODULE: ( state: ModuleEntities, action: EditModuleAction ): ModuleEntities => ({ ...state, [action.payload.id]: { ...state[action.payload.id], model: action.payload.model, }, }), DELETE_MODULE: ( state: ModuleEntities, action: DeleteModuleAction ): ModuleEntities => omit(state, action.payload.id), LOAD_FILE: ( state: ModuleEntities, action: LoadFileAction ): ModuleEntities => { const { file } = action.payload // @ts-expect-error(sa, 2021-6-10): falling back to {} will not create a valid `ModuleEntity`, as per TODO below it is theoritically unnecessary anyways return mapValues( // @ts-expect-error(sa, 2021-6-10): type narrow modules, they do not exist on the v3 schema file.modules || {}, // TODO: Ian 2019-11-11 this fallback to empty object is for JSONv3 protocols. Once JSONv4 is released, this should be handled in migration in PD (fileModule: FileModule, id: string) => ({ id, type: getModuleType(fileModule.model), model: fileModule.model, }) ) }, }, {} ) const initialPipetteState = {} export const pipetteInvariantProperties: Reducer< NormalizedPipetteById, any // @ts-expect-error(sa, 2021-6-10): cannot use string literals as action type // TODO IMMEDIATELY: refactor this to the old fashioned way if we cannot have type safety: https://github.com/redux-utilities/redux-actions/issues/282#issuecomment-595163081 > = handleActions( { LOAD_FILE: ( state: NormalizedPipetteById, action: LoadFileAction ): NormalizedPipetteById => { const { file } = action.payload const metadata = getPDMetadata(file) return mapValues( file.pipettes, ( filePipette: FilePipette, pipetteId: string ): NormalizedPipetteById[keyof NormalizedPipetteById] => { const tiprackDefURI = metadata.pipetteTiprackAssignments[pipetteId] assert( tiprackDefURI, `expected tiprackDefURI in file metadata for pipette ${pipetteId}` ) return { id: pipetteId, name: filePipette.name, tiprackDefURI, } } ) }, CREATE_PIPETTES: ( state: NormalizedPipetteById, action: CreatePipettesAction ): NormalizedPipetteById => { return { ...state, ...action.payload } }, DELETE_PIPETTES: ( state: NormalizedPipetteById, action: DeletePipettesAction ): NormalizedPipetteById => { return omit(state, action.payload) }, }, initialPipetteState ) export type OrderedStepIdsState = StepIdType[] const initialOrderedStepIdsState: string[] = [] // @ts-expect-error(sa, 2021-6-10): cannot use string literals as action type // TODO IMMEDIATELY: refactor this to the old fashioned way if we cannot have type safety: https://github.com/redux-utilities/redux-actions/issues/282#issuecomment-595163081 export const orderedStepIds: Reducer<OrderedStepIdsState, any> = handleActions( { SAVE_STEP_FORM: ( state: OrderedStepIdsState, action: SaveStepFormAction ) => { const id = action.payload.id if (!state.includes(id)) { return [...state, id] } return state }, DELETE_STEP: (state: OrderedStepIdsState, action: DeleteStepAction) => state.filter(stepId => stepId !== action.payload), DELETE_MULTIPLE_STEPS: ( state: OrderedStepIdsState, action: DeleteMultipleStepsAction ) => state.filter(id => !action.payload.includes(id)), LOAD_FILE: ( state: OrderedStepIdsState, action: LoadFileAction ): OrderedStepIdsState => getPDMetadata(action.payload.file).orderedStepIds, REORDER_SELECTED_STEP: ( state: OrderedStepIdsState, action: ReorderSelectedStepAction ): OrderedStepIdsState => { // TODO: BC 2018-11-27 make util function for reordering and use it everywhere const { delta, stepId } = action.payload const stepsWithoutSelectedStep = state.filter(s => s !== stepId) const selectedIndex = state.findIndex(s => s === stepId) const nextIndex = selectedIndex + delta if (delta <= 0 && selectedIndex === 0) return state return [ ...stepsWithoutSelectedStep.slice(0, nextIndex), stepId, ...stepsWithoutSelectedStep.slice(nextIndex), ] }, DUPLICATE_STEP: ( state: OrderedStepIdsState, action: DuplicateStepAction ): OrderedStepIdsState => { const { stepId, duplicateStepId } = action.payload const selectedIndex = state.findIndex(s => s === stepId) return [ ...state.slice(0, selectedIndex + 1), duplicateStepId, ...state.slice(selectedIndex + 1, state.length), ] }, DUPLICATE_MULTIPLE_STEPS: ( state: OrderedStepIdsState, action: DuplicateMultipleStepsAction ): OrderedStepIdsState => { const duplicateStepIds = action.payload.steps.map( ({ duplicateStepId }) => duplicateStepId ) const { indexToInsert } = action.payload return [ ...state.slice(0, indexToInsert), ...duplicateStepIds, ...state.slice(indexToInsert, state.length), ] }, REORDER_STEPS: ( state: OrderedStepIdsState, action: ReorderStepsAction ): OrderedStepIdsState => action.payload.stepIds, }, initialOrderedStepIdsState ) export type PresavedStepFormState = { stepType: StepType } | null export type PresavedStepFormAction = | AddStepAction | CancelStepFormAction | DeleteStepAction | DeleteMultipleStepsAction | SaveStepFormAction | SelectTerminalItemAction | SelectStepAction | SelectMultipleStepsAction export const presavedStepForm = ( state: PresavedStepFormState = null, action: PresavedStepFormAction ): PresavedStepFormState => { switch (action.type) { case 'ADD_STEP': return { stepType: action.payload.stepType, } case 'SELECT_TERMINAL_ITEM': return action.payload === PRESAVED_STEP_ID ? state : null case 'CANCEL_STEP_FORM': case 'DELETE_STEP': case 'DELETE_MULTIPLE_STEPS': case 'SAVE_STEP_FORM': case 'SELECT_STEP': case 'SELECT_MULTIPLE_STEPS': return null default: return state } } export interface RootState { orderedStepIds: OrderedStepIdsState labwareDefs: LabwareDefsRootState labwareInvariantProperties: NormalizedLabwareById pipetteInvariantProperties: NormalizedPipetteById moduleInvariantProperties: ModuleEntities presavedStepForm: PresavedStepFormState savedStepForms: SavedStepFormState unsavedForm: FormState batchEditFormChanges: BatchEditFormChangesState } // TODO Ian 2018-12-13: find some existing util to do this // semi-nested version of combineReducers? // TODO: Ian 2018-12-13 remove this 'action: any' type export const rootReducer: Reducer<RootState, any> = nestedCombineReducers( ({ action, state, prevStateFallback }) => ({ orderedStepIds: orderedStepIds(prevStateFallback.orderedStepIds, action), labwareInvariantProperties: labwareInvariantProperties( prevStateFallback.labwareInvariantProperties, action ), pipetteInvariantProperties: pipetteInvariantProperties( prevStateFallback.pipetteInvariantProperties, action ), moduleInvariantProperties: moduleInvariantProperties( prevStateFallback.moduleInvariantProperties, action ), labwareDefs: labwareDefsRootReducer(prevStateFallback.labwareDefs, action), // 'forms' reducers get full rootReducer state savedStepForms: savedStepForms(state, action), unsavedForm: unsavedForm(state, action), presavedStepForm: presavedStepForm( prevStateFallback.presavedStepForm, action ), batchEditFormChanges: batchEditFormChanges( prevStateFallback.batchEditFormChanges, action ), }) )
the_stack
export interface Result { /** * String identifying the format of the parsed MRZ. Supported formats are: * * * TD1 (identity card with three MRZ lines) * * TD2 (identity card with two MRZ lines) * * TD3 (passport) * * SWISS_DRIVING_LICENSE * * FRENCH_NATIONAL_ID */ format: 'TD1' | 'TD2' | 'TD3' | 'SWISS_DRIVING_LICENSE' | 'FRENCH_NATIONAL_ID'; /** `true` if all fields are valid. `false` otherwise. */ valid: boolean; /** * Object mapping field names to their respective value. The value is set to `null` * if it is invalid. The value may be different than the raw value. For example * `result.fields.sex` will be "male" when the raw value was "M". */ fields: ResultFields; /** * Array of objects describing all parsed fields. */ details: ResultDetails[]; } export interface ResultFields { documentNumber: string | null; documentNumberCheckDigit: string | null; documentCode: string | null; nationality: string | null; sex: 'male' | 'female' | 'nonspecified' | null; expirationDate: string | null; expirationDateCheckDigit: string | null; compositeCheckDigit: string | null; birthDate: string | null; birthDateCheckDigit: string | null; issueDate: string | null; firstName: string | null; lastName: string | null; issuingState: string | null; // td1 only optional1?: string | undefined; optional2?: string | undefined; // td2 only optional?: string | undefined; // td3 only personalNumber?: string | undefined; personalNumberCheckDigit?: string | undefined; // french national id only administrativeCode?: string | undefined; administrativeCode2?: string | undefined; // swiss driving license only languageCode?: string | undefined; pinCode?: string | undefined; versionNumber?: string | undefined; } export interface ResultDetails { /** Full english term for the field. */ label: string; /** Name of the field in `result.fields`. */ field: keyof Result['fields']; /** Value of the field or `null`. */ value: string | null; valid: boolean; /** Array of ranges that are necessary to compute this field. */ ranges: Range[]; /** Index of the line where the field is located. */ line: number; /** Index of the start of the field in `line`. */ start: number; /** Index of the end of the field in `line`. */ end: number; } export interface Range { line: number; start: number; end: number; raw: string; } /** * Parses the provided MRZ. The argument can be an array of lines or a single string * including line breaks. This function throws an error if the input is in an * unsupported format. It will never throw an error when there are invalid fields * in the MRZ. Instead, the `result.valid` value will be `false` and * details about the invalid fields can be found in `result.details`. */ export function parse(lines: string | ReadonlyArray<string>): Result; export namespace parse { function FRENCH_NATIONAL_ID(lines: string | ReadonlyArray<string>): Result; function SWISS_DRIVING_LICENSE(lines: string | ReadonlyArray<string>): Result; function TD1(lines: string | ReadonlyArray<string>): Result; function TD2(lines: string | ReadonlyArray<string>): Result; function TD3(lines: string | ReadonlyArray<string>): Result; } export const formats: { readonly TD1: 'TD1'; readonly TD2: 'TD2'; readonly TD3: 'TD3'; readonly SWISS_DRIVING_LICENSE: 'SWISS_DRIVING_LICENSE'; readonly FRENCH_NATIONAL_ID: 'FRENCH_NATIONAL_ID'; }; export const states: { readonly ABW: string; readonly AFG: string; readonly AGO: string; readonly AIA: string; readonly ALA: string; readonly ALB: string; readonly AND: string; readonly ANT: string; readonly ARE: string; readonly ARG: string; readonly ARM: string; readonly ASM: string; readonly ATA: string; readonly ATF: string; readonly ATG: string; readonly AUS: string; readonly AUT: string; readonly AZE: string; readonly BDI: string; readonly BEL: string; readonly BEN: string; readonly BES: string; readonly BFA: string; readonly BGD: string; readonly BGR: string; readonly BHR: string; readonly BHS: string; readonly BIH: string; readonly BLM: string; readonly BLR: string; readonly BLZ: string; readonly BMU: string; readonly BOL: string; readonly BRA: string; readonly BRB: string; readonly BRN: string; readonly BTN: string; readonly BVT: string; readonly BWA: string; readonly CAF: string; readonly CAN: string; readonly CCK: string; readonly CHE: string; readonly CHL: string; readonly CHN: string; readonly CIV: string; readonly CMR: string; readonly COD: string; readonly COG: string; readonly COK: string; readonly COL: string; readonly COM: string; readonly CPV: string; readonly CRI: string; readonly CUB: string; readonly CUW: string; readonly CXR: string; readonly CYM: string; readonly CYP: string; readonly CZE: string; readonly D: string; readonly DJI: string; readonly DMA: string; readonly DNK: string; readonly DOM: string; readonly DZA: string; readonly ECU: string; readonly EGY: string; readonly ERI: string; readonly ESH: string; readonly ESP: string; readonly EST: string; readonly ETH: string; readonly EUE: string; readonly FIN: string; readonly FJI: string; readonly FLK: string; readonly FRA: string; readonly FRO: string; readonly FSM: string; readonly GAB: string; readonly GBD: string; readonly GBN: string; readonly GBO: string; readonly GBP: string; readonly GBR: string; readonly GEO: string; readonly GGY: string; readonly GHA: string; readonly GIB: string; readonly GIN: string; readonly GLP: string; readonly GMB: string; readonly GNB: string; readonly GNQ: string; readonly GRC: string; readonly GRD: string; readonly GRL: string; readonly GTM: string; readonly GUF: string; readonly GUM: string; readonly GUY: string; readonly HKG: string; readonly HMD: string; readonly HND: string; readonly HRV: string; readonly HTI: string; readonly HUN: string; readonly IDN: string; readonly IMN: string; readonly IND: string; readonly IOT: string; readonly IRL: string; readonly IRN: string; readonly IRQ: string; readonly ISL: string; readonly ISR: string; readonly ITA: string; readonly JAM: string; readonly JEY: string; readonly JOR: string; readonly JPN: string; readonly KAZ: string; readonly KEN: string; readonly KGZ: string; readonly KHM: string; readonly KIR: string; readonly KNA: string; readonly KOR: string; readonly KWT: string; readonly LAO: string; readonly LBN: string; readonly LBR: string; readonly LBY: string; readonly LCA: string; readonly LIE: string; readonly LKA: string; readonly LSO: string; readonly LTU: string; readonly LUX: string; readonly LVA: string; readonly MAC: string; readonly MAF: string; readonly MAR: string; readonly MCO: string; readonly MDA: string; readonly MDG: string; readonly MDV: string; readonly MEX: string; readonly MHL: string; readonly MKD: string; readonly MLI: string; readonly MLT: string; readonly MMR: string; readonly MNE: string; readonly MNG: string; readonly MNP: string; readonly MOZ: string; readonly MRT: string; readonly MSR: string; readonly MTQ: string; readonly MUS: string; readonly MWI: string; readonly MYS: string; readonly MYT: string; readonly NAM: string; readonly NCL: string; readonly NER: string; readonly NFK: string; readonly NGA: string; readonly NIC: string; readonly NIU: string; readonly NLD: string; readonly NOR: string; readonly NPL: string; readonly NRU: string; readonly NTZ: string; readonly NZL: string; readonly OMN: string; readonly PAK: string; readonly PAN: string; readonly PCN: string; readonly PER: string; readonly PHL: string; readonly PLW: string; readonly PNG: string; readonly POL: string; readonly PRI: string; readonly PRK: string; readonly PRT: string; readonly PRY: string; readonly PSE: string; readonly PYF: string; readonly QAT: string; readonly REU: string; readonly ROU: string; readonly RUS: string; readonly RWA: string; readonly SAU: string; readonly SDN: string; readonly SEN: string; readonly SGP: string; readonly SGS: string; readonly SHN: string; readonly SJM: string; readonly SLB: string; readonly SLE: string; readonly SLV: string; readonly SMR: string; readonly SOM: string; readonly SPM: string; readonly SRB: string; readonly SSD: string; readonly STP: string; readonly SUR: string; readonly SVK: string; readonly SVN: string; readonly SWE: string; readonly SWZ: string; readonly SXM: string; readonly SYC: string; readonly SYR: string; readonly TCA: string; readonly TCD: string; readonly TGO: string; readonly THA: string; readonly TJK: string; readonly TKL: string; readonly TKM: string; readonly TLS: string; readonly TON: string; readonly TTO: string; readonly TUN: string; readonly TUR: string; readonly TUV: string; readonly TWN: string; readonly TZA: string; readonly UGA: string; readonly UKR: string; readonly UMI: string; readonly UNA: string; readonly UNK: string; readonly UNO: string; readonly URY: string; readonly USA: string; readonly UZB: string; readonly VAT: string; readonly VCT: string; readonly VEN: string; readonly VGB: string; readonly VIR: string; readonly VNM: string; readonly VUT: string; readonly WLF: string; readonly WSM: string; readonly XBA: string; readonly XCC: string; readonly XCO: string; readonly XEC: string; readonly XIM: string; readonly XOM: string; readonly XPO: string; readonly XXA: string; readonly XXB: string; readonly XXX: string; readonly YEM: string; readonly ZAF: string; readonly ZMB: string; readonly ZWE: string; readonly [code: string]: string | undefined; };
the_stack
import isNull from 'lodash/isNull'; import isUndefined from 'lodash/isUndefined'; import { MouseEvent as ReactMouseEvent, useContext, useEffect, useState } from 'react'; import { IoMdRefresh, IoMdRefreshCircle } from 'react-icons/io'; import { MdAdd, MdAddCircle } from 'react-icons/md'; import { RiArrowLeftRightLine } from 'react-icons/ri'; import { useHistory } from 'react-router-dom'; import API from '../../../api'; import { AppCtx, unselectOrg } from '../../../context/AppCtx'; import { AuthorizerAction, ErrorKind, Repository as Repo, SearchQuery } from '../../../types'; import ExternalLink from '../../common/ExternalLink'; import Loading from '../../common/Loading'; import NoData from '../../common/NoData'; import Pagination from '../../common/Pagination'; import ActionBtn from '../ActionBtn'; import RepositoryCard from './Card'; import ClaimOwnershipRepositoryModal from './ClaimOwnershipModal'; import RepositoryModal from './Modal'; import styles from './Repository.module.css'; interface ModalStatus { open: boolean; repository?: Repo; } interface Props { onAuthError: () => void; repoName?: string; visibleModal?: string; activePage?: string; } const DEFAULT_LIMIT = 10; const RepositoriesSection = (props: Props) => { const history = useHistory(); const { ctx, dispatch } = useContext(AppCtx); const [isLoading, setIsLoading] = useState(false); const [modalStatus, setModalStatus] = useState<ModalStatus>({ open: false, }); const [openClaimRepo, setOpenClaimRepo] = useState<boolean>(false); const [repositories, setRepositories] = useState<Repo[] | undefined>(undefined); const [activeOrg, setActiveOrg] = useState<undefined | string>(ctx.prefs.controlPanel.selectedOrg); const [apiError, setApiError] = useState<null | string>(null); const [activePage, setActivePage] = useState<number>(props.activePage ? parseInt(props.activePage) : 1); const calculateOffset = (pageNumber?: number): number => { return DEFAULT_LIMIT * ((pageNumber || activePage) - 1); }; const [offset, setOffset] = useState<number>(calculateOffset()); const [total, setTotal] = useState<number | undefined>(undefined); const onPageNumberChange = (pageNumber: number): void => { setOffset(calculateOffset(pageNumber)); setActivePage(pageNumber); }; const updatePageNumber = () => { history.replace({ search: `?page=${activePage}${props.repoName ? `&repo-name=${props.repoName}` : ''}${ props.visibleModal ? `&modal=${props.visibleModal}` : '' }`, }); }; async function fetchRepositories() { try { setIsLoading(true); let filters: { [key: string]: string[] } = {}; if (activeOrg) { filters.org = [activeOrg]; } else { filters.user = [ctx.user!.alias]; } let query: SearchQuery = { offset: offset, limit: DEFAULT_LIMIT, filters: filters, }; const data = await API.searchRepositories(query); const total = parseInt(data.paginationTotalCount); if (total > 0 && data.items.length === 0) { onPageNumberChange(1); } else { const repos = data.items; setRepositories(repos); setTotal(total); // Check if active repo logs modal is in the available repos if (!isUndefined(props.repoName)) { const activeRepo = repos.find((repo: Repo) => repo.name === props.repoName); // Clean query string if repo is not available if (isUndefined(activeRepo)) { dispatch(unselectOrg()); history.replace({ search: `?page=${activePage}`, }); } } else { updatePageNumber(); } } setApiError(null); setIsLoading(false); } catch (err: any) { setIsLoading(false); if (err.kind !== ErrorKind.Unauthorized) { setApiError('An error occurred getting the repositories, please try again later.'); setRepositories([]); } else { props.onAuthError(); } } } useEffect(() => { if (isUndefined(props.activePage)) { updatePageNumber(); } }, []); /* eslint-disable-line react-hooks/exhaustive-deps */ useEffect(() => { if (props.activePage && activePage !== parseInt(props.activePage)) { fetchRepositories(); } }, [activePage]); /* eslint-disable-line react-hooks/exhaustive-deps */ useEffect(() => { if (!isUndefined(repositories)) { if (activePage === 1) { // fetchRepositories is forced when context changes fetchRepositories(); } else { // when current page is different to 1, to update page number fetchRepositories is called onPageNumberChange(1); } } }, [activeOrg]); /* eslint-disable-line react-hooks/exhaustive-deps */ useEffect(() => { if (activeOrg !== ctx.prefs.controlPanel.selectedOrg) { setActiveOrg(ctx.prefs.controlPanel.selectedOrg); } }, [ctx.prefs.controlPanel.selectedOrg]); /* eslint-disable-line react-hooks/exhaustive-deps */ useEffect(() => { fetchRepositories(); }, []); /* eslint-disable-line react-hooks/exhaustive-deps */ return ( <main role="main" className="pe-xs-0 pe-sm-3 pe-md-0 d-flex flex-column flex-md-row justify-content-between my-md-4" > <div className="flex-grow-1 w-100"> <div> <div className="d-flex flex-row align-items-center justify-content-between pb-2 border-bottom"> <div className={`h3 pb-0 ${styles.title}`}>Repositories</div> <div> <button className={`btn btn-outline-secondary btn-sm text-uppercase me-0 me-md-2 ${styles.btnAction}`} onClick={fetchRepositories} aria-label="Refresh repositories list" > <div className="d-flex flex-row align-items-center justify-content-center"> <IoMdRefresh className="d-inline d-md-none" /> <IoMdRefreshCircle className="d-none d-md-inline me-2" /> <span className="d-none d-md-inline">Refresh</span> </div> </button> <button className={`btn btn-outline-secondary btn-sm text-uppercase me-0 me-md-2 ${styles.btnAction}`} onClick={() => setOpenClaimRepo(true)} aria-label="Open claim repository modal" > <div className="d-flex flex-row align-items-center justify-content-center"> <RiArrowLeftRightLine className="me-md-2" /> <span className="d-none d-md-inline">Claim ownership</span> </div> </button> <ActionBtn className={`btn btn-outline-secondary btn-sm text-uppercase ${styles.btnAction}`} contentClassName="justify-content-center" onClick={(e: ReactMouseEvent<HTMLButtonElement>) => { e.preventDefault(); setModalStatus({ open: true }); }} action={AuthorizerAction.AddOrganizationRepository} label="Open add repository modal" > <> <MdAdd className="d-inline d-md-none" /> <MdAddCircle className="d-none d-md-inline me-2" /> <span className="d-none d-md-inline">Add</span> </> </ActionBtn> </div> </div> </div> {modalStatus.open && ( <RepositoryModal open={modalStatus.open} repository={modalStatus.repository} onSuccess={fetchRepositories} onAuthError={props.onAuthError} onClose={() => setModalStatus({ open: false })} /> )} {openClaimRepo && ( <ClaimOwnershipRepositoryModal open={openClaimRepo} onAuthError={props.onAuthError} onClose={() => setOpenClaimRepo(false)} onSuccess={fetchRepositories} /> )} {(isLoading || isUndefined(repositories)) && <Loading />} <p className="mt-5"> If you want your repositories to be labeled as <span className="fw-bold">Verified Publisher</span>, you can add a{' '} <ExternalLink href="https://github.com/artifacthub/hub/blob/master/docs/metadata/artifacthub-repo.yml" className="text-reset" label="Open documentation" > <u>metadata file</u> </ExternalLink>{' '} to each of them including the repository ID provided below. This label will let users know that you own or have control over the repository. The repository metadata file must be located at the path used in the repository URL. </p> {!isUndefined(repositories) && ( <> {repositories.length === 0 ? ( <NoData issuesLinkVisible={!isNull(apiError)}> {isNull(apiError) ? ( <> <p className="h6 my-4">Add your first repository!</p> <ActionBtn className="btn btn-sm btn-outline-secondary" onClick={(e: ReactMouseEvent<HTMLButtonElement>) => { e.preventDefault(); setModalStatus({ open: true }); }} action={AuthorizerAction.AddOrganizationRepository} label="Open add first repository modal" > <div className="d-flex flex-row align-items-center text-uppercase"> <MdAddCircle className="me-2" /> <span>Add repository</span> </div> </ActionBtn> </> ) : ( <>{apiError}</> )} </NoData> ) : ( <> <div className="row mt-3 mt-md-4 gx-0 gx-xxl-4" data-testid="repoList"> {repositories.map((repo: Repo) => ( <RepositoryCard key={`repo_${repo.name}`} repository={repo} visibleModal={ // Legacy - old tracking errors email were not passing modal param !isUndefined(props.repoName) && repo.name === props.repoName ? props.visibleModal || 'tracking' : undefined } setModalStatus={setModalStatus} onSuccess={fetchRepositories} onAuthError={props.onAuthError} /> ))} </div> {!isUndefined(total) && ( <Pagination limit={DEFAULT_LIMIT} offset={offset} total={total} active={activePage} className="my-5" onChange={onPageNumberChange} /> )} </> )} </> )} </div> </main> ); }; export default RepositoriesSection;
the_stack
import { Logger } from 'common/logging/logger'; import { PromiseFactory, TimeoutError } from 'common/promises/promise-factory'; import { WindowMessagePoster } from 'injected/frameCommunicators/browser-backchannel-window-message-poster'; export type CommandMessage = { command: string; payload?: any; }; export type CommandMessageResponse = { // if payload is null, this means that there is nothing in this response message payload: any; }; export type CommandMessageResponseCallback = (response: CommandMessageResponse) => void; // A listener may optionally respond to a message it receives. If it wishes to do so, it should // return a Promise which resolves to the response. If it does not wish to respond to a message, // it will return a Promise that resolves to null. export type PromiseWindowCommandMessageListener = ( receivedMessage: CommandMessage, sourceWindow: Window, ) => Promise<CommandMessageResponse | null>; export type CallbackWindowCommandMessageListener = ( receivedMessage: CommandMessage, sourceWindow: Window, // When the listener has finished its word and determined a response, it should invoke this // responseCallback. That will result in the corresponding sendCallbackCommandMessage's // replyHandler being called. responseCallback: CommandMessageResponseCallback, ) => void; type WindowCommandMessageListenerRegistration = | { type: 'callback'; listener: CallbackWindowCommandMessageListener; } | { type: 'promise'; listener: PromiseWindowCommandMessageListener; }; type CommandMessageRequestWrapper = { type: 'CommandMessageRequest'; commandMessageId: string; // not the same as the window message's messageId! command: string; payload?: any; }; type CommandMessageResponseWrapper = { type: 'CommandMessageResponse'; requestCommandMessageId: string; // corresponds to the request's commandMessageId. Not related to the window message's messageId! payload: any; }; // RespondableCommandMessageCommunicator is responsible for: // * assigning listeners to commands (each command can only have one) // * assigning command message requests a unique commandMessageId and posting them to the window // * associating pending response callbacks to command requests using the new commandMessageId // * sending command response to pending response callbacks when a response is received from the window // // FrameMessenger and AxeFrameMessenger use a RespondableCommandMessageCommunicator to coordinate // commands between target page frames. export class RespondableCommandMessageCommunicator { // Single-use responseCallbacks are responsible for unregistering themselves when called. private responseCallbacks: { [requestMessageId: string]: CommandMessageResponseCallback; } = {}; private listenersByCommand: { [command: string]: WindowCommandMessageListenerRegistration; } = {}; // This needs to be long enough to consistently allow for a big, slow page to finish loading our // injected bundle, run our initializer, and allow for several round trips to the background // page (there will be 2 per nested iframe), even on a slow VM. public static promiseResponseTimeoutMilliseconds = 30000; constructor( private readonly windowMessagePoster: WindowMessagePoster, private readonly generateUIDFunc: () => string, private readonly promiseFactory: PromiseFactory, private readonly logger: Logger, ) {} public initialize() { this.windowMessagePoster.addMessageListener(this.onWindowMessage); } // Sends a message to a corresponding listener in the target Window, which must have been // previously registered using addCallbackCommandMessageListener in that Window. The provided // responseCallback will be invoked if and when the corresponding listener invokes the // corresponding responseCallback passed to it in the target Window. // // If allowMultipleResponses is specified, this will be allowed to happen multiple times. This // capability is required per axe-core's frameMessenger documentation, but it should only be // used if actually necessary, since there is currently no way for the communicator to know when // it's allowed to stop listening for further responses. public sendCallbackCommandMessage( target: Window, commandMessage: CommandMessage, responseCallback: (response: CommandMessageResponse) => void, responsesExpected: 'single' | 'multiple', ): void { const commandMessageRequestWrapper = this.createCommandMessageRequestWrapper(commandMessage); const messageId = commandMessageRequestWrapper.commandMessageId; let recordedResponseCallback = responseCallback; if (responsesExpected === 'single') { recordedResponseCallback = response => { delete this.responseCallbacks[messageId]; responseCallback(response); }; } this.responseCallbacks[messageId] = recordedResponseCallback; this.windowMessagePoster.postMessage(target, commandMessageRequestWrapper); } // Sends a message to a corresponding listener in the target Window, which must have been // previously registered using addPromiseCommandMessageListener in that Window. The returned // Promise will resolve if and when the corresponding listener in the target Window resolves. // // Unlike sendCallbackCommandMessage, this method has a timeout built in (see // RespondableCommandMessageCommunicator.promiseResponseTimeoutMilliseconds) public async sendPromiseCommandMessage( target: Window, commandMessage: CommandMessage, ): Promise<CommandMessageResponse> { let timedOut = false; // This creates a "deferred" Promise which we will resolved later in onWindowMessage (by // calling the resolver function we're storing in pendingResponseResolvers) when we receive // a matching response from the windowMessagePoster. let pendingResponseResolver: CommandMessageResponseCallback; const pendingResponsePromise = new Promise<CommandMessageResponse>(resolver => { pendingResponseResolver = resolver; }); const responseCallback = (response: CommandMessageResponse) => { if (timedOut) { this.logger.error( `Received a response for command ${commandMessage.command} after it timed out`, ); } pendingResponseResolver(response); }; this.sendCallbackCommandMessage(target, commandMessage, responseCallback, 'single'); try { return await this.promiseFactory.timeout( pendingResponsePromise, RespondableCommandMessageCommunicator.promiseResponseTimeoutMilliseconds, ); } catch (e) { // Timeout is the only option here; we never use (or store) the reject callback from // pendingResponsePromise timedOut = true; throw new TimeoutError( 'Timed out attempting to establish communication with target window. ' + 'Is there a script inside it intercepting window messages? ' + `Underlying error: ${e.message}`, ); } } // Registers a listener that will be invoked when other Windows make corresponding // sendPromiseCommandMessage invocations. Each time such a message is sent, the listener will be // called. The response the listener resolves with will become the value that the corresponding // sendPromiseCommandMessage call in the other Window resolves with. public addPromiseCommandMessageListener( command: string, listener: PromiseWindowCommandMessageListener, ): void { this.addCommandMessageListener(command, { type: 'promise', listener: listener }); } // Registers a listener that will be invoked when other Windows make corresponding // sendCallbackCommandMessage invocations. Each time such a message is sent, the listener will // be called with a new responseCallback. Each time the listener invokes that responseCallback, // the corresponding responseCallback that was passed to sendCallbackCommandMessage in the other // Window will be invoked with the same response. public addCallbackCommandMessageListener( command: string, listener: CallbackWindowCommandMessageListener, ): void { this.addCommandMessageListener(command, { type: 'callback', listener: listener }); } public removeCommandMessageListener(command: string): void { delete this.listenersByCommand[command]; } private addCommandMessageListener( command: string, listener: WindowCommandMessageListenerRegistration, ): void { if (this.listenersByCommand[command] != null) { throw new Error(`Cannot register two listeners for the same command (${command})`); } this.listenersByCommand[command] = listener; } private onWindowMessage = async (receivedMessage: any, sourceWindow: Window): Promise<void> => { if (isCommandMessageRequestWrapper(receivedMessage)) { await this.onRequestMessage(receivedMessage, sourceWindow); } else if (isCommandMessageResponseWrapper(receivedMessage)) { await this.onResponseMessage(receivedMessage); } }; private onResponseMessage = async ( receivedMessage: CommandMessageResponseWrapper, ): Promise<void> => { const responseCallback = this.responseCallbacks[receivedMessage.requestCommandMessageId]; const unwrappedResponse = { payload: receivedMessage.payload }; await this.logErrors(`${receivedMessage.requestCommandMessageId} response callback`, () => { responseCallback?.(unwrappedResponse); }); }; private onRequestMessage = async ( receivedMessage: CommandMessageRequestWrapper, sourceWindow: Window, ): Promise<void> => { const { command, commandMessageId } = receivedMessage; const unwrappedRequest: CommandMessage = { command: receivedMessage.command, payload: receivedMessage.payload, }; const listener = this.listenersByCommand[command]; const sendResponse = this.makeSendResponseCallback(commandMessageId, sourceWindow); if (listener == null) { sendResponse({ payload: null }); } else if (listener.type === 'callback') { await this.logErrors(`${command} listener callback`, () => listener.listener(unwrappedRequest, sourceWindow, sendResponse), ); } else if (listener.type === 'promise') { let listenerResponse: CommandMessageResponse | null = null; await this.logErrors(`${command} promise listener`, async () => { const possibleResponsePromise = listener.listener(unwrappedRequest, sourceWindow); if (possibleResponsePromise instanceof Promise) { listenerResponse = await possibleResponsePromise; } }); if (listenerResponse == null) { listenerResponse = { payload: null }; } sendResponse(listenerResponse); } }; private async logErrors(context, operation) { try { operation(); } catch (e) { this.logger.error(`Error at ${context}: ${e.message}`, e); } } private makeSendResponseCallback( requestCommandMessageId: string, sourceWindow: Window, ): CommandMessageResponseCallback { return (response: CommandMessageResponse) => { const responseWrapper = this.createCommandMessageResponseWrapper( requestCommandMessageId, response, ); this.windowMessagePoster.postMessage(sourceWindow, responseWrapper); }; } private createCommandMessageRequestWrapper( commandMessage: CommandMessage, ): CommandMessageRequestWrapper { const commandMessageId = this.generateUIDFunc(); return { type: 'CommandMessageRequest', commandMessageId, ...commandMessage, }; } private createCommandMessageResponseWrapper( commandMessageId: string, commandMessageResponse: CommandMessageResponse, ): CommandMessageResponseWrapper { return { type: 'CommandMessageResponse', requestCommandMessageId: commandMessageId, payload: commandMessageResponse.payload, }; } } function isCommandMessageRequestWrapper( rawMessage: any, ): rawMessage is CommandMessageRequestWrapper { return ( typeof rawMessage === 'object' && rawMessage.type === 'CommandMessageRequest' && typeof rawMessage.commandMessageId === 'string' && typeof rawMessage.command === 'string' ); } function isCommandMessageResponseWrapper( rawMessage: any, ): rawMessage is CommandMessageResponseWrapper { return ( typeof rawMessage === 'object' && rawMessage.type === 'CommandMessageResponse' && typeof rawMessage.requestCommandMessageId === 'string' ); }
the_stack
// (C) 1995-2013 Jean-loup Gailly and Mark Adler // (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin // // This software is provided 'as-is', without any express or implied // warranty. In no event will the authors be held liable for any damages // arising from the use of this software. // // Permission is granted to anyone to use this software for any purpose, // including commercial applications, and to alter it and redistribute it // freely, subject to the following restrictions: // // 1. The origin of this software must not be misrepresented; you must not // claim that you wrote the original software. If you use this software // in a product, an acknowledgment in the product documentation would be // appreciated but is not required. // 2. Altered source versions must be plainly marked as such, and must not be // misrepresented as being the original software. // 3. This notice may not be removed or altered from any source distribution. import * as utils from "../utils/common.js"; var MAXBITS = 15; var ENOUGH_LENS = 852; var ENOUGH_DISTS = 592; //var ENOUGH = (ENOUGH_LENS+ENOUGH_DISTS); var CODES = 0; var LENS = 1; var DISTS = 2; var lbase = [ /* Length codes 257..285 base */ 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31, 35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258, 0, 0 ]; var lext = [ /* Length codes 257..285 extra */ 16, 16, 16, 16, 16, 16, 16, 16, 17, 17, 17, 17, 18, 18, 18, 18, 19, 19, 19, 19, 20, 20, 20, 20, 21, 21, 21, 21, 16, 72, 78 ]; var dbase = [ /* Distance codes 0..29 base */ 1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193, 257, 385, 513, 769, 1025, 1537, 2049, 3073, 4097, 6145, 8193, 12289, 16385, 24577, 0, 0 ]; var dext = [ /* Distance codes 0..29 extra */ 16, 16, 16, 16, 17, 17, 18, 18, 19, 19, 20, 20, 21, 21, 22, 22, 23, 23, 24, 24, 25, 25, 26, 26, 27, 27, 28, 28, 29, 29, 64, 64 ]; export function inflate_table(type, lens, lens_index, codes, table, table_index, work, opts) { var bits = opts.bits; //here = opts.here; /* table entry for duplication */ var len = 0; /* a code's length in bits */ var sym = 0; /* index of code symbols */ var min = 0, max = 0; /* minimum and maximum code lengths */ var root = 0; /* number of index bits for root table */ var curr = 0; /* number of index bits for current table */ var drop = 0; /* code bits to drop for sub-table */ var left = 0; /* number of prefix codes available */ var used = 0; /* code entries in table used */ var huff = 0; /* Huffman code */ var incr; /* for incrementing code, index */ var fill; /* index for replicating entries */ var low; /* low bits for current root entry */ var mask; /* mask for low root bits */ var next; /* next available space in table */ var base = null; /* base value table to use */ var base_index = 0; // var shoextra; /* extra bits table to use */ var end; /* use base and extra for symbol > end */ var count = new utils.Buf16(MAXBITS + 1); //[MAXBITS+1]; /* number of codes of each length */ var offs = new utils.Buf16(MAXBITS + 1); //[MAXBITS+1]; /* offsets in table for each length */ var extra = null; var extra_index = 0; var here_bits, here_op, here_val; /* Process a set of code lengths to create a canonical Huffman code. The code lengths are lens[0..codes-1]. Each length corresponds to the symbols 0..codes-1. The Huffman code is generated by first sorting the symbols by length from short to long, and retaining the symbol order for codes with equal lengths. Then the code starts with all zero bits for the first code of the shortest length, and the codes are integer increments for the same length, and zeros are appended as the length increases. For the deflate format, these bits are stored backwards from their more natural integer increment ordering, and so when the decoding tables are built in the large loop below, the integer codes are incremented backwards. This routine assumes, but does not check, that all of the entries in lens[] are in the range 0..MAXBITS. The caller must assure this. 1..MAXBITS is interpreted as that code length. zero means that that symbol does not occur in this code. The codes are sorted by computing a count of codes for each length, creating from that a table of starting indices for each length in the sorted table, and then entering the symbols in order in the sorted table. The sorted table is work[], with that space being provided by the caller. The length counts are used for other purposes as well, i.e. finding the minimum and maximum length codes, determining if there are any codes at all, checking for a valid set of lengths, and looking ahead at length counts to determine sub-table sizes when building the decoding tables. */ /* accumulate lengths for codes (assumes lens[] all in 0..MAXBITS) */ for (len = 0; len <= MAXBITS; len++) { count[len] = 0; } for (sym = 0; sym < codes; sym++) { count[lens[lens_index + sym]]++; } /* bound code lengths, force root to be within code lengths */ root = bits; for (max = MAXBITS; max >= 1; max--) { if (count[max] !== 0) { break; } } if (root > max) { root = max; } if (max === 0) { /* no symbols to code at all */ //table.op[opts.table_index] = 64; //here.op = (var char)64; /* invalid code marker */ //table.bits[opts.table_index] = 1; //here.bits = (var char)1; //table.val[opts.table_index++] = 0; //here.val = (var short)0; table[table_index++] = (1 << 24) | (64 << 16) | 0; //table.op[opts.table_index] = 64; //table.bits[opts.table_index] = 1; //table.val[opts.table_index++] = 0; table[table_index++] = (1 << 24) | (64 << 16) | 0; opts.bits = 1; return 0; /* no symbols, but wait for decoding to report error */ } for (min = 1; min < max; min++) { if (count[min] !== 0) { break; } } if (root < min) { root = min; } /* check for an over-subscribed or incomplete set of lengths */ left = 1; for (len = 1; len <= MAXBITS; len++) { left <<= 1; left -= count[len]; if (left < 0) { return -1; } /* over-subscribed */ } if (left > 0 && (type === CODES || max !== 1)) { return -1; /* incomplete set */ } /* generate offsets into symbol table for each length for sorting */ offs[1] = 0; for (len = 1; len < MAXBITS; len++) { offs[len + 1] = offs[len] + count[len]; } /* sort symbols by length, by symbol order within each length */ for (sym = 0; sym < codes; sym++) { if (lens[lens_index + sym] !== 0) { work[offs[lens[lens_index + sym]]++] = sym; } } /* Create and fill in decoding tables. In this loop, the table being filled is at next and has curr index bits. The code being used is huff with length len. That code is converted to an index by dropping drop bits off of the bottom. For codes where len is less than drop + curr, those top drop + curr - len bits are incremented through all values to fill the table with replicated entries. root is the number of index bits for the root table. When len exceeds root, sub-tables are created pointed to by the root entry with an index of the low root bits of huff. This is saved in low to check for when a new sub-table should be started. drop is zero when the root table is being filled, and drop is root when sub-tables are being filled. When a new sub-table is needed, it is necessary to look ahead in the code lengths to determine what size sub-table is needed. The length counts are used for this, and so count[] is decremented as codes are entered in the tables. used keeps track of how many table entries have been allocated from the provided *table space. It is checked for LENS and DIST tables against the constants ENOUGH_LENS and ENOUGH_DISTS to guard against changes in the initial root table size constants. See the comments in inftrees.h for more information. sym increments through all symbols, and the loop terminates when all codes of length max, i.e. all codes, have been processed. This routine permits incomplete codes, so another loop after this one fills in the rest of the decoding tables with invalid code markers. */ /* set up for code type */ // poor man optimization - use if-else instead of switch, // to avoid deopts in old v8 if (type === CODES) { base = extra = work; /* dummy value--not used */ end = 19; } else if (type === LENS) { base = lbase; base_index -= 257; extra = lext; extra_index -= 257; end = 256; } else { /* DISTS */ base = dbase; extra = dext; end = -1; } /* initialize opts for loop */ huff = 0; /* starting code */ sym = 0; /* starting code symbol */ len = min; /* starting code length */ next = table_index; /* current table to fill in */ curr = root; /* current table index bits */ drop = 0; /* current bits to drop from code for index */ low = -1; /* trigger new sub-table when len > root */ used = 1 << root; /* use root table entries */ mask = used - 1; /* mask for comparing low */ /* check available table space */ if ((type === LENS && used > ENOUGH_LENS) || (type === DISTS && used > ENOUGH_DISTS)) { return 1; } /* process all codes and make table entries */ for (;;) { /* create table entry */ here_bits = len - drop; if (work[sym] < end) { here_op = 0; here_val = work[sym]; } else if (work[sym] > end) { here_op = extra[extra_index + work[sym]]; here_val = base[base_index + work[sym]]; } else { here_op = 32 + 64; /* end of block */ here_val = 0; } /* replicate for those indices with low len bits equal to huff */ incr = 1 << (len - drop); fill = 1 << curr; min = fill; /* save offset to next table */ do { fill -= incr; table[next + (huff >> drop) + fill] = (here_bits << 24) | (here_op << 16) | here_val |0; } while (fill !== 0); /* backwards increment the len-bit code huff */ incr = 1 << (len - 1); while (huff & incr) { incr >>= 1; } if (incr !== 0) { huff &= incr - 1; huff += incr; } else { huff = 0; } /* go to next symbol, update count, len */ sym++; if (--count[len] === 0) { if (len === max) { break; } len = lens[lens_index + work[sym]]; } /* create new sub-table if needed */ if (len > root && (huff & mask) !== low) { /* if first time, transition to sub-tables */ if (drop === 0) { drop = root; } /* increment past last table */ next += min; /* here min is 1 << curr */ /* determine length of next table */ curr = len - drop; left = 1 << curr; while (curr + drop < max) { left -= count[curr + drop]; if (left <= 0) { break; } curr++; left <<= 1; } /* check for enough space */ used += 1 << curr; if ((type === LENS && used > ENOUGH_LENS) || (type === DISTS && used > ENOUGH_DISTS)) { return 1; } /* point entry in root table to sub-table */ low = huff & mask; /*table.op[low] = curr; table.bits[low] = root; table.val[low] = next - opts.table_index;*/ table[low] = (root << 24) | (curr << 16) | (next - table_index) |0; } } /* fill in remaining table entry if code is incomplete (guaranteed to have at most one remaining entry, since if the code is incomplete, the maximum code length that was allowed to get this far is one bit) */ if (huff !== 0) { //table.op[next + huff] = 64; /* invalid code marker */ //table.bits[next + huff] = len - drop; //table.val[next + huff] = 0; table[next + huff] = ((len - drop) << 24) | (64 << 16) |0; } /* set return parameters */ //opts.table_index += used; opts.bits = root; return 0; };
the_stack
// clang-format off import 'chrome://settings/lazy_load.js'; import {webUIListenerCallback} from 'chrome://resources/js/cr.m.js'; import {flush} from 'chrome://resources/polymer/v3_0/polymer/polymer_bundled.min.js'; import {CrInputElement, SettingsOmniboxExtensionEntryElement, SettingsSearchEngineDialogElement, SettingsSearchEngineEntryElement, SettingsSearchEnginesPageElement} from 'chrome://settings/lazy_load.js'; import {ExtensionControlBrowserProxyImpl, loadTimeData, SearchEngine, SearchEnginesBrowserProxyImpl, SearchEnginesInfo, SearchEnginesInteractions} from 'chrome://settings/settings.js'; import {assertEquals, assertFalse, assertTrue} from 'chrome://webui-test/chai_assert.js'; import {eventToPromise} from 'chrome://webui-test/test_util.js'; import {TestExtensionControlBrowserProxy} from './test_extension_control_browser_proxy.js'; import {createSampleSearchEngine, TestSearchEnginesBrowserProxy} from './test_search_engines_browser_proxy.js'; // clang-format on function createSampleOmniboxExtension(): SearchEngine { return { canBeDefault: false, canBeEdited: false, canBeRemoved: false, canBeActivated: false, canBeDeactivated: false, default: false, displayName: 'Omnibox extension displayName', extension: { icon: 'chrome://extension-icon/some-extension-icon', id: 'dummyextensionid', name: 'Omnibox extension', canBeDisabled: false, }, id: 0, isOmniboxExtension: true, keyword: 'oe', modelIndex: 6, name: 'Omnibox extension', url: 'chrome-extension://dummyextensionid/?q=%s', urlLocked: false }; } suite('AddSearchEngineDialogTests', function() { let dialog: SettingsSearchEngineDialogElement; let browserProxy: TestSearchEnginesBrowserProxy; setup(function() { browserProxy = new TestSearchEnginesBrowserProxy(); SearchEnginesBrowserProxyImpl.setInstance(browserProxy); document.body.innerHTML = ''; dialog = document.createElement('settings-search-engine-dialog'); document.body.appendChild(dialog); }); teardown(function() { dialog.remove(); }); // Tests that the dialog calls 'searchEngineEditStarted' and // 'searchEngineEditCancelled' when closed from the 'cancel' button. test('DialogOpenAndCancel', function() { return browserProxy.whenCalled('searchEngineEditStarted').then(function() { dialog.$.cancel.click(); return browserProxy.whenCalled('searchEngineEditCancelled'); }); }); // Tests the dialog to add a new search engine. Specifically // - cr-input elements are empty initially. // - action button initially disabled. // - validation is triggered on 'input' event. // - action button is enabled when all fields are valid. // - action button triggers appropriate browser signal when tapped. test('DialogAddSearchEngine', function() { /** * Triggers an 'input' event on the cr-input element and checks that * validation is triggered. */ function inputAndValidate(inputId: string): Promise<void> { const inputElement = dialog.shadowRoot!.querySelector<CrInputElement>(`#${inputId}`)!; browserProxy.resetResolver('validateSearchEngineInput'); inputElement.dispatchEvent( new CustomEvent('input', {bubbles: true, composed: true})); return inputElement.value !== '' ? // Expecting validation only on non-empty values. browserProxy.whenCalled('validateSearchEngineInput') : Promise.resolve(); } const actionButton = dialog.$.actionButton; return browserProxy.whenCalled('searchEngineEditStarted') .then(() => { assertEquals('', dialog.$.searchEngine.value); assertEquals('', dialog.$.keyword.value); assertEquals('', dialog.$.queryUrl.value); assertTrue(actionButton.disabled); }) .then(() => inputAndValidate('searchEngine')) .then(() => inputAndValidate('keyword')) .then(() => inputAndValidate('queryUrl')) .then(() => { // Manually set the text to a non-empty string for all fields. dialog.$.searchEngine.value = 'foo'; dialog.$.keyword.value = 'bar'; dialog.$.queryUrl.value = 'baz'; return inputAndValidate('searchEngine'); }) .then(() => { // Assert that the action button has been enabled now that all // input is valid and non-empty. assertFalse(actionButton.disabled); actionButton.click(); return browserProxy.whenCalled('searchEngineEditCompleted'); }); }); test('DialogCloseWhenEnginesChangedModelEngineNotFound', function() { dialog.set('model', createSampleSearchEngine({id: 0, name: 'G'})); webUIListenerCallback('search-engines-changed', { defaults: [], actives: [], others: [createSampleSearchEngine({id: 1, name: 'H'})], extensions: [], }); return browserProxy.whenCalled('searchEngineEditCancelled'); }); test('DialogValidateInputsWhenEnginesChanged', function() { dialog.set('model', createSampleSearchEngine({name: 'G'})); dialog.set('keyword_', 'G'); webUIListenerCallback('search-engines-changed', { defaults: [], actives: [], others: [createSampleSearchEngine({name: 'G'})], extensions: [], }); return browserProxy.whenCalled('validateSearchEngineInput'); }); }); suite('SearchEngineEntryTests', function() { let entry: SettingsSearchEngineEntryElement; let browserProxy: TestSearchEnginesBrowserProxy; const searchEngine = createSampleSearchEngine( {canBeDefault: true, canBeEdited: true, canBeRemoved: true}); setup(function() { browserProxy = new TestSearchEnginesBrowserProxy(); SearchEnginesBrowserProxyImpl.setInstance(browserProxy); document.body.innerHTML = ''; entry = document.createElement('settings-search-engine-entry'); entry.set('engine', searchEngine); document.body.appendChild(entry); }); teardown(function() { entry.remove(); }); // Test that the <search-engine-entry> is populated according to its // underlying SearchEngine model. test('Initialization', function() { assertEquals( searchEngine.displayName, entry.shadowRoot!.querySelector('#name-column')!.textContent!.trim()); assertEquals( searchEngine.keyword, entry.shadowRoot!.querySelector('#keyword-column')!.textContent); assertEquals( searchEngine.url, entry.shadowRoot!.querySelector('#url-column')!.textContent); }); test('Remove_Enabled', function() { // Open action menu. entry.shadowRoot!.querySelector('cr-icon-button')!.click(); const menu = entry.shadowRoot!.querySelector('cr-action-menu')!; assertTrue(menu.open); const deleteButton = entry.$.delete; assertTrue(!!deleteButton); assertFalse(deleteButton.hidden); deleteButton.click(); return browserProxy.whenCalled('removeSearchEngine') .then(function(modelIndex) { assertFalse(menu.open); assertEquals(entry.engine.modelIndex, modelIndex); }); }); test('MakeDefault_Enabled', function() { // Open action menu. entry.shadowRoot!.querySelector('cr-icon-button')!.click(); const menu = entry.shadowRoot!.querySelector('cr-action-menu')!; assertTrue(menu.open); const makeDefaultButton = entry.$.makeDefault; assertTrue(!!makeDefaultButton); makeDefaultButton.click(); return browserProxy.whenCalled('setDefaultSearchEngine') .then(function(modelIndex) { assertFalse(menu.open); assertEquals(entry.engine.modelIndex, modelIndex); }); }); // Test that clicking the "edit" menu item fires an edit event. test('Edit_Enabled', function() { // Open action menu. entry.shadowRoot! .querySelector<HTMLElement>('cr-icon-button.icon-more-vert')!.click(); const menu = entry.shadowRoot!.querySelector('cr-action-menu')!; assertTrue(menu.open); const engine = entry.engine; const editButton = entry.$.edit; assertTrue(!!editButton); assertFalse(editButton.hidden); const promise = eventToPromise('edit-search-engine', entry).then(e => { assertEquals(engine, e.detail.engine); assertEquals( entry.shadowRoot!.querySelector('cr-icon-button'), e.detail.anchorElement); }); editButton.click(); return promise; }); /** * Checks that the given button is hidden for the given search engine. */ function testButtonHidden(searchEngine: SearchEngine, buttonId: string) { entry.engine = searchEngine; const button = entry.shadowRoot!.querySelector<HTMLButtonElement>(`#${buttonId}`); assertTrue(!!button); assertTrue(button!.hidden); } test('Remove_Hidden', function() { testButtonHidden(createSampleSearchEngine({canBeRemoved: false}), 'delete'); }); /** * Checks that the given button is disabled for the given search engine. */ function testButtonDisabled(searchEngine: SearchEngine, buttonId: string) { entry.engine = searchEngine; const button = entry.shadowRoot!.querySelector<HTMLButtonElement>(`#${buttonId}`); assertTrue(!!button); assertTrue(button!.disabled); } test('MakeDefault_Disabled', function() { testButtonDisabled( createSampleSearchEngine({canBeDefault: false}), 'makeDefault'); }); test('Edit_Disabled', function() { testButtonDisabled(createSampleSearchEngine({canBeEdited: false}), 'edit'); }); // Test that clicking the "activate" button fires an activate event. test('Activate', async function() { entry.set('isActiveSearchEnginesFlagEnabled', true); flush(); entry.engine = createSampleSearchEngine({canBeActivated: true}); const activateButton = entry.shadowRoot!.querySelector<HTMLButtonElement>( 'cr-button.secondary-button')!; assertTrue(!!activateButton); assertFalse(activateButton.hidden); activateButton.click(); // Ensure that the activate event is fired. const [modelIndex, isActive] = await browserProxy.whenCalled('setIsActiveSearchEngine'); assertEquals(entry.engine.modelIndex, modelIndex); assertTrue(isActive); }); // Test that clicking the "Deactivate" button fires a deactivate event. test('Deactivate', async function() { entry.set('isActiveSearchEnginesFlagEnabled', true); flush(); entry.engine = createSampleSearchEngine({canBeDeactivated: true}); // Open action menu. entry.shadowRoot! .querySelector<HTMLElement>('cr-icon-button.icon-more-vert')!.click(); const menu = entry.shadowRoot!.querySelector('cr-action-menu')!; assertTrue(menu.open); const deactivateButton = entry.shadowRoot!.querySelector<HTMLButtonElement>( 'button#deactivate.dropdown-item')!; assertTrue(!!deactivateButton); assertFalse(deactivateButton.hidden); deactivateButton.click(); // Ensure that the deactivate event is fired. const [modelIndex, isActive] = await browserProxy.whenCalled('setIsActiveSearchEngine'); assertEquals(entry.engine.modelIndex, modelIndex); assertFalse(isActive); }); }); suite('SearchEnginePageTests', function() { let page: SettingsSearchEnginesPageElement; let browserProxy: TestSearchEnginesBrowserProxy; const searchEnginesInfo: SearchEnginesInfo = { defaults: [createSampleSearchEngine({ id: 0, name: 'search_engine_G', displayName: 'search_engine_G displayName', keyword: 'search_engine_G' })], actives: [], others: [ createSampleSearchEngine({ id: 1, name: 'search_engine_B', displayName: 'search_engine_B displayName', keyword: 'search_engine_B' }), createSampleSearchEngine({ id: 2, name: 'search_engine_A', displayName: 'search_engine_A displayName', keyword: 'search_engine_A' }), ], extensions: [createSampleOmniboxExtension()], }; setup(function() { browserProxy = new TestSearchEnginesBrowserProxy(); // Purposefully pass a clone of |searchEnginesInfo| to avoid any // mutations on ground truth data. browserProxy.setSearchEnginesInfo({ defaults: searchEnginesInfo.defaults.slice(), actives: searchEnginesInfo.actives.slice(), others: searchEnginesInfo.others.slice(), extensions: searchEnginesInfo.extensions.slice(), }); loadTimeData.overrideValues({'showKeywordTriggerSetting': true}); SearchEnginesBrowserProxyImpl.setInstance(browserProxy); document.body.innerHTML = ''; page = document.createElement('settings-search-engines-page'); page.set('prefs.omnibox.keyword_space_triggering_enabled', { key: 'prefs.omnibox.keyword_space_triggering_enabled', type: chrome.settingsPrivate.PrefType.BOOLEAN, value: true, }); document.body.appendChild(page); return browserProxy.whenCalled('getSearchEnginesList'); }); teardown(function() { page.remove(); }); // Tests that the page is querying and displaying search engine info on // startup. test('Initialization', function() { const searchEnginesLists = page.shadowRoot!.querySelectorAll('settings-search-engines-list'); assertEquals(2, searchEnginesLists.length); flush(); const defaultsList = searchEnginesLists[0]!; const defaultsEntries = defaultsList.shadowRoot!.querySelectorAll( 'settings-search-engine-entry'); assertEquals(searchEnginesInfo.defaults.length, defaultsEntries.length); const othersList = searchEnginesLists[1]!; const othersEntries = othersList.shadowRoot!.querySelectorAll('settings-search-engine-entry'); assertEquals(searchEnginesInfo.others.length, othersEntries.length); // Ensure that the search engines have reverse alphabetical order in the // model. assertTrue( searchEnginesInfo.others[0]!.name > searchEnginesInfo.others[1]!.name); // Ensure that they are displayed in alphabetical order. assertEquals( searchEnginesInfo.others[1]!.name, othersEntries[0]!.engine.name); assertEquals( searchEnginesInfo.others[0]!.name, othersEntries[1]!.engine.name); const extensionEntries = page.shadowRoot!.querySelector('iron-list')!.items; assertEquals(searchEnginesInfo.extensions.length, extensionEntries!.length); }); // Test that the keyboard shortcut radio buttons are shown as expected, and // toggling them fires the appropriate events. test('KeyboardShortcutSettingToggle', async function() { const radioGroup = page.$.keyboardShortcutSettingGroup; assertTrue(!!radioGroup); assertFalse(radioGroup.hidden); const radioButtons = page.shadowRoot!.querySelectorAll('controlled-radio-button')!; assertEquals(2, radioButtons.length); assertEquals('true', radioButtons.item(0)!.name); assertEquals('false', radioButtons.item(1)!.name); // Check behavior when switching space triggering off. radioButtons.item(1)!.click(); flush(); assertEquals('false', radioGroup.selected); let result = await browserProxy.whenCalled('recordSearchEnginesPageHistogram'); assertEquals(SearchEnginesInteractions.KEYBOARD_SHORTCUT_TAB, result); browserProxy.reset(); // Check behavior when switching space triggering on. radioButtons.item(0).click(); flush(); assertEquals('true', radioGroup.selected); result = await browserProxy.whenCalled('recordSearchEnginesPageHistogram'); assertEquals( SearchEnginesInteractions.KEYBOARD_SHORTCUT_SPACE_OR_TAB, result); }); // Test that the "no other search engines" message is shown/hidden as // expected. test('NoOtherSearchEnginesMessage', function() { webUIListenerCallback('search-engines-changed', { defaults: [], actives: [], others: [], extensions: [], }); const message = page.shadowRoot!.querySelector('#noOtherEngines'); assertTrue(!!message); assertFalse(message!.hasAttribute('hidden')); webUIListenerCallback('search-engines-changed', { defaults: [], actives: [], others: [createSampleSearchEngine()], extensions: [], }); assertTrue(message!.hasAttribute('hidden')); }); // Tests that the add search engine dialog opens when the corresponding // button is tapped. test('AddSearchEngineDialog', function() { assertFalse( !!page.shadowRoot!.querySelector('settings-search-engine-dialog')); const addSearchEngineButton = page.$.addSearchEngine; assertTrue(!!addSearchEngineButton); addSearchEngineButton.click(); flush(); assertTrue( !!page.shadowRoot!.querySelector('settings-search-engine-dialog')); }); test('EditSearchEngineDialog', function() { const engine = searchEnginesInfo.others[0]!; page.dispatchEvent(new CustomEvent('edit-search-engine', { bubbles: true, composed: true, detail: {engine, anchorElement: page.$.addSearchEngine} })); return browserProxy.whenCalled('searchEngineEditStarted') .then(modelIndex => { assertEquals(engine.modelIndex, modelIndex); const dialog = page.shadowRoot!.querySelector('settings-search-engine-dialog')!; assertTrue(!!dialog); // Check that the cr-input fields are pre-populated. assertEquals(engine.name, dialog.$.searchEngine.value); assertEquals(engine.keyword, dialog.$.keyword.value); assertEquals(engine.url, dialog.$.queryUrl.value); assertFalse(dialog.$.actionButton.disabled); }); }); // Tests that filtering the three search engines lists works, and that the // "no search results" message is shown as expected. test('FilterSearchEngines', function() { flush(); function getListItems(listIndex: number) { const list = listIndex === 2 /* extensions */ ? page.shadowRoot!.querySelector('iron-list')!.items : page.shadowRoot! .querySelectorAll('settings-search-engines-list')[listIndex]! .shadowRoot!.querySelectorAll('settings-search-engine-entry'); return list; } function assertSearchResults( defaultsCount: number, othersCount: number, extensionsCount: number) { assertEquals(defaultsCount, getListItems(0)!.length); assertEquals(othersCount, getListItems(1)!.length); assertEquals(extensionsCount, getListItems(2)!.length); const noResultsElements = Array.from( page.shadowRoot!.querySelectorAll<HTMLElement>('.no-search-results')); assertEquals(defaultsCount > 0, noResultsElements[0]!.hidden); assertEquals(othersCount > 0, noResultsElements[1]!.hidden); assertEquals(extensionsCount > 0, noResultsElements[2]!.hidden); } assertSearchResults(1, 2, 1); // Search by name page.filter = searchEnginesInfo.defaults[0]!.name; flush(); assertSearchResults(1, 0, 0); // Search by displayName page.filter = searchEnginesInfo.others[0]!.displayName; flush(); assertSearchResults(0, 1, 0); // Search by keyword page.filter = searchEnginesInfo.others[1]!.keyword; flush(); assertSearchResults(0, 1, 0); // Search by URL page.filter = 'search?'; flush(); assertSearchResults(1, 2, 0); // Test case where none of the sublists have results. page.filter = 'does not exist'; flush(); assertSearchResults(0, 0, 0); // Test case where an 'extension' search engine matches. page.filter = 'extension'; flush(); assertSearchResults(0, 0, 1); }); }); suite('OmniboxExtensionEntryTests', function() { let entry: SettingsOmniboxExtensionEntryElement; let browserProxy: TestExtensionControlBrowserProxy; setup(function() { browserProxy = new TestExtensionControlBrowserProxy(); ExtensionControlBrowserProxyImpl.setInstance(browserProxy); document.body.innerHTML = ''; entry = document.createElement('settings-omnibox-extension-entry'); entry.set('engine', createSampleOmniboxExtension()); document.body.appendChild(entry); // Open action menu. entry.shadowRoot!.querySelector('cr-icon-button')!.click(); }); teardown(function() { entry.remove(); }); test('Manage', function() { const manageButton = entry.$.manage; assertTrue(!!manageButton); manageButton.click(); return browserProxy.whenCalled('manageExtension') .then(function(extensionId) { assertEquals(entry.engine.extension!.id, extensionId); }); }); test('Disable', function() { const disableButton = entry.$.disable; assertTrue(!!disableButton); disableButton.click(); return browserProxy.whenCalled('disableExtension') .then(function(extensionId) { assertEquals(entry.engine.extension!.id, extensionId); }); }); });
the_stack
import * as fs from 'fs'; import * as path from 'path'; import chalk = require('chalk'); import * as ts from 'typescript'; import { resolve } from './resolver'; export const DEFAULT_EXPORT = 'default'; export type ValueExport = string; export interface IRegistry { [key: string]: { exports: Set<ValueExport>; dependencies: Set<string> }; } interface ISourceFile extends ts.SourceFile { imports?: ts.StringLiteral[]; } const hasOwn = Object.prototype.hasOwnProperty; /** * Parse value exports in a file. * Only function, class, variable and re-exports are counted. */ function parseValueExports( filename: string, registry: IRegistry ): Set<ValueExport> { if (!path.isAbsolute(filename)) { filename = path.resolve(filename); } const cwd = path.dirname(filename); // Query from registry const cached = registry[filename]; if (cached) { return cached.exports; } // console.log(filename); // const source = fs.readFileSync(filename, { encoding: 'utf-8' }); // const sourceFile = ts.createSourceFile( // filename, // source, // ts.ScriptTarget.Latest, // true, // getScriptKind(filename) // ); const sourceFile = createSourceFile(filename); const exportedLocalVariables = getModuleLocalExportedValueNames(sourceFile!); const localValueVariables = getModuleValueNames( sourceFile!, cwd, registry, exportedLocalVariables ); // log([...localValueVariables]); const exportedVariables = getModuleValueExportNames( sourceFile!, cwd, registry, localValueVariables ); // Save to registry const moduleDependencies = getModuleRelativeImports(sourceFile?.imports, cwd); registry[filename] = { exports: exportedVariables, dependencies: moduleDependencies, }; return exportedVariables; } /** * Get all exported local value names * 1. export { a, b } * 2. export default c * * Excludes export ... from './x' */ function getModuleLocalExportedValueNames( sourceFile: ISourceFile ): Set<ValueExport> { const exportedVariables = new Set<ValueExport>(); sourceFile.statements.forEach(stmt => { if (ts.isExportDeclaration(stmt)) { const { exportClause, moduleSpecifier } = stmt; // Ignore exports from other modules if (moduleSpecifier) { return; } if (exportClause && ts.isNamedExports(exportClause)) { // export { A, B } const names = getBindingNames(exportClause); for (const { propertyName } of names) { exportedVariables.add(propertyName); } } } else if (ts.isExportAssignment(stmt)) { // Ignore export = if (!stmt.isExportEquals) { // export default c const { expression } = stmt; if (ts.isIdentifier(expression)) { exportedVariables.add(expression.text); } } } }); return exportedVariables; } /** * Get all value names in module * 1. local variables, * 2. functions, * 3. classes, * 4. imports of 1,2,3 */ function getModuleValueNames( sourceFile: ISourceFile, cwd: string, registry: IRegistry, exportedLocalVariables: Set<ValueExport> ): Set<ValueExport> { const localValueVariables = new Set<ValueExport>(); sourceFile.statements.forEach(stmt => { if (ts.isVariableStatement(stmt)) { // const a = 1; const declarations = stmt.declarationList.declarations; getVariableNames(declarations, localValueVariables); } else if (ts.isFunctionDeclaration(stmt) || ts.isClassDeclaration(stmt)) { // function fn() {} // class Klass {} const { name } = stmt; // functions can be anonymous if (name && ts.isIdentifier(name)) { localValueVariables.add(name.text); } } else if ( ts.isImportDeclaration(stmt) && isRelativeImportExportDeclaration(stmt) ) { const { importClause } = stmt; let shouldParseModule = false; const names = importClause?.namedBindings ? getBindingNames(importClause.namedBindings) : new Set([ { name: importClause?.name?.text, propertyName: DEFAULT_EXPORT }, ]); for (const { name } of names) { if (exportedLocalVariables.has(name!)) { shouldParseModule = true; } } if (shouldParseModule) { const dependentModulePath = convertRelativeModulePathToAbsolute( getModuleName(stmt), cwd ); const dependentModuleExports = parseValueExports( dependentModulePath, registry ); if (importClause?.namedBindings) { // import { A } from './x' // import { C as CC } from './c' for (const { name, propertyName } of names) { if (dependentModuleExports.has(propertyName)) { localValueVariables.add(name!); } else { console.warn( chalk.yellow( `Named import '${propertyName}' not found in module ${dependentModulePath}` ) ); } } } else { // import B from './B' if ( isModuleHasDefaultExport(dependentModuleExports) && importClause?.name?.text ) { localValueVariables.add(importClause?.name?.text); } } } } }); return localValueVariables; } /** * Get all exported values in module * 1. variables * 2. functions * 3. classes * 4. re-exports of 1,2,3 from other modules */ function getModuleValueExportNames( sourceFile: ISourceFile, cwd: string, registry: IRegistry, localValueVariables: Set<ValueExport> ): Set<ValueExport> { const exportedVariables = new Set<ValueExport>(); sourceFile.statements.forEach(stmt => { if (ts.isVariableStatement(stmt)) { // export const A = 1 if (isNodeExported(stmt as unknown as ts.Declaration)) { const vars = getVariableNames(stmt.declarationList.declarations); for (const v of vars) { if (localValueVariables.has(v)) { addToExports(exportedVariables, v); } } } } else if (ts.isFunctionDeclaration(stmt) || ts.isClassDeclaration(stmt)) { if (isExportDefaultNode(stmt)) { // export default function fn() {} // export default class Klass {} addToExports(exportedVariables, DEFAULT_EXPORT); } else { // export function fn() {} // export class Klass {} if (isNodeExported(stmt)) { const exportedVar = (ts.getNameOfDeclaration(stmt) as ts.Identifier) .text; if (localValueVariables.has(exportedVar)) { addToExports(exportedVariables, exportedVar); } } } } else if (ts.isExportDeclaration(stmt)) { const { exportClause, moduleSpecifier } = stmt; // Ignore export { A, B } from 'foobar' if (moduleSpecifier && !isRelativeImportExportDeclaration(stmt)) { return; } let dependentModuleExports = new Set<string>(); let dependentModulePath; // Parse dependency if we are re-exporting from relative module if (moduleSpecifier && isRelativeImportExportDeclaration(stmt)) { const importedModulePath = getModuleName(stmt); dependentModulePath = convertRelativeModulePathToAbsolute( importedModulePath, cwd ); dependentModuleExports = parseValueExports( dependentModulePath, registry ); } if (exportClause && ts.isNamedExports(exportClause)) { // export { A, B } from './x' // export { A, B } // FIXME: export { default as Foobar } from './x' const variableWhitelist = stmt.moduleSpecifier ? dependentModuleExports : localValueVariables; const names = getBindingNames(exportClause); for (const { name, propertyName } of names) { if (variableWhitelist?.has(propertyName)) { addToExports(exportedVariables, name); } else if (stmt.moduleSpecifier) { console.warn( chalk.yellow( `Named export '${propertyName}' not found in module ${dependentModulePath}\nYou can safely ignore this warning if it is an exported type` ) ); } } } else if (!exportClause) { // export * from './a' for (const i of dependentModuleExports) { // Don't re-export default export if (i !== DEFAULT_EXPORT) { addToExports(exportedVariables, i); } } } } else if (ts.isExportAssignment(stmt)) { // Ignore export = if (!stmt.isExportEquals) { // export default addToExports(exportedVariables, DEFAULT_EXPORT); } } }); return exportedVariables; } /** * Get all declared variable names */ function getVariableNames( declarations: ts.NodeArray<ts.VariableDeclaration>, variables = new Set<ValueExport>() ): Set<ValueExport> { declarations.forEach(decl => { if (ts.isVariableDeclaration(decl)) { const name = ts.getNameOfDeclaration(decl); if (name && ts.isIdentifier(name)) { variables.add(name.text); } else if ( name && (ts.isArrayBindingPattern(name) || ts.isObjectBindingPattern(name)) ) { name.elements.forEach(elem => { const elementName = ts.getNameOfDeclaration(elem) as ts.Identifier; variables.add(elementName.text); }); } } }); return variables; } /** * Get export/import names */ function getBindingNames( bindings: ts.NamedImportsOrExports | ts.NamespaceImport ): Set<{ name: string; propertyName: ValueExport }> { const names = new Set<{ name: string; propertyName: ValueExport }>(); if (ts.isNamespaceImport(bindings)) { const { name } = bindings; names.add({ name: name.text, propertyName: DEFAULT_EXPORT, }); } else { const { elements } = bindings; elements.forEach(b => { const { propertyName } = b; const localName = (ts.getNameOfDeclaration(b) as ts.Identifier).text; const nameFromModule = propertyName ? propertyName.text : localName; names.add({ name: localName, propertyName: nameFromModule, }); }); } // const { elements, name } = bindings; // if (name && ts.isIdentifier(name)) { // names.add({ // name: name.text, // propertyName: DEFAULT_EXPORT, // }); // } else if (elements) { // elements.forEach(b => { // const { propertyName } = b; // const localName = ts.getNameOfDeclaration(b).text; // const nameFromModule = propertyName ? propertyName.text : localName; // names.add({ // name: localName, // propertyName: nameFromModule, // }); // }); // } return names; } /** * Parse a module */ function createSourceFile(filename: string): ISourceFile | undefined { /** ts.CompilerHost */ const compilerHost: ts.CompilerHost = { fileExists: () => true, getCanonicalFileName: (filename: string) => filename, getCurrentDirectory: () => '', getDefaultLibFileName: () => 'lib.d.ts', getNewLine: () => '\n', getSourceFile: () => { const code = fs.readFileSync(filename, { encoding: 'utf-8' }); return ts.createSourceFile( filename, code, ts.ScriptTarget.Latest, true, getScriptKind(filename) ); }, readFile: () => undefined, useCaseSensitiveFileNames: () => true, writeFile: () => null, }; const program = ts.createProgram( [filename], { allowJs: true, noResolve: true, target: ts.ScriptTarget.Latest, experimentalDecorators: true, experimentalAsyncFunctions: true, jsx: ts.JsxEmit.Preserve, }, compilerHost ); return program.getSourceFile(filename); } /** * Check if stmt is a relative import */ function isRelativeImportExportDeclaration( stmt: ts.ImportDeclaration | ts.ExportDeclaration ): boolean { const moduleName = getModuleName(stmt); return !!(moduleName && moduleName.startsWith('.')); } /** * Check if a node is exported. * export = foobar is considered as false */ function isNodeExported(node: ts.Declaration): number { const flagToTest = ts.ModifierFlags.ExportDefault; const flag = ts.getCombinedModifierFlags(node); return flag & flagToTest; } /** * Check if a node is export default */ function isExportDefaultNode(node: ts.Declaration): boolean { const flag = ts.getCombinedModifierFlags(node); return flag === ts.ModifierFlags.ExportDefault; } /** * Get module name from import declaration */ function getModuleName( stmt: ts.ImportDeclaration | ts.ExportDeclaration ): string { return (stmt.moduleSpecifier as ts.StringLiteral).text; } /** * Convert relative module path to absolute */ function convertRelativeModulePathToAbsolute( moduleName: string, cwd: string ): string { return resolve({ cwd, moduleName, mainFiles: ['index'], extensions: ['ts', 'tsx', 'js', 'jsx'], }); } /** * Check if a module has default export * @param {Set.<ValueExport>} valueExports * @return {boolean} */ function isModuleHasDefaultExport(valueExports: Set<ValueExport>): boolean { for (const exp of valueExports) { if (exp === DEFAULT_EXPORT) { return true; } } return false; } /** * Guess script kind base on filename */ function getScriptKind(filename: string): ts.ScriptKind { if (filename.endsWith('.jsx')) { return ts.ScriptKind.JSX; } else if (filename.endsWith('.tsx')) { return ts.ScriptKind.TSX; } else if (filename.endsWith('.ts')) { return ts.ScriptKind.TS; } else if (filename.endsWith('.js')) { return ts.ScriptKind.JS; } return ts.ScriptKind.TS; } /** * Add element to exports, warn if already there */ function addToExports( set: Set<ValueExport>, elem: ValueExport ): Set<ValueExport> { if (set.has(elem)) { console.error(chalk.red(`Duplicate exports found ${elem}`)); } else { set.add(elem); } return set; } /** * Get all relative imports for module */ function getModuleRelativeImports( imports: ts.StringLiteral[] | undefined, cwd: string ): Set<string> { const importFiles = new Set<string>(); if (imports) { imports.forEach(imp => { const moduleName = imp.text; if (moduleName && moduleName.startsWith('.')) { importFiles.add(convertRelativeModulePathToAbsolute(moduleName, cwd)); } }); } return importFiles; } /** * Construct a module registry for root module */ export function getModuleRegistry(rootModule: string): IRegistry { const registry: IRegistry = {}; parseValueExports(rootModule, registry); const getRegistrySize = () => Object.keys(registry).length; let prevModuleCount = 0; while (getRegistrySize() > prevModuleCount) { prevModuleCount = getRegistrySize(); for (const key in registry) { if (hasOwn.call(registry, key)) { const mod = registry[key]; mod.dependencies.forEach( dep => registry[dep] || parseValueExports(dep, registry) ); } } } return registry; }
the_stack
import { IMetadata } from './imetadata'; import { IOption } from './ioption'; import { IThumbnail } from './ithumbnail'; /** * 无需上传即可获得视频元数据和视频帧的Blob图片 * * @author wangweiwei */ export class Video { /** * Video Element */ private videoElement: HTMLVideoElement; /** * Canvas Element */ private canvas: HTMLCanvasElement; /** * Canvas Context */ private canvasContext: CanvasRenderingContext2D; /** * 当前Video的帧图片 */ private thumbnails: IThumbnail[] = []; /** * 选项 */ private option: IOption = { quality: 0.7, interval: 1, scale: 0.7, start: 0 }; /** * 是否第一帧 */ private isStarted: boolean = true; /** * 帧图片数 */ private count: number = 0; /** * 版本 */ private version: string = '__VERSION__'; /** * 实例化Video对象 * - 创建视频元素 * - 创建canvas元素并拿到canvas context * - video元素赋值src,开始加载视频 * - 视频播放结束后的内存回收处理 * * @param blob string | Blob * */ constructor(blob: string | Blob) { if (!blob) { throw new Error('__NAME__ params error'); } // 初始化视频元素 this.videoElement = document.createElement('video') as HTMLVideoElement; this.videoElement.preload = 'metadata'; this.videoElement.muted = true; this.videoElement.volume = 0; this.videoElement.crossOrigin = 'anonymous'; // 初始化canvas const canvas: HTMLCanvasElement = document.createElement('canvas') as HTMLCanvasElement; this.canvas = canvas; this.canvasContext = canvas.getContext('2d') as CanvasRenderingContext2D; // 赋值src const URL = window.URL || window.webkitURL; this.videoElement.src = typeof blob === 'string' || blob instanceof String ? (blob as string) : URL.createObjectURL(blob); // 视频播放结束相关回收 const endedHandler = () => { const _blob: string | Blob = this.videoElement.src as string | Blob; if (!(typeof _blob === 'string' || _blob instanceof String)) { URL.revokeObjectURL(this.videoElement.src); } this.videoElement.removeEventListener('ended', endedHandler, false); }; this.videoElement.addEventListener('ended', endedHandler, false); } /** * 获取版本信息 */ getVersion() { return this.version; } /** * 获取帧图片 * * @param option IOption 选项 * * @return Promise<(Blob | null)[]> 帧图片Blob集合 */ getThumbnails(option?: IOption): Promise<IThumbnail[]> { // 选项赋值 if (option) { this.option = Object.assign(this.option, option); } return new Promise((resolve, reject) => { const canplayHandler = () => { const interval = this.option.interval || 1; const { videoWidth, videoHeight, duration } = this.videoElement; if (!this.isStarted) { this.videoElement.currentTime += interval; } else { this.videoElement.currentTime = this.option.start; this.isStarted = false; } }; const timeupdateHandler = () => { const { option, videoElement, canvasContext, thumbnails } = this; const { videoWidth, videoHeight, duration } = videoElement; const { quality, interval, start, end, scale } = option; const { currentTime } = videoElement; const isEnded = currentTime >= duration || currentTime > (end === undefined ? duration : end); const $interval = interval || 1; const $videoWidth = videoWidth * (scale || 1); const $videoHeight = videoHeight * (scale || 1); try { this.canvas.width = $videoWidth; this.canvas.height = $videoHeight; this.canvasContext.drawImage(this.videoElement, 0, 0, $videoWidth, $videoHeight); // blob 兼容性 if (!this.canvas.toBlob) { const binStr = atob(this.canvas.toDataURL('image/jpeg', quality).split(',')[1]); const len = binStr.length; const arr = new Uint8Array(len); for (let i = 0; i < len; i++) { arr[i] = binStr.charCodeAt(i); } const blob: Blob = new Blob([arr], { type: 'image/jpeg' }); canvasContext.clearRect(0, 0, $videoWidth, $videoHeight); canvasContext.restore(); if (isEnded) { videoElement.removeEventListener('canplaythrough', canplayHandler, false); videoElement.removeEventListener('timeupdate', timeupdateHandler, false); resolve(this.thumbnails); return; } thumbnails.push({ currentTime: start + $interval * this.count, blob }); this.count++; } else { this.canvas.toBlob( blob => { canvasContext.clearRect(0, 0, $videoWidth, $videoHeight); canvasContext.restore(); if (isEnded) { videoElement.removeEventListener('canplaythrough', canplayHandler, false); videoElement.removeEventListener('timeupdate', timeupdateHandler, false); resolve(this.thumbnails); return; } thumbnails.push({ currentTime: start + $interval * this.count, blob }); this.count++; }, 'image/jpeg', quality ); } } catch (error) { reject(error); } }; const progressHandler = () => { this.videoElement.play(); this.videoElement.removeEventListener('progress', progressHandler, false); } // 判断如果是Safari if(/^((?!chrome).)*safari((?!chrome).)*$/i.test(navigator.userAgent)) { this.videoElement.addEventListener('progress', progressHandler, false); } const endedHandler = () => { this.videoElement.removeEventListener('progress', progressHandler, false); this.videoElement.removeEventListener('ended', endedHandler, false); this.videoElement.removeEventListener('canplaythrough', canplayHandler, false); this.videoElement.removeEventListener('timeupdate', timeupdateHandler, false); this.videoElement.removeEventListener('error', errorHandler, false); }; const errorHandler = () => { const { error } = this.videoElement; if (error) { reject(new Error(`__NAME__ error ${error.code}; details: ${error.message}`)); } else { reject(new Error('__NAME__ unknown error')); } this.videoElement.removeEventListener('progress', progressHandler, false); this.videoElement.removeEventListener('ended', endedHandler, false); this.videoElement.removeEventListener('canplaythrough', canplayHandler, false); this.videoElement.removeEventListener('timeupdate', timeupdateHandler, false); this.videoElement.removeEventListener('error', errorHandler, false); }; this.videoElement.addEventListener('canplaythrough', canplayHandler, false); this.videoElement.addEventListener('timeupdate', timeupdateHandler, false); this.videoElement.addEventListener('ended', endedHandler, false); this.videoElement.addEventListener('error', errorHandler, false); }); } drawThumbnails() {} /** * 获取Metadata信息 * * @return Promise<IMetadata> video元数据信息 */ getMetadata(): Promise<IMetadata> { return new Promise((resolve, reject) => { const loadedmetadataHandler = () => { try { const { videoWidth, videoHeight, duration } = this.videoElement; // fix a bug for chrome // https://bugs.chromium.org/p/chromium/issues/detail?id=642012 if (duration === Infinity) { const timeupdateHandler = () => { this.videoElement.removeEventListener('timeupdate', timeupdateHandler, false); this.videoElement.removeEventListener('loadedmetadata', loadedmetadataHandler, false); resolve({ width: Math.floor(this.videoElement.videoWidth * 100) / 100, height: Math.floor(this.videoElement.videoHeight * 100) / 100, duration: Math.floor(this.videoElement.duration * 100) / 100 }); this.videoElement.currentTime = 0; }; this.videoElement.addEventListener('timeupdate', timeupdateHandler, false); this.videoElement.currentTime = Number.MAX_SAFE_INTEGER; } else { resolve({ width: Math.floor(videoWidth * 100) / 100, height: Math.floor(videoHeight * 100) / 100, duration: Math.floor(duration * 100) / 100 }); this.videoElement.removeEventListener('loadedmetadata', loadedmetadataHandler, false); } } catch (error) { reject(error); } }; const endedHandler = () => { this.videoElement.removeEventListener('loadedmetadata', loadedmetadataHandler, false); this.videoElement.removeEventListener('ended', endedHandler, false); this.videoElement.removeEventListener('error', errorHandler, false); }; const errorHandler = () => { const { error } = this.videoElement; if (error) { reject(new Error(`__NAME__ error ${error.code}; details: ${error.message}`)); } else { reject(new Error('__NAME__ unknown error')); } this.videoElement.removeEventListener('loadedmetadata', loadedmetadataHandler, false); this.videoElement.removeEventListener('ended', endedHandler, false); this.videoElement.removeEventListener('error', errorHandler, false); }; this.videoElement.addEventListener('loadedmetadata', loadedmetadataHandler, false); this.videoElement.addEventListener('ended', endedHandler, false); this.videoElement.addEventListener('error', errorHandler, false); }); } } /** * 获取Metadata信息 * * @param blob string | Blob * * @return Promise<IMetadata> video元数据信息 */ export async function getMetadata(blob: string | Blob): Promise<IMetadata> { const video: Video = new Video(blob); const metadata = await video.getMetadata(); return metadata; } /** * 获取帧频文件 * * @param blob string | Blob * * @param option IOption 选项 * * @return Promise<(Blob | null)[]> 帧图片Blob集合 */ export async function getThumbnails(blob: string | Blob, option?: IOption): Promise<IThumbnail[]> { const video: Video = new Video(blob); const thumbnails = await video.getThumbnails(option); return thumbnails; }
the_stack
import { ExtendRegexp } from './extend-regexp'; import { Link, Links, MarkedOptions, RulesInlineBase, RulesInlineBreaks, RulesInlineCallback, RulesInlineGfm, RulesInlinePedantic, } from './interfaces'; import { Marked } from './marked'; import { Renderer } from './renderer'; /** * Inline Lexer & Compiler. */ export class InlineLexer { protected static rulesBase: RulesInlineBase = null; /** * Pedantic Inline Grammar. */ protected static rulesPedantic: RulesInlinePedantic = null; /** * GFM Inline Grammar */ protected static rulesGfm: RulesInlineGfm = null; /** * GFM + Line Breaks Inline Grammar. */ protected static rulesBreaks: RulesInlineBreaks = null; protected rules: RulesInlineBase | RulesInlinePedantic | RulesInlineGfm | RulesInlineBreaks; protected renderer: Renderer; protected inLink: boolean; protected hasRulesGfm: boolean; protected ruleCallbacks: RulesInlineCallback[]; constructor( protected staticThis: typeof InlineLexer, protected links: Links, protected options: MarkedOptions = Marked.options, renderer?: Renderer ) { this.renderer = renderer || this.options.renderer || new Renderer(this.options); if (!this.links) { throw new Error(`InlineLexer requires 'links' parameter.`); } this.setRules(); } /** * Static Lexing/Compiling Method. */ static output(src: string, links: Links, options: MarkedOptions): string { const inlineLexer = new this(this, links, options); return inlineLexer.output(src); } protected static getRulesBase(): RulesInlineBase { if (this.rulesBase) { return this.rulesBase; } /** * Inline-Level Grammar. */ const base: RulesInlineBase = { escape: /^\\([\\`*{}\[\]()#+\-.!_>])/, autolink: /^<([^ <>]+(@|:\/)[^ <>]+)>/, tag: /^<!--[\s\S]*?-->|^<\/?\w+(?:"[^"]*"|'[^']*'|[^<'">])*?>/, link: /^!?\[(inside)\]\(href\)/, reflink: /^!?\[(inside)\]\s*\[([^\]]*)\]/, nolink: /^!?\[((?:\[[^\]]*\]|[^\[\]])*)\]/, strong: /^__([\s\S]+?)__(?!_)|^\*\*([\s\S]+?)\*\*(?!\*)/, em: /^\b_((?:[^_]|__)+?)_\b|^\*((?:\*\*|[\s\S])+?)\*(?!\*)/, code: /^(`+)([\s\S]*?[^`])\1(?!`)/, br: /^ {2,}\n(?!\s*$)/, text: /^[\s\S]+?(?=[\\<!\[_*`]| {2,}\n|$)/, _inside: /(?:\[[^\]]*\]|[^\[\]]|\](?=[^\[]*\]))*/, _href: /\s*<?([\s\S]*?)>?(?:\s+['"]([\s\S]*?)['"])?\s*/, }; base.link = new ExtendRegexp(base.link).setGroup('inside', base._inside).setGroup('href', base._href).getRegexp(); base.reflink = new ExtendRegexp(base.reflink).setGroup('inside', base._inside).getRegexp(); return (this.rulesBase = base); } protected static getRulesPedantic(): RulesInlinePedantic { if (this.rulesPedantic) { return this.rulesPedantic; } return (this.rulesPedantic = { ...this.getRulesBase(), ...{ strong: /^__(?=\S)([\s\S]*?\S)__(?!_)|^\*\*(?=\S)([\s\S]*?\S)\*\*(?!\*)/, em: /^_(?=\S)([\s\S]*?\S)_(?!_)|^\*(?=\S)([\s\S]*?\S)\*(?!\*)/, }, }); } protected static getRulesGfm(): RulesInlineGfm { if (this.rulesGfm) { return this.rulesGfm; } const base = this.getRulesBase(); const escape = new ExtendRegexp(base.escape).setGroup('])', '~|])').getRegexp(); const text = new ExtendRegexp(base.text).setGroup(']|', '~]|').setGroup('|', '|https?://|').getRegexp(); return (this.rulesGfm = { ...base, ...{ escape, url: /^(https?:\/\/[^\s<]+[^<.,:;"')\]\s])/, del: /^~~(?=\S)([\s\S]*?\S)~~/, text, }, }); } protected static getRulesBreaks(): RulesInlineBreaks { if (this.rulesBreaks) { return this.rulesBreaks; } const inline = this.getRulesGfm(); const gfm = this.getRulesGfm(); return (this.rulesBreaks = { ...gfm, ...{ br: new ExtendRegexp(inline.br).setGroup('{2,}', '*').getRegexp(), text: new ExtendRegexp(gfm.text).setGroup('{2,}', '*').getRegexp(), }, }); } protected setRules() { if (this.options.gfm) { if (this.options.breaks) { this.rules = this.staticThis.getRulesBreaks(); } else { this.rules = this.staticThis.getRulesGfm(); } } else if (this.options.pedantic) { this.rules = this.staticThis.getRulesPedantic(); } else { this.rules = this.staticThis.getRulesBase(); } this.hasRulesGfm = (this.rules as RulesInlineGfm).url !== undefined; } /** * Lexing/Compiling. */ output(nextPart: string): string { nextPart = nextPart; let execArr: RegExpExecArray; let out = ''; while (nextPart) { // escape if ((execArr = this.rules.escape.exec(nextPart))) { nextPart = nextPart.substring(execArr[0].length); out += execArr[1]; continue; } // autolink if ((execArr = this.rules.autolink.exec(nextPart))) { let text: string; let href: string; nextPart = nextPart.substring(execArr[0].length); if (execArr[2] === '@') { text = this.options.escape( execArr[1].charAt(6) === ':' ? this.mangle(execArr[1].substring(7)) : this.mangle(execArr[1]) ); href = this.mangle('mailto:') + text; } else { text = this.options.escape(execArr[1]); href = text; } out += this.renderer.link(href, null, text); continue; } // url (gfm) if (!this.inLink && this.hasRulesGfm && (execArr = (this.rules as RulesInlineGfm).url.exec(nextPart))) { let text: string; let href: string; nextPart = nextPart.substring(execArr[0].length); text = this.options.escape(execArr[1]); href = text; out += this.renderer.link(href, null, text); continue; } // tag if ((execArr = this.rules.tag.exec(nextPart))) { if (!this.inLink && /^<a /i.test(execArr[0])) { this.inLink = true; } else if (this.inLink && /^<\/a>/i.test(execArr[0])) { this.inLink = false; } nextPart = nextPart.substring(execArr[0].length); out += this.options.sanitize ? this.options.sanitizer ? this.options.sanitizer(execArr[0]) : this.options.escape(execArr[0]) : execArr[0]; continue; } // link if ((execArr = this.rules.link.exec(nextPart))) { nextPart = nextPart.substring(execArr[0].length); this.inLink = true; out += this.outputLink(execArr, { href: execArr[2], title: execArr[3], }); this.inLink = false; continue; } // reflink, nolink if ((execArr = this.rules.reflink.exec(nextPart)) || (execArr = this.rules.nolink.exec(nextPart))) { nextPart = nextPart.substring(execArr[0].length); const keyLink = (execArr[2] || execArr[1]).replace(/\s+/g, ' '); const link = this.links[keyLink.toLowerCase()]; if (!link || !link.href) { out += execArr[0].charAt(0); nextPart = execArr[0].substring(1) + nextPart; continue; } this.inLink = true; out += this.outputLink(execArr, link); this.inLink = false; continue; } // strong if ((execArr = this.rules.strong.exec(nextPart))) { nextPart = nextPart.substring(execArr[0].length); out += this.renderer.strong(this.output(execArr[2] || execArr[1])); continue; } // em if ((execArr = this.rules.em.exec(nextPart))) { nextPart = nextPart.substring(execArr[0].length); out += this.renderer.em(this.output(execArr[2] || execArr[1])); continue; } // code if ((execArr = this.rules.code.exec(nextPart))) { nextPart = nextPart.substring(execArr[0].length); out += this.renderer.codespan(this.options.escape(execArr[2].trim(), true)); continue; } // br if ((execArr = this.rules.br.exec(nextPart))) { nextPart = nextPart.substring(execArr[0].length); out += this.renderer.br(); continue; } // del (gfm) if (this.hasRulesGfm && (execArr = (this.rules as RulesInlineGfm).del.exec(nextPart))) { nextPart = nextPart.substring(execArr[0].length); out += this.renderer.del(this.output(execArr[1])); continue; } // text if ((execArr = this.rules.text.exec(nextPart))) { nextPart = nextPart.substring(execArr[0].length); out += this.renderer.text(this.options.escape(this.smartypants(execArr[0]))); continue; } if (nextPart) { throw new Error('Infinite loop on byte: ' + nextPart.charCodeAt(0)); } } return out; } /** * Compile Link. */ protected outputLink(execArr: RegExpExecArray, link: Link) { const href = this.options.escape(link.href); const title = link.title ? this.options.escape(link.title) : null; return execArr[0].charAt(0) !== '!' ? this.renderer.link(href, title, this.output(execArr[1])) : this.renderer.image(href, title, this.options.escape(execArr[1])); } /** * Smartypants Transformations. */ protected smartypants(text: string) { if (!this.options.smartypants) { return text; } return ( text // em-dashes .replace(/---/g, '\u2014') // en-dashes .replace(/--/g, '\u2013') // opening singles .replace(/(^|[-\u2014/(\[{"\s])'/g, '$1\u2018') // closing singles & apostrophes .replace(/'/g, '\u2019') // opening doubles .replace(/(^|[-\u2014/(\[{\u2018\s])"/g, '$1\u201c') // closing doubles .replace(/"/g, '\u201d') // ellipses .replace(/\.{3}/g, '\u2026') ); } /** * Mangle Links. */ protected mangle(text: string) { if (!this.options.mangle) { return text; } let out = ''; const length = text.length; for (let i = 0; i < length; i++) { let str: string; if (Math.random() > 0.5) { str = 'x' + text.charCodeAt(i).toString(16); } out += '&#' + str + ';'; } return out; } }
the_stack
import chalk from 'chalk' import execa from 'execa' import fs from 'fs' import path from 'path' import type { NormalizedPackageJson } from 'read-pkg-up' import readPkgUp from 'read-pkg-up' import { promisify } from 'util' const exists = promisify(fs.exists) const readFile = promisify(fs.readFile) /** * Async */ export async function getSchemaPath( schemaPathFromArgs?: string, opts: { cwd: string } = { cwd: process.cwd(), }, ): Promise<string | null> { return getSchemaPathInternal(schemaPathFromArgs, { cwd: opts.cwd, }) } export async function getSchemaPathInternal( schemaPathFromArgs?: string, opts: { cwd: string } = { cwd: process.cwd(), }, ): Promise<string | null> { if (schemaPathFromArgs) { // 1. try the user custom path const customSchemaPath = await getAbsoluteSchemaPath(path.resolve(schemaPathFromArgs)) if (!customSchemaPath) { throw new Error(`Provided --schema at ${schemaPathFromArgs} doesn't exist.`) } return customSchemaPath } // 2. Try the package.json `prisma.schema` custom path // 3. Try the conventional ./schema.prisma or ./prisma/schema.prisma paths // 4. Try resolving yarn workspaces and looking for a schema.prisma file there const schemaPath = (await getSchemaPathFromPackageJson(opts.cwd)) ?? (await getRelativeSchemaPath(opts.cwd)) ?? (await resolveYarnSchema(opts.cwd)) if (schemaPath) { return schemaPath } return null } // Example: // "prisma": { // "schema": "db/schema.prisma" // "seed": "ts-node db/seed.ts", // } export type PrismaConfig = { schema?: string seed?: string } export async function getPrismaConfigFromPackageJson(cwd: string) { const pkgJson = await readPkgUp({ cwd }) const prismaPropertyFromPkgJson = pkgJson?.packageJson?.prisma as PrismaConfig | undefined if (!pkgJson) { return null } return { data: prismaPropertyFromPkgJson, packagePath: pkgJson.path, } } export async function getSchemaPathFromPackageJson(cwd: string): Promise<string | null> { const prismaConfig = await getPrismaConfigFromPackageJson(cwd) if (!prismaConfig || !prismaConfig.data?.schema) { return null } const schemaPathFromPkgJson = prismaConfig.data.schema if (typeof schemaPathFromPkgJson !== 'string') { throw new Error( `Provided schema path \`${schemaPathFromPkgJson}\` from \`${path.relative( cwd, prismaConfig.packagePath, )}\` must be of type string`, ) } const absoluteSchemaPath = path.isAbsolute(schemaPathFromPkgJson) ? schemaPathFromPkgJson : path.resolve(path.dirname(prismaConfig.packagePath), schemaPathFromPkgJson) if ((await exists(absoluteSchemaPath)) === false) { throw new Error( `Provided schema path \`${path.relative(cwd, absoluteSchemaPath)}\` from \`${path.relative( cwd, prismaConfig.packagePath, )}\` doesn't exist.`, ) } return absoluteSchemaPath } async function resolveYarnSchema(cwd: string): Promise<string | null> { if (process.env.npm_config_user_agent?.includes('yarn')) { try { const { stdout: version } = await execa.command('yarn --version', { cwd, }) if (version.startsWith('2')) { return null } const { stdout } = await execa.command('yarn workspaces info --json', { cwd, }) const json = getJson(stdout) const workspaces = Object.values<{ location: string }>(json) const workspaceRootDir = await findWorkspaceRoot(cwd) if (!workspaceRootDir) { return null } // Iterate over the workspaces for (const workspace of workspaces) { const workspacePath = path.join(workspaceRootDir, workspace.location) const workspaceSchemaPath = getSchemaPathFromPackageJsonSync(workspacePath) ?? getRelativeSchemaPathSync(workspacePath) if (workspaceSchemaPath) { return workspaceSchemaPath } } const workspaceSchemaPathFromRoot = getSchemaPathFromPackageJsonSync(workspaceRootDir) ?? getRelativeSchemaPathSync(workspaceRootDir) if (workspaceSchemaPathFromRoot) { return workspaceSchemaPathFromRoot } } catch (e) { return null } } return null } function resolveYarnSchemaSync(cwd: string): string | null { if (process.env.npm_config_user_agent?.includes('yarn')) { try { const { stdout: version } = execa.commandSync('yarn --version', { cwd, }) if (version.startsWith('2')) { return null } const { stdout } = execa.commandSync('yarn workspaces info --json', { cwd, }) const json = getJson(stdout) const workspaces = Object.values<{ location: string }>(json) const workspaceRootDir = findWorkspaceRootSync(cwd) if (!workspaceRootDir) { return null } // Iterate over the workspaces for (const workspace of workspaces) { const workspacePath = path.join(workspaceRootDir, workspace.location) const workspaceSchemaPath = getSchemaPathFromPackageJsonSync(workspacePath) ?? getRelativeSchemaPathSync(workspacePath) if (workspaceSchemaPath) { return workspaceSchemaPath } } const workspaceSchemaPathFromRoot = getSchemaPathFromPackageJsonSync(workspaceRootDir) ?? getRelativeSchemaPathSync(workspaceRootDir) if (workspaceSchemaPathFromRoot) { return workspaceSchemaPathFromRoot } } catch (e) { return null } } return null } async function getAbsoluteSchemaPath(schemaPath: string): Promise<string | null> { if (await exists(schemaPath)) { return schemaPath } return null } export async function getRelativeSchemaPath(cwd: string): Promise<string | null> { let schemaPath: string | undefined schemaPath = path.join(cwd, 'schema.prisma') if (await exists(schemaPath)) { return schemaPath } schemaPath = path.join(cwd, `prisma/schema.prisma`) if (await exists(schemaPath)) { return schemaPath } return null } /** * Small helper that returns the directory which contains the `schema.prisma` file */ export async function getSchemaDir(schemaPathFromArgs?: string): Promise<string | null> { if (schemaPathFromArgs) { return path.resolve(path.dirname(schemaPathFromArgs)) } const schemaPath = await getSchemaPath(schemaPathFromArgs) if (!schemaPath) { return null } return path.dirname(schemaPath) } // TODO: This should probably return string | null to stay consistent with the other functions export async function getSchema(schemaPathFromArgs?: string): Promise<string> { const schemaPath = await getSchemaPath(schemaPathFromArgs) if (!schemaPath) { throw new Error( `Could not find a ${chalk.bold( 'schema.prisma', )} file that is required for this command.\nYou can either provide it with ${chalk.greenBright( '--schema', )}, set it as \`prisma.schema\` in your package.json or put it into the default location ${chalk.greenBright( './prisma/schema.prisma', )} https://pris.ly/d/prisma-schema-location`, ) } return readFile(schemaPath, 'utf-8') } /** * Sync */ export function getSchemaPathSync(schemaPathFromArgs?: string): string | null { return getSchemaPathSyncInternal(schemaPathFromArgs, { cwd: process.cwd(), }) } export function getSchemaPathSyncInternal( schemaPathFromArgs?: string, opts: { cwd: string } = { cwd: process.cwd(), }, ): string | null { if (schemaPathFromArgs) { // 1. Try the user custom path const customSchemaPath = getAbsoluteSchemaPathSync(path.resolve(schemaPathFromArgs)) if (!customSchemaPath) { throw new Error(`Provided --schema at ${schemaPathFromArgs} doesn't exist.`) } return customSchemaPath } // 2. Try the package.json `prisma.schema` custom path // 3. Try the conventional `./schema.prisma` or `./prisma/schema.prisma` paths // 4. Try resolving yarn workspaces and looking for a schema.prisma file there const schemaPath = getSchemaPathFromPackageJsonSync(opts.cwd) ?? getRelativeSchemaPathSync(opts.cwd) ?? resolveYarnSchemaSync(opts.cwd) if (schemaPath) { return schemaPath } return null } export function getSchemaPathFromPackageJsonSync(cwd: string): string | null { const pkgJson = readPkgUp.sync({ cwd }) const schemaPathFromPkgJson: string | undefined = pkgJson?.packageJson?.prisma?.schema if (!schemaPathFromPkgJson || !pkgJson) { return null } if (typeof schemaPathFromPkgJson !== 'string') { throw new Error( `Provided schema path \`${schemaPathFromPkgJson}\` from \`${path.relative( cwd, pkgJson.path, )}\` must be of type string`, ) } const absoluteSchemaPath = path.isAbsolute(schemaPathFromPkgJson) ? schemaPathFromPkgJson : path.resolve(path.dirname(pkgJson.path), schemaPathFromPkgJson) if (fs.existsSync(absoluteSchemaPath) === false) { throw new Error( `Provided schema path \`${path.relative(cwd, absoluteSchemaPath)}\` from \`${path.relative( cwd, pkgJson.path, )}\` doesn't exist.`, ) } return absoluteSchemaPath } function getAbsoluteSchemaPathSync(schemaPath: string): string | null { if (fs.existsSync(schemaPath)) { return schemaPath } return null } function getRelativeSchemaPathSync(cwd: string): string | null { let schemaPath = path.join(cwd, 'schema.prisma') if (fs.existsSync(schemaPath)) { return schemaPath } schemaPath = path.join(cwd, `prisma/schema.prisma`) if (fs.existsSync(schemaPath)) { return schemaPath } return null } /** * Sync version of the small helper that returns the directory which contains the `schema.prisma` file */ export function getSchemaDirSync(schemaPathFromArgs?: string): string | null { if (schemaPathFromArgs) { return path.resolve(path.dirname(schemaPathFromArgs)) } const schemaPath = getSchemaPathSync(schemaPathFromArgs) if (schemaPath) { return path.dirname(schemaPath) } return null } // TODO: This should probably return string | null to stay consistent with the other functions export function getSchemaSync(schemaPathFromArgs?: string): string { const schemaPath = getSchemaPathSync(schemaPathFromArgs) if (!schemaPath) { throw new Error( `Could not find a ${chalk.bold( 'schema.prisma', )} file that is required for this command.\nYou can either provide it with ${chalk.greenBright( '--schema', )}, set it as \`prisma.schema\` in your package.json or put it into the default location ${chalk.greenBright( './prisma/schema.prisma', )} https://pris.ly/d/prisma-schema-location`, ) } return fs.readFileSync(schemaPath, 'utf-8') } function getJson(stdout: string): any { const firstCurly = stdout.indexOf('{') const lastCurly = stdout.lastIndexOf('}') const sliced = stdout.slice(firstCurly, lastCurly + 1) return JSON.parse(sliced) } function isPkgJsonWorkspaceRoot(pkgJson: NormalizedPackageJson) { const workspaces = pkgJson.workspaces if (!workspaces) { return false } return Array.isArray(workspaces) || workspaces.packages !== undefined } async function isNearestPkgJsonWorkspaceRoot(cwd: string) { const pkgJson = await readPkgUp({ cwd }) if (!pkgJson) { return null } return { isRoot: isPkgJsonWorkspaceRoot(pkgJson.packageJson), path: pkgJson.path, } } function isNearestPkgJsonWorkspaceRootSync(cwd: string) { const pkgJson = readPkgUp.sync({ cwd }) if (!pkgJson) { return null } return { isRoot: isPkgJsonWorkspaceRoot(pkgJson.packageJson), path: pkgJson.path, } } async function findWorkspaceRoot(cwd: string): Promise<string | null> { let pkgJson = await isNearestPkgJsonWorkspaceRoot(cwd) if (!pkgJson) { return null } if (pkgJson.isRoot === true) { return path.dirname(pkgJson.path) } const pkgJsonParentDir = path.dirname(path.dirname(pkgJson.path)) pkgJson = await isNearestPkgJsonWorkspaceRoot(pkgJsonParentDir) if (!pkgJson || pkgJson.isRoot === false) { return null } return path.dirname(pkgJson.path) } function findWorkspaceRootSync(cwd: string): string | null { let pkgJson = isNearestPkgJsonWorkspaceRootSync(cwd) if (!pkgJson) { return null } if (pkgJson.isRoot === true) { return path.dirname(pkgJson.path) } const pkgJsonParentDir = path.dirname(path.dirname(pkgJson.path)) pkgJson = isNearestPkgJsonWorkspaceRootSync(pkgJsonParentDir) if (!pkgJson || pkgJson.isRoot === false) { return null } return path.dirname(pkgJson.path) }
the_stack
import { assert, expect } from "chai"; import { join } from "path"; import { restore as sinonRestore, spy as sinonSpy } from "sinon"; import { Guid, Id64 } from "@itwin/core-bentley"; import { CodeScopeSpec, CodeSpec, ElementProps, IModel } from "@itwin/core-common"; import { ClassRegistry } from "../../ClassRegistry"; import { ElementUniqueAspect, OnAspectIdArg, OnAspectPropsArg } from "../../ElementAspect"; import { FunctionalBreakdownElement, FunctionalComponentElement, FunctionalModel, FunctionalPartition, FunctionalSchema, InformationPartitionElement, OnChildElementIdArg, OnChildElementPropsArg, OnElementIdArg, OnElementInModelIdArg, OnElementInModelPropsArg, OnElementPropsArg, OnModelIdArg, OnModelPropsArg, OnSubModelIdArg, OnSubModelPropsArg, Schemas, StandaloneDb, } from "../../core-backend"; import { ElementOwnsChildElements, ElementOwnsUniqueAspect, SubjectOwnsPartitionElements } from "../../NavigationRelationship"; import { IModelTestUtils } from "../IModelTestUtils"; let iModelDb: StandaloneDb; const insertedLabel = "inserted label"; const updatedLabel = "updated label"; /** test schema for supplying element/model/aspect classes */ class TestSchema extends FunctionalSchema { public static override get schemaName() { return "TestFunctional"; } } /** partition element for testing `Element.onSubModelXxx` methods */ class TestFuncPartition extends InformationPartitionElement { public static override get className() { return "TestFuncPartition"; } public static override onSubModelInsert(arg: OnSubModelPropsArg): void { super.onSubModelInsert(arg); assert.equal(arg.iModel, iModelDb); assert.equal(arg.subModelProps.classFullName, TestFuncModel.classFullName); } public static override onSubModelInserted(arg: OnSubModelIdArg): void { super.onSubModelInserted(arg); assert.equal(arg.iModel, iModelDb); } public static override onSubModelDelete(arg: OnSubModelIdArg): void { super.onSubModelDelete(arg); assert.equal(arg.iModel, iModelDb); } public static override onSubModelDeleted(arg: OnSubModelIdArg): void { super.onSubModelDeleted(arg); assert.equal(arg.iModel, iModelDb); } } /** for testing `Model.onXxx` methods */ class TestFuncModel extends FunctionalModel { public static override get className() { return "TestFuncModel"; } public static dontDelete = ""; public static override onInsert(arg: OnModelPropsArg): void { super.onInsert(arg); assert.equal(arg.iModel, iModelDb); assert.equal(arg.props.classFullName, this.classFullName); } public static override onInserted(arg: OnModelIdArg): void { super.onInserted(arg); assert.equal(arg.iModel, iModelDb); } public static override onUpdate(arg: OnModelPropsArg): void { super.onUpdate(arg); assert.equal(arg.iModel, iModelDb); } public static override onUpdated(arg: OnModelIdArg): void { super.onUpdated(arg); assert.equal(arg.iModel, iModelDb); } public static override onDelete(arg: OnModelIdArg): void { super.onDelete(arg); assert.equal(arg.iModel, iModelDb); } public static override onDeleted(arg: OnModelIdArg): void { super.onDeleted(arg); assert.equal(arg.iModel, iModelDb); } public static override onInsertElement(arg: OnElementInModelPropsArg): void { super.onInsertElement(arg); assert.equal(arg.iModel, iModelDb); if (arg.elementProps.code.value === "badval") throw new Error("bad element"); } public static override onInsertedElement(arg: OnElementInModelIdArg): void { super.onInsertedElement(arg); assert.equal(arg.iModel, iModelDb); } public static override onUpdateElement(arg: OnElementInModelPropsArg): void { super.onUpdateElement(arg); assert.equal(arg.iModel, iModelDb); } public static override onUpdatedElement(arg: OnElementInModelIdArg): void { super.onUpdatedElement(arg); assert.equal(arg.iModel, iModelDb); } public static override onDeleteElement(arg: OnElementInModelIdArg): void { super.onDeleteElement(arg); assert.equal(arg.iModel, iModelDb); if (arg.elementId === this.dontDelete) throw new Error("dont delete my element"); } public static override onDeletedElement(arg: OnElementInModelIdArg): void { super.onDeletedElement(arg); assert.equal(arg.iModel, iModelDb); } } /** for testing `Element.onXxx` methods */ class Breakdown extends FunctionalBreakdownElement { public static override get className() { return "Breakdown"; } public static dontDeleteChild = ""; public static override onInsert(arg: OnElementPropsArg): void { arg.props.userLabel = insertedLabel; super.onInsert(arg); assert.equal(arg.iModel, iModelDb); assert.equal(arg.props.classFullName, this.classFullName); } public static override onInserted(arg: OnElementIdArg): void { super.onInserted(arg); assert.equal(arg.iModel, iModelDb); } public static override onUpdate(arg: OnElementPropsArg): void { arg.props.userLabel = updatedLabel; super.onUpdate(arg); assert.equal(arg.iModel, iModelDb); assert.equal(arg.props.classFullName, this.classFullName); } public static override onUpdated(arg: OnElementIdArg): void { super.onUpdated(arg); assert.equal(arg.iModel, iModelDb); } public static override onDelete(arg: OnElementIdArg): void { super.onDelete(arg); assert.equal(arg.iModel, iModelDb); } public static override onDeleted(arg: OnElementIdArg): void { super.onDeleted(arg); assert.equal(arg.iModel, iModelDb); } public static override onChildDelete(arg: OnChildElementIdArg): void { super.onChildDelete(arg); assert.equal(arg.iModel, iModelDb); if (arg.childId === this.dontDeleteChild) throw new Error("dont delete my child"); } public static override onChildDeleted(arg: OnChildElementIdArg): void { super.onChildDeleted(arg); assert.equal(arg.iModel, iModelDb); } public static override onChildInsert(arg: OnChildElementPropsArg): void { super.onChildInsert(arg); assert.equal(arg.iModel, iModelDb); } public static override onChildInserted(arg: OnChildElementIdArg): void { super.onChildInserted(arg); assert.equal(arg.iModel, iModelDb); } public static override onChildUpdate(arg: OnChildElementPropsArg): void { super.onChildUpdate(arg); assert.equal(arg.iModel, iModelDb); } public static override onChildUpdated(arg: OnChildElementIdArg): void { super.onChildUpdated(arg); assert.equal(arg.iModel, iModelDb); } public static override onChildAdd(arg: OnChildElementPropsArg): void { super.onChildAdd(arg); assert.equal(arg.iModel, iModelDb); } public static override onChildAdded(arg: OnChildElementIdArg): void { super.onChildAdded(arg); assert.equal(arg.iModel, iModelDb); } public static override onChildDrop(arg: OnChildElementIdArg): void { super.onChildDrop(arg); assert.equal(arg.iModel, iModelDb); } public static override onChildDropped(arg: OnChildElementIdArg): void { super.onChildDropped(arg); assert.equal(arg.iModel, iModelDb); } } /** for testing `ElementAspect.onXxx` methods */ class TestFuncAspect extends ElementUniqueAspect { public static override get className() { return "TestFuncAspect"; } public static expectedVal = ""; public static override onInsert(arg: OnAspectPropsArg): void { super.onInsert(arg); assert.equal(arg.iModel, iModelDb); assert.equal((arg.props as any).strProp, this.expectedVal); } public static override onInserted(arg: OnAspectPropsArg): void { super.onInserted(arg); assert.equal(arg.iModel, iModelDb); assert.equal((arg.props as any).strProp, this.expectedVal); } public static override onUpdate(arg: OnAspectPropsArg): void { super.onUpdate(arg); assert.equal(arg.iModel, iModelDb); assert.equal((arg.props as any).strProp, this.expectedVal); } public static override onUpdated(arg: OnAspectPropsArg): void { super.onUpdated(arg); assert.equal(arg.iModel, iModelDb); assert.equal((arg.props as any).strProp, this.expectedVal); } public static override onDelete(arg: OnAspectIdArg): void { super.onDelete(arg); assert.equal(arg.iModel, iModelDb); } public static override onDeleted(arg: OnAspectIdArg): void { super.onDeleted(arg); assert.equal(arg.iModel, iModelDb); } } class Component extends FunctionalComponentElement { public static override get className() { return "Component"; } } describe("Functional Domain", () => { afterEach(() => { sinonRestore(); }); it("should populate FunctionalModel and test Element, Model, and ElementAspect callbacks", async () => { iModelDb = StandaloneDb.createEmpty(IModelTestUtils.prepareOutputFile("FunctionalDomain", "FunctionalTest.bim"), { rootSubject: { name: "FunctionalTest", description: "Test of the Functional domain schema." }, client: "Functional", globalOrigin: { x: 0, y: 0 }, projectExtents: { low: { x: -500, y: -500, z: -50 }, high: { x: 500, y: 500, z: 50 } }, guid: Guid.createValue(), }); iModelDb.nativeDb.resetBriefcaseId(100); // Import the Functional schema FunctionalSchema.registerSchema(); Schemas.registerSchema(TestSchema); // eslint-disable-next-line @typescript-eslint/naming-convention ClassRegistry.registerModule({ TestFuncPartition, TestFuncModel, Breakdown, Component, TestFuncAspect }, TestSchema); await FunctionalSchema.importSchema(iModelDb); // eslint-disable-line deprecation/deprecation let commits = 0; let committed = 0; const elements = iModelDb.elements; const dropCommit = iModelDb.txns.onCommit.addListener(() => commits++); const dropCommitted = iModelDb.txns.onCommitted.addListener(() => committed++); iModelDb.saveChanges("Import Functional schema"); assert.equal(commits, 1); assert.equal(committed, 1); dropCommit(); dropCommitted(); IModelTestUtils.flushTxns(iModelDb); // importSchema below will fail if this is not called to flush local changes await iModelDb.importSchemas([join(__dirname, "../assets/TestFunctional.ecschema.xml")]); iModelDb.saveChanges("Import TestFunctional schema"); assert.equal(commits, 1); assert.equal(committed, 1); const spy = { model: { onInsert: sinonSpy(TestFuncModel, "onInsert"), onInserted: sinonSpy(TestFuncModel, "onInserted"), onUpdate: sinonSpy(TestFuncModel, "onUpdate"), onUpdated: sinonSpy(TestFuncModel, "onUpdated"), onDelete: sinonSpy(TestFuncModel, "onDelete"), onDeleted: sinonSpy(TestFuncModel, "onDeleted"), onInsertElement: sinonSpy(TestFuncModel, "onInsertElement"), onInsertedElement: sinonSpy(TestFuncModel, "onInsertedElement"), onUpdateElement: sinonSpy(TestFuncModel, "onUpdateElement"), onUpdatedElement: sinonSpy(TestFuncModel, "onUpdatedElement"), onDeleteElement: sinonSpy(TestFuncModel, "onDeleteElement"), onDeletedElement: sinonSpy(TestFuncModel, "onDeletedElement"), }, partition: { onSubModelInsert: sinonSpy(TestFuncPartition, "onSubModelInsert"), onSubModelInserted: sinonSpy(TestFuncPartition, "onSubModelInserted"), onSubModelDelete: sinonSpy(TestFuncPartition, "onSubModelDelete"), onSubModelDeleted: sinonSpy(TestFuncPartition, "onSubModelDeleted"), }, breakdown: { onInsert: sinonSpy(Breakdown, "onInsert"), onInserted: sinonSpy(Breakdown, "onInserted"), onUpdate: sinonSpy(Breakdown, "onUpdate"), onUpdated: sinonSpy(Breakdown, "onUpdated"), onDelete: sinonSpy(Breakdown, "onDelete"), onDeleted: sinonSpy(Breakdown, "onDeleted"), onChildDelete: sinonSpy(Breakdown, "onChildDelete"), onChildDeleted: sinonSpy(Breakdown, "onChildDeleted"), onChildInsert: sinonSpy(Breakdown, "onChildInsert"), onChildInserted: sinonSpy(Breakdown, "onChildInserted"), onChildUpdate: sinonSpy(Breakdown, "onChildUpdate"), onChildUpdated: sinonSpy(Breakdown, "onChildUpdated"), onChildAdd: sinonSpy(Breakdown, "onChildAdd"), onChildAdded: sinonSpy(Breakdown, "onChildAdded"), onChildDrop: sinonSpy(Breakdown, "onChildDrop"), onChildDropped: sinonSpy(Breakdown, "onChildDropped"), }, aspect: { onInsert: sinonSpy(TestFuncAspect, "onInsert"), onInserted: sinonSpy(TestFuncAspect, "onInserted"), onUpdate: sinonSpy(TestFuncAspect, "onUpdate"), onUpdated: sinonSpy(TestFuncAspect, "onUpdated"), onDelete: sinonSpy(TestFuncAspect, "onDelete"), onDeleted: sinonSpy(TestFuncAspect, "onDeleted"), }, }; const codeSpec = CodeSpec.create(iModelDb, "Test Functional Elements", CodeScopeSpec.Type.Model); iModelDb.codeSpecs.insert(codeSpec); assert.isTrue(Id64.isValidId64(codeSpec.id)); const partitionCode = FunctionalPartition.createCode(iModelDb, IModel.rootSubjectId, "Test Functional Model"); const partitionProps = { classFullName: TestFuncPartition.classFullName, model: IModel.repositoryModelId, parent: new SubjectOwnsPartitionElements(IModel.rootSubjectId), code: partitionCode, }; let partitionId = iModelDb.elements.insertElement(partitionProps); const modelId = iModelDb.models.insertModel({ classFullName: TestFuncModel.classFullName, modeledElement: { id: partitionId } }); assert.isTrue(Id64.isValidId64(modelId)); assert.isTrue(spy.model.onInsert.calledOnce); assert.isTrue(spy.model.onInserted.calledOnce); assert.equal(spy.model.onInserted.getCall(0).args[0].id, modelId); assert.isFalse(spy.model.onUpdate.called, "model insert should not call onUpdate"); assert.isFalse(spy.model.onUpdated.called, "model insert should not call onUpdated"); assert.isTrue(spy.partition.onSubModelInsert.calledOnce); assert.isTrue(spy.partition.onSubModelInserted.calledOnce); assert.equal(spy.partition.onSubModelInserted.getCall(0).args[0].subModelId, modelId, "Element.onSubModelInserted should have correct subModelId"); partitionProps.code.value = "Test Func 2"; partitionId = iModelDb.elements.insertElement(partitionProps); const modelId2 = iModelDb.models.insertModel({ classFullName: TestFuncModel.classFullName, modeledElement: { id: partitionId } }); assert.isTrue(Id64.isValidId64(modelId2)); assert.equal(spy.model.onInserted.getCall(1).args[0].id, modelId2, "second insert should set new id"); assert.equal(spy.model.onInsert.callCount, 2); assert.equal(spy.model.onInserted.callCount, 2); assert.equal(spy.partition.onSubModelInserted.getCall(1).args[0].subModelId, modelId2, "Element.onSubModelInserted should have correct subModelId"); const model2 = iModelDb.models.getModel(modelId2); model2.update(); assert.equal(spy.model.onUpdated.getCall(0).args[0].id, modelId2); assert.equal(spy.model.onUpdate.callCount, 1); assert.equal(spy.model.onUpdated.callCount, 1); model2.delete(); assert.isTrue(spy.model.onDelete.calledOnce); assert.isTrue(spy.model.onDeleted.calledOnce); assert.equal(spy.model.onDeleted.getCall(0).args[0].id, modelId2); assert.isTrue(spy.partition.onSubModelDelete.calledOnce); assert.isTrue(spy.partition.onSubModelDeleted.calledOnce); assert.equal(spy.partition.onSubModelDeleted.getCall(0).args[0].subModelId, modelId2); const breakdownProps = { classFullName: Breakdown.classFullName, model: modelId, code: { spec: codeSpec.id, scope: modelId, value: "Breakdown1" } }; const breakdownId = elements.insertElement(breakdownProps); assert.isTrue(Id64.isValidId64(breakdownId)); assert.isTrue(spy.model.onInsertElement.calledOnce); assert.isTrue(spy.model.onInsertedElement.calledOnce); assert.equal(spy.model.onInsertedElement.getCall(0).args[0].elementId, breakdownId); assert.isTrue(spy.breakdown.onInsert.calledOnce); assert.isTrue(spy.breakdown.onInserted.calledOnce); assert.equal(spy.breakdown.onInserted.getCall(0).args[0].id, breakdownId); assert.equal(spy.breakdown.onInsert.getCall(0).args[0].props, breakdownProps); const breakdown2Props: ElementProps = { classFullName: Breakdown.classFullName, model: modelId, code: { spec: codeSpec.id, scope: modelId, value: "badval" } }; // TestFuncModel.onInsertElement throws for this code.value expect(() => elements.insertElement(breakdown2Props)).to.throw("bad element"); breakdown2Props.code.value = "Breakdown2"; breakdown2Props.userLabel = "start label"; // gets overwritten in `onInsert` const bd2 = elements.insertElement(breakdown2Props); const aspect = { classFullName: TestFuncAspect.classFullName, element: new ElementOwnsUniqueAspect(bd2), strProp: "prop 1" }; TestFuncAspect.expectedVal = aspect.strProp; elements.insertAspect(aspect); assert.isTrue(spy.aspect.onInsert.calledOnce); assert.isTrue(spy.aspect.onInserted.calledOnce); assert.isFalse(spy.aspect.onUpdate.called); assert.isFalse(spy.aspect.onUpdated.called); assert.equal(spy.aspect.onInserted.getCall(0).args[0].props.element.id, bd2, "elemId from ElementAspect.onInserted"); aspect.strProp = "prop 2"; TestFuncAspect.expectedVal = aspect.strProp; elements.updateAspect(aspect); assert.equal(spy.aspect.onInsert.callCount, 1, "ElementAspect.onInsert should not be called on update"); assert.equal(spy.aspect.onInserted.callCount, 1, "ElementAspect.onInserted should should not be called on update"); assert.equal(spy.aspect.onUpdate.callCount, 1); assert.equal(spy.aspect.onUpdated.callCount, 1); assert.equal(spy.aspect.onUpdated.getCall(0).args[0].props.element.id, bd2, "from ElementAspect.onUpdated"); const aspects = elements.getAspects(bd2, TestFuncAspect.classFullName); assert.equal(aspects.length, 1); elements.deleteAspect(aspects[0].id); assert.equal(spy.aspect.onDelete.callCount, 1); assert.equal(spy.aspect.onDeleted.callCount, 1); assert.equal(spy.aspect.onDelete.getCall(0).args[0].aspectId, aspects[0].id); assert.equal(spy.aspect.onDeleted.getCall(0).args[0].aspectId, aspects[0].id); let bd2el = elements.getElement(bd2); assert.equal(bd2el.userLabel, insertedLabel, "label was modified by onInsert"); spy.breakdown.onUpdate.resetHistory(); spy.breakdown.onUpdated.resetHistory(); bd2el.userLabel = "nothing"; bd2el.update(); bd2el = elements.getElement(bd2); assert.equal(bd2el.userLabel, updatedLabel, "label was modified in onUpdate"); assert.equal(spy.breakdown.onUpdate.callCount, 1); assert.equal(spy.breakdown.onUpdated.callCount, 1); assert.equal(spy.breakdown.onUpdate.getCall(0).args[0].props.id, bd2); assert.equal(spy.breakdown.onUpdated.getCall(0).args[0].id, bd2); bd2el.delete(); assert.equal(spy.breakdown.onDelete.callCount, 1); assert.equal(spy.breakdown.onDeleted.callCount, 1); assert.equal(spy.breakdown.onDelete.getCall(0).args[0].id, bd2); assert.equal(spy.breakdown.onDeleted.getCall(0).args[0].id, bd2); const breakdown3Props = { classFullName: Breakdown.classFullName, model: modelId, code: { spec: codeSpec.id, scope: modelId, value: "bd3" }, }; const bd3 = elements.insertElement(breakdown3Props); const componentProps = { classFullName: Component.classFullName, model: modelId, parent: { id: breakdownId, relClassName: ElementOwnsChildElements.classFullName }, code: { spec: codeSpec.id, scope: modelId, value: "Component1" }, }; const componentId = elements.insertElement(componentProps); assert.isTrue(Id64.isValidId64(componentId)); assert.equal(spy.breakdown.onChildInserted.callCount, 1); assert.equal(spy.breakdown.onChildInserted.getCall(0).args[0].childId, componentId); // test model and element callbacks for updateElement spy.model.onUpdateElement.resetHistory(); spy.model.onUpdatedElement.resetHistory(); const compponent1 = elements.getElement(componentId); compponent1.update(); assert.equal(spy.model.onUpdateElement.callCount, 1); assert.equal(spy.model.onUpdatedElement.callCount, 1); assert.equal(spy.model.onUpdatedElement.getCall(0).args[0].elementId, componentId); assert.equal(spy.breakdown.onChildUpdate.callCount, 1); assert.equal(spy.breakdown.onChildUpdated.callCount, 1); assert.equal(spy.breakdown.onChildUpdate.getCall(0).args[0].parentId, breakdownId); assert.equal(spy.breakdown.onChildUpdated.getCall(0).args[0].childId, componentId); componentProps.code.value = "comp2"; const comp2 = elements.insertElement(componentProps); assert.equal(spy.breakdown.onChildInserted.callCount, 2); assert.equal(spy.breakdown.onChildInserted.getCall(1).args[0].childId, comp2); const el2 = elements.getElement(comp2); spy.model.onDeleteElement.resetHistory(); spy.model.onDeletedElement.resetHistory(); TestFuncModel.dontDelete = comp2; // block deletion through model expect(() => el2.delete()).to.throw("dont delete my element"); TestFuncModel.dontDelete = ""; // allow deletion through model Breakdown.dontDeleteChild = comp2; // but block through parent expect(() => el2.delete()).to.throw("dont delete my child"); // nope assert.equal(spy.model.onDeleteElement.callCount, 2, "Model.onElementDelete gets called even though element is not really deleted"); assert.equal(spy.model.onDeletedElement.callCount, 0, "make sure Model.onElementDeleted did not get called"); Breakdown.dontDeleteChild = ""; // now fully allow delete el2.delete(); assert.equal(spy.model.onDeleteElement.callCount, 3, "Model.onElementDelete should be called again"); assert.equal(spy.model.onDeletedElement.callCount, 1); assert.equal(spy.model.onDeletedElement.getCall(0).args[0].elementId, comp2); assert.equal(spy.breakdown.onChildDeleted.callCount, 1); assert.equal(spy.breakdown.onChildDeleted.getCall(0).args[0].childId, comp2); // next we make sure that changing the parent of an element calls the "onChildAdd/Drop/Added/Dropped" callbacks. // To do this we switch a component's parent from "breakDownId" to "bc3" componentProps.parent.id = bd3; const comp3 = elements.insertElement(componentProps); const compEl3 = elements.getElementProps(comp3); compEl3.parent!.id = breakdownId; elements.updateElement(compEl3); assert.equal(spy.breakdown.onChildAdd.callCount, 1); assert.equal(spy.breakdown.onChildAdd.getCall(0).args[0].parentId, breakdownId); assert.equal(spy.breakdown.onChildAdd.getCall(0).args[0].childProps.id, comp3); assert.equal(spy.breakdown.onChildDrop.callCount, 1); assert.equal(spy.breakdown.onChildDrop.getCall(0).args[0].parentId, bd3); assert.equal(spy.breakdown.onChildDrop.getCall(0).args[0].childId, comp3); assert.equal(spy.breakdown.onChildAdded.callCount, 1); assert.equal(spy.breakdown.onChildAdded.getCall(0).args[0].parentId, breakdownId); assert.equal(spy.breakdown.onChildAdded.getCall(0).args[0].childId, comp3); assert.equal(spy.breakdown.onChildDropped.callCount, 1); assert.equal(spy.breakdown.onChildDropped.getCall(0).args[0].parentId, bd3); assert.equal(spy.breakdown.onChildDropped.getCall(0).args[0].childId, comp3); iModelDb.saveChanges("Insert Functional elements"); // unregister test schema to make sure it will throw exceptions if it is not present (since it has the "SchemaHasBehavior" custom attribute) Schemas.unregisterSchema(TestSchema.schemaName); const errMsg = "Schema [TestFunctional] not registered, but is marked with SchemaHasBehavior"; expect(() => elements.deleteElement(breakdownId)).to.throw(errMsg); assert.isDefined(elements.getElement(breakdownId), "should not have been deleted"); expect(() => elements.updateElement(breakdownProps)).to.throw(errMsg); breakdownProps.code.value = "Breakdown 2"; expect(() => elements.insertElement(breakdownProps)).to.throw(errMsg); iModelDb.close(); }); });
the_stack
module TDev.RT { //? A collection of objects //@ stem("coll") icon("fa-list-ol") //@ enumerable serializable ctx(general,json) export class Collection<T> extends RTValue { constructor(public typeInfo:any) { super(); } static mkAny(typeInfo:any, a:any[] = []):Collection<any> { return Collection.mk<any>(typeInfo, a) } static mk<T>(a:T[], typeInfo:any):Collection<T> { return Collection.fromArray(a, typeInfo) } static mkStrings(a:string[]):Collection<string> { return Collection.fromArray(a, "string") } static mkNumbers(a:number[]):Collection<number> { return Collection.fromArray(a, "number") } static fromArray<T>(a:T[], typeInfo:any):Collection<T> { if (!a) return undefined; var r = new Collection<T>(typeInfo); r.a = a; return r; } public a:T[] = []; private _continuation:string; public get_enumerator() { return this.a.slice(0); } //? Gets the number of objects. public count() : number { return this.a.length; } //? Removes all objects from the collection //@ writesMutable public clear() : void { this.a = []; } //? Adds an object //@ writesMutable public add(item:T) : void { this.a.push(item); } //? Adds many objects at once //@ writesMutable public add_many(items:Collection<T>) : void { this.a.pushRange(items.a.slice(0)); } //? Gets the index of the first occurrence of an object. Returns -1 if not found or start is out of range. public index_of(item:T, start:number) : number { if (Util.isOOB(start, this.count())) return -1; for (var i = Util.indexCheck(start, this.count()); i < this.a.length; ++i) if (this.a[i] === item) return i; return -1; } //? Gets the object at position index. Returns invalid if index is out of range public at(index:number) : T { return this.a[Math.floor(index)]; } //? Checks if the item is in the collection public contains(item:T) : boolean { var i = this.index_of(item, 0); return (i >= 0); } //? Removes the first occurence of an object. Returns true if removed. //@ writesMutable ignoreReturnValue public remove(item:T) : boolean { var i = this.index_of(item, 0); if (i >= 0) { this.a.splice(i, 1); return true; } else return false; } //? Removes the object at position index. //@ writesMutable public remove_at(index:number) : void { if (Util.isOOB(index, this.count())) return; this.a.splice(Util.indexCheck(index, this.count()), 1); } //? Reverses the order of objects in the collection //@ writesMutable public reverse() : void { this.a.reverse(); } //? Gets a random object from the collection. Returns invalid if the collection is empty. public random() : T { return this.a.length == 0 ? undefined : this.at(Math_.random(this.a.length)); } //? Sets the object at position index. Does nothing if the index is out of range. //@ writesMutable public set_at(index:number, item:T) : void { var _index = Math.floor(index); if (0 <= _index && index < this.a.length) this.a[_index] = item; } //? Inserts an object at position index. Does nothing if index is out of range. //@ writesMutable public insert_at(index:number, item:T) : void { if (Util.isOOB(index, this.count() + 1)) return; this.a.splice(Util.indexCheck(index, this.count() + 1), 0, item); } //? Exports a JSON representation of the contents. //@ readsMutable [result].writesMutable public to_json(sf: IStackFrame): JsonObject { var ctx = new JsonExportCtx(sf); ctx.push(this); var json = this.exportJson(ctx); ctx.pop(this); return JsonObject.wrap(json); } //? Imports a JSON representation of the contents. //@ writesMutable public from_json(jobj: JsonObject, sf:IStackFrame): void { this.importJson(new JsonImportCtx(sf), jobj.value()); } //? Returns a collections of elements that satisfy the filter `condition` //@ readsMutable [result].writesMutable public where(condition:Predicate<T>, s:IStackFrame) : Collection<T> { var rt = s.rt return Collection.fromArray(this.a.filter(e => !!rt.runUserAction(condition, [e])), this.typeInfo) } //? Applies `converter` on all elements of the input collection and returns a collection of results //@ readsMutable [result].writesMutable public map_to<S>(converter:Converter<T,S>, s:IStackFrame, type_S:any) : Collection<S> { var rt = s.rt return Collection.fromArray(this.a.map(e => <S>rt.runUserAction(converter, [e])), type_S) } //? Returns a collection sorted using specified `comparison` function //@ readsMutable [result].writesMutable public sorted(comparison:Comparison<T>, s:IStackFrame) : Collection<T> { var rt = s.rt return Collection.fromArray(this.a.stableSorted((a, b) => rt.runValidUserAction(comparison, [a, b])), this.typeInfo) } //? Returns a collection sorted using specified comparison key //@ readsMutable [result].writesMutable public ordered_by(key:NumberConverter<T>, s:IStackFrame) : Collection<T> { var rt = s.rt return Collection.fromArray(this.a.stableSorted((a, b) => { return rt.runValidUserAction(key, [a]) - rt.runValidUserAction(key, [b]) }), this.typeInfo) } //? Returns a collection sorted using specified comparison key //@ readsMutable [result].writesMutable public ordered_by_string(key:StringConverter<T>, s:IStackFrame) : Collection<T> { var rt = s.rt return Collection.fromArray(this.a.stableSorted((a, b) => { return rt.runValidUserAction(key, [a]).localeCompare(rt.runValidUserAction(key, [b])) }), this.typeInfo) } //? Returns a collection with the `count` first elements if any. //@ readsMutable [result].writesMutable public take(count: number, s: IStackFrame): Collection<T> { return Collection.fromArray(this.a.slice(0, Math.floor(count)), this.typeInfo); } //? Returns a slice of the collection starting at `start`, and ends at, but does not include, the `end`. //@ readsMutable [result].writesMutable public slice(start: number, end: number): Collection<T> { return Collection.fromArray(this.a.slice(Math.floor(start), Math.floor(end)), this.typeInfo); } //? Gets the first element if any public first(): T { return this.at(0); } //? Gets the last element if any public last(): T { return this.at(this.count() - 1); } public jsonExportKey(ctx: JsonExportCtx) { return null; // conservative - recursion is possible if wrapped type is recursive } public exportJson(ctx: JsonExportCtx): any { if (this.a.length > 0 && (this.a[0]["exportJson"] === undefined)) { var a0 = this.a[0] if (typeof a0 == "string" || typeof a0 == "number" || typeof a0 == "boolean") { // primitives are OK } else Util.userError(lf("json export is not supported for this type")); } return ctx.encodeArrayNode(this, this.a.slice(0)); } public importJson(ctx: JsonImportCtx, json: any): RT.RTValue { var prev = this.a; this.a = [] if (!Array.isArray(json)) return this if (typeof this.typeInfo == "string") { if (this.typeInfo === "number") json.forEach(n => { if (typeof n === "number") this.a.push(<any>n) }) else if (this.typeInfo === "string") json.forEach(n => { if (typeof n === "string") this.a.push(<any>n) }) else if (this.typeInfo === "boolean") json.forEach(n => { if (typeof n === "boolean") this.a.push(<any>n) }) else Util.userError("json import is not supported for Collection of " + this.typeInfo); } else if (this.typeInfo instanceof RecordSingleton) { for (var n = 0; n < json.length; n++) { var o = ctx.importRecord(json, prev[n], n, this.typeInfo); if (o) this.a.push(<any>o); } } else if (typeof this.typeInfo === "function") { var ctor = this.typeInfo json.forEach(n => { var v = new ctor() v = v.importJson(ctx, n) if (v) this.a.push(v) }) } else { Util.userError("json import is not supported for this Collection") } return this } private getHtml() { var first = undefined for (var i = 0; i < this.a.length; ++i) if (this.a[i]) { first = this.a[i]; break; } var s = '['; for (var i = 0; i < this.a.length; ++i) { if (i > 0) s += ', '; s += this.a[i]; } s += ']'; return span(null, s); } private getRecord():RecordSingleton { if (this.typeInfo instanceof RecordSingleton) return <RecordSingleton>this.typeInfo return null } //? Display all objects on the wall public post_to_wall(s : IStackFrame): void { if (this.getRecord()) s.rt.postBoxedHtml(this.getRecord().getTable(<any[]>this.a, s), s.pc); else if (this.typeInfo.prototype instanceof RTValue) (<any[]>this.a).forEach((v: RTValue) => v.post_to_wall(s)); else s.rt.postBoxedHtml(this.getHtml(), s.pc); } public debuggerDisplay(clickHandler: () => any): HTMLElement { var e: HTMLElement; if (this.getRecord()) { try { e = this.getRecord().getTable(<any[]>this.a, null); } catch (e) { e = span(null, e.message || ""); // can be a "user error" when record originated from stale session } } else { e = this.getHtml() } return e.withClick(clickHandler); } //? Ask user to pick an entry from this collection //@ uiAsync returns(T) public pick_entry(text: string, r: ResumeCtx) { var rt = r.rt; var getView = (o: any) => { if (o.getIndexCard) return o.getIndexCard(r.stackframe) else if (o.getViewCore) return o.getViewCore(r.stackframe, null) else if (o.toString) return o.toString() else return o + "" }; var m = new ModalDialog(); var chosen = null; var btns = this.a.map((o: any) => div('modalDialogChooseItem', getView(o)).withClick(() => { chosen = o; m.dismiss(); })); m.add([div("wall-dialog-header", text)/* ,div("wall-dialog-body", caption)*/]); m.onDismiss = () => r.resumeVal(chosen); m.choose(btns); } //? Computes the sum of the key of the elements in the collection //@ readsMutable public sum_of(key: NumberConverter<T>, s: IStackFrame): number { var rt = s.rt var v = this.a.map(x => <number>rt.runValidUserAction(key, [x])); return Util.stableSum(v); } //? Computes the maximum of the key of the elements in the collection //@ readsMutable public max_of(key: NumberConverter<T>, s: IStackFrame): number { var rt = s.rt if (this.a.length == 0) return undefined; var m = <number>rt.runValidUserAction(key, [this.a[0]]); for (var i = 1; i < this.a.length; ++i) { var v = <number>rt.runValidUserAction(key, [this.a[i]]); if (v > m) m = v; } return m; } //? Computes the average of the key of the elements in the collection //@ readsMutable public avg_of(key: NumberConverter<T>, s: IStackFrame): number { var rt = s.rt if (this.a.length == 0) return undefined; return this.sum_of(key, s) / this.count(); } //? Computes the minimum of the key of the elements in the collection //@ readsMutable public min_of(key: NumberConverter<T>, s: IStackFrame): number { var rt = s.rt if (this.a.length == 0) return undefined; var m = <number>rt.runValidUserAction(key, [this.a[0]]); for (var i = 1; i < this.a.length; ++i) { var v = <number>rt.runValidUserAction(key, [this.a[i]]); if (v < m) m = v; } return m; } // // Methods specific to Collection<some-specific-type> // //? Computes the minimum of the values //@ readsMutable onlyOn(Number) public min(): number { var a = <number[]><any>this.a if (a.length == 0) return undefined; return this.a.min(); } //? Computes the maximum of the values //@ readsMutable onlyOn(Number) public max() : number { if (this.a.length == 0) return undefined; var a = <number[]><any>this.a return a.max(); } //? Computes the sum of the values //@ readsMutable onlyOn(Number) public sum(): number { if (this.a.length == 0) return 0; var a = <number[]><any>this.a return Util.stableSum(a); } //? Computes the average of the values //@ readsMutable onlyOn(Number) public avg(): number { if (this.a.length == 0) return 0; return this.sum() / this.a.length; } //? Sorts from the newest to oldest //@ writesMutable onlyOn(Message) public sort_by_date(): void { (<Message[]><any>this.a).sort(function (m1, m2) { if (!m1.time()) return 1; if (!m2.time()) return -1; return m1.time().d.valueOf() < m2.time().d.valueOf() ? -1 : 1; }); } //? Sorts the strings in this collection //@ writesMutable onlyOn(Number, String) public sort() : void { this.a.sort(); // TODO locale? } //? Sorts the places by distance to the location //@ writesMutable onlyOn(Location, Place) public sort_by_distance(loc:Location_) : void { var getLoc = (l) => { if (l instanceof Place) return (<Place>l).location() return <Location_>l } (<any[]>this.a).sort((l, r) => { var lloc = getLoc(l) var rloc = getLoc(r) if (!lloc && !rloc) return 0; if (!lloc) return 1; if (!rloc) return -1; return rloc.distance(lloc) - lloc.distance(rloc); }); } //? Concatenates the separator and items into a string //@ readsMutable onlyOn(Number, String) public join(separator:string) : string { return (<string[]><any>this.a).join(separator); } //? Gets the identifier of the next set of items (if any) //@ readsMutable public continuation(): string { return this._continuation || ""; } //? Sets the identifier of the next set of items //@ writesMutable public set_continuation(value : string) : void { this._continuation = value; } } // Backward-compat for javascript* APIs export module StringCollection { export function mk(v:string[]) { return Collection.mkStrings(v) } export function fromArray(v:string[]) { return Collection.mkStrings(v) } } export module NumberCollection { export function mk(v:number[]) { return Collection.mkNumbers(v) } export function fromArray(v:number[]) { return Collection.mkNumbers(v) } } }
the_stack
import {Request} from '../lib/request'; import {Response} from '../lib/response'; import {AWSError} from '../lib/error'; import {Service} from '../lib/service'; import {ServiceConfigurationOptions} from '../lib/service'; import {ConfigBase as Config} from '../lib/config-base'; interface Blob {} declare class ECRPUBLIC extends Service { /** * Constructs a service object. This object has one method for each API operation. */ constructor(options?: ECRPUBLIC.Types.ClientConfiguration) config: Config & ECRPUBLIC.Types.ClientConfiguration; /** * Checks the availability of one or more image layers within a repository in a public registry. When an image is pushed to a repository, each image layer is checked to verify if it has been uploaded before. If it has been uploaded, then the image layer is skipped. This operation is used by the Amazon ECR proxy and is not generally used by customers for pulling and pushing images. In most cases, you should use the docker CLI to pull, tag, and push images. */ batchCheckLayerAvailability(params: ECRPUBLIC.Types.BatchCheckLayerAvailabilityRequest, callback?: (err: AWSError, data: ECRPUBLIC.Types.BatchCheckLayerAvailabilityResponse) => void): Request<ECRPUBLIC.Types.BatchCheckLayerAvailabilityResponse, AWSError>; /** * Checks the availability of one or more image layers within a repository in a public registry. When an image is pushed to a repository, each image layer is checked to verify if it has been uploaded before. If it has been uploaded, then the image layer is skipped. This operation is used by the Amazon ECR proxy and is not generally used by customers for pulling and pushing images. In most cases, you should use the docker CLI to pull, tag, and push images. */ batchCheckLayerAvailability(callback?: (err: AWSError, data: ECRPUBLIC.Types.BatchCheckLayerAvailabilityResponse) => void): Request<ECRPUBLIC.Types.BatchCheckLayerAvailabilityResponse, AWSError>; /** * Deletes a list of specified images within a repository in a public registry. Images are specified with either an imageTag or imageDigest. You can remove a tag from an image by specifying the image's tag in your request. When you remove the last tag from an image, the image is deleted from your repository. You can completely delete an image (and all of its tags) by specifying the image's digest in your request. */ batchDeleteImage(params: ECRPUBLIC.Types.BatchDeleteImageRequest, callback?: (err: AWSError, data: ECRPUBLIC.Types.BatchDeleteImageResponse) => void): Request<ECRPUBLIC.Types.BatchDeleteImageResponse, AWSError>; /** * Deletes a list of specified images within a repository in a public registry. Images are specified with either an imageTag or imageDigest. You can remove a tag from an image by specifying the image's tag in your request. When you remove the last tag from an image, the image is deleted from your repository. You can completely delete an image (and all of its tags) by specifying the image's digest in your request. */ batchDeleteImage(callback?: (err: AWSError, data: ECRPUBLIC.Types.BatchDeleteImageResponse) => void): Request<ECRPUBLIC.Types.BatchDeleteImageResponse, AWSError>; /** * Informs Amazon ECR that the image layer upload has completed for a specified public registry, repository name, and upload ID. You can optionally provide a sha256 digest of the image layer for data validation purposes. When an image is pushed, the CompleteLayerUpload API is called once per each new image layer to verify that the upload has completed. This operation is used by the Amazon ECR proxy and is not generally used by customers for pulling and pushing images. In most cases, you should use the docker CLI to pull, tag, and push images. */ completeLayerUpload(params: ECRPUBLIC.Types.CompleteLayerUploadRequest, callback?: (err: AWSError, data: ECRPUBLIC.Types.CompleteLayerUploadResponse) => void): Request<ECRPUBLIC.Types.CompleteLayerUploadResponse, AWSError>; /** * Informs Amazon ECR that the image layer upload has completed for a specified public registry, repository name, and upload ID. You can optionally provide a sha256 digest of the image layer for data validation purposes. When an image is pushed, the CompleteLayerUpload API is called once per each new image layer to verify that the upload has completed. This operation is used by the Amazon ECR proxy and is not generally used by customers for pulling and pushing images. In most cases, you should use the docker CLI to pull, tag, and push images. */ completeLayerUpload(callback?: (err: AWSError, data: ECRPUBLIC.Types.CompleteLayerUploadResponse) => void): Request<ECRPUBLIC.Types.CompleteLayerUploadResponse, AWSError>; /** * Creates a repository in a public registry. For more information, see Amazon ECR repositories in the Amazon Elastic Container Registry User Guide. */ createRepository(params: ECRPUBLIC.Types.CreateRepositoryRequest, callback?: (err: AWSError, data: ECRPUBLIC.Types.CreateRepositoryResponse) => void): Request<ECRPUBLIC.Types.CreateRepositoryResponse, AWSError>; /** * Creates a repository in a public registry. For more information, see Amazon ECR repositories in the Amazon Elastic Container Registry User Guide. */ createRepository(callback?: (err: AWSError, data: ECRPUBLIC.Types.CreateRepositoryResponse) => void): Request<ECRPUBLIC.Types.CreateRepositoryResponse, AWSError>; /** * Deletes a repository in a public registry. If the repository contains images, you must either delete all images in the repository or use the force option which deletes all images on your behalf before deleting the repository. */ deleteRepository(params: ECRPUBLIC.Types.DeleteRepositoryRequest, callback?: (err: AWSError, data: ECRPUBLIC.Types.DeleteRepositoryResponse) => void): Request<ECRPUBLIC.Types.DeleteRepositoryResponse, AWSError>; /** * Deletes a repository in a public registry. If the repository contains images, you must either delete all images in the repository or use the force option which deletes all images on your behalf before deleting the repository. */ deleteRepository(callback?: (err: AWSError, data: ECRPUBLIC.Types.DeleteRepositoryResponse) => void): Request<ECRPUBLIC.Types.DeleteRepositoryResponse, AWSError>; /** * Deletes the repository policy associated with the specified repository. */ deleteRepositoryPolicy(params: ECRPUBLIC.Types.DeleteRepositoryPolicyRequest, callback?: (err: AWSError, data: ECRPUBLIC.Types.DeleteRepositoryPolicyResponse) => void): Request<ECRPUBLIC.Types.DeleteRepositoryPolicyResponse, AWSError>; /** * Deletes the repository policy associated with the specified repository. */ deleteRepositoryPolicy(callback?: (err: AWSError, data: ECRPUBLIC.Types.DeleteRepositoryPolicyResponse) => void): Request<ECRPUBLIC.Types.DeleteRepositoryPolicyResponse, AWSError>; /** * Returns the image tag details for a repository in a public registry. */ describeImageTags(params: ECRPUBLIC.Types.DescribeImageTagsRequest, callback?: (err: AWSError, data: ECRPUBLIC.Types.DescribeImageTagsResponse) => void): Request<ECRPUBLIC.Types.DescribeImageTagsResponse, AWSError>; /** * Returns the image tag details for a repository in a public registry. */ describeImageTags(callback?: (err: AWSError, data: ECRPUBLIC.Types.DescribeImageTagsResponse) => void): Request<ECRPUBLIC.Types.DescribeImageTagsResponse, AWSError>; /** * Returns metadata about the images in a repository in a public registry. Beginning with Docker version 1.9, the Docker client compresses image layers before pushing them to a V2 Docker registry. The output of the docker images command shows the uncompressed image size, so it may return a larger image size than the image sizes returned by DescribeImages. */ describeImages(params: ECRPUBLIC.Types.DescribeImagesRequest, callback?: (err: AWSError, data: ECRPUBLIC.Types.DescribeImagesResponse) => void): Request<ECRPUBLIC.Types.DescribeImagesResponse, AWSError>; /** * Returns metadata about the images in a repository in a public registry. Beginning with Docker version 1.9, the Docker client compresses image layers before pushing them to a V2 Docker registry. The output of the docker images command shows the uncompressed image size, so it may return a larger image size than the image sizes returned by DescribeImages. */ describeImages(callback?: (err: AWSError, data: ECRPUBLIC.Types.DescribeImagesResponse) => void): Request<ECRPUBLIC.Types.DescribeImagesResponse, AWSError>; /** * Returns details for a public registry. */ describeRegistries(params: ECRPUBLIC.Types.DescribeRegistriesRequest, callback?: (err: AWSError, data: ECRPUBLIC.Types.DescribeRegistriesResponse) => void): Request<ECRPUBLIC.Types.DescribeRegistriesResponse, AWSError>; /** * Returns details for a public registry. */ describeRegistries(callback?: (err: AWSError, data: ECRPUBLIC.Types.DescribeRegistriesResponse) => void): Request<ECRPUBLIC.Types.DescribeRegistriesResponse, AWSError>; /** * Describes repositories in a public registry. */ describeRepositories(params: ECRPUBLIC.Types.DescribeRepositoriesRequest, callback?: (err: AWSError, data: ECRPUBLIC.Types.DescribeRepositoriesResponse) => void): Request<ECRPUBLIC.Types.DescribeRepositoriesResponse, AWSError>; /** * Describes repositories in a public registry. */ describeRepositories(callback?: (err: AWSError, data: ECRPUBLIC.Types.DescribeRepositoriesResponse) => void): Request<ECRPUBLIC.Types.DescribeRepositoriesResponse, AWSError>; /** * Retrieves an authorization token. An authorization token represents your IAM authentication credentials and can be used to access any Amazon ECR registry that your IAM principal has access to. The authorization token is valid for 12 hours. This API requires the ecr-public:GetAuthorizationToken and sts:GetServiceBearerToken permissions. */ getAuthorizationToken(params: ECRPUBLIC.Types.GetAuthorizationTokenRequest, callback?: (err: AWSError, data: ECRPUBLIC.Types.GetAuthorizationTokenResponse) => void): Request<ECRPUBLIC.Types.GetAuthorizationTokenResponse, AWSError>; /** * Retrieves an authorization token. An authorization token represents your IAM authentication credentials and can be used to access any Amazon ECR registry that your IAM principal has access to. The authorization token is valid for 12 hours. This API requires the ecr-public:GetAuthorizationToken and sts:GetServiceBearerToken permissions. */ getAuthorizationToken(callback?: (err: AWSError, data: ECRPUBLIC.Types.GetAuthorizationTokenResponse) => void): Request<ECRPUBLIC.Types.GetAuthorizationTokenResponse, AWSError>; /** * Retrieves catalog metadata for a public registry. */ getRegistryCatalogData(params: ECRPUBLIC.Types.GetRegistryCatalogDataRequest, callback?: (err: AWSError, data: ECRPUBLIC.Types.GetRegistryCatalogDataResponse) => void): Request<ECRPUBLIC.Types.GetRegistryCatalogDataResponse, AWSError>; /** * Retrieves catalog metadata for a public registry. */ getRegistryCatalogData(callback?: (err: AWSError, data: ECRPUBLIC.Types.GetRegistryCatalogDataResponse) => void): Request<ECRPUBLIC.Types.GetRegistryCatalogDataResponse, AWSError>; /** * Retrieve catalog metadata for a repository in a public registry. This metadata is displayed publicly in the Amazon ECR Public Gallery. */ getRepositoryCatalogData(params: ECRPUBLIC.Types.GetRepositoryCatalogDataRequest, callback?: (err: AWSError, data: ECRPUBLIC.Types.GetRepositoryCatalogDataResponse) => void): Request<ECRPUBLIC.Types.GetRepositoryCatalogDataResponse, AWSError>; /** * Retrieve catalog metadata for a repository in a public registry. This metadata is displayed publicly in the Amazon ECR Public Gallery. */ getRepositoryCatalogData(callback?: (err: AWSError, data: ECRPUBLIC.Types.GetRepositoryCatalogDataResponse) => void): Request<ECRPUBLIC.Types.GetRepositoryCatalogDataResponse, AWSError>; /** * Retrieves the repository policy for the specified repository. */ getRepositoryPolicy(params: ECRPUBLIC.Types.GetRepositoryPolicyRequest, callback?: (err: AWSError, data: ECRPUBLIC.Types.GetRepositoryPolicyResponse) => void): Request<ECRPUBLIC.Types.GetRepositoryPolicyResponse, AWSError>; /** * Retrieves the repository policy for the specified repository. */ getRepositoryPolicy(callback?: (err: AWSError, data: ECRPUBLIC.Types.GetRepositoryPolicyResponse) => void): Request<ECRPUBLIC.Types.GetRepositoryPolicyResponse, AWSError>; /** * Notifies Amazon ECR that you intend to upload an image layer. When an image is pushed, the InitiateLayerUpload API is called once per image layer that has not already been uploaded. Whether or not an image layer has been uploaded is determined by the BatchCheckLayerAvailability API action. This operation is used by the Amazon ECR proxy and is not generally used by customers for pulling and pushing images. In most cases, you should use the docker CLI to pull, tag, and push images. */ initiateLayerUpload(params: ECRPUBLIC.Types.InitiateLayerUploadRequest, callback?: (err: AWSError, data: ECRPUBLIC.Types.InitiateLayerUploadResponse) => void): Request<ECRPUBLIC.Types.InitiateLayerUploadResponse, AWSError>; /** * Notifies Amazon ECR that you intend to upload an image layer. When an image is pushed, the InitiateLayerUpload API is called once per image layer that has not already been uploaded. Whether or not an image layer has been uploaded is determined by the BatchCheckLayerAvailability API action. This operation is used by the Amazon ECR proxy and is not generally used by customers for pulling and pushing images. In most cases, you should use the docker CLI to pull, tag, and push images. */ initiateLayerUpload(callback?: (err: AWSError, data: ECRPUBLIC.Types.InitiateLayerUploadResponse) => void): Request<ECRPUBLIC.Types.InitiateLayerUploadResponse, AWSError>; /** * Creates or updates the image manifest and tags associated with an image. When an image is pushed and all new image layers have been uploaded, the PutImage API is called once to create or update the image manifest and the tags associated with the image. This operation is used by the Amazon ECR proxy and is not generally used by customers for pulling and pushing images. In most cases, you should use the docker CLI to pull, tag, and push images. */ putImage(params: ECRPUBLIC.Types.PutImageRequest, callback?: (err: AWSError, data: ECRPUBLIC.Types.PutImageResponse) => void): Request<ECRPUBLIC.Types.PutImageResponse, AWSError>; /** * Creates or updates the image manifest and tags associated with an image. When an image is pushed and all new image layers have been uploaded, the PutImage API is called once to create or update the image manifest and the tags associated with the image. This operation is used by the Amazon ECR proxy and is not generally used by customers for pulling and pushing images. In most cases, you should use the docker CLI to pull, tag, and push images. */ putImage(callback?: (err: AWSError, data: ECRPUBLIC.Types.PutImageResponse) => void): Request<ECRPUBLIC.Types.PutImageResponse, AWSError>; /** * Create or updates the catalog data for a public registry. */ putRegistryCatalogData(params: ECRPUBLIC.Types.PutRegistryCatalogDataRequest, callback?: (err: AWSError, data: ECRPUBLIC.Types.PutRegistryCatalogDataResponse) => void): Request<ECRPUBLIC.Types.PutRegistryCatalogDataResponse, AWSError>; /** * Create or updates the catalog data for a public registry. */ putRegistryCatalogData(callback?: (err: AWSError, data: ECRPUBLIC.Types.PutRegistryCatalogDataResponse) => void): Request<ECRPUBLIC.Types.PutRegistryCatalogDataResponse, AWSError>; /** * Creates or updates the catalog data for a repository in a public registry. */ putRepositoryCatalogData(params: ECRPUBLIC.Types.PutRepositoryCatalogDataRequest, callback?: (err: AWSError, data: ECRPUBLIC.Types.PutRepositoryCatalogDataResponse) => void): Request<ECRPUBLIC.Types.PutRepositoryCatalogDataResponse, AWSError>; /** * Creates or updates the catalog data for a repository in a public registry. */ putRepositoryCatalogData(callback?: (err: AWSError, data: ECRPUBLIC.Types.PutRepositoryCatalogDataResponse) => void): Request<ECRPUBLIC.Types.PutRepositoryCatalogDataResponse, AWSError>; /** * Applies a repository policy to the specified public repository to control access permissions. For more information, see Amazon ECR Repository Policies in the Amazon Elastic Container Registry User Guide. */ setRepositoryPolicy(params: ECRPUBLIC.Types.SetRepositoryPolicyRequest, callback?: (err: AWSError, data: ECRPUBLIC.Types.SetRepositoryPolicyResponse) => void): Request<ECRPUBLIC.Types.SetRepositoryPolicyResponse, AWSError>; /** * Applies a repository policy to the specified public repository to control access permissions. For more information, see Amazon ECR Repository Policies in the Amazon Elastic Container Registry User Guide. */ setRepositoryPolicy(callback?: (err: AWSError, data: ECRPUBLIC.Types.SetRepositoryPolicyResponse) => void): Request<ECRPUBLIC.Types.SetRepositoryPolicyResponse, AWSError>; /** * Uploads an image layer part to Amazon ECR. When an image is pushed, each new image layer is uploaded in parts. The maximum size of each image layer part can be 20971520 bytes (or about 20MB). The UploadLayerPart API is called once per each new image layer part. This operation is used by the Amazon ECR proxy and is not generally used by customers for pulling and pushing images. In most cases, you should use the docker CLI to pull, tag, and push images. */ uploadLayerPart(params: ECRPUBLIC.Types.UploadLayerPartRequest, callback?: (err: AWSError, data: ECRPUBLIC.Types.UploadLayerPartResponse) => void): Request<ECRPUBLIC.Types.UploadLayerPartResponse, AWSError>; /** * Uploads an image layer part to Amazon ECR. When an image is pushed, each new image layer is uploaded in parts. The maximum size of each image layer part can be 20971520 bytes (or about 20MB). The UploadLayerPart API is called once per each new image layer part. This operation is used by the Amazon ECR proxy and is not generally used by customers for pulling and pushing images. In most cases, you should use the docker CLI to pull, tag, and push images. */ uploadLayerPart(callback?: (err: AWSError, data: ECRPUBLIC.Types.UploadLayerPartResponse) => void): Request<ECRPUBLIC.Types.UploadLayerPartResponse, AWSError>; } declare namespace ECRPUBLIC { export type AboutText = string; export type Architecture = string; export type ArchitectureList = Architecture[]; export type Arn = string; export interface AuthorizationData { /** * A base64-encoded string that contains authorization data for a public Amazon ECR registry. When the string is decoded, it is presented in the format user:password for public registry authentication using docker login. */ authorizationToken?: Base64; /** * The Unix time in seconds and milliseconds when the authorization token expires. Authorization tokens are valid for 12 hours. */ expiresAt?: ExpirationTimestamp; } export type Base64 = string; export interface BatchCheckLayerAvailabilityRequest { /** * The AWS account ID associated with the public registry that contains the image layers to check. If you do not specify a registry, the default public registry is assumed. */ registryId?: RegistryIdOrAlias; /** * The name of the repository that is associated with the image layers to check. */ repositoryName: RepositoryName; /** * The digests of the image layers to check. */ layerDigests: BatchedOperationLayerDigestList; } export interface BatchCheckLayerAvailabilityResponse { /** * A list of image layer objects corresponding to the image layer references in the request. */ layers?: LayerList; /** * Any failures associated with the call. */ failures?: LayerFailureList; } export interface BatchDeleteImageRequest { /** * The AWS account ID associated with the registry that contains the image to delete. If you do not specify a registry, the default public registry is assumed. */ registryId?: RegistryId; /** * The repository in a public registry that contains the image to delete. */ repositoryName: RepositoryName; /** * A list of image ID references that correspond to images to delete. The format of the imageIds reference is imageTag=tag or imageDigest=digest. */ imageIds: ImageIdentifierList; } export interface BatchDeleteImageResponse { /** * The image IDs of the deleted images. */ imageIds?: ImageIdentifierList; /** * Any failures associated with the call. */ failures?: ImageFailureList; } export type BatchedOperationLayerDigest = string; export type BatchedOperationLayerDigestList = BatchedOperationLayerDigest[]; export interface CompleteLayerUploadRequest { /** * The AWS account ID associated with the registry to which to upload layers. If you do not specify a registry, the default public registry is assumed. */ registryId?: RegistryIdOrAlias; /** * The name of the repository in a public registry to associate with the image layer. */ repositoryName: RepositoryName; /** * The upload ID from a previous InitiateLayerUpload operation to associate with the image layer. */ uploadId: UploadId; /** * The sha256 digest of the image layer. */ layerDigests: LayerDigestList; } export interface CompleteLayerUploadResponse { /** * The public registry ID associated with the request. */ registryId?: RegistryId; /** * The repository name associated with the request. */ repositoryName?: RepositoryName; /** * The upload ID associated with the layer. */ uploadId?: UploadId; /** * The sha256 digest of the image layer. */ layerDigest?: LayerDigest; } export interface CreateRepositoryRequest { /** * The name to use for the repository. This appears publicly in the Amazon ECR Public Gallery. The repository name may be specified on its own (such as nginx-web-app) or it can be prepended with a namespace to group the repository into a category (such as project-a/nginx-web-app). */ repositoryName: RepositoryName; /** * The details about the repository that are publicly visible in the Amazon ECR Public Gallery. */ catalogData?: RepositoryCatalogDataInput; } export interface CreateRepositoryResponse { /** * The repository that was created. */ repository?: Repository; catalogData?: RepositoryCatalogData; } export type CreationTimestamp = Date; export type DefaultRegistryAliasFlag = boolean; export interface DeleteRepositoryPolicyRequest { /** * The AWS account ID associated with the public registry that contains the repository policy to delete. If you do not specify a registry, the default public registry is assumed. */ registryId?: RegistryId; /** * The name of the repository that is associated with the repository policy to delete. */ repositoryName: RepositoryName; } export interface DeleteRepositoryPolicyResponse { /** * The registry ID associated with the request. */ registryId?: RegistryId; /** * The repository name associated with the request. */ repositoryName?: RepositoryName; /** * The JSON repository policy that was deleted from the repository. */ policyText?: RepositoryPolicyText; } export interface DeleteRepositoryRequest { /** * The AWS account ID associated with the public registry that contains the repository to delete. If you do not specify a registry, the default public registry is assumed. */ registryId?: RegistryId; /** * The name of the repository to delete. */ repositoryName: RepositoryName; /** * If a repository contains images, forces the deletion. */ force?: ForceFlag; } export interface DeleteRepositoryResponse { /** * The repository that was deleted. */ repository?: Repository; } export interface DescribeImageTagsRequest { /** * The AWS account ID associated with the public registry that contains the repository in which to describe images. If you do not specify a registry, the default public registry is assumed. */ registryId?: RegistryId; /** * The name of the repository that contains the image tag details to describe. */ repositoryName: RepositoryName; /** * The nextToken value returned from a previous paginated DescribeImageTags request where maxResults was used and the results exceeded the value of that parameter. Pagination continues from the end of the previous results that returned the nextToken value. This value is null when there are no more results to return. This option cannot be used when you specify images with imageIds. */ nextToken?: NextToken; /** * The maximum number of repository results returned by DescribeImageTags in paginated output. When this parameter is used, DescribeImageTags only returns maxResults results in a single page along with a nextToken response element. The remaining results of the initial request can be seen by sending another DescribeImageTags request with the returned nextToken value. This value can be between 1 and 1000. If this parameter is not used, then DescribeImageTags returns up to 100 results and a nextToken value, if applicable. This option cannot be used when you specify images with imageIds. */ maxResults?: MaxResults; } export interface DescribeImageTagsResponse { /** * The image tag details for the images in the requested repository. */ imageTagDetails?: ImageTagDetailList; /** * The nextToken value to include in a future DescribeImageTags request. When the results of a DescribeImageTags request exceed maxResults, this value can be used to retrieve the next page of results. This value is null when there are no more results to return. */ nextToken?: NextToken; } export interface DescribeImagesRequest { /** * The AWS account ID associated with the public registry that contains the repository in which to describe images. If you do not specify a registry, the default public registry is assumed. */ registryId?: RegistryId; /** * The repository that contains the images to describe. */ repositoryName: RepositoryName; /** * The list of image IDs for the requested repository. */ imageIds?: ImageIdentifierList; /** * The nextToken value returned from a previous paginated DescribeImages request where maxResults was used and the results exceeded the value of that parameter. Pagination continues from the end of the previous results that returned the nextToken value. This value is null when there are no more results to return. This option cannot be used when you specify images with imageIds. */ nextToken?: NextToken; /** * The maximum number of repository results returned by DescribeImages in paginated output. When this parameter is used, DescribeImages only returns maxResults results in a single page along with a nextToken response element. The remaining results of the initial request can be seen by sending another DescribeImages request with the returned nextToken value. This value can be between 1 and 1000. If this parameter is not used, then DescribeImages returns up to 100 results and a nextToken value, if applicable. This option cannot be used when you specify images with imageIds. */ maxResults?: MaxResults; } export interface DescribeImagesResponse { /** * A list of ImageDetail objects that contain data about the image. */ imageDetails?: ImageDetailList; /** * The nextToken value to include in a future DescribeImages request. When the results of a DescribeImages request exceed maxResults, this value can be used to retrieve the next page of results. This value is null when there are no more results to return. */ nextToken?: NextToken; } export interface DescribeRegistriesRequest { /** * The nextToken value returned from a previous paginated DescribeRegistries request where maxResults was used and the results exceeded the value of that parameter. Pagination continues from the end of the previous results that returned the nextToken value. This value is null when there are no more results to return. This token should be treated as an opaque identifier that is only used to retrieve the next items in a list and not for other programmatic purposes. */ nextToken?: NextToken; /** * The maximum number of repository results returned by DescribeRegistries in paginated output. When this parameter is used, DescribeRegistries only returns maxResults results in a single page along with a nextToken response element. The remaining results of the initial request can be seen by sending another DescribeRegistries request with the returned nextToken value. This value can be between 1 and 1000. If this parameter is not used, then DescribeRegistries returns up to 100 results and a nextToken value, if applicable. */ maxResults?: MaxResults; } export interface DescribeRegistriesResponse { /** * An object containing the details for a public registry. */ registries: RegistryList; /** * The nextToken value to include in a future DescribeRepositories request. When the results of a DescribeRepositories request exceed maxResults, this value can be used to retrieve the next page of results. This value is null when there are no more results to return. */ nextToken?: NextToken; } export interface DescribeRepositoriesRequest { /** * The AWS account ID associated with the registry that contains the repositories to be described. If you do not specify a registry, the default public registry is assumed. */ registryId?: RegistryId; /** * A list of repositories to describe. If this parameter is omitted, then all repositories in a registry are described. */ repositoryNames?: RepositoryNameList; /** * The nextToken value returned from a previous paginated DescribeRepositories request where maxResults was used and the results exceeded the value of that parameter. Pagination continues from the end of the previous results that returned the nextToken value. This value is null when there are no more results to return. This option cannot be used when you specify repositories with repositoryNames. This token should be treated as an opaque identifier that is only used to retrieve the next items in a list and not for other programmatic purposes. */ nextToken?: NextToken; /** * The maximum number of repository results returned by DescribeRepositories in paginated output. When this parameter is used, DescribeRepositories only returns maxResults results in a single page along with a nextToken response element. The remaining results of the initial request can be seen by sending another DescribeRepositories request with the returned nextToken value. This value can be between 1 and 1000. If this parameter is not used, then DescribeRepositories returns up to 100 results and a nextToken value, if applicable. This option cannot be used when you specify repositories with repositoryNames. */ maxResults?: MaxResults; } export interface DescribeRepositoriesResponse { /** * A list of repository objects corresponding to valid repositories. */ repositories?: RepositoryList; /** * The nextToken value to include in a future DescribeRepositories request. When the results of a DescribeRepositories request exceed maxResults, this value can be used to retrieve the next page of results. This value is null when there are no more results to return. */ nextToken?: NextToken; } export type ExpirationTimestamp = Date; export type ForceFlag = boolean; export interface GetAuthorizationTokenRequest { } export interface GetAuthorizationTokenResponse { /** * An authorization token data object that corresponds to a public registry. */ authorizationData?: AuthorizationData; } export interface GetRegistryCatalogDataRequest { } export interface GetRegistryCatalogDataResponse { /** * The catalog metadata for the public registry. */ registryCatalogData: RegistryCatalogData; } export interface GetRepositoryCatalogDataRequest { /** * The AWS account ID associated with the registry that contains the repositories to be described. If you do not specify a registry, the default public registry is assumed. */ registryId?: RegistryId; /** * The name of the repository to retrieve the catalog metadata for. */ repositoryName: RepositoryName; } export interface GetRepositoryCatalogDataResponse { /** * The catalog metadata for the repository. */ catalogData?: RepositoryCatalogData; } export interface GetRepositoryPolicyRequest { /** * The AWS account ID associated with the public registry that contains the repository. If you do not specify a registry, the default public registry is assumed. */ registryId?: RegistryId; /** * The name of the repository with the policy to retrieve. */ repositoryName: RepositoryName; } export interface GetRepositoryPolicyResponse { /** * The registry ID associated with the request. */ registryId?: RegistryId; /** * The repository name associated with the request. */ repositoryName?: RepositoryName; /** * The repository policy text associated with the repository. The policy text will be in JSON format. */ policyText?: RepositoryPolicyText; } export interface Image { /** * The AWS account ID associated with the registry containing the image. */ registryId?: RegistryIdOrAlias; /** * The name of the repository associated with the image. */ repositoryName?: RepositoryName; /** * An object containing the image tag and image digest associated with an image. */ imageId?: ImageIdentifier; /** * The image manifest associated with the image. */ imageManifest?: ImageManifest; /** * The manifest media type of the image. */ imageManifestMediaType?: MediaType; } export interface ImageDetail { /** * The AWS account ID associated with the public registry to which this image belongs. */ registryId?: RegistryId; /** * The name of the repository to which this image belongs. */ repositoryName?: RepositoryName; /** * The sha256 digest of the image manifest. */ imageDigest?: ImageDigest; /** * The list of tags associated with this image. */ imageTags?: ImageTagList; /** * The size, in bytes, of the image in the repository. If the image is a manifest list, this will be the max size of all manifests in the list. Beginning with Docker version 1.9, the Docker client compresses image layers before pushing them to a V2 Docker registry. The output of the docker images command shows the uncompressed image size, so it may return a larger image size than the image sizes returned by DescribeImages. */ imageSizeInBytes?: ImageSizeInBytes; /** * The date and time, expressed in standard JavaScript date format, at which the current image was pushed to the repository. */ imagePushedAt?: PushTimestamp; /** * The media type of the image manifest. */ imageManifestMediaType?: MediaType; /** * The artifact media type of the image. */ artifactMediaType?: MediaType; } export type ImageDetailList = ImageDetail[]; export type ImageDigest = string; export interface ImageFailure { /** * The image ID associated with the failure. */ imageId?: ImageIdentifier; /** * The code associated with the failure. */ failureCode?: ImageFailureCode; /** * The reason for the failure. */ failureReason?: ImageFailureReason; } export type ImageFailureCode = "InvalidImageDigest"|"InvalidImageTag"|"ImageTagDoesNotMatchDigest"|"ImageNotFound"|"MissingDigestAndTag"|"ImageReferencedByManifestList"|"KmsError"|string; export type ImageFailureList = ImageFailure[]; export type ImageFailureReason = string; export interface ImageIdentifier { /** * The sha256 digest of the image manifest. */ imageDigest?: ImageDigest; /** * The tag used for the image. */ imageTag?: ImageTag; } export type ImageIdentifierList = ImageIdentifier[]; export type ImageManifest = string; export type ImageSizeInBytes = number; export type ImageTag = string; export interface ImageTagDetail { /** * The tag associated with the image. */ imageTag?: ImageTag; /** * The time stamp indicating when the image tag was created. */ createdAt?: CreationTimestamp; /** * An object that describes the details of an image. */ imageDetail?: ReferencedImageDetail; } export type ImageTagDetailList = ImageTagDetail[]; export type ImageTagList = ImageTag[]; export interface InitiateLayerUploadRequest { /** * The AWS account ID associated with the registry to which you intend to upload layers. If you do not specify a registry, the default public registry is assumed. */ registryId?: RegistryIdOrAlias; /** * The name of the repository to which you intend to upload layers. */ repositoryName: RepositoryName; } export interface InitiateLayerUploadResponse { /** * The upload ID for the layer upload. This parameter is passed to further UploadLayerPart and CompleteLayerUpload operations. */ uploadId?: UploadId; /** * The size, in bytes, that Amazon ECR expects future layer part uploads to be. */ partSize?: PartSize; } export interface Layer { /** * The sha256 digest of the image layer. */ layerDigest?: LayerDigest; /** * The availability status of the image layer. */ layerAvailability?: LayerAvailability; /** * The size, in bytes, of the image layer. */ layerSize?: LayerSizeInBytes; /** * The media type of the layer, such as application/vnd.docker.image.rootfs.diff.tar.gzip or application/vnd.oci.image.layer.v1.tar+gzip. */ mediaType?: MediaType; } export type LayerAvailability = "AVAILABLE"|"UNAVAILABLE"|string; export type LayerDigest = string; export type LayerDigestList = LayerDigest[]; export interface LayerFailure { /** * The layer digest associated with the failure. */ layerDigest?: BatchedOperationLayerDigest; /** * The failure code associated with the failure. */ failureCode?: LayerFailureCode; /** * The reason for the failure. */ failureReason?: LayerFailureReason; } export type LayerFailureCode = "InvalidLayerDigest"|"MissingLayerDigest"|string; export type LayerFailureList = LayerFailure[]; export type LayerFailureReason = string; export type LayerList = Layer[]; export type LayerPartBlob = Buffer|Uint8Array|Blob|string; export type LayerSizeInBytes = number; export type LogoImageBlob = Buffer|Uint8Array|Blob|string; export type MarketplaceCertified = boolean; export type MaxResults = number; export type MediaType = string; export type NextToken = string; export type OperatingSystem = string; export type OperatingSystemList = OperatingSystem[]; export type PartSize = number; export type PrimaryRegistryAliasFlag = boolean; export type PushTimestamp = Date; export interface PutImageRequest { /** * The AWS account ID associated with the public registry that contains the repository in which to put the image. If you do not specify a registry, the default public registry is assumed. */ registryId?: RegistryIdOrAlias; /** * The name of the repository in which to put the image. */ repositoryName: RepositoryName; /** * The image manifest corresponding to the image to be uploaded. */ imageManifest: ImageManifest; /** * The media type of the image manifest. If you push an image manifest that does not contain the mediaType field, you must specify the imageManifestMediaType in the request. */ imageManifestMediaType?: MediaType; /** * The tag to associate with the image. This parameter is required for images that use the Docker Image Manifest V2 Schema 2 or Open Container Initiative (OCI) formats. */ imageTag?: ImageTag; /** * The image digest of the image manifest corresponding to the image. */ imageDigest?: ImageDigest; } export interface PutImageResponse { /** * Details of the image uploaded. */ image?: Image; } export interface PutRegistryCatalogDataRequest { /** * The display name for a public registry. The display name is shown as the repository author in the Amazon ECR Public Gallery. The registry display name is only publicly visible in the Amazon ECR Public Gallery for verified accounts. */ displayName?: RegistryDisplayName; } export interface PutRegistryCatalogDataResponse { /** * The catalog data for the public registry. */ registryCatalogData: RegistryCatalogData; } export interface PutRepositoryCatalogDataRequest { /** * The AWS account ID associated with the public registry the repository is in. If you do not specify a registry, the default public registry is assumed. */ registryId?: RegistryId; /** * The name of the repository to create or update the catalog data for. */ repositoryName: RepositoryName; /** * An object containing the catalog data for a repository. This data is publicly visible in the Amazon ECR Public Gallery. */ catalogData: RepositoryCatalogDataInput; } export interface PutRepositoryCatalogDataResponse { /** * The catalog data for the repository. */ catalogData?: RepositoryCatalogData; } export interface ReferencedImageDetail { /** * The sha256 digest of the image manifest. */ imageDigest?: ImageDigest; /** * The size, in bytes, of the image in the repository. If the image is a manifest list, this will be the max size of all manifests in the list. Beginning with Docker version 1.9, the Docker client compresses image layers before pushing them to a V2 Docker registry. The output of the docker images command shows the uncompressed image size, so it may return a larger image size than the image sizes returned by DescribeImages. */ imageSizeInBytes?: ImageSizeInBytes; /** * The date and time, expressed in standard JavaScript date format, at which the current image tag was pushed to the repository. */ imagePushedAt?: PushTimestamp; /** * The media type of the image manifest. */ imageManifestMediaType?: MediaType; /** * The artifact media type of the image. */ artifactMediaType?: MediaType; } export interface Registry { /** * The AWS account ID associated with the registry. If you do not specify a registry, the default public registry is assumed. */ registryId: RegistryId; /** * The Amazon Resource Name (ARN) of the public registry. */ registryArn: Arn; /** * The URI of a public registry. The URI contains a universal prefix and the registry alias. */ registryUri: Url; /** * Whether the account is verified. This indicates whether the account is an AWS Marketplace vendor. If an account is verified, each public repository will received a verified account badge on the Amazon ECR Public Gallery. */ verified: RegistryVerified; /** * An array of objects representing the aliases for a public registry. */ aliases: RegistryAliasList; } export interface RegistryAlias { /** * The name of the registry alias. */ name: RegistryAliasName; /** * The status of the registry alias. */ status: RegistryAliasStatus; /** * Whether or not the registry alias is the primary alias for the registry. If true, the alias is the primary registry alias and is displayed in both the repository URL and the image URI used in the docker pull commands on the Amazon ECR Public Gallery. A registry alias that is not the primary registry alias can be used in the repository URI in a docker pull command. */ primaryRegistryAlias: PrimaryRegistryAliasFlag; /** * Whether or not the registry alias is the default alias for the registry. When the first public repository is created, your public registry is assigned a default registry alias. */ defaultRegistryAlias: DefaultRegistryAliasFlag; } export type RegistryAliasList = RegistryAlias[]; export type RegistryAliasName = string; export type RegistryAliasStatus = "ACTIVE"|"PENDING"|"REJECTED"|string; export interface RegistryCatalogData { /** * The display name for a public registry. This appears on the Amazon ECR Public Gallery. Only accounts that have the verified account badge can have a registry display name. */ displayName?: RegistryDisplayName; } export type RegistryDisplayName = string; export type RegistryId = string; export type RegistryIdOrAlias = string; export type RegistryList = Registry[]; export type RegistryVerified = boolean; export interface Repository { /** * The Amazon Resource Name (ARN) that identifies the repository. The ARN contains the arn:aws:ecr namespace, followed by the region of the repository, AWS account ID of the repository owner, repository namespace, and repository name. For example, arn:aws:ecr:region:012345678910:repository/test. */ repositoryArn?: Arn; /** * The AWS account ID associated with the public registry that contains the repository. */ registryId?: RegistryId; /** * The name of the repository. */ repositoryName?: RepositoryName; /** * The URI for the repository. You can use this URI for container image push and pull operations. */ repositoryUri?: Url; /** * The date and time, in JavaScript date format, when the repository was created. */ createdAt?: CreationTimestamp; } export interface RepositoryCatalogData { /** * The short description of the repository. */ description?: RepositoryDescription; /** * The architecture tags that are associated with the repository. Only supported operating system tags appear publicly in the Amazon ECR Public Gallery. For more information, see RepositoryCatalogDataInput. */ architectures?: ArchitectureList; /** * The operating system tags that are associated with the repository. Only supported operating system tags appear publicly in the Amazon ECR Public Gallery. For more information, see RepositoryCatalogDataInput. */ operatingSystems?: OperatingSystemList; /** * The URL containing the logo associated with the repository. */ logoUrl?: ResourceUrl; /** * The longform description of the contents of the repository. This text appears in the repository details on the Amazon ECR Public Gallery. */ aboutText?: AboutText; /** * The longform usage details of the contents of the repository. The usage text provides context for users of the repository. */ usageText?: UsageText; /** * Whether or not the repository is certified by AWS Marketplace. */ marketplaceCertified?: MarketplaceCertified; } export interface RepositoryCatalogDataInput { /** * A short description of the contents of the repository. This text appears in both the image details and also when searching for repositories on the Amazon ECR Public Gallery. */ description?: RepositoryDescription; /** * The system architecture that the images in the repository are compatible with. On the Amazon ECR Public Gallery, the following supported architectures will appear as badges on the repository and are used as search filters. Linux Windows If an unsupported tag is added to your repository catalog data, it will be associated with the repository and can be retrieved using the API but will not be discoverable in the Amazon ECR Public Gallery. */ architectures?: ArchitectureList; /** * The operating systems that the images in the repository are compatible with. On the Amazon ECR Public Gallery, the following supported operating systems will appear as badges on the repository and are used as search filters. ARM ARM 64 x86 x86-64 If an unsupported tag is added to your repository catalog data, it will be associated with the repository and can be retrieved using the API but will not be discoverable in the Amazon ECR Public Gallery. */ operatingSystems?: OperatingSystemList; /** * The base64-encoded repository logo payload. The repository logo is only publicly visible in the Amazon ECR Public Gallery for verified accounts. */ logoImageBlob?: LogoImageBlob; /** * A detailed description of the contents of the repository. It is publicly visible in the Amazon ECR Public Gallery. The text must be in markdown format. */ aboutText?: AboutText; /** * Detailed information on how to use the contents of the repository. It is publicly visible in the Amazon ECR Public Gallery. The usage text provides context, support information, and additional usage details for users of the repository. The text must be in markdown format. */ usageText?: UsageText; } export type RepositoryDescription = string; export type RepositoryList = Repository[]; export type RepositoryName = string; export type RepositoryNameList = RepositoryName[]; export type RepositoryPolicyText = string; export type ResourceUrl = string; export interface SetRepositoryPolicyRequest { /** * The AWS account ID associated with the registry that contains the repository. If you do not specify a registry, the default public registry is assumed. */ registryId?: RegistryId; /** * The name of the repository to receive the policy. */ repositoryName: RepositoryName; /** * The JSON repository policy text to apply to the repository. For more information, see Amazon ECR Repository Policies in the Amazon Elastic Container Registry User Guide. */ policyText: RepositoryPolicyText; /** * If the policy you are attempting to set on a repository policy would prevent you from setting another policy in the future, you must force the SetRepositoryPolicy operation. This is intended to prevent accidental repository lock outs. */ force?: ForceFlag; } export interface SetRepositoryPolicyResponse { /** * The registry ID associated with the request. */ registryId?: RegistryId; /** * The repository name associated with the request. */ repositoryName?: RepositoryName; /** * The JSON repository policy text applied to the repository. */ policyText?: RepositoryPolicyText; } export type UploadId = string; export interface UploadLayerPartRequest { /** * The AWS account ID associated with the registry to which you are uploading layer parts. If you do not specify a registry, the default public registry is assumed. */ registryId?: RegistryIdOrAlias; /** * The name of the repository to which you are uploading layer parts. */ repositoryName: RepositoryName; /** * The upload ID from a previous InitiateLayerUpload operation to associate with the layer part upload. */ uploadId: UploadId; /** * The position of the first byte of the layer part witin the overall image layer. */ partFirstByte: PartSize; /** * The position of the last byte of the layer part within the overall image layer. */ partLastByte: PartSize; /** * The base64-encoded layer part payload. */ layerPartBlob: LayerPartBlob; } export interface UploadLayerPartResponse { /** * The registry ID associated with the request. */ registryId?: RegistryId; /** * The repository name associated with the request. */ repositoryName?: RepositoryName; /** * The upload ID associated with the request. */ uploadId?: UploadId; /** * The integer value of the last byte received in the request. */ lastByteReceived?: PartSize; } export type Url = string; export type UsageText = string; /** * A string in YYYY-MM-DD format that represents the latest possible API version that can be used in this service. Specify 'latest' to use the latest possible version. */ export type apiVersion = "2020-10-30"|"latest"|string; export interface ClientApiVersions { /** * A string in YYYY-MM-DD format that represents the latest possible API version that can be used in this service. Specify 'latest' to use the latest possible version. */ apiVersion?: apiVersion; } export type ClientConfiguration = ServiceConfigurationOptions & ClientApiVersions; /** * Contains interfaces for use with the ECRPUBLIC client. */ export import Types = ECRPUBLIC; } export = ECRPUBLIC;
the_stack
import { client, dataKey, portal } from "."; import { convertSkylinkToBase64, genKeyPairAndSeed, uriSkynetPrefix } from "../src"; import { randomUnicodeString } from "../utils/testing"; describe(`Upload and download end-to-end tests for portal '${portal}'`, () => { const fileData = "testing"; const json = { key: "testdownload" }; const plaintextType = "text/plain"; const plaintextMetadata = { filename: dataKey, length: fileData.length, subfiles: { HelloWorld: { filename: dataKey, contenttype: plaintextType, len: fileData.length }, }, tryfiles: ["index.html"], }; it("Should get file content for an existing entry link of depth 1", async () => { const entryLink = "AQDwh1jnoZas9LaLHC_D4-2yP9XYDdZzNtz62H4Dww1jDA"; const expectedDataLink = `${uriSkynetPrefix}XABvi7JtJbQSMAcDwnUnmp2FKDPjg8_tTTFP4BwMSxVdEg`; const { skylink } = await client.getFileContent(entryLink); expect(skylink).toEqual(expectedDataLink); }); it("Should get file content for an existing entry link of depth 2", async () => { const entryLinkBase32 = "0400mgds8arrfnu8e6b0sde9fbkmh4nl2etvun55m0fvidudsb7bk78"; const entryLink = convertSkylinkToBase64(entryLinkBase32); const expectedDataLink = `${uriSkynetPrefix}EAAFgq17B-MKsi0ARYKUMmf9vxbZlDpZkA6EaVBCG4YBAQ`; const { skylink } = await client.getFileContent(entryLink); expect(skylink).toEqual(expectedDataLink); }); it("Should upload and download directories", async () => { const directory = { "file1.jpeg": new File(["foo1"], "file1.jpeg"), // Test a space in the subfile name. "file 2.jpeg": new File(["foo2"], "file 2.jpeg"), "subdir/file3.jpeg": new File(["foo3"], "subdir/file3.jpeg"), }; const dirname = "dirname"; const dirType = "application/zip"; const { skylink } = await client.uploadDirectory(directory, dirname); expect(skylink).not.toEqual(""); // Get content for the skylink and check returned values. { const resp = await client.getFileContent(skylink); const { data, contentType, portalUrl, skylink: returnedSkylink } = resp; expect(data).toEqual(expect.any(String)); expect(contentType).toEqual(dirType); expect(portalUrl).toEqualPortalUrl(portal); expect(skylink).toEqual(returnedSkylink); } // Get file content for each subfile. { const { data } = await client.getFileContent(`${skylink}/file1.jpeg`); expect(data).toEqual("foo1"); } { const { data } = await client.getFileContent(`${skylink}/file 2.jpeg`); expect(data).toEqual("foo2"); } { const { data } = await client.getFileContent(`${skylink}/subdir:file3.jpeg`); expect(data).toEqual("foo3"); } }); it("Custom filenames should take effect", async () => { const customFilename = "asdf!!"; // Upload the data with a custom filename. const file = new File([fileData], dataKey); const { skylink } = await client.uploadFile(file, { customFilename }); expect(skylink).not.toEqual(""); // Get file metadata and check filename. const { metadata } = await client.getMetadata(skylink); expect(metadata).toEqual(expect.objectContaining({ filename: customFilename })); }); it("Should get plaintext file contents", async () => { // Upload the data to acquire its skylink. const file = new File([fileData], dataKey, { type: plaintextType }); const { skylink } = await client.uploadFile(file); expect(skylink).not.toEqual(""); // Get file content and check returned values. const { data, contentType, portalUrl, skylink: returnedSkylink } = await client.getFileContent(skylink); expect(data).toEqual(fileData); expect(contentType).toEqual("text/plain"); expect(portalUrl).toEqualPortalUrl(portal); expect(skylink).toEqual(returnedSkylink); }); it("Should get plaintext file metadata", async () => { // Upload the data to acquire its skylink. const file = new File([fileData], dataKey, { type: plaintextType }); const { skylink } = await client.uploadFile(file); expect(skylink).not.toEqual(""); // Get file metadata and check returned values. const { metadata, portalUrl, skylink: returnedSkylink } = await client.getMetadata(skylink); expect(metadata).toEqual(plaintextMetadata); expect(portalUrl).toEqualPortalUrl(portal); expect(skylink).toEqual(returnedSkylink); }); it("Should get JSON file contents", async () => { // Upload the data to acquire its skylink. const file = new File([JSON.stringify(json)], dataKey, { type: "application/json" }); const { skylink } = await client.uploadFile(file); const { data, contentType } = await client.getFileContent(skylink); expect(data).toEqual(expect.any(Object)); expect(data).toEqual(json); expect(contentType).toEqual("application/json"); }); it("Should get file contents when content type is not specified but inferred from filename", async () => { // Upload the data to acquire its skylink. Content type is inferred from filename. const file = new File([JSON.stringify(json)], `${dataKey}.json`); const { skylink } = await client.uploadFile(file); expect(skylink).not.toEqual(""); // Get file content and check returned values. const { data, contentType } = await client.getFileContent(skylink); expect(data).toEqual(expect.any(Object)); expect(data).toEqual(json); expect(contentType).toEqual("application/json"); }); it("should get file contents when content type is not specified", async () => { // Upload the data to acquire its skylink. Don't specify a content type. const file = new File([JSON.stringify(json)], dataKey); const { skylink } = await client.uploadFile(file); expect(skylink).not.toEqual(""); // Get file content and check returned values. const { data, contentType } = await client.getFileContent(skylink); expect(typeof data).toEqual("object"); expect(data).toEqual(json); expect(contentType).toEqual("application/octet-stream"); }); it('should get binary data with responseType: "arraybuffer"', async () => { // Hard-code skylink for a sqlite3 database. const skylink = "DABchy1Q3tBUggIP9IF_7ha9vAfBZ1d2aYRxUnHSQg9QNA"; // Get file content and check returned values. const { data, contentType } = await client.getFileContent(skylink, { responseType: "arraybuffer" }); expect(typeof data).toEqual("object"); expect(data instanceof ArrayBuffer).toBeTruthy(); expect(contentType).toEqual("application/octet-stream"); }); it("Should upload and download a file with spaces in the filename", async () => { const filename = " foo bar "; const file = new File(["asdf"], filename); expect(file.size).toEqual(4); const { skylink } = await client.uploadFile(file); expect(skylink).not.toEqual(""); // Get file content and check returned values. const { data } = await client.getFileContent(skylink); expect(data).toEqual("asdf"); }); it("Should upload and download a 0-byte file", async () => { const onProgress = (progress: number) => { expect(progress).toEqual(1); }; const file = new File([""], dataKey); expect(file.size).toEqual(0); const { skylink } = await client.uploadFile(file, { onUploadProgress: onProgress }); expect(skylink).not.toEqual(""); // Get file content and check returned values. const { data } = await client.getFileContent(skylink, { onDownloadProgress: onProgress }); expect(data).toEqual(""); }); it("Should upload and download a 1-byte file", async () => { const filedata = "a"; const onProgress = (progress: number) => { expect(progress).toBeLessThanOrEqual(1); }; const file = new File([filedata], dataKey); expect(file.size).toEqual(filedata.length); const { skylink } = await client.uploadFile(file, { onUploadProgress: onProgress }); expect(skylink).not.toEqual(""); // Get file content and check returned values. const { data } = await client.getFileContent(skylink, { onDownloadProgress: onProgress }); expect(data).toEqual(filedata); }); it("Should upload and download two files with different names and compare their etags", async () => { // Generate random filenames. const [filename1, filename2] = [randomUnicodeString(16), randomUnicodeString(16)]; const data = "file"; // Upload the files. const [{ skylink: skylink1 }, { skylink: skylink2 }] = await Promise.all([ client.uploadFile(new File([data], filename1)), client.uploadFile(new File([data], filename2)), ]); await expectDifferentEtags(skylink1, skylink2); }); it("Should upload and download two files with different contents and compare their etags", async () => { // Generate random file data. const [data1, data2] = [randomUnicodeString(4096), randomUnicodeString(4096)]; const filename = "file"; // Upload the files. const [{ skylink: skylink1 }, { skylink: skylink2 }] = await Promise.all([ client.uploadFile(new File([data1], filename)), client.uploadFile(new File([data2], filename)), ]); await expectDifferentEtags(skylink1, skylink2); }); it("Should update an etag for a resolver skylink after changing its data", async () => { const { publicKey, privateKey } = genKeyPairAndSeed(); // Generate random file data. const [data1, data2] = [randomUnicodeString(4096), randomUnicodeString(4096)]; const filename = "file"; // Generate a data key and get its entry link. const dataKey = randomUnicodeString(16); const entryLink = await client.registry.getEntryLink(publicKey, dataKey); // Upload two random files. const [{ skylink: skylink1 }, { skylink: skylink2 }] = await Promise.all([ client.uploadFile(new File([data1], filename)), client.uploadFile(new File([data2], filename)), ]); // Set the data link for the first file at a random data key. await client.db.setDataLink(privateKey, dataKey, skylink1); // Sleep for a bit to account for the portal's load balancer switching // servers. This helps ensure that the uploaded files are available. await new Promise((r) => setTimeout(r, 3000)); // Get the entry link's etag. const url = await client.getSkylinkUrl(entryLink); // @ts-expect-error Calling a private method. const response1 = await client.getFileContentRequest(url); const etag1 = response1.headers["etag"]; expect(etag1).toBeTruthy(); // Set the data link for the second file. await client.db.setDataLink(privateKey, dataKey, skylink2); // Check that the etag was updated. // @ts-expect-error Calling a private method. const response2 = await client.getFileContentRequest(url); const etag2 = response2.headers["etag"]; expect(etag2).toBeTruthy(); expect(etag2).not.toEqual(etag1); }); it("should fail to download a non-existent skylink", async () => { // Use a resolver skylink as it will time out faster. const skylink = "AQDwh1jnoZas9LaLHC_D4-2yO9XYDdZzNtz62H4Dww1jDB"; await expect(client.getFileContent(skylink)).rejects.toThrowError("Failed to resolve skylink"); }); }); /** * Runs the etag test on the given skylinks that expects different etags. * * @param skylink1 - The first skylink. * @param skylink2 - The second skylink. */ export async function expectDifferentEtags(skylink1: string, skylink2: string): Promise<void> { // The skylinks should differ. expect(skylink1).not.toEqual(skylink2); // Sleep for a bit to account for the portal's load balancer switching // servers. This helps ensure that the uploaded files are available. await new Promise((r) => setTimeout(r, 3000)); // Download the files. let [url1, url2] = await Promise.all([client.getSkylinkUrl(skylink1), client.getSkylinkUrl(skylink2)]); const [response1, response2] = await Promise.all([ // @ts-expect-error Calling a private method. client.getFileContentRequest(url1), // @ts-expect-error Calling a private method. client.getFileContentRequest(url2), ]); // Get the etags. const [etag1, etag2] = [response1.headers["etag"], response2.headers["etag"]]; expect(etag1).toBeTruthy(); expect(etag2).toBeTruthy(); // The etags should differ. expect(etag1).not.toEqual(etag2); // Download the files using nocache. [url1, url2] = [`${url1}?nocache=true`, `${url2}?nocache=true`]; const [response3, response4] = await Promise.all([ // @ts-expect-error Calling a private method. client.getFileContentRequest(url1), // @ts-expect-error Calling a private method. client.getFileContentRequest(url2), ]); // The etags should not have changed. const [etag3, etag4] = [response3.headers["etag"], response4.headers["etag"]]; expect(etag3).toEqual(etag1); expect(etag4).toEqual(etag2); }
the_stack
export as namespace system; /** * System events dispatched by {@link framework.CastReceiverContext}. * @see https://developers.google.com/cast/docs/reference/web_receiver/cast.framework.system#.EventType */ export enum EventType { ALLOW_GROUP_CHANGE = 'allowgroupchange', /** * Fired when there is a system error. */ ERROR = 'error', /** * Fired when system starts to create feedback report. */ FEEDBACK_STARTED = 'feedbackstarted', GROUP_CAPABILITIES = 'groupcapabilities', MAX_VIDEO_RESOLUTION_CHANGED = 'maxvideoresolutionchanged', PROXIMITY_CHANGED = 'proximitychanged', /** * Fired when the system is ready. */ READY = 'ready', /** * Fired when a new sender has connected. */ SENDER_CONNECTED = 'senderconnected', /** * Fired when a sender has disconnected. */ SENDER_DISCONNECTED = 'senderdisconnected', /** * Fired when the application is terminated */ SHUTDOWN = 'shutdown', /** * Fired when the standby state of the TV has changed. * This event is related to the visibility chnaged event, as if the TV is in standby * the visibility will be false, the visibility is more granular * (as it also detects that the TV has selected a different channel) * but it is not reliably detected in all TVs, * standby can be used in those cases as most TVs implement it. */ STANDBY_CHANGED = 'standbychanged', /** * Fired when the system volume has changed. */ SYSTEM_VOLUME_CHANGED = 'systemvolumechanged', /** * Fired when the visibility of the application has changed * (for example after a HDMI Input change or when the TV is turned * off/on and the cast device is externally powered). * Note that this API has the same effect as the webkitvisibilitychange event raised * by your document, we provided it as {@link framework.CastReceiverContext} * API for convenience and to avoid a dependency on a webkit-prefixed event. */ VISIBILITY_CHANGED = 'visibilitychanged', } /** * Represents the current system state. * @see https://developers.google.com/cast/docs/reference/web_receiver/cast.framework.system#.SystemState */ export enum SystemState { /** * The application has not been requested to start yet. */ NOT_STARTED = 'notstarted', /** * Application is ready to send and receive messages and it is in foreground. */ READY = 'ready', /** * Application is starting. */ STARTING = 'starting', /** * Application is starting but it is in background. */ STARTING_IN_BACKGROUND = 'startinginbackground', /** * Application is stopping. */ STOPPING = 'stopping', /** * Application is stopping but it is in background. */ STOPPING_IN_BACKGROUND = 'stoppinginbackground', } /** * Types of custom messages. * @see https://developers.google.com/cast/docs/reference/web_receiver/cast.framework.system#.MessageType */ export enum MessageType { /** * Messages are free-form strings. The application is responsible for encoding/decoding the information transmitted. */ STRING = 'string', /** * Messages are JSON-encoded. The underlying transport will use a JSON encoded string. */ JSON = 'json', } /** * Represents the current standby state reported by the platform. It may be UNKNOWN * if the cast platform was unable to determine the state yet. * @see https://developers.google.com/cast/docs/reference/web_receiver/cast.framework.system#.StandbyState */ export enum StandbyState { NOT_STANDBY = 'notstandby', STANDBY = 'standby', UNKNOWN = 'unknown', } /** * Represents the disconnect reason. * @see https://developers.google.com/cast/docs/reference/web_receiver/cast.framework.system#.DisconnectReason */ export enum DisconnectReason { /** * There was a protocol error. */ ERROR = 'error', /** * Connection close was actively requested by the sender application (usually * triggered by the user). */ REQUESTED_BY_SENDER = 'requested_by_sender', /** * It is unknown if the sender requested to disconnect gracefully calling close * (most likely it didn't, but the close message could have been lost). This * normally happens when there is a network timeout or if the sender application * crashes or if the sender OS closes the socket. */ UNKNOWN = 'unknown', } /** * Represent where the receiver was launched from. * @see https://developers.google.com/cast/docs/reference/web_receiver/cast.framework.system#.LaunchedFrom */ export enum LaunchedFrom { /** * App was launched by Cast V2 request. */ CAST = 'CAST', /** * App was launched by assistant request (e.g. voice command). */ CLOUD = 'CLOUD', /** * App was launched by DIAL request. */ DIAL = 'DIAL', /** * The launch owner could not be determined. */ UNKNOWN = 'UNKNOWN', } /** * Device capabilities. * @see https://developers.google.com/cast/docs/reference/web_receiver/cast.framework.system#.DeviceCapabilities */ export enum DeviceCapabilities { APP_FOREGROUND = 'app_foreground', /** * Audio Assistant support. For example, Google Home and Google Home Mini. */ AUDIO_ASSISTANT = 'audio_assistant', /** * Bluetooth support. */ BLUETOOTH_SUPPORTED = 'bluetooth_supported', /** * Display output support. For example, Chromecast and Cast TVs have display * support, Chromecast Audio and Google Home have not. */ DISPLAY_SUPPORTED = 'display_supported', /** * Hi-res audio (up to 24-bit / 96KHz) support. */ HI_RES_AUDIO_SUPPORTED = 'hi_res_audio_supported', /** * Flag to know if CBCS scheme (SAMPLE-AES) is supported. */ IS_CBCS_SUPPORTED = 'is_cbcs_supported', /** * Flag to know if the cast device is registered in cast developer console */ IS_DEVICE_REGISTERED = 'is_device_registered', IS_DOLBY_ATMOS_SUPPORTED = 'is_dolby_atmos_supported', /** * Dolby Vision support of the current setup (that is, Chromecast and the TV it is connected to). */ IS_DV_SUPPORTED = 'is_dv_supported', /** * If the device is a virtual device and represents a group target rather than standalone. */ IS_GROUP = 'is_group', /** * HDR video support of the current setup (that is, Chromecast and the TV it is connected to). */ IS_HDR_SUPPORTED = 'is_hdr_supported', REMOTE_CONTROL_OVERLAY_SUPPORTED = 'remote_control_overlay_supported', SLEEP_TIMER_OVERLAY_SUPPORTED = 'sleep_timer_overlay_supported', /** * Touch input support, that is, the devices have a touchable display. For * example, Google Nest Hub and Google Nest Hub Max. */ TOUCH_INPUT_SUPPORTED = 'touch_input_supported', } /** * Represents the current visibility state reported by the platform. * It may be UNKNOWN if the cast platform was unable to determine the state yet. * @see https://developers.google.com/cast/docs/reference/web_receiver/cast.framework.system#.VisibilityState */ export enum VisibilityState { NOT_VISIBLE = 'notvisible', UNKNOWN = 'unknown', VISIBLE = 'visible', } /** * Event dispatched by {@link framework.CastReceiverContext} when the visibility * of the application changes (HDMI input change; TV is turned off). * @see https://developers.google.com/cast/docs/reference/web_receiver/cast.framework.system.VisibilityChangedEvent */ export class VisibilityChangedEvent { constructor(isVisible: boolean); /** * Whether the Cast device is the active input or not. */ isVisible: boolean; } /** * Represents the system volume data. * @see https://developers.google.com/cast/docs/reference/web_receiver/cast.framework.system.SystemVolumeData */ export class SystemVolumeData { constructor(); /** * The level (from 0.0 to 1.0) of the system volume */ level: number; /** * Whether the system volume is muted or not. */ muted: boolean; } /** * Event dispatched by {@link framework.CastReceiverContext} when the system volume changes. * @see https://developers.google.com/cast/docs/reference/web_receiver/cast.framework.system.SystemVolumeChangedEvent */ export class SystemVolumeChangedEvent extends Event { constructor(volume: SystemVolumeData); /** * The system volume data */ data: SystemVolumeData; } /** * Event dispatched by {@link framework.CastReceiverContext} when the TV enters/leaves the standby state. * @see https://developers.google.com/cast/docs/reference/web_receiver/cast.framework.system.StandbyChangedEvent */ export class StandbyChangedEvent extends Event { constructor(isStandby: boolean); /** * Whether the TV is in standby. It will be false if the actual state is unknown. * It is important to note that this event will be raised when the platform * raises a standby change event from unknown to known or vice versa so the * application should always verify the isStandby property. To know if the * actual status is unknown, the application can call the getStandbyState * method. */ isStandby: boolean; } /** * Event dispatched by {@link framework.CastReceiverContext} when the application is shutdown. * @see https://developers.google.com/cast/docs/reference/web_receiver/cast.framework.system.ShutdownEvent */ export class ShutdownEvent extends Event {} /** * Event dispatched by {@link framework.CastReceiverContext} when a sender is disconnected. * @see https://developers.google.com/cast/docs/reference/web_receiver/cast.framework.system.SenderDisconnectedEvent */ export class SenderDisconnectedEvent extends Event { constructor(senderId: string, userAgent: string, reason: DisconnectReason); /** * The ID of the sender connected. */ senderId: string; /** * The user agent of the sender. */ userAgent: string; /** * The reason the sender was disconnected. */ reason: DisconnectReason; } /** * Event dispatched by {@link framework.CastReceiverContext} when a sender is connected. * @see https://developers.google.com/cast/docs/reference/web_receiver/cast.framework.system.SenderConnectedEvent */ export class SenderConnectedEvent extends Event { constructor(senderId: string, userAgent: string); /** * The ID of the sender connected. */ senderId: string; /** * The user agent of the sender. */ userAgent: string; } /** * Represents the data of a connected sender device. * @see https://developers.google.com/cast/docs/reference/web_receiver/cast.framework.system.Sender */ export interface Sender { /** * The sender Id. */ id: string; /** * Indicate the sender supports large messages (>64KB) */ largeMessageSupported?: boolean | undefined; /** * The userAgent of the sender. */ userAgent: string; } /** * Event dispatched by {@link framework.CastReceiverContext} when the system is ready. * @see https://developers.google.com/cast/docs/reference/web_receiver/cast.framework.system.ReadyEvent */ export class ReadyEvent extends Event { constructor(applicationData: ApplicationData); /** * The application data */ data: ApplicationData; } /** * Event dispatched by {@link framework.CastReceiverContext} when the system * needs to update the restriction on maximum video resolution. * @see https://developers.google.com/cast/docs/reference/web_receiver/cast.framework.system.MaxVideoResolutionChangedEvent */ export class MaxVideoResolutionChangedEvent extends Event { constructor(height: number); /** * Maximum video resolution requested by the system. The value of 0 means there is no restriction. */ height: number; } /** * Event dispatched by {@link framework.CastReceiverContext} when the system * starts to create feedback report. * @see https://developers.google.com/cast/docs/reference/web_receiver/cast.framework.system.FeedbackStartedEvent */ export class FeedbackStartedEvent extends Event {} /** * Event dispatched by {@link framework.CastReceiverContext} which contains system information. * @see https://developers.google.com/cast/docs/reference/web_receiver/cast.framework.system.Event */ export class Event { constructor(type: EventType, data?: any); /** * Event Type. */ type: EventType; /** * @deprecated * Event data (deprecated) */ data?: any; } /** * Represents the data of the launched application. * @see https://developers.google.com/cast/docs/reference/web_receiver/cast.framework.system.ApplicationData */ export class ApplicationData { constructor(); /** * The application image that is set in Cast Developer Console. */ iconUrl: string; /** * The application Id. */ id: string; /** * Indicate where the app was launched from. */ launchedFrom: LaunchedFrom; /** * The id of the sender that launched the application. */ launchingSenderId: string; /** * The application name. */ name: string; /** * The namespaces used by the application. */ namespaces: string[]; /** * The session Id. */ sessionId: number; }
the_stack
import { expectSaga } from 'redux-saga-test-plan' import * as matchers from 'redux-saga-test-plan/matchers' import { throwError } from 'redux-saga-test-plan/providers' import request from 'app/utils/request' import actions from 'app/containers/Organizations/actions' import { getOrganizations, addOrganization, editOrganization, deleteOrganization, getOrganizationDetail, getOrganizationsProjects, getOrganizationsMembers, getOrganizationsRole, addRole, getRoleListByMemberId, deleteRole, editRole, relRoleMember, getRelRoleMember, searchMember, inviteMember, deleteOrganizationMember, changeOrganizationMemberRole, getProjectAdmins, getVizVisbility, postVizVisbility } from 'app/containers/Organizations/sagas' import { mockStore } from './fixtures' import { getMockResponse } from 'test/utils/fixtures' describe('Organizations Sagas', () => { const { projects, organization, orgId, organizations, roles, role, member, members } = mockStore describe('getOrganizations Saga', () => { it('should dispatch the organizationsLoaded action if it requests the data successfully', () => { return expectSaga(getOrganizations) .provide([[matchers.call.fn(request), getMockResponse(projects)]]) .put(actions.organizationsLoaded(projects)) .run() }) it('should call the loadOrganizationsFail action if the response errors', () => { const errors = new Error('error') return expectSaga(getOrganizations) .provide([[matchers.call.fn(request), throwError(errors)]]) .put(actions.loadOrganizationsFail()) .run() }) }) describe('addOrganization Saga', () => { const addOrganizationActions = actions.addOrganization(organization, () => void 0) it('should dispatch the organizationAdded action if it requests the data successfully', () => { return expectSaga(addOrganization, addOrganizationActions) .provide([[matchers.call.fn(request), getMockResponse(projects)]]) .put(actions.organizationAdded(projects)) .run() }) it('should call the addOrganizationFail action if the response errors', () => { const errors = new Error('error') return expectSaga(addOrganization, addOrganizationActions) .provide([[matchers.call.fn(request), throwError(errors)]]) .put(actions.addOrganizationFail()) .run() }) }) describe('editOrganization Saga', () => { const editOrganizationActions = actions.editOrganization(organization) it('should dispatch the organizationEdited action if it requests the data successfully', () => { return expectSaga(editOrganization, editOrganizationActions) .provide([[matchers.call.fn(request), getMockResponse(organization)]]) .put(actions.organizationEdited(organization)) .run() }) it('should call the editOrganizationFail action if the response errors', () => { const errors = new Error('error') return expectSaga(editOrganization, editOrganizationActions) .provide([[matchers.call.fn(request), throwError(errors)]]) .put(actions.editOrganizationFail()) .run() }) }) describe('deleteOrganization Saga', () => { const deleteOrganizationActions = actions.deleteOrganization(orgId, () => void 0) it('should dispatch the organizationDeleted action if it requests the data successfully', () => { return expectSaga(deleteOrganization, deleteOrganizationActions) .provide([[matchers.call.fn(request), getMockResponse(organization)]]) .put(actions.organizationDeleted(orgId)) .run() }) it('should call the deleteOrganizationFail action if the response errors', () => { const errors = new Error('error') return expectSaga(deleteOrganization, deleteOrganizationActions) .provide([[matchers.call.fn(request), throwError(errors)]]) .put(actions.deleteOrganizationFail()) .run() }) }) describe('getOrganizationDetail Saga', () => { const loadOrganizationDetailActions = actions.loadOrganizationDetail(orgId) it('should dispatch the organizationDetailLoaded action if it requests the data successfully', () => { return expectSaga(getOrganizationDetail, loadOrganizationDetailActions) .provide([[matchers.call.fn(request), getMockResponse(organization)]]) .put(actions.organizationDetailLoaded(organization)) .run() }) }) describe('getOrganizationsProjects Saga', () => { const [id, keyword, pageNum, pageSize] = [orgId, 'password', 1, 20] const loadOrganizationProjectsActions = actions.loadOrganizationProjects({id, keyword, pageNum, pageSize}) it('should dispatch the organizationsProjectsLoaded action if it requests the data successfully', () => { return expectSaga(getOrganizationsProjects, loadOrganizationProjectsActions) .provide([[matchers.call.fn(request), getMockResponse(organizations)]]) .put(actions.organizationsProjectsLoaded(organizations)) .run() }) it('should call the loadOrganizationsProjectsFail action if the response errors', () => { const errors = new Error('error') return expectSaga(getOrganizationsProjects, loadOrganizationProjectsActions) .provide([[matchers.call.fn(request), throwError(errors)]]) .put(actions.loadOrganizationsProjectsFail()) .run() }) }) describe('getOrganizationsMembers Saga', () => { const loadOrganizationMembersActions = actions.loadOrganizationMembers(orgId) it('should dispatch the organizationsMembersLoaded action if it requests the data successfully', () => { return expectSaga(getOrganizationsMembers, loadOrganizationMembersActions) .provide([[matchers.call.fn(request), getMockResponse(organizations)]]) .put(actions.organizationsMembersLoaded(organizations)) .run() }) it('should call the loadOrganizationsMembersFail action if the response errors', () => { const errors = new Error('error') return expectSaga(getOrganizationsMembers, loadOrganizationMembersActions) .provide([[matchers.call.fn(request), throwError(errors)]]) .put(actions.loadOrganizationsMembersFail()) .run() }) }) describe('getOrganizationsMembers Saga', () => { const loadOrganizationRoleActions = actions.loadOrganizationRole(orgId) it('should dispatch the organizationsRoleLoaded action if it requests the data successfully', () => { return expectSaga(getOrganizationsRole, loadOrganizationRoleActions) .provide([[matchers.call.fn(request), getMockResponse(organizations)]]) .put(actions.organizationsRoleLoaded(organizations)) .run() }) it('should call the loadOrganizationsRoleFail action if the response errors', () => { const errors = new Error('error') return expectSaga(getOrganizationsRole, loadOrganizationRoleActions) .provide([[matchers.call.fn(request), throwError(errors)]]) .put(actions.loadOrganizationsRoleFail()) .run() }) }) describe('addRole Saga', () => { const [name, description, id, resolve] = ['name', 'desc', orgId, () => void 0] const loadOrganizationRoleActions = actions.addRole(name, description, id, resolve) it('should dispatch the roleAdded action if it requests the data successfully', () => { return expectSaga(addRole, loadOrganizationRoleActions) .provide([[matchers.call.fn(request), getMockResponse(roles)]]) .put(actions.roleAdded(roles)) .run() }) it('should call the addRoleFail action if the response errors', () => { const errors = new Error('error') return expectSaga(addRole, loadOrganizationRoleActions) .provide([[matchers.call.fn(request), throwError(errors)]]) .put(actions.addRoleFail()) .run() }) }) describe('getRoleListByMemberId Saga', () => { const [memberId, orgId, resolve] = [1, 1, () => void 0] const loadOrganizationRoleActions = actions.getRoleListByMemberId(memberId, orgId, resolve) it('should dispatch the getRoleListByMemberIdSuccess action if it requests the data successfully', () => { return expectSaga(getRoleListByMemberId, loadOrganizationRoleActions) .provide([[matchers.call.fn(request), getMockResponse(roles)]]) .put(actions.getRoleListByMemberIdSuccess(roles, memberId)) .run() }) it('should call the getRoleListByMemberIdFail action if the response errors', () => { const errors = new Error('error') return expectSaga(getRoleListByMemberId, loadOrganizationRoleActions) .provide([[matchers.call.fn(request), throwError(errors)]]) .put(actions.getRoleListByMemberIdFail(errors, memberId)) .run() }) }) describe('deleteRole Saga', () => { const [id, resolve ] = [1, () => void 0] const loadOrganizationRoleActions = actions.deleteRole(id, resolve) it('should dispatch the roleDeleted action if it requests the data successfully', () => { return expectSaga(deleteRole, loadOrganizationRoleActions) .provide([[matchers.call.fn(request), getMockResponse(role)]]) .put(actions.roleDeleted(role)) .run() }) it('should call the deleteRoleFail action if the response errors', () => { const errors = new Error('error') return expectSaga(deleteRole, loadOrganizationRoleActions) .provide([[matchers.call.fn(request), throwError(errors)]]) .put(actions.deleteRoleFail()) .run() }) }) describe('editRole Saga', () => { const [name, description, id, resolve] = ['name', 'desc', 1, () => void 0] const editRoleActions = actions.editRole(name, description, id, resolve) it('should dispatch the roleEdited action if it requests the data successfully', () => { return expectSaga(editRole, editRoleActions) .provide([[matchers.call.fn(request), getMockResponse(role)]]) .put(actions.roleEdited(role)) .run() }) it('should call the editRoleFail action if the response errors', () => { const errors = new Error('error') return expectSaga(editRole, editRoleActions) .provide([[matchers.call.fn(request), throwError(errors)]]) .put(actions.editRoleFail()) .run() }) }) describe('relRoleMember Saga', () => { const [id, memberIds, resolve] = [ 1, [1], () => void 0] const relRoleMemberActions = actions.relRoleMember(id, memberIds, resolve) it('should dispatch the relRoleMemberSuccess action if it requests the data successfully', () => { return expectSaga(relRoleMember, relRoleMemberActions) .provide([[matchers.call.fn(request), getMockResponse(role)]]) .put(actions.relRoleMemberSuccess()) .run() }) it('should call the relRoleMemberFail action if the response errors', () => { const errors = new Error('error') return expectSaga(relRoleMember, relRoleMemberActions) .provide([[matchers.call.fn(request), throwError(errors)]]) .put(actions.relRoleMemberFail()) .run() }) }) describe('relRoleMember Saga', () => { const [id, resolve] = [ 1, () => void 0] const getRelRoleMemberActions = actions.getRelRoleMember(id, resolve) it('should dispatch the getRelRoleMemberSuccess action if it requests the data successfully', () => { return expectSaga(getRelRoleMember, getRelRoleMemberActions) .provide([[matchers.call.fn(request), getMockResponse(role)]]) .put(actions.getRelRoleMemberSuccess()) .run() }) it('should call the getRelRoleMemberFail action if the response errors', () => { const errors = new Error('error') return expectSaga(getRelRoleMember, getRelRoleMemberActions) .provide([[matchers.call.fn(request), throwError(errors)]]) .put(actions.getRelRoleMemberFail()) .run() }) }) describe('searchMember Saga', () => { const searchMemberActions = actions.searchMember('keywords') it('should dispatch the memberSearched action if it requests the data successfully', () => { return expectSaga(searchMember, searchMemberActions) .provide([[matchers.call.fn(request), getMockResponse(member)]]) .put(actions.memberSearched(member)) .run() }) it('should call the searchMemberFail action if the response errors', () => { const errors = new Error('error') return expectSaga(searchMember, searchMemberActions) .provide([[matchers.call.fn(request), throwError(errors)]]) .put(actions.searchMemberFail()) .run() }) }) describe('inviteMember Saga', () => { const [ orgId, members, needEmail, resolve] = [1, [member], false, () => void 0 ] const inventMemberActions = actions.inviteMember(orgId, members, needEmail, resolve) it('should dispatch the inviteMemberSuccess action if it requests the data successfully', () => { return expectSaga(inviteMember, inventMemberActions) .provide([[matchers.call.fn(request), getMockResponse(member)]]) .put(actions.inviteMemberSuccess(member)) .run() }) it('should call the inviteMemberFail action if the response errors', () => { const errors = new Error('error') return expectSaga(inviteMember, inventMemberActions) .provide([[matchers.call.fn(request), throwError(errors)]]) .put(actions.inviteMemberFail()) .run() }) }) describe('deleteOrganizationMember Saga', () => { const [ relationId, resolve] = [1, () => void 0 ] const deleteOrganizationMemberActions = actions.deleteOrganizationMember(relationId, resolve) it('should dispatch the organizationMemberDeleted action if it requests the data successfully', () => { return expectSaga(deleteOrganizationMember, deleteOrganizationMemberActions) .provide([[matchers.call.fn(request), getMockResponse(relationId)]]) .put(actions.organizationMemberDeleted(relationId)) .run() }) it('should call the deleteOrganizationMemberFail action if the response errors', () => { const errors = new Error('error') return expectSaga(deleteOrganizationMember, deleteOrganizationMemberActions) .provide([[matchers.call.fn(request), throwError(errors)]]) .put(actions.deleteOrganizationMemberFail()) .run() }) }) describe('changeOrganizationMemberRole Saga', () => { const [ relationId, newRole, resolve ] = [1, role, () => void 0 ] const changeOrganizationMemberRoleActions = actions.changeOrganizationMemberRole(relationId, newRole, resolve) it('should dispatch the organizationMemberRoleChanged action if it requests the data successfully', () => { return expectSaga(changeOrganizationMemberRole, changeOrganizationMemberRoleActions) .provide([[matchers.call.fn(request), getMockResponse(member)]]) .put(actions.organizationMemberRoleChanged(relationId, member)) .run() }) it('should call the changeOrganizationMemberRoleFail action if the response errors', () => { const errors = new Error('error') return expectSaga(changeOrganizationMemberRole, changeOrganizationMemberRoleActions) .provide([[matchers.call.fn(request), throwError(errors)]]) .put(actions.changeOrganizationMemberRoleFail()) .run() }) }) describe('getProjectAdmins Saga', () => { const changeOrganizationMemberRoleActions = actions.loadProjectAdmin(orgId) it('should dispatch the projectAdminLoaded action if it requests the data successfully', () => { return expectSaga(getProjectAdmins, changeOrganizationMemberRoleActions) .provide([[matchers.call.fn(request), getMockResponse(members)]]) .put(actions.projectAdminLoaded(members)) .run() }) it('should call the loadProjectAdminFail action if the response errors', () => { const errors = new Error('error') return expectSaga(getProjectAdmins, changeOrganizationMemberRoleActions) .provide([[matchers.call.fn(request), throwError(errors)]]) .put(actions.loadProjectAdminFail()) .run() }) }) describe('getVizVisbility Saga', () => { const [roleId, projectId, resolve] = [ orgId, orgId, () => void 0] const getVizVisbilityActions = actions.getVizVisbility(roleId, projectId, resolve) it('should dispatch the getVizVisbilitySaga action if it requests the data successfully', () => { return expectSaga(getVizVisbility, getVizVisbilityActions) .provide([[matchers.call.fn(request), getMockResponse({})]]) .run() }) }) describe('postVizVisbility Saga', () => { const [id, permission, resolve] = [ orgId, {}, () => void 0] const postVizVisbilityActions = actions.postVizVisbility(id, permission, resolve) it('should dispatch the postVizVisbilityActions action if it requests the data successfully', () => { return expectSaga(getVizVisbility, postVizVisbilityActions) .provide([[matchers.call.fn(request), getMockResponse({})]]) .run() }) }) })
the_stack
import request from 'supertest'; import { resolve } from 'path'; import { readFileSync } from 'fs'; import * as redis from 'redis'; import { promisify } from 'util'; //promisify some node-redis client functionality import app from '../../src/server/server'; import redisMonitors from '../../src/server/redis-monitors/redis-monitors' import { recordKeyspaceHistory } from '../../src/server/redis-monitors/utils'; const testConnections = JSON.parse(readFileSync(resolve(__dirname, '../../src/server/tests-config/tests-config.json')).toString()); enum ENDPOINT_NAMES { KEYSPACES, KEYSPACE_HISTORIES, EVENTS, EVENT_TOTALS }; describe('Route Integration Tests', () => { type RedisModel = { client: redis.RedisClient; host: string; port: number; instanceId: number; recordKeyspaceHistoryFrequency: number; } let redisModels: RedisModel[] = []; //Start test redis servers and corresponding clients beforeAll(async () => { let instanceId = 1; for (let conn of testConnections) { const redisClient = promisifyRedisClient(redis.createClient({ host: conn.host, port: conn.port })); await redisClient.config('SET', 'notify-keyspace-events', 'KEA'); const redisModel = { client: redisClient, host: conn.host, port: conn.port, instanceId: instanceId, recordKeyspaceHistoryFrequency: conn.recordKeyspaceHistoryFrequency }; redisModels.push(redisModel); instanceId += 1; } }); afterAll(async () => { for (const redisModel of redisModels) { try { await redisModel.client.flushall(); } catch (e) { console.log(`Error occured flushing databases: ${e}`); } redisModel.client.quit(); } app.close(); }); it('should return a 404 status code for a request to a bad route', () => { return request(app).get('/obviously/bad/route') .expect(404); }) describe('/api/connections', () => { let response: request.Response; beforeAll(async () => { response = await request(app).get('/api/connections'); }); it('should respond with a 200 status code', () => { expect(response.status).toEqual(200); }); it('should respond with JSON', () => { expect(response.headers['content-type']).toEqual( expect.stringContaining('json') ); }); it('should respond with a body with one instances property containing an array', () => { expect(response.body).toEqual(expect.objectContaining({ instances: expect.any(Array) })); }); it('should provide the correct connection details', () => { response.body.instances.forEach((instanceDetail, idx) => { expect(instanceDetail).toEqual(expect.objectContaining( testConnections[idx] )); expect(instanceDetail.databases).toBeGreaterThanOrEqual(0); }); }); }) describe('/api/v2/keyspaces', () => { //Perform Redis commands to be captured by the route beforeAll(async () => { for (const model of redisModels) { await model.client.set('db0-key1', 'value1'); await model.client.set('db0-key2', 'value2'); await model.client.set('db0-key3', 'value3'); await model.client.set('db0-key4', 'value4'); await model.client.select(2); await model.client.set('db2-key2', 'value2'); await model.client.lpush('db2-key3', 'el2', 'el1'); await model.client.lpush('db2-key4', 'el2', 'el1'); await model.client.set('db2-key5', 'value5'); } }) afterAll(async () => { for (const model of redisModels) { await model.client.flushall(); } //clear out any logs in the monitors for (const monitor of redisMonitors) { for (const keyspace of monitor.keyspaces) { keyspace.eventLog.reset(); keyspace.keyspaceHistories.reset() } } }); //GET request for all keyspaces across all instances describe('GET "/"', () => { let response: request.Response; beforeAll(async () => { response = await request(app).get('/api/v2/keyspaces?pageNum=2&pageSize=3'); }); it('should return a 200 status code', () => { expect(response.status).toEqual(200); }); it('should respond with JSON', () => { expect(response.header['content-type']).toEqual( expect.stringContaining('json') ); }); it('should respond with a data object property of the proper length', () => { expect(response.body.data).toHaveLength(testConnections.length); }); it('each object in the data array should have instanceId and keyspaces properties', () => { response.body.data.forEach((instanceDetail) => { expect(instanceDetail).toEqual(expect.objectContaining({ instanceId: expect.any(Number), keyspaces: expect.any(Array) })); }) }) it('should provide the correct keyspace details', () => { //Technically, response body data also includes list data, but tests in a subsequent block will cover this response.body.data.forEach(instanceDetail => { expect(instanceDetail.keyspaces[0]).toEqual(expect.objectContaining({ keyTotal: 4, pageSize: 3, pageNum: 2, data: expect.arrayContaining([expect.objectContaining({ key: expect.any(String), value: expect.any(String), type: expect.any(String) })]) })); expect(instanceDetail.keyspaces[2]).toEqual(expect.objectContaining({ keyTotal: 4, pageSize: 3, pageNum: 2, data: expect.arrayContaining([expect.objectContaining({ key: expect.any(String), type: expect.any(String) })]) })); }); }); }); //GET request for a specific keyspace describe('GET "/:instanceId/:dbIndex"', () => { let response: request.Response; beforeAll(async () => { response = await request(app).get('/api/v2/keyspaces/1/2?pageSize=3&pageNum=1&refreshScan=1&keynameFilter=key3&keytypeFilter=list'); //Add extra values to test assertions of the refreshScan query parameter await redisModels[0].client.select(1); await redisModels[0].client.set('newkey', 'val'); }); it('should contain the correct properties in the response', () => { expect(response.body).toEqual(expect.objectContaining({ keyTotal: expect.any(Number), pageSize: expect.any(Number), pageNum: expect.any(Number), data: expect.any(Array) })) }); it('should change the keyTotal property to reflect the number of keys in the keyspace based on the filters', () => { expect(response.body.keyTotal).toEqual(1); }); it('should respond with the correct values', () => { expect(response.body).toEqual(expect.objectContaining({ keyTotal: 1, pageSize: 3, pageNum: 1, data: [{ key: 'db2-key3', value: ['el1', 'el2'], type: 'list' }] })); }); it('should not reflect newly added values into Redis if refreshScan is 0', async () => { const response = await request(app).get('/api/v2/keyspaces/1/1?refreshScan=0&keynameFilter=newkey'); expect(response.body).toEqual(expect.objectContaining({ keyTotal: 0, data: [] })); }); it('should reflect newly added values into Redis if refreshScan is 1', async () => { const response = await request(app).get('/api/v2/keyspaces/1/1?refreshScan=1&keynameFilter=newkey'); expect(response.body).toEqual(expect.objectContaining({ keyTotal: 1, data: [{key: 'newkey', value: 'val', type: 'string'}] })); }); }); }); describe('/api/v2/keyspaces/histories', () => { afterAll(() => { for (const monitor of redisMonitors) { for (const keyspace of monitor.keyspaces) { keyspace.eventLog.reset(); keyspace.keyspaceHistories.reset(); } } }); describe('GET /:instanceId/:dbIndex', () => { describe('Without query parameters', () => { let response; beforeAll(async () => { /* Utilizes mock timers to periodically use Redis commands and record them at different time intervals After commands are performed, sends request to grab keyspace history. */ //Clear out any existing keyspace histories for (const monitor of redisMonitors) { for (const keyspace of monitor.keyspaces) { keyspace.keyspaceHistories.reset(); } } let monitor; redisMonitors.forEach((redisMonitor) => { if (redisMonitor.instanceId === redisModels[0].instanceId) { monitor = redisMonitor; } }) const client = redisModels[0].client; await client.select(0); await client.set('key1', 'val'); await client.set('key2', 'val2'); await client.lpush('key3', 'el3', 'el2', 'el1'); await recordKeyspaceHistory(monitor, 0); await client.set('key4', 'val'); await client.set('key5', 'val2'); await client.lpush('key6', 'el3', 'el2', 'el1'); await recordKeyspaceHistory(monitor, 0); await client.del('key6'); await recordKeyspaceHistory(monitor, 0); response = await request(app).get('/api/v2/keyspaces/histories/1/0'); }); afterAll(async () => { for (const monitor of redisMonitors) { for (const keyspace of monitor.keyspaces) { keyspace.keyspaceHistories.reset(); } } for (const model of redisModels) { await model.client.flushall(); } }); it('should respond with a 200 status code and JSON', async () => { expect(response.status).toEqual(200); expect(response.headers['content-type']).toEqual( expect.stringContaining('json') ); }); //Mocks passage of time in order to test the correct historyCount it('should have return the correct number of histories recorded', () => { expect(response.body.historyCount).toEqual(3); expect(response.body.histories).toHaveLength(3); }); it('should return the correct data in the histories property', () => { const histories = response.body.histories; expect(histories[2].keyCount).toEqual(3); expect(histories[1].keyCount).toEqual(6); expect(histories[0].keyCount).toEqual(5); histories.forEach(history => { expect(history.timestamp).toBeLessThanOrEqual(Date.now()); expect(history.timestamp).toBeGreaterThanOrEqual( Date.now() - redisModels[0].recordKeyspaceHistoryFrequency * 4 ); expect(history.memoryUsage).toBeGreaterThan(0); }); }); it('should order the histories from newest to oldest', () => { const histories = response.body.histories; expect(histories[0].timestamp).toBeGreaterThanOrEqual(histories[1].timestamp); expect(histories[1].timestamp).toBeGreaterThanOrEqual(histories[2].timestamp); }); }); describe('Handling query parameters', () => { let response; beforeAll(async () => { //Clear out any existing keyspace histories for (const monitor of redisMonitors) { for (const keyspace of monitor.keyspaces) { keyspace.keyspaceHistories.reset(); } } let monitor; redisMonitors.forEach((redisMonitor) => { if (redisMonitor.instanceId === redisModels[0].instanceId) { monitor = redisMonitor; } }) const client = redisModels[0].client; await client.select(3); await client.set('key1', 'val'); await client.set('key2', 'val'); await recordKeyspaceHistory(monitor, 3); await client.set('beep3', 'val'); await recordKeyspaceHistory(monitor, 3); await client.set('beep4', 'val'); await recordKeyspaceHistory(monitor, 3); response = await request(app).get(`/api/v2/keyspaces/histories/${redisModels[0].instanceId}/3?historiesCount=1&keynameFilter=beep`); }); afterAll(async () => { for (const monitor of redisMonitors) { for (const keyspace of monitor.keyspaces) { keyspace.keyspaceHistories.reset(); } } for (const model of redisModels) { await model.client.flushall(); } }); it('should give the right number of histories based on the historiesCount parameter', () => { expect(response.body.histories).toHaveLength(2); }); it('should return the new historyCount from the redisMonitor process', () => { expect(response.body.historyCount).toEqual(3); }) it('the keycounts should reflect the keynameFilter specified', () => { expect(response.body.histories[0].keyCount).toEqual(2); expect(response.body.histories[1].keyCount).toEqual(1); }); }); }); }) describe('/api/v2/events', () => { describe('GET "/"', () => { let response: request.Response; beforeAll(async () => { //Emit 4 keyspace events for first 3 databases of each instance for (const model of redisModels) { for (let i = 0; i < 3; i++) { await model.client.select(i); await model.client.set('key1', 'wow'); await model.client.set('key3', 'wow3'); await model.client.lpush('key2', 'el1'); await model.client.del('key1'); const res = await model.client.get('key3'); } } response = await request(app).get('/api/v2/events'); }); afterAll(async () => { for (const model of redisModels) { await model.client.flushall(); } for (const monitor of redisMonitors) { for (const keyspace of monitor.keyspaces) { keyspace.eventLog.reset(); } } }); it('should return a 200 status code', () => { expect(response.status).toEqual(200); }) it('should respond with JSON', () => { expect(response.headers['content-type']).toEqual( expect.stringContaining('json') ); }); it('should respond with a data property of the proper length', () => { expect(response.body.data).toHaveLength(2); }); it('should return a data array where each element is an object containing instanceId and keyspaces properties', () => { response.body.data.forEach((instanceDetail) => { expect(instanceDetail).toEqual(expect.objectContaining({ instanceId: expect.any(Number), keyspaces: expect.any(Array) })); }); }); it('should capture and return, in the response body, any events that occured', () => { response.body.data.forEach(instanceDetail => { for (let i = 0; i < 3; i++) { const keyspaceDetail = instanceDetail.keyspaces[i]; expect(keyspaceDetail).toEqual(expect.objectContaining({ eventTotal: 4, pageSize: 5, //default, as this was not specified in the request pageNum: 1, //default, as this was not specified in the request data: expect.any(Array) })); expect(keyspaceDetail.data).toHaveLength(4); } }); }); it('should return events in the correct order, of most to least recent', () => { response.body.data.forEach(instanceDetail => { for (let i = 0; i < 3; i++) { const keyspaceDetail = instanceDetail.keyspaces[i]; expect(keyspaceDetail.data[0].key).toEqual('key1'); expect(keyspaceDetail.data[0].event).toEqual('del'); expect(keyspaceDetail.data[1].key).toEqual('key2'); expect(keyspaceDetail.data[1].event).toEqual('lpush'); expect(keyspaceDetail.data[2].key).toEqual('key3'); expect(keyspaceDetail.data[2].event).toEqual('set'); expect(keyspaceDetail.data[3].key).toEqual('key1'); expect(keyspaceDetail.data[3].event).toEqual('set'); for (let i = 0; i < keyspaceDetail.data.length - 1; i++) { expect(keyspaceDetail.data[i].timestamp).toBeGreaterThanOrEqual( keyspaceDetail.data[i + 1].timestamp); } } }); }); it('should properly filter for keynames', async () => { const res = await request(app).get('/api/v2/events?refreshData=0&keynameFilter=2'); res.body.data.forEach(instanceDetail => { for (let i = 0; i < 3; i++) { const keyspace = instanceDetail.keyspaces[i]; expect(keyspace).toEqual(expect.objectContaining({ eventTotal: 1, data: expect.any(Array) })); expect(keyspace.data).toHaveLength(1); } }); }); it('should properly filter for event types', async () => { const res = await request(app).get('/api/v2/events?refreshData=0&eventTypeFilter=del'); res.body.data.forEach(instanceDetail => { for (let i = 0; i < 3; i++) { const keyspace = instanceDetail.keyspaces[i]; expect(keyspace).toEqual(expect.objectContaining({ eventTotal: 1, data: expect.any(Array) })); expect(keyspace.data).toHaveLength(1); } }); }); it('should grab the proper event subset based on pagination parameters', async () => { const res = await request(app).get('/api/v2/events?refreshData=0&pageSize=3&pageNum=1'); res.body.data.forEach(instanceDetail => { for (let i = 0; i < 3; i++) { const keyspace = instanceDetail.keyspaces[i]; expect(keyspace.data).toHaveLength(3); } }); }); }); describe('GET "/:instanceId/:dbIndex"', () => { let response; beforeAll(async () => { for (const monitor of redisMonitors) { monitor.keyspaces.forEach(keyspace => { keyspace.eventLog.reset(); }) } //Test for instanceId 1, dbIndex 4 const client = redisModels[0].client await client.select(4); await client.set('key1', 'cool'); await client.set('key2', 'neato'); await client.set('key3', 'rick beato'); await client.lpush('key4', 'el2', 'el1'); await client.del('key1'); response = await request(app).get('/api/v2/events/1/4?pageSize=3'); }); afterAll(async () => { for (const model of redisModels) { await model.client.flushall(); } for (const monitor of redisMonitors) { for (const keyspace of monitor.keyspaces) { keyspace.eventLog.reset(); } } }); it('should respond with a 200 status code', () => { expect(response.status).toEqual(200); }); it('should respond with JSON', () => { expect(response.headers['content-type']).toEqual( expect.stringContaining('json') ); }); it('should contain the correct response body shape', () => { expect(response.body).toEqual(expect.objectContaining({ eventTotal: expect.any(Number), pageSize: expect.any(Number), pageNum: expect.any(Number), data: expect.any(Array) })); }); it('should contain the correct metadata values', () => { expect(response.body).toEqual(expect.objectContaining({ eventTotal: 5, pageSize: 3, pageNum: 1 //default since it was not specified in the request })); }); it('should contain the correct data for the three most recent events', () => { expect(response.body.data).toHaveLength(3); expect(response.body.data[0].key).toEqual('key1'); expect(response.body.data[0].event).toEqual('del'); expect(response.body.data[1].key).toEqual('key4'); expect(response.body.data[1].event).toEqual('lpush'); expect(response.body.data[2].key).toEqual('key3'); expect(response.body.data[2].event).toEqual('set'); }); it('should respond with the correct page', async () => { const response = await request(app).get('/api/v2/events/1/4?pageSize=2&pageNum=2'); expect(response.body.data).toHaveLength(2); expect(response.body.data[0].event).toEqual('set'); expect(response.body.data[1].event).toEqual('set'); }); it('should filter the response properly', async () => { const response = await request(app).get('/api/v2/events/1/4?pageSize=3&pageNum=1&keynameFilter=1&eventTypeFilter=set'); expect(response.body).toEqual(expect.objectContaining({ eventTotal: 1, pageNum: 1, pageSize: 3, data: expect.any(Array) })); expect(response.body.data).toHaveLength(1); expect(response.body.data[0]).toEqual(expect.objectContaining({ key: 'key1', event: 'set' })); }); it('should handle event log data refreshing properly', async () => { await redisModels[0].client.select(4); await redisModels[0].client.set('newkey', 'doge'); let response = await request(app).get('/api/v2/events/1/4?refreshData=0&keynameFilter=newk') expect(response.body).toEqual(expect.objectContaining({ eventTotal: 0, data: [] })); response = await request(app).get('/api/v2/events/1/4?refreshData=1&keynameFilter=newk') expect(response.body).toEqual(expect.objectContaining({ eventTotal: 1, data: expect.arrayContaining([expect.objectContaining({ key: 'newkey', event: 'set' })]) })); }); }); }); describe('/api/v2/events/totals', () => { describe('GET "/:instanceId/:dbIndex"', () => { it('should return a 400 status code if no timeInterval or eventTotal parameter is specified', async () => { const client = redisModels[0].client; await client.select(0); await client.set('oops', 'i did it again') const response = await request(app).get(`/api/v2/events/totals/${redisModels[0].instanceId}/0`); expect(response.status).toEqual(400); }) describe('with timeInterval parameter', () => { let response; beforeAll(async () => { const timeInterval = 200; const client = redisModels[0].client; await client.select(4); //Emit some events immediately to be captured and manually pass time to allow events to occur await client.set('key1', 'val'); await client.lpush('key2', 'el2', 'el1'); await client.del('key1'); await delay(timeInterval); //emit a second set events await client.set('key1', 'newval'); await client.rpush('key3', 'el1', 'el2'); await delay(timeInterval); //Emit a third set of events await client.del('key1'); await client.del('key3'); await client.set('key4', 'hellowurld'); await client.set('wow', 'money'); await delay(timeInterval); //Send a response to capture events response = await request(app).get(`/api/v2/events/totals/${redisModels[0].instanceId}/4?timeInterval=${timeInterval * 1.1}`); }); afterAll(async () => { await redisModels[0].client.flushall(); for (const monitor of redisMonitors) { monitor.keyspaces[4].eventLog.reset(); } }); it('should respond with a 200 status code and JSON', () => { expect(response.status).toEqual(200); expect(response.headers['content-type']).toEqual(expect.stringContaining('json')); }); it('should respond with the correct eventTotal', () => { expect(response.body.eventTotal).toEqual(9); }); it('should respond with the correct number of eventTotals intervals', () => { expect(response.body.eventTotals).toHaveLength(3); }) it('should order each eventTotal from most recent to least recent', () => { const totals = response.body.eventTotals; for (let i = 0; i < 2; i++) { expect(totals[i].start_time).toBeGreaterThanOrEqual(totals[i + 1].start_time); expect(totals[i].end_time).toBeGreaterThanOrEqual(totals[i + 1].end_time); } }) it('should capture the correct eventCount for each interval', () => { const totals = response.body.eventTotals; expect(totals[0].eventCount).toEqual(4); expect(totals[1].eventCount).toEqual(2); expect(totals[2].eventCount).toEqual(3); }); }); describe('with eventTotal parameter', () => { let response; beforeAll(async () => { const client = redisModels[0].client; await client.select(2); for (let i = 0; i < 320; i++) { await client.set(`key-${i}`, `val-${i}`); } response = await request(app).get(`/api/v2/events/totals/${redisModels[0].instanceId}/2?eventTotal=113`); }); afterAll(async () => { await redisModels[0].client.flushall(); for (const monitor of redisMonitors) { monitor.keyspaces[2].eventLog.reset(); } }) it('should provide the correct eventTotal metadata', () => { expect(response.body.eventTotal).toEqual(320); }); it('should provide a single element in the eventTotals array', () => { expect(response.body.eventTotals).toHaveLength(1); }); it('should provide the correct eventCount in the eventTotals array element', () => { expect(response.body.eventTotals[0].eventCount).toEqual(320 - 113); }); }); describe('handling filtering query parameters', () => { beforeAll(async () => { const client = redisModels[0].client; await client.select(6); for (let i = 0; i < 30; i++) { await client.set(`wow1-${i}`, 'coolbean'); await client.lpush(`wow-${i}`, 'el2', 'el1') await client.lpush(`erm-${i + 30}`, 'el2', 'el1'); await client.del(`wow1-${i}`); } }); afterAll(async () => { await redisModels[0].client.flushall(); for (const monitor of redisMonitors) { monitor.keyspaces[6].eventLog.reset(); } }) it('should not affect the eventTotal metadata', async () => { const response = await request(app).get(`/api/v2/events/totals/${redisModels[0].instanceId}/6?timeInterval=10000&eventTypes=set`); expect(response.body.eventTotal).toEqual(120); }); it('should filter for event types properly', async () => { const response = await request(app).get(`/api/v2/events/totals/${redisModels[0].instanceId}/6?eventTotal=0&eventTypes=lpush,del`); expect(response.body.eventTotals[0].eventCount).toEqual(90); }); it('should filter for keynameFilters properly', async () => { const response = await request(app).get(`/api/v2/events/totals/${redisModels[0].instanceId}/6?eventTotal=4&keynameFilter=erm`); expect(response.body.eventTotals[0].eventCount).toEqual(29); }); it('should filter for both event types and keynames simultaneously, properly', async () => { const response = await request(app).get(`/api/v2/events/totals/${redisModels[0].instanceId}/6?timeInterval=10000&keynameFilter=wow&eventTypes=lpush,del`); expect(response.body.eventTotals[0].eventCount).toEqual(60); }); }); }); }); }); const promisifyRedisClient = (redisClient: redis.RedisClient): redis.RedisClient => { redisClient.config = promisify(redisClient.config).bind(redisClient); redisClient.select = promisify(redisClient.select).bind(redisClient); redisClient.flushdb = promisify(redisClient.flushdb).bind(redisClient); redisClient.flushall = promisify(redisClient.flushall).bind(redisClient); redisClient.set = promisify(redisClient.set).bind(redisClient); redisClient.get = promisify(redisClient.get).bind(redisClient); redisClient.del = promisify(redisClient.del).bind(redisClient); redisClient.lpush = promisify(redisClient.lpush).bind(redisClient); redisClient.rpush = promisify(redisClient.rpush).bind(redisClient); redisClient.lrange = promisify(redisClient.lrange).bind(redisClient); return redisClient; } const delay = (ms) => { return new Promise(resolve => { setTimeout(resolve, ms) }) }
the_stack
import { Tween24 } from "./Tween24"; import { Ease24 } from "./index"; import { Sort24 } from "./index"; import { Event24 } from "./Event24"; import { Text24 } from "./utils/Text24"; import { HTMLUtil } from "./utils/HTMLUtil"; import { ButtonTween24 } from "./ButtonTween24"; export class Button24 { private static _DEFAULT_IN_EVENT :string = Event24.MOUSE_ENTER; private static _DEFAULT_OUT_EVENT:string = Event24.MOUSE_LEAVE; private _targetQuery :string; private _inEventType :string; private _outEventType :string; private _templates :ButtonTween24[]; private _inTweens :Tween24[]; private _outTweens :Tween24[]; private _stopInTweens :Tween24[]; private _stopOutTweens :Tween24[]; private _inEvent :Event24|null; private _outEvent :Event24|null; private _stopInEvent :Event24|null; private _stopOutEvent :Event24|null; private _onResizeBinded:any; constructor(targetQuery:string, inEventType:string, outEventType:string, templates:ButtonTween24[]) { this._targetQuery = targetQuery; this._templates = templates; this._inEventType = inEventType; this._outEventType = outEventType; this._inTweens = []; this._outTweens = []; this._stopInTweens = []; this._stopOutTweens = []; this._inEvent = null; this._outEvent = null; this._stopInEvent = null; this._stopOutEvent = null; this._onResizeBinded = this._onResize.bind(this); let needResizse:boolean = false; for (const template of templates) { if (template.inTween ) this._inTweens .push(template.inTween); if (template.outTween ) this._outTweens .push(template.outTween); if (template.stopInTween ) this._stopInTweens .push(template.stopInTween); if (template.stopOutTween) this._stopOutTweens.push(template.stopOutTween); needResizse ||= template.needResize; } if (needResizse) this.resizeAndReset(); this._addEvent(); } private _addEvent() { if (this._inTweens .length) this._inEvent = Event24.add(this._targetQuery, this._inEventType , Tween24.parallel(...this._inTweens)); if (this._outTweens.length) this._outEvent = Event24.add(this._targetQuery, this._outEventType, Tween24.parallel(...this._outTweens)); if (this._stopInTweens .length) this._stopInEvent = Event24.add(this._targetQuery, this._inEventType , Tween24.parallel(...this._stopInTweens )).addStopEvent(this._outEventType); if (this._stopOutTweens.length) this._stopOutEvent = Event24.add(this._targetQuery, this._outEventType, Tween24.parallel(...this._stopOutTweens)).addStopEvent(this._inEventType); } private _onResize(event:Event) { this.reset(); } private _onResizeTemplate() { for (const template of this._templates) { template.onResize(); } } reset() { Tween24.serial( Tween24.func(Event24.removeAllByTarget, this._targetQuery), Tween24.func(this._onResizeTemplate.bind(this)), Tween24.wait(0.01), Tween24.func(this._addEvent.bind(this)) ).play(); } resizeAndReset():Button24 { window.addEventListener("resize", this._onResizeBinded, false); return this; } removeResize():Button24 { window.removeEventListener("resize", this._onResizeBinded, false); return this; } willChange(use:boolean = true):Button24 { this._inEvent ?.willChange(use); this._outEvent ?.willChange(use); this._stopInEvent ?.willChange(use); this._stopOutEvent?.willChange(use); return this; } // ------------------------------------------ // // Static method // // ------------------------------------------ static set(targetQuery:string, ...templates:ButtonTween24[]):Button24 { const btn:Button24 = new Button24(targetQuery, Button24._DEFAULT_IN_EVENT, Button24._DEFAULT_OUT_EVENT, templates); return btn; } static _ColorChange(targetQuery:string, color:string):ButtonTween24 { const template:ButtonTween24 = new ButtonTween24(); const targets:HTMLElement[] = HTMLUtil.querySelectorAll(targetQuery); template.setStopInTween (Tween24.tween(targetQuery, 0.3, Ease24._4_QuartOut).color(color)); template.setStopOutTween( Tween24.serial( Tween24.prop(targetQuery).color(color), Tween24.tween(targetQuery, 0.6, Ease24._4_QuartOut).color(window.getComputedStyle(targets[0]).color) ) ); return template; } static _TextRollUp(targetQuery:string, velocity:number = 40, sort:Function = Sort24._Normal, textSpacing:number = 0):ButtonTween24 { const template:ButtonTween24 = new ButtonTween24(); const targets:HTMLElement[] = HTMLUtil.querySelectorAll(targetQuery); const createText:Function = function() { for (const target of targets) { const text:Text24 = Text24.getInstance(target) || new Text24(target, target.textContent?.trim() || "", true, true); text.spacing = textSpacing; } } createText(); template.setInTween( Tween24.serial( Tween24.propText(targetQuery).y("100%"), Tween24.lagTotalSort(0.2, sort, Tween24.tweenTextVelocity(targetQuery, velocity, Ease24._6_ExpoOut).y(0) ) ) ); template.setResizeFunc(function():void { Text24.removeByTarget(targetQuery); createText(); }); template.needResize = true; return template; } static _TextRollUpDown(targetQuery:string, sort:Function = Sort24._Normal, textSpacing:number = 0):ButtonTween24 { const template:ButtonTween24 = new ButtonTween24(); const targets:HTMLElement[] = HTMLUtil.querySelectorAll(targetQuery); const createText:Function = function() { for (const target of targets) { const text:Text24 = Text24.getInstance(target) || new Text24(target, target.textContent?.trim() || "", true, true); text.spacing = textSpacing; } } createText(); template.setStopInTween( Tween24.serial( Tween24.propText(targetQuery).y("100%"), Tween24.lagTotalSort(0.2, sort, Tween24.tweenTextVelocity(targetQuery, 40, Ease24._6_ExpoOut).y(0) ) ) ); template.setStopOutTween( Tween24.serial( Tween24.propText(targetQuery).y(0), Tween24.lagTotalSort(0.2, sort, Tween24.tweenTextVelocity(targetQuery, 40, Ease24._6_ExpoOut).y("100%") ), Tween24.propText(targetQuery).y(0) ) ); template.setResizeFunc(function():void { Text24.removeByTarget(targetQuery); createText(); }); template.needResize = true; return template; } static _FadeInOutArrow(targetQuery:string, startX:number|string = "-80%"):ButtonTween24 { const template:ButtonTween24 = new ButtonTween24(); template.setStopInTween( Tween24.serial( Tween24.prop(targetQuery).x(startX).opacity(0), Tween24.tween(targetQuery, 0.4, Ease24._4_QuartOut).x(0).opacity(1) ) ); template.setStopOutTween( Tween24.parallel( Tween24.tween(targetQuery, 0.12, Ease24._Linear).opacity(0), Tween24.tween(targetQuery, 0.6, Ease24._4_QuartOut).x(startX) ) ); Tween24.prop(targetQuery).x(startX).opacity(0).play(); template.needResize = true; return template; } /** * ボタンのテキストを、1文字ずつロールアップさせるアニメーションを設定します。 * @static * @param {string} buttonQuery ボタンの対象になるクエリ * @param {string} textQuery アニメーションさせるテキストを持っている対象のクエリ * @param {number} velocity ロールアップの速度(1秒間の移動ピクセル) * @param {number} overTotalLagTime マウスオーバー時のトータル時差(秒) * @param {number} outTotalLagTime マウスアウト時のトータル時差(秒) * @param {Function} easing ロールアップのイージング * @param {Function} sort テキストの再生順をソートする関数 * @param {number} textSpacing 文字間の調整(px) * @param {boolean} [resizeAndReset=false] ウィンドウのリサイズ時に、 * @memberof Button24 */ static setRollUpTextCharacterAnimation(buttonQuery:string, textQuery:string, velocity:number, overTotalLagTime:number, outTotalLagTime:number, easing:Function|null, sort:Function, textSpacing:number, resizeAndReset:boolean = false) { const createButton:Function = function() { const targets:HTMLElement[] = HTMLUtil.querySelectorAll(textQuery); let text:Text24; for (const target of targets) { text = new Text24(target, target.textContent?.trim() || "", true, true); text.spacing = textSpacing; } const setEvent:Function = function() { Event24.add(buttonQuery, Event24.MOUSE_ENTER, Tween24.lagTotalSort(overTotalLagTime, sort, Tween24.tweenTextVelocity(textQuery, velocity, easing).y("-100%") ) ).addStopEvent(Event24.MOUSE_LEAVE); Event24.add(buttonQuery, Event24.MOUSE_LEAVE, Tween24.lagTotalSort(outTotalLagTime, sort, Tween24.tweenTextVelocity(textQuery, velocity, easing).y(0) ) ).addStopEvent(Event24.MOUSE_ENTER); } setEvent(); } if (resizeAndReset) { Event24.add(window, "resize", Tween24.serial( Tween24.func(Event24.removeAllByTarget, buttonQuery), Tween24.func(Text24.removeByTarget, textQuery), Tween24.wait(0.01), Tween24.func(createButton) ) ); } createButton(); } }
the_stack
import { AxiosError, AxiosRequestConfig } from 'axios'; import type ReactLib from 'react'; import { type SyntheticEvent } from 'react'; import urlJoin from 'url-join'; import { Context, Spec } from './document-actions'; const isAxiosError = (error?: Error | AxiosError): error is AxiosError => Boolean(error) && Object.prototype.hasOwnProperty.call(error, 'isAxiosError'); interface Props { axios: (config: AxiosRequestConfig) => Promise<{ statusText: string; data: { configuration: { portal_gui_host: string; portal_is_legacy: boolean; }; }; status: number; }>; insomniaComponents: any; trackSegmentEvent: Context['__private']['analytics']['trackSegmentEvent']; store: Context['store']; spec: Spec; } interface PersistedState { kongPortalRbacToken: string; kongPortalApiUrl: string; kongPortalUrl: string; kongPortalUserWorkspace: string; } interface State extends PersistedState { workspaceId: string; isLoading: boolean; connectionError: AxiosError | Error | null; showUploadError: boolean; forceSpecOverwrite: boolean; kongSpecFileName: string; kongPortalLegacyMode: boolean; kongPortalDeployView: 'edit' | 'upload' | 'error' | 'overwrite' | 'success'; kongPortalDeployError: string; } const defaultPersistedState: PersistedState = { kongPortalRbacToken: '', kongPortalApiUrl: '', kongPortalUrl: '', kongPortalUserWorkspace: '', }; export function getDeployToPortalComponent(options: { React: typeof ReactLib; }): { DeployToPortal: ReactLib.ComponentType<Props> } { const { React } = options; class DeployToPortal extends React.Component<Props, State> { state: State = { ...defaultPersistedState, workspaceId: '', kongSpecFileName: '', isLoading: false, connectionError: null, showUploadError: false, kongPortalLegacyMode: false, kongPortalDeployView: 'edit', forceSpecOverwrite: false, kongPortalDeployError: '', }; _handleLoadingToggle = (status: boolean) => { this.setState({ isLoading: status }); }; _hasConnectInfo = () => { return ( this.state.kongPortalApiUrl.length > 0 && this.state.kongPortalUserWorkspace.length > 0 ); }; _handleEditKongConnection = () => { this.setState({ kongPortalDeployView: 'edit' }); }; _handleReturnToUpload = () => { this.setState({ kongPortalDeployView: 'upload' }); }; _handleUploadSpec = async ( overwrite: boolean, event?: SyntheticEvent<HTMLFormElement> ) => { if (event) { event.preventDefault(); } const { spec, axios, trackSegmentEvent } = this.props; const { kongSpecFileName, kongPortalUserWorkspace, kongPortalApiUrl, kongPortalRbacToken, kongPortalLegacyMode, } = this.state; let newSpec; let method: AxiosRequestConfig['method'] = 'post'; let urlFilePath = urlJoin( kongPortalApiUrl, kongPortalUserWorkspace + '/files' ); let headers = {}; // Check legacy mode if (kongPortalLegacyMode) { newSpec = { type: 'spec', name: kongSpecFileName, contents: spec.rawContents, }; } else { newSpec = { path: urlJoin('specs/', kongSpecFileName), contents: spec.rawContents, }; } // Check RBAC if (kongPortalRbacToken.length > 0) { headers = { 'Content-Type': 'application/json', 'Kong-Admin-Token': kongPortalRbacToken, }; } // Check overwrite intent if (overwrite) { method = 'patch'; urlFilePath = urlJoin( kongPortalApiUrl, kongPortalUserWorkspace, '/files/specs/', kongSpecFileName ); } try { const response = await axios({ method, url: urlFilePath, data: newSpec, headers, }); if (response.statusText === 'Created' || response.statusText === 'OK') { this.setState({ kongPortalDeployView: 'success' }); const action = overwrite ? 'replace_portal' : 'create_portal'; trackSegmentEvent('Kong Synced', { type: 'deploy', action }); } } catch (err) { if (err.response && err.response.status === 409) { this.setState({ kongPortalDeployView: 'overwrite' }); const action = overwrite ? 'replace_portal' : 'create_portal'; trackSegmentEvent('Kong Synced', { type: 'deploy', action, error: err.response.status + ': ' + err.response.statusText, }); } else { console.log('Failed to upload to dev portal', err.response); if (err.response && err.response.data && err.response.data.message) { this.setState({ kongPortalDeployError: err.response.data.message }); } this.setState({ kongPortalDeployView: 'error' }); } } }; _handleConnectKong = async (event: SyntheticEvent<HTMLFormElement>) => { event.preventDefault(); const { axios, trackSegmentEvent } = this.props; const { kongPortalUserWorkspace, kongPortalApiUrl, kongPortalRbacToken } = this.state; // Show loading animation this._handleLoadingToggle(true); try { // Check connection const apiUrl = urlJoin( kongPortalApiUrl, kongPortalUserWorkspace + '/kong' ); const response = await axios({ method: 'get', url: apiUrl, headers: { 'Kong-Admin-Token': kongPortalRbacToken, }, }); if (response.status === 200 || response.status === 201) { trackSegmentEvent('Kong Connected', { type: 'token', action: 'portal_deploy', }); // Set legacy mode for post upload formatting, suppress loader, set monitor portal URL, move to upload view const guiHost = response.data.configuration.portal_gui_host; this.setState({ kongPortalLegacyMode: response.data.configuration.portal_is_legacy, connectionError: null, kongPortalDeployView: 'upload', kongPortalUrl: urlJoin(`http://${guiHost}`, kongPortalUserWorkspace), }); this._handleLoadingToggle(false); } } catch (error: unknown) { if (error instanceof Error) { trackSegmentEvent('Kong Connected', { type: 'token', action: 'portal_deploy', error: error.message, }); console.log('Connection error', error); this._handleLoadingToggle(false); this.setState({ connectionError: error }); } } }; componentDidMount = async () => { const newState = { ...defaultPersistedState }; for (const key in newState) { const value = await this.props.store.getItem(key); newState[key as keyof PersistedState] = String(value); } this.setState(newState); }; componentDidUpdate = async () => { for (const key in defaultPersistedState) { await this.props.store.setItem( key, this.state[key as keyof PersistedState] ); } }; _handleKongPortalApiUrlChange = async (event: SyntheticEvent<HTMLInputElement>) => { this.setState({ kongPortalApiUrl: event.currentTarget.value }); }; _handleRBACKTokenChange = async (event: SyntheticEvent<HTMLInputElement>) => { this.setState({ kongPortalRbacToken: event.currentTarget.value }); }; _handleKongPortalUserWorkspaceChange = async ( event: SyntheticEvent<HTMLInputElement> ) => { this.setState({ kongPortalUserWorkspace: event.currentTarget.value }); }; render() { const { insomniaComponents: { Button }, } = this.props; const { kongPortalApiUrl, kongSpecFileName, kongPortalUserWorkspace, kongPortalDeployView, connectionError, kongPortalRbacToken, isLoading, showUploadError, kongPortalLegacyMode, kongPortalUrl, kongPortalDeployError, } = this.state; // Check input > enable connection & upload const connectIsEnabled = kongPortalApiUrl.length > 0 && kongPortalUserWorkspace.length > 0; const uploadIsEnabled = kongSpecFileName.length > 0; // Check view if (kongPortalDeployView === 'edit') { let connectionErrorElement: JSX.Element | null = null; if (connectionError) { const stack = connectionError.stack; let messageToShow = stack; if (isAxiosError(connectionError) && connectionError.response) { const response = connectionError.response; messageToShow = `${response.status} ${response.statusText}`; const responseMessage = response.data?.message; if (responseMessage) { messageToShow += `: ${responseMessage}`; } } connectionErrorElement = ( <p className="notice error margin-top-sm text-left"> Error. Please check your settings and try again. <details className="margin-top-sm"> <summary>More details</summary> <pre className="pad-top-sm selectable"> <code className="wide overflow-auto">{messageToShow}</code> </pre> </details> </p> ); } return ( // Kong Connection Details <form className="pad" onSubmit={this._handleConnectKong}> {connectionErrorElement} <div className="form-control form-control--outlined"> <label> Kong API URL <input type="url" placeholder="Eg. https://kong-api.domain.com" defaultValue={kongPortalApiUrl} onChange={this._handleKongPortalApiUrlChange} /> </label> <br /> <label> Kong Workspace Name <input type="text" placeholder="Eg. my-workspace-name" defaultValue={kongPortalUserWorkspace} onChange={this._handleKongPortalUserWorkspaceChange} /> </label> <br /> <label> Kong RBAC Token <input type="password" placeholder="Optional" defaultValue={kongPortalRbacToken} onChange={this._handleRBACKTokenChange} /> </label> </div> <div className="row margin-top"> <Button bg="surprise" type="submit" disabled={!connectIsEnabled} style={{ marginRight: 'var(--padding-sm)', }} > {isLoading ? 'Connecting...' : 'Connect to Kong'} </Button> <Button data-close-modal="true" type="button"> Cancel </Button> </div> </form> ); } else if (kongPortalDeployView === 'upload') { return ( // File Name > Upload <form className="pad" onSubmit={this._handleUploadSpec.bind(this, false)} > <p className="pad margin-top-sm" style={{ backgroundColor: '#EDF8F1', color: '#2A6F47', borderColor: '#B5E3C8', border: '1px solid green', textAlign: 'left', }} > <i className="fa fa-check" /> Connected to Kong <a className="success pull-right faint underline pointer" onClick={this._handleEditKongConnection} > Edit Connection </a> </p> {showUploadError && ( <p className="notice error margin-top-sm"> The file already exists on this workspace. </p> )} <div className="form-control form-control--outlined margin-top"> <label> File Name <input type="text" placeholder="Eg. unique-file-name.yaml" defaultValue="" onChange={evt => { this.setState({ kongSpecFileName: evt.target.value }); }} /> </label> </div> <div className="row margin-top"> <Button bg="surprise" type="submit" style={{ marginRight: 'var(--padding-sm)', }} disabled={!uploadIsEnabled} > {isLoading ? 'Uploading...' : 'Upload To Dev Portal'} </Button> <Button onClick={this._handleEditKongConnection} type="button"> Go Back </Button> </div> </form> ); } else if (kongPortalDeployView === 'success') { return ( <div className="pad"> <p className="no-pad no-margin-top"> The Document is now available on {kongPortalLegacyMode ? ( 'Dev Portal' ) : ( <a href={kongPortalUrl}>Dev Portal</a> )} </p> <div> <Button data-close-modal="true">Close</Button> </div> </div> ); } else if (kongPortalDeployView === 'error') { return ( // File Name > Upload <div className="pad"> <p className="notice error no-margin-top"> Error uploading spec <strong>{kongSpecFileName}</strong> to the{' '} <strong>{kongPortalUserWorkspace}</strong> workspace.{' '} <strong>{kongPortalDeployError}</strong> </p> <div className="row margin-top"> <Button bg="surprise" onClick={() => this._handleUploadSpec(false)} style={{ marginRight: 'var(--padding-sm)', }} disabled={!uploadIsEnabled} > Try Again </Button> <button onClick={this._handleReturnToUpload}>Go Back</button> </div> </div> ); } else if (kongPortalDeployView === 'overwrite') { return ( // File Name > Upload <div className="pad"> <p className="notice error no-margin-top"> File already exists in workspace. </p> <p className="no-pad no-margin-top"> Uploading spec <strong>{kongSpecFileName}</strong> to the{' '} <strong>{kongPortalUserWorkspace}</strong> workspace will overwrite the existing spec. </p> <div className="row margin-top"> <Button bg="surprise" onClick={() => this._handleUploadSpec(true)} style={{ marginRight: 'var(--padding-sm)', }} disabled={!uploadIsEnabled} > Overwrite Existing Spec </Button> <Button onClick={this._handleReturnToUpload}>Go Back</Button> </div> </div> ); } else { return <p>Nothing to see here...</p>; } } } return { DeployToPortal }; }
the_stack
// IMPORTANT // This file was generated by https://github.com/Maxim-Mazurok/google-api-typings-generator. Please do not edit it manually. // In case of any problems please post issue to https://github.com/Maxim-Mazurok/google-api-typings-generator // Generated from: https://photoslibrary.googleapis.com/\$discovery/rest?version=v1 /// <reference types="gapi.client" /> declare namespace gapi.client { /** Load Photos Library API v1 */ function load(name: "photoslibrary", version: "v1"): PromiseLike<void>; function load(name: "photoslibrary", version: "v1", callback: () => any): void; namespace photoslibrary { interface AddEnrichmentToAlbumRequest { /** The position in the album where the enrichment is to be inserted. */ albumPosition?: AlbumPosition; /** The enrichment to be added. */ newEnrichmentItem?: NewEnrichmentItem; } interface AddEnrichmentToAlbumResponse { /** Output only. Enrichment which was added. */ enrichmentItem?: EnrichmentItem; } interface Album { /** * [Output only] A URL to the cover photo's bytes. This shouldn't be used as * is. Parameters should be appended to this URL before use. See the * [developer * documentation](https://developers.google.com/photos/library/guides/access-media-items#base-urls) * for a complete list of supported parameters. For example, * `'=w2048-h1024'` sets the dimensions of the cover photo to have a width of * 2048 px and height of 1024 px. */ coverPhotoBaseUrl?: string; /** * [Output only] Identifier for the media item associated with the cover * photo. */ coverPhotoMediaItemId?: string; /** * [Ouput only] Identifier for the album. This is a persistent identifier that * can be used between sessions to identify this album. */ id?: string; /** * [Output only] True if you can create media items in this album. * This field is based on the scopes granted and permissions of the album. If * the scopes are changed or permissions of the album are changed, this field * is updated. */ isWriteable?: boolean; /** [Output only] The number of media items in the album. */ mediaItemsCount?: string; /** * [Output only] Google Photos URL for the album. The user needs to be signed * in to their Google Photos account to access this link. */ productUrl?: string; /** * [Output only] Information related to shared albums. * This field is only populated if the album is a shared album, the * developer created the album and the user has granted the * `photoslibrary.sharing` scope. */ shareInfo?: ShareInfo; /** * Name of the album displayed to the user in their Google Photos account. * This string shouldn't be more than 500 characters. */ title?: string; } interface AlbumPosition { /** Type of position, for a media or enrichment item. */ position?: string; /** * The enrichment item to which the position is relative to. * Only used when position type is AFTER_ENRICHMENT_ITEM. */ relativeEnrichmentItemId?: string; /** * The media item to which the position is relative to. * Only used when position type is AFTER_MEDIA_ITEM. */ relativeMediaItemId?: string; } interface BatchAddMediaItemsToAlbumRequest { /** * Identifiers of the MediaItems to be * added. * The maximum number of media items that can be added in one call is 50. */ mediaItemIds?: string[]; } // tslint:disable-next-line:no-empty-interface interface BatchAddMediaItemsToAlbumResponse { } interface BatchCreateMediaItemsRequest { /** * Identifier of the album where the media items are added. The media items * are also added to the user's library. This is an optional field. */ albumId?: string; /** * Position in the album where the media items are added. If not * specified, the media items are added to the end of the album (as per * the default value, that is, `LAST_IN_ALBUM`). The request fails if this * field is set and the `albumId` is not specified. The request will also fail * if you set the field and are not the owner of the shared album. */ albumPosition?: AlbumPosition; /** List of media items to be created. */ newMediaItems?: NewMediaItem[]; } interface BatchCreateMediaItemsResponse { /** Output only. List of media items created. */ newMediaItemResults?: NewMediaItemResult[]; } interface BatchGetMediaItemsResponse { /** * Output only. List of media items retrieved. * Note that even if the call to BatchGetMediaItems succeeds, there may have * been failures for some media items in the batch. These failures are * indicated in each * MediaItemResult.status. */ mediaItemResults?: MediaItemResult[]; } interface BatchRemoveMediaItemsFromAlbumRequest { /** * Identifiers of the MediaItems to be * removed. * * Must not contain repeated identifiers and cannot be empty. The maximum * number of media items that can be removed in one call is 50. */ mediaItemIds?: string[]; } // tslint:disable-next-line:no-empty-interface interface BatchRemoveMediaItemsFromAlbumResponse { } interface ContentFilter { /** * The set of categories which are not to be included in the media item search * results. The items in the set are ORed. There's a maximum of 10 * `excludedContentCategories` per request. */ excludedContentCategories?: string[]; /** * The set of categories to be included in the media item search results. * The items in the set are ORed. There's a maximum of 10 * `includedContentCategories` per request. */ includedContentCategories?: string[]; } interface ContributorInfo { /** Display name of the contributor. */ displayName?: string; /** URL to the profile picture of the contributor. */ profilePictureBaseUrl?: string; } interface CreateAlbumRequest { /** The album to be created. */ album?: Album; } interface Date { /** Day of month. Must be from 1 to 31 and valid for the year and month, or 0 if specifying a year/month where the day isn't significant. */ day?: number; /** * Month of year. Must be from 1 to 12, or 0 if specifying a year without a * month and day. */ month?: number; /** * Year of date. Must be from 1 to 9999, or 0 if specifying a date without * a year. */ year?: number; } interface DateFilter { /** * List of dates that match the media items' creation date. A maximum of * 5 dates can be included per request. */ dates?: Date[]; /** * List of dates ranges that match the media items' creation date. A * maximum of 5 dates ranges can be included per request. */ ranges?: DateRange[]; } interface DateRange { /** * The end date (included as part of the range). It must be specified in the * same format as the start date. */ endDate?: Date; /** * The start date (included as part of the range) in one of the formats * described. */ startDate?: Date; } interface EnrichmentItem { /** Identifier of the enrichment item. */ id?: string; } interface FeatureFilter { /** * The set of features to be included in the media item search results. * The items in the set are ORed and may match any of the specified features. */ includedFeatures?: string[]; } interface Filters { /** Filters the media items based on their content. */ contentFilter?: ContentFilter; /** Filters the media items based on their creation date. */ dateFilter?: DateFilter; /** * If set, the results exclude media items that were not created by this app. * Defaults to false (all media items are returned). This field is ignored if * the photoslibrary.readonly.appcreateddata scope is used. */ excludeNonAppCreatedData?: boolean; /** Filters the media items based on their features. */ featureFilter?: FeatureFilter; /** * If set, the results include media items that the user has archived. * Defaults to false (archived media items aren't included). */ includeArchivedMedia?: boolean; /** Filters the media items based on the type of media. */ mediaTypeFilter?: MediaTypeFilter; } interface JoinSharedAlbumRequest { /** Token to join the shared album on behalf of the user. */ shareToken?: string; } interface JoinSharedAlbumResponse { /** Shared album that the user has joined. */ album?: Album; } interface LatLng { /** The latitude in degrees. It must be in the range [-90.0, +90.0]. */ latitude?: number; /** The longitude in degrees. It must be in the range [-180.0, +180.0]. */ longitude?: number; } interface LeaveSharedAlbumRequest { /** Token to leave the shared album on behalf of the user. */ shareToken?: string; } // tslint:disable-next-line:no-empty-interface interface LeaveSharedAlbumResponse { } interface ListAlbumsResponse { /** * Output only. List of albums shown in the Albums tab of the user's Google * Photos app. */ albums?: Album[]; /** * Output only. Token to use to get the next set of albums. Populated if * there are more albums to retrieve for this request. */ nextPageToken?: string; } interface ListMediaItemsResponse { /** Output only. List of media items in the user's library. */ mediaItems?: MediaItem[]; /** * Output only. Token to use to get the next set of media items. Its presence * is the only reliable indicator of more media items being available in the * next request. */ nextPageToken?: string; } interface ListSharedAlbumsResponse { /** * Output only. Token to use to get the next set of shared albums. Populated * if there are more shared albums to retrieve for this request. */ nextPageToken?: string; /** Output only. List of shared albums. */ sharedAlbums?: Album[]; } interface Location { /** Position of the location on the map. */ latlng?: LatLng; /** Name of the location to be displayed. */ locationName?: string; } interface LocationEnrichment { /** Location for this enrichment item. */ location?: Location; } interface MapEnrichment { /** Destination location for this enrichemt item. */ destination?: Location; /** Origin location for this enrichment item. */ origin?: Location; } interface MediaItem { /** * A URL to the media item's bytes. This shouldn't be used as is. Parameters * should be appended to this URL before use. See the [developer * documentation](https://developers.google.com/photos/library/guides/access-media-items#base-urls) * for a complete list of supported parameters. For example, `'=w2048-h1024'` * will set the dimensions of a media item of type photo to have a width of * 2048 px and height of 1024 px. */ baseUrl?: string; /** Information about the user who created this media item. */ contributorInfo?: ContributorInfo; /** * Description of the media item. This is shown to the user in the item's * info section in the Google Photos app. */ description?: string; /** * Filename of the media item. This is shown to the user in the item's info * section in the Google Photos app. */ filename?: string; /** * Identifier for the media item. This is a persistent identifier that can be * used between sessions to identify this media item. */ id?: string; /** * Metadata related to the media item, such as, height, width, or * creation time. */ mediaMetadata?: MediaMetadata; /** MIME type of the media item. For example, `image/jpeg`. */ mimeType?: string; /** * Google Photos URL for the media item. This link is available to * the user only if they're signed in. */ productUrl?: string; } interface MediaItemResult { /** * Media item retrieved from the user's library. It's populated if no errors * occurred and the media item was fetched successfully. */ mediaItem?: MediaItem; /** * If an error occurred while accessing this media item, this field * is populated with information related to the error. For details regarding * this field, see Status. */ status?: Status; } interface MediaMetadata { /** * Time when the media item was first created (not when it was uploaded to * Google Photos). */ creationTime?: string; /** Original height (in pixels) of the media item. */ height?: string; /** Metadata for a photo media type. */ photo?: Photo; /** Metadata for a video media type. */ video?: Video; /** Original width (in pixels) of the media item. */ width?: string; } interface MediaTypeFilter { /** * The types of media items to be included. This field should be populated * with only one media type. If you specify multiple media types, it results * in an error. */ mediaTypes?: string[]; } interface NewEnrichmentItem { /** Location to be added to the album. */ locationEnrichment?: LocationEnrichment; /** Map to be added to the album. */ mapEnrichment?: MapEnrichment; /** Text to be added to the album. */ textEnrichment?: TextEnrichment; } interface NewMediaItem { /** * Description of the media item. This will be shown to the user in the item's * info section in the Google Photos app. * This string shouldn't be more than 1000 characters. */ description?: string; /** A new media item that has been uploaded via the included `uploadToken`. */ simpleMediaItem?: SimpleMediaItem; } interface NewMediaItemResult { /** * Media item created with the upload token. It's populated if no errors * occurred and the media item was created successfully. */ mediaItem?: MediaItem; /** * If an error occurred during the creation of this media item, this field * is populated with information related to the error. For details regarding * this field, see <a href="#Status">Status</a>. */ status?: Status; /** The upload token used to create this new media item. */ uploadToken?: string; } interface Photo { /** Aperture f number of the camera lens with which the photo was taken. */ apertureFNumber?: number; /** Brand of the camera with which the photo was taken. */ cameraMake?: string; /** Model of the camera with which the photo was taken. */ cameraModel?: string; /** Exposure time of the camera aperture when the photo was taken. */ exposureTime?: string; /** Focal length of the camera lens with which the photo was taken. */ focalLength?: number; /** ISO of the camera with which the photo was taken. */ isoEquivalent?: number; } interface SearchMediaItemsRequest { /** * Identifier of an album. If populated, lists all media items in * specified album. Can't set in conjunction with any filters. */ albumId?: string; /** * Filters to apply to the request. Can't be set in conjunction with an * `albumId`. */ filters?: Filters; /** * Maximum number of media items to return in the response. Fewer media items * might be returned than the specified number. The default `pageSize` is 25, * the maximum is 100. */ pageSize?: number; /** * A continuation token to get the next page of the results. Adding this to * the request returns the rows after the `pageToken`. The `pageToken` should * be the value returned in the `nextPageToken` parameter in the response to * the `searchMediaItems` request. */ pageToken?: string; } interface SearchMediaItemsResponse { /** Output only. List of media items that match the search parameters. */ mediaItems?: MediaItem[]; /** * Output only. Use this token to get the next set of media items. Its * presence is the only reliable indicator of more media items being available * in the next request. */ nextPageToken?: string; } interface ShareAlbumRequest { /** Options to be set when converting the album to a shared album. */ sharedAlbumOptions?: SharedAlbumOptions; } interface ShareAlbumResponse { /** Output only. Information about the shared album. */ shareInfo?: ShareInfo; } interface ShareInfo { /** * True if the user has joined the album. This is always true for the owner * of the shared album. */ isJoined?: boolean; /** True if the user owns the album. */ isOwned?: boolean; /** * A token that can be used by other users to join this shared album via the * API. */ shareToken?: string; /** * A link to the album that's now shared on the Google Photos website and app. * Anyone with the link can access this shared album and see all of the items * present in the album. */ shareableUrl?: string; /** Options that control the sharing of an album. */ sharedAlbumOptions?: SharedAlbumOptions; } interface SharedAlbumOptions { /** * True if the shared album allows collaborators (users who have joined * the album) to add media items to it. Defaults to false. */ isCollaborative?: boolean; /** * True if the shared album allows the owner and the collaborators (users * who have joined the album) to add comments to the album. Defaults to false. */ isCommentable?: boolean; } interface SimpleMediaItem { /** * File name with extension of the media item. This is shown to the user in * Google Photos. The file name specified during the <a * href="https://developers.google.com/photos/library/guides/upload-media">byte * upload process</a> is ignored if this field is set. The file name, * including the file extension, shouldn't be more than 255 characters. This * is an optional field. */ fileName?: string; /** Token identifying the media bytes that have been uploaded to Google. */ uploadToken?: string; } interface Status { /** The status code, which should be an enum value of google.rpc.Code. */ code?: number; /** * A list of messages that carry the error details. There is a common set of * message types for APIs to use. */ details?: Array<Record<string, any>>; /** * A developer-facing error message, which should be in English. Any * user-facing error message should be localized and sent in the * google.rpc.Status.details field, or localized by the client. */ message?: string; } interface TextEnrichment { /** Text for this enrichment item. */ text?: string; } // tslint:disable-next-line:no-empty-interface interface UnshareAlbumRequest { } // tslint:disable-next-line:no-empty-interface interface UnshareAlbumResponse { } interface Video { /** Brand of the camera with which the video was taken. */ cameraMake?: string; /** Model of the camera with which the video was taken. */ cameraModel?: string; /** Frame rate of the video. */ fps?: number; /** Processing status of the video. */ status?: string; } interface AlbumsResource { /** Adds an enrichment at a specified position in a defined album. */ addEnrichment(request: { /** V1 error format. */ "$.xgafv"?: string; /** OAuth access token. */ access_token?: string; /** Identifier of the album where the enrichment is to be added. */ albumId: string; /** Data format for response. */ alt?: string; /** JSONP */ callback?: string; /** Selector specifying which fields to include in a partial response. */ fields?: string; /** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */ key?: string; /** OAuth 2.0 token for the current user. */ oauth_token?: string; /** Returns response with indentations and line breaks. */ prettyPrint?: boolean; /** Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. */ quotaUser?: string; /** Legacy upload protocol for media (e.g. "media", "multipart"). */ uploadType?: string; /** Upload protocol for media (e.g. "raw", "multipart"). */ upload_protocol?: string; /** Request body */ resource: AddEnrichmentToAlbumRequest; }): Request<AddEnrichmentToAlbumResponse>; addEnrichment(request: { /** V1 error format. */ "$.xgafv"?: string; /** OAuth access token. */ access_token?: string; /** Identifier of the album where the enrichment is to be added. */ albumId: string; /** Data format for response. */ alt?: string; /** JSONP */ callback?: string; /** Selector specifying which fields to include in a partial response. */ fields?: string; /** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */ key?: string; /** OAuth 2.0 token for the current user. */ oauth_token?: string; /** Returns response with indentations and line breaks. */ prettyPrint?: boolean; /** Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. */ quotaUser?: string; /** Legacy upload protocol for media (e.g. "media", "multipart"). */ uploadType?: string; /** Upload protocol for media (e.g. "raw", "multipart"). */ upload_protocol?: string; }, body: AddEnrichmentToAlbumRequest): Request<AddEnrichmentToAlbumResponse>; /** * Adds one or more media items in a user's Google Photos library to * an album. The media items and albums must have been created by the * developer via the API. * * Media items are added to the end of the album. If multiple media items are * given, they are added in the order specified in this call. * * Each album can contain up to 20,000 media items. * * Only media items that are in the user's library can be added to an * album. For albums that are shared, the album must either be owned by the * user or the user must have joined the album as a collaborator. * * Partial success is not supported. The entire request will fail if an * invalid media item or album is specified. */ batchAddMediaItems(request: { /** V1 error format. */ "$.xgafv"?: string; /** OAuth access token. */ access_token?: string; /** * Identifier of the Album that the * media items are added to. */ albumId: string; /** Data format for response. */ alt?: string; /** JSONP */ callback?: string; /** Selector specifying which fields to include in a partial response. */ fields?: string; /** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */ key?: string; /** OAuth 2.0 token for the current user. */ oauth_token?: string; /** Returns response with indentations and line breaks. */ prettyPrint?: boolean; /** Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. */ quotaUser?: string; /** Legacy upload protocol for media (e.g. "media", "multipart"). */ uploadType?: string; /** Upload protocol for media (e.g. "raw", "multipart"). */ upload_protocol?: string; /** Request body */ resource: BatchAddMediaItemsToAlbumRequest; }): Request<{}>; batchAddMediaItems(request: { /** V1 error format. */ "$.xgafv"?: string; /** OAuth access token. */ access_token?: string; /** * Identifier of the Album that the * media items are added to. */ albumId: string; /** Data format for response. */ alt?: string; /** JSONP */ callback?: string; /** Selector specifying which fields to include in a partial response. */ fields?: string; /** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */ key?: string; /** OAuth 2.0 token for the current user. */ oauth_token?: string; /** Returns response with indentations and line breaks. */ prettyPrint?: boolean; /** Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. */ quotaUser?: string; /** Legacy upload protocol for media (e.g. "media", "multipart"). */ uploadType?: string; /** Upload protocol for media (e.g. "raw", "multipart"). */ upload_protocol?: string; }, body: BatchAddMediaItemsToAlbumRequest): Request<{}>; /** * Removes one or more media items from a specified album. The media items and * the album must have been created by the developer via the API. * * For albums that are shared, this action is only supported for media items * that were added to the album by this user, or for all media items if the * album was created by this user. * * Partial success is not supported. The entire request will fail and no * action will be performed on the album if an invalid media item or album is * specified. */ batchRemoveMediaItems(request: { /** V1 error format. */ "$.xgafv"?: string; /** OAuth access token. */ access_token?: string; /** * Identifier of the Album that the media * items are to be removed from. */ albumId: string; /** Data format for response. */ alt?: string; /** JSONP */ callback?: string; /** Selector specifying which fields to include in a partial response. */ fields?: string; /** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */ key?: string; /** OAuth 2.0 token for the current user. */ oauth_token?: string; /** Returns response with indentations and line breaks. */ prettyPrint?: boolean; /** Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. */ quotaUser?: string; /** Legacy upload protocol for media (e.g. "media", "multipart"). */ uploadType?: string; /** Upload protocol for media (e.g. "raw", "multipart"). */ upload_protocol?: string; /** Request body */ resource: BatchRemoveMediaItemsFromAlbumRequest; }): Request<{}>; batchRemoveMediaItems(request: { /** V1 error format. */ "$.xgafv"?: string; /** OAuth access token. */ access_token?: string; /** * Identifier of the Album that the media * items are to be removed from. */ albumId: string; /** Data format for response. */ alt?: string; /** JSONP */ callback?: string; /** Selector specifying which fields to include in a partial response. */ fields?: string; /** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */ key?: string; /** OAuth 2.0 token for the current user. */ oauth_token?: string; /** Returns response with indentations and line breaks. */ prettyPrint?: boolean; /** Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. */ quotaUser?: string; /** Legacy upload protocol for media (e.g. "media", "multipart"). */ uploadType?: string; /** Upload protocol for media (e.g. "raw", "multipart"). */ upload_protocol?: string; }, body: BatchRemoveMediaItemsFromAlbumRequest): Request<{}>; /** Creates an album in a user's Google Photos library. */ create(request: { /** V1 error format. */ "$.xgafv"?: string; /** OAuth access token. */ access_token?: string; /** Data format for response. */ alt?: string; /** JSONP */ callback?: string; /** Selector specifying which fields to include in a partial response. */ fields?: string; /** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */ key?: string; /** OAuth 2.0 token for the current user. */ oauth_token?: string; /** Returns response with indentations and line breaks. */ prettyPrint?: boolean; /** Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. */ quotaUser?: string; /** Legacy upload protocol for media (e.g. "media", "multipart"). */ uploadType?: string; /** Upload protocol for media (e.g. "raw", "multipart"). */ upload_protocol?: string; /** Request body */ resource: CreateAlbumRequest; }): Request<Album>; create(request: { /** V1 error format. */ "$.xgafv"?: string; /** OAuth access token. */ access_token?: string; /** Data format for response. */ alt?: string; /** JSONP */ callback?: string; /** Selector specifying which fields to include in a partial response. */ fields?: string; /** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */ key?: string; /** OAuth 2.0 token for the current user. */ oauth_token?: string; /** Returns response with indentations and line breaks. */ prettyPrint?: boolean; /** Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. */ quotaUser?: string; /** Legacy upload protocol for media (e.g. "media", "multipart"). */ uploadType?: string; /** Upload protocol for media (e.g. "raw", "multipart"). */ upload_protocol?: string; }, body: CreateAlbumRequest): Request<Album>; /** * Returns the album based on the specified `albumId`. * The `albumId` must be the ID of an album owned by the user or a shared * album that the user has joined. */ get(request: { /** V1 error format. */ "$.xgafv"?: string; /** OAuth access token. */ access_token?: string; /** Identifier of the album to be requested. */ albumId: string; /** Data format for response. */ alt?: string; /** JSONP */ callback?: string; /** Selector specifying which fields to include in a partial response. */ fields?: string; /** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */ key?: string; /** OAuth 2.0 token for the current user. */ oauth_token?: string; /** Returns response with indentations and line breaks. */ prettyPrint?: boolean; /** Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. */ quotaUser?: string; /** Legacy upload protocol for media (e.g. "media", "multipart"). */ uploadType?: string; /** Upload protocol for media (e.g. "raw", "multipart"). */ upload_protocol?: string; }): Request<Album>; /** * Lists all albums shown to a user in the Albums tab of the Google * Photos app. */ list(request: { /** V1 error format. */ "$.xgafv"?: string; /** OAuth access token. */ access_token?: string; /** Data format for response. */ alt?: string; /** JSONP */ callback?: string; /** * If set, the results exclude media items that were not created by this app. * Defaults to false (all albums are returned). This field is ignored if the * photoslibrary.readonly.appcreateddata scope is used. */ excludeNonAppCreatedData?: boolean; /** Selector specifying which fields to include in a partial response. */ fields?: string; /** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */ key?: string; /** OAuth 2.0 token for the current user. */ oauth_token?: string; /** * Maximum number of albums to return in the response. Fewer albums might be * returned than the specified number. The default `pageSize` is 20, the * maximum is 50. */ pageSize?: number; /** * A continuation token to get the next page of the results. Adding this to * the request returns the rows after the `pageToken`. The `pageToken` should * be the value returned in the `nextPageToken` parameter in the response to * the `listAlbums` request. */ pageToken?: string; /** Returns response with indentations and line breaks. */ prettyPrint?: boolean; /** Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. */ quotaUser?: string; /** Legacy upload protocol for media (e.g. "media", "multipart"). */ uploadType?: string; /** Upload protocol for media (e.g. "raw", "multipart"). */ upload_protocol?: string; }): Request<ListAlbumsResponse>; /** * Marks an album as shared and accessible to other users. This action can * only be performed on albums which were created by the developer via the * API. */ share(request: { /** V1 error format. */ "$.xgafv"?: string; /** OAuth access token. */ access_token?: string; /** * Identifier of the album to be shared. This `albumId` must belong to an * album created by the developer. */ albumId: string; /** Data format for response. */ alt?: string; /** JSONP */ callback?: string; /** Selector specifying which fields to include in a partial response. */ fields?: string; /** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */ key?: string; /** OAuth 2.0 token for the current user. */ oauth_token?: string; /** Returns response with indentations and line breaks. */ prettyPrint?: boolean; /** Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. */ quotaUser?: string; /** Legacy upload protocol for media (e.g. "media", "multipart"). */ uploadType?: string; /** Upload protocol for media (e.g. "raw", "multipart"). */ upload_protocol?: string; /** Request body */ resource: ShareAlbumRequest; }): Request<ShareAlbumResponse>; share(request: { /** V1 error format. */ "$.xgafv"?: string; /** OAuth access token. */ access_token?: string; /** * Identifier of the album to be shared. This `albumId` must belong to an * album created by the developer. */ albumId: string; /** Data format for response. */ alt?: string; /** JSONP */ callback?: string; /** Selector specifying which fields to include in a partial response. */ fields?: string; /** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */ key?: string; /** OAuth 2.0 token for the current user. */ oauth_token?: string; /** Returns response with indentations and line breaks. */ prettyPrint?: boolean; /** Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. */ quotaUser?: string; /** Legacy upload protocol for media (e.g. "media", "multipart"). */ uploadType?: string; /** Upload protocol for media (e.g. "raw", "multipart"). */ upload_protocol?: string; }, body: ShareAlbumRequest): Request<ShareAlbumResponse>; /** * Marks a previously shared album as private. This means that the album is * no longer shared and all the non-owners will lose access to the album. All * non-owner content will be removed from the album. If a non-owner has * previously added the album to their library, they will retain all photos in * their library. This action can only be performed on albums which were * created by the developer via the API. */ unshare(request: { /** V1 error format. */ "$.xgafv"?: string; /** OAuth access token. */ access_token?: string; /** * Identifier of the album to be unshared. This album id must belong to an * album created by the developer. */ albumId: string; /** Data format for response. */ alt?: string; /** JSONP */ callback?: string; /** Selector specifying which fields to include in a partial response. */ fields?: string; /** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */ key?: string; /** OAuth 2.0 token for the current user. */ oauth_token?: string; /** Returns response with indentations and line breaks. */ prettyPrint?: boolean; /** Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. */ quotaUser?: string; /** Legacy upload protocol for media (e.g. "media", "multipart"). */ uploadType?: string; /** Upload protocol for media (e.g. "raw", "multipart"). */ upload_protocol?: string; /** Request body */ resource: UnshareAlbumRequest; }): Request<{}>; unshare(request: { /** V1 error format. */ "$.xgafv"?: string; /** OAuth access token. */ access_token?: string; /** * Identifier of the album to be unshared. This album id must belong to an * album created by the developer. */ albumId: string; /** Data format for response. */ alt?: string; /** JSONP */ callback?: string; /** Selector specifying which fields to include in a partial response. */ fields?: string; /** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */ key?: string; /** OAuth 2.0 token for the current user. */ oauth_token?: string; /** Returns response with indentations and line breaks. */ prettyPrint?: boolean; /** Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. */ quotaUser?: string; /** Legacy upload protocol for media (e.g. "media", "multipart"). */ uploadType?: string; /** Upload protocol for media (e.g. "raw", "multipart"). */ upload_protocol?: string; }, body: UnshareAlbumRequest): Request<{}>; } interface MediaItemsResource { /** * Creates one or more media items in a user's Google Photos library. * * This is the second step for creating a media item. For details regarding * Step 1, uploading the raw bytes to a Google Server, see * <a href="/photos/library/guides/upload-media">Uploading media</a>. * * This call adds the media item to the library. If an album `id` is * specified, the call adds the media item to the album too. Each album can * contain up to 20,000 media items. By default, the media item will be added * to the end of the library or album. * * If an album `id` and position are both defined, the media item is * added to the album at the specified position. * * If the call contains multiple media items, they're added at the specified * position. * If you are creating a media item in a shared album where you are not the * owner, you are not allowed to position the media item. Doing so will result * in a `BAD REQUEST` error. */ batchCreate(request: { /** V1 error format. */ "$.xgafv"?: string; /** OAuth access token. */ access_token?: string; /** Data format for response. */ alt?: string; /** JSONP */ callback?: string; /** Selector specifying which fields to include in a partial response. */ fields?: string; /** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */ key?: string; /** OAuth 2.0 token for the current user. */ oauth_token?: string; /** Returns response with indentations and line breaks. */ prettyPrint?: boolean; /** Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. */ quotaUser?: string; /** Legacy upload protocol for media (e.g. "media", "multipart"). */ uploadType?: string; /** Upload protocol for media (e.g. "raw", "multipart"). */ upload_protocol?: string; /** Request body */ resource: BatchCreateMediaItemsRequest; }): Request<BatchCreateMediaItemsResponse>; batchCreate(request: { /** V1 error format. */ "$.xgafv"?: string; /** OAuth access token. */ access_token?: string; /** Data format for response. */ alt?: string; /** JSONP */ callback?: string; /** Selector specifying which fields to include in a partial response. */ fields?: string; /** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */ key?: string; /** OAuth 2.0 token for the current user. */ oauth_token?: string; /** Returns response with indentations and line breaks. */ prettyPrint?: boolean; /** Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. */ quotaUser?: string; /** Legacy upload protocol for media (e.g. "media", "multipart"). */ uploadType?: string; /** Upload protocol for media (e.g. "raw", "multipart"). */ upload_protocol?: string; }, body: BatchCreateMediaItemsRequest): Request<BatchCreateMediaItemsResponse>; /** * Returns the list of media items for the specified media item identifiers. * Items are returned in the same order as the supplied identifiers. */ batchGet(request: { /** V1 error format. */ "$.xgafv"?: string; /** OAuth access token. */ access_token?: string; /** Data format for response. */ alt?: string; /** JSONP */ callback?: string; /** Selector specifying which fields to include in a partial response. */ fields?: string; /** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */ key?: string; /** * Identifiers of the media items to be requested. * Must not contain repeated identifiers and cannot be empty. The maximum * number of media items that can be retrieved in one call is 50. */ mediaItemIds?: string | string[]; /** OAuth 2.0 token for the current user. */ oauth_token?: string; /** Returns response with indentations and line breaks. */ prettyPrint?: boolean; /** Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. */ quotaUser?: string; /** Legacy upload protocol for media (e.g. "media", "multipart"). */ uploadType?: string; /** Upload protocol for media (e.g. "raw", "multipart"). */ upload_protocol?: string; }): Request<BatchGetMediaItemsResponse>; /** Returns the media item for the specified media item identifier. */ get(request: { /** V1 error format. */ "$.xgafv"?: string; /** OAuth access token. */ access_token?: string; /** Data format for response. */ alt?: string; /** JSONP */ callback?: string; /** Selector specifying which fields to include in a partial response. */ fields?: string; /** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */ key?: string; /** Identifier of the media item to be requested. */ mediaItemId: string; /** OAuth 2.0 token for the current user. */ oauth_token?: string; /** Returns response with indentations and line breaks. */ prettyPrint?: boolean; /** Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. */ quotaUser?: string; /** Legacy upload protocol for media (e.g. "media", "multipart"). */ uploadType?: string; /** Upload protocol for media (e.g. "raw", "multipart"). */ upload_protocol?: string; }): Request<MediaItem>; /** List all media items from a user's Google Photos library. */ list(request: { /** V1 error format. */ "$.xgafv"?: string; /** OAuth access token. */ access_token?: string; /** Data format for response. */ alt?: string; /** JSONP */ callback?: string; /** Selector specifying which fields to include in a partial response. */ fields?: string; /** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */ key?: string; /** OAuth 2.0 token for the current user. */ oauth_token?: string; /** * Maximum number of media items to return in the response. Fewer media items * might be returned than the specified number. The default `pageSize` is 25, * the maximum is 100. */ pageSize?: number; /** * A continuation token to get the next page of the results. Adding this to * the request returns the rows after the `pageToken`. The `pageToken` should * be the value returned in the `nextPageToken` parameter in the response to * the `listMediaItems` request. */ pageToken?: string; /** Returns response with indentations and line breaks. */ prettyPrint?: boolean; /** Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. */ quotaUser?: string; /** Legacy upload protocol for media (e.g. "media", "multipart"). */ uploadType?: string; /** Upload protocol for media (e.g. "raw", "multipart"). */ upload_protocol?: string; }): Request<ListMediaItemsResponse>; /** * Searches for media items in a user's Google Photos library. * If no filters are set, then all media items in the user's library are * returned. * If an album is set, all media items in the specified album are returned. * If filters are specified, media items that match the filters from the * user's library are listed. If you set both the album and the filters, the * request results in an error. */ search(request: { /** V1 error format. */ "$.xgafv"?: string; /** OAuth access token. */ access_token?: string; /** Data format for response. */ alt?: string; /** JSONP */ callback?: string; /** Selector specifying which fields to include in a partial response. */ fields?: string; /** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */ key?: string; /** OAuth 2.0 token for the current user. */ oauth_token?: string; /** Returns response with indentations and line breaks. */ prettyPrint?: boolean; /** Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. */ quotaUser?: string; /** Legacy upload protocol for media (e.g. "media", "multipart"). */ uploadType?: string; /** Upload protocol for media (e.g. "raw", "multipart"). */ upload_protocol?: string; /** Request body */ resource: SearchMediaItemsRequest; }): Request<SearchMediaItemsResponse>; search(request: { /** V1 error format. */ "$.xgafv"?: string; /** OAuth access token. */ access_token?: string; /** Data format for response. */ alt?: string; /** JSONP */ callback?: string; /** Selector specifying which fields to include in a partial response. */ fields?: string; /** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */ key?: string; /** OAuth 2.0 token for the current user. */ oauth_token?: string; /** Returns response with indentations and line breaks. */ prettyPrint?: boolean; /** Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. */ quotaUser?: string; /** Legacy upload protocol for media (e.g. "media", "multipart"). */ uploadType?: string; /** Upload protocol for media (e.g. "raw", "multipart"). */ upload_protocol?: string; }, body: SearchMediaItemsRequest): Request<SearchMediaItemsResponse>; } interface SharedAlbumsResource { /** Returns the album based on the specified `shareToken`. */ get(request: { /** V1 error format. */ "$.xgafv"?: string; /** OAuth access token. */ access_token?: string; /** Data format for response. */ alt?: string; /** JSONP */ callback?: string; /** Selector specifying which fields to include in a partial response. */ fields?: string; /** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */ key?: string; /** OAuth 2.0 token for the current user. */ oauth_token?: string; /** Returns response with indentations and line breaks. */ prettyPrint?: boolean; /** Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. */ quotaUser?: string; /** Share token of the album to be requested. */ shareToken: string; /** Legacy upload protocol for media (e.g. "media", "multipart"). */ uploadType?: string; /** Upload protocol for media (e.g. "raw", "multipart"). */ upload_protocol?: string; }): Request<Album>; /** Joins a shared album on behalf of the Google Photos user. */ join(request: { /** V1 error format. */ "$.xgafv"?: string; /** OAuth access token. */ access_token?: string; /** Data format for response. */ alt?: string; /** JSONP */ callback?: string; /** Selector specifying which fields to include in a partial response. */ fields?: string; /** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */ key?: string; /** OAuth 2.0 token for the current user. */ oauth_token?: string; /** Returns response with indentations and line breaks. */ prettyPrint?: boolean; /** Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. */ quotaUser?: string; /** Legacy upload protocol for media (e.g. "media", "multipart"). */ uploadType?: string; /** Upload protocol for media (e.g. "raw", "multipart"). */ upload_protocol?: string; /** Request body */ resource: JoinSharedAlbumRequest; }): Request<JoinSharedAlbumResponse>; join(request: { /** V1 error format. */ "$.xgafv"?: string; /** OAuth access token. */ access_token?: string; /** Data format for response. */ alt?: string; /** JSONP */ callback?: string; /** Selector specifying which fields to include in a partial response. */ fields?: string; /** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */ key?: string; /** OAuth 2.0 token for the current user. */ oauth_token?: string; /** Returns response with indentations and line breaks. */ prettyPrint?: boolean; /** Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. */ quotaUser?: string; /** Legacy upload protocol for media (e.g. "media", "multipart"). */ uploadType?: string; /** Upload protocol for media (e.g. "raw", "multipart"). */ upload_protocol?: string; }, body: JoinSharedAlbumRequest): Request<JoinSharedAlbumResponse>; /** * Leaves a previously-joined shared album on behalf of the Google Photos * user. The user must not own this album. */ leave(request: { /** V1 error format. */ "$.xgafv"?: string; /** OAuth access token. */ access_token?: string; /** Data format for response. */ alt?: string; /** JSONP */ callback?: string; /** Selector specifying which fields to include in a partial response. */ fields?: string; /** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */ key?: string; /** OAuth 2.0 token for the current user. */ oauth_token?: string; /** Returns response with indentations and line breaks. */ prettyPrint?: boolean; /** Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. */ quotaUser?: string; /** Legacy upload protocol for media (e.g. "media", "multipart"). */ uploadType?: string; /** Upload protocol for media (e.g. "raw", "multipart"). */ upload_protocol?: string; /** Request body */ resource: LeaveSharedAlbumRequest; }): Request<{}>; leave(request: { /** V1 error format. */ "$.xgafv"?: string; /** OAuth access token. */ access_token?: string; /** Data format for response. */ alt?: string; /** JSONP */ callback?: string; /** Selector specifying which fields to include in a partial response. */ fields?: string; /** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */ key?: string; /** OAuth 2.0 token for the current user. */ oauth_token?: string; /** Returns response with indentations and line breaks. */ prettyPrint?: boolean; /** Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. */ quotaUser?: string; /** Legacy upload protocol for media (e.g. "media", "multipart"). */ uploadType?: string; /** Upload protocol for media (e.g. "raw", "multipart"). */ upload_protocol?: string; }, body: LeaveSharedAlbumRequest): Request<{}>; /** * Lists all shared albums available in the Sharing tab of the * user's Google Photos app. */ list(request: { /** V1 error format. */ "$.xgafv"?: string; /** OAuth access token. */ access_token?: string; /** Data format for response. */ alt?: string; /** JSONP */ callback?: string; /** * If set, the results exclude media items that were not created by this app. * Defaults to false (all albums are returned). This field is ignored if the * photoslibrary.readonly.appcreateddata scope is used. */ excludeNonAppCreatedData?: boolean; /** Selector specifying which fields to include in a partial response. */ fields?: string; /** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */ key?: string; /** OAuth 2.0 token for the current user. */ oauth_token?: string; /** * Maximum number of albums to return in the response. Fewer albums might be * returned than the specified number. The default `pageSize` is 20, the * maximum is 50. */ pageSize?: number; /** * A continuation token to get the next page of the results. Adding this to * the request returns the rows after the `pageToken`. The `pageToken` should * be the value returned in the `nextPageToken` parameter in the response to * the `listSharedAlbums` request. */ pageToken?: string; /** Returns response with indentations and line breaks. */ prettyPrint?: boolean; /** Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. */ quotaUser?: string; /** Legacy upload protocol for media (e.g. "media", "multipart"). */ uploadType?: string; /** Upload protocol for media (e.g. "raw", "multipart"). */ upload_protocol?: string; }): Request<ListSharedAlbumsResponse>; } const albums: AlbumsResource; const mediaItems: MediaItemsResource; const sharedAlbums: SharedAlbumsResource; } }
the_stack
declare module 'vscode' { /** * A reference to one of the workbench colors as defined in https://code.visualstudio.com/docs/getstarted/theme-color-reference. * Using a theme color is preferred over a custom color as it gives theme authors and users the possibility to change the color. */ export class ThemeColor { /** * Creates a reference to a theme color. * @param id of the color. The available colors are listed in https://code.visualstudio.com/docs/getstarted/theme-color-reference. */ constructor(id: string); } /** * A reference to a named icon. Currently, [File](#ThemeIcon.File), [Folder](#ThemeIcon.Folder), * and [ThemeIcon ids](https://code.visualstudio.com/api/references/icons-in-labels#icon-listing) are supported. * Using a theme icon is preferred over a custom icon as it gives product theme authors the possibility to change the icons. * * *Note* that theme icons can also be rendered inside labels and descriptions. Places that support theme icons spell this out * and they use the `$(<name>)`-syntax, for instance `quickPick.label = "Hello World $(globe)"`. */ export class ThemeIcon { /** * Reference to an icon representing a file. The icon is taken from the current file icon theme or a placeholder icon is used. */ static readonly File: ThemeIcon; /** * Reference to an icon representing a folder. The icon is taken from the current file icon theme or a placeholder icon is used. */ static readonly Folder: ThemeIcon; /** * The id of the icon. The available icons are listed in https://code.visualstudio.com/api/references/icons-in-labels#icon-listing. */ readonly id: string; /** * The optional ThemeColor of the icon. The color is currently only used in [TreeItem](#TreeItem). */ readonly color?: ThemeColor; /** * Creates a reference to a theme icon. * @param id id of the icon. The avaiable icons are listed in https://microsoft.github.io/vscode-codicons/dist/codicon.html. */ constructor(id: string); /** * Creates a reference to a theme icon. * @param id id of the icon. The available icons are listed in https://code.visualstudio.com/api/references/icons-in-labels#icon-listing. * @param color optional `ThemeColor` for the icon. The color is currently only used in [TreeItem](#TreeItem). */ constructor(id: string, color?: ThemeColor); } /** * Represents theme specific rendering styles for a [text editor decoration](#TextEditorDecorationType). */ export interface ThemableDecorationRenderOptions { /** * Background color of the decoration. Use rgba() and define transparent background colors to play well with other decorations. * Alternatively a color from the color registry can be [referenced](#ThemeColor). */ backgroundColor?: string | ThemeColor; /** * CSS styling property that will be applied to text enclosed by a decoration. */ outline?: string; /** * CSS styling property that will be applied to text enclosed by a decoration. * Better use 'outline' for setting one or more of the individual outline properties. */ outlineColor?: string | ThemeColor; /** * CSS styling property that will be applied to text enclosed by a decoration. * Better use 'outline' for setting one or more of the individual outline properties. */ outlineStyle?: string; /** * CSS styling property that will be applied to text enclosed by a decoration. * Better use 'outline' for setting one or more of the individual outline properties. */ outlineWidth?: string; /** * CSS styling property that will be applied to text enclosed by a decoration. */ border?: string; /** * CSS styling property that will be applied to text enclosed by a decoration. * Better use 'border' for setting one or more of the individual border properties. */ borderColor?: string | ThemeColor; /** * CSS styling property that will be applied to text enclosed by a decoration. * Better use 'border' for setting one or more of the individual border properties. */ borderRadius?: string; /** * CSS styling property that will be applied to text enclosed by a decoration. * Better use 'border' for setting one or more of the individual border properties. */ borderSpacing?: string; /** * CSS styling property that will be applied to text enclosed by a decoration. * Better use 'border' for setting one or more of the individual border properties. */ borderStyle?: string; /** * CSS styling property that will be applied to text enclosed by a decoration. * Better use 'border' for setting one or more of the individual border properties. */ borderWidth?: string; /** * CSS styling property that will be applied to text enclosed by a decoration. */ fontStyle?: string; /** * CSS styling property that will be applied to text enclosed by a decoration. */ fontWeight?: string; /** * CSS styling property that will be applied to text enclosed by a decoration. */ textDecoration?: string; /** * CSS styling property that will be applied to text enclosed by a decoration. */ cursor?: string; /** * CSS styling property that will be applied to text enclosed by a decoration. */ color?: string | ThemeColor; /** * CSS styling property that will be applied to text enclosed by a decoration. */ opacity?: string; /** * CSS styling property that will be applied to text enclosed by a decoration. */ letterSpacing?: string; /** * An **absolute path** or an URI to an image to be rendered in the gutter. */ gutterIconPath?: string | Uri; /** * Specifies the size of the gutter icon. * Available values are 'auto', 'contain', 'cover' and any percentage value. * For further information: https://msdn.microsoft.com/en-us/library/jj127316(v=vs.85).aspx */ gutterIconSize?: string; /** * The color of the decoration in the overview ruler. Use rgba() and define transparent colors to play well with other decorations. */ overviewRulerColor?: string | ThemeColor; /** * Defines the rendering options of the attachment that is inserted before the decorated text. */ before?: ThemableDecorationAttachmentRenderOptions; /** * Defines the rendering options of the attachment that is inserted after the decorated text. */ after?: ThemableDecorationAttachmentRenderOptions; } export interface ThemableDecorationAttachmentRenderOptions { /** * Defines a text content that is shown in the attachment. Either an icon or a text can be shown, but not both. */ contentText?: string; /** * An **absolute path** or an URI to an image to be rendered in the attachment. Either an icon * or a text can be shown, but not both. */ contentIconPath?: string | Uri; /** * CSS styling property that will be applied to the decoration attachment. */ border?: string; /** * CSS styling property that will be applied to text enclosed by a decoration. */ borderColor?: string | ThemeColor; /** * CSS styling property that will be applied to the decoration attachment. */ fontStyle?: string; /** * CSS styling property that will be applied to the decoration attachment. */ fontWeight?: string; /** * CSS styling property that will be applied to the decoration attachment. */ textDecoration?: string; /** * CSS styling property that will be applied to the decoration attachment. */ color?: string | ThemeColor; /** * CSS styling property that will be applied to the decoration attachment. */ backgroundColor?: string | ThemeColor; /** * CSS styling property that will be applied to the decoration attachment. */ margin?: string; /** * CSS styling property that will be applied to the decoration attachment. */ width?: string; /** * CSS styling property that will be applied to the decoration attachment. */ height?: string; } /** * Represents a color in RGBA space. */ export class Color { /** * The red component of this color in the range [0-1]. */ readonly red: number; /** * The green component of this color in the range [0-1]. */ readonly green: number; /** * The blue component of this color in the range [0-1]. */ readonly blue: number; /** * The alpha component of this color in the range [0-1]. */ readonly alpha: number; /** * Creates a new color instance. * * @param red The red component. * @param green The green component. * @param blue The blue component. * @param alpha The alpha component. */ constructor(red: number, green: number, blue: number, alpha: number); } /** * Represents a color range from a document. */ export class ColorInformation { /** * The range in the document where this color appears. */ range: Range; /** * The actual color value for this color range. */ color: Color; /** * Creates a new color range. * * @param range The range the color appears in. Must not be empty. * @param color The value of the color. * @param format The format in which this color is currently formatted. */ constructor(range: Range, color: Color); } /** * A color presentation object describes how a [`color`](#Color) should be represented as text and what * edits are required to refer to it from source code. * * For some languages one color can have multiple presentations, e.g. css can represent the color red with * the constant `Red`, the hex-value `#ff0000`, or in rgba and hsla forms. In csharp other representations * apply, e.g. `System.Drawing.Color.Red`. */ export class ColorPresentation { /** * The label of this color presentation. It will be shown on the color * picker header. By default this is also the text that is inserted when selecting * this color presentation. */ label: string; /** * An [edit](#TextEdit) which is applied to a document when selecting * this presentation for the color. When `falsy` the [label](#ColorPresentation.label) * is used. */ textEdit?: TextEdit; /** * An optional array of additional [text edits](#TextEdit) that are applied when * selecting this color presentation. Edits must not overlap with the main [edit](#ColorPresentation.textEdit) nor with themselves. */ additionalTextEdits?: TextEdit[]; /** * Creates a new color presentation. * * @param label The label of this color presentation. */ constructor(label: string); } /** * The document color provider defines the contract between extensions and feature of * picking and modifying colors in the editor. */ export interface DocumentColorProvider { /** * Provide colors for the given document. * * @param document The document in which the command was invoked. * @param token A cancellation token. * @return An array of [color information](#ColorInformation) or a thenable that resolves to such. The lack of a result * can be signaled by returning `undefined`, `null`, or an empty array. */ provideDocumentColors(document: TextDocument, token: CancellationToken): ProviderResult<ColorInformation[]>; /** * Provide [representations](#ColorPresentation) for a color. * * @param color The color to show and insert. * @param context A context object with additional information * @param token A cancellation token. * @return An array of color presentations or a thenable that resolves to such. The lack of a result * can be signaled by returning `undefined`, `null`, or an empty array. */ provideColorPresentations(color: Color, context: { document: TextDocument, range: Range }, token: CancellationToken): ProviderResult<ColorPresentation[]>; } }
the_stack
import {AuditoryDescription} from '../audio/auditory_description'; import {Axis, AxisOrder, DynamicCstr, DynamicCstrParser} from './dynamic_cstr'; import {Action, Precondition, SpeechRule} from './speech_rule'; import {SpeechRuleContext} from './speech_rule_context'; import {SpeechRuleEvaluator} from './speech_rule_evaluator'; import {SpeechRuleStore} from './speech_rule_store'; export abstract class BaseRuleStore implements SpeechRuleEvaluator, SpeechRuleStore { /** * Context for custom functions of this rule store. */ public context: SpeechRuleContext = new SpeechRuleContext(); /** * A priority list of dynamic constraint attributes. */ public parseOrder: AxisOrder = DynamicCstr.DEFAULT_ORDER; /** * A dynamic constraint parser. */ public parser: DynamicCstrParser = new DynamicCstrParser(this.parseOrder); /** * Default locale. */ public locale: string = DynamicCstr.DEFAULT_VALUES[Axis.LOCALE]; /** * Default modality. */ public modality: string = DynamicCstr.DEFAULT_VALUES[Axis.MODALITY]; /** * Default domain. */ public domain: string = ''; // TODO (TS): Sort out this type! /** * Mapping for parse methods. */ public parseMethods: any; /** * Initialisation flag. */ public initialized: boolean = false; /** * Inheritance store. None if null. */ public inherits: BaseRuleStore = null; /** * Type of rule store: standard, abstract, actions. */ public kind: string = 'standard'; /** * Local transcriptions for special characters. */ public customTranscriptions: {[key: string]: string} = {}; /** * Set of Preconditions */ protected preconditions: Map<string, Condition> = new Map(); /** * Set of speech rules in the store. */ private speechRules_: SpeechRule[] = []; /** * Rank in the rule store definition. This informs the secondary rank for * speech rules and takes order of definitions into account. */ private rank: number = 0; // TODO (sorge) Define the following methods directly on the precondition // classes. /** * Compares two static constraints (i.e., lists of precondition constraints) * and returns true if they are equal. * @param cstr1 First static constraints. * @param cstr2 Second static constraints. * @return True if the static constraints are equal. */ private static compareStaticConstraints_(cstr1: string[], cstr2: string[]): boolean { if (cstr1.length !== cstr2.length) { return false; } for (let i = 0, cstr: string; cstr = cstr1[i]; i++) { if (cstr2.indexOf(cstr) === -1) { return false; } } return true; } /** * Compares the preconditions of two speech rules. * @param rule1 The first speech rule. * @param rule2 The second speech rule. * @return True if the preconditions are equal. */ private static comparePreconditions_(rule1: SpeechRule, rule2: SpeechRule): boolean { let prec1 = rule1.precondition; let prec2 = rule2.precondition; if (prec1.query !== prec2.query) { return false; } return BaseRuleStore.compareStaticConstraints_( prec1.constraints, prec2.constraints); } /** * @override */ constructor() { this.parseMethods = { 'Rule': this.defineRule, 'Generator': this.generateRules, 'Action': this.defineAction, 'Precondition': this.definePrecondition, 'Ignore': this.ignoreRules }; } /** * @override */ public defineRule(name: string, dynamic: string, action: string, prec: string, ...args: string[]) { let postc = this.parseAction(action); let fullPrec = this.parsePrecondition(prec, args); let dynamicCstr = this.parseCstr(dynamic); if (!(postc && fullPrec && dynamicCstr)) { console.error(`Rule Error: ${prec}, (${dynamic}): ${action}`); return null; } let rule = new SpeechRule(name, dynamicCstr, fullPrec, postc); rule.precondition.rank = this.rank++; this.addRule(rule); return rule; } /** * @override */ public addRule(rule: SpeechRule) { rule.context = this.context; this.speechRules_.unshift(rule); } /** * @override */ public deleteRule(rule: SpeechRule) { let index = this.speechRules_.indexOf(rule); if (index !== -1) { this.speechRules_.splice(index, 1); } } /** * @override */ public findRule(pred: (rule: SpeechRule) => boolean) { for (let i = 0, rule; rule = this.speechRules_[i]; i++) { if (pred(rule)) { return rule; } } return null; } /** * @override */ public findAllRules(pred: (rule: SpeechRule) => boolean) { return this.speechRules_.filter(pred); } /** * @override */ public evaluateDefault(node: Node) { let rest = node.textContent.slice(0); if (rest.match(/^\s+$/)) { // Nothing but whitespace: Ignore. return this.evaluateWhitespace(rest); } return this.evaluateString(rest); } /** * @override */ public evaluateWhitespace(_str: string): AuditoryDescription[] { return []; } /** * @override */ public evaluateCustom(str: string) { let trans = this.customTranscriptions[str]; return trans !== undefined ? AuditoryDescription.create( {'text': trans}, {adjust: true, translate: false}) : null; } /** * @override */ public evaluateCharacter(str: string) { return this.evaluateCustom(str) || AuditoryDescription.create( {'text': str}, {adjust: true, translate: true}); } /** * @override */ public abstract evaluateString(str: string): AuditoryDescription[]; /** * Function to initialize the store with speech rules. It is called by the * speech rule engine upon parametrization with this store. The function * allows us to define sets of rules in separate files while depending on * functionality that is defined in the rule store. Essentially it is a way * of getting around dependencies. */ public abstract initialize(): void; /** * Removes duplicates of the given rule from the rule store. Thereby * duplicates are identified by having the same precondition and dynamic * constraint. * @param rule The rule. */ public removeDuplicates(rule: SpeechRule) { for (let i = this.speechRules_.length - 1, oldRule; oldRule = this.speechRules_[i]; i--) { if (oldRule !== rule && rule.dynamicCstr.equal(oldRule.dynamicCstr) && BaseRuleStore.comparePreconditions_(oldRule, rule)) { this.speechRules_.splice(i, 1); } } } /** * @return Set of all speech rules in the store. */ public getSpeechRules(): SpeechRule[] { return this.speechRules_; } /** * Sets the speech rule set of the store. * @param rules New rule set. */ public setSpeechRules(rules: SpeechRule[]) { this.speechRules_ = rules; } /** * @return All preconditions in the rule store. For analysis purposes. */ public getPreconditions(): Map<string, Condition> { return this.preconditions; } /** * Default constraint parser that adds the locale to the rest constraint * (generally, domain.style). * @param cstr The constraint string. * @return The parsed constraint including locale. */ public parseCstr(cstr: string): DynamicCstr { try { // TODO: Have a parser that respects generators. return this.parser.parse( this.locale + '.' + this.modality + (this.domain ? '.' + this.domain : '') + '.' + cstr); } catch (err) { if (err.name === 'RuleError') { console.error( 'Rule Error ', `Illegal Dynamic Constraint: ${cstr}.`, err.message); return null; } else { throw err; } } } /** * Parses precondition by resolving generator rules. * @param query The query constraint. * @param rest The rest constraints. * @return The new precondition. */ public parsePrecondition(query: string, rest: string[]): Precondition { try { let queryCstr = this.parsePrecondition_(query); query = queryCstr[0]; let restCstr = queryCstr.slice(1); for (let cstr of rest) { restCstr = restCstr.concat(this.parsePrecondition_(cstr)); } return new Precondition(query, ...restCstr); } catch (err) { if (err.name === 'RuleError') { console.error('Rule Error ', `Illegal preconditions: ${query}, ${rest}.`, err.message); return null; } else { throw err; } } } /** * Parses a speech rule action. * @param action The action string. * @return The new action. */ public parseAction(action: string) { try { return Action.fromString(action); } catch (err) { if (err.name === 'RuleError') { console.error('Rule Error ', `Illegal action: ${action}.`, err.message); return null; } else { throw err; } } } /** * Parses a rule set definition. * @param ruleSet The * definition object. */ public parse(ruleSet: RulesJson) { this.modality = ruleSet.modality || this.modality; this.locale = ruleSet.locale || this.locale; this.domain = ruleSet.domain || this.domain; this.kind = ruleSet.kind || this.kind; // TODO (TS): Fix this to avoid casting! this.context.parse(ruleSet.functions as any || []); if (this.kind !== 'actions') { this.inheritRules(); } this.parseRules(ruleSet.rules || []); } /** * Parse a list of rules, each given as a list of strings. * @param rules The list of rules. */ public parseRules(rules: string[][]) { for (let i = 0, rule; rule = rules[i]; i++) { let type = rule[0]; let method = this.parseMethods[type]; if (type && method) { method.apply(this, rule.slice(1)); } } } /** * Parses rules generated by the given generator function. * @param generator Name of the generator function. */ public generateRules(generator: string) { let method = this.context.customGenerators.lookup(generator); if (method) { method(this); } } /** * @override */ public defineAction(name: string, action: string) { let postc: Action; try { // TODO: Have a parser that respects generators. postc = Action.fromString(action); } catch (err) { if (err.name === 'RuleError') { console.error('Action Error ', action, err.message); return; } else { throw err; } } let prec = this.getFullPreconditions(name); if (!prec) { console.error(`Action Error: No precondition for action ${name}`); return; } // Overwrite previously defined rules! this.ignoreRules(name); let regexp = new RegExp('^\\w+\\.\\w+\\.' + (this.domain ? '\\w+\\.' : '')); prec.conditions.forEach(([dynamic, prec]) => { // TODO: Work this out wrt. domain. let newDynamic = this.parseCstr( dynamic.toString().replace(regexp, '')); this.addRule(new SpeechRule(name, newDynamic, prec, postc)); }); } /** * Returns a precondition from this or an inherited store, if one exists. * @param name The name of the condition. * @return The condition. */ public getFullPreconditions(name: string): Condition { let prec = this.preconditions.get(name); if (prec || !this.inherits) { return prec; } return this.inherits.getFullPreconditions(name); } /** * @override */ public definePrecondition(name: string, dynamic: string, prec: string, ...args: string[]) { let fullPrec = this.parsePrecondition(prec, args); let dynamicCstr = this.parseCstr(dynamic); if (!(fullPrec && dynamicCstr)) { console.error(`Precondition Error: ${prec}, (${dynamic})`); return; } fullPrec.rank = this.rank++; this.preconditions.set(name, new Condition(dynamicCstr, fullPrec)); } /** * Implements rule inheritance. */ public inheritRules() { if (!this.inherits || !this.inherits.getSpeechRules().length) { return; } let regexp = new RegExp('^\\w+\\.\\w+\\.' + (this.domain ? '\\w+\\.' : '')); this.inherits.getSpeechRules().forEach(rule => { // TODO: Work this out wrt. domain. let newDynamic = this.parseCstr( rule.dynamicCstr.toString().replace(regexp, '')); this.addRule(new SpeechRule(rule.name, newDynamic, rule.precondition, rule.action)); }); } /** * Deletes rules from the current store. This is important for omitting * inherited elements. * * @param name The name of the rule to be deleted. */ public ignoreRules(name: string, ...cstrs: string[]) { let rules = this.findAllRules((r: SpeechRule) => r.name === name); if (!cstrs.length) { rules.forEach(this.deleteRule.bind(this)); return; } let rest = []; for (let cstr of cstrs) { let dynamic = this.parseCstr(cstr); for (let rule of rules) { if (dynamic.equal(rule.dynamicCstr)) { this.deleteRule(rule); } else { rest.push(rule); } } rules = rest; rest = []; } } /** * Resolves a single precondition constraint. * @param cstr The precondition constraint. * @return Array of constraints, possibly generated. */ private parsePrecondition_(cstr: string): string[] { let generator = this.context.customGenerators.lookup(cstr); return generator ? generator() : [cstr]; } } // Conditions are clusters of preconditions that are used to define rules via // actions. export class Condition { private _conditions: [DynamicCstr, Precondition][] = []; private constraints: DynamicCstr[] = []; private allCstr: {[cond: string]: boolean} = {}; /** * * @param {DynamicCstr} dynamic * @param {Precondition} condition */ constructor(private base: DynamicCstr, condition: Precondition) { this.constraints.push(base); this.addCondition(base, condition); } public get conditions() { return this._conditions; } /** * Adds a dynamic constraint to a condition. This simply inherits the already * given preconditions. * * @param {DynamicCstr} dynamic */ public addConstraint(dynamic: DynamicCstr) { if (this.constraints.filter(cstr => cstr.equal(dynamic)).length) { return; } this.constraints.push(dynamic); let newConds: [DynamicCstr, Precondition][] = []; for (let [dyn, pre] of this.conditions) { if (this.base.equal(dyn)) { newConds.push([dynamic, pre]); } } this._conditions = this._conditions.concat(newConds); } public addBaseCondition(cond: Precondition) { this.addCondition(this.base, cond); } public addFullCondition(cond: Precondition) { this.constraints.forEach(cstr => this.addCondition(cstr, cond)); } private addCondition(dynamic: DynamicCstr, cond: Precondition) { let condStr = dynamic.toString() + ' ' + cond.toString(); if (this.allCstr.condStr) { return; } this.allCstr[condStr] = true; this._conditions.push([dynamic, cond]); } } export interface RulesJson { modality?: string; domain?: string; locale?: string; kind?: string; inherits?: string; functions?: {[key: string]: Function}; rules?: any[]; annotators?: any[]; }
the_stack
import { AbstractRawJavaScriptIndexCreationTask, GetTermsOperation, IDocumentStore } from "../../../../src"; import { disposeTestDocumentStore, testContext } from "../../../Utils/TestUtil"; import moment = require("moment"); import { AbstractRawJavaScriptTimeSeriesIndexCreationTask } from "../../../../src/Documents/Indexes/TimeSeries/AbstractRawJavaScriptTimeSeriesIndexCreationTask"; import { Employee } from "../../../Assets/Orders"; import { Company, User, Address } from "../../../Assets/Entities"; import { assertThat } from "../../../Utils/AssertExtensions"; import { RavenTestHelper } from "../../../Utils/RavenTestHelper"; describe("BasicTimeSeriesIndexes_JavaScript", function () { let store: IDocumentStore; beforeEach(async function () { store = await testContext.getDocumentStore(); }); afterEach(async () => await disposeTestDocumentStore(store)); it("basicMapIndexWithLoad", async () => { const now1 = new Date(); const now2 = moment().add(1, "second").toDate(); { const session = store.openSession(); const employee = new Employee(); employee.firstName = "John"; await session.store(employee, "employees/1"); const company = new Company(); await session.store(company, "companies/1"); session.timeSeriesFor(company, "HeartRate") .append(now1, 7.0, employee.id); const company2 = new Company(); await session.store(company2, "companies/11"); session.timeSeriesFor(company2, "HeartRate") .append(now1, 11, employee.id); await session.saveChanges(); } const timeSeriesIndex = new MyTsIndex_Load(); const indexName = timeSeriesIndex.getIndexName(); const indexDefinition = timeSeriesIndex.createIndexDefinition(); await timeSeriesIndex.execute(store); await testContext.waitForIndexing(store); let terms = await store.maintenance.send(new GetTermsOperation(indexName, "employee", null)); assertThat(terms) .hasSize(1) .contains("john"); { const session = store.openSession(); const employee = await session.load("employees/1", Employee); employee.firstName = "Bob"; await session.saveChanges(); } await testContext.waitForIndexing(store); terms = await store.maintenance.send(new GetTermsOperation(indexName, "employee", null)); assertThat(terms) .hasSize(1) .contains("bob"); { const session = store.openSession(); await session.delete("employees/1"); await session.saveChanges(); } await testContext.waitForIndexing(store); terms = await store.maintenance.send(new GetTermsOperation(indexName, "employee", null)); assertThat(terms) .hasSize(0); }); it("basicMapReduceIndexWithLoad", async function () { const today = testContext.utcToday(); { const session = store.openSession(); const address = new Address(); address.city = "NY"; await session.store(address, "addresses/1"); const user = new User(); user.addressId = address.id; await session.store(user, "users/1"); for (let i = 0; i < 10; i++) { session.timeSeriesFor(user, "heartRate") .append(today.clone().add(i, "hours").toDate(), 180 + i, address.id); } await session.saveChanges(); } const timeSeriesIndex = new AverageHeartRateDaily_ByDateAndCity(); const indexName = timeSeriesIndex.getIndexName(); const indexDefinition = timeSeriesIndex.createIndexDefinition(); await timeSeriesIndex.execute(store); await testContext.waitForIndexing(store); let terms = await store.maintenance.send(new GetTermsOperation(indexName, "heartBeat", null)); assertThat(terms) .hasSize(1) .contains("184.5"); terms = await store.maintenance.send(new GetTermsOperation(indexName, "date", null)); assertThat(terms) .hasSize(1); terms = await store.maintenance.send(new GetTermsOperation(indexName, "city", null)); assertThat(terms) .hasSize(1) .contains("ny"); terms = await store.maintenance.send(new GetTermsOperation(indexName, "count", null)); assertThat(terms) .hasSize(1) .contains("10"); { const session = store.openSession(); const address = await session.load("addresses/1", Address); address.city = "LA"; await session.saveChanges(); } await testContext.waitForIndexing(store); terms = await store.maintenance.send(new GetTermsOperation(indexName, "city", null)); assertThat(terms) .hasSize(1) .contains("la"); }); it("canMapAllTimeSeriesFromCollection", async function () { const now1 = new Date(); const now2 = moment().add(1, "seconds").toDate(); { const session = store.openSession(); const company = new Company(); await session.store(company, "companies/1"); session.timeSeriesFor(company, "heartRate") .append(now1, 7.0, "tag1"); session.timeSeriesFor(company, "likes") .append(now1, 3.0, "tag2"); await session.saveChanges(); } await new MyTsIndex_AllTimeSeries().execute(store); await testContext.waitForIndexing(store); const terms = await store.maintenance.send(new GetTermsOperation("MyTsIndex/AllTimeSeries", "heartBeat", null)); assertThat(terms) .hasSize(2) .contains("7") .contains("3"); }); it("basicMultiMapIndex", async function () { const now = testContext.utcToday(); const timeSeriesIndex = new MyMultiMapTsIndex(); await timeSeriesIndex.execute(store); { const session = store.openSession(); const company = new Company(); await session.store(company); session.timeSeriesFor(company, "heartRate") .append(now.toDate(), 2.5, "tag1"); session.timeSeriesFor(company, "heartRate2") .append(now.toDate(), 3.5, "tag2"); const user = new User(); await session.store(user); session.timeSeriesFor(user, "heartRAte") .append(now.toDate(), 4.5, "tag3"); await session.saveChanges(); } await testContext.waitForIndexing(store); { const session = store.openSession(); const results = await session.query(MyMultiMapTsIndexResult, MyMultiMapTsIndex) .all(); assertThat(results) .hasSize(3); } }); it("timeSeriesNamesFor", async function () { const now = testContext.utcToday(); { const index = new Companies_ByTimeSeriesNames(); await index.execute(store); { const session = store.openSession(); const company = new Company(); await session.store(company, "companies/1"); await session.saveChanges(); } await testContext.waitForIndexing(store); await RavenTestHelper.assertNoIndexErrors(store); let terms = await store.maintenance.send(new GetTermsOperation(index.getIndexName(), "names", null)); assertThat(terms) .hasSize(0); terms = await store.maintenance.send(new GetTermsOperation(index.getIndexName(), "names_IsArray", null)); assertThat(terms) .hasSize(1) .contains("true"); { const session = store.openSession(); const company = await session.load("companies/1", Company); session.timeSeriesFor(company, "heartRate") .append(now.toDate(), 2.5, "tag1"); session.timeSeriesFor(company, "heartRate2") .append(now.toDate(), 3.5, "tag2"); await session.saveChanges(); } await testContext.waitForIndexing(store); await RavenTestHelper.assertNoIndexErrors(store); terms = await store.maintenance.send(new GetTermsOperation(index.getIndexName(), "names", null)); assertThat(terms) .hasSize(2) .contains("heartrate") .contains("heartrate2"); terms = await store.maintenance.send(new GetTermsOperation(index.getIndexName(), "names_IsArray", null)); assertThat(terms) .hasSize(1) .contains("true"); } }); }); // tslint:disable-next-line:class-name class MyTsIndex_AllTimeSeries extends AbstractRawJavaScriptTimeSeriesIndexCreationTask { public constructor() { super(); this.maps.add("timeSeries.map('Companies', function (ts) {\n" + " return ts.Entries.map(entry => ({\n" + " heartBeat: entry.Values[0],\n" + " date: new Date(entry.Timestamp.getFullYear(), entry.Timestamp.getMonth(), entry.Timestamp.getDate()),\n" + " user: ts.documentId\n" + " }));\n" + " })"); } } // tslint:disable-next-line:class-name class MyTsIndex_Load extends AbstractRawJavaScriptTimeSeriesIndexCreationTask { public constructor() { super(); this.maps.add("timeSeries.map('Companies', 'HeartRate', function (ts) {\n" + "return ts.Entries.map(entry => ({\n" + " heartBeat: entry.Value,\n" + " date: new Date(entry.Timestamp.getFullYear(), entry.Timestamp.getMonth(), entry.Timestamp.getDate()),\n" + " user: ts.DocumentId,\n" + " employee: load(entry.Tag, 'Employees').firstName\n" + " }));\n" + "})"); } } // tslint:disable-next-line:class-name class AverageHeartRateDaily_ByDateAndCityResult { public heartBeat: number; public date: string; public city: string; public count: number; } // tslint:disable-next-line:class-name class AverageHeartRateDaily_ByDateAndCity extends AbstractRawJavaScriptTimeSeriesIndexCreationTask { public constructor() { super(); this.maps.add("timeSeries.map('Users', 'heartRate', function (ts) {\n" + "return ts.Entries.map(entry => ({\n" + " heartBeat: entry.Value,\n" + " date: new Date(entry.Timestamp.getFullYear(), entry.Timestamp.getMonth(), entry.Timestamp.getDate()),\n" + " city: load(entry.Tag, 'Addresses').city,\n" + " count: 1\n" + " }));\n" + "})"); this.reduce = "groupBy(r => ({ date: r.date, city: r.city }))\n" + " .aggregate(g => ({\n" + " heartBeat: g.values.reduce((total, val) => val.heartBeat + total, 0) / g.values.reduce((total, val) => val.count + total, 0),\n" + " date: g.key.date,\n" + " city: g.key.city\n" + " count: g.values.reduce((total, val) => val.count + total, 0)\n" + " }))"; } } class MyMultiMapTsIndexResult { public heartBeat: number; public date: string; public user: string; } class MyMultiMapTsIndex extends AbstractRawJavaScriptTimeSeriesIndexCreationTask { public constructor() { super(); this.maps.add("timeSeries.map('Companies', 'HeartRate', function (ts) {\n" + "return ts.Entries.map(entry => ({\n" + " HeartBeat: entry.Values[0],\n" + " Date: new Date(entry.Timestamp.getFullYear(), entry.Timestamp.getMonth(), entry.Timestamp.getDate()),\n" + " User: ts.DocumentId\n" + " }));\n" + "})"); this.maps.add("timeSeries.map('Companies', 'HeartRate2', function (ts) {\n" + "return ts.Entries.map(entry => ({\n" + " HeartBeat: entry.Values[0],\n" + " Date: new Date(entry.Timestamp.getFullYear(), entry.Timestamp.getMonth(), entry.Timestamp.getDate()),\n" + " User: ts.DocumentId\n" + " }));\n" + "})"); this.maps.add("timeSeries.map('Users', 'HeartRate', function (ts) {\n" + "return ts.Entries.map(entry => ({\n" + " HeartBeat: entry.Values[0],\n" + " Date: new Date(entry.Timestamp.getFullYear(), entry.Timestamp.getMonth(), entry.Timestamp.getDate()),\n" + " User: ts.DocumentId\n" + " }));\n" + "})"); } } // tslint:disable-next-line:class-name class Companies_ByTimeSeriesNames extends AbstractRawJavaScriptIndexCreationTask { public constructor() { super(); this.maps.add("map('Companies', function (company) {\n" + "return ({\n" + " names: timeSeriesNamesFor(company)\n" + "})\n" + "})"); } }
the_stack
* Function0 encapsulates a parameterless function * which returns a value. It adds some useful functions * to combine or transform functions. * * @param T the parameter type * @param U the result type */ export interface Function0<R> { /** * Invoke the function */ (): R; /** * Returns a new composed function which first calls the current * function and then the one you pass as parameter. */ andThen<V>(fn:(x:R)=>V): Function0<V>; } /** * Function1 encapsulates a function taking a single parameter * and returning a value. It adds some useful functions * to combine or transform functions. * * @param T the parameter type * @param U the result type */ export interface Function1<T,U> { /** * Invoke the function */ (x:T): U; /** * Returns a new composed function which first applies the current * function and then the one you pass as parameter. */ andThen<V>(fn:(x:U)=>V): Function1<T,V>; /** * */ compose<S>(fn:(x:S)=>T): Function1<S,U>; } /** * Function2 encapsulates a function taking two parameters * and returning a value. It adds some useful functions * to combine or transform functions. * * @param T1 the first parameter type * @param T2 the second parameter type * @param R the result type */ export interface Function2<T1,T2,R> { /** * Invoke the function */ (x:T1,y:T2): R; /** * Returns a new composed function which first applies the current * function and then the one you pass as parameter. */ andThen<V>(fn:(x:R)=>V): Function2<T1,T2,V>; /** * Returns a curried version of this function, for example: * * const plus5 = Function2.of( * (x:number,y:number)=>x+y) * .curried()(5); * assert.equal(6, plus5(1)); */ curried(): Function1<T1,Function1<T2,R>>; /** * Returns a version of this function which takes a tuple * instead of individual parameters. Useful in combination * with [[Vector.zip]] for instance. */ tupled(): Function1<[T1,T2],R>; /** * Returns a version of this function taking its parameters * in the reverse order. */ flipped(): Function2<T2,T1,R>; /** * Applies this function partially to one argument. * * const plus5 = Function2.of( * (x:number,y:number)=>x+y) * .apply1(5); * assert.equal(6, plus5(1)); */ apply1(param1:T1): Function1<T2,R>; } /** * Function3 encapsulates a function taking three parameters * and returning a value. It adds some useful functions * to combine or transform functions. * * @param T1 the first parameter type * @param T2 the second parameter type * @param T3 the third parameter type * @param R the result type */ export interface Function3<T1,T2,T3,R> { /** * Invoke the function */ (x:T1,y:T2,z:T3): R; /** * Returns a new composed function which first applies the current * function and then the one you pass as parameter. */ andThen<V>(fn:(x:R)=>V): Function3<T1,T2,T3,V>; /** * Returns a curried version of this function, for example: * See [[Function2.curried]] */ curried(): Function1<T1,Function1<T2,Function1<T3,R>>>; /** * Returns a version of this function which takes a tuple * instead of individual parameters. */ tupled(): Function1<[T1,T2,T3],R>; /** * Returns a version of this function taking its parameters * in the reverse order. */ flipped(): Function3<T3,T2,T1,R>; /** * Applies this function partially to one argument. * * const plus5 = Function3.of( * (x:number,y:number,z:number)=>x+y+z) * .apply1(5); * assert.equal(8, plus5(1,2)); */ apply1(param1:T1): Function2<T2,T3,R>; /** * Applies this function partially to two arguments. * * const plus54 = Function3.of( * (x:number,y:number,z:number)=>x+y+z) * .apply2(5,4); * assert.equal(12, plus54(3)); */ apply2(param1:T1, param2: T2): Function1<T3,R>; } /** * Function4 encapsulates a function taking four parameters * and returning a value. It adds some useful functions * to combine or transform functions. * * @param T1 the first parameter type * @param T2 the second parameter type * @param T3 the third parameter type * @param T4 the fourth parameter type * @param R the result type */ export interface Function4<T1,T2,T3,T4,R> { /** * Invoke the function */ (x:T1,y:T2,z:T3,a:T4): R; /** * Returns a new composed function which first applies the current * function and then the one you pass as parameter. */ andThen<V>(fn:(x:R)=>V): Function4<T1,T2,T3,T4,V>; /** * Returns a curried version of this function, for example: * See [[Function2.curried]] */ curried(): Function1<T1,Function1<T2,Function1<T3,Function1<T4,R>>>>; /** * Returns a version of this function which takes a tuple * instead of individual parameters. */ tupled(): Function1<[T1,T2,T3,T4],R>; /** * Returns a version of this function taking its parameters * in the reverse order. */ flipped(): Function4<T4,T3,T2,T1,R>; /** * Applies this function partially to one argument. * * const plus5 = Function4.of( * (x:number,y:number,z:number,a:number)=>x+y+z+a) * .apply1(5); * assert.equal(11, plus5(1,2,3)); */ apply1(param1:T1): Function3<T2,T3,T4,R>; /** * Applies this function partially to two arguments. * * const plus51 = Function4.of( * (x:number,y:number,z:number,a:number)=>x+y+z+a) * .apply2(5,1); * assert.equal(11, plus51(2,3)); */ apply2(param1:T1, param2: T2): Function2<T3,T4,R>; /** * Applies this function partially to three arguments. * * const plus512 = Function4.of( * (x:number,y:number,z:number,a:number)=>x+y+z+a) * .apply3(5,1,2); * assert.equal(11, plus512(3)); */ apply3(param1:T1, param2: T2, param3: T3): Function1<T4,R>; } /** * Function5 encapsulates a function taking give parameters * and returning a value. It adds some useful functions * to combine or transform functions. * * @param T1 the first parameter type * @param T2 the second parameter type * @param T3 the third parameter type * @param T4 the fourth parameter type * @param T5 the fifth parameter type * @param R the result type */ export interface Function5<T1,T2,T3,T4,T5,R> { /** * Invoke the function */ (x:T1,y:T2,z:T3,a:T4,b:T5): R; /** * Returns a new composed function which first applies the current * function and then the one you pass as parameter. */ andThen<V>(fn:(x:R)=>V): Function5<T1,T2,T3,T4,T5,V>; /** * Returns a curried version of this function, for example: * See [[Function2.curried]] */ curried(): Function1<T1,Function1<T2,Function1<T3,Function1<T4,Function1<T5,R>>>>>; /** * Returns a version of this function which takes a tuple * instead of individual parameters. */ tupled(): Function1<[T1,T2,T3,T4,T5],R>; /** * Returns a version of this function taking its parameters * in the reverse order. */ flipped(): Function5<T5,T4,T3,T2,T1,R>; /** * Applies this function partially to one argument. * * const plus5 = Function5.of( * (x:number,y:number,z:number,a:number,b:number)=>x+y+z+a+b) * .apply1(5); * assert.equal(15, plus5(1,2,3,4)); */ apply1(param1:T1): Function4<T2,T3,T4,T5,R>; /** * Applies this function partially to two arguments. * * const plus51 = Function5.of( * (x:number,y:number,z:number,a:number,b:number)=>x+y+z+a+b) * .apply2(5,1); * assert.equal(15, plus51(2,3,4)); */ apply2(param1:T1, param2: T2): Function3<T3,T4,T5,R>; /** * Applies this function partially to three arguments. * * const plus512 = Function5.of( * (x:number,y:number,z:number,a:number,b:number)=>x+y+z+a+b) * .apply3(5,1,2); * assert.equal(15, plus512(3,4)); */ apply3(param1:T1, param2: T2, param3: T3): Function2<T4,T5,R>; /** * Applies this function partially to four arguments. * * const plus5123 = Function5.of( * (x:number,y:number,z:number,a:number,b:number)=>x+y+z+a+b) * .apply4(5,1,2,3); * assert.equal(15, plus5123(4)); */ apply4(param1:T1, param2: T2, param3: T3, param4: T4): Function1<T5,R>; } /** * This is the type of the Function0 constant, which * offers some helper functions to deal * with [[Function0]] including * the ability to build [[Function0]] * from functions using [[Function0Static.of]]. * It also offers some builtin functions like [[Function0Static.constant]]. */ export class Function0Static { /** * The constant function of one parameter: * will always return the value you give, no * matter the parameter it's given. */ constant<R>(val:R): Function0<R> { return Function0.of(()=>val); } /** * Take a one-parameter function and lift it to become a [[Function1Static]], * enabling you to call [[Function1.andThen]] and other such methods on it. */ of<R>(fn:()=>R): Function0<R> { const r = <Function0<R>>(() => fn()); r.andThen = <V>(fn2:(x:R)=>V) => Function0.of(() => fn2(r())); return r; } } /** * The Function1 constant allows to call the [[Function0]] "static" methods. */ export const Function0 = new Function0Static(); /** * This is the type of the Function1 constant, which * offers some helper functions to deal * with [[Function1]] including * the ability to build [[Function1]] * from functions using [[Function1Static.of]]. * It also offers some builtin functions like [[Function1Static.constant]]. */ export class Function1Static { /** * The identity function. */ id<T>(): Function1<T,T> { return Function1.of((x:T)=>x); } /** * The constant function of one parameter: * will always return the value you give, no * matter the parameter it's given. */ constant<U,T>(val:T): Function1<U,T> { return Function1.of((x:U)=>val); } /** * Take a one-parameter function and lift it to become a [[Function1Static]], * enabling you to call [[Function1.andThen]] and other such methods on it. */ of<T,U>(fn:(x:T)=>U): Function1<T,U> { const r = <Function1<T,U>>(x => fn(x)); r.andThen = <V>(fn2:(x:U)=>V) => Function1.of((x:T) => fn2(r(x))); r.compose = <S>(fn2:(x:S)=>T) => Function1.of((x:S) => r(fn2(x))); return r; } } /** * The Function1 constant allows to call the [[Function1]] "static" methods. */ export const Function1 = new Function1Static(); /** * This is the type of the Function2 constant, which * offers some helper functions to deal * with [[Function2]] including * the ability to build [[Function2]] * from functions using [[Function2Static.of]]. * It also offers some builtin functions like [[Function2Static.constant]]. */ export class Function2Static { /** * The constant function of two parameters: * will always return the value you give, no * matter the parameters it's given. */ constant<T1,T2,R>(val:R): Function2<T1,T2,R> { return Function2.of((x:T1,y:T2)=>val); } /** * Take a two-parameter function and lift it to become a [[Function2]], * enabling you to call [[Function2.andThen]] and other such methods on it. */ of<T1,T2,R>(fn:(x:T1,y:T2)=>R): Function2<T1,T2,R> { const r = <Function2<T1,T2,R>>((x,y)=>fn(x,y)); r.andThen = <V>(fn2:(x:R)=>V) => Function2.of((x:T1,y:T2) => fn2(r(x,y))); r.curried = () => Function1.of((x:T1) => Function1.of((y:T2) => r(x,y))); r.tupled = () => Function1.of((pair:[T1,T2]) => r(pair[0],pair[1])); r.flipped = () => Function2.of((x:T2,y:T1) => r(y,x)); r.apply1 = (x:T1) => Function1.of((y:T2) => r(x,y)); return r; } } /** * The Function2 constant allows to call the [[Function2]] "static" methods. */ export const Function2 = new Function2Static(); /** * This is the type of the Function3 constant, which * offers some helper functions to deal * with [[Function3]] including * the ability to build [[Function3]] * from functions using [[Function3Static.of]]. * It also offers some builtin functions like [[Function3Static.constant]]. */ export class Function3Static { /** * The constant function of three parameters: * will always return the value you give, no * matter the parameters it's given. */ constant<T1,T2,T3,R>(val:R): Function3<T1,T2,T3,R> { return Function3.of((x:T1,y:T2,z:T3)=>val); } /** * Take a three-parameter function and lift it to become a [[Function3]], * enabling you to call [[Function3.andThen]] and other such methods on it. */ of<T1,T2,T3,R>(fn:(x:T1,y:T2,z:T3)=>R): Function3<T1,T2,T3,R> { const r = <Function3<T1,T2,T3,R>>((x,y,z)=>fn(x,y,z)); r.andThen = <V>(fn2:(x:R)=>V) => Function3.of((x:T1,y:T2,z:T3) => fn2(r(x,y,z))); r.curried = () => Function1.of((x:T1) => Function1.of((y:T2) => Function1.of((z:T3) => r(x,y,z)))); r.tupled = () => Function1.of((tuple:[T1,T2,T3]) => r(tuple[0],tuple[1],tuple[2])); r.flipped = () => Function3.of((x:T3,y:T2,z:T1) => r(z,y,x)); r.apply1 = (x:T1) => Function2.of((y:T2,z:T3) => r(x,y,z)); r.apply2 = (x:T1,y:T2) => Function1.of((z:T3) => r(x,y,z)); return r; } } /** * The Function3 constant allows to call the [[Function3]] "static" methods. */ export const Function3 = new Function3Static(); /** * This is the type of the Function4 constant, which * offers some helper functions to deal * with [[Function4]] including * the ability to build [[Function4]] * from functions using [[Function4Static.of]]. * It also offers some builtin functions like [[Function4Static.constant]]. */ export class Function4Static { /** * The constant function of four parameters: * will always return the value you give, no * matter the parameters it's given. */ constant<T1,T2,T3,T4,R>(val:R): Function4<T1,T2,T3,T4,R> { return Function4.of((x:T1,y:T2,z:T3,a:T4)=>val); } /** * Take a four-parameter function and lift it to become a [[Function4]], * enabling you to call [[Function4.andThen]] and other such methods on it. */ of<T1,T2,T3,T4,R>(fn:(x:T1,y:T2,z:T3,a:T4)=>R): Function4<T1,T2,T3,T4,R> { const r = <Function4<T1,T2,T3,T4,R>>((x,y,z,a)=>fn(x,y,z,a)); r.andThen = <V>(fn2:(x:R)=>V) => Function4.of((x:T1,y:T2,z:T3,a:T4) => fn2(r(x,y,z,a))); r.curried = () => Function1.of((x:T1) => Function1.of( (y:T2) => Function1.of((z:T3) => Function1.of((a:T4)=>r(x,y,z,a))))); r.tupled = () => Function1.of((tuple:[T1,T2,T3,T4]) => r(tuple[0],tuple[1],tuple[2],tuple[3])); r.flipped = () => Function4.of((x:T4,y:T3,z:T2,a:T1) => r(a,z,y,x)); r.apply1 = (x:T1) => Function3.of((y:T2,z:T3,a:T4) => r(x,y,z,a)); r.apply2 = (x:T1,y:T2) => Function2.of((z:T3,a:T4) => r(x,y,z,a)); r.apply3 = (x:T1,y:T2,z:T3) => Function1.of((a:T4) => r(x,y,z,a)); return r; } }; /** * The Function4 constant allows to call the [[Function4]] "static" methods. */ export const Function4 = new Function4Static(); /** * This is the type of the Function5 constant, which * offers some helper functions to deal * with [[Function5]] including * the ability to build [[Function5]] * from functions using [[Function5Static.of]]. * It also offers some builtin functions like [[Function5Static.constant]]. */ export class Function5Static { /** * The constant function of five parameters: * will always return the value you give, no * matter the parameters it's given. */ constant<T1,T2,T3,T4,T5,R>(val:R): Function5<T1,T2,T3,T4,T5,R> { return Function5.of((x:T1,y:T2,z:T3,a:T4,b:T5)=>val); } /** * Take a five-parameter function and lift it to become a [[Function5]], * enabling you to call [[Function5.andThen]] and other such methods on it. */ of<T1,T2,T3,T4,T5,R>(fn:(x:T1,y:T2,z:T3,a:T4,b:T5)=>R): Function5<T1,T2,T3,T4,T5,R> { const r = <Function5<T1,T2,T3,T4,T5,R>>((x,y,z,a,b)=>fn(x,y,z,a,b)); r.andThen = <V>(fn2:(x:R)=>V) => Function5.of((x:T1,y:T2,z:T3,a:T4,b:T5) => fn2(r(x,y,z,a,b))); r.curried = () => Function1.of((x:T1) => Function1.of( (y:T2) => Function1.of((z:T3) => Function1.of((a:T4)=>Function1.of((b:T5) => r(x,y,z,a,b)))))); r.tupled = () => Function1.of((tuple:[T1,T2,T3,T4,T5]) => r(tuple[0],tuple[1],tuple[2],tuple[3],tuple[4])); r.flipped = () => Function5.of((x:T5,y:T4,z:T3,a:T2,b:T1) => r(b,a,z,y,x)); r.apply1 = (x:T1) => Function4.of((y:T2,z:T3,a:T4,b:T5) => r(x,y,z,a,b)); r.apply2 = (x:T1,y:T2) => Function3.of((z:T3,a:T4,b:T5) => r(x,y,z,a,b)); r.apply3 = (x:T1,y:T2,z:T3) => Function2.of((a:T4,b:T5) => r(x,y,z,a,b)); r.apply4 = (x:T1,y:T2,z:T3,a:T4) => Function1.of((b:T5) => r(x,y,z,a,b)); return r; } } /** * The Function5 constant allows to call the [[Function5]] "static" methods. */ export const Function5 = new Function5Static();
the_stack
import postcss from 'postcss'; import whitespace from 'postcss-normalize-whitespace'; import autoprefixer from 'autoprefixer'; import nested from 'postcss-nested'; import { atomicifyRules } from '../atomicify-rules'; const transform = (css: TemplateStringsArray) => { const result = postcss([atomicifyRules(), whitespace, autoprefixer]).process(css[0], { from: undefined, }); return result.css; }; describe('atomicify rules', () => { beforeEach(() => { process.env.BROWSERSLIST = 'last 1 version'; }); it('should atomicify a single declaration', () => { const actual = transform` color: blue; `; expect(actual).toMatchInlineSnapshot(`"._syaz13q2{color:blue}"`); }); it('should prepend atomic class when nesting selector is prepended', () => { const actual = transform` [data-look='h100']& { display: block; } `; expect(actual).toMatchInlineSnapshot(`"[data-look='h100']._mi0g1ule{display:block}"`); }); it('should should atomicify multiple declarations', () => { const actual = transform` color: blue; font-size: 12px; `; expect(actual).toMatchInlineSnapshot(`"._syaz13q2{color:blue}._1wyb1fwx{font-size:12px}"`); }); it('should autoprefix atomic rules', () => { process.env.BROWSERSLIST = 'Edge 16'; const result = transform`user-select: none;`; expect(result).toMatchInlineSnapshot(`"._uiztglyw{-ms-user-select:none;user-select:none}"`); }); it('should double up class selector when two nesting selectors are found', () => { const result = transform` && { display: block; } `; expect(result).toMatchInlineSnapshot(`"._if291ule._if291ule{display:block}"`); }); it('should autoprefix atomic rules with multiple selectors', () => { process.env.BROWSERSLIST = 'Edge 16'; const result = transform` &:hover, &:focus { user-select: none; } `; expect(result).toMatchInlineSnapshot( `"._180hglyw:hover, ._1j5pglyw:focus{-ms-user-select:none;user-select:none}"` ); }); it('should autoprefix atrule atomic rules', () => { process.env.BROWSERSLIST = 'Edge 16'; const result = transform` @media (min-width: 30rem) { user-select: none; } `; expect(result).toMatchInlineSnapshot( `"@media (min-width: 30rem){._ufx4glyw{-ms-user-select:none;user-select:none}}"` ); }); it('should autoprefix atrule nested atomic rules', () => { process.env.BROWSERSLIST = 'Edge 16'; const result = transform` @media (min-width: 30rem) { div { user-select: none; } } `; expect(result).toMatchInlineSnapshot( `"@media (min-width: 30rem){._195xglyw div{-ms-user-select:none;user-select:none}}"` ); }); it('should autoprefix nested atrule atomic rules', () => { process.env.BROWSERSLIST = 'Edge 16'; const result = transform` @media (min-width: 30rem) { @media (min-width: 20rem) { user-select: none; } } `; expect(result).toMatchInlineSnapshot( `"@media (min-width: 30rem){@media (min-width: 20rem){._uf5eglyw{-ms-user-select:none;user-select:none}}}"` ); }); it('should callback with created class names', () => { const classes: string[] = []; const callback = (className: string) => { classes.push(className); }; const result = postcss([atomicifyRules({ callback }), whitespace]).process( ` display:block; text-align:center; @media (min-width: 30rem) { @media (min-width: 20rem) { user-select: none; } } div, span, :hover { user-select: none; } `, { from: undefined, } ); // Need to call this to fire the transformation. result.css; expect(classes).toMatchInlineSnapshot(` Array [ "_1e0c1ule", "_y3gn1h6o", "_uf5eglyw", "_2a8pglyw", "_18i0glyw", "_9iqnglyw", ] `); }); it('should atomicify a nested tag with class rule', () => { const actual = transform` div.primary { color: blue; } `; expect(actual).toMatchInlineSnapshot(`"._13ml13q2 div.primary{color:blue}"`); }); it('should atomicify a nested multi selector rule', () => { const actual = transform` div, span, li { color: blue; } `; expect(actual).toMatchInlineSnapshot( `"._65g013q2 div, ._1tjq13q2 span, ._thoc13q2 li{color:blue}"` ); }); it('should atomicify a multi nesting pseudo rule', () => { // Its assumed the pseudos will get a nesting selector from the nested plugin. const actual = transform` &:hover, &:focus { color: blue; } `; expect(actual).toMatchInlineSnapshot(`"._30l313q2:hover, ._f8pj13q2:focus{color:blue}"`); }); it('should atomicify a nested tag rule', () => { const actual = transform` div { color: blue; } `; expect(actual).toMatchInlineSnapshot(`"._65g013q2 div{color:blue}"`); }); it('should generate the same class hash for semantically same but different rules', () => { const firstActual = transform` &:first-child { color: blue; } `; const secondActual = transform` &:first-child { color: blue; } `; expect(firstActual).toEqual(secondActual); }); it('should double up selectors when using parent selector', () => { const actual = transform` && > * { margin-bottom: 1rem; } && > *:last-child { margin-bottom: 0; } `; expect(actual.split('}').join('}\n')).toMatchInlineSnapshot(` "._169r1j6v._169r1j6v > *{margin-bottom:1rem} ._1wzbidpf._1wzbidpf > *:last-child{margin-bottom:0} " `); }); it('should atomicify a rule when its selector has a nesting at the end', () => { // Its assumed the pseudos will get a nesting selector from the nested plugin. const actual = transform` &:first-child & { color: hotpink; } `; expect(actual).toMatchInlineSnapshot(`"._ngwg1q9v:first-child ._ngwg1q9v{color:hotpink}"`); }); it('should reference the atomic class with the nesting selector', () => { const actual = transform` & :first-child { color: blue; } `; expect(actual).toMatchInlineSnapshot(`"._prp213q2 :first-child{color:blue}"`); }); it('should atomicify a double tag rule', () => { const actual = transform` div span { color: blue; } `; expect(actual).toMatchInlineSnapshot(`"._8gsp13q2 div span{color:blue}"`); }); it('should atomicify a double tag with pseudos rule', () => { const actual = transform` div:hover span:active { color: blue; } `; expect(actual).toMatchInlineSnapshot(`"._f1kd13q2 div:hover span:active{color:blue}"`); }); it('should atomicify a nested tag pseudo rule', () => { const actual = transform` div:hover { color: blue; } `; expect(actual).toMatchInlineSnapshot(`"._1tui13q2 div:hover{color:blue}"`); }); it('should skip comments', () => { const actual = transform` /* hello world */ div:hover { /* hello world */ color: blue; } @media screen { /* hello world */ color: red; } `; expect(actual).toMatchInlineSnapshot( `"._1tui13q2 div:hover{color:blue}@media screen{._43475scu{color:red}}"` ); }); it('should blow up if a doubly nested rule was found', () => { expect(() => { transform` div { div { font-size: 12px; } } `; }).toThrow( 'atomicify-rules: <css input>:3:11: Nested rules need to be flattened first - run the "postcss-nested" plugin before this.' ); }); it('should not blow up if a doubly nested rule was found after nested plugin', () => { const result = postcss([nested, atomicifyRules(), whitespace, autoprefixer]).process( ` div { div { font-size: 12px; } } `, { from: undefined, } ); expect(result.css).toMatchInlineSnapshot(`"._73mn1fwx div div{font-size:12px}"`); }); it('should atomicify at rule styles', () => { const actual = transform` @media (min-width: 30rem) { display: block; font-size: 20px; } `; expect(actual).toMatchInlineSnapshot( `"@media (min-width: 30rem){._hi7c1ule{display:block}._1l5zgktf{font-size:20px}}"` ); }); it('should atomicify nested at rule styles', () => { const actual = transform` @media (min-width: 30rem) { @media (min-width: 20rem) { display: block; } } `; expect(actual).toMatchInlineSnapshot( `"@media (min-width: 30rem){@media (min-width: 20rem){._1l9l1ule{display:block}}}"` ); }); it('should atomicify at rule nested styles', () => { const actual = transform` @media (min-width: 30rem) { div { display: block; } } `; expect(actual).toMatchInlineSnapshot( `"@media (min-width: 30rem){._1v9q1ule div{display:block}}"` ); }); it('should atomicify double nested at rule nested styles', () => { const actual = transform` @media (min-width: 30rem) { @media (min-width: 20rem) { div { display: block; } } } `; expect(actual).toMatchInlineSnapshot( `"@media (min-width: 30rem){@media (min-width: 20rem){._1acs1ule div{display:block}}}"` ); }); it('should ignore unhanded at rules', () => { const actual = transform` @charset 'utf-8'; @import 'custom.css'; @namespace 'XML-namespace-URL'; @keyframes hello-world { from: { opacity: 0 } to { opacity: 1 } } @font-face { font-family: "Open Sans"; } `; expect(actual).toMatchInlineSnapshot( `"@charset 'utf-8';@import 'custom.css';@namespace 'XML-namespace-URL';@-webkit-keyframes hello-world{from:{opacity:0}to{opacity:1}}@keyframes hello-world{from:{opacity:0}to{opacity:1}}@font-face{font-family:\\"Open Sans\\"}"` ); }); it('should persist important flags in CSS', () => { const actual = transform` color: red!important; font-size: var(--font-size) !important; `; expect(actual).toMatchInlineSnapshot( `"._syaz1qpq{color:red!important}._1wybit0u{font-size:var(--font-size)!important}"` ); }); it('should generate a different hash when important flag is used', () => { const actual = transform` color: red!important; color: red; `; expect(actual).toMatchInlineSnapshot(`"._syaz1qpq{color:red!important}._syaz5scu{color:red}"`); }); });
the_stack
import { captureRejectionSymbol } from "../events.ts"; import Readable, { ReadableState } from "./readable.ts"; import Stream from "./stream.ts"; import Writable, { WritableState } from "./writable.ts"; import type { WritableEncodings } from "./writable.ts"; import { Buffer } from "../buffer.ts"; import { ERR_STREAM_ALREADY_FINISHED, ERR_STREAM_DESTROYED, ERR_UNKNOWN_ENCODING, } from "../_errors.ts"; import type { Encodings } from "../_utils.ts"; import createReadableStreamAsyncIterator from "./async_iterator.ts"; import type { ReadableStreamAsyncIterator } from "./async_iterator.ts"; import { _destroy, computeNewHighWaterMark, emitReadable, fromList, howMuchToRead, nReadingNextTick, updateReadableListening, } from "./readable_internal.ts"; import { kOnFinished, writeV } from "./writable_internal.ts"; import { endDuplex, finishMaybe, onwrite, readableAddChunk, } from "./duplex_internal.ts"; import { debuglog } from "../_util/_debuglog.ts"; export { errorOrDestroy } from "./duplex_internal.ts"; let debug = debuglog("stream", (fn) => { debug = fn; }); export interface DuplexOptions { allowHalfOpen?: boolean; autoDestroy?: boolean; decodeStrings?: boolean; defaultEncoding?: Encodings; destroy?( this: Duplex, error: Error | null, callback: (error: Error | null) => void, ): void; emitClose?: boolean; encoding?: Encodings; final?(this: Duplex, callback: (error?: Error | null) => void): void; highWaterMark?: number; objectMode?: boolean; read?(this: Duplex, size: number): void; readable?: boolean; readableHighWaterMark?: number; readableObjectMode?: boolean; writable?: boolean; writableCorked?: number; writableHighWaterMark?: number; writableObjectMode?: boolean; write?( this: Duplex, // deno-lint-ignore no-explicit-any chunk: any, encoding: Encodings, callback: (error?: Error | null) => void, ): void; writev?: writeV; } interface Duplex extends Readable, Writable {} /** * A duplex is an implementation of a stream that has both Readable and Writable * attributes and capabilities */ class Duplex extends Stream { allowHalfOpen = true; _final?: ( callback: (error?: Error | null | undefined) => void, ) => void; _readableState: ReadableState; _writableState: WritableState; _writev?: writeV | null; constructor(options?: DuplexOptions) { super(); const readableOptions = { autoDestroy: options?.autoDestroy, defaultEncoding: options?.defaultEncoding, destroy: options?.destroy as unknown as ( this: Readable, error: Error | null, callback: (error: Error | null) => void, ) => void, emitClose: options?.emitClose, encoding: options?.encoding, highWaterMark: options?.highWaterMark ?? options?.readableHighWaterMark, objectMode: options?.objectMode ?? options?.readableObjectMode, read: options?.read as unknown as (this: Readable) => void, }; const writableOptions = { autoDestroy: options?.autoDestroy, decodeStrings: options?.decodeStrings, defaultEncoding: options?.defaultEncoding, destroy: options?.destroy as unknown as ( this: Writable, error: Error | null, callback: (error: Error | null) => void, ) => void, emitClose: options?.emitClose, final: options?.final as unknown as ( this: Writable, callback: (error?: Error | null) => void, ) => void, highWaterMark: options?.highWaterMark ?? options?.writableHighWaterMark, objectMode: options?.objectMode ?? options?.writableObjectMode, write: options?.write as unknown as ( this: Writable, // deno-lint-ignore no-explicit-any chunk: any, encoding: string, callback: (error?: Error | null) => void, ) => void, writev: options?.writev as unknown as ( this: Writable, // deno-lint-ignore no-explicit-any chunks: Array<{ chunk: any; encoding: Encodings }>, callback: (error?: Error | null) => void, ) => void, }; this._readableState = new ReadableState(readableOptions); this._writableState = new WritableState( writableOptions, this as unknown as Writable, ); //Very important to override onwrite here, duplex implementation adds a check //on the readable side this._writableState.onwrite = onwrite.bind(undefined, this); if (options) { if (options.allowHalfOpen === false) { this.allowHalfOpen = false; } if (typeof options.destroy === "function") { this._destroy = options.destroy; } if (typeof options.final === "function") { this._final = options.final; } if (typeof options.read === "function") { this._read = options.read; } if (options.readable === false) { this.readable = false; this._readableState.readable = false; this._readableState.ended = true; this._readableState.endEmitted = true; } if (options.writable === false) { this.writable = false; this._writableState.writable = false; this._writableState.ending = true; this._writableState.ended = true; this._writableState.finished = true; } if (typeof options.write === "function") { this._write = options.write; } if (typeof options.writev === "function") { this._writev = options.writev; } } } [captureRejectionSymbol](err?: Error) { this.destroy(err); } [Symbol.asyncIterator](): ReadableStreamAsyncIterator { return createReadableStreamAsyncIterator(this); } _destroy( error: Error | null, callback: (error?: Error | null) => void, ): void { callback(error); } _read(size?: number) { return Readable.prototype._read.call(this, size); } _undestroy() { Writable.prototype._undestroy.call(this); Readable.prototype._undestroy.call(this); return; } destroy(err?: Error | null, cb?: (error?: Error | null) => void) { const r = this._readableState; const w = this._writableState; if (w.destroyed || r.destroyed) { if (typeof cb === "function") { cb(); } return this; } if (err) { // Avoid V8 leak, https://github.com/nodejs/node/pull/34103#issuecomment-652002364 err.stack; if (!w.errored) { w.errored = err; } if (!r.errored) { r.errored = err; } } w.destroyed = true; r.destroyed = true; this._destroy(err || null, (err) => { if (err) { // Avoid V8 leak, https://github.com/nodejs/node/pull/34103#issuecomment-652002364 err.stack; if (!w.errored) { w.errored = err; } if (!r.errored) { r.errored = err; } } w.closed = true; r.closed = true; if (typeof cb === "function") { cb(err); } if (err) { queueMicrotask(() => { const r = this._readableState; const w = this._writableState; if (!w.errorEmitted && !r.errorEmitted) { w.errorEmitted = true; r.errorEmitted = true; this.emit("error", err); } r.closeEmitted = true; if (w.emitClose || r.emitClose) { this.emit("close"); } }); } else { queueMicrotask(() => { const r = this._readableState; const w = this._writableState; r.closeEmitted = true; if (w.emitClose || r.emitClose) { this.emit("close"); } }); } }); return this; } isPaused() { return Readable.prototype.isPaused.call(this); } off = this.removeListener; on( event: "close" | "end" | "pause" | "readable" | "resume", listener: () => void, ): this; // deno-lint-ignore no-explicit-any on(event: "data", listener: (chunk: any) => void): this; on(event: "error", listener: (err: Error) => void): this; // deno-lint-ignore no-explicit-any on(event: string | symbol, listener: (...args: any[]) => void): this; on( ev: string | symbol, fn: | (() => void) // deno-lint-ignore no-explicit-any | ((chunk: any) => void) | ((err: Error) => void) // deno-lint-ignore no-explicit-any | ((...args: any[]) => void), ) { const res = super.on.call(this, ev, fn); const state = this._readableState; if (ev === "data") { state.readableListening = this.listenerCount("readable") > 0; if (state.flowing !== false) { this.resume(); } } else if (ev === "readable") { if (!state.endEmitted && !state.readableListening) { state.readableListening = state.needReadable = true; state.flowing = false; state.emittedReadable = false; if (state.length) { emitReadable(this); } else if (!state.reading) { queueMicrotask(() => nReadingNextTick(this)); } } } return res; } pause(): this { return Readable.prototype.pause.call(this) as this; } pipe<T extends Duplex | Writable>(dest: T, pipeOpts?: { end?: boolean }): T { // deno-lint-ignore ban-ts-comment // @ts-ignore return Readable.prototype.pipe.call(this, dest, pipeOpts); } // deno-lint-ignore no-explicit-any push(chunk: any, encoding?: Encodings): boolean { return readableAddChunk(this, chunk, encoding, false); } /** You can override either this method, or the async `_read` method */ read(n?: number) { debug("read", n); // Same as parseInt(undefined, 10), however V8 7.3 performance regressed // in this scenario, so we are doing it manually. if (n === undefined) { n = NaN; } const state = this._readableState; const nOrig = n; if (n > state.highWaterMark) { state.highWaterMark = computeNewHighWaterMark(n); } if (n !== 0) { state.emittedReadable = false; } if ( n === 0 && state.needReadable && ((state.highWaterMark !== 0 ? state.length >= state.highWaterMark : state.length > 0) || state.ended) ) { debug("read: emitReadable", state.length, state.ended); if (state.length === 0 && state.ended) { endDuplex(this); } else { emitReadable(this); } return null; } n = howMuchToRead(n, state); if (n === 0 && state.ended) { if (state.length === 0) { endDuplex(this); } return null; } let doRead = state.needReadable; debug("need readable", doRead); if ( state.length === 0 || state.length - (n as number) < state.highWaterMark ) { doRead = true; debug("length less than watermark", doRead); } if ( state.ended || state.reading || state.destroyed || state.errored || !state.constructed ) { doRead = false; debug("reading, ended or constructing", doRead); } else if (doRead) { debug("do read"); state.reading = true; state.sync = true; if (state.length === 0) { state.needReadable = true; } this._read(state.highWaterMark); state.sync = false; if (!state.reading) { n = howMuchToRead(nOrig, state); } } let ret; if ((n as number) > 0) { ret = fromList(n as number, state); } else { ret = null; } if (ret === null) { state.needReadable = state.length <= state.highWaterMark; n = 0; } else { state.length -= n as number; if (state.multiAwaitDrain) { (state.awaitDrainWriters as Set<Writable>).clear(); } else { state.awaitDrainWriters = null; } } if (state.length === 0) { if (!state.ended) { state.needReadable = true; } if (nOrig !== n && state.ended) { endDuplex(this); } } if (ret !== null && !state.errorEmitted && !state.closeEmitted) { state.dataEmitted = true; this.emit("data", ret); } return ret; } removeAllListeners( ev: | "close" | "data" | "end" | "error" | "pause" | "readable" | "resume" | symbol | undefined, ) { const res = super.removeAllListeners(ev); if (ev === "readable" || ev === undefined) { queueMicrotask(() => updateReadableListening(this)); } return res; } removeListener( event: "close" | "end" | "pause" | "readable" | "resume", listener: () => void, ): this; // deno-lint-ignore no-explicit-any removeListener(event: "data", listener: (chunk: any) => void): this; removeListener(event: "error", listener: (err: Error) => void): this; removeListener( event: string | symbol, // deno-lint-ignore no-explicit-any listener: (...args: any[]) => void, ): this; removeListener( ev: string | symbol, fn: | (() => void) // deno-lint-ignore no-explicit-any | ((chunk: any) => void) | ((err: Error) => void) // deno-lint-ignore no-explicit-any | ((...args: any[]) => void), ) { const res = super.removeListener.call(this, ev, fn); if (ev === "readable") { queueMicrotask(() => updateReadableListening(this)); } return res; } resume(): this { return Readable.prototype.resume.call(this) as this; } setEncoding(enc: Encodings): this { return Readable.prototype.setEncoding.call(this, enc) as this; } // deno-lint-ignore no-explicit-any unshift(chunk: any, encoding?: Encodings): boolean { return readableAddChunk(this, chunk, encoding, true); } unpipe(dest?: Writable): this { return Readable.prototype.unpipe.call(this, dest) as this; } wrap(stream: Stream): this { return Readable.prototype.wrap.call(this, stream) as this; } get readable(): boolean { const r = this._readableState; return !!r && r.readable && !r.destroyed && !r.errorEmitted && !r.endEmitted; } set readable(val: boolean) { if (this._readableState) { this._readableState.readable = val; } } get readableHighWaterMark(): number { return this._readableState.highWaterMark; } get readableBuffer() { return this._readableState && this._readableState.buffer; } get readableFlowing(): boolean | null { return this._readableState.flowing; } set readableFlowing(state: boolean | null) { if (this._readableState) { this._readableState.flowing = state; } } get readableLength() { return this._readableState.length; } get readableObjectMode() { return this._readableState ? this._readableState.objectMode : false; } get readableEncoding() { return this._readableState ? this._readableState.encoding : null; } get readableEnded() { return this._readableState ? this._readableState.endEmitted : false; } _write( // deno-lint-ignore no-explicit-any chunk: any, encoding: string, cb: (error?: Error | null) => void, ): void { return Writable.prototype._write.call(this, chunk, encoding, cb); } write( // deno-lint-ignore no-explicit-any chunk: any, x?: WritableEncodings | null | ((error: Error | null | undefined) => void), y?: ((error: Error | null | undefined) => void), ) { // deno-lint-ignore no-explicit-any return Writable.prototype.write.call(this, chunk, x as any, y); } cork() { return Writable.prototype.cork.call(this); } uncork() { return Writable.prototype.uncork.call(this); } setDefaultEncoding(encoding: string) { // node::ParseEncoding() requires lower case. if (typeof encoding === "string") { encoding = encoding.toLowerCase(); } if (!Buffer.isEncoding(encoding)) { throw new ERR_UNKNOWN_ENCODING(encoding); } this._writableState.defaultEncoding = encoding as Encodings; return this; } end(cb?: () => void): void; // deno-lint-ignore no-explicit-any end(chunk: any, cb?: () => void): void; // deno-lint-ignore no-explicit-any end(chunk: any, encoding: Encodings, cb?: () => void): void; end( // deno-lint-ignore no-explicit-any x?: any | (() => void), y?: Encodings | (() => void), z?: () => void, ) { const state = this._writableState; // deno-lint-ignore no-explicit-any let chunk: any | null; let encoding: Encodings | null; let cb: undefined | ((error?: Error) => void); if (typeof x === "function") { chunk = null; encoding = null; cb = x; } else if (typeof y === "function") { chunk = x; encoding = null; cb = y; } else { chunk = x; encoding = y as Encodings; cb = z; } if (chunk !== null && chunk !== undefined) { this.write(chunk, encoding); } if (state.corked) { state.corked = 1; this.uncork(); } let err: Error | undefined; if (!state.errored && !state.ending) { state.ending = true; debug("** Writable.end calling finishMaybe", state); finishMaybe(this, state, true); state.ended = true; } else if (state.finished) { err = new ERR_STREAM_ALREADY_FINISHED("end"); } else if (state.destroyed) { err = new ERR_STREAM_DESTROYED("end"); } if (typeof cb === "function") { if (err || state.finished) { queueMicrotask(() => { (cb as (error?: Error | undefined) => void)(err); }); } else { state[kOnFinished].push(cb); } } return this; } get destroyed() { if ( this._readableState === undefined || this._writableState === undefined ) { return false; } return this._readableState.destroyed && this._writableState.destroyed; } set destroyed(value: boolean) { if (this._readableState && this._writableState) { this._readableState.destroyed = value; this._writableState.destroyed = value; } } get writable() { const w = this._writableState; return !!w && w.writable !== false && !w.destroyed && !w.errored && !w.ending && !w.ended; } set writable(val) { if (this._writableState) { this._writableState.writable = !!val; } } get writableFinished() { return this._writableState ? this._writableState.finished : false; } get writableObjectMode() { return this._writableState ? this._writableState.objectMode : false; } get writableBuffer() { return this._writableState && this._writableState.getBuffer(); } get writableEnded() { return this._writableState ? this._writableState.ending : false; } get writableHighWaterMark() { return this._writableState && this._writableState.highWaterMark; } get writableCorked() { return this._writableState ? this._writableState.corked : 0; } get writableLength() { return this._writableState && this._writableState.length; } } export default Duplex;
the_stack
import { Localized } from "@fluent/react/compat"; import { FORM_ERROR } from "final-form"; import React, { FunctionComponent, useCallback, useState } from "react"; import { Form } from "react-final-form"; import { graphql } from "react-relay"; import useCommonTranslation, { COMMON_TRANSLATION, } from "coral-admin/helpers/useCommonTranslation"; import { useToggleState } from "coral-framework/hooks"; import { InvalidRequestError } from "coral-framework/lib/errors"; import { useMutation, withFragmentContainer } from "coral-framework/lib/relay"; import { GQLUSER_ROLE } from "coral-framework/schema"; import { Button, ButtonIcon, CallOut, Card, CardCloseButton, ClickOutside, Dropdown, DropdownButton, Flex, HorizontalGutter, ListGroup, ListGroupRow, Modal, Popover, Typography, } from "coral-ui/components/v2"; import { SiteModeratorActions_user } from "coral-admin/__generated__/SiteModeratorActions_user.graphql"; import { SiteModeratorActions_viewer } from "coral-admin/__generated__/SiteModeratorActions_viewer.graphql"; import ModalBodyText from "../ModalBodyText"; import ModalHeader from "../ModalHeader"; import ModalHeaderUsername from "../ModalHeaderUsername"; import DemoteUserMutation from "./DemoteUserMutation"; import PromoteUserMutation from "./PromoteUserMutation"; import UserRoleChangeButton from "./UserRoleChangeButton"; import UserRoleText from "./UserRoleText"; import styles from "./SiteModeratorActions.css"; interface Props { viewer: SiteModeratorActions_viewer; user: SiteModeratorActions_user; } const SiteModeratorActions: FunctionComponent<Props> = ({ viewer, user }) => { const promoteUser = useMutation(PromoteUserMutation); const demoteUser = useMutation(DemoteUserMutation); const notAvailableTranslation = useCommonTranslation( COMMON_TRANSLATION.NOT_AVAILABLE ); const [mode, setMode] = useState<"promote" | "demote" | null>(null); const [isModalVisible, , toggleModalVisibility] = useToggleState(); const [isPopoverVisible, , togglePopoverVisibility] = useToggleState(); const onPromote = useCallback(() => { setMode("promote"); togglePopoverVisibility(); toggleModalVisibility(); }, [toggleModalVisibility, togglePopoverVisibility]); const onDemote = useCallback(async () => { setMode("demote"); togglePopoverVisibility(); toggleModalVisibility(); }, [toggleModalVisibility, togglePopoverVisibility]); const onCancel = useCallback(() => { setMode(null); toggleModalVisibility(); }, [toggleModalVisibility]); const onSubmit = useCallback(async () => { try { if (mode === "promote") { await promoteUser({ userID: user.id }); } else if (mode === "demote") { await demoteUser({ userID: user.id }); } setMode(null); toggleModalVisibility(); return; } catch (err) { if (err instanceof InvalidRequestError) { return err.invalidArgs; } return { [FORM_ERROR]: err.message }; } }, [demoteUser, mode, promoteUser, toggleModalVisibility, user.id]); const viewerSites = viewer.moderationScopes?.sites || []; const userSites = user.moderationScopes?.sites || []; // These are sites that only the viewer has and the user does not. const uniqueViewerSites = viewerSites.filter( (s) => !userSites.find(({ id }) => s.id === id) ); // These are sites that only the user has and the viewer does not. const uniqueUserSites = userSites.filter( (s) => !viewerSites.find(({ id }) => s.id === id) ); // If the user is a site moderator and some of the sites on the user are the // same as the sites on the viewer, then we can demote this user. const canDemote = user.role === GQLUSER_ROLE.MODERATOR && !!user.moderationScopes?.scoped && userSites.some((s) => viewerSites.find(({ id }) => s.id === id)); // If the user is a site moderator, staff, or commenter and some of the sites // on the viewer are not on the user, then we can promote this user. const canPromote = ((user.role === GQLUSER_ROLE.MODERATOR && !!user.moderationScopes?.scoped) || user.role === GQLUSER_ROLE.STAFF || user.role === GQLUSER_ROLE.COMMENTER) && uniqueViewerSites.length > 0; const canPerformActions = canPromote || canDemote; if (!canPerformActions) { return ( <UserRoleText moderationScopesEnabled scoped={!!user.moderationScopes?.scoped} role={user.role} /> ); } return ( <> <Modal open={isModalVisible} onClose={onCancel}> {({ firstFocusableRef, lastFocusableRef }) => ( <Card className={styles.modal}> <Flex justifyContent="flex-end"> <CardCloseButton onClick={onCancel} ref={firstFocusableRef} /> </Flex> <Form onSubmit={onSubmit}> {({ handleSubmit, submitError, submitting }) => ( <form onSubmit={handleSubmit}> <HorizontalGutter spacing={3}> {mode === "promote" ? ( <Localized id="community-assignYourSitesTo" strong={<ModalHeaderUsername />} $username={user.username || notAvailableTranslation} > <ModalHeader> Assign your sites to{" "} <ModalHeaderUsername> {user.username} </ModalHeaderUsername> </ModalHeader> </Localized> ) : ( <Localized id="community-removeSiteModeratorPermissions"> <ModalHeader> Remove Site Moderator permissions </ModalHeader> </Localized> )} {submitError && ( <CallOut color="error" fullWidth> {submitError} </CallOut> )} {mode === "promote" ? ( <> <Localized id="community-siteModeratorsArePermitted"> <ModalBodyText> Site moderators are permitted to make moderation decisions and issue suspensions on the sites they are assigned. </ModalBodyText> </Localized> <ModalBodyText> <Localized id="community-assignThisUser"> <Typography variant="bodyCopyBold"> Assign this user to </Typography> </Localized> </ModalBodyText> </> ) : ( <Localized id="community-userNoLongerPermitted"> <ModalBodyText> User will no longer be permitted to make moderation decisions or assign suspensions on: </ModalBodyText> </Localized> )} <ListGroup> {viewerSites.map((site) => ( <ListGroupRow key={site.id}> <Typography>{site.name}</Typography> </ListGroupRow> ))} </ListGroup> {mode === "demote" && uniqueUserSites.length > 0 && ( <> <Localized id="community-stillHaveSiteModeratorPrivileges"> <ModalBodyText> They will still have Site Moderator privileges for: </ModalBodyText> </Localized> <ListGroup> {uniqueUserSites.map((site) => ( <ListGroupRow key={site.id}> <Typography>{site.name}</Typography> </ListGroupRow> ))} </ListGroup> </> )} <Flex justifyContent="flex-end" itemGutter="half"> <Localized id="community-siteModeratorModal-cancel"> <Button variant="flat" onClick={onCancel}> Cancel </Button> </Localized> {mode === "promote" ? ( <Localized id="community-siteModeratorModal-assign"> <Button type="submit" disabled={submitting} ref={lastFocusableRef} > Assign </Button> </Localized> ) : ( <Localized id="community-siteModeratorModal-remove"> <Button type="submit" color="alert" disabled={submitting} ref={lastFocusableRef} > Remove </Button> </Localized> )} </Flex> </HorizontalGutter> </form> )} </Form> </Card> )} </Modal> <Localized id="community-siteModeratorActions-popover" attrs={{ description: true }} > <Popover id="community-siteModeratorActions" placement="bottom-start" description="A dropdown to promote/demote a user to/from sites" visible={isPopoverVisible} body={ <ClickOutside onClickOutside={togglePopoverVisibility}> <Dropdown> {canPromote && (user.role === GQLUSER_ROLE.MODERATOR ? ( <Localized id="community-assignMySites"> <DropdownButton onClick={onPromote}> Assign my sites </DropdownButton> </Localized> ) : ( <UserRoleChangeButton role={GQLUSER_ROLE.MODERATOR} scoped moderationScopesEnabled onClick={onPromote} /> ))} {canDemote && ( <Localized id="community-removeMySites"> <DropdownButton onClick={onDemote}> Remove my sites </DropdownButton> </Localized> )} </Dropdown> </ClickOutside> } > {({ ref }) => ( <Localized id="community-changeRoleButton" attrs={{ "aria-label": true }} > <Button aria-label="Change role" className={styles.button} onClick={togglePopoverVisibility} uppercase={false} size="large" color="mono" ref={ref} variant="text" > <UserRoleText moderationScopesEnabled scoped={!!user.moderationScopes?.scoped} role={user.role} /> <ButtonIcon size="lg"> {isPopoverVisible ? "arrow_drop_up" : "arrow_drop_down"} </ButtonIcon> </Button> </Localized> )} </Popover> </Localized> </> ); }; const enhanced = withFragmentContainer<Props>({ viewer: graphql` fragment SiteModeratorActions_viewer on User { id moderationScopes { sites { id name } } } `, user: graphql` fragment SiteModeratorActions_user on User { id username role moderationScopes { scoped sites { id name } } } `, })(SiteModeratorActions); export default enhanced;
the_stack
import { TSDocConfiguration, TSDocTagDefinition, TSDocTagSyntaxKind } from '@microsoft/tsdoc'; import * as path from 'path'; import { TSDocConfigFile } from '../TSDocConfigFile'; function getRelativePath(testPath: string): string { return path.relative(__dirname, testPath).split('\\').join('/'); } expect.addSnapshotSerializer({ // eslint-disable-next-line @typescript-eslint/no-explicit-any test(value: any) { return value instanceof TSDocConfigFile; }, // eslint-disable-next-line @typescript-eslint/no-explicit-any print(value: unknown, print: (value: any) => string, indent: any, options: any, colors: any): any { const configFile: TSDocConfigFile = value as TSDocConfigFile; return print({ tsdocSchema: configFile.tsdocSchema, filePath: getRelativePath(configFile.filePath), fileNotFound: configFile.fileNotFound, extendsPaths: configFile.extendsPaths, extendsFiles: configFile.extendsFiles, noStandardTags: configFile.noStandardTags, tagDefinitions: configFile.tagDefinitions, supportForTags: Array.from(configFile.supportForTags).map(([tagName, supported]) => ({ tagName, supported })), messages: configFile.log.messages, supportedHtmlElements: configFile.supportedHtmlElements, reportUnsupportedHtmlElements: configFile.reportUnsupportedHtmlElements, }); }, }); function testLoadingFolder(assetPath: string): TSDocConfigFile { return TSDocConfigFile.loadForFolder(path.join(__dirname, assetPath)); } test('Load p1', () => { expect(testLoadingFolder('assets/p1')).toMatchInlineSnapshot(` Object { "extendsFiles": Array [], "extendsPaths": Array [], "fileNotFound": false, "filePath": "assets/p1/tsdoc.json", "messages": Array [], "noStandardTags": undefined, "reportUnsupportedHtmlElements": undefined, "supportForTags": Array [], "supportedHtmlElements": undefined, "tagDefinitions": Array [], "tsdocSchema": "https://developer.microsoft.com/json-schemas/tsdoc/v0/tsdoc.schema.json", } `); }); test('Load p2', () => { expect(testLoadingFolder('assets/p2')).toMatchInlineSnapshot(` Object { "extendsFiles": Array [], "extendsPaths": Array [], "fileNotFound": true, "filePath": "assets/p2/tsdoc.json", "messages": Array [ ParserMessage { "_text": undefined, "docNode": undefined, "messageId": "tsdoc-config-file-not-found", "textRange": TextRange { "buffer": "", "end": 0, "pos": 0, }, "tokenSequence": undefined, "unformattedText": "File not found", }, ], "noStandardTags": undefined, "reportUnsupportedHtmlElements": undefined, "supportForTags": Array [], "supportedHtmlElements": undefined, "tagDefinitions": Array [], "tsdocSchema": "", } `); }); test('Load p3', () => { expect(testLoadingFolder('assets/p3')).toMatchInlineSnapshot(` Object { "extendsFiles": Array [ Object { "extendsFiles": Array [], "extendsPaths": Array [], "fileNotFound": false, "filePath": "assets/p3/base1/tsdoc-base1.json", "messages": Array [], "noStandardTags": undefined, "reportUnsupportedHtmlElements": undefined, "supportForTags": Array [ Object { "supported": true, "tagName": "@base1", }, ], "supportedHtmlElements": undefined, "tagDefinitions": Array [ TSDocTagDefinition { "allowMultiple": false, "standardization": "None", "syntaxKind": 2, "tagName": "@base1", "tagNameWithUpperCase": "@BASE1", }, ], "tsdocSchema": "https://developer.microsoft.com/json-schemas/tsdoc/v0/tsdoc.schema.json", }, Object { "extendsFiles": Array [], "extendsPaths": Array [], "fileNotFound": false, "filePath": "assets/p3/base2/tsdoc-base2.json", "messages": Array [], "noStandardTags": undefined, "reportUnsupportedHtmlElements": undefined, "supportForTags": Array [ Object { "supported": false, "tagName": "@base2", }, ], "supportedHtmlElements": undefined, "tagDefinitions": Array [ TSDocTagDefinition { "allowMultiple": false, "standardization": "None", "syntaxKind": 2, "tagName": "@base2", "tagNameWithUpperCase": "@BASE2", }, ], "tsdocSchema": "https://developer.microsoft.com/json-schemas/tsdoc/v0/tsdoc.schema.json", }, ], "extendsPaths": Array [ "./base1/tsdoc-base1.json", "./base2/tsdoc-base2.json", ], "fileNotFound": false, "filePath": "assets/p3/tsdoc.json", "messages": Array [], "noStandardTags": undefined, "reportUnsupportedHtmlElements": undefined, "supportForTags": Array [ Object { "supported": true, "tagName": "@base2", }, ], "supportedHtmlElements": undefined, "tagDefinitions": Array [ TSDocTagDefinition { "allowMultiple": false, "standardization": "None", "syntaxKind": 2, "tagName": "@root", "tagNameWithUpperCase": "@ROOT", }, ], "tsdocSchema": "https://developer.microsoft.com/json-schemas/tsdoc/v0/tsdoc.schema.json", } `); }); test('Load p4', () => { expect(testLoadingFolder('assets/p4')).toMatchInlineSnapshot(` Object { "extendsFiles": Array [ Object { "extendsFiles": Array [], "extendsPaths": Array [], "fileNotFound": false, "filePath": "assets/p4/node_modules/example-lib/dist/tsdoc-example.json", "messages": Array [], "noStandardTags": undefined, "reportUnsupportedHtmlElements": undefined, "supportForTags": Array [], "supportedHtmlElements": undefined, "tagDefinitions": Array [ TSDocTagDefinition { "allowMultiple": false, "standardization": "None", "syntaxKind": 2, "tagName": "@example", "tagNameWithUpperCase": "@EXAMPLE", }, ], "tsdocSchema": "https://developer.microsoft.com/json-schemas/tsdoc/v0/tsdoc.schema.json", }, ], "extendsPaths": Array [ "example-lib/dist/tsdoc-example.json", ], "fileNotFound": false, "filePath": "assets/p4/tsdoc.json", "messages": Array [], "noStandardTags": undefined, "reportUnsupportedHtmlElements": undefined, "supportForTags": Array [], "supportedHtmlElements": undefined, "tagDefinitions": Array [ TSDocTagDefinition { "allowMultiple": false, "standardization": "None", "syntaxKind": 2, "tagName": "@root", "tagNameWithUpperCase": "@ROOT", }, ], "tsdocSchema": "https://developer.microsoft.com/json-schemas/tsdoc/v0/tsdoc.schema.json", } `); }); test('Re-serialize p3', () => { const configFile: TSDocConfigFile = TSDocConfigFile.loadForFolder(path.join(__dirname, 'assets/p3')); expect(configFile.hasErrors).toBe(false); // This is the data from p3/tsdoc.json, ignoring its "extends" field. expect(configFile.saveToObject()).toMatchInlineSnapshot(` Object { "$schema": "https://developer.microsoft.com/json-schemas/tsdoc/v0/tsdoc.schema.json", "supportForTags": Object { "@base2": true, }, "tagDefinitions": Array [ Object { "syntaxKind": "modifier", "tagName": "@root", }, ], } `); }); test('Re-serialize p3 without defaults', () => { const parserConfiguration: TSDocConfiguration = new TSDocConfiguration(); parserConfiguration.clear(true); const defaultsConfigFile: TSDocConfigFile = TSDocConfigFile.loadFromParser(parserConfiguration); expect(defaultsConfigFile.hasErrors).toBe(false); // This is the default configuration created by the TSDocConfigFile constructor. expect(defaultsConfigFile.saveToObject()).toMatchInlineSnapshot(` Object { "$schema": "https://developer.microsoft.com/json-schemas/tsdoc/v0/tsdoc.schema.json", "noStandardTags": true, "reportUnsupportedHtmlElements": false, } `); const configFile: TSDocConfigFile = TSDocConfigFile.loadForFolder(path.join(__dirname, 'assets/p3')); expect(configFile.hasErrors).toBe(false); configFile.noStandardTags = true; configFile.configureParser(parserConfiguration); const mergedConfigFile: TSDocConfigFile = TSDocConfigFile.loadFromParser(parserConfiguration); // This is the result of merging p3/tsdoc.json, tsdoc-base1.json, tsdoc-base2.json, and // the TSDocConfiguration defaults. expect(mergedConfigFile.saveToObject()).toMatchInlineSnapshot(` Object { "$schema": "https://developer.microsoft.com/json-schemas/tsdoc/v0/tsdoc.schema.json", "noStandardTags": true, "reportUnsupportedHtmlElements": false, "supportForTags": Object { "@base1": true, "@base2": true, }, "tagDefinitions": Array [ Object { "syntaxKind": "modifier", "tagName": "@base1", }, Object { "syntaxKind": "modifier", "tagName": "@base2", }, Object { "syntaxKind": "modifier", "tagName": "@root", }, ], } `); }); test('Re-serialize p3 with defaults', () => { const parserConfiguration: TSDocConfiguration = new TSDocConfiguration(); const defaultsConfigFile: TSDocConfigFile = TSDocConfigFile.loadFromParser(parserConfiguration); expect(defaultsConfigFile.hasErrors).toBe(false); // This is the default configuration created by the TSDocConfigFile constructor. expect(defaultsConfigFile.saveToObject()).toMatchInlineSnapshot(` Object { "$schema": "https://developer.microsoft.com/json-schemas/tsdoc/v0/tsdoc.schema.json", "noStandardTags": true, "reportUnsupportedHtmlElements": false, "tagDefinitions": Array [ Object { "syntaxKind": "modifier", "tagName": "@alpha", }, Object { "syntaxKind": "modifier", "tagName": "@beta", }, Object { "syntaxKind": "block", "tagName": "@defaultValue", }, Object { "allowMultiple": true, "syntaxKind": "block", "tagName": "@decorator", }, Object { "syntaxKind": "block", "tagName": "@deprecated", }, Object { "syntaxKind": "modifier", "tagName": "@eventProperty", }, Object { "allowMultiple": true, "syntaxKind": "block", "tagName": "@example", }, Object { "syntaxKind": "modifier", "tagName": "@experimental", }, Object { "syntaxKind": "inline", "tagName": "@inheritDoc", }, Object { "syntaxKind": "modifier", "tagName": "@internal", }, Object { "syntaxKind": "inline", "tagName": "@label", }, Object { "allowMultiple": true, "syntaxKind": "inline", "tagName": "@link", }, Object { "syntaxKind": "modifier", "tagName": "@override", }, Object { "syntaxKind": "modifier", "tagName": "@packageDocumentation", }, Object { "allowMultiple": true, "syntaxKind": "block", "tagName": "@param", }, Object { "syntaxKind": "block", "tagName": "@privateRemarks", }, Object { "syntaxKind": "modifier", "tagName": "@public", }, Object { "syntaxKind": "modifier", "tagName": "@readonly", }, Object { "syntaxKind": "block", "tagName": "@remarks", }, Object { "syntaxKind": "block", "tagName": "@returns", }, Object { "syntaxKind": "modifier", "tagName": "@sealed", }, Object { "syntaxKind": "block", "tagName": "@see", }, Object { "allowMultiple": true, "syntaxKind": "block", "tagName": "@throws", }, Object { "allowMultiple": true, "syntaxKind": "block", "tagName": "@typeParam", }, Object { "syntaxKind": "modifier", "tagName": "@virtual", }, ], } `); const configFile: TSDocConfigFile = TSDocConfigFile.loadForFolder(path.join(__dirname, 'assets/p3')); expect(configFile.hasErrors).toBe(false); configFile.configureParser(parserConfiguration); const mergedConfigFile: TSDocConfigFile = TSDocConfigFile.loadFromParser(parserConfiguration); // This is the result of merging p3/tsdoc.json, tsdoc-base1.json, tsdoc-base2.json, and // the TSDocConfiguration defaults. expect(mergedConfigFile.saveToObject()).toMatchInlineSnapshot(` Object { "$schema": "https://developer.microsoft.com/json-schemas/tsdoc/v0/tsdoc.schema.json", "noStandardTags": true, "reportUnsupportedHtmlElements": false, "supportForTags": Object { "@base1": true, "@base2": true, }, "tagDefinitions": Array [ Object { "syntaxKind": "modifier", "tagName": "@alpha", }, Object { "syntaxKind": "modifier", "tagName": "@beta", }, Object { "syntaxKind": "block", "tagName": "@defaultValue", }, Object { "allowMultiple": true, "syntaxKind": "block", "tagName": "@decorator", }, Object { "syntaxKind": "block", "tagName": "@deprecated", }, Object { "syntaxKind": "modifier", "tagName": "@eventProperty", }, Object { "allowMultiple": true, "syntaxKind": "block", "tagName": "@example", }, Object { "syntaxKind": "modifier", "tagName": "@experimental", }, Object { "syntaxKind": "inline", "tagName": "@inheritDoc", }, Object { "syntaxKind": "modifier", "tagName": "@internal", }, Object { "syntaxKind": "inline", "tagName": "@label", }, Object { "allowMultiple": true, "syntaxKind": "inline", "tagName": "@link", }, Object { "syntaxKind": "modifier", "tagName": "@override", }, Object { "syntaxKind": "modifier", "tagName": "@packageDocumentation", }, Object { "allowMultiple": true, "syntaxKind": "block", "tagName": "@param", }, Object { "syntaxKind": "block", "tagName": "@privateRemarks", }, Object { "syntaxKind": "modifier", "tagName": "@public", }, Object { "syntaxKind": "modifier", "tagName": "@readonly", }, Object { "syntaxKind": "block", "tagName": "@remarks", }, Object { "syntaxKind": "block", "tagName": "@returns", }, Object { "syntaxKind": "modifier", "tagName": "@sealed", }, Object { "syntaxKind": "block", "tagName": "@see", }, Object { "allowMultiple": true, "syntaxKind": "block", "tagName": "@throws", }, Object { "allowMultiple": true, "syntaxKind": "block", "tagName": "@typeParam", }, Object { "syntaxKind": "modifier", "tagName": "@virtual", }, Object { "syntaxKind": "modifier", "tagName": "@base1", }, Object { "syntaxKind": "modifier", "tagName": "@base2", }, Object { "syntaxKind": "modifier", "tagName": "@root", }, ], } `); }); test('Test noStandardTags for p5', () => { const configFile: TSDocConfigFile = TSDocConfigFile.loadForFolder(path.join(__dirname, 'assets/p5')); expect(configFile.hasErrors).toBe(false); const configuration: TSDocConfiguration = new TSDocConfiguration(); configFile.configureParser(configuration); // noStandardTags=true because tsdoc-base2.json overrides tsdoc-base1.json, and tsdoc.json is undefined expect(configuration.tagDefinitions.length).toEqual(0); }); test('Test noStandardTags for p6', () => { const configFile: TSDocConfigFile = TSDocConfigFile.loadForFolder(path.join(__dirname, 'assets/p6')); expect(configFile.hasErrors).toBe(false); const configuration: TSDocConfiguration = new TSDocConfiguration(); configFile.configureParser(configuration); // noStandardTags=false because tsdoc.json overrides tsdoc-base1.json expect(configuration.tagDefinitions.length).toBeGreaterThan(0); }); test('Test load p7', () => { expect(testLoadingFolder('assets/p7')).toMatchInlineSnapshot(` Object { "extendsFiles": Array [], "extendsPaths": Array [], "fileNotFound": false, "filePath": "assets/p7/tsdoc.json", "messages": Array [], "noStandardTags": undefined, "reportUnsupportedHtmlElements": undefined, "supportForTags": Array [], "supportedHtmlElements": Array [ "b", "u", ], "tagDefinitions": Array [], "tsdocSchema": "https://developer.microsoft.com/json-schemas/tsdoc/v0/tsdoc.schema.json", } `); }); test('p7 reportUnsupportedHtmlElements defaults to true when supportedHtmlElements is specified', () => { const configFile: TSDocConfigFile = TSDocConfigFile.loadForFolder(path.join(__dirname, 'assets/p7')); const flattened = new TSDocConfiguration(); configFile.updateParser(flattened); expect(flattened.validation.reportUnsupportedHtmlElements).toEqual(true); }); test('Test re-serialize p7', () => { const configFile: TSDocConfigFile = TSDocConfigFile.loadForFolder(path.join(__dirname, 'assets/p7')); expect(configFile.saveToObject()).toMatchInlineSnapshot(` Object { "$schema": "https://developer.microsoft.com/json-schemas/tsdoc/v0/tsdoc.schema.json", "supportedHtmlElements": Array [ "b", "u", ], } `); }); test('Test load p8', () => { expect(testLoadingFolder('assets/p8')).toMatchInlineSnapshot(` Object { "extendsFiles": Array [ Object { "extendsFiles": Array [], "extendsPaths": Array [], "fileNotFound": false, "filePath": "assets/p8/base1/tsdoc-base1.json", "messages": Array [], "noStandardTags": undefined, "reportUnsupportedHtmlElements": undefined, "supportForTags": Array [], "supportedHtmlElements": Array [ "span", "p", ], "tagDefinitions": Array [], "tsdocSchema": "https://developer.microsoft.com/json-schemas/tsdoc/v0/tsdoc.schema.json", }, ], "extendsPaths": Array [ "./base1/tsdoc-base1.json", ], "fileNotFound": false, "filePath": "assets/p8/tsdoc.json", "messages": Array [], "noStandardTags": undefined, "reportUnsupportedHtmlElements": undefined, "supportForTags": Array [], "supportedHtmlElements": Array [], "tagDefinitions": Array [], "tsdocSchema": "https://developer.microsoft.com/json-schemas/tsdoc/v0/tsdoc.schema.json", } `); }); test('p8 supportedHtmlElements are not inherited when an empty array is specified', () => { const configFile: TSDocConfigFile = TSDocConfigFile.loadForFolder(path.join(__dirname, 'assets/p8')); const flattened = new TSDocConfiguration(); configFile.updateParser(flattened); expect(flattened.supportedHtmlElements).toEqual([]); }); test('Test re-serialize p8', () => { const configFile: TSDocConfigFile = TSDocConfigFile.loadForFolder(path.join(__dirname, 'assets/p8')); expect(configFile.saveToObject()).toMatchInlineSnapshot(` Object { "$schema": "https://developer.microsoft.com/json-schemas/tsdoc/v0/tsdoc.schema.json", "supportedHtmlElements": Array [], } `); }); test('Test load p9', () => { expect(testLoadingFolder('assets/p9')).toMatchInlineSnapshot(` Object { "extendsFiles": Array [ Object { "extendsFiles": Array [], "extendsPaths": Array [], "fileNotFound": false, "filePath": "assets/p9/base1/tsdoc-base1.json", "messages": Array [], "noStandardTags": undefined, "reportUnsupportedHtmlElements": true, "supportForTags": Array [], "supportedHtmlElements": Array [ "span", "p", ], "tagDefinitions": Array [], "tsdocSchema": "https://developer.microsoft.com/json-schemas/tsdoc/v0/tsdoc.schema.json", }, ], "extendsPaths": Array [ "./base1/tsdoc-base1.json", ], "fileNotFound": false, "filePath": "assets/p9/tsdoc.json", "messages": Array [], "noStandardTags": undefined, "reportUnsupportedHtmlElements": false, "supportForTags": Array [], "supportedHtmlElements": undefined, "tagDefinitions": Array [], "tsdocSchema": "https://developer.microsoft.com/json-schemas/tsdoc/v0/tsdoc.schema.json", } `); }); test('p9 supportedHtmlElements are inherited', () => { const configFile: TSDocConfigFile = TSDocConfigFile.loadForFolder(path.join(__dirname, 'assets/p9')); const flattened = new TSDocConfiguration(); configFile.updateParser(flattened); expect(flattened.supportedHtmlElements).toEqual(['span', 'p']); }); test('p9 reportUnsupportedHtmlElements is overridden by "true"', () => { const configFile: TSDocConfigFile = TSDocConfigFile.loadForFolder(path.join(__dirname, 'assets/p9')); const flattened = new TSDocConfiguration(); configFile.updateParser(flattened); expect(flattened.validation.reportUnsupportedHtmlElements).toEqual(false); }); test('Test re-serialize p9', () => { const configFile: TSDocConfigFile = TSDocConfigFile.loadForFolder(path.join(__dirname, 'assets/p9')); expect(configFile.saveToObject()).toMatchInlineSnapshot(` Object { "$schema": "https://developer.microsoft.com/json-schemas/tsdoc/v0/tsdoc.schema.json", "reportUnsupportedHtmlElements": false, } `); }); test('p10 reportUnsupportedHtmlElements is overridden by "false"', () => { const configFile: TSDocConfigFile = TSDocConfigFile.loadForFolder(path.join(__dirname, 'assets/p10')); const flattened = new TSDocConfiguration(); configFile.updateParser(flattened); expect(flattened.validation.reportUnsupportedHtmlElements).toEqual(true); }); test('p11 reportUnsupportedHtmlElements is handled correctly with multiple parent configs', () => { const configFile: TSDocConfigFile = TSDocConfigFile.loadForFolder(path.join(__dirname, 'assets/p11')); const flattened = new TSDocConfiguration(); configFile.updateParser(flattened); expect(flattened.validation.reportUnsupportedHtmlElements).toEqual(true); }); test('p12 reportUnsupportedHtmlElements can be set to false, even when "supportedHtmlElements" is present', () => { const configFile: TSDocConfigFile = TSDocConfigFile.loadForFolder(path.join(__dirname, 'assets/p12')); const flattened = new TSDocConfiguration(); configFile.updateParser(flattened); expect(flattened.validation.reportUnsupportedHtmlElements).toEqual(false); }); test('Test loadFromObject()', () => { const configuration: TSDocConfiguration = new TSDocConfiguration(); configuration.clear(true); configuration.addTagDefinitions([ new TSDocTagDefinition({ syntaxKind: TSDocTagSyntaxKind.ModifierTag, tagName: '@tag1' }), new TSDocTagDefinition({ syntaxKind: TSDocTagSyntaxKind.BlockTag, tagName: '@tag2', allowMultiple: true }), new TSDocTagDefinition({ syntaxKind: TSDocTagSyntaxKind.InlineTag, tagName: '@tag3', allowMultiple: true }), ]); configuration.setSupportForTag(configuration.tagDefinitions[0], true); const configFile: TSDocConfigFile = TSDocConfigFile.loadFromParser(configuration); expect(configFile.hasErrors).toBe(false); const jsonObject: unknown = configFile.saveToObject(); const configFile2: TSDocConfigFile = TSDocConfigFile.loadFromObject(jsonObject); expect(configFile2.hasErrors).toBe(false); const jsonObject2: unknown = configFile2.saveToObject(); expect(jsonObject2).toMatchInlineSnapshot(` Object { "$schema": "https://developer.microsoft.com/json-schemas/tsdoc/v0/tsdoc.schema.json", "noStandardTags": true, "reportUnsupportedHtmlElements": false, "supportForTags": Object { "@tag1": true, }, "tagDefinitions": Array [ Object { "syntaxKind": "modifier", "tagName": "@tag1", }, Object { "allowMultiple": true, "syntaxKind": "block", "tagName": "@tag2", }, Object { "allowMultiple": true, "syntaxKind": "inline", "tagName": "@tag3", }, ], } `); expect(jsonObject2).toStrictEqual(jsonObject); }); test('Test loadFromObject() with extends', () => { const configuration: TSDocConfiguration = new TSDocConfiguration(); configuration.clear(true); const configFile: TSDocConfigFile = TSDocConfigFile.loadFromParser(configuration); expect(configFile.hasErrors).toBe(false); const jsonObject: unknown = configFile.saveToObject(); // eslint-disable-next-line (jsonObject as any)['extends'] = ['./some-file.json']; expect(() => { TSDocConfigFile.loadFromObject(jsonObject); }).toThrowError('The "extends" field cannot be used with TSDocConfigFile.loadFromObject()'); });
the_stack
import type { UnusedInterfaceTypeDef } from './kitchen-sink-definitions' import type { core } from 'nexus' export interface InputType { answer?: number | null // Int key: string // String! nestedInput?: InputType2 | null // InputType2 } export interface InputType2 { answer?: number | null // Int key: string // String! someDate: NexusGenScalars['Date'] // Date! } export interface NestedType { veryNested?: string | null // String } export interface SomeArg { arg?: NestedType | null // NestedType someField?: string | null // String } export interface NexusGenInputs { InputType: InputType InputType2: InputType2 NestedType: NestedType SomeArg: SomeArg } export interface NexusGenEnums {} export interface NexusGenScalars { String: string Int: number Float: number Boolean: boolean ID: string Date: Date } export interface NexusGenObjects { BooleanConnection: { // root type edges?: Array<NexusGenRootTypes['BooleanEdge'] | null> | null // [BooleanEdge] pageInfo: NexusGenRootTypes['PageInfo'] // PageInfo! } BooleanEdge: { // root type cursor: string // String! node?: boolean | null // Boolean } ComplexObject: { // root type id?: string | null // ID } DateConnection: { // root type edges?: Array<NexusGenRootTypes['DateEdge'] | null> | null // [DateEdge] pageInfo: NexusGenRootTypes['PageInfo'] // PageInfo! } DateEdge: { // root type cursor: string // String! node?: NexusGenScalars['Date'] | null // Date } Foo: { // root type name?: string | null // String ok?: boolean | null // Boolean } Mutation: {} PageInfo: { // root type endCursor?: string | null // String hasNextPage: boolean // Boolean! hasPreviousPage: boolean // Boolean! startCursor?: string | null // String } Query: {} SomeItem: { // root type id?: string | null // ID } SomeNode: { // root type data?: NexusGenRootTypes['SomeNode'] | null // SomeNode id?: string | null // ID } TestObj: { // root type a?: NexusGenRootTypes['Bar'] | null // Bar data?: NexusGenRootTypes['Node'] | null // Node item?: string | null // String ok?: boolean | null // Boolean } User: { // root type id?: string | null // ID name?: string | null // String } UserConnection: { // root type edges?: Array<NexusGenRootTypes['UserEdge'] | null> | null // [UserEdge] pageInfo: NexusGenRootTypes['PageInfo'] // PageInfo! } UserEdge: { // root type cursor: string // String! node?: NexusGenRootTypes['User'] | null // User } } export interface NexusGenInterfaces { Bar: core.Discriminate<'Foo', 'optional'> | core.Discriminate<'TestObj', 'optional'> Baz: core.Discriminate<'TestObj', 'optional'> Node: core.Discriminate<'SomeNode', 'required'> | core.Discriminate<'TestObj', 'required'> UnusedInterface: UnusedInterfaceTypeDef } export interface NexusGenUnions { TestUnion: core.Discriminate<'Foo', 'optional'> } export type NexusGenRootTypes = NexusGenInterfaces & NexusGenObjects & NexusGenUnions export type NexusGenAllTypes = NexusGenRootTypes & NexusGenScalars export interface NexusGenFieldTypes { BooleanConnection: { // field return type edges: Array<NexusGenRootTypes['BooleanEdge'] | null> | null // [BooleanEdge] pageInfo: NexusGenRootTypes['PageInfo'] // PageInfo! } BooleanEdge: { // field return type cursor: string // String! node: boolean | null // Boolean } ComplexObject: { // field return type id: string | null // ID } DateConnection: { // field return type edges: Array<NexusGenRootTypes['DateEdge'] | null> | null // [DateEdge] pageInfo: NexusGenRootTypes['PageInfo'] // PageInfo! } DateEdge: { // field return type cursor: string // String! node: NexusGenScalars['Date'] | null // Date } Foo: { // field return type argsTest: boolean | null // Boolean name: string | null // String ok: boolean | null // Boolean } Mutation: { // field return type ok: boolean | null // Boolean someMutationField: NexusGenRootTypes['Foo'] | null // Foo } PageInfo: { // field return type endCursor: string | null // String hasNextPage: boolean // Boolean! hasPreviousPage: boolean // Boolean! startCursor: string | null // String } Query: { // field return type asArgExample: string | null // String bar: NexusGenRootTypes['TestObj'] | null // TestObj booleanConnection: NexusGenRootTypes['BooleanConnection'] | null // BooleanConnection complexQuery: Array<NexusGenRootTypes['ComplexObject'] | null> | null // [ComplexObject] dateAsList: Array<NexusGenScalars['Date'] | null> | null // [Date] deprecatedConnection: NexusGenRootTypes['BooleanConnection'] // BooleanConnection! extended: NexusGenRootTypes['SomeItem'] | null // SomeItem getNumberOrNull: number | null // Int guardedConnection: NexusGenRootTypes['DateConnection'] | null // DateConnection inlineArgs: string | null // String inputAsArgExample: string | null // String protectedField: number | null // Int userConnectionAdditionalArgs: NexusGenRootTypes['UserConnection'] | null // UserConnection userConnectionBackwardOnly: NexusGenRootTypes['UserConnection'] | null // UserConnection userConnectionForwardOnly: NexusGenRootTypes['UserConnection'] | null // UserConnection usersConnectionNodes: NexusGenRootTypes['UserConnection'] | null // UserConnection usersConnectionResolve: NexusGenRootTypes['UserConnection'] | null // UserConnection } SomeItem: { // field return type id: string | null // ID } SomeNode: { // field return type data: NexusGenRootTypes['SomeNode'] | null // SomeNode id: string | null // ID } TestObj: { // field return type a: NexusGenRootTypes['Bar'] | null // Bar argsTest: boolean | null // Boolean data: NexusGenRootTypes['Node'] | null // Node id: string // ID! item: string | null // String ok: boolean | null // Boolean } User: { // field return type id: string | null // ID name: string | null // String } UserConnection: { // field return type edges: Array<NexusGenRootTypes['UserEdge'] | null> | null // [UserEdge] pageInfo: NexusGenRootTypes['PageInfo'] // PageInfo! } UserEdge: { // field return type cursor: string // String! node: NexusGenRootTypes['User'] | null // User } Bar: { // field return type argsTest: boolean | null // Boolean ok: boolean | null // Boolean } Baz: { // field return type a: NexusGenRootTypes['Bar'] | null // Bar ok: boolean | null // Boolean } Node: { // field return type data: NexusGenRootTypes['Node'] | null // Node id: string | null // ID } UnusedInterface: { // field return type ok: boolean | null // Boolean } } export interface NexusGenFieldTypeNames { BooleanConnection: { // field return type name edges: 'BooleanEdge' pageInfo: 'PageInfo' } BooleanEdge: { // field return type name cursor: 'String' node: 'Boolean' } ComplexObject: { // field return type name id: 'ID' } DateConnection: { // field return type name edges: 'DateEdge' pageInfo: 'PageInfo' } DateEdge: { // field return type name cursor: 'String' node: 'Date' } Foo: { // field return type name argsTest: 'Boolean' name: 'String' ok: 'Boolean' } Mutation: { // field return type name ok: 'Boolean' someMutationField: 'Foo' } PageInfo: { // field return type name endCursor: 'String' hasNextPage: 'Boolean' hasPreviousPage: 'Boolean' startCursor: 'String' } Query: { // field return type name asArgExample: 'String' bar: 'TestObj' booleanConnection: 'BooleanConnection' complexQuery: 'ComplexObject' dateAsList: 'Date' deprecatedConnection: 'BooleanConnection' extended: 'SomeItem' getNumberOrNull: 'Int' guardedConnection: 'DateConnection' inlineArgs: 'String' inputAsArgExample: 'String' protectedField: 'Int' userConnectionAdditionalArgs: 'UserConnection' userConnectionBackwardOnly: 'UserConnection' userConnectionForwardOnly: 'UserConnection' usersConnectionNodes: 'UserConnection' usersConnectionResolve: 'UserConnection' } SomeItem: { // field return type name id: 'ID' } SomeNode: { // field return type name data: 'SomeNode' id: 'ID' } TestObj: { // field return type name a: 'Bar' argsTest: 'Boolean' data: 'Node' id: 'ID' item: 'String' ok: 'Boolean' } User: { // field return type name id: 'ID' name: 'String' } UserConnection: { // field return type name edges: 'UserEdge' pageInfo: 'PageInfo' } UserEdge: { // field return type name cursor: 'String' node: 'User' } Bar: { // field return type name argsTest: 'Boolean' ok: 'Boolean' } Baz: { // field return type name a: 'Bar' ok: 'Boolean' } Node: { // field return type name data: 'Node' id: 'ID' } UnusedInterface: { // field return type name ok: 'Boolean' } } export interface FooArgsTestArgs { a: InputType | null // InputType } export interface MutationSomeMutationFieldArgs { id: string // ID! } export interface QueryAsArgExampleArgs { testAsArg: InputType // InputType! } export interface QueryBooleanConnectionArgs { after?: string | null // String first: number // Int! } export interface QueryComplexQueryArgs { count: number // Int! } export interface QueryDeprecatedConnectionArgs { after?: string | null // String before?: string | null // String first?: number | null // Int last?: number | null // Int } export interface QueryGetNumberOrNullArgs { a: number // Int! } export interface QueryGuardedConnectionArgs { after?: string | null // String first: number // Int! } export interface QueryInlineArgsArgs { someArg?: SomeArg | null // SomeArg } export interface QueryInputAsArgExampleArgs { testInput?: InputType | null // InputType testScalar?: string | null // String } export interface QueryUserConnectionAdditionalArgsArgs { after?: string | null // String first: number // Int! isEven?: boolean | null // Boolean } export interface QueryUserConnectionBackwardOnlyArgs { before?: string | null // String last: number // Int! } export interface QueryUserConnectionForwardOnlyArgs { after?: string | null // String first: number // Int! } export interface QueryUsersConnectionNodesArgs { after?: string | null // String before?: string | null // String first?: number | null // Int last?: number | null // Int } export interface QueryUsersConnectionResolveArgs { after?: string | null // String before?: string | null // String first?: number | null // Int last?: number | null // Int } export interface TestObjArgsTestArgs { a: InputType | null // InputType } export interface BarArgsTestArgs { a: InputType | null // InputType } export interface NexusGenArgTypes { Foo: { argsTest: FooArgsTestArgs } Mutation: { someMutationField: MutationSomeMutationFieldArgs } Query: { asArgExample: QueryAsArgExampleArgs booleanConnection: QueryBooleanConnectionArgs complexQuery: QueryComplexQueryArgs deprecatedConnection: QueryDeprecatedConnectionArgs getNumberOrNull: QueryGetNumberOrNullArgs guardedConnection: QueryGuardedConnectionArgs inlineArgs: QueryInlineArgsArgs inputAsArgExample: QueryInputAsArgExampleArgs userConnectionAdditionalArgs: QueryUserConnectionAdditionalArgsArgs userConnectionBackwardOnly: QueryUserConnectionBackwardOnlyArgs userConnectionForwardOnly: QueryUserConnectionForwardOnlyArgs usersConnectionNodes: QueryUsersConnectionNodesArgs usersConnectionResolve: QueryUsersConnectionResolveArgs } TestObj: { argsTest: TestObjArgsTestArgs } Bar: { argsTest: BarArgsTestArgs } } export interface NexusGenAbstractTypeMembers { TestUnion: 'Foo' Bar: 'Foo' | 'TestObj' Baz: 'TestObj' Node: 'SomeNode' | 'TestObj' } export interface NexusGenTypeInterfaces { Foo: 'Bar' SomeNode: 'Node' TestObj: 'Bar' | 'Baz' | 'Node' } export type NexusGenObjectNames = keyof NexusGenObjects export type NexusGenInputNames = keyof NexusGenInputs export type NexusGenEnumNames = never export type NexusGenInterfaceNames = keyof NexusGenInterfaces export type NexusGenScalarNames = keyof NexusGenScalars export type NexusGenUnionNames = keyof NexusGenUnions export type NexusGenObjectsUsingAbstractStrategyIsTypeOf = never export type NexusGenAbstractsUsingStrategyResolveType = 'Bar' | 'Baz' | 'TestUnion' export type NexusGenFeaturesConfig = { abstractTypeStrategies: { __typename: true resolveType: true isTypeOf: false } } export interface NexusGenTypes { context: any inputTypes: NexusGenInputs rootTypes: NexusGenRootTypes inputTypeShapes: NexusGenInputs & NexusGenEnums & NexusGenScalars argTypes: NexusGenArgTypes fieldTypes: NexusGenFieldTypes fieldTypeNames: NexusGenFieldTypeNames allTypes: NexusGenAllTypes typeInterfaces: NexusGenTypeInterfaces objectNames: NexusGenObjectNames inputNames: NexusGenInputNames enumNames: NexusGenEnumNames interfaceNames: NexusGenInterfaceNames scalarNames: NexusGenScalarNames unionNames: NexusGenUnionNames allInputTypes: NexusGenTypes['inputNames'] | NexusGenTypes['enumNames'] | NexusGenTypes['scalarNames'] allOutputTypes: | NexusGenTypes['objectNames'] | NexusGenTypes['enumNames'] | NexusGenTypes['unionNames'] | NexusGenTypes['interfaceNames'] | NexusGenTypes['scalarNames'] allNamedTypes: NexusGenTypes['allInputTypes'] | NexusGenTypes['allOutputTypes'] abstractTypes: NexusGenTypes['interfaceNames'] | NexusGenTypes['unionNames'] abstractTypeMembers: NexusGenAbstractTypeMembers objectsUsingAbstractStrategyIsTypeOf: NexusGenObjectsUsingAbstractStrategyIsTypeOf abstractsUsingStrategyResolveType: NexusGenAbstractsUsingStrategyResolveType features: NexusGenFeaturesConfig }
the_stack
module TDev.RT { //? A piece of text //@ stem("s") icon("fa-file-text-o") immutable isData builtin ctx(general,indexkey,cloudfield,walltap,enumerable,json) export module String_ { //? Returns a string collection that contains the substrings in this string that are delimited by elements of a specified string. //@ [separator].defl(",") //@ [result].writesMutable //@ robust export function split(self:string, separator:string) : Collection<string> { return Collection.mkStrings(self.split(separator)); } export function valueFromArtUrl(url: string) { var m = /^data:[^,]*base64,/i.exec(url) if (m) return Web.base64_decode(url.substring(m[0].length)); return null; } export function valueToArtUrl(value: string) { return "data:text/plain;base64," + Web.base64_encode(value); } export function fromArtUrl(url: string) { var value = valueFromArtUrl(url); if (value) return Promise.wrap(value); return ArtCache.getArtAsync(url) .then(dataUrl => { if (dataUrl) return Promise.as(valueFromArtUrl(dataUrl)); else Util.httpGetTextAsync(url) }) .then(txt => txt, e => { App.logEvent(App.ERROR, "art", lf("failed to load url {0}", url), undefined); return "" }); } //? Trims the string at the given length and adds ``...`` if necessary //@ [lim].defl(140) export function trim_overflow(self: string, lim: number): string { var v = self; if (v && v.length > lim) v = v.slice(0, lim) + "..."; return v; } //? Displays string on the wall export function post_to_wall(self:string, s:IStackFrame) { // backdoor for session testing if (dbg && self != null && self.indexOf("magic trap ") == 0) { var tests = new Revisions.SessionTests(s.rt); tests.runtest(self.substr(11)); return; } if (self != null) { if (s.rt.onCssPage()) s.rt.postUnboxedText(self, s.pc); else s.rt.postBoxedTextWithTap(self, self, s.pc); } } //? Returns the number of characters //@ robust export function count(self:string):number { return self.length; } //? Gets the charecter unicode value at a given index. Returns NaN if out of bounds export function code_at(self: string, index: number): number { return self.charCodeAt(index); } //? Gets the character at a specified index. Returns invalid if out of bounds. export function at(self:string, index:number):string { return index < 0 || index >= self.length ? undefined : self.charAt(index); } //? Returns a copy of this string converted to lowercase, using the casing rules of the current culture. //@ robust export function to_lower_case(self:string) : string { return self.toLocaleLowerCase(); } //? Returns a copy of this string converted to uppercase, using the casing rules of the current culture. //@ robust export function to_upper_case(self:string) : string { return self.toLocaleUpperCase(); } //? Use ``to_character_code`` instead //@ hidden export function to_unicode(self:string) : number { return self.length == 1 ? self.charCodeAt(0) : undefined; } //? Converts the first character into the character code number (unicode) export function to_character_code(self:string) : number { return self.length == 1 ? self.charCodeAt(0) : 0; } //? Compares two pieces of text //@ robust export function compare(self:string, other:string) : number { var r = self.localeCompare(other); if (r < 0) return -1; if (r > 0) return 1; return 0; } //? Concatenates two pieces of text //@ robust export function concat(self:string, other:string) : string { return self + other; } //? Concatenates two pieces of text //@ name("\u2225") infixPriority(6) //@ robust export function concat_op(self:string, other:string) : string { return self + other; } //@ robust export function concatAny(a:any, b:any) : string { function toStr(v:any) { if (v === undefined || v === null) return "(invalid)"; if (typeof v == "string") return v; if (typeof v == "JsonObject") return v.toString(); if (v.to_string) return v.to_string(); return v + ""; } return toStr(a) + toStr(b); } //? Returns a value indicating if the second string is contained //@ robust export function contains(self:string, value:string) : boolean { return self.indexOf(value) > -1; } //? Checks if two strings are the same //@ robust export function equals(self:string, other:string) : boolean { return self == other; } //? Determines whether the ending matches the specified string //@ robust export function ends_with(self:string, value:string) : boolean { var i = self.lastIndexOf(value); return i > -1 && i == (self.length - value.length); // TODO: more efficient implementation } //? Returns the index of the first occurence if found starting at a given position //@ robust export function index_of(self:string, value:string, start:number) : number { return self.indexOf(value, start); } //? Inserts a string at a given position export function insert(self: string, start: number, value: string): string { if (!value) return self; if (start < 0 || start > self.length) return undefined; return self.slice(0, start) + value + self.slice(start); } //? Indicates if the string is empty //@ robust export function is_empty(self:string) : boolean { return self.length == 0; } //? Indicates if the string matches a regular expression export function is_match_regex(self: string, pattern: string): boolean { var rx = new RegExp(pattern, ""); return rx.test(self); } //? Returns the index of the last occurence if found starting at a given position //@ robust export function last_index_of(self:string, value:string, start:number) : number { return self.lastIndexOf(value, start); } //? Gets the groups from the matching the regex expression (pattern). Returns an empty collection if no matches. export function match(self: string, pattern: string): Collection<string> { try { var rx = new RegExp(pattern, ""); var r = rx.exec(self); if (!r) return Collections.create_string_collection(); return Collection.mkStrings(Util.toArray(r)); } catch (e) { Time.log('invalid regex pattern: ' + pattern); return Collections.create_string_collection(); } } //? Gets the strings matching the regex expression (pattern) export function matches(self: string, pattern: string): Collection<string> { try { var rx = new RegExp(pattern, "g"); var r = self.match(rx); return Collection.mkStrings(r || []); } catch (e) { Time.log('invalid regex pattern: ' + pattern); return Collections.create_string_collection(); } } //? Returns the string with characters removed starting at a given index //@ robust export function remove(self:string, start:number) : string { return self.slice(0, start); } //? Returns a given string with a replacement //@ robust export function replace(self: string, old: string, new_: string): string { if (!old) return self; return self.split(old).join(new_); } //? Replace every match of the regex according to the replacement string export function replace_regex(self: string, pattern: string, replace: string): string { try { var rx = new RegExp(pattern, "g"); return self.replace(rx, replace); } catch (e) { Time.log('invalid regex pattern: ' + pattern); return undefined; } } //? Run `replacer` on every match of the regex export function replace_regex_with_converter(self: string, pattern: string, replace: StringConverter<Collection<string>>, s:IStackFrame): string { try { var rx = new RegExp(pattern, "g"); } catch (e) { Time.log('invalid regex pattern: ' + pattern); return undefined; } return self.replace(rx, (...args:string[]) => s.rt.runUserAction(replace, [Collection.fromArray(args, "string")])) } //? Determines whether the beginning matches the specified string export function starts_with(self:string, value:string) : boolean { return self.indexOf(value) == 0; // TODO: more efficient implementation } //? Returns a substring given a start index and a length export function substring(self:string, start:number, length:number) : string { return self.substr(start, length); } //? Removes all leading and trailing occurrences of a set of characters specified in a string from the current string. //@ [chars].defl(" \t") //@ robust export function trim(self: string, chars: string): string { if (!self || !chars) return self; return trim_start(trim_end(self, chars), chars); } //? Removes all leading occurrences of a set of characters specified in a string from the current string. //@ [chars].defl(" \t") //@ robust export function trim_start(self:string, chars:string) : string { if (!self || !chars) return self; var i = 0; for(; i < self.length && chars.indexOf(self[i]) > -1; i++) {} return self.substr(i); } //? Removes all trailing occurrences of a set of characters specified in a string from the current string. //@ [chars].defl(" \t") //@ robust export function trim_end(self: string, chars: string): string { if (!self || !chars) return self; var i = self.length; for(; i > 0 && chars.indexOf(self[i-1]) > -1; i--) {} return self.substring(0, i); } //? Parses the string as a time (12:30:12) and returns the number of seconds. export function to_time(self: string): number { if (self != null) { var s = trim(self, ' \t\n\r'); var m = s.match(/(\d{1,2})\s*:\s*(\d{1,2})\s*(:\s*(\d{1,2}))?\s*(pm|am)?/i); if (m) { var hours = parseFloat(m[1]); if (m[5] && /pm/i.test(m[5])) hours += 12; var minutes = parseFloat(m[2]); var seconds = m[4] ? parseFloat(m[4]) : 0; return Math_.clamp(0, 23, hours) * 3600 + Math_.clamp(0, 59, minutes) * 60 + seconds; } } return undefined; } //? Parses the string as a number export function to_number(self: string): number { // TODO: localization var r: number = undefined; if (/^\s*[-+]?\d*\.?(\d+([eE][-+]?\d+)?)?\s*$/.test(self)) { r = parseFloat(self); } else if (/^\s*[-+]?0x[a-z0-9]{1,4}\s*$/i.test(self)) { r = parseInt(self); } if (isNaN(r)) return undefined; return r; } //? Parses the string as a boolean export function to_boolean(self:string) : boolean { return self.trim().toLocaleLowerCase() == "true"; } //? Parses the string as a geo coordinate. export function to_location(self: string): Location_ { var s = trim_start(trim_end(self, ")}] "), "([{ "); var seps = ',;:'; for (var i = 0; i < seps.length; ++i) { var index = s.indexOf(seps[i]); if (index > -1) { var lat = to_number(s.substring(0, index)); var long = to_number(s.substring(index + 1)); if (lat && long && !isNaN(lat) && !isNaN(long)) { return Location_.mkShort(lat, long); } } } return undefined; } //? Shares the string (email, sms, facebook, social or '' to pick from a list) //@ uiAsync flow(SinkSharing) //@ [network].defl("social") export function share(self: string, network: string, r : ResumeCtx): void { HTML.showProgressNotification(lf("sharing text...")); ShareManager.shareTextAsync(self, network) .done(() => r.resume()); } // Stores text in the clipboard //? Stores text in the clipboard //@ flow(SinkClipboard) uiAsync export function copy_to_clipboard(self:string, r : ResumeCtx) : void { ShareManager.copyToClipboardAsync(self).done(() => r.resume()); } //? Parses the string as a date and time. export function to_datetime(self:string) : DateTime { return DateTime.parse(self); } //? Parses the string as a color. export function to_color(self: string): Color { return Color.fromHtml(self); } export function picker() { var inp = HTML.mkTextInput("text", lf("color")); return <IPicker>{ html: inp, validate: () => true, get: () => inp.value, set: function(v) { inp.value = v + "" } }; } //? Converts the value into a json data structure. export function to_json(self: string): JsonObject { return JsonObject.wrap(self); } } }
the_stack
declare module b2 { declare var waterParticle: any; declare var zombieParticle: any; declare var wallParticle: any; declare var springParticle: any; declare var elasticParticle: any; declare var viscousParticle: any; declare var powderParticle: any; declare var tensileParticle: any; declare var colorMixingParticle: any; declare var destructionListenerParticle: any; declare var barrierParticle: any; declare var staticPressureParticle: any; declare var reactiveParticle: any; declare var repulsiveParticle: any; declare var fixtureContactListenerParticle: any; declare var particleContactListenerParticle: any; declare var fixtureContactFilterParticle: any; declare var particleContactFilterParticle: any; declare class Vec2 { constructor(x: number, y: number); Set(newX: number, newY: number); Clone(); x: number y: number } declare class Filter { categoryBits: number maskBits: number groupIndex: number } declare class BodyDef { type: any position: b2.Vec2 linearDamping: number angularDamping: number fixedRotation: boolean bullet: boolean active: boolean userData: number filter: b2.Filter } declare class Fixture { SetDensity(density: number); filter: b2.Filter GetFriction(): number; SetFriction(friction: number): void; GetRestitution(): number; SetRestitution(restitution: number): void; TestPoint(worldPoint: b2.Vec2): boolean; GetBody(): b2.Body; } declare class MassData { } declare class Body { fixtures: b2.Fixture[] CreateFixtureFromShape(shape: b2.Shape, density: number): b2.Fixture; CreateFixtureFromDef(fixtureDefinition: b2.FixtureDef): b2.Fixture; GetPosition(): b2.Vec2; GetAngle(): number; GetMass(): number; GetInertia(): number; GetLocalCenter(): b2.Vec2; SetType(type: any); GetType(): any; SetBullet(flag: boolean); IsBullet(): boolean; SetSleepingAllowed(flag: boolean); IsSleepingAllowed(): boolean; SetAwake(flag: boolean); IsAwake(): boolean; SetActive(flag: boolean); IsActive(): boolean; SetFixedRotation(flag: boolean); IsFixedRotation(): boolean; GetWorldCenter(): b2.Vec2; GetLocalCenter(): b2.Vec2; ResetMassData(); DestroyFixture(fixture: b2.Fixture): void; SetLinearVelocity(lVelocity: b2.Vec2): void; GetLinearVelocity(): b2.Vec2; SetAngularVelocity(omega: number): void; GetAngularVelocity(): number; ApplyForce(force: b2.Vec2, point: b2.Vec2, wake: boolean): void; ApplyForceToCenter(force: b2.Vec2, wake: boolean): void; ApplyTorque(torque: number, wake: boolean): void; ApplyLinearImpulse(impulse: b2.Vec2, point: b2.Vec2, wake: boolean): void; ApplyAngularImpulse(impulse: number, wake: boolean): void; GetMass(): number; GetInertia(): number; GetWorldPoint(localPoint: b2.Vec2): b2.Vec2; GetLocalPoint(worldPoint: b2.Vec2): b2.Vec2; SetGravityScale(gScale: number): void; SetSleepingAllowed(flag: boolean): void; IsSleepingAllowed(): boolean; SetAwake(flag: boolean): void; IsAwake(): boolean; SetActive(flag: boolean): void; IsActive(): boolean; GetPositionX(): number; GetPositionY(): number; SetTransform(position: b2.Vec2, angle: number): void; SetLinearVelocity(v: b2.Vec2): void; GetLinearVelocity(): b2.Vec2; SetAngularVelocity(omega: number): void; GetAngularVelocity(): number; GetUserData(): number; } interface QueryCallback { ReportFixture(fixture: b2.Fixture): boolean; } declare class AABB { lowerBound: b2.Vec2 upperBound: b2.Vec2 } interface RayCastCallback { } declare class World { constructor(gravity: b2.Vec2); CreateBody(bodyDefinition: b2.BodyDef): b2.Body; CreateJoint(jointDefinition: b2.JointDef): b2.Joint; Step(timeStep: number, velocityIterations: number, positionIterations: number); SetContactListener(listener: b2.ContactListener): void; QueryAABB(callback: b2.QueryCallback, aabb: b2.AABB): void; RayCast(callback: b2.RayCastCallback, point1: b2.Vec2, point2: b2.Vec2): void; CreateParticleSystem(particleSystemDef: b2.ParticleSystemDef): b2.ParticleSystem; DestroyParticleSystem(particleSystem: b2.ParticleSystem): void; bodies: b2.Body[] particleSystems: b2.ParticleSystem[] } interface ContactListener { BeginContact(contact: b2.Contact): void; EndContact(contect: b2.Contact): void; PreSolve(contact: b2.Contact, manifold: b2.Manifold): void; PostSolve(contect: b2.Contact, manifold: b2.Manifold): void; } declare class Shape { radius: number GetPositionX(): number; GetPositionY(): number; SetPosition(x: number, y: number); } declare class EdgeShape extends b2.Shape { Set(v1: b2.Vec2, v2: b2.Vec2); } declare class ChainShape extends b2.Shape { CreateChain(points: Array<b2Vec2>); } declare class CircleShape extends b2.Shape { } declare class Transform { } declare class PolygonShape extends b2.Shape { SetAsBoxXY(halfWidth: number, halfHeight: number); SetAsBox(halfWidth: number, halfHeight: number); } declare var dynamicBody: any declare var kinematicBody: any declare var staticBody: any declare class FixtureDef { shape: any density: number friction: number restitution: number filter: b2.Filter } //Joint definitions declare class JointDef { collideConnected: boolean frequencyHz: number dampingRatio: number bodyA: b2.Body bodyB: b2.Body } declare class DistanceJointDef extends b2.JointDef { localAnchorA: b2.Vec2 localAnchorB: b2.Vec2 length: number InitializeAndCreate(bodyA: b2.Body, bodyB: b2.Body, anchorA: b2.Vec2, anchorB: b2.Vec2); } declare class RevoluteJointDef extends b2.JointDef { lowerAngle: number upperAngle: number enableLimit: boolean motorSpeed: number enableMotor: number localAnchorA: b2.Vec2 localAnchorB: b2.Vec2 InitializeAndCreate(bodyA: b2.Body, bodyB: b2.Body, sharedAnchorInWorldSpace: b2.Vec2); } declare class PrismaticJointDef extends b2.JointDef { lowerTranslation: number upperTranslation: number enableLimit: boolean maxMotorForce: number motorSpeed: number enableMotor: boolean } declare class PulleyJointDef extends b2.JointDef { } declare class GearJointDef extends b2.JointDef { } //Joint classes declare class Joint { } declare class DistanceJoint extends b2.Joint { } declare class RevoluteJoint extends b2.Joint { GetJointAngle(): number; GetJointSpeed(): number; GetMotorTorque(): number; SetMotorSpeed(speed: number); SetMaxMotorTorque(torque: number); } declare class PrismaticJoint extends b2.Joint { GetJointTranslation(): number; GetJointSpeed(): number; GetMotorForce(): number; SetMotorSpeed(speed: number); SetMotorForce(force: number); } declare class PulleyJoint extends b2.Joint { GetLengthA(): number; GetLengthB(): number; } declare class Contact { GetManifold(): b2.Manifold; GetFixtureA(): b2.Fixture; GetFixtureB(): b2.Fixture; SetEnabled(enabled: boolean): void; } declare class Manifold { } //Particles declare class ParticleColor { } declare class ParticleDef { flags: any position: b2.Vec2 color: b2.ParticleColor } declare class ParticleSystemDef { strictContactCheck = false; /** * Set the particle density. * See SetDensity for details. */ density = 1.0; /** * Change the particle gravity scale. Adjusts the effect of the * global gravity vector on particles. Default value is 1.0f. */ gravityScale = 1.0; /** * Particles behave as circles with this radius. In Box2D units. */ radius = 1.0; /** * Set the maximum number of particles. * By default, there is no maximum. The particle buffers can * continue to grow while b2World's block allocator still has * memory. * See SetMaxParticleCount for details. */ maxCount = 0; /** * Increases pressure in response to compression * Smaller values allow more compression */ pressureStrength = 0.005; /** * Reduces velocity along the collision normal * Smaller value reduces less */ dampingStrength = 1.0; /** * Restores shape of elastic particle groups * Larger values increase elastic particle velocity */ elasticStrength = 0.25; /** * Restores length of spring particle groups * Larger values increase spring particle velocity */ springStrength = 0.25; /** * Reduces relative velocity of viscous particles * Larger values slow down viscous particles more */ viscousStrength = 0.25; /** * Produces pressure on tensile particles * 0~0.2. Larger values increase the amount of surface tension. */ surfaceTensionPressureStrength = 0.2; /** * Smoothes outline of tensile particles * 0~0.2. Larger values result in rounder, smoother, * water-drop-like clusters of particles. */ surfaceTensionNormalStrength = 0.2; /** * Produces additional pressure on repulsive particles * Larger values repulse more * Negative values mean attraction. The range where particles * behave stably is about -0.2 to 2.0. */ repulsiveStrength = 1.0; /** * Produces repulsion between powder particles * Larger values repulse more */ powderStrength = 0.5; /** * Pushes particles out of solid particle group * Larger values repulse more */ ejectionStrength = 0.5; /** * Produces static pressure * Larger values increase the pressure on neighboring partilces * For a description of static pressure, see * http://en.wikipedia.org/wiki/Static_pressure#Static_pressure_in_fluid_dynamics */ staticPressureStrength = 0.2; /** * Reduces instability in static pressure calculation * Larger values make stabilize static pressure with fewer * iterations */ staticPressureRelaxation = 0.2; /** * Computes static pressure more precisely * See SetStaticPressureIterations for details */ staticPressureIterations = 8; /** * Determines how fast colors are mixed * 1.0f ==> mixed immediately * 0.5f ==> mixed half way each simulation step (see * b2World::Step()) */ colorMixingStrength = 0.5; /** * Whether to destroy particles by age when no more particles * can be created. See #b2ParticleSystem::SetDestructionByAge() * for more information. */ destroyByAge = true; /** * Granularity of particle lifetimes in seconds. By default * this is set to (1.0f / 60.0f) seconds. b2ParticleSystem uses * a 32-bit signed value to track particle lifetimes so the * maximum lifetime of a particle is (2^32 - 1) / (1.0f / * lifetimeGranularity) seconds. With the value set to 1/60 the * maximum lifetime or age of a particle is 2.27 years. */ lifetimeGranularity = 1.0 / 60.0; } declare class ParticleGroupDef { flags: any position: b2.Vec2 color: b2.ParticleColor angle: number angularVelocity: number shape: b2.Shape strength: number; groupFlags: number; } declare class ParticleGroup { SetGroupFlags(flags: any); GetGroupFlags(): any; DestroyParticles(callDestructionListener: boolean): void; } declare class ParticleSystem { CreateParticle(particleDefinition: b2.ParticleDef): number; DestroyParticlesInShape(shape: b2.Shape, transform: b2.Transform): void; CreateParticleGroup(particleGroupDefinition: b2.ParticleGroupDef); SetPaused(paused: boolean): void; SetParticleDestructionByAge(deletionByAge: boolean): void; SetParticleLifetime(particleIndex: number, lifetime: number): void; SetDensity(density: number): void; GetStuckCandidateCount(): number; GetStuckCandidates(): Array<number>; GetPositionBuffer(): Float32Array; GetColorBuffer(): Uint8Array; SetRadius(radious: number): void; } export class ParticleFlag { static b2_elasticParticle; } export class ParticleGroupFlag { static b2_solidParticleGroup; } }
the_stack
import * as Gio from "@gi-types/gio"; import * as GObject from "@gi-types/gobject"; import * as GLib from "@gi-types/glib"; export const ADDRESS_ANY_PORT: number; export const ADDRESS_FAMILY: string; export const ADDRESS_NAME: string; export const ADDRESS_PHYSICAL: string; export const ADDRESS_PORT: string; export const ADDRESS_PROTOCOL: string; export const ADDRESS_SOCKADDR: string; export const AUTH_DOMAIN_ADD_PATH: string; export const AUTH_DOMAIN_BASIC_AUTH_CALLBACK: string; export const AUTH_DOMAIN_BASIC_AUTH_DATA: string; export const AUTH_DOMAIN_DIGEST_AUTH_CALLBACK: string; export const AUTH_DOMAIN_DIGEST_AUTH_DATA: string; export const AUTH_DOMAIN_FILTER: string; export const AUTH_DOMAIN_FILTER_DATA: string; export const AUTH_DOMAIN_GENERIC_AUTH_CALLBACK: string; export const AUTH_DOMAIN_GENERIC_AUTH_DATA: string; export const AUTH_DOMAIN_PROXY: string; export const AUTH_DOMAIN_REALM: string; export const AUTH_DOMAIN_REMOVE_PATH: string; export const AUTH_HOST: string; export const AUTH_IS_AUTHENTICATED: string; export const AUTH_IS_FOR_PROXY: string; export const AUTH_REALM: string; export const AUTH_SCHEME_NAME: string; export const CHAR_HTTP_CTL: number; export const CHAR_HTTP_SEPARATOR: number; export const CHAR_URI_GEN_DELIMS: number; export const CHAR_URI_PERCENT_ENCODED: number; export const CHAR_URI_SUB_DELIMS: number; export const COOKIE_JAR_ACCEPT_POLICY: string; export const COOKIE_JAR_DB_FILENAME: string; export const COOKIE_JAR_READ_ONLY: string; export const COOKIE_JAR_TEXT_FILENAME: string; export const COOKIE_MAX_AGE_ONE_DAY: number; export const COOKIE_MAX_AGE_ONE_HOUR: number; export const COOKIE_MAX_AGE_ONE_WEEK: number; export const COOKIE_MAX_AGE_ONE_YEAR: number; export const FORM_MIME_TYPE_MULTIPART: string; export const FORM_MIME_TYPE_URLENCODED: string; export const HSTS_ENFORCER_DB_FILENAME: string; export const HSTS_POLICY_MAX_AGE_PAST: number; export const LOGGER_LEVEL: string; export const LOGGER_MAX_BODY_SIZE: string; export const MAJOR_VERSION: number; export const MESSAGE_FIRST_PARTY: string; export const MESSAGE_FLAGS: string; export const MESSAGE_HTTP_VERSION: string; export const MESSAGE_IS_TOP_LEVEL_NAVIGATION: string; export const MESSAGE_METHOD: string; export const MESSAGE_PRIORITY: string; export const MESSAGE_REASON_PHRASE: string; export const MESSAGE_REQUEST_BODY: string; export const MESSAGE_REQUEST_BODY_DATA: string; export const MESSAGE_REQUEST_HEADERS: string; export const MESSAGE_RESPONSE_BODY: string; export const MESSAGE_RESPONSE_BODY_DATA: string; export const MESSAGE_RESPONSE_HEADERS: string; export const MESSAGE_SERVER_SIDE: string; export const MESSAGE_SITE_FOR_COOKIES: string; export const MESSAGE_STATUS_CODE: string; export const MESSAGE_TLS_CERTIFICATE: string; export const MESSAGE_TLS_ERRORS: string; export const MESSAGE_URI: string; export const MICRO_VERSION: number; export const MINOR_VERSION: number; export const REQUEST_SESSION: string; export const REQUEST_URI: string; export const SERVER_ASYNC_CONTEXT: string; export const SERVER_HTTPS_ALIASES: string; export const SERVER_HTTP_ALIASES: string; export const SERVER_INTERFACE: string; export const SERVER_PORT: string; export const SERVER_RAW_PATHS: string; export const SERVER_SERVER_HEADER: string; export const SERVER_SSL_CERT_FILE: string; export const SERVER_SSL_KEY_FILE: string; export const SERVER_TLS_CERTIFICATE: string; export const SESSION_ACCEPT_LANGUAGE: string; export const SESSION_ACCEPT_LANGUAGE_AUTO: string; export const SESSION_ASYNC_CONTEXT: string; export const SESSION_HTTPS_ALIASES: string; export const SESSION_HTTP_ALIASES: string; export const SESSION_IDLE_TIMEOUT: string; export const SESSION_LOCAL_ADDRESS: string; export const SESSION_MAX_CONNS: string; export const SESSION_MAX_CONNS_PER_HOST: string; export const SESSION_PROXY_RESOLVER: string; export const SESSION_PROXY_URI: string; export const SESSION_SSL_CA_FILE: string; export const SESSION_SSL_STRICT: string; export const SESSION_SSL_USE_SYSTEM_CA_FILE: string; export const SESSION_TIMEOUT: string; export const SESSION_TLS_DATABASE: string; export const SESSION_TLS_INTERACTION: string; export const SESSION_USER_AGENT: string; export const SESSION_USE_NTLM: string; export const SESSION_USE_THREAD_CONTEXT: string; export const SOCKET_ASYNC_CONTEXT: string; export const SOCKET_FLAG_NONBLOCKING: string; export const SOCKET_IS_SERVER: string; export const SOCKET_LOCAL_ADDRESS: string; export const SOCKET_REMOTE_ADDRESS: string; export const SOCKET_SSL_CREDENTIALS: string; export const SOCKET_SSL_FALLBACK: string; export const SOCKET_SSL_STRICT: string; export const SOCKET_TIMEOUT: string; export const SOCKET_TLS_CERTIFICATE: string; export const SOCKET_TLS_ERRORS: string; export const SOCKET_TRUSTED_CERTIFICATE: string; export const SOCKET_USE_THREAD_CONTEXT: string; export const VERSION_MIN_REQUIRED: number; export function check_version(major: number, minor: number, micro: number): boolean; export function cookie_parse(header: string, origin: URI): Cookie | null; export function cookies_from_request(msg: Message): Cookie[]; export function cookies_from_response(msg: Message): Cookie[]; export function cookies_to_cookie_header(cookies: Cookie[]): string; export function cookies_to_request(cookies: Cookie[], msg: Message): void; export function cookies_to_response(cookies: Cookie[], msg: Message): void; export function form_decode(encoded_form: string): GLib.HashTable<string, string>; export function form_decode_multipart( msg: Message, file_control_name?: string | null ): [GLib.HashTable<string, string> | null, string | null, string | null, Buffer | null]; export function form_encode_datalist(form_data_set: GLib.Data): string; export function form_encode_hash(form_data_set: GLib.HashTable<string, string>): string; export function form_request_new_from_datalist(method: string, uri: string, form_data_set: GLib.Data): Message; export function form_request_new_from_hash( method: string, uri: string, form_data_set: GLib.HashTable<string, string> ): Message; export function form_request_new_from_multipart(uri: string, multipart: Multipart): Message; export function get_major_version(): number; export function get_micro_version(): number; export function get_minor_version(): number; export function get_resource(): Gio.Resource; export function header_contains(header: string, token: string): boolean; export function header_free_param_list(param_list: GLib.HashTable<string, string>): void; export function header_g_string_append_param(string: GLib.String, name: string, value: string): void; export function header_g_string_append_param_quoted(string: GLib.String, name: string, value: string): void; export function header_parse_list(header: string): string[]; export function header_parse_param_list(header: string): GLib.HashTable<string, string>; export function header_parse_param_list_strict(header: string): GLib.HashTable<string, string> | null; export function header_parse_quality_list(header: string): [string[], string[] | null]; export function header_parse_semi_param_list(header: string): GLib.HashTable<string, string>; export function header_parse_semi_param_list_strict(header: string): GLib.HashTable<string, string> | null; export function headers_parse(str: string, len: number, dest: MessageHeaders): boolean; export function headers_parse_request( str: string, len: number, req_headers: MessageHeaders ): [number, string | null, string | null, HTTPVersion | null]; export function headers_parse_response( str: string, len: number, headers: MessageHeaders ): [boolean, HTTPVersion | null, number | null, string | null]; export function headers_parse_status_line( status_line: string ): [boolean, HTTPVersion | null, number | null, string | null]; export function http_error_quark(): GLib.Quark; export function message_headers_iter_init(hdrs: MessageHeaders): MessageHeadersIter; export function request_error_quark(): GLib.Quark; export function requester_error_quark(): GLib.Quark; export function status_get_phrase(status_code: number): string; export function status_proxify(status_code: number): number; export function str_case_equal(v1?: any | null, v2?: any | null): boolean; export function str_case_hash(key?: any | null): number; export function tld_domain_is_public_suffix(domain: string): boolean; export function tld_error_quark(): GLib.Quark; export function tld_get_base_domain(hostname: string): string; export function uri_decode(part: string): string; export function uri_encode(part: string, escape_extra?: string | null): string; export function uri_normalize(part: string, unescape_extra?: string | null): string; export function value_array_new(): GObject.ValueArray; export function value_hash_insert_value(hash: GLib.HashTable<string, GObject.Value>, key: string, value: any): void; export function value_hash_new(): GLib.HashTable<string, GObject.Value>; export function websocket_client_prepare_handshake( msg: Message, origin?: string | null, protocols?: string[] | null ): void; export function websocket_client_prepare_handshake_with_extensions( msg: Message, origin?: string | null, protocols?: string[] | null, supported_extensions?: GObject.TypeClass[] | null ): void; export function websocket_client_verify_handshake(msg: Message): boolean; export function websocket_client_verify_handshake_with_extensions( msg: Message, supported_extensions?: GObject.TypeClass[] | null ): [boolean, WebsocketExtension[] | null]; export function websocket_error_get_quark(): GLib.Quark; export function websocket_server_check_handshake( msg: Message, origin?: string | null, protocols?: string[] | null ): boolean; export function websocket_server_check_handshake_with_extensions( msg: Message, origin?: string | null, protocols?: string[] | null, supported_extensions?: GObject.TypeClass[] | null ): boolean; export function websocket_server_process_handshake( msg: Message, expected_origin?: string | null, protocols?: string[] | null ): boolean; export function websocket_server_process_handshake_with_extensions( msg: Message, expected_origin?: string | null, protocols?: string[] | null, supported_extensions?: GObject.TypeClass[] | null ): [boolean, WebsocketExtension[] | null]; export function xmlrpc_build_method_call(method_name: string, params: GObject.Value[]): string | null; export function xmlrpc_build_method_response(value: any): string | null; export function xmlrpc_build_request(method_name: string, params: GLib.Variant): string; export function xmlrpc_build_response(value: GLib.Variant): string; export function xmlrpc_error_quark(): GLib.Quark; export function xmlrpc_fault_quark(): GLib.Quark; export function xmlrpc_message_new(uri: string, method_name: string, params: GLib.Variant): Message; export function xmlrpc_message_set_response(msg: Message, value: GLib.Variant): boolean; export function xmlrpc_parse_method_call(method_call: string, length: number): [boolean, string, GObject.ValueArray]; export function xmlrpc_parse_method_response(method_response: string, length: number): [boolean, unknown]; export function xmlrpc_parse_request(method_call: string, length: number): [string, XMLRPCParams]; export function xmlrpc_parse_response(method_response: string, length: number, signature?: string | null): GLib.Variant; export function xmlrpc_variant_get_datetime(variant: GLib.Variant): Date; export function xmlrpc_variant_new_datetime(date: Date): GLib.Variant; export type AddressCallback = (addr: Address, status: number) => void; export type AuthDomainBasicAuthCallback = ( domain: AuthDomainBasic, msg: Message, username: string, password: string ) => boolean; export type AuthDomainDigestAuthCallback = (domain: AuthDomainDigest, msg: Message, username: string) => string | null; export type AuthDomainFilter = (domain: AuthDomain, msg: Message) => boolean; export type AuthDomainGenericAuthCallback = (domain: AuthDomain, msg: Message, username: string) => boolean; export type ChunkAllocator = (msg: Message, max_len: number) => Buffer | null; export type LoggerFilter = (logger: Logger, msg: Message) => LoggerLogLevel; export type LoggerPrinter = (logger: Logger, level: LoggerLogLevel, direction: number, data: string) => void; export type MessageHeadersForeachFunc = (name: string, value: string) => void; export type PasswordManagerCallback = ( password_manager: PasswordManager, msg: Message, auth: Auth, retrying: boolean ) => void; export type ProxyResolverCallback = (proxy_resolver: ProxyResolver, msg: Message, arg: number, addr: Address) => void; export type ProxyURIResolverCallback = (resolver: ProxyURIResolver, status: number, proxy_uri: URI) => void; export type ServerCallback = ( server: Server, msg: Message, path: string, query: GLib.HashTable<string, string> | null, client: ClientContext ) => void; export type ServerWebsocketCallback = ( server: Server, connection: WebsocketConnection, path: string, client: ClientContext ) => void; export type SessionCallback = (session: Session, msg: Message) => void; export type SessionConnectProgressCallback = ( session: Session, event: Gio.SocketClientEvent, connection: Gio.IOStream ) => void; export type SocketCallback = (sock: Socket, status: number) => void; export type ByteArray = object | null; export namespace AddressFamily { export const $gtype: GObject.GType<AddressFamily>; } export enum AddressFamily { INVALID = -1, IPV4 = 2, IPV6 = 10, } export namespace CacheResponse { export const $gtype: GObject.GType<CacheResponse>; } export enum CacheResponse { FRESH = 0, NEEDS_VALIDATION = 1, STALE = 2, } export namespace CacheType { export const $gtype: GObject.GType<CacheType>; } export enum CacheType { SINGLE_USER = 0, SHARED = 1, } export namespace ConnectionState { export const $gtype: GObject.GType<ConnectionState>; } export enum ConnectionState { NEW = 0, CONNECTING = 1, IDLE = 2, IN_USE = 3, REMOTE_DISCONNECTED = 4, DISCONNECTED = 5, } export namespace CookieJarAcceptPolicy { export const $gtype: GObject.GType<CookieJarAcceptPolicy>; } export enum CookieJarAcceptPolicy { ALWAYS = 0, NEVER = 1, NO_THIRD_PARTY = 2, GRANDFATHERED_THIRD_PARTY = 3, } export namespace DateFormat { export const $gtype: GObject.GType<DateFormat>; } export enum DateFormat { HTTP = 1, COOKIE = 2, RFC2822 = 3, ISO8601_COMPACT = 4, ISO8601_FULL = 5, ISO8601 = 5, ISO8601_XMLRPC = 6, } export namespace Encoding { export const $gtype: GObject.GType<Encoding>; } export enum Encoding { UNRECOGNIZED = 0, NONE = 1, CONTENT_LENGTH = 2, EOF = 3, CHUNKED = 4, BYTERANGES = 5, } export namespace HTTPVersion { export const $gtype: GObject.GType<HTTPVersion>; } export enum HTTPVersion { HTTP_1_0 = 0, HTTP_1_1 = 1, } export namespace KnownStatusCode { export const $gtype: GObject.GType<KnownStatusCode>; } export enum KnownStatusCode { NONE = 0, CANCELLED = 1, CANT_RESOLVE = 2, CANT_RESOLVE_PROXY = 3, CANT_CONNECT = 4, CANT_CONNECT_PROXY = 5, SSL_FAILED = 6, IO_ERROR = 7, MALFORMED = 8, TRY_AGAIN = 9, TOO_MANY_REDIRECTS = 10, TLS_FAILED = 11, CONTINUE = 100, SWITCHING_PROTOCOLS = 101, PROCESSING = 102, OK = 200, CREATED = 201, ACCEPTED = 202, NON_AUTHORITATIVE = 203, NO_CONTENT = 204, RESET_CONTENT = 205, PARTIAL_CONTENT = 206, MULTI_STATUS = 207, MULTIPLE_CHOICES = 300, MOVED_PERMANENTLY = 301, FOUND = 302, MOVED_TEMPORARILY = 302, SEE_OTHER = 303, NOT_MODIFIED = 304, USE_PROXY = 305, NOT_APPEARING_IN_THIS_PROTOCOL = 306, TEMPORARY_REDIRECT = 307, BAD_REQUEST = 400, UNAUTHORIZED = 401, PAYMENT_REQUIRED = 402, FORBIDDEN = 403, NOT_FOUND = 404, METHOD_NOT_ALLOWED = 405, NOT_ACCEPTABLE = 406, PROXY_AUTHENTICATION_REQUIRED = 407, PROXY_UNAUTHORIZED = 407, REQUEST_TIMEOUT = 408, CONFLICT = 409, GONE = 410, LENGTH_REQUIRED = 411, PRECONDITION_FAILED = 412, REQUEST_ENTITY_TOO_LARGE = 413, REQUEST_URI_TOO_LONG = 414, UNSUPPORTED_MEDIA_TYPE = 415, REQUESTED_RANGE_NOT_SATISFIABLE = 416, INVALID_RANGE = 416, EXPECTATION_FAILED = 417, UNPROCESSABLE_ENTITY = 422, LOCKED = 423, FAILED_DEPENDENCY = 424, INTERNAL_SERVER_ERROR = 500, NOT_IMPLEMENTED = 501, BAD_GATEWAY = 502, SERVICE_UNAVAILABLE = 503, GATEWAY_TIMEOUT = 504, HTTP_VERSION_NOT_SUPPORTED = 505, INSUFFICIENT_STORAGE = 507, NOT_EXTENDED = 510, } export namespace LoggerLogLevel { export const $gtype: GObject.GType<LoggerLogLevel>; } export enum LoggerLogLevel { NONE = 0, MINIMAL = 1, HEADERS = 2, BODY = 3, } export namespace MemoryUse { export const $gtype: GObject.GType<MemoryUse>; } export enum MemoryUse { STATIC = 0, TAKE = 1, COPY = 2, TEMPORARY = 3, } export namespace MessageHeadersType { export const $gtype: GObject.GType<MessageHeadersType>; } export enum MessageHeadersType { REQUEST = 0, RESPONSE = 1, MULTIPART = 2, } export namespace MessagePriority { export const $gtype: GObject.GType<MessagePriority>; } export enum MessagePriority { VERY_LOW = 0, LOW = 1, NORMAL = 2, HIGH = 3, VERY_HIGH = 4, } export class RequestError extends GLib.Error { static $gtype: GObject.GType<RequestError>; constructor(options: { message: string; code: number }); constructor(copy: RequestError); // Properties static BAD_URI: number; static UNSUPPORTED_URI_SCHEME: number; static PARSING: number; static ENCODING: number; // Members static quark(): GLib.Quark; } export class RequesterError extends GLib.Error { static $gtype: GObject.GType<RequesterError>; constructor(options: { message: string; code: number }); constructor(copy: RequesterError); // Properties static BAD_URI: number; static UNSUPPORTED_URI_SCHEME: number; // Members static quark(): GLib.Quark; } export namespace SameSitePolicy { export const $gtype: GObject.GType<SameSitePolicy>; } export enum SameSitePolicy { NONE = 0, LAX = 1, STRICT = 2, } export namespace SocketIOStatus { export const $gtype: GObject.GType<SocketIOStatus>; } export enum SocketIOStatus { OK = 0, WOULD_BLOCK = 1, EOF = 2, ERROR = 3, } export namespace Status { export const $gtype: GObject.GType<Status>; } export enum Status { NONE = 0, CANCELLED = 1, CANT_RESOLVE = 2, CANT_RESOLVE_PROXY = 3, CANT_CONNECT = 4, CANT_CONNECT_PROXY = 5, SSL_FAILED = 6, IO_ERROR = 7, MALFORMED = 8, TRY_AGAIN = 9, TOO_MANY_REDIRECTS = 10, TLS_FAILED = 11, CONTINUE = 100, SWITCHING_PROTOCOLS = 101, PROCESSING = 102, OK = 200, CREATED = 201, ACCEPTED = 202, NON_AUTHORITATIVE = 203, NO_CONTENT = 204, RESET_CONTENT = 205, PARTIAL_CONTENT = 206, MULTI_STATUS = 207, MULTIPLE_CHOICES = 300, MOVED_PERMANENTLY = 301, FOUND = 302, MOVED_TEMPORARILY = 302, SEE_OTHER = 303, NOT_MODIFIED = 304, USE_PROXY = 305, NOT_APPEARING_IN_THIS_PROTOCOL = 306, TEMPORARY_REDIRECT = 307, PERMANENT_REDIRECT = 308, BAD_REQUEST = 400, UNAUTHORIZED = 401, PAYMENT_REQUIRED = 402, FORBIDDEN = 403, NOT_FOUND = 404, METHOD_NOT_ALLOWED = 405, NOT_ACCEPTABLE = 406, PROXY_AUTHENTICATION_REQUIRED = 407, PROXY_UNAUTHORIZED = 407, REQUEST_TIMEOUT = 408, CONFLICT = 409, GONE = 410, LENGTH_REQUIRED = 411, PRECONDITION_FAILED = 412, REQUEST_ENTITY_TOO_LARGE = 413, REQUEST_URI_TOO_LONG = 414, UNSUPPORTED_MEDIA_TYPE = 415, REQUESTED_RANGE_NOT_SATISFIABLE = 416, INVALID_RANGE = 416, EXPECTATION_FAILED = 417, UNPROCESSABLE_ENTITY = 422, LOCKED = 423, FAILED_DEPENDENCY = 424, INTERNAL_SERVER_ERROR = 500, NOT_IMPLEMENTED = 501, BAD_GATEWAY = 502, SERVICE_UNAVAILABLE = 503, GATEWAY_TIMEOUT = 504, HTTP_VERSION_NOT_SUPPORTED = 505, INSUFFICIENT_STORAGE = 507, NOT_EXTENDED = 510, } export class TLDError extends GLib.Error { static $gtype: GObject.GType<TLDError>; constructor(options: { message: string; code: number }); constructor(copy: TLDError); // Properties static INVALID_HOSTNAME: number; static IS_IP_ADDRESS: number; static NOT_ENOUGH_DOMAINS: number; static NO_BASE_DOMAIN: number; static NO_PSL_DATA: number; // Members static quark(): GLib.Quark; } export namespace WebsocketCloseCode { export const $gtype: GObject.GType<WebsocketCloseCode>; } export enum WebsocketCloseCode { NORMAL = 1000, GOING_AWAY = 1001, PROTOCOL_ERROR = 1002, UNSUPPORTED_DATA = 1003, NO_STATUS = 1005, ABNORMAL = 1006, BAD_DATA = 1007, POLICY_VIOLATION = 1008, TOO_BIG = 1009, NO_EXTENSION = 1010, SERVER_ERROR = 1011, TLS_HANDSHAKE = 1015, } export namespace WebsocketConnectionType { export const $gtype: GObject.GType<WebsocketConnectionType>; } export enum WebsocketConnectionType { UNKNOWN = 0, CLIENT = 1, SERVER = 2, } export namespace WebsocketDataType { export const $gtype: GObject.GType<WebsocketDataType>; } export enum WebsocketDataType { TEXT = 1, BINARY = 2, } export namespace WebsocketError { export const $gtype: GObject.GType<WebsocketError>; } export enum WebsocketError { FAILED = 0, NOT_WEBSOCKET = 1, BAD_HANDSHAKE = 2, BAD_ORIGIN = 3, } export namespace WebsocketState { export const $gtype: GObject.GType<WebsocketState>; } export enum WebsocketState { OPEN = 1, CLOSING = 2, CLOSED = 3, } export class XMLRPCError extends GLib.Error { static $gtype: GObject.GType<XMLRPCError>; constructor(options: { message: string; code: number }); constructor(copy: XMLRPCError); // Properties static ARGUMENTS: number; static RETVAL: number; // Members static quark(): GLib.Quark; } export namespace XMLRPCFault { export const $gtype: GObject.GType<XMLRPCFault>; } export enum XMLRPCFault { PARSE_ERROR_NOT_WELL_FORMED = -32700, PARSE_ERROR_UNSUPPORTED_ENCODING = -32701, PARSE_ERROR_INVALID_CHARACTER_FOR_ENCODING = -32702, SERVER_ERROR_INVALID_XML_RPC = -32600, SERVER_ERROR_REQUESTED_METHOD_NOT_FOUND = -32601, SERVER_ERROR_INVALID_METHOD_PARAMETERS = -32602, SERVER_ERROR_INTERNAL_XML_RPC_ERROR = -32603, APPLICATION_ERROR = -32500, SYSTEM_ERROR = -32400, TRANSPORT_ERROR = -32300, } export namespace Cacheability { export const $gtype: GObject.GType<Cacheability>; } export enum Cacheability { CACHEABLE = 1, UNCACHEABLE = 2, INVALIDATES = 4, VALIDATES = 8, } export namespace Expectation { export const $gtype: GObject.GType<Expectation>; } export enum Expectation { UNRECOGNIZED = 1, CONTINUE = 2, } export namespace MessageFlags { export const $gtype: GObject.GType<MessageFlags>; } export enum MessageFlags { NO_REDIRECT = 2, CAN_REBUILD = 4, OVERWRITE_CHUNKS = 8, CONTENT_DECODED = 16, CERTIFICATE_TRUSTED = 32, NEW_CONNECTION = 64, IDEMPOTENT = 128, IGNORE_CONNECTION_LIMITS = 256, DO_NOT_USE_AUTH_CACHE = 512, } export namespace ServerListenOptions { export const $gtype: GObject.GType<ServerListenOptions>; } export enum ServerListenOptions { HTTPS = 1, IPV4_ONLY = 2, IPV6_ONLY = 4, } export module Address { export interface ConstructorProperties extends GObject.Object.ConstructorProperties { [key: string]: any; family: AddressFamily; name: string; physical: string; port: number; protocol: string; sockaddr: any; } } export class Address extends GObject.Object implements Gio.SocketConnectable { static $gtype: GObject.GType<Address>; constructor(properties?: Partial<Address.ConstructorProperties>, ...args: any[]); _init(properties?: Partial<Address.ConstructorProperties>, ...args: any[]): void; // Properties family: AddressFamily; name: string; physical: string; port: number; protocol: string; sockaddr: any; // Constructors static ["new"](name: string, port: number): Address; static new_any(family: AddressFamily, port: number): Address; static new_from_sockaddr(sa: any | null, len: number): Address; // Members equal_by_ip(addr2: Address): boolean; equal_by_name(addr2: Address): boolean; get_gsockaddr(): Gio.SocketAddress; get_name(): string | null; get_physical(): string | null; get_port(): number; get_sockaddr(len: number): any | null; hash_by_ip(): number; hash_by_name(): number; is_resolved(): boolean; resolve_async( async_context: GLib.MainContext | null, cancellable: Gio.Cancellable | null, callback: AddressCallback ): void; resolve_sync(cancellable?: Gio.Cancellable | null): number; // Implemented Members enumerate(): Gio.SocketAddressEnumerator; proxy_enumerate(): Gio.SocketAddressEnumerator; to_string(): string; vfunc_enumerate(): Gio.SocketAddressEnumerator; vfunc_proxy_enumerate(): Gio.SocketAddressEnumerator; vfunc_to_string(): string; } export module Auth { export interface ConstructorProperties extends GObject.Object.ConstructorProperties { [key: string]: any; host: string; is_authenticated: boolean; isAuthenticated: boolean; is_for_proxy: boolean; isForProxy: boolean; realm: string; scheme_name: string; schemeName: string; } } export abstract class Auth extends GObject.Object { static $gtype: GObject.GType<Auth>; constructor(properties?: Partial<Auth.ConstructorProperties>, ...args: any[]); _init(properties?: Partial<Auth.ConstructorProperties>, ...args: any[]): void; // Properties host: string; is_authenticated: boolean; isAuthenticated: boolean; is_for_proxy: boolean; isForProxy: boolean; realm: string; scheme_name: string; schemeName: string; // Constructors static ["new"](type: GObject.GType, msg: Message, auth_header: string): Auth; // Members authenticate(username: string, password: string): void; can_authenticate(): boolean; get_authorization(msg: Message): string; get_host(): string; get_info(): string; get_protection_space(source_uri: URI): string[]; get_realm(): string; get_saved_password(user: string): string; get_saved_users(): string[]; get_scheme_name(): string; has_saved_password(username: string, password: string): void; is_ready(msg: Message): boolean; save_password(username: string, password: string): void; update(msg: Message, auth_header: string): boolean; vfunc_authenticate(username: string, password: string): void; vfunc_can_authenticate(): boolean; vfunc_get_authorization(msg: Message): string; vfunc_get_protection_space(source_uri: URI): string[]; vfunc_is_authenticated(): boolean; vfunc_is_ready(msg: Message): boolean; vfunc_update(msg: Message, auth_header: GLib.HashTable<any, any>): boolean; } export module AuthBasic { export interface ConstructorProperties extends Auth.ConstructorProperties { [key: string]: any; } } export class AuthBasic extends Auth { static $gtype: GObject.GType<AuthBasic>; constructor(properties?: Partial<AuthBasic.ConstructorProperties>, ...args: any[]); _init(properties?: Partial<AuthBasic.ConstructorProperties>, ...args: any[]): void; } export module AuthDigest { export interface ConstructorProperties extends Auth.ConstructorProperties { [key: string]: any; } } export class AuthDigest extends Auth { static $gtype: GObject.GType<AuthDigest>; constructor(properties?: Partial<AuthDigest.ConstructorProperties>, ...args: any[]); _init(properties?: Partial<AuthDigest.ConstructorProperties>, ...args: any[]): void; } export module AuthDomain { export interface ConstructorProperties extends GObject.Object.ConstructorProperties { [key: string]: any; add_path: string; addPath: string; filter: AuthDomainFilter; filter_data: any; filterData: any; generic_auth_callback: AuthDomainGenericAuthCallback; genericAuthCallback: AuthDomainGenericAuthCallback; generic_auth_data: any; genericAuthData: any; proxy: boolean; realm: string; remove_path: string; removePath: string; } } export abstract class AuthDomain extends GObject.Object { static $gtype: GObject.GType<AuthDomain>; constructor(properties?: Partial<AuthDomain.ConstructorProperties>, ...args: any[]); _init(properties?: Partial<AuthDomain.ConstructorProperties>, ...args: any[]): void; // Properties add_path: string; addPath: string; filter: AuthDomainFilter; filter_data: any; filterData: any; generic_auth_callback: AuthDomainGenericAuthCallback; genericAuthCallback: AuthDomainGenericAuthCallback; generic_auth_data: any; genericAuthData: any; proxy: boolean; realm: string; remove_path: string; removePath: string; // Members accepts(msg: Message): string | null; challenge(msg: Message): void; check_password(msg: Message, username: string, password: string): boolean; covers(msg: Message): boolean; get_realm(): string; set_filter(filter: AuthDomainFilter): void; set_generic_auth_callback(auth_callback: AuthDomainGenericAuthCallback): void; try_generic_auth_callback(msg: Message, username: string): boolean; vfunc_accepts(msg: Message, header: string): string; vfunc_challenge(msg: Message): string; vfunc_check_password(msg: Message, username: string, password: string): boolean; } export module AuthDomainBasic { export interface ConstructorProperties extends AuthDomain.ConstructorProperties { [key: string]: any; auth_callback: AuthDomainBasicAuthCallback; authCallback: AuthDomainBasicAuthCallback; auth_data: any; authData: any; } } export class AuthDomainBasic extends AuthDomain { static $gtype: GObject.GType<AuthDomainBasic>; constructor(properties?: Partial<AuthDomainBasic.ConstructorProperties>, ...args: any[]); _init(properties?: Partial<AuthDomainBasic.ConstructorProperties>, ...args: any[]): void; // Properties auth_callback: AuthDomainBasicAuthCallback; authCallback: AuthDomainBasicAuthCallback; auth_data: any; authData: any; // Members set_auth_callback(callback: AuthDomainBasicAuthCallback): void; } export module AuthDomainDigest { export interface ConstructorProperties extends AuthDomain.ConstructorProperties { [key: string]: any; auth_callback: AuthDomainDigestAuthCallback; authCallback: AuthDomainDigestAuthCallback; auth_data: any; authData: any; } } export class AuthDomainDigest extends AuthDomain { static $gtype: GObject.GType<AuthDomainDigest>; constructor(properties?: Partial<AuthDomainDigest.ConstructorProperties>, ...args: any[]); _init(properties?: Partial<AuthDomainDigest.ConstructorProperties>, ...args: any[]): void; // Properties auth_callback: AuthDomainDigestAuthCallback; authCallback: AuthDomainDigestAuthCallback; auth_data: any; authData: any; // Members set_auth_callback(callback: AuthDomainDigestAuthCallback): void; static encode_password(username: string, realm: string, password: string): string; } export module AuthManager { export interface ConstructorProperties extends GObject.Object.ConstructorProperties { [key: string]: any; } } export class AuthManager extends GObject.Object implements SessionFeature { static $gtype: GObject.GType<AuthManager>; constructor(properties?: Partial<AuthManager.ConstructorProperties>, ...args: any[]); _init(properties?: Partial<AuthManager.ConstructorProperties>, ...args: any[]): void; // Fields priv: AuthManagerPrivate; // Signals connect(id: string, callback: (...args: any[]) => any): number; connect_after(id: string, callback: (...args: any[]) => any): number; emit(id: string, ...args: any[]): void; connect( signal: "authenticate", callback: (_source: this, msg: Message, auth: Auth, retrying: boolean) => void ): number; connect_after( signal: "authenticate", callback: (_source: this, msg: Message, auth: Auth, retrying: boolean) => void ): number; emit(signal: "authenticate", msg: Message, auth: Auth, retrying: boolean): void; // Members clear_cached_credentials(): void; use_auth(uri: URI, auth: Auth): void; vfunc_authenticate(msg: Message, auth: Auth, retrying: boolean): void; // Implemented Members add_feature(type: GObject.GType): boolean; attach(session: Session): void; detach(session: Session): void; has_feature(type: GObject.GType): boolean; remove_feature(type: GObject.GType): boolean; vfunc_add_feature(type: GObject.GType): boolean; vfunc_attach(session: Session): void; vfunc_detach(session: Session): void; vfunc_has_feature(type: GObject.GType): boolean; vfunc_remove_feature(type: GObject.GType): boolean; vfunc_request_queued(session: Session, msg: Message): void; vfunc_request_started(session: Session, msg: Message, socket: Socket): void; vfunc_request_unqueued(session: Session, msg: Message): void; } export module AuthNTLM { export interface ConstructorProperties extends Auth.ConstructorProperties { [key: string]: any; } } export class AuthNTLM extends Auth { static $gtype: GObject.GType<AuthNTLM>; constructor(properties?: Partial<AuthNTLM.ConstructorProperties>, ...args: any[]); _init(properties?: Partial<AuthNTLM.ConstructorProperties>, ...args: any[]): void; } export module AuthNegotiate { export interface ConstructorProperties extends Auth.ConstructorProperties { [key: string]: any; } } export class AuthNegotiate extends Auth { static $gtype: GObject.GType<AuthNegotiate>; constructor(properties?: Partial<AuthNegotiate.ConstructorProperties>, ...args: any[]); _init(properties?: Partial<AuthNegotiate.ConstructorProperties>, ...args: any[]): void; // Members static supported(): boolean; } export module Cache { export interface ConstructorProperties extends GObject.Object.ConstructorProperties { [key: string]: any; cache_dir: string; cacheDir: string; cache_type: CacheType; cacheType: CacheType; } } export class Cache extends GObject.Object implements SessionFeature { static $gtype: GObject.GType<Cache>; constructor(properties?: Partial<Cache.ConstructorProperties>, ...args: any[]); _init(properties?: Partial<Cache.ConstructorProperties>, ...args: any[]): void; // Properties cache_dir: string; cacheDir: string; cache_type: CacheType; cacheType: CacheType; // Fields priv: CachePrivate; // Constructors static ["new"](cache_dir: string | null, cache_type: CacheType): Cache; // Members clear(): void; dump(): void; flush(): void; get_max_size(): number; load(): void; set_max_size(max_size: number): void; vfunc_get_cacheability(msg: Message): Cacheability; // Implemented Members add_feature(type: GObject.GType): boolean; attach(session: Session): void; detach(session: Session): void; has_feature(type: GObject.GType): boolean; remove_feature(type: GObject.GType): boolean; vfunc_add_feature(type: GObject.GType): boolean; vfunc_attach(session: Session): void; vfunc_detach(session: Session): void; vfunc_has_feature(type: GObject.GType): boolean; vfunc_remove_feature(type: GObject.GType): boolean; vfunc_request_queued(session: Session, msg: Message): void; vfunc_request_started(session: Session, msg: Message, socket: Socket): void; vfunc_request_unqueued(session: Session, msg: Message): void; } export module ContentDecoder { export interface ConstructorProperties extends GObject.Object.ConstructorProperties { [key: string]: any; } } export class ContentDecoder extends GObject.Object implements SessionFeature { static $gtype: GObject.GType<ContentDecoder>; constructor(properties?: Partial<ContentDecoder.ConstructorProperties>, ...args: any[]); _init(properties?: Partial<ContentDecoder.ConstructorProperties>, ...args: any[]): void; // Fields priv: ContentDecoderPrivate; // Implemented Members add_feature(type: GObject.GType): boolean; attach(session: Session): void; detach(session: Session): void; has_feature(type: GObject.GType): boolean; remove_feature(type: GObject.GType): boolean; vfunc_add_feature(type: GObject.GType): boolean; vfunc_attach(session: Session): void; vfunc_detach(session: Session): void; vfunc_has_feature(type: GObject.GType): boolean; vfunc_remove_feature(type: GObject.GType): boolean; vfunc_request_queued(session: Session, msg: Message): void; vfunc_request_started(session: Session, msg: Message, socket: Socket): void; vfunc_request_unqueued(session: Session, msg: Message): void; } export module ContentSniffer { export interface ConstructorProperties extends GObject.Object.ConstructorProperties { [key: string]: any; } } export class ContentSniffer extends GObject.Object implements SessionFeature { static $gtype: GObject.GType<ContentSniffer>; constructor(properties?: Partial<ContentSniffer.ConstructorProperties>, ...args: any[]); _init(properties?: Partial<ContentSniffer.ConstructorProperties>, ...args: any[]): void; // Fields priv: ContentSnifferPrivate; // Constructors static ["new"](): ContentSniffer; // Members get_buffer_size(): number; sniff(msg: Message, buffer: Buffer): [string, GLib.HashTable<string, string> | null]; vfunc_get_buffer_size(): number; vfunc_sniff(msg: Message, buffer: Buffer): [string, GLib.HashTable<string, string> | null]; // Implemented Members add_feature(type: GObject.GType): boolean; attach(session: Session): void; detach(session: Session): void; has_feature(type: GObject.GType): boolean; remove_feature(type: GObject.GType): boolean; vfunc_add_feature(type: GObject.GType): boolean; vfunc_attach(session: Session): void; vfunc_detach(session: Session): void; vfunc_has_feature(type: GObject.GType): boolean; vfunc_remove_feature(type: GObject.GType): boolean; vfunc_request_queued(session: Session, msg: Message): void; vfunc_request_started(session: Session, msg: Message, socket: Socket): void; vfunc_request_unqueued(session: Session, msg: Message): void; } export module CookieJar { export interface ConstructorProperties extends GObject.Object.ConstructorProperties { [key: string]: any; accept_policy: CookieJarAcceptPolicy; acceptPolicy: CookieJarAcceptPolicy; read_only: boolean; readOnly: boolean; } } export class CookieJar extends GObject.Object implements SessionFeature { static $gtype: GObject.GType<CookieJar>; constructor(properties?: Partial<CookieJar.ConstructorProperties>, ...args: any[]); _init(properties?: Partial<CookieJar.ConstructorProperties>, ...args: any[]): void; // Properties accept_policy: CookieJarAcceptPolicy; acceptPolicy: CookieJarAcceptPolicy; read_only: boolean; readOnly: boolean; // Signals connect(id: string, callback: (...args: any[]) => any): number; connect_after(id: string, callback: (...args: any[]) => any): number; emit(id: string, ...args: any[]): void; connect(signal: "changed", callback: (_source: this, old_cookie: Cookie, new_cookie: Cookie) => void): number; connect_after(signal: "changed", callback: (_source: this, old_cookie: Cookie, new_cookie: Cookie) => void): number; emit(signal: "changed", old_cookie: Cookie, new_cookie: Cookie): void; // Constructors static ["new"](): CookieJar; // Members add_cookie(cookie: Cookie): void; add_cookie_full(cookie: Cookie, uri?: URI | null, first_party?: URI | null): void; add_cookie_with_first_party(first_party: URI, cookie: Cookie): void; all_cookies(): Cookie[]; delete_cookie(cookie: Cookie): void; get_accept_policy(): CookieJarAcceptPolicy; get_cookie_list(uri: URI, for_http: boolean): Cookie[]; get_cookie_list_with_same_site_info( uri: URI, top_level: URI | null, site_for_cookies: URI | null, for_http: boolean, is_safe_method: boolean, is_top_level_navigation: boolean ): Cookie[]; get_cookies(uri: URI, for_http: boolean): string | null; is_persistent(): boolean; save(): void; set_accept_policy(policy: CookieJarAcceptPolicy): void; set_cookie(uri: URI, cookie: string): void; set_cookie_with_first_party(uri: URI, first_party: URI, cookie: string): void; vfunc_changed(old_cookie: Cookie, new_cookie: Cookie): void; vfunc_is_persistent(): boolean; vfunc_save(): void; // Implemented Members add_feature(type: GObject.GType): boolean; attach(session: Session): void; detach(session: Session): void; has_feature(type: GObject.GType): boolean; remove_feature(type: GObject.GType): boolean; vfunc_add_feature(type: GObject.GType): boolean; vfunc_attach(session: Session): void; vfunc_detach(session: Session): void; vfunc_has_feature(type: GObject.GType): boolean; vfunc_remove_feature(type: GObject.GType): boolean; vfunc_request_queued(session: Session, msg: Message): void; vfunc_request_started(session: Session, msg: Message, socket: Socket): void; vfunc_request_unqueued(session: Session, msg: Message): void; } export module CookieJarDB { export interface ConstructorProperties extends CookieJar.ConstructorProperties { [key: string]: any; filename: string; } } export class CookieJarDB extends CookieJar implements SessionFeature { static $gtype: GObject.GType<CookieJarDB>; constructor(properties?: Partial<CookieJarDB.ConstructorProperties>, ...args: any[]); _init(properties?: Partial<CookieJarDB.ConstructorProperties>, ...args: any[]): void; // Properties filename: string; // Constructors static ["new"](filename: string, read_only: boolean): CookieJarDB; static ["new"](...args: never[]): never; // Implemented Members add_feature(type: GObject.GType): boolean; attach(session: Session): void; detach(session: Session): void; has_feature(type: GObject.GType): boolean; remove_feature(type: GObject.GType): boolean; vfunc_add_feature(type: GObject.GType): boolean; vfunc_attach(session: Session): void; vfunc_detach(session: Session): void; vfunc_has_feature(type: GObject.GType): boolean; vfunc_remove_feature(type: GObject.GType): boolean; vfunc_request_queued(session: Session, msg: Message): void; vfunc_request_started(session: Session, msg: Message, socket: Socket): void; vfunc_request_unqueued(session: Session, msg: Message): void; } export module CookieJarText { export interface ConstructorProperties extends CookieJar.ConstructorProperties { [key: string]: any; filename: string; } } export class CookieJarText extends CookieJar implements SessionFeature { static $gtype: GObject.GType<CookieJarText>; constructor(properties?: Partial<CookieJarText.ConstructorProperties>, ...args: any[]); _init(properties?: Partial<CookieJarText.ConstructorProperties>, ...args: any[]): void; // Properties filename: string; // Constructors static ["new"](filename: string, read_only: boolean): CookieJarText; static ["new"](...args: never[]): never; // Implemented Members add_feature(type: GObject.GType): boolean; attach(session: Session): void; detach(session: Session): void; has_feature(type: GObject.GType): boolean; remove_feature(type: GObject.GType): boolean; vfunc_add_feature(type: GObject.GType): boolean; vfunc_attach(session: Session): void; vfunc_detach(session: Session): void; vfunc_has_feature(type: GObject.GType): boolean; vfunc_remove_feature(type: GObject.GType): boolean; vfunc_request_queued(session: Session, msg: Message): void; vfunc_request_started(session: Session, msg: Message, socket: Socket): void; vfunc_request_unqueued(session: Session, msg: Message): void; } export module HSTSEnforcer { export interface ConstructorProperties extends GObject.Object.ConstructorProperties { [key: string]: any; } } export class HSTSEnforcer extends GObject.Object implements SessionFeature { static $gtype: GObject.GType<HSTSEnforcer>; constructor(properties?: Partial<HSTSEnforcer.ConstructorProperties>, ...args: any[]); _init(properties?: Partial<HSTSEnforcer.ConstructorProperties>, ...args: any[]): void; // Fields priv: HSTSEnforcerPrivate; // Signals connect(id: string, callback: (...args: any[]) => any): number; connect_after(id: string, callback: (...args: any[]) => any): number; emit(id: string, ...args: any[]): void; connect( signal: "changed", callback: (_source: this, old_policy: HSTSPolicy, new_policy: HSTSPolicy) => void ): number; connect_after( signal: "changed", callback: (_source: this, old_policy: HSTSPolicy, new_policy: HSTSPolicy) => void ): number; emit(signal: "changed", old_policy: HSTSPolicy, new_policy: HSTSPolicy): void; connect(signal: "hsts-enforced", callback: (_source: this, message: Message) => void): number; connect_after(signal: "hsts-enforced", callback: (_source: this, message: Message) => void): number; emit(signal: "hsts-enforced", message: Message): void; // Constructors static ["new"](): HSTSEnforcer; // Members get_domains(session_policies: boolean): string[]; get_policies(session_policies: boolean): HSTSPolicy[]; has_valid_policy(domain: string): boolean; is_persistent(): boolean; set_policy(policy: HSTSPolicy): void; set_session_policy(domain: string, include_subdomains: boolean): void; vfunc_changed(old_policy: HSTSPolicy, new_policy: HSTSPolicy): void; vfunc_has_valid_policy(domain: string): boolean; vfunc_hsts_enforced(message: Message): void; vfunc_is_persistent(): boolean; // Implemented Members add_feature(type: GObject.GType): boolean; attach(session: Session): void; detach(session: Session): void; has_feature(type: GObject.GType): boolean; remove_feature(type: GObject.GType): boolean; vfunc_add_feature(type: GObject.GType): boolean; vfunc_attach(session: Session): void; vfunc_detach(session: Session): void; vfunc_has_feature(type: GObject.GType): boolean; vfunc_remove_feature(type: GObject.GType): boolean; vfunc_request_queued(session: Session, msg: Message): void; vfunc_request_started(session: Session, msg: Message, socket: Socket): void; vfunc_request_unqueued(session: Session, msg: Message): void; } export module HSTSEnforcerDB { export interface ConstructorProperties extends HSTSEnforcer.ConstructorProperties { [key: string]: any; filename: string; } } export class HSTSEnforcerDB extends HSTSEnforcer implements SessionFeature { static $gtype: GObject.GType<HSTSEnforcerDB>; constructor(properties?: Partial<HSTSEnforcerDB.ConstructorProperties>, ...args: any[]); _init(properties?: Partial<HSTSEnforcerDB.ConstructorProperties>, ...args: any[]): void; // Properties filename: string; // Fields priv: HSTSEnforcerDBPrivate | any; // Constructors static ["new"](filename: string): HSTSEnforcerDB; static ["new"](...args: never[]): never; // Implemented Members add_feature(type: GObject.GType): boolean; attach(session: Session): void; detach(session: Session): void; has_feature(type: GObject.GType): boolean; remove_feature(type: GObject.GType): boolean; vfunc_add_feature(type: GObject.GType): boolean; vfunc_attach(session: Session): void; vfunc_detach(session: Session): void; vfunc_has_feature(type: GObject.GType): boolean; vfunc_remove_feature(type: GObject.GType): boolean; vfunc_request_queued(session: Session, msg: Message): void; vfunc_request_started(session: Session, msg: Message, socket: Socket): void; vfunc_request_unqueued(session: Session, msg: Message): void; } export module Logger { export interface ConstructorProperties extends GObject.Object.ConstructorProperties { [key: string]: any; level: LoggerLogLevel; max_body_size: number; maxBodySize: number; } } export class Logger extends GObject.Object implements SessionFeature { static $gtype: GObject.GType<Logger>; constructor(properties?: Partial<Logger.ConstructorProperties>, ...args: any[]); _init(properties?: Partial<Logger.ConstructorProperties>, ...args: any[]): void; // Properties level: LoggerLogLevel; max_body_size: number; maxBodySize: number; // Constructors static ["new"](level: LoggerLogLevel, max_body_size: number): Logger; // Members attach(session: Session): void; detach(session: Session): void; set_printer(printer: LoggerPrinter): void; set_request_filter(request_filter: LoggerFilter): void; set_response_filter(response_filter: LoggerFilter): void; // Implemented Members add_feature(type: GObject.GType): boolean; has_feature(type: GObject.GType): boolean; remove_feature(type: GObject.GType): boolean; vfunc_add_feature(type: GObject.GType): boolean; vfunc_attach(session: Session): void; vfunc_detach(session: Session): void; vfunc_has_feature(type: GObject.GType): boolean; vfunc_remove_feature(type: GObject.GType): boolean; vfunc_request_queued(session: Session, msg: Message): void; vfunc_request_started(session: Session, msg: Message, socket: Socket): void; vfunc_request_unqueued(session: Session, msg: Message): void; } export module Message { export interface ConstructorProperties extends GObject.Object.ConstructorProperties { [key: string]: any; first_party: URI; firstParty: URI; flags: MessageFlags; http_version: HTTPVersion; httpVersion: HTTPVersion; is_top_level_navigation: boolean; isTopLevelNavigation: boolean; method: string; priority: MessagePriority; reason_phrase: string; reasonPhrase: string; request_body: MessageBody; requestBody: MessageBody; request_body_data: GLib.Bytes; requestBodyData: GLib.Bytes; request_headers: MessageHeaders; requestHeaders: MessageHeaders; response_body: MessageBody; responseBody: MessageBody; response_body_data: GLib.Bytes; responseBodyData: GLib.Bytes; response_headers: MessageHeaders; responseHeaders: MessageHeaders; server_side: boolean; serverSide: boolean; site_for_cookies: URI; siteForCookies: URI; status_code: number; statusCode: number; tls_certificate: Gio.TlsCertificate; tlsCertificate: Gio.TlsCertificate; tls_errors: Gio.TlsCertificateFlags; tlsErrors: Gio.TlsCertificateFlags; uri: URI; } } export class Message extends GObject.Object { static $gtype: GObject.GType<Message>; constructor(properties?: Partial<Message.ConstructorProperties>, ...args: any[]); _init(properties?: Partial<Message.ConstructorProperties>, ...args: any[]): void; // Properties first_party: URI; firstParty: URI; flags: MessageFlags; http_version: HTTPVersion; httpVersion: HTTPVersion; is_top_level_navigation: boolean; isTopLevelNavigation: boolean; method: string; priority: MessagePriority; reason_phrase: string; reasonPhrase: string; request_body: MessageBody; requestBody: MessageBody; request_body_data: GLib.Bytes; requestBodyData: GLib.Bytes; request_headers: MessageHeaders; requestHeaders: MessageHeaders; response_body: MessageBody; responseBody: MessageBody; response_body_data: GLib.Bytes; responseBodyData: GLib.Bytes; response_headers: MessageHeaders; responseHeaders: MessageHeaders; server_side: boolean; serverSide: boolean; site_for_cookies: URI; siteForCookies: URI; status_code: number; statusCode: number; tls_certificate: Gio.TlsCertificate; tlsCertificate: Gio.TlsCertificate; tls_errors: Gio.TlsCertificateFlags; tlsErrors: Gio.TlsCertificateFlags; uri: URI; // Signals connect(id: string, callback: (...args: any[]) => any): number; connect_after(id: string, callback: (...args: any[]) => any): number; emit(id: string, ...args: any[]): void; connect( signal: "content-sniffed", callback: (_source: this, type: string, params: GLib.HashTable<string, string>) => void ): number; connect_after( signal: "content-sniffed", callback: (_source: this, type: string, params: GLib.HashTable<string, string>) => void ): number; emit(signal: "content-sniffed", type: string, params: GLib.HashTable<string, string>): void; connect(signal: "finished", callback: (_source: this) => void): number; connect_after(signal: "finished", callback: (_source: this) => void): number; emit(signal: "finished"): void; connect(signal: "got-body", callback: (_source: this) => void): number; connect_after(signal: "got-body", callback: (_source: this) => void): number; emit(signal: "got-body"): void; connect(signal: "got-chunk", callback: (_source: this, chunk: Buffer) => void): number; connect_after(signal: "got-chunk", callback: (_source: this, chunk: Buffer) => void): number; emit(signal: "got-chunk", chunk: Buffer): void; connect(signal: "got-headers", callback: (_source: this) => void): number; connect_after(signal: "got-headers", callback: (_source: this) => void): number; emit(signal: "got-headers"): void; connect(signal: "got-informational", callback: (_source: this) => void): number; connect_after(signal: "got-informational", callback: (_source: this) => void): number; emit(signal: "got-informational"): void; connect( signal: "network-event", callback: (_source: this, event: Gio.SocketClientEvent, connection: Gio.IOStream) => void ): number; connect_after( signal: "network-event", callback: (_source: this, event: Gio.SocketClientEvent, connection: Gio.IOStream) => void ): number; emit(signal: "network-event", event: Gio.SocketClientEvent, connection: Gio.IOStream): void; connect(signal: "restarted", callback: (_source: this) => void): number; connect_after(signal: "restarted", callback: (_source: this) => void): number; emit(signal: "restarted"): void; connect(signal: "starting", callback: (_source: this) => void): number; connect_after(signal: "starting", callback: (_source: this) => void): number; emit(signal: "starting"): void; connect(signal: "wrote-body", callback: (_source: this) => void): number; connect_after(signal: "wrote-body", callback: (_source: this) => void): number; emit(signal: "wrote-body"): void; connect(signal: "wrote-body-data", callback: (_source: this, chunk: Buffer) => void): number; connect_after(signal: "wrote-body-data", callback: (_source: this, chunk: Buffer) => void): number; emit(signal: "wrote-body-data", chunk: Buffer): void; connect(signal: "wrote-chunk", callback: (_source: this) => void): number; connect_after(signal: "wrote-chunk", callback: (_source: this) => void): number; emit(signal: "wrote-chunk"): void; connect(signal: "wrote-headers", callback: (_source: this) => void): number; connect_after(signal: "wrote-headers", callback: (_source: this) => void): number; emit(signal: "wrote-headers"): void; connect(signal: "wrote-informational", callback: (_source: this) => void): number; connect_after(signal: "wrote-informational", callback: (_source: this) => void): number; emit(signal: "wrote-informational"): void; // Constructors static ["new"](method: string, uri_string: string): Message; static new_from_uri(method: string, uri: URI): Message; // Members content_sniffed(content_type: string, params: GLib.HashTable<any, any>): void; disable_feature(feature_type: GObject.GType): void; finished(): void; get_address(): Address; get_first_party(): URI; get_flags(): MessageFlags; get_http_version(): HTTPVersion; get_https_status(): [boolean, Gio.TlsCertificate, Gio.TlsCertificateFlags]; get_is_top_level_navigation(): boolean; get_priority(): MessagePriority; get_site_for_cookies(): URI; get_soup_request(): Request; get_uri(): URI; got_body(): void; got_chunk(chunk: Buffer): void; got_headers(): void; got_informational(): void; is_feature_disabled(feature_type: GObject.GType): boolean; is_keepalive(): boolean; restarted(): void; set_chunk_allocator(allocator: ChunkAllocator): void; set_first_party(first_party: URI): void; set_flags(flags: MessageFlags): void; set_http_version(version: HTTPVersion): void; set_is_top_level_navigation(is_top_level_navigation: boolean): void; set_priority(priority: MessagePriority): void; set_redirect(status_code: number, redirect_uri: string): void; set_request(content_type: string | null, req_use: MemoryUse, req_body?: Uint8Array | null): void; set_response(content_type: string | null, resp_use: MemoryUse, resp_body?: Uint8Array | null): void; set_site_for_cookies(site_for_cookies?: URI | null): void; set_status(status_code: number): void; set_status_full(status_code: number, reason_phrase: string): void; set_uri(uri: URI): void; starting(): void; wrote_body(): void; wrote_body_data(chunk: Buffer): void; wrote_chunk(): void; wrote_headers(): void; wrote_informational(): void; vfunc_finished(): void; vfunc_got_body(): void; vfunc_got_chunk(chunk: Buffer): void; vfunc_got_headers(): void; vfunc_got_informational(): void; vfunc_restarted(): void; vfunc_starting(): void; vfunc_wrote_body(): void; vfunc_wrote_chunk(): void; vfunc_wrote_headers(): void; vfunc_wrote_informational(): void; } export module MultipartInputStream { export interface ConstructorProperties extends Gio.FilterInputStream.ConstructorProperties { [key: string]: any; message: Message; } } export class MultipartInputStream extends Gio.FilterInputStream implements Gio.PollableInputStream { static $gtype: GObject.GType<MultipartInputStream>; constructor(properties?: Partial<MultipartInputStream.ConstructorProperties>, ...args: any[]); _init(properties?: Partial<MultipartInputStream.ConstructorProperties>, ...args: any[]): void; // Properties message: Message; // Constructors static ["new"](msg: Message, base_stream: Gio.InputStream): MultipartInputStream; // Members get_headers(): MessageHeaders | null; next_part(cancellable?: Gio.Cancellable | null): Gio.InputStream | null; next_part_async(io_priority: number, cancellable?: Gio.Cancellable | null): Promise<Gio.InputStream | null>; next_part_async( io_priority: number, cancellable: Gio.Cancellable | null, callback: Gio.AsyncReadyCallback<this> | null ): void; next_part_async( io_priority: number, cancellable?: Gio.Cancellable | null, callback?: Gio.AsyncReadyCallback<this> | null ): Promise<Gio.InputStream | null> | void; next_part_finish(result: Gio.AsyncResult): Gio.InputStream | null; // Implemented Members can_poll(): boolean; create_source(cancellable?: Gio.Cancellable | null): GLib.Source; is_readable(): boolean; read_nonblocking(buffer: Uint8Array | string, cancellable?: Gio.Cancellable | null): number; vfunc_can_poll(): boolean; vfunc_create_source(cancellable?: Gio.Cancellable | null): GLib.Source; vfunc_is_readable(): boolean; vfunc_read_nonblocking(buffer?: Uint8Array | null): number; } export module ProxyResolverDefault { export interface ConstructorProperties extends GObject.Object.ConstructorProperties { [key: string]: any; gproxy_resolver: Gio.ProxyResolver; gproxyResolver: Gio.ProxyResolver; } } export class ProxyResolverDefault extends GObject.Object implements ProxyURIResolver, SessionFeature { static $gtype: GObject.GType<ProxyResolverDefault>; constructor(properties?: Partial<ProxyResolverDefault.ConstructorProperties>, ...args: any[]); _init(properties?: Partial<ProxyResolverDefault.ConstructorProperties>, ...args: any[]): void; // Properties gproxy_resolver: Gio.ProxyResolver; gproxyResolver: Gio.ProxyResolver; // Implemented Members get_proxy_uri_async( uri: URI, async_context: GLib.MainContext | null, cancellable: Gio.Cancellable | null, callback: ProxyURIResolverCallback ): void; get_proxy_uri_sync(uri: URI, cancellable: Gio.Cancellable | null): [number, URI]; vfunc_get_proxy_uri_async( uri: URI, async_context: GLib.MainContext | null, cancellable: Gio.Cancellable | null, callback: ProxyURIResolverCallback ): void; vfunc_get_proxy_uri_sync(uri: URI, cancellable: Gio.Cancellable | null): [number, URI]; add_feature(type: GObject.GType): boolean; attach(session: Session): void; detach(session: Session): void; has_feature(type: GObject.GType): boolean; remove_feature(type: GObject.GType): boolean; vfunc_add_feature(type: GObject.GType): boolean; vfunc_attach(session: Session): void; vfunc_detach(session: Session): void; vfunc_has_feature(type: GObject.GType): boolean; vfunc_remove_feature(type: GObject.GType): boolean; vfunc_request_queued(session: Session, msg: Message): void; vfunc_request_started(session: Session, msg: Message, socket: Socket): void; vfunc_request_unqueued(session: Session, msg: Message): void; } export module Request { export interface ConstructorProperties extends GObject.Object.ConstructorProperties { [key: string]: any; session: Session; uri: URI; } } export class Request extends GObject.Object implements Gio.Initable { static $gtype: GObject.GType<Request>; constructor(properties?: Partial<Request.ConstructorProperties>, ...args: any[]); _init(properties?: Partial<Request.ConstructorProperties>, ...args: any[]): void; // Properties session: Session; uri: URI; // Fields priv: RequestPrivate; // Members get_content_length(): number; get_content_type(): string | null; get_session(): Session; get_uri(): URI; send(cancellable?: Gio.Cancellable | null): Gio.InputStream; send_async(cancellable?: Gio.Cancellable | null): Promise<Gio.InputStream>; send_async(cancellable: Gio.Cancellable | null, callback: Gio.AsyncReadyCallback<this> | null): void; send_async( cancellable?: Gio.Cancellable | null, callback?: Gio.AsyncReadyCallback<this> | null ): Promise<Gio.InputStream> | void; send_finish(result: Gio.AsyncResult): Gio.InputStream; vfunc_check_uri(uri: URI): boolean; vfunc_get_content_length(): number; vfunc_get_content_type(): string | null; vfunc_send(cancellable?: Gio.Cancellable | null): Gio.InputStream; vfunc_send_async(cancellable?: Gio.Cancellable | null): Promise<Gio.InputStream>; vfunc_send_async(cancellable: Gio.Cancellable | null, callback: Gio.AsyncReadyCallback<this> | null): void; vfunc_send_async( cancellable?: Gio.Cancellable | null, callback?: Gio.AsyncReadyCallback<this> | null ): Promise<Gio.InputStream> | void; vfunc_send_finish(result: Gio.AsyncResult): Gio.InputStream; // Implemented Members init(cancellable?: Gio.Cancellable | null): boolean; vfunc_init(cancellable?: Gio.Cancellable | null): boolean; } export module RequestData { export interface ConstructorProperties extends Request.ConstructorProperties { [key: string]: any; } } export class RequestData extends Request implements Gio.Initable { static $gtype: GObject.GType<RequestData>; constructor(properties?: Partial<RequestData.ConstructorProperties>, ...args: any[]); _init(properties?: Partial<RequestData.ConstructorProperties>, ...args: any[]): void; // Fields priv: RequestDataPrivate | any; // Implemented Members init(cancellable?: Gio.Cancellable | null): boolean; vfunc_init(cancellable?: Gio.Cancellable | null): boolean; } export module RequestFile { export interface ConstructorProperties extends Request.ConstructorProperties { [key: string]: any; } } export class RequestFile extends Request implements Gio.Initable { static $gtype: GObject.GType<RequestFile>; constructor(properties?: Partial<RequestFile.ConstructorProperties>, ...args: any[]); _init(properties?: Partial<RequestFile.ConstructorProperties>, ...args: any[]): void; // Fields priv: RequestFilePrivate | any; // Members get_file(): Gio.File; // Implemented Members init(cancellable?: Gio.Cancellable | null): boolean; vfunc_init(cancellable?: Gio.Cancellable | null): boolean; } export module RequestHTTP { export interface ConstructorProperties extends Request.ConstructorProperties { [key: string]: any; } } export class RequestHTTP extends Request implements Gio.Initable { static $gtype: GObject.GType<RequestHTTP>; constructor(properties?: Partial<RequestHTTP.ConstructorProperties>, ...args: any[]); _init(properties?: Partial<RequestHTTP.ConstructorProperties>, ...args: any[]): void; // Fields priv: RequestHTTPPrivate | any; // Members get_message(): Message; // Implemented Members init(cancellable?: Gio.Cancellable | null): boolean; vfunc_init(cancellable?: Gio.Cancellable | null): boolean; } export module Requester { export interface ConstructorProperties extends GObject.Object.ConstructorProperties { [key: string]: any; } } export class Requester extends GObject.Object implements SessionFeature { static $gtype: GObject.GType<Requester>; constructor(properties?: Partial<Requester.ConstructorProperties>, ...args: any[]); _init(properties?: Partial<Requester.ConstructorProperties>, ...args: any[]): void; // Fields priv: RequesterPrivate; // Constructors static ["new"](): Requester; // Members request(uri_string: string): Request; request_uri(uri: URI): Request; // Implemented Members add_feature(type: GObject.GType): boolean; attach(session: Session): void; detach(session: Session): void; has_feature(type: GObject.GType): boolean; remove_feature(type: GObject.GType): boolean; vfunc_add_feature(type: GObject.GType): boolean; vfunc_attach(session: Session): void; vfunc_detach(session: Session): void; vfunc_has_feature(type: GObject.GType): boolean; vfunc_remove_feature(type: GObject.GType): boolean; vfunc_request_queued(session: Session, msg: Message): void; vfunc_request_started(session: Session, msg: Message, socket: Socket): void; vfunc_request_unqueued(session: Session, msg: Message): void; } export module Server { export interface ConstructorProperties extends GObject.Object.ConstructorProperties { [key: string]: any; async_context: any; asyncContext: any; http_aliases: string[]; httpAliases: string[]; https_aliases: string[]; httpsAliases: string[]; interface: Address; port: number; raw_paths: boolean; rawPaths: boolean; server_header: string; serverHeader: string; ssl_cert_file: string; sslCertFile: string; ssl_key_file: string; sslKeyFile: string; tls_certificate: Gio.TlsCertificate; tlsCertificate: Gio.TlsCertificate; } } export class Server extends GObject.Object { static $gtype: GObject.GType<Server>; constructor(properties?: Partial<Server.ConstructorProperties>, ...args: any[]); _init(properties?: Partial<Server.ConstructorProperties>, ...args: any[]): void; // Properties async_context: any; asyncContext: any; http_aliases: string[]; httpAliases: string[]; https_aliases: string[]; httpsAliases: string[]; "interface": Address; port: number; raw_paths: boolean; rawPaths: boolean; server_header: string; serverHeader: string; ssl_cert_file: string; sslCertFile: string; ssl_key_file: string; sslKeyFile: string; tls_certificate: Gio.TlsCertificate; tlsCertificate: Gio.TlsCertificate; // Signals connect(id: string, callback: (...args: any[]) => any): number; connect_after(id: string, callback: (...args: any[]) => any): number; emit(id: string, ...args: any[]): void; connect( signal: "request-aborted", callback: (_source: this, message: Message, client: ClientContext) => void ): number; connect_after( signal: "request-aborted", callback: (_source: this, message: Message, client: ClientContext) => void ): number; emit(signal: "request-aborted", message: Message, client: ClientContext): void; connect( signal: "request-finished", callback: (_source: this, message: Message, client: ClientContext) => void ): number; connect_after( signal: "request-finished", callback: (_source: this, message: Message, client: ClientContext) => void ): number; emit(signal: "request-finished", message: Message, client: ClientContext): void; connect(signal: "request-read", callback: (_source: this, message: Message, client: ClientContext) => void): number; connect_after( signal: "request-read", callback: (_source: this, message: Message, client: ClientContext) => void ): number; emit(signal: "request-read", message: Message, client: ClientContext): void; connect( signal: "request-started", callback: (_source: this, message: Message, client: ClientContext) => void ): number; connect_after( signal: "request-started", callback: (_source: this, message: Message, client: ClientContext) => void ): number; emit(signal: "request-started", message: Message, client: ClientContext): void; // Members accept_iostream( stream: Gio.IOStream, local_addr?: Gio.SocketAddress | null, remote_addr?: Gio.SocketAddress | null ): boolean; add_auth_domain(auth_domain: AuthDomain): void; add_early_handler(path: string | null, callback: ServerCallback): void; add_handler(path: string | null, callback: ServerCallback): void; add_websocket_extension(extension_type: GObject.GType): void; add_websocket_handler( path: string | null, origin: string | null, protocols: string[] | null, callback: ServerWebsocketCallback ): void; disconnect(): void; disconnect(...args: never[]): never; get_async_context(): GLib.MainContext | null; get_listener(): Socket; get_listeners(): Gio.Socket[]; get_port(): number; get_uris(): URI[]; is_https(): boolean; listen(address: Gio.SocketAddress, options: ServerListenOptions): boolean; listen_all(port: number, options: ServerListenOptions): boolean; listen_fd(fd: number, options: ServerListenOptions): boolean; listen_local(port: number, options: ServerListenOptions): boolean; listen_socket(socket: Gio.Socket, options: ServerListenOptions): boolean; pause_message(msg: Message): void; quit(): void; remove_auth_domain(auth_domain: AuthDomain): void; remove_handler(path: string): void; remove_websocket_extension(extension_type: GObject.GType): void; run(): void; run_async(): void; set_ssl_cert_file(ssl_cert_file: string, ssl_key_file: string): boolean; unpause_message(msg: Message): void; vfunc_request_aborted(msg: Message, client: ClientContext): void; vfunc_request_finished(msg: Message, client: ClientContext): void; vfunc_request_read(msg: Message, client: ClientContext): void; vfunc_request_started(msg: Message, client: ClientContext): void; } export module Session { export interface ConstructorProperties extends GObject.Object.ConstructorProperties { [key: string]: any; accept_language: string; acceptLanguage: string; accept_language_auto: boolean; acceptLanguageAuto: boolean; async_context: any; asyncContext: any; http_aliases: string[]; httpAliases: string[]; https_aliases: string[]; httpsAliases: string[]; idle_timeout: number; idleTimeout: number; local_address: Address; localAddress: Address; max_conns: number; maxConns: number; max_conns_per_host: number; maxConnsPerHost: number; proxy_resolver: Gio.ProxyResolver; proxyResolver: Gio.ProxyResolver; proxy_uri: URI; proxyUri: URI; ssl_ca_file: string; sslCaFile: string; ssl_strict: boolean; sslStrict: boolean; ssl_use_system_ca_file: boolean; sslUseSystemCaFile: boolean; timeout: number; tls_database: Gio.TlsDatabase; tlsDatabase: Gio.TlsDatabase; tls_interaction: Gio.TlsInteraction; tlsInteraction: Gio.TlsInteraction; use_ntlm: boolean; useNtlm: boolean; use_thread_context: boolean; useThreadContext: boolean; user_agent: string; userAgent: string; } } export class Session extends GObject.Object { static $gtype: GObject.GType<Session>; constructor(properties?: Partial<Session.ConstructorProperties>, ...args: any[]); _init(properties?: Partial<Session.ConstructorProperties>, ...args: any[]): void; // Properties accept_language: string; acceptLanguage: string; accept_language_auto: boolean; acceptLanguageAuto: boolean; async_context: any; asyncContext: any; http_aliases: string[]; httpAliases: string[]; https_aliases: string[]; httpsAliases: string[]; idle_timeout: number; idleTimeout: number; local_address: Address; localAddress: Address; max_conns: number; maxConns: number; max_conns_per_host: number; maxConnsPerHost: number; proxy_resolver: Gio.ProxyResolver; proxyResolver: Gio.ProxyResolver; proxy_uri: URI; proxyUri: URI; ssl_ca_file: string; sslCaFile: string; ssl_strict: boolean; sslStrict: boolean; ssl_use_system_ca_file: boolean; sslUseSystemCaFile: boolean; timeout: number; tls_database: Gio.TlsDatabase; tlsDatabase: Gio.TlsDatabase; tls_interaction: Gio.TlsInteraction; tlsInteraction: Gio.TlsInteraction; use_ntlm: boolean; useNtlm: boolean; use_thread_context: boolean; useThreadContext: boolean; user_agent: string; userAgent: string; // Signals connect(id: string, callback: (...args: any[]) => any): number; connect_after(id: string, callback: (...args: any[]) => any): number; emit(id: string, ...args: any[]): void; connect( signal: "authenticate", callback: (_source: this, msg: Message, auth: Auth, retrying: boolean) => void ): number; connect_after( signal: "authenticate", callback: (_source: this, msg: Message, auth: Auth, retrying: boolean) => void ): number; emit(signal: "authenticate", msg: Message, auth: Auth, retrying: boolean): void; connect(signal: "connection-created", callback: (_source: this, connection: GObject.Object) => void): number; connect_after(signal: "connection-created", callback: (_source: this, connection: GObject.Object) => void): number; emit(signal: "connection-created", connection: GObject.Object): void; connect(signal: "request-queued", callback: (_source: this, msg: Message) => void): number; connect_after(signal: "request-queued", callback: (_source: this, msg: Message) => void): number; emit(signal: "request-queued", msg: Message): void; connect(signal: "request-started", callback: (_source: this, msg: Message, socket: Socket) => void): number; connect_after(signal: "request-started", callback: (_source: this, msg: Message, socket: Socket) => void): number; emit(signal: "request-started", msg: Message, socket: Socket): void; connect(signal: "request-unqueued", callback: (_source: this, msg: Message) => void): number; connect_after(signal: "request-unqueued", callback: (_source: this, msg: Message) => void): number; emit(signal: "request-unqueued", msg: Message): void; connect(signal: "tunneling", callback: (_source: this, connection: GObject.Object) => void): number; connect_after(signal: "tunneling", callback: (_source: this, connection: GObject.Object) => void): number; emit(signal: "tunneling", connection: GObject.Object): void; // Constructors static ["new"](): Session; // Members abort(): void; add_feature(feature: SessionFeature): void; add_feature_by_type(feature_type: GObject.GType): void; cancel_message(msg: Message, status_code: number): void; connect_async( uri: URI, cancellable?: Gio.Cancellable | null, progress_callback?: SessionConnectProgressCallback | null ): Promise<Gio.IOStream>; connect_async( uri: URI, cancellable: Gio.Cancellable | null, progress_callback: SessionConnectProgressCallback | null, callback: Gio.AsyncReadyCallback<this> | null ): void; connect_async( uri: URI, cancellable?: Gio.Cancellable | null, progress_callback?: SessionConnectProgressCallback | null, callback?: Gio.AsyncReadyCallback<this> | null ): Promise<Gio.IOStream> | void; connect_finish(result: Gio.AsyncResult): Gio.IOStream; get_async_context(): GLib.MainContext | null; get_feature(feature_type: GObject.GType): SessionFeature | null; get_feature_for_message(feature_type: GObject.GType, msg: Message): SessionFeature | null; get_features(feature_type: GObject.GType): SessionFeature[]; has_feature(feature_type: GObject.GType): boolean; pause_message(msg: Message): void; prefetch_dns(hostname: string, cancellable?: Gio.Cancellable | null, callback?: AddressCallback | null): void; prepare_for_uri(uri: URI): void; queue_message(msg: Message, callback?: SessionCallback | null): void; redirect_message(msg: Message): boolean; remove_feature(feature: SessionFeature): void; remove_feature_by_type(feature_type: GObject.GType): void; request(uri_string: string): Request; request_http(method: string, uri_string: string): RequestHTTP; request_http_uri(method: string, uri: URI): RequestHTTP; request_uri(uri: URI): Request; requeue_message(msg: Message): void; send(msg: Message, cancellable?: Gio.Cancellable | null): Gio.InputStream; send_async(msg: Message, cancellable?: Gio.Cancellable | null): Promise<Gio.InputStream>; send_async(msg: Message, cancellable: Gio.Cancellable | null, callback: Gio.AsyncReadyCallback<this> | null): void; send_async( msg: Message, cancellable?: Gio.Cancellable | null, callback?: Gio.AsyncReadyCallback<this> | null ): Promise<Gio.InputStream> | void; send_finish(result: Gio.AsyncResult): Gio.InputStream; send_message(msg: Message): number; steal_connection(msg: Message): Gio.IOStream; unpause_message(msg: Message): void; websocket_connect_async( msg: Message, origin?: string | null, protocols?: string[] | null, cancellable?: Gio.Cancellable | null ): Promise<WebsocketConnection>; websocket_connect_async( msg: Message, origin: string | null, protocols: string[] | null, cancellable: Gio.Cancellable | null, callback: Gio.AsyncReadyCallback<this> | null ): void; websocket_connect_async( msg: Message, origin?: string | null, protocols?: string[] | null, cancellable?: Gio.Cancellable | null, callback?: Gio.AsyncReadyCallback<this> | null ): Promise<WebsocketConnection> | void; websocket_connect_finish(result: Gio.AsyncResult): WebsocketConnection; would_redirect(msg: Message): boolean; vfunc_auth_required(msg: Message, auth: Auth, retrying: boolean): void; vfunc_authenticate(msg: Message, auth: Auth, retrying: boolean): void; vfunc_cancel_message(msg: Message, status_code: number): void; vfunc_flush_queue(): void; vfunc_kick(): void; vfunc_queue_message(msg: Message, callback?: SessionCallback | null): void; vfunc_request_started(msg: Message, socket: Socket): void; vfunc_requeue_message(msg: Message): void; vfunc_send_message(msg: Message): number; } export module SessionAsync { export interface ConstructorProperties extends Session.ConstructorProperties { [key: string]: any; } } export class SessionAsync extends Session { static $gtype: GObject.GType<SessionAsync>; constructor(properties?: Partial<SessionAsync.ConstructorProperties>, ...args: any[]); _init(properties?: Partial<SessionAsync.ConstructorProperties>, ...args: any[]): void; // Constructors static ["new"](): SessionAsync; } export module SessionSync { export interface ConstructorProperties extends Session.ConstructorProperties { [key: string]: any; } } export class SessionSync extends Session { static $gtype: GObject.GType<SessionSync>; constructor(properties?: Partial<SessionSync.ConstructorProperties>, ...args: any[]); _init(properties?: Partial<SessionSync.ConstructorProperties>, ...args: any[]): void; // Constructors static ["new"](): SessionSync; } export module Socket { export interface ConstructorProperties extends GObject.Object.ConstructorProperties { [key: string]: any; async_context: any; asyncContext: any; fd: number; gsocket: Gio.Socket; iostream: Gio.IOStream; ipv6_only: boolean; ipv6Only: boolean; is_server: boolean; isServer: boolean; local_address: Address; localAddress: Address; non_blocking: boolean; nonBlocking: boolean; remote_address: Address; remoteAddress: Address; ssl_creds: any; sslCreds: any; ssl_fallback: boolean; sslFallback: boolean; ssl_strict: boolean; sslStrict: boolean; timeout: number; tls_certificate: Gio.TlsCertificate; tlsCertificate: Gio.TlsCertificate; tls_errors: Gio.TlsCertificateFlags; tlsErrors: Gio.TlsCertificateFlags; trusted_certificate: boolean; trustedCertificate: boolean; use_thread_context: boolean; useThreadContext: boolean; } } export class Socket extends GObject.Object implements Gio.Initable { static $gtype: GObject.GType<Socket>; constructor(properties?: Partial<Socket.ConstructorProperties>, ...args: any[]); _init(properties?: Partial<Socket.ConstructorProperties>, ...args: any[]): void; // Properties async_context: any; asyncContext: any; fd: number; gsocket: Gio.Socket; iostream: Gio.IOStream; ipv6_only: boolean; ipv6Only: boolean; is_server: boolean; isServer: boolean; local_address: Address; localAddress: Address; non_blocking: boolean; nonBlocking: boolean; remote_address: Address; remoteAddress: Address; ssl_creds: any; sslCreds: any; ssl_fallback: boolean; sslFallback: boolean; ssl_strict: boolean; sslStrict: boolean; timeout: number; tls_certificate: Gio.TlsCertificate; tlsCertificate: Gio.TlsCertificate; tls_errors: Gio.TlsCertificateFlags; tlsErrors: Gio.TlsCertificateFlags; trusted_certificate: boolean; trustedCertificate: boolean; use_thread_context: boolean; useThreadContext: boolean; // Signals connect(id: string, callback: (...args: any[]) => any): number; connect_after(id: string, callback: (...args: any[]) => any): number; emit(id: string, ...args: any[]): void; connect(signal: "disconnected", callback: (_source: this) => void): number; connect_after(signal: "disconnected", callback: (_source: this) => void): number; emit(signal: "disconnected"): void; connect( signal: "event", callback: (_source: this, event: Gio.SocketClientEvent, connection: Gio.IOStream) => void ): number; connect_after( signal: "event", callback: (_source: this, event: Gio.SocketClientEvent, connection: Gio.IOStream) => void ): number; emit(signal: "event", event: Gio.SocketClientEvent, connection: Gio.IOStream): void; connect(signal: "new-connection", callback: (_source: this, _new: Socket) => void): number; connect_after(signal: "new-connection", callback: (_source: this, _new: Socket) => void): number; emit(signal: "new-connection", _new: Socket): void; connect(signal: "readable", callback: (_source: this) => void): number; connect_after(signal: "readable", callback: (_source: this) => void): number; emit(signal: "readable"): void; connect(signal: "writable", callback: (_source: this) => void): number; connect_after(signal: "writable", callback: (_source: this) => void): number; emit(signal: "writable"): void; // Members connect_async(cancellable: Gio.Cancellable | null, callback: SocketCallback): void; connect_sync(cancellable?: Gio.Cancellable | null): number; disconnect(): void; disconnect(...args: never[]): never; get_fd(): number; get_local_address(): Address; get_remote_address(): Address; is_connected(): boolean; is_ssl(): boolean; listen(): boolean; read(buffer: Uint8Array | string, cancellable?: Gio.Cancellable | null): [SocketIOStatus, number]; read_until( buffer: Uint8Array | string, boundary: any | null, boundary_len: number, got_boundary: boolean, cancellable?: Gio.Cancellable | null ): [SocketIOStatus, number]; start_proxy_ssl(ssl_host: string, cancellable?: Gio.Cancellable | null): boolean; start_ssl(cancellable?: Gio.Cancellable | null): boolean; write(buffer: Uint8Array | string, cancellable?: Gio.Cancellable | null): [SocketIOStatus, number]; vfunc_disconnected(): void; vfunc_new_connection(new_sock: Socket): void; vfunc_readable(): void; vfunc_writable(): void; // Implemented Members init(cancellable?: Gio.Cancellable | null): boolean; vfunc_init(cancellable?: Gio.Cancellable | null): boolean; } export module WebsocketConnection { export interface ConstructorProperties extends GObject.Object.ConstructorProperties { [key: string]: any; connection_type: WebsocketConnectionType; connectionType: WebsocketConnectionType; extensions: any; io_stream: Gio.IOStream; ioStream: Gio.IOStream; keepalive_interval: number; keepaliveInterval: number; max_incoming_payload_size: number; maxIncomingPayloadSize: number; origin: string; protocol: string; state: WebsocketState; uri: URI; } } export class WebsocketConnection extends GObject.Object { static $gtype: GObject.GType<WebsocketConnection>; constructor(properties?: Partial<WebsocketConnection.ConstructorProperties>, ...args: any[]); _init(properties?: Partial<WebsocketConnection.ConstructorProperties>, ...args: any[]): void; // Properties connection_type: WebsocketConnectionType; connectionType: WebsocketConnectionType; extensions: any; io_stream: Gio.IOStream; ioStream: Gio.IOStream; keepalive_interval: number; keepaliveInterval: number; max_incoming_payload_size: number; maxIncomingPayloadSize: number; origin: string; protocol: string; state: WebsocketState; uri: URI; // Signals connect(id: string, callback: (...args: any[]) => any): number; connect_after(id: string, callback: (...args: any[]) => any): number; emit(id: string, ...args: any[]): void; connect(signal: "closed", callback: (_source: this) => void): number; connect_after(signal: "closed", callback: (_source: this) => void): number; emit(signal: "closed"): void; connect(signal: "closing", callback: (_source: this) => void): number; connect_after(signal: "closing", callback: (_source: this) => void): number; emit(signal: "closing"): void; connect(signal: "error", callback: (_source: this, error: GLib.Error) => void): number; connect_after(signal: "error", callback: (_source: this, error: GLib.Error) => void): number; emit(signal: "error", error: GLib.Error): void; connect(signal: "message", callback: (_source: this, type: number, message: GLib.Bytes) => void): number; connect_after(signal: "message", callback: (_source: this, type: number, message: GLib.Bytes) => void): number; emit(signal: "message", type: number, message: GLib.Bytes | Uint8Array): void; connect(signal: "pong", callback: (_source: this, message: GLib.Bytes) => void): number; connect_after(signal: "pong", callback: (_source: this, message: GLib.Bytes) => void): number; emit(signal: "pong", message: GLib.Bytes | Uint8Array): void; // Constructors static ["new"]( stream: Gio.IOStream, uri: URI, type: WebsocketConnectionType, origin?: string | null, protocol?: string | null ): WebsocketConnection; static new_with_extensions( stream: Gio.IOStream, uri: URI, type: WebsocketConnectionType, origin: string | null, protocol: string | null, extensions: WebsocketExtension[] ): WebsocketConnection; // Members close(code: number, data?: string | null): void; get_close_code(): number; get_close_data(): string; get_connection_type(): WebsocketConnectionType; get_extensions(): WebsocketExtension[]; get_io_stream(): Gio.IOStream; get_keepalive_interval(): number; get_max_incoming_payload_size(): number; get_origin(): string | null; get_protocol(): string | null; get_state(): WebsocketState; get_uri(): URI; send_binary(data?: Uint8Array | null): void; send_message(type: WebsocketDataType, message: GLib.Bytes | Uint8Array): void; send_text(text: string): void; set_keepalive_interval(interval: number): void; set_max_incoming_payload_size(max_incoming_payload_size: number): void; vfunc_closed(): void; vfunc_closing(): void; vfunc_error(error: GLib.Error): void; vfunc_message(type: WebsocketDataType, message: GLib.Bytes | Uint8Array): void; vfunc_pong(message: GLib.Bytes | Uint8Array): void; } export module WebsocketExtension { export interface ConstructorProperties extends GObject.Object.ConstructorProperties { [key: string]: any; } } export abstract class WebsocketExtension extends GObject.Object { static $gtype: GObject.GType<WebsocketExtension>; constructor(properties?: Partial<WebsocketExtension.ConstructorProperties>, ...args: any[]); _init(properties?: Partial<WebsocketExtension.ConstructorProperties>, ...args: any[]): void; // Members configure(connection_type: WebsocketConnectionType, params?: GLib.HashTable<any, any> | null): boolean; get_request_params(): string | null; get_response_params(): string | null; process_incoming_message(header: number, payload: GLib.Bytes | Uint8Array): [GLib.Bytes, number]; process_outgoing_message(header: number, payload: GLib.Bytes | Uint8Array): [GLib.Bytes, number]; vfunc_configure(connection_type: WebsocketConnectionType, params?: GLib.HashTable<any, any> | null): boolean; vfunc_get_request_params(): string | null; vfunc_get_response_params(): string | null; vfunc_process_incoming_message(header: number, payload: GLib.Bytes | Uint8Array): [GLib.Bytes, number]; vfunc_process_outgoing_message(header: number, payload: GLib.Bytes | Uint8Array): [GLib.Bytes, number]; } export module WebsocketExtensionDeflate { export interface ConstructorProperties extends WebsocketExtension.ConstructorProperties { [key: string]: any; } } export class WebsocketExtensionDeflate extends WebsocketExtension { static $gtype: GObject.GType<WebsocketExtensionDeflate>; constructor(properties?: Partial<WebsocketExtensionDeflate.ConstructorProperties>, ...args: any[]); _init(properties?: Partial<WebsocketExtensionDeflate.ConstructorProperties>, ...args: any[]): void; } export module WebsocketExtensionManager { export interface ConstructorProperties extends GObject.Object.ConstructorProperties { [key: string]: any; } } export class WebsocketExtensionManager extends GObject.Object implements SessionFeature { static $gtype: GObject.GType<WebsocketExtensionManager>; constructor(properties?: Partial<WebsocketExtensionManager.ConstructorProperties>, ...args: any[]); _init(properties?: Partial<WebsocketExtensionManager.ConstructorProperties>, ...args: any[]): void; // Implemented Members add_feature(type: GObject.GType): boolean; attach(session: Session): void; detach(session: Session): void; has_feature(type: GObject.GType): boolean; remove_feature(type: GObject.GType): boolean; vfunc_add_feature(type: GObject.GType): boolean; vfunc_attach(session: Session): void; vfunc_detach(session: Session): void; vfunc_has_feature(type: GObject.GType): boolean; vfunc_remove_feature(type: GObject.GType): boolean; vfunc_request_queued(session: Session, msg: Message): void; vfunc_request_started(session: Session, msg: Message, socket: Socket): void; vfunc_request_unqueued(session: Session, msg: Message): void; } export class AuthManagerPrivate { static $gtype: GObject.GType<AuthManagerPrivate>; constructor(copy: AuthManagerPrivate); } export class Buffer { static $gtype: GObject.GType<Buffer>; constructor(use: MemoryUse, data: Uint8Array | string); constructor( properties?: Partial<{ data?: any; length?: number; }> ); constructor(copy: Buffer); // Fields data: any; length: number; // Constructors static ["new"](use: MemoryUse, data: Uint8Array | string): Buffer; static ["new"](data: Uint8Array | string): Buffer; static new_with_owner( data: Uint8Array | string, owner?: any | null, owner_dnotify?: GLib.DestroyNotify | null ): Buffer; // Members copy(): Buffer; free(): void; get_as_bytes(): GLib.Bytes; get_data(): Uint8Array; get_owner(): any | null; new_subbuffer(offset: number, length: number): Buffer; } export class CachePrivate { static $gtype: GObject.GType<CachePrivate>; constructor(copy: CachePrivate); } export class ClientContext { static $gtype: GObject.GType<ClientContext>; constructor(copy: ClientContext); // Members get_address(): Address | null; get_auth_domain(): AuthDomain | null; get_auth_user(): string | null; get_gsocket(): Gio.Socket | null; get_host(): string | null; get_local_address(): Gio.SocketAddress | null; get_remote_address(): Gio.SocketAddress | null; get_socket(): Socket; steal_connection(): Gio.IOStream; } export class Connection { static $gtype: GObject.GType<Connection>; constructor(copy: Connection); } export class ContentDecoderPrivate { static $gtype: GObject.GType<ContentDecoderPrivate>; constructor(copy: ContentDecoderPrivate); } export class ContentSnifferPrivate { static $gtype: GObject.GType<ContentSnifferPrivate>; constructor(copy: ContentSnifferPrivate); } export class Cookie { static $gtype: GObject.GType<Cookie>; constructor(name: string, value: string, domain: string, path: string, max_age: number); constructor( properties?: Partial<{ name?: string; value?: string; domain?: string; path?: string; expires?: Date; secure?: boolean; http_only?: boolean; }> ); constructor(copy: Cookie); // Fields name: string; value: string; domain: string; path: string; expires: Date; secure: boolean; http_only: boolean; // Constructors static ["new"](name: string, value: string, domain: string, path: string, max_age: number): Cookie; // Members applies_to_uri(uri: URI): boolean; copy(): Cookie; domain_matches(host: string): boolean; equal(cookie2: Cookie): boolean; free(): void; get_domain(): string; get_expires(): Date | null; get_http_only(): boolean; get_name(): string; get_path(): string; get_same_site_policy(): SameSitePolicy; get_secure(): boolean; get_value(): string; set_domain(domain: string): void; set_expires(expires: Date): void; set_http_only(http_only: boolean): void; set_max_age(max_age: number): void; set_name(name: string): void; set_path(path: string): void; set_same_site_policy(policy: SameSitePolicy): void; set_secure(secure: boolean): void; set_value(value: string): void; to_cookie_header(): string; to_set_cookie_header(): string; static parse(header: string, origin: URI): Cookie | null; } export class Date { static $gtype: GObject.GType<Date>; constructor(year: number, month: number, day: number, hour: number, minute: number, second: number); constructor( properties?: Partial<{ year?: number; month?: number; day?: number; hour?: number; minute?: number; second?: number; utc?: boolean; offset?: number; }> ); constructor(copy: Date); // Fields year: number; month: number; day: number; hour: number; minute: number; second: number; utc: boolean; offset: number; // Constructors static ["new"](year: number, month: number, day: number, hour: number, minute: number, second: number): Date; static new_from_now(offset_seconds: number): Date; static new_from_string(date_string: string): Date; static new_from_time_t(when: number): Date; // Members copy(): Date; free(): void; get_day(): number; get_hour(): number; get_minute(): number; get_month(): number; get_offset(): number; get_second(): number; get_utc(): number; get_year(): number; is_past(): boolean; to_string(format: DateFormat): string; to_time_t(): number; to_timeval(): GLib.TimeVal; } export class HSTSEnforcerDBPrivate { static $gtype: GObject.GType<HSTSEnforcerDBPrivate>; constructor(copy: HSTSEnforcerDBPrivate); } export class HSTSEnforcerPrivate { static $gtype: GObject.GType<HSTSEnforcerPrivate>; constructor(copy: HSTSEnforcerPrivate); } export class HSTSPolicy { static $gtype: GObject.GType<HSTSPolicy>; constructor(domain: string, max_age: number, include_subdomains: boolean); constructor( properties?: Partial<{ domain?: string; max_age?: number; expires?: Date; include_subdomains?: boolean; }> ); constructor(copy: HSTSPolicy); // Fields domain: string; max_age: number; expires: Date; include_subdomains: boolean; // Constructors static ["new"](domain: string, max_age: number, include_subdomains: boolean): HSTSPolicy; static new_from_response(msg: Message): HSTSPolicy; static new_full(domain: string, max_age: number, expires: Date, include_subdomains: boolean): HSTSPolicy; static new_session_policy(domain: string, include_subdomains: boolean): HSTSPolicy; // Members copy(): HSTSPolicy; equal(policy2: HSTSPolicy): boolean; free(): void; get_domain(): string; includes_subdomains(): boolean; is_expired(): boolean; is_session_policy(): boolean; } export class MessageBody { static $gtype: GObject.GType<MessageBody>; constructor(); constructor( properties?: Partial<{ data?: string; length?: number; }> ); constructor(copy: MessageBody); // Fields data: string; length: number; // Constructors static ["new"](): MessageBody; // Members append(use: MemoryUse, data: Uint8Array | string): void; append_buffer(buffer: Buffer): void; append(data: Uint8Array | string): void; complete(): void; flatten(): Buffer; free(): void; get_accumulate(): boolean; get_chunk(offset: number): Buffer | null; got_chunk(chunk: Buffer): void; set_accumulate(accumulate: boolean): void; truncate(): void; wrote_chunk(chunk: Buffer): void; } export class MessageHeaders { static $gtype: GObject.GType<MessageHeaders>; constructor(type: MessageHeadersType); constructor(copy: MessageHeaders); // Constructors static ["new"](type: MessageHeadersType): MessageHeaders; // Members append(name: string, value: string): void; clean_connection_headers(): void; clear(): void; foreach(func: MessageHeadersForeachFunc): void; free(): void; free_ranges(ranges: Range): void; get(name: string): string | null; get_content_disposition(): [boolean, string, GLib.HashTable<string, string>]; get_content_length(): number; get_content_range(): [boolean, number, number, number | null]; get_content_type(): [string | null, GLib.HashTable<string, string> | null]; get_encoding(): Encoding; get_expectations(): Expectation; get_headers_type(): MessageHeadersType; get_list(name: string): string | null; get_one(name: string): string | null; get_ranges(total_length: number): [boolean, Range[]]; header_contains(name: string, token: string): boolean; header_equals(name: string, value: string): boolean; remove(name: string): void; replace(name: string, value: string): void; set_content_disposition(disposition: string, params?: GLib.HashTable<string, string> | null): void; set_content_length(content_length: number): void; set_content_range(start: number, end: number, total_length: number): void; set_content_type(content_type: string, params?: GLib.HashTable<string, string> | null): void; set_encoding(encoding: Encoding): void; set_expectations(expectations: Expectation): void; set_range(start: number, end: number): void; set_ranges(ranges: Range, length: number): void; } export class MessageHeadersIter { static $gtype: GObject.GType<MessageHeadersIter>; constructor(copy: MessageHeadersIter); // Fields dummy: any[]; // Members next(): [boolean, string, string]; static init(hdrs: MessageHeaders): MessageHeadersIter; } export class MessageQueue { static $gtype: GObject.GType<MessageQueue>; constructor(copy: MessageQueue); } export class MessageQueueItem { static $gtype: GObject.GType<MessageQueueItem>; constructor(copy: MessageQueueItem); } export class Multipart { static $gtype: GObject.GType<Multipart>; constructor(mime_type: string); constructor(copy: Multipart); // Constructors static ["new"](mime_type: string): Multipart; static new_from_message(headers: MessageHeaders, body: MessageBody): Multipart; // Members append_form_file(control_name: string, filename: string, content_type: string, body: Buffer): void; append_form_string(control_name: string, data: string): void; append_part(headers: MessageHeaders, body: Buffer): void; free(): void; get_length(): number; get_part(part: number): [boolean, MessageHeaders, Buffer]; to_message(dest_headers: MessageHeaders, dest_body: MessageBody): void; } export class MultipartInputStreamPrivate { static $gtype: GObject.GType<MultipartInputStreamPrivate>; constructor(copy: MultipartInputStreamPrivate); } export class Range { static $gtype: GObject.GType<Range>; constructor( properties?: Partial<{ start?: number; end?: number; }> ); constructor(copy: Range); // Fields start: number; end: number; } export class RequestDataPrivate { static $gtype: GObject.GType<RequestDataPrivate>; constructor(copy: RequestDataPrivate); } export class RequestFilePrivate { static $gtype: GObject.GType<RequestFilePrivate>; constructor(copy: RequestFilePrivate); } export class RequestHTTPPrivate { static $gtype: GObject.GType<RequestHTTPPrivate>; constructor(copy: RequestHTTPPrivate); } export class RequestPrivate { static $gtype: GObject.GType<RequestPrivate>; constructor(copy: RequestPrivate); } export class RequesterPrivate { static $gtype: GObject.GType<RequesterPrivate>; constructor(copy: RequesterPrivate); } export class URI { static $gtype: GObject.GType<URI>; constructor(uri_string?: string | null); constructor( properties?: Partial<{ scheme?: string; user?: string; password?: string; host?: string; port?: number; path?: string; query?: string; fragment?: string; }> ); constructor(copy: URI); // Fields scheme: string; user: string; password: string; host: string; port: number; path: string; query: string; fragment: string; // Constructors static ["new"](uri_string?: string | null): URI; static new_with_base(base: URI, uri_string: string): URI; // Members copy(): URI; copy_host(): URI; equal(uri2: URI): boolean; free(): void; get_fragment(): string; get_host(): string; get_password(): string; get_path(): string; get_port(): number; get_query(): string; get_scheme(): string; get_user(): string; host_equal(v2: URI): boolean; host_hash(): number; set_fragment(fragment?: string | null): void; set_host(host?: string | null): void; set_password(password?: string | null): void; set_path(path: string): void; set_port(port: number): void; set_query(query?: string | null): void; set_query_from_form(form: GLib.HashTable<string, string>): void; set_scheme(scheme: string): void; set_user(user?: string | null): void; to_string(just_path_and_query: boolean): string; uses_default_port(): boolean; static decode(part: string): string; static encode(part: string, escape_extra?: string | null): string; static normalize(part: string, unescape_extra?: string | null): string; } export class WebsocketConnectionPrivate { static $gtype: GObject.GType<WebsocketConnectionPrivate>; constructor(copy: WebsocketConnectionPrivate); } export class XMLRPCParams { static $gtype: GObject.GType<XMLRPCParams>; constructor(copy: XMLRPCParams); // Members free(): void; parse(signature?: string | null): GLib.Variant; } export interface PasswordManagerNamespace { $gtype: GObject.GType<PasswordManager>; prototype: PasswordManagerPrototype; } export type PasswordManager = PasswordManagerPrototype; export interface PasswordManagerPrototype extends SessionFeature { // Members get_passwords_async( msg: Message, auth: Auth, retrying: boolean, async_context: GLib.MainContext, cancellable: Gio.Cancellable | null, callback: PasswordManagerCallback ): void; get_passwords_sync(msg: Message, auth: Auth, cancellable?: Gio.Cancellable | null): void; vfunc_get_passwords_async( msg: Message, auth: Auth, retrying: boolean, async_context: GLib.MainContext, cancellable: Gio.Cancellable | null, callback: PasswordManagerCallback ): void; vfunc_get_passwords_sync(msg: Message, auth: Auth, cancellable?: Gio.Cancellable | null): void; } export const PasswordManager: PasswordManagerNamespace; export interface ProxyResolverNamespace { $gtype: GObject.GType<ProxyResolver>; prototype: ProxyResolverPrototype; } export type ProxyResolver = ProxyResolverPrototype; export interface ProxyResolverPrototype extends SessionFeature { // Members get_proxy_async( msg: Message, async_context: GLib.MainContext, cancellable: Gio.Cancellable | null, callback: ProxyResolverCallback ): void; get_proxy_sync(msg: Message, cancellable: Gio.Cancellable | null): [number, Address]; vfunc_get_proxy_async( msg: Message, async_context: GLib.MainContext, cancellable: Gio.Cancellable | null, callback: ProxyResolverCallback ): void; vfunc_get_proxy_sync(msg: Message, cancellable: Gio.Cancellable | null): [number, Address]; } export const ProxyResolver: ProxyResolverNamespace; export interface ProxyURIResolverNamespace { $gtype: GObject.GType<ProxyURIResolver>; prototype: ProxyURIResolverPrototype; } export type ProxyURIResolver = ProxyURIResolverPrototype; export interface ProxyURIResolverPrototype extends SessionFeature { // Members get_proxy_uri_async( uri: URI, async_context: GLib.MainContext | null, cancellable: Gio.Cancellable | null, callback: ProxyURIResolverCallback ): void; get_proxy_uri_sync(uri: URI, cancellable: Gio.Cancellable | null): [number, URI]; vfunc_get_proxy_uri_async( uri: URI, async_context: GLib.MainContext | null, cancellable: Gio.Cancellable | null, callback: ProxyURIResolverCallback ): void; vfunc_get_proxy_uri_sync(uri: URI, cancellable: Gio.Cancellable | null): [number, URI]; } export const ProxyURIResolver: ProxyURIResolverNamespace; export interface SessionFeatureNamespace { $gtype: GObject.GType<SessionFeature>; prototype: SessionFeaturePrototype; } export type SessionFeature = SessionFeaturePrototype; export interface SessionFeaturePrototype extends GObject.Object { // Members add_feature(type: GObject.GType): boolean; attach(session: Session): void; detach(session: Session): void; has_feature(type: GObject.GType): boolean; remove_feature(type: GObject.GType): boolean; vfunc_add_feature(type: GObject.GType): boolean; vfunc_attach(session: Session): void; vfunc_detach(session: Session): void; vfunc_has_feature(type: GObject.GType): boolean; vfunc_remove_feature(type: GObject.GType): boolean; vfunc_request_queued(session: Session, msg: Message): void; vfunc_request_started(session: Session, msg: Message, socket: Socket): void; vfunc_request_unqueued(session: Session, msg: Message): void; } export const SessionFeature: SessionFeatureNamespace;
the_stack
module TDev { export module Collab { // ------------------ revisionservice collaboration API export interface CollaborationInfo { owner: string; ownerScriptguid: string; group: string; session: string; meta: string; } export function getSessionOwner(session: string): string { return session.substr(0, session.indexOf("0")); } export function getCollaborationsAsync(group: string): Promise { // CollaborationInfo[] var userid = Cloud.getUserId(); if (!userid) return undefined; return Revisions.getRevisionServiceTokenAsync().then((token) => { if (Cloud.isOffline()) return Promise.wrapError("Cloud is offline"); var url = Revisions.revisionservice_http() + "/collaborations/" + group + "?user=" + userid + "&access_token=" + encodeURIComponent(token); return Util.httpRequestAsync(url, "GET", undefined).then((s) => { var a = JSON.parse(s); if (Array.isArray(a)) return a.filter(j => (typeof j === "object")); }); }); } /*export function getCollaborationAsync(owner: string, scriptguid: string): Promise { // CollaborationInfo var sessionid = Revisions.astsessionid(owner, scriptguid); return Revisions.getRevisionServiceTokenAsync().then((token) => { if (Cloud.isOffline()) return Promise.wrapError("Cloud is offline"); var url = Revisions.revisionservice_http() + "/" + sessionid + "/collaboration" + "?user=" + owner + "&access_token=" + encodeURIComponent(token); return Util.httpRequestAsync(url, "GET", undefined).then((s) => { var x = JSON.parse(s); if (typeof x === "object") return <CollaborationInfo> x; }); }); }*/ export function startCollaborationAsync(scriptGuid: string, script: string, group: string): Promise { // session id TDev.tick(Ticks.collabStartCollaboration); var userid = Cloud.getUserId(); if (!userid) return undefined; var sessionid = Revisions.make_astsessionid(userid); var ci = <CollaborationInfo> {}; ci.owner = userid; ci.group = group; ci.ownerScriptguid = scriptGuid; ci.session = sessionid; ci["script"] = script; return Revisions.getRevisionServiceTokenAsync().then((token) => { if (Cloud.isOffline()) return Promise.wrapError("Cloud is offline"); var url = Revisions.revisionservice_http() + "/" + sessionid + "/collaboration" + "?user=" + userid + "&access_token=" + encodeURIComponent(token); return Util.httpRequestAsync(url, "POST", JSON.stringify(ci)).then( (s) => Editor.updateEditorStateAsync(scriptGuid, (st) => { st.collabSessionId = sessionid; st.groupId = this.publicId; }), (e) => { if (typeof (e) == "object" && e.errorMessage.indexOf("already in group") != -1) ModalDialog.info(lf("can't add twice"), lf("this script has already been added to a group.")); else if(typeof (e) == "object" && e.errorMessage.indexOf("invalid group") != -1) ModalDialog.info(lf("cannot add script to group"), lf("could not access this group.")); else if (typeof (e) == "object" && e.errorMessage.indexOf("not a group member") != -1) ModalDialog.info(lf("cannot add script to group"), lf("you are not a member of this group.")); else throw e; }); }); } export function stopCollaborationAsync(sessionid: string): Promise { // void TDev.tick(Ticks.collabStopCollaboration); var userid = Cloud.getUserId(); if (!userid) return undefined; var owner = Collab.getSessionOwner(sessionid); return Revisions.getRevisionServiceTokenAsync().then((token) => { if (Cloud.isOffline()) return Promise.wrapError("Cloud is offline"); var url = Revisions.revisionservice_http() + "/" + sessionid + "/collaboration" + "?user=" + userid + "&access_token=" + encodeURIComponent(token); return Util.httpRequestAsync(url, "DELETE", undefined).then((s) => { return; }); }); } /// -------- push and pull enable/disable // temporary pull suppression (initially false, controlled from editor while editing in calculator or other buffers) var pullIsTemporarilySuppressed: boolean = false; export function getTemporaryPullSuppression(): boolean { return pullIsTemporarilySuppressed; } export function setTemporaryPullSuppression(val: boolean) { if (pullIsTemporarilySuppressed == val) return; pullIsTemporarilySuppressed = val; if (ready && !val && delayed_pull) { // when suppression is over, pull now processAstTable(); } } // automatic push (initially true, setting is persisted on disk) var enable_automatic_push; export function getAutomaticPushEnabled(): boolean { return enable_automatic_push; } export function setAutomaticPushEnabled(val: boolean) { if (enable_automatic_push == val) return; enable_automatic_push = val; if (ready && val && delayed_push) // when turned on, push now pushAstToCloud(); } // automatic pull (initially true, setting is persisted on disk) var enable_automatic_pull; export function getAutomaticPullEnabled(): boolean { return enable_automatic_pull; } export function setAutomaticPullEnabled(val: boolean) { if (enable_automatic_pull == val) return; enable_automatic_pull = val; if (ready && val && delayed_pull) { // when turned on, pull now processAstTable(); } } /// ---------- chat & presence interface export function registerChangeHandler(handler: () => void) { changehandler = handler; } var changehandler: () => void; export function getConnectedUsers(): Revisions.Participant[]{ if (!AstSession || !AstSession.loaded || AstSession.faulted) return []; return AstSession.user_get_presence(); } export function postMessage(message: string) { TDev.tick(Ticks.collabPostChatMessage); if (!AstSession || !AstSession.loaded || AstSession.faulted) return; var uid = AstSession.user_create_item(ct_chatentry, [], []).uid; var userfield = AstSession.user_get_lval(ct_chattable_user, [uid], []) var timestampfield = AstSession.user_get_lval(ct_chattable_timestamp, [uid], []) var contentfield = AstSession.user_get_lval(ct_chattable_content, [uid], []) AstSession.user_modify_lval(userfield, Cloud.getUserId()); AstSession.user_modify_lval(timestampfield, new Date().toISOString()); AstSession.user_modify_lval(contentfield, message); AstSession.user_push(); } // This function is called by ast.ts, who notifies us when a new // statement becomes active. There's nothing to do if collaboration // isn't active. export function onActivation(stmt: AST.IStableNameEntry) { if (!AstSession || !AstSession.loaded || AstSession.faulted || !getAutomaticPushEnabled()) return; var action = TheEditor.currentAction(); // Happens when editing, say, a record definition, which _is_ an // [AST.Stmt] but isn't an action per se. if (!action) return; var stmtName: string = stmt ? stmt.getStableName() : ""; var actionName: string = action.getStableName(); var myNumber = AstSession.getMemberNumber(); if (myNumber === -1) { Util.log("Session not active yet! Not pushing info"); return; } var ct_lastedit = AstSession.user_get_lval(ct_participantindex_lastedit, [], [myNumber.toString()]); var ct_stmtname = AstSession.user_get_lval(ct_participantindex_stmtname, [], [myNumber.toString()]); var ct_actionname = AstSession.user_get_lval(ct_participantindex_actionname, [], [myNumber.toString()]); AstSession.user_modify_lval(ct_lastedit, new Date().toISOString()); AstSession.user_modify_lval(ct_stmtname, stmtName); AstSession.user_modify_lval(ct_actionname, actionName); AstSession.user_push(); } export interface IMessage { uid: string; user: string; timestamp: Date; content: string; confirmed: boolean; } export interface IParticipantInfo { lastEdit: Date; stmtName: string; actionName: string; sessionId: number; } var msg_expiration_msec = 15 * 60 * 1000; export function getLastTenMessages(): IMessage[]{ if (!AstSession || !AstSession.loaded || AstSession.faulted) return []; var items = AstSession.user_get_items_in_domain(ct_chatentry).sort((a, b) => a.compareTo(b)); var msgarray = []; var currenttime = new Date().getTime(); for (var i = 0; i < items.length; i++) { if (i < items.length - 10) AstSession.user_delete_item(items[i]); // delete all but 10 last messages else { var msg = <IMessage>{}; msg.uid = items[i].uid; var ukeys = [items[i].uid]; var lkeys = []; var timestampfield = AstSession.user_get_lval(ct_chattable_timestamp, ukeys, lkeys); var userfield = AstSession.user_get_lval(ct_chattable_user, ukeys, lkeys); var contentfield = AstSession.user_get_lval(ct_chattable_content, ukeys, lkeys); msg.user = AstSession.user_get_value(userfield); msg.timestamp = new Date(AstSession.user_get_value(timestampfield)); msg.content = AstSession.user_get_value(contentfield); msg.confirmed = AstSession.user_is_datum_confirmed(items[i]); if (currenttime - msg.timestamp.getTime() > msg_expiration_msec) AstSession.user_delete_item(items[i]); else msgarray.push(msg); } } return msgarray; } function getParticipantInfo(aSessionId): IParticipantInfo { var lastEditLval = AstSession.user_get_lval(ct_participantindex_lastedit, [], [aSessionId.toString()]); var stmtNameLval = AstSession.user_get_lval(ct_participantindex_stmtname, [], [aSessionId.toString()]); var actionNameLval = AstSession.user_get_lval(ct_participantindex_actionname, [], [aSessionId.toString()]); // Abort if this is an empty entry. var d = AstSession.user_is_defaultvalue; if (d(lastEditLval) && d(stmtNameLval) && d(actionNameLval)) return null; var lastEdit = AstSession.user_is_defaultvalue(lastEditLval) ? null : new Date(AstSession.user_get_value(lastEditLval)); var stmtName = AstSession.user_get_value(stmtNameLval); var actionName = AstSession.user_get_value(actionNameLval); return { lastEdit: lastEdit, stmtName: stmtName, actionName: actionName, sessionId: aSessionId } } function clearParticipantInfo(aSessionId) { var lastEditLval = AstSession.user_get_lval(ct_participantindex_lastedit, [], [aSessionId.toString()]); var stmtNameLval = AstSession.user_get_lval(ct_participantindex_stmtname, [], [aSessionId.toString()]); var actionNameLval = AstSession.user_get_lval(ct_participantindex_actionname, [], [aSessionId.toString()]); AstSession.user_modify_lval(lastEditLval, ""); AstSession.user_modify_lval(stmtNameLval, ""); AstSession.user_modify_lval(actionNameLval, ""); } export function getActiveParticipants(): IParticipantInfo[] { var connectedUserSet: StringMap<boolean> = {}; getConnectedUsers().forEach((x: Revisions.Participant) => connectedUserSet[x.sessionId] = true); var r: IParticipantInfo[] = []; var entries = AstSession.user_get_entries_in_indexdomain(ct_participantindex); entries.forEach(function (e) { var sessionId = parseInt(e.lkeys[0]); if (!(sessionId in connectedUserSet)) return; var info = getParticipantInfo(sessionId); if (!info) return; if (!info.lastEdit || (Date.now() - info.lastEdit.getTime()) > msg_expiration_msec) { clearParticipantInfo(sessionId); } else { r.push(info); } }); // Don't forget to push our changes (i.e. outdated messages that we // removed from the index!). AstSession.user_push(); return r; } export function getLastActivity(aUserId): IParticipantInfo { var mostRecent = null; this.getConnectedUsers().forEach(u => { if (u.userId == aUserId) { var info = getParticipantInfo(u.sessionId); if (mostRecent == null || info.lastEdit && mostRecent.lastEdit < info.lastEdit) mostRecent = info; } }); return mostRecent; } // cloud types for snap chat var ct_chatentry = Revisions.Parser.MakeDomain("chat", Revisions.Parser.DOMAIN_DYNAMIC, []); var ct_chattable = Revisions.Parser.MakeDomain("chattable", Revisions.Parser.DOMAIN_STATIC, [ct_chatentry]); var ct_chattable_user = Revisions.Parser.MakeProperty("user", ct_chattable, "string"); var ct_chattable_timestamp = Revisions.Parser.MakeProperty("timestamp", ct_chattable, "string"); var ct_chattable_content = Revisions.Parser.MakeProperty("content", ct_chattable, "string"); // cloud types for participant var ct_participantindex_key = Revisions.Parser.MakeDomain("participant", Revisions.Parser.DOMAIN_BUILTIN, []); var ct_participantindex = Revisions.Parser.MakeDomain("participantindex", Revisions.Parser.DOMAIN_STATIC, [ct_participantindex_key]); var ct_participantindex_lastedit = Revisions.Parser.MakeProperty("lastedit", ct_participantindex, "string"); var ct_participantindex_stmtname = Revisions.Parser.MakeProperty("stmtname", ct_participantindex, "string"); var ct_participantindex_actionname = Revisions.Parser.MakeProperty("actionname", ct_participantindex, "string"); // cloud types for AST merging var cloudtype_delta = Revisions.Parser.MakeDomain("delta", Revisions.Parser.DOMAIN_DYNAMIC, []); var cloudtype_deltatable = Revisions.Parser.MakeDomain("deltatable", Revisions.Parser.DOMAIN_STATIC, [cloudtype_delta]); var cloudtype_pre = Revisions.Parser.MakeProperty("pre", cloudtype_deltatable, "ast"); var cloudtype_post = Revisions.Parser.MakeProperty("post", cloudtype_deltatable, "ast"); var cloudtype_merge = Revisions.Parser.MakeProperty("merge", cloudtype_deltatable, "ast"); var cloudtype_desc = Revisions.Parser.MakeProperty("desc", cloudtype_deltatable, "string"); var cloudtype_stats = Revisions.Parser.MakeProperty("stats", cloudtype_deltatable, "string"); /// ---------------- hooks that are called from editor // called when a new Script is loaded into the Editor export function setCollab(astsession: string) { if (!astsession) { Util.log(">>> Stop Collab! " + Script); astSessionSlot.disconnect(false, "collab turned off"); ready = false; loadPromise = undefined; readyPromise = undefined; } else { var userid = Cloud.getUserId(); // TODO prompt sign in? if (userid) { Util.log(">>> Start Collab! " + astsession); var desc = getAstSessionDescriptor(astsession); ready = false; var p = readyPromise = new PromiseInv(); loadPromise = new PromiseInv(); prevCloudAst = currentCloudAst = undefined; enable_automatic_pull = true; enable_automatic_push = true; astSessionSlot.connect(desc); // calls afterLoad() once file is loaded, before it connects } } } export var readyPromise: PromiseInv; export var loadPromise: PromiseInv; // called immediately after the file is loaded function afterload(): Promise { if (AstSession.faulted) { // skip rest of loading - just be done with it, so the automatic reload can trigger readyPromise.success(undefined); loadPromise.success(false); } else { if (loaduserdata()) { TDev.tick(Ticks.collabResume); Util.log(">>> Resuming collab from file " + astdesc(currentCloudAst)); ready = true; // we are resuming from saved state TDev.TheEditor.undoMgr.pullIntoEditor().then(() => { readyPromise.success(undefined); loadPromise.success(false); }); } else { TDev.tick(Ticks.collabFirstLoad); // need to get initial version from revision server loadPromise.success(true); } } return Promise.as(); } function loaduserdata(): boolean { var pc = Collab.AstSession.user_get_userdata("asts"); if (!pc) return false; prevCloudAst = pc[0]; currentCloudAst = (pc.length > 1) ? pc[1] : pc[0]; enable_automatic_pull = Collab.AstSession.user_get_userdata("enable_automatic_pull"); enable_automatic_push = Collab.AstSession.user_get_userdata("enable_automatic_push"); return true; } function saveuserdata() { Collab.AstSession.user_set_userdata("asts", astEquals(prevCloudAst,currentCloudAst) ? [currentCloudAst] : [prevCloudAst, currentCloudAst], (pc, newpc) => (pc && newpc && pc.length == newpc.length && astEquals(pc[0], newpc[0]) && (!pc[1] || astEquals(pc[1], newpc[1]))) ); Collab.AstSession.user_set_userdata("enable_automatic_pull", enable_automatic_pull); Collab.AstSession.user_set_userdata("enable_automatic_push", enable_automatic_push); } //// -------------- global state export var enableUndo = false; export var AstSession: TDev.Revisions.ClientSession = undefined; // sync control export var ready = false; export var currentCloudAst: string[]; var prevCloudAst: string[]; var numberUnconfirmedDeltas = 0; // flags indicating presence of suppressed pushes or pulls var delayed_pull = false; var delayed_push = false; export function astEquals(ast1: string[], ast2: string[]):boolean { return ast1[0] == ast2[0] || ast1[1] === ast2[1]; } function randomsuffix(): string { var d = new Date(); var ms = d.getMilliseconds(); return String.fromCharCode("a".charCodeAt(0) + ms % 26) + String.fromCharCode("a".charCodeAt(0) + Math.floor(ms / 26) % 26); } export function astdesc(ast: string[]): string { return ast[0] + "(" + ast[1].length + ")"; } function onDoorBell() { if (!AstSession) { return; } if (AstSession.marooned) { var s = AstSession; AstSession.log("discard cache because it is marooned"); Script.editorState.collabSessionId = undefined; ModalDialog.infoAsync("Project Discontinued", lf("This project has been discontinued. You can continue to edit the script, but it will no longer synchronize with other team members.")) .thenalways(() => TDev.TheEditor.goToHubAsync()).done(); astSessionSlot.disconnect(true, "project discontinued"); // deletes the file from disk } else if (AstSession.faulted) { AstSession.log("local cache is corrupted - deleting"); ModalDialog.infoAsync("Cache Corrupted", lf("Sorry... we encountered a problem with the stored project state. Please try again to get the latest state from the server.")) .thenalways(() => TDev.TheEditor.goToHubAsync()).done(); return astSessionSlot.disconnect(true, "cache corrupted"); // deletes the file from disk } else { //TODO detect permission problems as well if (!AstSession.user_yield() && ready) return; processAstTable(); if (changehandler) changehandler(); } } export function recordAst(ast: string) : any { Util.assert(ready); TDev.tick(Ticks.collabRecordAst); var newast = [randomsuffix(), ast]; if (astEquals(currentCloudAst, newast)) return currentCloudAst; Util.log(">>> recordAst " + astdesc(newast)); currentCloudAst = newast; saveuserdata(); var wentout = pushAstToCloud(); if (!wentout) { //TODO : make pending changes visible //AstSession.user_push(); // AstSession.user_modify_lval(AstSession.user_get_lval(ct_participantindex_blockedpushes, [], [AstSession.getMemberNumber().toString()]), "A1"); } else { // clear unsaved changes } return newast; } export function pushAstToCloud(): boolean { Util.assert(ready); if (!enable_automatic_push || numberUnconfirmedDeltas >= 2) { delayed_push = true; return false; } delayed_push = false; numberUnconfirmedDeltas++; if (!astEquals(prevCloudAst, currentCloudAst)) { var desc = astdesc(prevCloudAst) + ", " + astdesc(currentCloudAst); Util.log(">>> pushAstToCloud: " + desc); var item = AstSession.user_create_item(cloudtype_delta, [], []); AstSession.user_modify_lval(AstSession.user_get_lval(cloudtype_pre, [item.uid], []), prevCloudAst); AstSession.user_modify_lval(AstSession.user_get_lval(cloudtype_post, [item.uid], []), currentCloudAst); AstSession.user_modify_lval(AstSession.user_get_lval(cloudtype_desc, [item.uid], []), desc); prevCloudAst = currentCloudAst; saveuserdata(); AstSession.user_push(); } return true; } export function processAstTable() { var items = AstSession.user_get_items_in_domain(cloudtype_delta).sort((a, b) => a.compareTo(b)); if (items.length < 1) { Util.assert(!ready); Util.log(">>> processAstTable (not ready)"); return; // have not received initial prefix from server yet } else if (!ready) { Util.log(">>> processAstTable first time, (" + items.length + ")"); } else Util.log(">>> processAstTable (" + items.length + ")"); var pos = 0; var cur = items[pos]; var cloud_ast = AstSession.user_get_value(AstSession.user_get_lval(cloudtype_merge, [cur.uid], [])); Util.assert(cloud_ast); var lkeys = []; // go through unmerged confirmed delta entries; delete all but last, and enter merge results var pos = 1; while (pos < items.length && AstSession.user_is_datum_confirmed(items[pos])) { AstSession.user_delete_item(items[pos - 1]); var ukeys = [items[pos].uid]; var merge_lval = AstSession.user_get_lval(cloudtype_merge, ukeys, lkeys); var stats_lval = AstSession.user_get_lval(cloudtype_stats, ukeys, lkeys); Util.assert(!AstSession.user_get_value(merge_lval)); var pre = AstSession.user_get_value(AstSession.user_get_lval(cloudtype_pre, ukeys, lkeys)); var post = AstSession.user_get_value(AstSession.user_get_lval(cloudtype_post, ukeys, lkeys)); cloud_ast = mergeAsts(pre, post, cloud_ast, (data) => AstSession.user_modify_lval(stats_lval, JSON.stringify(data))); AstSession.user_modify_lval(merge_lval, cloud_ast); pos++; } numberUnconfirmedDeltas = items.length - pos; // if automatic pull is off, this is all and we stop here if (ready && (!enable_automatic_pull || pullIsTemporarilySuppressed)) { delayed_pull = true; return; } else delayed_pull = false; // go through unconfirmed delta entries while (pos < items.length) { Util.assert(!AstSession.user_is_datum_confirmed(items[pos])); var ukeys = [items[pos].uid]; var pre = AstSession.user_get_value(AstSession.user_get_lval(cloudtype_pre, ukeys, lkeys)); var post = AstSession.user_get_value(AstSession.user_get_lval(cloudtype_post, ukeys, lkeys)); cloud_ast = mergeAsts(pre, post, cloud_ast); pos++; } if (!ready) { // first time currentCloudAst = cloud_ast; prevCloudAst = cloud_ast; saveuserdata(); ready = true; Util.log(">>> collab is ready " + astdesc(currentCloudAst)); TDev.TheEditor.undoMgr.pullIntoEditor().then(() => { readyPromise.success(undefined); }); } else { // merge with local delta (prev,current) var m = mergeAsts(prevCloudAst, currentCloudAst, cloud_ast); if (!astEquals(prevCloudAst, cloud_ast)) { prevCloudAst = cloud_ast; saveuserdata(); } if (!astEquals(currentCloudAst, m)) { currentCloudAst = m; saveuserdata(); } TDev.TheEditor.undoMgr.pullIntoEditor(); } // potentially push things that were delayed earlier if (delayed_push) pushAstToCloud(); } /// ------------------- the actual merge function export var testMode = true; function versionname(ast: string[]) { var full = ast[0]; var pos = full.indexOf("="); return (pos != -1) ? full.substr(0, pos) : full; } function mergeAsts(o_ast: string[], a_ast: string[], b_ast: string[], datacollector?: (IMergeData) => void) { // take shortcuts based on merge function equivalences if (astEquals(o_ast, b_ast) // easy merge: deltas are consecutive edits || astEquals(b_ast, a_ast)) // easy merge: identical change { return a_ast; } var os = o_ast[1]; var bs = b_ast[1]; var as = a_ast[1]; TDev.tick(Ticks.collabRealMerge); var name = randomsuffix(); var mergedesc = "m(" + versionname(o_ast) + "," + versionname(a_ast) + "," + versionname(b_ast) + ")"; var timer1 = Util.perfNow(); var b = (<any>TDev).AST.Parser.parseScript(bs); var o = (<any>TDev).AST.Parser.parseScript(os); var a = (<any>TDev).AST.Parser.parseScript(as); // (<any>TDev).AST.TypeChecker.tcApp(t1); // (<any>TDev).AST.TypeChecker.tcApp(t2); // (<any>TDev).AST.TypeChecker.tcApp(t3); // (<any>TDev).AST.TypeChecker.tcApp(t4); //var bss = b.serialize(); //var oss = o.serialize(); //var ass = a.serialize(); //if (t1ss !== t1s) debugger; //if (t2ss !== t2s) debugger; //if( t3ss !== t3s) debugger; //if( t4ss !== t4s) debugger; (<any>TDev).TheEditor.initIds(b); (<any>TDev).TheEditor.initIds(o); (<any>TDev).TheEditor.initIds(a); var timer2 = Util.perfNow(); //console.log(">> merging: \n" + t3.serialize() + "\n---------\n" + t4.serialize() + "\n-----------\n" + t2.serialize()); var merged = (<any>TDev).AST.Merge.merge3(o, a, b, datacollector); var mergeds = merged.serialize(); Util.assert(merged.things.length > 0 || a.things.length == 0 || b.things.length == 0); // TODO XXX - do we need to update the ancestors somehow? //console.log(">> merging: \n" + t3.serialize() + "\n---------\n" + t4.serialize() + "\n-----------\n" + t2.serialize()); // if we are in testing mode, record results and test equivalences if (testMode) var record = JSON.stringify({ "O": os, "A": as, "B": bs, "actual": mergeds }); return [name + "=" + mergedesc, mergeds]; } // session context functions var astSessionSlot = new Revisions.Slot( <Revisions.ISessionContext> { url_ws: () => Revisions.revisionservice_http().replace("http", "ws"), url_http: Revisions.revisionservice_http, tokensource: Revisions.getRevisionServiceTokenAsync, clearCachedData: clearCachedData, updateStatus: updateStatus, createSession: createSession, onDoorBell: onDoorBell, afterload: afterload }, () => AstSession, (cs?: TDev.Revisions.ClientSession) => { AstSession = cs; ready = false; currentCloudAst = undefined; prevCloudAst = undefined; } ); function updateStatus() { } function clearCachedData() { } function createSession(original: Revisions.ISessionParams): Revisions.ClientSession { var si = new Revisions.ClientSession(original.servername, original.localname, original.user); si.permissions = ""; si.title = ""; si.script = ""; si.readonly = false; si.user = original.user; return si; } function getAstSessionDescriptor(session: string): Revisions.ISessionParams { var desc = <Revisions.ISessionParams> {}; desc.servername = session; desc.localname = session; desc.permissions = ""; desc.readonly = false; desc.title = ""; desc.user = Cloud.getUserId(); desc.nodeserver = ""; desc.script = ""; return desc; } } }
the_stack
import { Component, OnDestroy, OnInit, ViewChild } from '@angular/core'; import { MatHorizontalStepper, MatStep, MatSelectionList } from '@angular/material'; import { FormBuilder, FormGroup, FormControl, Validators } from '@angular/forms'; import { HttpErrorResponse } from '@angular/common/http'; import { ScanService } from '../../services/scan.service'; import { DatasetService } from '../../services/dataset.service'; import { ScanMetadata } from '../../model/ScanMetadata'; import { UploadScansSelectorComponent, SelectedScan, UserFiles, IncompatibleFile, } from '../../components/upload-scans-selector/upload-scans-selector.component'; import { Observable } from 'rxjs/internal/Observable'; import { interval } from 'rxjs/internal/observable/interval'; import { throwError } from 'rxjs/internal/observable/throwError'; import { Subscription } from 'rxjs/Subscription'; import { PredefinedLabelToUpload } from '../../utils/PredefinedLabelHandler'; enum UploadMode { SINGLE_SCAN, MULTIPLE_SCANS } enum UploadingScanStatus { QUEUED, UPLOADING, WAITING_FOR_PROCESSING, PROCESSING, AVAILABLE, ERROR } enum UploadStep { SELECT_DATASET, SELECT_UPLOAD_MODE, SELECT_SCAN, UPLOADING, SUMMARY } class UploadingScan { id = ''; status: UploadingScanStatus = UploadingScanStatus.QUEUED; scan: SelectedScan; errorsDuringUpload = 0; constructor(scan: SelectedScan) { this.scan = scan; } public updateStatus(scanMetadata: ScanMetadata): void { switch (scanMetadata.status) { case 'STORED': { this.status = UploadingScanStatus.WAITING_FOR_PROCESSING; break; } case 'PROCESSING': { this.status = UploadingScanStatus.PROCESSING; break; } case 'AVAILABLE': { this.status = UploadingScanStatus.AVAILABLE; break; } } } } @Component({ selector: 'app-upload-page', templateUrl: './upload-page.component.html', providers: [ScanService], styleUrls: ['./upload-page.component.scss'] }) export class UploadPageComponent implements OnInit, OnDestroy { @ViewChild('scansForRetry') scansForRetry: MatSelectionList; @ViewChild('stepper') stepper: MatHorizontalStepper; @ViewChild('chooseModeStep') chooseModeStep: MatStep; @ViewChild('chooseFilesStep') chooseFilesStep: MatStep; @ViewChild('sendingFilesStep') sendingFilesStep: MatStep; @ViewChild('uploadCompletedStep') uploadCompletedStep: MatStep; @ViewChild('uploadSingleScanSelector') uploadSingleScanSelector: UploadScansSelectorComponent; @ViewChild('uploadMultipleScansSelector') uploadMultipleScansSelector: UploadScansSelectorComponent; scans: Array<SelectedScan> = []; queuedScans: Array<UploadingScan> = []; uploadingAndProcessingScans: Array<UploadingScan> = []; availableScans: Array<UploadingScan> = []; errorScans: Array<UploadingScan> = []; hasPredefinedLabels = false; incompatibleFiles: IncompatibleFile[] = []; slicesSent = 0; totalNumberOfSlices = 0; progress = 0.0; // Needed in template for comparison with Enum values UploadMode = UploadMode; UploadingScanStatus = UploadingScanStatus; uploadMode: UploadMode = UploadMode.SINGLE_SCAN; dataset: string; availableDatasets = []; chooseModeFormGroup: FormGroup; chooseFilesFormGroup: FormGroup; sendingFilesFormGroup: FormGroup; uploadCompletedFormGroup: FormGroup; chooseDatasetFormGroup: FormGroup; private pollScanStatusSubscription: Subscription; constructor(private scanService: ScanService, private datasetService: DatasetService, private formBuilder: FormBuilder) { } ngOnInit() { this.chooseModeFormGroup = this.formBuilder.group({ 'modeChosen': new FormControl(null, [Validators.required]), }); this.chooseFilesFormGroup = this.formBuilder.group({ 'filesChosen': new FormControl(null, [Validators.required]), }); this.sendingFilesFormGroup = this.formBuilder.group({ 'filesSent': new FormControl(null, [Validators.required]), }); this.uploadCompletedFormGroup = this.formBuilder.group({}); this.chooseDatasetFormGroup = this.formBuilder.group({ 'dataset': new FormControl(this.dataset, [Validators.required]), }); this.datasetService.getAvailableDatasets().then((availableDatasets) => { this.availableDatasets = availableDatasets; }); } ngOnDestroy(): void { if (this.pollScanStatusSubscription) { this.pollScanStatusSubscription.unsubscribe(); } } public chooseFiles(userFiles: UserFiles): void { this.scans = userFiles.scans; this.hasPredefinedLabels = !!this.scans.find((scan: SelectedScan) => { return scan.predefinedLabels.length > 0; }); this.totalNumberOfSlices = userFiles.numberOfSlices; this.incompatibleFiles = userFiles.incompatibleFiles; } private updateProgressBar(numberOfSlicesSent: number = 1): void { this.slicesSent += numberOfSlicesSent; this.progress = 100.0 * this.slicesSent / this.totalNumberOfSlices; } private pollScanUploadStatus() { const TIME_INTERVAL = 5000; // 5 seconds this.pollScanStatusSubscription = interval(TIME_INTERVAL).subscribe(_ => { // Iteration in reverse order makes it safe to remove elements from this array for (let i = this.uploadingAndProcessingScans.length - 1; i >= 0; i--) { const scanToMonitor = this.uploadingAndProcessingScans[i]; // Skip all Scans that were not fully created yet if (!scanToMonitor.id) { continue; } // Check Scan status and move it to appropiate state if needed this.scanService.getScanForScanId(scanToMonitor.id).then((metadata: ScanMetadata) => { scanToMonitor.updateStatus(metadata); }, (error: HttpErrorResponse) => { // Scan was removed from MedTagger due to all files corrupted if (error.status === 404) { scanToMonitor.status = UploadingScanStatus.ERROR; } }); // Move all erred and available Scans to uploaded array, so we won't monitor them again switch (scanToMonitor.status) { case UploadingScanStatus.ERROR: { this.uploadingAndProcessingScans.splice(i, 1); this.errorScans.push(scanToMonitor); break; } case UploadingScanStatus.AVAILABLE: { this.uploadingAndProcessingScans.splice(i, 1); this.availableScans.push(scanToMonitor); break; } } } // End polling once we've uploaded all Scans if (this.errorScans.length + this.availableScans.length === this.scans.length) { console.log('We\'ve uploaded all Scans, let\'s move on!'); if (this.pollScanStatusSubscription) { this.pollScanStatusSubscription.unsubscribe(); } this.sendingFilesFormGroup.controls['filesSent'].setValue('true'); this.stepper.next(); } }); } public async uploadFiles(): Promise<void> { this.chooseFilesFormGroup.controls['filesChosen'].setValue('true'); this.stepper.next(); this.slicesSent = 0; this.progress = 0.0; // Queue all Scans this.queuedScans = []; this.uploadingAndProcessingScans = []; this.availableScans = []; this.errorScans = []; for (const scan of this.scans) { this.queuedScans.push(new UploadingScan(scan)); } // Run polling of Scans upload progress in parallel to the uploading Scans this.pollScanUploadStatus(); // Upload all queued Scans one by one while (this.queuedScans.length > 0) { const queuedScan = this.queuedScans.pop(); queuedScan.status = UploadingScanStatus.UPLOADING; this.uploadingAndProcessingScans.push(queuedScan); try { await this.asyncUploadSingleScan(queuedScan); } catch (error) { queuedScan.status = UploadingScanStatus.ERROR; } } } private asyncUploadSingleScan(uploadingScan: UploadingScan): Promise<void> { const numberOfAllSlices = uploadingScan.scan.files.length; let numberOfSlicesSent = 0; return new Promise<void>((resolve, reject) => { this.uploadSingleScan(uploadingScan).then((newScan) => { console.log('Upload has started!'); newScan.subscribe( _ => { this.updateProgressBar(); numberOfSlicesSent += 1; }, _ => { this.updateProgressBar(numberOfAllSlices - numberOfSlicesSent); reject(); }, () => resolve(), ); }, (error: HttpErrorResponse) => { console.log('Could not create new Scan.'); reject(); }); }); } private uploadSingleScan(uploadingScan: UploadingScan): Promise<Observable<any | never>> { const dataset = this.chooseDatasetFormGroup.get('dataset').value; const numberOfSlices = uploadingScan.scan.files.length; return this.scanService.createNewScan(dataset, numberOfSlices).then((scanId: string) => { console.log('New Scan created with ID:', scanId, ', number of Slices:', numberOfSlices); uploadingScan.id = scanId; uploadingScan.scan.predefinedLabels.forEach((predefinedLabel: PredefinedLabelToUpload) => { // Filter and send only these additional data that are needed by the Predefined Label const additionalData = {}; predefinedLabel.neededFiles.forEach((fileName: string) => { additionalData[fileName] = uploadingScan.scan.additionalData[fileName]; }); console.log('Sending Predefined Label for Scan:', scanId, ' and Task:', predefinedLabel.taskKey); this.scanService.sendPredefinedLabel(scanId, predefinedLabel.taskKey, predefinedLabel.label, additionalData); }); return this.scanService.uploadSlices(scanId, uploadingScan.scan.files); }, () => { return throwError({error: 'Could not create Scan.'}); }); } private resetFormGroup(formGroup: FormGroup): void { formGroup.reset(); } public restart(): void { this.resetFormGroup(this.chooseDatasetFormGroup); this.resetFormGroup(this.chooseModeFormGroup); this.resetFormGroup(this.chooseFilesFormGroup); this.resetFormGroup(this.sendingFilesFormGroup); this.resetFormGroup(this.uploadCompletedFormGroup); if (this.uploadSingleScanSelector) { this.uploadSingleScanSelector.reinitialize(); } if (this.uploadMultipleScansSelector) { this.uploadMultipleScansSelector.reinitialize(); } this.scans = []; this.queuedScans = []; this.uploadingAndProcessingScans = []; this.availableScans = []; this.errorScans = []; this.incompatibleFiles = []; this.totalNumberOfSlices = 0; this.slicesSent = 0; if (!!this.scansForRetry && !!this.scansForRetry.selectedOptions) { this.scansForRetry.selectedOptions.clear(); } this.stepper.reset(); } public uploadAgain(): void { this.scans = []; this.incompatibleFiles = []; this.totalNumberOfSlices = 0; for (const listElement of this.scansForRetry.selectedOptions.selected) { this.totalNumberOfSlices += listElement.value.scan.files.length; this.scans.push(listElement.value.scan); } // Clear Upload and Summary page and go to the Uploading view triggering upload this.resetFormGroup(this.sendingFilesFormGroup); this.resetFormGroup(this.uploadCompletedFormGroup); this.sendingFilesStep.completed = false; this.uploadCompletedStep.completed = false; this.scansForRetry.selectedOptions.clear(); this.stepper.selectedIndex = UploadStep.UPLOADING; this.uploadFiles(); } public isGoogleChrome(): boolean { // TODO: It would be nice to check if there is some lib that does it for us // For now, this ugly method was taken (nearly) as-is from: https://stackoverflow.com/a/13348618 const isChromium = (window as any).chrome, winNav = window.navigator, vendorName = winNav.vendor, isOpera = winNav.userAgent.indexOf('OPR') > -1, isIEedge = winNav.userAgent.indexOf('Edge') > -1, isIOSChrome = winNav.userAgent.match('CriOS'); if (isIOSChrome) { return false; // We don't want to support mobile devices } else if ( isChromium !== null && typeof isChromium !== 'undefined' && vendorName === 'Google Inc.' && isOpera === false && isIEedge === false ) { return true; } else { return false; } } public selectUploadMode(uploadMode: UploadMode): void { this.uploadMode = uploadMode; this.chooseModeFormGroup.controls['modeChosen'].setValue('true'); this.stepper.next(); } }
the_stack
import * as _ from 'lodash'; // The following line is important to keep in that format so it can be rendered into the page export const config: IDashboardConfig = /*return*/ { id: "mbf_advanced_analytics", name: "MBF Advanced Analytics", icon: "equalizer", url: "mbf_advanced_analytics", description: "Bot Framework Advanced Analytics Dashboard", preview: "/images/default.png", category: 'Bots - Advanced', html: `POC - Additional info will be added in the future`, config: { connections: { }, layout: { isDraggable: true, isResizable: true, rowHeight: 30, verticalCompact: false, cols: { lg: 12,md: 10,sm: 6,xs: 4,xxs: 2 }, breakpoints: { lg: 1200,md: 996,sm: 768,xs: 480,xxs: 0 } } }, dataSources: [ { id: "timespan", type: "Constant", params: { values: ["24 hours","1 week","1 month","3 months"],selectedValue: "1 month" }, calculated: (state, dependencies) => { var queryTimespan = state.selectedValue === '24 hours' ? 'PT24H' : state.selectedValue === '1 week' ? 'P7D' : state.selectedValue === '1 month' ? 'P30D' : 'P90D'; var granularity = state.selectedValue === '24 hours' ? '5m' : state.selectedValue === '1 week' ? '1d' : '1d'; return { queryTimespan, granularity }; } }, { id: "modes", type: "Constant", params: { values: ["messages","users"],selectedValue: "messages" }, calculated: (state, dependencies) => { let flags = {}; flags['messages'] = (state.selectedValue === 'messages'); flags['users'] = (state.selectedValue !== 'messages'); return flags; } }, { id: "filters", type: "ApplicationInsights/Query", dependencies: { timespan: "timespan",queryTimespan: "timespan:queryTimespan",granularity: "timespan:granularity" }, params: { table: "nflbot_CL", queries: { filterChannels: { query: () => ` where recordType == 'intent' | extend channel=channelId | summarize channel_count=count() by tostring(channel) | order by channel_count `, mappings: { channel: (val) => val || "unknown",channel_count: (val) => val || 0 }, calculated: (filterChannels) => { const filters = filterChannels.map((x) => x.channel); let { selectedValues } = filterChannels; if (selectedValues === undefined) { selectedValues = []; } return { "channels-count": filterChannels, "channels-filters": filters, "channels-selected": selectedValues, }; } }, filterIntents: { query: () => ` where recordType == "intent" | summarize intent_count=count() by intentName | extend intent=intentName | order by intent_count `, mappings: { intent: (val) => val || "unknown",intent_count: (val) => val || 0 }, calculated: (filterIntents) => { const intents = filterIntents.map((x) => x.intent); let { selectedValues } = filterIntents; if (selectedValues === undefined) { selectedValues = []; } return { "intents-count": filterIntents, "intents-filters": intents, "intents-selected": selectedValues, }; } } } } }, { id: "nfl", type: "ApplicationInsights/Query", dependencies: { timespan: "timespan", queryTimespan: "timespan:queryTimespan", granularity: "timespan:granularity", selectedChannels: "filters:channels-selected", selectedIntents: "filters:intents-selected" }, params: { table: "nflbot_CL", queries: { queries_per_session: { query: () => ` where recordType == "intent" | summarize count_queries=count() by bin(timestamp, 1d), userId | summarize average=avg(count_queries), count_sessions=count(timestamp) | extend average=round(average, 1), count_sessions `, calculated: (result) => { return { avg_queries_per_session: (result && result.length && result[0].average) || 0, total_sessions: (result && result.length && result[0].count_sessions) || 0 } } }, total_users: { query: () => ` where recordType == 'intent' | summarize dcount(userId) by userId | count`, calculated: (total_users) => { return { total_users: (total_users.length && total_users[0].Count) || 0 } } }, returning_users: { query: (dependencies) => { let { timespan } = dependencies; let threshold = timespan === '24 hours' ? '24h' : timespan === '1 week' ? '7d' : timespan === '1 month' ? '30d' : '90d'; return ` where recordType == 'intent' and timestamp > ago(90d) | extend userId=substring(userId, 0, 1) | summarize dcount(userId), minTimestamp=min(timestamp), maxTimestamp=max(timestamp) by userId | where minTimestamp < ago(7d) and maxTimestamp > ago(7d) | count`; }, calculated: (returning_users) => { return { returning_users: (returning_users.length && returning_users[0].Count) || 0 } } }, timeline: { query: (dependencies) => { var { granularity } = dependencies; return ` where recordType == 'intent' | extend channel=channelId | summarize count=count() by bin(timestamp, 1d), channel | order by timestamp asc`; }, filters: [{ dependency: "selectedChannels", queryProperty: "channelId" }], calculated: (timeline, dependencies) => { // Timeline handling // ================= let _timeline = {}; let _channels = {}; let { timespan } = dependencies; /** * Looping through all results building timeline format values * Expected result: * { * timestampValue1: { channel1: count, channel2: count ... } * timestampValue2: { channel1: count2, channel2: count2 ... } * } * * Channels result: * { channel1_total: count, channel2_total: count ... } */ timeline.forEach(row => { var { channel, timestamp, count } = row; var timeValue = (new Date(timestamp)).getTime(); if (!_timeline[timeValue]) _timeline[timeValue] = { time: (new Date(timestamp)).toUTCString() }; if (!_channels[channel]) _channels[channel] = { name: channel, value: 0 }; _timeline[timeValue][channel] = count; _channels[channel].value += count; }); // Going over all the channels making sure that we add "0" count // For every timestamp on the timeline (for no value channels) var channels = Object.keys(_channels); var channelUsage = _.values(_channels); var timelineValues = _.map(_timeline, value => { channels.forEach(channel => { if (!value[channel]) value[channel] = 0; }); return value; }); return { "timeline-graphData": timelineValues, "timeline-channelUsage": channelUsage, "timeline-timeFormat": (timespan === "24 hours" ? 'hour' : 'date'), "timeline-channels": channels }; } }, "timeline-users": { query: (dependencies) => { var { granularity } = dependencies; return ` where recordType == 'intent' | extend userId=substring(userId, 0, 1) | summarize count=dcount(userId) by bin(timestamp, 1d), channel=channelId | order by timestamp asc`; }, calculated: (timeline, dependencies) => { // Timeline handling // ================= let _timeline = {}; let _channels = {}; let { timespan } = dependencies; /** * Looping through all results building timeline format values * Expected result: * { * timestampValue1: { channel1: count, channel2: count ... } * timestampValue2: { channel1: count2, channel2: count2 ... } * } * * Channels result: * { channel1_total: count, channel2_total: count ... } */ timeline.forEach(row => { var { channel, timestamp, count } = row; var timeValue = (new Date(timestamp)).getTime(); if (!_timeline[timeValue]) _timeline[timeValue] = { time: (new Date(timestamp)).toUTCString() }; if (!_channels[channel]) _channels[channel] = { name: channel, value: 0 }; _timeline[timeValue][channel] = count; _channels[channel].value += count; }); // Going over all the channels making sure that we add "0" count // For every timestamp on the timeline (for no value channels) var channels = Object.keys(_channels); var channelUsage = _.values(_channels); var timelineValues = _.map(_timeline, value => { channels.forEach(channel => { if (!value[channel]) value[channel] = 0; }); return value; }); return { "timeline-users-graphData": timelineValues, "timeline-users-channelUsage": channelUsage, "timeline-users-timeFormat": (timespan === "24 hours" ? 'hour' : 'date'), "timeline-users-channels": channels }; } }, intents: { query: () => ` where recordType == "intent" | summarize count_intents=count() by intentName | extend intent=substring(intentName, 0, 4) | order by intent `, filters: [{ dependency: "selectedIntents", queryProperty: "intentName" }], calculated: (intents) => { return { "intents-bars": [ 'count_intents' ] }; } } } } }, { id: "errors", type: "ApplicationInsights/Query", dependencies: { timespan: "timespan",queryTimespan: "timespan:queryTimespan" }, params: { query: () => ` exceptions | summarize count_error=count() by type, innermostMessage | order by count_error desc ` }, calculated: (state) => { var { values } = state; if (!values || !values.length) { return; } var errors = values; var types = {}; var typesTotal = 0; errors.forEach(error => { if (!types[error.type]) types[error.type] = { name: error.type, count: 0 }; types[error.type].count += error.count_error; typesTotal += error.count_error; }); return { errors, types: _.values(types), typesTotal, typesTotal_color: typesTotal > 0 ? '#D50000' : '#AEEA00', typesTotal_icon: typesTotal > 0 ? 'bug_report' : 'done' }; } } ], filters: [ { type: "TextFilter", dependencies: { selectedValue: "timespan",values: "timespan:values" }, actions: { onChange: "timespan:updateSelectedValue" }, first: true }, { type: "TextFilter", dependencies: { selectedValue: "modes",values: "modes:values" }, actions: { onChange: "modes:updateSelectedValue" }, first: true }, { type: "MenuFilter", title: "Channels", subtitle: "Select channels", icon: "forum", dependencies: { selectedValues: "filters:channels-selected",values: "filters:channels-filters" }, actions: { onChange: "filters:updateSelectedValues:channels-selected" }, first: true }, { type: "MenuFilter", title: "Intents", subtitle: "Select intents", icon: "textsms", dependencies: { selectedValues: "filters:intents-selected",values: "filters:intents-filters" }, actions: { onChange: "filters:updateSelectedValues:intents-selected" }, first: true } ], elements: [ { id: "timeline", type: "Timeline", title: "Message Rate", subtitle: "How many messages were sent per timeframe", size: { w: 6,h: 8 }, dependencies: { visible: "modes:messages", values: "nfl:timeline-graphData", lines: "nfl:timeline-channels", timeFormat: "nfl:timeline-timeFormat" } }, { id: "timeline", type: "Timeline", title: "Users Rate", subtitle: "How many users were sent per timeframe", size: { w: 6,h: 8 }, dependencies: { visible: "modes:users", values: "nfl:timeline-users-graphData", lines: "nfl:timeline-users-channels", timeFormat: "nfl:timeline-users-timeFormat" } }, { id: "channels", type: "PieData", title: "Channel Usage", subtitle: "Total messages sent per channel", size: { w: 3,h: 8 }, dependencies: { visible: "modes:messages",values: "nfl:timeline-channelUsage" }, props: { showLegend: false,compact: true, entityType: 'messages' } }, { id: "channels", type: "PieData", title: "Channel Usage (Users)", subtitle: "Total users sent per channel", size: { w: 3,h: 8 }, dependencies: { visible: "modes:users",values: "nfl:timeline-users-channelUsage" }, props: { showLegend: false,compact: true, entityType: 'users' } }, { id: "scores", type: "Scorecard", size: { w: 3,h: 8 }, dependencies: { card_errors_value: "errors:typesTotal", card_errors_heading: "::Errors", card_errors_color: "errors:typesTotal_color", card_errors_icon: "errors:typesTotal_icon", card_errors_subvalue: "errors:typesTotal", card_errors_subheading: "::Avg", card_errors_onClick: "::onErrorsClick", card_qps_value: "nfl:avg_queries_per_session", card_qps_heading: "::Q/Session", card_qps_color: "::#2196F3", card_qps_icon: "::av_timer", card_qps_subvalue: "nfl:total_sessions", card_qps_subheading: "::Sessions", card_users_value: "nfl:total_users", card_users_heading: "::Unique Users", card_users_subvalue: "nfl:returning_users", card_users_subheading: "::Returning", card_users_icon: "::account_circle" }, actions: { onErrorsClick: { action: "dialog:errors", params: { title: "args:heading",type: "args:type",innermostMessage: "args:innermostMessage",queryspan: "timespan:queryTimespan" } } } }, { id: "intents", type: "BarData", title: "Intents Graph", subtitle: "Intents usage per time", size: { w: 6,h: 8 }, dependencies: { values: "nfl:intents",bars: "nfl:intents-bars" }, props: { nameKey: "intent",showLegend: false }, actions: { onBarClick: { action: "dialog:intentsDialog", params: { title: "args:intentName",intent: "args:intentName",queryspan: "timespan:queryTimespan" } } } } ], dialogs: [ { id: "intentsDialog", width: "80%", params: ["title","intent","queryspan"], dataSources: [ { id: "intentsDialog-data", type: "ApplicationInsights/Query", dependencies: { intent: "dialog_intentsDialog:intent",queryTimespan: "dialog_intentsDialog:queryspan" }, params: { table: "nflbot_CL", queries: { "total-conversations": { query: ({ intent }) => ` where recordType == "intent" and intentName == 'Hello' | summarize count_intents=count() by conversationId | count `, calculated: (results) => { return { "total-conversations": (results && results.length && results[0].Count) || 0 } } }, intent_utterances: { query: ({ intent }) => ` where recordType == "intent" and intentName == '${intent}' | summarize count_utterances=count(), maxTimestamp=max(timestamp) by intentText | order by count_utterances | top 5 by count_utterances `, calculated: (utterances) => { return { "sample-utterances": [ { intentName: 'Bla', utterance: "What was BLA doing with BLA in BLA?", count: 7 }, { intentName: 'Bla', utterance: "What was Kiki doing with Kuku in Koko?", count: 4 }, { intentName: 'Bla', utterance: "What should K do with K in K?", count: 4 }, { intentName: 'Bla', utterance: "K@K-K", count: 2 }, { intentName: 'Bla', utterance: "Does K and K work with K?", count: 1 } ], "sample-success-rate": [ { type: "Success", percentage: "75%" }, { type: "Failure", percentage: "10%" }, { type: "Ambiguous", percentage: "15%" } ] }; } }, "entities-usage": { query: ({ intent }) => ` where recordType == "entity" | summarize entity_count=count() by entityType, conversationId | summarize total_count=count() by entity_count, entityType | order by entityType, entity_count asc | where total_count <= 5 and entityType !startswith "kindNameValue"`, calculated: (entityUsage) => { let count_values = _.uniq(entityUsage.map(e => e.total_count)); let barResults = {}; let results = entityUsage.forEach(entity => { barResults[entity.entityType] = barResults[entity.entityType] || { entityType: entity.entityType }; barResults[entity.entityType][entity.total_count] = entity.entity_count; }); return { "entities-usage": _.values(barResults), "entities-usage-bars": count_values }; } }, response_times: { query: () => ` where recordType == "response" | extend response=-responseMilliseconds | summarize sum0=sumif(response, response <= 1000), count0=countif(response <= 1000), sum1=sumif(response, 1000 < response and response <= 2000), count1=countif(1000 < response and response <= 2000), sum2=sumif(response, 2000 < response and response <= 3000), count2=countif(2000 < response and response <= 3000), sum3=sumif(response, response > 3000), count3=countif(response > 3000) | project avg0=sum0/count0, avg1=sum1/count1, avg2=sum2/count2, avg3=sum3/count3` }, intent_quality: { query: () => ` where recordType == "response" | summarize count_quality=count() by responseResult` }, intent_cache_hits: { query: () => ` where recordType == "response" | summarize count_hits=count() by responseCacheHit ` }, intent_disposition: { query: () => ` where recordType == "response" | summarize count_success=count() by serviceResultSuccess ` } } }, calculated: (state) => { let {intent_quality, intent_cache_hits, intent_disposition, response_times} = state; // Disposition let _disposition = { success: (_.find(intent_disposition, { serviceResultSuccess: true }) || {})['count_success'] || 0, fail: (_.find(intent_disposition, { serviceResultSuccess: false }) || {})['count_success'] || 0 }; let disposition = { success: Math.round(100 * _disposition.success / ((_disposition.success + _disposition.fail) || 1)), fail: Math.round(100 * _disposition.fail / ((_disposition.success + _disposition.fail) || 1)) }; // Quality let _quality = { default: (_.find(intent_quality, { responseResult: 'default' }) || {})['count_quality'] || 0, ambiguous: (_.find(intent_quality, { responseResult: 'ambiguous' }) || {})['count_quality'] || 0, normal: (_.find(intent_quality, { responseResult: 'normal' }) || {})['count_quality'] || 0, }; let quality = { default: Math.round(100 * _quality.default / ((_quality.default + _quality.ambiguous + _quality.normal) || 1)), ambiguous: Math.round(100 * _quality.ambiguous / ((_quality.default + _quality.ambiguous + _quality.normal) || 1)), normal: Math.round(100 * _quality.normal / ((_quality.default + _quality.ambiguous + _quality.normal) || 1)) }; // Cache let _cache = { hits: (_.find(intent_cache_hits, { responseCacheHit: true }) || {})['count_hits'] || 0, misses: (_.find(intent_cache_hits, { responseCacheHit: false }) || {})['count_hits'] || 0 }; let cache = { hits: Math.round(100 * _cache.hits / ((_cache.hits + _cache.misses) || 1)), misses: Math.round(100 * _cache.misses / ((_cache.hits + _cache.misses) || 1)) }; // Response times let times = (response_times && response_times.length && response_times[0]) || {}; return { "sample-response-types": [ { name: "Disposition", success: disposition.success, fail: disposition.fail }, { name: "Quality", default: quality.default, ambiguous: quality.ambiguous, normal: quality.normal }, { name: "Type", card: 80, bubble: 20 }, { name: "Image", success: 80, fail: 20 }, { name: "Requests", "Logged In": 44, "Anonymous": 56 }, { name: "Cache", hits: cache.hits, misses: cache.misses } ], "response-types-bars": [ { name: "success", color: "#00BFA5"}, { name: "fail", color: "#B71C1C" } , { name: "default", color: "#64FFDA" }, { name: "ambiguous", color: "#1DE9B6" }, { name: "normal", color: "#00BFA5" }, { name: "card", color: "#64FFDA" }, { name: "bubble", color: "#1DE9B6" }, { name: "Logged In", color: "#00BFA5" }, { name: "Anonymous", color: "#B71C1C" }, { name: "hits", color: "#00BFA5" }, { name: "misses", color: "#B71C1C" } ], "response-times_0": times.avg0 || 0, "response-times_1": times.avg1 || 0, "response-times_2": times.avg2 || 0, "response-times_3": times.avg3 || 0 } } } ], elements: [ { id: "conversations-count", type: "Scorecard", size: { w: 12,h: 2 }, dependencies: { card_conversations_value: "intentsDialog-data:total-conversations", card_conversations_heading: "::Conversations", card_conversations_color: "::#2196F3", card_conversations_icon: "::chat", card_conversations_onClick: "::onConversationsClick", card_responseTimes0_value: "intentsDialog-data:response-times_0", card_responseTimes0_heading: "::In <1 sec", card_responseTimes0_color: "::#03A9F4", card_responseTimes0_icon: "::av_timer", card_responseTimes1_value: "intentsDialog-data:response-times_1", card_responseTimes1_heading: "::In <2 sec", card_responseTimes1_color: "::#FFC107", card_responseTimes1_icon: "::av_timer", card_responseTimes2_value: "intentsDialog-data:response-times_2", card_responseTimes2_heading: "::In < 3 sec", card_responseTimes2_color: "::#FF5722", card_responseTimes2_icon: "::av_timer", card_responseTimes3_value: "intentsDialog-data:response-times_3", card_responseTimes3_heading: "::In 3+ sec", card_responseTimes3_color: "::#D50000", card_responseTimes3_icon: "::av_timer" }, actions: { onConversationsClick: { action: "dialog:conversations", params: { title: "dialog_intentsDialog:title",intent: "dialog_intentsDialog:intent",queryspan: "dialog_intentsDialog:queryspan" } } } }, { id: "entity-usage", type: "BarData", title: "Entity count appearances in intent", subtitle: "Entity usage and count for the selected intent", size: { w: 4,h: 8 }, dependencies: { values: "intentsDialog-data:entities-usage",bars: "intentsDialog-data:entities-usage-bars" }, props: { nameKey: "entityType" } }, { id: "response-statistics", type: "BarData", title: "Response Statistics", subtitle: "Entity usage and count for the selected intent", size: { w: 4,h: 8 }, dependencies: { values: "intentsDialog-data:sample-response-types",bars: "intentsDialog-data:response-types-bars" }, props: { nameKey: "name" } }, { id: "utterances", type: "Table", size: { w: 4, h: 8 }, dependencies: { values: "intentsDialog-data:intent_utterances" }, props: { cols: [ { header: "Utterance",field: "intentText" }, { header: "Count",field: "count_utterances", type: 'number' } ] }, } ] }, { id: "conversations", width: "60%", params: ["title","intent","queryspan"], dataSources: [ { id: "conversations-data", type: "ApplicationInsights/Query", dependencies: { intent: "dialog_conversations:intent",queryTimespan: "dialog_conversations:queryspan" }, params: { table: "nflbot_CL", queries: { conversations: { query: ({ intent }) => ` where recordType == "intent" and intentName == '${intent}' | summarize count_intents=count(), maxTimestamp=max(timestamp) by conversationId | order by maxTimestamp`, mappings: { id: (val, row, idx) => `Conversation ${idx}` } } } } } ], elements: [ { id: "conversations-list", type: "Table", title: "Conversations", size: { w: 12,h: 16 }, dependencies: { values: "conversations-data:conversations" }, props: { hideBorders: true, cols: [ { header: "Conversation Id",field: "id" }, { header: "Last Message",field: "maxTimestamp",type: "time",format: "MMM-DD HH:mm:ss" }, { header: "Count",field: "count_intents" }, { type: "button",value: "chat",click: "openMessagesDialog" } ] }, actions: { openMessagesDialog: { action: "dialog:messages", params: { title: "args:id",conversation: "args:conversationId",queryspan: "timespan:queryTimespan" } } } } ] }, { id: "messages", width: "50%", params: ["title","conversation","queryspan"], dataSources: [ { id: "messages-data", type: "ApplicationInsights/Query", dependencies: { conversation: "dialog_messages:conversation",queryTimespan: "dialog_messages:queryspan" }, params: { query: ({ conversation }) => ` nflbot_CL | where recordType in ("intent", "response") and (intentText != '' or responseText != '') | order by timestamp asc | extend message=strcat(responseText, intentText) | top 200 by timestamp asc | project timestamp, eventName=recordType, message ` } } ], elements: [ { id: "messages-list", type: "Table", title: "Messages", size: { w: 12,h: 16 }, dependencies: { values: "messages-data" }, props: { rowClassNameField: "eventName", cols: [ { header: "Timestamp",width: "50px",field: "timestamp",type: "time",format: "MMM-DD HH:mm:ss" }, { header: "Message",field: "message" } ] } } ] }, { id: "errors", width: "90%", params: ["title","queryspan"], dataSources: [ { id: "errors-group", type: "ApplicationInsights/Query", dependencies: { queryTimespan: "dialog_errors:queryspan" }, params: { query: () => ` exceptions | summarize error_count=count() by type, innermostMessage | project type, innermostMessage, error_count | order by error_count desc ` }, calculated: (state) => { const { values } = state; return { groups: values }; } }, { id: "errors-selection", type: "ApplicationInsights/Query", dependencies: { queryTimespan: "dialog_errors:queryspan",type: "args:type",innermostMessage: "args:innermostMessage" }, params: { query: ({ type, innermostMessage }) => ` exceptions | where type == '${type}' | where innermostMessage == "${innermostMessage}" | extend conversationId=customDimensions.conversationId | project timestamp, type, innermostMessage, client_IP, conversationId | order by timestamp` } } ], elements: [ { id: "errors-list", type: "SplitPanel", title: "Errors", size: { w: 12,h: 16 }, dependencies: { groups: "errors-group",values: "errors-selection" }, props: { group: { field: "type",secondaryField: "innermostMessage",countField: "error_count" }, cols: [ { header: "Timestamp",field: "timestamp" }, { header: "Type",field: "type",secondaryHeader: "Message",secondaryField: "innermostMessage" }, { header: "Conversation Id",field: "conversationId",secondaryHeader: "Client IP",secondaryField: "client_IP" }, { type: "button",value: "more",click: "openErrorDetail" } ] }, actions: { select: { action: "errors-selection:updateDependencies", params: { title: "args:type",type: "args:type",innermostMessage: "args:innermostMessage",queryspan: "timespan:queryTimespan" } }, openErrorDetail: { action: "dialog:errorDetail", params: { title: "args:innermostMessage", type: "args:type", innermostMessage: "args:innermostMessage", timestamp: "args:timestamp", conversationId: "args:conversationId", queryspan: "timespan:queryTimespan" } } } } ] }, { id: "errorDetail", width: "50%", params: ["title","timestamp","type","innermostMessage", "conversationId","queryspan"], dataSources: [ { id: "errorDetail-data", type: "ApplicationInsights/Query", dependencies: { timestamp: "dialog_errorDetail:timestamp", type: "dialog_errorDetail:type", innermostMessage: "dialog_errorDetail:innermostMessage", conversationId: "dialog_errorDetail:conversationId", queryTimespan: "dialog_errorDetail:queryspan" }, params: { query: ({ timestamp, type, innermostMessage, conversationId }) => ` exceptions | where timestamp == '${timestamp}' and type == '${type}' and innermostMessage == '${innermostMessage.replace(/'/g, "\\'")}' and customDimensions.conversationId == '${conversationId}' | extend conversationId=customDimensions.conversationId ` } } ], elements: [ { id: "errorDetail-item", type: "Detail", title: "Error detail", size: { w: 12,h: 16 }, dependencies: { values: "errorDetail-data" }, props: { cols: [ { header: "Timestamp",field: "timestamp" }, { header: "Type",field: "type" }, { header: "Message",field: "innermostMessage" }, { header: "Conversation ID",field: "conversationId" }, { header: "Details",field: "details" }, { header: "Custom Dimensions",field: "customDimensions" }, { header: "Client Type",field: "client_Type" }, { header: "Client IP",field: "client_IP" }, { header: "Client City",field: "client_City" }, { header: "Client State Or Province",field: "client_StateOrProvince" }, { header: "Client Country Or Region",field: "client_CountryOrRegion" }, { header: "Client Role Instance",field: "client_RoleInstance" } ] } } ] } ] }
the_stack
import React, { ReactElement } from "react"; import { components } from './pages'; import { MuiPickersUtilsProvider } from '@material-ui/pickers'; import FlexLayout, { Actions, DockLocation, Model, Node, TabNode } from 'flexlayout-react'; import 'flexlayout-react/style/light.css' import './workspace.css' import { getParameters, isMobile, isSmallScreen, NavigationContext } from "./utils"; import { Container, CssBaseline } from "@material-ui/core"; import { isJsonString } from "unigraph-dev-common/lib/utils/utils"; import { getRandomInt } from "unigraph-dev-common/lib/api/unigraph"; import { Search, StarOutlined, Menu, LocalOffer, Details } from "@material-ui/icons"; import { ContextMenu } from "./components/UnigraphCore/ContextMenu"; import { DndProvider } from "react-dnd"; import { HTML5Backend } from 'react-dnd-html5-backend' import { InlineSearch } from "./components/UnigraphCore/InlineSearchPopup"; import MomentUtils from '@date-io/moment'; const pages = window.unigraph.getState('registry/pages') export function WorkspacePageComponent({ children, maximize, paddingTop, id }: any) { //console.log(id) return <div id={"workspaceContainer"+id} style={{width: "100%", height: "100%", overflow: "auto"}}> <Container maxWidth={maximize ? false : "lg"} disableGutters style={{paddingTop: (maximize || !paddingTop) ? "0px" : "12px", height: "100%"}}> <CssBaseline/> {children} </Container> </div> } export const getComponentFromPage = (location: string, params: any = {}) => {return { type: 'tab', config: params, name: pages.value[location.slice(1)].name, component: '/pages' + location, enableFloat: 'true' }} const newWindowActions = { "new-tab": (model: Model, initJson: any) => { let newJson = {...initJson, id: getRandomInt().toString()}; newJson.config = newJson.config || {}; newJson.config.id = newJson.id; model.doAction(Actions.addNode(newJson, "workspace-main-tabset", DockLocation.CENTER, -1)); }, "new-pane": (model: Model, initJson: any) => { let node = getComponentFromPage(initJson); let action = Actions.addNode(node, "workspace-main-tabset", DockLocation.RIGHT, 0, true) model.doAction(action); }, "new-popout": (model: Model, initJson: any) => { let someId = getRandomInt().toString(); let node = getComponentFromPage(initJson) as any; node.id = someId; let action = Actions.addNode(node, "workspace-main-tabset", DockLocation.CENTER, -1, false) let newNode = model.doAction(action); model.doAction(Actions.floatTab(someId)) } } const newTab = (model: Model, initJson: any) => { // @ts-expect-error: already checked for isJsonString let userSettings = JSON.parse(isJsonString(window.localStorage.getItem('userSettings')) ? window.localStorage.getItem('userSettings') : "{}") let newWindowBehavior = userSettings['newWindow'] && Object.keys(newWindowActions).includes(userSettings['newWindow']) ? userSettings['newWindow'] : "new-tab" // @ts-expect-error: already checked and added fallback newWindowActions[newWindowBehavior](model, initJson) } window.newTab = newTab; const workspaceNavigator = (model: Model, location: string) => { let search = "?" + location.split('?')[1]; location = location.split('?')[0]; newTab(model, getComponentFromPage(location, getParameters(search.slice(1)))) } const mainTabsetId = 'workspace-main-tabset'; const setTitleOnRenderTab = (model: Model) => { // @ts-expect-error: using private API const idMap: Record<string, Node> = model._idMap; // @ts-expect-error: using private API const count = Object.values(idMap).reduce((count, it) => {if (it?._attributes?.type === "tab") return count+1; else return count;}, 0) - 1; // @ts-expect-error: using private API let selIndex = model.getActiveTabset()?._attributes?.selected; selIndex = selIndex ? selIndex : 0 let selName = "Loading" // @ts-expect-error: using private API if (model.getActiveTabset() === undefined) {model._setActiveTabset(model.getNodeById(mainTabsetId))} try { // @ts-expect-error: using private API selName = model.getActiveTabset()?._children?.[selIndex]?.getName(); } catch (e) {} const titleStr = `${selName} and ${count-5} other tabs - Unigraph` const titleStrZero = `${selName} - Unigraph` const finalTitle = count-5 > 0 ? titleStr : titleStrZero document.title = finalTitle; } export function WorkSpace(this: any) { var json = { global: { "tabSetTabStripHeight": 40 }, borders: [{ "type":"border", "location": "left", "id": "border-left", "selected": isSmallScreen() ? -1 : 0, "children": [ { "type": "tab", "enableClose":false, "minSize": 700, "maxSize": 700, "name": "App Drawer", "id": "app-drawer", "component": "/components/appdrawer", }, { "type": "tab", "enableClose":false, "minSize": 700, "maxSize": 700, "name": "Search", "id": "search-pane", "component": "/pages/search", } ] }, { "type":"border", "location": "bottom", "id": "border-bottom", "selected": -1, "children": [ { "type": "tab", "enableClose":false, "minSize": 700, "maxSize": 700, "name": "Categories", "id": "category-pane", "component": "/pages/categories", } ] }, { "type":"border", "location": "right", "id": "border-right", "selected": -1, "children": [ { "type": "tab", "enableClose":false, "minSize": 700, "maxSize": 700, "name": "Inspector", "id": "inspector-pane", "component": "/pages/inspector", } ] }], layout:{ "type": "row", "weight": 100, "children": [ { "type": "tabset", "id": mainTabsetId, "enableDeleteWhenEmpty": false, "weight": 50, "selected": 0, "children": [ {...getComponentFromPage('/home'), enableClose: false, id: "dashboard", enableDrag: false} ] } ] } }; const factory = (node: any) => { var component = node.getComponent(); var config = node.getConfig() || {}; if (component.startsWith('/pages/')) { const page = pages.value[(component.replace('/pages/', '') as string)] //console.log(page) return <WorkspacePageComponent maximize={page.maximize} paddingTop={page.paddingTop} id={config.id}> {page.constructor(config)} </WorkspacePageComponent> } else if (component.startsWith('/components/')) { return components[(component.replace('/components/', '') as string)].constructor(config) } else if (component.startsWith('/temp/')) { const tempComponent = window.unigraph.getState(component).value; return tempComponent.component({...config, ...tempComponent.params}); } } const [model, setModel] = React.useState(FlexLayout.Model.fromJson(json)); let memoMDFn: any = {} const getMouseDownFn = (id: string) => { const fn = (event: any) => { if (typeof event === 'object') { switch (event.button) { case 1: model.doAction(Actions.deleteTab(id)) break; default: break; } } } if (!memoMDFn[id]) { memoMDFn[id] = fn; } return memoMDFn[id]; } window.layoutModel = model; window.wsnavigator = workspaceNavigator.bind(this, model); return <NavigationContext.Provider value={workspaceNavigator.bind(this, model)}> <MuiPickersUtilsProvider utils={MomentUtils}> <div id="global-elements"> <ContextMenu /> <InlineSearch /> </div> <DndProvider backend={HTML5Backend}> <FlexLayout.Layout model={model} factory={factory} popoutURL={"./popout_page.html"} onRenderTab={(node: TabNode, renderValues: any) => { setTitleOnRenderTab(model); const nodeId = node.getId(); if (nodeId === "app-drawer") { renderValues.content = <Menu style={{verticalAlign: "middle", transform: "rotate(90deg)"}}/>; } if (nodeId === "search-pane") { renderValues.content = <Search style={{verticalAlign: "middle", transform: "rotate(90deg)"}}/>; } if (nodeId === "inspector-pane") { renderValues.content = <Details style={{verticalAlign: "middle", transform: "rotate(270deg)"}}/>; } if (nodeId === "category-pane") { renderValues.content = [<LocalOffer style={{verticalAlign: "middle", marginRight: "4px"}}/>, renderValues.content]; } if (node.isVisible() && nodeId !== "app-drawer" && nodeId !== "dashboard" && nodeId !== "search-pane" && nodeId !== "category-pane" && nodeId !== "inspector-pane") { renderValues.buttons.push(<div style={{zIndex: 999, transform: "scale(0.7)"}} onClick={async () => { const config = node.getConfig(); if (config) {delete config.undefine; delete config.id}; const uid = await window.unigraph.addObject({ name: node.getName(), env: "react-explorer", view: node.getComponent(), props: JSON.stringify({config: config}) }, "$/schema/view"); await window.unigraph.runExecutable("$/package/unigraph.core/0.0.1/executable/add-item-to-list", { item: uid[0], where: "$/entity/favorite_bar" }) }}><StarOutlined></StarOutlined></div>) } renderValues.buttons.push(<div id={"tabId"+nodeId}></div>); setTimeout(() => { const el = document.getElementById('tabId'+nodeId); if (el && el.parentElement && node.isEnableClose()) { const fn = getMouseDownFn(nodeId); el.parentElement.removeEventListener("mousedown", fn) el.parentElement.addEventListener("mousedown", fn) } }, 0) }}/> </DndProvider> </MuiPickersUtilsProvider> </NavigationContext.Provider> }
the_stack
// immutable proxies to host objects import { base58Encode } from "./context"; import {Convert} from "./convert"; import {ScAddress,ScAgentID,ScChainID,ScColor,ScHash,ScHname,ScRequestID} from "./hashtypes"; import * as host from "./host"; import {Key32,MapKey} from "./keys"; // value proxy for immutable ScAddress in host container export class ScImmutableAddress { objID: i32; keyID: Key32; constructor(objID: i32, keyID: Key32) { this.objID = objID; this.keyID = keyID; } // check if value exists in host container exists(): boolean { return host.exists(this.objID, this.keyID, host.TYPE_ADDRESS); } // human-readable string representation toString(): string { return this.value().toString(); } // get value from host container value(): ScAddress { return ScAddress.fromBytes(host.getBytes(this.objID, this.keyID, host.TYPE_ADDRESS)); } } // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // array proxy for immutable array of ScAddress export class ScImmutableAddressArray { objID: i32; constructor(id: i32) { this.objID = id; } // get value proxy for item at index, index can be 0..length()-1 getAddress(index: i32): ScImmutableAddress { return new ScImmutableAddress(this.objID, new Key32(index)); } // number of items in array length(): i32 { return host.getLength(this.objID); } } // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // value proxy for immutable ScAgentID in host container export class ScImmutableAgentID { objID: i32; keyID: Key32; constructor(objID: i32, keyID: Key32) { this.objID = objID; this.keyID = keyID; } // check if value exists in host container exists(): boolean { return host.exists(this.objID, this.keyID, host.TYPE_AGENT_ID); } // human-readable string representation toString(): string { return this.value().toString(); } // get value from host container value(): ScAgentID { return ScAgentID.fromBytes(host.getBytes(this.objID, this.keyID, host.TYPE_AGENT_ID)); } } // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // array proxy for immutable array of ScAgentID export class ScImmutableAgentIDArray { objID: i32; constructor(id: i32) { this.objID = id; } // get value proxy for item at index, index can be 0..length()-1 getAgentID(index: i32): ScImmutableAgentID { return new ScImmutableAgentID(this.objID, new Key32(index)); } // number of items in array length(): i32 { return host.getLength(this.objID); } } // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // value proxy for immutable Bool in host container export class ScImmutableBool { objID: i32; keyID: Key32; constructor(objID: i32, keyID: Key32) { this.objID = objID; this.keyID = keyID; } // check if value exists in host container exists(): boolean { return host.exists(this.objID, this.keyID, host.TYPE_BOOL); } // human-readable string representation toString(): string { return this.value().toString(); } // get value from host container value(): boolean { let bytes = host.getBytes(this.objID, this.keyID, host.TYPE_BOOL); return bytes[0] != 0; } } // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // array proxy for immutable array of Bool export class ScImmutableBoolArray { objID: i32; constructor(id: i32) { this.objID = id; } // get value proxy for item at index, index can be 0..length()-1 getBool(index: i32): ScImmutableBool { return new ScImmutableBool(this.objID, new Key32(index)); } // number of items in array length(): i32 { return host.getLength(this.objID); } } // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // value proxy for immutable bytes array in host container export class ScImmutableBytes { objID: i32; keyID: Key32; constructor(objID: i32, keyID: Key32) { this.objID = objID; this.keyID = keyID; } // check if value exists in host container exists(): boolean { return host.exists(this.objID, this.keyID, host.TYPE_BYTES); } // human-readable string representation toString(): string { return base58Encode(this.value()); } // get value from host container value(): u8[] { return host.getBytes(this.objID, this.keyID, host.TYPE_BYTES); } } // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // array proxy for immutable array of byte array export class ScImmutableBytesArray { objID: i32; constructor(id: i32) { this.objID = id; } // get value proxy for item at index, index can be 0..length()-1 getBytes(index: i32): ScImmutableBytes { return new ScImmutableBytes(this.objID, new Key32(index)); } // number of items in array length(): i32 { return host.getLength(this.objID); } } // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // value proxy for immutable ScChainID in host container export class ScImmutableChainID { objID: i32; keyID: Key32; constructor(objID: i32, keyID: Key32) { this.objID = objID; this.keyID = keyID; } // check if value exists in host container exists(): boolean { return host.exists(this.objID, this.keyID, host.TYPE_CHAIN_ID); } // human-readable string representation toString(): string { return this.value().toString(); } // get value from host container value(): ScChainID { return ScChainID.fromBytes(host.getBytes(this.objID, this.keyID, host.TYPE_CHAIN_ID)); } } // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // array proxy for immutable array of ScChainID export class ScImmutableChainIDArray { objID: i32; constructor(id: i32) { this.objID = id; } // get value proxy for item at index, index can be 0..length()-1 getChainID(index: i32): ScImmutableChainID { return new ScImmutableChainID(this.objID, new Key32(index)); } // number of items in array length(): i32 { return host.getLength(this.objID); } } // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // value proxy for immutable ScColor in host container export class ScImmutableColor { objID: i32; keyID: Key32; constructor(objID: i32, keyID: Key32) { this.objID = objID; this.keyID = keyID; } // check if value exists in host container exists(): boolean { return host.exists(this.objID, this.keyID, host.TYPE_COLOR); } // human-readable string representation toString(): string { return this.value().toString(); } // get value from host container value(): ScColor { return ScColor.fromBytes(host.getBytes(this.objID, this.keyID, host.TYPE_COLOR)); } } // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // array proxy for immutable array of ScColor export class ScImmutableColorArray { objID: i32; constructor(id: i32) { this.objID = id; } // get value proxy for item at index, index can be 0..length()-1 getColor(index: i32): ScImmutableColor { return new ScImmutableColor(this.objID, new Key32(index)); } // number of items in array length(): i32 { return host.getLength(this.objID); } } // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // value proxy for immutable ScHash in host container export class ScImmutableHash { objID: i32; keyID: Key32; constructor(objID: i32, keyID: Key32) { this.objID = objID; this.keyID = keyID; } // check if value exists in host container exists(): boolean { return host.exists(this.objID, this.keyID, host.TYPE_HASH); } // human-readable string representation toString(): string { return this.value().toString(); } // get value from host container value(): ScHash { return ScHash.fromBytes(host.getBytes(this.objID, this.keyID, host.TYPE_HASH)); } } // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // array proxy for immutable array of ScHash export class ScImmutableHashArray { objID: i32; constructor(id: i32) { this.objID = id; } // get value proxy for item at index, index can be 0..length()-1 getHash(index: i32): ScImmutableHash { return new ScImmutableHash(this.objID, new Key32(index)); } // number of items in array length(): i32 { return host.getLength(this.objID); } } // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // value proxy for immutable ScHname in host container export class ScImmutableHname { objID: i32; keyID: Key32; constructor(objID: i32, keyID: Key32) { this.objID = objID; this.keyID = keyID; } // check if value exists in host container exists(): boolean { return host.exists(this.objID, this.keyID, host.TYPE_HNAME); } // human-readable string representation toString(): string { return this.value().toString(); } // get value from host container value(): ScHname { return ScHname.fromBytes(host.getBytes(this.objID, this.keyID, host.TYPE_HNAME)); } } // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // array proxy for immutable array of ScHname export class ScImmutableHnameArray { objID: i32; constructor(id: i32) { this.objID = id; } // get value proxy for item at index, index can be 0..length()-1 getHname(index: i32): ScImmutableHname { return new ScImmutableHname(this.objID, new Key32(index)); } // number of items in array length(): i32 { return host.getLength(this.objID); } } // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // value proxy for immutable Int8 in host container export class ScImmutableInt8 { objID: i32; keyID: Key32; constructor(objID: i32, keyID: Key32) { this.objID = objID; this.keyID = keyID; } // check if value exists in host container exists(): boolean { return host.exists(this.objID, this.keyID, host.TYPE_INT8); } // human-readable string representation toString(): string { return this.value().toString(); } // get value from host container value(): i8 { let bytes = host.getBytes(this.objID, this.keyID, host.TYPE_INT8); return bytes[0] as i8; } } // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // array proxy for immutable array of Int8 export class ScImmutableInt8Array { objID: i32; constructor(id: i32) { this.objID = id; } // get value proxy for item at index, index can be 0..length()-1 getInt8(index: i32): ScImmutableInt8 { return new ScImmutableInt8(this.objID, new Key32(index)); } // number of items in array length(): i32 { return host.getLength(this.objID); } } // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // value proxy for immutable Int16 in host container export class ScImmutableInt16 { objID: i32; keyID: Key32; constructor(objID: i32, keyID: Key32) { this.objID = objID; this.keyID = keyID; } // check if value exists in host container exists(): boolean { return host.exists(this.objID, this.keyID, host.TYPE_INT16); } // human-readable string representation toString(): string { return this.value().toString(); } // get value from host container value(): i16 { let bytes = host.getBytes(this.objID, this.keyID, host.TYPE_INT16); return Convert.toI16(bytes); } } // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // array proxy for immutable array of Int16 export class ScImmutableInt16Array { objID: i32; constructor(id: i32) { this.objID = id; } // get value proxy for item at index, index can be 0..length()-1 getInt16(index: i32): ScImmutableInt16 { return new ScImmutableInt16(this.objID, new Key32(index)); } // number of items in array length(): i32 { return host.getLength(this.objID); } } // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // value proxy for immutable Int32 in host container export class ScImmutableInt32 { objID: i32; keyID: Key32; constructor(objID: i32, keyID: Key32) { this.objID = objID; this.keyID = keyID; } // check if value exists in host container exists(): boolean { return host.exists(this.objID, this.keyID, host.TYPE_INT32); } // human-readable string representation toString(): string { return this.value().toString(); } // get value from host container value(): i32 { let bytes = host.getBytes(this.objID, this.keyID, host.TYPE_INT32); return Convert.toI32(bytes); } } // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // array proxy for immutable array of Int32 export class ScImmutableInt32Array { objID: i32; constructor(id: i32) { this.objID = id; } // get value proxy for item at index, index can be 0..length()-1 getInt32(index: i32): ScImmutableInt32 { return new ScImmutableInt32(this.objID, new Key32(index)); } // number of items in array length(): i32 { return host.getLength(this.objID); } } // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // value proxy for immutable Int64 in host container export class ScImmutableInt64 { objID: i32; keyID: Key32; constructor(objID: i32, keyID: Key32) { this.objID = objID; this.keyID = keyID; } // check if value exists in host container exists(): boolean { return host.exists(this.objID, this.keyID, host.TYPE_INT64); } // human-readable string representation toString(): string { return this.value().toString(); } // get value from host container value(): i64 { let bytes = host.getBytes(this.objID, this.keyID, host.TYPE_INT64); return Convert.toI64(bytes); } } // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // array proxy for immutable array of Int64 export class ScImmutableInt64Array { objID: i32; constructor(id: i32) { this.objID = id; } // get value proxy for item at index, index can be 0..length()-1 getInt64(index: i32): ScImmutableInt64 { return new ScImmutableInt64(this.objID, new Key32(index)); } // number of items in array length(): i32 { return host.getLength(this.objID); } } // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // map proxy for immutable map export class ScImmutableMap { objID: i32; constructor(id: i32) { this.objID = id; } callFunc(keyID: Key32, params: u8[]): u8[] { return host.callFunc(this.objID, keyID, params); } // get value proxy for immutable ScAddress field specified by key getAddress(key: MapKey): ScImmutableAddress { return new ScImmutableAddress(this.objID, key.getKeyID()); } // get array proxy for ScImmutableAddressArray specified by key getAddressArray(key: MapKey): ScImmutableAddressArray { let arrID = host.getObjectID(this.objID, key.getKeyID(), host.TYPE_ADDRESS | host.TYPE_ARRAY); return new ScImmutableAddressArray(arrID); } // get value proxy for immutable ScAgentID field specified by key getAgentID(key: MapKey): ScImmutableAgentID { return new ScImmutableAgentID(this.objID, key.getKeyID()); } // get array proxy for ScImmutableAgentIDArray specified by key getAgentIDArray(key: MapKey): ScImmutableAgentIDArray { let arrID = host.getObjectID(this.objID, key.getKeyID(), host.TYPE_AGENT_ID | host.TYPE_ARRAY); return new ScImmutableAgentIDArray(arrID); } // get value proxy for immutable Bool field specified by key getBool(key: MapKey): ScImmutableBool { return new ScImmutableBool(this.objID, key.getKeyID()); } // get array proxy for ScImmutableBoolArray specified by key getBoolArray(key: MapKey): ScImmutableBoolArray { let arrID = host.getObjectID(this.objID, key.getKeyID(), host.TYPE_BOOL | host.TYPE_ARRAY); return new ScImmutableBoolArray(arrID); } // get value proxy for immutable bytes array field specified by key getBytes(key: MapKey): ScImmutableBytes { return new ScImmutableBytes(this.objID, key.getKeyID()); } // get array proxy for ScImmutableBytesArray specified by key getBytesArray(key: MapKey): ScImmutableBytesArray { let arrID = host.getObjectID(this.objID, key.getKeyID(), host.TYPE_BYTES | host.TYPE_ARRAY); return new ScImmutableBytesArray(arrID); } // get value proxy for immutable ScChainID field specified by key getChainID(key: MapKey): ScImmutableChainID { return new ScImmutableChainID(this.objID, key.getKeyID()); } // get array proxy for ScImmutableChainIDArray specified by key getChainIDArray(key: MapKey): ScImmutableChainIDArray { let arrID = host.getObjectID(this.objID, key.getKeyID(), host.TYPE_CHAIN_ID | host.TYPE_ARRAY); return new ScImmutableChainIDArray(arrID); } // get value proxy for immutable ScColor field specified by key getColor(key: MapKey): ScImmutableColor { return new ScImmutableColor(this.objID, key.getKeyID()); } // get array proxy for ScImmutableColorArray specified by key getColorArray(key: MapKey): ScImmutableColorArray { let arrID = host.getObjectID(this.objID, key.getKeyID(), host.TYPE_COLOR | host.TYPE_ARRAY); return new ScImmutableColorArray(arrID); } // get value proxy for immutable ScHash field specified by key getHash(key: MapKey): ScImmutableHash { return new ScImmutableHash(this.objID, key.getKeyID()); } // get array proxy for ScImmutableHashArray specified by key getHashArray(key: MapKey): ScImmutableHashArray { let arrID = host.getObjectID(this.objID, key.getKeyID(), host.TYPE_HASH | host.TYPE_ARRAY); return new ScImmutableHashArray(arrID); } // get value proxy for immutable ScHname field specified by key getHname(key: MapKey): ScImmutableHname { return new ScImmutableHname(this.objID, key.getKeyID()); } // get array proxy for ScImmutableHnameArray specified by key getHnameArray(key: MapKey): ScImmutableHnameArray { let arrID = host.getObjectID(this.objID, key.getKeyID(), host.TYPE_HNAME | host.TYPE_ARRAY); return new ScImmutableHnameArray(arrID); } // get value proxy for immutable Int8 field specified by key getInt8(key: MapKey): ScImmutableInt8 { return new ScImmutableInt8(this.objID, key.getKeyID()); } // get array proxy for ScImmutableInt8Array specified by key getInt8Array(key: MapKey): ScImmutableInt8Array { let arrID = host.getObjectID(this.objID, key.getKeyID(), host.TYPE_INT8 | host.TYPE_ARRAY); return new ScImmutableInt8Array(arrID); } // get value proxy for immutable Int16 field specified by key getInt16(key: MapKey): ScImmutableInt16 { return new ScImmutableInt16(this.objID, key.getKeyID()); } // get array proxy for ScImmutableInt16Array specified by key getInt16Array(key: MapKey): ScImmutableInt16Array { let arrID = host.getObjectID(this.objID, key.getKeyID(), host.TYPE_INT16 | host.TYPE_ARRAY); return new ScImmutableInt16Array(arrID); } // get value proxy for immutable Int32 field specified by key getInt32(key: MapKey): ScImmutableInt32 { return new ScImmutableInt32(this.objID, key.getKeyID()); } // get array proxy for ScImmutableInt32Array specified by key getInt32Array(key: MapKey): ScImmutableInt32Array { let arrID = host.getObjectID(this.objID, key.getKeyID(), host.TYPE_INT32 | host.TYPE_ARRAY); return new ScImmutableInt32Array(arrID); } // get value proxy for immutable Int64 field specified by key getInt64(key: MapKey): ScImmutableInt64 { return new ScImmutableInt64(this.objID, key.getKeyID()); } // get array proxy for ScImmutableInt64Array specified by key getInt64Array(key: MapKey): ScImmutableInt64Array { let arrID = host.getObjectID(this.objID, key.getKeyID(), host.TYPE_INT64 | host.TYPE_ARRAY); return new ScImmutableInt64Array(arrID); } // get map proxy for ScImmutableMap specified by key getMap(key: MapKey): ScImmutableMap { let mapID = host.getObjectID(this.objID, key.getKeyID(), host.TYPE_MAP); return new ScImmutableMap(mapID); } // get array proxy for ScImmutableMapArray specified by key getMapArray(key: MapKey): ScImmutableMapArray { let arrID = host.getObjectID(this.objID, key.getKeyID(), host.TYPE_MAP | host.TYPE_ARRAY); return new ScImmutableMapArray(arrID); } // get value proxy for immutable ScRequestID field specified by key getRequestID(key: MapKey): ScImmutableRequestID { return new ScImmutableRequestID(this.objID, key.getKeyID()); } // get array proxy for ScImmutableRequestIDArray specified by key getRequestIDArray(key: MapKey): ScImmutableRequestIDArray { let arrID = host.getObjectID(this.objID, key.getKeyID(), host.TYPE_REQUEST_ID | host.TYPE_ARRAY); return new ScImmutableRequestIDArray(arrID); } // get value proxy for immutable UTF-8 text string field specified by key getString(key: MapKey): ScImmutableString { return new ScImmutableString(this.objID, key.getKeyID()); } // get array proxy for ScImmutableStringArray specified by key getStringArray(key: MapKey): ScImmutableStringArray { let arrID = host.getObjectID(this.objID, key.getKeyID(), host.TYPE_STRING | host.TYPE_ARRAY); return new ScImmutableStringArray(arrID); } // get value proxy for immutable Uint8 field specified by key getUint8(key: MapKey): ScImmutableUint8 { return new ScImmutableUint8(this.objID, key.getKeyID()); } // get array proxy for ScImmutableUint8Array specified by key getUint8Array(key: MapKey): ScImmutableUint8Array { let arrID = host.getObjectID(this.objID, key.getKeyID(), host.TYPE_INT8 | host.TYPE_ARRAY); return new ScImmutableUint8Array(arrID); } // get value proxy for immutable Uint16 field specified by key getUint16(key: MapKey): ScImmutableUint16 { return new ScImmutableUint16(this.objID, key.getKeyID()); } // get array proxy for ScImmutableUint16Array specified by key getUint16Array(key: MapKey): ScImmutableUint16Array { let arrID = host.getObjectID(this.objID, key.getKeyID(), host.TYPE_INT16 | host.TYPE_ARRAY); return new ScImmutableUint16Array(arrID); } // get value proxy for immutable Uint32 field specified by key getUint32(key: MapKey): ScImmutableUint32 { return new ScImmutableUint32(this.objID, key.getKeyID()); } // get array proxy for ScImmutableUint32Array specified by key getUint32Array(key: MapKey): ScImmutableUint32Array { let arrID = host.getObjectID(this.objID, key.getKeyID(), host.TYPE_INT32 | host.TYPE_ARRAY); return new ScImmutableUint32Array(arrID); } // get value proxy for immutable Uint64 field specified by key getUint64(key: MapKey): ScImmutableUint64 { return new ScImmutableUint64(this.objID, key.getKeyID()); } // get array proxy for ScImmutableUint64Array specified by key getUint64Array(key: MapKey): ScImmutableUint64Array { let arrID = host.getObjectID(this.objID, key.getKeyID(), host.TYPE_INT64 | host.TYPE_ARRAY); return new ScImmutableUint64Array(arrID); } mapID(): i32 { return this.objID; } } // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // array proxy for immutable array of maps export class ScImmutableMapArray { objID: i32; constructor(id: i32) { this.objID = id; } // get value proxy for item at index, index can be 0..length()-1 getMap(index: i32): ScImmutableMap { let mapID = host.getObjectID(this.objID, new Key32(index), host.TYPE_MAP); return new ScImmutableMap(mapID); } // number of items in array length(): i32 { return host.getLength(this.objID); } } // value proxy for immutable ScRequestID in host container export class ScImmutableRequestID { objID: i32; keyID: Key32; constructor(objID: i32, keyID: Key32) { this.objID = objID; this.keyID = keyID; } // check if value exists in host container exists(): boolean { return host.exists(this.objID, this.keyID, host.TYPE_REQUEST_ID); } // human-readable string representation toString(): string { return this.value().toString(); } // get value from host container value(): ScRequestID { return ScRequestID.fromBytes(host.getBytes(this.objID, this.keyID, host.TYPE_REQUEST_ID)); } } // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // array proxy for immutable array of ScRequestID export class ScImmutableRequestIDArray { objID: i32; constructor(id: i32) { this.objID = id; } // get value proxy for item at index, index can be 0..length()-1 getRequestID(index: i32): ScImmutableRequestID { return new ScImmutableRequestID(this.objID, new Key32(index)); } // number of items in array length(): i32 { return host.getLength(this.objID); } } // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // value proxy for immutable UTF-8 text string in host container export class ScImmutableString { objID: i32; keyID: Key32; constructor(objID: i32, keyID: Key32) { this.objID = objID; this.keyID = keyID; } // check if value exists in host container exists(): boolean { return host.exists(this.objID, this.keyID, host.TYPE_STRING); } // human-readable string representation toString(): string { return this.value(); } // get value from host container value(): string { let bytes = host.getBytes(this.objID, this.keyID, host.TYPE_STRING); return Convert.toString(bytes); } } // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // array proxy for immutable array of UTF-8 text string export class ScImmutableStringArray { objID: i32; constructor(id: i32) { this.objID = id; } // get value proxy for item at index, index can be 0..length()-1 getString(index: i32): ScImmutableString { return new ScImmutableString(this.objID, new Key32(index)); } // number of items in array length(): i32 { return host.getLength(this.objID); } } // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // value proxy for immutable Uint8 in host container export class ScImmutableUint8 { objID: i32; keyID: Key32; constructor(objID: i32, keyID: Key32) { this.objID = objID; this.keyID = keyID; } // check if value exists in host container exists(): boolean { return host.exists(this.objID, this.keyID, host.TYPE_INT8); } // human-readable string representation toString(): string { return this.value().toString(); } // get value from host container value(): u8 { let bytes = host.getBytes(this.objID, this.keyID, host.TYPE_INT8); return bytes[0] as u8; } } // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // array proxy for immutable array of Uint8 export class ScImmutableUint8Array { objID: i32; constructor(id: i32) { this.objID = id; } // get value proxy for item at index, index can be 0..length()-1 getUint8(index: i32): ScImmutableUint8 { return new ScImmutableUint8(this.objID, new Key32(index)); } // number of items in array length(): u32 { return host.getLength(this.objID); } } // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // value proxy for immutable Uint16 in host container export class ScImmutableUint16 { objID: i32; keyID: Key32; constructor(objID: i32, keyID: Key32) { this.objID = objID; this.keyID = keyID; } // check if value exists in host container exists(): boolean { return host.exists(this.objID, this.keyID, host.TYPE_INT16); } // human-readable string representation toString(): string { return this.value().toString(); } // get value from host container value(): u16 { let bytes = host.getBytes(this.objID, this.keyID, host.TYPE_INT16); return Convert.toI16(bytes) as u16; } } // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // array proxy for immutable array of Uint16 export class ScImmutableUint16Array { objID: i32; constructor(id: i32) { this.objID = id; } // get value proxy for item at index, index can be 0..length()-1 getUint16(index: i32): ScImmutableUint16 { return new ScImmutableUint16(this.objID, new Key32(index)); } // number of items in array length(): i32 { return host.getLength(this.objID); } } // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // value proxy for immutable Uint32 in host container export class ScImmutableUint32 { objID: i32; keyID: Key32; constructor(objID: i32, keyID: Key32) { this.objID = objID; this.keyID = keyID; } // check if value exists in host container exists(): boolean { return host.exists(this.objID, this.keyID, host.TYPE_INT32); } // human-readable string representation toString(): string { return this.value().toString(); } // get value from host container value(): u32 { let bytes = host.getBytes(this.objID, this.keyID, host.TYPE_INT32); return Convert.toI32(bytes) as u32; } } // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // array proxy for immutable array of Uint32 export class ScImmutableUint32Array { objID: i32; constructor(id: i32) { this.objID = id; } // get value proxy for item at index, index can be 0..length()-1 getUint32(index: i32): ScImmutableUint32 { return new ScImmutableUint32(this.objID, new Key32(index)); } // number of items in array length(): i32 { return host.getLength(this.objID); } } // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // value proxy for immutable Uint64 in host container export class ScImmutableUint64 { objID: i32; keyID: Key32; constructor(objID: i32, keyID: Key32) { this.objID = objID; this.keyID = keyID; } // check if value exists in host container exists(): boolean { return host.exists(this.objID, this.keyID, host.TYPE_INT64); } // human-readable string representation toString(): string { return this.value().toString(); } // get value from host container value(): u64 { let bytes = host.getBytes(this.objID, this.keyID, host.TYPE_INT64); return Convert.toI64(bytes) as u64; } } // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // array proxy for immutable array of Uint64 export class ScImmutableUint64Array { objID: i32; constructor(id: i32) { this.objID = id; } // get value proxy for item at index, index can be 0..length()-1 getUint64(index: i32): ScImmutableUint64 { return new ScImmutableUint64(this.objID, new Key32(index)); } // number of items in array length(): i32 { return host.getLength(this.objID); } }
the_stack
import compareVersions from "compare-versions"; import * as fse from "fs-extra"; import * as path from "path"; import * as vscode from "vscode"; import { instrumentOperation, sendError, sendInfo, setUserError } from "vscode-extension-telemetry-wrapper"; import { XMLSerializer } from "@xmldom/xmldom"; import { getNonce } from "../utils"; import { Example, getSupportedVSCodeSettings, JavaConstants, SupportedSettings, VSCodeSettings } from "./FormatterConstants"; import { FormatterConverter } from "./FormatterConverter"; import { remoteProfileProvider, RemoteProfileProvider } from "./RemoteProfileProvider"; import { DOMElement, ExampleKind, ProfileContent } from "./types"; import { addDefaultProfile, downloadFile, getAbsoluteTargetPath, getProfilePath, getVSCodeSetting, isRemote, openFormatterSettings, parseProfile } from "./utils"; export class JavaFormatterSettingsEditorProvider implements vscode.CustomTextEditorProvider { public static readonly viewType = "java.formatterSettingsEditor"; private exampleKind: ExampleKind = ExampleKind.INDENTATION_EXAMPLE; private profileElements: Map<string, DOMElement> = new Map<string, DOMElement>(); private profileSettings: Map<string, string> = new Map<string, string>(); private lastElement: DOMElement | undefined; private settingsVersion: string = JavaConstants.CURRENT_FORMATTER_SETTINGS_VERSION; private checkedRequirement: boolean = false; private checkedProfileSettings: boolean = false; private diagnosticCollection: vscode.DiagnosticCollection = vscode.languages.createDiagnosticCollection(); private settingsUrl: string | undefined = vscode.workspace.getConfiguration("java").get<string>(JavaConstants.SETTINGS_URL_KEY); private webviewPanel: vscode.WebviewPanel | undefined; private profilePath: string = ""; private readOnly: boolean = false; constructor(private readonly context: vscode.ExtensionContext) { vscode.workspace.onDidChangeConfiguration(async (e) => { if (e.affectsConfiguration(`java.${JavaConstants.SETTINGS_URL_KEY}`) || e.affectsConfiguration(`java.${JavaConstants.SETTINGS_PROFILE_KEY}`)) { this.checkedProfileSettings = false; this.onChangeProfileSettings(); } else if (this.webviewPanel && (e.affectsConfiguration(VSCodeSettings.TAB_SIZE) || e.affectsConfiguration(VSCodeSettings.INSERT_SPACES) || e.affectsConfiguration(VSCodeSettings.DETECT_INDENTATION))) { await this.updateVSCodeSettings(); this.format(); } if (e.affectsConfiguration(`java.${JavaConstants.SETTINGS_URL_KEY}`)) { this.settingsUrl = vscode.workspace.getConfiguration("java").get<string>(JavaConstants.SETTINGS_URL_KEY); if (this.settingsUrl && !isRemote(this.settingsUrl)) { this.profilePath = await getProfilePath(this.settingsUrl); } } }); vscode.workspace.onDidChangeTextDocument(async (e: vscode.TextDocumentChangeEvent) => { if (!this.settingsUrl || e.document.uri.toString() !== vscode.Uri.file(this.profilePath).toString()) { return; } if (!await this.parseProfileAndUpdate(e.document)) { this.webviewPanel?.dispose(); } }); } public async showFormatterSettingsEditor(): Promise<void> { if (this.webviewPanel || !await this.checkProfileSettings() || !this.settingsUrl) { return; } const filePath = this.readOnly ? vscode.Uri.parse(this.settingsUrl).with({ scheme: RemoteProfileProvider.scheme }) : vscode.Uri.file(this.profilePath); vscode.commands.executeCommand("vscode.openWith", filePath, "java.formatterSettingsEditor"); } public reopenWithTextEditor(uri: any) { if (uri instanceof vscode.Uri) { vscode.commands.executeCommand("vscode.openWith", uri, "default"); } } public async resolveCustomTextEditor(document: vscode.TextDocument, webviewPanel: vscode.WebviewPanel, _token: vscode.CancellationToken): Promise<void> { // restrict one webviewpanel only if (this.webviewPanel) { vscode.commands.executeCommand("vscode.open", document.uri); webviewPanel.dispose(); return; } else { this.webviewPanel = webviewPanel; } this.webviewPanel.webview.options = { enableScripts: true, enableCommandUris: true, }; this.webviewPanel.onDidDispose(() => { this.webviewPanel = undefined; }); this.webviewPanel.webview.html = this.getHtmlForWebview(path.join(this.context.extensionPath, "out", "assets", "formatter-settings", "index.js")); this.webviewPanel.webview.onDidReceiveMessage(async (e) => { switch (e.command) { case "onWillInitialize": if (!await this.initialize(document)) { this.webviewPanel?.dispose(); } break; case "onWillChangeExampleKind": if (this.exampleKind !== e.exampleKind) { sendInfo("", { formatterExample: e.exampleKind }); this.exampleKind = e.exampleKind; this.format(); } break; case "onWillChangeSetting": const settingValue: string | undefined = FormatterConverter.webView2ProfileConvert(e.id, e.value.toString()); sendInfo("", { formatterSetting: e.id }); // "" represents an empty inputbox, we regard it as a valid value. if (settingValue === undefined) { return; } if (SupportedSettings.indentationSettings.includes(e.id)) { const config = vscode.workspace.getConfiguration(undefined, { languageId: "java" }); if (e.id === SupportedSettings.TABULATION_CHAR) { const targetValue = (settingValue === "tab") ? false : true; await config.update(VSCodeSettings.INSERT_SPACES, targetValue, undefined, true); } else if (e.id === SupportedSettings.TABULATION_SIZE) { await config.update(VSCodeSettings.TAB_SIZE, (settingValue === "") ? "" : Number(settingValue), undefined, true); } this.profileSettings.set(e.id, settingValue); } else if (e.id === VSCodeSettings.DETECT_INDENTATION) { const config = vscode.workspace.getConfiguration(undefined, { languageId: "java" }); await config.update(VSCodeSettings.DETECT_INDENTATION, (settingValue === "true"), undefined, true); } else { await this.modifyProfile(e.id, settingValue, document); } break; case "onWillDownloadAndUse": { const settingsUrl = vscode.workspace.getConfiguration("java").get<string>(JavaConstants.SETTINGS_URL_KEY); if (!settingsUrl || !isRemote(settingsUrl)) { vscode.window.showErrorMessage("The active formatter profile does not exist or is not remote, please check it in the Settings and try again.", "Open Settings").then((result) => { if (result === "Open Settings") { openFormatterSettings(); } }); return; } this.webviewPanel?.dispose(); await this.downloadAndUse(settingsUrl); break; } default: break; } }); await this.checkRequirement(); } private getHtmlForWebview(scriptPath: string) { const scriptPathOnDisk = vscode.Uri.file(scriptPath); const scriptUri = (scriptPathOnDisk).with({ scheme: "vscode-resource" }); // Use a nonce to whitelist which scripts can be run const nonce = getNonce(); return `<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width,initial-scale=1,shrink-to-fit=no"> <meta name="theme-color" content="#000000"> <title>Java Formatter Settings</title> </head> <body> <script nonce="${nonce}" src="${scriptUri}" type="module"></script> <noscript>You need to enable JavaScript to run this app.</noscript> <div id="formatterPanel"></div> </body> </html>`; } private async checkRequirement(): Promise<boolean> { if (this.checkedRequirement) { return true; } const javaExt = vscode.extensions.getExtension("redhat.java"); if (!javaExt) { vscode.window.showErrorMessage("The extension 'redhat.java' is not installed. Please install it and run this command again."); const err: Error = new Error("The extension 'redhat.java' is not installed."); setUserError(err); sendError(err); return false; } const javaExtVersion: string = javaExt.packageJSON.version; if (compareVersions(javaExtVersion, JavaConstants.MINIMUM_JAVA_EXTENSION_VERSION) < 0) { vscode.window.showErrorMessage(`The extension version of 'redhat.java' is too stale. Please install at least ${JavaConstants.MINIMUM_JAVA_EXTENSION_VERSION} and run this command again.`); const err: Error = new Error(`The extension version of 'redhat.java' (${javaExtVersion}) is too stale.`); setUserError(err); sendError(err); return false; } await javaExt.activate(); this.checkedRequirement = true; return true; } private async initialize(document: vscode.TextDocument): Promise<boolean> { this.exampleKind = ExampleKind.INDENTATION_EXAMPLE; if (!await this.checkRequirement() || !await this.checkProfileSettings() || !await this.parseProfileAndUpdate(document)) { return false; } this.webviewPanel?.webview.postMessage({ command: "changeReadOnlyState", value: this.readOnly, }); return true; } private async parseProfileAndUpdate(document: vscode.TextDocument): Promise<boolean> { const content: ProfileContent = parseProfile(document); if (!content.isValid) { vscode.window.showErrorMessage("The current profile is invalid, please check it in the Settings and try again.", "Open Settings").then((anwser) => { if (anwser === "Open Settings") { openFormatterSettings(); } }); return false; } this.diagnosticCollection.set(document.uri, content.diagnostics); if (this.webviewPanel) { this.profileElements = content.profileElements || this.profileElements; this.profileSettings = content.profileSettings || this.profileSettings; this.lastElement = content.lastElement || this.lastElement; this.settingsVersion = content.settingsVersion; if (content.supportedProfileSettings) { this.webviewPanel.webview.postMessage({ command: "loadProfileSetting", setting: Array.from(content.supportedProfileSettings.values()), }); } await this.updateVSCodeSettings(); this.format(); } return true; } private onChangeProfileSettings(): void { if (this.webviewPanel?.visible) { vscode.window.showInformationMessage(`Formatter Profile settings have been changed, do you want to reload this editor?`, "Yes", "No").then(async (result) => { if (result === "Yes") { vscode.commands.executeCommand("workbench.action.webview.reloadWebviewAction"); } }); } } private async updateVSCodeSettings(): Promise<void> { const supportedVSCodeSettings = getSupportedVSCodeSettings(); for (const setting of supportedVSCodeSettings.values()) { switch (setting.id) { case SupportedSettings.TABULATION_CHAR: setting.value = (getVSCodeSetting(VSCodeSettings.INSERT_SPACES, true) === false) ? "tab" : "space"; this.profileSettings.set(setting.id, setting.value); break; case SupportedSettings.TABULATION_SIZE: setting.value = String(getVSCodeSetting(VSCodeSettings.TAB_SIZE, 4)); this.profileSettings.set(setting.id, setting.value); break; case VSCodeSettings.DETECT_INDENTATION: setting.value = String(getVSCodeSetting(VSCodeSettings.DETECT_INDENTATION, true)); break; default: return; } } this.webviewPanel?.webview.postMessage({ command: "loadVSCodeSetting", setting: Array.from(supportedVSCodeSettings.values()), }); } private async format(): Promise<void> { const content = await vscode.commands.executeCommand<string>("java.execute.workspaceCommand", "java.edit.stringFormatting", Example.getExample(this.exampleKind), JSON.stringify([...this.profileSettings]), this.settingsVersion); if (this.webviewPanel?.webview) { this.webviewPanel.webview.postMessage({ command: "formattedContent", content: content, }); } } private async modifyProfile(id: string, value: string, document: vscode.TextDocument): Promise<void> { const profileElement = this.profileElements.get(id); if (!profileElement) { // add a new setting not exist in the profile if (!this.lastElement) { return; } const cloneElement = this.lastElement.cloneNode() as DOMElement; const originalString: string = new XMLSerializer().serializeToString(cloneElement); cloneElement.setAttribute("id", id); cloneElement.setAttribute("value", value); const edit: vscode.WorkspaceEdit = new vscode.WorkspaceEdit(); edit.insert(document.uri, new vscode.Position(cloneElement.lineNumber - 1, cloneElement.columnNumber - 1 + originalString.length), ((document.eol === vscode.EndOfLine.LF) ? "\n" : "\r\n") + " ".repeat(cloneElement.columnNumber - 1) + new XMLSerializer().serializeToString(cloneElement)); await vscode.workspace.applyEdit(edit); } else { // edit a current setting in the profile const originalSetting: string = new XMLSerializer().serializeToString(profileElement); profileElement.setAttribute("value", value); const edit: vscode.WorkspaceEdit = new vscode.WorkspaceEdit(); edit.replace(document.uri, new vscode.Range(new vscode.Position(profileElement.lineNumber - 1, profileElement.columnNumber - 1), new vscode.Position(profileElement.lineNumber - 1, profileElement.columnNumber - 1 + originalSetting.length)), new XMLSerializer().serializeToString(profileElement)); await vscode.workspace.applyEdit(edit); } } private async downloadAndUse(settingsUrl: string): Promise<boolean> { const profilePath = await getAbsoluteTargetPath(this.context, path.basename(settingsUrl)); const data = await downloadFile(settingsUrl); if (!data) { return false; } await fse.outputFile(profilePath, data); const workspaceFolders = vscode.workspace.workspaceFolders; await vscode.workspace.getConfiguration("java").update("format.settings.url", (workspaceFolders?.length ? vscode.workspace.asRelativePath(profilePath) : profilePath), !(workspaceFolders?.length)); this.showFormatterSettingsEditor(); return true; } private checkProfileSettings = instrumentOperation("java.formatter.checkProfileSetting", async (operationId: string) => { if (this.checkedProfileSettings) { return true; } this.readOnly = false; if (!this.settingsUrl) { sendInfo(operationId, { formatterProfileKind: "undefined" }); await vscode.window.showInformationMessage("No active Formatter Profile found, do you want to create a default one?", "Yes", "No").then((result) => { if (result === "Yes") { addDefaultProfile(this.context); } }); } else if (isRemote(this.settingsUrl)) { sendInfo(operationId, { formatterProfileKind: "remote" }); this.checkedProfileSettings = await vscode.window.showInformationMessage("The active formatter profile is remote, do you want to open it in read-only mode or download and use it locally?", "Open in read-only mode", "Download and use it locally").then(async (result) => { if (result === "Open in read-only mode") { const content = await downloadFile(this.settingsUrl!); if (!content) { return false; } remoteProfileProvider.setContent(this.settingsUrl!, content); this.readOnly = true; return true; } else if (result === "Download and use it locally") { this.downloadAndUse(this.settingsUrl!); return false; } else { return false; } }); } else { if (!this.profilePath) { this.profilePath = await getProfilePath(this.settingsUrl); } if (!(await fse.pathExists(this.profilePath))) { sendInfo(operationId, { formatterProfileKind: "notExist" }); await vscode.window.showInformationMessage("The active formatter profile does not exist, please check it in the Settings and try again.", "Open Settings", "Generate a default profile").then((result) => { if (result === "Open Settings") { openFormatterSettings(); } else if (result === "Generate a default profile") { addDefaultProfile(this.context); } }); return false; } sendInfo(operationId, { formatterProfileKind: "valid" }); this.checkedProfileSettings = true; } return this.checkedProfileSettings; }); } export let javaFormatterSettingsEditorProvider: JavaFormatterSettingsEditorProvider; export function initFormatterSettingsEditorProvider(context: vscode.ExtensionContext) { javaFormatterSettingsEditorProvider = new JavaFormatterSettingsEditorProvider(context); context.subscriptions.push(vscode.window.registerCustomEditorProvider(JavaFormatterSettingsEditorProvider.viewType, javaFormatterSettingsEditorProvider, { webviewOptions: { enableFindWidget: true, retainContextWhenHidden: true } })); }
the_stack
import * as vscode from 'vscode'; import * as chai from 'chai'; import * as sinonChai from 'sinon-chai'; import * as sinon from 'sinon'; import * as k8s from 'vscode-kubernetes-tools-api'; import { OdoImpl } from '../../../src/odo'; import { Build } from '../../../src/k8s/build'; import { Progress } from '../../../src/util/progress'; const {expect} = chai; chai.use(sinonChai); suite('K8s/build', () => { let quickPickStub: sinon.SinonStub; let sandbox: sinon.SinonSandbox; let termStub: sinon.SinonStub; let execStub: sinon.SinonStub; const errorMessage = 'FATAL ERROR'; const context = { id: 'dummy', impl: { id: 'build/nodejs-copm-nodejs-comp-8', metadata: undefined, name: 'nodejs-copm-nodejs-comp-8', namespace: 'myproject' } }; const buildData = `{ "apiVersion": "v1", "items": [ { "apiVersion": "build.openshift.io/v1", "kind": "Build", "metadata": { "annotations": { "openshift.io/build-config.name": "nodejs-copm-nodejs-comp" }, "creationTimestamp": "2019-07-19T13:29:52Z", "labels": { "app": "nodejs-comp" }, "name": "nodejs-copm-nodejs-comp-8", "namespace": "myproject", "resourceVersion": "60465", "selfLink": "/apis/build.openshift.io/v1/namespaces/myproject/builds/nodejs-copm-nodejs-comp-8", "uid": "4a5be709-aa29-11e9-99f2-5e5dae55d430" } } ], "kind": "List", "metadata": { "resourceVersion": "", "selfLink": "" } }`; setup(() => { sandbox = sinon.createSandbox(); termStub = sandbox.stub(OdoImpl.prototype, 'executeInTerminal'); execStub = sandbox.stub(OdoImpl.prototype, 'execute').resolves({ stdout: '', stderr: undefined, error: undefined }); sandbox.stub(Progress, 'execFunctionWithProgress').yields(); }); teardown(() => { sandbox.restore(); }); suite('BuildConfigNodeContributor', () => { const parent = { metadata: undefined, name: 'comp1-app', namespace: null, nodeType: 'resource', resourceKind: { abbreviation: 'bc', description: '', displayName: 'BuildConfigs', label: 'BuildConfigs', manifestKind: 'BuildConfigs', pluralDisplayName: 'BuildConfigs' } } as k8s.ClusterExplorerV1.ClusterExplorerNode; setup(() => { const api: k8s.API<k8s.KubectlV1> = { available: true, api: { invokeCommand: sandbox.stub().resolves({ stdout: 'namespace, name, 1', stderr: '', code: 0}), portForward: sandbox.stub() } }; sandbox.stub(k8s.extension.kubectl, 'v1').value(api); }); test('should able to get the children node of build Config', async () => { const bcnc = Build.getNodeContributor(); const result = await bcnc.getChildren(parent); expect(result.length).equals(1); }); }); suite('start build', () => { const startBuildCtx = { name: 'nodejs-comp-nodejs-app', metadata: undefined, namespace: null, nodeCategory: 'Kubernetes-explorer-node', nodeType: 'resource', resourceId: 'bc/nodejs-comp-nodejs-app' }; const noBcData = `{ "apiVersion": "v1", "items": [], "kind": "List", "metadata": { "resourceVersion": "", "selfLink": "" } }`; const mockData = `{ "apiVersion": "v1", "items": [ { "apiVersion": "build.openshift.io/v1", "kind": "BuildConfig", "metadata": { "annotations": { "app.kubernetes.io/component-source-type": "git", "app.kubernetes.io/url": "https://github.com/sclorg/nodejs-ex" }, "creationTimestamp": "2019-07-15T09:18:43Z", "name": "nodejs-comp-nodejs-app", "namespace": "myproject", "resourceVersion": "116630", "selfLink": "/apis/build.openshift.io/v1/namespaces/myproject/buildconfigs/nodejs-comp-nodejs-app", "uid": "8a66b3ff-a6e1-11e9-8dbe-22967c349399" }, "status": { "lastVersion": 8 } } ], "kind": "List", "metadata": { "resourceVersion": "", "selfLink": "" } }`; setup(() => { execStub.resolves({ error: undefined, stdout: mockData, stderr: '' }); quickPickStub = sandbox.stub(vscode.window, 'showQuickPick'); quickPickStub.resolves({label: 'nodejs-comp-nodejs-app'}); }); test('works from context menu', async () => { const result = await Build.startBuild(startBuildCtx); expect(result).equals(`Build '${startBuildCtx.name}' successfully started`); expect(execStub).calledWith(Build.command.startBuild(startBuildCtx.name)); }); test('works with no context', async () => { const result = await Build.startBuild(null); expect(result).equals(`Build '${startBuildCtx.name}' successfully started`); expect(execStub).calledWith(Build.command.startBuild(startBuildCtx.name)); }); test('returns null when no BuildConfig selected', async () => { quickPickStub.resolves(); const result = await Build.startBuild(null); expect(result).null; }); test('wraps errors in additional info', async () => { execStub.rejects(errorMessage); try { await Build.startBuild(startBuildCtx); } catch (err) { expect(err.message).equals(`Failed to start build with error '${errorMessage}'`); } }); test('throws error if there is no BuildConfigs to select', async () => { quickPickStub.restore(); execStub.resolves({ error: undefined, stdout: noBcData, stderr: '' }); let checkError: Error; try { await Build.startBuild(null); } catch (err) { checkError = err as Error; } expect(checkError.message).equals('You have no BuildConfigs available to start a build'); }); }); suite('Show Log', () => { setup(() => { execStub.resolves({ error: null, stdout: buildData, stderr: '' }); const buidConfig = {label: 'nodejs-copm-nodejs-comp'}; sandbox.stub(Build, 'getBuildConfigNames').resolves([buidConfig]); quickPickStub = sandbox.stub(vscode.window, 'showQuickPick'); quickPickStub.onFirstCall().resolves(buidConfig); quickPickStub.onSecondCall().resolves({label: 'nodejs-copm-nodejs-comp-8'}); }); test('works from context menu', async () => { await Build.showLog(context); expect(termStub).calledOnceWith(Build.command.showLog(context.impl.name, '-build')); }); test('works with no context', async () => { await Build.showLog(null); expect(termStub).calledOnceWith(Build.command.showLog('nodejs-copm-nodejs-comp-8', '-build')); }); test('returns null when no build selected', async () => { quickPickStub.onSecondCall().resolves(); const result = await Build.showLog(null); expect(result).null; }); }); suite('rebuild', () => { setup(() => { sandbox.stub<any, any>(Build, 'getBuildNames').resolves('nodejs-copm-nodejs-comp'); quickPickStub = sandbox.stub(vscode.window, 'showQuickPick'); quickPickStub.resolves({label: 'nodejs-copm-nodejs-comp-8'}); }); test('works from context menu', async () => { execStub.resolves({ error: null, stdout: 'nodejs-copm-nodejs-comp', stderr: '' }); await Build.rebuild(context); expect(termStub).calledOnceWith(Build.command.rebuildFrom(context.impl.name)); }); test('works with no context', async () => { execStub.onFirstCall().resolves({ error: null, stdout: buildData, stderr: '' }); execStub.onSecondCall().resolves({ error: null, stdout: 'nodejs-copm-nodejs-comp', stderr: '' }); await Build.rebuild(null); expect(termStub).calledOnceWith(Build.command.rebuildFrom('nodejs-copm-nodejs-comp-8')); }); test('returns null when no build selected to rebuild', async () => { execStub.onFirstCall().resolves({ error: null, stdout: buildData, stderr: '' }); execStub.onSecondCall().resolves({ error: null, stdout: 'nodejs-copm-nodejs-comp', stderr: '' }); quickPickStub.resolves(); const result = await Build.rebuild(null); expect(result).null; }); }); suite('followLog', () => { setup(() => { execStub.resolves({ error: null, stdout: buildData, stderr: '' }); sandbox.stub<any, any>(Build, 'getBuildNames').resolves('nodejs-copm-nodejs-comp'); quickPickStub = sandbox.stub(vscode.window, 'showQuickPick'); quickPickStub.resolves({label: 'nodejs-copm-nodejs-comp-8'}); }); test('works from context menu', async () => { await Build.followLog(context); expect(termStub).calledOnceWith(Build.command.followLog(context.impl.name, '-build')); }); test('works with no context', async () => { await Build.followLog(null); expect(termStub).calledOnceWith(Build.command.followLog('nodejs-copm-nodejs-comp-8', '-build')); }); test('returns null when no build selected', async () => { quickPickStub.resolves(); const result = await Build.followLog(null); expect(result).null; }); }); suite('Delete', ()=> { setup(() => { execStub.resolves({ error: null, stdout: buildData, stderr: '' }); sandbox.stub<any, any>(Build, 'getBuildNames').resolves('nodejs-copm-nodejs-comp'); quickPickStub = sandbox.stub(vscode.window, 'showQuickPick'); quickPickStub.resolves({label: 'nodejs-copm-nodejs-comp-8'}); }); test('works from context menu', async () => { const result = await Build.delete(context); expect(result).equals(`Build '${context.impl.name}' successfully deleted`); expect(execStub).calledWith(Build.command.delete(context.impl.name)); }); test('works with no context', async () => { const result = await Build.delete(null); expect(result).equals('Build \'nodejs-copm-nodejs-comp-8\' successfully deleted'); expect(execStub).calledWith(Build.command.delete('nodejs-copm-nodejs-comp-8')); }); test('returns null when no build selected to delete', async () => { quickPickStub.resolves(); const result = await Build.delete(null); expect(result).null; }); test('wraps errors in additional info', async () => { execStub.rejects(errorMessage); try { await Build.delete(context); } catch (err) { expect(err.message).equals(`Failed to delete build with error '${errorMessage}'`); } }); }); });
the_stack
import { action, observable, computed } from 'mobx'; import { File, FsApi, getFS } from '../services/Fs'; import { FileState } from './fileState'; import { Batch } from '../transfers/batch'; import { clipboard, shell } from 'electron'; import { lineEnding, DOWNLOADS_DIR } from '../utils/platform'; import { ViewDescriptor } from '../components/TabList'; import { WinState, WindowSettings } from './winState'; import { FavoritesState } from './favoritesState'; import { ViewState } from './viewState'; declare const ENV: { [key: string]: string | boolean | number | Record<string, unknown> }; // wait 1 sec before showing badge: this avoids // flashing (1) badge when the transfer is very fast const SHOW_BADGE_DELAY = 600; /** * Interface for a clipboard entry * * @interface */ interface Clipboard { srcFs: FsApi; srcPath: string; files: File[]; } /** * Interface for a transfer * * @interface */ interface TransferOptions { srcFs: FsApi; dstFs: FsApi; files: File[]; srcPath: string; dstPath: string; dstFsName: string; } /** * Maintains global application state: * * - list of ongoing transfers * - active view: explorer of file view * * Transfers are also starting from appState */ export class AppState { caches: FileState[] = []; winStates: WinState[] = observable<WinState>([]); favoritesState: FavoritesState = new FavoritesState(); @observable isExplorer = true; @observable isPrefsOpen = false; @observable isShortcutsOpen = false; @observable isExitDialogOpen = false; @action toggleSplitViewMode(): void { const winState = this.winStates[0]; winState.toggleSplitViewMode(); } /* transfers */ transfers = observable<Batch>([]); // current active transfers activeTransfers = observable<Batch>([]); /** * Creates the application state * * @param views The initial paths of the caches that we want to create */ constructor(views: Array<ViewDescriptor>, options: WindowSettings) { this.addWindow(options); for (const desc of views) { console.log('adding view', desc.viewId, desc.path); this.addView(ENV.CY ? '' : desc.path, desc.viewId); } this.initViewState(); } @action showDownloadsTab = (): void => { this.isExplorer = false; }; @action showExplorerTab = (): void => { this.isExplorer = true; }; @action /** * initialize each window's state: hardcoded to first window since we only have * one window now */ initViewState(): void { const winState = this.winStates[0]; winState.initState(); } /** * Prepares transferring files from clipboard to specified cache * The source cache is taken from the clipboard * * @param cache file cache to transfer files to * * @returns {Promise<FileTransfer[]>} */ prepareClipboardTransferTo(cache: FileState): Promise<boolean | void> { const options = { files: this.clipboard.files, srcFs: this.clipboard.srcFs, srcPath: this.clipboard.srcPath, dstFs: cache.getAPI(), dstPath: cache.path, dstFsName: cache.getFS().name, }; return this.addTransfer(options) .then((res) => { debugger; if ( options.dstPath === cache.path && options.dstFsName === cache.getFS().name && cache.getFS().options.needsRefresh ) { cache.reload(); } return res; }) .catch((/*err: LocalizedError*/) => { debugger; }); } /** * Prepares transferring files from source to destination cache * * @param srcCache file cache to transfer files from * @param dstCache file fache to transfer files to * @param files the list of files to transfer * * @returns {Promise<void>} */ prepareTransferTo(srcCache: FileState, dstCache: FileState, files: File[]): Promise<boolean | void> { if (!files.length) { return; } let srcApi = null; let srcPath = ''; // native drag and drop if (!srcCache) { srcPath = files[0].dir; const fs = getFS(srcPath); srcApi = new fs.API(srcPath, () => { // }); } const options = { files, srcFs: (srcCache && srcCache.getAPI()) || srcApi, srcPath: (srcCache && srcCache.path) || srcPath, dstFs: dstCache.getAPI(), dstPath: dstCache.path, dstFsName: dstCache.getFS().name, }; return this.addTransfer(options) .then((res) => { const fs = dstCache.getFS(); if (fs.options.needsRefresh && options.dstPath === dstCache.path && options.dstFsName === fs.name) { dstCache.reload(); } return res; }) .catch((/*err*/) => { debugger; }); } /** * Opens a file that has been transfered * * @param file the file to open */ openTransferedFile(batchId: number, file: File): void { // TODO: this is duplicate code from appState/prepareLocalTransfer and fileState.openFile() // because we don't have a reference to the destination cache const batch = this.transfers.find((transfer) => transfer.id === batchId); const api = batch.dstFs; const path = api.join(file.dir, file.fullname); shell.openPath(path); } /** * Prepares transferring files from srcCache to temp location * in local filesystem * * @param srcCache: cache to trasnfer files from * @param files the list of files to transfer * * @returns {Promise<FileTransfer[]>} */ prepareLocalTransfer(srcCache: FileState, files: File[]): Promise<string> { if (!files.length) { return Promise.resolve(''); } // simply open the file if src is local FS if (srcCache.getFS().name === 'local') { const api = srcCache.getAPI(); return Promise.resolve(api.join(files[0].dir, files[0].fullname)); } else { // first we need to get a FS for local const fs = getFS(DOWNLOADS_DIR); const api = new fs.API(DOWNLOADS_DIR, () => { // }); const options = { files, srcFs: srcCache.getAPI(), srcPath: srcCache.path, dstFs: api, dstPath: DOWNLOADS_DIR, dstFsName: fs.name, }; // TODO: use a temporary filename for destination file? return this.addTransfer(options) .then(() => { return api.join(DOWNLOADS_DIR, files[0].fullname); }) .catch((err) => { return Promise.reject(err); }); } } getViewFromCache(cache: FileState): ViewState { const winState = this.winStates[0]; const viewId = cache.viewId; return winState.getView(viewId); } /** * Returns the cache that's not active (ie: destination cache) * * NOTE: this would have no sense if we had more than two file caches */ getInactiveViewVisibleCache(): FileState { const winState = this.winStates[0]; const view = winState.getInactiveView(); return view.caches.find((cache) => cache.isVisible === true); } getViewVisibleCache(viewId: number): FileState { const winState = this.winStates[0]; const view = winState.getView(viewId); return view.caches.find((cache) => cache.isVisible === true); } getCachesForView(viewId: number): FileState[] { const winState = this.winStates[0]; const view = winState.getView(viewId); return view.caches; } @computed get totalTransferProgress(): number { let totalSize = 0; let totalProgress = 0; const runningTransfers = this.activeTransfers; // .filter(transfer => !transfer.status.match(/error|done/)); for (const transfer of runningTransfers) { totalSize += transfer.size; totalProgress += transfer.progress; } return (totalSize && totalProgress / totalSize) || 0; } getTransfer(transferId: number): Batch { return this.transfers.find((transfer) => transferId === transfer.id); } @computed get pendingTransfers(): number { const now = new Date(); const num = this.transfers.filter( (transfer) => transfer.progress && transfer.isStarted && now.getTime() - transfer.startDate.getTime() >= SHOW_BADGE_DELAY, ).length; return num; } @action // addTransfer(srcFs: FsApi, dstFs: FsApi, files: File[], srcPath: string, dstPath: string) { async addTransfer(options: TransferOptions): Promise<boolean | void> { let isDir = false; try { isDir = await options.dstFs.isDir(options.dstPath); } catch (err) { isDir = false; } if (!isDir) { return Promise.reject({ code: 'NODEST', }); } console.log('addTransfer', options.files, options.srcFs, options.dstFs, options.dstPath); const batch = new Batch(options.srcFs, options.dstFs, options.srcPath, options.dstPath); this.transfers.unshift(batch); return batch.setFileList(options.files).then(() => { batch.calcTotalSize(); batch.status = 'queued'; // console.log('got file list !'); // start transfer ? // setInterval(() => { // runInAction(() => { // console.log('progress up'); // batch.updateProgress(); // }); // }, 1000); const activeTransfers = this.transfers.filter((transfer) => !transfer.status.match(/error|done/)); // CHECKME if (this.activeTransfers.length === 1) { this.activeTransfers.clear(); } this.activeTransfers.push(batch); return batch.start(); }); } removeTransfer(transferId: number): void { const batch = this.transfers.find((transfer) => transfer.id === transferId); if (batch) { batch.cancel(); this.transfers.remove(batch); } } /* /transfers */ getActiveCache(): FileState { const winState = this.winStates[0]; const view = winState.getActiveView(); return this.isExplorer ? view.caches.find((cache) => cache.isVisible === true) : null; } @action refreshActiveView(): void { const cache = this.getActiveCache(); // only refresh view that's ready if (cache) { cache.reload(); } } addWindow(options: WindowSettings): void { const winState = new WinState(options); this.winStates.push(winState); } @action addView(path = '', viewId = -1): void { const winState = this.winStates[0]; const view = winState.getOrCreateView(viewId); // let view = this.getView(viewId); // if (!view) { // view = this.createView(viewId); // this.views[viewId] = view; // } view.addCache(path); } @action updateSelection(cache: FileState, newSelection: File[]): void { console.log('updateSelection', newSelection.length); cache.selected.replace(newSelection); for (const selected of cache.selected) { console.log(selected.fullname, selected.id.dev, selected.id.ino); } if (newSelection.length) { const file = newSelection.slice(-1)[0]; cache.setSelectedFile(file); } else { cache.setSelectedFile(null); } // for (let selected of cache.selected) { // console.log(selected.fullname, selected.id.dev, selected.id.ino); // } } @observable clipboard: Clipboard = { srcPath: '', srcFs: null, files: [], }; @action setClipboard(fileState: FileState): number { const files = fileState.selected.slice(0); this.clipboard = { srcFs: fileState.getAPI(), srcPath: fileState.path, files, }; console.log('clipboard', files); return files.length; } @action copySelectedItemsPath(fileState: FileState, filenameOnly = false): string { const files = fileState.selected; let text = ''; if (files.length) { const pathnames = files.map((file) => fileState.join((!filenameOnly && file.dir) || '', file.fullname)); text = pathnames.join(lineEnding); clipboard.writeText(text); } return text; } }
the_stack
import {ExpandedType} from 'compassql/build/src/query/expandedtype'; import {Axis} from 'vega-lite/build/src/axis'; import {Channel} from 'vega-lite/build/src/channel'; import {Legend} from 'vega-lite/build/src/legend'; import {Scale} from 'vega-lite/build/src/scale'; import {contains} from 'vega-lite/build/src/util'; import * as vlSchema from 'vega-lite/build/vega-lite-schema.json'; import {ShelfFieldDef, ShelfId} from '../../models/shelf/spec'; // ------------------------------------------------------------------------------ // Schema Interfaces // ------------------------------------------------------------------------------ export interface SchemaProperties { [key: string]: SchemaProperty; } export interface ObjectSchema { type: 'object'; title?: string; properties: SchemaProperties; } export interface StringSchema { type: 'string'; title: string; enum?: string[]; default?: string; } export interface IntegerSchema { type: 'number'; title: string; minimum: number; maximum: number; multipleOf: number; } export function isStringSchema(schema: SchemaProperty): schema is StringSchema { return schema.type === 'string'; } export type SchemaProperty = ObjectSchema | StringSchema | IntegerSchema; export interface UISchema { [key: string]: UISchemaItem; } // NOTE: keys for these interfaces follow the requirement for react-jsonSchema form // (https://mozilla-services.github.io/react-jsonschema-form/) export interface UISchemaItem { 'ui:widget'?: string; 'ui:placeholder'?: string; 'ui:emptyValue'?: string; } export interface PropertyEditorSchema { uiSchema: UISchema; schema: ObjectSchema; } // Currently supported customizble encoding channels that display caret in customizer UI export const CUSTOMIZABLE_ENCODING_CHANNELS = [Channel.X, Channel.Y, Channel.COLOR, Channel.SIZE, Channel.SHAPE]; // ------------------------------------------------------------------------------ // Channel-Field Indexes for custom encoding // Key is Tab name, value is list of fieldDef properties // ------------------------------------------------------------------------------ const AXIS_ORIENT_TITLE = ['title', 'orient'].map(p => ({prop: 'axis', nestedProp: p})); const LEGEND_ORIENT_TITLE = ['orient', 'title'].map(p => ({prop: 'legend', nestedProp: p})); const POSITION_FIELD_NOMINAL_INDEX = { 'Common': [ { prop: 'scale', nestedProp: 'type' }, ...AXIS_ORIENT_TITLE ] }; const POSITION_FIELD_TEMPORAL_INDEX = POSITION_FIELD_NOMINAL_INDEX; const POSITION_FIELD_QUANTITATIVE_INDEX = { 'Common': [ ...POSITION_FIELD_NOMINAL_INDEX.Common, {prop: 'stack'} ] }; const COLOR_CHANNEL_FIELD_INDEX = { 'Legend': ['orient', 'title', 'type'].map(p => ({prop: 'legend', nestedProp: p})), 'Scale': ['type', 'domain', 'scheme'].map(p => ({prop: 'scale', nestedProp: p})) }; const SIZE_CHANNEL_FIELD_INDEX = { 'Legend': ['orient', 'title'].map(p => ({prop: 'legend', nestedProp: p})), 'Scale': ['type', 'domain', 'range'].map(p => ({prop: 'scale', nestedProp: p})) }; const SHAPE_CHANNEL_FIELD_INDEX = { 'Legend': LEGEND_ORIENT_TITLE, 'Scale': ['domain', 'range'].map(p => ({prop: 'scale', nestedProp: p})) }; // ------------------------------------------------------------------------------ // Color Scheme Constants // ------------------------------------------------------------------------------ export const CATEGORICAL_COLOR_SCHEMES = ['accent', 'category10', 'category20', 'category20b', 'category20c', 'dark2', 'paired', 'pastel1', 'pastel1', 'set1', 'set2', 'set3', 'tableau10', 'tableau20']; export const SEQUENTIAL_COLOR_SCHEMES = ['blues', 'greens', 'greys', 'purples', 'reds', 'oranges', 'viridis', 'inferno', 'magma', 'plasma', 'bluegreen', 'bluepurple', 'greenblue', 'orangered', 'blueorange']; // ------------------------------------------------------------------------------ // Generator/Factory Methods // ------------------------------------------------------------------------------ export function generatePropertyEditorSchema(prop: string, nestedProp: string, propTab: string, fieldDef: ShelfFieldDef, channel: Channel): PropertyEditorSchema { const title = generateTitle(prop, nestedProp, propTab); const propertyKey = nestedProp ? prop + '_' + nestedProp : prop; switch (prop) { case 'scale': const scaleTypes: string[] = getSupportedScaleTypes(channel, fieldDef); return generateScaleEditorSchema(nestedProp as keyof Scale, scaleTypes, fieldDef, title, propertyKey); case 'axis': return generateAxisEditorSchema(nestedProp as keyof Axis, channel, title, propertyKey); case 'stack': return generateSelectSchema('stack', (vlSchema as any).definitions.StackOffset.enum, title); case 'legend': return generateLegendEditorSchema(nestedProp as keyof Legend, title, propertyKey); case 'format': return generateTextBoxSchema('format', '', title, 'string'); default: throw new Error('Property combination not recognized'); } } function generateLegendEditorSchema(legendProp: keyof Legend, title: string, propertyKey: string) { switch (legendProp) { case 'orient': return generateSelectSchema(propertyKey, (vlSchema as any).definitions.LegendOrient.enum, title); case 'title': return generateTextBoxSchema(propertyKey, '', title, 'string'); case 'type': return generateSelectSchema(propertyKey, (vlSchema as any).definitions.Legend.properties.type.enum, title); default: throw new Error('Property combination not recognized'); } } function generateAxisEditorSchema(axisProp: keyof Axis, channel: Channel, title: string, propertyKey: string) { switch (axisProp) { case 'orient': return generateSelectSchema(propertyKey, channel === 'y' ? ['left', 'right'] : ['top', 'bottom'], title); case 'title': return generateTextBoxSchema(propertyKey, '', title, 'string'); default: throw new Error('Property combination not recognized'); } } function generateScaleEditorSchema(scaleProp: keyof Scale, scaleTypes: string[], fieldDef: ShelfFieldDef, title: string, propertyKey: string) { switch (scaleProp) { case 'type': return generateSelectSchema(propertyKey, scaleTypes, title); case 'scheme': return generateSelectSchema(propertyKey, isContinuous(fieldDef) ? SEQUENTIAL_COLOR_SCHEMES : CATEGORICAL_COLOR_SCHEMES, title); case 'range': case 'domain': return generateTextBoxSchema(propertyKey, isDiscrete(fieldDef) ? 'a, b, c, ...' : 'Min Number, Max Number', title, 'string'); default: throw new Error('Provided property is not supported'); } } // TODO: Eventually refactor to Vega-Lite function getSupportedScaleTypes(channel: Channel, fieldDef: ShelfFieldDef): string[] { switch (fieldDef.type) { case ExpandedType.QUANTITATIVE: if (contains([Channel.X, Channel.Y], channel)) { return ["linear", "log", "pow", "sqrt"]; } else if (channel === Channel.COLOR) { return ["linear", "pow", "sqrt", "log", "sequential"]; } else if (channel === Channel.SIZE) { return ["linear", "pow", "sqrt", "log"]; } else { return []; } case ExpandedType.ORDINAL: case ExpandedType.NOMINAL: if (contains([Channel.X, Channel.Y], channel)) { return ["point", "band"]; } else if (channel === Channel.COLOR) { return ["ordinal"]; } else if (channel === Channel.SIZE) { return ["point", "band"]; } else { return []; } case ExpandedType.TEMPORAL: if (contains([Channel.X, Channel.Y], channel)) { return ["time", "utc"]; } else if (channel === Channel.COLOR) { return ["time", "utc", "sequential"]; } else if (channel === Channel.SIZE) { return ["time", "utc"]; } else { return []; } default: return []; } } function generateSelectSchema(propertyKey: string, enumVals: string[], title: string) { const schema: ObjectSchema = { type: 'object', properties: { [propertyKey]: { type: 'string', title: title, enum: enumVals } } }; const uiSchema: UISchema = { [propertyKey]: { 'ui:widget': 'select', 'ui:placeholder': 'auto', 'ui:emptyValue': 'auto' } }; return {schema, uiSchema}; } function generateTextBoxSchema(propKey: string, placeHolderText: string, title: string, primitiveType: 'string' | 'number') { const schema: ObjectSchema = { type: 'object', properties: { [propKey]: { title: title, type: primitiveType } as SchemaProperty } }; const uiSchema: UISchema = { [propKey]: { 'ui:emptyValue': '', 'ui:placeholder': placeHolderText } }; return {schema, uiSchema}; } export function getFieldPropertyGroupIndex(shelfId: ShelfId, fieldDef: ShelfFieldDef) { if (fieldDef && (shelfId.channel === Channel.X || shelfId.channel === Channel.Y)) { switch (fieldDef.type) { case ExpandedType.QUANTITATIVE: if (!isContinuous(fieldDef)) { return POSITION_FIELD_QUANTITATIVE_INDEX.Common.filter(t => { return t.prop !== "stack"; }); } return POSITION_FIELD_QUANTITATIVE_INDEX; case ExpandedType.ORDINAL: return POSITION_FIELD_NOMINAL_INDEX; case ExpandedType.NOMINAL: return POSITION_FIELD_NOMINAL_INDEX; case ExpandedType.TEMPORAL: return POSITION_FIELD_TEMPORAL_INDEX; } } else if (shelfId.channel === Channel.COLOR) { return COLOR_CHANNEL_FIELD_INDEX; } else if (shelfId.channel === Channel.SIZE) { return SIZE_CHANNEL_FIELD_INDEX; } else if (shelfId.channel === Channel.SHAPE) { return SHAPE_CHANNEL_FIELD_INDEX; } } export function generateFormData(shelfId: ShelfId, fieldDef: ShelfFieldDef) { const index = getFieldPropertyGroupIndex(shelfId, fieldDef); const formDataIndex = {}; for (const key of Object.keys(index)) { for (const customProp of index[key]) { const prop = customProp.prop; const nestedProp = customProp.nestedProp; const propertyKey = nestedProp ? prop + '_' + nestedProp : prop; const formData = fieldDef[prop] ? nestedProp ? fieldDef[prop][nestedProp] : fieldDef[prop] : undefined; // Display empty string when '?' is passed in to retrieve default value // '?' is passed when formData is empty to avoid passing in empty string as a property/nestedProp value formDataIndex[propertyKey] = formData === undefined ? '' : formData; } } return formDataIndex; } // ------------------------------------------------------------------------------ // General-Purpose Helper Methods // ------------------------------------------------------------------------------ export function isContinuous(fieldDef: ShelfFieldDef) { return contains([ExpandedType.ORDINAL, ExpandedType.TEMPORAL, ExpandedType.QUANTITATIVE], fieldDef.type); } export function isDiscrete(fieldDef: ShelfFieldDef) { return !isContinuous(fieldDef); } // Capitalize first letter for aesthetic purposes in form function toTitleCase(str: string) { return str.replace(/\w\S*/g, txt => { return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase(); }); } // Generate title for react-form with appropriate casing, prop, nestedProp function generateTitle(prop: string, nestedProp: string, propTab: string): string { let title; if (propTab === 'Common') { title = nestedProp ? prop + ' ' + nestedProp : prop; } else { title = nestedProp || prop; } return toTitleCase(title); }
the_stack
import { Observable } from 'rxjs/Observable' import { ErrorObservable } from 'rxjs/observable/ErrorObservable' import { Subscription } from 'rxjs/Subscription' import { ConnectableObservable } from 'rxjs/observable/ConnectableObservable' import * as lf from 'lovefield' import * as Exception from '../exception' import * as definition from './helper/definition' import version from '../version' import { Traversable } from '../shared' import { Mutation, Selector, QueryToken, PredicateProvider } from './modules' import { dispose, contextTableName, fieldIdentifier, hiddenColName } from './symbols' import { forEach, clone, contains, tryCatch, hasOwn, getType, assert, identity, warn } from '../utils' import { createPredicate, createPkClause, mergeTransactionResult, predicatableQuery, lfFactory } from './helper' import { Relationship, RDBType, DataStoreType, LeafType, StatementType, JoinMode } from '../interface/enum' import { Record, Fields, JoinInfo, Query, Clause, Predicate } from '../interface' import { SchemaDef, ColumnDef, ParsedSchema, Association, ScopedHandler } from '../interface' import { ColumnLeaf, NavigatorLeaf, ExecutorResult, UpsertContext, SelectContext } from '../interface' export class Database { public static version = version public static getTables(db: lf.Database, ...tableNames: string[]) { return tableNames.map((name) => db.getSchema().table(name)) } public database$: ConnectableObservable<lf.Database> private schemaDefs = new Map<string, SchemaDef<any>>() private schemas = new Map<string, ParsedSchema>() private schemaBuilder: lf.schema.Builder | null private connected = false // note thin cache will be unreliable in some eage case private storedIds = new Set<string>() private subscription: Subscription private findPrimaryKey = (name: string) => { return this.findSchema(name)!.pk } private findSchema = (name: string): ParsedSchema => { const schema = this.schemas.get(name) assert(schema, Exception.NonExistentTable(name)) return schema! } /** * @method defineSchema * @description 定义数据表的 metadata, 通过ReactiveDB查询时会根据这些 metadata 决定如何处理关联数据 */ defineSchema<T>(tableName: string, schema: SchemaDef<T>) { const advanced = !this.schemaDefs.has(tableName) && !this.connected assert(advanced, Exception.UnmodifiableTable()) const hasPK = Object.keys(schema) .some((key: string) => schema[key].primaryKey === true) assert(hasPK, Exception.PrimaryKeyNotProvided()) this.schemaDefs.set(tableName, schema) return this } /** * @constructor ReactiveDB * @param storeType 定义使用的BackStore类型 * @param enableInspector 是否允许外联Inspector * @param name 定义当前数据仓储的名字 * @param version 定义当前数据仓储的版本 */ constructor( storeType: DataStoreType = DataStoreType.MEMORY, enableInspector: boolean = false, name = 'ReactiveDB', version = 1 ) { this.schemaBuilder = lf.schema.create(name, version) this.database$ = lfFactory(this.schemaBuilder, { storeType, enableInspector }) } connect() { this.buildTables() this.connected = true // definition should be clear once database is connected this.schemaDefs.clear() this.subscription = this.database$.connect() } dump() { return this.database$.concatMap(db => db.export()) } load(data: any) { assert(!this.connected, Exception.DatabaseIsNotEmpty()) return this.database$ .concatMap(db => { forEach(data.tables, (entities: any[], name: string) => { const schema = this.findSchema(name) entities.forEach((entity: any) => this.storedIds.add(fieldIdentifier(name, entity[schema.pk]))) }) return db.import(data).catch(() => { forEach(data.tables, (entities: any[], name: string) => { const schema = this.findSchema(name) entities.forEach((entity: any) => this.storedIds.delete(fieldIdentifier(name, entity[schema.pk]))) }) }) }) } insert<T>(tableName: string, raw: T[]): Observable<ExecutorResult> insert<T>(tableName: string, raw: T): Observable<ExecutorResult> insert<T>(tableName: string, raw: T | T[]): Observable<ExecutorResult> insert<T>(tableName: string, raw: T | T[]): Observable<ExecutorResult> { return this.database$ .concatMap(db => { const schema = this.findSchema(tableName) const pk = schema.pk const columnMapper = schema.mapper const [ table ] = Database.getTables(db, tableName) const muts: Mutation[] = [] const entities = clone(raw) const iterator = Array.isArray(entities) ? entities : [entities] iterator.forEach((entity: any) => { const mut = new Mutation(db, table) const hiddenPayload = Object.create(null) columnMapper.forEach((mapper, key) => { // cannot create a hidden column for primary key if (!hasOwn(entity, key) || key === pk) { return } const val = entity[key] hiddenPayload[key] = mapper(val) hiddenPayload[hiddenColName(key)] = val }) mut.patch({ ...entity, ...hiddenPayload }) mut.withId(pk, entity[pk]) muts.push(mut) }) const { contextIds, queries } = Mutation.aggregate(db, muts, []) contextIds.forEach(id => this.storedIds.add(id)) return this.executor(db, queries) .do({ error: () => contextIds.forEach(id => this.storedIds.delete(id)) }) }) } get<T>(tableName: string, query: Query<T> = {}, mode: JoinMode = JoinMode.imlicit): QueryToken<T> { const selector$ = this.buildSelector<T>(tableName, query, mode) return new QueryToken<T>(selector$) } update<T>(tableName: string, clause: Predicate<T>, raw: Partial<T>): Observable<ExecutorResult> { const type = getType(raw) if (type !== 'Object') { return Observable.throw(Exception.InvalidType(['Object', type])) } const [ schema, err ] = tryCatch<ParsedSchema>(this.findSchema)(tableName) if (err) { return Observable.throw(err) } return this.database$ .concatMap<any, any>(db => { const entity = clone(raw) const [ table ] = Database.getTables(db, tableName) const columnMapper = schema!.mapper const hiddenPayload = Object.create(null) columnMapper.forEach((mapper, key) => { // cannot create a hidden column for primary key if (!hasOwn(entity, key) || key === schema!.pk) { return } const val = (entity as any)[key] hiddenPayload[key] = mapper(val) hiddenPayload[hiddenColName(key)] = val }) const mut = { ...(entity as any), ...hiddenPayload } const predicate = createPredicate(table, clause) const query = predicatableQuery(db, table, predicate!, StatementType.Update) forEach(mut, (val, key) => { const column = table[key] if (key === schema!.pk) { warn(`Primary key is not modifiable.`) } else if (!column) { warn(`Column: ${key} is not existent on table:${tableName}`) } else { query.set(column, val) } }) return this.executor(db, [query]) }) } delete<T>(tableName: string, clause: Predicate<T> = {}): Observable<ExecutorResult> { const [pk, err] = tryCatch<string>(this.findPrimaryKey)(tableName) if (err) { return Observable.throw(err) } return this.database$ .concatMap(db => { const [ table ] = Database.getTables(db, tableName) const column = table[pk!] const provider = new PredicateProvider(table, clause) const prefetch = predicatableQuery(db, table, provider.getPredicate(), StatementType.Select, column) return Observable.fromPromise(prefetch.exec()) .concatMap((scopedIds) => { const query = predicatableQuery(db, table, provider.getPredicate(), StatementType.Delete) scopedIds.forEach((entity: any) => this.storedIds.delete(fieldIdentifier(tableName, entity[pk!]))) return this.executor(db, [query]).do({ error: () => { scopedIds.forEach((entity: any) => this.storedIds.add(fieldIdentifier(tableName, entity[pk!]))) }}) }) }) } upsert<T>(tableName: string, raw: T): Observable<ExecutorResult> upsert<T>(tableName: string, raw: T[]): Observable<ExecutorResult> upsert<T>(tableName: string, raw: T | T[]): Observable<ExecutorResult> upsert<T>(tableName: string, raw: T | T[]): Observable<ExecutorResult> { return this.database$.concatMap(db => { const sharing = new Map<any, Mutation>() const insert: Mutation[] = [] const update: Mutation[] = [] this.traverseCompound(db, tableName, clone(raw), insert, update, sharing) const { contextIds, queries } = Mutation.aggregate(db, insert, update) if (queries.length > 0) { contextIds.forEach(id => this.storedIds.add(id)) return this.executor(db, queries) .do({ error: () => contextIds.forEach(id => this.storedIds.delete(id)) }) } else { return Observable.of({ result: false, insert: 0, update: 0, delete: 0, select: 0 }) } }) } remove<T>(tableName: string, clause: Clause<T> = {}): Observable<ExecutorResult> { const [schema, err] = tryCatch<ParsedSchema>(this.findSchema)(tableName) if (err) { return Observable.throw(err) } const disposeHandler = schema!.dispose return this.database$.concatMap((db) => { const [ table ] = Database.getTables(db, tableName) const predicate = createPredicate(table, clause.where) const queries: lf.query.Builder[] = [] const removedIds: any = [] queries.push(predicatableQuery(db, table, predicate!, StatementType.Delete)) const prefetch = predicatableQuery(db, table, predicate!, StatementType.Select) return Observable.fromPromise(prefetch.exec()) .concatMap((rootEntities) => { rootEntities.forEach(entity => { removedIds.push(fieldIdentifier(tableName, entity[schema!.pk])) }) if (disposeHandler) { const scope = this.createScopedHandler<T>(db, queries, removedIds) return disposeHandler(rootEntities, scope) .do(() => removedIds.forEach((id: string) => this.storedIds.delete(id))) .concatMap(() => this.executor(db, queries)) } else { removedIds.forEach((id: string) => this.storedIds.delete(id)) return this.executor(db, queries) } }) .do({ error: () => removedIds.forEach((id: string) => this.storedIds.add(id)) }) }) } dispose(): ErrorObservable | Observable<{ insert: number update: number delete: number result: boolean }> { if (!this.connected) { return Observable.throw(Exception.NotConnected()) } const cleanup = this.database$.map(db => db.getSchema().tables().map(t => db.delete().from(t))) return this.database$.concatMap(db => { return cleanup.concatMap(queries => this.executor(db, queries)) .do(() => { db.close() this.schemas.clear() this.storedIds.clear() this.schemaBuilder = null this.subscription.unsubscribe() }) }) } private buildTables() { this.schemaDefs.forEach((schemaDef, tableName) => { const tableBuilder = this.schemaBuilder!.createTable(tableName) this.parseSchemaDef(tableName, schemaDef, tableBuilder) }) } /** * 解析 schemaDefs, 根据解析后的 metadata 建表 */ private parseSchemaDef( tableName: string, schemaDef: SchemaDef<any>, tableBuilder: lf.schema.TableBuilder ) { const uniques: string[] = [] const indexes: string[] = [] const primaryKey: string[] = [] const nullable: string[] = [] const columns = new Map<string, RDBType>() const associations = new Map<string, Association>() const mapper = new Map<string, Function>() const disposeHandler = (typeof schemaDef.dispose === 'function' && schemaDef.dispose) || (typeof schemaDef[dispose] === 'function' && schemaDef[dispose]) || null // src: schemaDef; dest: uniques, indexes, primaryKey, nullable, associations, mapper // no short-curcuiting forEach(schemaDef, (def, key) => { if (typeof def === 'function') { return } if (!def.virtual) { this.createColumn(tableBuilder, key, def.type as RDBType, nullable, mapper) columns.set(key, def.type) if (def.primaryKey) { assert(!primaryKey[0], Exception.PrimaryKeyConflict()) primaryKey.push(key) } if (def.unique) { uniques.push(key) } if (def.index) { indexes.push(key) } const isNullable = ![def.primaryKey, def.index, def.unique].some(identity) if (isNullable) { nullable.push(key) } } else { associations.set(key, { where: def.virtual.where, type: def.type as Relationship, name: def.virtual.name }) } }) this.schemas.set(tableName, { pk: primaryKey[0], mapper, columns, dispose: disposeHandler, associations }) if (indexes.length) { tableBuilder.addIndex('index', indexes) } if (uniques.length) { tableBuilder.addUnique('unique', uniques) } if (nullable.length) { tableBuilder.addNullable(nullable) } tableBuilder.addPrimaryKey(primaryKey) } private buildSelector<T>( tableName: string, clause: Query<T>, mode: JoinMode ) { return this.database$.map((db) => { const schema = this.findSchema(tableName) const pk = schema.pk const containFields = !!clause.fields const containKey = containFields ? contains(pk, clause.fields!) : true const fields: Set<Fields> = containFields ? new Set(clause.fields) : new Set(schema.columns.keys()) const { table, columns, joinInfo, definition } = this.traverseQueryFields(db, tableName, fields, containKey, !containFields, [], {}, mode) const query = predicatableQuery(db, table!, null, StatementType.Select, ...columns) joinInfo.forEach((info: JoinInfo) => query.leftOuterJoin(info.table, info.predicate)) const orderDesc = (clause.orderBy || []).map(desc => { return { column: table![desc.fieldName], orderBy: !desc.orderBy ? null : lf.Order[desc.orderBy] } }) const matcher = { pk: { name: pk, queried: containKey }, definition, mainTable: table! } const { limit, skip } = clause const provider = new PredicateProvider(table!, clause.where!) return new Selector<T>(db, query, matcher, provider, limit, skip, orderDesc) }) } private createColumn( tableBuilder: lf.schema.TableBuilder, columnName: string, rdbType: RDBType, nullable: string[], mapper: Map<string, Function> ): lf.schema.TableBuilder { const hiddenName = hiddenColName(columnName) switch (rdbType) { case RDBType.ARRAY_BUFFER: return tableBuilder.addColumn(columnName, lf.Type.ARRAY_BUFFER) case RDBType.BOOLEAN: return tableBuilder.addColumn(columnName, lf.Type.BOOLEAN) case RDBType.DATE_TIME: nullable.push(hiddenName) mapper.set(columnName, (val: string) => val ? new Date(val).valueOf() : new Date(0).valueOf()) return tableBuilder .addColumn(columnName, lf.Type.INTEGER) .addColumn(hiddenName, lf.Type.STRING) case RDBType.INTEGER: return tableBuilder.addColumn(columnName, lf.Type.INTEGER) case RDBType.LITERAL_ARRAY: nullable.push(hiddenName) mapper.set(columnName, (val: any[]) => val ? val.join('|') : '') return tableBuilder .addColumn(columnName, lf.Type.STRING) .addColumn(hiddenName, lf.Type.OBJECT) case RDBType.NUMBER: return tableBuilder.addColumn(columnName, lf.Type.NUMBER) case RDBType.OBJECT: return tableBuilder.addColumn(columnName, lf.Type.OBJECT) case RDBType.STRING: return tableBuilder.addColumn(columnName, lf.Type.STRING) default: throw Exception.InvalidType() } } // context 用来标记DFS路径中的所有出现过的表,用于解决self-join时的二义性 // path 用来标记每个查询路径上出现的表,用于解决circular reference private traverseQueryFields( db: lf.Database, tableName: string, fieldsValue: Set<Fields>, hasKey: boolean, glob: boolean, path: string[] = [], context: Record = {}, mode: JoinMode ) { const schema = this.findSchema(tableName) const rootDefinition = Object.create(null) const navigators: string[] = [] const columns: lf.schema.Column[] = [] const joinInfo: JoinInfo[] = [] if (mode === JoinMode.imlicit && contains(tableName, path)) { // thinking mode: implicit & explicit return { columns, joinInfo, advanced: false, table: null, definition: null } } else { path.push(tableName) } schema.associations.forEach((_, nav) => { if (glob && !contains(nav, path)) { fieldsValue.add(nav) } navigators.push(nav) }) const onlyNavigator = Array.from(fieldsValue.keys()) .every(key => contains(key, navigators)) assert(!onlyNavigator, Exception.InvalidQuery()) if (!hasKey) { fieldsValue.add(schema.pk) } const suffix = (context[tableName] || 0) + 1 context[tableName] = suffix const contextName = contextTableName(tableName, suffix) const currentTable = Database.getTables(db, tableName)[0].as(contextName) const handleAdvanced = (ret: any, key: string, defs: Association | ColumnDef) => { if (!ret.advanced) { return } columns.push(...ret.columns) assert(!rootDefinition[key], Exception.AliasConflict(key, tableName)) if ((defs as ColumnDef).column) { rootDefinition[key] = defs } else { const { where, type } = defs as Association rootDefinition[key] = definition.revise(type!, ret.definition) const [ predicate, err ] = tryCatch(createPredicate)(currentTable, where(ret.table)) if (err) { warn( `Failed to build predicate, since ${err.message}` + `, on table: ${ret.table.getName()}` ) } const joinLink = predicate ? [{ table: ret.table, predicate }, ...ret.joinInfo] : ret.joinInfo joinInfo.push(...joinLink) } } const traversable = new Traversable<SelectContext>(fieldsValue) traversable.context((field, val, ctx) => { if (!ctx || ctx.isRoot || typeof field !== 'string') { return false } const isNavigatorLeaf = contains(field, navigators) const type = isNavigatorLeaf ? LeafType.navigator : LeafType.column const key = ctx.key ? ctx.key : val if (isNavigatorLeaf) { const description = schema.associations.get(ctx.key) if (!description) { warn(`Build a relationship failed, field: ${ctx.key}.`) return false } return { type, key, leaf: this.navigatorLeaf(description, ctx.key, val) } } if (!currentTable[field]) { warn(`Column: ${field} is not exist on ${tableName}`) return false } return { type, key, leaf: this.columnLeaf(currentTable, contextName, field) } }) traversable.forEach((ctx) => { switch (ctx.type) { case LeafType.column: const { column, identifier } = ctx.leaf as ColumnLeaf const type = schema.columns.get(ctx.key)! const columnDef = definition.create(identifier, schema.pk === ctx.key, type) handleAdvanced({ columns: [column], advanced: true }, ctx.key, columnDef) break case LeafType.navigator: const { containKey, fields, assocaiation } = ctx.leaf as NavigatorLeaf const ret = this.traverseQueryFields(db, assocaiation.name, new Set(fields), containKey, glob, path.slice(0), context, mode) handleAdvanced(ret, ctx.key, assocaiation) ctx.skip() break } }) return { columns, joinInfo, advanced: true, table: currentTable, definition: rootDefinition } } private traverseCompound( db: lf.Database, tableName: string, compoundEntites: any, insertMutList: Mutation[], updateMutList: Mutation[], sharing: Map<string, Mutation> ) { if (compoundEntites == null) { return } if (Array.isArray(compoundEntites)) { compoundEntites.forEach((item) => this.traverseCompound(db, tableName, item, insertMutList, updateMutList, sharing)) return } const schema = this.findSchema(tableName) const pk = schema.pk const pkVal = compoundEntites[pk] assert(pkVal !== undefined, Exception.PrimaryKeyNotProvided()) const [ table ] = Database.getTables(db, tableName) const identifier = fieldIdentifier(tableName, pkVal) const visited = contains(identifier, sharing) const stored = contains(identifier, this.storedIds) const mut = visited ? sharing.get(identifier)! : new Mutation(db, table) if (!visited) { const list = stored ? updateMutList : insertMutList list.push(mut) sharing.set(identifier, mut) } const traversable = new Traversable<UpsertContext>(compoundEntites) traversable.context((key, _, ctx) => { const isNavigator = schema.associations.has(key) const isColumn = schema.columns.has(key) const mapper = (isColumn && schema.mapper.get(key)) || null if (!(isColumn || isNavigator || ctx!.isRoot)) { // 若当前节点非 有效节点、叶子节点或者根节点中任意一种时,直接停止子节点的迭代 ctx!.skip() } return (ctx!.isRoot || (!isColumn && !isNavigator)) ? false : { mapper, visited, isNavigatorLeaf: isNavigator } }) traversable.forEach((ctx, node) => { // 考虑到叶节点可能存在`Object` type, 所以无论分支节点还是叶节点,其后的结构都不迭代 ctx.skip() if (ctx.isNavigatorLeaf) { const ref = schema.associations.get(ctx.key)!.name return this.traverseCompound(db, ref, node, insertMutList, updateMutList, sharing) } if (ctx.key !== pk) { // 如果字段不为主键 const res = ctx.mapper ? { [ctx.key]: ctx.mapper(node), [hiddenColName(ctx.key)]: node } : { [ctx.key]: node } mut.patch(res) } else if (ctx.key === pk && !ctx.visited) { // 如果该字段为该表主键, 且该节点是第一次在过程中访问 // i.e. sharing.has(identifier) is equl to false mut.withId(ctx.key, node) } }) } private columnLeaf(table: lf.schema.Table, tableName: string, key: string) { const column = table[key] const hiddenName = hiddenColName(key) const identifier = fieldIdentifier(tableName, key) const hiddenCol = table[hiddenName] const ret = hiddenCol ? hiddenCol.as(identifier) : column.as(identifier) return { identifier, column: ret } } private navigatorLeaf(assocaiation: Association, _: string, val: any) { const schema = this.findSchema(assocaiation.name) const fields = typeof val === 'string' ? new Set(schema.columns.keys()) : val return { fields, assocaiation, containKey: contains(schema.pk, val) } } private createScopedHandler<T>(db: lf.Database, queryCollection: any[], keys: any[]) { return (tableName: string): ScopedHandler => { const pk = this.findPrimaryKey(tableName) const remove = (entities: T[]) => { const [ table ] = Database.getTables(db, tableName) entities.forEach(entity => { const pkVal = entity[pk] const clause = createPkClause(pk, pkVal) const predicate = createPredicate(table, clause) const query = predicatableQuery(db, table, predicate!, StatementType.Delete) queryCollection.push(query) keys.push(fieldIdentifier(tableName, pkVal)) }) } const get = (where: Predicate<any> | null = null) => { const [ table ] = Database.getTables(db, tableName) const [ predicate, err ] = tryCatch(createPredicate)(table, where) if (err) { return Observable.throw(err) } const query = predicatableQuery(db, table, predicate!, StatementType.Select) return Observable.fromPromise<T[]>(query.exec() as any) } return [get, remove] } } private executor(db: lf.Database, queries: lf.query.Builder[]) { const tx = db.createTransaction() const handler = { error: () => warn(`Execute failed, transaction is already marked for rollback.`) } return Observable.fromPromise(tx.exec(queries)) .do(handler) .map((ret) => { return { result: true, ...mergeTransactionResult(queries, ret) } }) } }
the_stack
import {ChildProcess, spawnSync} from 'child_process'; import * as fs from 'fs'; import * as glob from 'glob'; import * as ini from 'ini'; import * as path from 'path'; import * as q from 'q'; import {Logger} from '../cli'; import {Config} from '../config'; import {spawn} from '../utils'; const noop = () => {}; // Make a function which configures a child process to automatically respond // to a certain question function respondFactory(question: string, answer: string, verbose: boolean): Function { return (child: ChildProcess) => { (<any>child.stdin).setDefaultEncoding('utf-8'); child.stdout.on('data', (data: Buffer|String) => { if (data != null) { if (verbose) { process.stdout.write(data as string); } if (data.toString().indexOf(question) != -1) { child.stdin.write(answer + '\n'); } } }); }; } // Run a command on the android SDK function runAndroidSDKCommand( sdkPath: string, cmd: string, args: string[], stdio?: string, config_fun?: Function): q.Promise<any> { let child = spawn(path.resolve(sdkPath, 'tools', 'android'), [cmd].concat(args), stdio); if (config_fun) { config_fun(child); }; let deferred = q.defer() child.on('exit', (code: number) => { if (deferred != null) { if (code) { deferred.reject(code); } else { deferred.resolve(); } deferred = null; } }); child.on('error', (err: Error) => { if (deferred != null) { deferred.reject(err); deferred = null; } }); return deferred.promise; } // Download updates via the android SDK function downloadAndroidUpdates( sdkPath: string, targets: string[], search_all: boolean, auto_accept: boolean, verbose: boolean): q.Promise<any> { return runAndroidSDKCommand( sdkPath, 'update', ['sdk', '-u'].concat(search_all ? ['-a'] : []).concat(['-t', targets.join(',')]), auto_accept ? 'pipe' : 'inherit', auto_accept ? respondFactory('Do you accept the license', 'y', verbose) : noop); } // Setup hardware acceleration for x86-64 emulation function setupHardwareAcceleration(sdkPath: string) { // TODO(sjelin): linux setup let toolDir = path.resolve(sdkPath, 'extras', 'intel', 'Hardware_Accelerated_Execution_Manager'); if (Config.osType() == 'Darwin') { console.log('Enabling hardware acceleration (requires root access)'); // We don't need the wrapped spawnSync because we know we're on OSX spawnSync('sudo', ['silent_install.sh'], {stdio: 'inherit', cwd: toolDir}); } else if (Config.osType() == 'Windows_NT') { console.log('Enabling hardware acceleration (requires admin access)'); // We don't need the wrapped spawnSync because we know we're on windows spawnSync('silent_install.bat', [], {stdio: 'inherit', cwd: toolDir}); } } // Get a list of all the SDK download targets for a given set of APIs, // architectures, and platforms function getAndroidSDKTargets( apiLevels: string[], architectures: string[], platforms: string[], oldAVDs: string[]): string[] { function getSysImgTarget(architecture: string, platform: string, level: string) { if (platform.toUpperCase() == 'DEFAULT') { platform = 'android'; } return 'sys-img-' + architecture + '-' + platform + '-' + level; } let targets = apiLevels .map((level) => { return 'android-' + level; }) .concat(architectures.reduce((targets, architecture) => { return targets.concat.apply(targets, platforms.map((platform) => { return apiLevels.map(getSysImgTarget.bind(null, architecture, platform)); })); }, [])); oldAVDs.forEach((name) => { let avd = new AVDDescriptor(name); if (targets.indexOf(avd.api) == -1) { targets.push(avd.api); } let sysImgTarget = getSysImgTarget(avd.architecture, avd.platform, avd.api.slice('android-'.length)); if (targets.indexOf(sysImgTarget) == -1) { targets.push(sysImgTarget); } }); return targets; } // All the information about an android virtual device class AVDDescriptor { api: string; platform: string; architecture: string; abi: string; name: string; constructor(api: string, platform?: string, architecture?: string) { if (platform != undefined) { this.api = api; this.platform = platform; this.architecture = architecture; this.name = [api, platform, architecture].join('-'); } else { this.name = api; let nameParts = this.name.split('-'); this.api = nameParts[0] + '-' + nameParts[1]; if (/v[0-9]+[a-z]+/.test(nameParts[nameParts.length - 1]) && (nameParts[nameParts.length - 2].slice(0, 3) == 'arm')) { this.architecture = nameParts[nameParts.length - 2] + '-' + nameParts[nameParts.length - 1]; } else { this.architecture = nameParts[nameParts.length - 1]; } this.platform = this.name.slice(this.api.length + 1, -this.architecture.length - 1); } this.abi = (this.platform.toUpperCase() == 'DEFAULT' ? '' : this.platform + '/') + this.architecture; } avdName(version: string): string { return this.name + '-v' + version + '-wd-manager'; } } // Gets the descriptors for all AVDs which are possible to make given the // SDKs which were downloaded function getAVDDescriptors(sdkPath: string): q.Promise<AVDDescriptor[]> { let deferred = q.defer<AVDDescriptor[]>(); // `glob` package always prefers patterns to use `/` glob('system-images/*/*/*', {cwd: sdkPath}, (err: Error, files: string[]) => { if (err) { deferred.reject(err); } else { deferred.resolve(files.map((file: string) => { // `file` could use `/` or `\`, so we use `path.normalize` let info = path.normalize(file).split(path.sep).slice(-3); return new AVDDescriptor(info[0], info[1], info[2]); })); } }); return deferred.promise; } function sequentialForEach<T>(array: T[], func: (x: T) => q.Promise<any>): q.Promise<any> { let ret = q(null); array.forEach((x: T) => { ret = ret.then(() => { return func(x); }); }); return ret; } // Configures the hardware.ini file for a system image of a new AVD function configureAVDHardware(sdkPath: string, desc: AVDDescriptor): q.Promise<any> { let file = path.resolve( sdkPath, 'system-images', desc.api, desc.platform, desc.architecture, 'hardware.ini'); return q.nfcall(fs.stat, file) .then( (stats: fs.Stats) => { return q.nfcall(fs.readFile, file); }, (err: Error) => { return q(''); }) .then((contents: string|Buffer) => { let config: any = ini.parse(contents.toString()); config['hw.keyboard'] = 'yes'; config['hw.battery'] = 'yes'; config['hw.ramSize'] = 1024; return q.nfcall(fs.writeFile, file, ini.stringify(config)); }); } // Make an android virtual device function makeAVD( sdkPath: string, desc: AVDDescriptor, version: string, verbose: boolean): q.Promise<any> { return runAndroidSDKCommand(sdkPath, 'delete', ['avd', '--name', desc.avdName(version)]) .then(noop, noop) .then(() => { return runAndroidSDKCommand( sdkPath, 'create', ['avd', '--name', desc.avdName(version), '--target', desc.api, '--abi', desc.abi], 'pipe', respondFactory('Do you wish to create a custom hardware profile', 'no', verbose)); }); } // Initialize the android SDK export function android( sdkPath: string, apiLevels: string[], architectures: string[], platforms: string[], acceptLicenses: boolean, version: string, oldAVDs: string[], logger: Logger, verbose: boolean): void { let avdDescriptors: AVDDescriptor[]; let tools = ['platform-tool', 'tool']; if ((Config.osType() == 'Darwin') || (Config.osType() == 'Windows_NT')) { tools.push('extra-intel-Hardware_Accelerated_Execution_Manager'); } logger.info('android-sdk: Downloading additional SDK updates'); downloadAndroidUpdates(sdkPath, tools, false, acceptLicenses, verbose) .then(() => { return setupHardwareAcceleration(sdkPath); }) .then(() => { logger.info( 'android-sdk: Downloading more additional SDK updates ' + '(this may take a while)'); return downloadAndroidUpdates( sdkPath, ['build-tools-24.0.0'].concat( getAndroidSDKTargets(apiLevels, architectures, platforms, oldAVDs)), true, acceptLicenses, verbose); }) .then(() => { return getAVDDescriptors(sdkPath); }) .then((descriptors: AVDDescriptor[]) => { avdDescriptors = descriptors; logger.info('android-sdk: Configuring virtual device hardware'); return sequentialForEach(avdDescriptors, (descriptor: AVDDescriptor) => { return configureAVDHardware(sdkPath, descriptor); }); }) .then(() => { return sequentialForEach(avdDescriptors, (descriptor: AVDDescriptor) => { logger.info('android-sdk: Setting up virtual device "' + descriptor.name + '"'); return makeAVD(sdkPath, descriptor, version, verbose); }); }) .then(() => { return q.nfcall( fs.writeFile, path.resolve(sdkPath, 'available_avds.json'), JSON.stringify(avdDescriptors.map((descriptor: AVDDescriptor) => { return descriptor.name; }))); }) .then(() => { logger.info('android-sdk: Initialization complete'); }) .done(); }; export function iOS(logger: Logger) { if (Config.osType() != 'Darwin') { throw new Error('Must be on a Mac to simulate iOS devices.'); } try { fs.statSync('/Applications/Xcode.app'); } catch (e) { logger.warn('You must install the xcode commandline tools!'); } }
the_stack
const Benchmark: any = require('benchmark'); import { execSync } from "child_process"; import { Vector } from "../src/Vector"; import { HashSet } from "../src/HashSet"; import { HashMap } from "../src/HashMap"; import { LinkedList } from "../src/LinkedList"; // import immutables through require for now so that // the immutables typescript type definitions are not // parsed: as of typescript 2.9rc and immutables 4.0.0rc9 // they don't compile. const imm: any = require('immutable'); // import * as imm from 'immutable'; const hamt: any = require("hamt_plus"); const hamtBase: any = require("hamt"); import * as Funkia from "list"; const lengths = [200, 10000]; function getPrerequisites(length:number): Prerequisites { // https://stackoverflow.com/a/43044960/516188 const getArray = (length:number) => Array.from({length}, () => Math.floor(Math.random() * length)); const array = getArray(length); const vec = Vector.ofIterable(array); const rawhamt = hamt.empty.mutate( (h:any) => { const iterator = array[Symbol.iterator](); let curItem = iterator.next(); while (!curItem.done) { h.set(h.size, curItem.value); curItem = iterator.next(); } }); let rawhamtBase = hamtBase.empty; const iterator = array[Symbol.iterator](); let curItem = iterator.next(); while (!curItem.done) { rawhamtBase = rawhamtBase.set(rawhamtBase.size, curItem.value); curItem = iterator.next(); } const list = LinkedList.ofIterable(array); const immList = imm.List(array); const funkiaList = Funkia.from(array); const idxThreeQuarters = array.length*3/4; const atThreeQuarters = array[idxThreeQuarters]; const hashset = HashSet.ofIterable(array); const immSet = imm.Set(array); const hashmap = HashMap.ofIterable<string,number>(array.map<[string,number]>(x => [x+"",x])); const immMap = imm.Map(array.map<[string,number]>(x => [x+"",x])); return {vec,immList,array,list,idxThreeQuarters, rawhamt,rawhamtBase,hashset,immSet,length,hashmap,immMap, funkiaList}; } interface Prerequisites { vec: Vector<number>; // immList: imm.List<number>; immList: any; array: number[]; list:LinkedList<number>; idxThreeQuarters: number; rawhamt: any; rawhamtBase: any; hashset: HashSet<number>; // immSet: imm.Set<number>; immSet: any; hashmap: HashMap<string,number>; // immMap: imm.Map<string,number>; immMap: any; length:number; funkiaList: Funkia.List<number>; } const preReqs = lengths.map(getPrerequisites); function _compare(preReqs: Prerequisites, items: Array<[string, (x:Prerequisites)=>any]>) { const benchSuite: any = new Benchmark.Suite; for (const item of items) { benchSuite.add(item[0], () => item[1](preReqs)); } benchSuite.on('cycle', function(event:any) { console.log(String(event.target)); }).on('complete', function(this:any) { console.log('Fastest is ' + this.filter('fastest').map('name') + "\n"); }).run(); } function compare(...items: Array<[string, (x:Prerequisites)=>any]>) { for (let i=0;i<lengths.length;i++) { let length = lengths[i]; console.log("n = " + length); _compare(preReqs[i], items); } } console.log("immList, immSet are the immutablejs list,set... https://facebook.github.io/immutable-js/"); console.log("funkiaList is the list from https://github.com/funkia/list"); process.stdout.write("node version: "); execSync("node --version", {stdio:[0,1,2]}); console.log(); compare(['Vector.toArray', (p:Prerequisites) => p.vec.toArray()], ['LinkedList.toArray', (p:Prerequisites) => p.list.toArray()], ['immList.toArray', (p:Prerequisites) => p.immList.toArray()], ['funkiaList.toArray', (p:Prerequisites) => Funkia.toArray(p.funkiaList)]); compare(['Vector.take', (p:Prerequisites) => p.vec.take(p.idxThreeQuarters)], ['Array.slice', (p:Prerequisites) => p.array.slice(0,p.idxThreeQuarters)], ['immList.take', (p:Prerequisites) => p.immList.take(p.idxThreeQuarters)], ['LinkedList.take', (p:Prerequisites) => p.list.take(p.idxThreeQuarters)], ['funkiaList.take', (p:Prerequisites) => Funkia.take(p.idxThreeQuarters, p.funkiaList)]); compare(['Vector.drop', (p:Prerequisites) => p.vec.drop(p.idxThreeQuarters)], ['Array.slice', (p:Prerequisites) => p.array.slice(p.idxThreeQuarters)], ['immList.slice', (p:Prerequisites) => p.immList.slice(p.idxThreeQuarters)], ['LinkedList.drop', (p:Prerequisites) => p.list.drop(p.idxThreeQuarters)], ['funkiaList.drop', (p:Prerequisites) => Funkia.drop(p.idxThreeQuarters, p.funkiaList)]); compare(['Vector.filter', (p:Prerequisites) => p.vec.filter(x => x%2===0)], ['Array.filter', (p:Prerequisites) => p.array.filter(x => x%2===0)], ['immList.filter', (p:Prerequisites) => p.immList.filter((x:number) => x%2===0)], ['LinkedList.filter', (p:Prerequisites) => p.list.filter(x => x%2===0)], ['funkiaList.filter', (p:Prerequisites) => Funkia.filter(x => x%2===0, p.funkiaList)]); compare(['Vector.map', (p:Prerequisites) => p.vec.map(x => x*2)], ['Array.map', (p:Prerequisites) => p.array.map(x => x*2)], ['immList.map', (p:Prerequisites) => p.immList.map((x:number) => x*2)], ['LinkedList.map', (p:Prerequisites) => p.list.map(x => x*2)], ['funkiaList.map', (p:Prerequisites) => Funkia.map(x => x*2, p.funkiaList)]); compare(['Vector.find', (p:Prerequisites) => p.vec.find(x => x===p.idxThreeQuarters)], ['Array.find', (p:Prerequisites) => p.array.find(x => x===p.idxThreeQuarters)], ['immList.find', (p:Prerequisites) => p.immList.find((x:number) => x===p.idxThreeQuarters)], ['LinkedList.find', (p:Prerequisites) => p.list.find(x => x===p.idxThreeQuarters)], ['funkiaList.find', (p:Prerequisites) => Funkia.find(x => x===p.idxThreeQuarters, p.funkiaList)]); compare(['Vector.ofIterable', (p:Prerequisites) => Vector.ofIterable(p.array)], ['rawhamt.build from iterable', (p:Prerequisites) => { hamt.empty.mutate( (h:any) => { const iterator = p.array[Symbol.iterator](); let curItem = iterator.next(); while (!curItem.done) { h.set(h.size, curItem.value); curItem = iterator.next(); } }) }], ['rawhamt.build from array', (p:Prerequisites) => { hamt.empty.mutate( (h:any) => { for (let i=0;i<p.array.length;i++) { h.set(i, p.array[i]); } }) }], ['rawhamtBase.build from iterable', (p:Prerequisites) => { let rawhamtBase = hamtBase.empty; const iterator = p.array[Symbol.iterator](); let curItem = iterator.next(); while (!curItem.done) { rawhamtBase = rawhamtBase.set(rawhamtBase.size, curItem.value); curItem = iterator.next(); } }], ['LinkedList.ofIterable', (p:Prerequisites) =>LinkedList.ofIterable(p.array)], ['immList.ofIterable', (p:Prerequisites) => imm.List(p.array)], ['funkiaList.ofArray', (p:Prerequisites) => Funkia.from(p.array)]); compare(['Vector.get(i)', (p:Prerequisites) => p.vec.get(p.length/2)], ['rawhamt.get(i)', (p:Prerequisites) => p.rawhamt.get(p.length/2)], ['rawhamtBase.get(i)', (p:Prerequisites) => p.rawhamtBase.get(p.length/2)], ['LinkedList.get(i)', (p:Prerequisites) => p.list.get(p.length/2)], ['Array.get(i)', (p:Prerequisites) => p.array[p.length/2]], ['immList.get(i)', (p:Prerequisites) => p.immList.get(p.length/2)], ['funkiaList.get(i)', (p:Prerequisites) => Funkia.nth(p.length/2, p.funkiaList)]); compare(['Vector.flatMap', (p:Prerequisites) => p.vec.flatMap(x => Vector.of(1,2))], ['LinkedList.flatMap', (p:Prerequisites) => p.list.flatMap(x =>LinkedList.of(1,2))], ['immList.flatMap', (p:Prerequisites) => p.immList.flatMap((x:number) => imm.List([1,2]))], ['funkiaList.chain', (p:Prerequisites) => Funkia.chain(x => Funkia.list(1,2), p.funkiaList)]); compare(['Vector.reverse', (p:Prerequisites) => p.vec.reverse()], ['Array.reverse', (p:Prerequisites) => p.array.reverse()], ['immList.reverse', (p:Prerequisites) => p.immList.reverse()], ['LinkedList.reverse', (p:Prerequisites) => p.list.reverse()], ['funkiaList.reverse', (p:Prerequisites) => Funkia.reverse(p.funkiaList)]); compare(['Vector.groupBy', (p:Prerequisites) => p.vec.groupBy(x => x%2)], ['LinkedList.groupBy', (p:Prerequisites) => p.list.groupBy(x => x%2)], ['immList.groupBy', (p:Prerequisites) => p.immList.groupBy((x:number) => x%2)]); compare( ['Vector.append', (p:Prerequisites) => { let v = Vector.empty<number>(); for (let item of p.array) { v = v.append(item); } }], ['Array.push', (p:Prerequisites) => { let v = []; for (let item of p.array) { v.push(item); } }], ['immList.push', (p:Prerequisites) => { // let v = imm.List<number>(); let v = imm.List(); for (let item of p.array) { v = v.push(item); } }], ['LinkedList.append', (p:Prerequisites) => { let v = LinkedList.empty<number>(); for (let item of p.array) { v = v.append(item); } }], ['Funkia.append', (p:Prerequisites) => { let v = Funkia.empty(); for (let item of p.array) { v = Funkia.append(item, v); } }]); compare( ['Vector.prepend', (p:Prerequisites) => { let v = Vector.empty<number>(); for (let item of p.array) { v = v.prepend(item); } }], ['Array.unshift', (p:Prerequisites) => { let v = []; for (let item of p.array) { v.unshift(item); } }], ['immList.unshift', (p:Prerequisites) => { // let v = imm.List<number>(); let v = imm.List(); for (let item of p.array) { v = v.unshift(item); } }], ['LinkedList.prepend', (p:Prerequisites) => { let v = LinkedList.empty<number>(); for (let item of p.array) { v = v.prepend(item); } }], ['Funkia.prepend', (p:Prerequisites) => { let v = Funkia.empty(); for (let item of p.array) { v = Funkia.prepend(item, v); } }]); function iterateOn<T>(coll: Iterable<T>) { const it = coll[Symbol.iterator](); let item = it.next(); while (!item.done) { item = it.next(); } } compare(['Vector.iterate', (p:Prerequisites) => iterateOn(p.vec)], ['Array.iterate', (p:Prerequisites) => iterateOn(p.array)], ['immList.iterate', (p:Prerequisites) => iterateOn(p.immList)], ['LinkedList.iterate', (p:Prerequisites) => iterateOn(p.list)], ['Funkia.iterate', (p:Prerequisites) => iterateOn(p.funkiaList)]); compare(['Vector.appendAll', (p:Prerequisites) => p.vec.appendAll(p.vec)], ['Array.appendAll', (p:Prerequisites) => p.array.concat(p.array)], ['immList.appendAll', (p:Prerequisites) => p.immList.concat(p.immList)], ['LinkedList.appendAll', (p:Prerequisites) => p.list.appendAll(p.list)], ['Funkia.concat', (p:Prerequisites) => Funkia.concat(p.funkiaList, p.funkiaList)]); compare(['Vector.prependAll', (p:Prerequisites) => p.vec.prependAll(p.vec)], ['Array.prependAll', (p:Prerequisites) => p.array.concat(p.array)], ['LinkedList.prependAll', (p:Prerequisites) => p.list.prependAll(p.list)]); compare(['Vector.foldLeft', (p:Prerequisites) => p.vec.foldLeft(0, (acc,i)=>acc+i)], ['Array.foldLeft', (p:Prerequisites) => p.array.reduce((acc,i)=>acc+i)], ['immList.foldLeft', (p:Prerequisites) => p.immList.reduce((acc:number,i:number)=>acc+i,0)], ['LinkedList.foldLeft', (p:Prerequisites) => p.vec.foldLeft(0, (acc,i)=>acc+i)], ['Funkia.foldl', (p:Prerequisites) => Funkia.foldl((i,acc)=>acc+i, 0, p.funkiaList)]); compare(['Vector.foldRight', (p:Prerequisites) => p.vec.foldRight(0, (i,acc)=>acc+i)], ['immList.foldRight', (p:Prerequisites) => p.immList.reduceRight((acc:number,i:number)=>acc+i,0)], ['LinkedList.foldRight', (p:Prerequisites) => p.vec.foldRight(0, (i,acc)=>acc+i)], ['Funkia.foldr', (p:Prerequisites) => Funkia.foldr((i,acc)=>acc+i, 0, p.funkiaList)]); compare(['HashSet.ofIterable', (p:Prerequisites) => HashSet.ofIterable(p.array)], ['immSet', (p:Prerequisites) => imm.Set(p.array)]); compare(['HashSet.ofIterable (from vector)', (p:Prerequisites) => HashSet.ofIterable(p.vec)], ['immSet (from vector)', (p:Prerequisites) => imm.Set(p.vec)]); compare(['HashSet.contains', (p:Prerequisites) => p.hashset.contains(p.array[Math.floor(Math.random()*p.array.length)])], ['immSet.contains', (p:Prerequisites) => p.immSet.contains(p.array[Math.floor(Math.random()*p.array.length)])]); compare(['HashSet.filter', (p:Prerequisites) => p.hashset.filter(x => x<p.length/2)], ['immSet.filter', (p:Prerequisites) => p.immSet.filter((x:number) => x<p.length/2)]); compare(['HashMap.ofIterable', (p:Prerequisites) => HashMap.ofIterable<string,number>(p.array.map<[string,number]>(x => [x+"",x]))], ['immMap', (p:Prerequisites) => imm.Map(p.array.map<[string,number]>(x => [x+"",x]))]); compare(['HashMap.ofIterable (from vector)', (p:Prerequisites) => HashMap.ofIterable(p.vec.map<[string,number]>(x => [x+"",x]))], ['immMap (from vector)', (p:Prerequisites) => imm.Map(p.vec.map<[string,number]>(x => [x+"",x]))]); compare(['HashMap.get', (p:Prerequisites) => p.hashmap.get(p.array[Math.floor(Math.random()*p.array.length)]+"")], ['immMap.get', (p:Prerequisites) => p.immMap.get(p.array[Math.floor(Math.random()*p.array.length)]+"")]); compare(['HashMap.filter', (p:Prerequisites) => p.hashmap.filter((k,v) => parseInt(k)<p.length/2)], ['immMap.filter', (p:Prerequisites) => p.immMap.filter((v:number,k:string) => parseInt(k)<p.length/2)]);
the_stack
import { any, anyArray, anyBoolean, anyNumber, anyObject, anyString, anyMap, anySet, isA, arrayIncludes, anyFunction, anySymbol, setHas, mapHas, objectContainsKey, objectContainsValue, notNull, notUndefined, notEmpty, captor, matches, } from './Matchers'; class Cls {} describe('Matchers', () => { describe('any', () => { test('returns true for false', () => { expect(any().asymmetricMatch(false)).toBe(true); }); test('returns true for undefined', () => { expect(any().asymmetricMatch(undefined)).toBe(true); }); test('returns true for null', () => { expect(any().asymmetricMatch(null)).toBe(true); }); test('Supports undefined in chain', () => { const f = jest.fn(); f(undefined); // @ts-ignore console.info(f.mock); expect(f).toHaveBeenCalledWith(any()); }); }); describe('anyString', () => { test('returns true for empty string', () => { expect(anyString().asymmetricMatch('')).toBe(true); }); test('returns true for non-empty string', () => { expect(anyString().asymmetricMatch('123')).toBe(true); }); test('returns false for number', () => { // @ts-ignore expect(anyString().asymmetricMatch(123)).toBe(false); }); test('returns false for null', () => { // @ts-ignore expect(anyString().asymmetricMatch(null)).toBe(false); }); test('returns false for undefined', () => { // @ts-ignore expect(anyString().asymmetricMatch(undefined)).toBe(false); }); }); describe('anyNumber', () => { test('returns true for 0', () => { expect(anyNumber().asymmetricMatch(0)).toBe(true); }); test('returns true for normal number', () => { expect(anyNumber().asymmetricMatch(123)).toBe(true); }); test('returns false for string', () => { // @ts-ignore expect(anyNumber().asymmetricMatch('123')).toBe(false); }); test('returns false for null', () => { // @ts-ignore expect(anyNumber().asymmetricMatch(null)).toBe(false); }); test('returns false for undefined', () => { // @ts-ignore expect(anyNumber().asymmetricMatch(undefined)).toBe(false); }); test('returns false for NaN', () => { expect(anyNumber().asymmetricMatch(NaN)).toBe(false); }); }); describe('anyBoolean', () => { test('returns true for true', () => { expect(anyBoolean().asymmetricMatch(true)).toBe(true); }); test('returns true for false', () => { expect(anyBoolean().asymmetricMatch(false)).toBe(true); }); test('returns false for string', () => { // @ts-ignore expect(anyBoolean().asymmetricMatch('true')).toBe(false); }); test('returns false for null', () => { // @ts-ignore expect(anyBoolean().asymmetricMatch(null)).toBe(false); }); test('returns false for undefined', () => { // @ts-ignore expect(anyBoolean().asymmetricMatch(undefined)).toBe(false); }); }); describe('anyFunction', () => { test('returns true for function', () => { expect(anyFunction().asymmetricMatch(() => {})).toBe(true); }); test('returns false for string', () => { // @ts-ignore expect(anyFunction().asymmetricMatch('true')).toBe(false); }); test('returns false for null', () => { // @ts-ignore expect(anyFunction().asymmetricMatch(null)).toBe(false); }); test('returns false for undefined', () => { // @ts-ignore expect(anyFunction().asymmetricMatch(undefined)).toBe(false); }); }); describe('anySymbol', () => { test('returns true for symbol', () => { expect(anySymbol().asymmetricMatch(Symbol('123'))).toBe(true); }); test('returns false for string', () => { // @ts-ignore expect(anySymbol().asymmetricMatch('123')).toBe(false); }); test('returns false for null', () => { // @ts-ignore expect(anySymbol().asymmetricMatch(null)).toBe(false); }); test('returns false for undefined', () => { // @ts-ignore expect(anySymbol().asymmetricMatch(undefined)).toBe(false); }); }); describe('anyObject', () => { test('returns true for object', () => { expect(anyObject().asymmetricMatch({})).toBe(true); }); test('returns true for new object', () => { expect(anyObject().asymmetricMatch(new Object())).toBe(true); }); test('returns true for new instance', () => { expect(anyObject().asymmetricMatch(new Cls())).toBe(true); }); test('returns true for new builtin', () => { expect(anyObject().asymmetricMatch(new Map())).toBe(true); }); test('returns false for string', () => { expect(anyObject().asymmetricMatch('123')).toBe(false); }); test('returns false for number', () => { expect(anyObject().asymmetricMatch(123)).toBe(false); }); test('returns false for null', () => { expect(anyObject().asymmetricMatch(null)).toBe(false); }); test('returns false for undefined', () => { expect(anyObject().asymmetricMatch(undefined)).toBe(false); }); }); describe('anyArray', () => { test('returns true for empty array', () => { expect(anyArray().asymmetricMatch([])).toBe(true); }); test('returns true for non empty', () => { expect(anyArray().asymmetricMatch([1, 2, 3])).toBe(true); }); test('returns false for object', () => { // @ts-ignore expect(anyArray().asymmetricMatch({})).toBe(false); }); test('returns false for null', () => { // @ts-ignored expect(anyArray().asymmetricMatch(null)).toBe(false); }); test('returns false for undefined', () => { // @ts-ignore expect(anyArray().asymmetricMatch(undefined)).toBe(false); }); }); describe('anyMap', () => { test('returns true for empty Map', () => { expect(anyMap().asymmetricMatch(new Map())).toBe(true); }); test('returns true for non empty', () => { const map = new Map(); map.set(1, 2); expect(anyMap().asymmetricMatch(map)).toBe(true); }); test('returns false for object', () => { // @ts-ignore expect(anyMap().asymmetricMatch({})).toBe(false); }); test('returns false for null', () => { // @ts-ignore expect(anyMap().asymmetricMatch(null)).toBe(false); }); test('returns false for undefined', () => { // @ts-ignore expect(anyMap().asymmetricMatch(undefined)).toBe(false); }); }); describe('anySet', () => { test('returns true for empty Set', () => { expect(anySet().asymmetricMatch(new Set())).toBe(true); }); test('returns true for non empty', () => { const set = new Set(); set.add(2); expect(anySet().asymmetricMatch(set)).toBe(true); }); test('returns false for object', () => { // @ts-ignore expect(anySet().asymmetricMatch({})).toBe(false); }); test('returns false for null', () => { // @ts-ignore expect(anySet().asymmetricMatch(null)).toBe(false); }); test('returns false for undefined', () => { // @ts-ignore expect(anySet().asymmetricMatch(undefined)).toBe(false); }); }); describe('isA', () => { test('returns true when class is the same builtin', () => { expect(isA(Map).asymmetricMatch(new Map())).toBe(true); }); test('returns true for non empty', () => { expect(isA(Cls).asymmetricMatch(new Cls())).toBe(true); }); test('returns false for object', () => { expect(isA(Cls).asymmetricMatch({})).toBe(false); }); test('returns false for null', () => { expect(isA(Cls).asymmetricMatch(null)).toBe(false); }); test('returns false for undefined', () => { expect(isA(Cls).asymmetricMatch(undefined)).toBe(false); }); }); describe('arrayIncludes', () => { test('returns true when array contains value', () => { expect(arrayIncludes('val').asymmetricMatch(['val', 'val2'])).toBe(true); }); test('returns false when array does not contain value', () => { expect(arrayIncludes('val3').asymmetricMatch(['val', 'val2'])).toBe(false); }); test('returns false when not a map', () => { // @ts-ignore expect(arrayIncludes('val3').asymmetricMatch({})).toBe(false); }); test('returns false when for null', () => { // @ts-ignore expect(arrayIncludes('val3').asymmetricMatch(null)).toBe(false); }); test('returns false when for undefined', () => { // @ts-ignore expect(arrayIncludes('val3').asymmetricMatch(undefined)).toBe(false); }); }); describe('mapHas', () => { test('returns true when map contains key', () => { expect(mapHas('key').asymmetricMatch(new Map([['key', 'val']]))).toBe(true); }); test('returns false when map does not contain key', () => { expect(mapHas('key3').asymmetricMatch(new Map([['key', 'val']]))).toBe(false); }); test('returns false when not a map', () => { // @ts-ignore expect(mapHas('val3').asymmetricMatch({})).toBe(false); }); test('returns false when for null', () => { // @ts-ignore expect(mapHas('val3').asymmetricMatch(null)).toBe(false); }); test('returns false when for undefined', () => { // @ts-ignore expect(mapHas('val3').asymmetricMatch(undefined)).toBe(false); }); }); describe('setHas', () => { test('returns true when set contains value', () => { expect(setHas('val').asymmetricMatch(new Set(['val']))).toBe(true); }); test('returns false when set does not contain value', () => { expect(setHas('val3').asymmetricMatch(new Set(['val', 'val2']))).toBe(false); }); test('returns false when not a set', () => { // @ts-ignore expect(setHas('val3').asymmetricMatch({})).toBe(false); }); test('returns false when for null', () => { // @ts-ignore expect(setHas('val3').asymmetricMatch(null)).toBe(false); }); test('returns false when for undefined', () => { // @ts-ignore expect(setHas('val3').asymmetricMatch(undefined)).toBe(false); }); }); describe('objectContainsKey', () => { test('returns true when object contains key', () => { expect(objectContainsKey('key').asymmetricMatch({ key: 'val' })).toBe(true); }); test('returns false when object does not contain key', () => { expect(objectContainsKey('key3').asymmetricMatch({ key: 'val' })).toBe(false); }); test('returns false when not a object', () => { expect(objectContainsKey('val3').asymmetricMatch(213)).toBe(false); }); test('returns false when for null', () => { expect(objectContainsKey('val3').asymmetricMatch(null)).toBe(false); }); test('returns false when for undefined', () => { expect(objectContainsKey('val3').asymmetricMatch(undefined)).toBe(false); }); }); describe('objectContainsValue', () => { test('returns true when object contains value', () => { expect(objectContainsValue('val').asymmetricMatch({ key: 'val' })).toBe(true); }); test('returns false when object does not contain value', () => { expect(objectContainsValue('val3').asymmetricMatch({ key: 'val' })).toBe(false); }); test('returns false when not a object', () => { expect(objectContainsValue('val3').asymmetricMatch(213)).toBe(false); }); test('returns false when for null', () => { expect(objectContainsValue('val3').asymmetricMatch(null)).toBe(false); }); test('returns false when for undefined', () => { expect(objectContainsValue('val3').asymmetricMatch(undefined)).toBe(false); }); }); describe('notNull', () => { test('returns true when object', () => { expect(notNull().asymmetricMatch({ key: 'val' })).toBe(true); }); test('returns true when undefined', () => { expect(notNull().asymmetricMatch(undefined)).toBe(true); }); test('returns true when empty string', () => { expect(notNull().asymmetricMatch('')).toBe(true); }); test('returns false when for null', () => { expect(notNull().asymmetricMatch(null)).toBe(false); }); }); describe('notUndefined', () => { test('returns true when object', () => { expect(notUndefined().asymmetricMatch({ key: 'val' })).toBe(true); }); test('returns true when null', () => { expect(notUndefined().asymmetricMatch(null)).toBe(true); }); test('returns true when empty string', () => { expect(notUndefined().asymmetricMatch('')).toBe(true); }); test('returns false when for undefined', () => { expect(notUndefined().asymmetricMatch(undefined)).toBe(false); }); }); describe('notEmpty', () => { test('returns true when object', () => { expect(notEmpty().asymmetricMatch({ key: 'val' })).toBe(true); }); test('returns true when null', () => { expect(notEmpty().asymmetricMatch(null)).toBe(false); }); test('returns true when empty string', () => { expect(notEmpty().asymmetricMatch('')).toBe(false); }); test('returns false when for undefined', () => { expect(notEmpty().asymmetricMatch(undefined)).toBe(false); }); }); describe('captor', () => { let fn: () => void; let doSomething: (...args: any[]) => void; beforeEach(() => { fn = jest.fn(); doSomething = (fn: (...args: any[]) => void, count: number) => { fn(String(count), count, { 1: 2 }); }; }); test('can capture arg with other matchers', () => { doSomething(fn, 1); const argCaptor = captor(); expect(fn).toHaveBeenCalledWith(argCaptor, any(), any()); expect(argCaptor.value).toBe('1'); }); test('stores all values', () => { doSomething(fn, 1); doSomething(fn, 2); doSomething(fn, 3); const argCaptor = captor(); expect(fn).toHaveBeenNthCalledWith(1, argCaptor, any(), any()); expect(fn).toHaveBeenNthCalledWith(2, argCaptor, any(), any()); expect(fn).toHaveBeenNthCalledWith(3, argCaptor, any(), any()); expect(argCaptor.value).toBe('3'); expect(argCaptor.values).toEqual(['1', '2', '3']); }); }); describe('matches function', () => { test('expects passes for when it returns true', () => { const fn = jest.fn(); fn(1); expect(fn).toHaveBeenCalledWith(matches((val) => val === 1)); }); test('expects with not passes for when it returns false', () => { const fn = jest.fn(); fn(1); expect(fn).not.toHaveBeenCalledWith(matches((val) => val === 2)); }); }); });
the_stack
import { GroupsHandlerService } from '../abstract/groups-handler.service'; import { Injectable } from '@angular/core'; import { BehaviorSubject, Observable, Subject } from 'rxjs'; // firebase // import * as firebase from 'firebase/app'; import firebase from "firebase/app"; import 'firebase/messaging'; import 'firebase/database'; import 'firebase/auth'; import 'firebase/storage'; // models import { ConversationModel } from '../../models/conversation'; // services //import { DatabaseProvider } from '../database'; // utils import { CustomLogger } from '../logger/customLogger'; import { AppConfigProvider } from '../../../app/services/app-config'; import { HttpClient, HttpHeaders } from '@angular/common/http'; import { GroupModel } from 'src/chat21-core/models/group'; import { avatarPlaceholder, getColorBck } from 'src/chat21-core/utils/utils-user'; import { LoggerService } from '../abstract/logger.service'; import { LoggerInstance } from '../logger/loggerInstance'; // @Injectable({ providedIn: 'root' }) @Injectable() export class FirebaseGroupsHandler extends GroupsHandlerService { // BehaviorSubject BSgroupDetail: BehaviorSubject<GroupModel>; SgroupDetail: Subject<GroupModel>; groupAdded: BehaviorSubject<GroupModel>; groupChanged: BehaviorSubject<GroupModel>; groupRemoved: BehaviorSubject<GroupModel>; // public params conversations: Array<ConversationModel> = []; uidConvSelected: string; // private params private tenant: string; private loggedUserId: string; private ref: firebase.database.Query; private BASE_URL = this.appConfig.getConfig().firebaseConfig.chat21ApiUrl; private logger:LoggerService = LoggerInstance.getInstance() // private audio: any; // private setTimeoutSound: any; constructor( public http: HttpClient, public appConfig: AppConfigProvider ) { super(); } /** * inizializzo groups handler */ initialize(tenant: string, loggedUserId: string) { this.tenant = tenant; this.loggedUserId = loggedUserId; this.BASE_URL = this.appConfig.getConfig().firebaseConfig.chat21ApiUrl; this.logger.debug('[FIREBASEGroupHandlerSERVICE] initialize', this.tenant, this.loggedUserId); } /** * mi connetto al nodo groups * creo la reference * mi sottoscrivo a change, removed, added */ connect() { //********* NOT IN USE ********** */ const that = this; const urlNodeGroups = '/apps/' + this.tenant + '/users/' + this.loggedUserId + '/groups'; this.logger.debug('[FIREBASEGroupHandlerSERVICE] connect -------> groups::', urlNodeGroups) this.ref = firebase.database().ref(urlNodeGroups) this.ref.on('child_added', (childSnapshot) => { that.logger.debug('[FIREBASEGroupHandlerSERVICE] child_added ------->', childSnapshot.val()) // that.added(childSnapshot); }); this.ref.on('child_changed', (childSnapshot) => { that.logger.debug('[FIREBASEGroupHandlerSERVICE] child_changed ------->', childSnapshot.val()) // that.changed(childSnapshot); }); this.ref.on('child_removed', (childSnapshot) => { that.logger.debug('[FIREBASEGroupHandlerSERVICE] child_removed ------->', childSnapshot.val()) // that.removed(childSnapshot); }); } /** * mi connetto al nodo groups/GROUPID * creo la reference * mi sottoscrivo a value */ getDetail(groupId: string, callback?: (group: GroupModel)=>void): Promise<GroupModel>{ const urlNodeGroupById = '/apps/' + this.tenant + '/users/' + this.loggedUserId + '/groups/' + groupId; this.logger.debug('[FIREBASEGroupHandlerSERVICE] getDetail -------> urlNodeGroupById::', urlNodeGroupById) const ref = firebase.database().ref(urlNodeGroupById) return new Promise((resolve) => { ref.off() ref.on('value', (childSnapshot) => { const group: GroupModel = childSnapshot.val(); group.uid = childSnapshot.key // that.BSgroupDetail.next(group) if (callback) { callback(group) } resolve(group) }); }); } onGroupChange(groupId: string): Observable<GroupModel> { const that = this; let SgroupDetail = new Subject<GroupModel>(); const urlNodeGroupById = '/apps/' + this.tenant + '/users/' + this.loggedUserId + '/groups/' + groupId; this.logger.log('[FIREBASEGroupHandlerSERVICE] onGroupChange -------> urlNodeGroupById::', urlNodeGroupById) const ref = firebase.database().ref(urlNodeGroupById) ref.off() ref.on('value', (childSnapshot) => { // this.groupValue(childSnapshot) if(childSnapshot.val() ) { const group: GroupModel = childSnapshot.val(); if (group) { group.uid = childSnapshot.key // that.BSgroupDetail.next(group) let groupCompleted = this.completeGroup(group) // this.SgroupDetail.next(groupCompleted) SgroupDetail.next(groupCompleted) } } }); // return this.SgroupDetail return SgroupDetail } // private groupValue(childSnapshot: any){ // const that = this; // let SgroupDetail = new Subject<GroupModel>(); // this.logger.debug('[FIREBASEGroupHandlerSERVICE] group detail::', childSnapshot.val(), childSnapshot) // const group: GroupModel = childSnapshot.val(); // this.logger.debug('[FIREBASEGroupHandlerSERVICE] groupValue ', group) // if (group) { // group.uid = childSnapshot.key // // that.BSgroupDetail.next(group) // let groupCompleted = this.completeGroup(group) // // this.SgroupDetail.next(groupCompleted) // SgroupDetail.next(groupCompleted) // } // } create(groupName: string, members: [string], callback?: (res: any, error: any) => void): Promise<any> { var that = this; let listMembers = {}; members.forEach(member => { listMembers[member] = 1 }); return new Promise((resolve, reject) =>{ this.getFirebaseToken((error, idToken) => { that.logger.debug('[FIREBASEGroupHandlerSERVICE] CREATE GROUP idToken', idToken, error) if (idToken) { const httpOptions = { headers: new HttpHeaders({ 'Accept': 'application/json', 'Content-Type': 'application/json', 'Authorization': 'Bearer ' + idToken, }) } const body = { "group_name": groupName, "group_members": listMembers } const url = that.BASE_URL + '/api/' + that.tenant + '/groups' that.http.post(url, body, httpOptions).toPromise().then((res) => { callback(res, null); resolve(res) }).catch(function (error) { // Handle error that.logger.error('[FIREBASEGroupHandlerSERVICE] createGROUP error: ', error); callback(null, error); reject(error); }); }else{ callback(null, error) reject(error) } }); }); } join(groupId: string, member: string, callback?: (res: any, error: any) => void) { var that = this; return new Promise((resolve, reject) =>{ this.getFirebaseToken((error, idToken) => { that.logger.debug('[FIREBASEGroupHandlerSERVICE] JOIN GROUP idToken', idToken, error) if (idToken) { const httpOptions = { headers: new HttpHeaders({ 'Accept': 'application/json', 'Content-Type': 'application/json', 'Authorization': 'Bearer ' + idToken, }) } const body = { "member_id": member } const url = that.BASE_URL + '/api/' + that.tenant + '/groups/' + groupId + '/members' that.http.post(url, body, httpOptions).toPromise().then((res) => { callback(res, null); resolve(res) }).catch(function (error) { // Handle error that.logger.error('[FIREBASEGroupHandlerSERVICE] createGROUP error: ', error); callback(null, error); reject(error); }); }else{ callback(null, error) reject(error) } }); }); } leave(groupId: string, callback?: (res: any, error: any) => void): Promise<any> { var that = this; return new Promise((resolve, reject) =>{ this.getFirebaseToken((error, idToken) => { that.logger.debug('[FIREBASEGroupHandlerSERVICE] LEAVE CONV idToken', idToken, error) if (idToken) { const httpOptions = { headers: new HttpHeaders({ 'Accept': 'application/json', 'Content-Type': 'application/json', 'Authorization': 'Bearer ' + idToken, }) } const url = that.BASE_URL + '/api/' + that.tenant + '/groups/' + groupId + '/members/' + that.loggedUserId that.http.delete(url, httpOptions).toPromise().then((res) => { callback(res, null); resolve(res) }).catch(function (error) { // Handle error that.logger.error('[FIREBASEGroupHandlerSERVICE] LEAVE idToken error: ', error); callback(null, error); reject(error); }); }else{ callback(null, error) reject(error) } }); }); } dispose() { this.conversations = []; this.uidConvSelected = ''; this.ref.off(); // this.ref.off("child_changed"); // this.ref.off("child_removed"); // this.ref.off("child_added"); this.logger.debug('[FIREBASEGroupHandlerSERVICE] DISPOSE', this.ref) } // // -------->>>> PRIVATE METHOD SECTION START <<<<---------------// private getFirebaseToken(callback) { const firebase_currentUser = firebase.auth().currentUser; this.logger.debug('[FIREBASEGroupHandlerSERVICE] // firebase current user ', firebase_currentUser); if (firebase_currentUser) { const that = this; firebase_currentUser.getIdToken(/* forceRefresh */ true) .then(function (idToken) { // qui richiama la callback callback(null, idToken); }).catch(function (error) { // Handle error that.logger.error('[FIREBASEGroupHandlerSERVICE] ERROR -> idToken.', error); callback(error, null); }); } } private completeGroup(group: any): GroupModel{ group.avatar = avatarPlaceholder(group.name); group.color = getColorBck(group.name); return group } // // -------->>>> PRIVATE METHOD SECTION SECTION END <<<<---------------// }
the_stack
import { BitwisePermissionFlags, BotWithCache, DiscordenoChannel, DiscordenoGuild, DiscordenoMember, DiscordenoRole, Errors, Overwrite, PermissionStrings, separateOverwrites, } from "../deps.ts"; /** Calculates the permissions this member has in the given guild */ export function calculateBasePermissions( bot: BotWithCache, guildOrId: bigint | DiscordenoGuild, memberOrId: bigint | DiscordenoMember, ) { const guild = typeof guildOrId === "bigint" ? bot.guilds.get(guildOrId) : guildOrId; const member = typeof memberOrId === "bigint" ? bot.members.get(memberOrId) : memberOrId; if (!guild || !member) return 8n; let permissions = 0n; // Calculate the role permissions bits, @everyone role is not in memberRoleIds so we need to pass guildId manualy permissions |= [...member.roles, guild.id] .map((id) => guild.roles.get(id)?.permissions) // Removes any edge case undefined .filter((perm) => perm) .reduce((bits, perms) => { bits! |= perms!; return bits; }, 0n) || 0n; // If the memberId is equal to the guild ownerId he automatically has every permission so we add ADMINISTRATOR permission if (guild.ownerId === member.id) permissions |= 8n; // Return the members permission bits as a string return permissions; } /** Calculates the permissions this member has for the given Channel */ export function calculateChannelOverwrites( bot: BotWithCache, channelOrId: bigint | DiscordenoChannel, memberOrId: bigint | DiscordenoMember, ) { const channel = typeof channelOrId === "bigint" ? bot.channels.get(channelOrId) : channelOrId; // This is a DM channel so return ADMINISTRATOR permission if (!channel?.guildId) return 8n; const member = typeof memberOrId === "bigint" ? bot.members.get(memberOrId) : memberOrId; if (!channel || !member) return 8n; // Get all the role permissions this member already has let permissions = calculateBasePermissions( bot, channel.guildId, member, ); // First calculate @everyone overwrites since these have the lowest priority const overwriteEveryone = channel.permissionOverwrites?.find((overwrite) => { const [_, id] = separateOverwrites(overwrite); return id === channel.guildId; }); if (overwriteEveryone) { const [_type, _id, allow, deny] = separateOverwrites(overwriteEveryone); // First remove denied permissions since denied < allowed permissions &= ~deny; permissions |= allow; } const overwrites = channel.permissionOverwrites; // In order to calculate the role permissions correctly we need to temporarily save the allowed and denied permissions let allow = 0n; let deny = 0n; const memberRoles = member.roles || []; // Second calculate members role overwrites since these have middle priority for (const overwrite of overwrites || []) { const [_type, id, allowBits, denyBits] = separateOverwrites(overwrite); if (!memberRoles.includes(id)) continue; deny |= denyBits; allow |= allowBits; } // After role overwrite calculate save allowed permissions first we remove denied permissions since "denied < allowed" permissions &= ~deny; permissions |= allow; // Third calculate member specific overwrites since these have the highest priority const overwriteMember = overwrites?.find((overwrite) => { const [_, id] = separateOverwrites(overwrite); return id === member.id; }); if (overwriteMember) { const [_type, _id, allowBits, denyBits] = separateOverwrites( overwriteMember, ); permissions &= ~denyBits; permissions |= allowBits; } return permissions; } /** Checks if the given permission bits are matching the given permissions. `ADMINISTRATOR` always returns `true` */ export function validatePermissions( permissionBits: bigint, permissions: PermissionStrings[], ) { if (permissionBits & 8n) return true; return permissions.every( (permission) => // Check if permission is in permissionBits permissionBits & BigInt(BitwisePermissionFlags[permission]), ); } /** Checks if the given member has these permissions in the given guild */ export function hasGuildPermissions( bot: BotWithCache, guild: bigint | DiscordenoGuild, member: bigint | DiscordenoMember, permissions: PermissionStrings[], ) { // First we need the role permission bits this member has const basePermissions = calculateBasePermissions( bot, guild, member, ); // Second use the validatePermissions function to check if the member has every permission return validatePermissions(basePermissions, permissions); } /** Checks if the bot has these permissions in the given guild */ export function botHasGuildPermissions( bot: BotWithCache, guild: bigint | DiscordenoGuild, permissions: PermissionStrings[], ) { // Since Bot is a normal member we can use the hasRolePermissions() function return hasGuildPermissions(bot, guild, bot.id, permissions); } /** Checks if the given member has these permissions for the given channel */ export function hasChannelPermissions( bot: BotWithCache, channel: bigint | DiscordenoChannel, member: bigint | DiscordenoMember, permissions: PermissionStrings[], ) { // First we need the overwrite bits this member has const channelOverwrites = calculateChannelOverwrites( bot, channel, member, ); // Second use the validatePermissions function to check if the member has every permission return validatePermissions(channelOverwrites, permissions); } /** Checks if the bot has these permissions f0r the given channel */ export function botHasChannelPermissions( bot: BotWithCache, channel: bigint | DiscordenoChannel, permissions: PermissionStrings[], ) { // Since Bot is a normal member we can use the hasRolePermissions() function return hasChannelPermissions(bot, channel, bot.id, permissions); } /** Returns the permissions that are not in the given permissionBits */ export function missingPermissions( permissionBits: bigint, permissions: PermissionStrings[], ) { if (permissionBits & 8n) return []; return permissions.filter((permission) => !(permissionBits & BigInt(BitwisePermissionFlags[permission]))); } /** Get the missing Guild permissions this member has */ export function getMissingGuildPermissions( bot: BotWithCache, guild: bigint | DiscordenoGuild, member: bigint | DiscordenoMember, permissions: PermissionStrings[], ) { // First we need the role permission bits this member has const permissionBits = calculateBasePermissions( bot, guild, member, ); // Second return the members missing permissions return missingPermissions(permissionBits, permissions); } /** Get the missing Channel permissions this member has */ export function getMissingChannelPermissions( bot: BotWithCache, channel: bigint | DiscordenoChannel, member: bigint | DiscordenoMember, permissions: PermissionStrings[], ) { // First we need the role permissino bits this member has const permissionBits = calculateChannelOverwrites( bot, channel, member, ); // Second returnn the members missing permissions return missingPermissions(permissionBits, permissions); } /** Throws an error if this member has not all of the given permissions */ export function requireGuildPermissions( bot: BotWithCache, guild: bigint | DiscordenoGuild, member: bigint | DiscordenoMember, permissions: PermissionStrings[], ) { const missing = getMissingGuildPermissions( bot, guild, member, permissions, ); if (missing.length) { // If the member is missing a permission throw an Error throw new Error(`Missing Permissions: ${missing.join(" & ")}`); } } /** Throws an error if the bot does not have all permissions */ export function requireBotGuildPermissions( bot: BotWithCache, guild: bigint | DiscordenoGuild, permissions: PermissionStrings[], ) { // Since Bot is a normal member we can use the throwOnMissingGuildPermission() function return requireGuildPermissions(bot, guild, bot.id, permissions); } /** Throws an error if this member has not all of the given permissions */ export function requireChannelPermissions( bot: BotWithCache, channel: bigint | DiscordenoChannel, member: bigint | DiscordenoMember, permissions: PermissionStrings[], ) { const missing = getMissingChannelPermissions( bot, channel, member, permissions, ); if (missing.length) { // If the member is missing a permission throw an Error throw new Error(`Missing Permissions: ${missing.join(" & ")}`); } } /** Throws an error if the bot has not all of the given channel permissions */ export function requireBotChannelPermissions( bot: BotWithCache, channel: bigint | DiscordenoChannel, permissions: PermissionStrings[], ) { // Since Bot is a normal member we can use the throwOnMissingChannelPermission() function return requireChannelPermissions(bot, channel, bot.id, permissions); } /** This function converts a bitwise string to permission strings */ export function calculatePermissions(permissionBits: bigint) { return Object.keys(BitwisePermissionFlags).filter((permission) => { // Since Object.keys() not only returns the permission names but also the bit values we need to return false if it is a Number if (Number(permission)) return false; // Check if permissionBits has this permission return permissionBits & BigInt(BitwisePermissionFlags[permission as PermissionStrings]); }) as PermissionStrings[]; } /** This function converts an array of permissions into the bitwise string. */ export function calculateBits(permissions: PermissionStrings[]) { return permissions .reduce((bits, perm) => { bits |= BigInt(BitwisePermissionFlags[perm]); return bits; }, 0n) .toString(); } /** Internal function to check if the bot has the permissions to set these overwrites */ export function requireOverwritePermissions( bot: BotWithCache, guildOrId: bigint | DiscordenoGuild, overwrites: Overwrite[], ) { let requiredPerms: Set<PermissionStrings> = new Set(["MANAGE_CHANNELS"]); overwrites?.forEach((overwrite) => { if (overwrite.allow) { overwrite.allow.forEach(requiredPerms.add, requiredPerms); } if (overwrite.deny) { overwrite.deny.forEach(requiredPerms.add, requiredPerms); } }); // MANAGE_ROLES permission can only be set by administrators if (requiredPerms.has("MANAGE_ROLES")) { requiredPerms = new Set<PermissionStrings>(["ADMINISTRATOR"]); } requireGuildPermissions(bot, guildOrId, bot.id, [ ...requiredPerms, ]); } /** Gets the highest role from the member in this guild */ export function highestRole( bot: BotWithCache, guildOrId: bigint | DiscordenoGuild, memberOrId: bigint | DiscordenoMember, ) { const guild = typeof guildOrId === "bigint" ? bot.guilds.get(guildOrId) : guildOrId; if (!guild) throw new Error(Errors.GUILD_NOT_FOUND); // Get the roles from the member const memberRoles = (typeof memberOrId === "bigint" ? bot.members.get(memberOrId) : memberOrId) ?.roles; // This member has no roles so the highest one is the @everyone role if (!memberRoles) return guild.roles.get(guild.id)!; let memberHighestRole: DiscordenoRole | undefined; for (const roleId of memberRoles) { const role = guild.roles.get(roleId); // Rare edge case handling if undefined if (!role) continue; // If memberHighestRole is still undefined we want to assign the role, // else we want to check if the current role position is higher than the current memberHighestRole if ( !memberHighestRole || memberHighestRole.position < role.position || memberHighestRole.position === role.position ) { memberHighestRole = role; } } // The member has at least one role so memberHighestRole must exist return memberHighestRole!; } /** Checks if the first role is higher than the second role */ export function higherRolePosition( bot: BotWithCache, guildOrId: bigint | DiscordenoGuild, roleId: bigint, otherRoleId: bigint, ) { const guild = typeof guildOrId === "bigint" ? bot.guilds.get(guildOrId) : guildOrId; if (!guild) return true; const role = guild.roles.get(roleId); const otherRole = guild.roles.get(otherRoleId); if (!role || !otherRole) throw new Error(Errors.ROLE_NOT_FOUND); // Rare edge case handling if (role.position === otherRole.position) { return role.id < otherRole.id; } return role.position > otherRole.position; } /** Checks if the member has a higher position than the given role */ export function isHigherPosition( bot: BotWithCache, guildOrId: bigint | DiscordenoGuild, memberId: bigint, compareRoleId: bigint, ) { const guild = typeof guildOrId === "bigint" ? bot.guilds.get(guildOrId) : guildOrId; if (!guild || guild.ownerId === memberId) return true; const memberHighestRole = highestRole(bot, guild, memberId); return higherRolePosition( bot, guild.id, memberHighestRole.id, compareRoleId, ); } /** Checks if a channel overwrite for a user id or a role id has permission in this channel */ export function channelOverwriteHasPermission( guildId: bigint, id: bigint, overwrites: bigint[], permissions: PermissionStrings[], ) { const overwrite = overwrites.find((perm) => { const [_, bitID] = separateOverwrites(perm); return id === bitID; }) || overwrites.find((perm) => { const [_, bitID] = separateOverwrites(perm); return bitID === guildId; }); if (!overwrite) return false; return permissions.every((perm) => { const [_type, _id, allowBits, denyBits] = separateOverwrites(overwrite); if (BigInt(denyBits) & BigInt(BitwisePermissionFlags[perm])) { return false; } if (BigInt(allowBits) & BigInt(BitwisePermissionFlags[perm])) { return true; } }); }
the_stack
// The MIT License (MIT) // // vs-deploy (https://github.com/mkloubert/vs-deploy) // Copyright (c) Marcel Joachim Kloubert <marcel.kloubert@gmx.net> // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to // deal in the Software without restriction, including without limitation the // rights to use, copy, modify, merge, publish, distribute, sublicense, and/or // sell copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. import * as deploy_contracts from '../contracts'; import * as deploy_helpers from '../helpers'; import * as deploy_objects from '../objects'; import * as deploy_values from '../values'; import * as FS from 'fs'; import * as HTTP from 'http'; import * as HTTPs from 'https'; import * as i18 from '../i18'; const MIME = require('mime'); import * as Moment from 'moment'; import * as Path from 'path'; import * as URL from 'url'; import * as vscode from 'vscode'; const DATE_RFC2822_UTC = "ddd, DD MMM YYYY HH:mm:ss [GMT]"; const TARGET_CACHE_PASSWORD = 'password'; interface DeployTargetHttp extends deploy_contracts.TransformableDeployTarget, deploy_contracts.PasswordObject { encodeUrlValues?: boolean; headers?: { [key: string]: any }; method?: string; password?: string; submitContentLength?: boolean; submitContentType?: boolean; submitDate?: boolean; submitFile?: boolean; submitFileHeader?: boolean; user?: string; url?: string; } /** * A data transformer sub context. */ export interface DataTransformerContext { /** * The path of the local file whats data should be transformed. */ file: string; /** * Gets the list of global variables defined in settings. */ globals: deploy_contracts.GlobalVariables; /** * The path to the remote file. */ remoteFile: string; /** * The target URL of the HTTP service. */ url: string; } class HttpPlugin extends deploy_objects.DeployPluginBase { public deployFile(file: string, target: DeployTargetHttp, opts?: deploy_contracts.DeployFileOptions): void { let now = Moment().utc(); if (!opts) { opts = {}; } let me = this; let hasCancelled = false; let completed = (err?: any) => { if (opts.onCompleted) { opts.onCompleted(me, { canceled: hasCancelled, error: err, file: file, target: target, }); } }; me.onCancelling(() => hasCancelled = true, opts); if (hasCancelled) { completed(); // cancellation requested } else { let relativePath = deploy_helpers.toRelativeTargetPathWithValues(file, target, me.context.values(), opts.baseDirectory); if (false === relativePath) { completed(new Error(i18.t('relativePaths.couldNotResolve', file))); return; } let url = deploy_helpers.toStringSafe(target.url).trim(); if (!url) { url = 'http://localhost'; } let method = deploy_helpers.toStringSafe(target.method).toUpperCase().trim(); if (!method) { method = 'PUT'; } let headers = target.headers; if (!headers) { headers = {}; } let user = deploy_helpers.toStringSafe(target.user); let pwd: string; if ('' !== user) { pwd = deploy_helpers.toStringSafe(target.password); if ('' === pwd) { pwd = undefined; } } let submitFileHeader = deploy_helpers.toBooleanSafe(target.submitFileHeader, false); if (submitFileHeader) { headers['X-vsdeploy-file'] = relativePath; } let contentType = deploy_helpers.detectMimeByFilename(file); try { if (opts.onBeforeDeploy) { opts.onBeforeDeploy(me, { destination: url, file: file, target: target, }); } let startRequest = () => { if ('' !== user) { headers['Authorization'] = 'Basic ' + (new Buffer(`${user}:${pwd}`)).toString('base64'); } // get file info FS.lstat(file, (err, stats) => { if (err) { completed(err); return; } let creationTime = Moment(stats.birthtime).utc(); let lastWriteTime = Moment(stats.mtime).utc(); // read file FS.readFile(file, (err, untransformedData) => { if (err) { completed(err); return; } try { let subCtx: DataTransformerContext = { globals: me.context.globals(), file: file, remoteFile: <string>relativePath, url: url, }; let tCtx = me.createDataTransformerContext(target, deploy_contracts.DataTransformerMode.Transform, subCtx); tCtx.data = untransformedData; let tResult = me.loadDataTransformer(target, deploy_contracts.DataTransformerMode.Transform)(tCtx); Promise.resolve(tResult).then((dataToSend) => { try { let parsePlaceHolders = (str: string, transformer: (val: any) => string): string => { let values = deploy_values.getBuildInValues().map(x => { let sv = new deploy_values.StaticValue({ name: x.name, value: transformer(x.value), }); sv.id = x.id; return sv; }); values.push(new deploy_values.StaticValue({ name: 'VSDeploy-Date', value: transformer(now.format(DATE_RFC2822_UTC)) })); values.push(new deploy_values.StaticValue({ name: 'VSDeploy-File', value: transformer(<string>relativePath) })); values.push(new deploy_values.StaticValue({ name: 'VSDeploy-File-Mime', value: transformer(contentType) })); let basename = Path.basename(file); values.push(new deploy_values.StaticValue({ name: 'VSDeploy-File-Name', value: transformer(basename) })); let extname = Path.extname(file); let rootname = basename.substr(0, basename.length - extname.length); values.push(new deploy_values.StaticValue({ name: 'VSDeploy-File-Root', value: transformer(rootname) })); values.push(new deploy_values.StaticValue({ name: 'VSDeploy-File-Size', value: transformer(dataToSend.length) })); values.push(new deploy_values.StaticValue({ name: 'VSDeploy-File-Time-Changed', value: transformer(lastWriteTime.format(DATE_RFC2822_UTC)) })); values.push(new deploy_values.StaticValue({ name: 'VSDeploy-File-Time-Created', value: transformer(lastWriteTime.format(DATE_RFC2822_UTC)) })); str = deploy_values.replaceWithValues(values, str); return deploy_helpers.toStringSafe(str); }; let encodeUrlValues = deploy_helpers.toBooleanSafe(target.encodeUrlValues, true); let targetUrl = URL.parse(parsePlaceHolders(url, encodeUrlValues ? encodeURIComponent : deploy_helpers.toStringSafe)); let submitFile = deploy_helpers.toBooleanSafe(target.submitFile, true); let submitContentLength = deploy_helpers.toBooleanSafe(target.submitContentLength, true); if (submitFile && submitContentLength) { headers['Content-length'] = deploy_helpers.toStringSafe(dataToSend.length, '0'); } let submitContentType = deploy_helpers.toBooleanSafe(target.submitContentType, true); if (submitFile && submitContentType) { headers['Content-type'] = contentType; } let submitDate = deploy_helpers.toBooleanSafe(target.submitDate, true); if (submitDate) { headers['Date'] = now.format(DATE_RFC2822_UTC); // RFC 2822 } let headersToSubmit = {}; for (let p in headers) { headersToSubmit[p] = parsePlaceHolders(headers[p], deploy_helpers.toStringSafe); } let protocol = deploy_helpers.toStringSafe(targetUrl.protocol).toLowerCase().trim(); if ('' === protocol) { protocol = 'http:'; } let httpModule: any; switch (protocol) { case 'http:': httpModule = HTTP; break; case 'https:': httpModule = HTTPs; break; } if (!httpModule) { completed(new Error(i18.t('plugins.http.protocolNotSupported', protocol))); return; } let hostName = deploy_helpers.toStringSafe(targetUrl.hostname).toLowerCase().trim(); if (!hostName) { hostName = 'localhost'; } let port = deploy_helpers.toStringSafe(targetUrl.port).trim(); if ('' === port) { port = 'http:' === protocol ? '80' : '443'; } // start the request let req = httpModule.request({ headers: headersToSubmit, host: hostName, method: method, path: targetUrl.path, port: parseInt(port), protocol: protocol, }, (resp) => { if (resp.statusCode > 399 && resp.statusCode < 500) { completed(new Error(`Client error: [${resp.statusCode}] '${resp.statusMessage}'`)); return; } if (resp.statusCode > 499 && resp.statusCode < 600) { completed(new Error(`Server error: [${resp.statusCode}] '${resp.statusMessage}'`)); return; } if (resp.statusCode > 599) { completed(new Error(`Error: [${resp.statusCode}] '${resp.statusMessage}'`)); return; } if (!(resp.statusCode > 199 && resp.statusCode < 300)) { completed(new Error(`No success: [${resp.statusCode}] '${resp.statusMessage}'`)); return; } completed(); }); req.once('error', (err) => { if (err) { completed(err); } }); if (submitFile) { // send file content req.write(dataToSend); } req.end(); } catch (e) { completed(e); } }).catch((err) => { completed(err); }); } catch (e) { completed(e); } }); }); }; let askForPasswordIfNeeded = () => { let showPasswordPrompt = false; if (!deploy_helpers.isEmptyString(user) && deploy_helpers.isNullOrUndefined(pwd)) { // user defined, but no password let pwdFromCache = deploy_helpers.toStringSafe(me.context.targetCache().get(target, TARGET_CACHE_PASSWORD)); if ('' === pwdFromCache) { // nothing in cache showPasswordPrompt = deploy_helpers.toBooleanSafe(target.promptForPassword, true); } else { pwd = pwdFromCache; } } if (showPasswordPrompt) { vscode.window.showInputBox({ ignoreFocusOut: true, placeHolder: i18.t('prompts.inputPassword'), password: true, }).then((passwordFromUser) => { if ('undefined' === typeof passwordFromUser) { hasCancelled = true; completed(null); // cancelled } else { pwd = passwordFromUser; me.context.targetCache().set(target, TARGET_CACHE_PASSWORD, passwordFromUser); startRequest(); } }, (err) => { completed(err); }); } else { startRequest(); } }; askForPasswordIfNeeded(); } catch (e) { completed(e); } } } public info(): deploy_contracts.DeployPluginInfo { return { description: i18.t('plugins.http.description'), }; } } /** * Creates a new Plugin. * * @param {deploy_contracts.DeployContext} ctx The deploy context. * * @returns {deploy_contracts.DeployPlugin} The new instance. */ export function createPlugin(ctx: deploy_contracts.DeployContext): deploy_contracts.DeployPlugin { return new HttpPlugin(ctx); }
the_stack
import { ColorScheme, ColorSchemePropertyName, excludeSettingsForSave, SystemSchedule } from "../Settings/ColorScheme"; import { ArgumentedEvent, ResponsiveEvent } from "../Events/Event"; import { injectable, Scope } from "../Utils/DI"; import { IBaseSettingsManager, BaseSettingsManager } from "../Settings/BaseSettingsManager"; import { IApplicationSettings } from "../Settings/IApplicationSettings"; import { IStorageManager } from "../Settings/IStorageManager"; import { ISettingsBus } from "../Settings/ISettingsBus"; import { IMatchPatternProcessor } from "../Settings/MatchPatternProcessor"; import { IRecommendations } from "../Settings/Recommendations"; import { ColorSchemes, ColorSchemeId, CustomColorSchemeId } from "../Settings/ColorSchemes"; import { ComponentShift } from "../Colors/ComponentShift"; import { ITranslationAccessor } from "../i18n/ITranslationAccessor"; import { HtmlEvent } from '../Events/HtmlEvent'; type AnyResponse = (args: any) => void; type ColorSchemeResponse = (settings: ColorScheme) => void; type ArgEvent<TRequestArgs> = ArgumentedEvent<TRequestArgs>; type RespEvent<TResponseMethod extends Function, TRequestArgs> = ResponsiveEvent<TResponseMethod, TRequestArgs>; const dom = HtmlEvent; export abstract class ISettingsManager { /** MidnightLizard should be running on this page */ abstract get isActive(): boolean; /** Complex processing mode is in use now */ abstract get isComplex(): boolean; /** Current settings for calculations */ abstract get shift(): ComponentShift; /** Current settings for communication */ abstract get currentSettings(): ColorScheme; abstract get onSettingsInitialized(): ArgEvent<ComponentShift>; abstract get onSettingsChanged(): RespEvent<(scheme: ColorScheme) => void, ComponentShift>; } @injectable(ISettingsManager) @injectable(IBaseSettingsManager, Scope.ExistingInstance) class SettingsManager extends BaseSettingsManager implements ISettingsManager { private skipOneSettingsUpdate: boolean = false; protected _scheduleUpdateTimeout?: number; constructor( _rootDocument: Document, app: IApplicationSettings, storageManager: IStorageManager, settingsBus: ISettingsBus, matchPatternProcessor: IMatchPatternProcessor, i18n: ITranslationAccessor, rec: IRecommendations) { super(_rootDocument, app, storageManager, settingsBus, matchPatternProcessor, i18n, rec); settingsBus.onCurrentSettingsRequested.addListener(this.onCurrentSettingsRequested, this); settingsBus.onIsEnabledToggleRequested.addListener(this.onIsEnabledToggleRequested, this); settingsBus.onNewSettingsApplicationRequested.addListener(this.onNewSettingsApplicationRequested, this); settingsBus.onSettingsDeletionRequested.addListener(this.onSettingsDeletionRequested, this); storageManager.onStorageChanged.addListener(this.onStorageChanged, this); } protected initCurSet() { super.initCurSet(); this.notifySettingsApplied(); } protected updateSchedule() { super.updateSchedule(); if (this._scheduleUpdateTimeout) { clearTimeout(this._scheduleUpdateTimeout); } if (this.UseSystemDarkSchedule) { dom.addEventListener(super.PrefersDarkColorSchemeMediaMatch(), "change", this.initCurrentSettings, this); } else if (this._scheduleStartTime !== 0 || this._scheduleFinishTime !== 24) { const today = new Date(); today.setHours(0, 0, 0, 0); const millisecondsUntilNextSwitch = [ this._scheduleStartTime, this._scheduleFinishTime, this._scheduleStartTime + 24, this._scheduleFinishTime + 24 ] .filter(h => h > this._curTime) .reduce((next, h) => h < next ? h : next, 99) * 60 * 60 * 1000 + today.getTime() - Date.now(); this._scheduleUpdateTimeout = window.setTimeout(() => { this.initCurrentSettings(); }, millisecondsUntilNextSwitch); } } protected async initCurrentSettings() { const storage = { ...ColorSchemes.default, ...ColorSchemes.dimmedDust, ...{ [this._settingsKey]: {} } }; try { const defaultSettings = await this._storageManager.get(storage); const settings = (defaultSettings as any)[this._settingsKey] as ColorScheme; delete (defaultSettings as any)[this._settingsKey]; await this.processDefaultSettings(defaultSettings, true); Object.assign(this._currentSettings, this._defaultSettings); if (settings) { this.assignSettings(this._currentSettings, settings); } this.updateSchedule(); this.initCurSet(); if (!this.isInit) { this._onSettingsInitialized.raise(this._shift); } else { this._onSettingsChanged.raise(() => null, this._shift); } } catch (ex) { this._app.isDebug && console.error(ex); } } protected async onSettingsDeletionRequested(response: AnyResponse) { if (window.top === window.self) { response(null); } if (this.isSelfMaintainable) { await this._storageManager.remove(this._settingsKey); } } protected onNewSettingsApplicationRequested(response: AnyResponse, newSettings?: ColorScheme) { this._currentSettings = newSettings!; this.saveCurrentSettings(); this.updateSchedule(); this.initCurSet(); this._onSettingsChanged.raise(response, this._shift); } protected onIsEnabledToggleRequested(response: AnyResponse, isEnabled?: boolean): void { if (isEnabled !== this._currentSettings.isEnabled) { this._currentSettings.isEnabled = isEnabled; this._onSettingsChanged.raise(response, this._shift); this.notifySettingsApplied(); } } protected onCurrentSettingsRequested(response: ColorSchemeResponse): void { this._currentSettings.location = this._rootDocument.location!.href; response(this._currentSettings); } protected async onStorageChanged(changes?: Partial<ColorScheme>) { if (changes && this.skipOneSettingsUpdate && this._settingsKey in changes) { this.skipOneSettingsUpdate = false; } else if (changes && ( //+ current website settings changed this._settingsKey in changes || //+ current website has default settings and they changed this._currentSettings.colorSchemeId === ColorSchemes.default.colorSchemeId && Object.keys(changes).find(key => !!key && !key.startsWith("cs:") && key !== "userColorSchemeIds") || //+ current website settings use default schedule and it changed this._currentSettings.useDefaultSchedule && ("scheduleStartHour" in changes || "scheduleFinishHour" in changes) || //+ color restoration options changed ("restoreColorsOnCopy" in changes || "restoreColorsOnPrint" in changes) || //+ current website color scheme changed `cs:${this._currentSettings.colorSchemeId}` in changes || // current website uses default settings and corresponding color scheme has changed this._currentSettings.colorSchemeId === ColorSchemes.default.colorSchemeId && `cs:${this.defaultColorSchemeId}` in changes || //+ storage type changed 'sync' in changes)) { this.initDefaultColorSchemes(); await this.initCurrentSettings(); } } /** it is main frame or child frame w/o access to the main frame */ protected get isSelfMaintainable() { let hasAccessToMainFrame: boolean = true; try { const test = window.top.location.hostname } catch { hasAccessToMainFrame = false; } return window.top === window.self || !hasAccessToMainFrame; } protected async saveCurrentSettings() { if (this.isSelfMaintainable) { try { this.skipOneSettingsUpdate = true; if (this._currentSettings.colorSchemeId === ColorSchemes.default.colorSchemeId) { await this._storageManager.set({ [this._settingsKey]: { runOnThisSite: this._currentSettings.runOnThisSite } }); } else if (this._currentSettings.colorSchemeId && this._currentSettings.colorSchemeId !== CustomColorSchemeId) { await this._storageManager.set({ [this._settingsKey]: { colorSchemeId: this._currentSettings.colorSchemeId, runOnThisSite: this._currentSettings.runOnThisSite } }); } else { let setting: ColorSchemePropertyName; const forSave = {} as any; for (setting in this._currentSettings) { if (excludeSettingsForSave.indexOf(setting) == -1) { forSave[setting] = this._currentSettings[setting]; } } await this._storageManager.set({ [this._settingsKey]: forSave }); } } catch (error) { const reason = await this.getErrorReason(error); alert("Midnight Lizard\n" + this._i18n.getMessage("applyOnPageFailureMessage") + reason); } } } protected getSettingNameForCookies(propertyName: ColorSchemePropertyName) { return "ML" + propertyName.match(/^[^A-Z]{1,4}|[A-Z][^A-Z]{0,2}/g)!.join("").toUpperCase(); } }
the_stack
import {ChartClass} from 'org_xprof/frontend/app/common/interfaces/chart'; interface FormatDiffInfo { rangeMin?: number; rangeMax?: number; hasColor: boolean; isLargeBetter: boolean; } interface FormatValueInfo { rangeMin?: number; rangeMax?: number; multiplier: number; fixed: number; suffix: string; } const RANGE_MIN = 0; const RANGE_MAX = 999; const XNOR = (a: boolean, b: boolean): boolean => { return (a && b) || (!a && !b); }; /** * Return the diffed pie-chart table based on category. */ export function computeCategoryDiffTable( groupView: google.visualization.DataView, baseGroupView: google.visualization.DataView, chart: ChartClass): google.visualization.DataTable|null { if (!groupView || !baseGroupView) { return null; } // Obtain a superset of categories, and the map from category to self time // in both baseline and current profiles. const categorySet = new Set(); // Assume set is unordered. const oldMap: {[key: string]: number} = {}; const newMap: {[key: string]: number} = {}; for (let i = 0; i < groupView.getNumberOfRows(); i++) { newMap[groupView.getValue(i, 0)] = groupView.getValue(i, 1); categorySet.add(groupView.getValue(i, 0)); } for (let i = 0; i < baseGroupView.getNumberOfRows(); i++) { oldMap[baseGroupView.getValue(i, 0)] = baseGroupView.getValue(i, 1); categorySet.add(baseGroupView.getValue(i, 0)); } // Initialize the oldTable and newTable with the superset of categories. const oldTable = new google.visualization.DataTable(); for (let i = 0; i < baseGroupView.getNumberOfColumns(); i++) { oldTable.addColumn({ 'type': baseGroupView.getColumnType(i), 'label': baseGroupView.getColumnLabel(i), }); } oldTable.addRows(categorySet.size); let rowID = 0; for (const skey of categorySet.keys()) { oldTable.setCell(rowID, 0, skey); oldTable.setCell(rowID, 1, 0.0); rowID++; } const newTable = oldTable.clone(); // Fill in the value in oldTable and newTable respectively. for (let i = 0; i < oldTable.getNumberOfRows(); i++) { if (oldTable.getValue(i, 0) in oldMap) { oldTable.setCell(i, 1, oldMap[oldTable.getValue(i, 0)]); } } for (let i = 0; i < newTable.getNumberOfRows(); i++) { if (newTable.getValue(i, 0) in newMap) { newTable.setCell(i, 1, newMap[newTable.getValue(i, 0)]); } } // Return the diffed pie-chart table. // tslint:disable-next-line:no-any return (chart as any)['computeDiff'](oldTable, newTable); } /** * Compute the stats difference between two tables. oldTable and newTable * need to be DataTable class, and function also returns DataTable class. * Assume the type and label of columns in both tables match, while their * row counts can be different. * This function works for both main table and opType aggregation table. * @param oldTable Previous data table to be compared.It is used to calculate * the difference from the new data table. * @param newTable Data table for current values.The increase or decrease is * displayed based on this value. * @param referenceCol Column number as a reference for comparing two data * tables. * @param comparisonCol Column number that has the actual value comparing two * data tables. * @param addColumnType The type of an additional column at the end for sorting * purpose. * @param addColumnLabel The label of an additional column at the end for * sorting purpose. * @param sortColumn Columns used for sorting the created data table. * @param hiddenColumns Number of hidden columns in the created data table. * @param formatDiffInfo Define hasColor and isLargeBetter for the range of the * column. If all values are true in 8 and false in all other ranges, it * can be defined as follows. If rangeMin is not defined, 0 is used. If * rangeMax is not defined, 999 is used. * [ * { * rangeMax: 7, * hasColor: false, * isLargeBetter: false, * }, * { * rangeMin: 8, * rangeMax: 8, * hasColor: true, * isLargeBetter: true, * }, * { * rangeMin: 9, * hasColor: true, * isLargeBetter: false, * }, * ] * @param formatValueInfo Defines multiplier, fixed, and suffix for the range of * the column. For example, column 0 multiplies by 100, removes the * decimal point, and adds a % sign. The remaining columns are displayed * up to two decimal places. In this case, it is defined as follows. If * rangeMin is not defined, 0 is used. If rangeMax is not defined, 999 is * used. * [ * { * rangeMin: 0, * rangeMax: 0, * multiplier: 100, * fixed: 0, * suffix: '%', * }, * { * rangeMin: 1, * multiplier: 1, * fixed: 2, * suffix: '', * }, * ] */ export function computeDiffTable( oldTable: google.visualization.DataTable, newTable: google.visualization.DataTable, referenceCol: number, comparisonCol: number, addColumnType: string, addColumnLabel: string, sortColumn: google.visualization.SortByColumn[], hiddenColumns: number[], formatDiffInfo: FormatDiffInfo[], formatValueInfo: FormatValueInfo[]): google.visualization.DataView { const colsCount = oldTable.getNumberOfColumns(); const diffTable = new google.visualization.DataTable(); // The first column can be rank ('number') or opType ('string'). diffTable.addColumn({ 'type': oldTable.getColumnType(0), 'label': oldTable.getColumnLabel(0), }); // Adds column label for diffTable. Assume old and new tables // have the same column types. for (let colIndex = 1; colIndex < colsCount; ++colIndex) { diffTable.addColumn({ 'type': 'string', 'label': oldTable.getColumnLabel(colIndex), }); } // Add additional column at the end for sorting purpose. diffTable.addColumn({ 'type': addColumnType, 'label': addColumnLabel, }); diffTable.addRows(oldTable.getNumberOfRows() + newTable.getNumberOfRows()); // Merge sort and diff the oldTable and newTable based on opName. const numDiffRows = mergeSortTables( diffTable, oldTable, newTable, referenceCol, comparisonCol, formatDiffInfo, formatValueInfo); // Hide the empty rows, and the last column in diffTable. const diffView = new google.visualization.DataView(diffTable); if (numDiffRows > 0) { diffView.setRows(0, numDiffRows - 1); sortColumn.push({column: colsCount, desc: true}); diffView.setRows(diffView.getSortedRows(sortColumn)); } hiddenColumns.push(colsCount); diffView.hideColumns(hiddenColumns); return diffView; } /** * The function takes in oldTable and newTable, sort them by referenceCol * column, and fill their difference into the generated diffTable. * The difference in comparisonCol column is filled in the last column * of diffTable, and used for sorting the diffTable afterwards, */ function mergeSortTables( diffTable: google.visualization.DataTable, oldTable: google.visualization.DataTable, newTable: google.visualization.DataTable, referenceCol: number, comparisonCol: number, formatDiffInfo: FormatDiffInfo[], formatValueInfo: FormatValueInfo[]): number { oldTable.sort({column: referenceCol, desc: false}); // Ascending order. newTable.sort({column: referenceCol, desc: false}); // Ascending order. const oldSize = oldTable.getNumberOfRows(); const newSize = newTable.getNumberOfRows(); // colsCount is number of columns in the original tables. In diffTable // there is one additional column at the end which is the difference // in self time between two stats. The column is used solely for // sorting the diffTable and gets hidden before function returns. const colsCount = oldTable.getNumberOfColumns(); const largeCharInASCII = '~~~~'; let rowIndex = 0; for (let oldRow = 0, newRow = 0; oldRow < oldSize || newRow < newSize; rowIndex++) { // Assign the largest character in ASCII table for comparison. const oldReferenceValue = (oldRow < oldSize) ? oldTable.getValue(oldRow, referenceCol) : largeCharInASCII; const newReferenceValue = (newRow < newSize) ? newTable.getValue(newRow, referenceCol) : largeCharInASCII; if (oldRow < oldSize && newRow < newSize && oldReferenceValue === newReferenceValue) { // If reference value is the same, then diff the two stats. for (let colIndex = 0; colIndex < colsCount; colIndex++) { if (colIndex !== 0 && oldTable.getColumnType(colIndex) === 'number') { const baseVal = oldTable.getValue(oldRow, colIndex); const diffVal = newTable.getValue(newRow, colIndex) - oldTable.getValue(oldRow, colIndex); diffTable.setCell( rowIndex, colIndex, formatValue(baseVal, colIndex, formatValueInfo) + formatDiff(diffVal, baseVal, colIndex, formatDiffInfo)); } else { // Use oldTable's string values, or rank. diffTable.setCell( rowIndex, colIndex, oldTable.getValue(oldRow, colIndex)); } } const diffValue = newTable.getValue(newRow, comparisonCol) - oldTable.getValue(oldRow, comparisonCol); diffTable.setCell(rowIndex, colsCount, diffValue); oldRow++, newRow++; } else if (newRow === newSize || oldReferenceValue < newReferenceValue) { // If only old stats, then assign the diff as negative old stats. for (let colIndex = 0; colIndex < colsCount; colIndex++) { if (colIndex !== 0 && oldTable.getColumnType(colIndex) === 'number') { const baseVal = oldTable.getValue(oldRow, colIndex); const diffVal = -oldTable.getValue(oldRow, colIndex); diffTable.setCell( rowIndex, colIndex, formatValue(baseVal, colIndex, formatValueInfo) + formatDiff(diffVal, baseVal, colIndex, formatDiffInfo)); } else { // Use oldTable's string values, or rank. diffTable.setCell( rowIndex, colIndex, oldTable.getValue(oldRow, colIndex)); } } const diffValue = -oldTable.getValue(oldRow, comparisonCol); diffTable.setCell(rowIndex, colsCount, diffValue); oldRow++; } else { // if (oldRow == oldSize || oldReferenceValue > newReferenceValue) // If only new stats, then assign the diff as new stats. for (let colIndex = 0; colIndex < colsCount; colIndex++) { if (colIndex !== 0 && newTable.getColumnType(colIndex) === 'number') { const baseVal = 0; const diffVal = newTable.getValue(newRow, colIndex); diffTable.setCell( rowIndex, colIndex, formatValue(baseVal, colIndex, formatValueInfo) + formatDiff(diffVal, baseVal, colIndex, formatDiffInfo)); } else { // Use newTable's string values, or rank. diffTable.setCell( rowIndex, colIndex, newTable.getValue(newRow, colIndex)); } } const diffValue = newTable.getValue(newRow, comparisonCol); diffTable.setCell(rowIndex, colsCount, diffValue); newRow++; } // End of if condition comparing opName. } // End of for loop over all rows. return rowIndex; } /** * Format value based on table column index. */ function formatValue( val: number, col: number, formatValueInfo: FormatValueInfo[]): string { for (const info of formatValueInfo) { const rangeMin = info.hasOwnProperty('rangeMin') ? info.rangeMin || 0 : RANGE_MIN; const rangeMax = info.hasOwnProperty('rangeMax') ? info.rangeMax || 0 : RANGE_MAX; if (col >= rangeMin && col <= rangeMax) { return (val * info.multiplier).toFixed(info.fixed) + info.suffix; } } return ''; } /** * Format diff value. */ function formatDiff( diffVal: number, baseVal: number, colIndex: number, formatDiffInfo: FormatDiffInfo[]): string { for (const info of formatDiffInfo) { const rangeMin = info.hasOwnProperty('rangeMin') ? info.rangeMin || 0 : RANGE_MIN; const rangeMax = info.hasOwnProperty('rangeMax') ? info.rangeMax || 0 : RANGE_MAX; if (colIndex >= rangeMin && colIndex <= rangeMax) { return formatDiffWithColor( diffVal, baseVal, info.hasColor, info.isLargeBetter); } } return ''; } /** * Format diff value with color. */ function formatDiffWithColor( dividend: number, divisor: number, hasColor: boolean, isLargeBetter: boolean): string { // If dividend is 0, return 0. if (!dividend) return '<font color="grey">(0)</font>'; let color; if (hasColor) { color = XNOR(dividend > 0, isLargeBetter) ? 'green' : 'red'; } else { color = 'black'; } let str; if (!divisor) { // If divisor is 0, return the original dividend value. str = '(+' + dividend.toFixed(1) + ')'; } else { str = dividend > 0 ? '(+' : '('; str += (dividend / divisor * 100).toFixed(0) + '%)'; } return str.fontcolor(color); } /** * Return the diffed pie-chart table based on category. */ export function computePivotTable( dataTable: google.visualization.DataTable, columnLabel: string, rowLabel: string, valueLabel: string, newColumnLabel: string, sortByValue: boolean): google.visualization.DataTable|null { if (!dataTable) { return null; } const columnIndex = dataTable.getColumnIndex(columnLabel); const rowIndex = dataTable.getColumnIndex(rowLabel); const valueIndex = dataTable.getColumnIndex(valueLabel); if (sortByValue) { // Set sort columns dataTable.sort({column: valueIndex, desc: true}); } // Creates pivotTable based on dataTable. The pivot table has one row for // each rowLabel column and one column for each columnLabel column. const pivotTable = new google.visualization.DataTable(); pivotTable.addColumn('string', newColumnLabel); const columnValues = dataTable.getDistinctValues(columnIndex); const columnValuesMap = new Map<string, number>(); columnValues.forEach(columnValue => { columnValuesMap.set(columnValue, pivotTable.getNumberOfColumns()); pivotTable.addColumn('number', columnValue); }); const rowValues = dataTable.getDistinctValues(rowIndex); const rowValuesMap = new Map<string, number>(); rowValues.forEach(rowValue => { const row = pivotTable.getNumberOfRows(); rowValuesMap.set(rowValue, row); pivotTable.addRow(); pivotTable.setValue(row, 0, rowValue); }); const numRows = dataTable.getNumberOfRows(); for (let i = 0; i < numRows; ++i) { const rowValue = dataTable.getValue(i, rowIndex) as string; const columnValue = dataTable.getValue(i, columnIndex) as string; const value = dataTable.getValue(i, valueIndex); pivotTable.setValue( rowValuesMap.get(rowValue)!, columnValuesMap.get(columnValue)!, value); } return pivotTable; } /** * Create a group table with a group column and a value column. * @param dataTable The data table to be changed to a group. * @param filters Filters on the data to be displayed. * @param gColumn The column index to group the data. * @param vColumn The column index that has data value. */ export function computeGroupView( dataTable: google.visualization.DataTable, filters: google.visualization.DataTableCellFilter[], gColumn: number, vColumn: number): google.visualization.DataView { const numberFormatter = new google.visualization.NumberFormat({'fractionDigits': 0}); const dataView = new google.visualization.DataView(dataTable); if (filters && filters.length > 0) { dataView.setRows(dataView.getFilteredRows(filters)); } const dataGroup = google.visualization.data.group( dataView, [gColumn], [{ 'column': vColumn, 'aggregation': google.visualization.data.sum, 'type': 'number', }]); dataGroup.sort({column: 1, desc: true}); numberFormatter.format(dataGroup, 1); return new google.visualization.DataView(dataGroup); }
the_stack
import * as fs from 'fs'; import * as inputParam from '../src/input-parameters'; import * as fileHelper from '../src/utilities/files-helper'; import { Kubectl, } from '../src/kubectl-object-model'; import { mocked } from 'ts-jest/utils'; import * as kubectlUtils from '../src/utilities/kubectl-util'; var path = require('path'); const inputParamMock = mocked(inputParam, true); var deploymentYaml = ""; import * as blueGreenHelper from '../src/utilities/strategy-helpers/blue-green-helper'; import * as blueGreenHelperService from '../src/utilities/strategy-helpers/service-blue-green-helper'; import * as blueGreenHelperIngress from '../src/utilities/strategy-helpers/ingress-blue-green-helper'; import * as blueGreenHelperSMI from '../src/utilities/strategy-helpers/smi-blue-green-helper'; beforeAll(() => { deploymentYaml = fs.readFileSync(path.join(__dirname, 'manifests', 'bg.yml'), 'utf8'); process.env["KUBECONFIG"] = 'kubeConfig'; }); test("deployBlueGreen - checks if deployment can be done, then deploys", () => { const fileHelperMock = mocked(fileHelper, true); const kubeCtl: jest.Mocked < Kubectl > = new Kubectl("") as any; let temp = { stdout: undefined }; fileHelperMock.writeObjectsToFile = jest.fn().mockReturnValue('hello'); kubeCtl.apply = jest.fn().mockReturnValue(''); kubeCtl.getResource = jest.fn().mockReturnValue(JSON.parse(JSON.stringify(temp))); const readFileSpy = jest.spyOn(fs, 'readFileSync').mockImplementation(() => deploymentYaml); //Invoke and assert expect(blueGreenHelperService.deployBlueGreenService(kubeCtl, ['manifests/bg.yaml'])).toMatchObject({ "newFilePaths": "hello", "result": "" }); expect(readFileSpy).toBeCalledWith("manifests/bg.yaml"); expect(fileHelperMock.writeObjectsToFile).toBeCalled(); expect(kubeCtl.apply).toBeCalled(); }); test("blueGreenPromote - checks if in deployed state and then promotes", () => { const fileHelperMock = mocked(fileHelper, true); const kubeCtl: jest.Mocked < Kubectl > = new Kubectl("") as any; let temp = { stdout: JSON.stringify({ "apiVersion": "v1", "kind": "Service", "metadata": { "name": "testservice" }, "spec": { "selector": { "app": "testapp", "k8s.deploy.color": "green" }, "ports": [{ "protocol": "TCP", "port": 80, "targetPort": 80 }] } }) }; fileHelperMock.writeObjectsToFile = jest.fn().mockReturnValue('hello'); kubeCtl.apply = jest.fn().mockReturnValue(''); kubeCtl.getResource = jest.fn().mockReturnValue(JSON.parse(JSON.stringify(temp))); const readFileSpy = jest.spyOn(fs, 'readFileSync').mockImplementation(() => deploymentYaml); //Invoke and assert const manifestObjects = blueGreenHelper.getManifestObjects(['manifests/bg.yaml']); expect(blueGreenHelperService.promoteBlueGreenService(kubeCtl, manifestObjects)).toMatchObject({}); expect(readFileSpy).toBeCalledWith("manifests/bg.yaml"); expect(kubeCtl.apply).toBeCalledWith("hello"); expect(fileHelperMock.writeObjectsToFile).toBeCalled(); }); test("blueGreenReject - routes servcies to old deployment and deletes new deployment", () => { const fileHelperMock = mocked(fileHelper, true); const kubeCtl: jest.Mocked < Kubectl > = new Kubectl("") as any; let temp = { stdout: JSON.stringify({ "apiVersion": "apps/v1beta1", "kind": "Deployment", "metadata": { "name": "testapp", "labels": { "k8s.deploy.color": "none" } }, "spec": { "selector": { "matchLabels": { "app": "testapp", "k8s.deploy.color": "none" } }, "replicas": 1, "template": { "metadata": { "labels": { "app": "testapp", "k8s.deploy.color": "none" } }, "spec": { "containers": [{ "name": "testapp", "image": "testcr.azurecr.io/testapp", "ports": [{ "containerPort": 80 }] }] } } } }) }; kubeCtl.delete = jest.fn().mockReturnValue(''); fileHelperMock.writeObjectsToFile = jest.fn().mockReturnValue('hello'); kubeCtl.apply = jest.fn().mockReturnValue(''); kubeCtl.getResource = jest.fn().mockReturnValue(JSON.parse(JSON.stringify(temp))); const readFileSpy = jest.spyOn(fs, 'readFileSync').mockImplementation(() => deploymentYaml); //Invoke and assert expect(blueGreenHelperService.rejectBlueGreenService(kubeCtl, ['manifests/bg.yaml'])).toMatchObject({}); expect(kubeCtl.delete).toBeCalledWith(["Deployment", "testapp-green"]); expect(readFileSpy).toBeCalledWith("manifests/bg.yaml"); expect(fileHelperMock.writeObjectsToFile).toBeCalled(); }); test("blueGreenReject - deletes services if old deployment does not exist", () => { const fileHelperMock = mocked(fileHelper, true); const kubeCtl: jest.Mocked < Kubectl > = new Kubectl("") as any; let temp = { stdout: undefined }; fileHelperMock.writeObjectsToFile = jest.fn().mockReturnValue('hello'); kubeCtl.apply = jest.fn().mockReturnValue(''); kubeCtl.delete = jest.fn().mockReturnValue(''); kubeCtl.getResource = jest.fn().mockReturnValue(JSON.parse(JSON.stringify(temp))); const readFileSpy = jest.spyOn(fs, 'readFileSync').mockImplementation(() => deploymentYaml); //Invoke and assert expect(blueGreenHelperService.rejectBlueGreenService(kubeCtl, ['manifests/bg.yaml'])).toMatchObject({}); expect(kubeCtl.delete).toBeCalledWith(["Deployment", "testapp-green"]); expect(readFileSpy).toBeCalledWith("manifests/bg.yaml"); expect(fileHelperMock.writeObjectsToFile).toBeCalled(); }); test("isIngressRoute() - returns true if route-method is ingress", () => { // default is service expect(blueGreenHelper.isIngressRoute()).toBeFalsy(); }); test("isIngressRoute() - returns true if route-method is ingress", () => { inputParamMock.routeMethod = 'ingress' expect(blueGreenHelper.isIngressRoute()).toBeTruthy(); }); test("deployBlueGreenIngress - creates deployments, services and other non ingress objects", () => { const fileHelperMock = mocked(fileHelper, true); const kubeCtl: jest.Mocked < Kubectl > = new Kubectl("") as any; let temp = { stdout: undefined }; fileHelperMock.writeObjectsToFile = jest.fn().mockReturnValue('hello'); kubeCtl.apply = jest.fn().mockReturnValue(''); kubeCtl.getResource = jest.fn().mockReturnValue(JSON.parse(JSON.stringify(temp))); const readFileSpy = jest.spyOn(fs, 'readFileSync').mockImplementation(() => deploymentYaml); //Invoke and assert expect(blueGreenHelperIngress.deployBlueGreenIngress(kubeCtl, ['manifests/bg.yaml'])).toMatchObject({ "newFilePaths": "hello", "result": "" }); expect(readFileSpy).toBeCalledWith("manifests/bg.yaml"); expect(kubeCtl.apply).toBeCalledWith("hello"); }); test("blueGreenPromoteIngress - checks if in deployed state and then promotes ingress", () => { const fileHelperMock = mocked(fileHelper, true); const kubeCtl: jest.Mocked < Kubectl > = new Kubectl("") as any; fileHelperMock.writeObjectsToFile = jest.fn().mockReturnValue('hello'); kubeCtl.apply = jest.fn().mockReturnValue(''); const readFileSpy = jest.spyOn(fs, 'readFileSync').mockImplementation(() => deploymentYaml); let temp = { stdout: JSON.stringify({ "apiVersion": "networking.k8s.io/v1beta1", "kind": "Ingress", "metadata": { "name": "testingress", "labels": { "k8s.deploy.color": "green" }, "annotations": { "nginx.ingress.kubernetes.io/rewrite-target": "/" } }, "spec": { "rules": [{ "http": { "paths": [{ "path": "/testpath", "pathType": "Prefix", "backend": { "serviceName": "testservice-green", "servicePort": 80 } }] } }] } }) }; kubeCtl.getResource = jest.fn().mockReturnValue(JSON.parse(JSON.stringify(temp))); const manifestObjects = blueGreenHelper.getManifestObjects(['manifests/bg.yaml']); //Invoke and assert expect(blueGreenHelperIngress.promoteBlueGreenIngress(kubeCtl, manifestObjects)).toMatchObject({}); expect(readFileSpy).toBeCalledWith("manifests/bg.yaml"); expect(kubeCtl.apply).toBeCalledWith("hello"); }); test("blueGreenRejectIngress - routes ingress to stable services and deletes new deployments and services", () => { const fileHelperMock = mocked(fileHelper, true); const kubeCtl: jest.Mocked < Kubectl > = new Kubectl("") as any; fileHelperMock.writeObjectsToFile = jest.fn().mockReturnValue('hello'); kubeCtl.apply = jest.fn().mockReturnValue(''); kubeCtl.delete = jest.fn().mockReturnValue(''); const readFileSpy = jest.spyOn(fs, 'readFileSync').mockImplementation(() => deploymentYaml); //Invoke and assert expect(blueGreenHelperIngress.rejectBlueGreenIngress(kubeCtl, ['manifests/bg.yaml'])).toMatchObject({}); expect(kubeCtl.delete).toBeCalledWith(["Deployment", "testapp-green"]); expect(kubeCtl.delete).toBeCalledWith(["Service", "testservice-green"]); expect(readFileSpy).toBeCalledWith("manifests/bg.yaml"); expect(fileHelperMock.writeObjectsToFile).toBeCalled(); }); test("isSMIRoute() - returns true if route-method is smi", () => { inputParamMock.routeMethod = 'smi' expect(blueGreenHelper.isSMIRoute()).toBeTruthy(); }); test("isSMIRoute() - returns true if route-method is smi", () => { inputParamMock.routeMethod = 'ingress' expect(blueGreenHelper.isSMIRoute()).toBeFalsy(); }); test("deployBlueGreenSMI - checks if deployment can be done, then deploys along this auxiliary services and trafficsplit", () => { const fileHelperMock = mocked(fileHelper, true); const kubeCtl: jest.Mocked < Kubectl > = new Kubectl("") as any; let temp = { stdout: undefined }; fileHelperMock.writeObjectsToFile = jest.fn().mockReturnValue('hello'); kubeCtl.apply = jest.fn().mockReturnValue(''); kubeCtl.getResource = jest.fn().mockReturnValue(JSON.parse(JSON.stringify(temp))); const readFileSpy = jest.spyOn(fs, 'readFileSync').mockImplementation(() => deploymentYaml); const kubectlUtilsMock = mocked(kubectlUtils, true); kubectlUtilsMock.getTrafficSplitAPIVersion = jest.fn().mockReturnValue('split.smi-spec.io/v1alpha2'); //Invoke and assert expect(blueGreenHelperSMI.deployBlueGreenSMI(kubeCtl, ['manifests/bg.yaml'])).toMatchObject({ "newFilePaths": "hello", "result": "" }); expect(readFileSpy).toBeCalledWith("manifests/bg.yaml"); expect(fileHelperMock.writeObjectsToFile).toBeCalled(); }); test("blueGreenPromoteSMI - checks weights of trafficsplit and then deploys", () => { const fileHelperMock = mocked(fileHelper, true); const kubeCtl: jest.Mocked < Kubectl > = new Kubectl("") as any; fileHelperMock.writeObjectsToFile = jest.fn().mockReturnValue('hello'); kubeCtl.apply = jest.fn().mockReturnValue(''); const readFileSpy = jest.spyOn(fs, 'readFileSync').mockImplementation(() => deploymentYaml); let temp = { stdout: JSON.stringify({ "apiVersion": "split.smi-spec.io/v1alpha2", "kind": "TrafficSplit", "metadata": { "name": "testservice-rollout" }, "spec": { "service": "testservice", "backends": [{ "service": "testservice-stable", "weight": 0 }, { "service": "testservice-green", "weight": 100 } ] } }) }; kubeCtl.getResource = jest.fn().mockReturnValue(JSON.parse(JSON.stringify(temp))); const manifestObjects = blueGreenHelper.getManifestObjects(['manifests/bg.yaml']); //Invoke and assert expect(blueGreenHelperSMI.promoteBlueGreenSMI(kubeCtl, manifestObjects)).toMatchObject({}); expect(readFileSpy).toBeCalledWith("manifests/bg.yaml"); }); test("blueGreenRejectSMI - routes servcies to old deployment and deletes new deployment, auxiliary services and trafficsplit", () => { const fileHelperMock = mocked(fileHelper, true); const kubeCtl: jest.Mocked < Kubectl > = new Kubectl("") as any; let temp = { stdout: JSON.stringify({ "apiVersion": "apps/v1beta1", "kind": "Deployment", "metadata": { "name": "testapp", "labels": { "k8s.deploy.color": "none" } }, "spec": { "selector": { "matchLabels": { "app": "testapp", "k8s.deploy.color": "none" } }, "replicas": 1, "template": { "metadata": { "labels": { "app": "testapp", "k8s.deploy.color": "none" } }, "spec": { "containers": [{ "name": "testapp", "image": "testcr.azurecr.io/testapp", "ports": [{ "containerPort": 80 }] }] } } } }) }; kubeCtl.delete = jest.fn().mockReturnValue(''); fileHelperMock.writeObjectsToFile = jest.fn().mockReturnValue('hello'); kubeCtl.apply = jest.fn().mockReturnValue(''); kubeCtl.getResource = jest.fn().mockReturnValue(JSON.parse(JSON.stringify(temp))); const readFileSpy = jest.spyOn(fs, 'readFileSync').mockImplementation(() => deploymentYaml); //Invoke and assert expect(blueGreenHelperSMI.rejectBlueGreenSMI(kubeCtl, ['manifests/bg.yaml'])).toMatchObject({}); expect(kubeCtl.delete).toBeCalledWith(["Deployment", "testapp-green"]); expect(kubeCtl.delete).toBeCalledWith(["Service", "testservice-green"]); expect(kubeCtl.delete).toBeCalledWith(["Service", "testservice-stable"]); expect(kubeCtl.delete).toBeCalledWith(["TrafficSplit", "testservice-trafficsplit"]); expect(readFileSpy).toBeCalledWith("manifests/bg.yaml"); }); test("blueGreenRejectSMI - deletes service if stable deployment doesn't exist", () => { const fileHelperMock = mocked(fileHelper, true); const kubeCtl: jest.Mocked < Kubectl > = new Kubectl("") as any; let temp = { stdout: undefined }; kubeCtl.delete = jest.fn().mockReturnValue(''); fileHelperMock.writeObjectsToFile = jest.fn().mockReturnValue('hello'); kubeCtl.apply = jest.fn().mockReturnValue(''); kubeCtl.getResource = jest.fn().mockReturnValue(JSON.parse(JSON.stringify(temp))); const readFileSpy = jest.spyOn(fs, 'readFileSync').mockImplementation(() => deploymentYaml); //Invoke and assert expect(blueGreenHelperSMI.rejectBlueGreenSMI(kubeCtl, ['manifests/bg.yaml'])).toMatchObject({}); expect(kubeCtl.delete).toBeCalledWith(["Deployment", "testapp-green"]); expect(kubeCtl.delete).toBeCalledWith(["Service", "testservice-green"]); expect(kubeCtl.delete).toBeCalledWith(["Service", "testservice-stable"]); expect(kubeCtl.delete).toBeCalledWith(["TrafficSplit", "testservice-trafficsplit"]); expect(readFileSpy).toBeCalledWith("manifests/bg.yaml"); }); // other functions and branches test("blueGreenRouteIngress - routes to green services in nextlabel is green", () => { const kubeCtl: jest.Mocked < Kubectl > = new Kubectl("") as any; const fileHelperMock = mocked(fileHelper, true); const ingEntList = [{ "apiVersion": "networking.k8s.io/v1beta1", "kind": "Ingress", "metadata": { "name": "test-ingress", "annotations": { "nginx.ingress.kubernetes.io/rewrite-target": "/" }, }, "spec": { "rules": [{ "http": { "paths": [{ "path": "/testpath", "pathType": "Prefix", "backend": { "serviceName": "testservice", "servicePort": 80 } }, { "path": "/testpath", "pathType": "Prefix", "backend": { "serviceName": "random", "servicePort": 80 } } ] } }] } }, { "apiVersion": "networking.k8s.io/v1beta1", "kind": "Ingress", "metadata": { "name": "test-ingress", "annotations": { "nginx.ingress.kubernetes.io/rewrite-target": "/" }, }, "spec": { "rules": [{ "http": { "paths": [{ "path": "/testpath", "pathType": "Prefix", "backend": { "serviceName": "random", "servicePort": 80 } }] } }] } } ]; const serEntList = [{ "apiVersion": "v1", "kind": "Service", "metadata": { "name": "testservice" }, "spec": { "selector": { "app": "testapp", }, "ports": [{ "protocol": "TCP", "port": 80, "targetPort": 80 }] } }]; let serviceEntityMap = new Map<string, string>(); serviceEntityMap.set('testservice', 'testservice-green'); fileHelperMock.writeObjectsToFile = jest.fn().mockReturnValue('hello'); kubeCtl.apply = jest.fn().mockReturnValue(''); //Invoke and assert expect(blueGreenHelperIngress.routeBlueGreenIngress(kubeCtl, 'green', serviceEntityMap, ingEntList)); expect(kubeCtl.apply).toBeCalled(); expect(fileHelperMock.writeObjectsToFile).toBeCalled(); }); test("shouldWePromoteIngress - throws if routed ingress does not exist", () => { const kubeCtl: jest.Mocked < Kubectl > = new Kubectl("") as any; let temp = { stdout: undefined } const ingEntList = [{ "apiVersion": "networking.k8s.io/v1beta1", "kind": "Ingress", "metadata": { "name": "test-ingress", "annotations": { "nginx.ingress.kubernetes.io/rewrite-target": "/" } }, "spec": { "rules": [{ "http": { "paths": [{ "path": "/testpath", "pathType": "Prefix", "backend": { "serviceName": "testservice", "servicePort": 80 } }] } }] } }]; let serviceEntityMap = new Map<string, string>(); serviceEntityMap.set('testservice', 'testservice-green'); kubeCtl.getResource = jest.fn().mockReturnValue(JSON.parse(JSON.stringify(temp))); //Invoke and assert expect(blueGreenHelperIngress.validateIngressesState(kubeCtl, ingEntList, serviceEntityMap)).toBeFalsy(); }); test("validateTrafficSplitState - throws if trafficsplit in wrong state", () => { const kubeCtl: jest.Mocked < Kubectl > = new Kubectl("") as any; let temp = { stdout: JSON.stringify({ "apiVersion": "split.smi-spec.io/v1alpha2", "kind": "TrafficSplit", "metadata": { "name": "testservice-trafficsplit" }, "spec": { "service": "testservice", "backends": [{ "service": "testservice-stable", "weight": 100 }, { "service": "testservice-green", "weight": 0 } ] } }) } const depEntList = [{ "apiVersion": "apps/v1beta1", "kind": "Deployment", "metadata": { "name": "testapp", }, "spec": { "selector": { "matchLabels": { "app": "testapp", } }, "replicas": 1, "template": { "metadata": { "labels": { "app": "testapp", } }, "spec": { "containers": [{ "name": "testapp", "image": "testcr.azurecr.io/testapp", "ports": [{ "containerPort": 80 }] }] } } } }]; const serEntList = [{ "apiVersion": "v1", "kind": "Service", "metadata": { "name": "testservice" }, "spec": { "selector": { "app": "testapp", }, "ports": [{ "protocol": "TCP", "port": 80, "targetPort": 80 }] } }]; kubeCtl.getResource = jest.fn().mockReturnValue(JSON.parse(JSON.stringify(temp))); //Invoke and assert expect(blueGreenHelperSMI.validateTrafficSplitsState(kubeCtl, serEntList)).toBeFalsy(); }); test("validateTrafficSplitState - throws if trafficsplit in wrong state", () => { const kubeCtl: jest.Mocked < Kubectl > = new Kubectl("") as any; let temp = { stdout: JSON.stringify({ "apiVersion": "split.smi-spec.io/v1alpha2", "kind": "TrafficSplit", "metadata": { "name": "testservice-trafficsplit" }, "spec": { "service": "testservice", "backends": [{ "service": "testservice-stable", "weight": 0 }, { "service": "testservice-green", "weight": 0 } ] } }) } const depEntList = [{ "apiVersion": "apps/v1beta1", "kind": "Deployment", "metadata": { "name": "testapp", }, "spec": { "selector": { "matchLabels": { "app": "testapp", } }, "replicas": 1, "template": { "metadata": { "labels": { "app": "testapp", } }, "spec": { "containers": [{ "name": "testapp", "image": "testcr.azurecr.io/testapp", "ports": [{ "containerPort": 80 }] }] } } } }]; const serEntList = [{ "apiVersion": "v1", "kind": "Service", "metadata": { "name": "testservice" }, "spec": { "selector": { "app": "testapp", }, "ports": [{ "protocol": "TCP", "port": 80, "targetPort": 80 }] } }]; kubeCtl.getResource = jest.fn().mockReturnValue(JSON.parse(JSON.stringify(temp))); //Invoke and assert expect(blueGreenHelperSMI.validateTrafficSplitsState(kubeCtl, serEntList)).toBeFalsy(); }); test("getSuffix() - returns BLUE_GREEN_SUFFIX if BLUE_GREEN_NEW_LABEL_VALUE is given, else emrty string", () => { expect(blueGreenHelper.getSuffix('green')).toBe('-green'); }); test("getSuffix() - returns BLUE_GREEN_SUFFIX if BLUE_GREEN_NEW_LABEL_VALUE is given, else emrty string", () => { expect(blueGreenHelper.getSuffix('random')).toBe(''); }); test("getServiceSpacLabel() - returns empty string if BLUE_GREEN_VERSION_LABEL in spec selector doesn't exist", () => { let input = { "apiVersion": "apps/v1", "kind": "Deployment", "metadata": { "name": "sample-deployment" }, "spec": { "selector": { "matchLabels": { "app": "sample", "k8s.deploy.color": "green" } }, "template": { "metadata": { "labels": { "app": "sample" }, "annotations": { "prometheus.io/scrape": "true", "prometheus.io/port": "8888" } }, "spec": { "containers": [{ "name": "sample", "image": "tsugunt/sample:v34", "ports": [{ "containerPort": 8888 }] }] } } } } expect(blueGreenHelperService.getServiceSpecLabel(input)).toBe(''); }); test("getDeploymentMatchLabels() - return false is input doesnt have matchLabels", () => { let input = { "apiVersion": "v1", "kind": "Service", "metadata": { "name": "sample-service" }, "spec": { "selector": { "app": "sample", "k8s.deploy.color": "green" }, "ports": [{ "protocol": "TCP", "port": 80, "targetPort": 8888, "nodePort": 31002 }], "type": "NodePort" } } expect(blueGreenHelper.getDeploymentMatchLabels(input)).toBeFalsy(); }); test("getServiceSelector() - return false if spec selector does not exist", () => { let input = { "apiVersion": "networking.k8s.io/v1beta1", "kind": "Ingress", "metadata": { "name": "test-ingress", "annotations": { "nginx.ingress.kubernetes.io/rewrite-target": "/" } }, "spec": { "rules": [{ "http": { "paths": [{ "path": "/testpath", "pathType": "Prefix", "backend": { "serviceName": "test", "servicePort": 80 } }] } }] } } expect(blueGreenHelper.getServiceSelector(input)).toBeFalsy(); });
the_stack
import nock from "nock"; import {createClient} from "../__mocks__/base"; import Modification from "../services/modification"; import Client from "../client"; import { CreatePaymentAmountUpdateRequest, CreatePaymentCancelRequest, CreatePaymentCaptureRequest, CreatePaymentRefundRequest, CreatePaymentReversalRequest, CreateStandalonePaymentCancelRequest, PaymentAmountUpdateResource, PaymentCancelResource, PaymentCaptureResource, PaymentRefundResource, PaymentReversalResource, StandalonePaymentCancelResource } from "../typings/checkout/models"; const invalidModificationResult = { "status": 422, "errorCode": "167", "message": "Original pspReference required for this operation", "errorType": "validation" }; const createAmountUpdateRequest = (): CreatePaymentAmountUpdateRequest => { return { reference: "863620292981235A", merchantAccount: process.env.ADYEN_MERCHANT!, amount: { currency: "EUR", value: 420 }, reason: CreatePaymentAmountUpdateRequest.ReasonEnum.DelayedCharge }; }; const createAmountUpdateResponse = (): PaymentAmountUpdateResource => { return { paymentPspReference: "863620292981235A", pspReference: "863620292981235B", reference: "reference", merchantAccount: process.env.ADYEN_MERCHANT!, amount: { currency: "EUR", value: 420, }, reason: CreatePaymentAmountUpdateRequest.ReasonEnum.DelayedCharge, status: PaymentAmountUpdateResource.StatusEnum.Received, }; }; const createCancelsRequest = (): CreatePaymentCancelRequest => { return { reference: "863620292981235B", merchantAccount: process.env.ADYEN_MERCHANT!, }; }; const createCancelsResponse = (): PaymentCancelResource => { return { merchantAccount: process.env.ADYEN_MERCHANT!, pspReference: "863620292981235B", paymentPspReference: "863620292981235A", status: PaymentCancelResource.StatusEnum.Received, }; }; const createStandaloneCancelsRequest = (): CreateStandalonePaymentCancelRequest => { return { reference: "reference", merchantAccount: process.env.ADYEN_MERCHANT!, paymentReference: "863620292981235B", }; }; const createStandaloneCancelsResponse = (): StandalonePaymentCancelResource => { return { reference: "reference", merchantAccount: process.env.ADYEN_MERCHANT!, paymentReference: "863620292981235B", pspReference: "863620292981235A", status: StandalonePaymentCancelResource.StatusEnum.Received, }; }; const createCapturesRequest = (): CreatePaymentCaptureRequest => { return { reference: "reference", merchantAccount: process.env.ADYEN_MERCHANT!, amount: { currency: "EUR", value: 420, } }; }; function createCapturesResponse(): PaymentCaptureResource { return { paymentPspReference: "863620292981235A", pspReference: "863620292981235B", reference: "reference", merchantAccount: process.env.ADYEN_MERCHANT!, amount: { currency: "EUR", value: 420, }, status: PaymentCaptureResource.StatusEnum.Received, }; } const createRefundsRequest = (): CreatePaymentRefundRequest => { return { merchantAccount: process.env.ADYEN_MERCHANT!, amount: { currency: "EUR", value: 420, } }; }; const createRefundsResponse = (): PaymentRefundResource => { return { paymentPspReference: "863620292981235A", pspReference: "863620292981235B", reference: "reference", merchantAccount: process.env.ADYEN_MERCHANT!, amount: { currency: "EUR", value: 420, }, status: PaymentRefundResource.StatusEnum.Received, }; }; const createReversalsRequest = (): CreatePaymentReversalRequest => { return { merchantAccount: process.env.ADYEN_MERCHANT! }; }; const createReversalsResponse = (): PaymentReversalResource => { return { paymentPspReference: "863620292981235A", pspReference: "863620292981235B", reference: "reference", merchantAccount: process.env.ADYEN_MERCHANT!, status: PaymentRefundResource.StatusEnum.Received, }; }; let client: Client; let modification: Modification; let scope: nock.Scope; const paymentPspReference = "863620292981235A"; const invalidPaymentPspReference = "invalid_psp_reference"; const isCI = process.env.CI === "true" || (typeof process.env.CI === "boolean" && process.env.CI); beforeEach((): void => { if (!nock.isActive()) { nock.activate(); } client = createClient(); modification = new Modification(client); scope = nock(`${client.config.checkoutEndpoint}/${Client.CHECKOUT_API_VERSION}`); }); afterEach(() => { nock.cleanAll(); }); describe("Modification", (): void => { test.each([isCI, true])("should perform an amount update request, isMock: %p", async (isMock): Promise<void> => { !isMock && nock.restore(); const request = createAmountUpdateRequest(); scope.post(`/payments/${paymentPspReference}/amountUpdates`) .reply(200, createAmountUpdateResponse()); try { const result = await modification.amountUpdates(paymentPspReference, request); expect(result).toBeTruthy(); } catch (e: any) { fail(e.message); } }); test.each([false, true])("should fail to perform an amount update request, isMock: %p", async (isMock): Promise<void> => { !isMock && nock.restore(); expect.assertions(2); const request = createAmountUpdateRequest(); scope.post(`/payments/${invalidPaymentPspReference}/amountUpdates`) .reply(422, invalidModificationResult); try { await modification.amountUpdates(invalidPaymentPspReference, request); } catch (e: any) { expect(e.statusCode).toBe(422); expect(e.message).toContain("Original pspReference required for this operation"); } }); test.each([isCI, true])("should perform a cancels request, isMock: %p", async (isMock): Promise<void> => { !isMock && nock.restore(); const request = createCancelsRequest(); scope.post(`/payments/${paymentPspReference}/cancels`) .reply(200, createCancelsResponse()); try { const result = await modification.cancels(paymentPspReference, request); expect(result).toBeTruthy(); } catch (e: any) { fail(e.message); } }); test.each([false, true])("should fail to perform a cancels request, isMock: %p", async (isMock): Promise<void> => { !isMock && nock.restore(); expect.assertions(2); const request = createCancelsRequest(); scope.post(`/payments/${invalidPaymentPspReference}/cancels`) .reply(422, invalidModificationResult); try { await modification.cancels(invalidPaymentPspReference, request); } catch (e: any) { expect(e.statusCode).toBe(422); expect(e.message).toContain("Original pspReference required for this operation"); } }); test.each([isCI, true])("should perform a standalone cancels request, isMock: %p", async (isMock): Promise<void> => { !isMock && nock.restore(); const request = createStandaloneCancelsRequest(); scope.post("/cancels") .reply(200, createStandaloneCancelsResponse()); try { const result = await modification.cancelsStandalone(request); expect(result).toBeTruthy(); } catch (e: any) { fail(e.message); } }); test.each([isCI, true])("should perform a captures request, isMock: %p", async (isMock): Promise<void> => { !isMock && nock.restore(); const request = createCapturesRequest(); scope.post(`/payments/${paymentPspReference}/captures`) .reply(200, createCapturesResponse()); try { const result = await modification.captures(paymentPspReference, request); expect(result).toBeTruthy(); } catch (e: any) { fail(e.message); } }); test.each([false, true])("should fail to perform a captures request, isMock: %p", async (isMock): Promise<void> => { !isMock && nock.restore(); expect.assertions(2); const request = createCapturesRequest(); scope.post(`/payments/${invalidPaymentPspReference}/captures`) .reply(422, invalidModificationResult); try { await modification.captures(invalidPaymentPspReference, request); } catch (e: any) { expect(e.statusCode).toBe(422); expect(e.message).toContain("Original pspReference required for this operation"); } }); test.each([isCI, true])("should perform a refunds request, isMock: %p", async (isMock): Promise<void> => { !isMock && nock.restore(); const request = createRefundsRequest(); scope.post(`/payments/${paymentPspReference}/refunds`) .reply(200, createRefundsResponse()); try { const result = await modification.refunds(paymentPspReference, request); expect(result).toBeTruthy(); } catch (e: any) { fail(e.message); } }); test.each([false, true])("should fail to perform a refunds request, isMock: %p", async (isMock): Promise<void> => { !isMock && nock.restore(); expect.assertions(2); const request = createRefundsRequest(); scope.post(`/payments/${invalidPaymentPspReference}/refunds`) .reply(422, invalidModificationResult); try { await modification.refunds(invalidPaymentPspReference, request); } catch (e: any) { expect(e.statusCode).toBe(422); expect(e.message).toContain("Original pspReference required for this operation"); } }); test.each([isCI, true])("should perform a reversals request, isMock: %p", async (isMock): Promise<void> => { !isMock && nock.restore(); const request = createReversalsRequest(); scope.post(`/payments/${paymentPspReference}/reversals`) .reply(200, createReversalsResponse()); try { const result = await modification.reversals(paymentPspReference, request); expect(result).toBeTruthy(); } catch (e: any) { fail(e.message); } }); test.each([false, true])("should fail to perform a reversals request, isMock: %p", async (isMock): Promise<void> => { !isMock && nock.restore(); expect.assertions(2); const request = createReversalsRequest(); scope.post(`/payments/${invalidPaymentPspReference}/reversals`) .reply(422, invalidModificationResult); try { await modification.reversals(invalidPaymentPspReference, request); } catch (e: any) { expect(e.statusCode).toBe(422); expect(e.message).toContain("Original pspReference required for this operation"); } }); });
the_stack
import 'chrome://resources/cr_elements/cr_button/cr_button.m.js'; import 'chrome://resources/polymer/v3_0/iron-icon/iron-icon.js'; import 'chrome://resources/polymer/v3_0/iron-iconset-svg/iron-iconset-svg.js'; import '/common/icons.js'; import './styles.js'; import {loadTimeData} from 'chrome://resources/js/load_time_data.m.js'; import {html} from 'chrome://resources/polymer/v3_0/polymer/polymer_bundled.min.js'; import {isNonEmptyArray} from '../../common/utils.js'; import {CurrentWallpaper, WallpaperLayout, WallpaperObserverInterface, WallpaperObserverReceiver, WallpaperProviderInterface, WallpaperType} from '../personalization_app.mojom-webui.js'; import {Paths} from '../personalization_router_element.js'; import {WithPersonalizationStore} from '../personalization_store.js'; import {getWallpaperLayoutEnum} from '../utils.js'; import {beginLoadSelectedImageAction, setSelectedImageAction} from './wallpaper_actions.js'; import {getDailyRefreshCollectionId, setCustomWallpaperLayout, setDailyRefreshCollectionId, updateDailyRefreshWallpaper} from './wallpaper_controller.js'; import {getWallpaperProvider} from './wallpaper_interface_provider.js'; let setTimeout = window.setTimeout; let clearTimeout = window.clearTimeout; export function mockTimeoutForTesting(mock: { setTimeout: typeof window.setTimeout, clearTimeout: typeof window.clearTimeout, }) { setTimeout = mock.setTimeout; clearTimeout = mock.clearTimeout; } /** * Set up the observer to listen for wallpaper changes. */ function initWallpaperObserver( wallpaperProvider: WallpaperProviderInterface, target: WallpaperObserverInterface): WallpaperObserverReceiver { const receiver = new WallpaperObserverReceiver(target); wallpaperProvider.setWallpaperObserver(receiver.$.bindNewPipeAndPassRemote()); return receiver; } /** * Wallpaper images sometimes have a resolution suffix appended to the end of * the image. This is typically to fetch a high resolution image to show as the * user's wallpaper. We do not want the full resolution here, so remove the * suffix to get a 512x512 preview. * TODO(b/186807814) support different resolution parameters here. */ function removeHighResolutionSuffix(url: string): string { return url.replace(/=w\d+$/, ''); } /** * Returns whether the given URL starts with http:// or https://. */ function hasHttpScheme(url: string): boolean { return url.startsWith('http://') || url.startsWith('https://'); } export class WallpaperSelected extends WithPersonalizationStore { static get is() { return 'wallpaper-selected'; } static get template() { return html`{__html_template__}`; } static get properties() { return { /** * The current collection id to display. */ collectionId: String, /** * The current path of the page. */ path: String, image_: { type: Object, observer: 'onImageChanged_', }, imageTitle_: { type: String, computed: 'computeImageTitle_(image_, dailyRefreshCollectionId_)', }, imageOtherAttribution_: { type: Array, computed: 'computeImageOtherAttribution_(image_)', }, dailyRefreshCollectionId_: String, isLoading_: Boolean, hasError_: { type: Boolean, computed: 'computeHasError_(image_, isLoading_, error_)', }, showImage_: { type: Boolean, computed: 'computeShowImage_(image_, isLoading_)', }, showWallpaperOptions_: { type: Boolean, computed: 'computeShowWallpaperOptions_(image_, path)', }, showCollectionOptions_: { type: Boolean, computed: 'computeShowCollectionOptions_(path)', }, showRefreshButton_: { type: Boolean, computed: 'isDailyRefreshCollectionId_(collectionId,dailyRefreshCollectionId_)', }, dailyRefreshIcon_: { type: String, computed: 'computeDailyRefreshIcon_(collectionId,dailyRefreshCollectionId_)', }, ariaPressed_: { type: String, computed: 'computeAriaPressed_(collectionId,dailyRefreshCollectionId_)', }, fillIcon_: { type: String, computed: 'computeFillIcon_(image_)', }, centerIcon_: { type: String, computed: 'computeCenterIcon_(image_)', }, error_: { type: String, value: null, }, showPreviewButton_: { type: Boolean, value() { return loadTimeData.getBoolean('fullScreenPreviewEnabled'); } } }; } collectionId: string; path: string; private image_: CurrentWallpaper|null; private imageTitle_: string; private imageOtherAttribution_: string[]; private dailyRefreshCollectionId_: string|null; private isLoading_: boolean; private hasError_: boolean; private showImage_: boolean; private showWallpaperOptions_: boolean; private showCollectionOptions_: boolean; private showRefreshButton_: boolean; private dailyRefreshIcon_: string; private ariaPressed_: string; private fillIcon_: string; private centerIcon_: string; private error_: string; private showPreviewButton_: boolean; private wallpaperProvider_: WallpaperProviderInterface; private wallpaperObserver_: WallpaperObserverReceiver|null; private initialLoadTimeout_: number|null; constructor() { super(); this.wallpaperProvider_ = getWallpaperProvider(); this.wallpaperObserver_ = null; } connectedCallback() { super.connectedCallback(); this.dispatch(beginLoadSelectedImageAction()); this.wallpaperObserver_ = initWallpaperObserver(this.wallpaperProvider_, this); this.watch('error_', state => state.error); this.watch('image_', state => state.wallpaper.currentSelected); this.watch( 'isLoading_', state => state.wallpaper.loading.setImage > 0 || state.wallpaper.loading.selected || state.wallpaper.loading.refreshWallpaper); this.watch( 'dailyRefreshCollectionId_', state => state.wallpaper.dailyRefresh.collectionId); this.updateFromStore(); getDailyRefreshCollectionId(this.wallpaperProvider_, this.getStore()); /** * Set a 2 minute timer. If no wallpaper information has been received by * then, dispatch a failure state. * @type {?number} */ this.initialLoadTimeout_ = setTimeout(() => { // If still loading the initial currently selected wallpaper image after // 120 seconds, consider this an error and update the store. this.dispatch(setSelectedImageAction(null)); this.initialLoadTimeout_ = null; }, 120 * 1000); } disconnectedCallback() { if (this.wallpaperObserver_) { this.wallpaperObserver_.$.close(); } } /** * Called when the wallpaper changes. */ onWallpaperChanged(currentWallpaper: CurrentWallpaper|null) { // Ignore updates while in fullscreen preview mode. The attribution // information is for the old (non-preview) wallpaper. This is because // setting an image in preview mode updates the image but not the stored // WallpaperInfo. The wallpaper app should treat the duration of preview // mode as loading. Another onWallpaperChanged will fire when preview mode // is canceled or confirmed. if (this.getState().wallpaper.fullscreen) { return; } // Clear the initial load timer if wallpaper information is received. if (this.initialLoadTimeout_) { clearTimeout(this.initialLoadTimeout_); this.initialLoadTimeout_ = null; } this.dispatch(setSelectedImageAction(currentWallpaper)); // Daily Refresh state should also get updated when wallpaper changes. getDailyRefreshCollectionId(this.wallpaperProvider_, this.getStore()); } /** * Return a chrome://image or data:// url to load the image safely. Returns * empty string in case |image| is null or invalid. */ private getImageSrc_(image: CurrentWallpaper|null): string { if (image && image.url) { if (hasHttpScheme(image.url.url)) { return `chrome://image?${removeHighResolutionSuffix(image.url.url)}`; } return image.url.url; } return ''; } private computeShowImage_(image: CurrentWallpaper|null, loading: boolean): boolean { // Specifically check === false to avoid undefined case while component is // initializing. return loading === false && !!image; } private computeImageTitle_( image: CurrentWallpaper|null, dailyRefreshCollectionId: string): string { if (!image) { return this.i18n('unknownImageAttribution'); } if (isNonEmptyArray(image.attribution)) { const title = image.attribution[0]; return dailyRefreshCollectionId ? this.i18n('dailyRefresh') + ': ' + title : title; } else { // Fallback to cached attribution. const attribution = this.getLocalStorageAttribution(image.key); if (isNonEmptyArray(attribution)) { const title = attribution[0]; return dailyRefreshCollectionId ? this.i18n('dailyRefresh') + ': ' + title : title; } } return this.i18n('unknownImageAttribution'); } private computeImageOtherAttribution_(image: CurrentWallpaper| null): string[] { if (!image) { return []; } if (isNonEmptyArray(image.attribution)) { return image.attribution.slice(1); } // Fallback to cached attribution. const attribution = this.getLocalStorageAttribution(image.key); if (isNonEmptyArray(attribution)) { return attribution.slice(1); } return []; } private computeShowWallpaperOptions_( image: CurrentWallpaper|null, path: string): boolean { return !!image && image.type === WallpaperType.kCustomized && path === Paths.LocalCollection; } private computeShowCollectionOptions_(path: string): boolean { return path === Paths.CollectionImages; } private getCenterAriaPressed_(image: CurrentWallpaper): string { return (!!image && image.layout === WallpaperLayout.kCenter).toString(); } private getFillAriaPressed_(image: CurrentWallpaper): string { return (!!image && image.layout === WallpaperLayout.kCenterCropped) .toString(); } private computeFillIcon_(image: CurrentWallpaper): string { if (!!image && image.layout === WallpaperLayout.kCenterCropped) { return 'personalization:checkmark'; } return 'personalization:layout_fill'; } private computeCenterIcon_(image: CurrentWallpaper): string { if (!!image && image.layout === WallpaperLayout.kCenter) { return 'personalization:checkmark'; } return 'personalization:layout_center'; } private onClickLayoutIcon_(event: Event) { const eventTarget = event.currentTarget as HTMLElement; const layout = getWallpaperLayoutEnum(eventTarget.dataset['layout']!); setCustomWallpaperLayout(layout, this.wallpaperProvider_, this.getStore()); } private computeDailyRefreshIcon_( collectionId: string, dailyRefreshCollectionId: string): string { if (this.isDailyRefreshCollectionId_( collectionId, dailyRefreshCollectionId)) { return 'personalization:checkmark'; } return 'personalization:change-daily'; } private computeAriaPressed_( collectionId: string, dailyRefreshCollectionId: string): string { if (this.isDailyRefreshCollectionId_( collectionId, dailyRefreshCollectionId)) { return 'true'; } return 'false'; } private onClickDailyRefreshToggle_(event: Event) { const eventTarget = event.currentTarget as HTMLElement; const collectionId = eventTarget.dataset['collectionId']; const dailyRefreshCollectionId = eventTarget.dataset['dailyRefreshCollectionId']; const isDailyRefreshCollectionId = this.isDailyRefreshCollectionId_( collectionId!, dailyRefreshCollectionId!); setDailyRefreshCollectionId( isDailyRefreshCollectionId ? '' : collectionId!, this.wallpaperProvider_, this.getStore()); // Only refresh the wallpaper if daily refresh is toggled on. if (!isDailyRefreshCollectionId) { updateDailyRefreshWallpaper(this.wallpaperProvider_, this.getStore()); } } /** * Determine the current collection view belongs to the collection that is * enabled with daily refresh. If true, highlight the toggle and display the * refresh button */ private isDailyRefreshCollectionId_( collectionId: string, dailyRefreshCollectionId: string): boolean { return collectionId === dailyRefreshCollectionId; } private onClickUpdateDailyRefreshWallpaper_() { updateDailyRefreshWallpaper(this.wallpaperProvider_, this.getStore()); } /** * Determine whether there is an error in showing selected image. An error * happens when there is no previously loaded image and either no new image * is being loaded or there is an error from upstream. */ private computeHasError_( image: CurrentWallpaper|null, loading: boolean, error: string|null): boolean { return (!loading || !!error) && !image; } private getAriaLabel_(image: CurrentWallpaper|null): string { if (!image) { return this.i18n('currentlySet') + ' ' + this.i18n('unknownImageAttribution'); } if (isNonEmptyArray(image.attribution)) { return [this.i18n('currentlySet'), ...image.attribution].join(' '); } // Fallback to cached attribution. const attribution = this.getLocalStorageAttribution(image.key); if (isNonEmptyArray(attribution)) { return [this.i18n('currentlySet'), ...attribution].join(' '); } return this.i18n('currentlySet') + ' ' + this.i18n('unknownImageAttribution'); } /** * Returns hidden state of loading placeholder. */ private showPlaceholders_(loading: boolean, showImage: boolean): boolean { return loading || !showImage; } /** * Cache the attribution in local storage when image is updated * Populate the attribution map in local storage when image is updated */ private async onImageChanged_( newImage: CurrentWallpaper|null, oldImage: CurrentWallpaper|null) { const attributionMap = JSON.parse((window.localStorage['attribution'] || '{}')); if (attributionMap.size == 0 || !!newImage && !!oldImage && newImage.key !== oldImage.key) { if (newImage) { attributionMap[newImage.key] = newImage.attribution; } if (oldImage) { delete attributionMap[oldImage.key]; } window.localStorage['attribution'] = JSON.stringify(attributionMap); } } getLocalStorageAttribution(key: string): string[] { const attributionMap = JSON.parse((window.localStorage['attribution'] || '{}')); const attribution = attributionMap[key]; if (!attribution) { console.warn('Unable to get attribution from local storage.', key); } return attribution; } /** * Return a container class depending on loading state. */ private getContainerClass_(isLoading: boolean, showImage: boolean): string { return this.showPlaceholders_(isLoading, showImage) ? 'loading' : ''; } } customElements.define(WallpaperSelected.is, WallpaperSelected);
the_stack
import { AbstractInputProps } from "../../input"; import { Box } from "../../box"; import { ButtonPresets } from "./ButtonPresets"; import { ChangeEvent, ComponentProps, FocusEvent, KeyboardEvent, SyntheticEvent, forwardRef, useCallback, useImperativeHandle, useMemo, useRef, useState } from "react"; import { ClearInputGroupContext, InputGroup, useInputGroupProps } from "../../input-group"; import { CrossButton } from "../../button"; import { DateInputMask, useDateInput } from "./useDateInput"; import { Divider } from "../../divider"; import { HtmlInput } from "../../html"; import { Keys, OmitInternalProps, augmentElement, cssModule, isNil, isNilOrEmpty, isNumber, mergeProps, omitProps, useAutoFocus, useControllableState, useDisposables, useEventCallback, useFocusWithin, useMergedRefs } from "../../shared"; import { MenuPresets } from "./MenuPresets"; import { ResponsiveProp, useResponsiveValue } from "../../styling"; import { areEqualDates, toMidnightDate } from "./dateUtils"; import { useFieldInputProps } from "../../field"; import { useToolbarProps } from "../../toolbar"; export interface DateRangePreset { endDate: Date; startDate: Date; text: string; } const DefaultElement = "div"; export interface InnerDateRangeInputProps extends Omit<AbstractInputProps<typeof DefaultElement>, "max" | "min"> { /* eslint-disable typescript-sort-keys/interface */ /** * The initial value of start date. */ defaultStartDate?: Date; /** * The initial value of end date. */ defaultEndDate?: Date; /** * A controlled start date value. */ startDate?: Date | null; /** * A controlled end date value. */ endDate?: Date | null; /** * Whether or not the input is disabled. */ disabled?: boolean; /* eslint-enable typescript-sort-keys/interface */ /** * Whether or not the input take up the width of its container. */ fluid?: ResponsiveProp<boolean>; /** * The maximum (inclusive) date. */ max?: Date; /** * The minimum (inclusive) date. */ min?: Date; /** * @ignore */ name?: string; /** * Called when the date(s) are / is applied. * @param {SyntheticEvent} event - React's original event. * @param {Object} startDate - Selected start date. * @param {Object} endDate - Selected end date. * @returns {void} */ onDatesChange?: (event: SyntheticEvent, startDate: Date, endDate: Date) => void; /** * Temporary text that occupies both date inputs when they are empty. */ placeholder?: string; /** * Array of pre-determined dates range. */ presets?: DateRangePreset[]; /** * The presets style to use. */ presetsVariant?: "compact" | "expanded"; /** * Whether or not the input is readonly. */ readOnly?: boolean; } const DateInput = forwardRef<HTMLInputElement, any>(({ autoFocus, disabled, max, min, onChange, onDateChange, placeholder = "dd/mm/yyyy", readOnly, required, validationState, value, ...rest }, ref) => { const inputRef = useMergedRefs(ref); useAutoFocus(inputRef, { delay: isNumber(autoFocus) ? autoFocus : undefined, isDisabled: !autoFocus || disabled || readOnly }); const dateProps = useDateInput({ forwardedRef: inputRef, max, min, onChange, onDateChange, value }); return ( <HtmlInput {...mergeProps( rest, { "aria-invalid": validationState === "invalid" ? true : undefined, "aria-required": required ? true : undefined, className: "o-ui-date-range-input-date-input", disabled, placeholder, readOnly, ref: inputRef, type: "text" }, dateProps )} /> ); }); const RangeInput = forwardRef<any, any>((props, ref) => { // eslint-disable-next-line @typescript-eslint/no-unused-vars const [_, isInField] = useFieldInputProps(); const [inputGroupProps, isInGroup] = useInputGroupProps(); const { active, as = "div", autoFocus, disabled, endDate, fluid, focus = false, hover, max, min, name, onBlur, onDatesChange, onFocus, placeholder, readOnly, required, startDate, validationState, ...rest } = mergeProps( props, inputGroupProps ); const [hasFocus, setHasFocus] = useState(focus); const containerRef = useRef<HTMLElement>(); const startDateRef = useRef<HTMLInputElement>(); const endDateRef = useRef<HTMLInputElement>(); const disposables = useDisposables(); useImperativeHandle(ref, () => { const element = containerRef.current; element.focus = () => { startDateRef.current?.focus(); }; return element; }); const handleStartDateChange = useEventCallback((event: ChangeEvent<HTMLInputElement>, newDate) => { if (!isNil(newDate) && !isNil(endDate) && newDate > endDate) { newDate = endDate; } if (!isNil(onDatesChange)) { onDatesChange(event, newDate, endDate); } }); const handleEndDateChange = useEventCallback((event: ChangeEvent<HTMLInputElement>, newDate) => { if (!isNil(newDate) && !isNil(startDate) && newDate < startDate) { newDate = startDate; } if (!isNil(onDatesChange)) { onDatesChange(event, startDate, newDate); } }); const handleStartDateInputValueChange = useEventCallback((event: ChangeEvent<HTMLInputElement>) => { if (event.target.value.length === DateInputMask.length) { // Defering because useDateInput is used in controlled mode and otherwise the value will not be updated when the value is clamped. disposables.requestAnimationFrame(() => { endDateRef.current?.focus(); }); } }); const handleEndDateInputValueChange = useEventCallback((event: ChangeEvent<HTMLInputElement>) => { // @ts-ignore const newCharacter = event.nativeEvent.data; // If the new character is not a digit, we don't want to do anything since the new character will be removed by the mask input. // The digit is test with a regex because this is how our mask input third party is doing it and we want to be consistant. if (/\d/.test(newCharacter)) { if (isNilOrEmpty(event.target.value)) { startDateRef.current?.focus(); } } }); const handleClearDates = useEventCallback((event: SyntheticEvent) => { // Deferring because otherwise the start date will not be blured which might result in not clearing the input properly. disposables.requestAnimationFrame(() => { startDateRef?.current.focus(); }); if (!isNil(onDatesChange)) { onDatesChange(event, null, null); } }); const handleContainerKeyDown = useEventCallback((event: KeyboardEvent) => { if (event.key === Keys.esc) { event.preventDefault(); handleClearDates(event); } }); const handleEndDateKeyDown = useEventCallback((event: KeyboardEvent) => { if (event.key === Keys.backspace) { if (isNilOrEmpty(endDateRef.current?.value)) { startDateRef.current?.focus(); } } }); const focusWithinProps = useFocusWithin({ onBlur: useEventCallback((event: FocusEvent) => { setHasFocus(false); if (!isNil(onBlur)) { onBlur(event); } }), onFocus: useEventCallback((event: FocusEvent) => { setHasFocus(true); if (!isNil(onFocus)) { onFocus(event); } }) }); const hasValue = !isNil(startDate) || !isNil(endDate); return ( <Box {...mergeProps( rest, { as, className: cssModule( "o-ui-date-range-input", validationState, fluid && "fluid", disabled && "disabled", readOnly && "readonly", active && "active", hasFocus && "focus", hover && "hover", isInGroup && "in-group" ), onKeyDown: handleContainerKeyDown, ref: containerRef, role: !isInField ? "group" : undefined }, focusWithinProps )} > <DateInput autoFocus={autoFocus} disabled={disabled} max={max} min={min} name={!isNil(name) ? `${name}-start-date` : undefined} onChange={handleStartDateInputValueChange} onDateChange={handleStartDateChange} placeholder={placeholder} readOnly={readOnly} ref={startDateRef} required={required} validationState={validationState} value={startDate} /> <Divider className="o-ui-date-range-input-divider" orientation="vertical" /> <DateInput disabled={disabled} max={max} min={min} name={!isNil(name) ? `${name}-end-date` : undefined} onChange={handleEndDateInputValueChange} onDateChange={handleEndDateChange} onKeyDown={handleEndDateKeyDown} placeholder={placeholder} readOnly={readOnly} ref={endDateRef} required={required} tabIndex={hasFocus ? 0 : -1} validationState={validationState} value={endDate} /> {hasValue && !disabled && !readOnly && <ClearInputGroupContext> <CrossButton aria-label="Clear dates" className="o-ui-date-range-input-clear-button" condensed onClick={handleClearDates} size="xs" /> </ClearInputGroupContext>} </Box> ); }); export function InnerDateRangeInput(props: InnerDateRangeInputProps) { const [toolbarProps] = useToolbarProps(); const [fieldProps] = useFieldInputProps(); const [inputGroupProps, isInGroup] = useInputGroupProps(); const { active, as = DefaultElement, autoFocus, defaultEndDate, defaultStartDate, disabled, endDate: endDateProp, fluid, focus = false, forwardedRef, hover, max, min, name, onBlur, onDatesChange, onFocus, placeholder, presets, presetsVariant = "compact", readOnly, required, startDate: startDateProp, validationState, ...rest } = mergeProps( props, omitProps(toolbarProps, ["orientation"]), fieldProps, inputGroupProps ); const fluidValue = useResponsiveValue(fluid); const [startDate, setStartDate] = useControllableState(startDateProp, defaultStartDate, null); const [endDate, setEndDate] = useControllableState(endDateProp, defaultEndDate, null); const containerRef = useRef<HTMLElement>(); const rangeRef = useRef<HTMLInputElement>(); useImperativeHandle(forwardedRef, () => { // For presets, used the group container as the ref element. if (!isNil(presets)) { const element = containerRef.current; element.focus = () => { rangeRef.current?.focus(); }; return element; } return rangeRef.current; }); const applyDates = useCallback((event: SyntheticEvent, newStartDate: Date, newEndDate: Date) => { if (!areEqualDates(startDate, newStartDate) || !areEqualDates(endDate, newEndDate)) { setStartDate(newStartDate); setEndDate(newEndDate); if (!isNil(onDatesChange)) { onDatesChange(event, newStartDate, newEndDate); } } }, [onDatesChange, startDate, setStartDate, endDate, setEndDate]); const handleSelectPreset = useEventCallback((event: SyntheticEvent, newIndex: number) => { const preset = presets[newIndex]; if (!isNil(preset)) { applyDates(event, preset.startDate, preset.endDate); } }); const presetsProps = useMemo(() => { if (!isNil(presets)) { const selectedIndex = presets.findIndex(x => areEqualDates(toMidnightDate(x.startDate), toMidnightDate(startDate)) && areEqualDates(toMidnightDate(x.endDate), toMidnightDate(endDate)) ); return { onSelectionChange: handleSelectPreset, selectedIndex: selectedIndex !== -1 ? selectedIndex : undefined, values: presets.map(x => x.text) }; } return null; }, [presets, startDate, endDate, handleSelectPreset]); const rangeMarkup = ( <RangeInput active={active} autoFocus={autoFocus} disabled={disabled} endDate={endDate} fluid={fluidValue} focus={focus} hover={hover} max={max} min={min} name={name} onBlur={onBlur} onDatesChange={applyDates} onFocus={onFocus} placeholder={placeholder} readOnly={readOnly} ref={rangeRef} required={required} startDate={startDate} validationState={validationState} /> ); if (!isNil(presetsProps)) { return presetsVariant === "compact" ? ( <InputGroup {...mergeProps( rest, { as, disabled, fluid: fluidValue, readOnly, ref: containerRef } )} > {rangeMarkup} <MenuPresets {...presetsProps} /> </InputGroup> ) : ( <Box {...mergeProps( rest, { as, className: cssModule( "o-ui-date-range-input-button-presets", fluidValue && "fluid" ), ref: containerRef } )} > {rangeMarkup} {!disabled && !readOnly && ( <ButtonPresets {...presetsProps} /> )} </Box> ); } return ( <ClearInputGroupContext> {augmentElement(rangeMarkup, mergeProps( rest, { as, className: isInGroup ? "o-ui-date-range-input-in-group" : undefined, ref: containerRef } ))} </ClearInputGroupContext> ); } // Cheating here because we want to mimick an input even it's a div. InnerDateRangeInput.defaultElement = "input"; export const DateRangeInput = forwardRef<any, OmitInternalProps<InnerDateRangeInputProps>>((props, ref) => ( <InnerDateRangeInput {...props} forwardedRef={ref} /> )); export type DateRangeInputProps = ComponentProps<typeof DateRangeInput>;
the_stack
import * as path from 'path'; import * as os from 'os'; import { getObject, getString, isBoolean } from '@salesforce/ts-types'; import { fs } from '@salesforce/core'; import * as archiver from 'archiver'; // 3pp import * as BBPromise from 'bluebird'; // Local import { set } from '@salesforce/kit'; import logger = require('../core/logApi'); import * as almError from '../core/almError'; import consts = require('../core/constants'); import StashApi = require('../core/stash'); import Stash = require('../core/stash'); import DeployReport = require('./mdapiDeployReportApi'); import { DeployOptions, mdapiDeployRecentValidation, MetadataTransportInfo } from './mdApiUtil'; const DEPLOY_ERROR_EXIT_CODE = 1; // convert params (lowercase) to expected deploy options (camelcase) const convertParamsToDeployOptions = function ({ rollbackonerror, testlevel, runtests, autoUpdatePackage, checkonly, ignorewarnings, singlepackage, }) { const deployOptions: DeployOptions = {}; deployOptions.rollbackOnError = rollbackonerror; if (testlevel) { deployOptions.testLevel = testlevel; } if (runtests) { deployOptions.runTests = runtests.split(','); } if (autoUpdatePackage) { deployOptions.autoUpdatePackage = autoUpdatePackage; } if (ignorewarnings) { deployOptions.ignoreWarnings = ignorewarnings; } if (checkonly) { deployOptions.checkOnly = checkonly; } if (singlepackage) { deployOptions.singlePackage = true; } return deployOptions; }; /** * API that wraps Metadata API to deploy source - directory or zip - to given org. * * @param force * @constructor */ class MdDeployApi { private readonly scratchOrg: object; private force: any; private logger: any; private timer: any; private _fsStatAsync: any; private _reporter: any; private loggingEnabled: boolean; private readonly stashTarget: string; constructor(org, pollIntervalStrategy?, stashTarget: string = StashApi.Commands.MDAPI_DEPLOY) { this.scratchOrg = org; this.force = org.force; this.logger = logger.child('md-deploy'); this.timer = process.hrtime(); this._fsStatAsync = BBPromise.promisify(fs.stat); // if source:deploy or source:push is the command, create a source report if (stashTarget === Stash.Commands.SOURCE_DEPLOY) { this._reporter = new DeployReport(org, pollIntervalStrategy, Stash.Commands.SOURCE_DEPLOY); } else { // create the default mdapi report this._reporter = new DeployReport(org, pollIntervalStrategy); } this.stashTarget = stashTarget; } _getElapsedTime() { const elapsed = process.hrtime(this.timer); this.timer = process.hrtime(); return (elapsed[0] * 1000 + elapsed[1] / 1000000).toFixed(3); } _zip(dir, zipfile) { const file = path.parse(dir); const outFile = zipfile || path.join(os.tmpdir() || '.', `${file.base}.zip`); const output = fs.createWriteStream(outFile); return new BBPromise((resolve, reject) => { const archive = archiver('zip', { zlib: { level: 9 } }); archive.on('end', () => { this.logger.debug(`${archive.pointer()} bytes written to ${outFile} using ${this._getElapsedTime()}ms`); resolve(outFile); }); archive.on('error', (err) => { this._logError(err); reject(err); }); archive.pipe(output); archive.directory(dir, file.base); archive.finalize(); }); } _log(message) { if (this.loggingEnabled) { this.logger.log(message); } } _logError(message) { if (this.loggingEnabled) { this.logger.error(message); } } _getMetadata({ deploydir, zipfile }) { // either zip root dir or pass given zip filepath return deploydir ? this._zip(deploydir, zipfile) : zipfile; } async _sendMetadata(zipPath, options) { zipPath = path.resolve(zipPath); const zipStream = this._createReadStream(zipPath); // REST is the default unless: // 1. SOAP is specified with the soapdeploy flag on the command // 2. The restDeploy SFDX config setting is explicitly false. if (await MetadataTransportInfo.isRestDeploy(options)) { this._log('*** Deploying with REST ***'); return this.force.mdapiRestDeploy(this.scratchOrg, zipStream, convertParamsToDeployOptions(options)); } else { this._log('*** Deploying with SOAP ***'); return this.force.mdapiSoapDeploy(this.scratchOrg, zipStream, convertParamsToDeployOptions(options)); } } _createReadStream(zipPath) { return fs.createReadStream(zipPath); } deploy(options) { // Logging is enabled if the output is not json and logging is not disabled // set .logginEnabled = true? for source this.loggingEnabled = options.source || options.verbose || (!options.json && !options.disableLogging); options.wait = +(options.wait || consts.DEFAULT_MDAPI_WAIT_MINUTES); // ignoreerrors is a boolean flag and is preferred over the deprecated rollbackonerror flag // KEEP THIS code for legacy with commands calling mdapiDeployApi directly. if (options.ignoreerrors !== undefined) { options.rollbackonerror = !options.ignoreerrors; } else if (options.rollbackonerror !== undefined) { // eslint-disable-next-line no-self-assign options.rollbackonerror = options.rollbackonerror; } else { options.rollbackonerror = true; } if (options.validateddeployrequestid) { return this._doDeployRecentValidation(options); } return this._doDeploy(options); } validate(context) { const options = context.flags; const deploydir = options.deploydir; const zipfile = options.zipfile; const validateddeployrequestid = options.validateddeployrequestid; const validationPromises = []; // Wait must be a number that is greater than zero or equal to -1. const validWaitValue = !isNaN(+options.wait) && (+options.wait === -1 || +options.wait >= 0); if (options.wait && !validWaitValue) { return BBPromise.reject(almError('mdapiCliInvalidWaitError')); } if (options.rollbackonerror && !isBoolean(options.rollbackonerror)) { // This should never get called since rollbackonerror is no longer an options // but keep for legacy. We want to default to true, so anything that isn't false. options.rollbackonerror = options.rollbackonerror.toLowerCase() !== 'false'; } if (!(deploydir || zipfile || validateddeployrequestid)) { return BBPromise.reject(almError('MissingRequiredParameter', 'deploydir|zipfile|validateddeployrequestid')); } if (validateddeployrequestid && !(validateddeployrequestid.length == 18 || validateddeployrequestid.length == 15)) { return BBPromise.reject(almError('mdDeployCommandCliInvalidRequestIdError', validateddeployrequestid)); } try { MetadataTransportInfo.validateExclusiveFlag(options, 'deploydir', 'jobid'); MetadataTransportInfo.validateExclusiveFlag(options, 'zipfile', 'jobid'); MetadataTransportInfo.validateExclusiveFlag(options, 'checkonly', 'jobid'); MetadataTransportInfo.validateExclusiveFlag(options, 'rollbackonerror', 'ignoreerrors'); MetadataTransportInfo.validateExclusiveFlag(options, 'soapdeploy', 'jobid'); } catch (e) { return BBPromise.reject(e); } // Validate required options if (deploydir) { // Validate that the deploy root is a directory. validationPromises.push( this._validateFileStat( deploydir, (fileData) => fileData.isDirectory(), BBPromise.resolve, almError('InvalidArgumentDirectoryPath', ['deploydir', deploydir]) ) ); } else if (zipfile) { // Validate that the zipfile is a file. validationPromises.push( this._validateFileStat( zipfile, (fileData) => fileData.isFile(), BBPromise.resolve, almError('InvalidArgumentFilePath', ['zipfile', zipfile]) ) ); } return BBPromise.all(validationPromises).then(() => BBPromise.resolve(options)); } // Accepts: // pathToValidate: a file path to validate // validationFunc: function that is called with the result of a fs.stat(), should return true or false // successFunc: function that returns a promise. // error: an Error object that will be thrown if the validationFunc returns false. // Returns: // Successfull Validation: The result of a call to successFunc. // Failed Validation: A rejected promise with the specified error, or a PathDoesNotExist // error if the file read fails. _validateFileStat(pathToValidate, validationFunc, successFunc, error) { return this._fsStatAsync(pathToValidate) .then((data) => { if (validationFunc(data)) { return successFunc(); } else { return BBPromise.reject(error); } }) .catch((err) => { err = err.code === 'ENOENT' ? almError('PathDoesNotExist', pathToValidate) : err; return BBPromise.reject(err); }); } async _doDeployStatus(result, options) { options.deprecatedStatusRequest = options.jobid ? true : false; options.jobid = options.jobid || result.id; if (await MetadataTransportInfo.isRestDeployWithWaitZero(options)) { options.result = result.deployResult; } else { options.result = result; options.result.status = options.result.state; } return this._reporter.report(options); } async _setStashVars(result, options) { await StashApi.setValues( { jobid: result.id, targetusername: options.targetusername, }, this.stashTarget ); return result; } async _doDeploy(options) { try { const zipPath = await this._getMetadata(options); let sendMetadataResponse; if (!options.jobid) { sendMetadataResponse = await this._sendMetadata(zipPath, options); } const stashedVars = await this._setStashVars(sendMetadataResponse, options); const deployStats = await this._doDeployStatus(stashedVars, options); return await this._throwErrorIfDeployFailed(deployStats); } catch (err) { if (err.name === 'sf:MALFORMED_ID') { throw almError('mdDeployCommandCliInvalidJobIdError', options.jobid); } else if ( options.testlevel !== 'NoTestRun' && getObject(err, 'result.details.runTestResult') && getString(err, 'result.details.runTestResult.numFailures') !== '0' ) { // if the deployment was running tests, and there were test failures err.name = 'testFailure'; throw err; } else { throw err; } } } async _doDeployRecentValidation(options) { let result; try { if (!options.jobid) { const body = await mdapiDeployRecentValidation(this.scratchOrg, options); result = {}; result.id = body; result.state = 'Queued'; } result = await this._setStashVars(result, options); result = await this._doDeployStatus(result, options); this._throwErrorIfDeployFailed(result); return result; } catch (err) { if (err.name === 'sf:MALFORMED_ID') { throw almError('mdDeployCommandCliInvalidJobIdError', options.jobid); } else { throw err; } } } _throwErrorIfDeployFailed(result) { if (['Failed', 'Canceled'].includes(result.status)) { const err = result.status === 'Canceled' ? almError('mdapiDeployCanceled') : almError('mdapiDeployFailed'); this._setExitCode(DEPLOY_ERROR_EXIT_CODE); set(err, 'result', result); return BBPromise.reject(err); } return BBPromise.resolve(result); } _setExitCode(code) { process.exitCode = code; } _minToMs(min) { return min * 60000; } } export = MdDeployApi;
the_stack
import DisplayObjectContainer from "./../../starling/display/DisplayObjectContainer"; import BitmapFont from "./../../starling/text/BitmapFont"; import Starling from "./../../starling/core/Starling"; import RectangleUtil from "./../../starling/utils/RectangleUtil"; import ArgumentError from "openfl/errors/ArgumentError"; import Sprite from "./../../starling/display/Sprite"; import Quad from "./../../starling/display/Quad"; import Matrix from "openfl/geom/Matrix"; import TrueTypeCompositor from "./../../starling/text/TrueTypeCompositor"; import SystemUtil from "./../../starling/utils/SystemUtil"; import Rectangle from "openfl/geom/Rectangle"; import TextFormat from "./../../starling/text/TextFormat"; import TextOptions from "./../../starling/text/TextOptions"; import MeshBatch from "./../../starling/display/MeshBatch"; import Painter from "./../rendering/Painter"; import DisplayObject from "./../display/DisplayObject"; import Point from "openfl/geom/Point"; import MeshStyle from "./../styles/MeshStyle"; import ITextCompositor from "./ITextCompositor"; declare namespace starling.text { /** A TextField displays text, using either standard true type fonts, custom bitmap fonts, * or a custom text representation. * * <p>Access the <code>format</code> property to modify the appearance of the text, like the * font name and size, a color, the horizontal and vertical alignment, etc. The border property * is useful during development, because it lets you see the bounds of the TextField.</p> * * <p>There are several types of fonts that can be displayed:</p> * * <ul> * <li>Standard TrueType fonts. This renders the text just like a conventional Flash * TextField. It is recommended to embed the font, since you cannot be sure which fonts * are available on the client system, and since this enhances rendering quality. * Simply pass the font name to the corresponding property.</li> * <li>Bitmap fonts. If you need speed or fancy font effects, use a bitmap font instead. * That is a font that has its glyphs rendered to a texture atlas. To use it, first * register the font with the method <code>registerBitmapFont</code>, and then pass * the font name to the corresponding property of the text field.</li> * <li>Custom text compositors. Any class implementing the <code>ITextCompositor</code> * interface can be used to render text. If the two standard options are not sufficient * for your needs, such a compositor might do the trick.</li> * </ul> * * <p>For bitmap fonts, we recommend one of the following tools:</p> * * <ul> * <li>Windows: <a href="http://www.angelcode.com/products/bmfont">Bitmap Font Generator</a> * from Angel Code (free). Export the font data as an XML file and the texture as a png * with white characters on a transparent background (32 bit).</li> * <li>Mac OS: <a href="http://glyphdesigner.71squared.com">Glyph Designer</a> from * 71squared or <a href="http://http://www.bmglyph.com">bmGlyph</a> (both commercial). * They support Starling natively.</li> * <li>Cross-Platform: <a href="http://kvazars.com/littera/">Littera</a> or * <a href="http://renderhjs.net/shoebox/">ShoeBox</a> are great tools, as well. * Both are free to use and were built with Adobe AIR.</li> * </ul> * * <p>When using a bitmap font, the 'color' property is used to tint the font texture. This * works by multiplying the RGB values of that property with those of the texture's pixel. * If your font contains just a single color, export it in plain white and change the 'color' * property to any value you like (it defaults to zero, which means black). If your font * contains multiple colors, change the 'color' property to <code>Color.WHITE</code> to get * the intended result.</p> * * <strong>Batching of TextFields</strong> * * <p>Normally, TextFields will require exactly one draw call. For TrueType fonts, you cannot * avoid that; bitmap fonts, however, may be batched if you enable the "batchable" property. * This makes sense if you have several TextFields with short texts that are rendered one * after the other (e.g. subsequent children of the same sprite), or if your bitmap font * texture is in your main texture atlas.</p> * * <p>The recommendation is to activate "batchable" if it reduces your draw calls (use the * StatsDisplay to check this) AND if the text fields contain no more than about 15-20 * characters. For longer texts, the batching would take up more CPU time than what is saved * by avoiding the draw calls.</p> */ export class TextField extends DisplayObjectContainer { /** Create a new text field with the given properties. */ public constructor(width:number, height:number, text?:string, format?:TextFormat); /** Disposes the underlying texture data. */ public /*override*/ dispose():void; /** @inheritDoc */ public /*override*/ render(painter:Painter):void; /** Forces the text to be recomposed before rendering it in the upcoming frame. Any changes * of the TextField itself will automatically trigger recomposition; changes in its * parents or the viewport, however, need to be processed manually. For example, you * might want to force recomposition to fix blurring caused by a scale factor change. */ public setRequiresRecomposition():void; // properties protected readonly isHorizontalAutoSize:boolean; protected get_isHorizontalAutoSize():boolean; protected readonly isVerticalAutoSize:boolean; protected get_isVerticalAutoSize():boolean; /** Returns the bounds of the text within the text field. */ public readonly textBounds:Rectangle; protected get_textBounds():Rectangle; /** @inheritDoc */ public /*override*/ getBounds(targetSpace:DisplayObject, out?:Rectangle):Rectangle; /** Returns the bounds of the text within the text field in the given coordinate space. */ public getTextBounds(targetSpace:DisplayObject, out?:Rectangle):Rectangle; /** @inheritDoc */ public /*override*/ hitTest(localPoint:Point):DisplayObject; /** @inheritDoc */ protected /*override*/ set_width(value:number):number; /** @inheritDoc */ protected /*override*/ set_height(value:number):number; /** The displayed text. */ public text:string; protected get_text():string; protected set_text(value:string):string; /** The format describes how the text will be rendered, describing the font name and size, * color, alignment, etc. * * <p>Note that you can edit the font properties directly; there's no need to reassign * the format for the changes to show up.</p> * * <listing> * textField:TextField = new TextField(100, 30, "Hello Starling"); * textField.format.font = "Arial"; * textField.format.color = Color.RED;</listing> * * @default Verdana, 12 pt, black, centered */ public format:TextFormat; protected get_format():TextFormat; protected set_format(value:TextFormat):TextFormat; /** The options that describe how the letters of a text should be assembled. * This class basically collects all the TextField's properties that are needed * during text composition. Since an instance of 'TextOptions' is passed to the * constructor, you can pass custom options to the compositor. */ protected readonly options:TextOptions; protected get_options():TextOptions; /** Draws a border around the edges of the text field. Useful for visual debugging. * @default false */ public border:boolean; public get_border():boolean; public set_border(value:boolean):boolean; /** Indicates whether the font size is automatically reduced if the complete text does * not fit into the TextField. @default false */ public autoScale:boolean; protected get_autoScale():boolean; protected set_autoScale(value:boolean):boolean; /** Specifies the type of auto-sizing the TextField will do. * Note that any auto-sizing will implicitly deactivate all auto-scaling. * @default none */ public autoSize:string; protected get_autoSize():string; protected set_autoSize(value:string):string; /** Indicates if the text should be wrapped at word boundaries if it does not fit into * the TextField otherwise. @default true */ public wordWrap:boolean; protected get_wordWrap():boolean; protected set_wordWrap(value:boolean):boolean; /** Indicates if TextField should be batched on rendering. * * <p>This works only with bitmap fonts, and it makes sense only for TextFields with no * more than 10-15 characters. Otherwise, the CPU costs will exceed any gains you get * from avoiding the additional draw call.</p> * * @default false */ public batchable:boolean; protected get_batchable():boolean; protected set_batchable(value:boolean):boolean; /** Indicates if text should be interpreted as HTML code. For a description * of the supported HTML subset, refer to the classic Flash 'TextField' documentation. * Clickable hyperlinks and images are not supported. Only works for * TrueType fonts! @default false */ public isHtmlText:boolean; protected get_isHtmlText():boolean; protected set_isHtmlText(value:boolean):boolean; // #if flash // /** An optional style sheet to be used for HTML text. For more information on style // * sheets, please refer to the StyleSheet class in the ActionScript 3 API reference. // * @default null */ // public styleSheet:StyleSheet; // protected get_styleSheet():StyleSheet; // protected set_styleSheet(value:StyleSheet):StyleSheet; // #end /** Controls whether or not the instance snaps to the nearest pixel. This can prevent the * object from looking blurry when it's not exactly aligned with the pixels of the screen. * @default true */ public pixelSnapping:boolean; protected get_pixelSnapping():boolean; protected set_pixelSnapping(value:boolean):boolean; /** The mesh style that is used to render the text. * Note that a style instance may only be used on one mesh at a time. */ public style:MeshStyle; protected get_style():MeshStyle; protected set_style(value:MeshStyle):MeshStyle; /** The Context3D texture format that is used for rendering of all TrueType texts. * The default provides a good compromise between quality and memory consumption; * use <pre>Context3DTextureFormat.BGRA</pre> for the highest quality. * * @default Context3DTextureFormat.BGRA_PACKED */ public static defaultTextureFormat:string; protected static get_defaultTextureFormat():string; protected static set_defaultTextureFormat(value:string):string; /** The default compositor used to arrange the letters of the text. * If a specific compositor was registered for a font, it takes precedence. * * @default TrueTypeCompositor */ public static defaultCompositor:ITextCompositor; protected static get_defaultCompositor():ITextCompositor; protected static set_defaultCompositor(value:ITextCompositor):ITextCompositor; /** Updates the list of embedded fonts. Call this method when you loaded a TrueType font * at runtime so that Starling can recognize it as such. */ public static updateEmbeddedFonts():void; // compositor registration /** Makes a text compositor (like a <code>BitmapFont</code>) available to any TextField in * the current stage3D context. The font is identified by its <code>name</code> (not * case sensitive). */ public static registerCompositor(compositor:ITextCompositor, name:string):void; /** Unregisters the text compositor and, optionally, disposes it. */ public static unregisterCompositor(name:string, dispose?:boolean):void; /** Returns a registered text compositor (or null, if the font has not been registered). * The name is not case sensitive. */ public static getCompositor(name:string):ITextCompositor; /** Makes a bitmap font available at any TextField in the current stage3D context. * The font is identified by its <code>name</code> (not case sensitive). * Per default, the <code>name</code> property of the bitmap font will be used, but you * can pass a custom name, as well. @return the name of the font. */ // @:deprecated("replaced by `registerCompositor`") public static registerBitmapFont(bitmapFont:BitmapFont, name?:string):string; /** Unregisters the bitmap font and, optionally, disposes it. */ // @:deprecated("replaced by `unregisterCompositor`") public static unregisterBitmapFont(name:string, dispose?:boolean):void; /** Returns a registered bitmap font compositor (or null, if no compositor has been * registered with that name, or if it's not a bitmap font). The name is not case * sensitive. */ public static getBitmapFont(name:string):BitmapFont; } } export default starling.text.TextField;
the_stack
import * as ts from "typescript"; /** * Creates a factory for a ts Transformer that calls the function of a transform visitor. * @param transformVisitor the transform visitor to return * @return the factory */ export function createTransformVisitorFactory(transformVisitor: TransformVisitor): ts.TransformerFactory<ts.SourceFile> { return function(transformationContext: ts.TransformationContext) { return createTransformer(transformVisitor, transformationContext); }; } /** * Creates a transformer for the given transform visitor * @param transformVisitor the transform visitor to wrap * @param transformationContext the transformation context * @return the transformer that wrapps the transform visitor */ export function createTransformer(transformVisitor: TransformVisitor, transformationContext: ts.TransformationContext): ts.Transformer<ts.SourceFile> { const context: TransformVisitorContext = { requestEmitHelper(emitHelper: ts.EmitHelper): void { transformationContext.requestEmitHelper(emitHelper); }, visit<T extends ts.Node>(node: T, visitor?: TransformVisitor): T { visitor = visitor || transformVisitor; const kindName = ts.SyntaxKind[node.kind]; const propertyName = `visit${kindName}`; const visitorFn = (visitor as any) [propertyName] as (node: ts.Node, context: TransformVisitorContext) => ts.VisitResult<ts.Node>; if (visitorFn) { return visitorFn.call(transformVisitor, node, context); } else { return visitor.fallback(node, context); } }, visitEachChild(node: ts.Node, visitor?: TransformVisitor) { // visitEachChild does not like to be called with a function type??? if (node.kind === ts.SyntaxKind.FunctionType) { return node; } return ts.visitEachChild(node, child => context.visit(child, visitor), transformationContext); }, visitLexicalEnvironment(nodes: ts.NodeArray<ts.Statement>, visitor?: TransformVisitor): ts.NodeArray<ts.Statement> { return ts.visitLexicalEnvironment(nodes, child => context.visit(child, visitor), transformationContext); } }; return context.visit; } /** * The Transform visitor has a method for each {@link ts.SyntaxKind} that is called for the nodes of this kind. * For the syntax kinds that are not specially handled (by an explicit method for this syntax kind) are handled * by the fallback method that each visitor implements. * * The second argument of each function is the transform visitor context that can be used to visit child nodes. */ export interface TransformVisitor { /** * Fallback function that is invoked for all the nodes that are not handled by an explicit method for the nodes syntax kind * @param node the node to handle * @param context the transform visitor context */ fallback<T extends ts.Node>(node: T, context: TransformVisitorContext): T; visitAsExpression?(asExpression: ts.AsExpression, context: TransformVisitorContext): ts.VisitResult<ts.Node>; visitAsyncKeyword?(asyncKeyword: ts.Token<ts.SyntaxKind.AsyncKeyword>, context: TransformVisitorContext): ts.VisitResult<ts.Node>; visitArrayLiteralExpression?(arrayLiteralExpression: ts.ArrayLiteralExpression, context: TransformVisitorContext): ts.VisitResult<ts.Node>; visitArrayType?(arrayType: ts.ArrayTypeNode, context: TransformVisitorContext): ts.VisitResult<ts.Node>; visitAwaitExpression?(awaitExpression: ts.AwaitExpression, context: TransformVisitorContext): ts.VisitResult<ts.Node>; visitBinaryExpression?(binaryExpression: ts.BinaryExpression, context: TransformVisitorContext): ts.VisitResult<ts.Node>; visitBlock?(block: ts.Block, context: TransformVisitorContext): ts.VisitResult<ts.Node>; visitBooleanKeyword?(booleanKeyword: ts.Token<ts.SyntaxKind.BooleanKeyword>, context: TransformVisitorContext): ts.VisitResult<ts.Node>; visitBreakStatement?(breakStatement: ts.BreakStatement, context: TransformVisitorContext): ts.VisitResult<ts.Node>; visitCallExpression?(callExpression: ts.CallExpression, context: TransformVisitorContext): ts.VisitResult<ts.Node>; visitClassDeclaration?(classDeclaration: ts.ClassDeclaration, context: TransformVisitorContext): ts.VisitResult<ts.Node>; visitConditionalExpression?(conditionalExpression: ts.ConditionalExpression, context: TransformVisitorContext): ts.VisitResult<ts.Node>; visitConstructor?(constructor: ts.ConstructorDeclaration, context: TransformVisitorContext): ts.VisitResult<ts.Node>; visitContinueStatement?(continueStatement: ts.ContinueStatement, context: TransformVisitorContext): ts.VisitResult<ts.Node>; visitElementAccessExpression?(elementAccessExpression: ts.ElementAccessExpression, context: TransformVisitorContext): ts.VisitResult<ts.Node>; visitExpressionStatement?(expressionStatement: ts.ExpressionStatement, context: TransformVisitorContext): ts.VisitResult<ts.Node>; visitExportKeyword?(exportKeyword: ts.Token<ts.SyntaxKind.ExportKeyword>, context: TransformVisitorContext): ts.VisitResult<ts.Node>; visitFalseKeyword?(falseKeyword: ts.Token<ts.SyntaxKind.FalseKeyword>, context: TransformVisitorContext): ts.VisitResult<ts.Node>; visitFirstLiteralToken?(firstLiteralToken: ts.Token<ts.SyntaxKind.FirstLiteralToken>, context: TransformVisitorContext): ts.VisitResult<ts.Node>; visitForStatement?(forStatement: ts.ForStatement, context: TransformVisitorContext): ts.VisitResult<ts.Node>; visitFunctionDeclaration?(functionDeclaration: ts.FunctionDeclaration, context: TransformVisitorContext): ts.VisitResult<ts.Node>; visitIdentifier?(identifier: ts.Identifier, context: TransformVisitorContext): ts.VisitResult<ts.Node>; visitIfStatement?(ifStatement: ts.IfStatement, context: TransformVisitorContext): ts.VisitResult<ts.Node>; visitIntKeyword?(intKeyword: ts.Token<ts.SyntaxKind.IntKeyword>, context: TransformVisitorContext): ts.VisitResult<ts.Node>; visitMethodDeclaration?(methodDeclaration: ts.MethodDeclaration, context: TransformVisitorContext): ts.VisitResult<ts.Node>; visitNewExpression?(newExpression: ts.NewExpression, context: TransformVisitorContext): ts.VisitResult<ts.Node>; visitNumberKeyword?(keyword: ts.Token<ts.SyntaxKind.NumberKeyword>, context: TransformVisitorContext): ts.VisitResult<ts.Node>; visitParameter?(parameter: ts.ParameterDeclaration, context: TransformVisitorContext): ts.VisitResult<ts.Node>; visitParenthesizedExpression?(parenthesizedExpression: ts.ParenthesizedExpression, context: TransformVisitorContext): ts.VisitResult<ts.Node>; visitPrivateKeyword?(privateKeyword: ts.Token<ts.SyntaxKind.PrivateKeyword>, context: TransformVisitorContext): ts.VisitResult<ts.Node>; visitPublicKeyword?(publicKeyword: ts.Token<ts.SyntaxKind.PublicKeyword>, context: TransformVisitorContext): ts.VisitResult<ts.Node>; visitPrefixUnaryExpression?(prefixUnaryExpression: ts.PrefixUnaryExpression, context: TransformVisitorContext): ts.VisitResult<ts.Node>; visitPropertyAccessExpression?(propertyAccessExpression: ts.PropertyAccessExpression, context: TransformVisitorContext): ts.VisitResult<ts.Node>; visitPropertyDeclaration?(propertyDeclaration: ts.PropertyDeclaration, context: TransformVisitorContext): ts.VisitResult<ts.Node>; visitReturnStatement?(returnStatement: ts.ReturnStatement, context: TransformVisitorContext): ts.VisitResult<ts.Node>; visitSourceFile?(sourceFile: ts.SourceFile, context: TransformVisitorContext): ts.VisitResult<ts.Node>; visitStringLiteral?(stringLiteral: ts.Token<ts.SyntaxKind.StringLiteral>, context: TransformVisitorContext): ts.VisitResult<ts.Node>; visitThisKeyword?(thisKeyword: ts.Token<ts.SyntaxKind.ThisKeyword>, context: TransformVisitorContext): ts.VisitResult<ts.Node>; visitTrueKeyword?(trueKeyword: ts.Token<ts.SyntaxKind.TrueKeyword>, context: TransformVisitorContext): ts.VisitResult<ts.Node>; visitTypeReference?(typeReference: ts.TypeReferenceNode, context: TransformVisitorContext): ts.VisitResult<ts.Node>; visitVariableDeclaration?(variableDeclaration: ts.VariableDeclaration, context: TransformVisitorContext): ts.VisitResult<ts.Node>; visitVariableDeclarationList?(variableDeclarationList: ts.VariableDeclarationList, context: TransformVisitorContext): ts.VisitResult<ts.Node>; visitVariableStatement?(variableStatement: ts.VariableStatement, context: TransformVisitorContext): ts.VisitResult<ts.Node>; visitWhileStatement?(whileStatement: ts.WhileStatement, context: TransformVisitorContext): ts.VisitResult<ts.Node>; visitFunctionType?(functionType: ts.FunctionTypeNode, context: TransformVisitorContext): ts.VisitResult<ts.Node>; } /** * The transform visitor context. * Allows the transform visitor to visit other nodes or all its children */ export interface TransformVisitorContext { /** * Requests a ts emit helper that is to be included in the current source file * @param emitHelper the emit helper to include */ requestEmitHelper(emitHelper: ts.EmitHelper): void; /** * Visits the given node * @param node the node to visit * @param visitor an optional visitor that should be called when visiting this node (by default, the current transform visitor) * @returns the value returned by the visit method of this node */ visit<T extends ts.Node>(node: T, visitor?: TransformVisitor): T; /** * Visits each child of the given node * @param node the node of whom the child nodes are to be visited * @param visitor an optional visitor that should be called when visiting this node (by default, the current transform visitor) * @returns the potentially updated node * @see ts.visitEachChild */ visitEachChild<T extends ts.Node>(node: T, visitor?: TransformVisitor): T; /** * Visits the nodes in a lexical environment * @param nodes the nodes to visit * @param visitor an optional visitor that should be called when visiting this node (by default, the current transform visitor) * @returns the (potentially) updated nodes */ visitLexicalEnvironment(nodes: ts.NodeArray<ts.Statement>, visitor?: TransformVisitor): ts.NodeArray<ts.Statement>; }
the_stack
import { CloneMode, IOptions, Options, WindowID, WindowProperty, WindowType } from "./api.js"; import { getCloneBounds } from "./getCloneBounds.js"; import { getOptions, getStorageWindowPropKey } from "./options-storage.js"; // Helper functions // ----------------------------------------------------------------------------- const getFromId = <T extends HTMLElement>(id: string, root = document) => root.getElementById(id) as T; const getFromClass = <T extends HTMLElement>(className: string, root = document) => Array.from(root.getElementsByClassName(className)) as T[]; const getFromTag = <T extends HTMLElement>(tagName: string, root = document) => Array.from(root.getElementsByTagName(tagName)) as T[]; // window that will be focused on pop-out const getFocusedName = (): WindowID => { const focused = getFromClass<HTMLInputElement>("focus-option").find(option => option.checked); return focused === undefined || focused.id === "focus-original" ? "original" : "new"; }; getOptions().then(options => { // save current state const save = () => { const update: Partial<IOptions> = { focus: getFocusedName(), resizeOriginal: getFromId<HTMLInputElement>("resize-original").checked, copyFullscreen: getFromId<HTMLInputElement>("copy-fullscreen").checked, cloneMode: getFromClass<HTMLInputElement>("clone-mode-option").find(cp => cp.checked)! .id as CloneMode, menuButtonType: getFromClass<HTMLInputElement>("menu-button-option") .find(mb => mb.checked) ?.getAttribute("data-value") as WindowType, }; // dimensions getFromClass("window").forEach(win => { ([ ["offsetWidth", "offsetWidth", "width"], ["offsetHeight", "offsetHeight", "height"], ["offsetLeft", "offsetWidth", "left"], ["offsetTop", "offsetHeight", "top"], ] as const).forEach(([prop, dim, setProp]) => { const windowDimension = win[prop]; const screenDimension = getFromId("screen")[dim]; const value = windowDimension / screenDimension; update[getStorageWindowPropKey(win.id as WindowID, setProp)] = value; }); }); options.update(update); }; // changing draggable/resizable windows, used when radio buttons override // resizing and positioning const updateWindowHandling = (inputId: string, windowId: WindowID, enableIfChecked: boolean) => { const checked = getFromId<HTMLInputElement>(inputId).checked; const action = enableIfChecked === checked ? "enable" : "disable"; const $win = $(`#${windowId}`); $win.draggable(action); $win.resizable(action); }; const updateResizeOriginal = () => { updateWindowHandling("resize-original", "original", true); const originalWin = getFromId("original"); const isResizing = getFromId<HTMLInputElement>("resize-original").checked; isResizing ? originalWin.classList.remove("disabled") : originalWin.classList.add("disabled"); }; const updateResizeNew = () => updateWindowHandling("clone-mode-no", "new", true); const updateClone = () => { const originalWin = getFromId("original"); const newWin = getFromId("new"); newWin.style.width = originalWin.style.width; newWin.style.height = originalWin.style.height; const monitor = getFromId("monitor"); const displayBounds = { left: 0, top: 0, width: monitor.clientWidth, height: monitor.clientHeight, }; const origBounds = { left: originalWin.offsetLeft, top: originalWin.offsetTop, width: originalWin.offsetWidth, height: originalWin.offsetHeight, }; const newBounds = getCloneBounds(origBounds, displayBounds, options.get("cloneMode")); (Object.entries(newBounds) as Array<[WindowProperty, number]>).forEach(([key, value]) => { newWin.style[key] = `${value}px`; }); }; // update appearance of windows depending on if they are active or not const updateFocus = () => { getFromClass("window").forEach(win => { const isBlurred = win.id !== getFocusedName(); isBlurred ? win.classList.add("blurred") : win.classList.remove("blurred"); }); }; const setWindowAsCurrent = (win: HTMLElement) => { getFromClass("window").forEach(_win => { _win === win ? _win.classList.add("current") : _win.classList.remove("current"); }); }; const updateMaxDimensions = () => { const cloneMode = options.get("cloneMode"); const $original = $("#original"); const maxWidth = cloneMode === "clone-mode-horizontal" ? $original.parent().width()! * 0.8 : Infinity; $original.resizable("option", "maxWidth", maxWidth); const maxHeight = cloneMode === "clone-mode-vertical" ? $original.parent().height()! * 0.8 : Infinity; $original.resizable("option", "maxHeight", maxHeight); }; // Main Function // --------------------------------------------------------------------------- // Each chunk has specifically *not* been broken out into a named function // as then it's more difficult to tell when / where they are being called // and if it's more than one const main = (options: Options) => { { // display shortcuts // ----------------------------------------------------------------------- chrome.commands.getAll(cmds => { if (cmds.length === 0) { return; } cmds .filter(cmd => cmd.name !== "_execute_browser_action") .forEach(cmd => { const name = document.createElement("span"); name.textContent = `${cmd.description}:`; name.classList.add("shortcut-label"); const shortcut = document.createElement("span"); shortcut.classList.add("shortcut"); shortcut.textContent = cmd.shortcut!; const li = document.createElement("li"); [name, shortcut].forEach(el => li.appendChild(el)); getFromId("shortcut-list").appendChild(li); }); }); } const gridsize = 20; // px to use for window grid { // Set monitor aspect ratio to match user's // ----------------------------------------------------------------------- const monitor = getFromId("monitor"); const ratio = screen.height / screen.width; const height = Math.round((monitor.clientWidth * ratio) / gridsize) * gridsize; monitor.style.height = `${height}px`; } { // restore options // ----------------------------------------------------------------------- getFromClass<HTMLInputElement>("focus-option").forEach(opt => { opt.checked = opt.id.includes(options.get("focus")); }); getFromId<HTMLInputElement>("resize-original").checked = options.get("resizeOriginal"); const curCloneOption = getFromClass<HTMLInputElement>("clone-mode-option").find( cp => cp.id === options.get("cloneMode"), )!; curCloneOption.checked = true; getFromId<HTMLInputElement>("copy-fullscreen").checked = options.get("copyFullscreen"); getFromClass<HTMLInputElement>("menu-button-option").forEach(opt => { opt.checked = opt.id.includes(options.get("menuButtonType")); }); } { // setup windows // ----------------------------------------------------------------------- getFromClass("window").forEach(win => { // Restore positions from options (["width", "height", "left", "top"] as WindowProperty[]).forEach(prop => { const value = options.get(getStorageWindowPropKey(win.id as WindowID, prop)); win.style[prop] = `${value * 100}%`; }); const grid = (["clientWidth", "clientHeight"] as const).map(d => { return getFromId("screen")[d] / gridsize; }); let saveTimeout: number; const update = () => { const shouldUpdateClone = win.id === "original" && options.isCloneEnabled; if (shouldUpdateClone) { updateClone(); } clearTimeout(saveTimeout); saveTimeout = setTimeout(save, 200); }; const $win = $(win); $win.draggable({ containment: "parent", grid, drag: update, start: update, stop: update, }); $win.resizable({ containment: "parent", handles: "all", grid: grid, minWidth: $win.parent().width()! * 0.2, minHeight: $win.parent().height()! * 0.2, resize: update, start: update, stop: update, }); win.addEventListener("mousedown", () => setWindowAsCurrent(win), false); win.addEventListener("touchstart", () => setWindowAsCurrent(win), false); }); updateResizeOriginal(); updateResizeNew(); updateFocus(); updateMaxDimensions(); if (options.isCloneEnabled) { updateClone(); } } { // add input handlers // ----------------------------------------------------------------------- getFromId("resize-original").onchange = updateResizeOriginal; getFromClass("focus-option").forEach(el => (el.onchange = updateFocus)); getFromTag("input").forEach(el => (el.onclick = save)); getFromId("commandsUrl").onclick = event => { chrome.tabs.create({ url: (event.target as HTMLAnchorElement).href }); }; getFromClass("clone-mode-option").forEach(el => { el.addEventListener( "change", () => { updateMaxDimensions(); if (options.isCloneEnabled) { updateClone(); } setWindowAsCurrent(getFromId("original")); updateResizeNew(); }, false, ); }); } }; // Loading // --------------------------------------------------------------------------- const onReady = (action: () => void) => { if (document.readyState !== "loading") { action(); } else { document.addEventListener("DOMContentLoaded", action); } }; onReady(() => main(options)); });
the_stack
import test from 'ava'; import {ObjectMapper} from '../src/databind/ObjectMapper'; import {JsonProperty} from '../src/decorators/JsonProperty'; import {JsonClassType} from '../src/decorators/JsonClassType'; import {JacksonError} from '../src/core/JacksonError'; import {JsonIncludeType} from '../src/decorators/JsonInclude'; test('SerializationFeature.SORT_PROPERTIES_ALPHABETICALLY set to true', t => { class Book { @JsonProperty() @JsonClassType({type: () => [String]}) name: string; @JsonProperty() @JsonClassType({type: () => [String]}) category: string; @JsonProperty() @JsonClassType({type: () => [Number]}) id: number; constructor(id: number, name: string, category: string) { this.id = id; this.name = name; this.category = category; } } class Writer { @JsonProperty() @JsonClassType({type: () => [Map, [String, Book]]}) bookMap: Map<string, Book> = new Map<string, Book>(); @JsonProperty() @JsonClassType({type: () => [String]}) name: string; @JsonProperty() @JsonClassType({type: () => [Number]}) id: number; constructor(id: number, name: string) { this.id = id; this.name = name; } } const book1 = new Book(42, 'Learning TypeScript', 'Web Development'); const book2 = new Book(21, 'Learning Spring', 'Java'); const writer = new Writer(1, 'John'); writer.bookMap.set('book 2', book2); writer.bookMap.set('book 1', book1); const objectMapper = new ObjectMapper(); objectMapper.defaultStringifierContext.features.serialization.SORT_PROPERTIES_ALPHABETICALLY = true; const jsonData = objectMapper.stringify<Writer>(writer); // eslint-disable-next-line max-len t.is(jsonData, '{"bookMap":{"book 2":{"category":"Java","id":21,"name":"Learning Spring"},"book 1":{"category":"Web Development","id":42,"name":"Learning TypeScript"}},"id":1,"name":"John"}'); }); test('SerializationFeature.ORDER_MAP_AND_OBJECT_LITERAL_ENTRIES_BY_KEYS set to true', t => { class Book { @JsonProperty() @JsonClassType({type: () => [String]}) name: string; @JsonProperty() @JsonClassType({type: () => [String]}) category: string; @JsonProperty() @JsonClassType({type: () => [Number]}) id: number; constructor(id: number, name: string, category: string) { this.id = id; this.name = name; this.category = category; } } class Writer { @JsonProperty() @JsonClassType({type: () => [Number]}) id: number; @JsonProperty() @JsonClassType({type: () => [String]}) name: string; @JsonProperty() @JsonClassType({type: () => [Map, [String, Book]]}) bookMap: Map<string, Book> = new Map<string, Book>(); @JsonProperty() @JsonClassType({type: () => [Object, [String, Book]]}) bookObjLiteral: {[key: string]: Book} = {}; constructor(id: number, name: string) { this.id = id; this.name = name; } } const book1 = new Book(42, 'Learning TypeScript', 'Web Development'); const book2 = new Book(21, 'Learning Spring', 'Java'); const writer = new Writer(1, 'John'); writer.bookMap.set('map book 2', book2); writer.bookMap.set('map book 1', book1); writer.bookObjLiteral = { 'obj literal book 2': book2, 'obj literal book 1': book1 }; const objectMapper = new ObjectMapper(); objectMapper.defaultStringifierContext.features.serialization.ORDER_MAP_AND_OBJECT_LITERAL_ENTRIES_BY_KEYS = true; const jsonData = objectMapper.stringify<Writer>(writer); // eslint-disable-next-line max-len t.assert(jsonData.includes(':{"map book 1":')); t.assert(jsonData.includes(',"map book 2":')); t.assert(jsonData.includes(':{"obj literal book 1":')); t.assert(jsonData.includes(',"obj literal book 2":')); // eslint-disable-next-line max-len t.deepEqual(JSON.parse(jsonData), JSON.parse('{"bookMap":{"map book 1":{"id":42,"name":"Learning TypeScript","category":"Web Development"},"map book 2":{"id":21,"name":"Learning Spring","category":"Java"}},"bookObjLiteral":{"obj literal book 1":{"id":42,"name":"Learning TypeScript","category":"Web Development"},"obj literal book 2":{"id":21,"name":"Learning Spring","category":"Java"}},"id":1,"name":"John"}')); }); test('SerializationFeature.FAIL_ON_SELF_REFERENCES set to false', t => { const errFailOnSelfReferences = t.throws<JacksonError>(() => { class User { @JsonProperty() @JsonClassType({type: () => [Number]}) id: number; @JsonProperty() @JsonClassType({type: () => [String]}) firstname: string; @JsonProperty() @JsonClassType({type: () => [String]}) lastname: string; @JsonProperty() @JsonClassType({type: () => [User]}) userRef: User; constructor(id: number, firstname: string, lastname: string) { this.id = id; this.firstname = firstname; this.lastname = lastname; } } const user = new User(1, 'John', 'Alfa'); user.userRef = user; const objectMapper = new ObjectMapper(); objectMapper.stringify<User>(user); }); t.assert(errFailOnSelfReferences instanceof JacksonError); // const errInfiniteRecursion = t.throws<Error>(() => { // class User { // @JsonProperty() @JsonClassType({type: () => [Number]}) // id: number; // @JsonProperty() @JsonClassType({type: () => [String]}) // firstname: string; // @JsonProperty() @JsonClassType({type: () => [String]}) // lastname: string; // @JsonProperty() @JsonClassType({type: () => [User]}) // userRef: User; // // constructor(id: number, firstname: string, lastname: string) { // this.id = id; // this.firstname = firstname; // this.lastname = lastname; // } // } // // const user = new User(1, 'John', 'Alfa'); // user.userRef = user; // const objectMapper = new ObjectMapper(); // objectMapper.defaultStringifierContext.features.serialization.FAIL_ON_SELF_REFERENCES = false; // objectMapper.stringify<User>(user); // }); // // t.assert(errInfiniteRecursion instanceof Error); }); test('SerializationFeature.WRITE_DATE_KEYS_AS_TIMESTAMPS set to true', t => { class Event { @JsonProperty() @JsonClassType({type: () => [String]}) name: string; @JsonProperty() @JsonClassType({type: () => [Map, [Date, String]]}) infoMap: Map<Date, string> = new Map<Date, string>(); @JsonProperty() @JsonClassType({type: () => [Object, [Date, String]]}) infoObjLiteral = {}; constructor(name: string) { this.name = name; } } const eventDate = new Date(1586993967000); const event = new Event('Event 1'); event.infoMap.set(eventDate, 'info map'); // @ts-ignore event.infoObjLiteral[eventDate] = 'info obj literal'; const objectMapper = new ObjectMapper(); objectMapper.defaultStringifierContext.features.serialization.WRITE_DATE_KEYS_AS_TIMESTAMPS = true; const jsonData = objectMapper.stringify<Event>(event); // eslint-disable-next-line max-len t.deepEqual(JSON.parse(jsonData), JSON.parse('{"infoMap":{"1586993967000":"info map"},"infoObjLiteral":{"1586993967000":"info obj literal"},"name":"Event 1"}')); }); test('SerializationFeature.WRITE_SELF_REFERENCES_AS_NULL set to true', t => { class User { @JsonProperty() @JsonClassType({type: () => [Number]}) id: number; @JsonProperty() @JsonClassType({type: () => [String]}) firstname: string; @JsonProperty() @JsonClassType({type: () => [String]}) lastname: string; @JsonProperty() @JsonClassType({type: () => [User]}) userRef: User; constructor(id: number, firstname: string, lastname: string) { this.id = id; this.firstname = firstname; this.lastname = lastname; } } const user = new User(1, 'John', 'Alfa'); user.userRef = user; const objectMapper = new ObjectMapper(); objectMapper.defaultStringifierContext.features.serialization.FAIL_ON_SELF_REFERENCES = false; objectMapper.defaultStringifierContext.features.serialization.WRITE_SELF_REFERENCES_AS_NULL = true; const jsonData = objectMapper.stringify<User>(user); // eslint-disable-next-line max-len t.deepEqual(JSON.parse(jsonData), JSON.parse('{"id":1,"firstname":"John","lastname":"Alfa","userRef":null}')); }); test('SerializationFeature.DEFAULT_PROPERTY_INCLUSION set to JsonIncludeType.NON_EMPTY', t => { class Employee { @JsonProperty() @JsonClassType({type: () => [Number]}) id: number; @JsonProperty() @JsonClassType({type: () => [String]}) name: string; @JsonProperty() @JsonClassType({type: () => [String]}) dept: string; @JsonProperty() @JsonClassType({type: () => [String]}) address: string; @JsonProperty() @JsonClassType({type: () => [Array, [String]]}) phones: string[]; @JsonProperty() @JsonClassType({type: () => [Map, [String, String]]}) otherInfo: Map<string, string>; constructor(id: number, name: string, dept: string, address: string, phones: string[], otherInfo: Map<string, string>) { this.id = id; this.name = name; this.dept = dept; this.address = address; this.phones = phones; this.otherInfo = otherInfo; } } const employee = new Employee(0, 'John', '', null, [], new Map<string, string>()); const objectMapper = new ObjectMapper(); objectMapper.defaultStringifierContext.features.serialization.DEFAULT_PROPERTY_INCLUSION = { value: JsonIncludeType.NON_EMPTY }; const jsonData = objectMapper.stringify<Employee>(employee); t.deepEqual(JSON.parse(jsonData), JSON.parse('{"id":0,"name":"John"}')); }); test('SerializationFeature.WRITE_DATES_AS_TIMESTAMPS set to false', t => { class User { @JsonProperty() @JsonClassType({type: () => [Number]}) id: number; @JsonProperty() @JsonClassType({type: () => [String]}) firstname: string; @JsonProperty() @JsonClassType({type: () => [String]}) lastname: string; @JsonProperty() @JsonClassType({type: () => [Date]}) birthday: Date; // eslint-disable-next-line no-shadow constructor(id: number, firstname: string, lastname: string, birthday: Date) { this.id = id; this.firstname = firstname; this.lastname = lastname; this.birthday = birthday; } } const birthday = new Date(1994, 11, 14); const user = new User(1, 'John', 'Alfa', birthday); const objectMapper = new ObjectMapper(); objectMapper.defaultStringifierContext.features.serialization.WRITE_DATES_AS_TIMESTAMPS = false; const jsonData = objectMapper.stringify<User>(user); const jsonDataParsed = JSON.parse(jsonData); t.assert(typeof jsonDataParsed.birthday === 'string'); t.is((new Date(jsonDataParsed.birthday)).toString(), birthday.toString()); }); test('SerializationFeature.WRITE_NAN_AS_ZERO set to true', t => { class User { @JsonProperty() @JsonClassType({type: () => [Number]}) id: number; @JsonProperty() @JsonClassType({type: () => [String]}) firstname: string; @JsonProperty() @JsonClassType({type: () => [String]}) lastname: string; @JsonProperty() @JsonClassType({type: () => [Number]}) age: number; constructor(id: number, firstname: string, lastname: string, age: number) { this.id = id; this.firstname = firstname; this.lastname = lastname; this.age = age; } } const user = new User(1, 'John', 'Alfa', NaN); const objectMapper = new ObjectMapper(); objectMapper.defaultStringifierContext.features.serialization.WRITE_NAN_AS_ZERO = true; const jsonData = objectMapper.stringify<User>(user); t.deepEqual(JSON.parse(jsonData), JSON.parse('{"id":1,"firstname":"John","lastname":"Alfa","age":0}')); }); test('Positive Infinity as NUMBER_MAX_VALUE and NUMBER_MAX_SAFE_INTEGER', t => { class User { @JsonProperty() @JsonClassType({type: () => [Number]}) id: number; @JsonProperty() @JsonClassType({type: () => [String]}) firstname: string; @JsonProperty() @JsonClassType({type: () => [String]}) lastname: string; @JsonProperty() @JsonClassType({type: () => [Number]}) age: number; constructor(id: number, firstname: string, lastname: string, age: number) { this.id = id; this.firstname = firstname; this.lastname = lastname; this.age = age; } } const user = new User(1, 'John', 'Alfa', Infinity); const objectMapper = new ObjectMapper(); objectMapper.defaultStringifierContext.features.serialization.WRITE_POSITIVE_INFINITY_AS_NUMBER_MAX_VALUE = true; let jsonData = objectMapper.stringify<User>(user); t.assert(isFinite(JSON.parse(jsonData).age)); objectMapper.defaultStringifierContext.features.serialization.WRITE_POSITIVE_INFINITY_AS_NUMBER_MAX_VALUE = false; objectMapper.defaultStringifierContext.features.serialization.WRITE_POSITIVE_INFINITY_AS_NUMBER_MAX_SAFE_INTEGER = true; jsonData = objectMapper.stringify<User>(user); t.assert(isFinite(JSON.parse(jsonData).age)); }); test('Negative Infinity as NUMBER_MIN_VALUE and NUMBER_MIN_SAFE_INTEGER', t => { class User { @JsonProperty() @JsonClassType({type: () => [Number]}) id: number; @JsonProperty() @JsonClassType({type: () => [String]}) firstname: string; @JsonProperty() @JsonClassType({type: () => [String]}) lastname: string; @JsonProperty() @JsonClassType({type: () => [Number]}) age: number; constructor(id: number, firstname: string, lastname: string, age: number) { this.id = id; this.firstname = firstname; this.lastname = lastname; this.age = age; } } const user = new User(1, 'John', 'Alfa', -Infinity); const objectMapper = new ObjectMapper(); objectMapper.defaultStringifierContext.features.serialization.WRITE_NEGATIVE_INFINITY_AS_NUMBER_MIN_VALUE = true; let jsonData = objectMapper.stringify<User>(user); t.assert(isFinite(JSON.parse(jsonData).age)); objectMapper.defaultStringifierContext.features.serialization.WRITE_NEGATIVE_INFINITY_AS_NUMBER_MIN_VALUE = false; objectMapper.defaultStringifierContext.features.serialization.WRITE_NEGATIVE_INFINITY_AS_NUMBER_MIN_SAFE_INTEGER = true; jsonData = objectMapper.stringify<User>(user); t.assert(isFinite(JSON.parse(jsonData).age)); });
the_stack
import { NetworkOrSignerOrProvider, ValidContractClass } from "../types"; import { z } from "zod"; import { ContractRegistry } from "./registry"; import { getContractAddressByChainId } from "../../constants/addresses"; import { ContractFactory } from "./factory"; import { SDKOptions } from "../../schema/sdk-options"; import { IStorage } from "../interfaces"; import { RPCConnectionHandler } from "./rpc-connection-handler"; import { Edition, EditionDrop, Marketplace, NFTCollection, NFTDrop, SignatureDrop, Pack, Split, Token, Vote, } from "../../contracts"; import { MarketplaceContractDeployMetadata, MultiwrapContractDeployMetadata, NFTContractDeployMetadata, SplitContractDeployMetadata, TokenContractDeployMetadata, VoteContractDeployMetadata, } from "../../types/deploy/deploy-metadata"; import { TokenDrop } from "../../contracts/token-drop"; import { Multiwrap } from "../../contracts/multiwrap"; /** * Handles deploying new contracts * @public */ export class ContractDeployer extends RPCConnectionHandler { /** * @internal * should never be accessed directly, use {@link ContractDeployer.getFactory} instead */ private _factory: Promise<ContractFactory> | undefined; /** * @internal * should never be accessed directly, use {@link ContractDeployer.getRegistry} instead */ private _registry: Promise<ContractRegistry> | undefined; private storage: IStorage; constructor( network: NetworkOrSignerOrProvider, options: SDKOptions, storage: IStorage, ) { super(network, options); this.storage = storage; } /** * Deploys an NFT Collection contract * * @remarks Deploys an NFT Collection contract and returns the address of the deployed contract * * @example * ```javascript * const contractAddress = await sdk.deployer.deployNFTCollection({ * name: "My Collection", * primary_sale_recipient: "your-address", * }); * ``` * @param metadata - the contract metadata * @returns the address of the deployed contract */ public async deployNFTCollection( metadata: NFTContractDeployMetadata, ): Promise<string> { return await this.deployBuiltInContract( NFTCollection.contractType, metadata, ); } /** * Deploys a new NFTDrop contract * * @remarks Deploys an NFT Drop contract and returns the address of the deployed contract * * @example * ```javascript * const contractAddress = await sdk.deployer.deployNFTDrop({ * name: "My Drop", * primary_sale_recipient: "your-address", * }); * ``` * @param metadata - the contract metadata * @returns the address of the deployed contract */ public async deployNFTDrop( metadata: NFTContractDeployMetadata, ): Promise<string> { return await this.deployBuiltInContract(NFTDrop.contractType, metadata); } /** * Deploys a new SignatureDrop contract * * @remarks Deploys a SignatureDrop contract and returns the address of the deployed contract * * @example * ```javascript * const contractAddress = await sdk.deployer.deploySignatureDrop({ * name: "My Signature Drop", * primary_sale_recipient: "your-address", * }); * ``` * @param metadata - the contract metadata * @returns the address of the deployed contract * @internal */ public async deploySignatureDrop( metadata: NFTContractDeployMetadata, ): Promise<string> { return await this.deployBuiltInContract( SignatureDrop.contractType, metadata, ); } /** * Deploys a new Multiwrap contract * * @remarks Deploys a Multiwrap contract and returns the address of the deployed contract * * @example * ```javascript * const contractAddress = await sdk.deployer.deployMultiwrap({ * name: "My Multiwrap", * }); * ``` * @param metadata - the contract metadata * @returns the address of the deployed contract * @beta */ public async deployMultiwrap( metadata: MultiwrapContractDeployMetadata, ): Promise<string> { return await this.deployBuiltInContract(Multiwrap.contractType, metadata); } /** * Deploys a new Edition contract * * @remarks Deploys an Edition contract and returns the address of the deployed contract * * @example * ```javascript * const contractAddress = await sdk.deployer.deployEdition({ * name: "My Edition", * primary_sale_recipient: "your-address", * }); * ``` * @param metadata - the contract metadata * @returns the address of the deployed contract */ public async deployEdition( metadata: NFTContractDeployMetadata, ): Promise<string> { return await this.deployBuiltInContract(Edition.contractType, metadata); } /** * Deploys a new EditionDrop contract * * @remarks Deploys an Edition Drop contract and returns the address of the deployed contract * * @example * ```javascript * const contractAddress = await sdk.deployer.deployEditionDrop({ * name: "My Edition Drop", * primary_sale_recipient: "your-address", * }); * ``` * @param metadata - the contract metadata * @returns the address of the deployed contract */ public async deployEditionDrop( metadata: NFTContractDeployMetadata, ): Promise<string> { const parsed = EditionDrop.schema.deploy.parse(metadata); return await this.deployBuiltInContract(EditionDrop.contractType, parsed); } /** * Deploys a new Token contract * * @remarks Deploys a Token contract and returns the address of the deployed contract * * @example * ```javascript * const contractAddress = await sdk.deployer.deployToken({ * name: "My Token", * primary_sale_recipient: "your-address", * }); * ``` * @param metadata - the contract metadata * @returns the address of the deployed contract */ public async deployToken( metadata: TokenContractDeployMetadata, ): Promise<string> { return await this.deployBuiltInContract(Token.contractType, metadata); } /** * Deploys a new Token Drop contract * * @remarks Deploys a Token Drop contract and returns the address of the deployed contract * * @example * ```javascript * const contractAddress = await sdk.deployer.deployTokenDrop({ * name: "My Token Drop", * primary_sale_recipient: "your-address", * }); * ``` * @param metadata - the contract metadata * @returns the address of the deployed contract */ public async deployTokenDrop( metadata: TokenContractDeployMetadata, ): Promise<string> { return await this.deployBuiltInContract(TokenDrop.contractType, metadata); } /** * Deploys a new Marketplace contract * * @remarks Deploys a Marketplace contract and returns the address of the deployed contract * * @example * ```javascript * const contractAddress = await sdk.deployer.deployMarketplace({ * name: "My Marketplace", * primary_sale_recipient: "your-address", * }); * ``` * @param metadata - the contract metadata * @returns the address of the deployed contract */ public async deployMarketplace( metadata: MarketplaceContractDeployMetadata, ): Promise<string> { return await this.deployBuiltInContract(Marketplace.contractType, metadata); } /** * Deploys a new Pack contract * * @remarks Deploys a Pack contract and returns the address of the deployed contract * * @example * ```javascript * const contractAddress = await sdk.deployer.deployPack({ * name: "My Pack", * primary_sale_recipient: "your-address", * }); * ``` * @param metadata - the contract metadata * @returns the address of the deployed contract */ public async deployPack( metadata: NFTContractDeployMetadata, ): Promise<string> { return await this.deployBuiltInContract(Pack.contractType, metadata); } /** * Deploys a new Split contract * * @remarks Deploys a Split contract and returns the address of the deployed contract * * @example * ```javascript * const contractAddress = await sdk.deployer.deploySplit({ * name: "My Split", * primary_sale_recipient: "your-address", * recipients: [ * { * address: "your-address", * sharesBps: 80 * 100, // 80% * }, * { * address: "another-address", * sharesBps: 20 * 100, // 20% * }, * ], * }); * ``` * @param metadata - the contract metadata * @returns the address of the deployed contract */ public async deploySplit( metadata: SplitContractDeployMetadata, ): Promise<string> { return await this.deployBuiltInContract(Split.contractType, metadata); } /** * Deploys a new Vote contract * * @remarks Deploys an Vote contract and returns the address of the deployed contract * * @example * ```javascript * const contractAddress = await sdk.deployer.deployVote({ * name: "My Vote", * primary_sale_recipient: "your-address", * voting_token_address: "your-token-contract-address", * }); * ``` * @param metadata - the contract metadata * @returns the address of the deployed contract */ public async deployVote( metadata: VoteContractDeployMetadata, ): Promise<string> { return await this.deployBuiltInContract(Vote.contractType, metadata); } /** * Deploys a new contract * * @internal * @param contractType - the type of contract to deploy * @param contractMetadata - the metadata to deploy the contract with * @returns a promise of the address of the newly deployed contract */ public async deployBuiltInContract<TContract extends ValidContractClass>( contractType: TContract["contractType"], contractMetadata: z.input<TContract["schema"]["deploy"]>, ): Promise<string> { const factory = await this.getFactory(); return await factory.deploy(contractType, contractMetadata); } /** * @internal */ public async getRegistry(): Promise<ContractRegistry> { // if we already have a registry just return it back if (this._registry) { return this._registry; } // otherwise get the registry address for the active chain and get a new one // have to do it like this otherwise we run it over and over and over // "this._registry" has to be assigned to the promise upfront. return (this._registry = this.getProvider() .getNetwork() .then(async ({ chainId }) => { const registryAddress = getContractAddressByChainId( chainId, "twRegistry", ); return new ContractRegistry( registryAddress, this.getSignerOrProvider(), this.options, ); })); } private async getFactory(): Promise<ContractFactory> { // if we already have a factory just return it back if (this._factory) { return this._factory; } // otherwise get the factory address for the active chain and get a new one // have to do it like this otherwise we run it over and over and over // "this._factory" has to be assigned to the promise upfront. return (this._factory = this.getProvider() .getNetwork() .then(async ({ chainId }) => { const factoryAddress = getContractAddressByChainId( chainId, "twFactory", ); return new ContractFactory( factoryAddress, this.getSignerOrProvider(), this.storage, this.options, ); })); } public override updateSignerOrProvider(network: NetworkOrSignerOrProvider) { super.updateSignerOrProvider(network); this.updateContractSignerOrProvider(); } private updateContractSignerOrProvider() { // has to be promises now this._factory?.then((factory) => { factory.updateSignerOrProvider(this.getSignerOrProvider()); }); // has to be promises now this._registry?.then((registry) => { registry.updateSignerOrProvider(this.getSignerOrProvider()); }); } }
the_stack
import { BaseResource, CloudError, AzureServiceClientOptions } from "@azure/ms-rest-azure-js"; import * as msRest from "@azure/ms-rest-js"; export { BaseResource, CloudError }; /** * Resource model definition. */ export interface Resource extends BaseResource { /** * Resource identifier. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly id?: string; /** * Resource type. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly type?: string; /** * Resource name. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly name?: string; } /** * Contains the possible cases for ResourceReference. */ export type ResourceReferenceUnion = ResourceReference | MachineReference | ProcessReference | PortReference | MachineReferenceWithHints | ClientGroupReference; /** * Represents a reference to another resource. */ export interface ResourceReference { /** * Polymorphic Discriminator */ kind: "ResourceReference"; /** * Resource URI. */ id: string; /** * Resource type qualifier. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly type?: string; /** * Resource name. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly name?: string; } /** * Reference to a machine. */ export interface MachineReference { /** * Polymorphic Discriminator */ kind: "ref:machine"; /** * Resource URI. */ id: string; /** * Resource type qualifier. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly type?: string; /** * Resource name. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly name?: string; } /** * Reference to a process. */ export interface ProcessReference { /** * Polymorphic Discriminator */ kind: "ref:process"; /** * Resource URI. */ id: string; /** * Resource type qualifier. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly type?: string; /** * Resource name. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly name?: string; /** * Machine hosting the process. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly machine?: MachineReference; } /** * Reference to a port. */ export interface PortReference { /** * Polymorphic Discriminator */ kind: "ref:port"; /** * Resource URI. */ id: string; /** * Resource type qualifier. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly type?: string; /** * Resource name. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly name?: string; /** * Machine hosting the port. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly machine?: MachineReference; /** * IP address of the port. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly ipAddress?: string; /** * Port number. */ portNumber?: number; } /** * A machine reference with a hint of the machine's name and operating system. */ export interface MachineReferenceWithHints { /** * Polymorphic Discriminator */ kind: "ref:machinewithhints"; /** * Resource URI. */ id: string; /** * Resource type qualifier. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly type?: string; /** * Resource name. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly name?: string; /** * Last known display name. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly displayNameHint?: string; /** * Last known operating system family. Possible values include: 'unknown', 'windows', 'linux', * 'solaris', 'aix' * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly osFamilyHint?: OperatingSystemFamily; } /** * Reference to a client group. */ export interface ClientGroupReference { /** * Polymorphic Discriminator */ kind: "ref:clientgroup"; /** * Resource URI. */ id: string; /** * Resource type qualifier. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly type?: string; /** * Resource name. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly name?: string; } /** * Contains the possible cases for CoreResource. */ export type CoreResourceUnion = CoreResource | Machine | Process | Port | ClientGroup | MachineGroup; /** * Marker resource for the core Service Map resources */ export interface CoreResource { /** * Polymorphic Discriminator */ kind: "CoreResource"; /** * Resource identifier. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly id?: string; /** * Resource type. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly type?: string; /** * Resource name. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly name?: string; /** * Resource ETAG. */ etag?: string; } /** * Describes a timezone. */ export interface Timezone { /** * Timezone full name. */ fullName?: string; } /** * Describes the configuration of the Dependency Agent installed on a machine. */ export interface AgentConfiguration { /** * Health Service Agent unique identifier. */ agentId: string; /** * Dependency Agent unique identifier. */ dependencyAgentId?: string; /** * Dependency Agent version number. */ dependencyAgentVersion?: string; /** * Dependency Agent revision number. */ dependencyAgentRevision?: string; /** * Specifies whether the machine has been rebooted since the Dependency Agent installation. * Possible values include: 'unknown', 'rebooted', 'notRebooted' */ rebootStatus?: MachineRebootStatus; /** * Machine clock granularity in milliseconds. */ clockGranularity?: number; } /** * Describes the resources of a machine. */ export interface MachineResourcesConfiguration { /** * Physical memory in megabytes (MB). */ physicalMemory?: number; /** * Number of CPUs. */ cpus?: number; /** * CPU speed in megahertz (Mhz). */ cpuSpeed?: number; /** * Describes the accuracy of the cpuSpeed field. Possible values include: 'actual', 'estimated' */ cpuSpeedAccuracy?: Accuracy; } /** * Describes an IPv4 network interface. */ export interface Ipv4NetworkInterface { /** * IPv4 address. */ ipAddress: string; /** * IPv4 subnet mask. Default value: '255.255.255.255'. */ subnetMask?: string; } /** * Describes an IPv6 network interface. */ export interface Ipv6NetworkInterface { /** * IPv6 address. */ ipAddress: string; } /** * Describes the network configuration of a machine. */ export interface NetworkConfiguration { /** * IPv4 interfaces. */ ipv4Interfaces?: Ipv4NetworkInterface[]; /** * IPv6 interfaces. */ ipv6Interfaces?: Ipv6NetworkInterface[]; /** * Default IPv4 gateways. */ defaultIpv4Gateways?: string[]; /** * MAC addresses of all active network interfaces. */ macAddresses?: string[]; /** * DNS names associated with the machine. */ dnsNames?: string[]; } /** * Describes the configuration of the operating system of a machine. */ export interface OperatingSystemConfiguration { /** * Windows, Linux, etc. Possible values include: 'unknown', 'windows', 'linux', 'solaris', 'aix' */ family: OperatingSystemFamily; /** * Operating system full name. */ fullName: string; /** * Operating system bitness (32-bit or 64-bit). Possible values include: '32bit', '64bit' */ bitness: Bitness; } /** * Describes the virtualization-related configuration of a machine. */ export interface VirtualMachineConfiguration { /** * Specifies the virtualization technology used by the machine (hyperv, vmware, etc.). Possible * values include: 'unknown', 'hyperv', 'ldom', 'lpar', 'vmware', 'virtualPc', 'xen' */ virtualMachineType?: VirtualMachineType; /** * The unique identifier of the virtual machine as reported by the underlying virtualization * system. */ nativeMachineId?: string; /** * The Name of the virtual machine. */ virtualMachineName?: string; /** * The unique identifier of the host of this virtual machine as reported by the underlying * virtualization system. */ nativeHostMachineId?: string; } /** * Describes the hypervisor configuration of a machine. */ export interface HypervisorConfiguration { /** * Specifies the virtualization technology used by the hypervisor (hyperv, vmware, etc.). * Possible values include: 'unknown', 'hyperv' */ hypervisorType?: HypervisorType; /** * The unique identifier of the hypervisor machine as reported by the underlying virtualization * system. */ nativeHostMachineId?: string; } /** * Contains the possible cases for HostingConfiguration. */ export type HostingConfigurationUnion = HostingConfiguration | AzureHostingConfiguration; /** * Describes the hosting configuration of a machine. */ export interface HostingConfiguration { /** * Polymorphic Discriminator */ kind: "HostingConfiguration"; /** * The hosting provider of the VM. Possible values include: 'azure' */ provider?: Provider; } /** * A machine resource represents a discovered computer system. It can be *monitored*, i.e., a * Dependency Agent is running on it, or *discovered*, i.e., its existence was inferred by * observing the data stream from monitored machines. As machines change, prior versions of the * machine resource are preserved and available for access. A machine is live during an interval of * time, if either its Dependency Agent has reported data during (parts) of that interval, or a * Dependency agent running on other machines has reported activity associated with the machine. */ export interface Machine { /** * Polymorphic Discriminator */ kind: "machine"; /** * Resource identifier. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly id?: string; /** * Resource type. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly type?: string; /** * Resource name. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly name?: string; /** * Resource ETAG. */ etag?: string; /** * UTC date and time when this resource was updated in the system. */ timestamp?: Date; /** * Specifies whether the machine is actively monitored or discovered. Possible values include: * 'monitored', 'discovered' */ monitoringState?: MonitoringState; /** * Specifies whether the machine is virtualized. Possible values include: 'unknown', 'physical', * 'virtual', 'hypervisor' */ virtualizationState?: VirtualizationState; /** * Name to use for display purposes */ displayName?: string; /** * Name of the machine, e.g., server */ computerName?: string; /** * Fully-qualified name of the machine, e.g., server.company.com */ fullyQualifiedDomainName?: string; /** * UTC date and time when the machine last booted */ bootTime?: Date; /** * Timezone of the machine. */ timezone?: Timezone; /** * Dependency Agent configuration. */ agent?: AgentConfiguration; /** * Machine resources (memory, cpu, etc.). */ resources?: MachineResourcesConfiguration; /** * Network configuration (ips, gateways, dns, etc.) */ networking?: NetworkConfiguration; /** * Operating system information. */ operatingSystem?: OperatingSystemConfiguration; /** * Virtualization-related configuration. Present only when `virtualizationState` is `virtual`. */ virtualMachine?: VirtualMachineConfiguration; /** * Hypervisor-related configuration. Present only when 'virtualizationState' is `hypervisor`. */ hypervisor?: HypervisorConfiguration; /** * Hosting-related configuration. Present if hosting information is discovered for the VM. */ hosting?: HostingConfigurationUnion; } /** * A service hosted by a process. */ export interface ProcessHostedService { /** * The name of the service. */ name?: string; /** * The service's display name. */ displayName?: string; } /** * Describes process metadata. */ export interface ProcessDetails { /** * A unique identifier for a process, generally resilient to process restart, computed by Service * Map. */ persistentKey?: string; /** * Represents the identity of the process pool assigned to the process by Dependency Agent. */ poolId?: number; /** * The Operating System Process Identifier (PID) of the first process in this process pool. */ firstPid?: number; /** * Process description. */ description?: string; /** * Name of company that created the process executable. */ companyName?: string; /** * Internal process name. */ internalName?: string; /** * Product name. */ productName?: string; /** * Product version. */ productVersion?: string; /** * File version. */ fileVersion?: string; /** * Process command line. */ commandLine?: string; /** * Process executable path. */ executablePath?: string; /** * Process workingDirectory. */ workingDirectory?: string; /** * Collection of services hosted by this Process (Windows only). */ services?: ProcessHostedService[]; /** * Process zone name (Linux only). */ zoneName?: string; } /** * Describes the user under which a process is running. */ export interface ProcessUser { /** * User name under which the process is running. */ userName?: string; /** * Domain name for the user. */ userDomain?: string; } /** * Contains the possible cases for ProcessHostingConfiguration. */ export type ProcessHostingConfigurationUnion = ProcessHostingConfiguration | AzureProcessHostingConfiguration; /** * Describes the hosting configuration of a process. */ export interface ProcessHostingConfiguration { /** * Polymorphic Discriminator */ kind: "ProcessHostingConfiguration"; /** * The hosting provider of the VM. Possible values include: 'azure' */ provider?: Provider1; } /** * A process resource represents a process running on a machine. The process may be actively * *monitored*, i.e., a Dependency Agent is running on its machine, or *discovered*, i.e., its * existence was inferred by observing the data stream from monitored machines. A process resource * represents a pool of actual operating system resources that share command lines and metadata. As * the process pool evolves over time, prior versions of the process resource are preserved and * available for access. A process is live during an interval of time, if that process is executing * during (parts) of that interval */ export interface Process { /** * Polymorphic Discriminator */ kind: "process"; /** * Resource identifier. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly id?: string; /** * Resource type. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly type?: string; /** * Resource name. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly name?: string; /** * Resource ETAG. */ etag?: string; /** * UTC date and time when this process resource was updated in the system */ timestamp?: Date; /** * Specifies whether the process is actively monitored or discovered. Possible values include: * 'monitored', 'discovered' */ monitoringState?: MonitoringState; /** * Machine hosting this process. */ machine?: ResourceReferenceUnion; /** * The name of the process executable */ executableName?: string; /** * Name to use for display purposes */ displayName?: string; /** * UTC date and time when the process started */ startTime?: Date; /** * The inferred role of this process based on its name, command line, etc. Possible values * include: 'webServer', 'appServer', 'databaseServer', 'ldapServer', 'smbServer' */ role?: ProcessRole; /** * The name of the product or suite of the process. The group is determined by its executable * name, command line, etc. */ group?: string; /** * Process metadata (command line, product name, etc.). */ details?: ProcessDetails; /** * Information about the account under which the process is executing. */ user?: ProcessUser; /** * Present only for a discovered process acting as a client of a monitored process/machine/port. * References the monitored process/machine/port that this process is a client of. */ clientOf?: ResourceReferenceUnion; /** * Present only for a discovered process acting as a server. References the port on which the * discovered process is accepting. */ acceptorOf?: ResourceReferenceUnion; /** * Information about the hosting environment */ hosting?: ProcessHostingConfigurationUnion; } /** * A port resource represents a server port on a machine. The port may be actively *monitored*, * i.e., a Dependency Agent is running on its machine, or *discovered*, i.e., its existence was * inferred by observing the data stream from monitored machines. A port is live during an interval * of time, if that port had associated activity during (parts) of that interval. */ export interface Port { /** * Polymorphic Discriminator */ kind: "port"; /** * Resource identifier. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly id?: string; /** * Resource type. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly type?: string; /** * Resource name. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly name?: string; /** * Resource ETAG. */ etag?: string; /** * Specifies whether the port is actively monitored or discovered. Possible values include: * 'monitored', 'discovered' */ monitoringState?: MonitoringState; /** * Machine hosting this port. */ machine?: ResourceReferenceUnion; /** * Name to use for display purposes. */ displayName?: string; /** * IP address associated with the port. At present only IPv4 addresses are supported. */ ipAddress?: string; /** * Port number. */ portNumber?: number; } /** * Represents a collection of clients of a resource. A client group can represent the clients of a * port, process, or a machine. */ export interface ClientGroup { /** * Polymorphic Discriminator */ kind: "clientGroup"; /** * Resource identifier. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly id?: string; /** * Resource type. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly type?: string; /** * Resource name. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly name?: string; /** * Resource ETAG. */ etag?: string; /** * Reference to the resource whose clients are represented by this group. */ clientsOf: ResourceReferenceUnion; } /** * Represents a member of a client group */ export interface ClientGroupMember extends Resource { /** * IP address. */ ipAddress?: string; /** * Port into which this client connected */ port?: PortReference; /** * Processes accepting on the above port that received connections from this client. */ processes?: ProcessReference[]; } /** * A user-defined logical grouping of machines. */ export interface MachineGroup { /** * Polymorphic Discriminator */ kind: "machineGroup"; /** * Resource identifier. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly id?: string; /** * Resource type. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly type?: string; /** * Resource name. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly name?: string; /** * Resource ETAG. */ etag?: string; /** * Type of the machine group. Possible values include: 'unknown', 'azure-cs', 'azure-sf', * 'azure-vmss', 'user-static' */ groupType?: MachineGroupType; /** * User defined name for the group */ displayName: string; /** * Count of machines in this group. The value of count may be bigger than the number of machines * in case of the group has been truncated due to exceeding the max number of machines a group * can handle. */ count?: number; /** * References of the machines in this group. The hints within each reference do not represent the * current value of the corresponding fields. They are a snapshot created during the last time * the machine group was updated. */ machines?: MachineReferenceWithHints[]; } /** * Base for all resource summaries. */ export interface Summary extends Resource { } /** * Machines by operating system. */ export interface MachineCountsByOperatingSystem { /** * Number of live Windows machines. */ windows: number; /** * Number of live Linux machines. */ linux: number; } /** * A summary of the machines in the workspace. */ export interface MachinesSummary extends Summary { /** * Summary interval start time. */ startTime: Date; /** * Summary interval end time. */ endTime: Date; /** * Total number of machines. */ total: number; /** * Number of live machines. */ live: number; /** * Machine counts by operating system. */ os: MachineCountsByOperatingSystem; } /** * Contains the possible cases for Relationship. */ export type RelationshipUnion = Relationship | Connection | Acceptor; /** * A typed relationship between two entities. */ export interface Relationship { /** * Polymorphic Discriminator */ kind: "Relationship"; /** * Resource identifier. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly id?: string; /** * Resource type. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly type?: string; /** * Resource name. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly name?: string; } /** * A network connection. */ export interface Connection { /** * Polymorphic Discriminator */ kind: "rel:connection"; /** * Resource identifier. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly id?: string; /** * Resource type. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly type?: string; /** * Resource name. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly name?: string; /** * Source resource of the relationship. */ source: ResourceReferenceUnion; /** * Destination resource of the relationship. */ destination: ResourceReferenceUnion; /** * Relationship start time. */ startTime?: Date; /** * Relationship end time. */ endTime?: Date; /** * Reference to the server port via which this connection has been established. */ serverPort?: PortReference; /** * Specifies whether there are only successful, failed or a mixture of both connections * represented by this resource. Possible values include: 'ok', 'failed', 'mixed' */ failureState?: ConnectionFailureState; } /** * A process accepting on a port. */ export interface Acceptor { /** * Polymorphic Discriminator */ kind: "rel:acceptor"; /** * Resource identifier. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly id?: string; /** * Resource type. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly type?: string; /** * Resource name. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly name?: string; /** * Port being accepted. */ source: PortReference; /** * Accepting process. */ destination: ProcessReference; /** * Relationship start time. */ startTime?: Date; /** * Relationship end time. */ endTime?: Date; } /** * Base for all summaries. */ export interface SummaryProperties { /** * Summary interval start time. */ startTime: Date; /** * Summary interval end time. */ endTime: Date; } /** * Relationship properties. */ export interface RelationshipProperties { /** * Source resource of the relationship. */ source: ResourceReferenceUnion; /** * Destination resource of the relationship. */ destination: ResourceReferenceUnion; /** * Relationship start time. */ startTime?: Date; /** * Relationship end time. */ endTime?: Date; } /** * Describes the VM image of a machine. */ export interface ImageConfiguration { /** * Publisher of the VM image. */ publisher?: string; /** * Offering of the VM image. */ offering?: string; /** * SKU of the VM image. */ sku?: string; /** * Version of the VM image. */ version?: string; } /** * Describes an Azure Cloud Service */ export interface AzureCloudServiceConfiguration { /** * Cloud Service name */ name?: string; /** * Cloud Service instance identifier */ instanceId?: string; /** * Cloud Service deployment identifier */ deployment?: string; /** * Cloud Service role name */ roleName?: string; /** * Used to specify type of an Azure Cloud Service role. Possible values include: 'unknown', * 'worker', 'web' */ roleType?: AzureCloudServiceRoleType; } /** * Describes an Azure Virtual Machine Scale Set */ export interface AzureVmScaleSetConfiguration { /** * Virtual Machine Scale Set name */ name?: string; /** * Virtual Machine Scale Set instance identifier */ instanceId?: string; /** * Virtual Machine Scale Set deployment identifier */ deployment?: string; /** * Unique identifier of the resource. */ resourceId?: string; } /** * Describes an Azure Service Fabric Cluster */ export interface AzureServiceFabricClusterConfiguration { /** * Service Fabric cluster name. */ name?: string; /** * Service Fabric cluster identifier. */ clusterId?: string; } /** * Provides information about how a machine is hosted in Azure */ export interface AzureHostingConfiguration { /** * Polymorphic Discriminator */ kind: "provider:azure"; /** * The hosting provider of the VM. Possible values include: 'azure' */ provider?: Provider; /** * Virtual Machine ID (unique identifier). */ vmId?: string; /** * Geographical location of the VM. */ location?: string; /** * Machine name according to the hosting provider. */ name?: string; /** * Size of the VM. */ size?: string; /** * Update domain of the VM. */ updateDomain?: string; /** * Fault domain of the VM. */ faultDomain?: string; /** * Subscription ID. */ subscriptionId?: string; /** * Resource group name within the specified subscription. */ resourceGroup?: string; /** * Unique identifier of the resource. */ resourceId?: string; /** * Image of the machine. */ image?: ImageConfiguration; /** * Contains information about machines hosted as an Azure Cloud Service */ cloudService?: AzureCloudServiceConfiguration; /** * Contains information about machines hosted as an Azure Virtual Machine Scale Set */ vmScaleSet?: AzureVmScaleSetConfiguration; /** * Contains information about machines that belong an Azure Service Fabric Cluster */ serviceFabricCluster?: AzureServiceFabricClusterConfiguration; } /** * Describes the hosting configuration of a process when hosted on azure */ export interface AzureProcessHostingConfiguration { /** * Polymorphic Discriminator */ kind: "provider:azure"; /** * The hosting provider of the VM. Possible values include: 'azure' */ provider?: Provider1; /** * Contains information about the cloud service the process belongs to */ cloudService?: AzureCloudServiceConfiguration; } /** * The nodes (entities) of a map. */ export interface MapNodes { /** * Machine resources. */ machines?: Machine[]; /** * Process resources. */ processes?: Process[]; /** * Port resources. */ ports?: Port[]; /** * Client Group resources. */ clientGroups?: ClientGroup[]; } /** * The edges (relationships) of a map. */ export interface MapEdges { /** * Network connections. */ connections?: Connection[]; /** * Processes accepting on a port. */ acceptors?: Acceptor[]; } /** * A map of resources and relationships between them. */ export interface Map { nodes: MapNodes; edges: MapEdges; } /** * Specifies the contents of a check liveness response. */ export interface Liveness { /** * Liveness interval start time. */ startTime: Date; /** * Liveness interval end time. */ endTime: Date; /** * `true` if the resource is live during [startTime, endTime], `false` otherwise */ live: boolean; } /** * Contains the possible cases for MapRequest. */ export type MapRequestUnion = MapRequest | SingleMachineDependencyMapRequest | MultipleMachinesMapRequestUnion; /** * Specifies the contents of request to generate a map. */ export interface MapRequest { /** * Polymorphic Discriminator */ kind: "MapRequest"; /** * Map interval start time. */ startTime?: Date; /** * Map interval end time. */ endTime?: Date; } /** * Specifies the computation of a single server dependency map. A single server dependency map * includes all direct dependencies of a given machine. */ export interface SingleMachineDependencyMapRequest { /** * Polymorphic Discriminator */ kind: "map:single-machine-dependency"; /** * Map interval start time. */ startTime?: Date; /** * Map interval end time. */ endTime?: Date; /** * URI of machine resource for which to generate the map. */ machineId: string; } /** * Contains the possible cases for MultipleMachinesMapRequest. */ export type MultipleMachinesMapRequestUnion = MultipleMachinesMapRequest | MachineListMapRequest | MachineGroupMapRequest; /** * Provides a base class for describing map requests for a collection of machines */ export interface MultipleMachinesMapRequest { /** * Polymorphic Discriminator */ kind: "MultipleMachinesMapRequest"; /** * Map interval start time. */ startTime?: Date; /** * Map interval end time. */ endTime?: Date; /** * If true, only processes between specified machines will be included. Any connections in or out * of those processes will be included. */ filterProcesses?: boolean; } /** * Specifies the computation of a one hope dependency map for a list of machines. The resulting map * includes all direct dependencies for the specified machines. */ export interface MachineListMapRequest { /** * Polymorphic Discriminator */ kind: "map:machine-list-dependency"; /** * Map interval start time. */ startTime?: Date; /** * Map interval end time. */ endTime?: Date; /** * If true, only processes between specified machines will be included. Any connections in or out * of those processes will be included. */ filterProcesses?: boolean; /** * a list of URIs of machine resources for which to generate the map. */ machineIds: string[]; } /** * Specifies the computation of a machine group dependency map. A machine group dependency map * includes all direct dependencies the machines in the group. */ export interface MachineGroupMapRequest { /** * Polymorphic Discriminator */ kind: "map:machine-group-dependency"; /** * Map interval start time. */ startTime?: Date; /** * Map interval end time. */ endTime?: Date; /** * If true, only processes between specified machines will be included. Any connections in or out * of those processes will be included. */ filterProcesses?: boolean; /** * URI of machine group resource for which to generate the map. */ machineGroupId: string; } /** * Specified the contents of a map response. */ export interface MapResponse { /** * Map interval start time. */ startTime: Date; /** * Map interval end time. */ endTime: Date; /** * The generated map. */ map: Map; } /** * Specifies the number of members in a client group. */ export interface ClientGroupMembersCount { /** * Membership interval start time. */ startTime: Date; /** * Membership interval start time. */ endTime: Date; /** * Client Group URI. */ groupId: string; /** * Number of members in the client group. Use this value together with the value of * ```accuracy```. If accuracy is `exact` then the value represents the actual number of members * in the cloud. When accuracy is `estimated`, the actual number of members is larger than the * value of ```count```. */ count: number; /** * Accuracy of the reported count. Possible values include: 'actual', 'estimated' */ accuracy: Accuracy; } /** * Error details. */ export interface ErrorModel { /** * Error code identifying the specific error. */ code: string; /** * Error message in the caller's locale. */ message?: string; } /** * An error response from the API. */ export interface ErrorResponse { /** * Error information. */ error: ErrorModel; } /** * Optional Parameters. */ export interface MachinesListByWorkspaceOptionalParams extends msRest.RequestOptionsBase { /** * Specifies whether to return live resources (true) or inventory resources (false). Defaults to * **true**. When retrieving live resources, the start time (`startTime`) and end time * (`endTime`) of the desired interval should be included. When retrieving inventory resources, * an optional timestamp (`timestamp`) parameter can be specified to return the version of each * resource closest (not-after) that timestamp. Default value: true. */ live?: boolean; /** * UTC date and time specifying the start time of an interval. When not specified the service * uses DateTime.UtcNow - 10m */ startTime?: Date; /** * UTC date and time specifying the end time of an interval. When not specified the service uses * DateTime.UtcNow */ endTime?: Date; /** * UTC date and time specifying a time instance relative to which to evaluate each machine * resource. Only applies when `live=false`. When not specified, the service uses * DateTime.UtcNow. */ timestamp?: Date; /** * Page size to use. When not specified, the default page size is 100 records. */ top?: number; } /** * Optional Parameters. */ export interface MachinesGetOptionalParams extends msRest.RequestOptionsBase { /** * UTC date and time specifying a time instance relative to which to evaluate the machine * resource. When not specified, the service uses DateTime.UtcNow. */ timestamp?: Date; } /** * Optional Parameters. */ export interface MachinesGetLivenessOptionalParams extends msRest.RequestOptionsBase { /** * UTC date and time specifying the start time of an interval. When not specified the service * uses DateTime.UtcNow - 10m */ startTime?: Date; /** * UTC date and time specifying the end time of an interval. When not specified the service uses * DateTime.UtcNow */ endTime?: Date; } /** * Optional Parameters. */ export interface MachinesListConnectionsOptionalParams extends msRest.RequestOptionsBase { /** * UTC date and time specifying the start time of an interval. When not specified the service * uses DateTime.UtcNow - 10m */ startTime?: Date; /** * UTC date and time specifying the end time of an interval. When not specified the service uses * DateTime.UtcNow */ endTime?: Date; } /** * Optional Parameters. */ export interface MachinesListProcessesOptionalParams extends msRest.RequestOptionsBase { /** * Specifies whether to return live resources (true) or inventory resources (false). Defaults to * **true**. When retrieving live resources, the start time (`startTime`) and end time * (`endTime`) of the desired interval should be included. When retrieving inventory resources, * an optional timestamp (`timestamp`) parameter can be specified to return the version of each * resource closest (not-after) that timestamp. Default value: true. */ live?: boolean; /** * UTC date and time specifying the start time of an interval. When not specified the service * uses DateTime.UtcNow - 10m */ startTime?: Date; /** * UTC date and time specifying the end time of an interval. When not specified the service uses * DateTime.UtcNow */ endTime?: Date; /** * UTC date and time specifying a time instance relative to which to evaluate all process * resource. Only applies when `live=false`. When not specified, the service uses * DateTime.UtcNow. */ timestamp?: Date; } /** * Optional Parameters. */ export interface MachinesListPortsOptionalParams extends msRest.RequestOptionsBase { /** * UTC date and time specifying the start time of an interval. When not specified the service * uses DateTime.UtcNow - 10m */ startTime?: Date; /** * UTC date and time specifying the end time of an interval. When not specified the service uses * DateTime.UtcNow */ endTime?: Date; } /** * Optional Parameters. */ export interface MachinesListMachineGroupMembershipOptionalParams extends msRest.RequestOptionsBase { /** * UTC date and time specifying the start time of an interval. When not specified the service * uses DateTime.UtcNow - 10m */ startTime?: Date; /** * UTC date and time specifying the end time of an interval. When not specified the service uses * DateTime.UtcNow */ endTime?: Date; } /** * Optional Parameters. */ export interface ProcessesGetOptionalParams extends msRest.RequestOptionsBase { /** * UTC date and time specifying a time instance relative to which to evaluate a resource. When * not specified, the service uses DateTime.UtcNow. */ timestamp?: Date; } /** * Optional Parameters. */ export interface ProcessesGetLivenessOptionalParams extends msRest.RequestOptionsBase { /** * UTC date and time specifying the start time of an interval. When not specified the service * uses DateTime.UtcNow - 10m */ startTime?: Date; /** * UTC date and time specifying the end time of an interval. When not specified the service uses * DateTime.UtcNow */ endTime?: Date; } /** * Optional Parameters. */ export interface ProcessesListAcceptingPortsOptionalParams extends msRest.RequestOptionsBase { /** * UTC date and time specifying the start time of an interval. When not specified the service * uses DateTime.UtcNow - 10m */ startTime?: Date; /** * UTC date and time specifying the end time of an interval. When not specified the service uses * DateTime.UtcNow */ endTime?: Date; } /** * Optional Parameters. */ export interface ProcessesListConnectionsOptionalParams extends msRest.RequestOptionsBase { /** * UTC date and time specifying the start time of an interval. When not specified the service * uses DateTime.UtcNow - 10m */ startTime?: Date; /** * UTC date and time specifying the end time of an interval. When not specified the service uses * DateTime.UtcNow */ endTime?: Date; } /** * Optional Parameters. */ export interface PortsGetOptionalParams extends msRest.RequestOptionsBase { /** * UTC date and time specifying the start time of an interval. When not specified the service * uses DateTime.UtcNow - 10m */ startTime?: Date; /** * UTC date and time specifying the end time of an interval. When not specified the service uses * DateTime.UtcNow */ endTime?: Date; } /** * Optional Parameters. */ export interface PortsGetLivenessOptionalParams extends msRest.RequestOptionsBase { /** * UTC date and time specifying the start time of an interval. When not specified the service * uses DateTime.UtcNow - 10m */ startTime?: Date; /** * UTC date and time specifying the end time of an interval. When not specified the service uses * DateTime.UtcNow */ endTime?: Date; } /** * Optional Parameters. */ export interface PortsListAcceptingProcessesOptionalParams extends msRest.RequestOptionsBase { /** * UTC date and time specifying the start time of an interval. When not specified the service * uses DateTime.UtcNow - 10m */ startTime?: Date; /** * UTC date and time specifying the end time of an interval. When not specified the service uses * DateTime.UtcNow */ endTime?: Date; } /** * Optional Parameters. */ export interface PortsListConnectionsOptionalParams extends msRest.RequestOptionsBase { /** * UTC date and time specifying the start time of an interval. When not specified the service * uses DateTime.UtcNow - 10m */ startTime?: Date; /** * UTC date and time specifying the end time of an interval. When not specified the service uses * DateTime.UtcNow */ endTime?: Date; } /** * Optional Parameters. */ export interface ClientGroupsGetOptionalParams extends msRest.RequestOptionsBase { /** * UTC date and time specifying the start time of an interval. When not specified the service * uses DateTime.UtcNow - 10m */ startTime?: Date; /** * UTC date and time specifying the end time of an interval. When not specified the service uses * DateTime.UtcNow */ endTime?: Date; } /** * Optional Parameters. */ export interface ClientGroupsGetMembersCountOptionalParams extends msRest.RequestOptionsBase { /** * UTC date and time specifying the start time of an interval. When not specified the service * uses DateTime.UtcNow - 10m */ startTime?: Date; /** * UTC date and time specifying the end time of an interval. When not specified the service uses * DateTime.UtcNow */ endTime?: Date; } /** * Optional Parameters. */ export interface ClientGroupsListMembersOptionalParams extends msRest.RequestOptionsBase { /** * UTC date and time specifying the start time of an interval. When not specified the service * uses DateTime.UtcNow - 10m */ startTime?: Date; /** * UTC date and time specifying the end time of an interval. When not specified the service uses * DateTime.UtcNow */ endTime?: Date; /** * Page size to use. When not specified, the default page size is 100 records. */ top?: number; } /** * Optional Parameters. */ export interface SummariesGetMachinesOptionalParams extends msRest.RequestOptionsBase { /** * UTC date and time specifying the start time of an interval. When not specified the service * uses DateTime.UtcNow - 10m */ startTime?: Date; /** * UTC date and time specifying the end time of an interval. When not specified the service uses * DateTime.UtcNow */ endTime?: Date; } /** * Optional Parameters. */ export interface MachineGroupsListByWorkspaceOptionalParams extends msRest.RequestOptionsBase { /** * UTC date and time specifying the start time of an interval. When not specified the service * uses DateTime.UtcNow - 10m */ startTime?: Date; /** * UTC date and time specifying the end time of an interval. When not specified the service uses * DateTime.UtcNow */ endTime?: Date; } /** * Optional Parameters. */ export interface MachineGroupsGetOptionalParams extends msRest.RequestOptionsBase { /** * UTC date and time specifying the start time of an interval. When not specified the service * uses DateTime.UtcNow - 10m */ startTime?: Date; /** * UTC date and time specifying the end time of an interval. When not specified the service uses * DateTime.UtcNow */ endTime?: Date; } /** * An interface representing ServicemapManagementClientOptions. */ export interface ServicemapManagementClientOptions extends AzureServiceClientOptions { baseUri?: string; } /** * @interface * Collection of Machine resources. * @extends Array<Machine> */ export interface MachineCollection extends Array<Machine> { /** * The URL to the next set of resources. */ nextLink?: string; } /** * @interface * Collection of Connection resources. * @extends Array<Connection> */ export interface ConnectionCollection extends Array<Connection> { /** * The URL to the next set of resources. */ nextLink?: string; } /** * @interface * Collection of Process resources. * @extends Array<Process> */ export interface ProcessCollection extends Array<Process> { /** * The URL to the next set of resources. */ nextLink?: string; } /** * @interface * Collection of Port resources. * @extends Array<Port> */ export interface PortCollection extends Array<Port> { /** * The URL to the next set of resources. */ nextLink?: string; } /** * @interface * Collection of Machine Group resources. * @extends Array<MachineGroup> */ export interface MachineGroupCollection extends Array<MachineGroup> { /** * The URL to the next set of resources. */ nextLink?: string; } /** * @interface * Collection of ClientGroupMember resources. * @extends Array<ClientGroupMember> */ export interface ClientGroupMembersCollection extends Array<ClientGroupMember> { /** * The URL to the next set of resources. */ nextLink?: string; } /** * Defines values for OperatingSystemFamily. * Possible values include: 'unknown', 'windows', 'linux', 'solaris', 'aix' * @readonly * @enum {string} */ export type OperatingSystemFamily = 'unknown' | 'windows' | 'linux' | 'solaris' | 'aix'; /** * Defines values for MonitoringState. * Possible values include: 'monitored', 'discovered' * @readonly * @enum {string} */ export type MonitoringState = 'monitored' | 'discovered'; /** * Defines values for VirtualizationState. * Possible values include: 'unknown', 'physical', 'virtual', 'hypervisor' * @readonly * @enum {string} */ export type VirtualizationState = 'unknown' | 'physical' | 'virtual' | 'hypervisor'; /** * Defines values for MachineRebootStatus. * Possible values include: 'unknown', 'rebooted', 'notRebooted' * @readonly * @enum {string} */ export type MachineRebootStatus = 'unknown' | 'rebooted' | 'notRebooted'; /** * Defines values for Accuracy. * Possible values include: 'actual', 'estimated' * @readonly * @enum {string} */ export type Accuracy = 'actual' | 'estimated'; /** * Defines values for Bitness. * Possible values include: '32bit', '64bit' * @readonly * @enum {string} */ export type Bitness = '32bit' | '64bit'; /** * Defines values for VirtualMachineType. * Possible values include: 'unknown', 'hyperv', 'ldom', 'lpar', 'vmware', 'virtualPc', 'xen' * @readonly * @enum {string} */ export type VirtualMachineType = 'unknown' | 'hyperv' | 'ldom' | 'lpar' | 'vmware' | 'virtualPc' | 'xen'; /** * Defines values for HypervisorType. * Possible values include: 'unknown', 'hyperv' * @readonly * @enum {string} */ export type HypervisorType = 'unknown' | 'hyperv'; /** * Defines values for ProcessRole. * Possible values include: 'webServer', 'appServer', 'databaseServer', 'ldapServer', 'smbServer' * @readonly * @enum {string} */ export type ProcessRole = 'webServer' | 'appServer' | 'databaseServer' | 'ldapServer' | 'smbServer'; /** * Defines values for MachineGroupType. * Possible values include: 'unknown', 'azure-cs', 'azure-sf', 'azure-vmss', 'user-static' * @readonly * @enum {string} */ export type MachineGroupType = 'unknown' | 'azure-cs' | 'azure-sf' | 'azure-vmss' | 'user-static'; /** * Defines values for ConnectionFailureState. * Possible values include: 'ok', 'failed', 'mixed' * @readonly * @enum {string} */ export type ConnectionFailureState = 'ok' | 'failed' | 'mixed'; /** * Defines values for AzureCloudServiceRoleType. * Possible values include: 'unknown', 'worker', 'web' * @readonly * @enum {string} */ export type AzureCloudServiceRoleType = 'unknown' | 'worker' | 'web'; /** * Defines values for Provider. * Possible values include: 'azure' * @readonly * @enum {string} */ export type Provider = 'azure'; /** * Defines values for Provider1. * Possible values include: 'azure' * @readonly * @enum {string} */ export type Provider1 = 'azure'; /** * Contains response data for the listByWorkspace operation. */ export type MachinesListByWorkspaceResponse = MachineCollection & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: MachineCollection; }; }; /** * Contains response data for the get operation. */ export type MachinesGetResponse = Machine & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: Machine; }; }; /** * Contains response data for the getLiveness operation. */ export type MachinesGetLivenessResponse = Liveness & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: Liveness; }; }; /** * Contains response data for the listConnections operation. */ export type MachinesListConnectionsResponse = ConnectionCollection & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: ConnectionCollection; }; }; /** * Contains response data for the listProcesses operation. */ export type MachinesListProcessesResponse = ProcessCollection & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: ProcessCollection; }; }; /** * Contains response data for the listPorts operation. */ export type MachinesListPortsResponse = PortCollection & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: PortCollection; }; }; /** * Contains response data for the listMachineGroupMembership operation. */ export type MachinesListMachineGroupMembershipResponse = MachineGroupCollection & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: MachineGroupCollection; }; }; /** * Contains response data for the listByWorkspaceNext operation. */ export type MachinesListByWorkspaceNextResponse = MachineCollection & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: MachineCollection; }; }; /** * Contains response data for the listConnectionsNext operation. */ export type MachinesListConnectionsNextResponse = ConnectionCollection & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: ConnectionCollection; }; }; /** * Contains response data for the listProcessesNext operation. */ export type MachinesListProcessesNextResponse = ProcessCollection & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: ProcessCollection; }; }; /** * Contains response data for the listPortsNext operation. */ export type MachinesListPortsNextResponse = PortCollection & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: PortCollection; }; }; /** * Contains response data for the listMachineGroupMembershipNext operation. */ export type MachinesListMachineGroupMembershipNextResponse = MachineGroupCollection & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: MachineGroupCollection; }; }; /** * Contains response data for the get operation. */ export type ProcessesGetResponse = Process & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: Process; }; }; /** * Contains response data for the getLiveness operation. */ export type ProcessesGetLivenessResponse = Liveness & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: Liveness; }; }; /** * Contains response data for the listAcceptingPorts operation. */ export type ProcessesListAcceptingPortsResponse = PortCollection & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: PortCollection; }; }; /** * Contains response data for the listConnections operation. */ export type ProcessesListConnectionsResponse = ConnectionCollection & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: ConnectionCollection; }; }; /** * Contains response data for the listAcceptingPortsNext operation. */ export type ProcessesListAcceptingPortsNextResponse = PortCollection & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: PortCollection; }; }; /** * Contains response data for the listConnectionsNext operation. */ export type ProcessesListConnectionsNextResponse = ConnectionCollection & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: ConnectionCollection; }; }; /** * Contains response data for the get operation. */ export type PortsGetResponse = Port & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: Port; }; }; /** * Contains response data for the getLiveness operation. */ export type PortsGetLivenessResponse = Liveness & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: Liveness; }; }; /** * Contains response data for the listAcceptingProcesses operation. */ export type PortsListAcceptingProcessesResponse = ProcessCollection & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: ProcessCollection; }; }; /** * Contains response data for the listConnections operation. */ export type PortsListConnectionsResponse = ConnectionCollection & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: ConnectionCollection; }; }; /** * Contains response data for the listAcceptingProcessesNext operation. */ export type PortsListAcceptingProcessesNextResponse = ProcessCollection & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: ProcessCollection; }; }; /** * Contains response data for the listConnectionsNext operation. */ export type PortsListConnectionsNextResponse = ConnectionCollection & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: ConnectionCollection; }; }; /** * Contains response data for the get operation. */ export type ClientGroupsGetResponse = ClientGroup & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: ClientGroup; }; }; /** * Contains response data for the getMembersCount operation. */ export type ClientGroupsGetMembersCountResponse = ClientGroupMembersCount & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: ClientGroupMembersCount; }; }; /** * Contains response data for the listMembers operation. */ export type ClientGroupsListMembersResponse = ClientGroupMembersCollection & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: ClientGroupMembersCollection; }; }; /** * Contains response data for the listMembersNext operation. */ export type ClientGroupsListMembersNextResponse = ClientGroupMembersCollection & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: ClientGroupMembersCollection; }; }; /** * Contains response data for the generate operation. */ export type MapsGenerateResponse = MapResponse & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: MapResponse; }; }; /** * Contains response data for the getMachines operation. */ export type SummariesGetMachinesResponse = MachinesSummary & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: MachinesSummary; }; }; /** * Contains response data for the listByWorkspace operation. */ export type MachineGroupsListByWorkspaceResponse = MachineGroupCollection & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: MachineGroupCollection; }; }; /** * Contains response data for the create operation. */ export type MachineGroupsCreateResponse = MachineGroup & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: MachineGroup; }; }; /** * Contains response data for the get operation. */ export type MachineGroupsGetResponse = MachineGroup & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: MachineGroup; }; }; /** * Contains response data for the update operation. */ export type MachineGroupsUpdateResponse = MachineGroup & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: MachineGroup; }; }; /** * Contains response data for the listByWorkspaceNext operation. */ export type MachineGroupsListByWorkspaceNextResponse = MachineGroupCollection & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: MachineGroupCollection; }; };
the_stack
import { expect } from "chai"; import { IModelConnection, SnapshotConnection } from "@itwin/core-frontend"; import { ContentSpecificationTypes, KeySet, RelationshipDirection, Ruleset, RuleTypes } from "@itwin/presentation-common"; import { Presentation } from "@itwin/presentation-frontend"; import { initialize, terminate } from "../../../IntegrationTests"; import { getFieldByLabel } from "../../../Utils"; import { printRuleset } from "../../Utils"; describe("Learning Snippets", () => { let imodel: IModelConnection; beforeEach(async () => { await initialize(); imodel = await SnapshotConnection.openFile("assets/datasets/Properties_60InstancesWithUrl2.ibim"); }); afterEach(async () => { await imodel.close(); await terminate(); }); describe("Content Specifications", () => { describe("Shared attributes", () => { it("uses `onlyIfNotHandled` attribute", async () => { // __PUBLISH_EXTRACT_START__ Presentation.SharedAttributes.OnlyIfNotHandled.Ruleset // This ruleset defines two specifications that return content for `bis.ViewDefinition` and `bis.PhysicalModel` // instances respectively. const ruleset: Ruleset = { id: "example", rules: [{ ruleType: RuleTypes.Content, specifications: [ { specType: ContentSpecificationTypes.ContentInstancesOfSpecificClasses, classes: { schemaName: "BisCore", classNames: ["ViewDefinition"], arePolymorphic: true }, }, // The following specification is defined second so it's lower in priority. Because it has `onlyIfNotHandled` attribute, // it's overriden by the specification above. { specType: ContentSpecificationTypes.ContentInstancesOfSpecificClasses, classes: { schemaName: "BisCore", classNames: ["PhysicalModel"], arePolymorphic: true }, onlyIfNotHandled: true, }, ], }], }; // __PUBLISH_EXTRACT_END__ printRuleset(ruleset); // Ensure that only `bis.ViewDefinition` instances are selected. const content = await Presentation.presentation.getContent({ imodel, rulesetOrId: ruleset, keys: new KeySet(), descriptor: {}, }); expect(content!.contentSet.length).to.eq(4); const field = getFieldByLabel(content!.descriptor.fields, "Category Selector"); content!.contentSet.forEach((record) => { expect(record.displayValues[field.name]).to.be.string("Default - View"); }); }); it("uses `priority` attribute", async () => { // __PUBLISH_EXTRACT_START__ Presentation.SharedAttributes.Priority.Ruleset // Specifications to return content for `bis.PhysicalModel` and `bis.DictionaryModel` respectively. // The `bis.PhysicalModel` specification has lower priority so it's displayed after the // higher priority specification. const ruleset: Ruleset = { id: "example", rules: [{ ruleType: RuleTypes.Content, specifications: [{ specType: ContentSpecificationTypes.ContentInstancesOfSpecificClasses, classes: { schemaName: "BisCore", classNames: ["PhysicalModel"] }, priority: 0, }, { specType: ContentSpecificationTypes.ContentInstancesOfSpecificClasses, classes: { schemaName: "BisCore", classNames: ["DictionaryModel"] }, priority: 1, }], }], }; // __PUBLISH_EXTRACT_END__ printRuleset(ruleset); // Ensure that only `bis.ViewDefinition` instances are selected. const content = await Presentation.presentation.getContent({ imodel, rulesetOrId: ruleset, keys: new KeySet(), descriptor: {}, }); expect(content!.contentSet.length).to.eq(2); const field = getFieldByLabel(content!.descriptor.fields, "Modeled Element"); expect(content!.contentSet[0].displayValues[field.name]).to.eq("BisCore.DictionaryModel"); expect(content!.contentSet[1].displayValues[field.name]).to.eq("Properties_60InstancesWithUrl2"); }); it("uses `relatedProperties` attribute", async () => { // __PUBLISH_EXTRACT_START__ Presentation.SharedAttributes.RelatedProperties.Ruleset // This ruleset returns content for `bis.SpatialViewDefinition`, which includes all properties from related `bis.DisplayStyle` instances. const ruleset: Ruleset = { id: "example", rules: [{ ruleType: RuleTypes.Content, specifications: [{ specType: ContentSpecificationTypes.ContentInstancesOfSpecificClasses, classes: { schemaName: "BisCore", classNames: ["SpatialViewDefinition"] }, relatedProperties: [{ propertiesSource: { relationship: { schemaName: "BisCore", className: "ViewDefinitionUsesDisplayStyle" }, direction: RelationshipDirection.Forward, }, }], }], }], }; // __PUBLISH_EXTRACT_END__ printRuleset(ruleset); // Ensure that derived `bis.DisplayStyle` instance properties are also returned with `bis.SpatialViewDefinition` content. const content = await Presentation.presentation.getContent({ imodel, rulesetOrId: ruleset, keys: new KeySet(), descriptor: {}, }); expect(content!.contentSet.length).to.eq(4); expect(content!.descriptor.fields).to.containSubset([{ label: "Display Style", nestedFields: [{ label: "Model" }, { label: "Code" }, { label: "User Label" }, { label: "Is Private" }], }]).and.to.have.lengthOf(18); }); it("uses `calculatedProperties` attribute", async () => { // __PUBLISH_EXTRACT_START__ Presentation.SharedAttributes.CalculatedProperties.Ruleset // In addition to returning content for all `bis.SpatialViewDefinition` instances, this ruleset also adds a // custom `Camera view direction` property to each instance. const ruleset: Ruleset = { id: "example", rules: [{ ruleType: RuleTypes.Content, specifications: [{ specType: ContentSpecificationTypes.ContentInstancesOfSpecificClasses, classes: { schemaName: "BisCore", classNames: ["SpatialViewDefinition"] }, calculatedProperties: [{ label: "Camera view direction", value: "IIf (this.pitch >= 10, \"Vertical upwards\", IIf (this.pitch <= -10, \"Vertical downwards\", \"Horizontal\"))", }], }], }], }; // __PUBLISH_EXTRACT_END__ printRuleset(ruleset); // Ensure that derived `bis.DisplayStyle` instance properties are also returned with `bis.SpatialViewDefinition` content. const content = await Presentation.presentation.getContent({ imodel, rulesetOrId: ruleset, keys: new KeySet(), descriptor: {}, }); expect(content!.contentSet.length).to.eq(4); expect(content!.descriptor.fields).to.containSubset([ { label: "Camera view direction" }, ]).and.to.have.lengthOf(18); }); it("uses `propertyCategories` attribute", async () => { // __PUBLISH_EXTRACT_START__ Presentation.SharedAttributes.PropertyCategories.Ruleset // This ruleset places camera-related `bis.SpatialViewDefinition` properties inside a custom category. const ruleset: Ruleset = { id: "example", rules: [{ ruleType: RuleTypes.Content, specifications: [{ specType: ContentSpecificationTypes.ContentInstancesOfSpecificClasses, classes: { schemaName: "BisCore", classNames: ["SpatialViewDefinition"] }, propertyCategories: [{ id: "camera_category", label: "Camera settings", autoExpand: true, }], propertyOverrides: [ { name: "EyePoint", categoryId: "camera_category" }, { name: "FocusDistance", categoryId: "camera_category" }, { name: "IsCameraOn", categoryId: "camera_category" }, ], }], }], }; // __PUBLISH_EXTRACT_END__ printRuleset(ruleset); // Ensure that the returned content has a custom category `Camera settings` and it contains the right properties. const content = await Presentation.presentation.getContent({ imodel, rulesetOrId: ruleset, keys: new KeySet(), descriptor: {}, }); expect(content!.descriptor.categories).containSubset([{ label: "Camera settings" }]); expect(content!.descriptor.fields).to.containSubset([{ label: "Eye Point", category: { label: "Camera settings" }, }, { label: "Focus Distance", category: { label: "Camera settings" }, }, { label: "Is Camera On", category: { label: "Camera settings" }, }]); }); it("uses `propertyOverrides` attribute", async () => { // __PUBLISH_EXTRACT_START__ Presentation.SharedAttributes.PropertyOverrides.Ruleset // The specification returns content for `bis.ViewDefinition` with one // overriden property label. const ruleset: Ruleset = { id: "example", rules: [{ ruleType: RuleTypes.Content, specifications: [{ specType: ContentSpecificationTypes.ContentInstancesOfSpecificClasses, classes: { schemaName: "BisCore", classNames: ["ViewDefinition"], arePolymorphic: true }, propertyOverrides: [{ name: "Model", labelOverride: "Container Model" }], }], }], }; // __PUBLISH_EXTRACT_END__ printRuleset(ruleset); // Ensure that the returned content has an overriden property label `Container Model`. const content = await Presentation.presentation.getContent({ imodel, rulesetOrId: ruleset, keys: new KeySet(), descriptor: {}, }); expect(content!.contentSet.length).to.eq(4); expect(content!.descriptor.fields).to.containSubset([ { label: "Category Selector" }, { label: "Code" }, { label: "Container Model" }, { label: "Description" }, { label: "Display Style" }, { label: "Is Private" }, { label: "User Label" }, ]).and.to.have.lengthOf(7); }); it("uses `relatedInstances` attribute", async () => { // __PUBLISH_EXTRACT_START__ Presentation.SharedAttributes.RelatedInstances.Ruleset // The specification returns content for `bis.ModelSelector` filtered by related // `bis.SpatialViewDefinition` instance `Yaw` property value. const ruleset: Ruleset = { id: "example", rules: [{ ruleType: RuleTypes.Content, specifications: [{ specType: ContentSpecificationTypes.ContentInstancesOfSpecificClasses, classes: { schemaName: "BisCore", classNames: ["ModelSelector"], arePolymorphic: true }, relatedInstances: [{ relationshipPath: { relationship: { schemaName: "BisCore", className: "SpatialViewDefinitionUsesModelSelector" }, direction: RelationshipDirection.Backward }, alias: "relatedInstance", }], instanceFilter: "relatedInstance.Yaw > 0", }], }], }; // __PUBLISH_EXTRACT_END__ printRuleset(ruleset); // Ensure only the `bis.ModelSelector` whose related SpatialViewDefinition with Yaw > 0 is returned. const content = await Presentation.presentation.getContent({ imodel, rulesetOrId: ruleset, keys: new KeySet(), descriptor: {}, }); expect(content!.contentSet.length).to.eq(1); const field = getFieldByLabel(content!.descriptor.fields, "Code"); expect(content!.contentSet[0].values[field.name]).to.eq("Default - View 2"); }); }); }); });
the_stack
import * as assert from 'assert'; import { EventEmitter } from 'events'; import * as mockery from 'mockery'; import { IMock, It, Mock, MockBehavior, Times } from 'typemoq'; import { chromeConnection, ISourceMapPathOverrides, telemetry, TargetVersions, Version } from 'vscode-chrome-debug-core'; import { DebugProtocol } from 'vscode-debugprotocol'; import { ChromeDebugAdapter as _ChromeDebugAdapter } from '../src/chromeDebugAdapter'; import { getMockChromeConnectionApi, IMockChromeConnectionAPI } from './debugProtocolMocks'; import * as testUtils from './testUtils'; import { ChromeProvidedPortConnection } from '../src/chromeProvidedPortConnection'; class MockChromeDebugSession { public sendEvent(event: DebugProtocol.Event): void { } public sendRequest(command: string, args: any, timeout: number, cb: (response: DebugProtocol.Response) => void): void { } } const MODULE_UNDER_TEST = '../src/chromeDebugAdapter'; suite('ChromeDebugAdapter', () => { let mockChromeConnection: IMock<ChromeProvidedPortConnection>; let mockEventEmitter: EventEmitter; let mockChrome: IMockChromeConnectionAPI; let mockChromeDebugSession: IMock<MockChromeDebugSession>; let chromeDebugAdapter: _ChromeDebugAdapter; setup(() => { testUtils.setupUnhandledRejectionListener(); testUtils.registerLocMocks(); mockery.enable({ useCleanCache: true, warnOnReplace: false, warnOnUnregistered: false }); // Create a ChromeConnection mock with .on and .attach. Tests can fire events via mockEventEmitter mockChromeConnection = Mock.ofType(ChromeProvidedPortConnection, MockBehavior.Strict); mockChrome = getMockChromeConnectionApi(); mockEventEmitter = mockChrome.mockEventEmitter; mockChromeDebugSession = Mock.ofType(MockChromeDebugSession, MockBehavior.Strict); mockChromeDebugSession .setup(x => x.sendEvent(It.isAny())) .verifiable(Times.atLeast(0)); mockChromeDebugSession .setup(x => x.sendRequest(It.isAnyString(), It.isAny(), It.isAnyNumber(), It.isAny())) .verifiable(Times.atLeast(0)); mockChromeConnection .setup(x => x.setTargetFilter(It.isAny())) .verifiable(Times.atLeast(0)); mockChromeConnection .setup(x => x.api) .returns(() => mockChrome.apiObjects) .verifiable(Times.atLeast(0)); mockChromeConnection .setup(x => x.attach(It.isValue(undefined), It.isAnyNumber(), It.isValue(undefined))) .returns(() => Promise.resolve()) .verifiable(Times.atLeast(0)); mockChromeConnection .setup(x => x.isAttached) .returns(() => false) .verifiable(Times.atLeast(0)); mockChromeConnection .setup(x => x.run()) .returns(() => Promise.resolve()) .verifiable(Times.atLeast(0)); mockChromeConnection .setup(x => x.onClose(It.isAny())) .verifiable(Times.atLeast(0)); mockChromeConnection .setup(x => x.events) .returns(x => null) .verifiable(Times.atLeast(0)); mockChromeConnection .setup(x => x.version) .returns(() => Promise.resolve(new TargetVersions(Version.unknownVersion(), Version.unknownVersion()))) .verifiable(Times.atLeast(0)); mockChromeConnection .setup(x => x.setUserDataDir(It.isAnyString())) .verifiable(Times.atLeast(0)); // Instantiate the ChromeDebugAdapter, injecting the mock ChromeConnection const cDAClass: typeof _ChromeDebugAdapter = require(MODULE_UNDER_TEST).ChromeDebugAdapter; chromeDebugAdapter = new cDAClass({ chromeConnection: function() { return mockChromeConnection.object; } } as any, mockChromeDebugSession.object as any); }); teardown(() => { testUtils.removeUnhandledRejectionListener(); mockery.deregisterAll(); mockery.disable(); mockChromeConnection.verifyAll(); }); suite('launch()', () => { let originalFork: any; let originalSpawn: any; let originalStatSync: any; setup(() => { mockChromeConnection .setup(x => x.attach(It.isValue(undefined), It.isAnyNumber(), It.isAnyString(), It.isValue(undefined), It.isValue(undefined))) .returns(() => Promise.resolve()) .verifiable(); mockChrome.Runtime .setup(x => x.evaluate(It.isAny())) .returns(() => Promise.resolve<any>({ result: { type: 'string', value: '123' }})); mockChrome.Network .setup(x => x.setCacheDisabled(It.isAny())) .returns(() => Promise.resolve()); }); teardown(() => { // Hacky mock cleanup require('child_process').fork = originalFork; require('fs').statSync = originalStatSync; }); test('launches with minimal correct args', () => { let spawnCalled = false; function fork(chromeSpawnHelperPath: string, [chromePath, ...args]: string[]): any { // Just assert that the chrome path is some string with 'chrome' in the path, and there are >0 args assert(chromeSpawnHelperPath.indexOf('chromeSpawnHelper.js') >= 0); return spawn(chromePath, args); } function spawn(chromePath: string, args: string[]): any { assert(chromePath.toLowerCase().indexOf('chrome') >= 0); assert(args.indexOf('--remote-debugging-port=9222') >= 0); assert(args.indexOf('about:blank') >= 0); // Now we use the landing page for all scenarios assert(args.indexOf('abc') >= 0); assert(args.indexOf('def') >= 0); spawnCalled = true; const stdio = { on: () => { } }; return { on: () => { }, unref: () => { }, stdout: stdio, stderr: stdio }; } // Mock fork/spawn for chrome process, and 'fs' for finding chrome.exe. // These are mocked as empty above - note that it's too late for mockery here. originalFork = require('child_process').fork; originalSpawn = require('child_process').spawn; require('child_process').fork = fork; require('child_process').spawn = spawn; originalStatSync = require('fs').statSync; require('fs').statSync = () => true; return chromeDebugAdapter.launch({ file: 'c:\\path with space\\index.html', runtimeArgs: ['abc', 'def'] }, new telemetry.TelemetryPropertyCollector()) .then(() => assert(spawnCalled)); }); test('launches unelevated with client', async () => { let telemetryPropertyCollector = new telemetry.TelemetryPropertyCollector(); chromeDebugAdapter.initialize({ adapterID: 'test debug adapter', pathFormat: 'path', supportsLaunchUnelevatedProcessRequest: true }); const originalGetPlatform = require('os').platform; require('os').platform = () => { return 'win32'; }; const originalGetBrowser = require('../src/utils').getBrowserPath; require('../src/utils').getBrowserPath = () => { return 'c:\\someplace\\chrome.exe'; }; const expectedProcessId = 325; let collectedLaunchParams: any; mockChromeDebugSession .setup(x => x.sendRequest('launchUnelevated', It.is((param: any) => { collectedLaunchParams = param; return true; }), 10000, It.is( (callback: (response: DebugProtocol.Response) => void) => { callback({ seq: null, type: 'command', request_seq: 100, command: 'launchUnelevated', success: true, body: { processId: expectedProcessId } }); return true; }))) .verifiable(Times.atLeast(1)); await chromeDebugAdapter.launch({ file: 'c:\\path with space\\index.html', runtimeArgs: ['abc', 'def'], shouldLaunchChromeUnelevated: true }, telemetryPropertyCollector); assert.equal(expectedProcessId, (<any>chromeDebugAdapter)._chromePID, 'Debug Adapter should receive the Chrome process id'); assert(collectedLaunchParams.process != null); assert(collectedLaunchParams.process.match(/chrome/i)); assert(collectedLaunchParams.args != null); assert(collectedLaunchParams.args.filter(arg => arg === '--no-default-browser-check').length !== 0, 'Should have seen the --no-default-browser-check parameter'); assert(collectedLaunchParams.args.filter(arg => arg === '--no-first-run').length !== 0, 'Should have seen the --no-first-run parameter'); assert(collectedLaunchParams.args.filter(arg => arg === 'abc').length !== 0, 'Should have seen the abc parameter'); assert(collectedLaunchParams.args.filter(arg => arg === 'def').length !== 0, 'Should have seen the def parameter'); assert(collectedLaunchParams.args.filter(arg => arg === 'about:blank').length !== 0, 'Should have seen the about:blank parameter'); assert(collectedLaunchParams.args.filter(arg => arg.match(/remote-debugging-port/)).length !== 0, 'Should have seen a parameter like remote-debugging-port'); assert(collectedLaunchParams.args.filter(arg => arg.match(/user-data-dir/)).length !== 0, 'Should have seen a parameter like user-data-dir'); const telemetryProperties = telemetryPropertyCollector.getProperties(); assert.equal(telemetryProperties.shouldLaunchChromeUnelevated, 'true', "Should send telemetry that Chrome is requested to be launched unelevated.'"); assert.equal(telemetryProperties.doesHostSupportLaunchUnelevated, 'true', "Should send telemetry that host supports launcheing Chrome unelevated.'"); require('os').platform = originalGetPlatform; require('../src/utils').getBrowserPath = originalGetBrowser; }); }); suite('resolveWebRootPattern', () => { const WEBROOT = testUtils.pathResolve('/project/webroot'); const resolveWebRootPattern = require(MODULE_UNDER_TEST).resolveWebRootPattern; test('does nothing when no ${webRoot} present', () => { const overrides: ISourceMapPathOverrides = { '/src': '/project' }; assert.deepEqual( resolveWebRootPattern(WEBROOT, overrides), overrides); }); test('resolves the webRoot pattern', () => { assert.deepEqual( resolveWebRootPattern(WEBROOT, <ISourceMapPathOverrides>{ '/src': '${webRoot}/app/src'}), { '/src': WEBROOT + '/app/src' }); assert.deepEqual( resolveWebRootPattern(WEBROOT, <ISourceMapPathOverrides>{ '${webRoot}/src': '${webRoot}/app/src'}), { [WEBROOT + '/src']: WEBROOT + '/app/src'}); }); test(`ignores the webRoot pattern when it's not at the beginning of the string`, () => { const overrides: ISourceMapPathOverrides = { '/another/${webRoot}/src': '/app/${webRoot}/src'}; assert.deepEqual( resolveWebRootPattern(WEBROOT, overrides), overrides); }); test('works on a set of overrides', () => { const overrides: ISourceMapPathOverrides = { '/src*': '${webRoot}/app', '*/app.js': '*/app.js', '/src/app.js': '/src/${webRoot}', '/app.js': '${webRoot}/app.js', '${webRoot}/app1.js': '${webRoot}/app.js' }; const expOverrides: ISourceMapPathOverrides = { '/src*': WEBROOT + '/app', '*/app.js': '*/app.js', '/src/app.js': '/src/${webRoot}', '/app.js': WEBROOT + '/app.js', [WEBROOT + '/app1.js']: WEBROOT + '/app.js' }; assert.deepEqual( resolveWebRootPattern(WEBROOT, overrides), expOverrides); }); }); });
the_stack
import queryString from 'querystringify'; import moment, { isDate, isMoment } from 'moment'; import { isArrayLike, ObservableMap } from 'mobx'; import { AxiosRequestConfig } from 'axios'; import isBoolean from 'lodash/isBoolean'; import isObject from 'lodash/isObject'; import isString from 'lodash/isString'; import isArray from 'lodash/isArray'; import isNumber from 'lodash/isNumber'; import isNil from 'lodash/isNil'; import _isEmpty from 'lodash/isEmpty'; import { isEmpty, parseNumber, warning } from '../utils'; import Field, { FieldProps, Fields } from './Field'; // import XLSX from 'xlsx'; import { BooleanValue, DataToJSON, FieldType, RecordStatus, SortOrder } from './enum'; import DataSet, { DataSetProps } from './DataSet'; import Record, { RecordDynamicProps } from './Record'; import Group from './Group'; import * as ObjectChainValue from '../object-chain-value'; import localeContext, { $l } from '../locale-context'; import { SubmitTypes, TransportType, TransportTypes } from './Transport'; import { formatString } from '../formatter'; import { treeReduce } from '../tree-helper'; import { iteratorFilterToArray, iteratorFind, iteratorSliceToArray, iteratorSome } from '../iterator-helper'; export const defaultTextField = 'meaning'; export const defaultValueField = 'value'; export function useNormal(dataToJSON: DataToJSON): boolean { return [DataToJSON.normal, DataToJSON['normal-self']].includes(dataToJSON); } export function useAll(dataToJSON: DataToJSON): boolean { return [DataToJSON.all, DataToJSON['all-self']].includes(dataToJSON); } export function useSelected(dataToJSON: DataToJSON): boolean { return [DataToJSON.selected, DataToJSON['selected-self']].includes(dataToJSON); } export function useCascade(dataToJSON: DataToJSON): boolean { return [DataToJSON.dirty, DataToJSON['dirty-field'], DataToJSON.selected, DataToJSON.all, DataToJSON.normal].includes( dataToJSON, ); } export function useDirty(dataToJSON: DataToJSON): boolean { return [DataToJSON.dirty, DataToJSON['dirty-self']].includes(dataToJSON); } export function useDirtyField(dataToJSON: DataToJSON): boolean { return [DataToJSON['dirty-field'], DataToJSON['dirty-field-self']].includes(dataToJSON); } export function append(url: string, suffix?: object) { if (suffix) { return url + queryString.stringify(suffix, url.indexOf('?') === -1); } return url; } export function getOrderFields(dataSet: DataSet): Field[] { const { fields, props: { combineSort } } = dataSet; if (combineSort) { return iteratorFilterToArray(fields.values(), (field) => field.order); } const found = iteratorFind(fields.values(), (field) => field.order); if (found) { return [found]; } return []; } function processOneToJSON(value, field: Field, record?: Record, checkRange = true) { if (!isEmpty(value)) { const range = field.get('range', record); if (range && checkRange) { if (isArrayLike(range)) { if (isObject(value)) { const [start, end] = range; value = { [start]: processOneToJSON(value[start], field, record, false), [end]: processOneToJSON(value[end], field, record, false), }; } } else if (isArrayLike(value)) { value = [ processOneToJSON(value[0], field, record, false), processOneToJSON(value[1], field, record, false), ]; } } else { if (isDate(value)) { value = moment(value); } if (isMoment(value)) { const { jsonDate } = field.dataSet.getConfig('formatter'); value = jsonDate ? value.format(jsonDate) : +value; } if (field.get('type', record) === FieldType.json) { value = JSON.stringify(value); } } } return value; } export function processToJSON(value, field: Field, record?: Record) { if (!isEmpty(value)) { const multiple = field.get('multiple', record); const range = field.get('range', record); if (isArrayLike(value) && (multiple || !range)) { value = value.map(v => processOneToJSON(v, field, record)); if (isString(multiple)) { return value.join(multiple); } return value; } return processOneToJSON(value, field, record); } return value; } export function arrayMove<T = Record>(array: T[], from: number, to: number): void { const startIndex = to < 0 ? array.length + to : to; const item = array.splice(from, 1)[0]; array.splice(startIndex, 0, item); } function processOne(value: any, field: Field, record?: Record, checkRange = true) { if (!isEmpty(value)) { const range = field.get('range', record); if (range && checkRange) { if (isArrayLike(range)) { if (isObject(value)) { const [start, end] = range; value[start] = processOne(value[start], field, record, false); value[end] = processOne(value[end], field, record, false); } } else if (isArrayLike(value)) { value[0] = processOne(value[0], field, record, false); value[1] = processOne(value[1], field, record, false); } } else if (value instanceof Date) { value = moment(value); } else if (!isObject(value)) { value = formatString(value, { trim: field.get('trim', record), format: field.get('format', record), }); switch (field.get('type', record)) { case FieldType.boolean: { const trueValue = field.get(BooleanValue.trueValue, record); const falseValue = field.get(BooleanValue.falseValue, record); if (value !== trueValue) { value = falseValue; } break; } case FieldType.number: case FieldType.currency: if (!isNaN(value)) { value = parseNumber(value, field.get('precision', record)); } else { value = undefined; } break; case FieldType.string: case FieldType.intl: case FieldType.email: case FieldType.url: value = String(value); break; case FieldType.date: case FieldType.dateTime: case FieldType.time: case FieldType.week: case FieldType.month: case FieldType.year: { const { jsonDate } = field.dataSet.getConfig('formatter'); value = jsonDate ? moment(value, jsonDate) : moment(value); break; } case FieldType.json: value = JSON.parse(value); break; default: } } } return value; } export function processValue(value: any, field?: Field, record?: Record, isCreated?: boolean): any { if (field) { const multiple = field.get('multiple', record); const range = field.get('range', record); if (multiple && field.get('type', record) !== FieldType.attachment) { if (isEmpty(value)) { if (isCreated) { // for defaultValue value = undefined; } else { value = []; } } else if (!isArray(value)) { if (isString(multiple) && isString(value)) { value = value.split(multiple); } else { value = [value]; } } } if (isArray(value) && (multiple || !range)) { return value.map(item => processOne(item, field, record)); } return processOne(value, field, record); } return value; } // 处理单个range const processRangeToText = (resultValue: any[], field: Field, record?: Record | undefined): string => { return resultValue.map((item) => { const valueRange = isMoment(item) ? item.format() : isObject(item) ? item[field.get('textField', record)] : item.toString(); return valueRange; }).join(`~`); }; export function processExportValue(value: any, field?: Field, record?: Record | undefined): any { if (field) { const multiple = field.get('multiple', record); const range = field.get('range', record); const textField = field.get('textField', record); if (multiple) { if (isEmpty(value)) { value = []; } else if (!isArray(value)) { if (isString(multiple) && isString(value)) { value = value.split(multiple); } else { value = [value]; } } } if (isArray(value) && (multiple || !range)) { if (!_isEmpty(field.getLookup(record))) { return value.map(item => field.getText(processOne(item, field, record), undefined, record)).join(','); } return value.map(item => { const itemValue = processOne(item, field, record); if (textField && itemValue && isObject(itemValue)) { return itemValue[textField]; } return itemValue; }).join(','); } if (isArray(value) && multiple && range) { if (!_isEmpty(field.getLookup(record))) { return value.map(item => field.getText(processRangeToText(processOne(item, field, record), field, record))).join(','); } return value.map(item => { return processRangeToText(processOne(item, field, record), field, record); }).join(','); } if (!_isEmpty(field.getLookup(record))) { return field.getText(processOne(value, field, record), undefined, record); } const resultValue = processOne(value, field, record); if (isMoment(resultValue)) { return resultValue.format(); } if (textField && resultValue && isObject(resultValue)) { if (range && isArrayLike(resultValue)) { return processRangeToText(resultValue, field, record); } return resultValue[textField]; } return resultValue; } return value; } /** * 实现如果名字是带有属性含义`.`找到能够导出的值 * @param dataItem 一行数据 * @param name 对应的fieldname * @param isBind 是否是从绑定获取值 */ export function getSplitValue(dataItem: any, name: string, isBind = true): any { const nameArray = name.split('.'); if (nameArray.length > 1) { let levelValue = dataItem; for (let i = 0; i < nameArray.length; i++) { if (!isObject(levelValue)) { break; } if (isBind || i !== 0) { levelValue = levelValue[nameArray[i]]; } } return levelValue; } if (isBind) { return dataItem ? dataItem[name] : undefined; } return dataItem; } export function childrenInfoForDelete(json: {}, children: { [key: string]: DataSet }): {} { return Object.keys(children).reduce((data, name) => { const child = children[name]; if (child) { data[name] = [childrenInfoForDelete({}, child.children)]; } return data; }, json); } function dataSorter<T>(fields: Field[], getter: (item: T, key: string) => any): (a: T, b: T) => number { const m = Number.MIN_SAFE_INTEGER; return (record1, record2) => { let result = 0; fields.some(field => { const { name, order } = field; const a = getter(record1, name) || m; const b = getter(record2, name) || m; if (isString(a) || isString(b)) { result = order === SortOrder.asc ? String(a).localeCompare(String(b)) : String(b).localeCompare(String(a)); } else { result = order === SortOrder.asc ? a - b : b - a; } return result !== 0; }); return result; }; } export function sortData(data: object[], dataSet: DataSet): object[] { if (data.length > 1 && !dataSet.paging) { const orderFields = getOrderFields(dataSet); if (orderFields.length > 0) { data.sort(dataSorter<object>(orderFields, (item, key) => item[key])); const { childrenField } = dataSet.props; if (childrenField) { data.forEach(item => { const childData = item[childrenField]; if (childData) { sortData(childData, dataSet); } }); } } } return data; } export function appendRecords(dataSet: DataSet, appendData: Record[], parent?: Record) { if (appendData.length) { const { originalData, records, props: { childrenField, parentField, idField } } = dataSet; let appended = false; if (childrenField) { if (parent) { appendData.forEach(record => { const { key } = record; const { children } = parent; if (children) { if (!children.find(child => child.key === key)) { children.push(record); } } else { parent.children = [record]; } if (!records.find(r => r.key === key)) { originalData.push(record); records.push(record); } }); appended = true; } } else if (parentField && idField) { appendData.forEach(record => { const parentId = record.get(parentField); const { key } = record; let found; let foundParent; records.some(r => { if (r.get(idField) === parentId) { record.parent = r; const { children } = r; if (children) { if (!children.find(child => child.key === key)) { children.push(record); } } else { r.children = [record]; } foundParent = r; } if (r.key === key) { found = r; } return found && foundParent; }); if (!found) { originalData.push(record); records.push(record); } }); appended = true; } if (!appended) { appendData.forEach(record => { const { key } = record; if (!records.find(r => r.key === key)) { originalData.push(record); records.push(record); } }); } } } export function sortTree(records: Record[], orderFields: Field[], deep?: boolean): Record[] { if (records.length > 1 && orderFields.length > 0) { if (deep) { records.forEach(child => { const { children } = child; if (children) { child.children = sortTree(children, orderFields, true); } }); } return records.sort(dataSorter<Record>(orderFields, (item, key) => item.get(key))); } return records; } interface Node { item: object; children: Node[]; } // 获取单个页面能够展示的数据 export function sliceTree(idField: string, parentField: string, allData: object[], pageSize: number): object[] { if (allData.length) { const rootMap: Map<string, Node> = new Map<string, Node>(); const itemMap: Map<string, Node> = new Map<string, Node>(); allData.forEach((item) => { const id = item[idField]; if (!isNil(id)) { const node: Node = { item, children: [], }; itemMap.set(id, node); rootMap.set(id, node); } }); itemMap.forEach((node, key) => { const parent = itemMap.get(node.item[parentField]); if (parent) { parent.children.push(node); rootMap.delete(key); } }); return treeReduce<object[], Node>(iteratorSliceToArray(rootMap.values(), 0, pageSize), (previousValue, node) => previousValue.concat(node.item), []); } return []; } export function checkParentByInsert({ parent }: DataSet) { if (parent && !parent.current) { throw new Error($l('DataSet', 'cannot_add_record_when_head_no_current')); } } function getValueType(value: any): FieldType { return isBoolean(value) ? FieldType.boolean : isNumber(value) ? FieldType.number : isString(value) ? FieldType.string : isMoment(value) ? FieldType.date : isObject(value) ? FieldType.object : FieldType.auto; } export function getBaseType(type: FieldType): FieldType { switch (type) { case FieldType.number: case FieldType.currency: return FieldType.number; case FieldType.dateTime: case FieldType.time: case FieldType.week: case FieldType.month: case FieldType.year: return FieldType.date; case FieldType.intl: case FieldType.url: case FieldType.email: return FieldType.string; default: return type; } } export function checkFieldType(value: any, field: Field, record?: Record): boolean { if (process.env.NODE_ENV !== 'production' && !isEmpty(value)) { const fieldType = getBaseType(field.get('type', record)); if (fieldType !== FieldType.auto) { if (isArrayLike(value)) { return value.every(item => checkFieldType(item, field, record)); } const valueType = field.get('type', record) === FieldType.boolean && [field.get(BooleanValue.trueValue, record), field.get(BooleanValue.falseValue, record)].includes(value) ? FieldType.boolean : getValueType(value); if ( fieldType !== FieldType.reactNode && fieldType !== valueType ) { warning( false, `Value type error: The value<${value}>'s type is ${valueType}, but the field<${field.name}>'s type is ${fieldType}.`, ); return false; } } } return true; } let iframe; /** * 目前定义为服务端请求的方法 * @param url 导出地址 * @param data 导出传递参数 * @param method 默认post请求 */ export function doExport(url, data, method = 'post') { if (!iframe) { iframe = document.createElement('iframe'); iframe.id = '_export_window'; iframe.name = '_export_window'; iframe.style.cssText = 'position:absolute;left:-10000px;top:-10000px;width:1px;height:1px;display:none'; document.body.appendChild(iframe); } const form = document.createElement('form'); form.target = '_export_window'; form.method = method; form.action = url; const s = document.createElement('input'); s.id = '_request_data'; s.type = 'hidden'; s.name = '_request_data'; s.value = JSON.stringify(data); form.appendChild(s); document.body.appendChild(form); form.submit(); document.body.removeChild(form); } function throwCycleBindingFields(map: Map<string, Field> = new Map()) { const keys = Array.from(map.keys()); throw new Error(`DataSet: Cycle binding fields[${[...keys].join(' -> ')} -> ${keys[0]}].`); } function getChainFieldNamePrivate(record: Record, fieldName: string, linkedMap: Map<string, Field> = new Map(), init = true): string { const field = record.dataSet.getField(fieldName); if (field) { const bind = field.get('bind', record); if (bind) { if (linkedMap.has(fieldName)) { throwCycleBindingFields(linkedMap); } linkedMap.set(fieldName, field); const names = bind.split('.'); if (names.length > 0) { if (names.length === 1) { return getChainFieldNamePrivate(record, bind, linkedMap); } return names.reduce((chainFieldName, name) => [getChainFieldNamePrivate(record, chainFieldName, linkedMap, false), name].join('.')); } } } else if (init && fieldName.indexOf('.') > -1) { return fieldName.split('.').reduce((chainFieldName, name) => [getChainFieldNamePrivate(record, chainFieldName, linkedMap, false), name].join('.')); } return fieldName; } export function getChainFieldName(record: Record, fieldName: string): string { return getChainFieldNamePrivate(record, fieldName); } export function findBindTargetFields(myField: Field, fields: Fields, deep?: boolean, record?: Record, bindFields: Map<string, Field> = new Map()): Field[] { const bind = myField.get('bind', record); if (bind) { iteratorSome(fields.entries(), ([fieldName, field]) => { if (field !== myField) { if ((bind === fieldName || bind.startsWith(`${fieldName}.`))) { if (bindFields.has(fieldName)) { throwCycleBindingFields(bindFields); } bindFields.set(fieldName, field); if (deep) { findBindTargetFields(field, fields, deep, record, bindFields); } return true; } } return false; }); } return Array.from(bindFields.values()); } export function findBindFields(myField: Field, fields: Fields, deep?: boolean, record?: Record | undefined, bindFields: Map<string, Field> = new Map()): Field[] { const { name } = myField; fields.forEach((field, fieldName) => { if (field !== myField) { const bind = field.get('bind', record); if (bind && (bind === name || bind.startsWith(`${name}.`))) { if (bindFields.has(fieldName)) { throwCycleBindingFields(bindFields); } bindFields.set(fieldName, field); if (deep) { findBindFields(field, fields, deep, record, bindFields); } } } }); return Array.from(bindFields.values()); } export function findBindField( myField: string, chainFieldName: string, record: Record, ): Field | undefined { return iteratorFind(record.dataSet.fields.values(), (field) => { const fieldName = field.name; if (fieldName !== myField) { const bind = field.get('bind', record); if (bind) { return chainFieldName === getChainFieldName(record, fieldName); } } return false; }); } export function generateRecordJSONData(array: object[], record: Record, dataToJSON: DataToJSON) { const normal = useNormal(dataToJSON); const json = normal ? !record.isRemoved && record.toData() : record.toJSONData(); if (json && (normal || useAll(dataToJSON) || (!useDirty(dataToJSON) && !useDirtyField(dataToJSON)) || json.__dirty)) { delete json.__dirty; array.push(json); } } export function prepareSubmitData( records: Record[], dataToJSON: DataToJSON, ): [object[], object[], object[]] { const created: object[] = []; const updated: object[] = []; const destroyed: object[] = []; function storeWith(status) { switch (status) { case RecordStatus.add: return created; case RecordStatus.delete: return destroyed; default: return updated; } } records.forEach(record => generateRecordJSONData(storeWith(record.status), record, dataToJSON)); return [created, updated, destroyed]; } function defaultAxiosConfigAdapter(config: AxiosRequestConfig): AxiosRequestConfig { return config; } function generateConfig( config: TransportType, dataSet: DataSet, data?: any, params?: any, options?: object, ): AxiosRequestConfig { if (isString(config)) { return { url: config, }; } if (typeof config === 'function') { return config({ ...options, data, dataSet, params }); } return config; } export function axiosConfigAdapter( type: TransportTypes, dataSet: DataSet, data?: any, params?: any, options?: object, ): AxiosRequestConfig { const newConfig: AxiosRequestConfig = { data, params, method: 'post', }; const { [type]: globalConfig, adapter: globalAdapter = defaultAxiosConfigAdapter } = dataSet.getConfig('transport') || {}; const { [type]: config, adapter } = dataSet.transport; if (globalConfig) { Object.assign(newConfig, generateConfig(globalConfig, dataSet, data, params, options)); } if (config) { Object.assign(newConfig, generateConfig(config, dataSet, data, params, options)); } if (newConfig.data && newConfig.method && newConfig.method.toLowerCase() === 'get') { newConfig.params = { ...newConfig.params, ...newConfig.data, }; } return (adapter || globalAdapter)(newConfig, type) || newConfig; } // 查询顶层父亲节点 export function findRootParent(children: Record) { if (children.parent) { return findRootParent(children.parent); } return children; } export function prepareForSubmit( type: SubmitTypes, data: object[], configs: AxiosRequestConfig[], dataSet: DataSet, ): object[] { if (data.length) { const newConfig = axiosConfigAdapter(type, dataSet, data); if (newConfig.url) { configs.push(newConfig); } else { return data; } } return []; } export function generateResponseData(item: any, dataKey?: string): object[] { if (item) { if (isArray(item)) { return item; } if (isObject(item)) { if (dataKey) { const result = ObjectChainValue.get(item, dataKey); if (result === undefined) { return [item]; } if (isArray(result)) { return result; } if (isObject(result)) { return [result]; } } else { return [item]; } } } return []; } export function getRecordValue( record: Record, cb: (record: Record, fieldName: string) => boolean, fieldName?: string | string[], ) { if (fieldName) { if (isArrayLike(fieldName)) { return fieldName.reduce<object>((value, key) => { value[key] = getRecordValue(record, cb, key); return value; }, {}); } const { dataSet } = record; const chainFieldName = getChainFieldName(record, fieldName); const { checkField } = dataSet.props; if (checkField && chainFieldName === getChainFieldName(record, checkField)) { const field = dataSet.getField(checkField); const trueValue = field ? field.get(BooleanValue.trueValue, record) : true; const falseValue = field ? field.get(BooleanValue.falseValue, record) : false; const { children } = record; if (children) { return children.every(child => cb(child, checkField) === trueValue) ? trueValue : falseValue; } } return ObjectChainValue.get(record.data, chainFieldName as string); } } export function processIntlField( name: string, callback: (props: FieldProps) => Field, fieldProps: FieldProps | undefined, dataSet: DataSet, ): [Field, Map<string, Field> | undefined] { const field = callback({ ...fieldProps, name }); if (fieldProps && fieldProps.type === FieldType.intl) { const { transformRequest } = fieldProps; const tlsKey = dataSet.getConfig('tlsKey'); const { supports } = localeContext; const languages = Object.keys(supports); const intlFields = new Map<string, Field>(); languages.forEach(language => intlFields.set(`${tlsKey}.${name}.${language}`, callback({ name: `${tlsKey}.${name}.${language}`, type: FieldType.string, label: `${supports[language]}`, transformRequest, dynamicProps: { bind: ({ record }) => { if (record) { const tls = record.get(tlsKey) || {}; if (name in tls && dataSet.lang === language) { return name; } } }, }, })), ); return [field, intlFields]; } return [field, undefined]; } export function findBindFieldBy(myField: Field, fields: Fields, prop: string, record?: Record): Field | undefined { const value = myField.get(prop, record); const myName = myField.name; return iteratorFind(fields.values(), field => { const bind = field.get('bind', record); return bind && bind === `${myName}.${value}`; }); } export function getLimit(limit: any, record: Record) { if (isString(limit) && record.dataSet.getField(limit)) { return record.get(limit); } return limit; } export function adapterDataToJSON( isSelected?: boolean, noCascade?: boolean, ): DataToJSON | undefined { if (isSelected) { if (noCascade) { return DataToJSON['selected-self']; } return DataToJSON.selected; } if (noCascade) { return DataToJSON['dirty-self']; } return undefined; } export function generateData(records: Record[]): { dirty: boolean; data: object[] } { let dirty = false; const data: object[] = records.reduce<object[]>((list, record) => { if (record.isRemoved) { dirty = true; } else { const d = record.toData(); if (d.__dirty) { dirty = true; } delete d.__dirty; list.push(d); } return list; }, []); return { dirty, data, }; } export function generateJSONData( ds: DataSet, records: Record[], ): { dirty: boolean; data: object[] } { const { dataToJSON } = ds; const data: object[] = []; records.forEach(record => generateRecordJSONData(data, record, dataToJSON)); return { dirty: data.length > 0, data, }; } export function getUniqueFieldNames(dataSet: DataSet): string[] { const keys: string[] = []; dataSet.fields.forEach((field, key) => { if (field.get('unique')) { keys.push(key); } }); return keys; } export function getUniqueKeysAndPrimaryKey(dataSet: DataSet): string[] { const keys: string[] = getUniqueFieldNames(dataSet); const { primaryKey } = dataSet.props; if (primaryKey) { keys.push(primaryKey); } return keys; } export function isDirtyRecord(record) { return record.status !== RecordStatus.sync || record.dirty; } export function getSpliceRecord(records: Record[], inserts: Record[], fromRecord?: Record): Record | undefined { if (fromRecord) { if (inserts.includes(fromRecord)) { return getSpliceRecord(records, inserts, records[records.indexOf(fromRecord) + 1]); } return fromRecord; } } // bugs in react native export function fixAxiosConfig(config: AxiosRequestConfig): AxiosRequestConfig { const { method } = config; if (method && method.toLowerCase() === 'get') { delete config.data; } return config; } const EMPTY_GROUP_KEY = Symbol('__empty_group__'); export function normalizeGroups(groups: string[], hGroups: string[], records: Record[]): Group[] { const optGroups: Group[] = []; const emptyGroup = new Group(EMPTY_GROUP_KEY, 0); records.forEach((record) => { let previousGroup: Group | undefined; groups.forEach((key) => { const label = record.get(key); if (!previousGroup) { previousGroup = optGroups.find(item => item.value === label); if (!previousGroup) { previousGroup = new Group(key, optGroups.length, label); optGroups.push(previousGroup); } } else { const { subGroups } = previousGroup; const parent = previousGroup; previousGroup = subGroups.find(item => item.value === label); if (!previousGroup) { previousGroup = new Group(key, subGroups.length, label, parent); subGroups.push(previousGroup); } } }); if (hGroups.length) { let { subHGroups } = previousGroup || emptyGroup; if (!subHGroups) { subHGroups = new Set<Group>(); (previousGroup || emptyGroup).subHGroups = subHGroups; } hGroups.forEach((key) => { const label = record.get(key); if (!previousGroup) { previousGroup = optGroups.find(item => item.value === label); if (!previousGroup) { previousGroup = new Group(key, optGroups.length, label); optGroups.push(previousGroup); } } else { const { subGroups } = previousGroup; const parent = previousGroup; previousGroup = subGroups.find(item => item.value === label); if (!previousGroup) { previousGroup = new Group(key, subGroups.length, label, parent); subGroups.push(previousGroup); } } }); if (previousGroup) { subHGroups.add(previousGroup); } } if (previousGroup) { const { records: groupRecords } = previousGroup; groupRecords.push(record); let parent: Group | undefined = previousGroup; while (parent) { parent.totalRecords.push(record); parent = parent.parent; } } }); if (!groups.length) { if (hGroups.length) { emptyGroup.subGroups = optGroups; } else { emptyGroup.records = records.slice(); } return [ emptyGroup, ]; } return optGroups; } /** * * @param data 导出需要导出的数据 * @param excelname 导出表单的名字 */ export function exportExcel(data, excelName) { import('xlsx').then(XLSX => { const ws = XLSX.utils.json_to_sheet(data, { skipHeader: true }); /* 新建空workbook,然后加入worksheet */ const wb = XLSX.utils.book_new(); /* 新建book */ XLSX.utils.book_append_sheet(wb, ws); /* 生成xlsx文件(book,sheet数据,sheet命名) */ XLSX.writeFile(wb, `${excelName}.xlsx`); /* 写文件(book,xlsx文件名称) */ }); } export function getSortedFields(dataSet: DataSet): ObservableMap { const { fields } = dataSet; if (dataSet.$needToSortFields) { const normalFields: [string, Field][] = []; const objectBindFields: [string, Field][] = []; const bindFields: [string, Field][] = []; const transformResponseField: [string, Field][] = []; const dynamicFields: [string, Field][] = []; const dynamicObjectBindFields: [string, Field][] = []; const dynamicBindFields: [string, Field][] = []; fields.forEach((field, name, map) => { const entry: [string, Field] = [name, field]; const dynamicProps = field.get('dynamicProps') || field.get('computedProps'); const type = field.get('type'); const bind = field.get('bind'); const transformResponse = field.get('transformResponse'); if (dynamicProps) { if (dynamicProps.bind) { if (type === FieldType.object) { dynamicObjectBindFields.push(entry); } else { dynamicBindFields.push(entry); } } else { dynamicFields.push(entry); } } else if (bind) { const targetNames = bind.split('.'); targetNames.pop(); if (targetNames.some((targetName) => { const target = map.get(targetName); return target && (target.get('computedProps') || target.get('dynamicProps')); })) { if (type === FieldType.object) { dynamicObjectBindFields.push(entry); } else { dynamicBindFields.push(entry); } } else if (transformResponse) { transformResponseField.push(entry); } else if (type === FieldType.object) { objectBindFields.push(entry); } else { bindFields.push(entry); } } else { normalFields.push(entry); } }); fields.replace([ ...normalFields, ...objectBindFields, ...bindFields, ...transformResponseField, ...dynamicFields, ...dynamicObjectBindFields, ...dynamicBindFields, ]); delete dataSet.$needToSortFields; } return fields; } export async function concurrentPromise( promiseLoaders: { getPromise: () => Promise<any> }[], cancelFnc: (readyPromiseNumber: number) => boolean, ) { const promiseLoadersLength = promiseLoaders.length; let fail = false; return new Promise((resolve, reject) => { const resulet: any = Array(promiseLoadersLength).fill(null); // 依次执行promise // 最大并发数 const maxConcurrent = Math.min(5, promiseLoadersLength); let currentPromiseIndex = 0; const execPromise = async (getPromise: () => Promise<any>, index: number) => { if (fail) { return; } if (cancelFnc(resulet.filter(Boolean).length)) { fail = true; reject(); return; } let res; try { res = await getPromise(); } catch (error) { fail = true; reject(error); return; } resulet[index] = res; // 判断是否完结 if (currentPromiseIndex === promiseLoadersLength - 1 && resulet.every(Boolean)) { resolve(resulet); return; } // 执行下一个promise if (currentPromiseIndex < promiseLoadersLength - 1) { ++currentPromiseIndex; execPromise(promiseLoaders[currentPromiseIndex]?.getPromise, currentPromiseIndex); } }; // 初始化执行 for (let i = 0; i < maxConcurrent; i++) { execPromise(promiseLoaders[i]?.getPromise, i); } currentPromiseIndex = maxConcurrent - 1; }); } export function treeSelect(dataSet: DataSet, record: Record, selected: Record[]) { dataSet.select(record); if (record.isSelected) { selected.push(record); const { children } = record; if (children) { children.forEach(child => treeSelect(dataSet, child, selected)); } } } export function treeUnSelect(dataSet: DataSet, record: Record, unSelected: Record[]) { dataSet.unSelect(record); if (!record.isSelected) { unSelected.push(record); const { children } = record; if (children) { children.forEach(child => treeUnSelect(dataSet, child, unSelected)); } } } export function treeSelectParent(dataSet: DataSet, record: Record, selected: Record[]) { const { parent } = record; if (parent && !parent.isSelected) { dataSet.select(parent); selected.push(parent); treeSelectParent(dataSet, parent, selected); } } export function treeUnSelectParent(dataSet: DataSet, record: Record, unSelected: Record[]) { const { parent } = record; if (parent && parent.isSelected) { const { children } = parent; if (children && children.every(child => !child.isSelected)) { dataSet.unSelect(parent); unSelected.push(parent); treeUnSelectParent(dataSet, parent, unSelected); } } } export function exchangeTreeNode(newRecord: Record, oldRecord: Record): Record { const { parent, children } = oldRecord; newRecord.parent = parent; newRecord.children = children; if (parent) { const { children: parentChildren } = parent; if (parentChildren) { const index = parentChildren.indexOf(oldRecord); if (index !== -1) { parentChildren.splice(index, 1, newRecord); } } } return newRecord; } export function getIf<T, V>(target: T, propName: string, defaultValue: V | (() => V)): V { const value = target[propName]; if (value === undefined) { target[propName] = typeof defaultValue === 'function' ? (defaultValue as () => V)() : defaultValue; return target[propName]; } return value; } export function getRecordDynamicProps<T extends keyof RecordDynamicProps>(record: Record, key: T, defaultValue: NonNullable<ReturnType<NonNullable<RecordDynamicProps[T]>>>): NonNullable<ReturnType<NonNullable<RecordDynamicProps[T]>>> { const { dataSet: { props: { record: recordProps } } } = record; if (recordProps) { const { dynamicProps } = recordProps; if (dynamicProps) { const hook = dynamicProps[key]; if (hook) { const result = hook(record); if (result !== undefined) { return result as NonNullable<ReturnType<NonNullable<RecordDynamicProps[T]>>>; } } } const value = recordProps[key]; if (value !== undefined) { return value as NonNullable<ReturnType<NonNullable<RecordDynamicProps[T]>>>; } } return defaultValue; } export function mergeDataSetProps(props: DataSetProps | undefined, dataSetProps?: DataSetProps | ((p: DataSetProps) => DataSetProps)): DataSetProps { if (typeof dataSetProps === 'function') { return dataSetProps(props || {}); } return { ...props, ...dataSetProps }; }
the_stack
import * as sinon from 'sinon'; import * as vscode from 'vscode'; import { RuntimeTreeItem } from '../../../extension/explorer/runtimeOps/disconnectedTree/RuntimeTreeItem'; import { ExtensionUtil } from '../../../extension/util/ExtensionUtil'; import { TestUtil } from '../../TestUtil'; import { ExtensionCommands } from '../../../ExtensionCommands'; import { VSCodeBlockchainOutputAdapter } from '../../../extension/logging/VSCodeBlockchainOutputAdapter'; import { FabricEnvironmentRegistry, FabricEnvironmentRegistryEntry, FabricRuntimeUtil, LogType, EnvironmentType } from 'ibm-blockchain-platform-common'; import { BlockchainEnvironmentExplorerProvider } from '../../../extension/explorer/environmentExplorer'; import { FabricRuntimeState } from '../../../extension/fabric/FabricRuntimeState'; import { LocalMicroEnvironment } from '../../../extension/fabric/environments/LocalMicroEnvironment'; import { LocalMicroEnvironmentManager } from '../../../extension/fabric/environments/LocalMicroEnvironmentManager'; import { UserInputUtil } from '../../../extension/commands/UserInputUtil'; describe('RuntimeTreeItem', () => { const environmentRegistry: FabricEnvironmentRegistry = FabricEnvironmentRegistry.instance(); const sandbox: sinon.SinonSandbox = sinon.createSandbox(); let clock: sinon.SinonFakeTimers; let provider: BlockchainEnvironmentExplorerProvider; let environmentRegistryEntry: FabricEnvironmentRegistryEntry; let localRuntime: LocalMicroEnvironment; let isBusyStub: sinon.SinonStub; let isRunningStub: sinon.SinonStub; let getStateStub: sinon.SinonStub; let onBusyCallback: any; let command: vscode.Command; before(async () => { await TestUtil.setupTests(sandbox); }); beforeEach(async () => { await ExtensionUtil.activateExtension(); await environmentRegistry.clear(); environmentRegistryEntry = new FabricEnvironmentRegistryEntry(); environmentRegistryEntry.name = FabricRuntimeUtil.LOCAL_FABRIC; environmentRegistryEntry.managedRuntime = true; environmentRegistryEntry.environmentType = EnvironmentType.LOCAL_ENVIRONMENT; provider = ExtensionUtil.getBlockchainEnvironmentExplorerProvider(); const runtimeManager: LocalMicroEnvironmentManager = LocalMicroEnvironmentManager.instance(); localRuntime = new LocalMicroEnvironment(FabricRuntimeUtil.LOCAL_FABRIC, 8080, 1, UserInputUtil.V2_0); // mockRuntime = sandbox.createStubInstance(LocalEnvironment); isBusyStub = sandbox.stub(localRuntime, 'isBusy'); isRunningStub = sandbox.stub(localRuntime, 'isRunning'); getStateStub = sandbox.stub(localRuntime, 'getState'); sandbox.stub(localRuntime, 'on').callsFake((name: string, callback: any) => { name.should.equal('busy'); onBusyCallback = callback; }); sandbox.stub(runtimeManager, 'getRuntime').returns(localRuntime); clock = sinon.useFakeTimers({ toFake: ['setInterval', 'clearInterval'] }); command = { command: ExtensionCommands.CONNECT_TO_ENVIRONMENT, title: '' }; }); afterEach(async () => { clock.runToLast(); clock.restore(); sandbox.restore(); await environmentRegistry.clear(); }); describe('#constructor', () => { it('should have the right properties for a runtime that is not running', async () => { isBusyStub.returns(false); isRunningStub.resolves(false); const treeItem: RuntimeTreeItem = await RuntimeTreeItem.newRuntimeTreeItem(provider, FabricRuntimeUtil.LOCAL_FABRIC, environmentRegistryEntry, command, localRuntime); await new Promise((resolve: any): any => { setTimeout(resolve, 0); }); treeItem.label.should.equal(`${FabricRuntimeUtil.LOCAL_FABRIC} ○ (click to start)`); treeItem.command.should.deep.equal(command); treeItem.tooltip.should.equal('Creates a local development runtime using Hyperledger Fabric Docker images'); }); it('should have the right properties for a runtime that is busy starting', async () => { isBusyStub.returns(true); isRunningStub.resolves(false); getStateStub.returns(FabricRuntimeState.STARTING); const treeItem: RuntimeTreeItem = await RuntimeTreeItem.newRuntimeTreeItem(provider, FabricRuntimeUtil.LOCAL_FABRIC, environmentRegistryEntry, command, localRuntime); await new Promise((resolve: any): any => { setTimeout(resolve, 0); }); treeItem.label.should.equal(`${FabricRuntimeUtil.LOCAL_FABRIC} runtime is starting... ◐`); treeItem.tooltip.should.equal('The local development runtime is starting...'); treeItem.command.should.deep.equal(command); }); it('should have the right properties for a runtime that is busy stopping', async () => { isBusyStub.returns(true); isRunningStub.resolves(false); getStateStub.returns(FabricRuntimeState.STOPPING); const treeItem: RuntimeTreeItem = await RuntimeTreeItem.newRuntimeTreeItem(provider, FabricRuntimeUtil.LOCAL_FABRIC, environmentRegistryEntry, command, localRuntime); await new Promise((resolve: any): any => { setTimeout(resolve, 0); }); treeItem.label.should.equal(`${FabricRuntimeUtil.LOCAL_FABRIC} runtime is stopping... ◐`); treeItem.tooltip.should.equal('The local development runtime is stopping...'); treeItem.command.should.deep.equal(command); }); it('should have the right properties for a runtime that is busy restarting', async () => { isBusyStub.returns(true); isRunningStub.resolves(false); getStateStub.returns(FabricRuntimeState.RESTARTING); const treeItem: RuntimeTreeItem = await RuntimeTreeItem.newRuntimeTreeItem(provider, FabricRuntimeUtil.LOCAL_FABRIC, environmentRegistryEntry, command, localRuntime); await new Promise((resolve: any): any => { setTimeout(resolve, 0); }); treeItem.label.should.equal(`${FabricRuntimeUtil.LOCAL_FABRIC} runtime is restarting... ◐`); treeItem.tooltip.should.equal('The local development runtime is restarting...'); treeItem.command.should.deep.equal(command); }); it('should animate the label for a runtime that is busy', async () => { isBusyStub.returns(true); isRunningStub.resolves(false); getStateStub.returns(FabricRuntimeState.STARTING); const treeItem: RuntimeTreeItem = await RuntimeTreeItem.newRuntimeTreeItem(provider, FabricRuntimeUtil.LOCAL_FABRIC, environmentRegistryEntry, command, localRuntime); await new Promise((resolve: any): any => { setTimeout(resolve, 0); }); const states: string[] = ['◐', '◓', '◑', '◒', '◐']; for (const state of states) { treeItem.label.should.equal(`${FabricRuntimeUtil.LOCAL_FABRIC} runtime is starting... ${state}`); clock.tick(500); await new Promise((resolve: any): any => { setTimeout(resolve, 0); }); } treeItem.command.should.deep.equal(command); }); it('should have the right properties for a runtime that is running', async () => { isBusyStub.returns(false); isRunningStub.resolves(true); const treeItem: RuntimeTreeItem = await RuntimeTreeItem.newRuntimeTreeItem(provider, FabricRuntimeUtil.LOCAL_FABRIC, environmentRegistryEntry, command, localRuntime); await new Promise((resolve: any): any => { setTimeout(resolve, 0); }); treeItem.label.should.equal(`${FabricRuntimeUtil.LOCAL_FABRIC} ●`); treeItem.tooltip.should.equal('The local development runtime is running'); treeItem.command.should.deep.equal(command); }); it('should have the right properties for a runtime that becomes busy', async () => { isBusyStub.returns(false); isRunningStub.resolves(false); const treeItem: RuntimeTreeItem = await RuntimeTreeItem.newRuntimeTreeItem(provider, FabricRuntimeUtil.LOCAL_FABRIC, environmentRegistryEntry, command, localRuntime); await new Promise((resolve: any): any => { setTimeout(resolve, 0); }); treeItem.label.should.equal(`${FabricRuntimeUtil.LOCAL_FABRIC} ○ (click to start)`); treeItem.command.should.deep.equal({ command: ExtensionCommands.CONNECT_TO_ENVIRONMENT, title: '' }); treeItem.tooltip.should.equal('Creates a local development runtime using Hyperledger Fabric Docker images'); isBusyStub.returns(true); getStateStub.returns(FabricRuntimeState.STARTING); onBusyCallback(true); await new Promise((resolve: any): any => { setTimeout(resolve, 0); }); treeItem.label.should.equal(`${FabricRuntimeUtil.LOCAL_FABRIC} runtime is starting... ◐`); treeItem.tooltip.should.equal('The local development runtime is starting...'); treeItem.command.should.deep.equal(command); }); it('should animate the label for a runtime that becomes busy', async () => { isBusyStub.returns(false); isRunningStub.resolves(false); const treeItem: RuntimeTreeItem = await RuntimeTreeItem.newRuntimeTreeItem(provider, FabricRuntimeUtil.LOCAL_FABRIC, environmentRegistryEntry, command, localRuntime); await new Promise((resolve: any): any => { setTimeout(resolve, 0); }); isBusyStub.returns(true); getStateStub.returns(FabricRuntimeState.STARTING); onBusyCallback(true); await new Promise((resolve: any): any => { setTimeout(resolve, 0); }); const states: string[] = ['◐', '◓', '◑', '◒', '◐']; for (const state of states) { treeItem.label.should.equal(`${FabricRuntimeUtil.LOCAL_FABRIC} runtime is starting... ${state}`); clock.tick(500); await new Promise((resolve: any): any => { setTimeout(resolve, 0); }); } treeItem.command.should.deep.equal(command); }); it('should have the right properties for a runtime that stops being busy', async () => { isBusyStub.returns(true); getStateStub.returns(FabricRuntimeState.STARTING); isRunningStub.resolves(false); const treeItem: RuntimeTreeItem = await RuntimeTreeItem.newRuntimeTreeItem(provider, FabricRuntimeUtil.LOCAL_FABRIC, environmentRegistryEntry, command, localRuntime); await new Promise((resolve: any): any => { setTimeout(resolve, 0); }); treeItem.label.should.equal(`${FabricRuntimeUtil.LOCAL_FABRIC} runtime is starting... ◐`); treeItem.tooltip.should.equal('The local development runtime is starting...'); isBusyStub.returns(false); onBusyCallback(false); await new Promise((resolve: any): any => { setTimeout(resolve, 0); }); treeItem.label.should.equal(`${FabricRuntimeUtil.LOCAL_FABRIC} ○ (click to start)`); treeItem.command.should.deep.equal(command); treeItem.tooltip.should.equal('Creates a local development runtime using Hyperledger Fabric Docker images'); }); it('should report errors animating the label for a runtime that is busy', async () => { isBusyStub.returns(true); getStateStub.returns(FabricRuntimeState.STARTING); isRunningStub.resolves(false); const treeItem: RuntimeTreeItem = await RuntimeTreeItem.newRuntimeTreeItem(provider, FabricRuntimeUtil.LOCAL_FABRIC, environmentRegistryEntry, command, localRuntime); sandbox.stub(treeItem, 'refresh').throws(new Error('such error')); const logSpy: sinon.SinonSpy = sandbox.spy(VSCodeBlockchainOutputAdapter.instance(), 'log'); await new Promise((resolve: any): any => { setTimeout(resolve, 0); }); const states: string[] = ['◐', '◓', '◑', '◒', '◐']; for (const state of states) { treeItem.label.should.equal(`${FabricRuntimeUtil.LOCAL_FABRIC} runtime is starting... ${state}`); clock.tick(500); await new Promise((resolve: any): any => { setTimeout(resolve, 0); }); logSpy.should.have.been.calledOnceWithExactly(LogType.ERROR, 'such error', 'Error: such error'); logSpy.resetHistory(); } }); }); });
the_stack
import * as TH from './type-helpers'; import { testType } from './utils/testing'; import { getType } from './get-type'; import { isOfType } from './is-of-type'; import { isActionOf } from './is-action-of'; import { StateType, ActionType } from './type-helpers'; import { actions, types } from './type-helpers-fixtures'; const { withTypeOnly, withPayload, withPayloadMeta, withMappedPayload, withMappedPayloadMeta, asyncAction, } = actions; // @dts-jest:group StateType { const reducer = ( state: boolean = false, action: ActionType<typeof withTypeOnly> ) => { switch (action.type) { case getType(withTypeOnly): return true; default: return false; } }; // @dts-jest:pass:snap testType<StateType<typeof reducer>>(); // @dts-jest:pass:snap reducer(undefined, withTypeOnly()); // => true } // @dts-jest:group ActionType { // @dts-jest:pass:snap testType<ActionType<typeof actions>>(); type RootAction = ActionType<typeof actions>; function getTypeReducer(action: RootAction): RootAction | undefined { switch (action.type) { case getType(actions.deep.nested.withTypeOnly): { return testType<{ type: 'VERY_DEEP_WITH_TYPE_ONLY' }>(action); } case getType(withTypeOnly): { return testType<{ type: 'WITH_TYPE_ONLY' }>(action); } case getType(withPayload): { return testType<{ type: 'WITH_PAYLOAD'; payload: number }>(action); } case getType(withPayloadMeta): { return testType<{ type: 'WITH_PAYLOAD_META'; payload: number; meta: string; }>(action); } case getType(withMappedPayload): { return testType<{ type: 'WITH_MAPPED_PAYLOAD'; payload: number }>( action ); } case getType(withMappedPayloadMeta): { return testType<{ type: 'WITH_MAPPED_PAYLOAD_META'; payload: number; meta: string; }>(action); } case getType(asyncAction.request): { return testType<{ type: 'FETCH_USER_REQUEST'; }>(action); } case getType(asyncAction.success): { return testType<{ type: 'FETCH_USER_SUCCESS'; payload: { firstName: string; lastName: string }; }>(action); } case getType(asyncAction.failure): { return testType<{ type: 'FETCH_USER_FAILURE'; payload: Error; }>(action); } default: return undefined; } } function isActionOfReducer(action: RootAction): RootAction | undefined { if (isActionOf(actions.deep.nested.withTypeOnly, action)) { return testType<{ type: 'VERY_DEEP_WITH_TYPE_ONLY' }>(action); } else if (isActionOf(withTypeOnly, action)) { return testType<{ type: 'WITH_TYPE_ONLY' }>(action); } else if (isActionOf(withPayload, action)) { return testType<{ type: 'WITH_PAYLOAD'; payload: number }>(action); } else if (isActionOf(withPayloadMeta, action)) { return testType<{ type: 'WITH_PAYLOAD_META'; payload: number; meta: string; }>(action); } else if (isActionOf(withMappedPayload, action)) { return testType<{ type: 'WITH_MAPPED_PAYLOAD'; payload: number }>(action); } else if (isActionOf(withMappedPayloadMeta, action)) { return testType<{ type: 'WITH_MAPPED_PAYLOAD_META'; payload: number; meta: string; }>(action); } else if (isActionOf(asyncAction.request, action)) { return testType<{ type: 'FETCH_USER_REQUEST'; }>(action); } return undefined; } function isActionOfCurriedReducer( action: RootAction ): RootAction | undefined { if (isActionOf(actions.deep.nested.withTypeOnly)(action)) { return testType<{ type: 'VERY_DEEP_WITH_TYPE_ONLY' }>(action); } else if (isActionOf(withTypeOnly)(action)) { return testType<{ type: 'WITH_TYPE_ONLY' }>(action); } else if (isActionOf(withPayload)(action)) { return testType<{ type: 'WITH_PAYLOAD'; payload: number }>(action); } else if (isActionOf(withPayloadMeta)(action)) { return testType<{ type: 'WITH_PAYLOAD_META'; payload: number; meta: string; }>(action); } else if (isActionOf(withMappedPayload)(action)) { return testType<{ type: 'WITH_MAPPED_PAYLOAD'; payload: number }>(action); } else if (isActionOf(withMappedPayloadMeta)(action)) { return testType<{ type: 'WITH_MAPPED_PAYLOAD_META'; payload: number; meta: string; }>(action); } else if (isActionOf(asyncAction.request)(action)) { return testType<{ type: 'FETCH_USER_REQUEST'; }>(action); } return undefined; } function isActionOfArrayReducer(action: RootAction): RootAction | undefined { if (isActionOf([actions.deep.nested.withTypeOnly])(action)) { return testType<{ type: 'VERY_DEEP_WITH_TYPE_ONLY' }>(action); } else if (isActionOf([withTypeOnly])(action)) { return testType<{ type: 'WITH_TYPE_ONLY' }>(action); } else if (isActionOf([withTypeOnly])(action)) { return testType<{ type: 'WITH_TYPE_ONLY' }>(action); } else if (isActionOf([withPayload])(action)) { return testType<{ type: 'WITH_PAYLOAD'; payload: number }>(action); } else if (isActionOf([withPayloadMeta])(action)) { return testType<{ type: 'WITH_PAYLOAD_META'; payload: number; meta: string; }>(action); } else if (isActionOf([withMappedPayload])(action)) { return testType<{ type: 'WITH_MAPPED_PAYLOAD'; payload: number }>(action); } else if (isActionOf([withMappedPayloadMeta])(action)) { return testType<{ type: 'WITH_MAPPED_PAYLOAD_META'; payload: number; meta: string; }>(action); } else if (isActionOf([asyncAction.request])(action)) { return testType<{ type: 'FETCH_USER_REQUEST'; }>(action); } return undefined; } function isOfTypeReducer(action: RootAction): RootAction | undefined { if (isOfType(types.VERY_DEEP_WITH_TYPE_ONLY, action)) { return testType<{ type: 'VERY_DEEP_WITH_TYPE_ONLY' }>(action); } else if (isOfType(types.WITH_TYPE_ONLY, action)) { return testType<{ type: 'WITH_TYPE_ONLY' }>(action); } else if (isOfType(types.WITH_PAYLOAD, action)) { return testType<{ type: 'WITH_PAYLOAD'; payload: number }>(action); } else if (isOfType(types.WITH_PAYLOAD_META, action)) { return testType<{ type: 'WITH_PAYLOAD_META'; payload: number; meta: string; }>(action); } else if (isOfType(types.WITH_MAPPED_PAYLOAD, action)) { return testType<{ type: 'WITH_MAPPED_PAYLOAD'; payload: number }>(action); } else if (isOfType(types.WITH_MAPPED_PAYLOAD_META, action)) { return testType<{ type: 'WITH_MAPPED_PAYLOAD_META'; payload: number; meta: string; }>(action); } else if (isOfType('FETCH_USER_REQUEST', action)) { return testType<{ type: 'FETCH_USER_REQUEST' }>(action); } return undefined; } function isOfTypeCurriedReducer(action: RootAction): RootAction | undefined { if (isOfType(types.VERY_DEEP_WITH_TYPE_ONLY)(action)) { return testType<{ type: 'VERY_DEEP_WITH_TYPE_ONLY' }>(action); } else if (isOfType(types.WITH_TYPE_ONLY)(action)) { return testType<{ type: 'WITH_TYPE_ONLY' }>(action); } else if (isOfType(types.WITH_PAYLOAD)(action)) { return testType<{ type: 'WITH_PAYLOAD'; payload: number }>(action); } else if (isOfType(types.WITH_PAYLOAD_META)(action)) { return testType<{ type: 'WITH_PAYLOAD_META'; payload: number; meta: string; }>(action); } else if (isOfType(types.WITH_MAPPED_PAYLOAD)(action)) { return testType<{ type: 'WITH_MAPPED_PAYLOAD'; payload: number }>(action); } else if (isOfType(types.WITH_MAPPED_PAYLOAD_META)(action)) { return testType<{ type: 'WITH_MAPPED_PAYLOAD_META'; payload: number; meta: string; }>(action); } else if (isOfType('FETCH_USER_REQUEST')(action)) { return testType<{ type: 'FETCH_USER_REQUEST' }>(action); } return undefined; } const emptyAction = withTypeOnly(); const expectedEmptyAction = { type: 'WITH_TYPE_ONLY' }; // @dts-jest:pass:snap getTypeReducer(emptyAction); // => expectedEmptyAction // @dts-jest:pass:snap isActionOfReducer(emptyAction); // => expectedEmptyAction // @dts-jest:pass:snap isActionOfCurriedReducer(emptyAction); // => expectedEmptyAction // @dts-jest:pass:snap isActionOfArrayReducer(emptyAction); // => expectedEmptyAction // @dts-jest:pass:snap isOfTypeReducer(emptyAction); // => expectedEmptyAction // @dts-jest:pass:snap isOfTypeCurriedReducer(emptyAction); // => expectedEmptyAction const payloadAction = withPayload(2); const expectedPayloadAction = { type: 'WITH_PAYLOAD', payload: 2 }; // @dts-jest:pass:snap getTypeReducer(payloadAction); // => expectedPayloadAction // @dts-jest:pass:snap isActionOfReducer(payloadAction); // => expectedPayloadAction // @dts-jest:pass:snap isActionOfCurriedReducer(payloadAction); // => expectedPayloadAction // @dts-jest:pass:snap isActionOfArrayReducer(payloadAction); // => expectedPayloadAction // @dts-jest:pass:snap isOfTypeReducer(payloadAction); // => expectedPayloadAction // @dts-jest:pass:snap isOfTypeCurriedReducer(payloadAction); // => expectedPayloadAction const payloadMetaAction = withPayloadMeta(2, 'metaValue'); const expectedPayloadMetaAction = { type: 'WITH_PAYLOAD_META', payload: 2, meta: 'metaValue', }; // @dts-jest:pass:snap getTypeReducer(payloadMetaAction); // => expectedPayloadMetaAction // @dts-jest:pass:snap isActionOfReducer(payloadMetaAction); // => expectedPayloadMetaAction // @dts-jest:pass:snap isActionOfCurriedReducer(payloadMetaAction); // => expectedPayloadMetaAction // @dts-jest:pass:snap isActionOfArrayReducer(payloadMetaAction); // => expectedPayloadMetaAction // @dts-jest:pass:snap isOfTypeReducer(payloadMetaAction); // => expectedPayloadMetaAction // @dts-jest:pass:snap isOfTypeCurriedReducer(payloadMetaAction); // => expectedPayloadMetaAction const mappedPayloadAction = withMappedPayload(2); const expectedMappedPayloadAction = { type: 'WITH_MAPPED_PAYLOAD', payload: 2, }; // @dts-jest:pass:snap getTypeReducer(mappedPayloadAction); // => expectedMappedPayloadAction // @dts-jest:pass:snap isActionOfReducer(mappedPayloadAction); // => expectedMappedPayloadAction // @dts-jest:pass:snap isActionOfCurriedReducer(mappedPayloadAction); // => expectedMappedPayloadAction // @dts-jest:pass:snap isActionOfArrayReducer(mappedPayloadAction); // => expectedMappedPayloadAction // @dts-jest:pass:snap isOfTypeReducer(mappedPayloadAction); // => expectedMappedPayloadAction // @dts-jest:pass:snap isOfTypeCurriedReducer(mappedPayloadAction); // => expectedMappedPayloadAction const mappedPayloadMetaAction = withMappedPayloadMeta(2, 'metaValue'); const expectedMappedPayloadMetaAction = { type: 'WITH_MAPPED_PAYLOAD_META', payload: 2, meta: 'metaValue', }; // @dts-jest:pass:snap getTypeReducer(mappedPayloadMetaAction); // => expectedMappedPayloadMetaAction // @dts-jest:pass:snap isActionOfReducer(mappedPayloadMetaAction); // => expectedMappedPayloadMetaAction // @dts-jest:pass:snap isActionOfCurriedReducer(mappedPayloadMetaAction); // => expectedMappedPayloadMetaAction // @dts-jest:pass:snap isActionOfArrayReducer(mappedPayloadMetaAction); // => expectedMappedPayloadMetaAction // @dts-jest:pass:snap isOfTypeReducer(mappedPayloadMetaAction); // => expectedMappedPayloadMetaAction // @dts-jest:pass:snap isOfTypeCurriedReducer(mappedPayloadMetaAction); // => expectedMappedPayloadMetaAction const asyncActionRequest = asyncAction.request(); const expectedAsyncActionRequest = { type: 'FETCH_USER_REQUEST', }; // @dts-jest:pass:snap getTypeReducer(asyncActionRequest); // => expectedAsyncActionRequest // @dts-jest:pass:snap isActionOfReducer(asyncActionRequest); // => expectedAsyncActionRequest // @dts-jest:pass:snap isActionOfCurriedReducer(asyncActionRequest); // => expectedAsyncActionRequest // @dts-jest:pass:snap isActionOfArrayReducer(asyncActionRequest); // => expectedAsyncActionRequest // @dts-jest:pass:snap isOfTypeReducer(asyncActionRequest); // => expectedAsyncActionRequest // @dts-jest:pass:snap isOfTypeCurriedReducer(asyncActionRequest); // => expectedAsyncActionRequest }
the_stack
'use strict'; import nls = require('vs/nls'); import {TPromise} from 'vs/base/common/winjs.base'; import paths = require('vs/base/common/paths'); import strings = require('vs/base/common/strings'); import {isWindows, isLinux} from 'vs/base/common/platform'; import URI from 'vs/base/common/uri'; import errors = require('vs/base/common/errors'); import {UntitledEditorModel} from 'vs/workbench/common/editor/untitledEditorModel'; import {ConfirmResult} from 'vs/workbench/common/editor'; import {IEventService} from 'vs/platform/event/common/event'; import {TextFileService as AbstractTextFileService} from 'vs/workbench/parts/files/common/textFileServices'; import {CACHE, TextFileEditorModel} from 'vs/workbench/parts/files/common/editors/textFileEditorModel'; import {ITextFileOperationResult, AutoSaveMode, IRawTextContent} from 'vs/workbench/parts/files/common/files'; import {IUntitledEditorService} from 'vs/workbench/services/untitled/common/untitledEditorService'; import {IFileService, IResolveContentOptions} from 'vs/platform/files/common/files'; import {BinaryEditorModel} from 'vs/workbench/common/editor/binaryEditorModel'; import {IInstantiationService} from 'vs/platform/instantiation/common/instantiation'; import {IWorkspaceContextService} from 'vs/platform/workspace/common/workspace'; import {ILifecycleService} from 'vs/platform/lifecycle/common/lifecycle'; import {ITelemetryService} from 'vs/platform/telemetry/common/telemetry'; import {IConfigurationService} from 'vs/platform/configuration/common/configuration'; import {IModeService} from 'vs/editor/common/services/modeService'; import {IWorkbenchEditorService} from 'vs/workbench/services/editor/common/editorService'; import {IWindowService} from 'vs/workbench/services/window/electron-browser/windowService'; import {IEditorGroupService} from 'vs/workbench/services/group/common/groupService'; import {IModelService} from 'vs/editor/common/services/modelService'; import {ModelBuilder} from 'vs/editor/node/model/modelBuilder'; import {IQuickOpenService} from 'vs/workbench/services/quickopen/common/quickOpenService'; import {QuickOpenController} from 'vs/workbench/browser/parts/quickopen/quickOpenController'; // TODO: import product from 'vs/platform/product'; import {IEnvironmentService} from 'vs/platform/environment/common/environment'; import {IWindowConfiguration} from 'vs/workbench/electron-browser/main'; // DESKTOP: import {IEnvService} from 'vs/code/electron-main/env'; export class TextFileService extends AbstractTextFileService { private instService: IInstantiationService; private static MAX_CONFIRM_FILES = 10; constructor( @IWorkspaceContextService contextService: IWorkspaceContextService, @IInstantiationService instantiationService: IInstantiationService, @IFileService fileService: IFileService, @IUntitledEditorService private untitledEditorService: IUntitledEditorService, @ILifecycleService private lifecycleService: ILifecycleService, @ITelemetryService telemetryService: ITelemetryService, @IConfigurationService configurationService: IConfigurationService, @IEventService eventService: IEventService, @IModeService private modeService: IModeService, @IWorkbenchEditorService editorService: IWorkbenchEditorService, @IEditorGroupService private editorGroupService: IEditorGroupService, @IWindowService private windowService: IWindowService, @IModelService modelService: IModelService, @IEnvironmentService private environmentService: IEnvironmentService ) { super(contextService, instantiationService, configurationService, telemetryService, editorService, eventService, fileService, modelService); this.instService = instantiationService; this.modeService = modeService; this.init(); } protected registerListeners(): void { super.registerListeners(); // Lifecycle this.lifecycleService.onWillShutdown(event => event.veto(this.beforeShutdown())); this.lifecycleService.onShutdown(this.onShutdown, this); // Application & Editor focus change window.addEventListener('blur', () => this.onWindowFocusLost()); window.addEventListener('blur', () => this.onEditorFocusChanged(), true); this.listenerToUnbind.push(this.editorGroupService.onEditorsChanged(() => this.onEditorFocusChanged())); } private onWindowFocusLost(): void { if (this.configuredAutoSaveOnWindowChange && this.isDirty()) { this.saveAll().done(null, errors.onUnexpectedError); } } private onEditorFocusChanged(): void { if (this.configuredAutoSaveOnFocusChange && this.isDirty()) { this.saveAll().done(null, errors.onUnexpectedError); } } public resolveTextContent(resource: URI, options?: IResolveContentOptions): TPromise<IRawTextContent> { return this.fileService.resolveStreamContent(resource, options).then((streamContent) => { return ModelBuilder.fromStringStream(streamContent.value, this.modelService.getCreationOptions()).then((res) => { let r: IRawTextContent = { resource: streamContent.resource, name: streamContent.name, mtime: streamContent.mtime, etag: streamContent.etag, mime: streamContent.mime, encoding: streamContent.encoding, value: res.rawText, valueLogicalHash: res.hash }; return r; }); }); } public beforeShutdown(): boolean | TPromise<boolean> { // Dirty files need treatment on shutdown if (this.getDirty().length) { // If auto save is enabled, save all files and then check again for dirty files if (this.getAutoSaveMode() !== AutoSaveMode.OFF) { return this.saveAll(false /* files only */).then(() => { if (this.getDirty().length) { return this.confirmBeforeShutdown(); // we still have dirty files around, so confirm normally } return false; // all good, no veto }); } // Otherwise just confirm what to do return this.confirmBeforeShutdown(); } return false; // no veto } private confirmBeforeShutdown(): boolean | TPromise<boolean> { let confirm = this.confirmSave(); // Save if (confirm === ConfirmResult.SAVE) { return this.saveAll(true /* includeUntitled */).then(result => { if (result.results.some(r => !r.success)) { return true; // veto if some saves failed } return false; // no veto }); } // Don't Save else if (confirm === ConfirmResult.DONT_SAVE) { return false; // no veto } // Cancel else if (confirm === ConfirmResult.CANCEL) { return true; // veto } } private onShutdown(): void { super.dispose(); } public revertAll(resources?: URI[], force?: boolean): TPromise<ITextFileOperationResult> { // Revert files return super.revertAll(resources, force).then(r => { // Revert untitled const reverted = this.untitledEditorService.revertAll(resources); reverted.forEach(res => r.results.push({ source: res, success: true })); return r; }); } public getDirty(resources?: URI[]): URI[] { // Collect files let dirty = super.getDirty(resources); // Add untitled ones if (!resources) { dirty.push(...this.untitledEditorService.getDirty()); } else { let dirtyUntitled = resources.map(r => this.untitledEditorService.get(r)).filter(u => u && u.isDirty()).map(u => u.getResource()); dirty.push(...dirtyUntitled); } return dirty; } public isDirty(resource?: URI): boolean { if (super.isDirty(resource)) { return true; } return this.untitledEditorService.getDirty().some(dirty => !resource || dirty.toString() === resource.toString()); } public confirmSave(resources?: URI[]): ConfirmResult { if (!!this.environmentService.extensionDevelopmentPath) { return ConfirmResult.DONT_SAVE; // no veto when we are in extension dev mode because we cannot assum we run interactive (e.g. tests) } let resourcesToConfirm = this.getDirty(resources); if (resourcesToConfirm.length === 0) { return ConfirmResult.DONT_SAVE; } let message = [ resourcesToConfirm.length === 1 ? nls.localize('saveChangesMessage', "Do you want to save the changes you made to {0}?", paths.basename(resourcesToConfirm[0].fsPath)) : nls.localize('saveChangesMessages', "Do you want to save the changes to the following {0} files?", resourcesToConfirm.length) ]; if (resourcesToConfirm.length > 1) { message.push(''); message.push(...resourcesToConfirm.slice(0, TextFileService.MAX_CONFIRM_FILES).map(r => paths.basename(r.fsPath))); if (resourcesToConfirm.length > TextFileService.MAX_CONFIRM_FILES) { if (resourcesToConfirm.length - TextFileService.MAX_CONFIRM_FILES === 1) { message.push(nls.localize('moreFile', "...1 additional file not shown")); } else { message.push(nls.localize('moreFiles', "...{0} additional files not shown", resourcesToConfirm.length - TextFileService.MAX_CONFIRM_FILES)); } } message.push(''); } // Button order // Windows: Save | Don't Save | Cancel // Mac: Save | Cancel | Don't Save // Linux: Don't Save | Cancel | Save const save = { label: resourcesToConfirm.length > 1 ? this.mnemonicLabel(nls.localize({ key: 'saveAll', comment: ['&& denotes a mnemonic'] }, "&&Save All")) : this.mnemonicLabel(nls.localize({ key: 'save', comment: ['&& denotes a mnemonic'] }, "&&Save")), result: ConfirmResult.SAVE }; const dontSave = { label: this.mnemonicLabel(nls.localize({ key: 'dontSave', comment: ['&& denotes a mnemonic'] }, "Do&&n't Save")), result: ConfirmResult.DONT_SAVE }; const cancel = { label: nls.localize('cancel', "Cancel"), result: ConfirmResult.CANCEL }; const buttons = []; if (isWindows) { buttons.push(save, dontSave, cancel); } else if (isLinux) { buttons.push(dontSave, cancel, save); } else { buttons.push(save, cancel, dontSave); } let opts: Electron.ShowMessageBoxOptions = { title: (<any>this.environmentService).product.nameLong, message: message.join('\n'), type: 'warning', detail: nls.localize('saveChangesDetail', "Your changes will be lost if you don't save them."), buttons: buttons.map(b => b.label), noLink: true, cancelId: buttons.indexOf(cancel) }; if (isLinux) { opts.defaultId = 2; } /* const choice = this.windowService.getWindow().showMessageBox(opts); return buttons[choice].result; */ // Need blocking modal behavior because this method returns a result // synchronously. if (window.confirm(nls.localize('saveFileOK', 'OK to save file?'))) { return ConfirmResult.SAVE; } else { if (window.confirm(nls.localize('performActionOK', 'OK to continue action without saving?'))) { return ConfirmResult.DONT_SAVE; } else { return ConfirmResult.CANCEL; } } } private mnemonicLabel(label: string): string { if (!isWindows) { return label.replace(/\(&&\w\)|&&/g, ''); // no mnemonic support on mac/linux } return label.replace(/&&/g, '&'); } public saveAll(includeUntitled?: boolean): TPromise<ITextFileOperationResult>; public saveAll(resources: URI[]): TPromise<ITextFileOperationResult>; public saveAll(arg1?: any): TPromise<ITextFileOperationResult> { // get all dirty let toSave: URI[] = []; if (Array.isArray(arg1)) { toSave = this.getDirty(arg1); } else { toSave = this.getDirty(); } // split up between files and untitled let filesToSave: URI[] = []; let untitledToSave: URI[] = []; toSave.forEach(s => { if (s.scheme === 'file') { filesToSave.push(s); } else if ((Array.isArray(arg1) || arg1 === true /* includeUntitled */) && s.scheme === 'untitled') { untitledToSave.push(s); } }); return this.doSaveAll(filesToSave, untitledToSave); } private doSaveAll(fileResources: URI[], untitledResources: URI[]): TPromise<ITextFileOperationResult> { // Preflight for untitled to handle cancellation from the dialog let targetsForUntitled: URI[] = []; for (let i = 0; i < untitledResources.length; i++) { let untitled = this.untitledEditorService.get(untitledResources[i]); if (untitled) { let targetPath: string; // Untitled with associated file path don't need to prompt if (this.untitledEditorService.hasAssociatedFilePath(untitled.getResource())) { targetPath = untitled.getResource().fsPath; } // Otherwise ask user else { targetPath = this.promptForPath(this.suggestFileName(untitledResources[i])); if (!targetPath) { return TPromise.as({ results: [...fileResources, ...untitledResources].map(r => { return { source: r }; }) }); } } targetsForUntitled.push(URI.file(targetPath)); } } // This returns a TPromise that performs the save. let saveAll = () => { // Handle files first that can just be saved return super.saveAll(fileResources).then(result => { // Handle untitled let untitledSaveAsPromises: TPromise<void>[] = []; targetsForUntitled.forEach((target, index) => { let untitledSaveAsPromise = this.saveAs(untitledResources[index], target).then(uri => { result.results.push({ source: untitledResources[index], target: uri, success: !!uri }); }); untitledSaveAsPromises.push(untitledSaveAsPromise); }); return TPromise.join(untitledSaveAsPromises).then(() => { return result; }); }); } // See if any of these need a commit message let needsCommitMessage: boolean = false; let resources: URI[] = [...fileResources, ...targetsForUntitled]; for (let i = 0; i < resources.length; i++) { let gistRegEx = (<IWindowConfiguration><any>this.environmentService).gistRegEx; if (!gistRegEx || !gistRegEx.test(paths.normalize(resources[i].fsPath))) { needsCommitMessage = true; break; } } if (needsCommitMessage) { // Prompt for a commit message. // We get the QuickOpenService here instead of via service injection because it hasn't // yet been instantiated when the textFileService is -- BIG CLUE THIS ISN'T THE RIGHT // PLACE TO DO THIS. // TODO: validateInput fn to put appropriate constraints on the commit message. let quickOpenService = this.instService.createInstance<IQuickOpenService>(QuickOpenController); return quickOpenService.input({ prompt: 'Enter a commit message.', placeHolder: 'Commit message'}).then((result) => { // If user canceled the input box. if (!result) { return TPromise.as({ results: [...fileResources, ...untitledResources].map((r) => { return { source: r }; }) }); } // This hack gets the commit message from here to the bowels of the githubFileService where // it is needed at updateContent time. Ideally it would be passed through IUpdateContentOptions // but that would involve forking a number of VSC source files. this.fileService.updateOptions({ commitMessage: result }); // Save the files return saveAll(); }); } else { // No commit message needed; just save. return saveAll(); } } public saveAs(resource: URI, target?: URI): TPromise<URI> { // Get to target resource if (!target) { let dialogPath = resource.fsPath; if (resource.scheme === 'untitled') { dialogPath = this.suggestFileName(resource); } const pathRaw = this.promptForPath(dialogPath); if (pathRaw) { target = URI.file(pathRaw); } } if (!target) { return TPromise.as(null); // user canceled } // Just save if target is same as models own resource if (resource.toString() === target.toString()) { return this.save(resource).then(() => resource); } // Do it return this.doSaveAs(resource, target); } private doSaveAs(resource: URI, target?: URI): TPromise<URI> { // Retrieve text model from provided resource if any let modelPromise: TPromise<TextFileEditorModel | UntitledEditorModel> = TPromise.as(null); if (resource.scheme === 'file') { modelPromise = TPromise.as(CACHE.get(resource)); } else if (resource.scheme === 'untitled') { let untitled = this.untitledEditorService.get(resource); if (untitled) { modelPromise = untitled.resolve(); } } return modelPromise.then(model => { // We have a model: Use it (can be null e.g. if this file is binary and not a text file or was never opened before) if (model) { return this.doSaveTextFileAs(model, resource, target); } // Otherwise we can only copy return this.fileService.copyFile(resource, target); }).then(() => { // Revert the source return this.revert(resource).then(() => { // Done: return target return target; }); }); } private doSaveTextFileAs(sourceModel: TextFileEditorModel | UntitledEditorModel, resource: URI, target: URI): TPromise<void> { // create the target file empty if it does not exist already return this.fileService.resolveFile(target).then(stat => stat, () => null).then(stat => stat || this.fileService.createFile(target)).then(stat => { // resolve a model for the file (which can be binary if the file is not a text file) return this.editorService.resolveEditorModel({ resource: target }).then((targetModel: TextFileEditorModel) => { // binary model: delete the file and run the operation again if (targetModel instanceof BinaryEditorModel) { return this.fileService.del(target).then(() => this.doSaveTextFileAs(sourceModel, resource, target)); } // text model: take over encoding and model value from source model targetModel.updatePreferredEncoding(sourceModel.getEncoding()); targetModel.textEditorModel.setValue(sourceModel.getValue()); // save model return targetModel.save(); }); }); } private suggestFileName(untitledResource: URI): string { let workspace = this.contextService.getWorkspace(); if (workspace) { return URI.file(paths.join(workspace.resource.fsPath, this.untitledEditorService.get(untitledResource).suggestFileName())).fsPath; } return this.untitledEditorService.get(untitledResource).suggestFileName(); } private promptForPath(defaultPath?: string): string { return this.windowService.getWindow().showSaveDialog(this.getSaveDialogOptions(defaultPath ? paths.normalize(defaultPath, true) : void 0)); } private getSaveDialogOptions(defaultPath?: string): Electron.SaveDialogOptions { let options: Electron.SaveDialogOptions = { defaultPath: defaultPath }; // Filters are working flaky in Electron and there are bugs. On Windows they are working // somewhat but we see issues: // - https://github.com/electron/electron/issues/3556 // - https://github.com/Microsoft/vscode/issues/451 // - Bug on Windows: When "All Files" is picked, the path gets an extra ".*" // - Bug on Windows: Cannot save file without extension // - Bug on Windows: Untitled files get just the first extension of the list // Until these issues are resolved, we disable the dialog file extension filtering. let disable = true; // Simply using if (true) flags the code afterwards as not reachable. if (disable) { return options; } interface IFilter { name: string; extensions: string[]; } // Build the file filter by using our known languages let ext: string = paths.extname(defaultPath); let matchingFilter: IFilter; let filters: IFilter[] = this.modeService.getRegisteredLanguageNames().map(languageName => { let extensions = this.modeService.getExtensions(languageName); if (!extensions || !extensions.length) { return null; } let filter: IFilter = { name: languageName, extensions: extensions.map(e => strings.trim(e, '.')) }; if (ext && extensions.indexOf(ext) >= 0) { matchingFilter = filter; return null; // matching filter will be added last to the top } return filter; }).filter(f => !!f); // Filters are a bit weird on Windows, based on having a match or not: // Match: we put the matching filter first so that it shows up selected and the all files last // No match: we put the all files filter first let allFilesFilter = { name: nls.localize('allFiles', "All Files"), extensions: ['*'] }; if (matchingFilter) { filters.unshift(matchingFilter); filters.push(allFilesFilter); } else { filters.unshift(allFilesFilter); } options.filters = filters; return options; } }
the_stack
import { FabricStyles, isTwoDimArray, IExplanationContext, IExplanationGenerators, IGlobalExplanation, ILocalExplanation, IExplanationModelMetadata, ITestDataset, ModelExplanationUtils, ModelTypes, IFeatureValueExplanation, IWeightedDropdownContext, WeightVectorOption, WeightVectors, JointDataset, IMultiClassBoundedCoordinates, TelemetryLevels } from "@responsible-ai/core-ui"; import { localization } from "@responsible-ai/localization"; import { IPlotlyProperty, SelectionContext, ModelMetadata } from "@responsible-ai/mlchartlib"; import { initializeIcons } from "@uifabric/icons"; import _ from "lodash"; import memoize from "memoize-one"; import { PrimaryButton, IComboBox, IComboBoxOption, IDropdownOption, Pivot, PivotItem, PivotLinkFormat, PivotLinkSize, IPivotItemProps } from "office-ui-fabric-react"; import React from "react"; import { EbmExplanation } from "./Controls/EbmExplanation"; import { FeatureImportanceBar } from "./Controls/FeatureImportance/FeatureImportanceBar"; import { FeatureImportanceModes } from "./Controls/FeatureImportance/FeatureImportanceModes"; import { IFeatureImportanceConfig, globalFeatureImportanceId, barId, FeatureImportanceWrapper } from "./Controls/FeatureImportance/FeatureImportanceWrapper"; import { ICEPlot } from "./Controls/ICEPlot"; import { PerturbationExploration } from "./Controls/PerturbationExploration"; import { DataExploration, dataScatterId } from "./Controls/Scatter/DataExploration"; import { ExplanationExploration, explanationScatterId } from "./Controls/Scatter/ExplanationExploration"; import { localBarId, SinglePointFeatureImportance } from "./Controls/SinglePointFeatureImportance"; import { explanationDashboardStyles } from "./ExplanationDashboard.styles"; import { IExplanationDashboardProps } from "./Interfaces/IExplanationDashboardProps"; import { IBarChartConfig } from "./SharedComponents/IBarChartConfig"; import { validateInputs } from "./validateInputs"; const rowIndex = "rowIndex"; export interface IDashboardContext { explanationContext: IExplanationContext; weightContext: IWeightedDropdownContext; } export interface IDashboardState { dashboardContext: IDashboardContext; activeGlobalTab: number; activeLocalTab: number; configs: { [key: string]: IPlotlyProperty | IFeatureImportanceConfig | IBarChartConfig; }; selectedRow: number | undefined; } export class ExplanationDashboard extends React.Component< IExplanationDashboardProps, IDashboardState > { private static iconsInitialized = false; private static globalTabKeys: string[] = [ "dataExploration", "globalImportance", "explanationExploration", "summaryImportance", "modelExplanation", "customVisualization" ]; private static localTabKeys: string[] = [ "featureImportance", "perturbationExploration", "ICE" ]; private static transposeLocalImportanceMatrix: ( input: number[][][] ) => number[][][] = memoize((input: number[][][]): number[][][] => { const numClasses = input.length; const numRows = input[0].length; const numFeatures = input[0][0].length; const result: number[][][] = new Array(numRows) .fill(0) .map(() => new Array(numFeatures).fill(0).map(() => new Array(numClasses).fill(0)) ); input.forEach((rowByFeature, classIndex) => { rowByFeature.forEach((featureArray, rowIndex) => { featureArray.forEach((value, featureIndex) => { result[rowIndex][featureIndex][classIndex] = value; }); }); }); return result; }); private static buildWeightDropdownOptions: ( explanationContext: IExplanationContext ) => IDropdownOption[] = memoize( (explanationContext: IExplanationContext): IDropdownOption[] => { const result: IDropdownOption[] = [ { key: WeightVectors.AbsAvg, text: localization.Interpret.absoluteAverage } ]; if (explanationContext.testDataset.predictedY) { result.push({ key: WeightVectors.Predicted, text: localization.Interpret.predictedClass }); } explanationContext.modelMetadata.classNames.forEach((name, index) => { result.push({ key: index, text: name }); }); return result; } ); private static getClassLength: (props: IExplanationDashboardProps) => number = memoize((props: IExplanationDashboardProps): number => { if ( props.precomputedExplanations && props.precomputedExplanations.localFeatureImportance && props.precomputedExplanations.localFeatureImportance.scores ) { const localImportances = props.precomputedExplanations.localFeatureImportance.scores; if ( (localImportances as number[][][]).every((dim1) => { return dim1.every((dim2) => Array.isArray(dim2)); }) ) { return localImportances.length; } // 2d is regression (could be a non-scikit convention binary, but that is not supported) return 1; } if ( props.precomputedExplanations && props.precomputedExplanations.globalFeatureImportance && props.precomputedExplanations.globalFeatureImportance.scores ) { // determine if passed in vaules is 1D or 2D if ( ( props.precomputedExplanations.globalFeatureImportance .scores as number[][] ).every((dim1) => Array.isArray(dim1)) ) { return ( props.precomputedExplanations.globalFeatureImportance .scores as number[][] )[0].length; } } if ( props.probabilityY && Array.isArray(props.probabilityY) && Array.isArray(props.probabilityY[0]) && props.probabilityY[0].length > 0 ) { return props.probabilityY[0].length; } // default to regression case return 1; }); private readonly selectionContext = new SelectionContext(rowIndex, 1); private selectionSubscription: string | undefined; private pivotItems: IPivotItemProps[]; public constructor(props: IExplanationDashboardProps) { super(props); ExplanationDashboard.initializeIcons(props); if (this.props.locale) { localization.setLanguage(this.props.locale); } const explanationContext: IExplanationContext = ExplanationDashboard.buildInitialExplanationContext(props); const defaultTopK = Math.min( 8, explanationContext.modelMetadata.featureNames.length ); this.pivotItems = []; if (explanationContext.testDataset.dataset !== undefined) { this.pivotItems.push({ headerText: localization.Interpret.dataExploration, itemKey: ExplanationDashboard.globalTabKeys[0] }); } if (explanationContext.globalExplanation !== undefined) { this.pivotItems.push({ headerText: localization.Interpret.globalImportance, itemKey: ExplanationDashboard.globalTabKeys[1] }); } if ( explanationContext.localExplanation !== undefined && explanationContext.testDataset.dataset !== undefined ) { this.pivotItems.push({ headerText: localization.Interpret.explanationExploration, itemKey: ExplanationDashboard.globalTabKeys[2] }); } if (explanationContext.localExplanation !== undefined) { this.pivotItems.push({ headerText: localization.Interpret.summaryImportance, itemKey: ExplanationDashboard.globalTabKeys[3] }); } if (explanationContext.ebmExplanation !== undefined) { this.pivotItems.push({ headerText: localization.Interpret.summaryImportance, itemKey: ExplanationDashboard.globalTabKeys[4] }); } if (explanationContext.customVis !== undefined) { this.pivotItems.push({ headerText: localization.Interpret.summaryImportance, itemKey: ExplanationDashboard.globalTabKeys[5] }); } this.state = { activeGlobalTab: this.pivotItems.length > 0 && this.pivotItems[0].itemKey ? ExplanationDashboard.globalTabKeys.indexOf( this.pivotItems[0].itemKey ) : 0, activeLocalTab: explanationContext.localExplanation === undefined && this.props.requestPredictions ? 1 : 0, configs: { [barId]: { displayMode: FeatureImportanceModes.Bar, id: barId, topK: defaultTopK }, [globalFeatureImportanceId]: { displayMode: FeatureImportanceModes.Beehive, id: globalFeatureImportanceId, topK: defaultTopK }, [localBarId]: { topK: defaultTopK } }, dashboardContext: { explanationContext, weightContext: { onSelection: this.onClassSelect, options: ExplanationDashboard.buildWeightDropdownOptions(explanationContext), selectedKey: props.predictedY ? WeightVectors.Predicted : WeightVectors.AbsAvg } }, selectedRow: undefined }; } public static buildInitialExplanationContext( props: IExplanationDashboardProps ): IExplanationContext { const explanationGenerators: IExplanationGenerators = { requestLocalFeatureExplanations: props.requestLocalFeatureExplanations, requestPredictions: props.requestPredictions }; const modelMetadata = ExplanationDashboard.buildModelMetadata(props); const errorMessage = validateInputs(props, modelMetadata); if (errorMessage !== undefined) { if (props.telemetryHook !== undefined) { props.telemetryHook({ context: errorMessage, level: TelemetryLevels.Error, message: "Invalid inputs" }); } return { customVis: undefined, ebmExplanation: undefined, explanationGenerators, globalExplanation: undefined, inputError: errorMessage, isGlobalDerived: false, jointDataset: undefined, localExplanation: undefined, modelMetadata, testDataset: {} }; } const testDataset: ITestDataset = { dataset: props.testData, predictedY: props.predictedY, probabilityY: props.probabilityY, trueY: props.trueY }; let localExplanation: ILocalExplanation | undefined; if ( props.precomputedExplanations && props.precomputedExplanations.localFeatureImportance !== undefined && props.precomputedExplanations.localFeatureImportance.scores !== undefined && testDataset ) { const weighting = props.predictedY ? WeightVectors.Predicted : WeightVectors.AbsAvg; const localFeatureMatrix = ExplanationDashboard.buildLocalFeatureMatrix( props.precomputedExplanations.localFeatureImportance.scores, modelMetadata.modelType ); const flattenedFeatureMatrix = ExplanationDashboard.buildLocalFlattenMatrix( localFeatureMatrix, modelMetadata.modelType, testDataset, weighting ); const intercepts = undefined; // if (props.precomputedExplanations.localFeatureImportance.intercept) { // intercepts = (modelMetadata.modelType === ModelTypes.regression ? // [props.precomputedExplanations.localFeatureImportance.intercept] : // props.precomputedExplanations.localFeatureImportance.intercept) as number[]; // } localExplanation = { flattenedValues: flattenedFeatureMatrix, intercepts, values: localFeatureMatrix }; } let globalExplanation: IGlobalExplanation | undefined; let isGlobalDerived = false; if ( props.precomputedExplanations && props.precomputedExplanations.globalFeatureImportance !== undefined && props.precomputedExplanations.globalFeatureImportance.scores !== undefined ) { const intercepts = undefined; // if (props.precomputedExplanations.globalFeatureImportance.intercept) { // intercepts = props.precomputedExplanations.globalFeatureImportance.intercept; // } // determine if passed in vaules is 1D or 2D // Use the global explanation if its been computed and is 2D if ( ( props.precomputedExplanations.globalFeatureImportance .scores as number[][] ).every((dim1) => Array.isArray(dim1)) ) { globalExplanation = {}; globalExplanation.perClassFeatureImportances = props .precomputedExplanations.globalFeatureImportance.scores as number[][]; globalExplanation.flattenedFeatureImportances = globalExplanation.perClassFeatureImportances.map( (classArray) => classArray.reduce((a, b) => a + b), 0 ); globalExplanation.intercepts = intercepts; } else if (localExplanation === undefined) { // Take the global if we can't build better from local globalExplanation = {}; globalExplanation.flattenedFeatureImportances = props .precomputedExplanations.globalFeatureImportance.scores as number[]; globalExplanation.intercepts = intercepts; } } if (globalExplanation === undefined && localExplanation !== undefined) { globalExplanation = ExplanationDashboard.buildGlobalExplanationFromLocal(localExplanation); isGlobalDerived = true; } let ebmExplanation: IFeatureValueExplanation | undefined; if ( props.precomputedExplanations && props.precomputedExplanations.ebmGlobalExplanation !== undefined ) { ebmExplanation = { displayParameters: { interpolation: "vh" }, featureList: props.precomputedExplanations.ebmGlobalExplanation.feature_list .map((featureExplanation) => { if (featureExplanation.type !== "univariate") { return undefined; } if ( featureExplanation.scores && isTwoDimArray(featureExplanation.scores) ) { return { lowerBounds: featureExplanation.lower_bounds ? featureExplanation.lower_bounds : undefined, names: featureExplanation.names, scores: featureExplanation.scores, type: "univariate", upperBounds: featureExplanation.upper_bounds ? featureExplanation.upper_bounds : undefined } as IMultiClassBoundedCoordinates; } return { lowerBounds: featureExplanation.lower_bounds ? [featureExplanation.lower_bounds] : undefined, names: featureExplanation.names, scores: [featureExplanation.scores], type: "univariate", upperBounds: featureExplanation.upper_bounds ? [featureExplanation.upper_bounds] : undefined } as IMultiClassBoundedCoordinates; }) .filter((featureExplanation) => featureExplanation !== undefined) }; } const jointDataset = new JointDataset({ dataset: props.testData, metadata: modelMetadata, predictedY: props.predictedY, trueY: props.trueY }); const customVis = props.precomputedExplanations && props.precomputedExplanations.customVis ? props.precomputedExplanations.customVis : undefined; return { customVis, ebmExplanation, explanationGenerators, globalExplanation, isGlobalDerived, jointDataset, localExplanation, modelMetadata, testDataset }; } private static initializeIcons(props: IExplanationDashboardProps): void { if ( ExplanationDashboard.iconsInitialized === false && props.shouldInitializeIcons !== false ) { initializeIcons(props.iconUrl); ExplanationDashboard.iconsInitialized = true; } } private static buildLocalFeatureMatrix( localExplanationRaw: number[][] | number[][][], modelType: ModelTypes ): number[][][] { switch (modelType) { case ModelTypes.Regression: { return (localExplanationRaw as number[][]).map((featureArray) => featureArray.map((val) => [val]) ); } case ModelTypes.Binary: { return ExplanationDashboard.transposeLocalImportanceMatrix( localExplanationRaw as number[][][] ).map((featuresByClasses) => featuresByClasses.map((classArray) => classArray.slice(0, 1)) ); } case ModelTypes.Multiclass: default: { return ExplanationDashboard.transposeLocalImportanceMatrix( localExplanationRaw as number[][][] ); } } } private static buildLocalFlattenMatrix( localExplanations: number[][][] | undefined, modelType: ModelTypes, testData: ITestDataset, weightVector: WeightVectorOption ): number[][] | undefined { if (!localExplanations) { return undefined; } switch (modelType) { case ModelTypes.Regression: case ModelTypes.Binary: { // no need to flatten what is already flat return localExplanations.map((featuresByClasses) => { return featuresByClasses.map((classArray) => { return classArray[0]; }); }); } case ModelTypes.Multiclass: default: { return localExplanations.map((featuresByClasses, rowIndex) => { return featuresByClasses.map((classArray) => { switch (weightVector) { case WeightVectors.Equal: { return classArray.reduce((a, b) => a + b) / classArray.length; } case WeightVectors.Predicted: { if (testData.predictedY) { return classArray[testData.predictedY[rowIndex]]; } return 0; } case WeightVectors.AbsAvg: { return ( classArray.reduce((a, b) => a + Math.abs(b), 0) / classArray.length ); } default: { return classArray[weightVector]; } } }); }); } } } private static buildGlobalExplanationFromLocal( localExplanation: ILocalExplanation ): IGlobalExplanation { return { perClassFeatureImportances: ModelExplanationUtils.absoluteAverageTensor( localExplanation.values ) // intercepts: localExplanation.intercepts ? localExplanation.intercepts.map(val => Math.abs(val)) : undefined }; } private static buildModelMetadata( props: IExplanationDashboardProps ): IExplanationModelMetadata { const modelType = ExplanationDashboard.getModelType(props); let featureNames = props.dataSummary.featureNames; let featureNamesAbridged: string[]; const maxLength = 18; if (featureNames !== undefined) { if (!featureNames.every((name) => typeof name === "string")) { featureNames = featureNames.map((x) => x.toString()); } featureNamesAbridged = featureNames.map((name) => { return name.length <= maxLength ? name : `${name.slice(0, maxLength)}...`; }); } else { let featureLength = 0; if (props.testData && props.testData[0] !== undefined) { featureLength = props.testData[0].length; } else if ( props.precomputedExplanations && props.precomputedExplanations.globalFeatureImportance && props.precomputedExplanations.globalFeatureImportance.scores ) { featureLength = props.precomputedExplanations.globalFeatureImportance.scores.length; } else if ( props.precomputedExplanations && props.precomputedExplanations.localFeatureImportance && props.precomputedExplanations.localFeatureImportance.scores ) { const localImportances = props.precomputedExplanations.localFeatureImportance.scores; if ( (localImportances as number[][][]).every((dim1) => { return dim1.every((dim2) => Array.isArray(dim2)); }) ) { featureLength = ( props.precomputedExplanations.localFeatureImportance .scores[0][0] as number[] ).length; } else { featureLength = ( props.precomputedExplanations.localFeatureImportance .scores[0] as number[] ).length; } } else if ( props.precomputedExplanations && props.precomputedExplanations.ebmGlobalExplanation ) { featureLength = props.precomputedExplanations.ebmGlobalExplanation.feature_list .length; } featureNames = ExplanationDashboard.buildIndexedNames( featureLength, localization.Interpret.defaultFeatureNames ); featureNamesAbridged = featureNames; } let classNames = props.dataSummary.classNames; const classLength = ExplanationDashboard.getClassLength(props); if (!classNames || classNames.length !== classLength) { classNames = ExplanationDashboard.buildIndexedNames( classLength, localization.Interpret.defaultClassNames ); } const featureIsCategorical = ModelMetadata.buildIsCategorical( featureNames.length, props.testData, props.dataSummary.categoricalMap ); const featureRanges = ModelMetadata.buildFeatureRanges( props.testData, featureIsCategorical, props.dataSummary.categoricalMap ) || []; return { classNames, featureIsCategorical, featureNames, featureNamesAbridged, featureRanges, modelType }; } private static buildIndexedNames( length: number, baseString: string ): string[] { return [...new Array(length).keys()].map((i) => localization.formatString(baseString, i.toString()) ); } private static getModelType(props: IExplanationDashboardProps): ModelTypes { // If python gave us a hint, use it if (props.modelInformation.method === "regressor") { return ModelTypes.Regression; } switch (ExplanationDashboard.getClassLength(props)) { case 1: return ModelTypes.Regression; case 2: return ModelTypes.Binary; default: return ModelTypes.Multiclass; } } public componentDidMount(): void { this.selectionSubscription = this.selectionContext.subscribe({ selectionCallback: (selections) => { let selectedRow: number | undefined; if (selections && selections.length > 0) { const numericValue = Number.parseInt(selections[0]); if (!Number.isNaN(numericValue)) { selectedRow = numericValue; } } this.setState({ selectedRow }); } }); this.fetchExplanations(); } public componentDidUpdate(prevProps: IExplanationDashboardProps): void { if (this.props.locale && prevProps.locale !== this.props.locale) { localization.setLanguage(this.props.locale); } if (_.isEqual(prevProps, this.props)) { return; } const newState = _.cloneDeep(this.state); newState.dashboardContext.explanationContext = ExplanationDashboard.buildInitialExplanationContext(this.props); if (newState.dashboardContext.explanationContext.localExplanation) { ( newState.configs[globalFeatureImportanceId] as IFeatureImportanceConfig ).displayMode = FeatureImportanceModes.Box; } this.setState(newState); this.fetchExplanations(); } public componentWillUnmount(): void { if (this.selectionSubscription) { this.selectionContext.unsubscribe(this.selectionSubscription); } } public render(): React.ReactNode { if (this.state.dashboardContext.explanationContext.inputError) { return ( <div>{this.state.dashboardContext.explanationContext.inputError}</div> ); } if (this.pivotItems.length === 0) { return <div>No valid views. Incomplete data.</div>; } return ( <div className={explanationDashboardStyles.explainerDashboard}> <div className={explanationDashboardStyles.chartsWrapper}> <div className={explanationDashboardStyles.globalChartsWrapper}> <Pivot id={"globalPivot"} selectedKey={ ExplanationDashboard.globalTabKeys[this.state.activeGlobalTab] } onLinkClick={this.handleGlobalTabClick} linkFormat={PivotLinkFormat.tabs} linkSize={PivotLinkSize.normal} headersOnly styles={FabricStyles.verticalTabsStyle} > {this.pivotItems.map((props) => ( <PivotItem key={props.itemKey} {...props} /> ))} </Pivot> {this.state.activeGlobalTab === 0 && ( <DataExploration dashboardContext={this.state.dashboardContext} theme={this.props.theme as any} selectionContext={this.selectionContext} selectedRow={this.state.selectedRow} plotlyProps={ this.state.configs[dataScatterId] as IPlotlyProperty } onChange={this.onConfigChanged} messages={ this.props.stringParams ? this.props.stringParams.contextualHelp : undefined } /> )} {this.state.activeGlobalTab === 1 && ( <FeatureImportanceBar dashboardContext={this.state.dashboardContext} theme={this.props.theme as any} selectionContext={this.selectionContext} selectedRow={this.state.selectedRow} config={this.state.configs[barId] as IFeatureImportanceConfig} onChange={this.onConfigChanged} messages={ this.props.stringParams ? this.props.stringParams.contextualHelp : undefined } /> )} {this.state.activeGlobalTab === 2 && ( <ExplanationExploration dashboardContext={this.state.dashboardContext} theme={this.props.theme as any} selectionContext={this.selectionContext} selectedRow={this.state.selectedRow} plotlyProps={ this.state.configs[explanationScatterId] as IPlotlyProperty } onChange={this.onConfigChanged} messages={ this.props.stringParams ? this.props.stringParams.contextualHelp : undefined } /> )} {this.state.activeGlobalTab === 3 && ( <FeatureImportanceWrapper dashboardContext={this.state.dashboardContext} theme={this.props.theme as any} selectionContext={this.selectionContext} selectedRow={this.state.selectedRow} config={ this.state.configs[ globalFeatureImportanceId ] as IFeatureImportanceConfig } onChange={this.onConfigChanged} messages={ this.props.stringParams ? this.props.stringParams.contextualHelp : undefined } /> )} {this.state.activeGlobalTab === 4 && ( <EbmExplanation explanationContext={ this.state.dashboardContext.explanationContext } theme={this.props.theme as any} /> )} {this.state.activeGlobalTab === 5 && ( <iframe title="custom" srcDoc={ this.state.dashboardContext.explanationContext.customVis } /> )} </div> {this.state.dashboardContext.explanationContext.localExplanation && ( <div className={explanationDashboardStyles.localChartsWrapper}> {this.state.selectedRow === undefined && ( <div className={explanationDashboardStyles.localPlaceholder}> <div className={explanationDashboardStyles.placeholderText}> {localization.Interpret.selectPoint} </div> </div> )} {this.state.selectedRow !== undefined && ( <div className={explanationDashboardStyles.tabbedViewer}> <Pivot selectedKey={ ExplanationDashboard.localTabKeys[ this.state.activeLocalTab ] } onLinkClick={this.handleLocalTabClick} linkFormat={PivotLinkFormat.tabs} linkSize={PivotLinkSize.normal} headersOnly styles={FabricStyles.verticalTabsStyle} > <PivotItem headerText={localization.Interpret.localFeatureImportance} itemKey={ExplanationDashboard.localTabKeys[0]} /> {this.props.requestPredictions !== undefined && this.state.dashboardContext.explanationContext.testDataset .dataset && this.props.requestPredictions && ( <PivotItem headerText={ localization.Interpret.perturbationExploration } itemKey={ExplanationDashboard.localTabKeys[1]} /> )}{" "} {this.props.requestPredictions !== undefined && this.state.dashboardContext.explanationContext.testDataset .dataset && ( <PivotItem headerText={localization.Interpret.ice} itemKey={ExplanationDashboard.localTabKeys[2]} /> )} </Pivot> <div className={explanationDashboardStyles.viewPanel}> <div className={explanationDashboardStyles.localCommands}> <PrimaryButton className={explanationDashboardStyles.clearButton} onClick={this.onClearSelection} text={localization.Interpret.clearSelection} /> </div> {this.state.activeLocalTab === 0 && ( <SinglePointFeatureImportance explanationContext={ this.state.dashboardContext.explanationContext } selectedRow={this.state.selectedRow} config={ this.state.configs[localBarId] as IBarChartConfig } onChange={this.onConfigChanged} messages={ this.props.stringParams ? this.props.stringParams.contextualHelp : undefined } theme={this.props.theme as any} /> )} {this.state.activeLocalTab === 1 && ( <PerturbationExploration explanationContext={ this.state.dashboardContext.explanationContext } invokeModel={this.props.requestPredictions} datapointIndex={+this.selectionContext.selectedIds[0]} theme={this.props.theme as any} messages={ this.props.stringParams ? this.props.stringParams.contextualHelp : undefined } /> )} {this.state.activeLocalTab === 2 && ( <ICEPlot explanationContext={ this.state.dashboardContext.explanationContext } invokeModel={this.props.requestPredictions} datapointIndex={+this.selectionContext.selectedIds[0]} theme={this.props.theme as any} messages={ this.props.stringParams ? this.props.stringParams.contextualHelp : undefined } /> )} </div> </div> )} </div> )} </div> </div> ); } private fetchExplanations(): void { const expContext = this.state.dashboardContext.explanationContext; const modelMetadata = expContext.modelMetadata; if ( !expContext.explanationGenerators.requestLocalFeatureExplanations || !expContext.testDataset || !expContext.testDataset.dataset || !expContext.localExplanation?.values ) { return; } const requestLocalFeatureExplanations = expContext.explanationGenerators.requestLocalFeatureExplanations; const testDataset = expContext.testDataset; const dataset = expContext.testDataset.dataset; this.setState( (prevState) => { const newState = _.cloneDeep(prevState); if (newState.dashboardContext.explanationContext) { newState.dashboardContext.explanationContext.localExplanation = { // a mock number, we can impl a progress bar if desired. percentComplete: 10, values: [] }; } return newState; }, () => { requestLocalFeatureExplanations( dataset, new AbortController().signal ).then((result) => { if (!result) { return; } this.setState((prevState) => { const weighting = prevState.dashboardContext.weightContext.selectedKey; const localFeatureMatrix = ExplanationDashboard.buildLocalFeatureMatrix( result, modelMetadata.modelType ); const flattenedFeatureMatrix = ExplanationDashboard.buildLocalFlattenMatrix( localFeatureMatrix, modelMetadata.modelType, testDataset, weighting ); const newState = _.cloneDeep(prevState); newState.dashboardContext.explanationContext.localExplanation = { flattenedValues: flattenedFeatureMatrix, percentComplete: undefined, values: localFeatureMatrix }; if ( prevState.dashboardContext.explanationContext .globalExplanation === undefined ) { newState.dashboardContext.explanationContext.globalExplanation = ExplanationDashboard.buildGlobalExplanationFromLocal( newState.dashboardContext.explanationContext.localExplanation ); newState.dashboardContext.explanationContext.isGlobalDerived = true; } return newState; }); }); } ); } private onClassSelect = ( _event: React.FormEvent<IComboBox>, item?: IComboBoxOption ): void => { if (!item) { return; } this.setState((prevState) => { const newWeightContext = _.cloneDeep( prevState.dashboardContext.weightContext ); newWeightContext.selectedKey = item.key as any; const flattenedFeatureMatrix = ExplanationDashboard.buildLocalFlattenMatrix( prevState.dashboardContext.explanationContext.localExplanation ?.values, prevState.dashboardContext.explanationContext.modelMetadata.modelType, prevState.dashboardContext.explanationContext.testDataset, item.key as any ); return { dashboardContext: { explanationContext: { explanationGenerators: prevState.dashboardContext.explanationContext .explanationGenerators, globalExplanation: prevState.dashboardContext.explanationContext.globalExplanation, isGlobalDerived: prevState.dashboardContext.explanationContext.isGlobalDerived, jointDataset: prevState.dashboardContext.explanationContext.jointDataset, localExplanation: { flattenedValues: flattenedFeatureMatrix, intercepts: prevState.dashboardContext.explanationContext.localExplanation ?.intercepts, values: prevState.dashboardContext.explanationContext.localExplanation ?.values || [] }, modelMetadata: prevState.dashboardContext.explanationContext.modelMetadata, testDataset: prevState.dashboardContext.explanationContext.testDataset }, weightContext: newWeightContext } }; }); }; private onConfigChanged = ( newConfig: IPlotlyProperty | IFeatureImportanceConfig | IBarChartConfig, configId: string ): void => { this.setState((prevState) => { const newConfigs = _.cloneDeep(prevState.configs); newConfigs[configId] = newConfig; return { configs: newConfigs }; }); }; private handleGlobalTabClick = (item?: PivotItem): void => { let index = typeof item?.props.itemKey == "string" ? ExplanationDashboard.globalTabKeys.indexOf(item.props.itemKey) : 0; if (index === -1) { index = 0; } this.setState({ activeGlobalTab: index }); }; private handleLocalTabClick = (item?: PivotItem): void => { let index = typeof item?.props.itemKey == "string" ? ExplanationDashboard.localTabKeys.indexOf(item.props.itemKey) : 0; if (index === -1) { index = 0; } this.setState({ activeLocalTab: index }); }; private onClearSelection = (): void => { this.selectionContext.onSelect([]); this.setState({ activeLocalTab: 0 }); (document.querySelector("#globalPivot button") as any).focus(); }; }
the_stack
import * as utils from '../utils' /******************************************************************************* * An indexed version of the min D-heap. For more information on D-heaps, see * ./min-d-heap.ts * * This version of a heap allows us to add key value pairs. This gives us * logarithmic removals and updates, instead of linear. * * We could add do this in a hacky way by adding a mapping from values to indices. * So if we wanted to update or remove a specific value we know the index in the heap * in O(1) time. * * But then using non-primitive complex objects become a hassle. We have to tell * the heap class how to access the value. A better solution is to base it off * unique keys associated with all the nodes. * * enqueue(val) - O(log_d(n)) * dequeue() - O(log_d(n)) * peek() - O(1) * remove(val) - O(log_d(n))! improved from O(n) * update(key, val) - O(log_d(n))! improved from O(n) * decreaseKey(key, val) - O(log_d(n))! improved from O(n) * increaseKey(key, val) - O(log_d(n))! improved from O(n) * * More info can be found here: https://algs4.cs.princeton.edu/24pq/IndexMinPQ.java.html ******************************************************************************/ class MinIndexedDHeap<T> { private d: number // the degree of every node in the heap private sz: number // size of heap private values: Array<T | null> // maps key indices -> values public heap: number[] // maps positions in heap -> key indices public pm: number[] // maps key indices -> positions in heap private compare: utils.CompareFunction<T> constructor(degree: number, compareFunction?: utils.CompareFunction<T>) { this.d = Math.max(2, degree) // degree must be at least 2 this.sz = 0 this.values = [] this.heap = [] this.pm = [] this.compare = compareFunction || utils.defaultCompare } /***************************************************************************** NICETIES *****************************************************************************/ /** * Returns the size of the heap - O(1) * @returns {number} */ size(): number { return this.sz } /** * Returns true if the heap is empty, false otherwise - O(1) * @returns {boolean} */ isEmpty(): boolean { return this.size() == 0 } /***************************************************************************** INSERTION *****************************************************************************/ /** * Adds an value with index to the heap, while maintaing heap invariant - O(log_d(n)) * @param {number} key - index of node * @param {T} value - value of node * @returns {void} */ add(key: number, value: T): boolean { if (this.contains(key)) return false this.values[key] = value // add element to value lookup first this.heap.push(key) // update heap this.sz += 1 const keyPosition = this.size() - 1 this.pm[key] = keyPosition // update position map this.swim(keyPosition) // O(log_d(n)) return true } /***************************************************************************** ACCESSING *****************************************************************************/ /** * Peeks at the top most element in the heap - O(1) * @returns {T} */ peek(): T | null { if (this.isEmpty()) return null const key = this.heap[0] // get top most element const value = this.values[key] return value // get the value associated with key } valueOf(key: number): T | null { if (!this.contains(key)) return null const value = this.values[key] return value } /***************************************************************************** UPDATING *****************************************************************************/ updateKey(key: number, value: T): boolean { if (!this.contains(key)) return false if (!this.values[key]) return false // this means key was unset, so technically it does not exist // update key value lookup first this.values[key] = value // find the key's position in the heap const position = this.pm[key] // O(1) access! no linear seach required :) // and then heapify this.sink(position) this.swim(position) return true } decreaseKey(key: number, newValue: T): boolean { if (!this.contains(key)) return false const oldValue = this.values[key] if (!oldValue) return false // ensure newValue is less than oldValue before updating key value lookup if (this.lessForValues(newValue, oldValue)) this.values[key] = newValue // find position of key const positionOfKey = this.pm[key] // O(1) access! no linear search required // and heapify this.swim(positionOfKey) // O(log_dn) return true } increaseKey(key: number, newValue: T): boolean { if (!this.contains(key)) return false const oldValue = this.values[key] if (!oldValue) return false // ensure newValue is greater than oldValue before updating key value lookup if (this.lessForValues(oldValue, newValue)) this.values[key] = newValue // find position of key const positionOfKey = this.pm[key] // O(1) access! no linear search required // and heapify this.sink(positionOfKey) // O(log_dn) return true } /***************************************************************************** SEARCHING *****************************************************************************/ /** * Returns true if key is in heap, false otherwise - O(1) * @param {number} key * @returns {boolean} */ contains(key: number): boolean { // position map tells us if key exists in heap return this.pm[key] !== undefined && this.pm[key] !== -1 // O(1) access! no linear search required } /***************************************************************************** DELETION *****************************************************************************/ /** * Removes and returns top most element of heap - O(log_d(n)) * @returns {T} */ poll(): T | null { if (this.isEmpty()) return null const keyToBeRemoved = this.heap[0] const removedValue = this.values[keyToBeRemoved] // get the key's value this.deleteKey(keyToBeRemoved) // O(log(n)) return removedValue } deleteKey(key: number): T | null { if (!this.contains(key)) return null // save value for return, and delete it const value = this.values[key] if (value === null) throw new Error() this.values[key] = null // swap root node with last node const removedElementPosition = this.pm[key] const lastElementPosition = this.size() - 1 this.swap(removedElementPosition, lastElementPosition) // remove last key from heap this.heap.pop() this.sz -= 1 // heapify the last element which was swapped this.sink(removedElementPosition) this.swim(removedElementPosition) // remove key from position map this.pm[key] = -1 return value } /** * Clears the heap - O(1) * @returns {void} */ clear(): void { this.values.length = 0 this.pm.length = 0 this.heap.length = 0 this.sz = 0 } /***************************************************************************** HELPERS *****************************************************************************/ // O(1) private getChildrenPositions(parentIndex: number): number[] { const indices = [] for (let i = 1; i <= this.d; i++) { indices.push(parentIndex * this.d + i) } return indices } // O(1) private getParentPosition(childIndex: number): number { return Math.floor((childIndex - 1) / this.d) } /** * Returns true if value of value at positionA is less than value at positionB * @param {number} positionA * @param {number} positionB */ private lessForPositions(positionA: number, positionB: number): boolean { // we need to compare values, but we were given positions... // find the keys first from positions with heap const keyA = this.heap[positionA] const keyB = this.heap[positionB] // then find values of keys with key value lookup const valueA = this.values[keyA] const valueB = this.values[keyB] if (valueA === null || valueB === null) throw new Error(utils.VALUE_DOES_NOT_EXIST_ERROR) // now we can compare the raw values return this.compare(valueA, valueB) < 0 } private lessForValues(a: T, b: T): boolean { return this.compare(a, b) < 0 } /** * Sinks element with index k until heap invariant is satisfied - O(dlog(n)) * O(dlog(n)) because in the worst case we sink the element down the entire * height of the tree. At each level, we have to do d comparisons to find * smallest child to swim down. * @param {number} k * @returns {void} */ private sink(k: number): void { // eslint-disable-next-line while (true) { const childrenPositions = this.getChildrenPositions(k) // get position of smallest child - O(d) let smallestChildPosition = childrenPositions[0] // assume left most child is smallest at first for (const childPosition of childrenPositions) { const childPositionIsInBounds = childPosition < this.size() const currentChildIsSmallerThanCurrentMin = this.lessForPositions( childPosition, smallestChildPosition ) if (childPositionIsInBounds && currentChildIsSmallerThanCurrentMin) { smallestChildPosition = childPosition } } const childPositionOutOfBounds = smallestChildPosition >= this.size() const elementIsLessThanChild = this.lessForPositions(k, smallestChildPosition) if (childPositionOutOfBounds || elementIsLessThanChild) break this.swap(smallestChildPosition, k) // O(1) k = smallestChildPosition // point k to child node, and we repeat loop } } /** * Swims an element with index k until heap invariant is satisfied - O(log_d(n)) * O(logd(n)) because in the worst case we swim the element up the entire tree * @param {number} k * @returns {void} */ private swim(k: number): void { let parentPosition = this.getParentPosition(k) while (k > 0 && this.lessForPositions(k, parentPosition)) { this.swap(parentPosition, k) k = parentPosition // move k pointer up after swapping parentPosition = this.getParentPosition(k) // update parentIndex } } // O(1) private swap(positionI: number, positionJ: number): void { // notice how we don't touch this.values at all // this.values maps keys -> value // we only update heap and positionMap // swap their positions in position map // 1. first get keys... const keyI = this.heap[positionI] const keyJ = this.heap[positionJ] // 2. then swap them in the lookup map for positions this.pm[keyI] = positionJ // keyI will now be at positionJ this.pm[keyJ] = positionI // keyJ will now be at positionI // ==================================== // now swap keys in actual heap const temp = this.heap[positionI] this.heap[positionI] = this.heap[positionJ] this.heap[positionJ] = temp } } export default MinIndexedDHeap
the_stack
import React, { ReactElement, useCallback, useEffect, useReducer, useRef, useState, Children, } from 'react'; import debounce from 'lodash/debounce'; import {EnableSelectionMinor} from '@shopify/polaris-icons'; import type {CheckboxHandles} from '../../types'; import {classNames} from '../../utilities/css'; import {isElementOfType} from '../../utilities/components'; import {Button} from '../Button'; import {EventListener} from '../EventListener'; import {Sticky} from '../Sticky'; import {Spinner} from '../Spinner'; import { CheckableButtonKey, CheckableButtons, ResourceListContext, ResourceListSelectedItems, SELECT_ALL_ITEMS, } from '../../utilities/resource-list'; import {Select, SelectOption} from '../Select'; import {EmptySearchResult} from '../EmptySearchResult'; import {useI18n} from '../../utilities/i18n'; import {ResourceItem} from '../ResourceItem'; import {useLazyRef} from '../../utilities/use-lazy-ref'; import {BulkActions, BulkActionsProps} from '../BulkActions'; import {CheckableButton} from '../CheckableButton'; import styles from './ResourceList.scss'; const SMALL_SCREEN_WIDTH = 458; const SMALL_SPINNER_HEIGHT = 28; const LARGE_SPINNER_HEIGHT = 45; function getAllItemsOnPage<TItemType>( items: TItemType[], idForItem: (item: TItemType, index: number) => string, ) { return items.map((item: TItemType, index: number) => { return idForItem(item, index); }); } const isSmallScreen = () => { return typeof window === 'undefined' ? false : window.innerWidth < SMALL_SCREEN_WIDTH; }; function defaultIdForItem<TItemType extends {id?: any}>( item: TItemType, index: number, ) { return Object.prototype.hasOwnProperty.call(item, 'id') ? item.id : index.toString(); } export interface ResourceListProps<TItemType = any> { /** Item data; each item is passed to renderItem */ items: TItemType[]; filterControl?: React.ReactNode; /** The markup to display when no resources exist yet. Renders when set and items is empty. */ emptyState?: React.ReactNode; /** The markup to display when no results are returned on search or filter of the list. Renders when `filterControl` is set, items are empty, and `emptyState` is not set. * @default EmptySearchResult */ emptySearchState?: React.ReactNode; /** Name of the resource, such as customers or products */ resourceName?: { singular: string; plural: string; }; /** Up to 2 bulk actions that will be given more prominence */ promotedBulkActions?: BulkActionsProps['promotedActions']; /** Actions available on the currently selected items */ bulkActions?: BulkActionsProps['actions']; /** Collection of IDs for the currently selected items */ selectedItems?: ResourceListSelectedItems; /** Whether or not the list has filter(s) applied */ isFiltered?: boolean; /** Renders a Select All button at the top of the list and checkboxes in front of each list item. For use when bulkActions aren't provided. **/ selectable?: boolean; /** Whether or not there are more items than currently set on the items prop. Determines whether or not to set the paginatedSelectAllAction and paginatedSelectAllText props on the BulkActions component. */ hasMoreItems?: boolean; /** Overlays item list with a spinner while a background action is being performed */ loading?: boolean; /** Boolean to show or hide the header */ showHeader?: boolean; /** Total number of resources */ totalItemsCount?: number; /** Current value of the sort control */ sortValue?: string; /** Collection of sort options to choose from */ sortOptions?: SelectOption[]; /** ReactNode to display instead of the sort control */ alternateTool?: React.ReactNode; /** Callback when sort option is changed */ onSortChange?(selected: string, id: string): void; /** Callback when selection is changed */ onSelectionChange?(selectedItems: ResourceListSelectedItems): void; /** Function to render each list item, must return a ResourceItem component */ renderItem(item: TItemType, id: string, index: number): React.ReactNode; /** Function to customize the unique ID for each item */ idForItem?(item: TItemType, index: number): string; /** Function to resolve the ids of items */ resolveItemId?(item: TItemType): string; } type ResourceListType = (<TItemType>( value: ResourceListProps<TItemType>, ) => ReactElement) & { Item: typeof ResourceItem; }; export const ResourceList: ResourceListType = function ResourceList<TItemType>({ items, filterControl, emptyState, emptySearchState, resourceName: resourceNameProp, promotedBulkActions, bulkActions, selectedItems = [], isFiltered, selectable, hasMoreItems, loading, showHeader, totalItemsCount, sortValue, sortOptions, alternateTool, onSortChange, onSelectionChange, renderItem, idForItem = defaultIdForItem, resolveItemId, }: ResourceListProps<TItemType>) { const i18n = useI18n(); const [selectMode, setSelectMode] = useState( Boolean(selectedItems && selectedItems.length > 0), ); const [loadingPosition, setLoadingPositionState] = useState(0); const [lastSelected, setLastSelected] = useState<number>(); const [smallScreen, setSmallScreen] = useState(isSmallScreen()); const forceUpdate: (x?: number) => void = useReducer<(x?: number) => number>( (x = 0) => x + 1, 0, )[1]; const [checkableButtons, setCheckableButtons] = useState<CheckableButtons>( new Map(), ); const defaultResourceName = useLazyRef(() => ({ singular: i18n.translate('Polaris.ResourceList.defaultItemSingular'), plural: i18n.translate('Polaris.ResourceList.defaultItemPlural'), })); const listRef: React.RefObject<HTMLUListElement> = useRef(null); const handleSelectMode = (selectMode: boolean) => { setSelectMode(selectMode); if (!selectMode && onSelectionChange) { onSelectionChange([]); } }; const handleResize = debounce( () => { const newSmallScreen = isSmallScreen(); if ( selectedItems && selectedItems.length === 0 && selectMode && !newSmallScreen ) { handleSelectMode(false); } if (smallScreen !== newSmallScreen) { setSmallScreen(newSmallScreen); } }, 50, {leading: true, trailing: true, maxWait: 50}, ); const isSelectable = Boolean( (promotedBulkActions && promotedBulkActions.length > 0) || (bulkActions && bulkActions.length > 0) || selectable, ); const bulkSelectState = (): boolean | 'indeterminate' => { let selectState: boolean | 'indeterminate' = 'indeterminate'; if ( !selectedItems || (Array.isArray(selectedItems) && selectedItems.length === 0) ) { selectState = false; } else if ( selectedItems === SELECT_ALL_ITEMS || (Array.isArray(selectedItems) && selectedItems.length === items.length) ) { selectState = true; } return selectState; }; const resourceName = resourceNameProp ? resourceNameProp : defaultResourceName.current; const headerTitle = () => { const itemsCount = items.length; const resource = !loading && ((!totalItemsCount && itemsCount === 1) || totalItemsCount === 1) ? resourceName.singular : resourceName.plural; if (loading) { return i18n.translate('Polaris.ResourceList.loading', {resource}); } else if (totalItemsCount) { return i18n.translate('Polaris.ResourceList.showingTotalCount', { itemsCount, totalItemsCount, resource, }); } else { return i18n.translate('Polaris.ResourceList.showing', { itemsCount, resource, }); } }; const bulkActionsLabel = () => { const selectedItemsCount = selectedItems === SELECT_ALL_ITEMS ? `${items.length}+` : selectedItems.length; return i18n.translate('Polaris.ResourceList.selected', { selectedItemsCount, }); }; const bulkActionsAccessibilityLabel = () => { const selectedItemsCount = selectedItems.length; const totalItemsCount = items.length; const allSelected = selectedItemsCount === totalItemsCount; if (totalItemsCount === 1 && allSelected) { return i18n.translate( 'Polaris.ResourceList.a11yCheckboxDeselectAllSingle', { resourceNameSingular: resourceName.singular, }, ); } else if (totalItemsCount === 1) { return i18n.translate( 'Polaris.ResourceList.a11yCheckboxSelectAllSingle', { resourceNameSingular: resourceName.singular, }, ); } else if (allSelected) { return i18n.translate( 'Polaris.ResourceList.a11yCheckboxDeselectAllMultiple', { itemsLength: items.length, resourceNamePlural: resourceName.plural, }, ); } else { return i18n.translate( 'Polaris.ResourceList.a11yCheckboxSelectAllMultiple', { itemsLength: items.length, resourceNamePlural: resourceName.plural, }, ); } }; const paginatedSelectAllText = () => { if (!isSelectable || !hasMoreItems) { return; } if (selectedItems === SELECT_ALL_ITEMS) { return i18n.translate( isFiltered ? 'Polaris.ResourceList.allFilteredItemsSelected' : 'Polaris.ResourceList.allItemsSelected', { itemsLength: items.length, resourceNamePlural: resourceName.plural, }, ); } }; const paginatedSelectAllAction = () => { if (!isSelectable || !hasMoreItems) { return; } const actionText = selectedItems === SELECT_ALL_ITEMS ? i18n.translate('Polaris.Common.undo') : i18n.translate( isFiltered ? 'Polaris.ResourceList.selectAllFilteredItems' : 'Polaris.ResourceList.selectAllItems', { itemsLength: items.length, resourceNamePlural: resourceName.plural, }, ); return { content: actionText, onAction: handleSelectAllItemsInStore, }; }; const emptySearchResultText = { title: i18n.translate('Polaris.ResourceList.emptySearchResultTitle', { resourceNamePlural: resourceName.plural, }), description: i18n.translate( 'Polaris.ResourceList.emptySearchResultDescription', ), }; const handleSelectAllItemsInStore = () => { const newlySelectedItems = selectedItems === SELECT_ALL_ITEMS ? getAllItemsOnPage(items, idForItem) : SELECT_ALL_ITEMS; if (onSelectionChange) { onSelectionChange(newlySelectedItems); } }; const setLoadingPosition = useCallback(() => { if (listRef.current != null) { if (typeof window === 'undefined') { return; } const overlay = listRef.current.getBoundingClientRect(); const viewportHeight = Math.max( document.documentElement ? document.documentElement.clientHeight : 0, window.innerHeight || 0, ); const overflow = viewportHeight - overlay.height; const spinnerHeight = items.length === 1 ? SMALL_SPINNER_HEIGHT : LARGE_SPINNER_HEIGHT; const spinnerPosition = overflow > 0 ? (overlay.height - spinnerHeight) / 2 : (viewportHeight - overlay.top - spinnerHeight) / 2; setLoadingPositionState(spinnerPosition); } }, [listRef, items.length]); const itemsExist = items.length > 0; useEffect(() => { if (loading) { setLoadingPosition(); } }, [loading, setLoadingPosition]); useEffect(() => { if (selectedItems && selectedItems.length > 0 && !selectMode) { setSelectMode(true); } if ((!selectedItems || selectedItems.length === 0) && !isSmallScreen()) { setSelectMode(false); } }, [selectedItems, selectMode]); useEffect(() => { forceUpdate(); }, [forceUpdate, items]); const renderItemWithId = (item: TItemType, index: number) => { const id = idForItem(item, index); const itemContent = renderItem(item, id, index); if ( process.env.NODE_ENV === 'development' && !isElementOfType(itemContent, ResourceItem) ) { // eslint-disable-next-line no-console console.warn( '<ResourceList /> renderItem function should return a <ResourceItem />.', ); } return itemContent; }; const handleMultiSelectionChange = ( lastSelected: number, currentSelected: number, resolveItemId: (item: TItemType) => string, ) => { const min = Math.min(lastSelected, currentSelected); const max = Math.max(lastSelected, currentSelected); return items.slice(min, max + 1).map(resolveItemId); }; const handleCheckableButtonRegistration = ( key: CheckableButtonKey, button: CheckboxHandles, ) => { if (!checkableButtons.get(key)) { setCheckableButtons(new Map(checkableButtons).set(key, button)); } }; const handleSelectionChange = ( selected: boolean, id: string, sortOrder: number | undefined, shiftKey: boolean, ) => { if (selectedItems == null || onSelectionChange == null) { return; } let newlySelectedItems = selectedItems === SELECT_ALL_ITEMS ? getAllItemsOnPage(items, idForItem) : [...selectedItems]; if (sortOrder !== undefined) { setLastSelected(sortOrder); } const lastSelectedFromState = lastSelected; let selectedIds: string[] = [id]; if ( shiftKey && lastSelectedFromState != null && sortOrder !== undefined && resolveItemId ) { selectedIds = handleMultiSelectionChange( lastSelectedFromState, sortOrder, resolveItemId, ); } newlySelectedItems = [...new Set([...newlySelectedItems, ...selectedIds])]; if (!selected) { for (const selectedId of selectedIds) { newlySelectedItems.splice(newlySelectedItems.indexOf(selectedId), 1); } } if (newlySelectedItems.length === 0 && !isSmallScreen()) { handleSelectMode(false); } else if (newlySelectedItems.length > 0) { handleSelectMode(true); } if (onSelectionChange) { onSelectionChange(newlySelectedItems); } }; const handleToggleAll = () => { let newlySelectedItems: string[]; if ( (Array.isArray(selectedItems) && selectedItems.length === items.length) || selectedItems === SELECT_ALL_ITEMS ) { newlySelectedItems = []; } else { newlySelectedItems = items.map((item, index) => { return idForItem(item, index); }); } if (newlySelectedItems.length === 0 && !isSmallScreen()) { handleSelectMode(false); } else if (newlySelectedItems.length > 0) { handleSelectMode(true); } let checkbox: CheckboxHandles | undefined; if (isSmallScreen()) { checkbox = checkableButtons.get('bulkSm'); } else if (newlySelectedItems.length === 0) { checkbox = checkableButtons.get('plain'); } else { checkbox = checkableButtons.get('bulkLg'); } if (onSelectionChange) { onSelectionChange(newlySelectedItems); } // setTimeout ensures execution after the Transition on BulkActions setTimeout(() => { checkbox && checkbox.focus(); }, 0); }; const bulkActionsMarkup = isSelectable ? ( <div className={styles.BulkActionsWrapper}> <BulkActions label={bulkActionsLabel()} accessibilityLabel={bulkActionsAccessibilityLabel()} selected={bulkSelectState()} onToggleAll={handleToggleAll} selectMode={selectMode} onSelectModeToggle={handleSelectMode} promotedActions={promotedBulkActions} paginatedSelectAllAction={paginatedSelectAllAction()} paginatedSelectAllText={paginatedSelectAllText()} actions={bulkActions} disabled={loading} smallScreen={smallScreen} /> </div> ) : null; const filterControlMarkup = filterControl ? ( <div className={styles.FiltersWrapper}>{filterControl}</div> ) : null; const sortingSelectMarkup = sortOptions && sortOptions.length > 0 && !alternateTool ? ( <div className={styles.SortWrapper}> <Select label={i18n.translate('Polaris.ResourceList.sortingLabel')} labelInline={!smallScreen} labelHidden={smallScreen} options={sortOptions} onChange={onSortChange} value={sortValue} disabled={selectMode} /> </div> ) : null; const alternateToolMarkup = alternateTool && !sortingSelectMarkup ? ( <div className={styles.AlternateToolWrapper}>{alternateTool}</div> ) : null; const headerTitleMarkup = ( <div className={styles.HeaderTitleWrapper}>{headerTitle()}</div> ); const selectButtonMarkup = isSelectable ? ( <div className={styles.SelectButtonWrapper}> <Button disabled={selectMode} icon={EnableSelectionMinor} onClick={() => handleSelectMode(true)} > {i18n.translate('Polaris.ResourceList.selectButtonText')} </Button> </div> ) : null; const checkableButtonMarkup = isSelectable ? ( <div className={styles.CheckableButtonWrapper}> <CheckableButton accessibilityLabel={bulkActionsAccessibilityLabel()} label={headerTitle()} onToggleAll={handleToggleAll} plain disabled={loading} /> </div> ) : null; const needsHeader = isSelectable || (sortOptions && sortOptions.length > 0) || alternateTool; const headerWrapperOverlay = loading ? ( <div className={styles['HeaderWrapper-overlay']} /> ) : null; const showEmptyState = emptyState && !itemsExist && !loading; const showEmptySearchState = !showEmptyState && filterControl && !itemsExist && !loading; const headerMarkup = !showEmptyState && showHeader !== false && !showEmptySearchState && (showHeader || needsHeader) && listRef.current && ( <div className={styles.HeaderOuterWrapper}> <Sticky boundingElement={listRef.current}> {(isSticky: boolean) => { const headerClassName = classNames( styles.HeaderWrapper, sortOptions && sortOptions.length > 0 && !alternateTool && styles['HeaderWrapper-hasSort'], alternateTool && styles['HeaderWrapper-hasAlternateTool'], isSelectable && styles['HeaderWrapper-hasSelect'], loading && styles['HeaderWrapper-disabled'], isSelectable && selectMode && styles['HeaderWrapper-inSelectMode'], isSticky && styles['HeaderWrapper-isSticky'], ); return ( <div className={headerClassName}> <EventListener event="resize" handler={handleResize} /> {headerWrapperOverlay} <div className={styles.HeaderContentWrapper}> {headerTitleMarkup} {checkableButtonMarkup} {alternateToolMarkup} {sortingSelectMarkup} {selectButtonMarkup} </div> {bulkActionsMarkup} </div> ); }} </Sticky> </div> ); const emptySearchStateMarkup = showEmptySearchState ? emptySearchState || ( <div className={styles.EmptySearchResultWrapper}> <EmptySearchResult {...emptySearchResultText} withIllustration /> </div> ) : null; const emptyStateMarkup = showEmptyState ? emptyState : null; const defaultTopPadding = 8; const topPadding = loadingPosition > 0 ? loadingPosition : defaultTopPadding; const spinnerStyle = {paddingTop: `${topPadding}px`}; const spinnerSize = items.length < 2 ? 'small' : 'large'; const loadingOverlay = loading ? ( <> <li className={styles.SpinnerContainer} style={spinnerStyle}> <Spinner size={spinnerSize} accessibilityLabel="Items are loading" /> </li> <li className={styles.LoadingOverlay} /> </> ) : null; const className = classNames( styles.ItemWrapper, loading && styles['ItemWrapper-isLoading'], ); const loadingWithoutItemsMarkup = loading && !itemsExist ? ( <div className={className} tabIndex={-1}> {loadingOverlay} </div> ) : null; const resourceListClassName = classNames( styles.ResourceList, loading && styles.disabledPointerEvents, selectMode && styles.disableTextSelection, ); const listMarkup = itemsExist ? ( <ul className={resourceListClassName} ref={listRef} aria-live="polite" aria-busy={loading} > {loadingOverlay} {Children.toArray(items.map(renderItemWithId))} </ul> ) : null; // This is probably a legit error but I don't have the time to refactor this // eslint-disable-next-line react/jsx-no-constructed-context-values const context = { selectable: isSelectable, selectedItems, selectMode, resourceName, loading, onSelectionChange: handleSelectionChange, registerCheckableButtons: handleCheckableButtonRegistration, }; return ( <ResourceListContext.Provider value={context}> <div className={styles.ResourceListWrapper}> {filterControlMarkup} {headerMarkup} {listMarkup} {emptySearchStateMarkup} {emptyStateMarkup} {loadingWithoutItemsMarkup} </div> </ResourceListContext.Provider> ); }; ResourceList.Item = ResourceItem; export {FilterControl} from './components'; export type {FilterControlProps} from './components';
the_stack
import { AccessLevelList } from "../shared/access-level"; import { PolicyStatement, Operator } from "../shared"; /** * Statement provider for service [license-manager](https://docs.aws.amazon.com/service-authorization/latest/reference/list_awslicensemanager.html). * * @param sid [SID](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_sid.html) of the statement */ export class LicenseManager extends PolicyStatement { public servicePrefix = 'license-manager'; /** * Statement provider for service [license-manager](https://docs.aws.amazon.com/service-authorization/latest/reference/list_awslicensemanager.html). * * @param sid [SID](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_sid.html) of the statement */ constructor (sid?: string) { super(sid); } /** * Grants permission to accept a grant * * Access Level: Write * * https://docs.aws.amazon.com/license-manager/latest/APIReference/API_AcceptGrant.html */ public toAcceptGrant() { return this.to('AcceptGrant'); } /** * Grants permission to check in license entitlements back to pool * * Access Level: Write * * https://docs.aws.amazon.com/license-manager/latest/APIReference/API_CheckInLicense.html */ public toCheckInLicense() { return this.to('CheckInLicense'); } /** * Grants permission to check out license entitlements for borrow use case * * Access Level: Write * * https://docs.aws.amazon.com/license-manager/latest/APIReference/API_CheckoutBorrowLicense.html */ public toCheckoutBorrowLicense() { return this.to('CheckoutBorrowLicense'); } /** * Grants permission to check out license entitlements * * Access Level: Write * * https://docs.aws.amazon.com/license-manager/latest/APIReference/API_CheckoutLicense.html */ public toCheckoutLicense() { return this.to('CheckoutLicense'); } /** * Grants permission to create a new grant for license * * Access Level: Write * * https://docs.aws.amazon.com/license-manager/latest/APIReference/API_CreateGrant.html */ public toCreateGrant() { return this.to('CreateGrant'); } /** * Grants permission to create new version of grant * * Access Level: Write * * https://docs.aws.amazon.com/license-manager/latest/APIReference/API_CreateGrantVersion.html */ public toCreateGrantVersion() { return this.to('CreateGrantVersion'); } /** * Grants permission to create a new license * * Access Level: Write * * https://docs.aws.amazon.com/license-manager/latest/APIReference/API_CreateLicense.html */ public toCreateLicense() { return this.to('CreateLicense'); } /** * Grants permission to create a new license configuration * * Access Level: Write * * Possible conditions: * - .ifAwsRequestTag() * - .ifAwsTagKeys() * * https://docs.aws.amazon.com/license-manager/latest/APIReference/API_CreateLicenseConfiguration.html */ public toCreateLicenseConfiguration() { return this.to('CreateLicenseConfiguration'); } /** * Grants permission to create a license conversion task for a resource * * Access Level: Write * * https://docs.aws.amazon.com/license-manager/latest/APIReference/API_CreateLicenseConversionTaskForResource.html */ public toCreateLicenseConversionTaskForResource() { return this.to('CreateLicenseConversionTaskForResource'); } /** * Grants permission to create a report generator for a license configuration * * Access Level: Write * * https://docs.aws.amazon.com/license-manager/latest/APIReference/API_CreateLicenseManagerReportGenerator.html */ public toCreateLicenseManagerReportGenerator() { return this.to('CreateLicenseManagerReportGenerator'); } /** * Grants permission to create new version of license. * * Access Level: Write * * https://docs.aws.amazon.com/license-manager/latest/APIReference/API_CreateLicenseVersion.html */ public toCreateLicenseVersion() { return this.to('CreateLicenseVersion'); } /** * Grants permission to create a new token for license * * Access Level: Write * * https://docs.aws.amazon.com/license-manager/latest/APIReference/API_CreateToken.html */ public toCreateToken() { return this.to('CreateToken'); } /** * Deletes a grant * * Access Level: Write * * https://docs.aws.amazon.com/license-manager/latest/APIReference/API_DeleteGrant.html */ public toDeleteGrant() { return this.to('DeleteGrant'); } /** * Grants permission to delete a license * * Access Level: Write * * https://docs.aws.amazon.com/license-manager/latest/APIReference/API_DeleteLicense.html */ public toDeleteLicense() { return this.to('DeleteLicense'); } /** * Grants permission to permanently delete a license configuration * * Access Level: Write * * https://docs.aws.amazon.com/license-manager/latest/APIReference/API_DeleteLicenseConfiguration.html */ public toDeleteLicenseConfiguration() { return this.to('DeleteLicenseConfiguration'); } /** * Grants permission to delete a report generator * * Access Level: Write * * https://docs.aws.amazon.com/license-manager/latest/APIReference/API_DeleteLicenseManagerReportGenerator.html */ public toDeleteLicenseManagerReportGenerator() { return this.to('DeleteLicenseManagerReportGenerator'); } /** * Grants permission to delete token * * Access Level: Write * * https://docs.aws.amazon.com/license-manager/latest/APIReference/API_DeleteToken.html */ public toDeleteToken() { return this.to('DeleteToken'); } /** * Grants permission to extend consumption period of already checkout license entitlements * * Access Level: Write * * https://docs.aws.amazon.com/license-manager/latest/APIReference/API_ExtendLicenseConsumption.html */ public toExtendLicenseConsumption() { return this.to('ExtendLicenseConsumption'); } /** * Grants permission to get access token * * Access Level: Read * * https://docs.aws.amazon.com/license-manager/latest/APIReference/API_GetAccessToken.html */ public toGetAccessToken() { return this.to('GetAccessToken'); } /** * Grants permission to get a grant * * Access Level: Read * * https://docs.aws.amazon.com/license-manager/latest/APIReference/API_GetGrant.html */ public toGetGrant() { return this.to('GetGrant'); } /** * Grants permission to get a license * * Access Level: Read * * https://docs.aws.amazon.com/license-manager/latest/APIReference/API_GetLicense.html */ public toGetLicense() { return this.to('GetLicense'); } /** * Grants permission to get a license configuration * * Access Level: Read * * https://docs.aws.amazon.com/license-manager/latest/APIReference/API_GetLicenseConfiguration.html */ public toGetLicenseConfiguration() { return this.to('GetLicenseConfiguration'); } /** * Grants permission to retrieve a license conversion task * * Access Level: Read * * https://docs.aws.amazon.com/license-manager/latest/APIReference/API_GetLicenseConversionTask.html */ public toGetLicenseConversionTask() { return this.to('GetLicenseConversionTask'); } /** * Grants permission to get a report generator * * Access Level: Read * * https://docs.aws.amazon.com/license-manager/latest/APIReference/API_GetLicenseManagerReportGenerator.html */ public toGetLicenseManagerReportGenerator() { return this.to('GetLicenseManagerReportGenerator'); } /** * Grants permission to get a license usage * * Access Level: Read * * https://docs.aws.amazon.com/license-manager/latest/APIReference/API_GetLicenseUsage.html */ public toGetLicenseUsage() { return this.to('GetLicenseUsage'); } /** * Grants permission to get service settings * * Access Level: List * * https://docs.aws.amazon.com/license-manager/latest/APIReference/API_GetServiceSettings.html */ public toGetServiceSettings() { return this.to('GetServiceSettings'); } /** * Grants permission to list associations for a selected license configuration * * Access Level: List * * https://docs.aws.amazon.com/license-manager/latest/APIReference/API_ListAssociationsForLicenseConfiguration.html */ public toListAssociationsForLicenseConfiguration() { return this.to('ListAssociationsForLicenseConfiguration'); } /** * Grants permission to list distributed grants * * Access Level: List * * https://docs.aws.amazon.com/license-manager/latest/APIReference/API_ListDistributedGrants.html */ public toListDistributedGrants() { return this.to('ListDistributedGrants'); } /** * Grants permission to list the license configuration operations that failed * * Access Level: List * * https://docs.aws.amazon.com/license-manager/latest/APIReference/API_ListFailuresForLicenseConfigurationOperations.html */ public toListFailuresForLicenseConfigurationOperations() { return this.to('ListFailuresForLicenseConfigurationOperations'); } /** * Grants permission to list license configurations * * Access Level: Read * * https://docs.aws.amazon.com/license-manager/latest/APIReference/API_ListLicenseConfigurations.html */ public toListLicenseConfigurations() { return this.to('ListLicenseConfigurations'); } /** * Grants permission to list license conversion tasks * * Access Level: List * * https://docs.aws.amazon.com/license-manager/latest/APIReference/API_ListLicenseConversionTasks.html */ public toListLicenseConversionTasks() { return this.to('ListLicenseConversionTasks'); } /** * Grants permission to list report generators * * Access Level: List * * https://docs.aws.amazon.com/license-manager/latest/APIReference/API_ListLicenseManagerReportGenerators.html */ public toListLicenseManagerReportGenerators() { return this.to('ListLicenseManagerReportGenerators'); } /** * Grants permission to list license specifications associated with a selected resource * * Access Level: List * * https://docs.aws.amazon.com/license-manager/latest/APIReference/API_ListLicenseSpecificationsForResource.html */ public toListLicenseSpecificationsForResource() { return this.to('ListLicenseSpecificationsForResource'); } /** * Grants permission to list license versions * * Access Level: List * * https://docs.aws.amazon.com/license-manager/latest/APIReference/API_ListLicenseVersions.html */ public toListLicenseVersions() { return this.to('ListLicenseVersions'); } /** * Grants permission to list licenses * * Access Level: Read * * https://docs.aws.amazon.com/license-manager/latest/APIReference/API_ListLicenses.html */ public toListLicenses() { return this.to('ListLicenses'); } /** * Grants permission to list received grants * * Access Level: List * * https://docs.aws.amazon.com/license-manager/latest/APIReference/API_ListReceivedGrants.html */ public toListReceivedGrants() { return this.to('ListReceivedGrants'); } /** * Grants permission to list received licenses * * Access Level: List * * https://docs.aws.amazon.com/license-manager/latest/APIReference/API_ListReceivedLicenses.html */ public toListReceivedLicenses() { return this.to('ListReceivedLicenses'); } /** * Grants permission to list resource inventory * * Access Level: List * * https://docs.aws.amazon.com/license-manager/latest/APIReference/API_ListResourceInventory.html */ public toListResourceInventory() { return this.to('ListResourceInventory'); } /** * Grants permission to list tags for a selected resource * * Access Level: Read * * https://docs.aws.amazon.com/license-manager/latest/APIReference/API_ListTagsForResource.html */ public toListTagsForResource() { return this.to('ListTagsForResource'); } /** * Grants permission to list tokens * * Access Level: List * * https://docs.aws.amazon.com/license-manager/latest/APIReference/API_ListTokens.html */ public toListTokens() { return this.to('ListTokens'); } /** * Grants permission to list usage records for selected license configuration * * Access Level: List * * https://docs.aws.amazon.com/license-manager/latest/APIReference/API_ListUsageForLicenseConfiguration.html */ public toListUsageForLicenseConfiguration() { return this.to('ListUsageForLicenseConfiguration'); } /** * Grants permission to reject a grant * * Access Level: Write * * https://docs.aws.amazon.com/license-manager/latest/APIReference/API_RejectGrant.html */ public toRejectGrant() { return this.to('RejectGrant'); } /** * Grants permission to tag a selected resource * * Access Level: Tagging * * Possible conditions: * - .ifAwsRequestTag() * - .ifAwsTagKeys() * * https://docs.aws.amazon.com/license-manager/latest/APIReference/API_TagResource.html */ public toTagResource() { return this.to('TagResource'); } /** * Grants permission to untag a selected resource * * Access Level: Tagging * * https://docs.aws.amazon.com/license-manager/latest/APIReference/API_UntagResource.html */ public toUntagResource() { return this.to('UntagResource'); } /** * Grants permission to update an existing license configuration * * Access Level: Write * * https://docs.aws.amazon.com/license-manager/latest/APIReference/API_UpdateLicenseConfiguration.html */ public toUpdateLicenseConfiguration() { return this.to('UpdateLicenseConfiguration'); } /** * Grants permission to update a report generator for a license configuration * * Access Level: Write * * https://docs.aws.amazon.com/license-manager/latest/APIReference/API_UpdateLicenseManagerReportGenerator.html */ public toUpdateLicenseManagerReportGenerator() { return this.to('UpdateLicenseManagerReportGenerator'); } /** * Grants permission to updates license specifications for a selected resource * * Access Level: Write * * https://docs.aws.amazon.com/license-manager/latest/APIReference/API_UpdateLicenseSpecificationsForResource.html */ public toUpdateLicenseSpecificationsForResource() { return this.to('UpdateLicenseSpecificationsForResource'); } /** * Grants permission to updates service settings * * Access Level: Permissions management * * https://docs.aws.amazon.com/license-manager/latest/APIReference/API_UpdateServiceSettings.html */ public toUpdateServiceSettings() { return this.to('UpdateServiceSettings'); } protected accessLevelList: AccessLevelList = { "Write": [ "AcceptGrant", "CheckInLicense", "CheckoutBorrowLicense", "CheckoutLicense", "CreateGrant", "CreateGrantVersion", "CreateLicense", "CreateLicenseConfiguration", "CreateLicenseConversionTaskForResource", "CreateLicenseManagerReportGenerator", "CreateLicenseVersion", "CreateToken", "DeleteGrant", "DeleteLicense", "DeleteLicenseConfiguration", "DeleteLicenseManagerReportGenerator", "DeleteToken", "ExtendLicenseConsumption", "RejectGrant", "UpdateLicenseConfiguration", "UpdateLicenseManagerReportGenerator", "UpdateLicenseSpecificationsForResource" ], "Read": [ "GetAccessToken", "GetGrant", "GetLicense", "GetLicenseConfiguration", "GetLicenseConversionTask", "GetLicenseManagerReportGenerator", "GetLicenseUsage", "ListLicenseConfigurations", "ListLicenses", "ListTagsForResource" ], "List": [ "GetServiceSettings", "ListAssociationsForLicenseConfiguration", "ListDistributedGrants", "ListFailuresForLicenseConfigurationOperations", "ListLicenseConversionTasks", "ListLicenseManagerReportGenerators", "ListLicenseSpecificationsForResource", "ListLicenseVersions", "ListReceivedGrants", "ListReceivedLicenses", "ListResourceInventory", "ListTokens", "ListUsageForLicenseConfiguration" ], "Tagging": [ "TagResource", "UntagResource" ], "Permissions management": [ "UpdateServiceSettings" ] }; /** * Adds a resource of type license-configuration to the statement * * https://docs.aws.amazon.com/license-manager/latest/userguide/license-configurations.html * * @param licenseConfigurationId - Identifier for the licenseConfigurationId. * @param account - Account of the resource; defaults to empty string: all accounts. * @param region - Region of the resource; defaults to empty string: all regions. * @param partition - Partition of the AWS account [aws, aws-cn, aws-us-gov]; defaults to `aws`. * * Possible conditions: * - .ifResourceTag() */ public onLicenseConfiguration(licenseConfigurationId: string, account?: string, region?: string, partition?: string) { var arn = 'arn:${Partition}:license-manager:${Region}:${Account}:license-configuration:${LicenseConfigurationId}'; arn = arn.replace('${LicenseConfigurationId}', licenseConfigurationId); arn = arn.replace('${Account}', account || '*'); arn = arn.replace('${Region}', region || '*'); arn = arn.replace('${Partition}', partition || 'aws'); return this.on(arn); } /** * Adds a resource of type license to the statement * * https://docs.aws.amazon.com/license-manager/latest/userguide/seller-issued-licenses.html * * @param licenseId - Identifier for the licenseId. * @param account - Account of the resource; defaults to empty string: all accounts. * @param partition - Partition of the AWS account [aws, aws-cn, aws-us-gov]; defaults to `aws`. */ public onLicense(licenseId: string, account?: string, partition?: string) { var arn = 'arn:${Partition}:license-manager::${Account}:license:${LicenseId}'; arn = arn.replace('${LicenseId}', licenseId); arn = arn.replace('${Account}', account || '*'); arn = arn.replace('${Partition}', partition || 'aws'); return this.on(arn); } /** * Adds a resource of type grant to the statement * * https://docs.aws.amazon.com/license-manager/latest/userguide/granted-licenses.html * * @param grantId - Identifier for the grantId. * @param account - Account of the resource; defaults to empty string: all accounts. * @param partition - Partition of the AWS account [aws, aws-cn, aws-us-gov]; defaults to `aws`. */ public onGrant(grantId: string, account?: string, partition?: string) { var arn = 'arn:${Partition}:license-manager::${Account}:grant:${GrantId}'; arn = arn.replace('${GrantId}', grantId); arn = arn.replace('${Account}', account || '*'); arn = arn.replace('${Partition}', partition || 'aws'); return this.on(arn); } /** * Adds a resource of type report-generator to the statement * * https://docs.aws.amazon.com/license-manager/latest/userguide/report-generators.html * * @param reportGeneratorId - Identifier for the reportGeneratorId. * @param account - Account of the resource; defaults to empty string: all accounts. * @param region - Region of the resource; defaults to empty string: all regions. * @param partition - Partition of the AWS account [aws, aws-cn, aws-us-gov]; defaults to `aws`. * * Possible conditions: * - .ifResourceTag() */ public onReportGenerator(reportGeneratorId: string, account?: string, region?: string, partition?: string) { var arn = 'arn:${Partition}:license-manager:${Region}:${Account}:report-generator:${ReportGeneratorId}'; arn = arn.replace('${ReportGeneratorId}', reportGeneratorId); arn = arn.replace('${Account}', account || '*'); arn = arn.replace('${Region}', region || '*'); arn = arn.replace('${Partition}', partition || 'aws'); return this.on(arn); } /** * Filters access based on tag key-value pairs attached to the resource * * https://docs.aws.amazon.com/license-manager/latest/userguide/identity-access-management.html * * Applies to resource types: * - license-configuration * - report-generator * * @param tagKey The tag key to check * @param value The value(s) to check * @param operator Works with [string operators](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_condition_operators.html#Conditions_String). **Default:** `StringLike` */ public ifResourceTag(tagKey: string, value: string | string[], operator?: Operator | string) { return this.if(`ResourceTag/${ tagKey }`, value, operator || 'StringLike'); } }
the_stack
import { CloudflareApiError, listScripts, listTails, Tail, setEqual, setIntersect, setSubtract, isTailMessageCronEvent, parseHeaderFilter, TailFilter, TailMessage, TailOptions, ErrorInfo, UnparsedMessage, formatLocalYyyyMmDdHhMmSs, AdditionalLog, generateUuid, dumpMessagePretty, parseLogProps, HeaderFilter } from './deps_app.ts'; import { AppConstants } from './app_constants.ts'; import { DemoMode } from './demo_mode.ts'; import { QpsController } from './qps_controller.ts'; import { SwitchableTailControllerCallbacks, TailController, TailControllerCallbacks, TailKey, unpackTailKey } from './tail_controller.ts'; import { CfGqlClient } from '../../common/analytics/cfgql_client.ts'; import { computeDurableObjectsCostsTable, DurableObjectsCostsTable } from '../../common/analytics/durable_objects_costs.ts'; // deno-lint-ignore no-explicit-any export type ConsoleLogger = (...data: any[]) => void; export class WebtailAppVM { private _profiles: TextItem[] = []; get profiles(): TextItem[] { return this.demoMode ? DemoMode.profiles : this._profiles; } get realProfiles(): TextItem[] { return this._profiles; } private _selectedProfileId: string | undefined; get selectedProfileId(): string | undefined { return this.demoMode ? DemoMode.selectedProfileId : this._selectedProfileId; } set selectedProfileId(value: string | undefined) { if (this.demoMode) { DemoMode.setSelectedProfileId(value); return; } if (this._selectedProfileId === value) return; this._selectedProfileId = value; this.onChange(); this.state.selectedProfileId = value; saveState(this.state); this.findScripts(); } private _analytics: TextItem[] = [{ id: 'durable-objects', text: 'Durable Objects', description: 'Daily metrics and associated costs' }]; get analytics(): TextItem[] { return this._analytics; } private _selectedAnalyticId: string | undefined; get selectedAnalyticId(): string | undefined { return this._selectedAnalyticId; } analyticsState: AnalyticsState = { querying: false }; private _scripts: TextItem[] = []; get scripts(): TextItem[] { return this.demoMode ? DemoMode.scripts : this._scripts; } private _selectedScriptIds: ReadonlySet<string> = new Set<string>(); get selectedScriptIds(): ReadonlySet<string> { return this.demoMode ? DemoMode.selectedScriptIds : this._selectedScriptIds; } set selectedScriptIds(scriptIds: ReadonlySet<string>) { if (this._selectedAnalyticId !== undefined) { this._selectedAnalyticId = undefined; this.onChange(); } if (this.demoMode) { DemoMode.setSelectedScriptIds(scriptIds); return; } if (setEqual(this._selectedScriptIds, scriptIds)) return; this._selectedScriptIds = new Set(scriptIds); this.onChange(); const profile = this.selectedProfileId && this.state.profiles[this.selectedProfileId]; if (profile) { profile.selectedScriptIds = [...scriptIds]; saveState(this.state); } this.setTails(); } profileForm = new ProfileFormVM(); filterForm = new FilterFormVM(); filter: FilterState = {}; extraFields: string[] = []; private _tails: ReadonlySet<TailKey> = new Set(); get tails(): ReadonlySet<TailKey> { return this.demoMode ? DemoMode.tails : this._tails; } set tails(tails: ReadonlySet<TailKey>) { if (this.demoMode) DemoMode.tails = tails; this._tails = tails; } welcomeShowing = false; aboutShowing = false; // private readonly state = loadState(); private readonly tailController: TailController; private readonly tailControllerCallbacks: TailControllerCallbacks; private readonly qpsController: QpsController; private demoMode = false; onChange: () => void = () => {}; logger: ConsoleLogger = () => {}; onResetOutput: () => void = () => {}; onQpsChange: (qps: number) => void = () => {}; constructor() { // deno-lint-ignore no-this-alias const dis = this; this.qpsController = new QpsController(20, { onQpsChanged(qps: number) { if (dis.demoMode) return; dis.onQpsChange(qps); } }); const logTailsChange = (action: string, tailKeys: ReadonlySet<TailKey>) => { if (tailKeys.size > 0) this.logWithPrefix(`${action} ${[...tailKeys].map(v => unpackTailKey(v).scriptId).sort().join(', ')}`); }; const logWithPrefix = this.logWithPrefix.bind(this); const verboseWithPrefix = this.verboseWithPrefix.bind(this); const callbacks: TailControllerCallbacks = { onTailCreating(_accountId: string, scriptId: string) { verboseWithPrefix(`Creating tail for ${scriptId}...`); }, onTailCreated(_accountId: string, scriptId: string, tookMillis: number, tail: Tail) { verboseWithPrefix(`Created tail for ${scriptId} in ${tookMillis}ms, ${JSON.stringify(tail)}`); }, onTailConnectionOpen(_accountId: string, scriptId: string, _timeStamp: number, tookMillis: number) { verboseWithPrefix(`Opened tail for ${scriptId} in ${tookMillis}ms`); }, onTailConnectionClose(accountId: string, scriptId: string, timeStamp: number, code: number, reason: string, wasClean: boolean) { console.log('onTailConnectionClose', { accountId, scriptId, timeStamp, code, reason, wasClean }); verboseWithPrefix(`Closed tail for ${scriptId}, ${JSON.stringify({code, reason, wasClean })}`); }, onTailConnectionError(accountId: string, scriptId: string, timeStamp: number, errorInfo?: ErrorInfo) { console.log('onTailConnectionError', { accountId, scriptId, timeStamp, errorInfo }); logWithPrefix(`Error in tail for ${scriptId}`, { errorInfo }); }, onTailConnectionMessage(_accountId: string, _scriptId: string, _timeStamp: number, message: TailMessage) { if (computeMessagePassesFilter(message, dis.filter)) { dumpMessagePretty(message, dis.logger, dis.computeAdditionalLogs(message)); } if (dis.demoMode) return; dis.qpsController.addEvent(message.eventTimestamp); }, onTailConnectionUnparsedMessage(_accountId: string, scriptId: string, _timeStamp: number, message: UnparsedMessage, parseError: Error) { console.log(message); logWithPrefix(`Unparsed message in tail for ${scriptId}`, parseError.stack || parseError.message); }, onTailsChanged(tails: ReadonlySet<TailKey>) { if (setEqual(dis.tails, tails)) return; // dis.logger('onTailsChanged', [...tails].map(v => unpackTailKey(v).scriptId)); const removed = setSubtract(dis.tails, tails); logTailsChange('Untailing', removed); const added = setSubtract(tails, dis.tails); logTailsChange('Tailing', added); dis.tails = tails; dis.onChange(); }, onNetworkStatusChanged(online: boolean) { if (online) { logWithPrefix('%cONLINE%c', 'color: green'); } else { logWithPrefix('%cOFFLINE%c', 'color: red'); } }, onTailFailedToStart(_accountId: string, scriptId: string, trigger: string, error: Error) { verboseWithPrefix(`Tail for ${scriptId} failed to start (${trigger}): ${error.name} ${error.message}`); }, }; const websocketPingIntervalSeconds = AppConstants.WEBSOCKET_PING_INTERVAL_SECONDS; const inactiveTailSeconds = AppConstants.INACTIVE_TAIL_SECONDS; this.tailController = new TailController(new SwitchableTailControllerCallbacks(callbacks, () => !this.demoMode), { websocketPingIntervalSeconds, inactiveTailSeconds }); this.tailControllerCallbacks = callbacks; this.extraFields = [...(this.state.extraFields || [])]; this.filter = this.state.filter || {}; this.applyFilter({ save: false }); } start() { this.reloadProfiles(); this.recomputeWelcomeShowing(); this.performInitialSelection(); } newProfile() { if (this.demoMode) { if (this.welcomeShowing) { // keep going } else { return; } } this.profileForm.profileId = generateUuid(); this.profileForm.showing = true; this.profileForm.title = 'New Profile'; this.profileForm.name = this._profiles.length === 0 ? 'default' : `profile${this._profiles.length + 1}`; this.profileForm.accountId = ''; this.profileForm.apiToken = ''; this.profileForm.deleteVisible = false; this.profileForm.enabled = true; this.profileForm.outputMessage = ''; this.profileForm.computeSaveEnabled(); this.onChange(); } editProfile(profileId: string) { if (this.demoMode) return; const profile = this.state.profiles[profileId]; if (!profile) throw new Error(`Profile ${profileId} not found`); this._selectedProfileId = profileId; const { name, accountId, apiToken } = profile; this.profileForm.profileId = profileId; this.profileForm.showing = true; this.profileForm.title = 'Edit Profile'; this.profileForm.name = name; this.profileForm.accountId = accountId; this.profileForm.apiToken = apiToken; this.profileForm.deleteVisible = true; this.profileForm.enabled = true; this.profileForm.outputMessage = ''; this.profileForm.computeSaveEnabled(); this.onChange(); } deleteProfile(profileId: string) { console.log('delete profile', profileId); const profile = this.state.profiles[profileId]; if (!profile) throw new Error(`Profile ${profileId} not found`); delete this.state.profiles[profileId]; saveState(this.state); this.profileForm.showing = false; this.reloadProfiles(); this.recomputeWelcomeShowing(); this.performInitialSelection(); } cancelProfile() { this.profileForm.showing = false; this.onChange(); } setProfileName(name: string) { this.profileForm.name = name; this.profileForm.computeSaveEnabled(); this.onChange(); } setProfileAccountId(accountId: string) { this.profileForm.accountId = accountId; this.profileForm.computeSaveEnabled(); this.onChange(); } setProfileApiToken(apiToken: string) { this.profileForm.apiToken = apiToken; this.profileForm.computeSaveEnabled(); this.onChange(); } saveProfile() { const { profileForm } = this; const { profileId } = profileForm; const newProfile: ProfileState = { name: profileForm.name.trim(), accountId: profileForm.accountId.trim(), apiToken: profileForm.apiToken.trim(), }; this.trySaveProfile(profileId, newProfile); } editEventFilter() { if (this.demoMode) return; const { filter, filterForm } = this; filterForm.showing = true; filterForm.enabled = true; filterForm.fieldName = 'Event type:'; filterForm.fieldValueChoices = [ { id: 'all', text: 'All' }, { id: 'cron', text: 'CRON trigger' }, { id: 'http', text: 'HTTP request' }, ]; filterForm.fieldValueOptions = []; filterForm.fieldValue = filter.event1 === 'http' ? 'http' : filter.event1 === 'cron' ? 'cron' : 'all'; filterForm.helpText = 'Choose which types of events to show'; filterForm.applyValue = () => { if (filter.event1 === filterForm.fieldValue) return; filter.event1 = filterForm.fieldValue; this.applyFilter({ save: true }); const selectedChoiceText = filterForm.fieldValueChoices.find(v => v.id === filterForm.fieldValue)!.text; this.logWithPrefix(`Event type filter changed to: ${selectedChoiceText}`) }; this.onChange(); } editStatusFilter() { if (this.demoMode) return; const { filter, filterForm } = this; filterForm.showing = true; filterForm.enabled = true; filterForm.fieldName = 'Status:'; filterForm.fieldValueChoices = [ { id: 'all', text: 'All' }, { id: 'success', text: 'Success' }, { id: 'error', text: 'Error' }, ]; filterForm.fieldValueOptions = []; filterForm.fieldValue = filter.status1 === 'success' ? 'success' : filter.status1 === 'error' ? 'error' : 'all'; filterForm.helpText = 'Show events this this status'; filterForm.applyValue = () => { if (filter.status1 === filterForm.fieldValue) return; filter.status1 = filterForm.fieldValue; this.applyFilter({ save: true }); const selectedChoiceText = filterForm.fieldValueChoices.find(v => v.id === filterForm.fieldValue)!.text; this.logWithPrefix(`Status filter changed to: ${selectedChoiceText}`) }; this.onChange(); } editIpAddressFilter() { if (this.demoMode) return; const { filter, filterForm } = this; const isValidIpAddress = (ipAddress: string) => { return /^(self|[\d\.:a-f]{3,})$/.test(ipAddress); // 2001:db8:3:4::192.0.2.33, doesn't need to be comprehensive }; const checkValidIpAddress = (ipAddress: string) => { if (!isValidIpAddress(ipAddress)) throw new Error(`Bad ip address: ${ipAddress}`); return ipAddress; }; const parseFilterIpAddressesFromFieldValue = () => { const { fieldValue } = filterForm; const v = (fieldValue || '').trim(); if (v === '') return []; return distinct(v.split(',').map(v => v.trim().toLowerCase()).filter(v => v !== '').map(checkValidIpAddress)); }; const computeFieldValueFromFilterIpAddresses = () => { return distinct(filter.ipAddress1 || []).join(', '); }; filterForm.showing = true; filterForm.enabled = true; filterForm.fieldName = 'IP address(s):'; filterForm.fieldValueChoices = []; filterForm.fieldValueOptions = []; filterForm.fieldValue = computeFieldValueFromFilterIpAddresses(); filterForm.helpText = `'self' to filter your own address, comma-separated if multiple, e.g. self, 1.1.1.1`; filterForm.applyValue = () => { const newValue = parseFilterIpAddressesFromFieldValue(); if (setEqual(new Set(filter.ipAddress1 || []), new Set(newValue))) return; filter.ipAddress1 = newValue; this.applyFilter({ save: true }); const text = newValue.length === 0 ? 'any IP address' : newValue.join(', '); this.logWithPrefix(`IP address filter changed to: ${text}`); }; this.onChange(); } editMethodFilter() { if (this.demoMode) return; const { filter, filterForm } = this; const parseFilterMethodsFromFieldValue = () => { const { fieldValue } = filterForm; const v = (fieldValue || '').trim(); if (v === '') return []; return distinct(v.split(',').map(v => v.trim().toUpperCase()).filter(v => v !== '')); }; const computeFieldValueFromFilterMethods = () => { return distinct(filter.method1 || []).map(v => v.toUpperCase()).join(', '); }; filterForm.showing = true; filterForm.enabled = true; filterForm.fieldName = 'HTTP Method(s):'; filterForm.fieldValueChoices = []; filterForm.fieldValueOptions = []; filterForm.fieldValue = computeFieldValueFromFilterMethods(); filterForm.helpText = 'comma-separated if multiple, e.g. GET, POST'; filterForm.applyValue = () => { const newValue = parseFilterMethodsFromFieldValue(); if (setEqual(new Set(filter.method1 || []), new Set(newValue))) return; filter.method1 = newValue; this.applyFilter({ save: true }); const text = newValue.length === 0 ? 'any method' : newValue.join(', '); this.logWithPrefix(`Method filter changed to: ${text}`); }; this.onChange(); } editSamplingRateFilter() { if (this.demoMode) return; const parseSampleRateFromFieldValue = () => { const { fieldValue } = filterForm; const v = (fieldValue || '').trim(); if (v === '') return 1; const num = parseFloat(v); if (!isValidSamplingRate(num)) throw new Error(`Invalid rate: ${v}`); return num; }; const { filter, filterForm } = this; filterForm.showing = true; filterForm.enabled = true; filterForm.fieldName = 'Sampling rate:'; filterForm.fieldValueChoices = []; filterForm.fieldValueOptions = []; filterForm.fieldValue = (typeof filter.samplingRate1 === 'number' && isValidSamplingRate(filter.samplingRate1) ? filter.samplingRate1 : 1).toFixed(2); filterForm.helpText = 'Can range from 0 (0%) to 1 (100%)'; filterForm.applyValue = () => { const newValue = parseSampleRateFromFieldValue(); if (filter.samplingRate1 === newValue) return; filter.samplingRate1 = newValue; this.applyFilter({ save: true }); const text = newValue === 1 ? 'no sampling' : `${newValue} (${(newValue * 100).toFixed(2)}%)`; this.logWithPrefix(`Sample rate filter changed to: ${text}`); }; this.onChange(); } editSearchFilter() { if (this.demoMode) return; const { filter, filterForm } = this; filterForm.showing = true; filterForm.enabled = true; filterForm.fieldName = 'Search text:'; filterForm.fieldValueChoices = []; filterForm.fieldValueOptions = []; filterForm.fieldValue = filter.search1 || ''; filterForm.helpText = 'Filter by a text match in console.log messages'; filterForm.applyValue = () => { if (filter.search1 === filterForm.fieldValue) return; filter.search1 = filterForm.fieldValue; this.applyFilter({ save: true }); const text = (filter.search1 || '').length === 0 ? 'no search filter' : `'${filter.search1}'`; this.logWithPrefix(`Search filter changed to: ${text}`); }; this.onChange(); } editHeaderFilter() { if (this.demoMode) return; const { filter, filterForm } = this; const parseFilterHeadersFromFieldValue = () => { const { fieldValue } = filterForm; const v = (fieldValue || '').trim(); if (v === '') return []; return distinct(v.split(',').map(v => v.trim()).filter(v => v !== '')); }; const computeFieldValueFromFilterHeaders = () => { return distinct(filter.header1 || []).join(', '); }; filterForm.showing = true; filterForm.enabled = true; filterForm.fieldName = 'Header(s):'; filterForm.fieldValueChoices = []; filterForm.fieldValueOptions = []; filterForm.fieldValue = computeFieldValueFromFilterHeaders(); filterForm.helpText = `'key', or 'key:query', comma-separated if multiple`; filterForm.applyValue = () => { const newValue = parseFilterHeadersFromFieldValue(); if (setEqual(new Set(filter.header1 || []), new Set(newValue))) return; filter.header1 = newValue; this.applyFilter({ save: true }); const text = newValue.length === 0 ? 'no header filter' : newValue.join(', '); this.logWithPrefix(`Header filter changed to: ${text}`); }; this.onChange(); } editLogpropFilter() { if (this.demoMode) return; const { filter, filterForm } = this; const parseLogpropFiltersFromFieldValue = () => { const { fieldValue } = filterForm; const v = (fieldValue || '').trim(); if (v === '') return []; return distinct(v.split(',').map(v => v.trim()).filter(v => v !== '')); }; const computeFieldValueFromLogPropFilters = () => { return distinct(filter.logprop1 || []).join(', '); }; filterForm.showing = true; filterForm.enabled = true; filterForm.fieldName = 'Logprop(s):'; filterForm.fieldValueChoices = []; filterForm.fieldValueOptions = []; filterForm.fieldValue = computeFieldValueFromLogPropFilters(); filterForm.helpText = `'key', or 'key:value', comma-separated if multiple, value may include *`; filterForm.applyValue = () => { const newValue = parseLogpropFiltersFromFieldValue(); this.setLogpropFilter(newValue); }; this.onChange(); } setLogpropFilter(logpropFilters: string[]) { const { filter } = this; if (setEqual(new Set(filter.logprop1 || []), new Set(logpropFilters))) return; filter.logprop1 = logpropFilters; this.applyFilter({ save: true }); const text = logpropFilters.length === 0 ? 'no logprop filter' : logpropFilters.join(', '); this.logWithPrefix(`Logprop filter changed to: ${text}`); } hasAnyFilters(): boolean { const { filter } = this; const { event1 } = filter; return computeTailOptionsForFilter(filter).filters.length > 0 || typeof event1 === 'string' && event1 !== '' && event1 !== 'all'; } resetFilters() { if (this.demoMode) return; this.filter = {}; this.applyFilter({ save: true }); this.logWithPrefix(`Filters reset`); this.onChange(); } cancelFilter() { console.log('cancelFilter'); this.filterForm.showing = false; this.onChange(); } saveFilter() { console.log('saveFilter'); const { filterForm } = this; filterForm.enabled = false; filterForm.outputMessage = 'Checking filter...'; this.onChange(); try { filterForm.applyValue(); filterForm.outputMessage = ``; filterForm.showing = false; } catch (e) { filterForm.outputMessage = `Error: ${e.message}`; } finally { filterForm.enabled = true; this.onChange(); } } selectFilterChoice(id: string) { if (this.filterForm.fieldValue === id) return; this.filterForm.fieldValue = id; this.onChange(); } editSelectionFields() { if (this.demoMode) return; const { filterForm } = this; filterForm.showing = true; filterForm.enabled = true; filterForm.fieldName = 'Additional fields:'; filterForm.fieldValueChoices = []; filterForm.fieldValueOptions = EXTRA_FIELDS_OPTIONS; filterForm.fieldValue = (this.extraFields || []).join(','); filterForm.helpText = 'Select additional fields to show in the output'; filterForm.applyValue = () => { const newValues = distinct((filterForm.fieldValue || '').split(',').map(v => v.trim()).filter(v => v !== '')); if (setEqual(new Set(this.extraFields || []), new Set(newValues))) return; this.extraFields = newValues; this.applyFilter({ save: true}); const extraFieldsText = this.computeSelectionFieldsText(); this.logWithPrefix(`Output fields changed to: ${extraFieldsText}`) }; this.onChange(); } computeSelectionFieldsText(): string { return ['standard fields', ...this.extraFields.map(id => EXTRA_FIELDS_OPTIONS.find(v => v.id === id)?.text || id)].join(', '); } toggleFilterOption(id: string) { const extraFields = distinct((this.filterForm.fieldValue || '').split(',').map(v => v.trim()).filter(v => v !== '')); const i = extraFields.indexOf(id); if (i >= 0) { extraFields.splice(i, 1); } else { extraFields.push(id); } const fieldValue = extraFields.join(','); if (this.filterForm.fieldValue === fieldValue) return; this.filterForm.fieldValue = fieldValue; this.onChange(); } toggleDemoMode() { this.setDemoMode(!this.demoMode); this.onChange(); } resetOutput() { if (this.demoMode) return; this.onResetOutput(); } showAbout() { if (this.demoMode) return; this.aboutShowing = true; this.onChange(); } closeAbout() { this.aboutShowing = false; this.onChange(); } showAnalytic(analyticId: string) { const analytic = this.analytics.find(v => v.id === analyticId); if (!analytic || analytic.id === this._selectedAnalyticId) return; if (this.selectedProfileId === undefined) return; const profile = this.state.profiles[this.selectedProfileId]; if (profile === undefined) return; const { accountId, apiToken } = profile; this._selectedAnalyticId = analyticId; this.analyticsState.querying = true; this.analyticsState.durableObjectsCosts = undefined; this.analyticsState.error = undefined; this.onChange(); const client = new CfGqlClient({ accountId, apiToken }); this.queryDurableObjectsCosts(client); } // private setDemoMode(demoMode: boolean) { if (this.demoMode === demoMode) return; this.demoMode = demoMode; if (demoMode) { console.log('Enable demo mode'); this.onQpsChange(12.34); this.onResetOutput(); DemoMode.logFakeOutput(this.tailControllerCallbacks); } else { console.log('Disable demo mode'); this.onQpsChange(this.qpsController.qps); this.onResetOutput(); } } private applyFilter(opts: { save: boolean }) { const { save } = opts; this.state.filter = this.filter; this.state.extraFields = this.extraFields; if (save) saveState(this.state); const tailOptions = computeTailOptionsForFilter(this.filter); this.tailController.setTailOptions(tailOptions); } // deno-lint-ignore no-explicit-any private logWithPrefix(...data: any) { const time = formatLocalYyyyMmDdHhMmSs(new Date()); if (data.length > 0 && typeof data[0] === 'string') { data = [`[%c${time}%c] ${data[0]}`, 'color: gray', '', ...data.slice(1)]; } this.logger(...data); } private verboseWithPrefix(message: string) { const time = formatLocalYyyyMmDdHhMmSs(new Date()); this.logger(`[%c${time}%c] %c${message}%c`, 'color: gray', '', 'color: gray'); } private performInitialSelection() { const initiallySelectedProfileId = computeInitiallySelectedProfileId(this.state, this._profiles); if (initiallySelectedProfileId) { console.log(`Initially selecting profile: ${this.state.profiles[initiallySelectedProfileId].name}`); this.selectedProfileId = initiallySelectedProfileId; } else { this.onChange(); } } private async trySaveProfile(profileId: string, profile: ProfileState) { const { profileForm } = this; profileForm.enabled = false; profileForm.progressVisible = true; profileForm.outputMessage = 'Checking profile...'; this.onChange(); try { const canListTails = await computeCanListTails(profile.accountId, profile.apiToken); if (canListTails) { this.state.profiles[profileId] = profile; saveState(this.state); profileForm.outputMessage = ''; this.reloadProfiles(); this.recomputeWelcomeShowing(); profileForm.showing = false; this.selectedProfileId = profileId; } else { profileForm.outputMessage = `These credentials do not have permission to tail`; } } catch (e) { profileForm.outputMessage = `Error: ${e.message}`; } finally { profileForm.progressVisible = false; profileForm.enabled = true; this.onChange(); } } private reloadProfiles() { const { state } = this; this._profiles.splice(0); for (const [profileId, profile] of Object.entries(state.profiles)) { const name = profile.name || '(unnamed)'; this._profiles.push({ id: profileId, text: name }); } } private async findScripts() { try { if (this.selectedProfileId === undefined) return; const profile = this.state.profiles[this.selectedProfileId]; if (profile === undefined) return; const { accountId, apiToken } = profile; this.verboseWithPrefix(`Finding scripts for ${profile.name.toUpperCase()}...`); const start = Date.now(); const scripts = await listScripts(accountId, apiToken); if (!this.demoMode) this.verboseWithPrefix(`Found ${scripts.length} scripts in ${Date.now() - start}ms`); this._scripts.splice(0); for (const script of scripts) { // this.logger(`Found script ${script.id}`); this._scripts.push({ id: script.id, text: script.id }); } this._scripts.sort((lhs, rhs) => lhs.text.localeCompare(rhs.text)); const selectedScriptIds = this.computeSelectedScriptIdsAfterFindScripts(); if (selectedScriptIds.size > 0) { this.selectedScriptIds = selectedScriptIds; } if (!this.demoMode) this.onChange(); } catch (e) { if (!this.demoMode) this.logger(`Error in findScripts: ${e.stack}`); } } private computeSelectedScriptIdsAfterFindScripts(): Set<string> { if (this._scripts.length === 0) { console.log('Initially selecting no scripts, no scripts to select'); return new Set(); } if (this.selectedProfileId && this.selectedProfileId && this.selectedProfileId === this.state.selectedProfileId) { const initialProfile = this.state.profiles[this.selectedProfileId]; if (initialProfile && initialProfile.selectedScriptIds && initialProfile.selectedScriptIds.length > 0) { const currentScriptIds = new Set(this._scripts.map(v => v.id)); const candidates = setIntersect(currentScriptIds, new Set(initialProfile.selectedScriptIds)); if (candidates.size > 0) { console.log(`Initially selecting script${candidates.size === 1 ? '' : 's'} ${[...candidates].sort().join(', ')}: remembered from last time`); return candidates; } } } const firstScriptId = this._scripts[0].id console.log(`Initially selecting script ${firstScriptId}: first one in the list`); return new Set([this._scripts[0].id]); // first one in the list } private async setTails() { if (this.selectedProfileId === undefined) return; const profile = this.state.profiles[this.selectedProfileId]; if (profile === undefined) return; const { accountId, apiToken } = profile; try { await this.tailController.setTails(accountId, apiToken, this._selectedScriptIds); } catch (e) { this.logger('Error in setTails', e.stack || e.message); } } private computeAdditionalLogs(message: TailMessage): readonly AdditionalLog[] { const rt: AdditionalLog[] = []; const includeIpAddress = this.extraFields.includes('ip-address'); const includeUserAgent = this.extraFields.includes('user-agent'); const includeReferer = this.extraFields.includes('referer'); if (includeIpAddress || includeUserAgent || includeReferer) { if (!isTailMessageCronEvent(message.event)) { if (includeIpAddress) { const ipAddress = message.event.request.headers['cf-connecting-ip'] || undefined; if (ipAddress) rt.push(computeAdditionalLogForExtraField('IP address', ipAddress)); } if (includeUserAgent) { const userAgent = message.event.request.headers['user-agent'] || undefined; if (userAgent) rt.push(computeAdditionalLogForExtraField('User agent', userAgent)); } if (includeReferer) { const referer = message.event.request.headers['referer'] || undefined; if (referer) { const refererUrl = tryParseUrl(referer); let log = true; if (refererUrl !== undefined) { const requestUrl = tryParseUrl(message.event.request.url); if (requestUrl && requestUrl.origin === refererUrl.origin) { log = false; } } if (log) rt.push(computeAdditionalLogForExtraField('Referer', referer)); } } } } return rt; } private recomputeWelcomeShowing() { const shouldShow = this.profiles.length === 0; if (shouldShow === this.welcomeShowing) return; this.setDemoMode(shouldShow); this.welcomeShowing = shouldShow; } private async queryDurableObjectsCosts(client: CfGqlClient) { try { this.analyticsState.durableObjectsCosts = await computeDurableObjectsCostsTable(client, { lookbackDays: 28 }); if (this.analyticsState.durableObjectsCosts.accountTable.rows.length === 0) { this.analyticsState.durableObjectsCosts = undefined; throw new Error('No durable object analytics found'); } } catch (e) { console.warn(e); let error = `${e}`; if (error.includes('(code=authz)')) { error = `The auth token for this profile does not have the Account Analytics:Read permission.` } this.analyticsState.error = error; } finally { this.analyticsState.querying = false; this.onChange(); } } } function computeAdditionalLogForExtraField(name: string, value: string): AdditionalLog { return { data: [` %c|%c [%c${name}%c] ${value}`, 'color:gray', '', 'color:gray' ] }; } export class ProfileFormVM { showing = false; enabled = false; name = ''; accountId = ''; apiToken = ''; deleteVisible = false; saveEnabled = false; profileId = ''; title = ''; progressVisible = false; outputMessage = ''; computeSaveEnabled() { this.saveEnabled = this.name.trim().length > 0 && this.apiToken.trim().length > 0 && this.accountId.trim().length > 0; } } export class FilterFormVM { showing = false; enabled = false; fieldName = ''; fieldValueChoices: TextItem[] = []; fieldValueOptions: TextItem[] = []; fieldValue?: string; // (fieldValueChoices: selected item id) (fieldValueOptions: comma-sep item ids) (text: free form text from input) helpText = ''; outputMessage = ''; applyValue: () => void = () => {}; } export interface TextItem { readonly id: string; readonly text: string; readonly description?: string; } export interface FilterState { event1?: string; // all, cron, http status1?: string; // all, error, success ipAddress1?: string[]; // addresses, or self method1?: string[]; // GET, POST, etc samplingRate1?: number; // 0 to 1 search1?: string; // search string header1?: string[]; // foo, or foo:bar logprop1?: string[]; // foo:bar } export interface AnalyticsState { querying: boolean; error?: string; durableObjectsCosts?: DurableObjectsCostsTable; } // const EXTRA_FIELDS_OPTIONS: TextItem[] = [ { id: 'ip-address', text: 'IP address' }, { id: 'user-agent', text: 'User agent' }, { id: 'referer', text: 'Referer' }, ]; const STATE_KEY = 'state1'; function loadState(): State { try { const json = localStorage.getItem(STATE_KEY) || undefined; if (json) { const obj = JSON.parse(json); const rt = parseState(obj); // console.log('loadState: returning state', JSON.stringify(rt)); return rt; } } catch (e) { console.warn('loadState: Error loading state', e.stack || e); } console.log('loadState: returning new state'); return { profiles: {} }; } // deno-lint-ignore no-explicit-any function parseState(parsed: any): State { if (typeof parsed !== 'object') throw new Error(`Expected object`); const { profiles } = parsed; if (typeof profiles !== 'object') throw new Error(`Expected profiles object`); for (const [profileId, profileState] of Object.entries(profiles)) { if (typeof profileId !== 'string') throw new Error('Profile id must be string'); parseProfileState(profileState); } return parsed as State; } // deno-lint-ignore no-explicit-any function parseProfileState(parsed: any): ProfileState { if (typeof parsed !== 'object' || parsed === null) throw new Error('Profile state must be object'); const { name, accountId, apiToken } = parsed; if (typeof name !== 'string' || name.trim().length === 0) throw new Error(`Profile state name must exist`); if (typeof accountId !== 'string' || accountId.trim().length === 0) throw new Error(`Profile state accountId must exist`); if (typeof apiToken !== 'string' || apiToken.trim().length === 0) throw new Error(`Profile state apiToken must exist`); return parsed as ProfileState; } function saveState(state: State) { localStorage.setItem(STATE_KEY, JSON.stringify(state)); } async function computeCanListTails(accountId: string, apiToken: string): Promise<boolean> { try { await listTails(accountId, '' /*unlikely script name*/, apiToken); return true; } catch (e) { if (e instanceof CloudflareApiError && e.status === 404) { // status=404, errors=10007 workers.api.error.script_not_found return true; } else { // status=400, errors=7003 Could not route to /accounts/.../workers/scripts/tails, perhaps your object identifier is invalid?, 7000 No route for that URI } return false; } } function isValidSamplingRate(samplingRate: number): boolean { return !isNaN(samplingRate) && samplingRate >= 0 && samplingRate <= 1; } function computeInitiallySelectedProfileId(state: State, profiles: TextItem[]) { if (state.selectedProfileId && state.profiles[state.selectedProfileId]) return state.selectedProfileId; if (profiles.length > 0) return profiles[0].id; return undefined; } function computeTailOptionsForFilter(filter: FilterState): TailOptions { const filters: TailFilter[] = []; if (filter.status1 === 'error') { filters.push({ outcome: [ 'exception', 'exceededCpu', 'canceled', 'unknown' ]}); } else if (filter.status1 === 'success') { filters.push({ outcome: [ 'ok' ]}); } if (filter.samplingRate1 !== undefined && isValidSamplingRate(filter.samplingRate1) && filter.samplingRate1 < 1) { filters.push({ sampling_rate: filter.samplingRate1 }); } if (filter.search1 !== undefined && filter.search1.length > 0) { filters.push({ query: filter.search1 }); } if (filter.method1 && filter.method1.length > 0) { filters.push({ method: filter.method1 }); } if (filter.ipAddress1 && filter.ipAddress1.length > 0) { filters.push({ client_ip: filter.ipAddress1 }); } if (filter.header1 && filter.header1.length > 0) { for (const header of filter.header1) { filters.push(parseHeaderFilter(header)); } } return { filters }; } function computeMessagePassesFilter(message: TailMessage, filter: FilterState): boolean { if (!computeMessagePassesLogPropFilter(message, filter.logprop1)) return false; if (filter.event1 === 'cron' || filter.event1 === 'http') { const isCron = isTailMessageCronEvent(message); return isCron && filter.event1 === 'cron' || !isCron && filter.event1 === 'http'; } return true; } function computeMessagePassesLogPropFilter(message: TailMessage, logprop1?: string[]): boolean { if (logprop1 === undefined || logprop1.length === 0) return true; const logpropFilters = logprop1.map(parseHeaderFilter); const { props } = parseLogProps(message.logs); for (const logpropFilter of logpropFilters) { if (computePropsPassLogpropFilter(props, logpropFilter)) return true; } return false; } function computePropsPassLogpropFilter(props: Record<string, unknown>, logpropFilter: HeaderFilter): boolean { const val = props[logpropFilter.key]; if (val === undefined) return false; if (logpropFilter.query === undefined) return true; const q = logpropFilter.query.trim().replaceAll(/\*+/g, '*'); if (!q.includes('*')) return q === val; if (q === '*') return true; if (typeof val !== 'string') return false; const pattern = '^' + escapeForRegex(q).replaceAll('\\*', '.*') + '$'; return new RegExp(pattern).test(val); } function escapeForRegex(str: string): string { return str.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&'); } function distinct(values: string[]): string[] { // and maintain order const rt: string[] = []; for (const value of values) { if (!rt.includes(value)) { rt.push(value); } } return rt; } function tryParseUrl(url: string): URL | undefined { try { return new URL(url); } catch { return undefined; } } // interface State { readonly profiles: Record<string, ProfileState>; // profileId -> state selectedProfileId?: string; filter?: FilterState; extraFields?: string[]; // ip-address, user-agent, referer } interface ProfileState { readonly name: string; readonly accountId: string; readonly apiToken: string; selectedScriptIds?: string[]; }
the_stack
import * as L from 'leaflet'; declare module 'leaflet' { interface MapOptions { drawControl?: boolean; drawControlTooltips?: boolean; touchExtend?: boolean; } class DrawMap extends Map { mergeOptions(options?: MapOptions): void; addInitHook(): void; } interface ToolbarAction { title: string; text: string; callback: () => void; context: object; } interface ToolbarModeHandler { enabled: boolean; handler: Handler; title: string; } interface ToolbarOptions { polyline?: DrawOptions.PolylineOptions; polygon?: DrawOptions.PolygonOptions; rectangle?: DrawOptions.RectangleOptions; circle?: DrawOptions.CircleOptions; marker?: DrawOptions.MarkerOptions; circlemarker?: DrawOptions.CircleOptions; } interface PrecisionOptions { km?: number; ha?: number; m?: number; mi?: number; ac?: number; yd?: number; ft?: number; nm?: number; } class Toolbar extends Class { constructor(options?: ToolbarOptions); addToolbar(map: DrawMap): HTMLElement | void; removeToolbar(): void; } class DrawToolbar extends Toolbar { getModeHandlers(map: DrawMap): ToolbarModeHandler[]; getActions(handler: Draw.Feature): ToolbarAction[]; setOptions(options: Control.DrawConstructorOptions): void; } class EditToolbar extends Toolbar { getModeHandlers(map: DrawMap): ToolbarModeHandler[]; getActions(handler: Draw.Feature): ToolbarAction[]; setOptions(options: Control.DrawConstructorOptions): void; } namespace Control { interface DrawConstructorOptions { /** * The initial position of the control (one of the map corners). * * @default 'topleft' */ position?: ControlPosition; /** * The options used to configure the draw toolbar. * * @default {} */ draw?: DrawOptions; /** * The options used to configure the edit toolbar. * * @default false */ edit?: EditOptions; } interface DrawOptions { /** * Polyline draw handler options. Set to false to disable handler. * * @default {} */ polyline?: DrawOptions.PolylineOptions | false; /** * Polygon draw handler options. Set to false to disable handler. * * @default {} */ polygon?: DrawOptions.PolygonOptions | false; /** * Rectangle draw handler options. Set to false to disable handler. * * @default {} */ rectangle?: DrawOptions.RectangleOptions | false; /** * Circle draw handler options. Set to false to disable handler. * * @default {} */ circle?: DrawOptions.CircleOptions | false; /** * Circle marker draw handler options. Set to false to disable handler. * * @default {} */ circlemarker?: DrawOptions.CircleMarkerOptions | false; /** * Marker draw handler options. Set to false to disable handler. * * @default {} */ marker?: DrawOptions.MarkerOptions | false; } interface EditOptions { /** * This is the FeatureGroup that stores all editable shapes. * THIS IS REQUIRED FOR THE EDIT TOOLBAR TO WORK * * @default null */ featureGroup: FeatureGroup; /** * Edit handler options. Set to false to disable handler. * * @default null */ edit?: DrawOptions.EditHandlerOptions | false; /** * Delete handler options. Set to false to disable handler. * * Default value: null */ remove?: null | false; } class Draw extends Control { constructor(options?: DrawConstructorOptions); initialize(options?: DrawOptions): void; setDrawingOptions(options?: DrawOptions): void; } } namespace DrawOptions { interface SimpleShapeOptions { /** * Determines if the draw tool remains enabled after drawing a shape. * * @default false */ repeatMode?: boolean; } interface PolylineOptions extends SimpleShapeOptions { /** * Determines if line segments can cross. * * @default true */ allowIntersection?: boolean; /** * Configuration options for the error that displays if an intersection is detected. * * @default { color: '#b00b00', timeout: 2500 } */ drawError?: DrawErrorOptions; /** * Distance in pixels between each guide dash. * * @default 20 */ guidelineDistance?: number; /** * The options used when drawing the polyline/polygon on the map. * * @default { stroke: true, color: '#3388ff', weight: 4, opacity: 0.5, fill: false, clickable: true } */ shapeOptions?: L.PolylineOptions & { clickable?: boolean; }; /** * Whether to display distance in the tooltip * * @default true */ showLength?: boolean; /** * Determines which measurement system (metric or imperial) is used. * * @default true */ metric?: boolean; /** * When not metric, to use feet instead of yards for display. * * @default true */ feet?: boolean; /** * When not metric, not feet use nautic mile for display * * @default false */ nautic?: boolean; /** * This should be a high number to ensure that you can draw over all other layers on the map. * * @default 2000 */ zIndexOffset?: number; icon?: Icon | DivIcon; touchIcon?: Icon | DivIcon; /** * The maximum length of the guide line * * @default 4000 */ maxGuideLineLength?: number; /** * To change distance calculation * * @default 1 */ factor?: number; /** * Once this number of points are placed, finish shape * * @default 0 */ maxPoints?: number; } interface PolygonOptions extends PolylineOptions { /** * Show the area of the drawn polygon in m², ha or km². * The area is only approximate and become less accurate the larger the polygon is. * * @default false */ showArea?: boolean; /** * Show the length of the drawn line. * The area is only approximate and become less accurate the larger the polygon is. * * @default false */ showLength?: boolean; /** * Defines the precision for each type of unit (e.g. {km: 2, ft: 0} * * @default {} */ precision?: PrecisionOptions; } interface RectangleOptions extends SimpleShapeOptions { /** * The options used when drawing the rectangle on the map. * * @default {stroke: true, weight: 4, opacity: 0.5, fill: true, fillColor: null, fillOpacity: 0.2, showArea: true, clickable: true } */ shapeOptions?: PathOptions; /** * Whether to use the metric measurement system or imperial * * @default true */ metric?: boolean; } interface CircleOptions extends SimpleShapeOptions { /** * The options used when drawing the circle on the map. * * @default { stroke: true, color: '#3388ff', weight: 4, opacity: 0.5, fill: true, fillColor: null, fillOpacity: 0.2, clickable: true } */ shapeOptions?: PathOptions; /** * Whether to show the radius in the tooltip * * @default true */ showRadius?: boolean; /** * Whether to use the metric measurement system or imperial * * @default true */ metric?: boolean; /** * When not metric, use feet instead of yards for display * * @default true */ feet?: boolean; /** * When not metric, not feet use nautic mile for display * * @default false */ nautic?: boolean; } interface CircleMarkerOptions { /** * Whether to draw stroke around the circle marker. * * @default true */ stroke?: boolean; /** * The stroke color of the circle marker. * * @default '#3388ff' */ color?: string; /** * The stroke width in pixels of the circle marker. * * @default 4 */ weight?: number; /** * The stroke opacity of the circle marker. * * @default 0.5 */ opacity?: number; /** * Whether to fill the circle marker with color. * * @default true */ fill?: boolean; /** * The fill color of the circle marker. Defaults to the value of the color option. * * @default null */ fillColor?: string; /** * The opacity of the circle marker. * * @default 0.2 */ fillOpacity?: number; /** * Whether you can click the circle marker. * * @default true */ clickable?: boolean; /** * This should be a high number to ensure that you can draw over all other layers on the map. * * @default 2000 */ zIndexOffset?: number; } interface MarkerOptions { /** * The icon displayed when drawing a marker. * * @default L.Icon.Default() */ icon?: Icon | DivIcon; /** * This should be a high number to ensure that you can draw over all other layers on the map. * * @default 2000 */ zIndexOffset?: number; /** * Determines if the draw tool remains enabled after drawing a shape. * * @default false */ repeatMode?: boolean; } interface EditPolyOptions { /** * This is the FeatureGroup that stores all editable shapes * THIS IS REQUIRED FOR THE EDIT TOOLBAR TO WORK */ featureGroup: FeatureGroup; /** * Edit handler options. Set to false to disable handler. */ edit: EditHandlerOptions; /** * Delete handler options. Set to false to disable handler. */ remove: any; /** * Set polygon editing options */ poly: EditPolyOptions; /** * Determines if line segments can cross * * @default true */ allowIntersection: boolean; } interface EditHandlerOptions { /** * The path options for how the layers will look while in edit mode. * If this is set to null the editable path options will not be set. * * @default { dashArray: '10, 10', fill: true, fillColor: '#fe57a1', fillOpacity: 0.1, maintainColor: false } */ selectedPathOptions?: PathOptions; } interface DrawErrorOptions { color?: string; timeout?: number; message?: string; } } namespace Draw { namespace Event { const CREATED: 'draw:created'; const DELETED: 'draw:deleted'; const DELETESTART: 'draw:deletestart'; const DELETESTOP: 'draw:deletestop'; const DRAWSTART: 'draw:drawstart'; const DRAWSTOP: 'draw:drawstop'; const DRAWVERTEX: 'draw:drawvertex'; const EDITED: 'draw:edited'; const EDITMOVE: 'draw:editmove'; const EDITRESIZE: 'draw:editresize'; const EDITSTART: 'draw:editstart'; const EDITSTOP: 'draw:editstop'; const EDITVERTEX: 'draw:editvertex'; const MARKERCONTEXT: 'draw:markercontext'; const TOOLBARCLOSED: 'draw:toolbarclosed'; const TOOLBAROPENED: 'draw:toolbaropened'; } /** * EventHandlers to be used in looping over all events * * @example * for (const key in eventHandlers) { map.off(eventHandlers[key], LeafletFn); } */ interface EventHandlers { onCreated: typeof Event.CREATED; onDeleted: typeof Event.DELETED; onDeleteStart: typeof Event.DELETESTART; onDeleteStop: typeof Event.DELETESTOP; onDrawStart: typeof Event.DRAWSTART; onDrawStop: typeof Event.DRAWSTOP; onDrawVertex: typeof Event.DRAWVERTEX; onEdited: typeof Event.EDITED; onEditMove: typeof Event.EDITMOVE; onEditResize: typeof Event.EDITRESIZE; onEditStart: typeof Event.EDITSTART; onEditStop: typeof Event.EDITSTOP; onEditVertex: typeof Event.EDITVERTEX; onMarkerContext: typeof Event.MARKERCONTEXT; onToolbarClosed: typeof Event.TOOLBARCLOSED; onToolbarOpened: typeof Event.TOOLBAROPENED; // Requires an index signature of type string to be properly useful [key: string]: string; } class Feature extends Handler { initialize( map: DrawMap, options: | DrawOptions.PolylineOptions | DrawOptions.PolygonOptions | DrawOptions.RectangleOptions | DrawOptions.MarkerOptions | DrawOptions.EditHandlerOptions ): void; setOptions( options: | DrawOptions.PolylineOptions | DrawOptions.PolygonOptions | DrawOptions.RectangleOptions | DrawOptions.MarkerOptions | DrawOptions.EditHandlerOptions ): void; } class SimpleShape extends Feature { constructor( map: DrawMap, options?: DrawOptions.SimpleShapeOptions ) } class Marker extends Feature { constructor( map: DrawMap, options?: DrawOptions.MarkerOptions ) } class CircleMarker extends Marker { constructor( map: DrawMap, options?: DrawOptions.MarkerOptions ) } class Circle extends SimpleShape { constructor( map: DrawMap, options?: DrawOptions.CircleOptions ) } class Polyline extends Feature { constructor( map: DrawMap, options?: DrawOptions.PolylineOptions ) deleteLastVertex(): void; addVertex(latlng: LatLng): void; completeShape(): void; } class Rectangle extends SimpleShape { constructor( map: DrawMap, options?: DrawOptions.RectangleOptions ) } class Polygon extends Polyline { constructor( map: DrawMap, options?: DrawOptions.PolygonOptions ) } class Tooltip extends Class { constructor(map: DrawMap); dispose(): void; updateContent(labelText?: { text: string, subtext?: string }): Tooltip; updatePosition(latlng: LatLng): Tooltip; showAsError(): Tooltip; removeError(): Tooltip; } } namespace DrawEvents { interface Created extends LeafletEvent { /** * Layer that was just created. */ layer: Circle | CircleMarker | Marker | Polygon | Polyline | Rectangle; /** * The type of layer this is. One of: polyline, polygon, rectangle, circle, marker. */ layerType: string; } interface Edited extends LeafletEvent { /** * List of all layers just edited on the map. */ layers: LayerGroup; } /** * Triggered when layers have been removed (and saved) from the FeatureGroup. */ interface Deleted extends LeafletEvent { /** * List of all layers just removed from the map. */ layers: LayerGroup; } interface DrawStart extends LeafletEvent { /** * The type of layer this is. One of: polyline, polygon, rectangle, circle, marker */ layerType: string; } interface DrawStop extends LeafletEvent { /** * The type of layer this is. One of: polyline, polygon, rectangle, circle, marker */ layerType: string; } interface DrawVertex extends LeafletEvent { /** * List of all layers just being added from the map. */ layers: LayerGroup; } interface EditStart extends LeafletEvent { /** * The type of edit this is. One of: edit */ handler: string; } interface EditMove extends LeafletEvent { /** * Layer that was just moved. */ layer: Layer; } interface EditResize extends LeafletEvent { /** * Layer that was just resized. */ layer: Layer; } interface EditVertex extends LeafletEvent { /** * List of all layers just being edited from the map. */ layers: LayerGroup; poly: Polyline | Polygon; } interface EditStop extends LeafletEvent { /** * The type of edit this is. One of: edit */ handler: string; } interface DeleteStart extends LeafletEvent { /** * The type of edit this is. One of: remove */ handler: string; } interface DeleteStop extends LeafletEvent { /** * The type of edit this is. One of: remove */ handler: string; } type ToolbarOpened = LeafletEvent; type ToolbarClosed = LeafletEvent; type MarkerContext = LeafletEvent; } namespace GeometryUtil { /** * Shortcut function for planar distance between two {L.LatLng} at current zoom. */ function distance(map: DrawMap, latlanA: LatLng, latlngB: LatLng): number; /** * Returns the area of a polygon drawn with leaflet.draw */ function geodesicArea(coordinates: LatLngLiteral[]): number; /** * Returns n in specified number format (if defined) and precision */ function formattedNumber(n: string, precision: number): string; /** * Returns a readable area string in yards or metric */ function readableArea(area: number, isMetric?: boolean, precision?: PrecisionOptions): string; /** * Converts a metric distance to one of [ feet, nauticalMile, metric or yards ] string * The value will be rounded as defined by the precision option object. */ function readableDistance( distance: number, isMetric?: boolean, isFeet?: boolean, isNauticalMile?: boolean, precision?: PrecisionOptions ): string; /** * Returns true if the Leaflet version is 0.7.x, false otherwise. */ function isVersion07x(): boolean; } namespace LatLngUtil { /** * Clone the latLng point or points or nested points and return an array with those points */ function cloneLatLngs(latlngs: LatLng[]): LatLng[][]; /** * Clone the latLng and return a new LatLng object. */ function cloneLatLng(latlng: LatLng): LatLng; } namespace LineUtil { /** * Checks to see if two line segments intersect. * Does not handle degenerate cases. */ function segmentsIntersect(): boolean; } namespace Polygon { /** * Checks a polygon for any intersecting line segments. * Ignores holes. */ function intersects(): boolean; } namespace EditToolbar { class Edit extends Toolbar { constructor(map: DrawMap, options?: ToolbarOptions); revertLayers(): void; save(): void; } class Delete extends Toolbar { constructor(map: DrawMap, options?: ToolbarOptions); revertLayers(): void; save(): void; removeAllLayers(): void; } } namespace EditOptions { interface EditPolyVerticesEditOptions { icon?: Icon | DivIcon; touchIcon?: Icon | DivIcon; drawError?: DrawOptions.DrawErrorOptions; } interface EditSimpleShapeOptions { moveIcon?: Icon | DivIcon; resizeIcon?: Icon | DivIcon; touchMoveIcon?: Icon | DivIcon; touchResizeIcon?: Icon | DivIcon; } } namespace Edit { class Circle extends CircleMarker { constructor(shape: Circle, options?: EditOptions.EditSimpleShapeOptions); } class CircleMarker extends SimpleShape { constructor(shape: CircleMarker, options?: EditOptions.EditSimpleShapeOptions); } class Marker extends Handler { constructor(marker: Marker, options?: object); } class Polyline extends Handler { constructor(polyline: Draw.Polyline); updateMarkers(): void; } class PolyVerticesEdit extends Handler { constructor(poly: Polyline, latlngs: LatLngExpression[], options?: EditOptions.EditPolyVerticesEditOptions); updateMarkers(): void; } class Rectangle extends SimpleShape { constructor(shape: Rectangle, options?: EditOptions.EditSimpleShapeOptions); } class SimpleShape extends Handler { constructor(shape: SimpleShape, options?: EditOptions.EditSimpleShapeOptions); updateMarkers(): void; } } namespace Localization { interface DrawLocal { draw: Draw; edit: Edit; } interface Draw { toolbar: DrawToolbar; handlers: DrawHandlers; } interface Edit { toolbar: EditToolbar; handlers: EditHandlers; } interface Action { title: string; text: string; } interface DrawToolbar { actions: Action; finish: Action; undo: Action; buttons: { polyline: string; polygon: string; rectangle: string; circle: string; marker: string; circlemarker: string; }; } interface Tooltip { start?: string; cont?: string; end?: string; } interface DrawHandlers { circle: { tooltip: { start: string; }; radius: string; }; circlemarker: { tooltip: { start: string; }; }; marker: { tooltip: { start: string; }; }; polygon: { tooltip: { start: string; cont: string; end: string; }; }; polyline: { error: string; tooltip: { start: string; cont: string; end: string; }; }; rectangle: { tooltip: { start: string; }; }; simpleshape: { tooltip: { end: string; }; }; } interface EditToolbar { actions: { save: Action; cancel: Action; clearAll: Action; }; buttons: { edit: string; editDisabled: string; remove: string; removeDisabled: string; }; } interface EditHandlers { edit: { tooltip: { text: string; subtext: string; }; }; remove: { tooltip: { text: string; }; }; } } function map(element: string | HTMLElement, options?: MapOptions): DrawMap; const drawVersion: string; const drawLocal: Localization.DrawLocal; }
the_stack
import bigInt from 'big-integer'; import { JSONPath } from 'jsonpath-plus'; import { KeyStore, Signer } from '../../../types/ExternalInterfaces'; import * as TezosTypes from '../../../types/tezos/TezosChainTypes'; import { TezosNodeReader } from '../TezosNodeReader'; import { TezosNodeWriter } from '../TezosNodeWriter'; import { TezosContractUtils } from './TezosContractUtils'; import { TezosMessageUtils } from '../TezosMessageUtil'; interface DexterPoolSimpleStorage { balanceMap: number; administrator: string; token: string; tokenBalance: number; xtzBalance: number; selfIsUpdatingTokenPool: boolean; freeze_baker: boolean; lqt_total: number; } /** * Contract wrapper for http://dexter.exchange/ pool contracts, intended for use on mainnet with KT1Puc9St8wdNoGtLiD2WXaHbWU7styaxYhD (usdtz) and KT1DrJV8vhkdLEj76h1H9Q4irZDqAkMPo1Qf (tzbtc). * * Tested on carthagenet with KT1RtNatBzmk2AvJKm9Mx6b55GcQejJneK7t. * * Based on integration documentation provided at https://gitlab.com/camlcase-dev/dexter-integration. */ export namespace DexterPoolHelper { const DexterPoolLiquidityOperationGasLimit = 500_000; const DexterPoolLiquidityOperationStorageLimit = 5_000; const DexterPoolExchangeOperationGasLimit = 500_000; const DexterPoolExchangeOperationStorageLimit = 5_000; const ExchangeMultiplier = 997; /** * Gets the contract code at the specified address at the head block and compares it to the known hash of the code. This function processes Micheline format contracts. * * @param server Destination Tezos node. * @param address Contract address to query. */ export async function verifyDestination(server: string, address: string): Promise<boolean> { return TezosContractUtils.verifyDestination(server, address, 'a72954311c48dcc28279590d82870611'); } /** * In contrast to verifyDestination, this function uses compares Michelson hashes. * * @param script */ export function verifyScript(script: string): boolean { return TezosContractUtils.verifyScript(script, 'yyy'); } /** * Queries the tezos node directly for basic contract storage. * * @param server Destination Tezos node. * @param address Contract address to query. * @returns * - balanceMap: bigmap index of the liquidity balance map * - administrator: Contract administrator * - token: Token address this pool services * - tokenBalance: Total token balance held in the pool * - xtzBalance: Total XTZ balance held in the pool * - selfIsUpdatingTokenPool * - freeze_baker * - lqt_total Liquidity token balance */ export async function getSimpleStorage(server: string, address: string): Promise<DexterPoolSimpleStorage> { const storageResult = await TezosNodeReader.getContractStorage(server, address); return { balanceMap: Number(JSONPath({ path: '$.args[0].int', json: storageResult })[0]), administrator: JSONPath({ path: '$.args[2].args[0].string', json: storageResult })[0], token: JSONPath({ path: '$.args[2].args[1].string', json: storageResult })[0], tokenBalance: Number(JSONPath({ path: '$.args[3].int', json: storageResult })[0]), xtzBalance: Number(JSONPath({ path: '$.args[4].int', json: storageResult })[0]), selfIsUpdatingTokenPool: (JSONPath({ path: '$.args[1].args[0].prim', json: storageResult })[0]).toString().toLowerCase().startsWith('t'), freeze_baker: (JSONPath({ path: '$.args[1].args[0].prim', json: storageResult })[0]).toString().toLowerCase().startsWith('t'), lqt_total: Number(JSONPath({ path: '$.args[1].args[2].int', json: storageResult })[0]) }; } /** * Queries the Tezos node for the liquidity balance of the requested account. * * @param server Destination Tezos node. * @param mapid bigmap id of the pool to query. * @param account Account to query. */ export async function getAccountBalance(server: string, mapid: number, account: string): Promise<number> { try { const packedKey = TezosMessageUtils.encodeBigMapKey(Buffer.from(TezosMessageUtils.writePackedData(account, 'address'), 'hex')); const mapResult = await TezosNodeReader.getValueForBigMapKey(server, mapid, packedKey); if (mapResult === undefined) { throw new Error(`Map ${mapid} does not contain a record for ${account}`); } const jsonresult = JSONPath({ path: '$.args[0].int', json: mapResult }); return Number(jsonresult[0]); } catch { return 0; } } /** * * @param server Destination Tezos node. * @param address Pool contract address. * @param account * @returns Raw values that are not scaled. */ export async function getAccountPoolShare(server: string, address: string, account: string): Promise<{token: number, xtz: number}> { try { const storage = await getSimpleStorage(server, address); const packedKey = TezosMessageUtils.encodeBigMapKey(Buffer.from(TezosMessageUtils.writePackedData(account, 'address'), 'hex')); const mapResult = await TezosNodeReader.getValueForBigMapKey(server, storage.balanceMap, packedKey); if (mapResult === undefined) { throw new Error(`Map ${storage.balanceMap} does not contain a record for ${account}`); } const poolBalance = bigInt(JSONPath({ path: '$.args[0].int', json: mapResult })[0]); const poolTotal = bigInt(storage.lqt_total); const tokenBalance = bigInt(storage.tokenBalance); const xtzBalance = bigInt(storage.xtzBalance); return { token: tokenBalance.multiply(poolBalance).divide(poolTotal).toJSNumber(), xtz: xtzBalance.multiply(poolBalance).divide(poolTotal).toJSNumber() }; } catch (error) { return { token: 0, xtz: 0 }; } } /** * Queries the Tezos node for the liquidity balance approval for a given spender on the requested account. * * @param server Destination Tezos node. * @param mapid bigmap id of the pool to query. * @param account Account to query. * @param spender Spender to get balance for. */ export async function getAccountAllowance(server: string, mapid: number, account: string, spender: string) { const packedKey = TezosMessageUtils.encodeBigMapKey(Buffer.from(TezosMessageUtils.writePackedData(account, 'address'), 'hex')); const mapResult = await TezosNodeReader.getValueForBigMapKey(server, mapid, packedKey); if (mapResult === undefined) { throw new Error(`Map ${mapid} does not contain a record for ${account}/${spender}`); } let allowances = new Map<string, number>(); JSONPath({ path: '$.args[1][*].args', json: mapResult }).forEach(v => allowances[v[0]['string']] = Number(v[1]['int'])); return allowances[spender] || 0; } /** * Adds liquidity to the pool using the `addLiquidity` entry point of the contract pool. Deposits both XTZ and a matching token balance. * * @param server Destination Tezos node. * @param signer * @param keyStore * @param contract * @param fee * @param liquidityAmount Expected liquidity amount * @param xtzAmount * @param tokenAmount * @param expiration Request expiration date. */ export async function addLiquidity(server: string, signer: Signer, keyStore: KeyStore, contract: string, fee: number, liquidityAmount: number, xtzAmount: number, tokenAmount: number, expiration: Date): Promise<string> { //(pair (address :owner) (nat :minLqtMinted)) (pair (nat :maxTokensDeposited) (timestamp :deadline))) const parameters = `(Pair (Pair "${keyStore.publicKeyHash}" ${liquidityAmount}) (Pair ${tokenAmount} "${expiration.toISOString()}"))`; const nodeResult = await TezosNodeWriter.sendContractInvocationOperation(server, signer, keyStore, contract, xtzAmount, fee, DexterPoolLiquidityOperationStorageLimit, DexterPoolLiquidityOperationGasLimit, 'addLiquidity', parameters, TezosTypes.TezosParameterFormat.Michelson); return TezosContractUtils.clearRPCOperationGroupHash(nodeResult.operationGroupID); } /** * Removes liquidity from the pool using the `removeLiquidity` entry point. * * @param server Destination Tezos node. * @param signer * @param keyStore * @param contract * @param fee * @param balance Liquidity amount to withdraw. * @param xtzBalance Expected XTZ balance * @param tokenBalance Expected token balance * @param expiration Request expiration date. */ export async function removeLiquidity(server: string, signer: Signer, keyStore: KeyStore, contract: string, fee: number, balance: number, xtzBalance: number, tokenBalance: number, expiration: Date): Promise<string> { //(pair (address :owner) (pair (address :to) (nat :lqtBurned))) (pair (mutez :minXtzWithdrawn) (pair (nat :minTokensWithdrawn) (timestamp :deadline))) const parameters = `(Pair (Pair "${keyStore.publicKeyHash}" (Pair "${keyStore.publicKeyHash}" ${balance})) (Pair ${xtzBalance} (Pair ${tokenBalance} "${expiration.toISOString()}")))`; const nodeResult = await TezosNodeWriter.sendContractInvocationOperation(server, signer, keyStore, contract, 0, fee, DexterPoolLiquidityOperationStorageLimit, DexterPoolLiquidityOperationGasLimit, 'removeLiquidity', parameters, TezosTypes.TezosParameterFormat.Michelson); return TezosContractUtils.clearRPCOperationGroupHash(nodeResult.operationGroupID); } /** * * Convert an XTZz balance into an token balance. * @param server * @param signer * @param keyStore * @param contract * @param fee * @param xtzAmount * @param tokenAmount * @param expiration Request expiration date. */ export async function xtzToToken(server: string, signer: Signer, keyStore: KeyStore, contract: string, fee: number, xtzAmount: number, tokenAmount: number, expiration: Date): Promise<string> { //(pair %xtzToToken (address :to) (pair (nat :minTokensBought) (timestamp :deadline))) const parameters = `(Pair "${keyStore.publicKeyHash}" (Pair ${tokenAmount} "${expiration.toISOString()}"))`; const nodeResult = await TezosNodeWriter.sendContractInvocationOperation(server, signer, keyStore, contract, xtzAmount, fee, DexterPoolExchangeOperationStorageLimit, DexterPoolExchangeOperationGasLimit, 'xtzToToken', parameters, TezosTypes.TezosParameterFormat.Michelson); return TezosContractUtils.clearRPCOperationGroupHash(nodeResult.operationGroupID); } /** * Convert a token balance into an XTZ balance. * * @param server Destination Tezos node. * @param signer * @param keyStore * @param contract * @param fee * @param xtzAmount * @param tokenAmount * @param expiration Request expiration date. */ export async function tokenToXtz(server: string, signer: Signer, keyStore: KeyStore, contract: string, fee: number, xtzAmount: number, tokenAmount: number, expiration: Date): Promise<string> { //(pair %tokenToXtz (pair (address :owner) (address :to)) (pair (nat :tokensSold) (pair (mutez :minXtzBought) (timestamp :deadline)))) const parameters = `(Pair (Pair "${keyStore.publicKeyHash}" "${keyStore.publicKeyHash}") (Pair ${tokenAmount} (Pair ${xtzAmount} "${expiration.toISOString()}")))`; const nodeResult = await TezosNodeWriter.sendContractInvocationOperation(server, signer, keyStore, contract, 0, fee, DexterPoolExchangeOperationStorageLimit, DexterPoolExchangeOperationGasLimit, 'tokenToXtz', parameters, TezosTypes.TezosParameterFormat.Michelson); return TezosContractUtils.clearRPCOperationGroupHash(nodeResult.operationGroupID); } /** * Untested function that should allow exchange of a token for a different token instead of xtz. * * @param server Destination Tezos node. * @param signer * @param keyStore * @param contract * @param fee * @param otherPoolContract * @param sellAmount * @param buyAmount * @param expiration Request expiration date. */ export async function tokenToToken(server: string, signer: Signer, keyStore: KeyStore, contract: string, fee: number, otherPoolContract: string, sellAmount: number, buyAmount: number, expiration: Date): Promise<string> { //(pair %tokenToToken (pair (address :outputDexterContract) (pair (nat :minTokensBought) (address :owner))) (pair (address :to) (pair (nat :tokensSold) (timestamp :deadline)))) const parameters = `(Pair (Pair "${otherPoolContract}" (Pair ${buyAmount} "${keyStore.publicKeyHash}")) (Pair "${keyStore.publicKeyHash}" (Pair ${sellAmount} "${expiration.toISOString()}")))`; const nodeResult = await TezosNodeWriter.sendContractInvocationOperation(server, signer, keyStore, contract, 0, fee, DexterPoolExchangeOperationStorageLimit, 1_000_000, 'tokenToToken', parameters, TezosTypes.TezosParameterFormat.Michelson); return TezosContractUtils.clearRPCOperationGroupHash(nodeResult.operationGroupID); } /** * Approves a spender for a share of the liquidity balance on the given account. * * @param server Destination Tezos node. * @param signer * @param keyStore * @param contract * @param fee * @param spender * @param newAllowance * @param currentAllowance */ export async function approve(server: string, signer: Signer, keyStore: KeyStore, contract: string, fee: number, spender: string, newAllowance: number, currentAllowance: number): Promise<string> { //(pair %approve (address :spender) (pair (nat :allowance) (nat :currentAllowance))) const parameters = `(Pair "${spender}" (Pair ${newAllowance} ${currentAllowance}))`; const nodeResult = await TezosNodeWriter.sendContractInvocationOperation(server, signer, keyStore, contract, 0, fee, DexterPoolExchangeOperationStorageLimit, DexterPoolExchangeOperationGasLimit, 'approve', parameters, TezosTypes.TezosParameterFormat.Michelson); return TezosContractUtils.clearRPCOperationGroupHash(nodeResult.operationGroupID); } /** * Show pending applied operations against this contract in the mempool */ export async function previewTransactions() { // TODO } /** * Calculate the token requirement for the proposed XTZ deposit. * * @param xtzDeposit XTZ amount of the proposed transaction * @param tokenBalance Pool token balance * @param xtzBalance Pool XTZ balance * @return {number} Matching token balance for the proposed deposit */ export function calcTokenLiquidityRequirement(xtzDeposit: number, tokenBalance: number, xtzBalance: number): number { return bigInt(xtzDeposit).multiply(bigInt(tokenBalance)).divide(bigInt(xtzBalance)).toJSNumber(); } /** * XTZ/Token exchange rate for a given XTZ trade. * * @param xtzAmount Proposed XTZ deposit * @param tokenBalance Current token balance in the pool * @param xtzBalance Current XTZ balance in the pool */ export function getTokenExchangeRate(xtzAmount: number, tokenBalance: number, xtzBalance: number, xtzDecimals: number = 6) { const n = bigInt(xtzAmount).multiply(bigInt(tokenBalance)).multiply(bigInt(ExchangeMultiplier)); const d = bigInt(xtzBalance).multiply(bigInt(1000)).add(bigInt(xtzAmount).multiply(bigInt(ExchangeMultiplier))); const tokenAmount = n.divide(d); const dm = tokenAmount.divmod(bigInt(xtzAmount)); const f = dm.remainder.multiply(bigInt(10 ** xtzDecimals)).divide(bigInt(xtzAmount)); return { tokenAmount: tokenAmount.toJSNumber(), rate: parseFloat(`${dm.quotient.toJSNumber()}.${f.toJSNumber()}`) }; } /** * Token/XTZ exchange rate for a given token trade. * * @param tokenAmount Proposed token deposit * @param tokenBalance Current token balance in the pool * @param xtzBalance Current XTZ balance in the pool */ export function getXTZExchangeRate(tokenAmount: number, tokenBalance: number, xtzBalance: number, tokenDecimals: number = 6) { const n = bigInt(tokenAmount).multiply(bigInt(xtzBalance)).multiply(bigInt(ExchangeMultiplier)); const d = bigInt(tokenBalance).multiply(bigInt(1000)).add(bigInt(tokenAmount).multiply(bigInt(ExchangeMultiplier))) const xtzAmount = n.divide(d); const dm = xtzAmount.divmod(bigInt(tokenAmount)); const f = dm.remainder.multiply(bigInt(10 ** tokenDecimals)).divide(bigInt(tokenAmount)); return { xtzAmount: xtzAmount.toJSNumber(), rate: parseFloat(`${dm.quotient.toJSNumber()}.${f.toJSNumber()}`) }; } /** * Returns the amount of liquidity tokens a particular XTZ deposit would receive. * @param xtzDeposit * @param liquidityBalance * @param xtzBalance */ export function estimateLiquidityAmount(xtzDeposit: number, liquidityBalance: number, xtzBalance: number) { return bigInt(xtzDeposit).multiply(bigInt(liquidityBalance)).divide(bigInt(xtzBalance)).toJSNumber(); } /** * Estimates the cost of buying 1% share of the pool in terms of XTZ */ export function estimateShareCost(xtzBalance: number, tokenBalance: number, liquidityBalance: number): { xtzCost: number, tokenCost: number } { const xtzShare = bigInt(xtzBalance).divide(bigInt(99)).toJSNumber(); const tokenShare = calcTokenLiquidityRequirement(xtzShare, tokenBalance, xtzBalance); // TODO: use estimateLiquidityAmount return { xtzCost: xtzShare, tokenCost: tokenShare }; } }
the_stack
import { remove, createElement, closest, formatUnit, Browser, KeyboardEventArgs, extend } from '@syncfusion/ej2-base'; import { isNullOrUndefined, removeClass } from '@syncfusion/ej2-base'; import { DataManager, Query } from '@syncfusion/ej2-data'; import { IGrid, IRenderer, NotifyArgs, VirtualInfo, IModelGenerator, InterSection, RowSelectEventArgs } from '../base/interface'; import { Column } from '../models/column'; import { Row } from '../models/row'; import { dataReady, modelChanged, refreshVirtualBlock, contentReady } from '../base/constant'; import * as events from '../base/constant'; import { SentinelType, Offsets } from '../base/type'; import { RenderType, freezeMode, freezeTable } from '../base/enum'; import { ContentRender } from './content-renderer'; import { HeaderRender } from './header-renderer'; import { ServiceLocator } from '../services/service-locator'; import { InterSectionObserver, ScrollDirection } from '../services/intersection-observer'; import { RendererFactory } from '../services/renderer-factory'; import { VirtualRowModelGenerator } from '../services/virtual-row-model-generator'; import { isGroupAdaptive, ensureLastRow, ensureFirstRow, getEditedDataIndex, getTransformValues } from '../base/util'; import { setStyleAttribute } from '@syncfusion/ej2-base'; import { Grid } from '../base/grid'; import * as literals from '../base/string-literals'; import { VirtualFreezeRenderer } from './virtual-freeze-renderer'; /** * VirtualContentRenderer * * @hidden */ export class VirtualContentRenderer extends ContentRender implements IRenderer { private count: number; private maxPage: number; private maxBlock: number; private prevHeight: number = 0; /** @hidden */ public observer: InterSectionObserver; /** * @hidden */ public vgenerator: VirtualRowModelGenerator; /** @hidden */ public header: VirtualHeaderRenderer; /** @hidden */ public startIndex: number = 0; private preStartIndex: number = 0; private preEndIndex: number; /** @hidden */ public startColIndex: number; /** @hidden */ public endColIndex: number; private locator: ServiceLocator; private preventEvent: boolean = false; private actions: string[] = ['filtering', 'searching', 'grouping', 'ungrouping']; /** @hidden */ public content: HTMLElement; /** @hidden */ public movableContent: HTMLElement; /** @hidden */ public offsets: { [x: number]: number } = {}; private tmpOffsets: { [x: number]: number } = {}; /** @hidden */ public virtualEle: VirtualElementHandler = new VirtualElementHandler(); private offsetKeys: string[] = []; private isFocused: boolean = false; private isSelection: boolean = false; private selectedRowIndex: number; private isBottom: boolean = false; private rndrCount: number = 0; /** @hidden */ public activeKey: string; /** @hidden */ public rowIndex: number; /** @hidden */ public blzRowIndex: number; /** @hidden */ public blazorDataLoad: boolean; private cellIndex: number; private empty: string | number | Element = undefined; private isAdd: boolean; private isCancel: boolean = false; /** @hidden */ public requestType: string; private editedRowIndex: number; private requestTypes: string[] = ['beginEdit', 'cancel', 'delete', 'add', 'save']; private isNormaledit: boolean = this.parent.editSettings.mode === 'Normal'; /** @hidden */ public virtualData: Object = {}; private emptyRowData: Object = {}; private vfColIndex: number[] = []; private frzIdx: number = 1; private initialRowTop: number; private isContextMenuOpen: boolean = false; private selectRowIndex: number; private isSelectionScroll: boolean = false; private validationCheck: boolean = false; private validationCol: Column; constructor(parent: IGrid, locator?: ServiceLocator) { super(parent, locator); this.locator = locator; this.eventListener('on'); this.parent.on(events.columnVisibilityChanged, this.setVisible, this); this.vgenerator = <VirtualRowModelGenerator>this.generator; } public renderTable(): void { this.header = <VirtualHeaderRenderer>this.locator.getService<RendererFactory>('rendererFactory').getRenderer(RenderType.Header); super.renderTable(); this.virtualEle.table = <HTMLElement>this.getTable(); this.virtualEle.content = this.content = <HTMLElement>this.getPanel().querySelector('.' + literals.content); this.virtualEle.renderWrapper(<number>this.parent.height); this.virtualEle.renderPlaceHolder(); this.virtualEle.wrapper.style.position = 'absolute'; const debounceEvent: boolean = (this.parent.dataSource instanceof DataManager && !this.parent.dataSource.dataSource.offline); const opt: InterSection = { container: this.content, pageHeight: this.getBlockHeight() * 2, debounceEvent: debounceEvent, axes: this.parent.enableColumnVirtualization ? ['X', 'Y'] : ['Y'] }; this.observer = new InterSectionObserver(this.virtualEle.wrapper, opt); } public renderEmpty(tbody: HTMLElement): void { this.getTable().appendChild(tbody); this.virtualEle.adjustTable(0, 0); } public getReorderedFrozenRows(args: NotifyArgs): Row<Column>[] { const blockIndex: number[] = args.virtualInfo.blockIndexes; const colsIndex: number[] = args.virtualInfo.columnIndexes; const page: number = args.virtualInfo.page; args.virtualInfo.blockIndexes = [1, 2]; args.virtualInfo.page = 1; if (!args.renderMovableContent) { args.virtualInfo.columnIndexes = []; } const recordslength: number = this.parent.getCurrentViewRecords().length; const firstRecords: object[] = this.parent.renderModule.data.dataManager.dataSource.json.slice(0, recordslength); const virtualRows: Row<Column>[] = this.vgenerator.generateRows(firstRecords, args); args.virtualInfo.blockIndexes = blockIndex; args.virtualInfo.columnIndexes = colsIndex; args.virtualInfo.page = page; return virtualRows.splice(0, this.parent.frozenRows); } private scrollListener(scrollArgs: ScrollArg): void { this.scrollAfterEdit(); if (this.parent.enablePersistence) { this.parent.scrollPosition = scrollArgs.offset; } if (this.preventEvent || this.parent.isDestroyed) { this.preventEvent = false; return; } if (isNullOrUndefined(document.activeElement)) { this.isFocused = false; } else { this.isFocused = this.content === closest(document.activeElement, '.' + literals.content) || this.content === document.activeElement; } const info: SentinelType = scrollArgs.sentinel; const viewInfo: VirtualInfo = this.currentInfo = this.getInfoFromView(scrollArgs.direction, info, scrollArgs.offset); if (isGroupAdaptive(this.parent)) { if (viewInfo.blockIndexes && this.prevInfo.blockIndexes.toString() === viewInfo.blockIndexes.toString()) { return; } else { viewInfo.event = 'refresh-virtual-block'; if (!isNullOrUndefined(viewInfo.offsets)) { viewInfo.offsets.top = this.content.scrollTop; } this.parent.pageSettings.currentPage = viewInfo.page; this.parent.notify( viewInfo.event, { requestType: 'virtualscroll', virtualInfo: viewInfo, focusElement: scrollArgs.focusElement }); return; } } if (this.prevInfo && ((info.axis === 'Y' && this.prevInfo.blockIndexes.toString() === viewInfo.blockIndexes.toString()) || (info.axis === 'X' && this.prevInfo.columnIndexes.toString() === viewInfo.columnIndexes.toString()))) { if (Browser.isIE) { this.parent.hideSpinner(); } this.requestType = this.requestType === 'virtualscroll' ? this.empty as string : this.requestType; if (info.axis === 'Y') { this.restoreEdit(); } return; } this.parent.setColumnIndexesInView(this.parent.enableColumnVirtualization ? viewInfo.columnIndexes : []); this.parent.pageSettings.currentPage = viewInfo.loadNext && !viewInfo.loadSelf ? viewInfo.nextInfo.page : viewInfo.page; this.requestType = 'virtualscroll'; this.parent.notify(viewInfo.event, { requestType: 'virtualscroll', virtualInfo: viewInfo, focusElement: scrollArgs.focusElement }); } private block(blk: number): boolean { return this.vgenerator.isBlockAvailable(blk); } private getInfoFromView(direction: string, info: SentinelType, e: Offsets): VirtualInfo { let isBlockAdded: boolean = false; let tempBlocks: number[] = []; const infoType: VirtualInfo = { direction: direction, sentinelInfo: info, offsets: e, startIndex: this.preStartIndex, endIndex: this.preEndIndex }; infoType.page = this.getPageFromTop(e.top, infoType); infoType.blockIndexes = tempBlocks = this.vgenerator.getBlockIndexes(infoType.page); infoType.loadSelf = !this.vgenerator.isBlockAvailable(tempBlocks[infoType.block]); const blocks: number[] = this.ensureBlocks(infoType); if (this.activeKey === 'upArrow' && infoType.blockIndexes.toString() !== blocks.toString()) { // To avoid dupilcate row index problem in key focus support const newBlock: number = blocks[blocks.length - 1]; if (infoType.blockIndexes.indexOf(newBlock) === -1) { isBlockAdded = true; } } infoType.blockIndexes = blocks; infoType.loadNext = !blocks.filter((val: number) => tempBlocks.indexOf(val) === -1) .every(this.block.bind(this)); infoType.event = (infoType.loadNext || infoType.loadSelf) ? modelChanged : refreshVirtualBlock; infoType.nextInfo = infoType.loadNext ? { page: Math.max(1, infoType.page + (direction === 'down' ? 1 : -1)) } : {}; if (isBlockAdded) { infoType.blockIndexes = [infoType.blockIndexes[0] - 1, infoType.blockIndexes[0], infoType.blockIndexes[0] + 1]; } if (this.activeKey === 'downArrow') { const firstBlock: number = Math.ceil(this.rowIndex / this.getBlockSize()); if (firstBlock !== 1 && (infoType.blockIndexes[1] !== firstBlock || infoType.blockIndexes.length < 3)) { infoType.blockIndexes = [firstBlock - 1, firstBlock, firstBlock + 1]; } } infoType.columnIndexes = info.axis === 'X' ? this.vgenerator.getColumnIndexes() : this.parent.getColumnIndexesInView(); if (this.parent.enableColumnVirtualization && info.axis === 'X') { infoType.event = refreshVirtualBlock; } return infoType; } private setKeyboardNavIndex(): void { this.blazorDataLoad = true; if (this.activeKey === 'downArrow' || this.activeKey === 'upArrow') { this.blzRowIndex = this.activeKey === 'downArrow' ? this.rowIndex + 1 : this.rowIndex - 1; (document.activeElement as HTMLElement).blur(); } } public ensureBlocks(info: VirtualInfo): number[] { let index: number = info.blockIndexes[info.block]; let mIdx: number; const old: number = index; const max: Function = Math.max; let indexes: number[] = info.direction === 'down' ? [max(index, 1), ++index, ++index] : [max(index - 1, 1), index, index + 1]; if (this.parent.enableColumnVirtualization && this.parent.isFrozenGrid()) { // To avoid frozen content white space issue if (info.sentinelInfo.axis === 'X' || (info.sentinelInfo.axis === 'Y' && (info.page === this.prevInfo.page))) { indexes = this.prevInfo.blockIndexes; } } indexes = indexes.filter((val: number, ind: number) => indexes.indexOf(val) === ind); if (this.prevInfo.blockIndexes.toString() === indexes.toString()) { return indexes; } if (info.loadSelf || (info.direction === 'down' && this.isEndBlock(old))) { indexes = this.vgenerator.getBlockIndexes(info.page); } indexes.some((val: number, ind: number) => { const result: boolean = val === (isGroupAdaptive(this.parent) ? this.getGroupedTotalBlocks() : this.getTotalBlocks()); if (result) { mIdx = ind; } return result; }); if (mIdx !== undefined) { indexes = indexes.slice(0, mIdx + 1); if (info.block === 0 && indexes.length === 1 && this.vgenerator.isBlockAvailable(indexes[0] - 1)) { indexes = [indexes[0] - 1, indexes[0]]; } } return indexes; } // tslint:disable-next-line:max-func-body-length public appendContent(target: HTMLElement, newChild: DocumentFragment | HTMLElement, e: NotifyArgs): void { // currentInfo value will be used if there are multiple dom updates happened due to mousewheel const isFrozen: boolean = this.parent.isFrozenGrid(); const frzCols: number = this.parent.getFrozenColumns() || this.parent.getFrozenLeftColumnsCount(); const colVFtable: boolean = this.parent.enableColumnVirtualization && isFrozen; this.checkFirstBlockColIndexes(e); const info: VirtualInfo = e.virtualInfo.sentinelInfo && e.virtualInfo.sentinelInfo.axis === 'Y' && this.currentInfo.page && this.currentInfo.page !== e.virtualInfo.page ? this.currentInfo : e.virtualInfo; this.prevInfo = this.prevInfo || e.virtualInfo; let cBlock: number = (info.columnIndexes[0]) - 1; if (colVFtable && info.columnIndexes[0] === frzCols) { cBlock = (info.columnIndexes[0] - frzCols) - 1; } const cOffset: number = this.getColumnOffset(cBlock); let width: string; const blocks: number[] = info.blockIndexes; if (this.parent.groupSettings.columns.length) { this.refreshOffsets(); } if (this.parent.height === '100%') { this.parent.element.style.height = '100%'; } const vHeight: string | number = this.parent.height.toString().indexOf('%') < 0 ? this.content.getBoundingClientRect().height : this.parent.element.getBoundingClientRect().height; if (!this.requestTypes.some((value: string) => value === this.requestType)) { const translate: number = this.getTranslateY(this.content.scrollTop, <number>vHeight, info); this.virtualEle.adjustTable(colVFtable ? 0 : cOffset, translate); if (colVFtable) { this.virtualEle.adjustMovableTable(cOffset, 0); } } if (this.parent.enableColumnVirtualization) { this.header.virtualEle.adjustTable(colVFtable ? 0 : cOffset, 0); if (colVFtable) { this.header.virtualEle.adjustMovableTable(cOffset, 0); } } if (this.parent.enableColumnVirtualization) { const cIndex: number[] = info.columnIndexes; width = this.getColumnOffset(cIndex[cIndex.length - 1]) - this.getColumnOffset(cIndex[0] - 1) + ''; if (colVFtable) { this.header.virtualEle.setMovableWrapperWidth(width); } else { this.header.virtualEle.setWrapperWidth(width); } } if (colVFtable) { this.virtualEle.setMovableWrapperWidth(width, <boolean>Browser.isIE || Browser.info.name === 'edge'); } else { this.virtualEle.setWrapperWidth(width, <boolean>Browser.isIE || Browser.info.name === 'edge'); } if (!isNullOrUndefined(target.parentNode)) { remove(target); } let tbody: HTMLElement; if (isFrozen) { if (e.renderFrozenRightContent) { tbody = this.parent.getContent().querySelector('.e-frozen-right-content').querySelector( literals.tbody); } else if (!e.renderMovableContent) { tbody = this.parent.getFrozenVirtualContent().querySelector( literals.tbody); } else if (e.renderMovableContent) { tbody = this.parent.getMovableVirtualContent().querySelector( literals.tbody); } } else { tbody = this.parent.element.querySelector('.' + literals.content).querySelector( literals.tbody); } if (tbody) { remove(tbody); target = null; } const isReact: boolean = this.parent.isReact && !isNullOrUndefined(this.parent.rowTemplate); if (!isReact) { target = this.parent.createElement( literals.tbody, { attrs: { role: 'rowgroup' } }); target.appendChild(newChild); } else { target = newChild as HTMLElement; } if (this.parent.frozenRows && e.requestType === 'virtualscroll' && this.parent.pageSettings.currentPage === 1) { for (let i: number = 0; i < this.parent.frozenRows; i++) { target.children[0].remove(); } } if (isFrozen) { if (e.renderFrozenRightContent) { this.parent.getContent().querySelector('.e-frozen-right-content').querySelector('.' + literals.table).appendChild(target); this.requestType = this.requestType === 'virtualscroll' ? this.empty as string : this.requestType; } else if (!e.renderMovableContent) { this.parent.getFrozenVirtualContent().querySelector('.' + literals.table).appendChild(target); } else if (e.renderMovableContent) { this.parent.getMovableVirtualContent().querySelector('.' + literals.table).appendChild(target); if (this.parent.getFrozenMode() !== literals.leftRight) { this.requestType = this.requestType === 'virtualscroll' ? this.empty as string : this.requestType; } } if (this.vfColIndex.length) { e.virtualInfo.columnIndexes = info.columnIndexes = extend([], this.vfColIndex) as number[]; this.vfColIndex = e.renderMovableContent ? [] : this.vfColIndex; } } else { this.getTable().appendChild(target); this.requestType = this.requestType === 'virtualscroll' ? this.empty as string : this.requestType; } if (this.parent.groupSettings.columns.length) { if (!isGroupAdaptive(this.parent) && info.direction === 'up') { const blk: number = this.offsets[this.getTotalBlocks()] - this.prevHeight; this.preventEvent = true; const sTop: number = this.content.scrollTop; this.content.scrollTop = sTop + blk; } this.setVirtualHeight(); this.observer.setPageHeight(this.getOffset(blocks[blocks.length - 1]) - this.getOffset(blocks[0] - 1)); } this.prevInfo = info; if (this.isFocused && this.activeKey !== 'downArrow' && this.activeKey !== 'upArrow') { this.content.focus(); } const lastPage: number = Math.ceil(this.getTotalBlocks() / 2); if (this.isBottom) { this.isBottom = false; this.parent.getContent().firstElementChild.scrollTop = this.offsets[this.offsetKeys.length - 1]; } if ((this.parent.pageSettings.currentPage === lastPage) && blocks.length === 1) { this.isBottom = true; this.parent.getContent().firstElementChild.scrollTop = this.offsets[this.offsetKeys.length - 2]; } if (e.requestType === 'virtualscroll' && e.virtualInfo.sentinelInfo.axis === 'X') { this.parent.notify(events.autoCol, {}); } this.focusCell(e); this.restoreEdit(e); this.restoreAdd(e); this.ensureSelectedRowPosition(); this.validationScrollLeft(e, isFrozen); if (!this.initialRowTop) { const gridTop: number = this.parent.element.getBoundingClientRect().top; this.initialRowTop = this.parent.getRowByIndex(0).getBoundingClientRect().top - gridTop; } const tableName: freezeTable = (<{ tableName?: freezeTable }>e).tableName; const isLoaded: boolean = this.parent.getFrozenMode() === 'Left-Right' ? tableName === 'frozen-right' : tableName === 'movable'; if (!isFrozen || isLoaded) { this.vgenerator.startIndex = null; this.vgenerator.currentInfo = {}; this.vgenerator.includePrevPage = null; } } private validationScrollLeft(e: NotifyArgs, isFrozen: boolean): void { const left: number = this.parent.getFrozenColumns(); const table: freezeMode = this.parent.getFrozenMode(); const trigger: boolean = !isFrozen || e && (left || table === 'Left' || table === 'Right' ? e.renderMovableContent : e.renderFrozenRightContent); if (this.validationCheck && trigger) { if (this.validationCol) { const offset: number = this.vgenerator.cOffsets[(this.validationCol.index - this.parent.getVisibleFrozenColumns()) - 1]; this.validationCol = null; if (this.parent.isFrozenGrid()) { this.movableContent.scrollLeft = offset; } else { this.content.scrollLeft = offset; } } else { this.validationCheck = false; this.parent.editModule.editFormValidate(); } } } private ensureSelectedRowPosition(): void { if (!this.isSelection && this.isSelectionScroll && !isNullOrUndefined(this.selectRowIndex)) { this.isSelectionScroll = false; const row: Element = this.parent.getRowByIndex(this.selectRowIndex); if (row && !this.isRowInView(row)) { this.rowSelected({ rowIndex: this.selectRowIndex, row: row }, true); } } } private checkFirstBlockColIndexes(e: NotifyArgs): void { if (this.parent.enableColumnVirtualization && this.parent.isFrozenGrid() && e.virtualInfo.columnIndexes[0] === 0) { const indexes: number[] = []; const frozenCols: number = this.parent.getFrozenColumns() || this.parent.getFrozenLeftColumnsCount(); if (!e.renderMovableContent && e.virtualInfo.columnIndexes.length > frozenCols) { this.vfColIndex = e.virtualInfo.columnIndexes; for (let i: number = 0; i < frozenCols; i++) { indexes.push(i); } e.virtualInfo.columnIndexes = indexes; } else if (e.renderMovableContent) { if (!this.vfColIndex.length) { this.vfColIndex = extend([], e.virtualInfo.columnIndexes) as number[]; } e.virtualInfo.columnIndexes = extend([], this.vfColIndex) as number[]; e.virtualInfo.columnIndexes.splice(0, frozenCols); } } } // eslint-disable-next-line @typescript-eslint/no-unused-vars private focusCell(e: NotifyArgs): void { if (this.activeKey !== 'upArrow' && this.activeKey !== 'downArrow') { return; } const row: Element = this.parent.getRowByIndex(this.rowIndex); // eslint-disable-next-line @typescript-eslint/no-explicit-any const cell: any = (<{ cells?: HTMLElement[] }>row).cells[this.cellIndex]; cell.focus({ preventScroll: true }); this.parent.selectRow(parseInt(row.getAttribute(literals.ariaRowIndex), 10)); this.activeKey = this.empty as string; } private restoreEdit(e?: NotifyArgs): void { if (this.isNormaledit) { const left: number = this.parent.getFrozenColumns(); const isFrozen: boolean = e && this.parent.isFrozenGrid(); const table: freezeMode = this.parent.getFrozenMode(); const trigger: boolean = e && (left || table === 'Left' || table === 'Right' ? e.renderMovableContent : e.renderFrozenRightContent); if ((!isFrozen || (isFrozen && trigger)) && this.parent.editSettings.allowEditing && this.parent.editModule && !isNullOrUndefined(this.editedRowIndex)) { let row: HTMLTableRowElement = this.getRowByIndex(this.editedRowIndex) as HTMLTableRowElement; let content: Element = this.content; const keys: string[] = Object.keys(this.virtualData); const isXaxis: boolean = e && e.virtualInfo && e.virtualInfo.sentinelInfo.axis === 'X'; if (isFrozen && isXaxis) { row = this.parent.getMovableRowByIndex(this.editedRowIndex) as HTMLTableRowElement; content = this.movableContent; } if (keys.length && row && !content.querySelector('.' + literals.editedRow)) { const top: number = row.getBoundingClientRect().top; if (isXaxis || (top < this.content.offsetHeight && top > this.parent.getRowHeight())) { this.parent.isEdit = false; this.parent.editModule.startEdit(row); } } if (row && this.content.querySelector('.' + literals.editedRow) && !keys.length) { const rowData: Object = extend({}, this.getRowObjectByIndex(this.editedRowIndex)); this.virtualData = this.getVirtualEditedData(rowData); } } this.restoreAdd(e); } } private getVirtualEditedData(rowData: Object): Object { const editForms: Element[] = [].slice.call(this.parent.element.getElementsByClassName('e-gridform')); const isFormDestroyed: boolean = this.parent.editModule && this.parent.editModule.formObj && this.parent.editModule.formObj.isDestroyed; if (!isFormDestroyed) { for (let i: number = 0; i < editForms.length; i++) { rowData = this.parent.editModule.getCurrentEditedData(editForms[i], rowData); } } return rowData; } private restoreAdd(e?: NotifyArgs): void { const left: number = this.parent.getFrozenColumns(); const isFrozen: boolean = e && this.parent.isFrozenGrid(); const table: freezeMode = this.parent.getFrozenMode(); const isXaxis: boolean = e && e.virtualInfo && e.virtualInfo.sentinelInfo && e.virtualInfo.sentinelInfo.axis === 'X'; const startAdd: boolean = isXaxis && isFrozen ? !(this.parent.getMovableVirtualHeader().querySelector('.' + literals.addedRow) || this.parent.getMovableVirtualContent().querySelector('.' + literals.addedRow)) : !this.parent.element.querySelector('.' + literals.addedRow); const trigger: boolean = e && (left || table === 'Left' || table === 'Right' ? e.renderMovableContent : e.renderFrozenRightContent); if ((!isFrozen || (isFrozen && trigger)) && this.isNormaledit && this.isAdd && startAdd) { const isTop: boolean = this.parent.editSettings.newRowPosition === 'Top' && this.content.scrollTop < this.parent.getRowHeight(); const isBottom: boolean = this.parent.editSettings.newRowPosition === 'Bottom' && this.parent.pageSettings.currentPage === this.maxPage; if (isTop || isBottom) { this.parent.isEdit = false; this.parent.addRecord(); } } } protected onDataReady(e?: NotifyArgs): void { if (!isNullOrUndefined(e.count)) { this.count = e.count; this.maxPage = Math.ceil(e.count / this.parent.pageSettings.pageSize); } this.vgenerator.checkAndResetCache(e.requestType); if (['refresh', 'filtering', 'searching', 'grouping', 'ungrouping', 'reorder', undefined] .some((value: string) => { return e.requestType === value; })) { this.refreshOffsets(); } this.setVirtualHeight(); this.resetScrollPosition(e.requestType); } /** * @param {number} height - specifies the height * @returns {void} * @hidden */ // eslint-disable-next-line @typescript-eslint/no-unused-vars public setVirtualHeight(height?: number): void { const width: string = this.parent.enableColumnVirtualization ? this.getColumnOffset(this.parent.columns.length + this.parent.groupSettings.columns.length - 1) + 'px' : '100%'; if (this.parent.isFrozenGrid()) { let virtualHeightTemp: number = (this.parent.pageSettings.currentPage === 1 && Object.keys(this.offsets).length <= 2) ? this.offsets[1] : this.offsets[this.getTotalBlocks() - 2]; const scrollableElementHeight: number = this.content.clientHeight; virtualHeightTemp = virtualHeightTemp > scrollableElementHeight ? virtualHeightTemp : 0; // To overcome the white space issue in last page (instead of position absolute) this.virtualEle.setVirtualHeight(virtualHeightTemp, width); } else { const virtualHeight: number = (this.offsets[isGroupAdaptive(this.parent) ? this.getGroupedTotalBlocks() : this.getTotalBlocks()]); this.virtualEle.setVirtualHeight(virtualHeight, width); } if (this.parent.enableColumnVirtualization) { this.header.virtualEle.setVirtualHeight(1, width); if (this.parent.isFrozenGrid()) { this.virtualEle.setMovableVirtualHeight(1, width); this.header.virtualEle.setMovableVirtualHeight(1, width); } } } private getPageFromTop(sTop: number, info: VirtualInfo): number { const total: number = (isGroupAdaptive(this.parent)) ? this.getGroupedTotalBlocks() : this.getTotalBlocks(); let page: number = 0; this.offsetKeys.some((offset: string) => { let iOffset: number = Number(offset); const border: boolean = sTop <= this.offsets[offset] || (iOffset === total && sTop > this.offsets[offset]); if (border) { if (this.offsetKeys.length % 2 !== 0 && iOffset.toString() === this.offsetKeys[this.offsetKeys.length - 2] && sTop <= this.offsets[this.offsetKeys.length - 1]) { iOffset = iOffset + 1; } info.block = iOffset % 2 === 0 ? 1 : 0; page = Math.max(1, Math.min(this.vgenerator.getPage(iOffset), this.maxPage)); } return border; }); return page; } protected getTranslateY(sTop: number, cHeight: number, info?: VirtualInfo, isOnenter?: boolean): number { if (info === undefined) { info = { page: this.getPageFromTop(sTop, {}) }; info.blockIndexes = this.vgenerator.getBlockIndexes(info.page); } const block: number = (info.blockIndexes[0] || 1) - 1; const translate: number = this.getOffset(block); const endTranslate: number = this.getOffset(info.blockIndexes[info.blockIndexes.length - 1]); if (isOnenter) { info = this.prevInfo; } let result: number = translate > sTop ? this.getOffset(block - 1) : endTranslate < (sTop + cHeight) ? this.getOffset(block + 1) : translate; const blockHeight: number = this.offsets[info.blockIndexes[info.blockIndexes.length - 1]] - this.tmpOffsets[info.blockIndexes[0]]; const totalBlocks: number = isGroupAdaptive(this.parent) ? this.getGroupedTotalBlocks() : this.getTotalBlocks(); if (result + blockHeight > this.offsets[totalBlocks]) { result -= (result + blockHeight) - this.offsets[totalBlocks]; } return result; } public getOffset(block: number): number { return Math.min(this.offsets[block] | 0, this.offsets[this.maxBlock] | 0); } private onEntered(): Function { return (element: HTMLElement, current: SentinelType, direction: string, e: Offsets, isWheel: boolean, check: boolean) => { if (Browser.isIE && !isWheel && check && !this.preventEvent) { this.parent.showSpinner(); } const colVFtable: boolean = this.parent.enableColumnVirtualization && this.parent.isFrozenGrid(); const xAxis: boolean = current.axis === 'X'; const top: number = this.prevInfo.offsets ? this.prevInfo.offsets.top : null; const height: number = this.content.getBoundingClientRect().height; let x: number = this.getColumnOffset(xAxis ? this.vgenerator.getColumnIndexes()[0] - 1 : this.prevInfo.columnIndexes[0] - 1); if (xAxis && !colVFtable) { const idx: number = Object.keys(this.vgenerator.cOffsets).length - this.prevInfo.columnIndexes.length; const maxLeft: number = this.vgenerator.cOffsets[idx - 1]; x = x > maxLeft ? maxLeft : x; //TODO: This fix horizontal scrollbar jumping issue in column virtualization. } const y: number = this.getTranslateY(e.top, height, xAxis && top === e.top ? this.prevInfo : undefined, true); this.virtualEle.adjustTable(colVFtable ? 0 : x, Math.min(y, this.offsets[this.maxBlock])); if (colVFtable) { this.virtualEle.adjustMovableTable(x, 0); } if (this.parent.enableColumnVirtualization) { this.header.virtualEle.adjustTable(colVFtable ? 0 : x, 0); if (colVFtable) { this.header.virtualEle.adjustMovableTable(x, 0); } } }; } private dataBound(): void { this.parent.notify(events.refreshVirtualFrozenHeight, {}); if (this.isSelection && this.activeKey !== 'upArrow' && this.activeKey !== 'downArrow') { this.parent.selectRow(this.selectedRowIndex); } else { this.activeKey = this.empty as string; } } private rowSelected(args: RowSelectEventArgs, isSelection?: boolean): void { if ((this.isSelection || isSelection) && !this.isLastBlockRow(args.rowIndex)) { const transform: { width: number, height: number } = getTransformValues(this.content.firstElementChild); const gridTop: number = this.parent.element.getBoundingClientRect().top; const rowTop: number = (args.row as HTMLElement).getBoundingClientRect().top - gridTop; const height: number = this.content.getBoundingClientRect().height; const isBottom: boolean = height < rowTop; const remainHeight: number = isBottom ? rowTop - height : this.initialRowTop - rowTop; let translateY: number = isBottom ? transform.height - remainHeight : transform.height + remainHeight; this.virtualEle.adjustTable(transform.width, translateY); const lastRowTop: number = this.content.querySelector('tbody').lastElementChild.getBoundingClientRect().top - gridTop; if (lastRowTop < height) { translateY = translateY + (height - ((args.row as HTMLElement).getBoundingClientRect().top - gridTop)); this.virtualEle.adjustTable(transform.width, translateY - (this.parent.getRowHeight() / 2)); } } this.isSelection = false; } private isLastBlockRow(index: number): boolean { const scrollEle: Element = this.parent.getContent().firstElementChild; const visibleRowCount: number = Math.floor((scrollEle as HTMLElement).offsetHeight / this.parent.getRowHeight()) - 1; const startIdx: number = (this.maxPage * this.parent.pageSettings.pageSize) - visibleRowCount; return index >= startIdx; } private refreshMaxPage(): void { if (this.parent.groupSettings.columns.length && this.parent.vcRows.length) { this.maxPage = Math.ceil(this.parent.vcRows.length / this.parent.pageSettings.pageSize); } } private setVirtualPageQuery(args: { query: Query, skipPage: boolean }): void { const row: Element = this.parent.getContent().querySelector('.e-row'); if (row && this.parent.isManualRefresh && this.currentInfo.blockIndexes && this.currentInfo.blockIndexes.length === 3) { this.vgenerator.startIndex = parseInt(row.getAttribute('aria-rowindex'), 10); this.vgenerator.currentInfo = extend({}, this.currentInfo); this.vgenerator.currentInfo.blockIndexes = this.currentInfo.blockIndexes.slice(); const includePrevPage: boolean = this.vgenerator.includePrevPage = this.currentInfo.blockIndexes[0] % 2 === 0; if (includePrevPage) { this.vgenerator.startIndex = this.vgenerator.startIndex - this.getBlockSize(); this.vgenerator.currentInfo.blockIndexes.unshift(this.currentInfo.blockIndexes[0] - 1); } else { this.vgenerator.currentInfo.blockIndexes.push(this.currentInfo.blockIndexes[this.currentInfo.blockIndexes.length - 1] + 1); } const skip: number = (this.vgenerator.currentInfo.blockIndexes[0] - 1) * this.getBlockSize(); const take: number = this.vgenerator.currentInfo.blockIndexes.length * this.getBlockSize(); args.query.skip(skip); args.query.take(take); args.skipPage = true; } } public eventListener(action: string): void { this.parent[action](dataReady, this.onDataReady, this); this.parent.addEventListener(events.dataBound, this.dataBound.bind(this)); this.parent.addEventListener(events.actionBegin, this.actionBegin.bind(this)); this.parent.addEventListener(events.actionComplete, this.actionComplete.bind(this)); this.parent.addEventListener(events.rowSelected, this.rowSelected.bind(this)); this.parent[action](refreshVirtualBlock, this.refreshContentRows, this); this.parent[action](events.selectVirtualRow, this.selectVirtualRow, this); this.parent[action](events.virtaulCellFocus, this.virtualCellFocus, this); this.parent[action](events.virtualScrollEditActionBegin, this.editActionBegin, this); this.parent[action](events.virtualScrollAddActionBegin, this.addActionBegin, this); this.parent[action](events.virtualScrollEdit, this.restoreEdit, this); this.parent[action](events.virtualScrollEditSuccess, this.editSuccess, this); this.parent[action](events.refreshVirtualCache, this.refreshCache, this); this.parent[action](events.editReset, this.resetIsedit, this); this.parent[action](events.getVirtualData, this.getVirtualData, this); this.parent[action](events.virtualScrollEditCancel, this.editCancel, this); this.parent[action](events.refreshVirtualMaxPage, this.refreshMaxPage, this); this.parent[action](events.setVirtualPageQuery, this.setVirtualPageQuery, this); this.parent[action](events.selectRowOnContextOpen, this.selectRowOnContextOpen, this); this.parent[action](events.resetVirtualFocus, this.resetVirtualFocus, this); this.parent[action](events.refreshVirtualEditFormCells, this.refreshCells, this); this.parent[action](events.scrollToEdit, this.scrollToEdit, this); const event: string[] = this.actions; for (let i: number = 0; i < event.length; i++) { this.parent[action](`${event[i]}-begin`, this.onActionBegin, this); } const fn: Function = () => { this.observer.observe((scrollArgs: ScrollArg) => this.scrollListener(scrollArgs), this.onEntered()); const gObj: IGrid = this.parent; if (gObj.enablePersistence && gObj.scrollPosition) { this.content.scrollTop = gObj.scrollPosition.top; const scrollValues: ScrollArg = { direction: 'down', sentinel: this.observer.sentinelInfo.down, offset: gObj.scrollPosition, focusElement: gObj.element }; this.scrollListener(scrollValues); if (gObj.enableColumnVirtualization) { this.content.scrollLeft = gObj.scrollPosition.left; } } this.parent.off(contentReady, fn); }; this.parent.on(contentReady, fn, this); } private scrollToEdit(col: Column): void { const isFrozen: boolean = this.parent.isFrozenGrid(); let allowScroll: boolean = true; this.validationCheck = true; if (this.isAdd && this.content.scrollTop > 0) { allowScroll = false; const keys: string[] = Object.keys(this.offsets); this.content.scrollTop = this.parent.editSettings.newRowPosition === 'Top' ? 0 : this.offsets[keys.length - 1]; } const row: Element = this.parent.getRowByIndex(this.editedRowIndex); if (!row && !isNullOrUndefined(this.editedRowIndex)) { if (!row || !this.isRowInView(row)) { const rowIndex: number = this.parent.getRowHeight(); const scrollTop: number = this.editedRowIndex * rowIndex; if (!isNullOrUndefined(scrollTop)) { allowScroll = false; this.content.scrollTop = scrollTop; } } } if (col && allowScroll) { let offset: number = this.vgenerator.cOffsets[(col.index - this.parent.getVisibleFrozenColumns()) - 1]; if (!this.parent.enableColumnVirtualization) { const header: Element = this.parent.getHeaderContent().querySelector('.e-headercelldiv[e-mappinguid="' + col.uid + '"]'); offset = isFrozen ? (header.parentElement as HTMLElement).offsetLeft - (this.parent.getFrozenVirtualHeader() as HTMLElement).offsetWidth : (header.parentElement as HTMLElement).offsetLeft; } if (isFrozen) { this.parent.getMovableVirtualContent().scrollLeft = this.parent.enableRtl ? -Math.abs(offset) : offset; } else { this.content.scrollLeft = this.parent.enableRtl ? -Math.abs(offset) : offset; } } if (col && !allowScroll) { this.validationCol = col; } } private refreshCells(rowObj: Row<Column>): void { rowObj.cells = this.vgenerator.generateCells(rowObj.foreignKeyData); } private resetVirtualFocus(e: { isCancel: boolean }): void { this.isCancel = e.isCancel; } /** * @param {Object} data - specifies the data * @param {Object} data.virtualData -specifies the data * @param {boolean} data.isAdd - specifies isAdd * @param {boolean} data.isCancel - specifies boolean in cancel * @param {boolean} data.isScroll - specifies boolean for scroll * @returns {void} * @hidden */ public getVirtualData(data: { virtualData: Object, isAdd: boolean, isCancel: boolean, isScroll: boolean }): void { if (this.isNormaledit) { const error: Element = this.parent.element.querySelector('.e-griderror:not([style*="display: none"])'); const keys: string[] = Object.keys(this.virtualData); data.isScroll = keys.length !== 0 && this.currentInfo.sentinelInfo && this.currentInfo.sentinelInfo.axis === 'X'; if (error) { return; } this.virtualData = keys.length ? this.virtualData : data.virtualData; this.getVirtualEditedData(this.virtualData); data.virtualData = this.virtualData; data.isAdd = this.isAdd; data.isCancel = this.isCancel; } } private selectRowOnContextOpen(args: { isOpen: boolean }): void { this.isContextMenuOpen = args.isOpen; } private editCancel(args: { data: Object }): void { const dataIndex: number = getEditedDataIndex(this.parent, args.data); if (!isNullOrUndefined(dataIndex)) { args.data = this.parent.getCurrentViewRecords()[dataIndex]; } } private editSuccess(args?: EditArgs): void { if (this.isNormaledit) { if (!this.isAdd && args.data) { this.updateCurrentViewData(args.data); } this.isAdd = false; } } private updateCurrentViewData(data: Object): void { const dataIndex: number = getEditedDataIndex(this.parent, data); if (!isNullOrUndefined(dataIndex)) { this.parent.getCurrentViewRecords()[dataIndex] = data; } } private actionBegin(args: NotifyArgs): void { if (args.requestType !== 'virtualscroll') { this.requestType = args.requestType; } if (!args.cancel) { this.parent.notify(events.refreshVirtualFrozenRows, args); } } private virtualCellFocus(e: KeyboardEventArgs): void { // To decide the action (select or scroll), when using arrow keys for cell focus const ele: Element = document.activeElement; if (ele.classList.contains(literals.rowCell) && e && (e.action === 'upArrow' || e.action === 'downArrow')) { let rowIndex: number = parseInt(ele.parentElement.getAttribute(literals.ariaRowIndex), 10); if (e && (e.action === 'downArrow' || e.action === 'upArrow')) { const scrollEle: Element = this.parent.getContent().firstElementChild; if (e.action === 'downArrow') { rowIndex += 1; } else { rowIndex -= 1; } this.rowIndex = rowIndex; this.cellIndex = parseInt(ele.getAttribute(literals.ariaColIndex), 10); const row: Element = this.parent.getRowByIndex(rowIndex); const page: number = this.parent.pageSettings.currentPage; const visibleRowCount: number = Math.floor((scrollEle as HTMLElement).offsetHeight / this.parent.getRowHeight()) - 1; let emptyRow: boolean = false; if (isNullOrUndefined(row)) { emptyRow = true; if ((e.action === 'downArrow' && page === this.maxPage - 1) || (e.action === 'upArrow' && page === 1)) { emptyRow = false; } } if (emptyRow || (ensureLastRow(row, this.parent) && e.action === 'downArrow') || (ensureFirstRow(row, this.parent.getRowHeight() * 2) && e.action === 'upArrow')) { this.activeKey = e.action; scrollEle.scrollTop = e.action === 'downArrow' ? (rowIndex - visibleRowCount) * this.parent.getRowHeight() : rowIndex * this.parent.getRowHeight(); } else { this.activeKey = this.empty as string; } this.parent.selectRow(rowIndex); } } } private editActionBegin(e: { data: Object, index: number, isScroll: boolean }): void { this.editedRowIndex = e.index; const rowData: Object = extend({}, this.getRowObjectByIndex(e.index)); const keys: string[] = Object.keys(this.virtualData); e.data = keys.length ? this.virtualData : rowData; e.isScroll = keys.length !== 0 && this.currentInfo.sentinelInfo && this.currentInfo.sentinelInfo.axis === 'X'; } private refreshCache(args: { data: Object }): void { const block: number = Math.ceil((this.editedRowIndex + 1) / this.getBlockSize()); const index: number = this.editedRowIndex - ((block - 1) * this.getBlockSize()); this.vgenerator.cache[block][index].data = args.data; if (this.vgenerator.movableCache[block]) { this.vgenerator.movableCache[block][index].data = args.data; } if (this.vgenerator.frozenRightCache[block]) { this.vgenerator.frozenRightCache[block][index].data = args.data; } } private actionComplete(args: NotifyArgs): void { if (!this.parent.enableVirtualization) { return; } const editRequestTypes: string[] = ['delete', 'save', 'cancel']; const dataActionRequestTypes: string[] = ['sorting', 'filtering', 'grouping', 'refresh', 'searching', 'ungrouping', 'reorder']; if (editRequestTypes.some((value: string) => value === args.requestType)) { this.refreshOffsets(); if (this.parent.isFrozenGrid()) { this.vgenerator.refreshColOffsets(); (this.parent.contentModule as VirtualFreezeRenderer).virtualRenderer.virtualEle.setVirtualHeight(); } else { this.refreshVirtualElement(); } } if (this.isNormaledit && (dataActionRequestTypes.some((value: string) => value === args.requestType) || editRequestTypes.some((value: string) => value === args.requestType))) { this.isCancel = true; this.isAdd = false; this.editedRowIndex = this.empty as number; this.virtualData = {}; if (this.parent.editModule) { this.parent.editModule.editModule.previousData = undefined; } } if (this.parent.enableColumnVirtualization && args.requestType as string === 'filterafteropen' && this.currentInfo.columnIndexes && this.currentInfo.columnIndexes[0] > 0) { (this.parent as Grid).resetFilterDlgPosition((<{ columnName?: string }>args).columnName); } } private resetIsedit(): void { if (this.parent.enableVirtualization && this.isNormaledit) { if ((this.parent.editSettings.allowEditing && Object.keys(this.virtualData).length) || (this.parent.editSettings.allowAdding && this.isAdd)) { this.parent.isEdit = true; } } } private scrollAfterEdit(): void { if (this.parent.editModule && this.parent.editSettings.allowEditing && this.isNormaledit) { if (this.parent.element.querySelector('.e-gridform')) { const editForm: Element = this.parent.element.querySelector('.' + literals.editedRow); const addForm: Element = this.parent.element.querySelector('.' + literals.addedRow); if (editForm || addForm) { const rowData: Object = editForm ? extend({}, this.getRowObjectByIndex(this.editedRowIndex)) : extend({}, this.emptyRowData); const keys: string[] = Object.keys(this.virtualData); this.virtualData = keys.length ? this.getVirtualEditedData(this.virtualData) : this.getVirtualEditedData(rowData); } } } } private createEmptyRowdata(): void { (<{ columnModel?: Column[] }>this.parent).columnModel.filter((e: Column) => { this.emptyRowData[e.field] = this.empty; }); } private addActionBegin(args: { startEdit: boolean }): void { if (this.isNormaledit) { if (!Object.keys(this.emptyRowData).length) { this.createEmptyRowdata(); } this.isAdd = true; const page: number = this.parent.pageSettings.currentPage; if (!this.parent.frozenRows && this.content.scrollTop > 0 && this.parent.editSettings.newRowPosition === 'Top') { this.isAdd = true; this.onActionBegin(); args.startEdit = false; this.content.scrollTop = 0; } if (page < this.maxPage - 1 && this.parent.editSettings.newRowPosition === 'Bottom') { this.isAdd = true; this.parent.setProperties({ pageSettings: { currentPage: this.maxPage - 1 } }, true); args.startEdit = false; this.content.scrollTop = this.offsets[this.offsetKeys.length]; } } } /** * @param {number} index - specifies the index * @returns {Object} returns the object * @hidden */ public getRowObjectByIndex(index: number): Object { const data: Object = this.getRowCollection(index, false, true); return data; } public getBlockSize(): number { return this.parent.pageSettings.pageSize >> 1; } public getBlockHeight(): number { return this.getBlockSize() * this.parent.getRowHeight(); } public isEndBlock(index: number): boolean { const totalBlocks: number = isGroupAdaptive(this.parent) ? this.getGroupedTotalBlocks() : this.getTotalBlocks(); return index >= totalBlocks || index === totalBlocks - 1; } public getGroupedTotalBlocks(): number { const rows: Object[] = this.parent.vcRows; return Math.floor((rows.length / this.getBlockSize()) < 1 ? 1 : rows.length / this.getBlockSize()); } public getTotalBlocks(): number { return Math.ceil(this.count / this.getBlockSize()); } public getColumnOffset(block: number): number { return this.vgenerator.cOffsets[block] | 0; } public getModelGenerator(): IModelGenerator<Column> { return new VirtualRowModelGenerator(this.parent); } private resetScrollPosition(action: string): void { if (this.actions.some((value: string) => value === action)) { this.preventEvent = this.content.scrollTop !== 0; this.content.scrollTop = 0; } if (action !== 'virtualscroll') { this.isAdd = false; } } // eslint-disable-next-line @typescript-eslint/no-unused-vars private onActionBegin(e?: NotifyArgs): void { //Update property silently.. this.parent.setProperties({ pageSettings: { currentPage: 1 } }, true); } public getRows(): Row<Column>[] { return this.vgenerator.getRows(); } public getRowByIndex(index: number): Element { let row: Element; if (isGroupAdaptive(this.parent)) { row = this.parent.getDataRows()[index]; } else if (this.prevInfo) { row = this.getRowCollection(index, false) as Element; } return row; } public getMovableVirtualRowByIndex(index: number): Element { return this.getRowCollection(index, true) as Element; } public getFrozenRightVirtualRowByIndex(index: number): Element { return this.getRowCollection(index, false, false, true) as Element; } public getRowCollection(index: number, isMovable: boolean, isRowObject?: boolean, isFrozenRight?: boolean): Element | Object { const prev: number[] = this.prevInfo.blockIndexes; let startIdx: number = (prev[0] - 1) * this.getBlockSize(); let rowCollection: Element[] = isMovable ? this.parent.getMovableDataRows() : this.parent.getDataRows(); rowCollection = isFrozenRight ? this.parent.getFrozenRightDataRows() : rowCollection; let collection: Element[] | Object[] = isRowObject ? this.parent.getCurrentViewRecords() : rowCollection; if (isRowObject && this.parent.allowGrouping && this.parent.groupSettings.columns.length) { startIdx = parseInt(this.parent.getRows()[0].getAttribute(literals.ariaRowIndex), 10); collection = collection.filter((m: object) => { return isNullOrUndefined((<{items?: object }>m).items); }); } let selectedRow: Element | Object = collection[index - startIdx]; if (this.parent.frozenRows && this.parent.pageSettings.currentPage > 1) { if (!isRowObject) { selectedRow = index <= this.parent.frozenRows ? rowCollection[index] : rowCollection[(index - startIdx) + this.parent.frozenRows]; } else { selectedRow = index <= this.parent.frozenRows ? this.parent.getRowsObject()[index].data : selectedRow; } } return selectedRow; } public getVirtualRowIndex(index: number): number { const prev: number[] = this.prevInfo.blockIndexes; const startIdx: number = (prev[0] - 1) * this.getBlockSize(); return startIdx + index; } /** * @returns {void} * @hidden */ public refreshOffsets(): void { const gObj: IGrid = this.parent; let row: number = 0; const bSize: number = this.getBlockSize(); const total: number = isGroupAdaptive(this.parent) ? this.getGroupedTotalBlocks() : this.getTotalBlocks(); this.prevHeight = this.offsets[total]; this.maxBlock = total % 2 === 0 ? total - 2 : total - 1; this.offsets = {}; //Row offset update // eslint-disable-next-line prefer-spread const blocks: number[] = Array.apply(null, Array(total)).map(() => ++row); for (let i: number = 0; i < blocks.length; i++) { const tmp: number = (this.vgenerator.cache[blocks[i]] || []).length; const rem: number = !isGroupAdaptive(this.parent) ? this.count % bSize : (gObj.vcRows.length % bSize); const size: number = !isGroupAdaptive(this.parent) && blocks[i] in this.vgenerator.cache ? tmp * this.parent.getRowHeight() : rem && blocks[i] === total ? rem * this.parent.getRowHeight() : this.getBlockHeight(); // let size: number = this.parent.groupSettings.columns.length && block in this.vgenerator.cache ? // tmp * getRowHeight() : this.getBlockHeight(); this.offsets[blocks[i]] = (this.offsets[blocks[i] - 1] | 0) + size; this.tmpOffsets[blocks[i]] = this.offsets[blocks[i] - 1] | 0; } this.offsetKeys = Object.keys(this.offsets); if (isGroupAdaptive(this.parent)) { this.parent.vGroupOffsets = this.offsets; } //Column offset update if (this.parent.enableColumnVirtualization) { this.vgenerator.refreshColOffsets(); } } public refreshVirtualElement(): void { this.vgenerator.refreshColOffsets(); this.setVirtualHeight(); } public setVisible(columns?: Column[]): void { const gObj: IGrid = this.parent; const frozenCols: number = this.parent.getFrozenColumns(); let fcntColGrp: HTMLCollection; let mcntColGrp: HTMLCollection; if (frozenCols) { fcntColGrp = [].slice.call(this.parent.getFrozenVirtualContent().querySelectorAll('col')); mcntColGrp = [].slice.call(this.parent.getMovableVirtualContent().querySelectorAll('col')); } let rows: Row<Column>[] = []; rows = <Row<Column>[]>this.getRows(); let testRow: Row<Column>; rows.some((r: Row<Column>) => { if (r.isDataRow) { testRow = r; } return r.isDataRow; }); let isRefresh: boolean = true; if (!gObj.groupSettings.columns.length && testRow) { isRefresh = false; } let tr: Object = gObj.getDataRows(); for (let c: number = 0, clen: number = columns.length; c < clen; c++) { const column: Column = columns[c]; let idx: number = gObj.getNormalizedColumnIndex(column.uid); const displayVal: string = column.visible === true ? '' : 'none'; let colGrp: HTMLCollection; if (fcntColGrp && mcntColGrp) { if (idx >= frozenCols) { colGrp = mcntColGrp; tr = this.parent.getMovableRows(); idx = idx - frozenCols; } else { colGrp = fcntColGrp; } } else { colGrp = this.getColGroup().children; } if (idx !== -1 && testRow && idx < testRow.cells.length) { setStyleAttribute(colGrp[idx] as HTMLElement, { 'display': displayVal }); } if (!isRefresh) { let width: number; if (column.width) { if (column.visible) { width = this.virtualEle.wrapper.offsetWidth + parseInt(column.width.toString(), 10); } else { width = this.virtualEle.wrapper.offsetWidth - parseInt(column.width.toString(), 10); } } if (width > gObj.width) { this.setDisplayNone(tr, idx, displayVal, rows); if (this.parent.enableColumnVirtualization) { this.virtualEle.setWrapperWidth(width + ''); } this.refreshVirtualElement(); } else { isRefresh = true; } } if (!this.parent.invokedFromMedia && column.hideAtMedia) { this.parent.updateMediaColumns(column); } this.parent.invokedFromMedia = false; } if (isRefresh || frozenCols) { this.refreshContentRows({ requestType: 'refresh' }); } else { this.parent.notify(events.partialRefresh, { rows: rows, args: { isFrozen: false, rows: rows } }); } } private selectVirtualRow(args: { selectedIndex: number, isAvailable: boolean }): void { args.isAvailable = args.selectedIndex < this.count; if (args.isAvailable && !this.isContextMenuOpen && this.activeKey !== 'upArrow' && this.activeKey !== 'downArrow' && !this.isSelection && !this.requestTypes.some((value: string) => value === this.requestType) && !this.parent.selectionModule.isInteracted) { const selectedRow: Element = this.parent.getRowByIndex(args.selectedIndex); const rowHeight: number = this.parent.getRowHeight(); if (!selectedRow || !this.isRowInView(selectedRow)) { this.isSelection = true; this.selectedRowIndex = args.selectedIndex; const scrollTop: number = (args.selectedIndex + 1) * rowHeight; if (!isNullOrUndefined(scrollTop)) { const direction: ScrollDirection = this.content.scrollTop < scrollTop ? 'down' : 'up'; this.selectRowIndex = args.selectedIndex; this.content.scrollTop = scrollTop; this.isSelectionScroll = this.observer.check(direction); } } } if (this.parent.isFrozenGrid() && this.requestType) { if (this.parent.getTablesCount() === this.frzIdx) { this.requestType = this.empty as string; this.frzIdx = 1; } else { this.frzIdx++; } } else { this.requestType = this.empty as string; } } private isRowInView(row: Element): boolean { const top: number = row.getBoundingClientRect().top; const bottom: number = row.getBoundingClientRect().bottom; return (top >= this.content.getBoundingClientRect().top && bottom <= this.content.getBoundingClientRect().bottom); } } /** * @hidden */ export class VirtualHeaderRenderer extends HeaderRender implements IRenderer { public virtualEle: VirtualElementHandler = new VirtualElementHandler(); /** @hidden */ public gen: VirtualRowModelGenerator; public movableTbl: Element; private isMovable: boolean = false; constructor(parent: IGrid, locator: ServiceLocator) { super(parent, locator); this.gen = new VirtualRowModelGenerator(this.parent); this.parent.on(events.columnVisibilityChanged, this.setVisible, this); this.parent.on(refreshVirtualBlock, (e?: NotifyArgs) => e.virtualInfo.sentinelInfo.axis === 'X' ? this.refreshUI() : null, this); } public renderTable(): void { this.gen.refreshColOffsets(); this.parent.setColumnIndexesInView(this.gen.getColumnIndexes(<HTMLElement>this.getPanel().querySelector('.' + literals.headerContent))); super.renderTable(); this.virtualEle.table = <HTMLElement>this.getTable(); this.virtualEle.content = <HTMLElement>this.getPanel().querySelector('.' + literals.headerContent); this.virtualEle.content.style.position = 'relative'; this.virtualEle.renderWrapper(); this.virtualEle.renderPlaceHolder('absolute'); } public appendContent(table: Element): void { if (!this.isMovable) { this.virtualEle.wrapper.appendChild(table); } else { this.virtualEle.movableWrapper.appendChild(table); this.isMovable = false; } } public refreshUI(): void { this.isMovable = this.parent.isFrozenGrid(); this.setFrozenTable(this.parent.getMovableVirtualContent()); this.gen.refreshColOffsets(); this.parent.setColumnIndexesInView(this.gen.getColumnIndexes(<HTMLElement>this.getPanel().querySelector('.' + literals.headerContent))); super.refreshUI(); this.setFrozenTable(this.parent.getFrozenVirtualContent()); } public setVisible(columns?: Column[]): void { const gObj: IGrid = this.parent; let displayVal: string; let idx: number; let needFullRefresh: boolean; const frozenCols: number = this.parent.getFrozenColumns(); let fhdrColGrp: HTMLCollection; let mhdrColGrp: HTMLCollection; if (frozenCols) { fhdrColGrp = [].slice.call(this.parent.getFrozenVirtualHeader().querySelectorAll('col')); mhdrColGrp = [].slice.call(this.parent.getMovableVirtualHeader().querySelectorAll('col')); } for (let c: number = 0, clen: number = columns.length; c < clen; c++) { const column: Column = columns[c]; idx = gObj.getNormalizedColumnIndex(column.uid); displayVal = column.visible ? '' : 'none'; let colGrp: HTMLCollection; if (fhdrColGrp && mhdrColGrp) { if (idx >= frozenCols) { colGrp = mhdrColGrp; idx = idx - frozenCols; } else { colGrp = fhdrColGrp; } } else { colGrp = this.getColGroup().children; } setStyleAttribute(<HTMLElement>colGrp[idx], { 'display': displayVal }); if (gObj.enableColumnVirtualization && !gObj.groupSettings.columns.length) { let tablewidth: number; if (column.visible) { tablewidth = this.virtualEle.wrapper.offsetWidth + parseInt(column.width.toString(), 10); } else { tablewidth = this.virtualEle.wrapper.offsetWidth - parseInt(column.width.toString(), 10); } if (tablewidth > gObj.width) { this.setDisplayNone(column, displayVal); this.virtualEle.setWrapperWidth(tablewidth + ''); this.gen.refreshColOffsets(); } else { needFullRefresh = true; } } else { needFullRefresh = true; } if (needFullRefresh && !frozenCols) { this.refreshUI(); } } if (frozenCols) { this.parent.notify(events.columnPositionChanged, {}); } } private setFrozenTable(content: Element): void { if (this.parent.isFrozenGrid() && this.parent.enableColumnVirtualization && (<{ isXaxis?: Function }>this.parent.contentModule).isXaxis()) { (<{ setTable?: Function }>(<Grid>this.parent).contentModule) .setTable(content.querySelector('.' + literals.table)); } } private setDisplayNone(col: Column, displayVal: string): void { const frozenCols: boolean = this.parent.isFrozenGrid(); let table: Element = this.getTable(); if (frozenCols && col.getFreezeTableName() === 'movable') { table = this.parent.getMovableVirtualHeader().querySelector('.' + literals.table); } for (const ele of [].slice.apply(table.querySelectorAll('th.e-headercell'))) { if (ele.querySelector('[e-mappinguid]') && ele.querySelector('[e-mappinguid]').getAttribute('e-mappinguid') === col.uid) { setStyleAttribute(<HTMLElement>ele, { 'display': displayVal }); if (displayVal === '') { removeClass([ele], 'e-hide'); } break; } } } } /** * @hidden */ export class VirtualElementHandler { public wrapper: HTMLElement; public placeholder: HTMLElement; public content: HTMLElement; public table: HTMLElement; public movableWrapper: HTMLElement; public movablePlaceholder: HTMLElement; public movableTable: HTMLElement; public movableContent: HTMLElement; public renderWrapper(height?: number): void { this.wrapper = createElement('div', { className: 'e-virtualtable', styles: `min-height:${formatUnit(height)}` }); this.wrapper.appendChild(this.table); this.content.appendChild(this.wrapper); } public renderPlaceHolder(position: string = 'relative'): void { this.placeholder = createElement('div', { className: 'e-virtualtrack', styles: `position:${position}` }); this.content.appendChild(this.placeholder); } public renderFrozenWrapper(height?: number): void { this.wrapper = createElement('div', { className: 'e-virtualtable', styles: `min-height:${formatUnit(height)}; display: flex` }); this.content.appendChild(this.wrapper); } public renderFrozenPlaceHolder(): void { this.placeholder = createElement('div', { className: 'e-virtualtrack' }); this.content.appendChild(this.placeholder); } public renderMovableWrapper(height?: number): void { this.movableWrapper = createElement('div', { className: 'e-virtualtable', styles: `min-height:${formatUnit(height)}` }); this.movableContent.appendChild(this.movableWrapper); } public renderMovablePlaceHolder(): void { this.movablePlaceholder = createElement('div', { className: 'e-virtualtrack' }); this.movableContent.appendChild(this.movablePlaceholder); } public adjustTable(xValue: number, yValue: number): void { this.wrapper.style.transform = `translate(${xValue}px, ${yValue}px)`; } public adjustMovableTable(xValue: number, yValue: number): void { this.movableWrapper.style.transform = `translate(${xValue}px, ${yValue}px)`; } public setMovableWrapperWidth(width: string, full?: boolean): void { this.movableWrapper.style.width = width ? `${width}px` : full ? '100%' : ''; } public setMovableVirtualHeight(height?: number, width?: string): void { this.movablePlaceholder.style.height = `${height}px`; this.movablePlaceholder.style.width = width; } public setWrapperWidth(width: string, full?: boolean): void { this.wrapper.style.width = width ? `${width}px` : full ? '100%' : ''; } public setVirtualHeight(height?: number, width?: string): void { this.placeholder.style.height = `${height}px`; this.placeholder.style.width = width; } public setFreezeWrapperWidth(wrapper: HTMLElement, width: string, full?: boolean): void { wrapper.style.width = width ? `${width}px` : full ? '100%' : ''; } } type ScrollArg = { direction: string, sentinel: SentinelType, offset: Offsets, focusElement: HTMLElement }; interface EditArgs { data?: Object; requestType?: string; previousData?: Object; selectedRow?: number; type?: string; promise?: Promise<Object>; row?: Element; }
the_stack
interface IListenerInstrumentation { /** * Predicate-Method telling whether the instrumentation should be applied on the given attachment Target of the event and the given event type. * * @param attachmenTarget the element onto which the listener to check for was attached * @param eventType the type name of the event, e.g. "click" * * @return true, if this listener instrumentation shall be executed on the given element and event type */ shouldInstrument(attachmenTarget: EventTarget, eventType: string): boolean; /** * Called when an instrumented listener is executed. * * @param event the event for which the listener is executed. * @param originalCallback the callback function of the event listener * @param executeOriginalListener the method for executing the original listener (synchronously) */ instrument(event: Event, originalCallback: UncallableFunction, executeOriginalListener: () => any): void; } /** * Instrumentation module. * * Allows to disable the instrumentation for a scope. Disabling instrumentation is necessary, because plugins also make use of * instrumented functions, such as setTimeout for example. Also provides the infrastructure for instrumenting listeners. * */ namespace Instrumentation { /** * This variable holds how often disable() has been called to make sure that nested disable() and reenable() calls are handled correctly. */ let instrumentationStackDepth = 0; /** * Returns whether the instruemtnation has currently been disabled via disable(); */ export function isEnabled(): boolean { return (instrumentationStackDepth === 0); } /** * Disables the instrumentation until reenable() is called; * This disabling allows you to use instrumented function with generating traces, for example for sending AJAX requests. */ export function disable() { instrumentationStackDepth++; } /** * Reenables the instrumentation after a disable() call. */ export function reenable() { instrumentationStackDepth--; } /** * Disables the instrumentation, runs the given function and afterwards reenables the instrumentation. * * @param func * the function to execute without isntrumentation. * @returns the return value of func */ export function runWithout<T>(func: (this: void) => T): T { disable(); const result = func(); reenable(); return result; } /** * Wraps the given function in a function which executes exactly the same task but with instrumentation disabled. * * @param func * the function to wrap * @returns the wrapper for func which has instrumentation disabled. */ export function disableFor<T extends Function>(func: T): T { return (function (this: any) { disable(); const result = func.apply(this, arguments); reenable(); return result; }) as any; } /** * Marker to prevent instrumentation of already instrumented function */ type InstrumentedCallback = Function & { _is_inspectIT_function?: true }; /** * List of all registered listener instrumentations. */ const listenerInstrumentations: IListenerInstrumentation[] = []; /** * Lookup table for getting the original callback belonging to an instrumented one. */ const callbackInstrumentations = new WeakMapImpl<Function, InstrumentedCallback>(); /** * Cache for querying / storing the instrumentation applied to a given element and event type. */ const activeEventInstrumentations = new WeakMapImpl<EventTarget, IDictionary<IListenerInstrumentation[]>>(); /** * Registers a listener instrumentation. * * @param instrumentation the instrumentation ro register. */ export function addListenerInstrumentation(instrumentation: IListenerInstrumentation) { listenerInstrumentations.push(instrumentation); } /** * Checks if registered listener instrumentations apply on the given element and listener. * This check is only done once and afterwards cached for the element. * * @param attachmentTarget the event target to check, the lement to which the listener was attached * @param eventType the type of the event, e.g. "click" */ function getActiveEventInstrumentations(attachmentTarget: EventTarget, eventType: string): IListenerInstrumentation[] { let dict = activeEventInstrumentations.get(attachmentTarget); if (!dict) { dict = {}; activeEventInstrumentations.set(attachmentTarget, dict); } if (!(eventType in dict)) { // never checked before, check available instrumentations dict[eventType] = []; for (const instr of listenerInstrumentations) { if (instr.shouldInstrument(attachmentTarget, eventType)) { dict[eventType].push(instr); } } } return dict[eventType]; } /** * Instruments the given event-listener callback. * Does nothing if the callback is already instrumented. * * @param originalCallback the callback to instrument * @return the instrumented callback */ export function instrumentEventCallback<T extends Function>(originalCallback: T): T { // check if listener instrumentation is enabled if (!SETTINGS.allowListenerInstrumentation) { return originalCallback; } // prevent instrumentation of instrumentation if ((originalCallback as InstrumentedCallback)._is_inspectIT_function) { return originalCallback; } // check if already instrumented let instrumentedCallback = callbackInstrumentations.get(originalCallback); if (!instrumentedCallback) { instrumentedCallback = function (this: any, event: Event) { // sanity check if parameters are available if (!event) { return originalCallback.apply(this, arguments); } else { let returnValue: any; const filteredInstrumentations = getActiveEventInstrumentations(event.currentTarget, event.type); const originalArgs = arguments; const originalThis = this; let currentListenerIndex = -1; // recursive iterator // when this function is invoked, it either calls the next instrumentation or the actual callback // if all instrumentations were executed const continueFunc = function () { currentListenerIndex++; if (currentListenerIndex < filteredInstrumentations.length) { // call the next listener filteredInstrumentations[currentListenerIndex].instrument(event, originalCallback as any, continueFunc); } else { // finally call the original callback and keep its return value returnValue = originalCallback.apply(originalThis, originalArgs); } return returnValue; }; // start the call chain of calling first all instrumentations and finally calling the original callback continueFunc(); return returnValue; } } as any; instrumentedCallback!._is_inspectIT_function = true; callbackInstrumentations.set(originalCallback, instrumentedCallback!); } return instrumentedCallback! as T; } export function initListenerInstrumentation() { if (!SETTINGS.allowListenerInstrumentation) { return; } if ((typeof EventTarget !== "undefined") && EventTarget.prototype.hasOwnProperty("addEventListener") && EventTarget.prototype.hasOwnProperty("removeEventListener")) { // Chrome, Safari, Firefox, Edge instrumentForPrototype(EventTarget.prototype); } else { // IE11 solution instrumentForPrototype(Node.prototype); instrumentForPrototype(XMLHttpRequest.prototype); instrumentForPrototype(window); } function instrumentForPrototype(prototypeToInstrument: EventTarget) { const uninstrumentedAddEventListener = prototypeToInstrument.addEventListener; (prototypeToInstrument as any).addEventListener = function (this: EventTarget, type: string, callback: Function) { // check instrumentation disabled flag if (!isEnabled()) { return uninstrumentedAddEventListener.apply(this, arguments); } // fetch the existing instrumented callback or create a new one // every callback is guaranteed to be only instrumented once const instrumentedCallback = instrumentEventCallback(callback); // Attach the instrumented listener const modifiedArgs = Array.prototype.slice.call(arguments); modifiedArgs[1] = instrumentedCallback; return uninstrumentedAddEventListener.apply(this, modifiedArgs); }; const uninstrumentedRemoveEventListener = prototypeToInstrument.removeEventListener; (prototypeToInstrument as any).removeEventListener = function (this: EventTarget, type: string, callback: Function) { // check instrumentation disabled flag if (!isEnabled()) { return uninstrumentedRemoveEventListener.apply(this, arguments); } const instrumentedCallback = callbackInstrumentations.get(callback); if (instrumentedCallback) { const modifiedArgs = Array.prototype.slice.call(arguments); modifiedArgs[1] = instrumentedCallback; return uninstrumentedRemoveEventListener.apply(this, modifiedArgs); } else { return uninstrumentedRemoveEventListener.apply(this, arguments); } }; } } }
the_stack
import {assert, use as chaiUse} from 'chai'; import * as path from 'path'; import {Analyzer} from '../../core/analyzer'; import {ClassScanner} from '../../javascript/class-scanner'; import {ScannedPolymerElement} from '../../polymer/polymer-element'; import {CodeUnderliner, createForDirectory, fixtureDir, runScanner} from '../test-utils'; chaiUse(require('chai-subset')); suite('Polymer2ElementScanner with old jsdoc annotations', () => { let analyzer: Analyzer; let underliner: CodeUnderliner; suiteSetup(async () => { const testFilesDir = path.resolve(fixtureDir, 'polymer2-old-jsdoc/'); ({analyzer, underliner} = await createForDirectory(testFilesDir)); }); async function getElements(filename: string): Promise<ScannedPolymerElement[]> { const {features} = await runScanner(analyzer, new ClassScanner(), filename); return features.filter((e) => e instanceof ScannedPolymerElement) as ScannedPolymerElement[]; } async function getTestProps(element: ScannedPolymerElement) { // tslint:disable-next-line: no-any Hacky test code const props: any = { className: element.className, superClass: element.superClass && element.superClass.identifier, tagName: element.tagName, description: element.description, summary: element.summary, properties: await Promise.all( Array.from(element.properties.values()).map(async (p) => { // tslint:disable-next-line: no-any Hacky test code const result = {name: p.name, description: p.description} as any; if (p.type) { result.type = p.type; } if (p.observerExpression) { result.propertiesInObserver = p.observerExpression.properties.map((p) => p.name); } if (p.computedExpression) { result.propertiesInComputed = p.computedExpression.properties.map((p) => p.name); } if (p.warnings.length > 0) { result.warningUnderlines = await underliner.underline(p.warnings); } return result; })), attributes: Array.from(element.attributes.values()).map((a) => ({ name: a.name, })), methods: Array.from(element.methods.values()).map((m) => ({ name: m.name, params: m.params, return: m.return, description: m.description })), warningUnderlines: await underliner.underline(element.warnings), }; if (element.observers.length > 0) { props.observers = element.observers.map((o) => o.expression); props.observerProperties = element.observers.filter((o) => o.parsedExpression) .map((o) => o.parsedExpression!.properties.map((p) => p.name)); } if (element.mixins.length > 0) { props.mixins = element.mixins.map((m) => m.identifier); } return props; } test('Finds two basic elements', async () => { const elements = await getElements('test-element-1.js'); const elementData = await Promise.all(elements.map(getTestProps)); assert.deepEqual(elementData, [ { tagName: 'test-element', className: 'TestElement', superClass: 'Polymer.Element', description: '', summary: '', properties: [{ name: 'foo', description: 'The foo prop.', type: '(m-test | function)', }], attributes: [{ name: 'foo', }], methods: [], warningUnderlines: [], }, { tagName: undefined, className: 'BaseElement', superClass: 'Polymer.Element', description: 'A very basic element', summary: 'A basic element', properties: [{ name: 'foo', description: 'A base foo element.', type: 'string | null | undefined', }], attributes: [{ name: 'foo', }], methods: [], warningUnderlines: [], }, ]); const underlinedSource1 = await underliner.underline(elements[0].sourceRange); assert.equal(underlinedSource1, ` class TestElement extends Polymer.Element { ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ static get properties() { ~~~~~~~~~~~~~~~~~~~~~~~~~~~ return { ~~~~~~~~~~~~ /** ~~~~~~~~~ * The foo prop. ~~~~~~~~~~~~~~~~~~~~~~ * @public ~~~~~~~~~~~~~~~~ * @type {m-test|function} ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */ ~~~~~~~~~ foo: { ~~~~~~~~~~~~ notify: true, ~~~~~~~~~~~~~~~~~~~~~ type: String, ~~~~~~~~~~~~~~~~~~~~~ } ~~~~~~~ } ~~~~~ } ~~~ } ~`); const underlinedSource2 = await underliner.underline(elements[1].sourceRange); assert.equal(underlinedSource2, ` class BaseElement extends Polymer.Element { ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ static get properties() { ~~~~~~~~~~~~~~~~~~~~~~~~~~~ return { ~~~~~~~~~~~~ /** A base foo element. */ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ foo: { ~~~~~~~~~~~~ notify: true, ~~~~~~~~~~~~~~~~~~~~~ type: String, ~~~~~~~~~~~~~~~~~~~~~ }, ~~~~~~~~ }; ~~~~~~ } ~~~ } ~`); }); test('Uses static is getter for tagName', async () => { const elements = await getElements('test-element-2.js'); const elementData = await Promise.all(elements.map(getTestProps)); assert.deepEqual(elementData, [ { tagName: 'test-element', className: 'TestElement', superClass: 'HTMLElement', description: '', summary: '', properties: [], attributes: [], methods: [], warningUnderlines: [], }, ]); }); test('Finds vanilla elements', async () => { const elements = await getElements('test-element-4.js'); const elementData = await Promise.all(elements.map(getTestProps)); assert.deepEqual(elementData, [ { tagName: 'test-element', className: 'TestElement', superClass: 'HTMLElement', description: '', summary: '', properties: [], attributes: [ { name: 'a', }, { name: 'b', } ], methods: [], warningUnderlines: [], }, ]); }); test('Observed attributes override induced attributes', async () => { const elements = await getElements('test-element-5.js'); const elementData = await Promise.all(elements.map(getTestProps)); assert.deepEqual(elementData, [ { tagName: 'test-element', className: 'TestElement', superClass: 'Polymer.Element', description: '', summary: '', properties: [{ name: 'foo', description: '', type: 'string | null | undefined', }], attributes: [ { name: 'a', }, { name: 'b', } ], methods: [], warningUnderlines: [], }, ]); }); test('properly sets className for elements with the memberof tag', async () => { const elements = await getElements('test-element-8.js'); const elementData = await Promise.all(elements.map(getTestProps)); assert.deepEqual(elementData, [ { tagName: 'test-element-one', className: 'Polymer.TestElementOne', superClass: 'Polymer.Element', description: `This element is a member of Polymer namespace and is registered with its namespaced name.`, summary: '', properties: [{ name: 'foo', description: '', type: 'string | null | undefined', }], attributes: [{ name: 'foo', }], methods: [], warningUnderlines: [], }, { tagName: 'test-element-two', className: 'Polymer.TestElementTwo', superClass: 'Polymer.Element', description: `This element is a member of Polymer namespace and is registered without its namespaced name.`, summary: '', properties: [{ name: 'foo', description: '', type: 'string | null | undefined', }], attributes: [{ name: 'foo', }], methods: [], warningUnderlines: [], } ]); }); test('Read @appliesMixin annotations', async () => { const elements = await getElements('test-element-6.js'); const elementData = await Promise.all(elements.map(getTestProps)); assert.deepEqual(elementData, [ { tagName: 'test-element', className: 'TestElement', superClass: 'Polymer.Element', description: '', summary: '', properties: [], attributes: [], methods: [], mixins: ['Mixin2', 'Mixin1'], warningUnderlines: [], }, ]); }); test('Reads just @appliesMixin annotation', async () => { const elements = await getElements('test-element-9.js'); const elementData = await Promise.all(elements.map(getTestProps)); assert.deepEqual(elementData, [ { tagName: undefined, className: 'BaseElement', superClass: 'Polymer.Element', description: '', summary: '', properties: [], attributes: [], methods: [], warningUnderlines: [], }, { tagName: undefined, className: 'SubElement', superClass: 'BaseElement', description: '', summary: '', properties: [], attributes: [], methods: [], mixins: ['Mixin'], warningUnderlines: [], }, { tagName: undefined, className: 'SubElement2', superClass: 'BaseElement', description: '', summary: '', properties: [], attributes: [], methods: [], mixins: ['Mixin'], warningUnderlines: [], }, { tagName: undefined, className: 'window.MyElement', superClass: 'MixedElement', description: '', summary: '', properties: [], attributes: [], methods: [], mixins: ['MyMixin'], warningUnderlines: [], } ]); }); test( 'properly reads properties and methods of elements and element classes', async () => { const elements = await getElements('test-element-10.js'); const elementData = await Promise.all(elements.map(getTestProps)); assert.deepEqual(elementData, [ { tagName: 'test-element', className: 'TestElement', superClass: 'Polymer.Element', description: ``, summary: '', properties: [ {name: 'customInstanceGetter', description: undefined}, { name: 'foo', description: '', type: 'string | null | undefined', } ], attributes: [{ name: 'foo', }], methods: [ { name: 'customInstanceFunction', description: '', params: [], return: undefined }, { name: 'customInstanceFunctionWithJSDoc', description: 'This is the description for ' + 'customInstanceFunctionWithJSDoc.', params: [], return: { desc: 'The number 5, always.', type: 'Number', }, }, { name: 'customInstanceFunctionWithParams', description: '', params: [ { name: 'a', type: undefined, defaultValue: undefined, rest: undefined, description: undefined }, { name: 'b', type: undefined, defaultValue: undefined, rest: undefined, description: undefined }, { name: 'c', type: undefined, defaultValue: undefined, rest: undefined, description: undefined } ], return: undefined, }, { name: 'customInstanceFunctionWithParamsAndJSDoc', description: 'This is the description for ' + 'customInstanceFunctionWithParamsAndJSDoc.', params: [ { name: 'a', type: 'Number', defaultValue: undefined, rest: undefined, description: 'The first argument', }, { name: 'b', type: 'Number', defaultValue: undefined, rest: undefined, description: undefined }, { name: 'c', type: 'Number', defaultValue: undefined, rest: undefined, description: 'The third argument', } ], return: { desc: 'The number 7, always.', type: 'Number', }, }, { name: 'customInstanceFunctionWithParamsAndPrivateJSDoc', description: 'This is the description for\n' + 'customInstanceFunctionWithParamsAndPrivateJSDoc.', params: [], return: undefined, }, ], warningUnderlines: [], }, ]); }); test('warns for bad observers and computed properties', async () => { const elements = await getElements('test-element-12.js'); const elementData = await Promise.all(elements.map(getTestProps)); assert.deepEqual( elementData, [{ attributes: [{name: 'parse-error'}, {name: 'bad-kind-of-expression'}], className: 'TestElement', description: '', methods: [], properties: [ { name: 'parseError', type: 'string | null | undefined', description: '', warningUnderlines: [ ` computed: 'let let let', ~`, ` observer: 'let let let', ~`, ] }, { name: 'badKindOfExpression', type: 'string | null | undefined', description: '', propertiesInComputed: ['foo'], propertiesInObserver: ['foo', 'bar', 'baz'], warningUnderlines: [ ` computed: 'foo', ~~~`, ` observer: 'foo(bar, baz)' ~~~~~~~~~~~~~`, ] } ], summary: '', superClass: 'Polymer.Element', tagName: 'test-element', warningUnderlines: [ ` 'let let let parseError', ~`, ` 'foo', ~~~` ], observers: [ 'let let let parseError', 'foo', 'foo(bar)', ], observerProperties: [['foo'], ['foo', 'bar']], }]); }); test('can identify elements registered with ClassName.is', async () => { const elements = await getElements('test-element-11.js'); const elementData = await Promise.all(elements.map(getTestProps)); assert.deepEqual( elementData, [{ attributes: [{name: 'prop1'}], className: 'MyElement', description: '', methods: [], properties: [ {name: 'prop1', description: '', type: 'string | null | undefined'} ], summary: '', superClass: 'Polymer.Element', tagName: 'my-app', warningUnderlines: [], }]); }); });
the_stack
import { codeModelSchema, SchemaResponse, CodeModel, Schema, ObjectSchema, GroupSchema, isObjectSchema, SchemaType, GroupProperty, ParameterLocation, Operation, Parameter, VirtualParameter, getAllProperties, ImplementationLocation, OperationGroup, Request, SchemaContext, StringSchema, ChoiceSchema, SealedChoiceSchema } from '@azure-tools/codemodel'; import { camelCase, deconstruct, excludeXDash, fixLeadingNumber, pascalCase, lowest, maximum, minimum, getPascalIdentifier, serialize } from '@azure-tools/codegen'; import { items, values, keys, Dictionary, length } from '@azure-tools/linq'; import { System } from '@azure-tools/codegen-csharp'; import { Channel, Host, Session, startSession } from '@azure-tools/autorest-extension-base'; import { SchemaDetails } from '../llcsharp/code-model'; import { SchemaDefinitionResolver } from '../llcsharp/schema/schema-resolver'; import { PwshModel } from '../utils/PwshModel'; import { ModelState } from '../utils/model-state'; import { SchemaDetails as NewSchemaDetails } from '../utils/schema'; type State = ModelState<PwshModel>; function setPropertyNames(schema: Schema) { // name each property in this schema // skip-for-time-being if (!isObjectSchema(schema)) { return; } for (const propertySchema of values(schema.properties)) { const propertyDetails = propertySchema.language.default; propertyDetails.required = propertySchema.required ?? false; propertyDetails.readOnly = propertySchema.readOnly ?? false; const className = schema.language.csharp?.name; let pname = getPascalIdentifier(propertyDetails.name); if (pname === className) { pname = `${pname}Property`; } if (pname === 'default') { pname = '@default'; } propertySchema.language.csharp = { ...propertyDetails, name: pname // and so are the propertyNmaes }; if (propertyDetails.isNamedStream) { propertySchema.language.csharp.namedStreamPropertyName = pascalCase(fixLeadingNumber([...deconstruct(propertyDetails.name), 'filename'])); } } } function setSchemaNames(schemaGroups: Dictionary<Array<Schema>>, azure: boolean, serviceNamespace: string) { const baseNamespace = new Set<string>(); const subNamespace = new Map<string, Set<string>>(); // dolauli need to notice this -- schemas in the namespace of the lowest supported api version // in Azure Mode, we want to always put schemas into the namespace of the lowest supported apiversion. // otherwise, we just want to differientiate with a simple incremental numbering scheme. for (const group of values(schemaGroups)) { for (const schema of group) { if (schema.language.default.skip) { continue; } let thisNamespace = baseNamespace; let thisApiversion = ''; // create the namespace if required if (azure) { const versions = [...values(schema.apiVersions).select(v => v.version)]; if (schema.language.default?.uid !== 'universal-parameter-type') { if (versions && length(versions) > 0) { thisApiversion = minimum(versions); thisNamespace = subNamespace.get(thisApiversion) || new Set<string>(); subNamespace.set(thisApiversion, thisNamespace); } } } // for each schema, we're going to set the name // to the suggested name, unless we have collisions // at which point, we're going to add a number (for now?) const details = schema.language.default; let schemaName = getPascalIdentifier(details.name); const apiName = (!thisApiversion) ? '' : getPascalIdentifier(`Api ${thisApiversion}`); const ns = (!thisApiversion) ? [] : ['.', apiName]; let n = 1; while (thisNamespace.has(schemaName)) { schemaName = getPascalIdentifier(`${details.name}_${n++}`); } thisNamespace.add(schemaName); // object types. if (schema.type === SchemaType.Object || schema.type === SchemaType.Dictionary || schema.type === SchemaType.Any) { schema.language.csharp = { ...details, apiversion: thisApiversion, apiname: apiName, interfaceName: 'I' + pascalCase(fixLeadingNumber([...deconstruct(schemaName)])), // objects have an interfaceName internalInterfaceName: 'I' + pascalCase(fixLeadingNumber([...deconstruct(schemaName), 'Internal'])), // objects have an ineternal interfaceName for setting private members. fullInternalInterfaceName: `${pascalCase([serviceNamespace, '.', 'Models', ...ns])}.${'I' + pascalCase(fixLeadingNumber([...deconstruct(schemaName), 'Internal']))}`, name: getPascalIdentifier(schemaName), namespace: pascalCase([serviceNamespace, '.', 'Models', ...ns]), // objects have a namespace fullname: `${pascalCase([serviceNamespace, '.', 'Models', ...ns])}.${getPascalIdentifier(schemaName)}`, }; } else if (schema.type === SchemaType.Choice || schema.type === SchemaType.SealedChoice) { // oh, it's an enum type const choiceSchema = <ChoiceSchema<StringSchema> | SealedChoiceSchema<StringSchema>>schema; schema.language.csharp = <SchemaDetails>{ ...details, interfaceName: 'I' + pascalCase(fixLeadingNumber([...deconstruct(schemaName)])), name: getPascalIdentifier(schemaName), namespace: pascalCase([serviceNamespace, '.', 'Support']), fullname: `${pascalCase([serviceNamespace, '.', 'Support'])}.${getPascalIdentifier(schemaName)}`, enum: { ...schema.language.default.enum, name: getPascalIdentifier(schema.language.default.name), values: choiceSchema.choices.map(each => { return { ...each, name: getPascalIdentifier(each.language.default.name), description: each.language.default.description }; }) } }; } else { schema.language.csharp = <SchemaDetails>{ ...details, interfaceName: '<INVALID_INTERFACE>', internalInterfaceName: '<INVALID_INTERFACE>', name: schemaName, namespace: '<INVALID_NAMESPACE>', fullname: '<INVALID_FULLNAME>' }; // xichen: for invalid namespace case, we won't create model class. So we do not need consider dup case thisNamespace.delete(schemaName); } // name each property in this schema setPropertyNames(schema); // fix enum names if (schema.type === SchemaType.Choice || schema.type === SchemaType.SealedChoice) { schema.language.csharp.enum.name = getPascalIdentifier(schema.language.default.name); // and the value names themselves for (const value of values(schema.language.csharp.enum.values)) { // In m3, enum.name and enum.value are same. But in m4, enum.name is named by m4. // To keep same action as m3, use enum.value here (<any>value).name = getPascalIdentifier((<any>value).value); } } } } } async function setOperationNames(state: State, resolver: SchemaDefinitionResolver) { // keep a list of operation names that we've assigned. const operationNames = new Set<string>(); for (const operationGroup of values(state.model.operationGroups)) { for (const operation of values(operationGroup.operations)) { const details = operation.language.default; // come up with a name const oName = getPascalIdentifier(operationGroup.$key + '_' + details.name); let i = 1; let operationName = oName; while (operationNames.has(operationName)) { // if we have used that name, try again. operationName = `${oName}${i++}`; } operationNames.add(operationName); operation.language.csharp = { ...details, // inherit name: operationName, }; // parameters are camelCased. for (const parameter of values(operation.parameters)) { const parameterDetails = parameter.language.default; let propName = camelCase(fixLeadingNumber(deconstruct(parameterDetails.serializedName))); if (propName === 'default') { propName = '@default'; } parameter.language.csharp = { ...parameterDetails, name: propName }; } const responses = [...values(operation.responses), ...values(operation.exceptions)]; for (const rsp of responses) { // per responseCode const response = <SchemaResponse>rsp; const responseTypeDefinition = response.schema ? resolver.resolveTypeDeclaration(<any>response.schema, true, state) : undefined; const headerSchema = response.language.default.headerSchema; const headerTypeDefinition = headerSchema ? resolver.resolveTypeDeclaration(<any>headerSchema, true, state.path('schemas', headerSchema.language.default.name)) : undefined; let code = (System.Net.HttpStatusCode[response.protocol.http?.statusCodes[0]] ? System.Net.HttpStatusCode[response.protocol.http?.statusCodes[0]].value : response.protocol.http?.statusCodes[0]).replace('global::System.Net.HttpStatusCode', ''); let rawValue = code.replace(/\./, ''); if (response.protocol.http?.statusCodes[0] === 'default' || rawValue === 'default' || '') { rawValue = 'any response code not handled elsewhere'; code = 'default'; response.language.default.isErrorResponse = true; } response.language.csharp = { ...response.language.default, responseType: responseTypeDefinition ? responseTypeDefinition.declaration : '', headerType: headerTypeDefinition ? headerTypeDefinition.declaration : '', name: (length(response.protocol.http?.mimeTypes) <= 1) ? camelCase(fixLeadingNumber(deconstruct(`on ${code}`))) : // the common type (or the only one.) camelCase(fixLeadingNumber(deconstruct(`on ${code} ${response.protocol.http?.mimeTypes[0]}`))), description: (length(response.protocol.http?.mimeTypes) <= 1) ? `a delegate that is called when the remote service returns ${response.protocol.http?.statusCodes[0]} (${rawValue}).` : `a delegate that is called when the remote service returns ${response.protocol.http?.statusCodes[0]} (${rawValue}) with a Content-Type matching ${response.protocol.http?.mimeTypes.join(',')}.` }; } } } } async function nameStuffRight(state: State): Promise<PwshModel> { const resolver = new SchemaDefinitionResolver(); const model = state.model; // set the namespace for the service const serviceNamespace = await state.getValue('namespace', 'Sample.API'); const azure = await state.getValue('azure', false) || await state.getValue('azure-arm', false); const clientName = getPascalIdentifier(model.language.default.name); // dolauli see model.details.csharp for c# related staff // set c# client details (name) model.language.csharp = { ...model.language.default, // copy everything by default name: clientName, namespace: serviceNamespace, fullname: `${serviceNamespace}.${clientName}` }; setSchemaNames(<Dictionary<Array<Schema>>><any>model.schemas, azure, serviceNamespace); await setOperationNames(state, resolver); return model; } export async function csnamerV2(service: Host) { // dolauli add names for http operations and schemas //return processCodeModel(nameStuffRight, service, 'csnamer'); //const session = await startSession<PwshModel>(service, {}, codeModelSchema); //const result = tweakModelV2(session); const state = await new ModelState<PwshModel>(service).init(); await service.WriteFile('code-model-v4-csnamer-v2.yaml', serialize(await nameStuffRight(state)), undefined, 'code-model-v4'); }
the_stack
import './user_layer.css'; import {AnnotationPropertySpec, annotationPropertySpecsToJson, AnnotationType, LocalAnnotationSource, parseAnnotationPropertySpecs} from 'neuroglancer/annotation'; import {AnnotationDisplayState, AnnotationLayerState} from 'neuroglancer/annotation/annotation_layer_state'; import {MultiscaleAnnotationSource} from 'neuroglancer/annotation/frontend_source'; import {CoordinateTransformSpecification, makeCoordinateSpace} from 'neuroglancer/coordinate_transform'; import {DataSourceSpecification, localAnnotationsUrl, LocalDataSource} from 'neuroglancer/datasource'; import {LayerManager, LayerReference, ManagedUserLayer, registerLayerType, registerLayerTypeDetector, UserLayer} from 'neuroglancer/layer'; import {LoadedDataSubsource} from 'neuroglancer/layer_data_source'; import {Overlay} from 'neuroglancer/overlay'; import {getWatchableRenderLayerTransform} from 'neuroglancer/render_coordinate_transform'; import {RenderLayerRole} from 'neuroglancer/renderlayer'; import {SegmentationDisplayState} from 'neuroglancer/segmentation_display_state/frontend'; import {SegmentationUserLayer} from 'neuroglancer/segmentation_user_layer'; import {TrackableBoolean, TrackableBooleanCheckbox} from 'neuroglancer/trackable_boolean'; import {makeCachedLazyDerivedWatchableValue, WatchableValue} from 'neuroglancer/trackable_value'; import {AnnotationLayerView, MergedAnnotationStates, UserLayerWithAnnotationsMixin} from 'neuroglancer/ui/annotations'; import {animationFrameDebounce} from 'neuroglancer/util/animation_frame_debounce'; import {Borrowed, Owned, RefCounted} from 'neuroglancer/util/disposable'; import {updateChildren} from 'neuroglancer/util/dom'; import {parseArray, parseFixedLengthArray, stableStringify, verify3dVec, verifyFinitePositiveFloat, verifyObject, verifyOptionalObjectProperty, verifyString, verifyStringArray} from 'neuroglancer/util/json'; import {NullarySignal} from 'neuroglancer/util/signal'; import {DependentViewWidget} from 'neuroglancer/widget/dependent_view_widget'; import {makeHelpButton} from 'neuroglancer/widget/help_button'; import {LayerReferenceWidget} from 'neuroglancer/widget/layer_reference'; import {makeMaximizeButton} from 'neuroglancer/widget/maximize_button'; import {RenderScaleWidget} from 'neuroglancer/widget/render_scale_widget'; import {ShaderCodeWidget} from 'neuroglancer/widget/shader_code_widget'; import {registerLayerShaderControlsTool, ShaderControls} from 'neuroglancer/widget/shader_controls'; import {Tab} from 'neuroglancer/widget/tab_view'; const POINTS_JSON_KEY = 'points'; const ANNOTATIONS_JSON_KEY = 'annotations'; const ANNOTATION_PROPERTIES_JSON_KEY = 'annotationProperties'; const ANNOTATION_RELATIONSHIPS_JSON_KEY = 'annotationRelationships'; const CROSS_SECTION_RENDER_SCALE_JSON_KEY = 'crossSectionAnnotationSpacing'; const PROJECTION_RENDER_SCALE_JSON_KEY = 'projectionAnnotationSpacing'; const SHADER_JSON_KEY = 'shader'; const SHADER_CONTROLS_JSON_KEY = 'shaderControls'; function addPointAnnotations(annotations: LocalAnnotationSource, obj: any) { if (obj === undefined) { return; } parseArray(obj, (x, i) => { annotations.add({ type: AnnotationType.POINT, id: '' + i, point: verify3dVec(x), properties: [], }); }); } function isValidLinkedSegmentationLayer(layer: ManagedUserLayer) { const userLayer = layer.layer; if (userLayer === null) { return true; } if (userLayer instanceof SegmentationUserLayer) { return true; } return false; } function getSegmentationDisplayState(layer: ManagedUserLayer|undefined): SegmentationDisplayState| null { if (layer === undefined) { return null; } const userLayer = layer.layer; if (userLayer === null) { return null; } if (!(userLayer instanceof SegmentationUserLayer)) { return null; } return userLayer.displayState; } interface LinkedSegmentationLayer { layerRef: Owned<LayerReference>; showMatches: TrackableBoolean; seenGeneration: number; } const LINKED_SEGMENTATION_LAYER_JSON_KEY = 'linkedSegmentationLayer'; const FILTER_BY_SEGMENTATION_JSON_KEY = 'filterBySegmentation'; const IGNORE_NULL_SEGMENT_FILTER_JSON_KEY = 'ignoreNullSegmentFilter'; class LinkedSegmentationLayers extends RefCounted { changed = new NullarySignal(); private curGeneration = -1; private wasLoading: boolean|undefined = undefined; constructor( public layerManager: Borrowed<LayerManager>, public annotationStates: Borrowed<MergedAnnotationStates>, public annotationDisplayState: Borrowed<AnnotationDisplayState>) { super(); this.registerDisposer(annotationStates.changed.add(() => this.update())); this.registerDisposer(annotationStates.isLoadingChanged.add(() => this.update())); this.update(); } private update() { const generation = this.annotationStates.changed.count; const isLoading = this.annotationStates.isLoading; if (this.curGeneration === generation && isLoading === this.wasLoading) return; this.wasLoading = isLoading; this.curGeneration = generation; const {map} = this; let changed = false; for (const relationship of this.annotationStates.relationships) { let state = map.get(relationship); if (state === undefined) { state = this.addRelationship(relationship); changed = true; } state.seenGeneration = generation; } if (!isLoading) { for (const [relationship, state] of map) { if (state.seenGeneration !== generation) { map.delete(relationship); changed = true; } } } if (changed) { this.changed.dispatch(); } } private addRelationship(relationship: string): LinkedSegmentationLayer { const relationshipState = this.annotationDisplayState.relationshipStates.get(relationship); const layerRef = new LayerReference(this.layerManager.addRef(), isValidLinkedSegmentationLayer); layerRef.registerDisposer(layerRef.changed.add(() => { relationshipState.segmentationState.value = layerRef.layerName === undefined ? undefined : getSegmentationDisplayState(layerRef.layer); })); const {showMatches} = relationshipState; const state = { layerRef, showMatches, seenGeneration: -1, }; layerRef.changed.add(this.changed.dispatch); showMatches.changed.add(this.changed.dispatch); this.map.set(relationship, state); return state; } get(relationship: string): LinkedSegmentationLayer { this.update(); return this.map.get(relationship)!; } private unbind(state: LinkedSegmentationLayer) { state.layerRef.changed.remove(this.changed.dispatch); state.showMatches.changed.remove(this.changed.dispatch); } reset() { for (const state of this.map.values()) { state.showMatches.reset(); } } toJSON() { const {map} = this; if (map.size === 0) return {}; let linkedJson: {[relationship: string]: string}|undefined = undefined; const filterBySegmentation = []; for (const [name, state] of map) { if (state.showMatches.value) { filterBySegmentation.push(name); } const {layerName} = state.layerRef; if (layerName !== undefined) { (linkedJson = linkedJson || {})[name] = layerName; } } filterBySegmentation.sort(); return { [LINKED_SEGMENTATION_LAYER_JSON_KEY]: linkedJson, [FILTER_BY_SEGMENTATION_JSON_KEY]: filterBySegmentation.length === 0 ? undefined : filterBySegmentation, }; } restoreState(json: any) { const {isLoading} = this.annotationStates; verifyOptionalObjectProperty(json, LINKED_SEGMENTATION_LAYER_JSON_KEY, linkedJson => { if (typeof linkedJson === 'string') { linkedJson = {'segments': linkedJson}; } verifyObject(linkedJson); for (const key of Object.keys(linkedJson)) { const value = verifyString(linkedJson[key]); let state = this.map.get(key); if (state === undefined) { if (!isLoading) continue; state = this.addRelationship(key); } state.layerRef.layerName = value; } for (const [relationship, state] of this.map) { if (!Object.prototype.hasOwnProperty.call(linkedJson, relationship)) { state.layerRef.layerName = undefined; } } }); verifyOptionalObjectProperty(json, FILTER_BY_SEGMENTATION_JSON_KEY, filterJson => { if (typeof filterJson === 'boolean') { filterJson = (filterJson === true) ? ['segments'] : []; } for (const key of verifyStringArray(filterJson)) { let state = this.map.get(key); if (state === undefined) { if (!isLoading) continue; state = this.addRelationship(key); } state.showMatches.value = true; } }); } disposed() { const {map} = this; for (const state of map.values()) { this.unbind(state); } map.clear(); super.disposed(); } private map = new Map<string, LinkedSegmentationLayer>(); } class LinkedSegmentationLayerWidget extends RefCounted { element = document.createElement('label'); seenGeneration = -1; constructor(public relationship: string, public state: LinkedSegmentationLayer) { super(); const {element} = this; const checkboxWidget = this.registerDisposer(new TrackableBooleanCheckbox(state.showMatches)); const layerWidget = new LayerReferenceWidget(state.layerRef); element.appendChild(checkboxWidget.element); element.appendChild(document.createTextNode(relationship)); element.appendChild(layerWidget.element); } } class LinkedSegmentationLayersWidget extends RefCounted { widgets = new Map<string, LinkedSegmentationLayerWidget>(); element = document.createElement('div'); constructor(public linkedSegmentationLayers: LinkedSegmentationLayers) { super(); this.element.style.display = 'contents'; const debouncedUpdateView = this.registerCancellable(animationFrameDebounce(() => this.updateView())); this.registerDisposer( this.linkedSegmentationLayers.annotationStates.changed.add(debouncedUpdateView)); this.updateView(); } private updateView() { const {linkedSegmentationLayers} = this; const {annotationStates} = linkedSegmentationLayers; const generation = annotationStates.changed.count; const {widgets} = this; function* getChildren(this: LinkedSegmentationLayersWidget) { for (const relationship of annotationStates.relationships) { let widget = widgets.get(relationship); if (widget === undefined) { widget = new LinkedSegmentationLayerWidget( relationship, linkedSegmentationLayers.get(relationship)); } widget.seenGeneration = generation; yield widget.element; } } for (const [relationship, widget] of widgets) { if (widget.seenGeneration !== generation) { widget.dispose(); widgets.delete(relationship); } } updateChildren(this.element, getChildren.call(this)); } disposed() { super.disposed(); for (const widget of this.widgets.values()) { widget.dispose(); } } } const Base = UserLayerWithAnnotationsMixin(UserLayer); export class AnnotationUserLayer extends Base { localAnnotations: LocalAnnotationSource|undefined; private localAnnotationProperties: AnnotationPropertySpec[]|undefined; private localAnnotationRelationships: string[]; annotationProperties = new WatchableValue<AnnotationPropertySpec[]|undefined>(undefined); private localAnnotationsJson: any = undefined; private pointAnnotationsJson: any = undefined; linkedSegmentationLayers = this.registerDisposer(new LinkedSegmentationLayers( this.manager.rootLayers, this.annotationStates, this.annotationDisplayState)); disposed() { const {localAnnotations} = this; if (localAnnotations !== undefined) { localAnnotations.dispose(); } super.disposed(); } constructor(managedLayer: Borrowed<ManagedUserLayer>) { super(managedLayer); this.linkedSegmentationLayers.changed.add(this.specificationChanged.dispatch); this.annotationDisplayState.ignoreNullSegmentFilter.changed.add( this.specificationChanged.dispatch); this.annotationCrossSectionRenderScaleTarget.changed.add(this.specificationChanged.dispatch); this.tabs.add( 'rendering', {label: 'Rendering', order: -100, getter: () => new RenderingOptionsTab(this)}); this.tabs.default = 'annotations'; } restoreState(specification: any) { super.restoreState(specification); this.linkedSegmentationLayers.restoreState(specification); this.localAnnotationsJson = specification[ANNOTATIONS_JSON_KEY]; this.localAnnotationProperties = verifyOptionalObjectProperty( specification, ANNOTATION_PROPERTIES_JSON_KEY, parseAnnotationPropertySpecs); this.localAnnotationRelationships = verifyOptionalObjectProperty( specification, ANNOTATION_RELATIONSHIPS_JSON_KEY, verifyStringArray, ['segments']); this.pointAnnotationsJson = specification[POINTS_JSON_KEY]; this.annotationCrossSectionRenderScaleTarget.restoreState( specification[CROSS_SECTION_RENDER_SCALE_JSON_KEY]); this.annotationProjectionRenderScaleTarget.restoreState( specification[PROJECTION_RENDER_SCALE_JSON_KEY]); this.annotationDisplayState.ignoreNullSegmentFilter.restoreState( specification[IGNORE_NULL_SEGMENT_FILTER_JSON_KEY]); this.annotationDisplayState.shader.restoreState(specification[SHADER_JSON_KEY]); this.annotationDisplayState.shaderControls.restoreState( specification[SHADER_CONTROLS_JSON_KEY]); } getLegacyDataSourceSpecifications( sourceSpec: any, layerSpec: any, legacyTransform: CoordinateTransformSpecification|undefined, explicitSpecs: DataSourceSpecification[]): DataSourceSpecification[] { if (Object.prototype.hasOwnProperty.call(layerSpec, 'source')) { return super.getLegacyDataSourceSpecifications( sourceSpec, layerSpec, legacyTransform, explicitSpecs); } const scales = verifyOptionalObjectProperty( layerSpec, 'voxelSize', voxelSizeObj => parseFixedLengthArray( new Float64Array(3), voxelSizeObj, x => verifyFinitePositiveFloat(x) / 1e9)); const units = ['m', 'm', 'm']; if (scales !== undefined) { const inputSpace = makeCoordinateSpace({rank: 3, units, scales, names: ['x', 'y', 'z']}); if (legacyTransform === undefined) { legacyTransform = { outputSpace: inputSpace, sourceRank: 3, transform: undefined, inputSpace, }; } else { legacyTransform = { ...legacyTransform, inputSpace, }; } } return [{ url: localAnnotationsUrl, transform: legacyTransform, enableDefaultSubsources: true, subsources: new Map(), }]; } activateDataSubsources(subsources: Iterable<LoadedDataSubsource>) { let hasLocalAnnotations = false; let properties: AnnotationPropertySpec[]|undefined; for (const loadedSubsource of subsources) { const {subsourceEntry} = loadedSubsource; const {local} = subsourceEntry.subsource; const setProperties = (newProperties: AnnotationPropertySpec[]) => { if (properties !== undefined && stableStringify(newProperties) !== stableStringify(properties)) { loadedSubsource.deactivate('Annotation properties are not compatible'); return false; } properties = newProperties; return true; }; if (local === LocalDataSource.annotations) { if (hasLocalAnnotations) { loadedSubsource.deactivate('Only one local annotations source per layer is supported'); continue; } hasLocalAnnotations = true; if (!setProperties(this.localAnnotationProperties ?? [])) continue; loadedSubsource.activate(refCounted => { const localAnnotations = this.localAnnotations = new LocalAnnotationSource( loadedSubsource.loadedDataSource.transform, this.localAnnotationProperties ?? [], this.localAnnotationRelationships); try { localAnnotations.restoreState(this.localAnnotationsJson); } catch { } refCounted.registerDisposer(() => { localAnnotations.dispose(); this.localAnnotations = undefined; }); refCounted.registerDisposer( this.localAnnotations.changed.add(this.specificationChanged.dispatch)); try { addPointAnnotations(this.localAnnotations, this.pointAnnotationsJson); } catch { } this.pointAnnotationsJson = undefined; this.localAnnotationsJson = undefined; const state = new AnnotationLayerState({ localPosition: this.localPosition, transform: refCounted.registerDisposer(getWatchableRenderLayerTransform( this.manager.root.coordinateSpace, this.localPosition.coordinateSpace, loadedSubsource.loadedDataSource.transform, undefined)), source: localAnnotations.addRef(), displayState: this.annotationDisplayState, dataSource: loadedSubsource.loadedDataSource.layerDataSource, subsourceIndex: loadedSubsource.subsourceIndex, subsourceId: subsourceEntry.id, role: RenderLayerRole.ANNOTATION, }); this.addAnnotationLayerState(state, loadedSubsource); }); continue; } const {annotation} = subsourceEntry.subsource; if (annotation !== undefined) { if (!setProperties(annotation.properties)) continue; loadedSubsource.activate(() => { const state = new AnnotationLayerState({ localPosition: this.localPosition, transform: loadedSubsource.getRenderLayerTransform(), source: annotation, displayState: this.annotationDisplayState, dataSource: loadedSubsource.loadedDataSource.layerDataSource, subsourceIndex: loadedSubsource.subsourceIndex, subsourceId: subsourceEntry.id, role: RenderLayerRole.ANNOTATION, }); this.addAnnotationLayerState(state, loadedSubsource); }); continue; } loadedSubsource.deactivate('Not compatible with annotation layer'); } const prevAnnotationProperties = this.annotationProperties.value; if (stableStringify(prevAnnotationProperties) !== stableStringify(properties)) { this.annotationProperties.value = properties; } } initializeAnnotationLayerViewTab(tab: AnnotationLayerView) { const hasChunkedSource = tab.registerDisposer(makeCachedLazyDerivedWatchableValue( states => states.some(x => x.source instanceof MultiscaleAnnotationSource), this.annotationStates)); const renderScaleControls = tab.registerDisposer( new DependentViewWidget(hasChunkedSource, (hasChunkedSource, parent, refCounted) => { if (!hasChunkedSource) return; { const renderScaleWidget = refCounted.registerDisposer(new RenderScaleWidget( this.annotationCrossSectionRenderScaleHistogram, this.annotationCrossSectionRenderScaleTarget)); renderScaleWidget.label.textContent = 'Spacing (cross section)'; parent.appendChild(renderScaleWidget.element); } { const renderScaleWidget = refCounted.registerDisposer(new RenderScaleWidget( this.annotationProjectionRenderScaleHistogram, this.annotationProjectionRenderScaleTarget)); renderScaleWidget.label.textContent = 'Spacing (projection)'; parent.appendChild(renderScaleWidget.element); } })); tab.element.insertBefore(renderScaleControls.element, tab.element.firstChild); { const checkbox = tab.registerDisposer( new TrackableBooleanCheckbox(this.annotationDisplayState.ignoreNullSegmentFilter)); const label = document.createElement('label'); label.appendChild(document.createTextNode('Ignore null related segment filter')); label.title = 'Display all annotations if filtering by related segments is enabled but no segments are selected'; label.appendChild(checkbox.element); tab.element.appendChild(label); } tab.element.appendChild( tab.registerDisposer(new LinkedSegmentationLayersWidget(this.linkedSegmentationLayers)) .element); } toJSON() { const x = super.toJSON(); x[CROSS_SECTION_RENDER_SCALE_JSON_KEY] = this.annotationCrossSectionRenderScaleTarget.toJSON(); x[PROJECTION_RENDER_SCALE_JSON_KEY] = this.annotationProjectionRenderScaleTarget.toJSON(); if (this.localAnnotations !== undefined) { x[ANNOTATIONS_JSON_KEY] = this.localAnnotations.toJSON(); } else if (this.localAnnotationsJson !== undefined) { x[ANNOTATIONS_JSON_KEY] = this.localAnnotationsJson; } x[ANNOTATION_PROPERTIES_JSON_KEY] = annotationPropertySpecsToJson(this.localAnnotationProperties); const {localAnnotationRelationships} = this; x[ANNOTATION_RELATIONSHIPS_JSON_KEY] = (localAnnotationRelationships.length === 1 && localAnnotationRelationships[0] === 'segments') ? undefined : localAnnotationRelationships; x[IGNORE_NULL_SEGMENT_FILTER_JSON_KEY] = this.annotationDisplayState.ignoreNullSegmentFilter.toJSON(); x[SHADER_JSON_KEY] = this.annotationDisplayState.shader.toJSON(); x[SHADER_CONTROLS_JSON_KEY] = this.annotationDisplayState.shaderControls.toJSON(); Object.assign(x, this.linkedSegmentationLayers.toJSON()); return x; } static type = 'annotation'; static typeAbbreviation = 'ann'; } function makeShaderCodeWidget(layer: AnnotationUserLayer) { return new ShaderCodeWidget({ shaderError: layer.annotationDisplayState.shaderError, fragmentMain: layer.annotationDisplayState.shader, shaderControlState: layer.annotationDisplayState.shaderControls, }); } class ShaderCodeOverlay extends Overlay { codeWidget = this.registerDisposer(makeShaderCodeWidget(this.layer)); constructor(public layer: AnnotationUserLayer) { super(); this.content.appendChild(this.codeWidget.element); this.codeWidget.textEditor.refresh(); } } class RenderingOptionsTab extends Tab { codeWidget = this.registerDisposer(makeShaderCodeWidget(this.layer)); constructor(public layer: AnnotationUserLayer) { super(); const {element} = this; element.classList.add('neuroglancer-annotation-rendering-tab'); element.appendChild( this .registerDisposer(new DependentViewWidget( layer.annotationProperties, (properties, parent) => { if (properties === undefined || properties.length === 0) return; const propertyList = document.createElement('div'); parent.appendChild(propertyList); propertyList.classList.add('neuroglancer-annotation-shader-property-list'); for (const property of properties) { const div = document.createElement('div'); div.classList.add('neuroglancer-annotation-shader-property'); const typeElement = document.createElement('span'); typeElement.classList.add('neuroglancer-annotation-shader-property-type'); typeElement.textContent = property.type; const nameElement = document.createElement('span'); nameElement.classList.add('neuroglancer-annotation-shader-property-identifier'); nameElement.textContent = `prop_${property.identifier}`; div.appendChild(typeElement); div.appendChild(nameElement); const {description} = property; if (description !== undefined) { div.title = description; } propertyList.appendChild(div); } })) .element); let topRow = document.createElement('div'); topRow.className = 'neuroglancer-segmentation-dropdown-skeleton-shader-header'; let label = document.createElement('div'); label.style.flex = '1'; label.textContent = 'Annotation shader:'; topRow.appendChild(label); topRow.appendChild(makeMaximizeButton({ title: 'Show larger editor view', onClick: () => { new ShaderCodeOverlay(this.layer); } })); topRow.appendChild(makeHelpButton({ title: 'Documentation on annotation rendering', href: 'https://github.com/google/neuroglancer/blob/master/src/neuroglancer/annotation/rendering.md', })); element.appendChild(topRow); element.appendChild(this.codeWidget.element); element.appendChild(this.registerDisposer(new ShaderControls( layer.annotationDisplayState.shaderControls, this.layer.manager.root.display, this.layer, {visibility: this.visibility})) .element); } } registerLayerType(AnnotationUserLayer); registerLayerType(AnnotationUserLayer, 'pointAnnotation'); registerLayerTypeDetector(subsource => { if (subsource.local === LocalDataSource.annotations) { return {layerConstructor: AnnotationUserLayer, priority: 100}; } if (subsource.annotation !== undefined) { return {layerConstructor: AnnotationUserLayer, priority: 1}; } return undefined; }); registerLayerShaderControlsTool( AnnotationUserLayer, layer => ({ shaderControlState: layer.annotationDisplayState.shaderControls, }));
the_stack
// (Desktop|Mobile|Android|iOS[CLI): (New|Improved|Fixed): Some message..... (#ISSUE) import { execCommand, githubUsername } from './tool-utils'; interface LogEntry { message: string; commit: string; author: Author; } enum Platform { Android = 'android', Ios = 'ios', Desktop = 'desktop', Clipper = 'clipper', Server = 'server', Cli = 'cli', PluginGenerator = 'plugin-generator', } enum PublishFormat { Full = 'full', Simple = 'simple', } interface Options { publishFormat: PublishFormat; } interface Author { email: string; name: string; login: string; } // From https://stackoverflow.com/a/6234804/561309 function escapeHtml(unsafe: string) { // We only escape <> as this is enough for Markdown return unsafe .replace(/</g, '&lt;') .replace(/>/g, '&gt;'); } async function gitLog(sinceTag: string) { const commandResult = await execCommand(`git log --pretty=format:"%H::::DIV::::%ae::::DIV::::%an::::DIV::::%s" ${sinceTag}..HEAD`); const lines = commandResult.split('\n'); const output = []; for (const line of lines) { if (!line.trim()) continue; const splitted = line.split('::::DIV::::'); const commit = splitted[0]; const authorEmail = splitted[1]; const authorName = splitted[2]; const message = splitted[3].trim(); output.push({ commit: commit, message: message, author: { email: authorEmail, name: authorName, login: await githubUsername(authorEmail, authorName), }, }); } return output; } async function gitTags() { const lines: string = await execCommand('git tag --sort=committerdate'); return lines.split('\n').map(l => l.trim()).filter(l => !!l); } function platformFromTag(tagName: string): Platform { if (tagName.indexOf('v') === 0) return Platform.Desktop; if (tagName.indexOf('android') >= 0) return Platform.Android; if (tagName.indexOf('ios') >= 0) return Platform.Ios; if (tagName.indexOf('clipper') === 0) return Platform.Clipper; if (tagName.indexOf('cli') === 0) return Platform.Cli; if (tagName.indexOf('server') === 0) return Platform.Server; if (tagName.indexOf('plugin-generator') === 0) return Platform.PluginGenerator; throw new Error(`Could not determine platform from tag: "${tagName}"`); } function filterLogs(logs: LogEntry[], platform: Platform) { const output = []; const revertedLogs = []; // eslint-disable-next-line no-unused-vars, @typescript-eslint/no-unused-vars // let updatedTranslations = false; for (const log of logs) { // Save to an array any commit that has been reverted, and exclude // these from the final output array. const revertMatches = log.message.split('\n')[0].trim().match(/^Revert "(.*?)"$/); if (revertMatches && revertMatches.length >= 2) { revertedLogs.push(revertMatches[1]); continue; } if (revertedLogs.indexOf(log.message) >= 0) continue; let prefix = log.message.trim().toLowerCase().split(':'); if (prefix.length <= 1) continue; prefix = prefix[0].split(',').map(s => s.trim()); let addIt = false; // "All" refers to desktop, CLI and mobile app. Clipper and Server are not included. if (prefix.indexOf('all') >= 0 && (platform !== 'clipper' && platform !== 'server')) addIt = true; if ((platform === 'android' || platform === 'ios') && prefix.indexOf('mobile') >= 0) addIt = true; if (platform === 'android' && prefix.indexOf('android') >= 0) addIt = true; if (platform === 'ios' && prefix.indexOf('ios') >= 0) addIt = true; if (platform === 'desktop' && prefix.indexOf('desktop') >= 0) addIt = true; if (platform === 'desktop' && (prefix.indexOf('desktop') >= 0 || prefix.indexOf('api') >= 0 || prefix.indexOf('plugins') >= 0 || prefix.indexOf('macos') >= 0)) addIt = true; if (platform === 'cli' && prefix.indexOf('cli') >= 0) addIt = true; if (platform === 'clipper' && prefix.indexOf('clipper') >= 0) addIt = true; if (platform === 'server' && prefix.indexOf('server') >= 0) addIt = true; // Translation updates often comes in format "Translation: Update pt_PT.po" // but that's not useful in a changelog especially since most people // don't know country and language codes. So we catch all these and // bundle them all up in a single "Updated translations" at the end. if (log.message.match(/Translation: Update .*?\.po/)) { // updatedTranslations = true; addIt = false; } if (addIt) output.push(log); } // Actually we don't really need this info - translations are being updated all the time // if (updatedTranslations) output.push({ message: 'Updated translations' }); return output; } function formatCommitMessage(commit: string, msg: string, author: Author, options: Options): string { options = Object.assign({}, { publishFormat: 'full' }, options); let output = ''; const splitted = msg.split(':'); let subModule = ''; const isPlatformPrefix = (prefixString: string) => { const prefix = prefixString.split(',').map(p => p.trim().toLowerCase()); for (const p of prefix) { if (['android', 'mobile', 'ios', 'desktop', 'cli', 'clipper', 'all', 'api', 'plugins', 'server'].indexOf(p) >= 0) return true; } return false; }; if (splitted.length) { const platform = splitted[0].trim().toLowerCase(); if (platform === 'api') subModule = 'api'; if (platform === 'plugins') subModule = 'plugins'; if (isPlatformPrefix(platform)) { splitted.splice(0, 1); } output = splitted.join(':'); } output = output.split('\n')[0].trim(); const detectType = (msg: string) => { msg = msg.trim().toLowerCase(); if (msg.indexOf('fix') === 0) return 'fixed'; if (msg.indexOf('add') === 0) return 'new'; if (msg.indexOf('change') === 0) return 'improved'; if (msg.indexOf('update') === 0) return 'improved'; if (msg.indexOf('improve') === 0) return 'improved'; return 'improved'; }; const parseCommitMessage = (msg: string, subModule: string) => { const parts = msg.split(':'); if (parts.length === 1) { return { type: detectType(msg), message: msg.trim(), subModule: subModule, }; } let originalType = parts[0].trim(); let t = originalType.toLowerCase(); parts.splice(0, 1); let message = parts.join(':').trim(); let type = null; // eg. "All: Resolves #712: New: Support for note history (#1415)" // "Resolves" doesn't tell us if it's new or improved so check the // third token (which in this case is "new"). if (t.indexOf('resolves') === 0 && ['new', 'improved', 'fixed'].indexOf(parts[0].trim().toLowerCase()) >= 0) { t = parts[0].trim().toLowerCase(); parts.splice(0, 1); message = parts.join(':').trim(); } else if (t.indexOf('resolves') === 0) { // If we didn't have the third token default to "improved" t = 'improved'; message = parts.join(':').trim(); } if (t.indexOf('fix') === 0) type = 'fixed'; if (t.indexOf('new') === 0) type = 'new'; if (t.indexOf('improved') === 0) type = 'improved'; if (t.indexOf('security') === 0) type = 'security'; if (!type) { type = detectType(message); if (originalType.toLowerCase() === 'tinymce') originalType = 'WYSIWYG'; message = `${originalType}: ${message}`; } const issueNumberMatch = output.match(/#(\d+)/); const issueNumber = issueNumberMatch && issueNumberMatch.length >= 2 ? issueNumberMatch[1] : null; return { type: type, message: message, issueNumber: issueNumber, subModule: subModule, }; }; const commitMessage = parseCommitMessage(output, subModule); const messagePieces = []; messagePieces.push(`${capitalizeFirstLetter(commitMessage.type)}`); if (commitMessage.subModule) messagePieces.push(`${capitalizeFirstLetter(commitMessage.subModule)}`); messagePieces.push(`${capitalizeFirstLetter(commitMessage.message)}`); output = messagePieces.join(': '); const issueRegex = /\((#[0-9]+)\)$/; if (options.publishFormat === 'full') { if (commitMessage.issueNumber) { const formattedIssueNum = `(#${commitMessage.issueNumber})`; if (output.indexOf(formattedIssueNum) < 0) output += ` ${formattedIssueNum}`; } let authorMd = null; const isLaurent = author.login === 'laurent22' || author.email === 'laurent22@users.noreply.github.com'; if (author && (author.login || author.name) && !isLaurent) { if (author.login) { const escapedLogin = author.login.replace(/\]/g, ''); authorMd = `[@${escapedLogin}](https://github.com/${encodeURI(author.login)})`; } else { authorMd = `${author.name}`; } } if (output.match(issueRegex)) { if (authorMd) { output = output.replace(issueRegex, `($1 by ${authorMd})`); } } else { const commitStrings = [commit.substr(0, 7)]; if (authorMd) commitStrings.push(`by ${authorMd}`); output += ` (${commitStrings.join(' ')})`; } } if (options.publishFormat !== 'full') { output = output.replace(issueRegex, ''); } return escapeHtml(output); } function createChangeLog(logs: LogEntry[], options: Options) { const output = []; for (const log of logs) { output.push(formatCommitMessage(log.commit, log.message, log.author, options)); } return output; } function capitalizeFirstLetter(string: string) { return string.charAt(0).toUpperCase() + string.slice(1); } // This function finds the first relevant tag starting from the given tag. // The first "relevant tag" is the one that exists, and from which there are changes. async function findFirstRelevantTag(baseTag: string, platform: Platform, allTags: string[]) { let baseTagIndex = allTags.indexOf(baseTag); if (baseTagIndex < 0) baseTagIndex = allTags.length; for (let i = baseTagIndex - 1; i >= 0; i--) { const tag = allTags[i]; if (platformFromTag(tag) !== platform) continue; try { const logs = await gitLog(tag); const filteredLogs = filterLogs(logs, platform); if (filteredLogs.length) return tag; } catch (error) { if (error.message.indexOf('unknown revision') >= 0) { // We skip the error - it means this particular tag has never been created } else { throw error; } } } throw new Error(`Could not find previous tag for: ${baseTag}`); } async function main() { const argv = require('yargs').argv; if (!argv._.length) throw new Error('Tag name must be specified. Provide the tag of the new version and git-changelog will walk backward to find the changes to the previous relevant tag.'); const allTags = await gitTags(); const fromTagName = argv._[0]; let toTagName = argv._.length >= 2 ? argv._[1] : ''; const platform = platformFromTag(fromTagName); if (!toTagName) toTagName = await findFirstRelevantTag(fromTagName, platform, allTags); const logsSinceTags = await gitLog(toTagName); const filteredLogs = filterLogs(logsSinceTags, platform); let publishFormat: PublishFormat = PublishFormat.Full; if (['android', 'ios'].indexOf(platform) >= 0) publishFormat = PublishFormat.Simple; if (argv.publishFormat) publishFormat = argv.publishFormat; let changelog = createChangeLog(filteredLogs, { publishFormat: publishFormat }); const changelogFixes = []; const changelogImproves = []; const changelogNews = []; for (const l of changelog) { if (l.indexOf('Fix') === 0 || l.indexOf('Security') === 0) { changelogFixes.push(l); } else if (l.indexOf('Improve') === 0) { changelogImproves.push(l); } else if (l.indexOf('New') === 0) { changelogNews.push(l); } else { throw new Error(`Invalid changelog line: ${l}`); } } changelogFixes.sort(); changelogImproves.sort(); changelogNews.sort(); changelog = [].concat(changelogNews).concat(changelogImproves).concat(changelogFixes); const changelogString = changelog.map(l => `- ${l}`); console.info(changelogString.join('\n')); } main().catch((error) => { console.error('Fatal error'); console.error(error); process.exit(1); });
the_stack
import { MetadataBearer as $MetadataBearer, SmithyException as __SmithyException } from "@aws-sdk/types"; export enum EncryptionMode { SSE_KMS = "SSE_KMS", SSE_S3 = "SSE_S3", } /** * <p>A structure that contains the configuration of encryption-at-rest settings for canary artifacts that the canary * uploads to Amazon S3. </p> * <p>For more information, see * <a href="https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/CloudWatch_Synthetics_artifact_encryption.html">Encrypting canary artifacts</a> * </p> */ export interface S3EncryptionConfig { /** * <p> The encryption method to use for artifacts created by this canary. Specify <code>SSE_S3</code> to use * server-side encryption (SSE) with an Amazon S3-managed * key. Specify <code>SSE-KMS</code> to use server-side encryption with a customer-managed KMS key.</p> * <p>If you omit this parameter, an * Amazon Web Services-managed KMS key is used. * </p> */ EncryptionMode?: EncryptionMode | string; /** * <p>The ARN of the customer-managed KMS key to use, if you specify <code>SSE-KMS</code> * for <code>EncryptionMode</code> * </p> */ KmsKeyArn?: string; } export namespace S3EncryptionConfig { /** * @internal */ export const filterSensitiveLog = (obj: S3EncryptionConfig): any => ({ ...obj, }); } /** * <p>A structure that contains the configuration for canary artifacts, including the * encryption-at-rest settings for artifacts that the canary uploads to Amazon S3.</p> */ export interface ArtifactConfigInput { /** * <p>A structure that contains the configuration of the encryption-at-rest settings for artifacts that the canary uploads * to Amazon S3. * Artifact encryption functionality is available only for canaries that use Synthetics runtime version * syn-nodejs-puppeteer-3.3 or later. For more information, see * <a href="https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/CloudWatch_Synthetics_artifact_encryption.html">Encrypting canary artifacts</a> * </p> */ S3Encryption?: S3EncryptionConfig; } export namespace ArtifactConfigInput { /** * @internal */ export const filterSensitiveLog = (obj: ArtifactConfigInput): any => ({ ...obj, }); } /** * <p>A structure that contains the configuration for canary artifacts, including * the encryption-at-rest settings for artifacts that the canary uploads to Amazon S3.</p> */ export interface ArtifactConfigOutput { /** * <p>A structure that contains the configuration of encryption settings for canary artifacts that are stored in Amazon S3. </p> */ S3Encryption?: S3EncryptionConfig; } export namespace ArtifactConfigOutput { /** * @internal */ export const filterSensitiveLog = (obj: ArtifactConfigOutput): any => ({ ...obj, }); } /** * <p>A structure representing a screenshot that is used as a baseline during visual monitoring comparisons made by the canary.</p> */ export interface BaseScreenshot { /** * <p>The name of the screenshot. This is generated the first time the canary is run after the <code>UpdateCanary</code> operation that * specified for this canary to perform visual monitoring.</p> */ ScreenshotName: string | undefined; /** * <p>Coordinates that define the part of a screen to ignore during screenshot comparisons. To obtain the coordinates to use here, use the * CloudWatch Logs console to draw the boundaries on the screen. For more information, see {LINK}</p> */ IgnoreCoordinates?: string[]; } export namespace BaseScreenshot { /** * @internal */ export const filterSensitiveLog = (obj: BaseScreenshot): any => ({ ...obj, }); } /** * <p>This structure contains information about the canary's Lambda handler and * where its code is stored by CloudWatch Synthetics.</p> */ export interface CanaryCodeOutput { /** * <p>The ARN of the Lambda layer where Synthetics stores the canary script code.</p> */ SourceLocationArn?: string; /** * <p>The entry point to use for the source code when running the canary.</p> */ Handler?: string; } export namespace CanaryCodeOutput { /** * @internal */ export const filterSensitiveLog = (obj: CanaryCodeOutput): any => ({ ...obj, }); } /** * <p>A structure that contains information about a canary run.</p> */ export interface CanaryRunConfigOutput { /** * <p>How long the canary is allowed to run before it must stop.</p> */ TimeoutInSeconds?: number; /** * <p>The maximum amount of memory available to the canary while it is running, in MB. This value * must be a multiple of 64.</p> */ MemoryInMB?: number; /** * <p>Displays whether this canary run used active X-Ray tracing. </p> */ ActiveTracing?: boolean; } export namespace CanaryRunConfigOutput { /** * @internal */ export const filterSensitiveLog = (obj: CanaryRunConfigOutput): any => ({ ...obj, }); } /** * <p>How long, in seconds, for the canary to continue making regular runs according to the schedule in the * <code>Expression</code> value.</p> */ export interface CanaryScheduleOutput { /** * <p>A <code>rate</code> expression or a <code>cron</code> expression that defines how often the canary is to run.</p> * <p>For a rate expression, The syntax is * <code>rate(<i>number unit</i>)</code>. <i>unit</i> * can be <code>minute</code>, <code>minutes</code>, or <code>hour</code>. </p> * <p>For example, <code>rate(1 minute)</code> runs the canary once a minute, <code>rate(10 minutes)</code> runs it once every * 10 minutes, and <code>rate(1 hour)</code> runs it once every hour. You can * specify a frequency between <code>rate(1 minute)</code> and <code>rate(1 hour)</code>.</p> * <p>Specifying <code>rate(0 minute)</code> or <code>rate(0 hour)</code> is a special value * that causes the * canary to run only once when it is started.</p> * <p>Use <code>cron(<i>expression</i>)</code> to specify a cron * expression. For information about the syntax for cron expressions, see * <a href="https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/CloudWatch_Synthetics_Canaries_cron.html"> * Scheduling canary runs using cron</a>.</p> */ Expression?: string; /** * <p>How long, in seconds, for the canary to continue making regular runs after it * was created. The runs are performed according to the schedule in the * <code>Expression</code> value.</p> */ DurationInSeconds?: number; } export namespace CanaryScheduleOutput { /** * @internal */ export const filterSensitiveLog = (obj: CanaryScheduleOutput): any => ({ ...obj, }); } export enum CanaryState { CREATING = "CREATING", DELETING = "DELETING", ERROR = "ERROR", READY = "READY", RUNNING = "RUNNING", STARTING = "STARTING", STOPPED = "STOPPED", STOPPING = "STOPPING", UPDATING = "UPDATING", } export enum CanaryStateReasonCode { INVALID_PERMISSIONS = "INVALID_PERMISSIONS", } /** * <p>A structure that contains the current state of the canary.</p> */ export interface CanaryStatus { /** * <p>The current state of the canary.</p> */ State?: CanaryState | string; /** * <p>If the canary has insufficient permissions to run, this field provides more details.</p> */ StateReason?: string; /** * <p>If the canary cannot run or has failed, this field displays the reason.</p> */ StateReasonCode?: CanaryStateReasonCode | string; } export namespace CanaryStatus { /** * @internal */ export const filterSensitiveLog = (obj: CanaryStatus): any => ({ ...obj, }); } /** * <p>This structure contains information about when the canary was created and modified.</p> */ export interface CanaryTimeline { /** * <p>The date and time the canary was created.</p> */ Created?: Date; /** * <p>The date and time the canary was most recently modified.</p> */ LastModified?: Date; /** * <p>The date and time that the canary's most recent run started.</p> */ LastStarted?: Date; /** * <p>The date and time that the canary's most recent run ended.</p> */ LastStopped?: Date; } export namespace CanaryTimeline { /** * @internal */ export const filterSensitiveLog = (obj: CanaryTimeline): any => ({ ...obj, }); } /** * <p>If this canary performs visual monitoring by comparing screenshots, this structure contains the ID of the canary run that is used as the baseline for screenshots, and the coordinates * of any parts of those screenshots that are ignored during visual monitoring comparison.</p> * <p>Visual monitoring is supported only on canaries running the <b>syn-puppeteer-node-3.2</b> runtime or later.</p> */ export interface VisualReferenceOutput { /** * <p>An array of screenshots that are used as the baseline for comparisons during visual monitoring.</p> */ BaseScreenshots?: BaseScreenshot[]; /** * <p>The ID of the canary run that produced the screenshots that are used as the baseline for visual monitoring comparisons during future runs of this canary.</p> */ BaseCanaryRunId?: string; } export namespace VisualReferenceOutput { /** * @internal */ export const filterSensitiveLog = (obj: VisualReferenceOutput): any => ({ ...obj, }); } /** * <p>If this canary is to test an endpoint in a VPC, this structure contains * information about the subnets and security groups of the VPC endpoint. * For more information, see <a href="https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/CloudWatch_Synthetics_Canaries_VPC.html"> * Running a Canary in a VPC</a>.</p> */ export interface VpcConfigOutput { /** * <p>The IDs of the VPC where this canary is to run.</p> */ VpcId?: string; /** * <p>The IDs of the subnets where this canary is to run.</p> */ SubnetIds?: string[]; /** * <p>The IDs of the security groups for this canary.</p> */ SecurityGroupIds?: string[]; } export namespace VpcConfigOutput { /** * @internal */ export const filterSensitiveLog = (obj: VpcConfigOutput): any => ({ ...obj, }); } /** * <p>This structure contains all information about one canary in your account.</p> */ export interface Canary { /** * <p>The unique ID of this canary.</p> */ Id?: string; /** * <p>The name of the canary.</p> */ Name?: string; /** * <p>This structure contains information about the canary's Lambda handler and * where its code is stored by CloudWatch Synthetics.</p> */ Code?: CanaryCodeOutput; /** * <p>The ARN of the IAM role used to run the canary. This role must include <code>lambda.amazonaws.com</code> as a principal in the trust * policy.</p> */ ExecutionRoleArn?: string; /** * <p>A structure that contains information about how often the canary is to run, and when * these runs are to stop.</p> */ Schedule?: CanaryScheduleOutput; /** * <p>A structure that contains information about a canary run.</p> */ RunConfig?: CanaryRunConfigOutput; /** * <p>The number of days to retain data about successful runs of this canary.</p> */ SuccessRetentionPeriodInDays?: number; /** * <p>The number of days to retain data about failed runs of this canary.</p> */ FailureRetentionPeriodInDays?: number; /** * <p>A structure that contains information about the canary's status.</p> */ Status?: CanaryStatus; /** * <p>A structure that contains information about when the canary was created, modified, and * most recently run.</p> */ Timeline?: CanaryTimeline; /** * <p>The location in Amazon S3 where Synthetics stores artifacts from the runs of this * canary. Artifacts include the log file, screenshots, and HAR files.</p> */ ArtifactS3Location?: string; /** * <p>The ARN of the Lambda function that is used as your canary's engine. For more information * about Lambda ARN format, see <a href="https://docs.aws.amazon.com/lambda/latest/dg/lambda-api-permissions-ref.html">Resources and Conditions for Lambda Actions</a>.</p> */ EngineArn?: string; /** * <p>Specifies the runtime version to use for the canary. For more information about * runtime versions, see <a href="https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/CloudWatch_Synthetics_Canaries_Library.html"> * Canary Runtime Versions</a>.</p> */ RuntimeVersion?: string; /** * <p>If this canary is to test an endpoint in a VPC, this structure contains * information about the subnets and security groups of the VPC endpoint. * For more information, see <a href="https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/CloudWatch_Synthetics_Canaries_VPC.html"> * Running a Canary in a VPC</a>.</p> */ VpcConfig?: VpcConfigOutput; /** * <p>If this canary performs visual monitoring by comparing screenshots, this structure contains the ID of the canary run to use as the baseline for screenshots, and the coordinates * of any parts of the screen to ignore during the visual monitoring comparison.</p> */ VisualReference?: VisualReferenceOutput; /** * <p>The list of key-value pairs that are associated with the canary.</p> */ Tags?: { [key: string]: string }; /** * <p>A structure that contains the configuration for canary artifacts, including * the encryption-at-rest settings for artifacts that the canary uploads to Amazon S3.</p> */ ArtifactConfig?: ArtifactConfigOutput; } export namespace Canary { /** * @internal */ export const filterSensitiveLog = (obj: Canary): any => ({ ...obj, }); } export enum CanaryRunState { FAILED = "FAILED", PASSED = "PASSED", RUNNING = "RUNNING", } export enum CanaryRunStateReasonCode { CANARY_FAILURE = "CANARY_FAILURE", EXECUTION_FAILURE = "EXECUTION_FAILURE", } /** * <p>This structure contains the status information about a canary run.</p> */ export interface CanaryRunStatus { /** * <p>The current state of the run.</p> */ State?: CanaryRunState | string; /** * <p>If run of the canary failed, this field contains the reason for the error.</p> */ StateReason?: string; /** * <p>If this value is <code>CANARY_FAILURE</code>, an exception occurred in the * canary code. If this value is <code>EXECUTION_FAILURE</code>, an exception occurred in * CloudWatch Synthetics.</p> */ StateReasonCode?: CanaryRunStateReasonCode | string; } export namespace CanaryRunStatus { /** * @internal */ export const filterSensitiveLog = (obj: CanaryRunStatus): any => ({ ...obj, }); } /** * <p>This structure contains the start and end times of a single canary run.</p> */ export interface CanaryRunTimeline { /** * <p>The start time of the run.</p> */ Started?: Date; /** * <p>The end time of the run.</p> */ Completed?: Date; } export namespace CanaryRunTimeline { /** * @internal */ export const filterSensitiveLog = (obj: CanaryRunTimeline): any => ({ ...obj, }); } /** * <p>This structure contains the details about one run of one canary.</p> */ export interface CanaryRun { /** * <p>A unique ID that identifies this canary run.</p> */ Id?: string; /** * <p>The name of the canary.</p> */ Name?: string; /** * <p>The status of this run.</p> */ Status?: CanaryRunStatus; /** * <p>A structure that contains the start and end times of this run.</p> */ Timeline?: CanaryRunTimeline; /** * <p>The location where the canary stored artifacts from the run. Artifacts include * the log file, screenshots, and HAR files.</p> */ ArtifactS3Location?: string; } export namespace CanaryRun { /** * @internal */ export const filterSensitiveLog = (obj: CanaryRun): any => ({ ...obj, }); } /** * <p>This structure contains information about the most recent run of a single canary.</p> */ export interface CanaryLastRun { /** * <p>The name of the canary.</p> */ CanaryName?: string; /** * <p>The results from this canary's most recent run.</p> */ LastRun?: CanaryRun; } export namespace CanaryLastRun { /** * @internal */ export const filterSensitiveLog = (obj: CanaryLastRun): any => ({ ...obj, }); } /** * <p>Use this structure to input your script code for the canary. This structure contains the * Lambda handler with the location where the canary should start running the script. If the * script is stored in an S3 bucket, the bucket name, key, and version are also included. If * the script was passed into the canary directly, the script code is contained in the value * of <code>Zipfile</code>. </p> */ export interface CanaryCodeInput { /** * <p>If your canary script is located in S3, specify the bucket name here. Do not include <code>s3://</code> as the * start of the bucket name.</p> */ S3Bucket?: string; /** * <p>The S3 key of your script. For more information, see <a href="https://docs.aws.amazon.com/AmazonS3/latest/dev/UsingObjects.html">Working with Amazon S3 Objects</a>.</p> */ S3Key?: string; /** * <p>The S3 version ID of your script.</p> */ S3Version?: string; /** * <p>If you input your canary script directly into the canary instead of referring to an S3 * location, the value of this parameter is the base64-encoded contents of the .zip file that * contains the script. It must be smaller than 256 Kb.</p> */ ZipFile?: Uint8Array; /** * <p>The entry point to use for the source code when running the canary. This value must end * with the string <code>.handler</code>. The string is limited to 29 characters or fewer.</p> */ Handler: string | undefined; } export namespace CanaryCodeInput { /** * @internal */ export const filterSensitiveLog = (obj: CanaryCodeInput): any => ({ ...obj, }); } /** * <p>A structure that contains input information for a canary run.</p> */ export interface CanaryRunConfigInput { /** * <p>How long the canary is allowed to run before it must stop. You can't set this time to be longer * than the frequency of the runs of this canary.</p> * <p>If you omit this field, the * frequency of the canary is used as this value, up to a maximum of 14 minutes.</p> */ TimeoutInSeconds?: number; /** * <p>The maximum amount of memory available to the canary while it is running, in MB. This value must be a multiple of 64.</p> */ MemoryInMB?: number; /** * <p>Specifies whether this canary is to use active X-Ray tracing when it runs. Active tracing * enables * this canary run to be displayed in the ServiceLens and X-Ray service maps even if the canary does * not hit an endpoint that has X-Ray tracing enabled. Using X-Ray tracing incurs charges. * For more information, see <a href="https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/CloudWatch_Synthetics_Canaries_tracing.html"> * Canaries and X-Ray tracing</a>.</p> * <p>You can enable active tracing only for canaries that use version <code>syn-nodejs-2.0</code> * or later for their canary runtime.</p> */ ActiveTracing?: boolean; /** * <p>Specifies the keys and values to use for any environment variables * used in the canary script. Use the following format:</p> * <p>{ "key1" : "value1", "key2" : "value2", ...}</p> * <p>Keys must start with a letter and be at least two characters. The total size * of your environment variables cannot exceed 4 KB. You can't specify any Lambda * reserved environment variables as the keys for your environment variables. For * more information about reserved keys, see <a href="https://docs.aws.amazon.com/lambda/latest/dg/configuration-envvars.html#configuration-envvars-runtime"> * Runtime environment variables</a>.</p> */ EnvironmentVariables?: { [key: string]: string }; } export namespace CanaryRunConfigInput { /** * @internal */ export const filterSensitiveLog = (obj: CanaryRunConfigInput): any => ({ ...obj, }); } /** * <p>This structure specifies how often a canary is to make runs and the date and time * when it should stop making runs.</p> */ export interface CanaryScheduleInput { /** * <p>A <code>rate</code> expression or a <code>cron</code> expression that defines how often the canary is to run.</p> * <p>For a rate expression, The syntax is * <code>rate(<i>number unit</i>)</code>. <i>unit</i> * can be <code>minute</code>, <code>minutes</code>, or <code>hour</code>. </p> * <p>For example, <code>rate(1 minute)</code> runs the canary once a minute, <code>rate(10 minutes)</code> runs it once every * 10 minutes, and <code>rate(1 hour)</code> runs it once every hour. You can * specify a frequency between <code>rate(1 minute)</code> and <code>rate(1 hour)</code>.</p> * <p>Specifying <code>rate(0 minute)</code> or <code>rate(0 hour)</code> is a special value * that causes the * canary to run only once when it is started.</p> * <p>Use <code>cron(<i>expression</i>)</code> to specify a cron * expression. You can't schedule a canary to wait for more than a year before running. For information about the syntax for cron expressions, see * <a href="https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/CloudWatch_Synthetics_Canaries_cron.html"> * Scheduling canary runs using cron</a>.</p> */ Expression: string | undefined; /** * <p>How long, in seconds, for the canary to continue making regular runs according to * the schedule in the <code>Expression</code> value. If you specify 0, the canary continues * making runs until you stop it. If you omit this field, the default of 0 is used.</p> */ DurationInSeconds?: number; } export namespace CanaryScheduleInput { /** * @internal */ export const filterSensitiveLog = (obj: CanaryScheduleInput): any => ({ ...obj, }); } /** * <p>A conflicting operation is already in progress.</p> */ export interface ConflictException extends __SmithyException, $MetadataBearer { name: "ConflictException"; $fault: "client"; Message?: string; } export namespace ConflictException { /** * @internal */ export const filterSensitiveLog = (obj: ConflictException): any => ({ ...obj, }); } /** * <p>If this canary is to test an endpoint in a VPC, this structure contains * information about the subnets and security groups of the VPC endpoint. * For more information, see <a href="https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/CloudWatch_Synthetics_Canaries_VPC.html"> * Running a Canary in a VPC</a>.</p> */ export interface VpcConfigInput { /** * <p>The IDs of the subnets where this canary is to run.</p> */ SubnetIds?: string[]; /** * <p>The IDs of the security groups for this canary.</p> */ SecurityGroupIds?: string[]; } export namespace VpcConfigInput { /** * @internal */ export const filterSensitiveLog = (obj: VpcConfigInput): any => ({ ...obj, }); } export interface CreateCanaryRequest { /** * <p>The name for this canary. Be sure to give it a descriptive name * that distinguishes it from other canaries in your account.</p> * <p>Do not include secrets or proprietary information in your canary names. The canary name * makes up part of the canary ARN, and the ARN is included in outbound calls over the * internet. For more information, see <a href="https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/servicelens_canaries_security.html">Security * Considerations for Synthetics Canaries</a>.</p> */ Name: string | undefined; /** * <p>A structure that includes the entry point from which the canary should start * running your script. If the script is stored in * an S3 bucket, the bucket name, key, and version are also included. * </p> */ Code: CanaryCodeInput | undefined; /** * <p>The location in Amazon S3 where Synthetics stores artifacts from the test runs of this * canary. Artifacts include the log file, screenshots, and HAR files. The name of the * S3 bucket can't include a period (.).</p> */ ArtifactS3Location: string | undefined; /** * <p>The ARN of the IAM role to be used to run the canary. This role must already exist, * and must include <code>lambda.amazonaws.com</code> as a principal in the trust * policy. The role must also have the following permissions:</p> * <ul> * <li> * <p> * <code>s3:PutObject</code> * </p> * </li> * <li> * <p> * <code>s3:GetBucketLocation</code> * </p> * </li> * <li> * <p> * <code>s3:ListAllMyBuckets</code> * </p> * </li> * <li> * <p> * <code>cloudwatch:PutMetricData</code> * </p> * </li> * <li> * <p> * <code>logs:CreateLogGroup</code> * </p> * </li> * <li> * <p> * <code>logs:CreateLogStream</code> * </p> * </li> * <li> * <p> * <code>logs:PutLogEvents</code> * </p> * </li> * </ul> */ ExecutionRoleArn: string | undefined; /** * <p>A structure that contains information about how often the canary is to run and when * these test runs are to stop.</p> */ Schedule: CanaryScheduleInput | undefined; /** * <p>A structure that contains the configuration for individual canary runs, * such as timeout value.</p> */ RunConfig?: CanaryRunConfigInput; /** * <p>The number of days to retain data about successful runs of this canary. If you omit * this field, the default of 31 days is used. The valid range is 1 to 455 days.</p> */ SuccessRetentionPeriodInDays?: number; /** * <p>The number of days to retain data about failed runs of this canary. If you omit * this field, the default of 31 days is used. The valid range is 1 to 455 days.</p> */ FailureRetentionPeriodInDays?: number; /** * <p>Specifies the runtime version to use for the canary. For a list of valid * runtime versions and more information about * runtime versions, see <a href="https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/CloudWatch_Synthetics_Canaries_Library.html"> * Canary Runtime Versions</a>.</p> */ RuntimeVersion: string | undefined; /** * <p>If this canary is to test an endpoint in a VPC, this structure contains * information about the subnet and security groups of the VPC endpoint. * For more information, see <a href="https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/CloudWatch_Synthetics_Canaries_VPC.html"> * Running a Canary in a VPC</a>.</p> */ VpcConfig?: VpcConfigInput; /** * <p>A list of key-value pairs to associate with the canary. * You can associate as many as 50 tags with a canary.</p> * <p>Tags can help you organize and categorize your * resources. You can also use them to scope user permissions, by * granting a user permission to access or change only the resources that have * certain tag values.</p> */ Tags?: { [key: string]: string }; /** * <p>A structure that contains the configuration for canary artifacts, including * the encryption-at-rest settings for artifacts that the canary uploads to Amazon S3.</p> */ ArtifactConfig?: ArtifactConfigInput; } export namespace CreateCanaryRequest { /** * @internal */ export const filterSensitiveLog = (obj: CreateCanaryRequest): any => ({ ...obj, }); } export interface CreateCanaryResponse { /** * <p>The full details about the canary you have created.</p> */ Canary?: Canary; } export namespace CreateCanaryResponse { /** * @internal */ export const filterSensitiveLog = (obj: CreateCanaryResponse): any => ({ ...obj, }); } /** * <p>An unknown internal error occurred.</p> */ export interface InternalServerException extends __SmithyException, $MetadataBearer { name: "InternalServerException"; $fault: "server"; Message?: string; } export namespace InternalServerException { /** * @internal */ export const filterSensitiveLog = (obj: InternalServerException): any => ({ ...obj, }); } /** * <p>A parameter could not be validated.</p> */ export interface ValidationException extends __SmithyException, $MetadataBearer { name: "ValidationException"; $fault: "client"; Message?: string; } export namespace ValidationException { /** * @internal */ export const filterSensitiveLog = (obj: ValidationException): any => ({ ...obj, }); } export interface DeleteCanaryRequest { /** * <p>The name of the canary that you want to delete. To find the names of your canaries, use <a href="https://docs.aws.amazon.com/AmazonSynthetics/latest/APIReference/API_DescribeCanaries.html">DescribeCanaries</a>.</p> */ Name: string | undefined; } export namespace DeleteCanaryRequest { /** * @internal */ export const filterSensitiveLog = (obj: DeleteCanaryRequest): any => ({ ...obj, }); } export interface DeleteCanaryResponse {} export namespace DeleteCanaryResponse { /** * @internal */ export const filterSensitiveLog = (obj: DeleteCanaryResponse): any => ({ ...obj, }); } /** * <p>One of the specified resources was not found.</p> */ export interface ResourceNotFoundException extends __SmithyException, $MetadataBearer { name: "ResourceNotFoundException"; $fault: "client"; Message?: string; } export namespace ResourceNotFoundException { /** * @internal */ export const filterSensitiveLog = (obj: ResourceNotFoundException): any => ({ ...obj, }); } export interface DescribeCanariesRequest { /** * <p>A token that indicates that there is more data * available. You can use this token in a subsequent operation to retrieve the next * set of results.</p> */ NextToken?: string; /** * <p>Specify this parameter to limit how many canaries are returned each time you use * the <code>DescribeCanaries</code> operation. If you omit this parameter, the default of 100 is used.</p> */ MaxResults?: number; } export namespace DescribeCanariesRequest { /** * @internal */ export const filterSensitiveLog = (obj: DescribeCanariesRequest): any => ({ ...obj, }); } export interface DescribeCanariesResponse { /** * <p>Returns an array. Each item in the array contains the full information about * one canary.</p> */ Canaries?: Canary[]; /** * <p>A token that indicates that there is more data * available. You can use this token in a subsequent <code>DescribeCanaries</code> operation to retrieve the next * set of results.</p> */ NextToken?: string; } export namespace DescribeCanariesResponse { /** * @internal */ export const filterSensitiveLog = (obj: DescribeCanariesResponse): any => ({ ...obj, }); } export interface DescribeCanariesLastRunRequest { /** * <p>A token that indicates that there is more data * available. You can use this token in a subsequent <code>DescribeCanaries</code> operation to retrieve the next * set of results.</p> */ NextToken?: string; /** * <p>Specify this parameter to limit how many runs are returned each time you use * the <code>DescribeLastRun</code> operation. If you omit this parameter, the default of 100 is used.</p> */ MaxResults?: number; } export namespace DescribeCanariesLastRunRequest { /** * @internal */ export const filterSensitiveLog = (obj: DescribeCanariesLastRunRequest): any => ({ ...obj, }); } export interface DescribeCanariesLastRunResponse { /** * <p>An array that contains the information from the most recent run of each * canary.</p> */ CanariesLastRun?: CanaryLastRun[]; /** * <p>A token that indicates that there is more data * available. You can use this token in a subsequent <code>DescribeCanariesLastRun</code> operation to retrieve the next * set of results.</p> */ NextToken?: string; } export namespace DescribeCanariesLastRunResponse { /** * @internal */ export const filterSensitiveLog = (obj: DescribeCanariesLastRunResponse): any => ({ ...obj, }); } export interface DescribeRuntimeVersionsRequest { /** * <p>A token that indicates that there is more data * available. You can use this token in a subsequent <code>DescribeRuntimeVersions</code> operation to retrieve the next * set of results.</p> */ NextToken?: string; /** * <p>Specify this parameter to limit how many runs are returned each time you use * the <code>DescribeRuntimeVersions</code> operation. If you omit this parameter, the default of 100 is used.</p> */ MaxResults?: number; } export namespace DescribeRuntimeVersionsRequest { /** * @internal */ export const filterSensitiveLog = (obj: DescribeRuntimeVersionsRequest): any => ({ ...obj, }); } /** * <p>This structure contains information about one canary runtime version. For more information about * runtime versions, see <a href="https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/CloudWatch_Synthetics_Canaries_Library.html"> * Canary Runtime Versions</a>.</p> */ export interface RuntimeVersion { /** * <p>The name of the runtime version. For a list of valid runtime versions, * see <a href="https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/CloudWatch_Synthetics_Canaries_Library.html"> * Canary Runtime Versions</a>.</p> */ VersionName?: string; /** * <p>A description of the runtime version, created by Amazon.</p> */ Description?: string; /** * <p>The date that the runtime version was released.</p> */ ReleaseDate?: Date; /** * <p>If this runtime version is deprecated, this value is the date of deprecation.</p> */ DeprecationDate?: Date; } export namespace RuntimeVersion { /** * @internal */ export const filterSensitiveLog = (obj: RuntimeVersion): any => ({ ...obj, }); } export interface DescribeRuntimeVersionsResponse { /** * <p>An array of objects that display the details about each Synthetics canary runtime * version.</p> */ RuntimeVersions?: RuntimeVersion[]; /** * <p>A token that indicates that there is more data * available. You can use this token in a subsequent <code>DescribeRuntimeVersions</code> operation to retrieve the next * set of results.</p> */ NextToken?: string; } export namespace DescribeRuntimeVersionsResponse { /** * @internal */ export const filterSensitiveLog = (obj: DescribeRuntimeVersionsResponse): any => ({ ...obj, }); } export interface GetCanaryRequest { /** * <p>The name of the canary that you want details for.</p> */ Name: string | undefined; } export namespace GetCanaryRequest { /** * @internal */ export const filterSensitiveLog = (obj: GetCanaryRequest): any => ({ ...obj, }); } export interface GetCanaryResponse { /** * <p>A strucure that contains the full information about the canary.</p> */ Canary?: Canary; } export namespace GetCanaryResponse { /** * @internal */ export const filterSensitiveLog = (obj: GetCanaryResponse): any => ({ ...obj, }); } export interface GetCanaryRunsRequest { /** * <p>The name of the canary that you want to see runs for.</p> */ Name: string | undefined; /** * <p>A token that indicates that there is more data * available. You can use this token in a subsequent <code>GetCanaryRuns</code> operation to retrieve the next * set of results.</p> */ NextToken?: string; /** * <p>Specify this parameter to limit how many runs are returned each time you use * the <code>GetCanaryRuns</code> operation. If you omit this parameter, the default of 100 is used.</p> */ MaxResults?: number; } export namespace GetCanaryRunsRequest { /** * @internal */ export const filterSensitiveLog = (obj: GetCanaryRunsRequest): any => ({ ...obj, }); } export interface GetCanaryRunsResponse { /** * <p>An array of structures. Each structure contains the details of one of the * retrieved canary runs.</p> */ CanaryRuns?: CanaryRun[]; /** * <p>A token that indicates that there is more data * available. You can use this token in a subsequent <code>GetCanaryRuns</code> * operation to retrieve the next * set of results.</p> */ NextToken?: string; } export namespace GetCanaryRunsResponse { /** * @internal */ export const filterSensitiveLog = (obj: GetCanaryRunsResponse): any => ({ ...obj, }); } export interface ListTagsForResourceRequest { /** * <p>The ARN of the canary that you want to view tags for.</p> * <p>The ARN format of a canary is * <code>arn:aws:synthetics:<i>Region</i>:<i>account-id</i>:canary:<i>canary-name</i> * </code>.</p> */ ResourceArn: string | undefined; } export namespace ListTagsForResourceRequest { /** * @internal */ export const filterSensitiveLog = (obj: ListTagsForResourceRequest): any => ({ ...obj, }); } export interface ListTagsForResourceResponse { /** * <p>The list of tag keys and values associated with the canary that you specified.</p> */ Tags?: { [key: string]: string }; } export namespace ListTagsForResourceResponse { /** * @internal */ export const filterSensitiveLog = (obj: ListTagsForResourceResponse): any => ({ ...obj, }); } export interface StartCanaryRequest { /** * <p>The name of the canary that you want to run. To find * canary names, use <a href="https://docs.aws.amazon.com/AmazonSynthetics/latest/APIReference/API_DescribeCanaries.html">DescribeCanaries</a>.</p> */ Name: string | undefined; } export namespace StartCanaryRequest { /** * @internal */ export const filterSensitiveLog = (obj: StartCanaryRequest): any => ({ ...obj, }); } export interface StartCanaryResponse {} export namespace StartCanaryResponse { /** * @internal */ export const filterSensitiveLog = (obj: StartCanaryResponse): any => ({ ...obj, }); } export interface StopCanaryRequest { /** * <p>The name of the canary that you want to stop. To find the names of your * canaries, use <a href="https://docs.aws.amazon.com/AmazonSynthetics/latest/APIReference/API_DescribeCanaries.html">DescribeCanaries</a>.</p> */ Name: string | undefined; } export namespace StopCanaryRequest { /** * @internal */ export const filterSensitiveLog = (obj: StopCanaryRequest): any => ({ ...obj, }); } export interface StopCanaryResponse {} export namespace StopCanaryResponse { /** * @internal */ export const filterSensitiveLog = (obj: StopCanaryResponse): any => ({ ...obj, }); } export interface TagResourceRequest { /** * <p>The ARN of the canary that you're adding tags to.</p> * <p>The ARN format of a canary is * <code>arn:aws:synthetics:<i>Region</i>:<i>account-id</i>:canary:<i>canary-name</i> * </code>.</p> */ ResourceArn: string | undefined; /** * <p>The list of key-value pairs to associate with the canary.</p> */ Tags: { [key: string]: string } | undefined; } export namespace TagResourceRequest { /** * @internal */ export const filterSensitiveLog = (obj: TagResourceRequest): any => ({ ...obj, }); } export interface TagResourceResponse {} export namespace TagResourceResponse { /** * @internal */ export const filterSensitiveLog = (obj: TagResourceResponse): any => ({ ...obj, }); } export interface UntagResourceRequest { /** * <p>The ARN of the canary that you're removing tags from.</p> * <p>The ARN format of a canary is * <code>arn:aws:synthetics:<i>Region</i>:<i>account-id</i>:canary:<i>canary-name</i> * </code>.</p> */ ResourceArn: string | undefined; /** * <p>The list of tag keys to remove from the resource.</p> */ TagKeys: string[] | undefined; } export namespace UntagResourceRequest { /** * @internal */ export const filterSensitiveLog = (obj: UntagResourceRequest): any => ({ ...obj, }); } export interface UntagResourceResponse {} export namespace UntagResourceResponse { /** * @internal */ export const filterSensitiveLog = (obj: UntagResourceResponse): any => ({ ...obj, }); } /** * <p>An object that specifies what screenshots to use as a baseline for visual monitoring by this canary, and optionally the parts of the screenshots to ignore during the visual monitoring comparison.</p> * * <p>Visual monitoring is supported only on canaries running the <b>syn-puppeteer-node-3.2</b> * runtime or later. For more information, see <a href="https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/CloudWatch_Synthetics_Library_SyntheticsLogger_VisualTesting.html"> * Visual monitoring</a> and <a href="https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/CloudWatch_Synthetics_Canaries_Blueprints_VisualTesting.html"> * Visual monitoring blueprint</a> * </p> */ export interface VisualReferenceInput { /** * <p>An array of screenshots that will be used as the baseline for visual monitoring in future runs of this canary. If there is a screenshot that you don't want to be used for * visual monitoring, remove it from this array.</p> */ BaseScreenshots?: BaseScreenshot[]; /** * <p>Specifies which canary run to use the screenshots from as the baseline for future visual monitoring with this canary. Valid values are * <code>nextrun</code> to use the screenshots from the next run after this update is made, <code>lastrun</code> to use the screenshots from the most recent run * before this update was made, or the value of <code>Id</code> in the <a href="https://docs.aws.amazon.com/AmazonSynthetics/latest/APIReference/API_CanaryRun.html"> * CanaryRun</a> from any past run of this canary.</p> */ BaseCanaryRunId: string | undefined; } export namespace VisualReferenceInput { /** * @internal */ export const filterSensitiveLog = (obj: VisualReferenceInput): any => ({ ...obj, }); } export interface UpdateCanaryRequest { /** * <p>The name of the canary that you want to update. To find the names of your * canaries, use <a href="https://docs.aws.amazon.com/AmazonSynthetics/latest/APIReference/API_DescribeCanaries.html">DescribeCanaries</a>.</p> * <p>You cannot change the name of a canary that has already been created.</p> */ Name: string | undefined; /** * <p>A structure that includes the entry point from which the canary should start * running your script. If the script is stored in * an S3 bucket, the bucket name, key, and version are also included. * </p> */ Code?: CanaryCodeInput; /** * <p>The ARN of the IAM role to be used to run the canary. This role must already exist, * and must include <code>lambda.amazonaws.com</code> as a principal in the trust * policy. The role must also have the following permissions:</p> * <ul> * <li> * <p> * <code>s3:PutObject</code> * </p> * </li> * <li> * <p> * <code>s3:GetBucketLocation</code> * </p> * </li> * <li> * <p> * <code>s3:ListAllMyBuckets</code> * </p> * </li> * <li> * <p> * <code>cloudwatch:PutMetricData</code> * </p> * </li> * <li> * <p> * <code>logs:CreateLogGroup</code> * </p> * </li> * <li> * <p> * <code>logs:CreateLogStream</code> * </p> * </li> * <li> * <p> * <code>logs:CreateLogStream</code> * </p> * </li> * </ul> */ ExecutionRoleArn?: string; /** * <p>Specifies the runtime version to use for the canary. * For a list of valid runtime versions and for more information about * runtime versions, see <a href="https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/CloudWatch_Synthetics_Canaries_Library.html"> * Canary Runtime Versions</a>.</p> */ RuntimeVersion?: string; /** * <p>A structure that contains information about how often the canary is to run, and when * these runs are to stop.</p> */ Schedule?: CanaryScheduleInput; /** * <p>A structure that contains the timeout value that is used for each individual run of the * canary.</p> */ RunConfig?: CanaryRunConfigInput; /** * <p>The number of days to retain data about successful runs of this canary.</p> */ SuccessRetentionPeriodInDays?: number; /** * <p>The number of days to retain data about failed runs of this canary.</p> */ FailureRetentionPeriodInDays?: number; /** * <p>If this canary is to test an endpoint in a VPC, this structure contains * information about the subnet and security groups of the VPC endpoint. * For more information, see <a href="https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/CloudWatch_Synthetics_Canaries_VPC.html"> * Running a Canary in a VPC</a>.</p> */ VpcConfig?: VpcConfigInput; /** * <p>Defines the screenshots to use as the baseline for comparisons during visual monitoring comparisons during future runs of this canary. If you omit this * parameter, no changes are made to any baseline screenshots that the canary might be using already.</p> * <p>Visual monitoring is supported only on canaries running the <b>syn-puppeteer-node-3.2</b> * runtime or later. For more information, see <a href="https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/CloudWatch_Synthetics_Library_SyntheticsLogger_VisualTesting.html"> * Visual monitoring</a> and <a href="https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/CloudWatch_Synthetics_Canaries_Blueprints_VisualTesting.html"> * Visual monitoring blueprint</a> * </p> */ VisualReference?: VisualReferenceInput; /** * <p>The location in Amazon S3 where Synthetics stores artifacts from the test runs of this canary. * Artifacts include the log file, screenshots, and HAR files. The name of the * S3 bucket can't include a period (.).</p> */ ArtifactS3Location?: string; /** * <p>A structure that contains the configuration for canary artifacts, * including the encryption-at-rest settings for artifacts that * the canary uploads to Amazon S3.</p> */ ArtifactConfig?: ArtifactConfigInput; } export namespace UpdateCanaryRequest { /** * @internal */ export const filterSensitiveLog = (obj: UpdateCanaryRequest): any => ({ ...obj, }); } export interface UpdateCanaryResponse {} export namespace UpdateCanaryResponse { /** * @internal */ export const filterSensitiveLog = (obj: UpdateCanaryResponse): any => ({ ...obj, }); }
the_stack
import { ApiPromise } from '@polkadot/api'; import { Abi } from '@polkadot/api-contract'; import type { AbiConstructor } from '@polkadot/api-contract/types'; import type { SubmittableExtrinsic } from '@polkadot/api/types'; import { Bytes } from '@polkadot/types'; import type { Weight } from '@polkadot/types/interfaces'; import type { CodeHash } from '@polkadot/types/interfaces/contracts'; import type { AccountId } from '@polkadot/types/interfaces/types'; import type { AnyJson, ISubmittableResult } from '@polkadot/types/types'; import { compactAddLength, compactStripLength, isFunction, u8aConcat, u8aToHex, u8aToU8a } from '@polkadot/util'; import { blake2AsU8a, decodeAddress } from '@polkadot/util-crypto'; import BN from 'bn.js'; import chalk from 'chalk'; import log from 'redspot/logger'; import { RedspotPluginError } from 'redspot/plugins'; import type { Signer } from 'redspot/types'; import { buildTx } from './buildTx'; import Contract from './contract'; import { converSignerToAddress } from './helpers'; import { BigNumber, CallOverrides, TransactionParams } from './types'; export type ContractFunction<T = any> = (...args: Array<any>) => Promise<T>; type ContractAbi = Record<string, unknown> | Abi; type ConstructorOrId = AbiConstructor | string | number; const pluginName = 'redspot-patract'; export default class ContractFactory { readonly abi: Abi; readonly wasm: Uint8Array; readonly api: ApiPromise; readonly signer: string; public gasLimit?: BigNumber; readonly populateTransaction: { putCode: ( code: string | Bytes | Uint8Array ) => SubmittableExtrinsic<'promise', ISubmittableResult>; instantiate: ( codeHash: string | Uint8Array | CodeHash, data: string | Uint8Array | Bytes, endowment: BigNumber, gasLimit: BigNumber ) => SubmittableExtrinsic<'promise', ISubmittableResult>; }; /** * @param wasm contract wasm * @param contractAbi contract abi * @param apiProvider api promise * @param signer signer */ constructor( wasm: Uint8Array | string | Buffer, contractAbi: ContractAbi, apiProvider: ApiPromise, signer: Signer | string ) { this.abi = contractAbi instanceof Abi ? contractAbi : new Abi(contractAbi, apiProvider.registry.getChainProperties()); this.wasm = u8aToU8a(wasm); this.api = apiProvider; this.signer = converSignerToAddress(signer); this.populateTransaction = { putCode: this.#buildPutCode, instantiate: this.#buildInstantiate }; } #buildPutCode = (wasmCode: Uint8Array | string | Buffer) => { return this.api.tx.contracts.putCode(wasmCode); }; #buildInstantiateWithCode = ( wasmCode: Uint8Array | string | Buffer, data: string | Uint8Array | Bytes, endowment: BigNumber, gasLimit: BigNumber, salt?: Uint8Array | string | null ) => { const hasStorageDeposit = this.api.tx.contracts.instantiateWithCode.meta.args.length === 6; const storageDepositLimit = null; return hasStorageDeposit ? this.api.tx.contracts.instantiateWithCode( endowment, gasLimit, storageDepositLimit, wasmCode, u8aConcat(data, salt), // @ts-ignore salt ) : // eslint-disable-next-line @typescript-eslint/ban-ts-comment // @ts-ignore old style without storage deposit this.api.tx.contracts.instantiateWithCode( endowment, gasLimit, wasmCode, u8aConcat(data, salt), salt ); }; #buildInstantiate = ( codeHash: string | Uint8Array | CodeHash, data: string | Uint8Array | Bytes, endowment: BigNumber, gasLimit: BigNumber, salt?: Uint8Array | string | null ) => { const withSalt = this.api.tx.contracts.instantiate.meta.args.length === 5; const hasStorageDeposit = this.api.tx.contracts.instantiateWithCode.meta.args.length === 6; const storageDepositLimit = null; const tx = withSalt ? this.api.tx.contracts.instantiate( endowment, gasLimit, codeHash, u8aConcat(data, salt), salt ) : hasStorageDeposit ? this.api.tx.contracts.instantiate( endowment, gasLimit, storageDepositLimit, codeHash, u8aConcat(data, salt), //@ts-ignore salt ) : // eslint-disable-next-line @typescript-eslint/ban-ts-comment // @ts-ignore new style with salt included this.api.tx.contracts.instantiate(endowment, gasLimit, codeHash, data); return tx; }; /** * Uploading wasm . wasm will read from a local file * * @param overrides CallOverrides */ #putCode = async (overrides?: Partial<CallOverrides>): Promise<CodeHash> => { const options = { ...overrides }; const wasmHash = (this.abi.json as any).source.hash; const codeStorage = await this.api.query.contracts.codeStorage(wasmHash); if (!codeStorage.isEmpty) { const hash = this.api.registry.createType('CodeHash', wasmHash); log.info(`Use the uploaded codehash: ${hash.toString()}`); return hash; } delete options.value; delete options.gasLimit; delete options.dest; const contractName = this.abi.info.contract.name.toString(); const wasmCode = u8aToHex(this.wasm); log.info(''); log.info(chalk.magenta(`===== PutCode ${contractName} =====`)); log.info( 'WasmCode: ', wasmCode.replace(/^(\w{32})(\w*)(\w{30})$/g, '$1......$3') ); const tx = this.#buildPutCode(wasmCode); const status = await buildTx(this.api.registry, tx, this.signer, { ...options }).catch((error) => { log.error(error.error || error); throw new RedspotPluginError(pluginName, 'PutCode failed'); }); // const record = status.result.findRecord('contracts', 'CodeStored'); const records = status.result.filterRecords('contracts', 'CodeStored'); // There may be multiple Instantiated events const record = records[records.length - 1]; const depositRecord = status.result.findRecord('balances', 'Deposit'); const codeHash = record?.event.data[0] as CodeHash; if (!codeHash) { throw new RedspotPluginError( pluginName, `Can't get codehash for contracts` ); } if (depositRecord && depositRecord?.event?.data?.[1]) { log.success( `Transaction fees: ${chalk.yellow( depositRecord.event.data[1]?.toString() )}` ); } log.success(`${contractName} codeHash: ${chalk.blue(codeHash.toHex())}`); return codeHash; }; /** * Instantiated Contracts * * @param constructorOrId Constructor name or constructor id * @param args Parameters of the constructor * @returns Contract Address */ public instantiate = async ( constructorOrId: ConstructorOrId, ...args: TransactionParams ): Promise<AccountId> => { const { params, overrides } = this._parseArgs(constructorOrId, ...args); const contractName = this.abi.info.contract.name.toString(); const codeHash = (this.abi.json as any).source.hash; const constructor = this.abi.findConstructor(constructorOrId); const encoded = constructor.toU8a(params); const tombstoneDeposit = ( (this.api.consts.contracts.tombstoneDeposit as any) || new BN(0) ).muln(10); const contractDeposit = (this.api.consts.contracts.contractDeposit as any) || new BN(0); const mindeposit = this.api.consts.balances.existentialDeposit .add(tombstoneDeposit) .add(contractDeposit); const endowment = overrides.value; if (overrides.value) { const endowmentConverted = this.api.createType( 'BalanceOf', overrides.value ); if (endowmentConverted.lt(mindeposit)) { throw new Error( `endowment should not be less than ${mindeposit.toString()}, but get ${endowmentConverted.toString()}` ); } } const salt = await ContractFactory.encodeSalt(overrides.salt, this.signer); const maximumBlockWeight = this.api.consts.system.blockWeights ? this.api.consts.system.blockWeights.maxBlock : (this.api.consts.system.maximumBlockWeight as Weight); const gasLimit = overrides.gasLimit || this.gasLimit || maximumBlockWeight.muln(2).divn(10); delete overrides.value; delete overrides.gasLimit; delete overrides.dest; delete overrides.salt; const tx = this.#buildInstantiate( codeHash, encoded, endowment, gasLimit, salt ); log.info(''); log.info(chalk.magenta(`===== Instantiate ${contractName} =====`)); log.info('Endowment: ', endowment.toString()); log.info('GasLimit: ', gasLimit.toString()); log.info('CodeHash: ', codeHash.toString()); log.info('InputData: ', u8aToHex(encoded)); log.info('Salt: ', salt.toString()); const status = await buildTx(this.api.registry, tx, this.signer, { ...overrides }).catch((error) => { log.error(error.error || error); throw new RedspotPluginError(pluginName, 'Instantiation failed'); }); const records = status.result.filterRecords('contracts', 'Instantiated'); // There may be multiple Instantiated events const record = records[records.length - 1]; const depositRecord = status.result.findRecord('balances', 'Deposit'); const successRecord = status.result.findRecord( 'system', 'ExtrinsicSuccess' ); const address = record.event.data[1] as AccountId; if (!address) { throw new RedspotPluginError( pluginName, `The instantiation contract failed` ); } if (depositRecord && depositRecord?.event?.data?.[1]) { log.success( `Transaction fees: ${chalk.yellow( depositRecord.event.data[1]?.toString() )}` ); } if (successRecord && (successRecord?.event?.data?.[0] as any).weight) { log.success( `The gas consumption of ${contractName} instantiate: ${chalk.yellow( (successRecord?.event?.data?.[0] as any).weight.toString() )}` ); } log.success(`${contractName} address: ${chalk.blue(address.toString())}`); return address; }; /** * instantiateWithCode * * @param constructorOrId Constructor name or constructor id * @param args Parameters of the constructor * @returns Contract Address */ public instantiateWithCode = async ( constructorOrId: ConstructorOrId, ...args: TransactionParams ): Promise<AccountId> => { const { params, overrides } = this._parseArgs(constructorOrId, ...args); const contractName = this.abi.info.contract.name.toString(); const wasmCode = u8aToHex(this.wasm); const constructor = this.abi.findConstructor(constructorOrId); const encoded = constructor.toU8a(params); const tombstoneDeposit = ( (this.api.consts.contracts.tombstoneDeposit as any) || new BN(0) ).muln(10); const contractDeposit = (this.api.consts.contracts.contractDeposit as any) || new BN(0); const mindeposit = this.api.consts.balances.existentialDeposit .add(tombstoneDeposit) .add(contractDeposit); const endowment = overrides.value || mindeposit; if (overrides.value) { const endowmentConverted = this.api.createType( 'BalanceOf', overrides.value ); if (endowmentConverted.lt(mindeposit)) { throw new Error( `endowment should not be less than ${mindeposit.toString()}, but get ${endowmentConverted.toString()}` ); } } const salt = await ContractFactory.encodeSalt(overrides.salt, this.signer); const maximumBlockWeight = this.api.consts.system.blockWeights ? this.api.consts.system.blockWeights.maxBlock : (this.api.consts.system.maximumBlockWeight as Weight); const gasLimit = overrides.gasLimit || this.gasLimit || maximumBlockWeight.muln(2).divn(10); delete overrides.value; delete overrides.gasLimit; delete overrides.dest; delete overrides.salt; const tx = this.#buildInstantiateWithCode( wasmCode, encoded, endowment, gasLimit, salt ); log.info(''); log.info(chalk.magenta(`===== InstantiateWithCode ${contractName} =====`)); log.info('Endowment: ', endowment.toString()); log.info('GasLimit: ', gasLimit.toString()); log.info('CodeHash: ', (this.abi.json as any).source.hash); log.info('InputData: ', u8aToHex(encoded)); log.info('Salt: ', salt.toString()); const status = await buildTx(this.api.registry, tx, this.signer, { ...overrides }).catch((error) => { log.error(error.error || error); throw new RedspotPluginError(pluginName, 'Instantiation failed'); }); const records = status.result.filterRecords('contracts', 'Instantiated'); // There may be multiple Instantiated events const record = records[records.length - 1]; const depositRecord = status.result.findRecord('balances', 'Deposit'); const successRecord = status.result.findRecord( 'system', 'ExtrinsicSuccess' ); const address = record.event.data[1] as AccountId; if (!address) { throw new RedspotPluginError( pluginName, `The instantiation contract failed` ); } if (depositRecord && depositRecord?.event?.data?.[1]) { log.success( `Transaction fees: ${chalk.yellow( depositRecord.event.data[1]?.toString() )}` ); } if (successRecord && (successRecord?.event?.data?.[0] as any).weight) { log.success( `The gas consumption of ${contractName} instantiate: ${chalk.yellow( (successRecord?.event?.data?.[0] as any).weight.toString() )}` ); } log.success(`${contractName} address: ${chalk.blue(address.toString())}`); return address; }; /** * Upload wasm and instantiate it. * * @param constructorOrId Constructor name or constructor id * @param args Parameters of the constructor * @returns Contract */ async deploy( constructorOrId: ConstructorOrId, ...args: TransactionParams ): Promise<Contract> { const { params, overrides } = this._parseArgs(constructorOrId, ...args); let contractAddress: AccountId; if (!isFunction(this.api.tx.contracts.instantiateWithCode)) { await this.#putCode(overrides); contractAddress = await this.instantiate( constructorOrId, ...params, overrides ); } else { contractAddress = await this.instantiateWithCode( constructorOrId, ...params, overrides ); } const contract = new Contract( contractAddress, this.abi, this.api, this.signer ); contract.gasLimit = this.gasLimit; return contract; } /** * Deploys a contract, and if the same contract address is detected, returns an instance of that contract. * * @param constructorOrId Constructor name or constructor id * @param args Parameters of the constructor */ async deployed(constructorOrId: ConstructorOrId, ...args: TransactionParams) { const { params, overrides } = this._parseArgs(constructorOrId, ...args); const deployedAddress = await this.getContractAddress( constructorOrId, params, overrides.salt ); console.log('deployedAddress:', deployedAddress.toString()); const contractInfo = await this.api.query.contracts.contractInfoOf( deployedAddress ); if (contractInfo.isEmpty) { return this.deploy(constructorOrId, ...params, overrides); } log.warn( 'The same WASM code and the instantiation parameter contract have been deployed.' ); log.info( `Use contracts that have already been deployed: ${chalk.cyan( deployedAddress.toString() )}` ); const contract = new Contract( deployedAddress, this.abi, this.api, this.signer ); contract.gasLimit = this.gasLimit; return contract; } /** * Calculate the contract address * * @param constructorOrId Constructor name or constructor id * @param params Parameters of the constructor * * @returns Contract address */ async getContractAddress( constructorOrId: ConstructorOrId, params: unknown[], salt?: Uint8Array | string | null ) { const withSalt = this.api.tx.contracts.instantiate.meta.args.length === 5; if (withSalt) { const encodedSalt = await ContractFactory.encodeSalt(salt, this.signer); const codeHash = blake2AsU8a(this.wasm); const [_, encodedStrip] = compactStripLength(encodedSalt); const buf = u8aConcat(decodeAddress(this.signer), codeHash, encodedStrip); const address = blake2AsU8a(buf); return this.api.registry.createType('AccountId', address); } else { const codeHash = blake2AsU8a(this.wasm); const constructor = this.abi.findConstructor(constructorOrId); const encoded = constructor.toU8a(params); const [_, encodedStrip] = compactStripLength(encoded); const dataHash = blake2AsU8a(encodedStrip); const buf = u8aConcat(codeHash, dataHash, decodeAddress(this.signer)); const address = blake2AsU8a(buf); return this.api.registry.createType('AccountId', address); } } /** * Create Contract Instances by Contract Address * * @param address Contract address * @returns Contract */ attach(address: string): Contract { return (<any>this.constructor).getContract( address, this.abi, this.api, this.signer ); } /** * Change contract signer * * @param signer Signer * @returns Contract Factory */ connect(signer: Signer | string) { return new (<{ new (...args: any[]): ContractFactory }>this.constructor)( this.wasm, this.abi, this.api, signer ); } _parseArgs(constructorOrId: ConstructorOrId, ...args: TransactionParams) { let overrides: Partial<CallOverrides> = {}; if (overrides.signer) { throw new Error( 'Signer is not supported. Use connect instead, e.g. contractFactory.connect(signer)' ); } let params: unknown[] = []; const constructor = this.abi.findConstructor(constructorOrId); if ( args.length === constructor.args.length + 1 && typeof args[args.length - 1] === 'object' ) { overrides = { ...(args[args.length - 1] as Partial<CallOverrides>) }; params = [...args.slice(0, -1)]; } else if (args.length !== constructor.args.length) { throw new RedspotPluginError( pluginName, `Expected ${constructor.args.length} arguments to contract message '${constructor.identifier}', found ${args.length}` ); } else { params = [...(args as unknown[])]; } return { overrides, params }; } static async encodeSalt( salt: Uint8Array | string | null = '', signerAddress?: string ): Promise<Uint8Array> { const EMPTY_SALT = new Uint8Array(); return salt instanceof Bytes ? salt : salt && salt.length ? compactAddLength(u8aToU8a(salt)) : EMPTY_SALT; } /** * Create Contract Instances * * @param address Contract address * @param contractAbi Contract abi * @param apiProvider Api promise * @param signer Signer * @returns Contract */ static getContract( address: string, contractAbi: ContractAbi, apiProvider: ApiPromise, signer: Signer | string ): Contract { return new Contract(address, contractAbi, apiProvider, signer); } }
the_stack
import { expect } from "chai"; import * as sinon from "sinon"; import * as moq from "typemoq"; import { BeEvent, Id64String, using } from "@itwin/core-bentley"; import { IModelConnection, PerModelCategoryVisibility, SpatialViewState, Viewport, ViewState, ViewState3d } from "@itwin/core-frontend"; import { createRandomId } from "@itwin/presentation-common/lib/cjs/test"; import { FilteredPresentationTreeDataProvider } from "@itwin/presentation-components"; import { PropertyRecord } from "@itwin/appui-abstract"; import { isPromiseLike } from "@itwin/core-react"; import { ModelsVisibilityHandler, ModelsVisibilityHandlerProps } from "../../../appui-react/imodel-components/models-tree/ModelsVisibilityHandler"; import { TestUtils } from "../../TestUtils"; import { createCategoryNode, createElementClassGroupingNode, createElementNode, createModelNode, createSubjectNode } from "../Common"; import { IModelHierarchyChangeEventArgs, Presentation, PresentationManager } from "@itwin/presentation-frontend"; describe("ModelsVisibilityHandler", () => { before(async () => { await TestUtils.initializeUiFramework(); }); after(() => { TestUtils.terminateUiFramework(); }); const imodelMock = moq.Mock.ofType<IModelConnection>(); beforeEach(() => { imodelMock.reset(); }); interface ViewportMockProps { viewState?: ViewState; perModelCategoryVisibility?: PerModelCategoryVisibility.Overrides; onViewedCategoriesPerModelChanged?: BeEvent<(vp: Viewport) => void>; onViewedCategoriesChanged?: BeEvent<(vp: Viewport) => void>; onViewedModelsChanged?: BeEvent<(vp: Viewport) => void>; onAlwaysDrawnChanged?: BeEvent<() => void>; onNeverDrawnChanged?: BeEvent<() => void>; } const mockViewport = (props?: ViewportMockProps) => { if (!props) props = {}; if (!props.viewState) props.viewState = moq.Mock.ofType<ViewState>().object; if (!props.perModelCategoryVisibility) props.perModelCategoryVisibility = moq.Mock.ofType<PerModelCategoryVisibility.Overrides>().object; if (!props.onViewedCategoriesPerModelChanged) props.onViewedCategoriesPerModelChanged = new BeEvent<(vp: Viewport) => void>(); if (!props.onViewedCategoriesChanged) props.onViewedCategoriesChanged = new BeEvent<(vp: Viewport) => void>(); if (!props.onViewedModelsChanged) props.onViewedModelsChanged = new BeEvent<(vp: Viewport) => void>(); if (!props.onAlwaysDrawnChanged) props.onAlwaysDrawnChanged = new BeEvent<() => void>(); if (!props.onNeverDrawnChanged) props.onNeverDrawnChanged = new BeEvent<() => void>(); const vpMock = moq.Mock.ofType<Viewport>(); vpMock.setup((x) => x.iModel).returns(() => imodelMock.object); vpMock.setup((x) => x.view).returns(() => props!.viewState!); vpMock.setup((x) => x.perModelCategoryVisibility).returns(() => props!.perModelCategoryVisibility!); vpMock.setup((x) => x.onViewedCategoriesPerModelChanged).returns(() => props!.onViewedCategoriesPerModelChanged!); vpMock.setup((x) => x.onViewedCategoriesChanged).returns(() => props!.onViewedCategoriesChanged!); vpMock.setup((x) => x.onViewedModelsChanged).returns(() => props!.onViewedModelsChanged!); vpMock.setup((x) => x.onAlwaysDrawnChanged).returns(() => props!.onAlwaysDrawnChanged!); vpMock.setup((x) => x.onNeverDrawnChanged).returns(() => props!.onNeverDrawnChanged!); return vpMock; }; const createHandler = (partialProps?: Partial<ModelsVisibilityHandlerProps>): ModelsVisibilityHandler => { if (!partialProps) partialProps = {}; const props: ModelsVisibilityHandlerProps = { rulesetId: "test", viewport: partialProps.viewport || mockViewport().object, hierarchyAutoUpdateEnabled: partialProps.hierarchyAutoUpdateEnabled, }; return new ModelsVisibilityHandler(props); }; interface SubjectModelIdsMockProps { imodelMock: moq.IMock<IModelConnection>; subjectsHierarchy: Map<Id64String, Id64String[]>; subjectModels: Map<Id64String, Array<{ id: Id64String, content?: string }>>; } const mockSubjectModelIds = (props: SubjectModelIdsMockProps) => { props.imodelMock.setup((x) => x.query(moq.It.is((q: string) => (-1 !== q.indexOf("FROM bis.Subject"))))) .returns(async function* () { const list = new Array<{ id: Id64String, parentId: Id64String }>(); props.subjectsHierarchy.forEach((ids, parentId) => ids.forEach((id) => list.push({ id, parentId }))); while (list.length) yield list.shift(); }); props.imodelMock.setup((x) => x.query(moq.It.is((q: string) => (-1 !== q.indexOf("FROM bis.InformationPartitionElement"))))) .returns(async function* () { const list = new Array<{ id: Id64String, subjectId: Id64String, content?: string }>(); props.subjectModels.forEach((modelInfos, subjectId) => modelInfos.forEach((modelInfo) => list.push({ id: modelInfo.id, subjectId, content: modelInfo.content }))); while (list.length) yield list.shift(); }); }; describe("constructor", () => { it("should subscribe for viewport change events", () => { const vpMock = mockViewport(); createHandler({ viewport: vpMock.object }); expect(vpMock.object.onViewedCategoriesPerModelChanged.numberOfListeners).to.eq(1); expect(vpMock.object.onViewedCategoriesChanged.numberOfListeners).to.eq(1); expect(vpMock.object.onViewedModelsChanged.numberOfListeners).to.eq(1); expect(vpMock.object.onAlwaysDrawnChanged.numberOfListeners).to.eq(1); expect(vpMock.object.onNeverDrawnChanged.numberOfListeners).to.eq(1); }); it("should subscribe for 'onIModelHierarchyChanged' event if hierarchy auto update is enabled", () => { const presentationManagerMock = moq.Mock.ofType<PresentationManager>(); const changeEvent = new BeEvent<(args: IModelHierarchyChangeEventArgs) => void>(); presentationManagerMock.setup((x) => x.onIModelHierarchyChanged).returns(() => changeEvent); Presentation.setPresentationManager(presentationManagerMock.object); createHandler({ viewport: mockViewport().object, hierarchyAutoUpdateEnabled: true }); expect(changeEvent.numberOfListeners).to.eq(1); }); }); describe("dispose", () => { it("should unsubscribe from viewport change events", () => { const vpMock = mockViewport(); using(createHandler({ viewport: vpMock.object }), (_) => { }); expect(vpMock.object.onViewedCategoriesPerModelChanged.numberOfListeners).to.eq(0); expect(vpMock.object.onViewedCategoriesChanged.numberOfListeners).to.eq(0); expect(vpMock.object.onViewedModelsChanged.numberOfListeners).to.eq(0); expect(vpMock.object.onAlwaysDrawnChanged.numberOfListeners).to.eq(0); expect(vpMock.object.onNeverDrawnChanged.numberOfListeners).to.eq(0); }); it("should unsubscribe from 'onIModelHierarchyChanged' event", () => { const presentationManagerMock = moq.Mock.ofType<PresentationManager>(); const changeEvent = new BeEvent<(args: IModelHierarchyChangeEventArgs) => void>(); presentationManagerMock.setup((x) => x.onIModelHierarchyChanged).returns(() => changeEvent); Presentation.setPresentationManager(presentationManagerMock.object); using(createHandler({ viewport: mockViewport().object, hierarchyAutoUpdateEnabled: true }), (_) => { }); expect(changeEvent.numberOfListeners).to.eq(0); }); }); describe("getDisplayStatus", () => { it("returns disabled when node is not an instance node", async () => { const node = { __key: { type: "custom", version: 0, pathFromRoot: [], }, id: "custom", label: PropertyRecord.fromString("custom"), }; const vpMock = mockViewport(); await using(createHandler({ viewport: vpMock.object }), async (handler) => { const result = handler.getVisibilityStatus(node, node.__key); expect(isPromiseLike(result)).to.be.false; expect(result).to.include({ state: "hidden", isDisabled: true }); }); }); describe("subject", () => { it("return disabled when active view is not spatial", async () => { const node = createSubjectNode(); const vpMock = mockViewport(); await using(createHandler({ viewport: vpMock.object }), async (handler) => { const result = handler.getVisibilityStatus(node, node.__key); expect(isPromiseLike(result)).to.be.true; if (isPromiseLike(result)) expect(await result).to.include({ state: "hidden", isDisabled: true }); }); }); it("return 'hidden' when all models are not displayed", async () => { const subjectIds = ["0x1", "0x2"]; const node = createSubjectNode(subjectIds); mockSubjectModelIds({ imodelMock, subjectsHierarchy: new Map([["0x0", subjectIds]]), subjectModels: new Map([ [subjectIds[0], [{ id: "0x3" }, { id: "0x4" }]], [subjectIds[1], [{ id: "0x5" }, { id: "0x6" }]], ]), }); const viewStateMock = moq.Mock.ofType<ViewState3d>(); viewStateMock.setup((x) => x.isSpatialView()).returns(() => true); viewStateMock.setup((x) => x.viewsModel("0x3")).returns(() => false); viewStateMock.setup((x) => x.viewsModel("0x4")).returns(() => false); viewStateMock.setup((x) => x.viewsModel("0x5")).returns(() => false); viewStateMock.setup((x) => x.viewsModel("0x6")).returns(() => false); const vpMock = mockViewport({ viewState: viewStateMock.object }); await using(createHandler({ viewport: vpMock.object }), async (handler) => { const result = handler.getVisibilityStatus(node, node.__key); expect(isPromiseLike(result)).to.be.true; if (isPromiseLike(result)) expect(await result).to.include({ state: "hidden" }); }); }); it("return 'visible' when at least one direct model is displayed", async () => { const subjectIds = ["0x1", "0x2"]; const node = createSubjectNode(subjectIds); mockSubjectModelIds({ imodelMock, subjectsHierarchy: new Map([["0x0", subjectIds]]), subjectModels: new Map([ [subjectIds[0], [{ id: "0x3" }, { id: "0x4" }]], [subjectIds[1], [{ id: "0x5" }, { id: "0x6" }]], ]), }); const viewStateMock = moq.Mock.ofType<ViewState3d>(); viewStateMock.setup((x) => x.isSpatialView()).returns(() => true); viewStateMock.setup((x) => x.viewsModel("0x3")).returns(() => false); viewStateMock.setup((x) => x.viewsModel("0x4")).returns(() => false); viewStateMock.setup((x) => x.viewsModel("0x5")).returns(() => true); viewStateMock.setup((x) => x.viewsModel("0x6")).returns(() => false); const vpMock = mockViewport({ viewState: viewStateMock.object }); await using(createHandler({ viewport: vpMock.object }), async (handler) => { const result = handler.getVisibilityStatus(node, node.__key); expect(isPromiseLike(result)).to.be.true; if (isPromiseLike(result)) expect(await result).to.include({ state: "visible" }); }); }); it("return 'visible' when at least one nested model is displayed", async () => { const subjectIds = ["0x1", "0x2"]; const node = createSubjectNode(subjectIds); mockSubjectModelIds({ imodelMock, subjectsHierarchy: new Map([ [subjectIds[0], ["0x3"]], [subjectIds[1], ["0x4"]], ["0x3", ["0x5", "0x6"]], ["0x7", ["0x8"]], ]), subjectModels: new Map([ ["0x6", [{ id: "0x10" }, { id: "0x11" }]], ]), }); const viewStateMock = moq.Mock.ofType<ViewState3d>(); viewStateMock.setup((x) => x.isSpatialView()).returns(() => true); viewStateMock.setup((x) => x.viewsModel("0x10")).returns(() => true); viewStateMock.setup((x) => x.viewsModel("0x11")).returns(() => false); const vpMock = mockViewport({ viewState: viewStateMock.object }); await using(createHandler({ viewport: vpMock.object }), async (handler) => { const result = handler.getVisibilityStatus(node, node.__key); expect(isPromiseLike(result)).to.be.true; if (isPromiseLike(result)) expect(await result).to.include({ state: "visible" }); }); }); it("initializes subject models cache only once", async () => { const node = createSubjectNode(); const key = node.__key.instanceKeys[0]; mockSubjectModelIds({ imodelMock, subjectsHierarchy: new Map([["0x0", [key.id]]]), subjectModels: new Map([[key.id, [{ id: "0x1" }, { id: "0x2" }]]]), }); const viewStateMock = moq.Mock.ofType<ViewState3d>(); viewStateMock.setup((x) => x.isSpatialView()).returns(() => true); viewStateMock.setup((x) => x.viewsModel(moq.It.isAny())).returns(() => false); const vpMock = mockViewport({ viewState: viewStateMock.object }); await using(createHandler({ viewport: vpMock.object }), async (handler) => { await Promise.all([handler.getVisibilityStatus(node, node.__key), handler.getVisibilityStatus(node, node.__key)]); // expect the `query` to be called only twice (once for subjects and once for models) imodelMock.verify((x) => x.query(moq.It.isAnyString()), moq.Times.exactly(2)); }); }); describe("filtered", () => { it("return 'visible' when subject node matches filter and at least one model is visible", async () => { const node = createSubjectNode(); const key = node.__key.instanceKeys[0]; const filteredProvider = moq.Mock.ofType<FilteredPresentationTreeDataProvider>(); filteredProvider.setup((x) => x.nodeMatchesFilter(node)).returns(() => true); mockSubjectModelIds({ imodelMock, subjectsHierarchy: new Map([["0x0", [key.id]]]), subjectModels: new Map([[key.id, [{ id: "0x10" }, { id: "0x20" }]]]), }); const viewStateMock = moq.Mock.ofType<ViewState3d>(); viewStateMock.setup((x) => x.isSpatialView()).returns(() => true); viewStateMock.setup((x) => x.viewsModel("0x10")).returns(() => true); viewStateMock.setup((x) => x.viewsModel("0x20")).returns(() => false); const vpMock = mockViewport({ viewState: viewStateMock.object }); await using(createHandler({ viewport: vpMock.object }), async (handler) => { handler.setFilteredDataProvider(filteredProvider.object); const result = handler.getVisibilityStatus(node, node.__key); expect(isPromiseLike(result)).to.be.true; if (isPromiseLike(result)) expect(await result).to.include({ state: "visible" }); filteredProvider.verifyAll(); }); }); it("return 'visible' when subject node with children matches filter and at least one model is visible", async () => { const parentSubjectId = "0x1"; const childSubjectId = "0x2"; const node = createSubjectNode(parentSubjectId); const childNode = createSubjectNode(childSubjectId); const filteredProvider = moq.Mock.ofType<FilteredPresentationTreeDataProvider>(); filteredProvider.setup(async (x) => x.getNodes(node)).returns(async () => [childNode]).verifiable(moq.Times.never()); filteredProvider.setup(async (x) => x.getNodes(childNode)).returns(async () => []).verifiable(moq.Times.never()); filteredProvider.setup((x) => x.nodeMatchesFilter(moq.It.isAny())).returns(() => true); mockSubjectModelIds({ imodelMock, subjectsHierarchy: new Map([ [parentSubjectId, [childSubjectId]], ]), subjectModels: new Map([ [parentSubjectId, [{ id: "0x10" }, { id: "0x11" }]], [childSubjectId, [{ id: "0x20" }]], ]), }); const viewStateMock = moq.Mock.ofType<ViewState3d>(); viewStateMock.setup((x) => x.isSpatialView()).returns(() => true); viewStateMock.setup((x) => x.viewsModel("0x10")).returns(() => true); viewStateMock.setup((x) => x.viewsModel("0x11")).returns(() => false); viewStateMock.setup((x) => x.viewsModel("0x20")).returns(() => false); const vpMock = mockViewport({ viewState: viewStateMock.object }); await using(createHandler({ viewport: vpMock.object }), async (handler) => { handler.setFilteredDataProvider(filteredProvider.object); const result = handler.getVisibilityStatus(node, node.__key); expect(isPromiseLike(result)).to.be.true; if (isPromiseLike(result)) expect(await result).to.include({ state: "visible" }); filteredProvider.verifyAll(); }); }); it("return 'visible' when subject node with children does not match filter and at least one child has visible models", async () => { const parentSubjectId = "0x1"; const childSubjectIds = ["0x2", "0x3"]; const node = createSubjectNode(parentSubjectId); const childNodes = [createSubjectNode(childSubjectIds[0]), createSubjectNode(childSubjectIds[1])]; const filteredProvider = moq.Mock.ofType<FilteredPresentationTreeDataProvider>(); filteredProvider.setup(async (x) => x.getNodes(node)).returns(async () => childNodes).verifiable(moq.Times.once()); filteredProvider.setup(async (x) => x.getNodes(childNodes[0])).returns(async () => []).verifiable(moq.Times.never()); filteredProvider.setup(async (x) => x.getNodes(childNodes[1])).returns(async () => []).verifiable(moq.Times.never()); filteredProvider.setup((x) => x.getNodeKey(childNodes[0])).returns(() => childNodes[0].__key).verifiable(moq.Times.once()); filteredProvider.setup((x) => x.getNodeKey(childNodes[1])).returns(() => childNodes[1].__key).verifiable(moq.Times.once()); filteredProvider.setup((x) => x.nodeMatchesFilter(node)).returns(() => false); filteredProvider.setup((x) => x.nodeMatchesFilter(childNodes[0])).returns(() => true); filteredProvider.setup((x) => x.nodeMatchesFilter(childNodes[1])).returns(() => true); mockSubjectModelIds({ imodelMock, subjectsHierarchy: new Map([ [parentSubjectId, childSubjectIds], ]), subjectModels: new Map([ [parentSubjectId, [{ id: "0x10" }]], [childSubjectIds[0], [{ id: "0x20" }]], [childSubjectIds[1], [{ id: "0x30" }]], ]), }); const viewStateMock = moq.Mock.ofType<ViewState3d>(); viewStateMock.setup((x) => x.isSpatialView()).returns(() => true); viewStateMock.setup((x) => x.viewsModel("0x10")).returns(() => false); viewStateMock.setup((x) => x.viewsModel("0x20")).returns(() => false); viewStateMock.setup((x) => x.viewsModel("0x30")).returns(() => true); const vpMock = mockViewport({ viewState: viewStateMock.object }); await using(createHandler({ viewport: vpMock.object }), async (handler) => { handler.setFilteredDataProvider(filteredProvider.object); const result = handler.getVisibilityStatus(node, node.__key); expect(isPromiseLike(result)).to.be.true; if (isPromiseLike(result)) expect(await result).to.include({ state: "visible" }); filteredProvider.verifyAll(); }); }); it("return 'hidden' when subject node with children does not match filter and children models are not visible", async () => { const parentSubjectIds = ["0x1", "0x2"]; const childSubjectId = "0x3"; const node = createSubjectNode(parentSubjectIds); const childNode = createSubjectNode(childSubjectId); const filteredProvider = moq.Mock.ofType<FilteredPresentationTreeDataProvider>(); filteredProvider.setup(async (x) => x.getNodes(node)).returns(async () => [childNode]).verifiable(moq.Times.once()); filteredProvider.setup(async (x) => x.getNodes(childNode)).returns(async () => []).verifiable(moq.Times.never()); filteredProvider.setup((x) => x.getNodeKey(childNode)).returns(() => childNode.__key).verifiable(moq.Times.once()); filteredProvider.setup((x) => x.nodeMatchesFilter(node)).returns(() => false); filteredProvider.setup((x) => x.nodeMatchesFilter(childNode)).returns(() => true); mockSubjectModelIds({ imodelMock, subjectsHierarchy: new Map([ [parentSubjectIds[0], [childSubjectId]], [parentSubjectIds[1], [childSubjectId]], ]), subjectModels: new Map([ [parentSubjectIds[0], [{ id: "0x10" }]], [parentSubjectIds[1], [{ id: "0x20" }]], [childSubjectId, [{ id: "0x30" }]], ]), }); const viewStateMock = moq.Mock.ofType<ViewState3d>(); viewStateMock.setup((x) => x.isSpatialView()).returns(() => true); viewStateMock.setup((x) => x.viewsModel("0x10")).returns(() => false); viewStateMock.setup((x) => x.viewsModel("0x20")).returns(() => false); viewStateMock.setup((x) => x.viewsModel("0x30")).returns(() => false); const vpMock = mockViewport({ viewState: viewStateMock.object }); await using(createHandler({ viewport: vpMock.object }), async (handler) => { handler.setFilteredDataProvider(filteredProvider.object); const result = handler.getVisibilityStatus(node, node.__key); expect(isPromiseLike(result)).to.be.true; if (isPromiseLike(result)) expect(await result).to.include({ state: "hidden" }); filteredProvider.verifyAll(); }); }); }); }); describe("model", () => { it("return disabled when active view is not spatial", async () => { const node = createModelNode(); const vpMock = mockViewport(); await using(createHandler({ viewport: vpMock.object }), async (handler) => { const result = handler.getVisibilityStatus(node, node.__key); expect(isPromiseLike(result)).to.be.false; expect(result).to.include({ state: "hidden", isDisabled: true }); }); }); it("return 'visible' when displayed", async () => { const node = createModelNode(); const key = node.__key.instanceKeys[0]; const viewStateMock = moq.Mock.ofType<ViewState3d>(); viewStateMock.setup((x) => x.isSpatialView()).returns(() => true); viewStateMock.setup((x) => x.viewsModel(key.id)).returns(() => true); const vpMock = mockViewport({ viewState: viewStateMock.object }); await using(createHandler({ viewport: vpMock.object }), async (handler) => { const result = handler.getVisibilityStatus(node, node.__key); expect(isPromiseLike(result)).to.be.false; expect(result).to.include({ state: "visible" }); }); }); it("returns 'hidden' when not displayed", async () => { const node = createModelNode(); const key = node.__key.instanceKeys[0]; const viewStateMock = moq.Mock.ofType<ViewState3d>(); viewStateMock.setup((x) => x.isSpatialView()).returns(() => true); viewStateMock.setup((x) => x.viewsModel(key.id)).returns(() => false); const vpMock = mockViewport({ viewState: viewStateMock.object }); await using(createHandler({ viewport: vpMock.object }), async (handler) => { const result = handler.getVisibilityStatus(node, node.__key); expect(isPromiseLike(result)).to.be.false; expect(result).to.include({ state: "hidden" }); }); }); }); describe("category", () => { it("return disabled when model not displayed", async () => { const parentModelNode = createModelNode(); const parentModelKey = parentModelNode.__key.instanceKeys[0]; const categoryNode = createCategoryNode(parentModelKey); const viewStateMock = moq.Mock.ofType<ViewState3d>(); viewStateMock.setup((x) => x.isSpatialView()).returns(() => true); viewStateMock.setup((x) => x.viewsModel(parentModelKey.id)).returns(() => false); const vpMock = mockViewport({ viewState: viewStateMock.object }); await using(createHandler({ viewport: vpMock.object }), async (handler) => { const result = handler.getVisibilityStatus(categoryNode, categoryNode.__key); expect(isPromiseLike(result)).to.be.false; expect(result).to.include({ state: "hidden", isDisabled: true }); }); }); it("return 'visible' when model displayed, category not displayed but per-model override says it's displayed", async () => { const parentModelNode = createModelNode(); const parentModelKey = parentModelNode.__key.instanceKeys[0]; const categoryNode = createCategoryNode(parentModelKey); const categoryKey = categoryNode.__key.instanceKeys[0]; const viewStateMock = moq.Mock.ofType<ViewState3d>(); viewStateMock.setup((x) => x.viewsCategory(categoryKey.id)).returns(() => false); viewStateMock.setup((x) => x.isSpatialView()).returns(() => true); viewStateMock.setup((x) => x.viewsModel(parentModelKey.id)).returns(() => true); const perModelCategoryVisibilityMock = moq.Mock.ofType<PerModelCategoryVisibility.Overrides>(); perModelCategoryVisibilityMock.setup((x) => x.getOverride(parentModelKey.id, categoryKey.id)).returns(() => PerModelCategoryVisibility.Override.Show); const vpMock = mockViewport({ viewState: viewStateMock.object, perModelCategoryVisibility: perModelCategoryVisibilityMock.object }); await using(createHandler({ viewport: vpMock.object }), async (handler) => { const result = handler.getVisibilityStatus(categoryNode, categoryNode.__key); expect(isPromiseLike(result)).to.be.false; expect(result).to.include({ state: "visible" }); }); }); it("return 'visible' when model displayed, category displayed and there're no per-model overrides", async () => { const parentModelNode = createModelNode(); const parentModelKey = parentModelNode.__key.instanceKeys[0]; const categoryNode = createCategoryNode(parentModelKey); const key = categoryNode.__key.instanceKeys[0]; const viewStateMock = moq.Mock.ofType<ViewState3d>(); viewStateMock.setup((x) => x.viewsCategory(key.id)).returns(() => true); viewStateMock.setup((x) => x.isSpatialView()).returns(() => true); viewStateMock.setup((x) => x.viewsModel(parentModelKey.id)).returns(() => true); const vpMock = mockViewport({ viewState: viewStateMock.object }); await using(createHandler({ viewport: vpMock.object }), async (handler) => { const result = handler.getVisibilityStatus(categoryNode, categoryNode.__key); expect(isPromiseLike(result)).to.be.false; expect(result).to.include({ state: "visible" }); }); }); it("return 'hidden' when model displayed, category displayed but per-model override says it's not displayed", async () => { const parentModelNode = createModelNode(); const parentModelKey = parentModelNode.__key.instanceKeys[0]; const categoryNode = createCategoryNode(parentModelKey); const categoryKey = categoryNode.__key.instanceKeys[0]; const viewStateMock = moq.Mock.ofType<ViewState3d>(); viewStateMock.setup((x) => x.viewsCategory(categoryKey.id)).returns(() => true); viewStateMock.setup((x) => x.isSpatialView()).returns(() => true); viewStateMock.setup((x) => x.viewsModel(parentModelKey.id)).returns(() => true); const perModelCategoryVisibilityMock = moq.Mock.ofType<PerModelCategoryVisibility.Overrides>(); perModelCategoryVisibilityMock.setup((x) => x.getOverride(parentModelKey.id, categoryKey.id)).returns(() => PerModelCategoryVisibility.Override.Hide); const vpMock = mockViewport({ viewState: viewStateMock.object, perModelCategoryVisibility: perModelCategoryVisibilityMock.object }); await using(createHandler({ viewport: vpMock.object }), async (handler) => { const result = handler.getVisibilityStatus(categoryNode, categoryNode.__key); expect(isPromiseLike(result)).to.be.false; expect(result).to.include({ state: "hidden" }); }); }); it("return 'hidden' when model displayed, category not displayed and there're no per-model overrides", async () => { const parentModelNode = createModelNode(); const parentModelKey = parentModelNode.__key.instanceKeys[0]; const categoryNode = createCategoryNode(parentModelKey); const key = categoryNode.__key.instanceKeys[0]; const viewStateMock = moq.Mock.ofType<ViewState3d>(); viewStateMock.setup((x) => x.viewsCategory(key.id)).returns(() => false); viewStateMock.setup((x) => x.isSpatialView()).returns(() => true); viewStateMock.setup((x) => x.viewsModel(parentModelKey.id)).returns(() => true); const vpMock = mockViewport({ viewState: viewStateMock.object }); await using(createHandler({ viewport: vpMock.object }), async (handler) => { const result = handler.getVisibilityStatus(categoryNode, categoryNode.__key); expect(isPromiseLike(result)).to.be.false; expect(result).to.include({ state: "hidden" }); }); }); it("return 'hidden' when category has no parent model and category is not displayed", async () => { const categoryNode = createCategoryNode(); const categoryKey = categoryNode.__key.instanceKeys[0]; const viewStateMock = moq.Mock.ofType<ViewState3d>(); viewStateMock.setup((x) => x.viewsCategory(categoryKey.id)).returns(() => false); const vpMock = mockViewport({ viewState: viewStateMock.object }); await using(createHandler({ viewport: vpMock.object }), async (handler) => { const result = handler.getVisibilityStatus(categoryNode, categoryNode.__key); expect(isPromiseLike(result)).to.be.false; expect(result).to.include({ state: "hidden" }); }); }); }); describe("element class grouping", () => { it("returns disabled when model not displayed", async () => { const groupedElementIds = ["0x11", "0x12", "0x13"]; const node = createElementClassGroupingNode(groupedElementIds); const viewStateMock = moq.Mock.ofType<ViewState3d>(); viewStateMock.setup((x) => x.isSpatialView()).returns(() => true); viewStateMock.setup((x) => x.viewsModel("0x2")).returns(() => false); const vpMock = mockViewport({ viewState: viewStateMock.object }); await using(createHandler({ viewport: vpMock.object }), async (handler) => { // note: need to override to avoid running queries on the imodel (handler as any).getGroupedElementIds = async () => ({ categoryId: "0x1", modelId: "0x2", elementIds: groupedElementIds }); const result = handler.getVisibilityStatus(node, node.__key); expect(isPromiseLike(result)).to.be.true; expect(await result).to.include({ state: "hidden", isDisabled: true }); }); }); it("returns 'visible' when model displayed and at least one element is in always displayed list", async () => { const groupedElementIds = ["0x11", "0x12", "0x13"]; const node = createElementClassGroupingNode(groupedElementIds); const viewStateMock = moq.Mock.ofType<ViewState3d>(); viewStateMock.setup((x) => x.viewsCategory("0x1")).returns(() => false); viewStateMock.setup((x) => x.isSpatialView()).returns(() => true); viewStateMock.setup((x) => x.viewsModel("0x2")).returns(() => true); const vpMock = mockViewport({ viewState: viewStateMock.object }); const alwaysDrawn = new Set([groupedElementIds[1]]); vpMock.setup((x) => x.neverDrawn).returns(() => undefined); vpMock.setup((x) => x.alwaysDrawn).returns(() => alwaysDrawn); await using(createHandler({ viewport: vpMock.object }), async (handler) => { // note: need to override to avoid running queries on the imodel (handler as any).getGroupedElementIds = async () => ({ categoryId: "0x1", modelId: "0x2", elementIds: groupedElementIds }); const result = handler.getVisibilityStatus(node, node.__key); expect(isPromiseLike(result)).to.be.true; expect(await result).to.include({ state: "visible" }); }); }); it("returns 'hidden' when model displayed and there's at least one element in always exclusive displayed list that's not grouped under node", async () => { const groupedElementIds = ["0x11", "0x12", "0x13"]; const node = createElementClassGroupingNode(groupedElementIds); const viewStateMock = moq.Mock.ofType<ViewState3d>(); viewStateMock.setup((x) => x.viewsCategory("0x1")).returns(() => true); viewStateMock.setup((x) => x.isSpatialView()).returns(() => true); viewStateMock.setup((x) => x.viewsModel("0x2")).returns(() => true); const vpMock = mockViewport({ viewState: viewStateMock.object }); const alwaysDrawn = new Set(["0x4"]); vpMock.setup((x) => x.neverDrawn).returns(() => undefined); vpMock.setup((x) => x.alwaysDrawn).returns(() => alwaysDrawn); vpMock.setup((x) => x.isAlwaysDrawnExclusive).returns(() => true); await using(createHandler({ viewport: vpMock.object }), async (handler) => { // note: need to override to avoid running queries on the imodel (handler as any).getGroupedElementIds = async () => ({ categoryId: "0x1", modelId: "0x2", elementIds: groupedElementIds }); const result = handler.getVisibilityStatus(node, node.__key); expect(isPromiseLike(result)).to.be.true; expect(await result).to.include({ state: "hidden" }); }); }); it("returns 'hidden' when model displayed and all elements are in never displayed list", async () => { const groupedElementIds = ["0x11", "0x12", "0x13"]; const node = createElementClassGroupingNode(groupedElementIds); const viewStateMock = moq.Mock.ofType<ViewState3d>(); viewStateMock.setup((x) => x.viewsCategory("0x1")).returns(() => true); viewStateMock.setup((x) => x.isSpatialView()).returns(() => true); viewStateMock.setup((x) => x.viewsModel("0x2")).returns(() => true); const vpMock = mockViewport({ viewState: viewStateMock.object }); const neverDrawn = new Set(groupedElementIds); vpMock.setup((x) => x.neverDrawn).returns(() => neverDrawn); vpMock.setup((x) => x.alwaysDrawn).returns(() => new Set()); await using(createHandler({ viewport: vpMock.object }), async (handler) => { // note: need to override to avoid running queries on the imodel (handler as any).getGroupedElementIds = async () => ({ categoryId: "0x1", modelId: "0x2", elementIds: groupedElementIds }); const result = handler.getVisibilityStatus(node, node.__key); expect(isPromiseLike(result)).to.be.true; expect(await result).to.include({ state: "hidden" }); }); }); it("returns 'hidden' when model displayed and category not displayed", async () => { const groupedElementIds = ["0x11", "0x12", "0x13"]; const node = createElementClassGroupingNode(groupedElementIds); const viewStateMock = moq.Mock.ofType<ViewState3d>(); viewStateMock.setup((x) => x.viewsCategory("0x1")).returns(() => false); viewStateMock.setup((x) => x.isSpatialView()).returns(() => true); viewStateMock.setup((x) => x.viewsModel("0x2")).returns(() => true); const vpMock = mockViewport({ viewState: viewStateMock.object }); const neverDrawn = new Set(["0x11"]); vpMock.setup((x) => x.neverDrawn).returns(() => neverDrawn); vpMock.setup((x) => x.alwaysDrawn).returns(() => new Set()); await using(createHandler({ viewport: vpMock.object }), async (handler) => { // note: need to override to avoid running queries on the imodel (handler as any).getGroupedElementIds = async () => ({ categoryId: "0x1", modelId: "0x2", elementIds: groupedElementIds }); const result = handler.getVisibilityStatus(node, node.__key); expect(isPromiseLike(result)).to.be.true; expect(await result).to.include({ state: "hidden" }); }); }); it("returns 'visible' when model displayed and category displayed", async () => { const groupedElementIds = ["0x11", "0x12", "0x13"]; const node = createElementClassGroupingNode(groupedElementIds); const viewStateMock = moq.Mock.ofType<ViewState3d>(); viewStateMock.setup((x) => x.viewsCategory("0x1")).returns(() => true); viewStateMock.setup((x) => x.isSpatialView()).returns(() => true); viewStateMock.setup((x) => x.viewsModel("0x2")).returns(() => true); const vpMock = mockViewport({ viewState: viewStateMock.object }); const neverDrawn = new Set(["0x11"]); vpMock.setup((x) => x.neverDrawn).returns(() => neverDrawn); vpMock.setup((x) => x.alwaysDrawn).returns(() => new Set()); await using(createHandler({ viewport: vpMock.object }), async (handler) => { // note: need to override to avoid running queries on the imodel (handler as any).getGroupedElementIds = async () => ({ categoryId: "0x1", modelId: "0x2", elementIds: groupedElementIds }); const result = handler.getVisibilityStatus(node, node.__key); expect(isPromiseLike(result)).to.be.true; expect(await result).to.include({ state: "visible" }); }); }); }); describe("element", () => { it("returns disabled when modelId not set", async () => { const node = createElementNode(undefined, "0x1"); const viewStateMock = moq.Mock.ofType<ViewState3d>(); viewStateMock.setup((x) => x.isSpatialView()).returns(() => true); viewStateMock.setup((x) => x.viewsModel(moq.It.isAny())).returns(() => true); const vpMock = mockViewport({ viewState: viewStateMock.object }); await using(createHandler({ viewport: vpMock.object }), async (handler) => { const result = handler.getVisibilityStatus(node, node.__key); expect(isPromiseLike(result)).to.be.false; expect(result).to.include({ state: "hidden", isDisabled: true }); }); }); it("returns disabled when model not displayed", async () => { const node = createElementNode("0x2", "0x1"); const viewStateMock = moq.Mock.ofType<ViewState3d>(); viewStateMock.setup((x) => x.isSpatialView()).returns(() => true); viewStateMock.setup((x) => x.viewsModel("0x2")).returns(() => false); const vpMock = mockViewport({ viewState: viewStateMock.object }); await using(createHandler({ viewport: vpMock.object }), async (handler) => { const result = handler.getVisibilityStatus(node, node.__key); expect(isPromiseLike(result)).to.be.false; expect(result).to.include({ state: "hidden", isDisabled: true }); }); }); it("returns 'hidden' when model displayed, category displayed, but element is in never displayed list", async () => { const node = createElementNode("0x2", "0x1"); const key = node.__key.instanceKeys[0]; const viewStateMock = moq.Mock.ofType<ViewState3d>(); viewStateMock.setup((x) => x.viewsCategory("0x1")).returns(() => true); viewStateMock.setup((x) => x.isSpatialView()).returns(() => true); viewStateMock.setup((x) => x.viewsModel("0x2")).returns(() => true); const vpMock = mockViewport({ viewState: viewStateMock.object }); const neverDrawn = new Set([key.id]); vpMock.setup((x) => x.neverDrawn).returns(() => neverDrawn); vpMock.setup((x) => x.alwaysDrawn).returns(() => undefined); await using(createHandler({ viewport: vpMock.object }), async (handler) => { const result = handler.getVisibilityStatus(node, node.__key); expect(isPromiseLike(result)).to.be.false; expect(result).to.include({ state: "hidden" }); }); }); it("returns 'visible' when model displayed and element is in always displayed list", async () => { const node = createElementNode("0x2", "0x1"); const key = node.__key.instanceKeys[0]; const viewStateMock = moq.Mock.ofType<ViewState3d>(); viewStateMock.setup((x) => x.viewsCategory("0x1")).returns(() => false); viewStateMock.setup((x) => x.isSpatialView()).returns(() => true); viewStateMock.setup((x) => x.viewsModel("0x2")).returns(() => true); const vpMock = mockViewport({ viewState: viewStateMock.object }); const alwaysDrawn = new Set([key.id]); vpMock.setup((x) => x.neverDrawn).returns(() => undefined); vpMock.setup((x) => x.alwaysDrawn).returns(() => alwaysDrawn); await using(createHandler({ viewport: vpMock.object }), async (handler) => { const result = handler.getVisibilityStatus(node, node.__key); expect(isPromiseLike(result)).to.be.false; expect(result).to.include({ state: "visible" }); }); }); it("returns 'visible' when model displayed, category displayed and element is in neither 'never' nor 'always' displayed", async () => { const node = createElementNode("0x2", "0x1"); const viewStateMock = moq.Mock.ofType<ViewState3d>(); viewStateMock.setup((x) => x.viewsCategory("0x1")).returns(() => true); viewStateMock.setup((x) => x.isSpatialView()).returns(() => true); viewStateMock.setup((x) => x.viewsModel("0x2")).returns(() => true); const vpMock = mockViewport({ viewState: viewStateMock.object }); vpMock.setup((x) => x.alwaysDrawn).returns(() => undefined); vpMock.setup((x) => x.neverDrawn).returns(() => undefined); await using(createHandler({ viewport: vpMock.object }), async (handler) => { const result = handler.getVisibilityStatus(node, node.__key); expect(isPromiseLike(result)).to.be.false; expect(result).to.include({ state: "visible" }); }); }); it("returns 'hidden' when model displayed, category not displayed and element is in neither 'never' nor 'always' displayed", async () => { const node = createElementNode("0x2", "0x1"); const viewStateMock = moq.Mock.ofType<ViewState3d>(); viewStateMock.setup((x) => x.viewsCategory("0x1")).returns(() => false); viewStateMock.setup((x) => x.isSpatialView()).returns(() => true); viewStateMock.setup((x) => x.viewsModel("0x2")).returns(() => true); const vpMock = mockViewport({ viewState: viewStateMock.object }); vpMock.setup((x) => x.alwaysDrawn).returns(() => undefined); vpMock.setup((x) => x.neverDrawn).returns(() => undefined); await using(createHandler({ viewport: vpMock.object }), async (handler) => { const result = handler.getVisibilityStatus(node, node.__key); expect(isPromiseLike(result)).to.be.false; expect(result).to.include({ state: "hidden" }); }); }); it("returns 'hidden' when model displayed, category displayed and some other element is exclusively 'always' displayed", async () => { const node = createElementNode("0x2", "0x1"); const viewStateMock = moq.Mock.ofType<ViewState3d>(); viewStateMock.setup((x) => x.viewsCategory("0x1")).returns(() => true); viewStateMock.setup((x) => x.isSpatialView()).returns(() => true); viewStateMock.setup((x) => x.viewsModel("0x2")).returns(() => true); const vpMock = mockViewport({ viewState: viewStateMock.object }); vpMock.setup((x) => x.isAlwaysDrawnExclusive).returns(() => true); vpMock.setup((x) => x.alwaysDrawn).returns(() => new Set([createRandomId()])); vpMock.setup((x) => x.neverDrawn).returns(() => undefined); await using(createHandler({ viewport: vpMock.object }), async (handler) => { const result = handler.getVisibilityStatus(node, node.__key); expect(isPromiseLike(result)).to.be.false; expect(result).to.include({ state: "hidden" }); }); }); it("returns 'hidden' when model displayed, categoryId not set and element is in neither 'never' nor 'always' displayed", async () => { const node = createElementNode("0x2", undefined); const viewStateMock = moq.Mock.ofType<ViewState3d>(); viewStateMock.setup((x) => x.viewsCategory(moq.It.isAny())).returns(() => true); viewStateMock.setup((x) => x.isSpatialView()).returns(() => true); viewStateMock.setup((x) => x.viewsModel("0x2")).returns(() => true); const vpMock = mockViewport({ viewState: viewStateMock.object }); vpMock.setup((x) => x.alwaysDrawn).returns(() => new Set()); vpMock.setup((x) => x.neverDrawn).returns(() => new Set()); await using(createHandler({ viewport: vpMock.object }), async (handler) => { const result = handler.getVisibilityStatus(node, node.__key); expect(isPromiseLike(result)).to.be.false; expect(result).to.include({ state: "hidden" }); }); }); }); }); describe("changeVisibility", () => { it("does nothing when node is not an instance node", async () => { const node = { __key: { type: "custom", version: 0, pathFromRoot: [], }, id: "custom", label: PropertyRecord.fromString("custom"), }; const vpMock = mockViewport(); vpMock.setup(async (x) => x.addViewedModels(moq.It.isAny())).verifiable(moq.Times.never()); await using(createHandler({ viewport: vpMock.object }), async (handler) => { await handler.changeVisibility(node, node.__key, true); vpMock.verifyAll(); }); }); describe("subject", () => { it("does nothing for non-spatial views", async () => { const node = createSubjectNode(); const viewStateMock = moq.Mock.ofType<ViewState>(); viewStateMock.setup((x) => x.isSpatialView()).returns(() => false); const vpMock = mockViewport({ viewState: viewStateMock.object }); vpMock.setup(async (x) => x.addViewedModels(moq.It.isAny())).verifiable(moq.Times.never()); await using(createHandler({ viewport: vpMock.object }), async (handler) => { // note: need to override to avoid running a query on the imodel (handler as any).getSubjectModelIds = async () => ["0x1", "0x2"]; await handler.changeVisibility(node, node.__key, true); vpMock.verifyAll(); }); }); it("makes all subject models visible", async () => { const node = createSubjectNode(); const subjectModelIds = ["0x1", "0x2"]; const viewStateMock = moq.Mock.ofType<SpatialViewState>(); viewStateMock.setup((x) => x.isSpatialView()).returns(() => true); const vpMock = mockViewport({ viewState: viewStateMock.object }); vpMock.setup(async (x) => x.addViewedModels(subjectModelIds)).verifiable(); await using(createHandler({ viewport: vpMock.object }), async (handler) => { // note: need to override to avoid running a query on the imodel (handler as any).getSubjectModelIds = async () => subjectModelIds; await handler.changeVisibility(node, node.__key, true); vpMock.verifyAll(); }); }); it("makes all subject models hidden", async () => { const node = createSubjectNode(); const subjectModelIds = ["0x1", "0x2"]; const viewStateMock = moq.Mock.ofType<SpatialViewState>(); viewStateMock.setup((x) => x.isSpatialView()).returns(() => true); const vpMock = mockViewport({ viewState: viewStateMock.object }); vpMock.setup((x) => x.changeModelDisplay(subjectModelIds, false)).verifiable(); await using(createHandler({ viewport: vpMock.object }), async (handler) => { // note: need to override to avoid running a query on the imodel (handler as any).getSubjectModelIds = async () => subjectModelIds; await handler.changeVisibility(node, node.__key, false); vpMock.verifyAll(); }); }); describe("filtered", () => { ["visible", "hidden"].map((mode) => { it(`makes all subject models ${mode} when subject node does not have children`, async () => { const node = createSubjectNode(); const key = node.__key.instanceKeys[0]; const subjectModelIds = ["0x1", "0x2"]; const filteredDataProvider = moq.Mock.ofType<FilteredPresentationTreeDataProvider>(); filteredDataProvider.setup(async (x) => x.getNodes(node)).returns(async () => []).verifiable(moq.Times.never()); filteredDataProvider.setup((x) => x.nodeMatchesFilter(node)).returns(() => true); const viewStateMock = moq.Mock.ofType<SpatialViewState>(); viewStateMock.setup((x) => x.isSpatialView()).returns(() => true); mockSubjectModelIds({ imodelMock, subjectsHierarchy: new Map([]), subjectModels: new Map([ [key.id, [{ id: subjectModelIds[0], content: "reference" }, { id: subjectModelIds[1] }]], ]), }); const vpMock = mockViewport({ viewState: viewStateMock.object }); if (mode === "visible") { vpMock.setup(async (x) => x.addViewedModels(subjectModelIds)).verifiable(); } else { vpMock.setup((x) => x.changeModelDisplay(subjectModelIds, false)).verifiable(); } await using(createHandler({ viewport: vpMock.object }), async (handler) => { handler.setFilteredDataProvider(filteredDataProvider.object); await handler.changeVisibility(node, node.__key, mode === "visible"); vpMock.verifyAll(); filteredDataProvider.verifyAll(); }); }); it(`makes only children ${mode} if parent node does not match filter`, async () => { const node = createSubjectNode("0x1"); const childNode = createSubjectNode("0x2"); const parentSubjectModelIds = ["0x10", "0x11"]; const childSubjectModelIds = ["0x20"]; const filteredDataProvider = moq.Mock.ofType<FilteredPresentationTreeDataProvider>(); filteredDataProvider.setup(async (x) => x.getNodes(node)).returns(async () => [childNode]).verifiable(moq.Times.once()); filteredDataProvider.setup(async (x) => x.getNodes(childNode)).returns(async () => []).verifiable(moq.Times.never()); filteredDataProvider.setup((x) => x.getNodeKey(childNode)).returns(() => childNode.__key).verifiable(moq.Times.once()); filteredDataProvider.setup((x) => x.nodeMatchesFilter(node)).returns(() => false); filteredDataProvider.setup((x) => x.nodeMatchesFilter(childNode)).returns(() => true); const viewStateMock = moq.Mock.ofType<SpatialViewState>(); viewStateMock.setup((x) => x.isSpatialView()).returns(() => true); mockSubjectModelIds({ imodelMock, subjectsHierarchy: new Map([ ["0x1", ["0x2"]], ]), subjectModels: new Map([ ["0x1", [{ id: parentSubjectModelIds[0] }, { id: parentSubjectModelIds[1] }]], ["0x2", [{ id: childSubjectModelIds[0] }]], ]), }); const vpMock = mockViewport({ viewState: viewStateMock.object }); if (mode === "visible") { vpMock.setup(async (x) => x.addViewedModels(childSubjectModelIds)).verifiable(); } else { vpMock.setup((x) => x.changeModelDisplay(childSubjectModelIds, false)).verifiable(); } await using(createHandler({ viewport: vpMock.object }), async (handler) => { handler.setFilteredDataProvider(filteredDataProvider.object); await handler.changeVisibility(node, node.__key, mode === "visible"); vpMock.verifyAll(); filteredDataProvider.verifyAll(); }); }); }); }); }); describe("model", () => { it("does nothing for non-spatial views", async () => { const node = createModelNode(); const viewStateMock = moq.Mock.ofType<ViewState>(); viewStateMock.setup((x) => x.isSpatialView()).returns(() => false); const vpMock = mockViewport({ viewState: viewStateMock.object }); vpMock.setup(async (x) => x.addViewedModels(moq.It.isAny())).verifiable(moq.Times.never()); await using(createHandler({ viewport: vpMock.object }), async (handler) => { await handler.changeVisibility(node, node.__key, true); vpMock.verifyAll(); }); }); it("makes model visible", async () => { const node = createModelNode(); const key = node.__key.instanceKeys[0]; const viewStateMock = moq.Mock.ofType<SpatialViewState>(); viewStateMock.setup((x) => x.isSpatialView()).returns(() => true); const vpMock = mockViewport({ viewState: viewStateMock.object }); vpMock.setup(async (x) => x.addViewedModels([key.id])).verifiable(); await using(createHandler({ viewport: vpMock.object }), async (handler) => { await handler.changeVisibility(node, node.__key, true); vpMock.verifyAll(); }); }); it("makes model hidden", async () => { const node = createModelNode(); const key = node.__key.instanceKeys[0]; const viewStateMock = moq.Mock.ofType<SpatialViewState>(); viewStateMock.setup((x) => x.isSpatialView()).returns(() => true); const vpMock = mockViewport({ viewState: viewStateMock.object }); vpMock.setup((x) => x.changeModelDisplay([key.id], false)).verifiable(); await using(createHandler({ viewport: vpMock.object }), async (handler) => { await handler.changeVisibility(node, node.__key, false); vpMock.verifyAll(); }); }); }); describe("category", () => { it("makes category visible through per-model override when it's not visible through category selector", async () => { const parentModelNode = createModelNode(); const parentModelKey = parentModelNode.__key.instanceKeys[0]; const categoryNode = createCategoryNode(parentModelKey); const categoryKey = categoryNode.__key.instanceKeys[0]; const viewStateMock = moq.Mock.ofType<ViewState3d>(); viewStateMock.setup((x) => x.viewsCategory(categoryKey.id)).returns(() => false); const perModelCategoryVisibilityMock = moq.Mock.ofType<PerModelCategoryVisibility.Overrides>(); const vpMock = mockViewport({ viewState: viewStateMock.object, perModelCategoryVisibility: perModelCategoryVisibilityMock.object }); await using(createHandler({ viewport: vpMock.object }), async (handler) => { await handler.changeVisibility(categoryNode, categoryNode.__key, true); perModelCategoryVisibilityMock.verify((x) => x.setOverride(parentModelKey.id, categoryKey.id, PerModelCategoryVisibility.Override.Show), moq.Times.once()); vpMock.verify((x) => x.changeCategoryDisplay(moq.It.isAny(), moq.It.isAny(), moq.It.isAny()), moq.Times.never()); }); }); it("makes category hidden through override when it's visible through category selector", async () => { const parentModelNode = createModelNode(); const parentModelKey = parentModelNode.__key.instanceKeys[0]; const categoryNode = createCategoryNode(parentModelKey); const categoryKey = categoryNode.__key.instanceKeys[0]; const viewStateMock = moq.Mock.ofType<ViewState3d>(); viewStateMock.setup((x) => x.viewsCategory(categoryKey.id)).returns(() => true); const perModelCategoryVisibilityMock = moq.Mock.ofType<PerModelCategoryVisibility.Overrides>(); const vpMock = mockViewport({ viewState: viewStateMock.object, perModelCategoryVisibility: perModelCategoryVisibilityMock.object }); await using(createHandler({ viewport: vpMock.object }), async (handler) => { await handler.changeVisibility(categoryNode, categoryNode.__key, false); perModelCategoryVisibilityMock.verify((x) => x.setOverride(parentModelKey.id, categoryKey.id, PerModelCategoryVisibility.Override.Hide), moq.Times.once()); vpMock.verify((x) => x.changeCategoryDisplay(moq.It.isAny(), moq.It.isAny(), moq.It.isAny()), moq.Times.never()); }); }); it("removes category override and enables all sub-categories when making visible and it's visible through category selector", async () => { const parentModelNode = createModelNode(); const parentModelKey = parentModelNode.__key.instanceKeys[0]; const categoryNode = createCategoryNode(parentModelKey); const categoryKey = categoryNode.__key.instanceKeys[0]; const viewStateMock = moq.Mock.ofType<ViewState3d>(); viewStateMock.setup((x) => x.viewsCategory(categoryKey.id)).returns(() => true); const perModelCategoryVisibilityMock = moq.Mock.ofType<PerModelCategoryVisibility.Overrides>(); const vpMock = mockViewport({ viewState: viewStateMock.object, perModelCategoryVisibility: perModelCategoryVisibilityMock.object }); await using(createHandler({ viewport: vpMock.object }), async (handler) => { await handler.changeVisibility(categoryNode, categoryNode.__key, true); perModelCategoryVisibilityMock.verify((x) => x.setOverride(parentModelKey.id, categoryKey.id, PerModelCategoryVisibility.Override.None), moq.Times.once()); vpMock.verify((x) => x.changeCategoryDisplay([categoryKey.id], true, true), moq.Times.once()); }); }); it("removes category override when making hidden and it's hidden through category selector", async () => { const parentModelNode = createModelNode(); const parentModelKey = parentModelNode.__key.instanceKeys[0]; const categoryNode = createCategoryNode(parentModelKey); const categoryKey = categoryNode.__key.instanceKeys[0]; const viewStateMock = moq.Mock.ofType<ViewState3d>(); viewStateMock.setup((x) => x.viewsCategory(categoryKey.id)).returns(() => false); const perModelCategoryVisibilityMock = moq.Mock.ofType<PerModelCategoryVisibility.Overrides>(); const vpMock = mockViewport({ viewState: viewStateMock.object, perModelCategoryVisibility: perModelCategoryVisibilityMock.object }); await using(createHandler({ viewport: vpMock.object }), async (handler) => { await handler.changeVisibility(categoryNode, categoryNode.__key, false); perModelCategoryVisibilityMock.verify((x) => x.setOverride(parentModelKey.id, categoryKey.id, PerModelCategoryVisibility.Override.None), moq.Times.once()); vpMock.verify((x) => x.changeCategoryDisplay(moq.It.isAny(), moq.It.isAny(), moq.It.isAny()), moq.Times.never()); }); }); it("makes category visible in selector and enables all sub-categories when category has no parent model", async () => { const categoryNode = createCategoryNode(); const categoryKey = categoryNode.__key.instanceKeys[0]; const vpMock = mockViewport(); await using(createHandler({ viewport: vpMock.object }), async (handler) => { await handler.changeVisibility(categoryNode, categoryNode.__key, true); vpMock.verify((x) => x.changeCategoryDisplay([categoryKey.id], true, true), moq.Times.once()); }); }); it("makes category hidden in selector when category has no parent model", async () => { const categoryNode = createCategoryNode(); const categoryKey = categoryNode.__key.instanceKeys[0]; const vpMock = mockViewport(); vpMock.setup((x) => x.changeCategoryDisplay([categoryKey.id], false)).verifiable(); await using(createHandler({ viewport: vpMock.object }), async (handler) => { await handler.changeVisibility(categoryNode, categoryNode.__key, false); vpMock.verify((x) => x.changeCategoryDisplay([categoryKey.id], false, false), moq.Times.once()); }); }); }); describe("element class grouping", () => { it("makes elements visible by removing from never displayed list and adding to always displayed list when category is not displayed", async () => { const groupedElementIds = ["0x11", "0x12", "0x13"]; const node = createElementClassGroupingNode(groupedElementIds); const viewStateMock = moq.Mock.ofType<ViewState3d>(); viewStateMock.setup((x) => x.viewsCategory("0x1")).returns(() => false); viewStateMock.setup((x) => x.isSpatialView()).returns(() => true); viewStateMock.setup((x) => x.viewsModel("0x2")).returns(() => false); const vpMock = mockViewport({ viewState: viewStateMock.object }); const alwaysDisplayed = new Set<string>(); const neverDisplayed = new Set([groupedElementIds[0]]); vpMock.setup((x) => x.isAlwaysDrawnExclusive).returns(() => false); vpMock.setup((x) => x.alwaysDrawn).returns(() => alwaysDisplayed); vpMock.setup((x) => x.neverDrawn).returns(() => neverDisplayed); vpMock.setup((x) => x.setAlwaysDrawn(moq.It.is((set) => { return set.size === 3 && groupedElementIds.reduce<boolean>((result, id) => (result && set.has(id)), true); }), false)).verifiable(); vpMock.setup((x) => x.setNeverDrawn(moq.It.is((set) => (set.size === 0)))).verifiable(); await using(createHandler({ viewport: vpMock.object }), async (handler) => { // note: need to override to avoid running queries on the imodel (handler as any).getGroupedElementIds = async () => ({ categoryId: "0x1", modelId: "0x2", elementIds: groupedElementIds }); await handler.changeVisibility(node, node.__key, true); vpMock.verifyAll(); }); }); }); describe("element", () => { it("makes element visible by only removing from never displayed list when element's category is displayed", async () => { const node = createElementNode("0x4", "0x3"); const key = node.__key.instanceKeys[0]; const assemblyChildrenIds = ["0x1", "0x2"]; const viewStateMock = moq.Mock.ofType<ViewState3d>(); viewStateMock.setup((x) => x.viewsCategory("0x3")).returns(() => true); viewStateMock.setup((x) => x.isSpatialView()).returns(() => true); viewStateMock.setup((x) => x.viewsModel("0x4")).returns(() => true); const vpMock = mockViewport({ viewState: viewStateMock.object }); const alwaysDisplayed = new Set<string>(); const neverDisplayed = new Set([key.id]); vpMock.setup((x) => x.isAlwaysDrawnExclusive).returns(() => false); vpMock.setup((x) => x.alwaysDrawn).returns(() => alwaysDisplayed); vpMock.setup((x) => x.neverDrawn).returns(() => neverDisplayed); vpMock.setup((x) => x.setNeverDrawn(moq.It.is((set) => (set.size === 0)))).verifiable(); vpMock.setup((x) => x.setAlwaysDrawn(moq.It.is((set) => (set.size === 0)), false)).verifiable(); await using(createHandler({ viewport: vpMock.object }), async (handler) => { // note: need to override to avoid running queries on the imodel (handler as any).getAssemblyElementIds = async () => assemblyChildrenIds; await handler.changeVisibility(node, node.__key, true); vpMock.verifyAll(); }); }); it("makes element visible by removing from never displayed list and adding to always displayed list when category is not displayed", async () => { const node = createElementNode("0x4", "0x3"); const key = node.__key.instanceKeys[0]; const assemblyChildrenIds = ["0x1", "0x2"]; const viewStateMock = moq.Mock.ofType<ViewState3d>(); viewStateMock.setup((x) => x.viewsCategory("0x4")).returns(() => false); viewStateMock.setup((x) => x.isSpatialView()).returns(() => true); viewStateMock.setup((x) => x.viewsModel("0x3")).returns(() => false); const vpMock = mockViewport({ viewState: viewStateMock.object }); const alwaysDisplayed = new Set<string>(); const neverDisplayed = new Set([key.id]); vpMock.setup((x) => x.isAlwaysDrawnExclusive).returns(() => false); vpMock.setup((x) => x.alwaysDrawn).returns(() => alwaysDisplayed); vpMock.setup((x) => x.neverDrawn).returns(() => neverDisplayed); vpMock.setup((x) => x.setAlwaysDrawn(moq.It.is((set) => { return set.size === 3 && set.has(key.id) && assemblyChildrenIds.reduce<boolean>((result, id) => (result && set.has(id)), true); }), false)).verifiable(); vpMock.setup((x) => x.setNeverDrawn(moq.It.is((set) => (set.size === 0)))).verifiable(); await using(createHandler({ viewport: vpMock.object }), async (handler) => { // note: need to override to avoid running a query on the imodel (handler as any).getAssemblyElementIds = async () => assemblyChildrenIds; await handler.changeVisibility(node, node.__key, true); vpMock.verifyAll(); }); }); it("makes element visible by adding to always displayed list when category is displayed, but element is hidden due to other elements exclusively always drawn", async () => { const node = createElementNode("0x4", "0x3"); const key = node.__key.instanceKeys[0]; const viewStateMock = moq.Mock.ofType<ViewState3d>(); viewStateMock.setup((x) => x.viewsCategory("0x4")).returns(() => true); viewStateMock.setup((x) => x.isSpatialView()).returns(() => true); viewStateMock.setup((x) => x.viewsModel("0x3")).returns(() => true); const vpMock = mockViewport({ viewState: viewStateMock.object }); const alwaysDisplayed = new Set<Id64String>([createRandomId()]); vpMock.setup((x) => x.isAlwaysDrawnExclusive).returns(() => true); vpMock.setup((x) => x.alwaysDrawn).returns(() => alwaysDisplayed); vpMock.setup((x) => x.neverDrawn).returns(() => undefined); vpMock.setup((x) => x.setAlwaysDrawn(moq.It.is((set) => { return set.size === 2 && set.has(key.id); }), true)).verifiable(); vpMock.setup((x) => x.setNeverDrawn(moq.It.is((set) => (set.size === 0)))).verifiable(); await using(createHandler({ viewport: vpMock.object }), async (handler) => { // note: need to override to avoid running a query on the imodel (handler as any).getAssemblyElementIds = async () => []; await handler.changeVisibility(node, node.__key, true); vpMock.verifyAll(); }); }); it("makes element hidden by only removing from always displayed list when element's category is not displayed", async () => { const node = createElementNode("0x4", "0x3"); const key = node.__key.instanceKeys[0]; const assemblyChildrenIds = ["0x1", "0x2"]; const viewStateMock = moq.Mock.ofType<ViewState3d>(); viewStateMock.setup((x) => x.viewsCategory("0x3")).returns(() => false); viewStateMock.setup((x) => x.isSpatialView()).returns(() => true); viewStateMock.setup((x) => x.viewsModel("0x4")).returns(() => true); const vpMock = mockViewport({ viewState: viewStateMock.object }); const alwaysDisplayed = new Set([key.id]); const neverDisplayed = new Set<string>(); vpMock.setup((x) => x.isAlwaysDrawnExclusive).returns(() => false); vpMock.setup((x) => x.alwaysDrawn).returns(() => alwaysDisplayed); vpMock.setup((x) => x.neverDrawn).returns(() => neverDisplayed); vpMock.setup((x) => x.setNeverDrawn(moq.It.is((set) => (set.size === 0)))).verifiable(); vpMock.setup((x) => x.setAlwaysDrawn(moq.It.is((set) => (set.size === 0)), false)).verifiable(); await using(createHandler({ viewport: vpMock.object }), async (handler) => { // note: need to override to avoid running queries on the imodel (handler as any).getAssemblyElementIds = async () => assemblyChildrenIds; await handler.changeVisibility(node, node.__key, false); vpMock.verifyAll(); }); }); it("makes element hidden by removing from always displayed list and adding to never displayed list when category is displayed", async () => { const node = createElementNode("0x4", "0x3"); const key = node.__key.instanceKeys[0]; const assemblyChildrenIds = ["0x1", "0x2"]; const viewStateMock = moq.Mock.ofType<ViewState3d>(); viewStateMock.setup((x) => x.viewsCategory("0x3")).returns(() => true); viewStateMock.setup((x) => x.isSpatialView()).returns(() => true); viewStateMock.setup((x) => x.viewsModel("0x4")).returns(() => true); const vpMock = mockViewport({ viewState: viewStateMock.object }); const alwaysDisplayed = new Set([key.id]); const neverDisplayed = new Set<string>(); vpMock.setup((x) => x.isAlwaysDrawnExclusive).returns(() => false); vpMock.setup((x) => x.alwaysDrawn).returns(() => alwaysDisplayed); vpMock.setup((x) => x.neverDrawn).returns(() => neverDisplayed); vpMock.setup((x) => x.setAlwaysDrawn(moq.It.is((set) => (set.size === 0)), false)).verifiable(); vpMock.setup((x) => x.setNeverDrawn(moq.It.is((set) => { return set.size === 3 && set.has(key.id) && assemblyChildrenIds.reduce<boolean>((result, id) => (result && set.has(id)), true); }))).verifiable(); await using(createHandler({ viewport: vpMock.object }), async (handler) => { // note: need to override to avoid running a query on the imodel (handler as any).getAssemblyElementIds = async () => assemblyChildrenIds; await handler.changeVisibility(node, node.__key, false); vpMock.verifyAll(); }); }); it("makes element hidden by removing from always displayed list when category is displayed and there are exclusively always drawn elements", async () => { const node = createElementNode("0x4", "0x3"); const key = node.__key.instanceKeys[0]; const viewStateMock = moq.Mock.ofType<ViewState3d>(); viewStateMock.setup((x) => x.viewsCategory("0x3")).returns(() => true); viewStateMock.setup((x) => x.isSpatialView()).returns(() => true); viewStateMock.setup((x) => x.viewsModel("0x4")).returns(() => true); const vpMock = mockViewport({ viewState: viewStateMock.object }); const alwaysDisplayed = new Set([key.id, createRandomId()]); vpMock.setup((x) => x.isAlwaysDrawnExclusive).returns(() => true); vpMock.setup((x) => x.alwaysDrawn).returns(() => alwaysDisplayed); vpMock.setup((x) => x.neverDrawn).returns(() => undefined); vpMock.setup((x) => x.setAlwaysDrawn(moq.It.is((set) => (set.size === 1 && !set.has(key.id))), true)).verifiable(); vpMock.setup((x) => x.setNeverDrawn(moq.It.is((set) => (set.size === 0)))).verifiable(); await using(createHandler({ viewport: vpMock.object }), async (handler) => { // note: need to override to avoid running a query on the imodel (handler as any).getAssemblyElementIds = async () => []; await handler.changeVisibility(node, node.__key, false); vpMock.verifyAll(); }); }); }); }); describe("visibility change event", () => { it("raises event on `onAlwaysDrawnChanged` event", async () => { const evt = new BeEvent(); const vpMock = mockViewport({ onAlwaysDrawnChanged: evt }); await using(createHandler({ viewport: vpMock.object }), async (handler) => { const spy = sinon.spy(); handler.onVisibilityChange.addListener(spy); evt.raiseEvent(vpMock.object); await new Promise((resolve) => setTimeout(resolve)); expect(spy).to.be.calledOnce; }); }); it("raises event on `onNeverDrawnChanged` event", async () => { const evt = new BeEvent(); const vpMock = mockViewport({ onNeverDrawnChanged: evt }); await using(createHandler({ viewport: vpMock.object }), async (handler) => { const spy = sinon.spy(); handler.onVisibilityChange.addListener(spy); evt.raiseEvent(vpMock.object); await new Promise((resolve) => setTimeout(resolve)); expect(spy).to.be.calledOnce; }); }); it("raises event on `onViewedCategoriesChanged` event", async () => { const evt = new BeEvent(); const vpMock = mockViewport({ onViewedCategoriesChanged: evt }); await using(createHandler({ viewport: vpMock.object }), async (handler) => { const spy = sinon.spy(); handler.onVisibilityChange.addListener(spy); evt.raiseEvent(vpMock.object); await new Promise((resolve) => setTimeout(resolve)); expect(spy).to.be.calledOnce; }); }); it("raises event on `onViewedModelsChanged` event", async () => { const evt = new BeEvent(); const vpMock = mockViewport({ onViewedModelsChanged: evt }); await using(createHandler({ viewport: vpMock.object }), async (handler) => { const spy = sinon.spy(); handler.onVisibilityChange.addListener(spy); evt.raiseEvent(vpMock.object); await new Promise((resolve) => setTimeout(resolve)); expect(spy).to.be.calledOnce; }); }); it("raises event on `onViewedCategoriesPerModelChanged` event", async () => { const evt = new BeEvent(); const vpMock = mockViewport({ onViewedCategoriesPerModelChanged: evt }); await using(createHandler({ viewport: vpMock.object }), async (handler) => { const spy = sinon.spy(); handler.onVisibilityChange.addListener(spy); evt.raiseEvent(vpMock.object); await new Promise((resolve) => setTimeout(resolve)); expect(spy).to.be.calledOnce; }); }); it("raises event once when multiple affecting events are fired", async () => { const evts = { onViewedCategoriesPerModelChanged: new BeEvent<(vp: Viewport) => void>(), onViewedCategoriesChanged: new BeEvent<(vp: Viewport) => void>(), onViewedModelsChanged: new BeEvent<(vp: Viewport) => void>(), onAlwaysDrawnChanged: new BeEvent<() => void>(), onNeverDrawnChanged: new BeEvent<() => void>(), }; const vpMock = mockViewport({ ...evts }); await using(createHandler({ viewport: vpMock.object }), async (handler) => { const spy = sinon.spy(); handler.onVisibilityChange.addListener(spy); evts.onViewedCategoriesPerModelChanged.raiseEvent(vpMock.object); evts.onViewedCategoriesChanged.raiseEvent(vpMock.object); evts.onViewedModelsChanged.raiseEvent(vpMock.object); evts.onAlwaysDrawnChanged.raiseEvent(); evts.onNeverDrawnChanged.raiseEvent(); await new Promise((resolve) => setTimeout(resolve)); expect(spy).to.be.calledOnce; }); }); }); });
the_stack
import ono from 'ono'; import * as express from 'express'; import * as _uniq from 'lodash.uniq'; import * as middlewares from './middlewares'; import { Application, Response, NextFunction, Router } from 'express'; import { OpenApiContext } from './framework/openapi.context'; import { Spec } from './framework/openapi.spec.loader'; import { OpenApiValidatorOpts, ValidateRequestOpts, ValidateResponseOpts, OpenApiRequest, OpenApiRequestHandler, OpenApiRequestMetadata, ValidateSecurityOpts, OpenAPIV3, } from './framework/types'; import { defaultResolver } from './resolvers'; import { OperationHandlerOptions } from './framework/types'; import { defaultSerDes } from './framework/base.serdes'; import { SchemaPreprocessor } from './middlewares/parsers/schema.preprocessor'; import { AjvOptions } from './framework/ajv/options'; export { OpenApiValidatorOpts, InternalServerError, UnsupportedMediaType, RequestEntityTooLarge, BadRequest, MethodNotAllowed, NotAcceptable, NotFound, Unauthorized, Forbidden, } from './framework/types'; export class OpenApiValidator { readonly options: OpenApiValidatorOpts; readonly ajvOpts: AjvOptions; constructor(options: OpenApiValidatorOpts) { this.validateOptions(options); this.normalizeOptions(options); if (options.validateApiSpec == null) options.validateApiSpec = true; if (options.validateRequests == null) options.validateRequests = true; if (options.validateResponses == null) options.validateResponses = false; if (options.validateSecurity == null) options.validateSecurity = true; if (options.fileUploader == null) options.fileUploader = {}; if (options.$refParser == null) options.$refParser = { mode: 'bundle' }; if (options.unknownFormats == null) options.unknownFormats === true; if (options.validateFormats == null) options.validateFormats = 'fast'; if (options.formats == null) options.formats = []; if (typeof options.operationHandlers === 'string') { /** * Internally, we want to convert this to a value typed OperationHandlerOptions. * In this way, we can treat the value as such when we go to install (rather than * re-interpreting it over and over). */ options.operationHandlers = { basePath: options.operationHandlers, resolver: defaultResolver, }; } else if (typeof options.operationHandlers !== 'object') { // This covers cases where operationHandlers is null, undefined or false. options.operationHandlers = false; } if (options.validateResponses === true) { options.validateResponses = { removeAdditional: false, coerceTypes: false, onError: null, }; } if (options.validateRequests === true) { options.validateRequests = { allowUnknownQueryParameters: false, coerceTypes: false, }; } if (options.validateSecurity === true) { options.validateSecurity = {}; } this.options = options; this.ajvOpts = new AjvOptions(options); } installMiddleware(spec: Promise<Spec>): OpenApiRequestHandler[] { const middlewares: OpenApiRequestHandler[] = []; const pContext = spec .then((spec) => { const apiDoc = spec.apiDoc; const ajvOpts = this.ajvOpts.preprocessor; const resOpts = this.options.validateResponses as ValidateRequestOpts; const sp = new SchemaPreprocessor( apiDoc, ajvOpts, resOpts, ).preProcess(); return { context: new OpenApiContext(spec, this.options.ignorePaths, this.options.ignoreUndocumented), responseApiDoc: sp.apiDocRes, error: null, }; }) .catch((e) => { return { context: null, responseApiDoc: null, error: e, }; }); const self = this; // using named functions instead of anonymous functions to allow traces to be more useful let inited = false; // install path params middlewares.push(function pathParamsMiddleware(req, res, next) { return pContext .then(({ context, error }) => { // Throw if any error occurred during spec load. if (error) throw error; if (!inited) { // Would be nice to pass the current Router object here if the route // is attach to a Router and not the app. // Doing so would enable path params to be type coerced when provided to // the final middleware. // Unfortunately, it is not possible to get the current Router from a handler function self.installPathParams(req.app, context); inited = true; } next(); }) .catch(next); }); // metadata middleware let metamw; middlewares.push(function metadataMiddleware(req, res, next) { return pContext .then(({ context, responseApiDoc }) => { metamw = metamw || self.metadataMiddleware(context, responseApiDoc); return metamw(req, res, next); }) .catch(next); }); if (this.options.fileUploader) { // multipart middleware let fumw; middlewares.push(function multipartMiddleware(req, res, next) { return pContext .then(({ context: { apiDoc } }) => { fumw = fumw || self.multipartMiddleware(apiDoc); return fumw(req, res, next); }) .catch(next); }); } // security middlware let scmw; middlewares.push(function securityMiddleware(req, res, next) { return pContext .then(({ context: { apiDoc } }) => { const components = apiDoc.components; if (self.options.validateSecurity && components?.securitySchemes) { scmw = scmw || self.securityMiddleware(apiDoc); return scmw(req, res, next); } else { next(); } }) .catch(next); }); // request middlweare if (this.options.validateRequests) { let reqmw; middlewares.push(function requestMiddleware(req, res, next) { return pContext .then(({ context: { apiDoc } }) => { reqmw = reqmw || self.requestValidationMiddleware(apiDoc); return reqmw(req, res, next); }) .catch(next); }); } // response middleware if (this.options.validateResponses) { let resmw; middlewares.push(function responseMiddleware(req, res, next) { return pContext .then(({ responseApiDoc }) => { resmw = resmw || self.responseValidationMiddleware(responseApiDoc); return resmw(req, res, next); }) .catch(next); }) } // op handler middleware if (this.options.operationHandlers) { let router: Router = null; middlewares.push(function operationHandlersMiddleware(req, res, next) { if (router) return router(req, res, next); return pContext .then( ({ context }) => (router = self.installOperationHandlers(req.baseUrl, context)), ) .then((router) => router(req, res, next)) .catch(next); }); } return middlewares; } installPathParams(app: Application | Router, context: OpenApiContext): void { const pathParams: string[] = []; for (const route of context.routes) { if (route.pathParams.length > 0) { pathParams.push(...route.pathParams); } } // install param on routes with paths for (const p of _uniq(pathParams)) { app.param( p, ( req: OpenApiRequest, res: Response, next: NextFunction, value: any, name: string, ) => { const openapi = <OpenApiRequestMetadata>req.openapi; if (openapi?.pathParams) { const { pathParams } = openapi; // override path params req.params[name] = pathParams[name] || req.params[name]; } next(); }, ); } } private metadataMiddleware( context: OpenApiContext, responseApiDoc: OpenAPIV3.Document, ) { return middlewares.applyOpenApiMetadata(context, responseApiDoc); } private multipartMiddleware(apiDoc: OpenAPIV3.Document) { return middlewares.multipart(apiDoc, { multerOpts: this.options.fileUploader, ajvOpts: this.ajvOpts.multipart, }); } private securityMiddleware(apiDoc: OpenAPIV3.Document) { const securityHandlers = (<ValidateSecurityOpts>( this.options.validateSecurity ))?.handlers; return middlewares.security(apiDoc, securityHandlers); } private requestValidationMiddleware(apiDoc: OpenAPIV3.Document) { const requestValidator = new middlewares.RequestValidator( apiDoc, this.ajvOpts.request, ); return (req, res, next) => requestValidator.validate(req, res, next); } private responseValidationMiddleware(apiDoc: OpenAPIV3.Document) { return new middlewares.ResponseValidator( apiDoc, this.ajvOpts.response, // This has already been converted from boolean if required this.options.validateResponses as ValidateResponseOpts, ).validate(); } installOperationHandlers(baseUrl: string, context: OpenApiContext): Router { const router = express.Router({ mergeParams: true }); this.installPathParams(router, context); for (const route of context.routes) { const { method, expressRoute } = route; /** * This if-statement is here to "narrow" the type of options.operationHandlers * to OperationHandlerOptions (down from string | false | OperationHandlerOptions) * At this point of execution it _should_ be impossible for this to NOT be the correct * type as we re-assign during construction to verify this. */ if (this.isOperationHandlerOptions(this.options.operationHandlers)) { const { basePath, resolver } = this.options.operationHandlers; const path = expressRoute.indexOf(baseUrl) === 0 ? expressRoute.substring(baseUrl.length) : expressRoute; router[method.toLowerCase()]( path, resolver(basePath, route, context.apiDoc), ); } } return router; } private validateOptions(options: OpenApiValidatorOpts): void { if (!options.apiSpec) throw ono('apiSpec required'); const securityHandlers = (<any>options).securityHandlers; if (securityHandlers != null) { throw ono( 'securityHandlers is not supported. Use validateSecurities.handlers instead.', ); } if (options.coerceTypes) { console.warn('coerceTypes is deprecated.'); } const multerOpts = (<any>options).multerOpts; if (multerOpts != null) { throw ono('multerOpts is not supported. Use fileUploader instead.'); } const unknownFormats = options.unknownFormats; if (typeof unknownFormats === 'boolean') { if (!unknownFormats) { throw ono( "unknownFormats must contain an array of unknownFormats, 'ignore' or true", ); } } else if ( typeof unknownFormats === 'string' && unknownFormats !== 'ignore' && !Array.isArray(unknownFormats) ) throw ono( "unknownFormats must contain an array of unknownFormats, 'ignore' or true", ); } private normalizeOptions(options: OpenApiValidatorOpts): void { if (!options.serDes) { options.serDes = defaultSerDes; } else { if (!Array.isArray(options.unknownFormats)) { options.unknownFormats = Array<string>(); } options.serDes.forEach((currentSerDes) => { if ( (options.unknownFormats as string[]).indexOf(currentSerDes.format) === -1 ) { (options.unknownFormats as string[]).push(currentSerDes.format); } }); defaultSerDes.forEach((currentDefaultSerDes) => { let defaultSerDesOverride = options.serDes.find( (currentOptionSerDes) => { return currentDefaultSerDes.format === currentOptionSerDes.format; }, ); if (!defaultSerDesOverride) { options.serDes.push(currentDefaultSerDes); } }); } } private isOperationHandlerOptions( value: false | string | OperationHandlerOptions, ): value is OperationHandlerOptions { if ((value as OperationHandlerOptions).resolver) { return true; } else { return false; } } }
the_stack